trusty-code 0.2.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
//! Conversation transcript for the multi-turn agent loop.
//!
//! Why: The loop must accumulate the full message history (system, user,
//! assistant turns, and tool results) to send back to the model on each
//! iteration and to render a final answer. Wrapping the `Vec<ChatMessage>` in a
//! small type gives the loop intent-revealing helpers (`push_assistant`,
//! `push_tool_result`) and keeps message-construction details out of the loop
//! body. (#2070) It also owns non-destructive context compaction (vision spec
//! §5.4): each entry carries a `compacted` flag rather than the message ever
//! being deleted, so the outward, model-facing view can shrink while the
//! stored history stays fully auditable.
//! What: `Transcript` owns an ordered `Vec<TranscriptEntry>` (message +
//! compacted flag + pinned flag); helpers append the seed messages, an
//! assistant turn (text and/or tool calls), and a `tool` role result message.
//! `assistant_text` concatenates the assistant text turns for the final
//! `AgentOutput`. `maybe_compact` (#2070) applies [`super::compaction`]'s
//! threshold policy; `to_messages` renders the model-facing view —
//! contiguous compacted runs collapsed to one summary message, followed by a
//! replayed copy of the last user message once any compaction has occurred
//! (§5.4 items 2-3) — while `messages` always returns the complete,
//! uncompacted raw history. `push_tool_result` (#2070) pins any
//! [`crate::tools::USE_SKILL_TOOL_NAME`] result forever — §5.4 item 5's
//! "preserve skill outputs... forever" — alongside `system`/`user` turns.
//! Test: `agent_loop::tests` build transcripts indirectly through the loop;
//! `transcript::tests` cover the helpers and compaction directly.

use std::sync::{Arc, Mutex};

use crate::llm::{ChatMessage, ChatResponse, ToolCall};
use crate::tools::USE_SKILL_TOOL_NAME;

use super::compaction::{CompactionConfig, should_compact, summarize_span};
use super::goals::GoalSlots;

/// One stored conversation turn plus its compaction state (#2070).
///
/// Why: Non-destructive compaction requires the original message to survive
/// even after it stops being sent to the model verbatim; a bare flag next to
/// the message (rather than removing it from the vector) is the simplest
/// representation that satisfies both "shrink what the model sees" and
/// "never lose the audit trail". `pinned` is a SEPARATE flag from `compacted`
/// (rather than overloading `compacted`) because a pinned entry must never
/// transition to `compacted` at all — it is a permanent exemption, not a
/// one-way state like compaction itself.
/// What: `message` is the original, untouched `ChatMessage`; `compacted`
/// starts `false` and is set `true` by `Transcript::maybe_compact` — never
/// reset, since compaction is a one-way transform for a given entry. `pinned`
/// starts `false` and is set `true` only at construction time (never later)
/// for entries `maybe_compact` must always skip — currently: skill outputs
/// (`push_tool_result` sets it when `name == USE_SKILL_TOOL_NAME`; §5.4 item
/// 5 also covers `system`/`user` role turns, but those are matched by role
/// directly in `maybe_compact` rather than via this flag, since they are
/// identifiable without extra state).
/// Test: `transcript::tests::maybe_compact_marks_middle_span_only`,
/// `transcript::tests::maybe_compact_never_compacts_pinned_skill_output`.
#[derive(Debug, Clone)]
struct TranscriptEntry {
    message: ChatMessage,
    compacted: bool,
    pinned: bool,
    /// The cadence-turn range `(start, end)` active when this entry was
    /// marked `compacted` by the #2346 cadence compressor — `None` for an
    /// uncompacted entry OR one compacted by the threshold path
    /// (`Transcript::maybe_compact`), which has no turn-range concept.
    /// `to_messages`'s `flush_span` reads this to append a
    /// "full detail in session memory (turns N-M)" pointer onto the
    /// synthetic summary message, but only for spans the cadence
    /// compressor produced.
    cadence_turn_range: Option<(usize, usize)>,
}

impl TranscriptEntry {
    /// An ordinary entry: uncompacted, unpinned.
    fn fresh(message: ChatMessage) -> Self {
        Self {
            message,
            compacted: false,
            pinned: false,
            cadence_turn_range: None,
        }
    }

    /// A permanently-exempt entry (#2070): uncompacted and, unlike `fresh`,
    /// never eligible to become compacted by `Transcript::maybe_compact`.
    fn pinned(message: ChatMessage) -> Self {
        Self {
            message,
            compacted: false,
            pinned: true,
            cadence_turn_range: None,
        }
    }
}

