trusty-code 0.8.2

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! Cadence compressor (#2346, epic #2343 "Infinite Sessions" ticket 3):
//! continuous every-N-turn history compression that keeps the model-facing
//! transcript under a fixed fraction of the model's context window at ALL
//! times, so [`super::compaction`]'s threshold compactor becomes a backstop
//! that should never fire in steady state, rather than the primary
//! token-efficiency mechanism.
//!
//! Why: The pre-#2346 design only compacts REACTIVELY, once
//! `estimate_total_tokens` crosses ~75% of the window
//! (`CompactionConfig::for_context_window`) — by the time that fires, the
//! transcript has already grown close to the limit, and every fire triggers
//! a "re-anchor thrash" (the last-user-message replay). The epic's hard
//! constraint is working context >= 60% of the window AT ALL TIMES and ZERO
//! threshold-compaction events in a steady long-running session. A
//! proactive, turn-count-driven cadence — compress every `cadence_turns`
//! turns, THEN continuously enforce the budget every turn regardless of
//! cadence — achieves both: routine cadence firing keeps growth bounded in
//! the common case, and the continuous-enforcement loop is the safety net
//! for a single pathological oversized turn that would otherwise blow the
//! budget between cadence fires.
//! What: [`CadenceConfig`] (`cadence_turns` + `max_overhead_fraction_pct`,
//! resolved from the project's `settings.json` `code_harness.*` keys and two
//! escape-hatch env vars via [`resolve_cadence_config`], mirroring
//! `crate::mode`'s precedence convention); [`maybe_cadence_compress`] (the
//! turn-boundary entry point `agent_loop::AgentLoop` calls) which (1) ticks
//! the transcript's turn counter and, on a cadence-fire turn, unconditionally
//! compacts the span older than the active zone via
//! `Transcript::compact_span_tagged` (#2278 group-safety and #2070 pinned/
//! system/user exemptions reused verbatim, never reimplemented here), then
//! (2) ALWAYS runs [`enforce_budget`] — a small, hard-bounded loop that keeps
//! shrinking the active zone and re-compacting until
//! `estimate_total_tokens(to_messages())` is back under the
//! `max_overhead_fraction_pct` cap or nothing compactable remains (logging a
//! warning, never panicking or looping forever, on that documented floor).
//! Summarisation itself stays the existing deterministic
//! `super::compaction::summarize_span` — see this module's doc note on the
//! LLM-summary follow-up below.
//!
//! **LLM vs. deterministic summary (design decision, ticket-sanctioned):**
//! the epic's prose says "LLM auto-compresses history", but wiring a
//! synchronous `InferenceAdapter::chat` call into this turn boundary would
//! make cadence's own summarisation step a new network-dependent failure
//! mode for a mechanism whose entire point is to keep the loop robust and
//! fast — and every turn already pays for one real model round-trip. Per
//! the ticket's own explicit guidance ("do NOT block the epic on perfect
//! summarization"), this ships the deterministic `summarize_span` fallback
//! now, with the summary text pointing at the durable per-turn memory record
//! (#2345's `chat_turn_append`/`memory_remember` dual-write) via a
//! "turns N-M — use recall_session" pointer (see [`super::transcript::flush_span`]).
//! An LLM-generated abstractive summary (bounded to ~500 tokens, prompted to
//! preserve decisions/open-questions/artifact names) is the natural
//! follow-up once `agent_loop::AgentLoop` exposes a clean async hook at this
//! boundary — tracked for #2349/#2350 rather than blocking this ticket.
//! Test: `cadence::tests::*`.

use std::path::Path;

use super::Transcript;
use super::compaction::estimate_total_tokens;

/// Turn-count cadence at which history compression fires by default (epic
/// #2343: "N=8 default, config knob").
pub const DEFAULT_CADENCE_TURNS: usize = 8;

/// Fraction (as a whole-number percentage) of the model's context window the
/// working transcript may occupy before continuous enforcement kicks in
/// (epic #2343: "max_overhead_fraction=0.40 knob").
pub const DEFAULT_MAX_OVERHEAD_FRACTION_PCT: usize = 40;

/// Escape-hatch env var overriding [`CadenceConfig::cadence_turns`] for one
/// process, mirroring `crate::mode::MODE_ENV_VAR`'s precedent.
pub const CADENCE_TURNS_ENV_VAR: &str = "TCODE_CADENCE_TURNS";

/// Escape-hatch env var overriding
/// [`CadenceConfig::max_overhead_fraction_pct`] for one process.
pub const CADENCE_OVERHEAD_FRACTION_ENV_VAR: &str = "TCODE_CADENCE_MAX_OVERHEAD_FRACTION_PCT";

/// Tuning knobs for the #2346 cadence compressor.
///
/// Why: A caller needs to control both "how often" (turn-count cadence) and
/// "how much of the window is overhead" (the budget the cadence + continuous
/// enforcement together must respect) — bundling them mirrors
/// `CompactionConfig`'s own two-knob shape.
/// What: `cadence_turns` is the turn-count period `maybe_cadence_compress`
/// fires the unconditional compaction pass on (0 disables cadence firing
/// entirely, though continuous enforcement still applies — see
/// `Transcript::tick_cadence_turn`'s docs); `max_overhead_fraction_pct` is
/// the whole-number percentage of the model's real context window
/// [`CadenceConfig::overhead_cap_tokens`] resolves the absolute cap from.
/// Test: `cadence::tests::default_is_sane`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CadenceConfig {
    /// Compress every this-many completed turns.
    pub cadence_turns: usize,
    /// Whole-number percentage of the context window the working transcript
    /// may occupy.
    pub max_overhead_fraction_pct: usize,
}

