Skip to main content

trusty_code/agent_loop/
cadence.rs

1//! Cadence compressor (#2346, epic #2343 "Infinite Sessions" ticket 3):
2//! continuous every-N-turn history compression that keeps the model-facing
3//! transcript under a fixed fraction of the model's context window at ALL
4//! times, so [`super::compaction`]'s threshold compactor becomes a backstop
5//! that should never fire in steady state, rather than the primary
6//! token-efficiency mechanism.
7//!
8//! Why: The pre-#2346 design only compacts REACTIVELY, once
9//! `estimate_total_tokens` crosses ~75% of the window
10//! (`CompactionConfig::for_context_window`) — by the time that fires, the
11//! transcript has already grown close to the limit, and every fire triggers
12//! a "re-anchor thrash" (the last-user-message replay). The epic's hard
13//! constraint is working context >= 60% of the window AT ALL TIMES and ZERO
14//! threshold-compaction events in a steady long-running session. A
15//! proactive, turn-count-driven cadence — compress every `cadence_turns`
16//! turns, THEN continuously enforce the budget every turn regardless of
17//! cadence — achieves both: routine cadence firing keeps growth bounded in
18//! the common case, and the continuous-enforcement loop is the safety net
19//! for a single pathological oversized turn that would otherwise blow the
20//! budget between cadence fires.
21//! What: [`CadenceConfig`] (`cadence_turns` + `max_overhead_fraction_pct`,
22//! resolved from `.claude/settings.json`'s `code_harness.*` keys and two
23//! escape-hatch env vars via [`resolve_cadence_config`], mirroring
24//! `crate::mode`'s precedence convention); [`maybe_cadence_compress`] (the
25//! turn-boundary entry point `agent_loop::AgentLoop` calls) which (1) ticks
26//! the transcript's turn counter and, on a cadence-fire turn, unconditionally
27//! compacts the span older than the active zone via
28//! `Transcript::compact_span_tagged` (#2278 group-safety and #2070 pinned/
29//! system/user exemptions reused verbatim, never reimplemented here), then
30//! (2) ALWAYS runs [`enforce_budget`] — a small, hard-bounded loop that keeps
31//! shrinking the active zone and re-compacting until
32//! `estimate_total_tokens(to_messages())` is back under the
33//! `max_overhead_fraction_pct` cap or nothing compactable remains (logging a
34//! warning, never panicking or looping forever, on that documented floor).
35//! Summarisation itself stays the existing deterministic
36//! `super::compaction::summarize_span` — see this module's doc note on the
37//! LLM-summary follow-up below.
38//!
39//! **LLM vs. deterministic summary (design decision, ticket-sanctioned):**
40//! the epic's prose says "LLM auto-compresses history", but wiring a
41//! synchronous `LlmClientTrait::chat` call into this turn boundary would
42//! make cadence's own summarisation step a new network-dependent failure
43//! mode for a mechanism whose entire point is to keep the loop robust and
44//! fast — and every turn already pays for one real model round-trip. Per
45//! the ticket's own explicit guidance ("do NOT block the epic on perfect
46//! summarization"), this ships the deterministic `summarize_span` fallback
47//! now, with the summary text pointing at the durable per-turn memory record
48//! (#2345's `chat_turn_append`/`memory_remember` dual-write) via a
49//! "turns N-M — use recall_session" pointer (see [`super::transcript::flush_span`]).
50//! An LLM-generated abstractive summary (bounded to ~500 tokens, prompted to
51//! preserve decisions/open-questions/artifact names) is the natural
52//! follow-up once `agent_loop::AgentLoop` exposes a clean async hook at this
53//! boundary — tracked for #2349/#2350 rather than blocking this ticket.
54//! Test: `cadence::tests::*`.
55
56use std::path::Path;
57
58use super::Transcript;
59use super::compaction::estimate_total_tokens;
60
61/// Turn-count cadence at which history compression fires by default (epic
62/// #2343: "N=8 default, config knob").
63pub const DEFAULT_CADENCE_TURNS: usize = 8;
64
65/// Fraction (as a whole-number percentage) of the model's context window the
66/// working transcript may occupy before continuous enforcement kicks in
67/// (epic #2343: "max_overhead_fraction=0.40 knob").
68pub const DEFAULT_MAX_OVERHEAD_FRACTION_PCT: usize = 40;
69
70/// Escape-hatch env var overriding [`CadenceConfig::cadence_turns`] for one
71/// process, mirroring `crate::mode::MODE_ENV_VAR`'s precedent.
72pub const CADENCE_TURNS_ENV_VAR: &str = "TCODE_CADENCE_TURNS";
73
74/// Escape-hatch env var overriding
75/// [`CadenceConfig::max_overhead_fraction_pct`] for one process.
76pub const CADENCE_OVERHEAD_FRACTION_ENV_VAR: &str = "TCODE_CADENCE_MAX_OVERHEAD_FRACTION_PCT";
77
78/// Tuning knobs for the #2346 cadence compressor.
79///
80/// Why: A caller needs to control both "how often" (turn-count cadence) and
81/// "how much of the window is overhead" (the budget the cadence + continuous
82/// enforcement together must respect) — bundling them mirrors
83/// `CompactionConfig`'s own two-knob shape.
84/// What: `cadence_turns` is the turn-count period `maybe_cadence_compress`
85/// fires the unconditional compaction pass on (0 disables cadence firing
86/// entirely, though continuous enforcement still applies — see
87/// `Transcript::tick_cadence_turn`'s docs); `max_overhead_fraction_pct` is
88/// the whole-number percentage of the model's real context window
89/// [`CadenceConfig::overhead_cap_tokens`] resolves the absolute cap from.
90/// Test: `cadence::tests::default_is_sane`.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub struct CadenceConfig {
93    /// Compress every this-many completed turns.
94    pub cadence_turns: usize,
95    /// Whole-number percentage of the context window the working transcript
96    /// may occupy.
97    pub max_overhead_fraction_pct: usize,
98}
99
100impl Default for CadenceConfig {
101    /// The epic's stated defaults: `cadence_turns: 8`,
102    /// `max_overhead_fraction_pct: 40`.
103    /// Test: `cadence::tests::default_is_sane`.
104    fn default() -> Self {
105        Self {
106            cadence_turns: DEFAULT_CADENCE_TURNS,
107            max_overhead_fraction_pct: DEFAULT_MAX_OVERHEAD_FRACTION_PCT,
108        }
109    }
110}
111
112impl CadenceConfig {
113    /// Resolve the absolute overhead-token cap for a given context window.
114    ///
115    /// Why: The budget arithmetic (epic #2343: on a 200K window, 40% ->
116    /// 80K overhead cap, 120K working floor) needs the model's REAL context
117    /// window — a property of the model, resolved separately via
118    /// `crate::provider::resolve_context_window` — combined with this
119    /// config's fraction.
120    /// What: `context_window * max_overhead_fraction_pct / 100`.
121    /// Test: `cadence::tests::overhead_cap_matches_epic_arithmetic`.
122    pub fn overhead_cap_tokens(&self, context_window: usize) -> usize {
123        context_window * self.max_overhead_fraction_pct / 100
124    }
125}
126
127/// Resolve a project's [`CadenceConfig`] via the `code_harness.*`
128/// `.claude/settings.json` precedence chain `crate::mode::resolve_mode`
129/// establishes, adapted to this config's two knobs.
130///
131/// Why: An operator needs to tune cadence per-project (`settings.json`) or
132/// per-process (the escape-hatch env vars) without a code change, matching
133/// every other `code_harness.*` knob in this crate. Unlike `resolve_mode`,
134/// there is no `task.run`-request tier — this ticket does not add a
135/// per-call cadence override to the wire protocol, so the chain is simply
136/// env var (highest) > `settings.json` > built-in default.
137/// What: Starts from `.claude/settings.json`'s `code_harness.cadence_turns`/
138/// `code_harness.max_overhead_fraction_pct` (via
139/// [`read_settings_json_cadence`], falling back to [`CadenceConfig::default`]
140/// when the file/keys are absent or malformed — never an error, matching
141/// `crate::mode::read_settings_json_mode`'s graceful-degrade convention),
142/// then overrides either field from [`CADENCE_TURNS_ENV_VAR`]/
143/// [`CADENCE_OVERHEAD_FRACTION_ENV_VAR`] when set to a valid `usize` (an
144/// unparseable value is logged via `tracing::warn!` and the prior tier's
145/// value is kept, rather than erroring the whole run).
146/// Test: `cadence::tests::resolve_cadence_config_settings_json_override`,
147/// `cadence::tests::resolve_cadence_config_env_wins_over_settings_json`.
148pub fn resolve_cadence_config(project_root: &Path) -> CadenceConfig {
149    let mut cfg = read_settings_json_cadence(project_root).unwrap_or_default();
150
151    if let Ok(raw) = std::env::var(CADENCE_TURNS_ENV_VAR) {
152        match raw.trim().parse::<usize>() {
153            Ok(v) => cfg.cadence_turns = v,
154            Err(e) => tracing::warn!(
155                "{CADENCE_TURNS_ENV_VAR}={raw:?} is not a valid usize ({e}); keeping {}",
156                cfg.cadence_turns
157            ),
158        }
159    }
160    if let Ok(raw) = std::env::var(CADENCE_OVERHEAD_FRACTION_ENV_VAR) {
161        match raw.trim().parse::<usize>() {
162            Ok(v) => cfg.max_overhead_fraction_pct = v,
163            Err(e) => tracing::warn!(
164                "{CADENCE_OVERHEAD_FRACTION_ENV_VAR}={raw:?} is not a valid usize ({e}); keeping {}",
165                cfg.max_overhead_fraction_pct
166            ),
167        }
168    }
169    cfg
170}
171
172/// Read `<project_root>/.claude/settings.json`'s `code_harness.cadence_turns`
173/// / `code_harness.max_overhead_fraction_pct` keys.
174///
175/// Why: mirrors `crate::mode::read_settings_json_mode`'s graceful-degrade
176/// convention for the same project-scoped config file.
177/// What: `None` when the file is missing, unreadable, not valid JSON, or has
178/// no `code_harness` object at all; otherwise `Some(CadenceConfig)` starting
179/// from [`CadenceConfig::default`] with either field overridden by whichever
180/// of the two keys is present and a valid non-negative integer (a present
181/// but wrong-typed key is silently skipped for that field, not an error for
182/// the whole read).
183/// Test: `cadence::tests::resolve_cadence_config_settings_json_override`,
184/// `cadence::tests::read_settings_json_cadence_missing_file_is_not_an_error`.
185fn read_settings_json_cadence(project_root: &Path) -> Option<CadenceConfig> {
186    let path = project_root.join(".claude").join("settings.json");
187    let raw = std::fs::read_to_string(path).ok()?;
188    let value: serde_json::Value = serde_json::from_str(&raw).ok()?;
189    let harness = value.get("code_harness")?;
190
191    let mut cfg = CadenceConfig::default();
192    if let Some(turns) = harness
193        .get("cadence_turns")
194        .and_then(serde_json::Value::as_u64)
195    {
196        cfg.cadence_turns = turns as usize;
197    }
198    if let Some(pct) = harness
199        .get("max_overhead_fraction_pct")
200        .and_then(serde_json::Value::as_u64)
201    {
202        cfg.max_overhead_fraction_pct = pct as usize;
203    }
204    Some(cfg)
205}
206
207/// Outcome of one [`maybe_cadence_compress`] call, for observability/tests.
208///
209/// Why: `agent_loop::AgentLoop`'s turn boundary and unit tests both need to
210/// know what happened without re-deriving it from `Transcript`'s counters.
211/// What: `fired` — whether the scheduled cadence compaction ran THIS turn;
212/// `rounds` — total compaction rounds this call performed (the cadence round,
213/// if any, plus every continuous-enforcement round); `within_budget` —
214/// whether the transcript ended at/under the overhead cap (`false` only on
215/// the documented floor: the active zone alone, after full compaction,
216/// still exceeds the cap).
217/// Test: `cadence::tests::*`.
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub struct CadenceOutcome {
220    pub fired: bool,
221    pub rounds: usize,
222    pub within_budget: bool,
223}
224
225/// The turn-boundary entry point: tick the cadence counter, compress on
226/// schedule, then continuously enforce the overhead budget every turn.
227///
228/// Why: This is what makes the epic's "ZERO threshold-compaction events in
229/// steady state" metric achievable — see the module doc's overview. Called
230/// BEFORE `Transcript::maybe_compact` at the same turn boundary
231/// (`AgentLoop::run_inner`), so the threshold compactor only ever sees a
232/// transcript this function already kept under budget.
233/// What: `transcript.tick_cadence_turn(cfg.cadence_turns)` advances the
234/// counter and reports whether this is a scheduled fire; if so,
235/// `transcript.compact_span_tagged` unconditionally compacts everything
236/// older than `keep_last_messages` (the active zone — reused from the
237/// caller's own `CompactionConfig::keep_last_messages`, not a new knob).
238/// Regardless of whether cadence fired this turn, [`enforce_budget`] then
239/// runs: it re-checks `estimate_total_tokens(transcript.to_messages())`
240/// against `cfg.overhead_cap_tokens(context_window)` and, if still over,
241/// keeps shrinking the active zone and re-compacting (still via the SAME
242/// group-safe `compact_span_tagged`) until under budget or the active zone
243/// hits zero with nothing left to compact — at which point it warns (via
244/// `tracing::warn!`) and returns rather than looping forever.
245/// Test: `cadence::tests::fires_every_n_turns`,
246/// `cadence::tests::stays_under_budget_every_turn`,
247/// `cadence::tests::single_oversized_turn_still_ends_under_budget`,
248/// `cadence::tests::floor_exceeded_warns_not_panics`.
249pub fn maybe_cadence_compress(
250    transcript: &mut Transcript,
251    cfg: &CadenceConfig,
252    keep_last_messages: usize,
253    context_window: usize,
254) -> CadenceOutcome {
255    let fired = transcript.tick_cadence_turn(cfg.cadence_turns);
256    let mut rounds = 0;
257    if fired {
258        let range = transcript.begin_cadence_range();
259        if transcript.compact_span_tagged(keep_last_messages, range) {
260            transcript.advance_cadence_fire_marker();
261        }
262        rounds += 1;
263    }
264
265    let cap = cfg.overhead_cap_tokens(context_window);
266    let (enforcement_rounds, within_budget) = enforce_budget(transcript, cap, keep_last_messages);
267
268    CadenceOutcome {
269        fired,
270        rounds: rounds + enforcement_rounds,
271        within_budget,
272    }
273}
274
275/// Continuously compact until `transcript`'s model-facing view is at/under
276/// `cap_tokens`, or nothing compactable remains.
277///
278/// Why: A single pathological turn (e.g. a 60K-token `write_file` argument)
279/// can blow the overhead cap even immediately after a cadence fire, since
280/// cadence only ever protects the last `active_zone` messages, never
281/// compacts them. Requirement 3 of #2346 ("continuous budget enforcement")
282/// is this loop: shrink the protected active zone one message at a time and
283/// re-compact (group-safely) until the budget is satisfied.
284/// What: Starting at `keep_last = active_zone`, loop: if already under
285/// `cap_tokens`, return `(rounds, true)`. Otherwise compact tagged with the
286/// transcript's current cadence range, then either shrink `keep_last` by one
287/// (more rounds to go) or, once `keep_last == 0`, either loop back (that
288/// round newly compacted something — recheck the budget) or return
289/// `(rounds, false)` with a `tracing::warn!` (nothing left to compact and
290/// still over budget — the documented floor: pinned/system/user content
291/// alone exceeds the cap). Bounded by `active_zone + 2` iterations — never an
292/// unbounded loop.
293/// Test: `cadence::tests::stays_under_budget_every_turn`,
294/// `cadence::tests::single_oversized_turn_still_ends_under_budget`,
295/// `cadence::tests::floor_exceeded_warns_not_panics`.
296fn enforce_budget(
297    transcript: &mut Transcript,
298    cap_tokens: usize,
299    active_zone: usize,
300) -> (usize, bool) {
301    let mut keep_last = active_zone;
302    let mut rounds = 0;
303
304    loop {
305        if estimate_total_tokens(&transcript.to_messages()) <= cap_tokens {
306            return (rounds, true);
307        }
308
309        let range = transcript.begin_cadence_range();
310        let compacted = transcript.compact_span_tagged(keep_last, range);
311        rounds += 1;
312        if compacted {
313            transcript.advance_cadence_fire_marker();
314        }
315
316        if keep_last == 0 {
317            if !compacted {
318                tracing::warn!(
319                    cap_tokens,
320                    "cadence: overhead cap still exceeded after compacting every eligible \
321                     entry — the active zone (pinned + system/user turns) alone exceeds \
322                     budget; this is a documented floor, not an error"
323                );
324                return (rounds, false);
325            }
326            continue;
327        }
328        keep_last -= 1;
329    }
330}
331
332#[cfg(test)]
333#[path = "cadence_tests.rs"]
334mod tests;