/// Running conversation history for one agent-loop run.
///
/// Why: Centralises message accumulation so the loop body stays focused on
/// control flow rather than `ChatMessage` plumbing, and (#2070) centralises
/// the compaction state machine so the loop only has to call
/// `maybe_compact` at its turn boundary.
/// What: A thin wrapper over `Vec<TranscriptEntry>` with append helpers, a
/// raw-history accessor, a compacted model-facing view, and an
/// assistant-text accessor. `last_compaction_len` records the entry count at
/// the moment compaction most recently fired (`None` if it has never fired
/// in this run) — `to_messages` compares it against the CURRENT entry count
/// to append the last-user-message replay (§5.4 item 3) only on the turn
/// compaction actually fired on, not on every subsequent call. (#2347) `goals`
/// holds the session's 5 fixed privileged goal slots behind an `Arc<Mutex<_>>`
/// (rather than a bare `GoalSlots`) so `tools::goals::{SetGoalTool,
/// ClearGoalTool}` — constructed and registered into the PM's tool registry
/// BEFORE this `Transcript` value is handed to `AgentLoop::run_with_transcript`
/// — can mutate the SAME live state `to_messages` reads on every call via
/// `Self::goals_handle`'s cloned `Arc`. Deliberately NOT a real
/// `TranscriptEntry`: it is rendered fresh into the model-facing view on every
/// `to_messages` call rather than stored/compacted, so it can never be folded
/// into a compaction summary and never drifts from the live tool-mutated state.
/// Test: `transcript::tests::*`.
#[derive(Debug, Default, Clone)]
pub struct Transcript {
    entries: Vec<TranscriptEntry>,
    assistant_texts: Vec<String>,
    last_compaction_len: Option<usize>,
    goals: Arc<Mutex<GoalSlots>>,
    /// (#2346) Count of agent-loop turn boundaries this transcript has
    /// observed via `tick_cadence_turn`, cumulative for the transcript's
    /// entire lifetime — including across repeated `task.run` calls on the
    /// same persistent session transcript, since this field lives on
    /// `Transcript` (the session-persistent piece) rather than on
    /// `AgentLoop` (reconstructed fresh per call).
    cadence_turn_count: usize,
    /// (#2346) The `cadence_turn_count` value as of the last time the
    /// cadence compressor actually marked new entries `compacted` — the
    /// start of the NEXT reported turn range is always one past this.
    cadence_last_fire_turn: usize,
    /// (#2346) Number of times the cadence compressor has fired (marked at
    /// least one new entry `compacted`) — an observability/test counter,
    /// distinct from `compacted_count` (which counts entries, not events).
    cadence_fire_count: usize,
    /// (#2349) Number of times the #2308 threshold compactor
    /// (`Self::maybe_compact`) has actually fired — i.e. returned `true` —
    /// cumulative for the transcript's entire lifetime, mirroring
    /// `cadence_fire_count`'s same "events, not entries" accounting. Under
    /// epic #2343's cadence system this is meant to stay `0` in steady state
    /// (see [`Self::record_threshold_compaction`]'s docs); exposed
    /// read-only via [`Self::compaction_events`] and, from there, onto
    /// `session::TranscriptRecord.compaction_events`.
    threshold_compaction_events: u32,
}

impl Transcript {
    /// Seed a transcript with a system prompt and the user task.
    ///
    /// Why: Every run starts from exactly these two turns; bundling the seed in
    /// a constructor prevents the loop from forgetting either.
    /// What: Pushes a `system` message then a `user` message, both starting
    /// uncompacted. `maybe_compact` (#2070) never marks `system` or `user`
    /// role entries — see its docs — so these two seed turns are preserved
    /// forever regardless of how long the run continues.
    /// Test: `transcript::tests::seed_has_two_messages`.
    pub fn seed(system: &str, task: &str) -> Self {
        Self {
            entries: vec![
                TranscriptEntry::fresh(ChatMessage::system(system)),
                TranscriptEntry::fresh(ChatMessage::user(task)),
            ],
            assistant_texts: Vec::new(),
            last_compaction_len: None,
            goals: Arc::new(Mutex::new(GoalSlots::new())),
            cadence_turn_count: 0,
            cadence_last_fire_turn: 0,
            cadence_fire_count: 0,
            threshold_compaction_events: 0,
        }
    }

    /// Append the assistant turn from a model response.
    ///
    /// Why: The model's turn (text and any tool calls) must be added to history
    /// before the tool results, so the next request reflects the real ordering
    /// the API expects.
    /// What: Reconstructs a `ChatMessage` with `role = "assistant"`, carrying the
    /// optional text content and the emitted tool calls; records the text (if
    /// any) for the final answer.
    /// Test: `transcript::tests::push_assistant_records_text`.
    pub fn push_assistant(&mut self, text: Option<String>, tool_calls: &[ToolCall]) {
        if let Some(t) = &text
            && !t.is_empty()
        {
            self.assistant_texts.push(t.clone());
        }
        let tool_calls = if tool_calls.is_empty() {
            None
        } else {
            Some(tool_calls.to_vec())
        };
        self.entries.push(TranscriptEntry::fresh(ChatMessage {
            role: "assistant".into(),
            content: text,
            tool_calls,
            tool_call_id: None,
            name: None,
            cache_control: None,
        }));
    }