impl Default for CadenceConfig {
    /// The epic's stated defaults: `cadence_turns: 8`,
    /// `max_overhead_fraction_pct: 40`.
    /// Test: `cadence::tests::default_is_sane`.
    fn default() -> Self {
        Self {
            cadence_turns: DEFAULT_CADENCE_TURNS,
            max_overhead_fraction_pct: DEFAULT_MAX_OVERHEAD_FRACTION_PCT,
        }
    }
}

impl CadenceConfig {
    /// Resolve the absolute overhead-token cap for a given context window.
    ///
    /// Why: The budget arithmetic (epic #2343: on a 200K window, 40% ->
    /// 80K overhead cap, 120K working floor) needs the model's REAL context
    /// window — a property of the model, resolved separately via
    /// `crate::provider::resolve_context_window` — combined with this
    /// config's fraction.
    /// What: `context_window * max_overhead_fraction_pct / 100`.
    /// Test: `cadence::tests::overhead_cap_matches_epic_arithmetic`.
    pub fn overhead_cap_tokens(&self, context_window: usize) -> usize {
        context_window * self.max_overhead_fraction_pct / 100
    }
}

/// Resolve a project's [`CadenceConfig`] via the `code_harness.*`
/// `settings.json` precedence chain `crate::mode::resolve_mode` establishes,
/// adapted to this config's two knobs.
///
/// Why: An operator needs to tune cadence per-project (`settings.json`) or
/// per-process (the escape-hatch env vars) without a code change, matching
/// every other `code_harness.*` knob in this crate. Unlike `resolve_mode`,
/// there is no `task.run`-request tier — this ticket does not add a
/// per-call cadence override to the wire protocol, so the chain is simply
/// env var (highest) > `settings.json` > built-in default.
/// What: Starts from the resolved `settings.json`'s `code_harness.cadence_turns`/
/// `code_harness.max_overhead_fraction_pct` (via
/// [`read_settings_json_cadence`], falling back to [`CadenceConfig::default`]
/// when the file/keys are absent or malformed — never an error, matching
/// `crate::mode::read_settings_json_mode`'s graceful-degrade convention),
/// then overrides either field from [`CADENCE_TURNS_ENV_VAR`]/
/// [`CADENCE_OVERHEAD_FRACTION_ENV_VAR`] when set to a valid `usize` (an
/// unparseable value is logged via `tracing::warn!` and the prior tier's
/// value is kept, rather than erroring the whole run).
/// Test: `cadence::tests::resolve_cadence_config_settings_json_override`,
/// `cadence::tests::resolve_cadence_config_env_wins_over_settings_json`.
pub fn resolve_cadence_config(project_root: &Path) -> CadenceConfig {
    let mut cfg = read_settings_json_cadence(project_root).unwrap_or_default();

    if let Ok(raw) = std::env::var(CADENCE_TURNS_ENV_VAR) {
        match raw.trim().parse::<usize>() {
            Ok(v) => cfg.cadence_turns = v,
            Err(e) => tracing::warn!(
                "{CADENCE_TURNS_ENV_VAR}={raw:?} is not a valid usize ({e}); keeping {}",
                cfg.cadence_turns
            ),
        }
    }
    if let Ok(raw) = std::env::var(CADENCE_OVERHEAD_FRACTION_ENV_VAR) {
        match raw.trim().parse::<usize>() {
            Ok(v) => cfg.max_overhead_fraction_pct = v,
            Err(e) => tracing::warn!(
                "{CADENCE_OVERHEAD_FRACTION_ENV_VAR}={raw:?} is not a valid usize ({e}); keeping {}",
                cfg.max_overhead_fraction_pct
            ),
        }
    }
    cfg
}

