| 1 | //! Context compaction (`/compact`), mirroring pi's coding agent. |
| 2 | //! |
| 3 | //! Older turns are summarized by the model into a structured context |
| 4 | //! checkpoint (`Goal`, `Progress`, `Next Steps`, …) that replaces them in the |
| 5 | //! context sent to the model, while the most recent ~`KEEP_RECENT_TOKENS` stay |
| 6 | //! verbatim. The summary is stored as a `compaction` message row (with |
| 7 | //! `cut_msg_id` pointing at the first kept message) so the agent loop can |
| 8 | //! rebuild the context without the summarized turns. |
| 9 | |
| 10 | use std::collections:: |
| 11 | use std::sync:: |
| 12 | |
| 13 | use anyhow::{Result |
| 14 | use rusqlite::Connection |
| 15 | use serde_json::Value |
| 16 | |
| 17 | use crate::db::{self |
| 18 | use crate::llm::{self |
| 19 | |
| 20 | /// Recent context (estimated tokens) that compaction always keeps verbatim. |
| 21 | const KEEP_RECENT_TOKENS: usize |
| 22 | /// Reserved for the summary + provider overhead when auto-compacting. Manual |
| 23 | /// compaction uses it to size the summarization request. |
| 24 | const RESERVE_TOKENS: usize |
| 25 | /// Conservative chars-per-token heuristic (pi uses chars/4). |
| 26 | const CHARS_PER_TOKEN: usize |
| 27 | /// Token weight of a pasted image in a user message. |
| 28 | const ESTIMATED_IMAGE_CHARS: usize |
| 29 | /// Tool results are truncated to this many chars when serialized for |
| 30 | /// summarization — the full content isn't needed for a summary. |
| 31 | const TOOL_RESULT_MAX_CHARS: usize |
| 32 | |
| 33 | /// Wrap the stored summary in these tags when it is injected back into the |
| 34 | /// model context (pi's `COMPACTION_SUMMARY_PREFIX` / `_SUFFIX`). |
| 35 | pub const COMPACTION_SUMMARY_PREFIX |
| 36 | pub const COMPACTION_SUMMARY_SUFFIX |
| 37 | |
| 38 | const SUMMARIZATION_SYSTEM_PROMPT: &str |
| 39 | |
| 40 | Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary."; |
| 41 | |
| 42 | const SUMMARIZATION_PROMPT: &str |
| 43 | |
| 44 | Use this EXACT format: |
| 45 | |
| 46 | ## Goal |
| 47 | [What is the user trying to accomplish? Can be multiple items if the session covers different tasks.] |
| 48 | |
| 49 | ## Constraints & Preferences |
| 50 | - [Any constraints, preferences, or requirements mentioned by user] |
| 51 | - [Or \"(none)\" if none were mentioned] |
| 52 | |
| 53 | ## Progress |
| 54 | ### Done |
| 55 | - [x] [Completed tasks/changes] |
| 56 | |
| 57 | ### In Progress |
| 58 | - [ ] [Current work] |
| 59 | |
| 60 | ### Blocked |
| 61 | - [Issues preventing progress, if any] |
| 62 | |
| 63 | ## Key Decisions |
| 64 | - **[Decision]**: [Brief rationale] |
| 65 | |
| 66 | ## Next Steps |
| 67 | 1. [Ordered list of what should happen next] |
| 68 | |
| 69 | ## Critical Context |
| 70 | - [Any data, examples, or references needed to continue] |
| 71 | - [Or \"(none)\" if not applicable] |
| 72 | |
| 73 | Keep each section concise. Preserve exact file paths, function names, and error messages."; |
| 74 | |
| 75 | const UPDATE_SUMMARIZATION_PROMPT: &str |
| 76 | |
| 77 | Update the existing structured summary with new information. RULES: |
| 78 | - PRESERVE all existing information from the previous summary |
| 79 | - ADD new progress, decisions, and context from the new messages |
| 80 | - UPDATE the Progress section: move items from \"In Progress\" to \"Done |
| 81 | - UPDATE \"Next Steps\" based on what was accomplished |
| 82 | - PRESERVE exact file paths, function names, and error messages |
| 83 | - If something is no longer relevant, you may remove it |
| 84 | |
| 85 | Use this EXACT format: |
| 86 | |
| 87 | ## Goal |
| 88 | [Preserve existing goals, add new ones if the task expanded] |
| 89 | |
| 90 | ## Constraints & Preferences |
| 91 | - [Preserve existing, add new ones discovered] |
| 92 | |
| 93 | ## Progress |
| 94 | ### Done |
| 95 | - [x] [Include previously done items AND newly completed items] |
| 96 | |
| 97 | ### In Progress |
| 98 | - [ ] [Current work - update based on progress] |
| 99 | |
| 100 | ### Blocked |
| 101 | - [Current blockers - remove if resolved] |
| 102 | |
| 103 | ## Key Decisions |
| 104 | - **[Decision]**: [Brief rationale] (preserve all previous, add new) |
| 105 | |
| 106 | ## Next Steps |
| 107 | 1. [Update based on current state] |
| 108 | |
| 109 | ## Critical Context |
| 110 | - [Preserve important context, add new if needed] |
| 111 | |
| 112 | Keep each section concise. Preserve exact file paths, function names, and error messages."; |
| 113 | |
| 114 | const TURN_PREFIX_SUMMARIZATION_PROMPT: &str |
| 115 | "This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained. |
| 116 | |
| 117 | Summarize the prefix to provide context for the retained suffix: |
| 118 | |
| 119 | ## Original Request |
| 120 | [What did the user ask for in this turn?] |
| 121 | |
| 122 | ## Early Progress |
| 123 | - [Key decisions and work done in the prefix] |
| 124 | |
| 125 | ## Context for Suffix |
| 126 | - [Information needed to understand the retained recent work] |
| 127 | |
| 128 | Be concise. Focus on what's needed to understand the kept suffix."; |
| 129 | |
| 130 | /// Result of a manual compaction run. |
| 131 | pub struct CompactionResult |
| 132 | /// Estimated total context tokens before compaction. |
| 133 | pub tokens_before: usize |
| 134 | /// Number of message rows folded into the summary. |
| 135 | pub dropped: usize |
| 136 | /// Number of message rows kept verbatim. |
| 137 | pub kept: usize |
| 138 | } |
| 139 | |
| 140 | /// Estimate how many context tokens a stored message contributes, using the |
| 141 | /// same chars/4 heuristic pi uses (deliberately conservative / an overestimate). |
| 142 | pub fn estimate_tokens(m |
| 143 | let mut chars |
| 144 | match m.role.as_str |
| 145 | "user" => { |
| 146 | if let Some |
| 147 | && let Ok |
| 148 | { |
| 149 | chars += parts. |
| 150 | } |
| 151 | } |
| 152 | "assistant" => { |
| 153 | chars += m |
| 154 | .tool_calls |
| 155 | .as_deref() |
| 156 | .map(|s| |
| 157 | .unwrap_or(0); |
| 158 | } |
| 159 | _ => {} |
| 160 | } |
| 161 | chars.div_ceil(CHARS_PER_TOKEN |
| 162 | } |
| 163 | |
| 164 | /// Estimate how many context tokens a resolved, ready-to-send message |
| 165 | /// contributes (same chars/4 heuristic as `estimate_tokens`). Counts the |
| 166 | /// content plus any tool call JSON. Used for the threshold check so the |
| 167 | /// estimate reflects what actually goes to the provider — folded history that |
| 168 | /// `resolve_compaction` drops must not keep pushing the estimate over the |
| 169 | /// threshold (that made every round after a compaction re-compact). |
| 170 | pub fn estimate_llm_tokens(m |
| 171 | let mut chars |
| 172 | for t in & |
| 173 | chars += t. |
| 174 | chars += t. |
| 175 | chars += t. |
| 176 | } |
| 177 | if let Some |
| 178 | chars += name. |
| 179 | } |
| 180 | chars.div_ceil(CHARS_PER_TOKEN |
| 181 | } |
| 182 | |
| 183 | /// Total estimated context tokens of a resolved message list (the actual |
| 184 | /// request payload, per pi's `estimateContextTokens`). |
| 185 | pub fn estimate_llm_context_tokens(messages |
| 186 | messages.iter().map |
| 187 | } |
| 188 | |
| 189 | /// Messages that may end up on the summary/keep boundary. Tool results are |
| 190 | /// never cut points — they must follow their assistant tool call. |
| 191 | fn is_cut_point(m: |
| 192 | matches!(m.role |
| 193 | } |
| 194 | |
| 195 | /// Estimate the total context tokens of the stored conversation (pi's |
| 196 | /// `estimateContextTokens`), using the same chars/4 heuristic as |
| 197 | /// `estimate_tokens`. |
| 198 | pub fn estimate_context_tokens(messages |
| 199 | messages.iter().map |
| 200 | } |
| 201 | |
| 202 | /// Whether the context has grown within `RESERVE_TOKENS` of the provider's |
| 203 | /// context window and should be proactively compacted before the next request |
| 204 | /// (pi's `shouldCompact`: `contextTokens > contextWindow - reserveTokens`). |
| 205 | pub fn should_compact(context_tokens |
| 206 | context_tokens > context_window. |
| 207 | } |
| 208 | |
| 209 | /// Messages that start a turn (cutting before these is always clean). |
| 210 | fn is_turn_start(m: |
| 211 | matches!(m.role |
| 212 | } |
| 213 | |
| 214 | struct CutPoint { |
| 215 | /// Index of the first entry to keep. |
| 216 | first_kept_index: usize |
| 217 | /// Index of the user message that starts a split turn, if cutting mid-turn. |
| 218 | turn_start_index: Option |
| 219 | /// Whether the cut lands mid-turn (cut point is not a user message). |
| 220 | is_split_turn: bool |
| 221 | } |
| 222 | |
| 223 | /// Find the cut point that keeps approximately `KEEP_RECENT_TOKENS`: walk |
| 224 | /// backwards from the newest message accumulating estimated sizes, then cut at |
| 225 | /// the closest valid cut point. Only considers messages at/after `start`. |
| 226 | fn find_cut_point(messages: |
| 227 | let end = |
| 228 | let cut_points: Vec |
| 229 | .filter(|&i |
| 230 | .collect(); |
| 231 | if cut_points.is_empty() |
| 232 | return CutPoint { |
| 233 | first_kept_index: start, |
| 234 | turn_start_index: None |
| 235 | is_split_turn: false, |
| 236 | }; |
| 237 | } |
| 238 | |
| 239 | let mut accumulated |
| 240 | let mut cut_index |
| 241 | for i in ( |
| 242 | let tokens = |
| 243 | if tokens == 0 |
| 244 | continue; |
| 245 | } |
| 246 | accumulated += tokens; |
| 247 | if accumulated >= KEEP_RECENT_TOKENS |
| 248 | for &c in |
| 249 | if c >= i |
| 250 | cut_index = c; |
| 251 | break; |
| 252 | } |
| 253 | } |
| 254 | break; |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | let starts_turn = |
| 259 | let turn_start_index = |
| 260 | None |
| 261 | } else { |
| 262 | (start..=cut_index) |
| 263 | .rev() |
| 264 | .find(|&i |
| 265 | }; |
| 266 | |
| 267 | CutPoint { |
| 268 | first_kept_index: cut_index, |
| 269 | turn_start_index, |
| 270 | is_split_turn: turn_start_index.is_some |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | /// Serialize messages to plain text so the summarizer treats them as a |
| 275 | /// document, not a conversation to continue (pi's `serializeConversation`). |
| 276 | fn serialize_conversation(messages: |
| 277 | let mut parts |
| 278 | for m in messages |
| 279 | match m.role.as_str |
| 280 | "user" => { |
| 281 | if let Some |
| 282 | && !c.is_empty |
| 283 | { |
| 284 | parts.push(format! |
| 285 | } |
| 286 | } |
| 287 | "assistant" => { |
| 288 | let mut calls |
| 289 | if let Some |
| 290 | && let Ok |
| 291 | { |
| 292 | for t in & |
| 293 | let name = |
| 294 | let args = |
| 295 | calls.push(format! |
| 296 | } |
| 297 | } |
| 298 | if let Some |
| 299 | && !c.is_empty |
| 300 | { |
| 301 | parts.push(format! |
| 302 | } |
| 303 | if !calls.is_empty |
| 304 | parts.push(format! |
| 305 | } |
| 306 | } |
| 307 | "tool" => { |
| 308 | if let Some |
| 309 | && !c.is_empty |
| 310 | { |
| 311 | parts.push(format! |
| 312 | } |
| 313 | } |
| 314 | _ => {} |
| 315 | } |
| 316 | } |
| 317 | parts.join("\ |
| 318 | } |
| 319 | |
| 320 | fn truncate_for_summary(text: |
| 321 | let max_chars = |
| 322 | if text.chars() |
| 323 | return text.to_string(); |
| 324 | } |
| 325 | let kept: String |
| 326 | let truncated = |
| 327 | format!("{kept} |
| 328 | } |
| 329 | |
| 330 | /// Extract read/write/edit file paths from tool calls (pi's file-op tracking). |
| 331 | fn extract_file_ops(messages: |
| 332 | let mut read |
| 333 | let mut written |
| 334 | let mut edited |
| 335 | |
| 336 | for m in messages |
| 337 | if m.role != |
| 338 | continue; |
| 339 | } |
| 340 | let Some( |
| 341 | continue; |
| 342 | }; |
| 343 | let Ok( |
| 344 | continue; |
| 345 | }; |
| 346 | for t in & |
| 347 | let Some( |
| 348 | continue; |
| 349 | }; |
| 350 | match t["name" |
| 351 | Some("read_file") |
| 352 | read.insert(path |
| 353 | } |
| 354 | Some("write_file") |
| 355 | written.insert(path |
| 356 | } |
| 357 | Some("edit_file") |
| 358 | edited.insert(path |
| 359 | } |
| 360 | _ => {} |
| 361 | } |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | let modified: BTreeSet |
| 366 | let read_only: Vec |
| 367 | (read_only, modified. |
| 368 | } |
| 369 | |
| 370 | /// Append `<read-files>` / `<modified-files>` sections to the summary (pi's |
| 371 | /// `formatFileOperations`). |
| 372 | fn format_file_operations(read_files: |
| 373 | let mut sections |
| 374 | if !read_files.is_empty |
| 375 | sections.push(format! |
| 376 | "<read-files>\n{}\n</read-files>" |
| 377 | read_files.join("\ |
| 378 | )); |
| 379 | } |
| 380 | if !modified_files.is_empty |
| 381 | sections.push(format! |
| 382 | "<modified-files>\n{}\n</modified-files>" |
| 383 | modified_files.join("\ |
| 384 | )); |
| 385 | } |
| 386 | if sections.is_empty() |
| 387 | return String::new |
| 388 | } |
| 389 | format!("\n\ |
| 390 | } |
| 391 | |
| 392 | /// One LLM call that turns `messages` into the structured summary. If a |
| 393 | /// previous summary exists, the update prompt merges it in. |
| 394 | fn summarize( |
| 395 | messages: &[StoredMessage |
| 396 | previous_summary: Option |
| 397 | cfg: &ProviderConfig |
| 398 | model: &str |
| 399 | custom_instructions: Option |
| 400 | cancel: &AtomicBool |
| 401 | ) -> Result<String |
| 402 | let conversation_text = |
| 403 | let mut prompt_text |
| 404 | if let Some |
| 405 | prompt_text.push_str(&format! |
| 406 | "<previous-summary>\n{prev}\n |
| 407 | )); |
| 408 | } |
| 409 | prompt_text.push_str(if |
| 410 | UPDATE_SUMMARIZATION_PROMPT |
| 411 | } else { |
| 412 | SUMMARIZATION_PROMPT |
| 413 | }); |
| 414 | if let Some |
| 415 | && !ci.trim |
| 416 | { |
| 417 | prompt_text.push_str(&format! |
| 418 | } |
| 419 | |
| 420 | let msg = |
| 421 | role: "user". |
| 422 | content: Some |
| 423 | tool_call_id: None |
| 424 | name: None |
| 425 | tool_calls: vec![], |
| 426 | reasoning: None |
| 427 | images: vec![], |
| 428 | }; |
| 429 | // Summaries are standalone requests: cap output at a fraction of the |
| 430 | // reserved budget (pi: min(0.8 * reserveTokens, model max)), but never less |
| 431 | // than the provider's configured max_tokens. |
| 432 | let mut sum_cfg |
| 433 | sum_cfg.max_tokens = sum_cfg |
| 434 | let mut retry_sink |
| 435 | eprintln!( |
| 436 | " ⟳ summarization retry ({attempt}/{max} |
| 437 | wait_ms / 1000 |
| 438 | ); |
| 439 | }; |
| 440 | let resp = |
| 441 | &sum_cfg, |
| 442 | model, |
| 443 | SUMMARIZATION_SYSTEM_PROMPT, |
| 444 | &[msg], |
| 445 | &[], |
| 446 | None, |
| 447 | Some(&mut |
| 448 | cancel, |
| 449 | )?; |
| 450 | Ok(resp. |
| 451 | } |
| 452 | |
| 453 | /// Summarize the prefix of a turn that was too large to keep whole. |
| 454 | fn summarize_turn_prefix( |
| 455 | messages: &[StoredMessage |
| 456 | cfg: &ProviderConfig |
| 457 | model: &str |
| 458 | cancel: &AtomicBool |
| 459 | ) -> Result<String |
| 460 | let conversation_text = |
| 461 | let prompt_text = |
| 462 | "<conversation>\n{conversation_text}\n |
| 463 | ); |
| 464 | let msg = |
| 465 | role: "user". |
| 466 | content: Some |
| 467 | tool_call_id: None |
| 468 | name: None |
| 469 | tool_calls: vec![], |
| 470 | reasoning: None |
| 471 | images: vec![], |
| 472 | }; |
| 473 | let mut sum_cfg |
| 474 | // Smaller budget for the turn prefix (pi: 0.5 * reserveTokens). |
| 475 | sum_cfg.max_tokens = sum_cfg |
| 476 | let mut retry_sink |
| 477 | eprintln!( |
| 478 | " ⟳ turn-prefix summarization retry ({attempt}/{max} |
| 479 | wait_ms / 1000 |
| 480 | ); |
| 481 | }; |
| 482 | let resp = |
| 483 | &sum_cfg, |
| 484 | model, |
| 485 | SUMMARIZATION_SYSTEM_PROMPT, |
| 486 | &[msg], |
| 487 | &[], |
| 488 | None, |
| 489 | Some(&mut |
| 490 | cancel, |
| 491 | )?; |
| 492 | Ok(resp. |
| 493 | } |
| 494 | |
| 495 | /// Manually compact the session: summarize everything before a cut point that |
| 496 | /// keeps ~`KEEP_RECENT_TOKENS`, then record a `compaction` message row that |
| 497 | /// replaces the summarized turns in future context. Mirrors pi's `/compact`. |
| 498 | pub fn run( |
| 499 | conn: &Connection |
| 500 | session_id: i64 |
| 501 | cfg: &ProviderConfig |
| 502 | model: &str |
| 503 | custom_instructions: Option |
| 504 | cancel: &AtomicBool |
| 505 | ) -> Result<CompactionResult |
| 506 | // Session-global thinking effort (see `/effort`) applies to the summarizer |
| 507 | // call too; same rule as agent runs. |
| 508 | let mut cfg |
| 509 | if let Some |
| 510 | cfg.effort = Some |
| 511 | } |
| 512 | let messages = |
| 513 | if messages.is_empty() |
| 514 | bail!("Nothing to compact (session is empty)"); |
| 515 | } |
| 516 | if messages.last() |
| 517 | bail!("Already compacted — continue chatting before compacting again"); |
| 518 | } |
| 519 | |
| 520 | // Find the previous compaction (if any): its summary becomes the base for |
| 521 | // the update prompt, and its cut marks the earliest entry worth re-reading. |
| 522 | let mut previous_summary |
| 523 | let mut boundary_start |
| 524 | for (i, m |
| 525 | if m.role == |
| 526 | previous_summary = m. |
| 527 | boundary_start = messages |
| 528 | .iter() |
| 529 | .position(|x| |
| 530 | .unwrap_or(i + |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | let tokens_before = |
| 535 | |
| 536 | let cut = |
| 537 | let history_end = |
| 538 | let to_summarize = |
| 539 | let turn_prefix: & |
| 540 | Some(ts) |
| 541 | None => &[], |
| 542 | }; |
| 543 | |
| 544 | if to_summarize.is_empty() |
| 545 | bail!("Nothing to compact (session is small enough)"); |
| 546 | } |
| 547 | |
| 548 | let summary = |
| 549 | let history_text = |
| 550 | "No prior history.".to_string() |
| 551 | } else { |
| 552 | summarize( |
| 553 | to_summarize, |
| 554 | previous_summary.as_deref(), |
| 555 | &cfg, |
| 556 | model, |
| 557 | custom_instructions, |
| 558 | cancel, |
| 559 | )? |
| 560 | }; |
| 561 | let prefix_text = |
| 562 | format!("{history_text} |
| 563 | } else { |
| 564 | summarize( |
| 565 | to_summarize, |
| 566 | previous_summary.as_deref(), |
| 567 | &cfg, |
| 568 | model, |
| 569 | custom_instructions, |
| 570 | cancel, |
| 571 | )? |
| 572 | }; |
| 573 | |
| 574 | // File operation tracking survives the summarization (pi appends these to |
| 575 | // every compaction entry so future summaries can stay path-accurate). |
| 576 | let mut op_sources |
| 577 | op_sources.extend(turn_prefix |
| 578 | let (read_files, |
| 579 | let summary = |
| 580 | "{summary}{}", |
| 581 | format_file_operations(&read_files, |
| 582 | ); |
| 583 | |
| 584 | let first_kept_id = |
| 585 | db::add_compaction(conn |
| 586 | db::touch_session(conn |
| 587 | |
| 588 | let dropped = |
| 589 | Ok(CompactionResult |
| 590 | tokens_before, |
| 591 | dropped, |
| 592 | kept: messages.len |
| 593 | }) |
| 594 | } |
| 595 | |
| 596 | #[cfg(test)] |
| 597 | mod tests { |
| 598 | use super::*; |
| 599 | |
| 600 | fn msg(id: |
| 601 | StoredMessage { |
| 602 | id, |
| 603 | session_id: 1, |
| 604 | role: role.into |
| 605 | content: Some |
| 606 | tool_call_id: None |
| 607 | name: None |
| 608 | tool_calls: None |
| 609 | reasoning: None |
| 610 | images: None |
| 611 | usage: None |
| 612 | cut_msg_id: None |
| 613 | created_at: id, |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | #[test] |
| 618 | fn estimate_tokens_is_chars_over_four() { |
| 619 | assert_eq!(estimate_tokens( |
| 620 | assert_eq!(estimate_tokens( |
| 621 | assert_eq!(estimate_tokens( |
| 622 | } |
| 623 | |
| 624 | #[test] |
| 625 | fn threshold_triggers_within_reserve_of_window() { |
| 626 | // pi's shouldCompact: contextTokens > contextWindow - reserveTokens. |
| 627 | assert!(should_compact( |
| 628 | assert!(should_compact( |
| 629 | assert!(!should_compact |
| 630 | assert!(!should_compact |
| 631 | // A window smaller than the reserve saturates to zero: only a truly |
| 632 | // empty context avoids tripping. |
| 633 | assert!(!should_compact |
| 634 | assert!(should_compact( |
| 635 | |
| 636 | // estimate_context_tokens is the sum of the per-message estimates. |
| 637 | let msgs = |
| 638 | assert_eq!(estimate_context_tokens( |
| 639 | } |
| 640 | |
| 641 | #[test] |
| 642 | fn cut_point_keeps_recent_tokens() { |
| 643 | // 40 user messages of ~1000 chars (~250 tokens each) = ~10k tokens: |
| 644 | // small enough that nothing gets cut. |
| 645 | let msgs: Vec |
| 646 | .map(|i| |
| 647 | .collect(); |
| 648 | let cut = |
| 649 | assert_eq!(cut.first_kept_index |
| 650 | assert!(!cut. |
| 651 | |
| 652 | // 200 messages of ~1000 chars (~250 tokens) = ~50k tokens: the cut |
| 653 | // should land somewhere after the 80-most-recent (~20k) and keep a |
| 654 | // clean user boundary. |
| 655 | let msgs: Vec |
| 656 | .map(|i| |
| 657 | .collect(); |
| 658 | let cut = |
| 659 | assert!(cut.first_kept_index |
| 660 | assert!(!cut. |
| 661 | assert!(msgs[cut |
| 662 | } |
| 663 | |
| 664 | #[test] |
| 665 | fn cut_point_never_lands_on_tool_result() { |
| 666 | let mut msgs |
| 667 | msgs.push(msg |
| 668 | for i in 0 |
| 669 | let mut call |
| 670 | call.tool_calls = Some |
| 671 | serde_json::to_string(&vec! |
| 672 | "id": format! |
| 673 | })]) |
| 674 | .unwrap(), |
| 675 | ); |
| 676 | msgs.push(call |
| 677 | msgs.push(msg |
| 678 | } |
| 679 | let cut = |
| 680 | assert!(msgs[cut |
| 681 | } |
| 682 | |
| 683 | #[test] |
| 684 | fn split_turn_when_cut_lands_mid_turn() { |
| 685 | // A single huge turn: the cut must fall inside it and report the turn |
| 686 | // start (the user message at index 0). |
| 687 | let mut msgs |
| 688 | for i in 0 |
| 689 | let mut call |
| 690 | call.tool_calls = Some |
| 691 | serde_json::to_string(&vec! |
| 692 | "id": format! |
| 693 | "arguments": {"path" |
| 694 | })]) |
| 695 | .unwrap(), |
| 696 | ); |
| 697 | msgs.push(call |
| 698 | msgs.push(msg |
| 699 | } |
| 700 | let cut = |
| 701 | assert!(cut.is_split_turn |
| 702 | assert_eq!(cut.turn_start_index |
| 703 | assert!(msgs[cut |
| 704 | } |
| 705 | |
| 706 | #[test] |
| 707 | fn serialize_conversation_formats_roles() { |
| 708 | let mut call |
| 709 | call.tool_calls = Some |
| 710 | serde_json::to_string(&vec! |
| 711 | "id": "c1", |
| 712 | })]) |
| 713 | .unwrap(), |
| 714 | ); |
| 715 | let msgs = |
| 716 | msg(1, "user |
| 717 | call, |
| 718 | msg(3, "tool |
| 719 | ]; |
| 720 | let out = |
| 721 | assert!(out.contains |
| 722 | assert!(out.contains |
| 723 | assert!(out.contains |
| 724 | assert!(out.contains |
| 725 | assert!(out.contains |
| 726 | } |
| 727 | |
| 728 | #[test] |
| 729 | fn file_ops_are_deduplicated_and_split() { |
| 730 | let mut a |
| 731 | a.tool_calls = Some |
| 732 | serde_json::json!({ |
| 733 | serde_json::json!({ |
| 734 | serde_json::json!({ |
| 735 | serde_json::json!({ |
| 736 | serde_json::json!({ |
| 737 | ]) |
| 738 | .unwrap()); |
| 739 | let (read, |
| 740 | assert_eq!(read, |
| 741 | assert_eq!(modified, |
| 742 | |
| 743 | let formatted = |
| 744 | assert!(formatted.contains |
| 745 | assert!(formatted.contains |
| 746 | } |
| 747 | } |