    /// Append a `tool` role result message answering a specific tool call.
    ///
    /// Why: The API requires each tool call to be answered by a `tool` message
    /// referencing its `tool_call_id`, or the next assistant turn errors.
    /// (#2070) A `use_skill` result is the loaded body of a skill the model
    /// deliberately chose to invoke — §5.4 item 5 requires it survive
    /// compaction forever, the same guarantee `system`/`user` turns get.
    /// What: Pushes a `ChatMessage::tool_result` with the call id, function
    /// name, and textual result — as a permanently `pinned` entry when
    /// `name == `[`USE_SKILL_TOOL_NAME`], otherwise as an ordinary compaction-
    /// eligible entry.
    /// Test: `transcript::tests::push_tool_result_sets_call_id`,
    /// `transcript::tests::maybe_compact_never_compacts_pinned_skill_output`,
    /// `transcript::tests::maybe_compact_still_compacts_non_skill_tool_results`.
    pub fn push_tool_result(&mut self, tool_call_id: &str, name: &str, content: &str) {
        let message = ChatMessage::tool_result(tool_call_id, name, content);
        let entry = if name == USE_SKILL_TOOL_NAME {
            TranscriptEntry::pinned(message)
        } else {
            TranscriptEntry::fresh(message)
        };
        self.entries.push(entry);
    }

    /// Return the complete, uncompacted raw message history.
    ///
    /// Why: (#2070) Non-destructive compaction is only meaningful if the full
    /// history stays retrievable for audit even after `to_messages` starts
    /// collapsing older turns; this is that escape hatch.
    /// What: Clones every entry's original `ChatMessage`, in order, regardless
    /// of its `compacted` flag.
    /// Test: `transcript::tests::messages_reflects_appends`,
    /// `transcript::tests::compacted_entries_remain_in_raw_history`.
    pub fn messages(&self) -> Vec<ChatMessage> {
        self.entries.iter().map(|e| e.message.clone()).collect()
    }

    /// Render the model-facing view: compacted spans collapsed to a summary,
    /// the live goal slots injected at position `[1]`, plus a replayed last
    /// user message once compaction has occurred.
    ///
    /// Why: This is what `ChatRequest.messages` actually sends — it must
    /// shrink once compaction fires (the whole point of §5.4) while staying
    /// a valid, coherently-ordered conversation. (#2347) The goals injection
    /// happens HERE, fresh on every call, rather than being a stored
    /// `TranscriptEntry` — that is what makes it immune to compaction (it
    /// never exists as an entry `maybe_compact` could mark) and immune to
    /// drift (it always reflects whatever `tools::goals::{SetGoalTool,
    /// ClearGoalTool}` most recently wrote via the same `Arc<Mutex<_>>`).
    /// What: Walks entries in order; a run of one-or-more contiguous
    /// `compacted` entries is replaced by ONE synthetic `system`-role message
    /// (`super::compaction::summarize_span`'s one-line text, plus (#2346) a
    /// "full detail in session memory (turns N-M)" pointer appended when any
    /// entry in the span carries a `cadence_turn_range` — see
    /// [`flush_span`]'s docs) in its place; uncompacted entries pass through
    /// unchanged. (#2347) If `self.goals.render()` returns `Some`, a
    /// synthetic `system`-role message carrying that text is inserted at
    /// index `1` (immediately after the real system message, which
    /// `Transcript::seed` always places at index `0` and `maybe_compact`
    /// never touches) — or appended if `out` is empty, a defensive case that
    /// never occurs via `seed`. A poisoned goals lock degrades to "no goals
    /// block" rather than panicking (mirrors `run_task::recorder`'s
    /// poisoned-lock convention). After that insertion, if
    /// `last_compaction_len` equals the CURRENT entry count (i.e. this call
    /// is happening on the very turn `maybe_compact` last fired on — the
    /// loop calls `maybe_compact` then `to_messages` back-to-back before any
    /// further entries are appended), the LAST `user`-role entry's message is
    /// cloned and appended again at the very end — §5.4 item 3's "re-anchor
    /// the model" replay. On every later call the entry count has grown past
    /// `last_compaction_len`, so the replay does not repeat until compaction
    /// fires again. A transcript with no `user` entry (never happens via
    /// `seed`, but guarded rather than assumed) simply skips the replay.
    /// Test: `transcript::tests::to_messages_collapses_compacted_span`,
    /// `transcript::tests::to_messages_replays_last_user_message_after_compaction`,
    /// `transcript::tests::to_messages_does_not_replay_on_every_subsequent_turn`,
    /// `transcript::tests::to_messages_is_passthrough_before_compaction`,
    /// `transcript::tests::to_messages_injects_goals_at_position_one`,
    /// `transcript::tests::to_messages_omits_goals_message_when_all_empty`,
    /// `transcript::tests::to_messages_goals_survive_aggressive_compaction`.
    pub fn to_messages(&self) -> Vec<ChatMessage> {
        // #2347: `+ 1` accounts for the goals-injection message inserted
        // below, so the common case never reallocates.
        let mut out = Vec::with_capacity(self.entries.len() + 1);
        let mut compacted_span: Vec<(ChatMessage, Option<(usize, usize)>)> = Vec::new();

        for entry in &self.entries {
            if entry.compacted {
                compacted_span.push((entry.message.clone(), entry.cadence_turn_range));
                continue;
            }
            flush_span(&mut out, &mut compacted_span);
            out.push(entry.message.clone());
        }
        flush_span(&mut out, &mut compacted_span);

        let goals_text = self.goals.lock().ok().and_then(|g| g.render());
        if let Some(text) = goals_text {
            let insert_at = out.len().min(1);
            out.insert(insert_at, ChatMessage::system(text));
        }

        if self.last_compaction_len == Some(self.entries.len())
            && let Some(last_user) = self.entries.iter().rev().find(|e| e.message.role == "user")
        {
            out.push(last_user.message.clone());
        }

        out
    }