/// Read the project's `settings.json` `code_harness.cadence_turns` /
/// `code_harness.max_overhead_fraction_pct` keys.
///
/// Why: this reader and `crate::mode::read_settings_json_mode` read the SAME
/// physical file. #5426 moved that file to `.trusty-code/settings.json` and left
/// this one joining `.claude/settings.json`, so a `.trusty-code`-only project
/// kept its mode override and silently lost its cadence override (code-critic
/// HIGH, PR #6980). Both now resolve through one function.
/// What: the file comes from [`crate::paths::settings_file`] — `.trusty-code/`
/// then `.claude/` then `.open-mpm/`. `None` when no file resolves or it has no
/// `code_harness` object; otherwise `Some(CadenceConfig)` starting from
/// [`CadenceConfig::default`] with either field overridden by whichever of the
/// two keys is present and a valid non-negative integer (a present but
/// wrong-typed key is skipped for that field, not an error for the whole read).
/// A file that resolved but then fails to read or parse warns with the path
/// tried before degrading, matching `mode`'s fail-open convention.
/// Test: `cadence::tests::resolve_cadence_config_settings_json_override`,
/// `cadence::tests::read_settings_json_cadence_missing_file_is_not_an_error`,
/// `cadence::tests::trusty_code_settings_json_sets_cadence_without_a_claude_dir`.
fn read_settings_json_cadence(project_root: &Path) -> Option<CadenceConfig> {
    // #5426: resolved, not joined — the same resolver `crate::mode` uses.
    let resolved = crate::paths::settings_file(project_root);
    if resolved.source == crate::paths::ConfigSource::Default {
        return None;
    }
    let path = resolved.path;
    let raw = match std::fs::read_to_string(&path) {
        Ok(raw) => raw,
        Err(e) => {
            tracing::warn!(
                path = %path.display(),
                error = %e,
                "project settings.json resolved but could not be read; \
                 keeping the default cadence configuration"
            );
            return None;
        }
    };
    let value: serde_json::Value = match serde_json::from_str(&raw) {
        Ok(value) => value,
        Err(e) => {
            tracing::warn!(
                path = %path.display(),
                error = %e,
                "project settings.json is not valid JSON; \
                 keeping the default cadence configuration"
            );
            return None;
        }
    };
    let harness = value.get("code_harness")?;

    let mut cfg = CadenceConfig::default();
    if let Some(turns) = harness
        .get("cadence_turns")
        .and_then(serde_json::Value::as_u64)
    {
        cfg.cadence_turns = turns as usize;
    }
    if let Some(pct) = harness
        .get("max_overhead_fraction_pct")
        .and_then(serde_json::Value::as_u64)
    {
        cfg.max_overhead_fraction_pct = pct as usize;
    }
    Some(cfg)
}

