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 the project's `settings.json` `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/// `settings.json` precedence chain `crate::mode::resolve_mode` establishes,
129/// 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 the resolved `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 the project's `settings.json` `code_harness.cadence_turns` /
173/// `code_harness.max_overhead_fraction_pct` keys.
174///
175/// Why: this reader and `crate::mode::read_settings_json_mode` read the SAME
176/// physical file. #5426 moved that file to `.trusty-code/settings.json` and left
177/// this one joining `.claude/settings.json`, so a `.trusty-code`-only project
178/// kept its mode override and silently lost its cadence override (code-critic
179/// HIGH, PR #6980). Both now resolve through one function.
180/// What: the file comes from [`crate::paths::settings_file`] — `.trusty-code/`
181/// then `.claude/` then `.open-mpm/`. `None` when no file resolves or it has no
182/// `code_harness` object; otherwise `Some(CadenceConfig)` starting from
183/// [`CadenceConfig::default`] with either field overridden by whichever of the
184/// two keys is present and a valid non-negative integer (a present but
185/// wrong-typed key is skipped for that field, not an error for the whole read).
186/// A file that resolved but then fails to read or parse warns with the path
187/// tried before degrading, matching `mode`'s fail-open convention.
188/// Test: `cadence::tests::resolve_cadence_config_settings_json_override`,
189/// `cadence::tests::read_settings_json_cadence_missing_file_is_not_an_error`,
190/// `cadence::tests::trusty_code_settings_json_sets_cadence_without_a_claude_dir`.
191fn read_settings_json_cadence(project_root: &Path) -> Option<CadenceConfig> {
192    // #5426: resolved, not joined — the same resolver `crate::mode` uses.
193    let resolved = crate::paths::settings_file(project_root);
194    if resolved.source == crate::paths::ConfigSource::Default {
195        return None;
196    }
197    let path = resolved.path;
198    let raw = match std::fs::read_to_string(&path) {
199        Ok(raw) => raw,
200        Err(e) => {
201            tracing::warn!(
202                path = %path.display(),
203                error = %e,
204                "project settings.json resolved but could not be read; \
205                 keeping the default cadence configuration"
206            );
207            return None;
208        }
209    };
210    let value: serde_json::Value = match serde_json::from_str(&raw) {
211        Ok(value) => value,
212        Err(e) => {
213            tracing::warn!(
214                path = %path.display(),
215                error = %e,
216                "project settings.json is not valid JSON; \
217                 keeping the default cadence configuration"
218            );
219            return None;
220        }
221    };
222    let harness = value.get("code_harness")?;
223
224    let mut cfg = CadenceConfig::default();
225    if let Some(turns) = harness
226        .get("cadence_turns")
227        .and_then(serde_json::Value::as_u64)
228    {
229        cfg.cadence_turns = turns as usize;
230    }
231    if let Some(pct) = harness
232        .get("max_overhead_fraction_pct")
233        .and_then(serde_json::Value::as_u64)
234    {
235        cfg.max_overhead_fraction_pct = pct as usize;
236    }
237    Some(cfg)
238}
239
240/// Outcome of one [`maybe_cadence_compress`] call, for observability/tests.
241///
242/// Why: `agent_loop::AgentLoop`'s turn boundary and unit tests both need to
243/// know what happened without re-deriving it from `Transcript`'s counters.
244/// What: `fired` — whether the scheduled cadence compaction ran THIS turn;
245/// `rounds` — total compaction rounds this call performed (the cadence round,
246/// if any, plus every continuous-enforcement round); `within_budget` —
247/// whether the transcript ended at/under the overhead cap (`false` only on
248/// the documented floor: the active zone alone, after full compaction,
249/// still exceeds the cap); `overhead_tokens` — the REAL
250/// [`estimate_total_tokens`] measurement of the model-facing transcript as
251/// [`enforce_budget`] last observed it (i.e. after enforcement settled), which
252/// is what makes a working-context indicator renderable from a measured value
253/// rather than a projection.
254/// Test: `cadence::tests::*`.
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub struct CadenceOutcome {
257    pub fired: bool,
258    pub rounds: usize,
259    pub within_budget: bool,
260    /// Measured model-facing transcript size, in estimated tokens, after this
261    /// call's enforcement settled.
262    pub overhead_tokens: usize,
263}
264
265impl CadenceOutcome {
266    /// Percentage of `context_window` consumed by session overhead.
267    ///
268    /// Why: the Infinite Sessions guarantee is stated as a ratio ("overhead
269    /// <= 40%, working context >= 60%"), but this outcome measures ABSOLUTE
270    /// tokens — a consumer rendering a budget meter needs the ratio, and
271    /// deriving it in one place keeps every consumer's arithmetic identical.
272    /// What: `overhead_tokens / context_window * 100`, saturating at 100 and
273    /// returning 100 for a zero `context_window` (treat an unknown window as
274    /// fully consumed — the conservative reading, and never a divide-by-zero).
275    /// Test: `cadence::tests::overhead_pct_is_ratio_of_window`,
276    /// `cadence::tests::pct_helpers_saturate_and_never_divide_by_zero`.
277    pub fn overhead_pct(&self, context_window: usize) -> u8 {
278        if context_window == 0 {
279            return 100;
280        }
281        let pct = self.overhead_tokens.saturating_mul(100) / context_window;
282        pct.min(100) as u8
283    }
284
285    /// Percentage of `context_window` still available for real work — the
286    /// figure the Infinite Sessions guarantee requires to stay `>= 60`.
287    ///
288    /// Why: the headline number a UI budget indicator renders.
289    /// What: `100 - overhead_pct(context_window)`, so the two always sum to
290    /// exactly 100.
291    /// Test: `cadence::tests::working_and_overhead_pct_sum_to_100`.
292    pub fn working_context_pct(&self, context_window: usize) -> u8 {
293        100 - self.overhead_pct(context_window)
294    }
295}
296
297/// The turn-boundary entry point: tick the cadence counter, compress on
298/// schedule, then continuously enforce the overhead budget every turn.
299///
300/// Why: This is what makes the epic's "ZERO threshold-compaction events in
301/// steady state" metric achievable — see the module doc's overview. Called
302/// BEFORE `Transcript::maybe_compact` at the same turn boundary
303/// (`AgentLoop::run_inner`), so the threshold compactor only ever sees a
304/// transcript this function already kept under budget.
305/// What: `transcript.tick_cadence_turn(cfg.cadence_turns)` advances the
306/// counter and reports whether this is a scheduled fire; if so,
307/// `transcript.compact_span_tagged` unconditionally compacts everything
308/// older than `keep_last_messages` (the active zone — reused from the
309/// caller's own `CompactionConfig::keep_last_messages`, not a new knob).
310/// Regardless of whether cadence fired this turn, [`enforce_budget`] then
311/// runs: it re-checks `estimate_total_tokens(transcript.to_messages())`
312/// against `cfg.overhead_cap_tokens(context_window)` and, if still over,
313/// keeps shrinking the active zone and re-compacting (still via the SAME
314/// group-safe `compact_span_tagged`) until under budget or the active zone
315/// hits zero with nothing left to compact — at which point it warns (via
316/// `tracing::warn!`) and returns rather than looping forever.
317/// Test: `cadence::tests::fires_every_n_turns`,
318/// `cadence::tests::stays_under_budget_every_turn`,
319/// `cadence::tests::single_oversized_turn_still_ends_under_budget`,
320/// `cadence::tests::floor_exceeded_warns_not_panics`.
321pub fn maybe_cadence_compress(
322    transcript: &mut Transcript,
323    cfg: &CadenceConfig,
324    keep_last_messages: usize,
325    context_window: usize,
326) -> CadenceOutcome {
327    let fired = transcript.tick_cadence_turn(cfg.cadence_turns);
328    let mut rounds = 0;
329    if fired {
330        let range = transcript.begin_cadence_range();
331        if transcript.compact_span_tagged(keep_last_messages, range) {
332            transcript.advance_cadence_fire_marker();
333        }
334        rounds += 1;
335    }
336
337    let cap = cfg.overhead_cap_tokens(context_window);
338    let (enforcement_rounds, within_budget, overhead_tokens) =
339        enforce_budget(transcript, cap, keep_last_messages);
340
341    CadenceOutcome {
342        fired,
343        rounds: rounds + enforcement_rounds,
344        within_budget,
345        overhead_tokens,
346    }
347}
348
349/// Continuously compact until `transcript`'s model-facing view is at/under
350/// `cap_tokens`, or nothing compactable remains.
351///
352/// Why: A single pathological turn (e.g. a 60K-token `write_file` argument)
353/// can blow the overhead cap even immediately after a cadence fire, since
354/// cadence only ever protects the last `active_zone` messages, never
355/// compacts them. Requirement 3 of #2346 ("continuous budget enforcement")
356/// is this loop: shrink the protected active zone one message at a time and
357/// re-compact (group-safely) until the budget is satisfied.
358/// What: Starting at `keep_last = active_zone`, loop: measure the model-facing
359/// transcript once per iteration; if already under `cap_tokens`, return
360/// `(rounds, true, measured)`. Otherwise compact tagged with the transcript's
361/// current cadence range, then either shrink `keep_last` by one (more rounds
362/// to go) or, once `keep_last == 0`, either loop back (that round newly
363/// compacted something — recheck the budget) or return `(rounds, false,
364/// measured)` with a `tracing::warn!` (nothing left to compact and still over
365/// budget — the documented floor: pinned/system/user content alone exceeds the
366/// cap; the measurement is still accurate there precisely BECAUSE that round
367/// compacted nothing). Bounded by `active_zone + 2` iterations — never an
368/// unbounded loop.
369///
370/// The third return element is the token measurement this loop already had to
371/// compute for its own budget check — returning it rather than dropping it is
372/// what lets a caller report a REAL working-context figure without paying for a
373/// second `estimate_total_tokens` pass over the whole transcript.
374/// Test: `cadence::tests::stays_under_budget_every_turn`,
375/// `cadence::tests::single_oversized_turn_still_ends_under_budget`,
376/// `cadence::tests::floor_exceeded_warns_not_panics`,
377/// `cadence::tests::outcome_reports_measured_overhead_tokens`.
378fn enforce_budget(
379    transcript: &mut Transcript,
380    cap_tokens: usize,
381    active_zone: usize,
382) -> (usize, bool, usize) {
383    let mut keep_last = active_zone;
384    let mut rounds = 0;
385
386    loop {
387        let measured = estimate_total_tokens(&transcript.to_messages());
388        if measured <= cap_tokens {
389            return (rounds, true, measured);
390        }
391
392        let range = transcript.begin_cadence_range();
393        let compacted = transcript.compact_span_tagged(keep_last, range);
394        rounds += 1;
395        if compacted {
396            transcript.advance_cadence_fire_marker();
397        }
398
399        if keep_last == 0 {
400            if !compacted {
401                tracing::warn!(
402                    cap_tokens,
403                    measured,
404                    "cadence: overhead cap still exceeded after compacting every eligible \
405                     entry — the active zone (pinned + system/user turns) alone exceeds \
406                     budget; this is a documented floor, not an error"
407                );
408                return (rounds, false, measured);
409            }
410            continue;
411        }
412        keep_last -= 1;
413    }
414}
415
416#[cfg(test)]
417#[path = "cadence_tests.rs"]
418mod tests;