    /// Apply the compaction policy: mark eligible older entries `compacted`.
    ///
    /// Why: (#2070) This is the turn-boundary hook the agent loop calls —
    /// gated by the caller on `HarnessMode::DailyDriver` (Parity must never
    /// compact, per §5.9's D2 reconciliation) — so growth is bounded without
    /// the loop body needing to know compaction's internals. (#2278) A raw
    /// entry-COUNT cutoff has no tool-call awareness: when it lands between
    /// an assistant entry carrying `tool_calls` and one of its answering
    /// `tool`-role entries, the assistant gets folded into the compacted
    /// summary while the answering entry survives verbatim in the kept
    /// zone — an orphaned tool result with no tool use, which providers
    /// with a strict pairing invariant (Bedrock's Converse API) reject
    /// outright.
    /// What: No-ops (returns `false`) unless the CURRENT model-facing view
    /// (`to_messages()`, not the ever-growing raw history — raw size would
    /// re-trigger every turn even after compaction shrank what's actually
    /// sent) exceeds `cfg.token_threshold`. Otherwise computes the naive
    /// count-based cutoff `keep_from = len - cfg.keep_last_messages`, then
    /// (#2278) [`turn_group_start`]/[`turn_group_end`] check whether that
    /// cutoff falls INSIDE a turn group — an assistant entry carrying
    /// `tool_calls` plus the maximal contiguous run of `tool`-role entries
    /// immediately following it (naturally covering multi-tool-call turns:
    /// N `tool_calls` followed by up to N `tool` entries). If so, the whole
    /// group is pulled FORWARD into the kept zone by moving `keep_from` back
    /// to the group's start — `cfg.keep_last_messages` becomes a soft floor
    /// that may slightly enlarge the active zone rather than ever splitting
    /// a group. Marks every entry before the (possibly adjusted) `keep_from`
    /// as `compacted = true`, EXCEPT entries already compacted (a one-way
    /// transform), `pinned` entries (§5.4 item 5's skill-output half — see
    /// `push_tool_result`), and `system`/`user` role entries (§5.4 item 5's
    /// "preserve... user requests forever" half). Records `last_compaction_len
    /// = Some(self.entries.len())` and returns `true` only if at least one
    /// entry was newly marked (an already-fully-compacted or
    /// entirely-preserved prefix is a no-op, not a spurious trigger) — this
    /// marker is what lets `to_messages` replay the last user message
    /// exactly once, on this turn, rather than on every subsequent call.
    /// Test: `transcript::tests::maybe_compact_is_noop_below_threshold`,
    /// `transcript::tests::maybe_compact_never_touches_system_or_user`,
    /// `transcript::tests::maybe_compact_never_compacts_pinned_skill_output`,
    /// `transcript::tests::maybe_compact_still_compacts_non_skill_tool_results`,
    /// `transcript::tests::maybe_compact_pulls_whole_multi_tool_call_group_forward`.
    pub fn maybe_compact(&mut self, cfg: &CompactionConfig) -> bool {
        if !should_compact(&self.to_messages(), cfg) {
            return false;
        }
        let keep_from = resolve_keep_from(&self.entries, cfg.keep_last_messages);
        self.mark_compacted(keep_from, None)
    }