/// Outcome of one [`maybe_cadence_compress`] call, for observability/tests.
///
/// Why: `agent_loop::AgentLoop`'s turn boundary and unit tests both need to
/// know what happened without re-deriving it from `Transcript`'s counters.
/// What: `fired` — whether the scheduled cadence compaction ran THIS turn;
/// `rounds` — total compaction rounds this call performed (the cadence round,
/// if any, plus every continuous-enforcement round); `within_budget` —
/// whether the transcript ended at/under the overhead cap (`false` only on
/// the documented floor: the active zone alone, after full compaction,
/// still exceeds the cap); `overhead_tokens` — the REAL
/// [`estimate_total_tokens`] measurement of the model-facing transcript as
/// [`enforce_budget`] last observed it (i.e. after enforcement settled), which
/// is what makes a working-context indicator renderable from a measured value
/// rather than a projection.
/// Test: `cadence::tests::*`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CadenceOutcome {
    pub fired: bool,
    pub rounds: usize,
    pub within_budget: bool,
    /// Measured model-facing transcript size, in estimated tokens, after this
    /// call's enforcement settled.
    pub overhead_tokens: usize,
}

impl CadenceOutcome {
    /// Percentage of `context_window` consumed by session overhead.
    ///
    /// Why: the Infinite Sessions guarantee is stated as a ratio ("overhead
    /// <= 40%, working context >= 60%"), but this outcome measures ABSOLUTE
    /// tokens — a consumer rendering a budget meter needs the ratio, and
    /// deriving it in one place keeps every consumer's arithmetic identical.
    /// What: `overhead_tokens / context_window * 100`, saturating at 100 and
    /// returning 100 for a zero `context_window` (treat an unknown window as
    /// fully consumed — the conservative reading, and never a divide-by-zero).
    /// Test: `cadence::tests::overhead_pct_is_ratio_of_window`,
    /// `cadence::tests::pct_helpers_saturate_and_never_divide_by_zero`.
    pub fn overhead_pct(&self, context_window: usize) -> u8 {
        if context_window == 0 {
            return 100;
        }
        let pct = self.overhead_tokens.saturating_mul(100) / context_window;
        pct.min(100) as u8
    }

    /// Percentage of `context_window` still available for real work — the
    /// figure the Infinite Sessions guarantee requires to stay `>= 60`.
    ///
    /// Why: the headline number a UI budget indicator renders.
    /// What: `100 - overhead_pct(context_window)`, so the two always sum to
    /// exactly 100.
    /// Test: `cadence::tests::working_and_overhead_pct_sum_to_100`.
    pub fn working_context_pct(&self, context_window: usize) -> u8 {
        100 - self.overhead_pct(context_window)
    }
}

