| 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 | /// Messages that may end up on the summary/keep boundary. Tool results are |
| 165 | /// never cut points — they must follow their assistant tool call. |
| 166 | fn is_cut_point(m: |
| 167 | matches!(m.role |
| 168 | } |
| 169 | |
| 170 | /// Estimate the total context tokens of the stored conversation (pi's |
| 171 | /// `estimateContextTokens`), using the same chars/4 heuristic as |
| 172 | /// `estimate_tokens`. |
| 173 | pub fn estimate_context_tokens(messages |
| 174 | messages.iter().map |
| 175 | } |
| 176 | |
| 177 | /// Whether the context has grown within `RESERVE_TOKENS` of the provider's |
| 178 | /// context window and should be proactively compacted before the next request |
| 179 | /// (pi's `shouldCompact`: `contextTokens > contextWindow - reserveTokens`). |
| 180 | pub fn should_compact(context_tokens |
| 181 | context_tokens > context_window. |
| 182 | } |
| 183 | |
| 184 | /// Messages that start a turn (cutting before these is always clean). |
| 185 | fn is_turn_start(m: |
| 186 | matches!(m.role |
| 187 | } |
| 188 | |
| 189 | struct CutPoint { |
| 190 | /// Index of the first entry to keep. |
| 191 | first_kept_index: usize |
| 192 | /// Index of the user message that starts a split turn, if cutting mid-turn. |
| 193 | turn_start_index: Option |
| 194 | /// Whether the cut lands mid-turn (cut point is not a user message). |
| 195 | is_split_turn: bool |
| 196 | } |
| 197 | |
| 198 | /// Find the cut point that keeps approximately `KEEP_RECENT_TOKENS`: walk |
| 199 | /// backwards from the newest message accumulating estimated sizes, then cut at |
| 200 | /// the closest valid cut point. Only considers messages at/after `start`. |
| 201 | fn find_cut_point(messages: |
| 202 | let end = |
| 203 | let cut_points: Vec |
| 204 | .filter(|&i |
| 205 | .collect(); |
| 206 | if cut_points.is_empty() |
| 207 | return CutPoint { |
| 208 | first_kept_index: start, |
| 209 | turn_start_index: None |
| 210 | is_split_turn: false, |
| 211 | }; |
| 212 | } |
| 213 | |
| 214 | let mut accumulated |
| 215 | let mut cut_index |
| 216 | for i in ( |
| 217 | let tokens = |
| 218 | if tokens == 0 |
| 219 | continue; |
| 220 | } |
| 221 | accumulated += tokens; |
| 222 | if accumulated >= KEEP_RECENT_TOKENS |
| 223 | for &c in |
| 224 | if c >= i |
| 225 | cut_index = c; |
| 226 | break; |
| 227 | } |
| 228 | } |
| 229 | break; |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | let starts_turn = |
| 234 | let turn_start_index = |
| 235 | None |
| 236 | } else { |
| 237 | (start..=cut_index) |
| 238 | .rev() |
| 239 | .find(|&i |
| 240 | }; |
| 241 | |
| 242 | CutPoint { |
| 243 | first_kept_index: cut_index, |
| 244 | turn_start_index, |
| 245 | is_split_turn: turn_start_index.is_some |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | /// Serialize messages to plain text so the summarizer treats them as a |
| 250 | /// document, not a conversation to continue (pi's `serializeConversation`). |
| 251 | fn serialize_conversation(messages: |
| 252 | let mut parts |
| 253 | for m in messages |
| 254 | match m.role.as_str |
| 255 | "user" => { |
| 256 | if let Some |
| 257 | && !c.is_empty |
| 258 | { |
| 259 | parts.push(format! |
| 260 | } |
| 261 | } |
| 262 | "assistant" => { |
| 263 | let mut calls |
| 264 | if let Some |
| 265 | && let Ok |
| 266 | { |
| 267 | for t in & |
| 268 | let name = |
| 269 | let args = |
| 270 | calls.push(format! |
| 271 | } |
| 272 | } |
| 273 | if let Some |
| 274 | && !c.is_empty |
| 275 | { |
| 276 | parts.push(format! |
| 277 | } |
| 278 | if !calls.is_empty |
| 279 | parts.push(format! |
| 280 | } |
| 281 | } |
| 282 | "tool" => { |
| 283 | if let Some |
| 284 | && !c.is_empty |
| 285 | { |
| 286 | parts.push(format! |
| 287 | } |
| 288 | } |
| 289 | _ => {} |
| 290 | } |
| 291 | } |
| 292 | parts.join("\ |
| 293 | } |
| 294 | |
| 295 | fn truncate_for_summary(text: |
| 296 | let max_chars = |
| 297 | if text.chars() |
| 298 | return text.to_string(); |
| 299 | } |
| 300 | let kept: String |
| 301 | let truncated = |
| 302 | format!("{kept} |
| 303 | } |
| 304 | |
| 305 | /// Extract read/write/edit file paths from tool calls (pi's file-op tracking). |
| 306 | fn extract_file_ops(messages: |
| 307 | let mut read |
| 308 | let mut written |
| 309 | let mut edited |
| 310 | |
| 311 | for m in messages |
| 312 | if m.role != |
| 313 | continue; |
| 314 | } |
| 315 | let Some( |
| 316 | continue; |
| 317 | }; |
| 318 | let Ok( |
| 319 | continue; |
| 320 | }; |
| 321 | for t in & |
| 322 | let Some( |
| 323 | continue; |
| 324 | }; |
| 325 | match t["name" |
| 326 | Some("read_file") |
| 327 | read.insert(path |
| 328 | } |
| 329 | Some("write_file") |
| 330 | written.insert(path |
| 331 | } |
| 332 | Some("edit_file") |
| 333 | edited.insert(path |
| 334 | } |
| 335 | _ => {} |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | let modified: BTreeSet |
| 341 | let read_only: Vec |
| 342 | (read_only, modified. |
| 343 | } |
| 344 | |
| 345 | /// Append `<read-files>` / `<modified-files>` sections to the summary (pi's |
| 346 | /// `formatFileOperations`). |
| 347 | fn format_file_operations(read_files: |
| 348 | let mut sections |
| 349 | if !read_files.is_empty |
| 350 | sections.push(format! |
| 351 | "<read-files>\n{}\n</read-files>" |
| 352 | read_files.join("\ |
| 353 | )); |
| 354 | } |
| 355 | if !modified_files.is_empty |
| 356 | sections.push(format! |
| 357 | "<modified-files>\n{}\n</modified-files>" |
| 358 | modified_files.join("\ |
| 359 | )); |
| 360 | } |
| 361 | if sections.is_empty() |
| 362 | return String::new |
| 363 | } |
| 364 | format!("\n\ |
| 365 | } |
| 366 | |
| 367 | /// One LLM call that turns `messages` into the structured summary. If a |
| 368 | /// previous summary exists, the update prompt merges it in. |
| 369 | fn summarize( |
| 370 | messages: &[StoredMessage |
| 371 | previous_summary: Option |
| 372 | cfg: &ProviderConfig |
| 373 | model: &str |
| 374 | custom_instructions: Option |
| 375 | cancel: &AtomicBool |
| 376 | ) -> Result<String |
| 377 | let conversation_text = |
| 378 | let mut prompt_text |
| 379 | if let Some |
| 380 | prompt_text.push_str(&format! |
| 381 | "<previous-summary>\n{prev}\n |
| 382 | )); |
| 383 | } |
| 384 | prompt_text.push_str(if |
| 385 | UPDATE_SUMMARIZATION_PROMPT |
| 386 | } else { |
| 387 | SUMMARIZATION_PROMPT |
| 388 | }); |
| 389 | if let Some |
| 390 | && !ci.trim |
| 391 | { |
| 392 | prompt_text.push_str(&format! |
| 393 | } |
| 394 | |
| 395 | let msg = |
| 396 | role: "user". |
| 397 | content: Some |
| 398 | tool_call_id: None |
| 399 | name: None |
| 400 | tool_calls: vec![], |
| 401 | reasoning: None |
| 402 | images: vec![], |
| 403 | }; |
| 404 | // Summaries are standalone requests: cap output at a fraction of the |
| 405 | // reserved budget (pi: min(0.8 * reserveTokens, model max)), but never less |
| 406 | // than the provider's configured max_tokens. |
| 407 | let mut sum_cfg |
| 408 | sum_cfg.max_tokens = sum_cfg |
| 409 | let mut retry_sink |
| 410 | eprintln!( |
| 411 | " ⟳ summarization retry ({attempt}/{max} |
| 412 | wait_ms / 1000 |
| 413 | ); |
| 414 | }; |
| 415 | let resp = |
| 416 | &sum_cfg, |
| 417 | model, |
| 418 | SUMMARIZATION_SYSTEM_PROMPT, |
| 419 | &[msg], |
| 420 | &[], |
| 421 | None, |
| 422 | Some(&mut |
| 423 | cancel, |
| 424 | )?; |
| 425 | Ok(resp. |
| 426 | } |
| 427 | |
| 428 | /// Summarize the prefix of a turn that was too large to keep whole. |
| 429 | fn summarize_turn_prefix( |
| 430 | messages: &[StoredMessage |
| 431 | cfg: &ProviderConfig |
| 432 | model: &str |
| 433 | cancel: &AtomicBool |
| 434 | ) -> Result<String |
| 435 | let conversation_text = |
| 436 | let prompt_text = |
| 437 | "<conversation>\n{conversation_text}\n |
| 438 | ); |
| 439 | let msg = |
| 440 | role: "user". |
| 441 | content: Some |
| 442 | tool_call_id: None |
| 443 | name: None |
| 444 | tool_calls: vec![], |
| 445 | reasoning: None |
| 446 | images: vec![], |
| 447 | }; |
| 448 | let mut sum_cfg |
| 449 | // Smaller budget for the turn prefix (pi: 0.5 * reserveTokens). |
| 450 | sum_cfg.max_tokens = sum_cfg |
| 451 | let mut retry_sink |
| 452 | eprintln!( |
| 453 | " ⟳ turn-prefix summarization retry ({attempt}/{max} |
| 454 | wait_ms / 1000 |
| 455 | ); |
| 456 | }; |
| 457 | let resp = |
| 458 | &sum_cfg, |
| 459 | model, |
| 460 | SUMMARIZATION_SYSTEM_PROMPT, |
| 461 | &[msg], |
| 462 | &[], |
| 463 | None, |
| 464 | Some(&mut |
| 465 | cancel, |
| 466 | )?; |
| 467 | Ok(resp. |
| 468 | } |
| 469 | |
| 470 | /// Manually compact the session: summarize everything before a cut point that |
| 471 | /// keeps ~`KEEP_RECENT_TOKENS`, then record a `compaction` message row that |
| 472 | /// replaces the summarized turns in future context. Mirrors pi's `/compact`. |
| 473 | pub fn run( |
| 474 | conn: &Connection |
| 475 | session_id: i64 |
| 476 | cfg: &ProviderConfig |
| 477 | model: &str |
| 478 | custom_instructions: Option |
| 479 | cancel: &AtomicBool |
| 480 | ) -> Result<CompactionResult |
| 481 | // Session-global thinking effort (see `/effort`) applies to the summarizer |
| 482 | // call too; same rule as agent runs. |
| 483 | let mut cfg |
| 484 | if let Some |
| 485 | cfg.effort = Some |
| 486 | } |
| 487 | let messages = |
| 488 | if messages.is_empty() |
| 489 | bail!("Nothing to compact (session is empty)"); |
| 490 | } |
| 491 | if messages.last() |
| 492 | bail!("Already compacted — continue chatting before compacting again"); |
| 493 | } |
| 494 | |
| 495 | // Find the previous compaction (if any): its summary becomes the base for |
| 496 | // the update prompt, and its cut marks the earliest entry worth re-reading. |
| 497 | let mut previous_summary |
| 498 | let mut boundary_start |
| 499 | for (i, m |
| 500 | if m.role == |
| 501 | previous_summary = m. |
| 502 | boundary_start = messages |
| 503 | .iter() |
| 504 | .position(|x| |
| 505 | .unwrap_or(i + |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | let tokens_before = |
| 510 | |
| 511 | let cut = |
| 512 | let history_end = |
| 513 | let to_summarize = |
| 514 | let turn_prefix: & |
| 515 | Some(ts) |
| 516 | None => &[], |
| 517 | }; |
| 518 | |
| 519 | if to_summarize.is_empty() |
| 520 | bail!("Nothing to compact (session is small enough)"); |
| 521 | } |
| 522 | |
| 523 | let summary = |
| 524 | let history_text = |
| 525 | "No prior history.".to_string() |
| 526 | } else { |
| 527 | summarize( |
| 528 | to_summarize, |
| 529 | previous_summary.as_deref(), |
| 530 | &cfg, |
| 531 | model, |
| 532 | custom_instructions, |
| 533 | cancel, |
| 534 | )? |
| 535 | }; |
| 536 | let prefix_text = |
| 537 | format!("{history_text} |
| 538 | } else { |
| 539 | summarize( |
| 540 | to_summarize, |
| 541 | previous_summary.as_deref(), |
| 542 | &cfg, |
| 543 | model, |
| 544 | custom_instructions, |
| 545 | cancel, |
| 546 | )? |
| 547 | }; |
| 548 | |
| 549 | // File operation tracking survives the summarization (pi appends these to |
| 550 | // every compaction entry so future summaries can stay path-accurate). |
| 551 | let mut op_sources |
| 552 | op_sources.extend(turn_prefix |
| 553 | let (read_files, |
| 554 | let summary = |
| 555 | "{summary}{}", |
| 556 | format_file_operations(&read_files, |
| 557 | ); |
| 558 | |
| 559 | let first_kept_id = |
| 560 | db::add_compaction(conn |
| 561 | db::touch_session(conn |
| 562 | |
| 563 | let dropped = |
| 564 | Ok(CompactionResult |
| 565 | tokens_before, |
| 566 | dropped, |
| 567 | kept: messages.len |
| 568 | }) |
| 569 | } |
| 570 | |
| 571 | #[cfg(test)] |
| 572 | mod tests { |
| 573 | use super::*; |
| 574 | |
| 575 | fn msg(id: |
| 576 | StoredMessage { |
| 577 | id, |
| 578 | session_id: 1, |
| 579 | role: role.into |
| 580 | content: Some |
| 581 | tool_call_id: None |
| 582 | name: None |
| 583 | tool_calls: None |
| 584 | reasoning: None |
| 585 | images: None |
| 586 | usage: None |
| 587 | cut_msg_id: None |
| 588 | created_at: id, |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | #[test] |
| 593 | fn estimate_tokens_is_chars_over_four() { |
| 594 | assert_eq!(estimate_tokens( |
| 595 | assert_eq!(estimate_tokens( |
| 596 | assert_eq!(estimate_tokens( |
| 597 | } |
| 598 | |
| 599 | #[test] |
| 600 | fn threshold_triggers_within_reserve_of_window() { |
| 601 | // pi's shouldCompact: contextTokens > contextWindow - reserveTokens. |
| 602 | assert!(should_compact( |
| 603 | assert!(should_compact( |
| 604 | assert!(!should_compact |
| 605 | assert!(!should_compact |
| 606 | // A window smaller than the reserve saturates to zero: only a truly |
| 607 | // empty context avoids tripping. |
| 608 | assert!(!should_compact |
| 609 | assert!(should_compact( |
| 610 | |
| 611 | // estimate_context_tokens is the sum of the per-message estimates. |
| 612 | let msgs = |
| 613 | assert_eq!(estimate_context_tokens( |
| 614 | } |
| 615 | |
| 616 | #[test] |
| 617 | fn cut_point_keeps_recent_tokens() { |
| 618 | // 40 user messages of ~1000 chars (~250 tokens each) = ~10k tokens: |
| 619 | // small enough that nothing gets cut. |
| 620 | let msgs: Vec |
| 621 | .map(|i| |
| 622 | .collect(); |
| 623 | let cut = |
| 624 | assert_eq!(cut.first_kept_index |
| 625 | assert!(!cut. |
| 626 | |
| 627 | // 200 messages of ~1000 chars (~250 tokens) = ~50k tokens: the cut |
| 628 | // should land somewhere after the 80-most-recent (~20k) and keep a |
| 629 | // clean user boundary. |
| 630 | let msgs: Vec |
| 631 | .map(|i| |
| 632 | .collect(); |
| 633 | let cut = |
| 634 | assert!(cut.first_kept_index |
| 635 | assert!(!cut. |
| 636 | assert!(msgs[cut |
| 637 | } |
| 638 | |
| 639 | #[test] |
| 640 | fn cut_point_never_lands_on_tool_result() { |
| 641 | let mut msgs |
| 642 | msgs.push(msg |
| 643 | for i in 0 |
| 644 | let mut call |
| 645 | call.tool_calls = Some |
| 646 | serde_json::to_string(&vec! |
| 647 | "id": format! |
| 648 | })]) |
| 649 | .unwrap(), |
| 650 | ); |
| 651 | msgs.push(call |
| 652 | msgs.push(msg |
| 653 | } |
| 654 | let cut = |
| 655 | assert!(msgs[cut |
| 656 | } |
| 657 | |
| 658 | #[test] |
| 659 | fn split_turn_when_cut_lands_mid_turn() { |
| 660 | // A single huge turn: the cut must fall inside it and report the turn |
| 661 | // start (the user message at index 0). |
| 662 | let mut msgs |
| 663 | for i in 0 |
| 664 | let mut call |
| 665 | call.tool_calls = Some |
| 666 | serde_json::to_string(&vec! |
| 667 | "id": format! |
| 668 | "arguments": {"path" |
| 669 | })]) |
| 670 | .unwrap(), |
| 671 | ); |
| 672 | msgs.push(call |
| 673 | msgs.push(msg |
| 674 | } |
| 675 | let cut = |
| 676 | assert!(cut.is_split_turn |
| 677 | assert_eq!(cut.turn_start_index |
| 678 | assert!(msgs[cut |
| 679 | } |
| 680 | |
| 681 | #[test] |
| 682 | fn serialize_conversation_formats_roles() { |
| 683 | let mut call |
| 684 | call.tool_calls = Some |
| 685 | serde_json::to_string(&vec! |
| 686 | "id": "c1", |
| 687 | })]) |
| 688 | .unwrap(), |
| 689 | ); |
| 690 | let msgs = |
| 691 | msg(1, "user |
| 692 | call, |
| 693 | msg(3, "tool |
| 694 | ]; |
| 695 | let out = |
| 696 | assert!(out.contains |
| 697 | assert!(out.contains |
| 698 | assert!(out.contains |
| 699 | assert!(out.contains |
| 700 | assert!(out.contains |
| 701 | } |
| 702 | |
| 703 | #[test] |
| 704 | fn file_ops_are_deduplicated_and_split() { |
| 705 | let mut a |
| 706 | a.tool_calls = Some |
| 707 | serde_json::json!({ |
| 708 | serde_json::json!({ |
| 709 | serde_json::json!({ |
| 710 | serde_json::json!({ |
| 711 | serde_json::json!({ |
| 712 | ]) |
| 713 | .unwrap()); |
| 714 | let (read, |
| 715 | assert_eq!(read, |
| 716 | assert_eq!(modified, |
| 717 | |
| 718 | let formatted = |
| 719 | assert!(formatted.contains |
| 720 | assert!(formatted.contains |
| 721 | } |
| 722 | } |