    /// Mark every eligible entry before `keep_from` as `compacted`, tagging
    /// each newly-marked entry with `cadence_range` (#2346).
    ///
    /// Why: [`Self::maybe_compact`] (threshold-triggered, no turn-range
    /// concept) and the #2346 cadence compressor's
    /// [`Self::compact_span_tagged`] both need to apply the EXACT same
    /// pinned/`system`/`user`/already-compacted exemptions — this is the one
    /// place that logic lives, so the two callers can never independently
    /// drift.
    /// What: For every entry in `self.entries[..keep_from]` that is not
    /// already `compacted`, not `pinned`, and not `system`/`user` role, sets
    /// `compacted = true` and `cadence_turn_range = cadence_range`. Records
    /// `last_compaction_len` and returns whether anything was newly marked,
    /// exactly as `maybe_compact` did before this extraction.
    /// Test: `transcript::tests::maybe_compact_marks_middle_span_only` (via
    /// `maybe_compact`); `transcript::tests::compact_span_tagged_*` (via the
    /// cadence path).
    fn mark_compacted(&mut self, keep_from: usize, cadence_range: Option<(usize, usize)>) -> bool {
        let mut newly_compacted = false;
        for entry in &mut self.entries[..keep_from] {
            if entry.compacted || entry.pinned {
                continue;
            }
            if entry.message.role == "system" || entry.message.role == "user" {
                continue;
            }
            entry.compacted = true;
            entry.cadence_turn_range = cadence_range;
            newly_compacted = true;
        }
        if newly_compacted {
            self.last_compaction_len = Some(self.entries.len());
        }
        newly_compacted
    }

    /// Advance the cadence turn counter and report whether THIS turn is a
    /// cadence-fire turn (#2346).
    ///
    /// Why: `agent_loop::cadence::maybe_cadence_compress` needs a
    /// session-persistent counter (see [`Self::cadence_turn_count`]'s field
    /// doc for why it lives on `Transcript`, not `AgentLoop`) it can advance
    /// exactly once per turn boundary and compare against the configured
    /// cadence.
    /// What: Increments `cadence_turn_count`, then returns `true` when
    /// `cadence_turns > 0` and the new count is an exact multiple of it —
    /// `cadence_turns == 0` never fires (guards the modulo and treats "0" as
    /// "cadence disabled" rather than firing every turn).
    /// Test: `cadence::tests::fires_every_n_turns`.
    pub(super) fn tick_cadence_turn(&mut self, cadence_turns: usize) -> bool {
        self.cadence_turn_count += 1;
        cadence_turns > 0 && self.cadence_turn_count.is_multiple_of(cadence_turns)
    }

    /// The turn range `(start, end)` a cadence compression happening RIGHT
    /// NOW should be tagged with (#2346).
    ///
    /// Why: A span's "turns N-M" label (surfaced in the summary text via
    /// [`flush_span`]) must cover every turn since the LAST fire, not just
    /// the current one — otherwise a gap between fires would be
    /// unaccounted-for in the durable-memory pointer.
    /// What: `(cadence_last_fire_turn + 1, cadence_turn_count)`.
    /// Test: `cadence::tests::summary_references_turn_range`.
    pub(super) fn begin_cadence_range(&self) -> (usize, usize) {
        (self.cadence_last_fire_turn + 1, self.cadence_turn_count)
    }

    /// Record that a cadence fire just happened (#2346).
    ///
    /// Why: [`Self::begin_cadence_range`]'s next call must start the range
    /// right after this fire's end, and `cadence_fire_count` is the
    /// "cadence fires exactly every N turns" test's observability hook.
    /// What: Sets `cadence_last_fire_turn = cadence_turn_count` and
    /// increments `cadence_fire_count`.
    /// Test: `cadence::tests::fires_every_n_turns`.
    pub(super) fn advance_cadence_fire_marker(&mut self) {
        self.cadence_last_fire_turn = self.cadence_turn_count;
        self.cadence_fire_count += 1;
    }

