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
//! 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 `.claude/settings.json`'s `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 Path;
use Transcript;
use 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`.
/// Resolve a project's [`CadenceConfig`] via the `code_harness.*`
/// `.claude/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 `.claude/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`.
/// Read `<project_root>/.claude/settings.json`'s `code_harness.cadence_turns`
/// / `code_harness.max_overhead_fraction_pct` keys.
///
/// Why: mirrors `crate::mode::read_settings_json_mode`'s graceful-degrade
/// convention for the same project-scoped config file.
/// What: `None` when the file is missing, unreadable, not valid JSON, or has
/// no `code_harness` object at all; 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 silently skipped for that field, not an error for
/// the whole read).
/// Test: `cadence::tests::resolve_cadence_config_settings_json_override`,
/// `cadence::tests::read_settings_json_cadence_missing_file_is_not_an_error`.
/// 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::*`.
/// 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`.
/// 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`.