|
16 | 16 | //! - Frozen conversation snapshot |
17 | 17 | //! - Fire-and-forget (daemon thread pattern) |
18 | 18 |
|
| 19 | +use std::sync::atomic::{AtomicU64, Ordering}; |
| 20 | +use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
| 21 | + |
19 | 22 | use crate::extras::dirge_paths::ProjectPaths; |
20 | 23 | use crate::provider::AnyAgent; |
21 | 24 |
|
| 25 | +/// Minimum interval between background reviews (seconds). |
| 26 | +const MIN_REVIEW_INTERVAL_SECS: u64 = 900; // 15 minutes |
| 27 | + |
| 28 | +/// Last review timestamp (Unix seconds). |
| 29 | +static LAST_REVIEW: AtomicU64 = AtomicU64::new(0); |
| 30 | + |
22 | 31 | /// Review prompt focused on project memory and pitfalls. |
23 | 32 | /// Port of Hermes's `_MEMORY_REVIEW_PROMPT` adapted for coding context. |
24 | 33 | const MEMORY_REVIEW_PROMPT: &str = r#"Review the conversation above and update project memory. |
@@ -90,17 +99,29 @@ Be specific and actionable. Future sessions should benefit from what you learned |
90 | 99 | /// This is fire-and-forget — it runs in a `tokio::spawn` task and |
91 | 100 | /// returns immediately. Failures are logged to stderr and never |
92 | 101 | /// block the user. |
93 | | -pub fn spawn_background_review( |
94 | | - agent: AnyAgent, |
95 | | - _paths: ProjectPaths, |
96 | | - transcript: String, |
97 | | -) { |
| 102 | +pub fn spawn_background_review(agent: AnyAgent, _paths: ProjectPaths, transcript: String) { |
| 103 | + // Rate-limit: skip if a review ran recently. Uses atomic |
| 104 | + // compare-and-swap so concurrent Done events from different |
| 105 | + // sessions don't race — only the first one wins. |
| 106 | + let now = SystemTime::now() |
| 107 | + .duration_since(UNIX_EPOCH) |
| 108 | + .map(|d| d.as_secs()) |
| 109 | + .unwrap_or(0); |
| 110 | + let last = LAST_REVIEW.load(Ordering::Relaxed); |
| 111 | + if now.saturating_sub(last) < MIN_REVIEW_INTERVAL_SECS { |
| 112 | + tracing::debug!( |
| 113 | + target: "dirge::review", |
| 114 | + elapsed_secs = %(now - last), |
| 115 | + "Skipping background review — last review was too recent" |
| 116 | + ); |
| 117 | + return; |
| 118 | + } |
| 119 | + LAST_REVIEW.store(now, Ordering::Relaxed); |
| 120 | + |
98 | 121 | tokio::spawn(async move { |
99 | 122 | // Build a review runner with only memory + skill tools. |
100 | | - let review_runner = agent.spawn_review_runner( |
101 | | - COMBINED_REVIEW_PROMPT.to_string(), |
102 | | - transcript, |
103 | | - ); |
| 123 | + let review_runner = |
| 124 | + agent.spawn_review_runner(COMBINED_REVIEW_PROMPT.to_string(), transcript); |
104 | 125 |
|
105 | 126 | // Drain events. We don't render them — the review runs |
106 | 127 | // silently in the background. |
@@ -134,3 +155,145 @@ pub fn spawn_background_review( |
134 | 155 | } |
135 | 156 | }); |
136 | 157 | } |
| 158 | + |
| 159 | +/// Build a human-readable transcript from session messages for |
| 160 | +/// background review. Includes user text, assistant text, tool |
| 161 | +/// call names+args, and tool results. Compaction summaries are |
| 162 | +/// included as system context. |
| 163 | +pub fn build_transcript(session: &crate::session::Session) -> String { |
| 164 | + let mut out = String::new(); |
| 165 | + for msg in &session.messages { |
| 166 | + match msg.role { |
| 167 | + crate::session::MessageRole::User => { |
| 168 | + out.push_str(&format!("User: {}\n\n", msg.content)); |
| 169 | + } |
| 170 | + crate::session::MessageRole::Assistant => { |
| 171 | + if !msg.content.is_empty() { |
| 172 | + out.push_str(&format!("Assistant: {}\n", msg.content)); |
| 173 | + } |
| 174 | + for tc in &msg.tool_calls { |
| 175 | + let args_str = |
| 176 | + serde_json::to_string(&tc.args).unwrap_or_else(|_| "{}".to_string()); |
| 177 | + out.push_str(&format!(" [Tool: {}({})]\n", tc.name, args_str)); |
| 178 | + match &tc.state { |
| 179 | + crate::session::ToolCallState::Completed { result } => { |
| 180 | + let truncated = truncate_tool_result(result); |
| 181 | + out.push_str(&format!(" [Result: {}]\n", truncated)); |
| 182 | + } |
| 183 | + crate::session::ToolCallState::Interrupted => { |
| 184 | + out.push_str(" [Result: <interrupted>]\n"); |
| 185 | + } |
| 186 | + crate::session::ToolCallState::Failed { error } => { |
| 187 | + out.push_str(&format!(" [Result: <failed: {}>]\n", error)); |
| 188 | + } |
| 189 | + } |
| 190 | + } |
| 191 | + if !msg.content.is_empty() || !msg.tool_calls.is_empty() { |
| 192 | + out.push('\n'); |
| 193 | + } |
| 194 | + } |
| 195 | + crate::session::MessageRole::System => { |
| 196 | + out.push_str(&format!("[System: {}]\n\n", msg.content)); |
| 197 | + } |
| 198 | + } |
| 199 | + } |
| 200 | + out |
| 201 | +} |
| 202 | + |
| 203 | +fn truncate_tool_result(result: &str) -> String { |
| 204 | + const MAX_TOOL_RESULT: usize = 2000; |
| 205 | + if result.len() <= MAX_TOOL_RESULT { |
| 206 | + result.to_string() |
| 207 | + } else { |
| 208 | + let truncated: String = result.chars().take(MAX_TOOL_RESULT).collect(); |
| 209 | + format!("{}… (truncated, {} bytes total)", truncated, result.len()) |
| 210 | + } |
| 211 | +} |
| 212 | + |
| 213 | +#[cfg(test)] |
| 214 | +mod tests { |
| 215 | + use super::*; |
| 216 | + use crate::session::{MessageRole, Session, ToolCallEntry, ToolCallState}; |
| 217 | + |
| 218 | + fn make_session() -> Session { |
| 219 | + Session::new("test-provider", "test-model", 128_000) |
| 220 | + } |
| 221 | + |
| 222 | + #[test] |
| 223 | + fn transcript_includes_user_and_assistant() { |
| 224 | + let mut s = make_session(); |
| 225 | + s.add_message(MessageRole::User, "how do I build this?"); |
| 226 | + s.add_message(MessageRole::Assistant, "Run cargo build"); |
| 227 | + |
| 228 | + let t = build_transcript(&s); |
| 229 | + assert!(t.contains("User: how do I build this?")); |
| 230 | + assert!(t.contains("Assistant: Run cargo build")); |
| 231 | + } |
| 232 | + |
| 233 | + #[test] |
| 234 | + fn transcript_includes_tool_calls_and_results() { |
| 235 | + let mut s = make_session(); |
| 236 | + s.add_message(MessageRole::User, "read the file"); |
| 237 | + let tc = ToolCallEntry { |
| 238 | + id: "call-1".to_string(), |
| 239 | + name: "read".to_string(), |
| 240 | + args: serde_json::json!({"path": "/tmp/x"}), |
| 241 | + state: ToolCallState::Completed { |
| 242 | + result: "file contents here".to_string(), |
| 243 | + }, |
| 244 | + }; |
| 245 | + s.add_message_with_tool_calls(MessageRole::Assistant, "Let me read that.", vec![tc]); |
| 246 | + |
| 247 | + let t = build_transcript(&s); |
| 248 | + assert!(t.contains("[Tool: read(")); |
| 249 | + assert!(t.contains("[Result: file contents here]")); |
| 250 | + } |
| 251 | + |
| 252 | + #[test] |
| 253 | + fn transcript_truncates_large_tool_results() { |
| 254 | + let mut s = make_session(); |
| 255 | + let big = "x".repeat(3000); |
| 256 | + let tc = ToolCallEntry { |
| 257 | + id: "c1".to_string(), |
| 258 | + name: "bash".to_string(), |
| 259 | + args: serde_json::json!({"cmd": "cat big.txt"}), |
| 260 | + state: ToolCallState::Completed { |
| 261 | + result: big.clone(), |
| 262 | + }, |
| 263 | + }; |
| 264 | + s.add_message_with_tool_calls(MessageRole::Assistant, "", vec![tc]); |
| 265 | + |
| 266 | + let t = build_transcript(&s); |
| 267 | + assert!(t.contains("truncated")); |
| 268 | + assert!(!t.contains(&big)); |
| 269 | + } |
| 270 | + |
| 271 | + #[test] |
| 272 | + fn transcript_includes_system_messages() { |
| 273 | + let mut s = make_session(); |
| 274 | + s.add_message( |
| 275 | + MessageRole::System, |
| 276 | + "compaction summary: previous work on auth module", |
| 277 | + ); |
| 278 | + s.add_message(MessageRole::User, "continue"); |
| 279 | + |
| 280 | + let t = build_transcript(&s); |
| 281 | + assert!(t.contains("[System: compaction summary")); |
| 282 | + assert!(t.contains("User: continue")); |
| 283 | + } |
| 284 | + |
| 285 | + #[test] |
| 286 | + fn transcript_handles_interrupted_tool() { |
| 287 | + let mut s = make_session(); |
| 288 | + let tc = ToolCallEntry { |
| 289 | + id: "ci".to_string(), |
| 290 | + name: "bash".to_string(), |
| 291 | + args: serde_json::json!({}), |
| 292 | + state: ToolCallState::Interrupted, |
| 293 | + }; |
| 294 | + s.add_message_with_tool_calls(MessageRole::Assistant, "", vec![tc]); |
| 295 | + |
| 296 | + let t = build_transcript(&s); |
| 297 | + assert!(t.contains("<interrupted>")); |
| 298 | + } |
| 299 | +} |
0 commit comments