/// The turn-boundary entry point: tick the cadence counter, compress on
/// schedule, then continuously enforce the overhead budget every turn.
///
/// Why: This is what makes the epic's "ZERO threshold-compaction events in
/// steady state" metric achievable — see the module doc's overview. Called
/// BEFORE `Transcript::maybe_compact` at the same turn boundary
/// (`AgentLoop::run_inner`), so the threshold compactor only ever sees a
/// transcript this function already kept under budget.
/// What: `transcript.tick_cadence_turn(cfg.cadence_turns)` advances the
/// counter and reports whether this is a scheduled fire; if so,
/// `transcript.compact_span_tagged` unconditionally compacts everything
/// older than `keep_last_messages` (the active zone — reused from the
/// caller's own `CompactionConfig::keep_last_messages`, not a new knob).
/// Regardless of whether cadence fired this turn, [`enforce_budget`] then
/// runs: it re-checks `estimate_total_tokens(transcript.to_messages())`
/// against `cfg.overhead_cap_tokens(context_window)` and, if still over,
/// keeps shrinking the active zone and re-compacting (still via the SAME
/// group-safe `compact_span_tagged`) until under budget or the active zone
/// hits zero with nothing left to compact — at which point it warns (via
/// `tracing::warn!`) and returns rather than looping forever.
/// Test: `cadence::tests::fires_every_n_turns`,
/// `cadence::tests::stays_under_budget_every_turn`,
/// `cadence::tests::single_oversized_turn_still_ends_under_budget`,
/// `cadence::tests::floor_exceeded_warns_not_panics`.
pub fn maybe_cadence_compress(
    transcript: &mut Transcript,
    cfg: &CadenceConfig,
    keep_last_messages: usize,
    context_window: usize,
) -> CadenceOutcome {
    let fired = transcript.tick_cadence_turn(cfg.cadence_turns);
    let mut rounds = 0;
    if fired {
        let range = transcript.begin_cadence_range();
        if transcript.compact_span_tagged(keep_last_messages, range) {
            transcript.advance_cadence_fire_marker();
        }
        rounds += 1;
    }

    let cap = cfg.overhead_cap_tokens(context_window);
    let (enforcement_rounds, within_budget, overhead_tokens) =
        enforce_budget(transcript, cap, keep_last_messages);

    CadenceOutcome {
        fired,
        rounds: rounds + enforcement_rounds,
        within_budget,
        overhead_tokens,
    }
}

/// Continuously compact until `transcript`'s model-facing view is at/under
/// `cap_tokens`, or nothing compactable remains.
///
/// Why: A single pathological turn (e.g. a 60K-token `write_file` argument)
/// can blow the overhead cap even immediately after a cadence fire, since
/// cadence only ever protects the last `active_zone` messages, never
/// compacts them. Requirement 3 of #2346 ("continuous budget enforcement")
/// is this loop: shrink the protected active zone one message at a time and
/// re-compact (group-safely) until the budget is satisfied.
/// What: Starting at `keep_last = active_zone`, loop: measure the model-facing
/// transcript once per iteration; if already under `cap_tokens`, return
/// `(rounds, true, measured)`. Otherwise compact tagged with the transcript's
/// current cadence range, then either shrink `keep_last` by one (more rounds
/// to go) or, once `keep_last == 0`, either loop back (that round newly
/// compacted something — recheck the budget) or return `(rounds, false,
/// measured)` with a `tracing::warn!` (nothing left to compact and still over
/// budget — the documented floor: pinned/system/user content alone exceeds the
/// cap; the measurement is still accurate there precisely BECAUSE that round
/// compacted nothing). Bounded by `active_zone + 2` iterations — never an
/// unbounded loop.
///
/// The third return element is the token measurement this loop already had to
/// compute for its own budget check — returning it rather than dropping it is
/// what lets a caller report a REAL working-context figure without paying for a
/// second `estimate_total_tokens` pass over the whole transcript.
/// Test: `cadence::tests::stays_under_budget_every_turn`,
/// `cadence::tests::single_oversized_turn_still_ends_under_budget`,
/// `cadence::tests::floor_exceeded_warns_not_panics`,
/// `cadence::tests::outcome_reports_measured_overhead_tokens`.
fn enforce_budget(
    transcript: &mut Transcript,
    cap_tokens: usize,
    active_zone: usize,
) -> (usize, bool, usize) {
    let mut keep_last = active_zone;
    let mut rounds = 0;

    loop {
        let measured = estimate_total_tokens(&transcript.to_messages());
        if measured <= cap_tokens {
            return (rounds, true, measured);
        }

        let range = transcript.begin_cadence_range();
        let compacted = transcript.compact_span_tagged(keep_last, range);
        rounds += 1;
        if compacted {
            transcript.advance_cadence_fire_marker();
        }

        if keep_last == 0 {
            if !compacted {
                tracing::warn!(
                    cap_tokens,
                    measured,
                    "cadence: overhead cap still exceeded after compacting every eligible \
                     entry — the active zone (pinned + system/user turns) alone exceeds \
                     budget; this is a documented floor, not an error"
                );
                return (rounds, false, measured);
            }
            continue;
        }
        keep_last -= 1;
    }
}

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