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 std::sync::{Arc, Mutex};
28
29use crate::llm::{ChatMessage, ChatResponse, ToolCall};
30use crate::tools::USE_SKILL_TOOL_NAME;
31
32use super::compaction::{CompactionConfig, should_compact, summarize_span};
33use super::goals::GoalSlots;
34
35/// One stored conversation turn plus its compaction state (#2070).
36///
37/// Why: Non-destructive compaction requires the original message to survive
38/// even after it stops being sent to the model verbatim; a bare flag next to
39/// the message (rather than removing it from the vector) is the simplest
40/// representation that satisfies both "shrink what the model sees" and
41/// "never lose the audit trail". `pinned` is a SEPARATE flag from `compacted`
42/// (rather than overloading `compacted`) because a pinned entry must never
43/// transition to `compacted` at all — it is a permanent exemption, not a
44/// one-way state like compaction itself.
45/// What: `message` is the original, untouched `ChatMessage`; `compacted`
46/// starts `false` and is set `true` by `Transcript::maybe_compact` — never
47/// reset, since compaction is a one-way transform for a given entry. `pinned`
48/// starts `false` and is set `true` only at construction time (never later)
49/// for entries `maybe_compact` must always skip — currently: skill outputs
50/// (`push_tool_result` sets it when `name == USE_SKILL_TOOL_NAME`; §5.4 item
51/// 5 also covers `system`/`user` role turns, but those are matched by role
52/// directly in `maybe_compact` rather than via this flag, since they are
53/// identifiable without extra state).
54/// Test: `transcript::tests::maybe_compact_marks_middle_span_only`,
55/// `transcript::tests::maybe_compact_never_compacts_pinned_skill_output`.
56#[derive(Debug, Clone)]
57struct TranscriptEntry {
58    message: ChatMessage,
59    compacted: bool,
60    pinned: bool,
61    /// The cadence-turn range `(start, end)` active when this entry was
62    /// marked `compacted` by the #2346 cadence compressor — `None` for an
63    /// uncompacted entry OR one compacted by the threshold path
64    /// (`Transcript::maybe_compact`), which has no turn-range concept.
65    /// `to_messages`'s `flush_span` reads this to append a
66    /// "full detail in session memory (turns N-M)" pointer onto the
67    /// synthetic summary message, but only for spans the cadence
68    /// compressor produced.
69    cadence_turn_range: Option<(usize, usize)>,
70}
71
72impl TranscriptEntry {
73    /// An ordinary entry: uncompacted, unpinned.
74    fn fresh(message: ChatMessage) -> Self {
75        Self {
76            message,
77            compacted: false,
78            pinned: false,
79            cadence_turn_range: None,
80        }
81    }
82
83    /// A permanently-exempt entry (#2070): uncompacted and, unlike `fresh`,
84    /// never eligible to become compacted by `Transcript::maybe_compact`.
85    fn pinned(message: ChatMessage) -> Self {
86        Self {
87            message,
88            compacted: false,
89            pinned: true,
90            cadence_turn_range: None,
91        }
92    }
93}
94
95/// Running conversation history for one agent-loop run.
96///
97/// Why: Centralises message accumulation so the loop body stays focused on
98/// control flow rather than `ChatMessage` plumbing, and (#2070) centralises
99/// the compaction state machine so the loop only has to call
100/// `maybe_compact` at its turn boundary.
101/// What: A thin wrapper over `Vec<TranscriptEntry>` with append helpers, a
102/// raw-history accessor, a compacted model-facing view, and an
103/// assistant-text accessor. `last_compaction_len` records the entry count at
104/// the moment compaction most recently fired (`None` if it has never fired
105/// in this run) — `to_messages` compares it against the CURRENT entry count
106/// to append the last-user-message replay (§5.4 item 3) only on the turn
107/// compaction actually fired on, not on every subsequent call. (#2347) `goals`
108/// holds the session's 5 fixed privileged goal slots behind an `Arc<Mutex<_>>`
109/// (rather than a bare `GoalSlots`) so `tools::goals::{SetGoalTool,
110/// ClearGoalTool}` — constructed and registered into the PM's tool registry
111/// BEFORE this `Transcript` value is handed to `AgentLoop::run_with_transcript`
112/// — can mutate the SAME live state `to_messages` reads on every call via
113/// `Self::goals_handle`'s cloned `Arc`. Deliberately NOT a real
114/// `TranscriptEntry`: it is rendered fresh into the model-facing view on every
115/// `to_messages` call rather than stored/compacted, so it can never be folded
116/// into a compaction summary and never drifts from the live tool-mutated state.
117/// Test: `transcript::tests::*`.
118#[derive(Debug, Default, Clone)]
119pub struct Transcript {
120    entries: Vec<TranscriptEntry>,
121    assistant_texts: Vec<String>,
122    last_compaction_len: Option<usize>,
123    goals: Arc<Mutex<GoalSlots>>,
124    /// (#2346) Count of agent-loop turn boundaries this transcript has
125    /// observed via `tick_cadence_turn`, cumulative for the transcript's
126    /// entire lifetime — including across repeated `task.run` calls on the
127    /// same persistent session transcript, since this field lives on
128    /// `Transcript` (the session-persistent piece) rather than on
129    /// `AgentLoop` (reconstructed fresh per call).
130    cadence_turn_count: usize,
131    /// (#2346) The `cadence_turn_count` value as of the last time the
132    /// cadence compressor actually marked new entries `compacted` — the
133    /// start of the NEXT reported turn range is always one past this.
134    cadence_last_fire_turn: usize,
135    /// (#2346) Number of times the cadence compressor has fired (marked at
136    /// least one new entry `compacted`) — an observability/test counter,
137    /// distinct from `compacted_count` (which counts entries, not events).
138    cadence_fire_count: usize,
139    /// (#2349) Number of times the #2308 threshold compactor
140    /// (`Self::maybe_compact`) has actually fired — i.e. returned `true` —
141    /// cumulative for the transcript's entire lifetime, mirroring
142    /// `cadence_fire_count`'s same "events, not entries" accounting. Under
143    /// epic #2343's cadence system this is meant to stay `0` in steady state
144    /// (see [`Self::record_threshold_compaction`]'s docs); exposed
145    /// read-only via [`Self::compaction_events`] and, from there, onto
146    /// `session::TranscriptRecord.compaction_events`.
147    threshold_compaction_events: u32,
148}
149
150impl Transcript {
151    /// Seed a transcript with a system prompt and the user task.
152    ///
153    /// Why: Every run starts from exactly these two turns; bundling the seed in
154    /// a constructor prevents the loop from forgetting either.
155    /// What: Pushes a `system` message then a `user` message, both starting
156    /// uncompacted. `maybe_compact` (#2070) never marks `system` or `user`
157    /// role entries — see its docs — so these two seed turns are preserved
158    /// forever regardless of how long the run continues.
159    /// Test: `transcript::tests::seed_has_two_messages`.
160    pub fn seed(system: &str, task: &str) -> Self {
161        Self {
162            entries: vec![
163                TranscriptEntry::fresh(ChatMessage::system(system)),
164                TranscriptEntry::fresh(ChatMessage::user(task)),
165            ],
166            assistant_texts: Vec::new(),
167            last_compaction_len: None,
168            goals: Arc::new(Mutex::new(GoalSlots::new())),
169            cadence_turn_count: 0,
170            cadence_last_fire_turn: 0,
171            cadence_fire_count: 0,
172            threshold_compaction_events: 0,
173        }
174    }
175
176    /// Append the assistant turn from a model response.
177    ///
178    /// Why: The model's turn (text and any tool calls) must be added to history
179    /// before the tool results, so the next request reflects the real ordering
180    /// the API expects.
181    /// What: Reconstructs a `ChatMessage` with `role = "assistant"`, carrying the
182    /// optional text content and the emitted tool calls; records the text (if
183    /// any) for the final answer.
184    /// Test: `transcript::tests::push_assistant_records_text`.
185    pub fn push_assistant(&mut self, text: Option<String>, tool_calls: &[ToolCall]) {
186        if let Some(t) = &text
187            && !t.is_empty()
188        {
189            self.assistant_texts.push(t.clone());
190        }
191        let tool_calls = if tool_calls.is_empty() {
192            None
193        } else {
194            Some(tool_calls.to_vec())
195        };
196        self.entries.push(TranscriptEntry::fresh(ChatMessage {
197            role: "assistant".into(),
198            content: text,
199            tool_calls,
200            tool_call_id: None,
201            name: None,
202            cache_control: None,
203        }));
204    }
205
206    /// Append a `tool` role result message answering a specific tool call.
207    ///
208    /// Why: The API requires each tool call to be answered by a `tool` message
209    /// referencing its `tool_call_id`, or the next assistant turn errors.
210    /// (#2070) A `use_skill` result is the loaded body of a skill the model
211    /// deliberately chose to invoke — §5.4 item 5 requires it survive
212    /// compaction forever, the same guarantee `system`/`user` turns get.
213    /// What: Pushes a `ChatMessage::tool_result` with the call id, function
214    /// name, and textual result — as a permanently `pinned` entry when
215    /// `name == `[`USE_SKILL_TOOL_NAME`], otherwise as an ordinary compaction-
216    /// eligible entry.
217    /// Test: `transcript::tests::push_tool_result_sets_call_id`,
218    /// `transcript::tests::maybe_compact_never_compacts_pinned_skill_output`,
219    /// `transcript::tests::maybe_compact_still_compacts_non_skill_tool_results`.
220    pub fn push_tool_result(&mut self, tool_call_id: &str, name: &str, content: &str) {
221        let message = ChatMessage::tool_result(tool_call_id, name, content);
222        let entry = if name == USE_SKILL_TOOL_NAME {
223            TranscriptEntry::pinned(message)
224        } else {
225            TranscriptEntry::fresh(message)
226        };
227        self.entries.push(entry);
228    }
229
230    /// Return the complete, uncompacted raw message history.
231    ///
232    /// Why: (#2070) Non-destructive compaction is only meaningful if the full
233    /// history stays retrievable for audit even after `to_messages` starts
234    /// collapsing older turns; this is that escape hatch.
235    /// What: Clones every entry's original `ChatMessage`, in order, regardless
236    /// of its `compacted` flag.
237    /// Test: `transcript::tests::messages_reflects_appends`,
238    /// `transcript::tests::compacted_entries_remain_in_raw_history`.
239    pub fn messages(&self) -> Vec<ChatMessage> {
240        self.entries.iter().map(|e| e.message.clone()).collect()
241    }
242
243    /// Render the model-facing view: compacted spans collapsed to a summary,
244    /// the live goal slots injected at position `[1]`, plus a replayed last
245    /// user message once compaction has occurred.
246    ///
247    /// Why: This is what `ChatRequest.messages` actually sends — it must
248    /// shrink once compaction fires (the whole point of §5.4) while staying
249    /// a valid, coherently-ordered conversation. (#2347) The goals injection
250    /// happens HERE, fresh on every call, rather than being a stored
251    /// `TranscriptEntry` — that is what makes it immune to compaction (it
252    /// never exists as an entry `maybe_compact` could mark) and immune to
253    /// drift (it always reflects whatever `tools::goals::{SetGoalTool,
254    /// ClearGoalTool}` most recently wrote via the same `Arc<Mutex<_>>`).
255    /// What: Walks entries in order; a run of one-or-more contiguous
256    /// `compacted` entries is replaced by ONE synthetic `system`-role message
257    /// (`super::compaction::summarize_span`'s one-line text, plus (#2346) a
258    /// "full detail in session memory (turns N-M)" pointer appended when any
259    /// entry in the span carries a `cadence_turn_range` — see
260    /// [`flush_span`]'s docs) in its place; uncompacted entries pass through
261    /// unchanged. (#2347) If `self.goals.render()` returns `Some`, a
262    /// synthetic `system`-role message carrying that text is inserted at
263    /// index `1` (immediately after the real system message, which
264    /// `Transcript::seed` always places at index `0` and `maybe_compact`
265    /// never touches) — or appended if `out` is empty, a defensive case that
266    /// never occurs via `seed`. A poisoned goals lock degrades to "no goals
267    /// block" rather than panicking (mirrors `run_task::recorder`'s
268    /// poisoned-lock convention). After that insertion, if
269    /// `last_compaction_len` equals the CURRENT entry count (i.e. this call
270    /// is happening on the very turn `maybe_compact` last fired on — the
271    /// loop calls `maybe_compact` then `to_messages` back-to-back before any
272    /// further entries are appended), the LAST `user`-role entry's message is
273    /// cloned and appended again at the very end — §5.4 item 3's "re-anchor
274    /// the model" replay. On every later call the entry count has grown past
275    /// `last_compaction_len`, so the replay does not repeat until compaction
276    /// fires again. A transcript with no `user` entry (never happens via
277    /// `seed`, but guarded rather than assumed) simply skips the replay.
278    /// Test: `transcript::tests::to_messages_collapses_compacted_span`,
279    /// `transcript::tests::to_messages_replays_last_user_message_after_compaction`,
280    /// `transcript::tests::to_messages_does_not_replay_on_every_subsequent_turn`,
281    /// `transcript::tests::to_messages_is_passthrough_before_compaction`,
282    /// `transcript::tests::to_messages_injects_goals_at_position_one`,
283    /// `transcript::tests::to_messages_omits_goals_message_when_all_empty`,
284    /// `transcript::tests::to_messages_goals_survive_aggressive_compaction`.
285    pub fn to_messages(&self) -> Vec<ChatMessage> {
286        // #2347: `+ 1` accounts for the goals-injection message inserted
287        // below, so the common case never reallocates.
288        let mut out = Vec::with_capacity(self.entries.len() + 1);
289        let mut compacted_span: Vec<(ChatMessage, Option<(usize, usize)>)> = Vec::new();
290
291        for entry in &self.entries {
292            if entry.compacted {
293                compacted_span.push((entry.message.clone(), entry.cadence_turn_range));
294                continue;
295            }
296            flush_span(&mut out, &mut compacted_span);
297            out.push(entry.message.clone());
298        }
299        flush_span(&mut out, &mut compacted_span);
300
301        let goals_text = self.goals.lock().ok().and_then(|g| g.render());
302        if let Some(text) = goals_text {
303            let insert_at = out.len().min(1);
304            out.insert(insert_at, ChatMessage::system(text));
305        }
306
307        if self.last_compaction_len == Some(self.entries.len())
308            && let Some(last_user) = self.entries.iter().rev().find(|e| e.message.role == "user")
309        {
310            out.push(last_user.message.clone());
311        }
312
313        out
314    }
315
316    /// Apply the compaction policy: mark eligible older entries `compacted`.
317    ///
318    /// Why: (#2070) This is the turn-boundary hook the agent loop calls —
319    /// gated by the caller on `HarnessMode::DailyDriver` (Parity must never
320    /// compact, per §5.9's D2 reconciliation) — so growth is bounded without
321    /// the loop body needing to know compaction's internals. (#2278) A raw
322    /// entry-COUNT cutoff has no tool-call awareness: when it lands between
323    /// an assistant entry carrying `tool_calls` and one of its answering
324    /// `tool`-role entries, the assistant gets folded into the compacted
325    /// summary while the answering entry survives verbatim in the kept
326    /// zone — an orphaned tool result with no tool use, which providers
327    /// with a strict pairing invariant (Bedrock's Converse API) reject
328    /// outright.
329    /// What: No-ops (returns `false`) unless the CURRENT model-facing view
330    /// (`to_messages()`, not the ever-growing raw history — raw size would
331    /// re-trigger every turn even after compaction shrank what's actually
332    /// sent) exceeds `cfg.token_threshold`. Otherwise computes the naive
333    /// count-based cutoff `keep_from = len - cfg.keep_last_messages`, then
334    /// (#2278) [`turn_group_start`]/[`turn_group_end`] check whether that
335    /// cutoff falls INSIDE a turn group — an assistant entry carrying
336    /// `tool_calls` plus the maximal contiguous run of `tool`-role entries
337    /// immediately following it (naturally covering multi-tool-call turns:
338    /// N `tool_calls` followed by up to N `tool` entries). If so, the whole
339    /// group is pulled FORWARD into the kept zone by moving `keep_from` back
340    /// to the group's start — `cfg.keep_last_messages` becomes a soft floor
341    /// that may slightly enlarge the active zone rather than ever splitting
342    /// a group. Marks every entry before the (possibly adjusted) `keep_from`
343    /// as `compacted = true`, EXCEPT entries already compacted (a one-way
344    /// transform), `pinned` entries (§5.4 item 5's skill-output half — see
345    /// `push_tool_result`), and `system`/`user` role entries (§5.4 item 5's
346    /// "preserve... user requests forever" half). Records `last_compaction_len
347    /// = Some(self.entries.len())` and returns `true` only if at least one
348    /// entry was newly marked (an already-fully-compacted or
349    /// entirely-preserved prefix is a no-op, not a spurious trigger) — this
350    /// marker is what lets `to_messages` replay the last user message
351    /// exactly once, on this turn, rather than on every subsequent call.
352    /// Test: `transcript::tests::maybe_compact_is_noop_below_threshold`,
353    /// `transcript::tests::maybe_compact_never_touches_system_or_user`,
354    /// `transcript::tests::maybe_compact_never_compacts_pinned_skill_output`,
355    /// `transcript::tests::maybe_compact_still_compacts_non_skill_tool_results`,
356    /// `transcript::tests::maybe_compact_pulls_whole_multi_tool_call_group_forward`.
357    pub fn maybe_compact(&mut self, cfg: &CompactionConfig) -> bool {
358        if !should_compact(&self.to_messages(), cfg) {
359            return false;
360        }
361        let keep_from = resolve_keep_from(&self.entries, cfg.keep_last_messages);
362        self.mark_compacted(keep_from, None)
363    }
364
365    /// Mark every eligible entry before `keep_from` as `compacted`, tagging
366    /// each newly-marked entry with `cadence_range` (#2346).
367    ///
368    /// Why: [`Self::maybe_compact`] (threshold-triggered, no turn-range
369    /// concept) and the #2346 cadence compressor's
370    /// [`Self::compact_span_tagged`] both need to apply the EXACT same
371    /// pinned/`system`/`user`/already-compacted exemptions — this is the one
372    /// place that logic lives, so the two callers can never independently
373    /// drift.
374    /// What: For every entry in `self.entries[..keep_from]` that is not
375    /// already `compacted`, not `pinned`, and not `system`/`user` role, sets
376    /// `compacted = true` and `cadence_turn_range = cadence_range`. Records
377    /// `last_compaction_len` and returns whether anything was newly marked,
378    /// exactly as `maybe_compact` did before this extraction.
379    /// Test: `transcript::tests::maybe_compact_marks_middle_span_only` (via
380    /// `maybe_compact`); `transcript::tests::compact_span_tagged_*` (via the
381    /// cadence path).
382    fn mark_compacted(&mut self, keep_from: usize, cadence_range: Option<(usize, usize)>) -> bool {
383        let mut newly_compacted = false;
384        for entry in &mut self.entries[..keep_from] {
385            if entry.compacted || entry.pinned {
386                continue;
387            }
388            if entry.message.role == "system" || entry.message.role == "user" {
389                continue;
390            }
391            entry.compacted = true;
392            entry.cadence_turn_range = cadence_range;
393            newly_compacted = true;
394        }
395        if newly_compacted {
396            self.last_compaction_len = Some(self.entries.len());
397        }
398        newly_compacted
399    }
400
401    /// Advance the cadence turn counter and report whether THIS turn is a
402    /// cadence-fire turn (#2346).
403    ///
404    /// Why: `agent_loop::cadence::maybe_cadence_compress` needs a
405    /// session-persistent counter (see [`Self::cadence_turn_count`]'s field
406    /// doc for why it lives on `Transcript`, not `AgentLoop`) it can advance
407    /// exactly once per turn boundary and compare against the configured
408    /// cadence.
409    /// What: Increments `cadence_turn_count`, then returns `true` when
410    /// `cadence_turns > 0` and the new count is an exact multiple of it —
411    /// `cadence_turns == 0` never fires (guards the modulo and treats "0" as
412    /// "cadence disabled" rather than firing every turn).
413    /// Test: `cadence::tests::fires_every_n_turns`.
414    pub(super) fn tick_cadence_turn(&mut self, cadence_turns: usize) -> bool {
415        self.cadence_turn_count += 1;
416        cadence_turns > 0 && self.cadence_turn_count.is_multiple_of(cadence_turns)
417    }
418
419    /// The turn range `(start, end)` a cadence compression happening RIGHT
420    /// NOW should be tagged with (#2346).
421    ///
422    /// Why: A span's "turns N-M" label (surfaced in the summary text via
423    /// [`flush_span`]) must cover every turn since the LAST fire, not just
424    /// the current one — otherwise a gap between fires would be
425    /// unaccounted-for in the durable-memory pointer.
426    /// What: `(cadence_last_fire_turn + 1, cadence_turn_count)`.
427    /// Test: `cadence::tests::summary_references_turn_range`.
428    pub(super) fn begin_cadence_range(&self) -> (usize, usize) {
429        (self.cadence_last_fire_turn + 1, self.cadence_turn_count)
430    }
431
432    /// Record that a cadence fire just happened (#2346).
433    ///
434    /// Why: [`Self::begin_cadence_range`]'s next call must start the range
435    /// right after this fire's end, and `cadence_fire_count` is the
436    /// "cadence fires exactly every N turns" test's observability hook.
437    /// What: Sets `cadence_last_fire_turn = cadence_turn_count` and
438    /// increments `cadence_fire_count`.
439    /// Test: `cadence::tests::fires_every_n_turns`.
440    pub(super) fn advance_cadence_fire_marker(&mut self) {
441        self.cadence_last_fire_turn = self.cadence_turn_count;
442        self.cadence_fire_count += 1;
443    }
444
445    /// Unconditionally compact the span older than `keep_last_messages`,
446    /// tagged with `cadence_range` — the #2346 cadence compressor's
447    /// entry point into the shared group-safe marking machinery.
448    ///
449    /// Why: Unlike [`Self::maybe_compact`], this is NEVER gated on a token
450    /// threshold — cadence fires on a turn-count schedule regardless of
451    /// current size, and the continuous-budget-enforcement loop
452    /// (`agent_loop::cadence::enforce_budget`) calls this repeatedly with a
453    /// shrinking `keep_last_messages` until the transcript is back under
454    /// budget. Reuses [`resolve_keep_from`] (#2278 group-safety) so a
455    /// cadence-triggered cutoff can never split a tool-call/tool-result pair
456    /// any more than the threshold path can.
457    /// What: Delegates to [`resolve_keep_from`] then [`Self::mark_compacted`]
458    /// with `Some(cadence_range)`.
459    /// Test: `cadence::tests::*`.
460    pub(super) fn compact_span_tagged(
461        &mut self,
462        keep_last_messages: usize,
463        cadence_range: (usize, usize),
464    ) -> bool {
465        let keep_from = resolve_keep_from(&self.entries, keep_last_messages);
466        self.mark_compacted(keep_from, Some(cadence_range))
467    }
468
469    /// Cumulative count of agent-loop turn boundaries observed (#2346).
470    ///
471    /// Why: Lives on `Transcript` (not `AgentLoop`, which is reconstructed
472    /// fresh on every `task.run` call — see `task::executor::run_and_record`)
473    /// so cadence counts turns CUMULATIVELY across a session's whole
474    /// lifetime, matching the epic's "500+ turn interactive session" framing
475    /// rather than resetting every call.
476    /// What: The current `cadence_turn_count`.
477    /// Test: `cadence::tests::fires_every_n_turns`.
478    pub fn cadence_turn_count(&self) -> usize {
479        self.cadence_turn_count
480    }
481
482    /// Number of times the cadence compressor has fired (#2346).
483    ///
484    /// Why: The turn-count test ("cadence fires exactly every N turns") and
485    /// the "compaction_events == 0" acceptance test both need an
486    /// observability counter distinct from `compacted_count` (entries, not
487    /// events).
488    /// What: The current `cadence_fire_count`.
489    /// Test: `cadence::tests::fires_every_n_turns`.
490    pub fn cadence_fire_count(&self) -> usize {
491        self.cadence_fire_count
492    }
493
494    /// Record that the #2308 threshold compactor (`Self::maybe_compact`)
495    /// actually fired on this call (#2349, epic #2343).
496    ///
497    /// Why: Under the #2346 cadence system, a threshold fire is no longer
498    /// the primary token-efficiency mechanism (cadence is) — it becomes a
499    /// never-event regression signal that cadence sizing, daemon
500    /// availability, or turn-size assumptions were violated. The call site
501    /// (`agent_loop::AgentLoop::maybe_compact_transcript`) increments this
502    /// on EVERY threshold fire regardless of whether cadence is enabled —
503    /// see that method's docs for why the *logging* half of this signal is
504    /// cadence-gated while the counter itself is not. `pub(crate)` (rather
505    /// than `pub(super)`) so `session::registry_tests` can exercise the
506    /// `session.get_transcript` wiring end-to-end without going through a
507    /// full `AgentLoop` run.
508    /// What: Saturating-increments `threshold_compaction_events` by one.
509    /// Test: `agent_loop::tests::forced_degradation_increments_counter_and_logs_error`,
510    /// `agent_loop::tests::cadence_none_threshold_fire_does_not_log_error`,
511    /// `registry_tests::get_transcript_reports_compaction_events`.
512    pub(crate) fn record_threshold_compaction(&mut self) {
513        self.threshold_compaction_events = self.threshold_compaction_events.saturating_add(1);
514    }
515
516    /// Cumulative count of #2308 threshold-compactor fires (#2349).
517    ///
518    /// Why: The epic #2343 success metric is a "500+ turn session with
519    /// `compaction_events == 0`" — this is the field that metric reads,
520    /// exposed onto `session::TranscriptRecord.compaction_events` via
521    /// `SessionRegistry::get_transcript`.
522    /// What: The current `threshold_compaction_events`.
523    /// Test: `agent_loop::tests::forced_degradation_increments_counter_and_logs_error`,
524    /// `cadence_tests::stays_under_budget_every_turn_and_threshold_never_fires`.
525    pub fn compaction_events(&self) -> u32 {
526        self.threshold_compaction_events
527    }
528
529    /// Number of entries currently marked `compacted`.
530    ///
531    /// Why: Test/observability accessor proving compaction happened without
532    /// exposing the private `TranscriptEntry` type.
533    /// What: Counts entries with `compacted == true`.
534    /// Test: `transcript::tests::maybe_compact_marks_middle_span_only`.
535    pub fn compacted_count(&self) -> usize {
536        self.entries.iter().filter(|e| e.compacted).count()
537    }
538
539    /// Join all recorded assistant text turns into the final answer string.
540    ///
541    /// Why: The `AgentOutput.content` should be the model's prose across the
542    /// run, not the raw JSON transcript; joining the text turns yields that.
543    /// What: Joins the recorded non-empty assistant texts with blank lines.
544    /// Test: `transcript::tests::assistant_text_joins_turns`.
545    pub fn assistant_text(&self) -> String {
546        self.assistant_texts.join("\n\n")
547    }
548
549    /// Convenience accessor: push the assistant turn straight from a response.
550    ///
551    /// Why: Callers usually have a `ChatResponse` in hand; this saves them
552    /// destructuring `first_text`/`first_tool_calls` at the call site.
553    /// What: Extracts the first choice's text and tool calls and delegates to
554    /// `push_assistant`.
555    /// Test: `transcript::tests::push_response_appends_assistant`.
556    pub fn push_response(&mut self, resp: &ChatResponse) {
557        let text = resp.first_text();
558        let calls = resp.first_tool_calls().to_vec();
559        self.push_assistant(text, &calls);
560    }
561
562    /// Append a plain `user`-role turn WITHOUT re-seeding a system message
563    /// (#2344).
564    ///
565    /// Why: `session::SessionRegistry::begin_pm_transcript` uses this to
566    /// hand a SUBSEQUENT `task.run` on the same session its new request as a
567    /// fresh user turn on top of the growing, already-seeded conversation —
568    /// `Transcript::seed` is only ever called ONCE per session, on its
569    /// first run.
570    /// What: Pushes an uncompacted, unpinned `user`-role `ChatMessage`.
571    /// Test: `transcript_tests::push_user_appends_without_reseeding_system`.
572    pub fn push_user(&mut self, task: &str) {
573        self.entries
574            .push(TranscriptEntry::fresh(ChatMessage::user(task)));
575    }
576
577    /// Number of assistant text turns recorded so far (#2344).
578    ///
579    /// Why: `AgentLoop::run_with_transcript` needs a marker of "how much
580    /// assistant text existed before this run" so it can later scope the
581    /// run's OWN reported output to just its new turns via
582    /// [`Self::assistant_text_since`], even though the underlying
583    /// conversation is persistent and keeps growing across runs.
584    /// What: The current length of the internal `assistant_texts`
585    /// accumulator.
586    /// Test: `transcript_tests::assistant_text_since_scopes_to_new_turns_only`.
587    pub fn assistant_text_mark(&self) -> usize {
588        self.assistant_texts.len()
589    }
590
591    /// Join assistant text turns recorded SINCE `mark` (#2344).
592    ///
593    /// Why: Pairs with [`Self::assistant_text_mark`] — see its docs.
594    /// What: Joins `self.assistant_texts[mark..]` the same way
595    /// [`Self::assistant_text`] joins the whole vec. An out-of-range `mark`
596    /// (should never happen — only ever produced by `assistant_text_mark` on
597    /// the same instance) degrades to an empty string rather than panicking.
598    /// Test: `transcript_tests::assistant_text_since_scopes_to_new_turns_only`,
599    /// `transcript_tests::assistant_text_since_out_of_range_mark_is_empty_not_panicking`.
600    pub fn assistant_text_since(&self, mark: usize) -> String {
601        self.assistant_texts.get(mark..).unwrap_or(&[]).join("\n\n")
602    }
603
604    /// A cloned handle to this transcript's live goal slots (#2347).
605    ///
606    /// Why: `tools::goals::{SetGoalTool, ClearGoalTool}` need mutable access
607    /// to the EXACT SAME `GoalSlots` this `Transcript` renders in
608    /// `to_messages` — cloning the `Arc` (rather than copying the data)
609    /// means a tool's `set`/`clear` call is visible to `to_messages` on the
610    /// very next turn, with no separate sync step. Callers register the
611    /// goal tools with this handle BEFORE handing the `Transcript` to
612    /// `AgentLoop::run_with_transcript` (see `task::executor::run_and_record`).
613    /// What: `Arc::clone` of the internal `goals` field.
614    /// Test: `transcript_tests::goals_handle_mutation_visible_in_to_messages`.
615    pub fn goals_handle(&self) -> Arc<Mutex<GoalSlots>> {
616        Arc::clone(&self.goals)
617    }
618}
619
620/// Compute the group-safe cutoff index for a naive `keep_last_messages`
621/// active-zone size (#2278 Fix A; extracted for #2346 so the cadence
622/// compressor shares this EXACT logic with [`Transcript::maybe_compact`]).
623///
624/// Why: A raw entry-count cutoff (`entries.len() - keep_last_messages`) has
625/// no tool-call awareness — see [`Transcript::maybe_compact`]'s docs for the
626/// Bedrock `ValidationException` this fixes. Both compaction callers
627/// (threshold and cadence) need the identical adjustment, so it is pulled out
628/// once rather than risking the two independently drifting.
629/// What: Computes the naive cutoff, then — if it falls strictly inside a
630/// [`turn_group_start`]/[`turn_group_end`] group — pulls it forward to the
631/// group's start. Returns the (possibly adjusted) cutoff.
632/// Test: `transcript::tests::maybe_compact_pulls_whole_multi_tool_call_group_forward`.
633fn resolve_keep_from(entries: &[TranscriptEntry], keep_last_messages: usize) -> usize {
634    let mut keep_from = entries.len().saturating_sub(keep_last_messages);
635    if keep_from > 0
636        && keep_from < entries.len()
637        && let Some(group_start) = turn_group_start(entries, keep_from - 1)
638        && turn_group_end(entries, group_start) >= keep_from
639    {
640        keep_from = group_start;
641    }
642    keep_from
643}
644
645/// If entry `idx` belongs to a turn group, return the group's assistant
646/// entry index (#2278 Fix A).
647///
648/// Why: `maybe_compact` needs to know whether its naive count-based cutoff
649/// lands inside an atomic assistant-`tool_calls` + answering-`tool`-entries
650/// group, so it can pull the whole group forward rather than splitting it.
651/// What: A turn group is one assistant entry with `tool_calls: Some(_)` plus
652/// the maximal contiguous run of `tool`-role entries immediately following
653/// it. Walks backward from `idx` through any contiguous `tool`-role entries;
654/// the walk stops at the first non-`tool` entry, which is the group's
655/// assistant entry IF it carries `tool_calls` — returns its index in that
656/// case, `None` otherwise (covers `idx` itself already being that assistant
657/// entry, when the backward walk takes zero steps).
658/// Test: `transcript::tests::maybe_compact_pulls_whole_multi_tool_call_group_forward`.
659fn turn_group_start(entries: &[TranscriptEntry], idx: usize) -> Option<usize> {
660    let mut i = idx;
661    while entries[i].message.role == "tool" {
662        if i == 0 {
663            return None;
664        }
665        i -= 1;
666    }
667    (entries[i].message.role == "assistant" && entries[i].message.tool_calls.is_some()).then_some(i)
668}
669
670/// Return the last index of the turn group starting at `group_start`
671/// (#2278 Fix A).
672///
673/// Why: Once [`turn_group_start`] confirms a group exists, `maybe_compact`
674/// must know where it ENDS to tell whether it straddles the naive cutoff —
675/// naturally spanning however many `tool` entries answer a multi-tool-call
676/// turn, not just one.
677/// What: Scans forward from `group_start` while the next entry is `tool`-role;
678/// returns the last such index (or `group_start` itself if no `tool` entry
679/// immediately follows, e.g. a `tool_calls` turn with no results recorded
680/// yet).
681/// Test: `transcript::tests::maybe_compact_pulls_whole_multi_tool_call_group_forward`.
682fn turn_group_end(entries: &[TranscriptEntry], group_start: usize) -> usize {
683    let mut i = group_start;
684    while i + 1 < entries.len() && entries[i + 1].message.role == "tool" {
685        i += 1;
686    }
687    i
688}
689
690/// Flush a pending compacted span into `out` as one summary message, if any.
691///
692/// Why: `to_messages` needs to collapse a contiguous run of compacted entries
693/// exactly once, whether the run ends because a non-compacted entry follows
694/// or because the entries list ended; sharing this helper avoids duplicating
695/// the "if non-empty, summarise and clear" logic at both call sites. (#2346)
696/// A span produced by the cadence compressor carries a `cadence_turn_range`
697/// on each of its entries; appending a durable-memory pointer to the summary
698/// text (rather than inventing a second, cadence-specific summary format)
699/// keeps the deterministic `summarize_span` base identical for both
700/// compaction paths.
701/// What: If `span` is non-empty, pushes one `ChatMessage::system` carrying
702/// `summarize_span`'s text over the span's messages, then — if any entry in
703/// the span carries a `cadence_turn_range` — appends
704/// `" — full detail preserved in session memory (turns {min}-{max}); use
705/// recall_session to retrieve"` using the min start / max end across all
706/// tagged entries in the span (a span can, in principle, straddle more than
707/// one cadence fire once the continuous-budget-enforcement loop has run more
708/// than once on the same turn). A span with no tagged entries (the threshold
709/// path, or #2070 pre-#2346 behaviour) gets no pointer appended — byte-
710/// identical to before this ticket. Clears `span` either way.
711/// Test: `transcript::tests::to_messages_collapses_compacted_span` (no
712/// pointer, threshold path unchanged); `cadence::tests::summary_references_turn_range`.
713fn flush_span(out: &mut Vec<ChatMessage>, span: &mut Vec<(ChatMessage, Option<(usize, usize)>)>) {
714    if span.is_empty() {
715        return;
716    }
717    let messages: Vec<ChatMessage> = span.iter().map(|(m, _)| m.clone()).collect();
718    let mut text = summarize_span(&messages);
719
720    let start = span.iter().filter_map(|(_, r)| r.map(|(s, _)| s)).min();
721    let end = span.iter().filter_map(|(_, r)| r.map(|(_, e)| e)).max();
722    if let (Some(start), Some(end)) = (start, end) {
723        text.push_str(&format!(
724            " — full detail preserved in session memory (turns {start}-{end}); \
725             use recall_session to retrieve"
726        ));
727    }
728
729    out.push(ChatMessage::system(text));
730    span.clear();
731}
732
733#[cfg(test)]
734#[path = "transcript_tests.rs"]
735mod tests;