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 `InferenceAdapter::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); `overhead_tokens` — the REAL
217/// [`estimate_total_tokens`] measurement of the model-facing transcript as
218/// [`enforce_budget`] last observed it (i.e. after enforcement settled), which
219/// is what makes a working-context indicator renderable from a measured value
220/// rather than a projection.
221/// Test: `cadence::tests::*`.
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223pub struct CadenceOutcome {
224 pub fired: bool,
225 pub rounds: usize,
226 pub within_budget: bool,
227 /// Measured model-facing transcript size, in estimated tokens, after this
228 /// call's enforcement settled.
229 pub overhead_tokens: usize,
230}
231
232impl CadenceOutcome {
233 /// Percentage of `context_window` consumed by session overhead.
234 ///
235 /// Why: the Infinite Sessions guarantee is stated as a ratio ("overhead
236 /// <= 40%, working context >= 60%"), but this outcome measures ABSOLUTE
237 /// tokens — a consumer rendering a budget meter needs the ratio, and
238 /// deriving it in one place keeps every consumer's arithmetic identical.
239 /// What: `overhead_tokens / context_window * 100`, saturating at 100 and
240 /// returning 100 for a zero `context_window` (treat an unknown window as
241 /// fully consumed — the conservative reading, and never a divide-by-zero).
242 /// Test: `cadence::tests::overhead_pct_is_ratio_of_window`,
243 /// `cadence::tests::pct_helpers_saturate_and_never_divide_by_zero`.
244 pub fn overhead_pct(&self, context_window: usize) -> u8 {
245 if context_window == 0 {
246 return 100;
247 }
248 let pct = self.overhead_tokens.saturating_mul(100) / context_window;
249 pct.min(100) as u8
250 }
251
252 /// Percentage of `context_window` still available for real work — the
253 /// figure the Infinite Sessions guarantee requires to stay `>= 60`.
254 ///
255 /// Why: the headline number a UI budget indicator renders.
256 /// What: `100 - overhead_pct(context_window)`, so the two always sum to
257 /// exactly 100.
258 /// Test: `cadence::tests::working_and_overhead_pct_sum_to_100`.
259 pub fn working_context_pct(&self, context_window: usize) -> u8 {
260 100 - self.overhead_pct(context_window)
261 }
262}
263
264/// The turn-boundary entry point: tick the cadence counter, compress on
265/// schedule, then continuously enforce the overhead budget every turn.
266///
267/// Why: This is what makes the epic's "ZERO threshold-compaction events in
268/// steady state" metric achievable — see the module doc's overview. Called
269/// BEFORE `Transcript::maybe_compact` at the same turn boundary
270/// (`AgentLoop::run_inner`), so the threshold compactor only ever sees a
271/// transcript this function already kept under budget.
272/// What: `transcript.tick_cadence_turn(cfg.cadence_turns)` advances the
273/// counter and reports whether this is a scheduled fire; if so,
274/// `transcript.compact_span_tagged` unconditionally compacts everything
275/// older than `keep_last_messages` (the active zone — reused from the
276/// caller's own `CompactionConfig::keep_last_messages`, not a new knob).
277/// Regardless of whether cadence fired this turn, [`enforce_budget`] then
278/// runs: it re-checks `estimate_total_tokens(transcript.to_messages())`
279/// against `cfg.overhead_cap_tokens(context_window)` and, if still over,
280/// keeps shrinking the active zone and re-compacting (still via the SAME
281/// group-safe `compact_span_tagged`) until under budget or the active zone
282/// hits zero with nothing left to compact — at which point it warns (via
283/// `tracing::warn!`) and returns rather than looping forever.
284/// Test: `cadence::tests::fires_every_n_turns`,
285/// `cadence::tests::stays_under_budget_every_turn`,
286/// `cadence::tests::single_oversized_turn_still_ends_under_budget`,
287/// `cadence::tests::floor_exceeded_warns_not_panics`.
288pub fn maybe_cadence_compress(
289 transcript: &mut Transcript,
290 cfg: &CadenceConfig,
291 keep_last_messages: usize,
292 context_window: usize,
293) -> CadenceOutcome {
294 let fired = transcript.tick_cadence_turn(cfg.cadence_turns);
295 let mut rounds = 0;
296 if fired {
297 let range = transcript.begin_cadence_range();
298 if transcript.compact_span_tagged(keep_last_messages, range) {
299 transcript.advance_cadence_fire_marker();
300 }
301 rounds += 1;
302 }
303
304 let cap = cfg.overhead_cap_tokens(context_window);
305 let (enforcement_rounds, within_budget, overhead_tokens) =
306 enforce_budget(transcript, cap, keep_last_messages);
307
308 CadenceOutcome {
309 fired,
310 rounds: rounds + enforcement_rounds,
311 within_budget,
312 overhead_tokens,
313 }
314}
315
316/// Continuously compact until `transcript`'s model-facing view is at/under
317/// `cap_tokens`, or nothing compactable remains.
318///
319/// Why: A single pathological turn (e.g. a 60K-token `write_file` argument)
320/// can blow the overhead cap even immediately after a cadence fire, since
321/// cadence only ever protects the last `active_zone` messages, never
322/// compacts them. Requirement 3 of #2346 ("continuous budget enforcement")
323/// is this loop: shrink the protected active zone one message at a time and
324/// re-compact (group-safely) until the budget is satisfied.
325/// What: Starting at `keep_last = active_zone`, loop: measure the model-facing
326/// transcript once per iteration; if already under `cap_tokens`, return
327/// `(rounds, true, measured)`. Otherwise compact tagged with the transcript's
328/// current cadence range, then either shrink `keep_last` by one (more rounds
329/// to go) or, once `keep_last == 0`, either loop back (that round newly
330/// compacted something — recheck the budget) or return `(rounds, false,
331/// measured)` with a `tracing::warn!` (nothing left to compact and still over
332/// budget — the documented floor: pinned/system/user content alone exceeds the
333/// cap; the measurement is still accurate there precisely BECAUSE that round
334/// compacted nothing). Bounded by `active_zone + 2` iterations — never an
335/// unbounded loop.
336///
337/// The third return element is the token measurement this loop already had to
338/// compute for its own budget check — returning it rather than dropping it is
339/// what lets a caller report a REAL working-context figure without paying for a
340/// second `estimate_total_tokens` pass over the whole transcript.
341/// Test: `cadence::tests::stays_under_budget_every_turn`,
342/// `cadence::tests::single_oversized_turn_still_ends_under_budget`,
343/// `cadence::tests::floor_exceeded_warns_not_panics`,
344/// `cadence::tests::outcome_reports_measured_overhead_tokens`.
345fn enforce_budget(
346 transcript: &mut Transcript,
347 cap_tokens: usize,
348 active_zone: usize,
349) -> (usize, bool, usize) {
350 let mut keep_last = active_zone;
351 let mut rounds = 0;
352
353 loop {
354 let measured = estimate_total_tokens(&transcript.to_messages());
355 if measured <= cap_tokens {
356 return (rounds, true, measured);
357 }
358
359 let range = transcript.begin_cadence_range();
360 let compacted = transcript.compact_span_tagged(keep_last, range);
361 rounds += 1;
362 if compacted {
363 transcript.advance_cadence_fire_marker();
364 }
365
366 if keep_last == 0 {
367 if !compacted {
368 tracing::warn!(
369 cap_tokens,
370 measured,
371 "cadence: overhead cap still exceeded after compacting every eligible \
372 entry — the active zone (pinned + system/user turns) alone exceeds \
373 budget; this is a documented floor, not an error"
374 );
375 return (rounds, false, measured);
376 }
377 continue;
378 }
379 keep_last -= 1;
380 }
381}
382
383#[cfg(test)]
384#[path = "cadence_tests.rs"]
385mod tests;