    /// Unconditionally compact the span older than `keep_last_messages`,
    /// tagged with `cadence_range` — the #2346 cadence compressor's
    /// entry point into the shared group-safe marking machinery.
    ///
    /// Why: Unlike [`Self::maybe_compact`], this is NEVER gated on a token
    /// threshold — cadence fires on a turn-count schedule regardless of
    /// current size, and the continuous-budget-enforcement loop
    /// (`agent_loop::cadence::enforce_budget`) calls this repeatedly with a
    /// shrinking `keep_last_messages` until the transcript is back under
    /// budget. Reuses [`resolve_keep_from`] (#2278 group-safety) so a
    /// cadence-triggered cutoff can never split a tool-call/tool-result pair
    /// any more than the threshold path can.
    /// What: Delegates to [`resolve_keep_from`] then [`Self::mark_compacted`]
    /// with `Some(cadence_range)`.
    /// Test: `cadence::tests::*`.
    pub(super) fn compact_span_tagged(
        &mut self,
        keep_last_messages: usize,
        cadence_range: (usize, usize),
    ) -> bool {
        let keep_from = resolve_keep_from(&self.entries, keep_last_messages);
        self.mark_compacted(keep_from, Some(cadence_range))
    }

    /// Cumulative count of agent-loop turn boundaries observed (#2346).
    ///
    /// Why: Lives on `Transcript` (not `AgentLoop`, which is reconstructed
    /// fresh on every `task.run` call — see `task::executor::run_and_record`)
    /// so cadence counts turns CUMULATIVELY across a session's whole
    /// lifetime, matching the epic's "500+ turn interactive session" framing
    /// rather than resetting every call.
    /// What: The current `cadence_turn_count`.
    /// Test: `cadence::tests::fires_every_n_turns`.
    pub fn cadence_turn_count(&self) -> usize {
        self.cadence_turn_count
    }

    /// Number of times the cadence compressor has fired (#2346).
    ///
    /// Why: The turn-count test ("cadence fires exactly every N turns") and
    /// the "compaction_events == 0" acceptance test both need an
    /// observability counter distinct from `compacted_count` (entries, not
    /// events).
    /// What: The current `cadence_fire_count`.
    /// Test: `cadence::tests::fires_every_n_turns`.
    pub fn cadence_fire_count(&self) -> usize {
        self.cadence_fire_count
    }

    /// Record that the #2308 threshold compactor (`Self::maybe_compact`)
    /// actually fired on this call (#2349, epic #2343).
    ///
    /// Why: Under the #2346 cadence system, a threshold fire is no longer
    /// the primary token-efficiency mechanism (cadence is) — it becomes a
    /// never-event regression signal that cadence sizing, daemon
    /// availability, or turn-size assumptions were violated. The call site
    /// (`agent_loop::AgentLoop::maybe_compact_transcript`) increments this
    /// on EVERY threshold fire regardless of whether cadence is enabled —
    /// see that method's docs for why the *logging* half of this signal is
    /// cadence-gated while the counter itself is not. `pub(crate)` (rather
    /// than `pub(super)`) so `session::registry_tests` can exercise the
    /// `session.get_transcript` wiring end-to-end without going through a
    /// full `AgentLoop` run.
    /// What: Saturating-increments `threshold_compaction_events` by one.
    /// Test: `agent_loop::tests::forced_degradation_increments_counter_and_logs_error`,
    /// `agent_loop::tests::cadence_none_threshold_fire_does_not_log_error`,
    /// `registry_tests::get_transcript_reports_compaction_events`.
    pub(crate) fn record_threshold_compaction(&mut self) {
        self.threshold_compaction_events = self.threshold_compaction_events.saturating_add(1);
    }

    /// Cumulative count of #2308 threshold-compactor fires (#2349).
    ///
    /// Why: The epic #2343 success metric is a "500+ turn session with
    /// `compaction_events == 0`" — this is the field that metric reads,
    /// exposed onto `session::TranscriptRecord.compaction_events` via
    /// `SessionRegistry::get_transcript`.
    /// What: The current `threshold_compaction_events`.
    /// Test: `agent_loop::tests::forced_degradation_increments_counter_and_logs_error`,
    /// `cadence_tests::stays_under_budget_every_turn_and_threshold_never_fires`.
    pub fn compaction_events(&self) -> u32 {
        self.threshold_compaction_events
    }

    /// Number of entries currently marked `compacted`.
    ///
    /// Why: Test/observability accessor proving compaction happened without
    /// exposing the private `TranscriptEntry` type.
    /// What: Counts entries with `compacted == true`.
    /// Test: `transcript::tests::maybe_compact_marks_middle_span_only`.
    pub fn compacted_count(&self) -> usize {
        self.entries.iter().filter(|e| e.compacted).count()
    }

    /// Join all recorded assistant text turns into the final answer string.
    ///
    /// Why: The `AgentOutput.content` should be the model's prose across the
    /// run, not the raw JSON transcript; joining the text turns yields that.
    /// What: Joins the recorded non-empty assistant texts with blank lines.
    /// Test: `transcript::tests::assistant_text_joins_turns`.
    pub fn assistant_text(&self) -> String {
        self.assistant_texts.join("\n\n")
    }

