1use std::collections::BTreeMap;
13
14use serde::{Deserialize, Serialize};
15use ts_rs::TS;
16
17use crate::context_metadata::{ContextStrategy, ToolResultContext, fallback_strategy};
18use crate::message::{AgentMessage, Content, TextContent};
19
20#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
26pub struct ContextProjectionBudget {
27 pub max_tool_result_chars: usize,
28 pub max_context_tokens: usize,
29 pub default_preview_chars: usize,
30 #[serde(default = "default_microcompact_after_turns")]
32 pub microcompact_after_turns: u32,
33 #[serde(default = "default_compaction_threshold")]
35 pub compaction_threshold: f32,
36}
37
38fn default_microcompact_after_turns() -> u32 { 5 }
39fn default_compaction_threshold() -> f32 { 0.75 }
40
41impl Default for ContextProjectionBudget {
42 fn default() -> Self {
43 Self {
44 max_tool_result_chars: 50_000,
45 max_context_tokens: 100_000,
46 default_preview_chars: 2000,
47 microcompact_after_turns: default_microcompact_after_turns(),
48 compaction_threshold: default_compaction_threshold(),
49 }
50 }
51}
52
53#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
55pub struct ApiUsageSnapshot {
56 pub estimated_tokens: usize,
58 pub actual_input_tokens: usize,
60}
61
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
64pub struct ContextReplacement {
65 pub tool_call_id: String,
66 pub tool_name: String,
67 pub artifact_id: String,
68 pub original_chars: usize,
69 pub preview_chars: usize,
70 pub strategy: ContextStrategy,
71}
72
73#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
75pub struct ContextProjectionState {
76 pub replacements: BTreeMap<String, ContextReplacement>,
77 #[serde(default)]
79 pub last_api_usage: Option<ApiUsageSnapshot>,
80 #[serde(default)]
82 pub turns_since_compaction: u32,
83}
84
85#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
87pub struct ContextProjectionReport {
88 pub estimated_tokens: usize,
89 pub replacements: Vec<ContextReplacement>,
90 pub dropped_messages: usize,
91 #[serde(default)]
93 pub needs_compaction: bool,
94 #[serde(default)]
96 pub cache_breakpoints: Vec<usize>,
97}
98
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
101pub struct ProjectionInput {
102 pub system_prompt: String,
103 pub messages: Vec<AgentMessage>,
104 pub budget: ContextProjectionBudget,
105 pub state: ContextProjectionState,
106}
107
108#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
110pub struct ProjectionOutput {
111 pub projected_messages: Vec<AgentMessage>,
112 pub updated_state: ContextProjectionState,
113 pub report: ContextProjectionReport,
114}
115
116pub fn estimate_tokens(messages: &[AgentMessage]) -> usize {
122 let chars = count_message_chars(messages);
123 (chars + 3) / 4
124}
125
126pub fn estimate_tokens_for_text(text: &str) -> usize {
128 (text.chars().count() + 3) / 4
129}
130
131fn calibrated_estimate(chars: usize, state: &ContextProjectionState) -> usize {
133 let raw = (chars + 3) / 4;
134 if let Some(ref api) = state.last_api_usage {
135 if api.estimated_tokens > 0 {
136 let ratio = api.actual_input_tokens as f64 / api.estimated_tokens as f64;
137 return (raw as f64 * ratio).round() as usize;
138 }
139 }
140 raw
141}
142
143fn count_message_chars(messages: &[AgentMessage]) -> usize {
144 let mut total = 0;
145 for msg in messages {
146 match msg {
147 AgentMessage::User(u) => {
148 for block in &u.content {
149 if let Content::Text(t) = block {
150 total += t.text.chars().count();
151 }
152 }
153 }
154 AgentMessage::Assistant(a) => {
155 for block in &a.content {
156 match block {
157 Content::Text(t) => total += t.text.chars().count(),
158 Content::ToolCall(tc) => {
159 total += tc.name.as_str().len();
160 total += serde_json::to_string(&tc.arguments)
161 .map(|s| s.len())
162 .unwrap_or(0);
163 }
164 Content::Image(_) => {}
165 }
166 }
167 }
168 AgentMessage::ToolResult(tr) => {
169 for block in &tr.content {
170 if let Content::Text(t) = block {
171 total += t.text.chars().count();
172 }
173 }
174 }
175 }
176 }
177 total
178}
179
180fn extract_text(content: &[Content]) -> String {
186 content
187 .iter()
188 .filter_map(|b| match b {
189 Content::Text(t) => Some(t.text.as_str()),
190 _ => None,
191 })
192 .collect::<Vec<_>>()
193 .join("\n")
194}
195
196fn char_count(text: &str) -> usize {
197 text.chars().count()
198}
199
200fn take_head_chars(text: &str, max_chars: usize) -> String {
201 text.chars().take(max_chars).collect()
202}
203
204fn take_tail_chars(text: &str, max_chars: usize) -> String {
205 let count = char_count(text);
206 text.chars().skip(count.saturating_sub(max_chars)).collect()
207}
208
209fn tool_result_context(details: &Option<crate::types::ToolDetails>) -> Option<ToolResultContext> {
210 let value = details.as_ref()?.0.clone();
211
212 serde_json::from_value::<ToolResultContext>(value.clone())
213 .ok()
214 .or_else(|| {
215 value
216 .get("context")
217 .cloned()
218 .and_then(|context| serde_json::from_value::<ToolResultContext>(context).ok())
219 })
220}
221
222fn apply_strategy(text: &str, strategy: &ContextStrategy, _default_preview_chars: usize) -> String {
224 match strategy {
225 ContextStrategy::KeepFull => text.to_string(),
226 ContextStrategy::Head { max_chars } => {
227 let n = *max_chars;
228 if char_count(text) <= n {
229 text.to_string()
230 } else {
231 take_head_chars(text, n)
232 }
233 }
234 ContextStrategy::Tail { max_chars } => {
235 let n = *max_chars;
236 if char_count(text) <= n {
237 text.to_string()
238 } else {
239 take_tail_chars(text, n)
240 }
241 }
242 ContextStrategy::HeadTail {
243 head_chars,
244 tail_chars,
245 } => {
246 let text_chars = char_count(text);
247 if text_chars <= head_chars + tail_chars {
248 text.to_string()
249 } else {
250 let head = take_head_chars(text, *head_chars);
251 let tail = take_tail_chars(text, *tail_chars);
252 format!(
253 "{}\n\n... ({} chars omitted)\n\n{}",
254 head,
255 text_chars - head_chars - tail_chars,
256 tail
257 )
258 }
259 }
260 ContextStrategy::DropIfOld => text.to_string(), ContextStrategy::Microcompacted => {
262 text.to_string()
264 }
265 }
266}
267
268fn build_preview_text(
270 artifact_id: &str,
271 tool_name: &str,
272 strategy_name: &str,
273 preview: &str,
274) -> String {
275 format!(
276 "<context-artifact id=\"{artifact_id}\" tool=\"{tool_name}\">\n\
277 Tool result was too large and was replaced with a preview.\n\
278 Full content should be available from host artifact: {artifact_id}\n\
279 Strategy: {strategy_name}\n\
280 Preview:\n\
281 {preview}\n\
282 </context-artifact>"
283 )
284}
285
286fn strategy_name(strategy: &ContextStrategy) -> &'static str {
288 match strategy {
289 ContextStrategy::KeepFull => "keep_full",
290 ContextStrategy::Head { .. } => "head",
291 ContextStrategy::Tail { .. } => "tail",
292 ContextStrategy::HeadTail { .. } => "head_tail",
293 ContextStrategy::DropIfOld => "drop_if_old",
294 ContextStrategy::Microcompacted => "microcompacted",
295 }
296}
297
298pub fn project(input: ProjectionInput) -> ProjectionOutput {
307 let mut replacements: Vec<ContextReplacement> = Vec::new();
308 let mut updated_state = input.state.clone();
309 let mut projected = Vec::with_capacity(input.messages.len());
310
311 for msg in &input.messages {
313 match msg {
314 AgentMessage::ToolResult(tr) => {
315 let text = extract_text(&tr.content);
316 let tool_call_id_str = tr.tool_call_id.as_str().to_string();
317 let tool_name_str = tr.tool_name.as_str().to_string();
318
319 if let Some(prior) = updated_state.replacements.get(&tool_call_id_str) {
321 let preview = apply_strategy(&text, &prior.strategy, input.budget.default_preview_chars);
323 let marker = build_preview_text(
324 &prior.artifact_id,
325 &tool_name_str,
326 strategy_name(&prior.strategy),
327 &preview,
328 );
329 let new_msg = AgentMessage::ToolResult(crate::message::ToolResultMessage {
330 role: "tool_result".to_string(),
331 tool_call_id: tr.tool_call_id.clone(),
332 tool_name: tr.tool_name.clone(),
333 content: vec![Content::Text(TextContent { text: marker })],
334 details: tr.details.clone(),
335 is_error: tr.is_error,
336 timestamp: tr.timestamp,
337 });
338 projected.push(new_msg);
339 replacements.push(prior.clone());
340 continue;
341 }
342
343 let text_chars = char_count(&text);
345 if text_chars <= input.budget.max_tool_result_chars {
346 projected.push(msg.clone());
348 continue;
349 }
350
351 let metadata = tool_result_context(&tr.details);
353 let strategy = metadata
354 .as_ref()
355 .map(|context| context.strategy.clone())
356 .unwrap_or_else(|| fallback_strategy(&tool_name_str));
357
358 if matches!(strategy, ContextStrategy::KeepFull) {
360 projected.push(msg.clone());
361 continue;
362 }
363
364 let preview = apply_strategy(&text, &strategy, input.budget.default_preview_chars);
365 let artifact_id = format!("tool-result-{tool_call_id_str}");
366 let sname = strategy_name(&strategy);
367
368 let replacement = ContextReplacement {
369 tool_call_id: tool_call_id_str.clone(),
370 tool_name: tool_name_str.clone(),
371 artifact_id: artifact_id.clone(),
372 original_chars: metadata
373 .as_ref()
374 .map(|context| context.original_chars)
375 .unwrap_or(text_chars),
376 preview_chars: char_count(&preview),
377 strategy: strategy.clone(),
378 };
379
380 let marker = build_preview_text(&artifact_id, &tool_name_str, sname, &preview);
381 let new_msg = AgentMessage::ToolResult(crate::message::ToolResultMessage {
382 role: "tool_result".to_string(),
383 tool_call_id: tr.tool_call_id.clone(),
384 tool_name: tr.tool_name.clone(),
385 content: vec![Content::Text(TextContent { text: marker })],
386 details: tr.details.clone(),
387 is_error: tr.is_error,
388 timestamp: tr.timestamp,
389 });
390
391 updated_state
392 .replacements
393 .insert(tool_call_id_str, replacement.clone());
394 replacements.push(replacement);
395 projected.push(new_msg);
396 }
397 _ => {
398 projected.push(msg.clone());
399 }
400 }
401 }
402
403 let turn_boundaries = find_turn_boundaries(&projected);
405 let total_turns = turn_boundaries.len().saturating_sub(1);
406 if total_turns > input.budget.microcompact_after_turns as usize {
407 let cutoff_turn = total_turns.saturating_sub(input.budget.microcompact_after_turns as usize);
408 for turn_idx in 0..cutoff_turn {
409 let start = turn_boundaries[turn_idx];
410 let end = turn_boundaries[turn_idx + 1];
411 for i in start..end {
412 if let AgentMessage::ToolResult(tr) = &projected[i] {
413 let tcid = tr.tool_call_id.as_str().to_string();
414 if updated_state.replacements.contains_key(&tcid) {
416 continue;
417 }
418 let text = extract_text(&tr.content);
419 let char_count_val = char_count(&text);
420 let summary = format!(
421 "<tool-summary tool=\"{}\" call=\"{}\">Result: {} chars</tool-summary>",
422 tr.tool_name.as_str(),
423 tcid,
424 char_count_val,
425 );
426 let replacement = ContextReplacement {
427 tool_call_id: tcid.clone(),
428 tool_name: tr.tool_name.as_str().to_string(),
429 artifact_id: format!("microcompact-{tcid}"),
430 original_chars: char_count_val,
431 preview_chars: char_count(&summary),
432 strategy: ContextStrategy::Microcompacted,
433 };
434 updated_state.replacements.insert(tcid, replacement.clone());
435 replacements.push(replacement);
436
437 projected[i] = AgentMessage::ToolResult(crate::message::ToolResultMessage {
438 role: "tool_result".to_string(),
439 tool_call_id: tr.tool_call_id.clone(),
440 tool_name: tr.tool_name.clone(),
441 content: vec![Content::Text(TextContent { text: summary })],
442 details: tr.details.clone(),
443 is_error: tr.is_error,
444 timestamp: tr.timestamp,
445 });
446 }
447 }
448 }
449 }
450
451 let msg_chars = count_message_chars(&projected);
453 let sys_chars = input.system_prompt.chars().count();
454 let msg_tokens = calibrated_estimate(msg_chars, &input.state);
455 let sys_tokens = calibrated_estimate(sys_chars, &input.state);
456 let total_tokens = msg_tokens + sys_tokens;
457
458 let usage_pct = total_tokens as f32 / input.budget.max_context_tokens as f32;
460 let needs_compaction;
461 let (trimmed, dropped_count) = if usage_pct > 1.0 {
462 needs_compaction = true;
464 trim_to_budget(&projected, input.budget.max_context_tokens, sys_tokens)
465 } else if usage_pct > input.budget.compaction_threshold {
466 needs_compaction = true;
468 (projected, 0)
469 } else {
470 needs_compaction = false;
471 (projected, 0)
472 };
473
474 let final_tokens = calibrated_estimate(count_message_chars(&trimmed), &input.state) + sys_tokens;
476
477 let cache_breakpoints = compute_cache_breakpoints(&trimmed);
479
480 let report = ContextProjectionReport {
481 estimated_tokens: final_tokens,
482 replacements,
483 dropped_messages: dropped_count,
484 needs_compaction,
485 cache_breakpoints,
486 };
487
488 ProjectionOutput {
489 projected_messages: trimmed,
490 updated_state,
491 report,
492 }
493}
494
495fn trim_to_budget(
503 messages: &[AgentMessage],
504 max_tokens: usize,
505 system_tokens: usize,
506) -> (Vec<AgentMessage>, usize) {
507 let boundaries = find_turn_boundaries(messages);
508
509 let mut start_idx = 0;
511 for i in 0..boundaries.len().saturating_sub(1) {
512 let remaining = &messages[boundaries[i]..];
513 let tokens = estimate_tokens(remaining) + system_tokens;
514 if tokens <= max_tokens {
515 start_idx = boundaries[i];
516 break;
517 }
518 if i == boundaries.len().saturating_sub(2) {
520 start_idx = boundaries[boundaries.len().saturating_sub(1)];
521 }
522 }
523
524 let kept = &messages[start_idx..];
527
528 let adjusted_start = if !kept.is_empty() {
530 match &kept[0] {
531 AgentMessage::ToolResult(_) => {
532 if start_idx > 0 {
534 let mut adj = start_idx;
536 while adj > 0 {
537 adj -= 1;
538 if matches!(messages[adj], AgentMessage::Assistant(_)) {
539 break;
540 }
541 }
542 adj
543 } else {
544 start_idx
545 }
546 }
547 _ => start_idx,
548 }
549 } else {
550 start_idx
551 };
552
553 let final_messages = messages[adjusted_start..].to_vec();
554 let dropped = adjusted_start;
555 (final_messages, dropped)
556}
557
558fn find_turn_boundaries(messages: &[AgentMessage]) -> Vec<usize> {
561 let mut boundaries: Vec<usize> = vec![0];
562 for (i, msg) in messages.iter().enumerate() {
563 if i > 0 && matches!(msg, AgentMessage::User(_)) {
564 boundaries.push(i);
565 }
566 }
567 boundaries.push(messages.len());
568 boundaries
569}
570
571fn compute_cache_breakpoints(messages: &[AgentMessage]) -> Vec<usize> {
574 let boundaries = find_turn_boundaries(messages);
575 if boundaries.len() >= 3 {
577 vec![boundaries[boundaries.len() - 2]]
578 } else {
579 vec![]
580 }
581}
582
583#[cfg(test)]
588mod tests {
589 use super::*;
590 use crate::message::{AssistantMessage, ToolResultMessage, UserMessage};
591 use crate::types::{ToolArguments, ToolCallId, ToolDetails, ToolName};
592 use crate::message::{Content, ToolCall as ToolCallContent};
593
594 fn user_msg(text: &str) -> AgentMessage {
595 AgentMessage::User(UserMessage::new_text(text))
596 }
597
598 fn assistant_text(text: &str) -> AgentMessage {
599 AgentMessage::Assistant(AssistantMessage {
600 content: vec![Content::Text(TextContent { text: text.into() })],
601 api: crate::types::ApiName::new("test"),
602 provider: crate::types::ProviderName::new("test"),
603 model: crate::types::ModelId::new("test"),
604 stop_reason: crate::message::StopReason::EndTurn,
605 error_message: None,
606 timestamp: 0,
607 usage: crate::message::TokenUsage::default(),
608 })
609 }
610
611 fn assistant_tool_call(id: &str, name: &str, args: &str) -> AgentMessage {
612 AgentMessage::Assistant(AssistantMessage {
613 content: vec![Content::ToolCall(ToolCallContent {
614 id: ToolCallId::new(id),
615 name: ToolName::new(name),
616 arguments: ToolArguments::new(serde_json::from_str(args).unwrap()),
617 })],
618 api: crate::types::ApiName::new("test"),
619 provider: crate::types::ProviderName::new("test"),
620 model: crate::types::ModelId::new("test"),
621 stop_reason: crate::message::StopReason::ToolUse,
622 error_message: None,
623 timestamp: 0,
624 usage: crate::message::TokenUsage::default(),
625 })
626 }
627
628 fn tool_result_msg(id: &str, name: &str, text: &str) -> AgentMessage {
629 AgentMessage::ToolResult(ToolResultMessage {
630 role: "tool_result".to_string(),
631 tool_call_id: ToolCallId::new(id),
632 tool_name: ToolName::new(name),
633 content: vec![Content::Text(TextContent { text: text.into() })],
634 details: None,
635 is_error: false,
636 timestamp: 0,
637 })
638 }
639
640 fn tool_result_msg_with_details(
641 id: &str,
642 name: &str,
643 text: &str,
644 details: serde_json::Value,
645 ) -> AgentMessage {
646 AgentMessage::ToolResult(ToolResultMessage {
647 role: "tool_result".to_string(),
648 tool_call_id: ToolCallId::new(id),
649 tool_name: ToolName::new(name),
650 content: vec![Content::Text(TextContent { text: text.into() })],
651 details: Some(ToolDetails::new(details)),
652 is_error: false,
653 timestamp: 0,
654 })
655 }
656
657 fn default_budget() -> ContextProjectionBudget {
658 ContextProjectionBudget {
659 max_tool_result_chars: 1000,
660 max_context_tokens: 100_000,
661 default_preview_chars: 200,
662 microcompact_after_turns: 5,
663 compaction_threshold: 0.75,
664 }
665 }
666
667 #[test]
670 fn token_estimate_counts_user_text() {
671 let msgs = vec![user_msg("Hello, world!")]; assert_eq!(estimate_tokens(&msgs), (13 + 3) / 4);
673 }
674
675 #[test]
676 fn token_estimate_counts_assistant_tool_call_arguments() {
677 let msgs = vec![assistant_tool_call("tc-1", "bash", r#"{"command":"ls"}"#)];
678 let tokens = estimate_tokens(&msgs);
679 let args_str = serde_json::to_string(&ToolArguments::new(serde_json::json!({"command":"ls"}))).unwrap();
681 let expected = (4 + args_str.len() + 3) / 4;
682 assert_eq!(tokens, expected);
683 }
684
685 #[test]
686 fn token_estimate_counts_tool_result_text() {
687 let text = "file contents here"; let msgs = vec![tool_result_msg("tc-1", "read", text)];
689 assert_eq!(estimate_tokens(&msgs), (19 + 3) / 4);
690 }
691
692 #[test]
695 fn read_uses_head_preview() {
696 let big = "A".repeat(5000);
697 let msgs = vec![tool_result_msg("tc-1", "read", &big)];
698 let output = project(ProjectionInput {
699 system_prompt: "test".into(),
700 messages: msgs.clone(),
701 budget: default_budget(),
702 state: ContextProjectionState::default(),
703 });
704
705 assert_eq!(output.report.replacements.len(), 1);
706 let replacement = &output.report.replacements[0];
707 assert_eq!(replacement.tool_name, "read");
708 assert_eq!(replacement.artifact_id, "tool-result-tc-1");
709
710 if let AgentMessage::ToolResult(tr) = &output.projected_messages[0] {
712 let text = extract_text(&tr.content);
713 assert!(text.contains("<context-artifact"));
714 assert!(text.contains("head"));
715 assert!(text.contains(&"A".repeat(100)));
717 } else {
718 panic!("expected tool result");
719 }
720 }
721
722 #[test]
723 fn bash_uses_tail_preview() {
724 let big = "A".repeat(3000) + &"B".repeat(2000);
725 let msgs = vec![tool_result_msg("tc-2", "bash", &big)];
726 let output = project(ProjectionInput {
727 system_prompt: "test".into(),
728 messages: msgs,
729 budget: default_budget(),
730 state: ContextProjectionState::default(),
731 });
732
733 assert_eq!(output.report.replacements.len(), 1);
734 if let AgentMessage::ToolResult(tr) = &output.projected_messages[0] {
735 let text = extract_text(&tr.content);
736 assert!(text.contains("tail"));
737 assert!(text.contains(&"B".repeat(200)));
739 } else {
740 panic!("expected tool result");
741 }
742 }
743
744 #[test]
745 fn edit_defaults_to_keep_full() {
746 let big = "X".repeat(5000);
747 let msgs = vec![tool_result_msg("tc-3", "edit", &big)];
748 let output = project(ProjectionInput {
749 system_prompt: "test".into(),
750 messages: msgs,
751 budget: default_budget(),
752 state: ContextProjectionState::default(),
753 });
754
755 assert_eq!(output.report.replacements.len(), 0);
758 }
759
760 #[test]
761 fn metadata_strategy_overrides_tool_name_fallback() {
762 let big = "A".repeat(3000) + &"B".repeat(2000);
763 let details = serde_json::json!({
764 "content_kind": "file_read",
765 "strategy": { "type": "tail", "max_chars": 200 },
766 "original_chars": 5000,
767 "truncated_by_tool": false,
768 "path": "src/lib.rs"
769 });
770 let msgs = vec![tool_result_msg_with_details("tc-meta", "read", &big, details)];
771
772 let output = project(ProjectionInput {
773 system_prompt: "test".into(),
774 messages: msgs,
775 budget: default_budget(),
776 state: ContextProjectionState::default(),
777 });
778
779 assert_eq!(output.report.replacements.len(), 1);
780 assert!(matches!(
781 output.report.replacements[0].strategy,
782 ContextStrategy::Tail { max_chars: 200 }
783 ));
784
785 if let AgentMessage::ToolResult(tr) = &output.projected_messages[0] {
786 let text = extract_text(&tr.content);
787 assert!(text.contains("tail"));
788 assert!(text.contains(&"B".repeat(100)));
789 assert!(!text.contains(&"A".repeat(500)));
790 } else {
791 panic!("expected tool result");
792 }
793 }
794
795 #[test]
796 fn nested_context_metadata_strategy_overrides_tool_name_fallback() {
797 let big = "A".repeat(3000) + &"B".repeat(2000);
798 let details = serde_json::json!({
799 "exitCode": 0,
800 "context": {
801 "content_kind": "file_read",
802 "strategy": { "type": "tail", "max_chars": 200 },
803 "original_chars": 5000,
804 "truncated_by_tool": false,
805 "path": "src/lib.rs"
806 }
807 });
808 let msgs = vec![tool_result_msg_with_details("tc-nested", "read", &big, details)];
809
810 let output = project(ProjectionInput {
811 system_prompt: "test".into(),
812 messages: msgs,
813 budget: default_budget(),
814 state: ContextProjectionState::default(),
815 });
816
817 assert_eq!(output.report.replacements.len(), 1);
818 assert!(matches!(
819 output.report.replacements[0].strategy,
820 ContextStrategy::Tail { max_chars: 200 }
821 ));
822 }
823
824 #[test]
825 fn replacement_ids_are_deterministic() {
826 let big = "A".repeat(5000);
827 let msgs = vec![tool_result_msg("tc-det", "bash", &big)];
828
829 let output1 = project(ProjectionInput {
830 system_prompt: "test".into(),
831 messages: msgs.clone(),
832 budget: default_budget(),
833 state: ContextProjectionState::default(),
834 });
835
836 let output2 = project(ProjectionInput {
837 system_prompt: "test".into(),
838 messages: msgs,
839 budget: default_budget(),
840 state: ContextProjectionState::default(),
841 });
842
843 assert_eq!(
844 output1.report.replacements[0].artifact_id,
845 output2.report.replacements[0].artifact_id,
846 );
847 assert_eq!(
848 output1.report.replacements[0].artifact_id,
849 "tool-result-tc-det",
850 );
851 }
852
853 #[test]
854 fn repeated_projection_same_state_is_byte_identical() {
855 let big = "A".repeat(5000);
856 let msgs = vec![tool_result_msg("tc-stable", "bash", &big)];
857
858 let output1 = project(ProjectionInput {
859 system_prompt: "test".into(),
860 messages: msgs.clone(),
861 budget: default_budget(),
862 state: ContextProjectionState::default(),
863 });
864
865 let output2 = project(ProjectionInput {
866 system_prompt: "test".into(),
867 messages: msgs,
868 budget: default_budget(),
869 state: output1.updated_state.clone(),
870 });
871
872 assert_eq!(
873 serde_json::to_string(&output1.projected_messages).unwrap(),
874 serde_json::to_string(&output2.projected_messages).unwrap(),
875 );
876 }
877
878 #[test]
879 fn canonical_input_transcript_is_not_mutated() {
880 let big = "A".repeat(5000);
881 let msgs = vec![tool_result_msg("tc-imm", "read", &big)];
882 let msgs_json_before = serde_json::to_string(&msgs).unwrap();
883
884 project(ProjectionInput {
885 system_prompt: "test".into(),
886 messages: msgs,
887 budget: default_budget(),
888 state: ContextProjectionState::default(),
889 });
890
891 drop(msgs_json_before);
894 }
895
896 #[test]
897 fn small_tool_result_stays_inline() {
898 let msgs = vec![tool_result_msg("tc-small", "read", "hello")];
899 let output = project(ProjectionInput {
900 system_prompt: "test".into(),
901 messages: msgs,
902 budget: default_budget(),
903 state: ContextProjectionState::default(),
904 });
905
906 assert_eq!(output.report.replacements.len(), 0);
907 }
908
909 #[test]
910 fn trimming_drops_old_messages_when_over_budget() {
911 let mut msgs = Vec::new();
912 for i in 0..20 {
913 msgs.push(user_msg(&format!("turn {i}: {}", "A".repeat(200))));
914 msgs.push(assistant_text(&format!("response {i}: {}", "B".repeat(200))));
915 }
916
917 let budget = ContextProjectionBudget {
918 max_tool_result_chars: 50_000,
919 max_context_tokens: 500,
920 default_preview_chars: 200,
921 microcompact_after_turns: 5,
922 compaction_threshold: 0.75,
923 };
924
925 let output = project(ProjectionInput {
926 system_prompt: "test".into(),
927 messages: msgs.clone(),
928 budget,
929 state: ContextProjectionState::default(),
930 });
931
932 assert!(
933 output.projected_messages.len() < msgs.len(),
934 "expected fewer than {} messages, got {}",
935 msgs.len(),
936 output.projected_messages.len(),
937 );
938 assert!(output.report.dropped_messages > 0);
939 assert!(!output.projected_messages.is_empty());
940 }
941
942 #[test]
943 fn trimming_does_not_leave_orphan_tool_results() {
944 let mut msgs = Vec::new();
945 for i in 0..20 {
946 msgs.push(user_msg(&format!("turn {i}: {}", "X".repeat(200))));
947 msgs.push(assistant_tool_call(
948 &format!("tc-{i}"),
949 "bash",
950 r#"{"command":"echo"}"#,
951 ));
952 msgs.push(tool_result_msg(&format!("tc-{i}"), "bash", &"Y".repeat(200)));
953 }
954
955 let budget = ContextProjectionBudget {
956 max_tool_result_chars: 50_000,
957 max_context_tokens: 500,
958 default_preview_chars: 200,
959 microcompact_after_turns: 5,
960 compaction_threshold: 0.75,
961 };
962
963 let output = project(ProjectionInput {
964 system_prompt: "test".into(),
965 messages: msgs,
966 budget,
967 state: ContextProjectionState::default(),
968 });
969
970 let mut tool_call_ids = std::collections::HashSet::new();
972 for msg in &output.projected_messages {
973 if let AgentMessage::Assistant(a) = msg {
974 for block in &a.content {
975 if let Content::ToolCall(tc) = block {
976 tool_call_ids.insert(tc.id.as_str().to_string());
977 }
978 }
979 }
980 }
981
982 for msg in &output.projected_messages {
984 if let AgentMessage::ToolResult(tr) = msg {
985 assert!(
986 tool_call_ids.contains(tr.tool_call_id.as_str()),
987 "orphan tool_result: {}",
988 tr.tool_call_id.as_str(),
989 );
990 }
991 }
992 }
993
994 #[test]
995 fn prior_state_reuses_replacement() {
996 let big = "A".repeat(5000);
997 let msgs = vec![tool_result_msg("tc-prior", "bash", &big)];
998
999 let output1 = project(ProjectionInput {
1001 system_prompt: "test".into(),
1002 messages: msgs.clone(),
1003 budget: default_budget(),
1004 state: ContextProjectionState::default(),
1005 });
1006
1007 let output2 = project(ProjectionInput {
1009 system_prompt: "test".into(),
1010 messages: msgs,
1011 budget: default_budget(),
1012 state: output1.updated_state.clone(),
1013 });
1014
1015 assert_eq!(
1017 serde_json::to_string(&output1.projected_messages).unwrap(),
1018 serde_json::to_string(&output2.projected_messages).unwrap(),
1019 );
1020 }
1021
1022 #[test]
1023 fn soft_threshold_signals_compaction_without_trimming() {
1024 let mut msgs = Vec::new();
1025 for i in 0..10 {
1028 msgs.push(user_msg(&format!("turn {i}: {}", "A".repeat(50))));
1029 msgs.push(assistant_text(&format!("response {i}: {}", "B".repeat(50))));
1030 }
1031
1032 let budget = ContextProjectionBudget {
1033 max_tool_result_chars: 50_000,
1034 max_context_tokens: 400,
1035 default_preview_chars: 200,
1036 microcompact_after_turns: 100, compaction_threshold: 0.5, };
1039
1040 let output = project(ProjectionInput {
1041 system_prompt: "test".into(),
1042 messages: msgs.clone(),
1043 budget,
1044 state: ContextProjectionState::default(),
1045 });
1046
1047 assert!(output.report.needs_compaction, "should signal compaction");
1049 assert_eq!(output.report.dropped_messages, 0, "should not drop messages");
1050 }
1051
1052 #[test]
1053 fn hard_limit_trims_and_signals_compaction() {
1054 let mut msgs = Vec::new();
1055 for i in 0..20 {
1056 msgs.push(user_msg(&format!("turn {i}: {}", "A".repeat(200))));
1057 msgs.push(assistant_text(&format!("response {i}: {}", "B".repeat(200))));
1058 }
1059
1060 let budget = ContextProjectionBudget {
1061 max_tool_result_chars: 50_000,
1062 max_context_tokens: 500,
1063 default_preview_chars: 200,
1064 microcompact_after_turns: 100,
1065 compaction_threshold: 0.75,
1066 };
1067
1068 let output = project(ProjectionInput {
1069 system_prompt: "test".into(),
1070 messages: msgs,
1071 budget,
1072 state: ContextProjectionState::default(),
1073 });
1074
1075 assert!(output.report.needs_compaction, "should signal compaction");
1077 assert!(output.report.dropped_messages > 0, "should drop messages");
1078 }
1079
1080 #[test]
1081 fn cache_breakpoints_placed_at_second_to_last_turn() {
1082 let msgs = vec![
1083 user_msg("turn 0"),
1084 assistant_text("response 0"),
1085 user_msg("turn 1"),
1086 assistant_text("response 1"),
1087 user_msg("turn 2"),
1088 assistant_text("response 2"),
1089 ];
1090
1091 let output = project(ProjectionInput {
1092 system_prompt: "test".into(),
1093 messages: msgs,
1094 budget: default_budget(),
1095 state: ContextProjectionState::default(),
1096 });
1097
1098 assert_eq!(output.report.cache_breakpoints.len(), 1);
1099 assert_eq!(output.report.cache_breakpoints[0], 4);
1101 }
1102
1103 #[test]
1104 fn no_cache_breakpoint_with_few_turns() {
1105 let msgs = vec![
1106 user_msg("turn 0"),
1107 assistant_text("response 0"),
1108 ];
1109
1110 let output = project(ProjectionInput {
1111 system_prompt: "test".into(),
1112 messages: msgs,
1113 budget: default_budget(),
1114 state: ContextProjectionState::default(),
1115 });
1116
1117 assert!(output.report.cache_breakpoints.is_empty());
1118 }
1119
1120 #[test]
1121 fn microcompact_shrinks_old_tool_results() {
1122 let mut msgs = Vec::new();
1124 for i in 0..8 {
1125 msgs.push(user_msg(&format!("turn {i}")));
1126 msgs.push(assistant_tool_call(&format!("tc-{i}"), "bash", r#"{"command":"ls"}"#));
1127 msgs.push(tool_result_msg(&format!("tc-{i}"), "bash", &format!("output {i}: {}", "X".repeat(300))));
1128 }
1129
1130 let budget = ContextProjectionBudget {
1132 microcompact_after_turns: 3,
1133 ..default_budget()
1134 };
1135
1136 let output = project(ProjectionInput {
1137 system_prompt: "test".into(),
1138 messages: msgs,
1139 budget,
1140 state: ContextProjectionState::default(),
1141 });
1142
1143 let microcompacted_ids: Vec<&str> = output.report.replacements
1145 .iter()
1146 .filter(|r| matches!(r.strategy, ContextStrategy::Microcompacted))
1147 .map(|r| r.tool_call_id.as_str())
1148 .collect();
1149 assert!(microcompacted_ids.contains(&"tc-0"), "tc-0 should be microcompacted");
1150 assert!(microcompacted_ids.contains(&"tc-4"), "tc-4 should be microcompacted");
1151 assert!(!microcompacted_ids.contains(&"tc-5"), "tc-5 should not be microcompacted");
1153 assert!(!microcompacted_ids.contains(&"tc-7"), "tc-7 should not be microcompacted");
1154
1155 if let AgentMessage::ToolResult(tr) = &output.projected_messages[2] {
1157 let text = extract_text(&tr.content);
1158 assert!(text.contains("<tool-summary"), "expected microcompact summary, got: {text}");
1159 } else {
1160 panic!("expected tool result at index 2");
1161 }
1162 }
1163
1164 #[test]
1165 fn calibrated_estimate_uses_api_ratio() {
1166 let state = ContextProjectionState {
1170 last_api_usage: Some(ApiUsageSnapshot {
1171 estimated_tokens: 25,
1172 actual_input_tokens: 35,
1173 }),
1174 ..Default::default()
1175 };
1176 assert_eq!(calibrated_estimate(80, &state), 28);
1178 }
1179
1180 #[test]
1181 fn calibrated_estimate_falls_back_to_chars_div_4() {
1182 let state = ContextProjectionState::default();
1183 assert_eq!(calibrated_estimate(80, &state), 20);
1185 }
1186
1187 #[test]
1188 fn microcompact_skips_already_replaced_results() {
1189 let big = "A".repeat(5000);
1190 let msgs = vec![
1194 user_msg("turn 0"),
1195 assistant_tool_call("tc-big", "bash", r#"{"command":"ls"}"#),
1196 tool_result_msg("tc-big", "bash", &big),
1197 user_msg("turn 1"),
1198 assistant_tool_call("tc-small", "read", r#"{"path":"x.rs"}"#),
1199 tool_result_msg("tc-small", "read", "small content"),
1200 user_msg("turn 2"),
1201 ];
1202
1203 let budget = ContextProjectionBudget {
1204 microcompact_after_turns: 1, ..default_budget()
1206 };
1207
1208 let output = project(ProjectionInput {
1209 system_prompt: "test".into(),
1210 messages: msgs,
1211 budget,
1212 state: ContextProjectionState::default(),
1213 });
1214
1215 let tc_big_replacement = output.report.replacements.iter()
1217 .find(|r| r.tool_call_id == "tc-big")
1218 .unwrap();
1219 assert!(
1220 matches!(tc_big_replacement.strategy, ContextStrategy::Tail { .. }),
1221 "tc-big should use tail strategy from Phase 1, got {:?}",
1222 tc_big_replacement.strategy,
1223 );
1224
1225 let tc_small_replacement = output.report.replacements.iter()
1227 .find(|r| r.tool_call_id == "tc-small")
1228 .unwrap();
1229 assert!(
1230 matches!(tc_small_replacement.strategy, ContextStrategy::Microcompacted),
1231 "tc-small should be microcompacted, got {:?}",
1232 tc_small_replacement.strategy,
1233 );
1234 }
1235}