Skip to main content

trusty_code/agent_loop/
transcript.rs

1//! Conversation transcript for the multi-turn agent loop.
2//!
3//! Why: The loop must accumulate the full message history (system, user,
4//! assistant turns, and tool results) to send back to the model on each
5//! iteration and to render a final answer. Wrapping the `Vec<ChatMessage>` in a
6//! small type gives the loop intent-revealing helpers (`push_assistant`,
7//! `push_tool_result`) and keeps message-construction details out of the loop
8//! body. (#2070) It also owns non-destructive context compaction (vision spec
9//! §5.4): each entry carries a `compacted` flag rather than the message ever
10//! being deleted, so the outward, model-facing view can shrink while the
11//! stored history stays fully auditable.
12//! What: `Transcript` owns an ordered `Vec<TranscriptEntry>` (message +
13//! compacted flag + pinned flag); helpers append the seed messages, an
14//! assistant turn (text and/or tool calls), and a `tool` role result message.
15//! `assistant_text` concatenates the assistant text turns for the final
16//! `AgentOutput`. `maybe_compact` (#2070) applies [`super::compaction`]'s
17//! threshold policy; `to_messages` renders the model-facing view —
18//! contiguous compacted runs collapsed to one summary message, followed by a
19//! replayed copy of the last user message once any compaction has occurred
20//! (§5.4 items 2-3) — while `messages` always returns the complete,
21//! uncompacted raw history. `push_tool_result` (#2070) pins any
22//! [`crate::tools::USE_SKILL_TOOL_NAME`] result forever — §5.4 item 5's
23//! "preserve skill outputs... forever" — alongside `system`/`user` turns.
24//! Test: `agent_loop::tests` build transcripts indirectly through the loop;
25//! `transcript::tests` cover the helpers and compaction directly.
26
27use crate::llm::{ChatMessage, ChatResponse, ToolCall};
28use crate::tools::USE_SKILL_TOOL_NAME;
29
30use super::compaction::{CompactionConfig, should_compact, summarize_span};
31
32/// One stored conversation turn plus its compaction state (#2070).
33///
34/// Why: Non-destructive compaction requires the original message to survive
35/// even after it stops being sent to the model verbatim; a bare flag next to
36/// the message (rather than removing it from the vector) is the simplest
37/// representation that satisfies both "shrink what the model sees" and
38/// "never lose the audit trail". `pinned` is a SEPARATE flag from `compacted`
39/// (rather than overloading `compacted`) because a pinned entry must never
40/// transition to `compacted` at all — it is a permanent exemption, not a
41/// one-way state like compaction itself.
42/// What: `message` is the original, untouched `ChatMessage`; `compacted`
43/// starts `false` and is set `true` by `Transcript::maybe_compact` — never
44/// reset, since compaction is a one-way transform for a given entry. `pinned`
45/// starts `false` and is set `true` only at construction time (never later)
46/// for entries `maybe_compact` must always skip — currently: skill outputs
47/// (`push_tool_result` sets it when `name == USE_SKILL_TOOL_NAME`; §5.4 item
48/// 5 also covers `system`/`user` role turns, but those are matched by role
49/// directly in `maybe_compact` rather than via this flag, since they are
50/// identifiable without extra state).
51/// Test: `transcript::tests::maybe_compact_marks_middle_span_only`,
52/// `transcript::tests::maybe_compact_never_compacts_pinned_skill_output`.
53#[derive(Debug, Clone)]
54struct TranscriptEntry {
55    message: ChatMessage,
56    compacted: bool,
57    pinned: bool,
58}
59
60impl TranscriptEntry {
61    /// An ordinary entry: uncompacted, unpinned.
62    fn fresh(message: ChatMessage) -> Self {
63        Self {
64            message,
65            compacted: false,
66            pinned: false,
67        }
68    }
69
70    /// A permanently-exempt entry (#2070): uncompacted and, unlike `fresh`,
71    /// never eligible to become compacted by `Transcript::maybe_compact`.
72    fn pinned(message: ChatMessage) -> Self {
73        Self {
74            message,
75            compacted: false,
76            pinned: true,
77        }
78    }
79}
80
81/// Running conversation history for one agent-loop run.
82///
83/// Why: Centralises message accumulation so the loop body stays focused on
84/// control flow rather than `ChatMessage` plumbing, and (#2070) centralises
85/// the compaction state machine so the loop only has to call
86/// `maybe_compact` at its turn boundary.
87/// What: A thin wrapper over `Vec<TranscriptEntry>` with append helpers, a
88/// raw-history accessor, a compacted model-facing view, and an
89/// assistant-text accessor. `compaction_triggered` records whether ANY
90/// compaction has happened yet in this run — once `true`, `to_messages`
91/// starts appending the last-user-message replay (§5.4 item 3) on every
92/// subsequent call, re-anchoring the model on every following turn, not just
93/// the turn compaction fired on.
94/// Test: `transcript::tests::*`.
95#[derive(Debug, Default, Clone)]
96pub struct Transcript {
97    entries: Vec<TranscriptEntry>,
98    assistant_texts: Vec<String>,
99    compaction_triggered: bool,
100}
101
102impl Transcript {
103    /// Seed a transcript with a system prompt and the user task.
104    ///
105    /// Why: Every run starts from exactly these two turns; bundling the seed in
106    /// a constructor prevents the loop from forgetting either.
107    /// What: Pushes a `system` message then a `user` message, both starting
108    /// uncompacted. `maybe_compact` (#2070) never marks `system` or `user`
109    /// role entries — see its docs — so these two seed turns are preserved
110    /// forever regardless of how long the run continues.
111    /// Test: `transcript::tests::seed_has_two_messages`.
112    pub fn seed(system: &str, task: &str) -> Self {
113        Self {
114            entries: vec![
115                TranscriptEntry::fresh(ChatMessage::system(system)),
116                TranscriptEntry::fresh(ChatMessage::user(task)),
117            ],
118            assistant_texts: Vec::new(),
119            compaction_triggered: false,
120        }
121    }
122
123    /// Append the assistant turn from a model response.
124    ///
125    /// Why: The model's turn (text and any tool calls) must be added to history
126    /// before the tool results, so the next request reflects the real ordering
127    /// the API expects.
128    /// What: Reconstructs a `ChatMessage` with `role = "assistant"`, carrying the
129    /// optional text content and the emitted tool calls; records the text (if
130    /// any) for the final answer.
131    /// Test: `transcript::tests::push_assistant_records_text`.
132    pub fn push_assistant(&mut self, text: Option<String>, tool_calls: &[ToolCall]) {
133        if let Some(t) = &text
134            && !t.is_empty()
135        {
136            self.assistant_texts.push(t.clone());
137        }
138        let tool_calls = if tool_calls.is_empty() {
139            None
140        } else {
141            Some(tool_calls.to_vec())
142        };
143        self.entries.push(TranscriptEntry::fresh(ChatMessage {
144            role: "assistant".into(),
145            content: text,
146            tool_calls,
147            tool_call_id: None,
148            name: None,
149            cache_control: None,
150        }));
151    }
152
153    /// Append a `tool` role result message answering a specific tool call.
154    ///
155    /// Why: The API requires each tool call to be answered by a `tool` message
156    /// referencing its `tool_call_id`, or the next assistant turn errors.
157    /// (#2070) A `use_skill` result is the loaded body of a skill the model
158    /// deliberately chose to invoke — §5.4 item 5 requires it survive
159    /// compaction forever, the same guarantee `system`/`user` turns get.
160    /// What: Pushes a `ChatMessage::tool_result` with the call id, function
161    /// name, and textual result — as a permanently `pinned` entry when
162    /// `name == `[`USE_SKILL_TOOL_NAME`], otherwise as an ordinary compaction-
163    /// eligible entry.
164    /// Test: `transcript::tests::push_tool_result_sets_call_id`,
165    /// `transcript::tests::maybe_compact_never_compacts_pinned_skill_output`,
166    /// `transcript::tests::maybe_compact_still_compacts_non_skill_tool_results`.
167    pub fn push_tool_result(&mut self, tool_call_id: &str, name: &str, content: &str) {
168        let message = ChatMessage::tool_result(tool_call_id, name, content);
169        let entry = if name == USE_SKILL_TOOL_NAME {
170            TranscriptEntry::pinned(message)
171        } else {
172            TranscriptEntry::fresh(message)
173        };
174        self.entries.push(entry);
175    }
176
177    /// Return the complete, uncompacted raw message history.
178    ///
179    /// Why: (#2070) Non-destructive compaction is only meaningful if the full
180    /// history stays retrievable for audit even after `to_messages` starts
181    /// collapsing older turns; this is that escape hatch.
182    /// What: Clones every entry's original `ChatMessage`, in order, regardless
183    /// of its `compacted` flag.
184    /// Test: `transcript::tests::messages_reflects_appends`,
185    /// `transcript::tests::compacted_entries_remain_in_raw_history`.
186    pub fn messages(&self) -> Vec<ChatMessage> {
187        self.entries.iter().map(|e| e.message.clone()).collect()
188    }
189
190    /// Render the model-facing view: compacted spans collapsed to a summary,
191    /// plus a replayed last user message once compaction has occurred.
192    ///
193    /// Why: This is what `ChatRequest.messages` actually sends — it must
194    /// shrink once compaction fires (the whole point of §5.4) while staying
195    /// a valid, coherently-ordered conversation.
196    /// What: Walks entries in order; a run of one-or-more contiguous
197    /// `compacted` entries is replaced by ONE synthetic `system`-role message
198    /// (`super::compaction::summarize_span`'s one-line text) in its place;
199    /// uncompacted entries pass through unchanged. After the walk, if
200    /// `compaction_triggered` is `true` (i.e. compaction has fired at least
201    /// once in this transcript's life), the LAST `user`-role entry's message
202    /// is cloned and appended again at the very end — §5.4 item 3's
203    /// "re-anchor the model" replay. A transcript with no `user` entry (never
204    /// happens via `seed`, but guarded rather than assumed) simply skips the
205    /// replay.
206    /// Test: `transcript::tests::to_messages_collapses_compacted_span`,
207    /// `transcript::tests::to_messages_replays_last_user_message_after_compaction`,
208    /// `transcript::tests::to_messages_is_passthrough_before_compaction`.
209    pub fn to_messages(&self) -> Vec<ChatMessage> {
210        let mut out = Vec::with_capacity(self.entries.len());
211        let mut compacted_span: Vec<ChatMessage> = Vec::new();
212
213        for entry in &self.entries {
214            if entry.compacted {
215                compacted_span.push(entry.message.clone());
216                continue;
217            }
218            flush_span(&mut out, &mut compacted_span);
219            out.push(entry.message.clone());
220        }
221        flush_span(&mut out, &mut compacted_span);
222
223        if self.compaction_triggered
224            && let Some(last_user) = self.entries.iter().rev().find(|e| e.message.role == "user")
225        {
226            out.push(last_user.message.clone());
227        }
228
229        out
230    }
231
232    /// Apply the compaction policy: mark eligible older entries `compacted`.
233    ///
234    /// Why: (#2070) This is the turn-boundary hook the agent loop calls —
235    /// gated by the caller on `HarnessMode::DailyDriver` (Parity must never
236    /// compact, per §5.9's D2 reconciliation) — so growth is bounded without
237    /// the loop body needing to know compaction's internals.
238    /// What: No-ops (returns `false`) unless the CURRENT model-facing view
239    /// (`to_messages()`, not the ever-growing raw history — raw size would
240    /// re-trigger every turn even after compaction shrank what's actually
241    /// sent) exceeds `cfg.token_threshold`. Otherwise, marks every entry
242    /// before the trailing `cfg.keep_last_messages` (the active work zone,
243    /// §5.4 item 4) as `compacted = true`, EXCEPT entries already compacted
244    /// (a one-way transform), `pinned` entries (§5.4 item 5's skill-output
245    /// half — see `push_tool_result`), and `system`/`user` role entries
246    /// (§5.4 item 5's "preserve... user requests forever" half). Sets
247    /// `compaction_triggered` and returns `true` only if at least one entry
248    /// was newly marked (an already-fully-compacted or entirely-preserved
249    /// prefix is a no-op, not a spurious trigger).
250    /// Test: `transcript::tests::maybe_compact_marks_middle_span_only`,
251    /// `transcript::tests::maybe_compact_is_noop_below_threshold`,
252    /// `transcript::tests::maybe_compact_never_touches_system_or_user`,
253    /// `transcript::tests::maybe_compact_never_compacts_pinned_skill_output`,
254    /// `transcript::tests::maybe_compact_still_compacts_non_skill_tool_results`.
255    pub fn maybe_compact(&mut self, cfg: &CompactionConfig) -> bool {
256        if !should_compact(&self.to_messages(), cfg) {
257            return false;
258        }
259
260        let keep_from = self.entries.len().saturating_sub(cfg.keep_last_messages);
261        let mut newly_compacted = false;
262
263        for entry in &mut self.entries[..keep_from] {
264            if entry.compacted || entry.pinned {
265                continue;
266            }
267            if entry.message.role == "system" || entry.message.role == "user" {
268                continue;
269            }
270            entry.compacted = true;
271            newly_compacted = true;
272        }
273
274        if newly_compacted {
275            self.compaction_triggered = true;
276        }
277        newly_compacted
278    }
279
280    /// Number of entries currently marked `compacted`.
281    ///
282    /// Why: Test/observability accessor proving compaction happened without
283    /// exposing the private `TranscriptEntry` type.
284    /// What: Counts entries with `compacted == true`.
285    /// Test: `transcript::tests::maybe_compact_marks_middle_span_only`.
286    pub fn compacted_count(&self) -> usize {
287        self.entries.iter().filter(|e| e.compacted).count()
288    }
289
290    /// Join all recorded assistant text turns into the final answer string.
291    ///
292    /// Why: The `AgentOutput.content` should be the model's prose across the
293    /// run, not the raw JSON transcript; joining the text turns yields that.
294    /// What: Joins the recorded non-empty assistant texts with blank lines.
295    /// Test: `transcript::tests::assistant_text_joins_turns`.
296    pub fn assistant_text(&self) -> String {
297        self.assistant_texts.join("\n\n")
298    }
299
300    /// Convenience accessor: push the assistant turn straight from a response.
301    ///
302    /// Why: Callers usually have a `ChatResponse` in hand; this saves them
303    /// destructuring `first_text`/`first_tool_calls` at the call site.
304    /// What: Extracts the first choice's text and tool calls and delegates to
305    /// `push_assistant`.
306    /// Test: `transcript::tests::push_response_appends_assistant`.
307    pub fn push_response(&mut self, resp: &ChatResponse) {
308        let text = resp.first_text();
309        let calls = resp.first_tool_calls().to_vec();
310        self.push_assistant(text, &calls);
311    }
312}
313
314/// Flush a pending compacted span into `out` as one summary message, if any.
315///
316/// Why: `to_messages` needs to collapse a contiguous run of compacted entries
317/// exactly once, whether the run ends because a non-compacted entry follows
318/// or because the entries list ended; sharing this helper avoids duplicating
319/// the "if non-empty, summarise and clear" logic at both call sites.
320/// What: If `span` is non-empty, pushes one `ChatMessage::system` carrying
321/// `summarize_span(span)`'s text, then clears `span`.
322fn flush_span(out: &mut Vec<ChatMessage>, span: &mut Vec<ChatMessage>) {
323    if span.is_empty() {
324        return;
325    }
326    out.push(ChatMessage::system(summarize_span(span)));
327    span.clear();
328}
329
330// ── Tests ─────────────────────────────────────────────────────────────────────
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335    use crate::llm::{FunctionCall, ToolCall};
336
337    fn sample_call(id: &str, name: &str) -> ToolCall {
338        ToolCall {
339            id: id.into(),
340            kind: "function".into(),
341            function: FunctionCall {
342                name: name.into(),
343                arguments: "{}".into(),
344            },
345        }
346    }
347
348    /// `seed` produces exactly a system + user message pair.
349    ///
350    /// Why: Guards the run's starting state.
351    /// What: Seed and assert two messages with the expected roles.
352    /// Test: this test.
353    #[test]
354    fn seed_has_two_messages() {
355        let t = Transcript::seed("you are helpful", "do the thing");
356        assert_eq!(t.messages().len(), 2);
357        assert_eq!(t.messages()[0].role, "system");
358        assert_eq!(t.messages()[1].role, "user");
359    }
360
361    /// `push_assistant` records non-empty text for the final answer.
362    ///
363    /// Why: The final `AgentOutput` is built from assistant text turns.
364    /// What: Push text + no calls; assert `assistant_text` returns it.
365    /// Test: this test.
366    #[test]
367    fn push_assistant_records_text() {
368        let mut t = Transcript::seed("s", "u");
369        t.push_assistant(Some("hello".into()), &[]);
370        assert_eq!(t.assistant_text(), "hello");
371        assert_eq!(t.messages().last().expect("msg").role, "assistant");
372    }
373
374    /// An empty-string assistant turn is not recorded as text.
375    ///
376    /// Why: Tool-only turns often carry empty/None content; they must not add
377    /// blank lines to the final answer.
378    /// What: Push empty text; assert `assistant_text` stays empty.
379    /// Test: this test.
380    #[test]
381    fn push_assistant_skips_empty_text() {
382        let mut t = Transcript::seed("s", "u");
383        t.push_assistant(Some(String::new()), &[sample_call("c1", "echo")]);
384        assert_eq!(t.assistant_text(), "");
385    }
386
387    /// `push_tool_result` appends a `tool` message bound to the call id.
388    ///
389    /// Why: The API requires tool results to reference their call id.
390    /// What: Push a tool result; assert role and `tool_call_id`.
391    /// Test: this test.
392    #[test]
393    fn push_tool_result_sets_call_id() {
394        let mut t = Transcript::seed("s", "u");
395        t.push_tool_result("call_1", "echo", "echoed");
396        let messages = t.messages();
397        let last = messages.last().expect("msg");
398        assert_eq!(last.role, "tool");
399        assert_eq!(last.tool_call_id.as_deref(), Some("call_1"));
400        assert_eq!(last.name.as_deref(), Some("echo"));
401    }
402
403    /// `messages` reflects appended turns in order.
404    ///
405    /// Why: The model must see the real chronological history.
406    /// What: Seed, push assistant + tool result, assert length grows by two.
407    /// Test: this test.
408    #[test]
409    fn messages_reflects_appends() {
410        let mut t = Transcript::seed("s", "u");
411        t.push_assistant(None, &[sample_call("c1", "echo")]);
412        t.push_tool_result("c1", "echo", "ok");
413        assert_eq!(t.messages().len(), 4);
414    }
415
416    /// `assistant_text` joins multiple text turns with blank lines.
417    ///
418    /// Why: A multi-turn final answer should read as coherent prose.
419    /// What: Push two text turns; assert the joined form.
420    /// Test: this test.
421    #[test]
422    fn assistant_text_joins_turns() {
423        let mut t = Transcript::seed("s", "u");
424        t.push_assistant(Some("first".into()), &[]);
425        t.push_assistant(Some("second".into()), &[]);
426        assert_eq!(t.assistant_text(), "first\n\nsecond");
427    }
428
429    /// `to_messages` is a byte-identical passthrough before compaction fires.
430    ///
431    /// Why: Parity mode (and any DailyDriver run under the threshold) must
432    /// see exactly the raw history — no summary, no replay.
433    /// What: Build a small transcript, assert `to_messages() == messages()`.
434    /// Test: this test.
435    #[test]
436    fn to_messages_is_passthrough_before_compaction() {
437        let mut t = Transcript::seed("s", "u");
438        t.push_assistant(Some("hi".into()), &[]);
439        assert_eq!(t.to_messages(), t.messages());
440    }
441
442    /// `maybe_compact` is a no-op below the threshold.
443    ///
444    /// Why: Compaction must not fire on ordinary, short runs.
445    /// What: A tiny transcript against a generous threshold; assert no
446    /// change and a `false` return.
447    /// Test: this test.
448    #[test]
449    fn maybe_compact_is_noop_below_threshold() {
450        let mut t = Transcript::seed("s", "u");
451        t.push_assistant(Some("hi".into()), &[]);
452        let cfg = CompactionConfig {
453            token_threshold: 10_000,
454            keep_last_messages: 1,
455        };
456        assert!(!t.maybe_compact(&cfg));
457        assert_eq!(t.compacted_count(), 0);
458    }
459
460    /// `maybe_compact` marks only the middle span, never `system`/`user`.
461    ///
462    /// Why: §5.4 item 5 requires user requests (and the system preamble) to
463    /// be preserved forever; only assistant/tool turns outside the active
464    /// zone are compaction-eligible.
465    /// What: Build a transcript with several assistant/tool turns after a
466    /// long user task, set a low threshold and a small active zone, compact,
467    /// and assert the system/user entries stay uncompacted while middle
468    /// entries are marked.
469    /// Test: this test.
470    #[test]
471    fn maybe_compact_never_touches_system_or_user() {
472        let mut t = Transcript::seed("s", &"long task ".repeat(50));
473        for i in 0..10 {
474            t.push_assistant(Some(format!("assistant turn {i}")), &[]);
475            t.push_tool_result(&format!("c{i}"), "bash", "output");
476        }
477        let cfg = CompactionConfig {
478            token_threshold: 1,
479            keep_last_messages: 2,
480        };
481        assert!(t.maybe_compact(&cfg));
482        assert!(t.compacted_count() > 0);
483
484        let raw = t.messages();
485        assert_eq!(raw[0].role, "system");
486        assert_eq!(raw[1].role, "user");
487        // Non-destructive: every original entry is still present in the raw
488        // history even though some are now marked compacted internally.
489        assert_eq!(raw.len(), 2 + 20);
490    }
491
492    /// A `use_skill` tool result is pinned: it survives compaction even when
493    /// it falls outside the active zone and the transcript is well past the
494    /// threshold (#2070, §5.4 item 5).
495    ///
496    /// Why: This is the exact gap QA flagged — skill outputs flow through the
497    /// ordinary `push_tool_result` channel and, without pinning, would be
498    /// just as compaction-eligible as any other tool result.
499    /// What: Push a `use_skill` result early, then enough later turns to push
500    /// it well outside a small active zone; force compaction with an
501    /// aggressive config; assert `to_messages()` still contains the skill
502    /// result's ORIGINAL content verbatim (not replaced by a summary), and
503    /// that `messages()` (raw) also still has it — pinned entries are never
504    /// marked `compacted` at all, not merely retrievable via raw history.
505    /// Test: this test.
506    #[test]
507    fn maybe_compact_never_compacts_pinned_skill_output() {
508        let mut t = Transcript::seed("s", "task");
509        t.push_tool_result(
510            "call_skill",
511            USE_SKILL_TOOL_NAME,
512            "full skill body: do the distinctive thing",
513        );
514        for i in 0..10 {
515            t.push_assistant(Some(format!("turn {i}")), &[]);
516            t.push_tool_result(&format!("c{i}"), "bash", "output");
517        }
518        let cfg = CompactionConfig {
519            token_threshold: 1,
520            keep_last_messages: 2,
521        };
522        assert!(t.maybe_compact(&cfg));
523
524        let compacted_view = t.to_messages();
525        assert!(
526            compacted_view
527                .iter()
528                .any(|m| m.content.as_deref() == Some("full skill body: do the distinctive thing")),
529            "pinned skill output must survive verbatim in the compacted view: {compacted_view:?}"
530        );
531    }
532
533    /// Non-skill tool results (e.g. `bash`, `read_file`) remain
534    /// compaction-eligible — pinning must not accidentally exempt everything
535    /// and defeat compaction (#2070).
536    ///
537    /// Why: The fix for the skill-output gap must be narrowly scoped to
538    /// `USE_SKILL_TOOL_NAME`; a broad "pin every tool result" mistake would
539    /// silently disable compaction for ordinary long tool-heavy runs.
540    /// What: Same shape as the skill-pinning test but with only ordinary
541    /// `bash` tool results outside the active zone; assert compaction still
542    /// collapses them into a summary (the compacted view is materially
543    /// smaller than the raw history, and a summary marker is present).
544    /// Test: this test.
545    #[test]
546    fn maybe_compact_still_compacts_non_skill_tool_results() {
547        let mut t = Transcript::seed("s", "task");
548        for i in 0..10 {
549            t.push_assistant(Some(format!("turn {i}")), &[]);
550            t.push_tool_result(&format!("c{i}"), "bash", "output");
551        }
552        let cfg = CompactionConfig {
553            token_threshold: 1,
554            keep_last_messages: 2,
555        };
556        assert!(t.maybe_compact(&cfg));
557
558        let compacted_view = t.to_messages();
559        assert!(compacted_view.len() < t.messages().len());
560        assert!(
561            compacted_view.iter().any(|m| m
562                .content
563                .as_deref()
564                .unwrap_or("")
565                .contains("[compacted")),
566            "expected non-skill tool results to still collapse into a summary: {compacted_view:?}"
567        );
568    }
569
570    /// A compacted span collapses to exactly one summary message.
571    ///
572    /// Why: §5.4 item 2 — replace compacted content with a one-line summary,
573    /// not one summary per original message.
574    /// What: Force compaction, then assert `to_messages()` is shorter than
575    /// the raw history and contains a `[compacted ...]` marker.
576    /// Test: this test.
577    #[test]
578    fn to_messages_collapses_compacted_span() {
579        let mut t = Transcript::seed("s", "task");
580        for i in 0..10 {
581            t.push_assistant(Some(format!("turn {i}")), &[]);
582            t.push_tool_result(&format!("c{i}"), "bash", "output");
583        }
584        let cfg = CompactionConfig {
585            token_threshold: 1,
586            keep_last_messages: 2,
587        };
588        assert!(t.maybe_compact(&cfg));
589
590        let compacted_view = t.to_messages();
591        assert!(compacted_view.len() < t.messages().len());
592        let has_summary = compacted_view
593            .iter()
594            .any(|m| m.content.as_deref().unwrap_or("").contains("[compacted"));
595        assert!(
596            has_summary,
597            "expected a summary message in {compacted_view:?}"
598        );
599    }
600
601    /// After compaction fires, `to_messages` replays the last user message
602    /// at the tail.
603    ///
604    /// Why: §5.4 item 3 — re-anchor the model on the original task after
605    /// older turns are collapsed.
606    /// What: Force compaction, assert the LAST message in `to_messages()` is
607    /// a `user`-role message whose content matches the seeded task.
608    /// Test: this test.
609    #[test]
610    fn to_messages_replays_last_user_message_after_compaction() {
611        let mut t = Transcript::seed("s", "the original task");
612        for i in 0..10 {
613            t.push_assistant(Some(format!("turn {i}")), &[]);
614            t.push_tool_result(&format!("c{i}"), "bash", "output");
615        }
616        let cfg = CompactionConfig {
617            token_threshold: 1,
618            keep_last_messages: 2,
619        };
620        assert!(t.maybe_compact(&cfg));
621
622        let compacted_view = t.to_messages();
623        let last = compacted_view.last().expect("non-empty view");
624        assert_eq!(last.role, "user");
625        assert_eq!(last.content.as_deref(), Some("the original task"));
626    }
627
628    /// `maybe_compact` never panics on a minimal (seed-only) transcript, even
629    /// with a threshold/active-zone combination that would otherwise compact
630    /// everything.
631    ///
632    /// Why: The loop calls `maybe_compact` at every turn boundary, including
633    /// the very first one, when the transcript holds only the seeded
634    /// system+user pair; an off-by-one in the active-zone slice bound must
635    /// not panic on this smallest possible input.
636    /// What: Seed a transcript (2 entries), force a trigger with a
637    /// zero-threshold config and an active zone larger than the transcript,
638    /// call `maybe_compact`, and assert it returns `false` (nothing eligible
639    /// — both entries are `system`/`user`) with no panic.
640    /// Test: this test.
641    #[test]
642    fn maybe_compact_is_noop_on_seed_only_transcript() {
643        let mut t = Transcript::seed("s", "u");
644        let cfg = CompactionConfig {
645            token_threshold: 0,
646            keep_last_messages: 100,
647        };
648        assert!(!t.maybe_compact(&cfg));
649        assert_eq!(t.compacted_count(), 0);
650        assert_eq!(t.to_messages(), t.messages());
651    }
652
653    /// Compacted entries remain retrievable in the raw history (non-destructive).
654    ///
655    /// Why: §5.4's core promise is auditability — a compacted turn must
656    /// still be readable in full, not summarised-and-gone.
657    /// What: Force compaction, assert `messages()` still contains the
658    /// original, uncompacted text of a turn that was marked `compacted`.
659    /// Test: this test.
660    #[test]
661    fn compacted_entries_remain_in_raw_history() {
662        let mut t = Transcript::seed("s", "task");
663        t.push_assistant(Some("distinctive-early-turn-text".into()), &[]);
664        for i in 0..10 {
665            t.push_assistant(Some(format!("turn {i}")), &[]);
666            t.push_tool_result(&format!("c{i}"), "bash", "output");
667        }
668        let cfg = CompactionConfig {
669            token_threshold: 1,
670            keep_last_messages: 2,
671        };
672        assert!(t.maybe_compact(&cfg));
673        assert!(t.compacted_count() > 0);
674
675        let raw = t.messages();
676        assert!(
677            raw.iter()
678                .any(|m| m.content.as_deref() == Some("distinctive-early-turn-text")),
679            "compacted entry's original content must survive in the raw history"
680        );
681    }
682}