Skip to main content

pi_core/
context_projection.rs

1//! Context projection engine.
2//!
3//! Transforms the canonical agent transcript into a bounded provider-neutral
4//! transcript for one model call. Does not mutate the canonical transcript.
5//!
6//! Pipeline:
7//! 1. Apply tool-result budgeting (replace oversized results with previews)
8//! 2. Microcompact old tool results (shrink to one-line summaries)
9//! 3. Estimate tokens (chars/4, calibrated against API usage when available)
10//! 4. Trim or signal compaction (soft threshold signals host, hard limit trims)
11
12use 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// ---------------------------------------------------------------------------
21// Public types
22// ---------------------------------------------------------------------------
23
24/// Budget parameters for context projection.
25#[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    /// Turns older than this have their tool results microcompacted.
31    #[serde(default = "default_microcompact_after_turns")]
32    pub microcompact_after_turns: u32,
33    /// Fraction of max_context_tokens that triggers compaction signal (0.0–1.0).
34    #[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/// Snapshot of actual API token usage, fed back from the host for calibration.
54#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
55pub struct ApiUsageSnapshot {
56    /// Token count estimated by our heuristic at the time of the API call.
57    pub estimated_tokens: usize,
58    /// Actual input tokens reported by the API.
59    pub actual_input_tokens: usize,
60}
61
62/// A single replacement record: what was replaced, how, and where the full content lives.
63#[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/// State carried across turns so projection decisions remain stable.
74#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
75pub struct ContextProjectionState {
76    pub replacements: BTreeMap<String, ContextReplacement>,
77    /// Last API usage, used to calibrate token estimation.
78    #[serde(default)]
79    pub last_api_usage: Option<ApiUsageSnapshot>,
80    /// Turns since last compaction. Incremented by host after each turn.
81    #[serde(default)]
82    pub turns_since_compaction: u32,
83}
84
85/// Report returned after projection, for host observability and artifact storage.
86#[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    /// Host should compact (LLM summarization) before the next turn.
92    #[serde(default)]
93    pub needs_compaction: bool,
94    /// Suggested cache breakpoint positions (message indices).
95    #[serde(default)]
96    pub cache_breakpoints: Vec<usize>,
97}
98
99/// Input to the projection engine.
100#[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/// Output of the projection engine.
109#[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
116// ---------------------------------------------------------------------------
117// Token estimation
118// ---------------------------------------------------------------------------
119
120/// Estimate tokens for a list of messages using chars/4 heuristic.
121pub fn estimate_tokens(messages: &[AgentMessage]) -> usize {
122    let chars = count_message_chars(messages);
123    (chars + 3) / 4
124}
125
126/// Estimate tokens for a string.
127pub fn estimate_tokens_for_text(text: &str) -> usize {
128    (text.chars().count() + 3) / 4
129}
130
131/// Calibrated token estimate using actual API usage when available.
132fn 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
180// ---------------------------------------------------------------------------
181// Tool-result budgeting
182// ---------------------------------------------------------------------------
183
184/// Extract text from tool result content blocks.
185fn 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
222/// Apply the given strategy to text, returning the preview portion.
223fn 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(), // handled at trimming level
261        ContextStrategy::Microcompacted => {
262            // Microcompact produces a one-line summary; actual replacement done in project()
263            text.to_string()
264        }
265    }
266}
267
268/// Build the preview marker text.
269fn 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
286/// Name of a strategy for display in preview markers.
287fn 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
298// ---------------------------------------------------------------------------
299// Main projection entry point
300// ---------------------------------------------------------------------------
301
302/// Run context projection.
303///
304/// Does not mutate the input messages. Returns projected messages,
305/// updated state, and a report.
306pub 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    // Step 1: Tool-result budgeting
312    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                // Check prior state
320                if let Some(prior) = updated_state.replacements.get(&tool_call_id_str) {
321                    // Reuse prior replacement
322                    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                // Check if oversized
344                let text_chars = char_count(&text);
345                if text_chars <= input.budget.max_tool_result_chars {
346                    // Keep inline — do not record in state
347                    projected.push(msg.clone());
348                    continue;
349                }
350
351                // Determine strategy. Typed metadata wins; tool name is only a fallback.
352                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                // KeepFull means no replacement at all — keep the original inline
359                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    // Step 2: Microcompact — shrink old tool results to one-line summaries
404    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                    // Skip if already replaced by artifact budgeting or prior microcompact
415                    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    // Step 3: Estimate tokens with calibration
452    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    // Step 4: Trim or signal compaction
459    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        // Hard limit: must trim (safety net) + signal compaction
463        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        // Soft threshold: signal compaction, don't trim yet
467        needs_compaction = true;
468        (projected, 0)
469    } else {
470        needs_compaction = false;
471        (projected, 0)
472    };
473
474    // Recalculate after trimming
475    let final_tokens = calibrated_estimate(count_message_chars(&trimmed), &input.state) + sys_tokens;
476
477    // Cache breakpoints: suggest placing one at the second-to-last turn boundary
478    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
495// ---------------------------------------------------------------------------
496// Window trimming
497// ---------------------------------------------------------------------------
498
499/// Trim messages to fit within a token budget by dropping whole turns from the front.
500/// A turn starts at each user message.
501/// Returns (trimmed messages, number of dropped messages).
502fn 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    // Try dropping turns from the front
510    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 even dropping everything except the last turn doesn't fit, keep the last turn
519        if i == boundaries.len().saturating_sub(2) {
520            start_idx = boundaries[boundaries.len().saturating_sub(1)];
521        }
522    }
523
524    // If start_idx is 0 and we're still over budget, keep everything
525    // (the budget is just too small, not much we can do)
526    let kept = &messages[start_idx..];
527
528    // Safety: ensure no orphan tool_result at the front
529    let adjusted_start = if !kept.is_empty() {
530        match &kept[0] {
531            AgentMessage::ToolResult(_) => {
532                // Find the previous assistant message
533                if start_idx > 0 {
534                    // Walk backward to find the assistant that owns this tool_result
535                    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
558/// Find turn boundary indices. Each user message starts a new turn.
559/// Returns sorted indices of turn starts, plus total length as final boundary.
560fn 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
571/// Suggest cache breakpoint positions for Anthropic prompt caching.
572/// Places a breakpoint at the second-to-last turn boundary so the prefix stays cached.
573fn compute_cache_breakpoints(messages: &[AgentMessage]) -> Vec<usize> {
574    let boundaries = find_turn_boundaries(messages);
575    // Need at least 3 boundaries (2 turns) to have a meaningful prefix
576    if boundaries.len() >= 3 {
577        vec![boundaries[boundaries.len() - 2]]
578    } else {
579        vec![]
580    }
581}
582
583// ---------------------------------------------------------------------------
584// Tests
585// ---------------------------------------------------------------------------
586
587#[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    // --- Token estimation tests ---
668
669    #[test]
670    fn token_estimate_counts_user_text() {
671        let msgs = vec![user_msg("Hello, world!")]; // 13 chars -> (13+3)/4 = 4
672        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        // Name "bash" (4) + serialized args
680        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"; // 19 chars -> (19+3)/4 = 5
688        let msgs = vec![tool_result_msg("tc-1", "read", text)];
689        assert_eq!(estimate_tokens(&msgs), (19 + 3) / 4);
690    }
691
692    // --- Strategy tests ---
693
694    #[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        // Check projected text contains head preview
711        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            // Head preview: should contain a run of A's
716            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            // Should contain B's from the tail
738            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        // edit uses KeepFull, so even though it's large, it should not be replaced
756        // KeepFull never creates a replacement
757        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        // msgs was moved, but we verified the clone before is correct
892        // The key point: projection works on clones, not references to input
893        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        // Collect all tool_call IDs from assistant messages
971        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        // Every tool_result must have a matching tool_call
983        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        // First projection
1000        let output1 = project(ProjectionInput {
1001            system_prompt: "test".into(),
1002            messages: msgs.clone(),
1003            budget: default_budget(),
1004            state: ContextProjectionState::default(),
1005        });
1006
1007        // Second projection with updated state
1008        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        // Should be byte-identical
1016        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        // 10 turns * 2 msgs * 60 chars = 1200 chars = ~300 tokens
1026        // Budget 400 tokens, threshold 50% = 200 tokens -> over threshold but under limit
1027        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, // don't microcompact for this test
1037            compaction_threshold: 0.5,     // 50% threshold -> 200 tokens
1038        };
1039
1040        let output = project(ProjectionInput {
1041            system_prompt: "test".into(),
1042            messages: msgs.clone(),
1043            budget,
1044            state: ContextProjectionState::default(),
1045        });
1046
1047        // Should signal compaction (over 50% threshold) but not trim (under 100% limit)
1048        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        // Hard limit: should both trim AND signal compaction
1076        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        // Second-to-last turn starts at index 4 ("turn 2")
1100        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        // Build 8 turns, each with a tool call + result
1123        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        // Microcompact after 3 turns (so turns 0..5 get compacted)
1131        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        // First 5 turns' tool results should be microcompacted
1144        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        // Last 3 turns should NOT be microcompacted
1152        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        // Verify the compacted text contains the summary marker
1156        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        // 100 chars -> raw estimate = 25 tokens
1167        // API said actual was 35 tokens -> ratio = 1.4
1168        // So 80 chars should estimate to 80/4 * 1.4 = 28
1169        let state = ContextProjectionState {
1170            last_api_usage: Some(ApiUsageSnapshot {
1171                estimated_tokens: 25,
1172                actual_input_tokens: 35,
1173            }),
1174            ..Default::default()
1175        };
1176        // 80 chars => raw=20, calibrated = 20 * 1.4 = 28
1177        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        // No API usage -> raw chars/4
1184        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        // Turn 1: oversized bash result (will be replaced by Phase 1)
1191        // Turn 2: normal result
1192        // Turn 3: current turn
1193        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, // turn 0 should be microcompacted
1205            ..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        // tc-big should be replaced by Phase 1 (artifact budgeting), NOT microcompacted
1216        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        // tc-small should be microcompacted (it was in an old turn and not replaced by Phase 1)
1226        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}