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