    /// Convenience accessor: push the assistant turn straight from a response.
    ///
    /// Why: Callers usually have a `ChatResponse` in hand; this saves them
    /// destructuring `first_text`/`first_tool_calls` at the call site.
    /// What: Extracts the first choice's text and tool calls and delegates to
    /// `push_assistant`.
    /// Test: `transcript::tests::push_response_appends_assistant`.
    pub fn push_response(&mut self, resp: &ChatResponse) {
        let text = resp.first_text();
        let calls = resp.first_tool_calls().to_vec();
        self.push_assistant(text, &calls);
    }

    /// Append a plain `user`-role turn WITHOUT re-seeding a system message
    /// (#2344).
    ///
    /// Why: `session::SessionRegistry::begin_pm_transcript` uses this to
    /// hand a SUBSEQUENT `task.run` on the same session its new request as a
    /// fresh user turn on top of the growing, already-seeded conversation —
    /// `Transcript::seed` is only ever called ONCE per session, on its
    /// first run.
    /// What: Pushes an uncompacted, unpinned `user`-role `ChatMessage`.
    /// Test: `transcript_tests::push_user_appends_without_reseeding_system`.
    pub fn push_user(&mut self, task: &str) {
        self.entries
            .push(TranscriptEntry::fresh(ChatMessage::user(task)));
    }

    /// Number of assistant text turns recorded so far (#2344).
    ///
    /// Why: `AgentLoop::run_with_transcript` needs a marker of "how much
    /// assistant text existed before this run" so it can later scope the
    /// run's OWN reported output to just its new turns via
    /// [`Self::assistant_text_since`], even though the underlying
    /// conversation is persistent and keeps growing across runs.
    /// What: The current length of the internal `assistant_texts`
    /// accumulator.
    /// Test: `transcript_tests::assistant_text_since_scopes_to_new_turns_only`.
    pub fn assistant_text_mark(&self) -> usize {
        self.assistant_texts.len()
    }

    /// Join assistant text turns recorded SINCE `mark` (#2344).
    ///
    /// Why: Pairs with [`Self::assistant_text_mark`] — see its docs.
    /// What: Joins `self.assistant_texts[mark..]` the same way
    /// [`Self::assistant_text`] joins the whole vec. An out-of-range `mark`
    /// (should never happen — only ever produced by `assistant_text_mark` on
    /// the same instance) degrades to an empty string rather than panicking.
    /// Test: `transcript_tests::assistant_text_since_scopes_to_new_turns_only`,
    /// `transcript_tests::assistant_text_since_out_of_range_mark_is_empty_not_panicking`.
    pub fn assistant_text_since(&self, mark: usize) -> String {
        self.assistant_texts.get(mark..).unwrap_or(&[]).join("\n\n")
    }

    /// A cloned handle to this transcript's live goal slots (#2347).
    ///
    /// Why: `tools::goals::{SetGoalTool, ClearGoalTool}` need mutable access
    /// to the EXACT SAME `GoalSlots` this `Transcript` renders in
    /// `to_messages` — cloning the `Arc` (rather than copying the data)
    /// means a tool's `set`/`clear` call is visible to `to_messages` on the
    /// very next turn, with no separate sync step. Callers register the
    /// goal tools with this handle BEFORE handing the `Transcript` to
    /// `AgentLoop::run_with_transcript` (see `task::executor::run_and_record`).
    /// What: `Arc::clone` of the internal `goals` field.
    /// Test: `transcript_tests::goals_handle_mutation_visible_in_to_messages`.
    pub fn goals_handle(&self) -> Arc<Mutex<GoalSlots>> {
        Arc::clone(&self.goals)
    }
}

/// Compute the group-safe cutoff index for a naive `keep_last_messages`
/// active-zone size (#2278 Fix A; extracted for #2346 so the cadence
/// compressor shares this EXACT logic with [`Transcript::maybe_compact`]).
///
/// Why: A raw entry-count cutoff (`entries.len() - keep_last_messages`) has
/// no tool-call awareness — see [`Transcript::maybe_compact`]'s docs for the
/// Bedrock `ValidationException` this fixes. Both compaction callers
/// (threshold and cadence) need the identical adjustment, so it is pulled out
/// once rather than risking the two independently drifting.
/// What: Computes the naive cutoff, then — if it falls strictly inside a
/// [`turn_group_start`]/[`turn_group_end`] group — pulls it forward to the
/// group's start. Returns the (possibly adjusted) cutoff.
/// Test: `transcript::tests::maybe_compact_pulls_whole_multi_tool_call_group_forward`.
fn resolve_keep_from(entries: &[TranscriptEntry], keep_last_messages: usize) -> usize {
    let mut keep_from = entries.len().saturating_sub(keep_last_messages);
    if keep_from > 0
        && keep_from < entries.len()
        && let Some(group_start) = turn_group_start(entries, keep_from - 1)
        && turn_group_end(entries, group_start) >= keep_from
    {
        keep_from = group_start;
    }
    keep_from
}

