| 1 | //! Agent-driven context purging. |
| 2 | //! |
| 3 | //! Unlike compaction (which summarises old messages via LLM), purge lets the |
| 4 | //! agent analyse the conversation history and surgically remove or rewrite |
| 5 | //! individual messages that are no longer needed. The agent uses the |
| 6 | //! `purge_context` tool to submit a list of operations; the engine validates |
| 7 | //! and executes them. |
| 8 | |
| 9 | use regex::Regex; |
| 10 | use std::fmt::Write; |
| 11 | use tokio::sync::mpsc::Sender; |
| 12 | |
| 13 | use crate::core::events::Event; |
| 14 | use crate::llm_client::LlmClient; |
| 15 | use codewhale_config::ProviderKind; |
| 16 | use codewhale_models::Role; |
| 17 | use codewhale_models::{ContentBlock, Message, MessageRequest, Tool}; |
| 18 | use codewhale_runtime::fast_hash::{FastHashMap, FastHashSet}; |
| 19 | use codewhale_runtime::regex_cache::compile_user_regex; |
| 20 | |
| 21 | // ── Prompt‑building constants ────────────────────────────────────────────── |
| 22 | |
| 23 | const TEXT_SNIPPET_CHARS: usize = 60; |
| 24 | const TOOL_RESULT_SNIPPET_CHARS: usize = 80; |
| 25 | const TOOL_USE_ARGS_CHARS: usize = 120; |
| 26 | |
| 27 | // ── Prompt instruction template ───────────────────────────────────────────── |
| 28 | |
| 29 | const PURGE_INSTRUCTIONS: &str = "\ |
| 30 | ## Context Purge |
| 31 | |
| 32 | Free space in the conversation's context window. Below is the current history with stable numeric IDs.\ |
| 33 | Identify content that is clearly no longer needed for the ongoing work. |
| 34 | |
| 35 | ### Operations |
| 36 | |
| 37 | remove — Delete an entire message by its ID. Example: |
| 38 | {\"op\": \"remove\", \"msg\": 3} |
| 39 | |
| 40 | replace — Rewrite part of a specific content block using regex substitution. |
| 41 | pattern uses Rust regex syntax. Must specify both `block` and |
| 42 | `pattern` and `with`. Example: |
| 43 | {\"op\": \"replace\", \"msg\": 7, \"block\": 0, |
| 44 | \"pattern\": \"read \\\\d+ files\", \"with\": \"read files\"} |
| 45 | |
| 46 | offload — Preserve a complete message in durable session storage and replace it |
| 47 | with a compact retrieval handle. Use for long material that may be needed |
| 48 | again; retrieve_tool_result can recover exact content later. Example: |
| 49 | {\"op\": \"offload\", \"msg\": 3} |
| 50 | |
| 51 | ### Pairing rule |
| 52 | |
| 53 | Every ToolUse block is paired with its ToolResult. If you remove a message |
| 54 | containing a tool call, its result will be removed too — and vice versa. You |
| 55 | do not need to list both. Offload similarly archives the entire paired group, |
| 56 | including thinking, signatures, media, and tool data; no original blocks are discarded. |
| 57 | |
| 58 | ### What to keep |
| 59 | |
| 60 | - Important decisions, architectural choices |
| 61 | - File paths that are still relevant |
| 62 | - Tool outputs that contain information not yet acted upon |
| 63 | |
| 64 | ### What to prune |
| 65 | |
| 66 | - Verbose tool outputs whose information has been fully consumed |
| 67 | - Redundant confirmations (\"done\", \"ok\", \"that worked\") |
| 68 | - Superseded file reads (the file was later written/modified) |
| 69 | - Boilerplate that the model already incorporated into later work |
| 70 | |
| 71 | Be conservative. When in doubt, keep the message. |
| 72 | |
| 73 | ### Conversation |
| 74 | "; |
| 75 | |
| 76 | // ── Purge operation types ─────────────────────────────────────────────────── |
| 77 | |
| 78 | /// A single purge operation submitted by the agent. |
| 79 | #[derive(Debug, Clone)] |
| 80 | pub enum PurgeOp { |
| 81 | /// Remove an entire message (plus its tool-call/result counterpart). |
| 82 | Remove { msg_id: usize }, |
| 83 | /// Archive an entire message and its paired tool messages before replacing them with a handle. |
| 84 | Offload { msg_id: usize }, |
| 85 | /// Regex-replace within a specific content block. |
| 86 | Replace { |
| 87 | msg_id: usize, |
| 88 | block_idx: usize, |
| 89 | pattern: Regex, |
| 90 | with: String, |
| 91 | }, |
| 92 | } |
| 93 | |
| 94 | /// Result of executing purge operations. |
| 95 | #[derive(Debug, Clone)] |
| 96 | pub struct PurgeResult { |
| 97 | /// The remaining messages after all operations. |
| 98 | pub messages: Vec<Message>, |
| 99 | /// How many messages were removed. |
| 100 | pub removed_count: usize, |
| 101 | /// How many replace operations were applied. |
| 102 | pub replaced_count: usize, |
| 103 | /// Messages preserved in a durable session artifact instead of active context. |
| 104 | pub offloaded_count: usize, |
| 105 | } |
| 106 | |
| 107 | // ── Event emission helpers ────────────────────────────────────────────────── |
| 108 | |
| 109 | /// Emit a `PurgeStarted` event to the UI. |
| 110 | pub async fn emit_purge_started(tx: &Sender<Event>, message: String) { |
| 111 | let _ = tx.send(Event::PurgeStarted { message }).await; |
| 112 | } |
| 113 | |
| 114 | /// Emit a `PurgeCompleted` event to the UI. |
| 115 | pub async fn emit_purge_completed( |
| 116 | tx: &Sender<Event>, |
| 117 | messages_before: usize, |
| 118 | messages_after: usize, |
| 119 | removed_count: usize, |
| 120 | replaced_count: usize, |
| 121 | message: String, |
| 122 | ) { |
| 123 | let _ = tx |
| 124 | .send(Event::PurgeCompleted { |
| 125 | messages_before, |
| 126 | messages_after, |
| 127 | removed_count, |
| 128 | replaced_count, |
| 129 | message, |
| 130 | }) |
| 131 | .await; |
| 132 | } |
| 133 | |
| 134 | /// Emit a `PurgeFailed` event to the UI. |
| 135 | pub async fn emit_purge_failed(tx: &Sender<Event>, message: String) { |
| 136 | let _ = tx.send(Event::PurgeFailed { message }).await; |
| 137 | } |
| 138 | |
| 139 | // ── Prompt builder ────────────────────────────────────────────────────────── |
| 140 | |
| 141 | /// Build the purge request user message — a formatted listing of the current |
| 142 | /// conversation with ephemeral sequential IDs. |
| 143 | pub fn build_purge_prompt(messages: &[Message]) -> String { |
| 144 | let mut buf = String::with_capacity(messages.len().saturating_mul(256)); |
| 145 | buf.push_str(PURGE_INSTRUCTIONS); |
| 146 | |
| 147 | for (idx, msg) in messages.iter().enumerate() { |
| 148 | let msg_id = idx + 1; // 1‑based for the agent |
| 149 | if msg.role == "user" { |
| 150 | // User messages: always a single block — omit block index. |
| 151 | format_user_message(&mut buf, msg_id, msg); |
| 152 | } else { |
| 153 | // Assistant messages: may be multi‑block — show block indices. |
| 154 | let _ = writeln!(buf, "[{msg_id}] {role}", role = msg.role); |
| 155 | for (blk_idx, block) in msg.content.iter().enumerate() { |
| 156 | format_content_block(&mut buf, blk_idx, block); |
| 157 | } |
| 158 | buf.push('\n'); |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | buf |
| 163 | } |
| 164 | |
| 165 | fn format_user_message(buf: &mut String, msg_id: usize, msg: &Message) { |
| 166 | let block = msg.content.first(); |
| 167 | match block { |
| 168 | Some(ContentBlock::Text { text, .. }) => { |
| 169 | let snippet = truncate_str(text, TEXT_SNIPPET_CHARS); |
| 170 | let _ = writeln!( |
| 171 | buf, |
| 172 | "[{msg_id}] user Text ({len} chars): \"{snippet}\"", |
| 173 | len = text.len() |
| 174 | ); |
| 175 | } |
| 176 | Some(ContentBlock::ToolResult { |
| 177 | content, |
| 178 | tool_use_id, |
| 179 | .. |
| 180 | }) => { |
| 181 | let snippet = truncate_str(content, TOOL_RESULT_SNIPPET_CHARS); |
| 182 | let _ = writeln!( |
| 183 | buf, |
| 184 | "[{msg_id}] user ToolResult (id={tool_use_id}, {len} chars): \"{snippet}\"", |
| 185 | len = content.len(), |
| 186 | ); |
| 187 | } |
| 188 | _ => { |
| 189 | let _ = writeln!(buf, "[{msg_id}] user (non‑text block)"); |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | fn format_content_block(buf: &mut String, blk_idx: usize, block: &ContentBlock) { |
| 195 | match block { |
| 196 | ContentBlock::Text { text, .. } => { |
| 197 | let snippet = truncate_str(text, TEXT_SNIPPET_CHARS); |
| 198 | let _ = writeln!( |
| 199 | buf, |
| 200 | " [{blk_idx}] Text ({len} chars): \"{snippet}\"", |
| 201 | len = text.len(), |
| 202 | ); |
| 203 | } |
| 204 | ContentBlock::Thinking { .. } => { |
| 205 | // Omit thinking blocks — API-mandated on tool-call messages; |
| 206 | // the agent cannot remove them, so listing them only adds noise. |
| 207 | } |
| 208 | ContentBlock::ToolUse { |
| 209 | name, input, id, .. |
| 210 | } => { |
| 211 | let args = serde_json::to_string(input).unwrap_or_default(); |
| 212 | let args_preview = truncate_str(&args, TOOL_USE_ARGS_CHARS); |
| 213 | let _ = writeln!( |
| 214 | buf, |
| 215 | " [{blk_idx}] ToolUse ({name}, id={id}, args={args_preview})" |
| 216 | ); |
| 217 | } |
| 218 | ContentBlock::ToolResult { |
| 219 | content, |
| 220 | tool_use_id, |
| 221 | .. |
| 222 | } => { |
| 223 | let snippet = truncate_str(content, TOOL_RESULT_SNIPPET_CHARS); |
| 224 | let _ = writeln!( |
| 225 | buf, |
| 226 | " [{blk_idx}] ToolResult (id={tool_use_id}, {len} chars): \"{snippet}\"", |
| 227 | len = content.len(), |
| 228 | ); |
| 229 | } |
| 230 | ContentBlock::ServerToolUse { |
| 231 | name, input, id, .. |
| 232 | } => { |
| 233 | let args = serde_json::to_string(input).unwrap_or_default(); |
| 234 | let args_preview = truncate_str(&args, TOOL_USE_ARGS_CHARS); |
| 235 | let _ = writeln!( |
| 236 | buf, |
| 237 | " [{blk_idx}] ServerToolUse ({name}, id={id}, args={args_preview})" |
| 238 | ); |
| 239 | } |
| 240 | ContentBlock::ToolSearchToolResult { |
| 241 | tool_use_id, |
| 242 | content, |
| 243 | .. |
| 244 | } => { |
| 245 | let snippet = truncate_str(&content.to_string(), TOOL_RESULT_SNIPPET_CHARS); |
| 246 | let _ = writeln!( |
| 247 | buf, |
| 248 | " [{blk_idx}] ToolSearchToolResult (id={tool_use_id}, content={snippet})" |
| 249 | ); |
| 250 | } |
| 251 | ContentBlock::CodeExecutionToolResult { |
| 252 | tool_use_id, |
| 253 | content, |
| 254 | .. |
| 255 | } => { |
| 256 | let snippet = truncate_str(&content.to_string(), TOOL_RESULT_SNIPPET_CHARS); |
| 257 | let _ = writeln!( |
| 258 | buf, |
| 259 | " [{blk_idx}] CodeExecutionToolResult (id={tool_use_id}, content={snippet})" |
| 260 | ); |
| 261 | } |
| 262 | ContentBlock::WebSearchToolResult { |
| 263 | tool_use_id, |
| 264 | content, |
| 265 | .. |
| 266 | } => { |
| 267 | let snippet = truncate_str(&content.to_string(), TOOL_RESULT_SNIPPET_CHARS); |
| 268 | let _ = writeln!( |
| 269 | buf, |
| 270 | " [{blk_idx}] WebSearchToolResult (id={tool_use_id}, content={snippet})" |
| 271 | ); |
| 272 | } |
| 273 | ContentBlock::WebFetchToolResult { |
| 274 | tool_use_id, |
| 275 | content, |
| 276 | .. |
| 277 | } => { |
| 278 | let snippet = truncate_str(&content.to_string(), TOOL_RESULT_SNIPPET_CHARS); |
| 279 | let _ = writeln!( |
| 280 | buf, |
| 281 | " [{blk_idx}] WebFetchToolResult (id={tool_use_id}, content={snippet})" |
| 282 | ); |
| 283 | } |
| 284 | ContentBlock::WebSearchCall { |
| 285 | id, kind, status, .. |
| 286 | } => { |
| 287 | let _ = writeln!( |
| 288 | buf, |
| 289 | " [{blk_idx}] WebSearchCall (id={}, kind={}, status={})", |
| 290 | id, |
| 291 | kind.as_deref().unwrap_or(""), |
| 292 | status |
| 293 | ); |
| 294 | } |
| 295 | ContentBlock::ServerToolCalls { steps } => { |
| 296 | let _ = writeln!(buf, " [{blk_idx}] ServerToolCalls (steps={})", steps.len()); |
| 297 | } |
| 298 | ContentBlock::File { file_id } => { |
| 299 | let _ = writeln!(buf, " [{blk_idx}] File (file_id={file_id})"); |
| 300 | } |
| 301 | ContentBlock::ImageUrl { .. } => {} |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | fn truncate_str(text: &str, max_chars: usize) -> String { |
| 306 | if text.chars().count() <= max_chars { |
| 307 | return text.to_string(); |
| 308 | } |
| 309 | let take = max_chars.saturating_sub(3); |
| 310 | let mut out: String = text.chars().take(take).collect(); |
| 311 | out.push_str("..."); |
| 312 | out |
| 313 | } |
| 314 | |
| 315 | // ── Operation parser ──────────────────────────────────────────────────────── |
| 316 | |
| 317 | /// Parse the `purge_context` tool input JSON into a list of validated |
| 318 | /// `PurgeOp`s. Returns an error string on invalid input. |
| 319 | pub fn parse_purge_operations( |
| 320 | input: &serde_json::Value, |
| 321 | message_count: usize, |
| 322 | ) -> Result<Vec<PurgeOp>, String> { |
| 323 | let ops = input |
| 324 | .get("operations") |
| 325 | .and_then(|v| v.as_array()) |
| 326 | .ok_or_else(|| "missing or invalid 'operations' array".to_string())?; |
| 327 | |
| 328 | let mut parsed = Vec::with_capacity(ops.len()); |
| 329 | |
| 330 | for (i, op) in ops.iter().enumerate() { |
| 331 | let op_type = op |
| 332 | .get("op") |
| 333 | .and_then(|v| v.as_str()) |
| 334 | .ok_or_else(|| format!("operation[{i}]: missing 'op' field"))?; |
| 335 | |
| 336 | let msg = op |
| 337 | .get("msg") |
| 338 | .and_then(|v| v.as_u64()) |
| 339 | .ok_or_else(|| format!("operation[{i}]: missing or invalid 'msg'"))?; |
| 340 | |
| 341 | let msg_id = usize::try_from(msg).unwrap_or(usize::MAX); |
| 342 | if msg_id == 0 || msg_id > message_count { |
| 343 | return Err(format!( |
| 344 | "operation[{i}]: msg {msg} out of range (1–{message_count})" |
| 345 | )); |
| 346 | } |
| 347 | |
| 348 | match op_type { |
| 349 | "remove" => { |
| 350 | parsed.push(PurgeOp::Remove { msg_id }); |
| 351 | } |
| 352 | "offload" => parsed.push(PurgeOp::Offload { msg_id }), |
| 353 | "replace" => { |
| 354 | let block_idx = op |
| 355 | .get("block") |
| 356 | .and_then(|v| v.as_u64()) |
| 357 | .map(|v| v as usize) |
| 358 | .ok_or_else(|| format!("operation[{i}]: 'replace' requires 'block'"))?; |
| 359 | |
| 360 | let pattern_str = op |
| 361 | .get("pattern") |
| 362 | .and_then(|v| v.as_str()) |
| 363 | .ok_or_else(|| format!("operation[{i}]: 'replace' requires 'pattern'"))?; |
| 364 | |
| 365 | let with = op |
| 366 | .get("with") |
| 367 | .and_then(|v| v.as_str()) |
| 368 | .unwrap_or("") |
| 369 | .to_string(); |
| 370 | |
| 371 | let pattern = compile_user_regex(pattern_str) |
| 372 | .map_err(|e| format!("operation[{i}]: invalid regex pattern: {e}"))?; |
| 373 | |
| 374 | parsed.push(PurgeOp::Replace { |
| 375 | msg_id, |
| 376 | block_idx, |
| 377 | pattern, |
| 378 | with, |
| 379 | }); |
| 380 | } |
| 381 | other => { |
| 382 | return Err(format!( |
| 383 | "operation[{i}]: unknown op '{other}' (expected 'remove', 'replace' or 'offload')" |
| 384 | )); |
| 385 | } |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | Ok(parsed) |
| 390 | } |
| 391 | |
| 392 | // ── Operation executor ────────────────────────────────────────────────────── |
| 393 | |
| 394 | /// Execute a list of purge operations against the message history. |
| 395 | /// |
| 396 | /// Operations are processed in the order given but effective removal runs |
| 397 | /// from highest index to lowest to keep earlier indices stable. After all |
| 398 | /// user-requested operations, tool‑call/result pair cascading runs to |
| 399 | /// prevent orphaned blocks. |
| 400 | pub fn execute_purge_operations( |
| 401 | messages: &[Message], |
| 402 | ops: &[PurgeOp], |
| 403 | session_id: &str, |
| 404 | ) -> Result<PurgeResult, String> { |
| 405 | let mut offloaded: FastHashSet<usize> = ops |
| 406 | .iter() |
| 407 | .filter_map(|op| { |
| 408 | if let PurgeOp::Offload { msg_id } = op { |
| 409 | msg_id.checked_sub(1).filter(|idx| *idx < messages.len()) |
| 410 | } else { |
| 411 | None |
| 412 | } |
| 413 | }) |
| 414 | .collect(); |
| 415 | cascade_tool_pair_removals(messages, &mut offloaded); |
| 416 | // Publish original, full-fidelity messages before any destructive operation. |
| 417 | // Failure leaves the caller's conversation intact, including mixed operations. |
| 418 | let mut pointer = if offloaded.is_empty() { |
| 419 | None |
| 420 | } else { |
| 421 | Some(publish_offloaded_context(session_id, messages, &offloaded)?) |
| 422 | }; |
| 423 | let mut msgs = messages.to_vec(); |
| 424 | let mut msg_indices_to_remove: FastHashSet<usize> = FastHashSet::default(); |
| 425 | let mut replaced_count = 0usize; |
| 426 | |
| 427 | // Phase 1: collect removes and apply replaces. |
| 428 | for op in ops { |
| 429 | match op { |
| 430 | PurgeOp::Remove { msg_id } => { |
| 431 | let idx = msg_id.saturating_sub(1); |
| 432 | if idx < msgs.len() { |
| 433 | msg_indices_to_remove.insert(idx); |
| 434 | } |
| 435 | } |
| 436 | PurgeOp::Offload { .. } => {} |
| 437 | PurgeOp::Replace { |
| 438 | msg_id, |
| 439 | block_idx, |
| 440 | pattern, |
| 441 | with, |
| 442 | } => { |
| 443 | let idx = msg_id.saturating_sub(1); |
| 444 | if idx >= msgs.len() || offloaded.contains(&idx) { |
| 445 | continue; |
| 446 | } |
| 447 | if let Some(block) = msgs[idx].content.get_mut(*block_idx) { |
| 448 | let old_text = block_content_text(block).to_string(); |
| 449 | let new_text = pattern.replace_all(&old_text, with.as_str()).to_string(); |
| 450 | apply_block_replacement(block, &new_text); |
| 451 | replaced_count = replaced_count.saturating_add(1); |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | // Phase 2: cascade removal to tool-call/result counterparts. |
| 458 | cascade_tool_pair_removals(&msgs, &mut msg_indices_to_remove); |
| 459 | |
| 460 | // Archival takes precedence over remove/replace when a paired group overlaps. |
| 461 | let removed_count = msg_indices_to_remove.difference(&offloaded).count(); |
| 462 | let first_offloaded = offloaded.iter().min().copied(); |
| 463 | let mut retained = Vec::with_capacity(msgs.len()); |
| 464 | for (idx, msg) in msgs.into_iter().enumerate() { |
| 465 | if Some(idx) == first_offloaded |
| 466 | && let Some(text) = pointer.take() |
| 467 | { |
| 468 | retained.push(Message { |
| 469 | role: messages[idx].role.clone(), |
| 470 | content: vec![ContentBlock::Text { |
| 471 | text, |
| 472 | cache_control: None, |
| 473 | }], |
| 474 | }); |
| 475 | } |
| 476 | if !offloaded.contains(&idx) && !msg_indices_to_remove.contains(&idx) { |
| 477 | retained.push(msg); |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | Ok(PurgeResult { |
| 482 | messages: retained, |
| 483 | removed_count, |
| 484 | replaced_count, |
| 485 | offloaded_count: offloaded.len(), |
| 486 | }) |
| 487 | } |
| 488 | |
| 489 | fn publish_offloaded_context( |
| 490 | session_id: &str, |
| 491 | messages: &[Message], |
| 492 | selected: &FastHashSet<usize>, |
| 493 | ) -> Result<String, String> { |
| 494 | use crate::tools::large_output_router::{ |
| 495 | EvidenceArtifact, EvidenceRetentionState, publish_evidence_metadata, unix_millis_now, |
| 496 | }; |
| 497 | let archived: Vec<_> = messages |
| 498 | .iter() |
| 499 | .enumerate() |
| 500 | .filter(|(idx, _)| selected.contains(idx)) |
| 501 | .map(|(idx, message)| serde_json::json!({"message_id": idx + 1, "message": message})) |
| 502 | .collect(); |
| 503 | let bytes = serde_json::to_vec_pretty(&serde_json::json!({ |
| 504 | "schema_version": 1, |
| 505 | "messages": archived, |
| 506 | })) |
| 507 | .map_err(|err| format!("Could not encode offloaded context; history unchanged: {err}"))?; |
| 508 | let call_id = format!("purge_{}", uuid::Uuid::new_v4()); |
| 509 | let handle = codewhale_runtime::artifacts::artifact_id_for_tool_call(&call_id); |
| 510 | let metadata = EvidenceArtifact { |
| 511 | handle: handle.clone(), |
| 512 | digest: codewhale_runtime::hashing::sha256_hex(&bytes), |
| 513 | size_bytes: bytes.len().try_into().unwrap_or(u64::MAX), |
| 514 | content_type: "application/json".to_string(), |
| 515 | tool_name: "purge_context".to_string(), |
| 516 | call_id, |
| 517 | origin_session: session_id.to_string(), |
| 518 | generation: 1, |
| 519 | redacted: false, |
| 520 | encoding: "utf-8".to_string(), |
| 521 | retention_state: EvidenceRetentionState::Live, |
| 522 | created_at_unix_ms: unix_millis_now(), |
| 523 | // This is the only full copy after offload: retain it with the session. |
| 524 | retain_until_unix_ms: u64::MAX, |
| 525 | storage_path: codewhale_runtime::artifacts::session_artifact_relative_path(&handle), |
| 526 | }; |
| 527 | publish_evidence_metadata(session_id, &metadata) |
| 528 | .and_then(|_| { |
| 529 | codewhale_runtime::artifacts::write_session_artifact_immutable( |
| 530 | session_id, &handle, &bytes, |
| 531 | ) |
| 532 | }) |
| 533 | .map_err(|err| format!("Could not store offloaded context; history unchanged: {err}"))?; |
| 534 | Ok(format!( |
| 535 | "[Offloaded context: {} messages preserved exactly in session artifact {handle}, generation 1. \ |
| 536 | Use retrieve_tool_result with ref={handle}, mode=query/lines to inspect, or mode=bytes for exact recovery. \ |
| 537 | The archive includes original message IDs and complete content blocks. Retained until this session is deleted.]", |
| 538 | selected.len() |
| 539 | )) |
| 540 | } |
| 541 | |
| 542 | /// When a message containing a ToolUse or ToolResult is marked for removal, |
| 543 | /// cascade that removal to its unambiguous counterpart. Corrupt or ambiguous |
| 544 | /// identities cannot select another exchange for deletion. Runs a fixpoint |
| 545 | /// loop until the remove set is closed under proven pairing. |
| 546 | fn cascade_tool_pair_removals(messages: &[Message], remove_set: &mut FastHashSet<usize>) { |
| 547 | if remove_set.is_empty() { |
| 548 | return; |
| 549 | } |
| 550 | |
| 551 | // A reused provider ID is not a unique host identity. Ambiguous entries |
| 552 | // cannot select another exchange's counterpart for deletion. |
| 553 | let mut call_id_to_idx = FastHashMap::default(); |
| 554 | let mut result_id_to_idx = FastHashMap::default(); |
| 555 | for (idx, msg) in messages.iter().enumerate() { |
| 556 | for block in &msg.content { |
| 557 | let Some(key) = block |
| 558 | .tool_call_key() |
| 559 | .filter(|key| !key.as_str().trim().is_empty()) |
| 560 | else { |
| 561 | continue; |
| 562 | }; |
| 563 | let (map, provider_id) = match block { |
| 564 | ContentBlock::ToolUse { id, .. } | ContentBlock::ServerToolUse { id, .. } => { |
| 565 | (&mut call_id_to_idx, id.as_str()) |
| 566 | } |
| 567 | ContentBlock::ToolResult { tool_use_id, .. } |
| 568 | | ContentBlock::ToolSearchToolResult { tool_use_id, .. } |
| 569 | | ContentBlock::CodeExecutionToolResult { tool_use_id, .. } |
| 570 | | ContentBlock::WebSearchToolResult { tool_use_id, .. } |
| 571 | | ContentBlock::WebFetchToolResult { tool_use_id, .. } => { |
| 572 | (&mut result_id_to_idx, tool_use_id.as_str()) |
| 573 | } |
| 574 | _ => continue, |
| 575 | }; |
| 576 | map.entry(key) |
| 577 | .and_modify(|entry| *entry = None) |
| 578 | .or_insert(Some((idx, provider_id))); |
| 579 | } |
| 580 | } |
| 581 | |
| 582 | // Fixpoint: when a tool-call is removed, also remove its result (and vice versa). |
| 583 | let max_iters = messages.len().max(10); |
| 584 | for _ in 0..max_iters { |
| 585 | let snapshot: Vec<usize> = remove_set.iter().copied().collect(); |
| 586 | let mut changed = false; |
| 587 | |
| 588 | for idx in snapshot { |
| 589 | let msg = &messages[idx]; |
| 590 | for block in &msg.content { |
| 591 | match block { |
| 592 | ContentBlock::ToolUse { id, .. } | ContentBlock::ServerToolUse { id, .. } => { |
| 593 | if let Some(&(result_idx, provider_id)) = block |
| 594 | .tool_call_key() |
| 595 | .and_then(|key| result_id_to_idx.get(&key)) |
| 596 | .and_then(Option::as_ref) |
| 597 | && provider_id == id.as_str() |
| 598 | && block |
| 599 | .tool_call_key() |
| 600 | .and_then(|key| call_id_to_idx.get(&key)) |
| 601 | .and_then(Option::as_ref) |
| 602 | .is_some_and(|(call_idx, _)| *call_idx == idx) |
| 603 | && remove_set.insert(result_idx) |
| 604 | { |
| 605 | changed = true; |
| 606 | } |
| 607 | } |
| 608 | ContentBlock::ToolResult { tool_use_id, .. } |
| 609 | | ContentBlock::ToolSearchToolResult { tool_use_id, .. } |
| 610 | | ContentBlock::CodeExecutionToolResult { tool_use_id, .. } |
| 611 | | ContentBlock::WebSearchToolResult { tool_use_id, .. } |
| 612 | | ContentBlock::WebFetchToolResult { tool_use_id, .. } => { |
| 613 | if let Some(&(call_idx, provider_id)) = block |
| 614 | .tool_call_key() |
| 615 | .and_then(|key| call_id_to_idx.get(&key)) |
| 616 | .and_then(Option::as_ref) |
| 617 | && provider_id == tool_use_id.as_str() |
| 618 | && block |
| 619 | .tool_call_key() |
| 620 | .and_then(|key| result_id_to_idx.get(&key)) |
| 621 | .and_then(Option::as_ref) |
| 622 | .is_some_and(|(result_idx, _)| *result_idx == idx) |
| 623 | && remove_set.insert(call_idx) |
| 624 | { |
| 625 | changed = true; |
| 626 | } |
| 627 | } |
| 628 | _ => {} |
| 629 | } |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | if !changed { |
| 634 | break; |
| 635 | } |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | fn block_content_text(block: &ContentBlock) -> &str { |
| 640 | match block { |
| 641 | ContentBlock::Text { text, .. } => text, |
| 642 | ContentBlock::ToolResult { content, .. } => content, |
| 643 | _ => "", |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | fn apply_block_replacement(block: &mut ContentBlock, new_text: &str) { |
| 648 | match block { |
| 649 | ContentBlock::Text { text, .. } => { |
| 650 | *text = new_text.to_string(); |
| 651 | } |
| 652 | ContentBlock::ToolResult { content, .. } => { |
| 653 | *content = new_text.to_string(); |
| 654 | } |
| 655 | _ => {} |
| 656 | } |
| 657 | } |
| 658 | |
| 659 | // ── Tool definition builder ────────────────────────────────────────────────── |
| 660 | |
| 661 | /// Build the `purge_context` tool definition sent to the model during a purge |
| 662 | /// turn. This tool is ad-hoc — it is not registered in the normal tool catalog |
| 663 | /// and has no dispatch handler. |
| 664 | pub fn build_purge_tool() -> Tool { |
| 665 | Tool { |
| 666 | tool_type: None, |
| 667 | name: "purge_context".to_string(), |
| 668 | description: "Remove, condense, or durably offload conversation history to free context window space." |
| 669 | .to_string(), |
| 670 | input_schema: serde_json::json!({ |
| 671 | "type": "object", |
| 672 | "properties": { |
| 673 | "operations": { |
| 674 | "type": "array", |
| 675 | "items": { |
| 676 | "type": "object", |
| 677 | "properties": { |
| 678 | "op": {"type": "string", "enum": ["remove", "replace", "offload"]}, |
| 679 | "msg": {"type": "integer"}, |
| 680 | "block": {"type": "integer"}, |
| 681 | "pattern": {"type": "string"}, |
| 682 | "with": {"type": "string"} |
| 683 | }, |
| 684 | "required": ["op", "msg"] |
| 685 | } |
| 686 | } |
| 687 | }, |
| 688 | "required": ["operations"] |
| 689 | }), |
| 690 | allowed_callers: None, |
| 691 | defer_loading: None, |
| 692 | input_examples: None, |
| 693 | strict: Some(true), |
| 694 | cache_control: None, |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | // ── Orchestration ──────────────────────────────────────────────────────────── |
| 699 | |
| 700 | /// Run a full purge cycle: build the prompt, call the model with the |
| 701 | /// `purge_context` tool, parse the response, and execute the operations. |
| 702 | /// |
| 703 | /// Returns the `PurgeResult` with the modified message list on success, |
| 704 | /// or a human-readable error string on failure. |
| 705 | /// |
| 706 | /// Cost reporting is handled internally as a side-effect of the API call. |
| 707 | /// The caller is responsible for emitting start/completed/failed events |
| 708 | /// and for replacing the session message list with `PurgeResult.messages`. |
| 709 | pub async fn run_purge( |
| 710 | client: &impl LlmClient, |
| 711 | provider: ProviderKind, |
| 712 | session_id: &str, |
| 713 | messages: &[Message], |
| 714 | model: &str, |
| 715 | reasoning_effort: Option<String>, |
| 716 | max_tokens: u32, |
| 717 | accounting_origin: Option<crate::cost_status::NativeUsageOrigin>, |
| 718 | ) -> Result<PurgeResult, String> { |
| 719 | // 1. Build the purge prompt from the current conversation. |
| 720 | let prompt = build_purge_prompt(messages); |
| 721 | |
| 722 | // 2. Clone messages and inject the prompt as a user message. |
| 723 | let mut request_messages = messages.to_vec(); |
| 724 | request_messages.push(Message { |
| 725 | role: Role::User, |
| 726 | content: vec![ContentBlock::Text { |
| 727 | text: prompt, |
| 728 | cache_control: None, |
| 729 | }], |
| 730 | }); |
| 731 | |
| 732 | // 3. Build the tool definition and the request. |
| 733 | let purge_tool = build_purge_tool(); |
| 734 | let max_tokens = crate::route_budget::request_output_cap_for_input( |
| 735 | provider, |
| 736 | model, |
| 737 | client.route_limits(), |
| 738 | max_tokens, |
| 739 | u64::try_from(crate::compaction::estimate_request_input_tokens( |
| 740 | &request_messages, |
| 741 | None, |
| 742 | Some(std::slice::from_ref(&purge_tool)), |
| 743 | )) |
| 744 | .unwrap_or(u64::MAX), |
| 745 | ) |
| 746 | .ok_or_else(|| { |
| 747 | "Purge request does not fit this model's context window; the conversation was not changed" |
| 748 | .to_string() |
| 749 | })?; |
| 750 | let request = MessageRequest { |
| 751 | model: model.to_string(), |
| 752 | messages: request_messages, |
| 753 | max_tokens, |
| 754 | system: None, |
| 755 | tools: Some(vec![purge_tool]), |
| 756 | tool_choice: None, |
| 757 | metadata: None, |
| 758 | thinking: None, |
| 759 | reasoning_effort, |
| 760 | stream: Some(false), |
| 761 | temperature: None, |
| 762 | top_p: None, |
| 763 | safety_check: None, |
| 764 | title: None, |
| 765 | }; |
| 766 | |
| 767 | let cost_scope = accounting_origin.as_ref().map_or_else( |
| 768 | crate::cost_status::scope_token, |
| 769 | crate::cost_status::NativeUsageOrigin::scope, |
| 770 | ); |
| 771 | let cost_route = client.effective_route_envelope(model, chrono::Utc::now()); |
| 772 | let source = crate::cost_status::NativeUsageSource::capture_with_origin( |
| 773 | format!("purge:{}", uuid::Uuid::new_v4()), |
| 774 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 775 | accounting_origin, |
| 776 | ); |
| 777 | let observation = source.observation(); |
| 778 | let wire = observation.wire_observations.clone(); |
| 779 | let response = crate::llm_client::observe_request_retries( |
| 780 | Some(observation), |
| 781 | client.create_message(request), |
| 782 | ) |
| 783 | .await; |
| 784 | let wire = wire.drain(); |
| 785 | let record = source.response_record(&cost_route, &response, &wire); |
| 786 | crate::cost_status::record_runtime_usage_async(cost_scope, source.origin(), &record).await; |
| 787 | let response = response.map_err(|error| format!("Purge API error: {error}"))?; |
| 788 | |
| 789 | // A truncated response can still carry a complete-looking `purge_context` |
| 790 | // call; executing it would mutate the session from incomplete output. |
| 791 | if codewhale_models::is_incomplete_stop_reason(response.stop_reason.as_deref()) { |
| 792 | return Err(format!( |
| 793 | "Purge model response incomplete: provider stop reason `{}`; no purge was applied.", |
| 794 | codewhale_models::stop_reason_detail(response.stop_reason.as_deref()) |
| 795 | )); |
| 796 | } |
| 797 | |
| 798 | if let Some(warning) = response.tool_projection_warning { |
| 799 | return Err(crate::core::events::render_tool_projection_warning( |
| 800 | &warning, |
| 801 | )); |
| 802 | } |
| 803 | |
| 804 | // 5. Find the `purge_context` tool call in the response. |
| 805 | let tool_input = response.content.iter().find_map(|block| { |
| 806 | if let ContentBlock::ToolUse { name, input, .. } = block |
| 807 | && name == "purge_context" |
| 808 | { |
| 809 | return Some(input.clone()); |
| 810 | } |
| 811 | None |
| 812 | }); |
| 813 | |
| 814 | match tool_input { |
| 815 | Some(input) => { |
| 816 | let ops = parse_purge_operations(&input, messages.len()) |
| 817 | .map_err(|e| format!("Purge parse error: {e}"))?; |
| 818 | execute_purge_operations(messages, &ops, session_id) |
| 819 | } |
| 820 | None => Err("Purge: model did not call purge_context tool".to_string()), |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | // ── Tests ─────────────────────────────────────────────────────────────────── |
| 825 | |
| 826 | #[cfg(test)] |
| 827 | mod tests { |
| 828 | use super::*; |
| 829 | use serde_json::json; |
| 830 | |
| 831 | fn msg_text(role: &str, text: &str) -> Message { |
| 832 | Message { |
| 833 | role: Role::from(role), |
| 834 | content: vec![ContentBlock::Text { |
| 835 | text: text.to_string(), |
| 836 | cache_control: None, |
| 837 | }], |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | fn msg_tool_use(id: &str, name: &str, input: serde_json::Value) -> Message { |
| 842 | Message { |
| 843 | role: Role::Assistant, |
| 844 | content: vec![ContentBlock::ToolUse { |
| 845 | execution_id: None, |
| 846 | id: id.to_string(), |
| 847 | name: name.to_string(), |
| 848 | input, |
| 849 | caller: None, |
| 850 | thought_signature: None, |
| 851 | }], |
| 852 | } |
| 853 | } |
| 854 | |
| 855 | fn msg_tool_result(id: &str, content: &str) -> Message { |
| 856 | Message { |
| 857 | role: Role::User, |
| 858 | content: vec![ContentBlock::ToolResult { |
| 859 | execution_id: None, |
| 860 | tool_use_id: id.to_string(), |
| 861 | content: content.to_string(), |
| 862 | is_error: None, |
| 863 | content_blocks: None, |
| 864 | }], |
| 865 | } |
| 866 | } |
| 867 | |
| 868 | #[test] |
| 869 | fn purge_counterparts_use_execution_identity_without_legacy_fallback() { |
| 870 | let messages: Vec<Message> = serde_json::from_value(json!([ |
| 871 | {"role":"assistant","content":[{"type":"tool_use","id":"wire","execution_id":"first","name":"read","input":{}}]}, |
| 872 | {"role":"user","content":[{"type":"tool_result","tool_use_id":"wire","execution_id":"first","content":"first"}]}, |
| 873 | {"role":"assistant","content":[{"type":"tool_use","id":"wire","execution_id":"second","name":"read","input":{}}]}, |
| 874 | {"role":"user","content":[{"type":"tool_result","tool_use_id":"wire","execution_id":"second","content":"second"}]}, |
| 875 | {"role":"assistant","content":[{"type":"tool_use","id":"first","name":"read","input":{}}]}, |
| 876 | {"role":"user","content":[{"type":"tool_result","tool_use_id":"first","content":"legacy"}]} |
| 877 | ])).unwrap(); |
| 878 | for (selected, expected) in [(0, vec![0, 1]), (3, vec![2, 3]), (4, vec![4, 5])] { |
| 879 | let mut remove = FastHashSet::from_iter([selected]); |
| 880 | cascade_tool_pair_removals(&messages, &mut remove); |
| 881 | assert_eq!(remove, FastHashSet::from_iter(expected)); |
| 882 | } |
| 883 | let mut ambiguous = messages.clone(); |
| 884 | ambiguous.push(messages[0].clone()); |
| 885 | let mut remove = FastHashSet::from_iter([0]); |
| 886 | cascade_tool_pair_removals(&ambiguous, &mut remove); |
| 887 | assert_eq!(remove, FastHashSet::from_iter([0])); |
| 888 | } |
| 889 | |
| 890 | #[test] |
| 891 | fn offload_round_trips_full_paired_context_through_the_existing_retrieval_tool() { |
| 892 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 893 | use crate::tools::spec::{ToolContext, ToolSpec}; |
| 894 | use crate::tools::tool_result_retrieval::RetrieveToolResultTool; |
| 895 | use base64::Engine as _; |
| 896 | |
| 897 | let _env = lock_test_env(); |
| 898 | let _cost_guard = crate::cost_status::test_scope(); |
| 899 | let home = tempfile::tempdir().unwrap(); |
| 900 | let state = home.path().join("explicit-state"); |
| 901 | let _state = EnvVarGuard::set("CODEWHALE_HOME", &state); |
| 902 | let session_id = "purge-owned-session"; |
| 903 | let messages: Vec<Message> = serde_json::from_value(json!([ |
| 904 | {"role":"user", "content":[{"type":"text", "text":"Keep the task"}]}, |
| 905 | {"role":"assistant", "content":[ |
| 906 | {"type":"thinking", "thinking":"retained reasoning", "signature":"signed-exact"}, |
| 907 | {"type":"tool_use", "id":"read-original", "name":"read_file", "input":{"path":"old.rs"}, "thought_signature":"google-exact"} |
| 908 | ]}, |
| 909 | {"role":"user", "content":[ |
| 910 | {"type":"tool_result", "tool_use_id":"read-original", "content":"original-file-data\n".repeat(1000), "content_blocks":[{"type":"image","source":{"data":"Zml4dHVyZQ=="}}]}, |
| 911 | {"type":"image_url", "image_url":{"url":"data:image/png;base64,Zml4dHVyZQ=="}} |
| 912 | ]}, |
| 913 | {"role":"assistant", "content":[{"type":"text", "text":"Keep the current answer"}]} |
| 914 | ])).unwrap(); |
| 915 | let original = messages.clone(); |
| 916 | let mock = MockLlmClient::new(vec![]); |
| 917 | mock.push_message_response(msg_response_with_tool_call(json!([ |
| 918 | {"op":"offload", "msg":3} |
| 919 | ]))); |
| 920 | let runtime = tokio::runtime::Builder::new_current_thread() |
| 921 | .enable_all() |
| 922 | .build() |
| 923 | .unwrap(); |
| 924 | let result = runtime |
| 925 | .block_on(run_purge( |
| 926 | &mock, |
| 927 | ProviderKind::Deepseek, |
| 928 | session_id, |
| 929 | &messages, |
| 930 | "mock", |
| 931 | None, |
| 932 | 4096, |
| 933 | Some( |
| 934 | crate::session_manager::SessionManager::default_location() |
| 935 | .expect("fixture manager") |
| 936 | .expect_absent_session(session_id) |
| 937 | .expect("native fixture source") |
| 938 | .usage_origin(crate::cost_status::scope_token()) |
| 939 | .expect("native fixture origin"), |
| 940 | ), |
| 941 | )) |
| 942 | .unwrap(); |
| 943 | assert_eq!(messages, original); |
| 944 | assert_eq!(result.offloaded_count, 2); |
| 945 | assert_eq!(result.removed_count, 0); |
| 946 | assert_eq!(result.messages.len(), 3); |
| 947 | assert_eq!(result.messages[0], original[0]); |
| 948 | assert_eq!(result.messages[2], original[3]); |
| 949 | assert!( |
| 950 | serde_json::to_vec(&result.messages).unwrap().len() |
| 951 | < serde_json::to_vec(&original).unwrap().len() |
| 952 | ); |
| 953 | let pointer = block_content_text(&result.messages[1].content[0]); |
| 954 | let handle = pointer |
| 955 | .split_whitespace() |
| 956 | .find(|part| part.starts_with("art_purge_")) |
| 957 | .unwrap() |
| 958 | .trim_end_matches(','); |
| 959 | let context = ToolContext::new(home.path()).with_state_namespace(session_id); |
| 960 | let retrieved = runtime |
| 961 | .block_on(RetrieveToolResultTool.execute( |
| 962 | json!({"ref":handle,"mode":"bytes","generation":1,"max_bytes":131072}), |
| 963 | &context, |
| 964 | )) |
| 965 | .unwrap(); |
| 966 | let payload: serde_json::Value = serde_json::from_str(&retrieved.content).unwrap(); |
| 967 | let bytes = base64::engine::general_purpose::STANDARD |
| 968 | .decode(payload["data"].as_str().unwrap()) |
| 969 | .unwrap(); |
| 970 | let archive: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); |
| 971 | let restored: Vec<Message> = archive["messages"] |
| 972 | .as_array() |
| 973 | .unwrap() |
| 974 | .iter() |
| 975 | .map(|entry| serde_json::from_value(entry["message"].clone()).unwrap()) |
| 976 | .collect(); |
| 977 | assert_eq!(restored, original[1..3]); |
| 978 | assert_eq!(archive["messages"][0]["message_id"], 2); |
| 979 | assert_eq!(archive["messages"][1]["message_id"], 3); |
| 980 | let metadata = |
| 981 | crate::tools::large_output_router::read_evidence_metadata(session_id, handle).unwrap(); |
| 982 | assert_eq!(metadata.retain_until_unix_ms, u64::MAX); |
| 983 | let path = state |
| 984 | .join("sessions") |
| 985 | .join(session_id) |
| 986 | .join(&metadata.storage_path); |
| 987 | assert_eq!(std::fs::read(&path).unwrap(), bytes); |
| 988 | let other = ToolContext::new(home.path()).with_state_namespace("another-session"); |
| 989 | assert!( |
| 990 | runtime |
| 991 | .block_on( |
| 992 | RetrieveToolResultTool.execute(json!({"ref":handle,"mode":"bytes"}), &other) |
| 993 | ) |
| 994 | .is_err() |
| 995 | ); |
| 996 | std::fs::write(path, b"changed fixture").unwrap(); |
| 997 | assert!( |
| 998 | runtime |
| 999 | .block_on( |
| 1000 | RetrieveToolResultTool.execute(json!({"ref":handle,"mode":"bytes"}), &context) |
| 1001 | ) |
| 1002 | .is_err() |
| 1003 | ); |
| 1004 | } |
| 1005 | |
| 1006 | #[test] |
| 1007 | fn offload_closes_server_tool_pairs_and_wins_over_overlapping_destructive_operations() { |
| 1008 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 1009 | let _env = lock_test_env(); |
| 1010 | let home = tempfile::tempdir().unwrap(); |
| 1011 | let _state = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 1012 | let messages: Vec<Message> = serde_json::from_value(json!([ |
| 1013 | {"role":"assistant", "content":[ |
| 1014 | {"type":"server_tool_use", "id":"search", "name":"tool_search", "input":{}}, |
| 1015 | {"type":"server_tool_use", "id":"execute", "name":"code_execution", "input":{}} |
| 1016 | ]}, |
| 1017 | {"role":"assistant", "content":[{"type":"tool_search_tool_result", "tool_use_id":"search", "content":{"tools":["read"]}}]}, |
| 1018 | {"role":"assistant", "content":[{"type":"code_execution_tool_result", "tool_use_id":"execute", "content":{"output":"exact"}}]}, |
| 1019 | {"role":"user", "content":[{"type":"text", "text":"keep"}]} |
| 1020 | ])).unwrap(); |
| 1021 | let ops = parse_purge_operations( |
| 1022 | &json!({"operations":[ |
| 1023 | {"op":"remove", "msg":1}, {"op":"offload", "msg":2}, |
| 1024 | {"op":"replace", "msg":3, "block":0, "pattern":"exact", "with":"lost"} |
| 1025 | ]}), |
| 1026 | messages.len(), |
| 1027 | ) |
| 1028 | .unwrap(); |
| 1029 | let result = execute_purge_operations(&messages, &ops, "server-pairs").unwrap(); |
| 1030 | assert_eq!(result.offloaded_count, 3); |
| 1031 | assert_eq!(result.removed_count, 0); |
| 1032 | assert_eq!(result.replaced_count, 0); |
| 1033 | assert_eq!(result.messages.len(), 2); |
| 1034 | assert_eq!(result.messages[1], messages[3]); |
| 1035 | } |
| 1036 | |
| 1037 | #[test] |
| 1038 | fn offload_storage_failure_leaves_mixed_purge_history_unchanged() { |
| 1039 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 1040 | let _env = lock_test_env(); |
| 1041 | let home = tempfile::tempdir().unwrap(); |
| 1042 | let _state = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 1043 | std::fs::write(home.path().join("sessions"), b"not a directory").unwrap(); |
| 1044 | let messages = vec![msg_text("user", "keep"), msg_text("assistant", "original")]; |
| 1045 | let original = messages.clone(); |
| 1046 | let ops = parse_purge_operations(&json!({"operations":[ |
| 1047 | {"op":"remove", "msg":1}, {"op":"replace", "msg":2, "block":0, "pattern":"original", "with":"lost"}, {"op":"offload", "msg":2} |
| 1048 | ]}), messages.len()).unwrap(); |
| 1049 | let error = execute_purge_operations(&messages, &ops, "storage-failure").unwrap_err(); |
| 1050 | assert!(error.contains("history unchanged")); |
| 1051 | assert_eq!(messages, original); |
| 1052 | } |
| 1053 | |
| 1054 | #[test] |
| 1055 | fn parse_remove_operations() { |
| 1056 | let input = json!({ |
| 1057 | "operations": [ |
| 1058 | {"op": "remove", "msg": 1}, |
| 1059 | {"op": "remove", "msg": 3} |
| 1060 | ] |
| 1061 | }); |
| 1062 | let ops = parse_purge_operations(&input, 5).unwrap(); |
| 1063 | assert_eq!(ops.len(), 2); |
| 1064 | assert!(matches!(ops[0], PurgeOp::Remove { msg_id: 1 })); |
| 1065 | assert!(matches!(ops[1], PurgeOp::Remove { msg_id: 3 })); |
| 1066 | } |
| 1067 | |
| 1068 | #[test] |
| 1069 | fn parse_replace_operation() { |
| 1070 | let input = json!({ |
| 1071 | "operations": [ |
| 1072 | {"op": "replace", "msg": 2, "block": 0, "pattern": "hello", "with": "hi"} |
| 1073 | ] |
| 1074 | }); |
| 1075 | let ops = parse_purge_operations(&input, 5).unwrap(); |
| 1076 | assert_eq!(ops.len(), 1); |
| 1077 | assert!(matches!(ops[0], PurgeOp::Replace { msg_id: 2, .. })); |
| 1078 | } |
| 1079 | |
| 1080 | #[test] |
| 1081 | fn parse_rejects_out_of_range_msg() { |
| 1082 | let input = json!({"operations": [{"op": "remove", "msg": 10}]}); |
| 1083 | assert!(parse_purge_operations(&input, 5).is_err()); |
| 1084 | } |
| 1085 | |
| 1086 | #[test] |
| 1087 | fn parse_rejects_invalid_regex() { |
| 1088 | let input = json!({ |
| 1089 | "operations": [{"op": "replace", "msg": 1, "block": 0, "pattern": "[", "with": "x"}] |
| 1090 | }); |
| 1091 | assert!(parse_purge_operations(&input, 5).is_err()); |
| 1092 | } |
| 1093 | |
| 1094 | #[test] |
| 1095 | fn execute_remove_works() { |
| 1096 | let msgs = vec![ |
| 1097 | msg_text("user", "hello"), |
| 1098 | msg_text("assistant", "hi there"), |
| 1099 | msg_text("user", "bye"), |
| 1100 | ]; |
| 1101 | let ops = vec![PurgeOp::Remove { msg_id: 2 }]; |
| 1102 | let result = execute_purge_operations(&msgs, &ops, "purge-test").unwrap(); |
| 1103 | assert_eq!(result.removed_count, 1); |
| 1104 | assert_eq!(result.messages.len(), 2); |
| 1105 | } |
| 1106 | |
| 1107 | #[test] |
| 1108 | fn execute_replace_text_block() { |
| 1109 | let msgs = vec![msg_text("assistant", "Hello world! Hello again!")]; |
| 1110 | let pattern = Regex::new("Hello").unwrap(); |
| 1111 | let ops = vec![PurgeOp::Replace { |
| 1112 | msg_id: 1, |
| 1113 | block_idx: 0, |
| 1114 | pattern, |
| 1115 | with: "Hi".to_string(), |
| 1116 | }]; |
| 1117 | let result = execute_purge_operations(&msgs, &ops, "purge-test").unwrap(); |
| 1118 | assert_eq!(result.replaced_count, 1); |
| 1119 | |
| 1120 | if let ContentBlock::Text { text, .. } = &result.messages[0].content[0] { |
| 1121 | assert_eq!(text, "Hi world! Hi again!"); |
| 1122 | } else { |
| 1123 | panic!("expected text block"); |
| 1124 | } |
| 1125 | } |
| 1126 | |
| 1127 | #[test] |
| 1128 | fn tool_call_result_pairing_cascaded() { |
| 1129 | // Message 2 (idx 1) is a tool call. Message 3 (idx 2) is its result. |
| 1130 | // Removing the tool call should cascade to remove the result too. |
| 1131 | let msgs = vec![ |
| 1132 | msg_text("user", "read a file"), |
| 1133 | msg_tool_use("call_01", "read_file", json!({"path": "x.rs"})), |
| 1134 | msg_tool_result("call_01", "fn main() {}"), |
| 1135 | ]; |
| 1136 | let ops = vec![PurgeOp::Remove { msg_id: 2 }]; // remove tool call only |
| 1137 | let result = execute_purge_operations(&msgs, &ops, "purge-test").unwrap(); |
| 1138 | // Both tool call and its result should be gone (cascaded). |
| 1139 | assert_eq!( |
| 1140 | result.removed_count, 2, |
| 1141 | "tool call + its result should both be removed" |
| 1142 | ); |
| 1143 | assert_eq!(result.messages.len(), 1); |
| 1144 | } |
| 1145 | |
| 1146 | #[test] |
| 1147 | fn tool_result_removal_cascades_to_call() { |
| 1148 | // Removing the result should cascade to remove the call. |
| 1149 | let msgs = vec![ |
| 1150 | msg_text("user", "read a file"), |
| 1151 | msg_tool_use("call_01", "read_file", json!({"path": "x.rs"})), |
| 1152 | msg_tool_result("call_01", "fn main() {}"), |
| 1153 | ]; |
| 1154 | let ops = vec![PurgeOp::Remove { msg_id: 3 }]; // remove result only |
| 1155 | let result = execute_purge_operations(&msgs, &ops, "purge-test").unwrap(); |
| 1156 | assert_eq!( |
| 1157 | result.removed_count, 2, |
| 1158 | "tool result + its call should both be removed" |
| 1159 | ); |
| 1160 | assert_eq!(result.messages.len(), 1); |
| 1161 | } |
| 1162 | |
| 1163 | #[test] |
| 1164 | fn prompt_truncates_long_content() { |
| 1165 | let long_text = "x".repeat(200); |
| 1166 | let msgs = vec![msg_text("user", &long_text)]; |
| 1167 | let prompt = build_purge_prompt(&msgs); |
| 1168 | assert!(prompt.contains("(200 chars)")); |
| 1169 | assert!(prompt.contains("xxx...")); // truncated |
| 1170 | assert!(!prompt.contains(&long_text)); |
| 1171 | } |
| 1172 | |
| 1173 | #[test] |
| 1174 | fn prompt_shows_full_short_content() { |
| 1175 | let msgs = vec![msg_text("user", "hi")]; |
| 1176 | let prompt = build_purge_prompt(&msgs); |
| 1177 | assert!(prompt.contains("\"hi\"")); |
| 1178 | assert!(!prompt.contains("...")); |
| 1179 | } |
| 1180 | |
| 1181 | #[test] |
| 1182 | fn prompt_omits_thinking_blocks() { |
| 1183 | let msgs = vec![Message { |
| 1184 | role: Role::Assistant, |
| 1185 | content: vec![ |
| 1186 | ContentBlock::Thinking { |
| 1187 | signature: None, |
| 1188 | state: None, |
| 1189 | thinking: "let me think...".to_string(), |
| 1190 | redacted_data: None, |
| 1191 | }, |
| 1192 | ContentBlock::Text { |
| 1193 | text: "done".to_string(), |
| 1194 | cache_control: None, |
| 1195 | }, |
| 1196 | ], |
| 1197 | }]; |
| 1198 | let prompt = build_purge_prompt(&msgs); |
| 1199 | assert!(!prompt.contains("let me think")); |
| 1200 | assert!(prompt.contains("Text (4 chars)")); |
| 1201 | } |
| 1202 | |
| 1203 | #[test] |
| 1204 | fn build_purge_tool_has_correct_shape() { |
| 1205 | let tool = build_purge_tool(); |
| 1206 | assert_eq!(tool.name, "purge_context"); |
| 1207 | let schema = &tool.input_schema; |
| 1208 | assert_eq!(schema["type"], "object"); |
| 1209 | assert!(schema["properties"]["operations"]["type"] == "array"); |
| 1210 | let ops_item = &schema["properties"]["operations"]["items"]; |
| 1211 | assert_eq!(ops_item["type"], "object"); |
| 1212 | let required = ops_item["required"].as_array().unwrap(); |
| 1213 | assert!(required.contains(&json!("op"))); |
| 1214 | assert!(required.contains(&json!("msg"))); |
| 1215 | } |
| 1216 | |
| 1217 | use crate::llm_client::mock::MockLlmClient; |
| 1218 | use codewhale_models::{MessageResponse, Usage}; |
| 1219 | |
| 1220 | fn msg_response_with_tool_call(operations: serde_json::Value) -> MessageResponse { |
| 1221 | MessageResponse { |
| 1222 | tool_projection_warning: None, |
| 1223 | id: "resp_test".to_string(), |
| 1224 | r#type: "message".to_string(), |
| 1225 | role: "assistant".to_string(), |
| 1226 | content: vec![ContentBlock::ToolUse { |
| 1227 | execution_id: None, |
| 1228 | id: "call_purge".to_string(), |
| 1229 | name: "purge_context".to_string(), |
| 1230 | input: json!({"operations": operations}), |
| 1231 | caller: None, |
| 1232 | thought_signature: None, |
| 1233 | }], |
| 1234 | model: "mock-model".to_string(), |
| 1235 | stop_reason: None, |
| 1236 | stop_sequence: None, |
| 1237 | container: None, |
| 1238 | usage: Usage::default(), |
| 1239 | title: None, |
| 1240 | stop_details: None, |
| 1241 | refusal: None, |
| 1242 | } |
| 1243 | } |
| 1244 | |
| 1245 | fn msg_response_without_tool_call(text: &str) -> MessageResponse { |
| 1246 | MessageResponse { |
| 1247 | tool_projection_warning: None, |
| 1248 | id: "resp_plain".to_string(), |
| 1249 | r#type: "message".to_string(), |
| 1250 | role: "assistant".to_string(), |
| 1251 | content: vec![ContentBlock::Text { |
| 1252 | text: text.to_string(), |
| 1253 | cache_control: None, |
| 1254 | }], |
| 1255 | model: "mock".to_string(), |
| 1256 | stop_reason: None, |
| 1257 | stop_sequence: None, |
| 1258 | container: None, |
| 1259 | usage: Usage::default(), |
| 1260 | title: None, |
| 1261 | stop_details: None, |
| 1262 | refusal: None, |
| 1263 | } |
| 1264 | } |
| 1265 | |
| 1266 | #[tokio::test] |
| 1267 | async fn run_purge_removes_message() { |
| 1268 | let _env = crate::test_support::lock_test_env(); |
| 1269 | let home = tempfile::tempdir().unwrap(); |
| 1270 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 1271 | let _cost_guard = crate::cost_status::test_scope(); |
| 1272 | let mock = MockLlmClient::new(vec![]); |
| 1273 | mock.push_message_response(msg_response_with_tool_call(json!([ |
| 1274 | {"op": "remove", "msg": 2} |
| 1275 | ]))); |
| 1276 | |
| 1277 | let messages = vec![ |
| 1278 | msg_text("user", "hello"), |
| 1279 | msg_text("assistant", "remove me"), |
| 1280 | msg_text("user", "bye"), |
| 1281 | ]; |
| 1282 | |
| 1283 | let result = run_purge( |
| 1284 | &mock, |
| 1285 | ProviderKind::Deepseek, |
| 1286 | "purge-test", |
| 1287 | &messages, |
| 1288 | "mock", |
| 1289 | None, |
| 1290 | 4096, |
| 1291 | Some( |
| 1292 | crate::session_manager::SessionManager::default_location() |
| 1293 | .expect("fixture manager") |
| 1294 | .expect_absent_session("purge-test") |
| 1295 | .expect("native fixture source") |
| 1296 | .usage_origin(crate::cost_status::scope_token()) |
| 1297 | .expect("native fixture origin"), |
| 1298 | ), |
| 1299 | ) |
| 1300 | .await |
| 1301 | .unwrap(); |
| 1302 | assert_eq!(result.removed_count, 1); |
| 1303 | assert_eq!(result.replaced_count, 0); |
| 1304 | assert_eq!(result.messages.len(), 2); |
| 1305 | |
| 1306 | if let ContentBlock::Text { text, .. } = &result.messages[0].content[0] { |
| 1307 | assert_eq!(text, "hello"); |
| 1308 | } else { |
| 1309 | panic!( |
| 1310 | "expected text block, got {:?}", |
| 1311 | result.messages[0].content[0] |
| 1312 | ); |
| 1313 | } |
| 1314 | if let ContentBlock::Text { text, .. } = &result.messages[1].content[0] { |
| 1315 | assert_eq!(text, "bye"); |
| 1316 | } else { |
| 1317 | panic!( |
| 1318 | "expected text block, got {:?}", |
| 1319 | result.messages[1].content[0] |
| 1320 | ); |
| 1321 | } |
| 1322 | } |
| 1323 | |
| 1324 | #[tokio::test] |
| 1325 | async fn run_purge_replace_condenses_text() { |
| 1326 | let _env = crate::test_support::lock_test_env(); |
| 1327 | let home = tempfile::tempdir().unwrap(); |
| 1328 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 1329 | let _cost_guard = crate::cost_status::test_scope(); |
| 1330 | let mock = MockLlmClient::new(vec![]); |
| 1331 | mock.push_message_response(msg_response_with_tool_call(json!([ |
| 1332 | {"op": "replace", "msg": 1, "block": 0, "pattern": "very long and verbose", "with": "short"} |
| 1333 | ]))); |
| 1334 | |
| 1335 | let messages = vec![msg_text("assistant", "this is very long and verbose text")]; |
| 1336 | |
| 1337 | let result = run_purge( |
| 1338 | &mock, |
| 1339 | ProviderKind::Deepseek, |
| 1340 | "purge-test", |
| 1341 | &messages, |
| 1342 | "mock", |
| 1343 | None, |
| 1344 | 4096, |
| 1345 | Some( |
| 1346 | crate::session_manager::SessionManager::default_location() |
| 1347 | .expect("fixture manager") |
| 1348 | .expect_absent_session("purge-test") |
| 1349 | .expect("native fixture source") |
| 1350 | .usage_origin(crate::cost_status::scope_token()) |
| 1351 | .expect("native fixture origin"), |
| 1352 | ), |
| 1353 | ) |
| 1354 | .await |
| 1355 | .unwrap(); |
| 1356 | assert_eq!(result.removed_count, 0); |
| 1357 | assert_eq!(result.replaced_count, 1); |
| 1358 | |
| 1359 | if let ContentBlock::Text { text, .. } = &result.messages[0].content[0] { |
| 1360 | assert_eq!(text, "this is short text"); |
| 1361 | } else { |
| 1362 | panic!( |
| 1363 | "expected text block, got {:?}", |
| 1364 | result.messages[0].content[0] |
| 1365 | ); |
| 1366 | } |
| 1367 | } |
| 1368 | |
| 1369 | #[tokio::test] |
| 1370 | async fn run_purge_errors_when_no_tool_call() { |
| 1371 | let _env = crate::test_support::lock_test_env(); |
| 1372 | let home = tempfile::tempdir().unwrap(); |
| 1373 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 1374 | let _cost_guard = crate::cost_status::test_scope(); |
| 1375 | let mock = MockLlmClient::new(vec![]); |
| 1376 | mock.push_message_response(msg_response_without_tool_call("nothing to clean up")); |
| 1377 | |
| 1378 | let messages = vec![msg_text("user", "hi")]; |
| 1379 | let err = run_purge( |
| 1380 | &mock, |
| 1381 | ProviderKind::Deepseek, |
| 1382 | "purge-test", |
| 1383 | &messages, |
| 1384 | "mock", |
| 1385 | None, |
| 1386 | 4096, |
| 1387 | Some( |
| 1388 | crate::session_manager::SessionManager::default_location() |
| 1389 | .expect("fixture manager") |
| 1390 | .expect_absent_session("purge-test") |
| 1391 | .expect("native fixture source") |
| 1392 | .usage_origin(crate::cost_status::scope_token()) |
| 1393 | .expect("native fixture origin"), |
| 1394 | ), |
| 1395 | ) |
| 1396 | .await |
| 1397 | .unwrap_err(); |
| 1398 | assert!(err.contains("did not call purge_context")); |
| 1399 | } |
| 1400 | |
| 1401 | #[tokio::test] |
| 1402 | async fn run_purge_errors_on_api_failure() { |
| 1403 | let _env = crate::test_support::lock_test_env(); |
| 1404 | let home = tempfile::tempdir().unwrap(); |
| 1405 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 1406 | let _cost_guard = crate::cost_status::test_scope(); |
| 1407 | // No canned response — MockLlmClient returns an error. |
| 1408 | let mock = MockLlmClient::new(vec![]); |
| 1409 | let messages = vec![msg_text("user", "hi")]; |
| 1410 | let err = run_purge( |
| 1411 | &mock, |
| 1412 | ProviderKind::Deepseek, |
| 1413 | "purge-test", |
| 1414 | &messages, |
| 1415 | "mock", |
| 1416 | None, |
| 1417 | 4096, |
| 1418 | Some( |
| 1419 | crate::session_manager::SessionManager::default_location() |
| 1420 | .expect("fixture manager") |
| 1421 | .expect_absent_session("purge-test") |
| 1422 | .expect("native fixture source") |
| 1423 | .usage_origin(crate::cost_status::scope_token()) |
| 1424 | .expect("native fixture origin"), |
| 1425 | ), |
| 1426 | ) |
| 1427 | .await |
| 1428 | .unwrap_err(); |
| 1429 | assert!(err.contains("Purge API error")); |
| 1430 | } |
| 1431 | |
| 1432 | #[tokio::test] |
| 1433 | async fn purge_succeeds_with_unknown_cost() { |
| 1434 | let _cost_guard = crate::cost_status::test_scope(); |
| 1435 | let workspace = tempfile::tempdir().unwrap(); |
| 1436 | let broken_sessions_file = workspace.path().join("not-a-sessions-dir"); |
| 1437 | std::fs::write(&broken_sessions_file, b"file").unwrap(); |
| 1438 | |
| 1439 | for origin in [ |
| 1440 | None, |
| 1441 | Some(crate::cost_status::NativeUsageOrigin::session( |
| 1442 | crate::cost_status::scope_token(), |
| 1443 | broken_sessions_file, |
| 1444 | "purge-broken-session".to_string(), |
| 1445 | )), |
| 1446 | ] { |
| 1447 | let mock = MockLlmClient::new(vec![]); |
| 1448 | mock.push_message_response(msg_response_with_tool_call(json!([ |
| 1449 | {"op": "remove", "msg": 2} |
| 1450 | ]))); |
| 1451 | let messages = vec![ |
| 1452 | msg_text("user", "hello"), |
| 1453 | msg_text("assistant", "remove me"), |
| 1454 | msg_text("user", "bye"), |
| 1455 | ]; |
| 1456 | let result = run_purge( |
| 1457 | &mock, |
| 1458 | ProviderKind::Deepseek, |
| 1459 | "purge-unknown-cost", |
| 1460 | &messages, |
| 1461 | "mock", |
| 1462 | None, |
| 1463 | 4096, |
| 1464 | origin, |
| 1465 | ) |
| 1466 | .await |
| 1467 | .expect("purge must succeed with unknown cost"); |
| 1468 | assert_eq!(result.removed_count, 1); |
| 1469 | assert_eq!(result.messages.len(), 2); |
| 1470 | } |
| 1471 | } |
| 1472 | } |
| 1473 |