/// If entry `idx` belongs to a turn group, return the group's assistant
/// entry index (#2278 Fix A).
///
/// Why: `maybe_compact` needs to know whether its naive count-based cutoff
/// lands inside an atomic assistant-`tool_calls` + answering-`tool`-entries
/// group, so it can pull the whole group forward rather than splitting it.
/// What: A turn group is one assistant entry with `tool_calls: Some(_)` plus
/// the maximal contiguous run of `tool`-role entries immediately following
/// it. Walks backward from `idx` through any contiguous `tool`-role entries;
/// the walk stops at the first non-`tool` entry, which is the group's
/// assistant entry IF it carries `tool_calls` — returns its index in that
/// case, `None` otherwise (covers `idx` itself already being that assistant
/// entry, when the backward walk takes zero steps).
/// Test: `transcript::tests::maybe_compact_pulls_whole_multi_tool_call_group_forward`.
fn turn_group_start(entries: &[TranscriptEntry], idx: usize) -> Option<usize> {
    let mut i = idx;
    while entries[i].message.role == "tool" {
        if i == 0 {
            return None;
        }
        i -= 1;
    }
    (entries[i].message.role == "assistant" && entries[i].message.tool_calls.is_some()).then_some(i)
}

/// Return the last index of the turn group starting at `group_start`
/// (#2278 Fix A).
///
/// Why: Once [`turn_group_start`] confirms a group exists, `maybe_compact`
/// must know where it ENDS to tell whether it straddles the naive cutoff —
/// naturally spanning however many `tool` entries answer a multi-tool-call
/// turn, not just one.
/// What: Scans forward from `group_start` while the next entry is `tool`-role;
/// returns the last such index (or `group_start` itself if no `tool` entry
/// immediately follows, e.g. a `tool_calls` turn with no results recorded
/// yet).
/// Test: `transcript::tests::maybe_compact_pulls_whole_multi_tool_call_group_forward`.
fn turn_group_end(entries: &[TranscriptEntry], group_start: usize) -> usize {
    let mut i = group_start;
    while i + 1 < entries.len() && entries[i + 1].message.role == "tool" {
        i += 1;
    }
    i
}

/// Flush a pending compacted span into `out` as one summary message, if any.
///
/// Why: `to_messages` needs to collapse a contiguous run of compacted entries
/// exactly once, whether the run ends because a non-compacted entry follows
/// or because the entries list ended; sharing this helper avoids duplicating
/// the "if non-empty, summarise and clear" logic at both call sites. (#2346)
/// A span produced by the cadence compressor carries a `cadence_turn_range`
/// on each of its entries; appending a durable-memory pointer to the summary
/// text (rather than inventing a second, cadence-specific summary format)
/// keeps the deterministic `summarize_span` base identical for both
/// compaction paths.
/// What: If `span` is non-empty, pushes one `ChatMessage::system` carrying
/// `summarize_span`'s text over the span's messages, then — if any entry in
/// the span carries a `cadence_turn_range` — appends
/// `" — full detail preserved in session memory (turns {min}-{max}); use
/// recall_session to retrieve"` using the min start / max end across all
/// tagged entries in the span (a span can, in principle, straddle more than
/// one cadence fire once the continuous-budget-enforcement loop has run more
/// than once on the same turn). A span with no tagged entries (the threshold
/// path, or #2070 pre-#2346 behaviour) gets no pointer appended — byte-
/// identical to before this ticket. Clears `span` either way.
/// Test: `transcript::tests::to_messages_collapses_compacted_span` (no
/// pointer, threshold path unchanged); `cadence::tests::summary_references_turn_range`.
fn flush_span(out: &mut Vec<ChatMessage>, span: &mut Vec<(ChatMessage, Option<(usize, usize)>)>) {
    if span.is_empty() {
        return;
    }
    let messages: Vec<ChatMessage> = span.iter().map(|(m, _)| m.clone()).collect();
    let mut text = summarize_span(&messages);

    let start = span.iter().filter_map(|(_, r)| r.map(|(s, _)| s)).min();
    let end = span.iter().filter_map(|(_, r)| r.map(|(_, e)| e)).max();
    if let (Some(start), Some(end)) = (start, end) {
        text.push_str(&format!(
            " — full detail preserved in session memory (turns {start}-{end}); \
             use recall_session to retrieve"
        ));
    }

    out.push(ChatMessage::system(text));
    span.clear();
}

#[cfg(test)]
#[path = "transcript_tests.rs"]
mod tests;