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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! Durable compression-effectiveness telemetry (epic #3866, Slice A #3867 +
//! Slice B #3868).
//!
//! Why: `cadence::CadenceOutcome` and the #2308 threshold compactor both
//! compute real token/ratio numbers every time they fire, and — before this
//! module — every one of those numbers was thrown away past a
//! `tracing::info!`/`tracing::error!` line (stderr-only, never aggregated)
//! or an in-memory-only cache that resets on session end. Owner directive:
//! "measure compression effectiveness, and use logging to track it." This
//! module is the durable, structured, cross-session, machine-aggregable
//! third channel `crate::logging`'s own "logs vs. events" doc note says
//! `tracing`/`crate::events` cannot serve — see `crates/trusty-code/src/
//! logging/mod.rs`.
//! What: [`CompressionEvent`] is one JSONL record per compression/
//! summarization event, appended (best-effort, mirroring
//! `trusty-agents::usage::append_usage`'s failure posture exactly) to
//! `~/.trusty-code/compression.jsonl` via [`write_compression_event`].
//! [`record_compaction_alarm`]/[`lifetime_compaction_alarm_count`] are
//! Slice B's durable "has threshold compaction EVER fired under cadence"
//! never-event alarm: a dedicated append-only log
//! (`~/.trusty-code/compaction_alarm.log`), one line per fire, counted by
//! line rather than read-modify-write so concurrent fires can never race
//! each other into a lost increment.
//! Test: `telemetry::tests::*`.
use OpenOptions;
use ;
use ;
/// [`CompressionEvent::surface`] value for the #2346 cadence compressor.
pub const SURFACE_TCODE_CADENCE: &str = "tcode-cadence";
/// [`CompressionEvent::surface`] value for the #2308 threshold compactor.
pub const SURFACE_TCODE_THRESHOLD: &str = "tcode-threshold";
/// [`CompressionEvent::surface`] value for a #3911 cadence floor-breach
/// backstop fire — see [`record_cadence_floor_breach`].
pub const SURFACE_TCODE_CADENCE_FLOOR_BREACH: &str = "tcode-cadence-floor-breach";
/// `surface_detail` used for every [`SURFACE_TCODE_CADENCE`] record.
pub const DETAIL_CADENCE: &str = "cadence";
/// `surface_detail` used for every [`SURFACE_TCODE_THRESHOLD`] record.
pub const DETAIL_THRESHOLD: &str = "threshold";
/// `surface_detail` used for every [`SURFACE_TCODE_CADENCE_FLOOR_BREACH`]
/// record.
pub const DETAIL_CADENCE_FLOOR_BREACH: &str = "cadence-floor-breach";
/// Filename of the durable compression-telemetry JSONL, under whatever data
/// directory the caller resolves (production: `crate::workstreams::
/// default_data_dir()`, i.e. `~/.trusty-code`).
const COMPRESSION_LOG_FILENAME: &str = "compression.jsonl";
/// Filename of Slice B's durable compaction-alarm log, one line per
/// `cadence: Some(_)` threshold-compaction fire.
const COMPACTION_ALARM_LOG_FILENAME: &str = "compaction_alarm.log";
/// Filename of the #3911 durable cadence floor-breach alarm log, one line
/// per turn `cadence::enforce_budget` exhausted every eligible entry and
/// STILL exceeded the overhead cap (`CadenceOutcome::within_budget ==
/// false`) — the never-event alarm for a cadence-level 60%-floor breach,
/// mirroring [`COMPACTION_ALARM_LOG_FILENAME`]'s identical append-only
/// design but for the cadence backstop rather than the threshold one.
const CADENCE_FLOOR_BREACH_ALARM_LOG_FILENAME: &str = "cadence_floor_breach_alarm.log";
/// Escape-hatch env var overriding [`default_data_dir`] for one process,
/// mirroring `cadence::CADENCE_TURNS_ENV_VAR`'s precedent. Test-only in
/// practice (production never sets it) — lets a test point every telemetry
/// write/read at an isolated temp directory instead of the real
/// `~/.trusty-code`.
pub const DATA_DIR_ENV_VAR: &str = "TCODE_TELEMETRY_DATA_DIR";
/// Serializes tests that mutate [`DATA_DIR_ENV_VAR`], mirroring
/// `cadence_env_helper::CADENCE_ENV_LOCK`'s identical rationale. `pub(crate)`
/// (not private) so other test modules mutating the SAME env var
/// (`agent_loop::compression_telemetry_tests`) share ONE lock —
/// `mode::MODE_ENV_LOCK`'s identical cross-module rationale. `#[cfg(test)]`
/// since production never touches this var at all.
pub static DATA_DIR_ENV_LOCK: Mutex = const_new;
/// Resolve the data directory every telemetry read/write in this module
/// uses: [`DATA_DIR_ENV_VAR`] when set (test isolation), otherwise
/// `crate::workstreams::default_data_dir()` (`~/.trusty-code`, production).
/// The directory [`DATA_DIR_ENV_VAR`] names, if it is set.
///
/// Why: #6999 gave `crate::workstreams::default_data_dir` a side effect — it
/// creates and chmods `~/.trusty-code` — so a test that asserted on
/// [`default_data_dir`] to check the UNSET branch did real I/O in whatever
/// `$HOME` the run had. Reading the variable separately lets that branch be
/// asserted without resolving, creating, or chmod'ing anything.
/// What: the variable parsed as a `PathBuf`, or `None` when unset.
/// Test: `agent_loop::telemetry_tests::default_data_dir_honors_env_override`,
/// `agent_loop::telemetry_tests::default_data_dir_falls_back_to_workstreams_default_when_unset`.
/// One JSONL line: a single compression/summarization event (issue #3867).
///
/// Why: a flat, all-primitive shape keeps the log trivially grep-able and
/// loadable into jq/pandas/DuckDB for Slice C's report, and lets every field
/// be asserted individually in tests without a custom deserializer.
/// What: field names and semantics match issue #3867's schema exactly — see
/// the issue body for the authoritative field-by-field spec. `ratio` is
/// `tokens_after / tokens_before`, `0.0` when `tokens_before == 0` (never a
/// divide-by-zero or NaN, mirroring `tm compress`'s `log_compression_stats`
/// guard). `working_context_pct_after`/`overhead_pct_after` are `None` for
/// surfaces with no `CadenceOutcome` to derive them from (`agents-ws-summary`
/// per the issue; this crate never emits that surface).
/// Test: `tests::compression_event_serializes_expected_schema`,
/// `tests::ratio_guards_divide_by_zero`.
/// `tokens_after / tokens_before`, `0.0` when `tokens_before == 0`.
///
/// Why: never divide by zero, never produce NaN — a JSONL consumer (Slice
/// C's report, or a human `jq`-ing the file) must never have to guard
/// against either.
/// Test: `tests::ratio_guards_divide_by_zero`, `tests::ratio_is_after_over_before`.
/// Resolve `<data_dir>/compression.jsonl`.
/// Resolve `<data_dir>/compaction_alarm.log`.
/// Resolve `<data_dir>/cadence_floor_breach_alarm.log` (issue #3911).
/// Append `event` as one JSONL line to `<data_dir>/compression.jsonl`.
///
/// Why: emission must never fail the compaction/cadence operation it
/// instruments — this is observability, not control flow.
/// What: best-effort `mkdir -p` of `data_dir`, then opens the file in
/// `create + append` mode and writes one `serde_json::to_string(event)` line
/// followed by `\n`, flushing so the bytes are visible to a concurrent
/// reader. Any I/O or serialization failure logs at `debug!` and returns —
/// mirrors `trusty-agents::usage::append_usage`'s failure posture exactly
/// (issue #3867 acceptance criteria: "a broken/unwritable log directory must
/// not fail the compression/summarization operation itself").
/// Test: `tests::write_compression_event_creates_and_appends`,
/// `tests::write_compression_event_unwritable_dir_does_not_panic`.
/// Append one line to `<data_dir>/compaction_alarm.log`, recording that a
/// `cadence: Some(_)` threshold-compaction fire just happened (issue #3868).
///
/// Why: a durable, cross-session, cheap-to-query answer to "has threshold
/// compaction ever fired under cadence" needs a signal that survives past
/// the `tracing::error!` at the call site and the in-memory `Transcript`
/// counter, both of which reset on session end. Append-only (one line per
/// fire, never read-modify-write) so concurrent fires from different
/// sessions can never race each other into a lost increment — the count is
/// always "number of lines", never a stored integer that can be
/// clobbered by two writers reading the same stale value.
/// What: best-effort, matching [`write_compression_event`]'s failure
/// posture. `cadence: None` runs must NEVER call this — see
/// `agent_loop::AgentLoop::maybe_compact_transcript`'s call site, which only
/// reaches this function inside its `self.config.cadence.is_some()` branch.
/// Test: `tests::record_compaction_alarm_appends_one_line_per_call`,
/// `tests::record_compaction_alarm_unwritable_dir_does_not_panic`.
/// Count how many times [`record_compaction_alarm`] has ever fired for
/// `data_dir` — the lifetime, cross-session, cross-restart alarm count
/// exposed on `session.get_context_budget` as `lifetime_compaction_alarm_count`
/// (issue #3868).
///
/// Why: reading a line count from disk on every query is cheap (this is
/// meant to stay a NEVER-event — the file should almost always be empty or
/// absent) and trivially correct — no separate stored counter that could
/// drift from the log it's supposedly summarizing.
/// What: `0` when the file is missing or unreadable (never an error — a
/// fresh install with no alarm history is the common case, not a fault);
/// otherwise the number of non-empty lines.
/// Test: `tests::lifetime_compaction_alarm_count_zero_when_missing`,
/// `tests::lifetime_compaction_alarm_count_matches_fire_count`.
/// Append one line to `<data_dir>/cadence_floor_breach_alarm.log`, recording
/// that `cadence::enforce_budget` exhausted every eligible entry and STILL
/// exceeded the overhead cap this turn (issue #3911's backstop).
///
/// Why: before this, a cadence-level 60%-floor breach produced only an
/// in-process `tracing::warn!` inside `cadence::enforce_budget` — invisible
/// outside stderr, never durable, never counted. The load-realistic soak
/// (epic #3866, PR #3909) proved this breach can and does happen under
/// heavy load (floor 48%) while EVERY other alarm signal
/// (`lifetime_compaction_alarm_count`, `TranscriptRecord.compaction_events`)
/// stayed at 0 — because those signals watch the THRESHOLD compactor, a
/// mechanically independent trigger cadence's own floor breach never
/// crosses (see [`record_cadence_floor_breach`]'s docs for why). This is
/// the durable signal that closes that gap. Same append-only,
/// count-by-lines design as [`record_compaction_alarm`] for the identical
/// reason: concurrent fires from different sessions can never race each
/// other into a lost increment.
/// What: best-effort, matching [`write_compression_event`]'s failure
/// posture.
/// Test: `tests::record_cadence_floor_breach_alarm_appends_one_line_per_call`,
/// `tests::record_cadence_floor_breach_alarm_unwritable_dir_does_not_panic`.
/// Count how many times [`record_cadence_floor_breach_alarm`] has ever
/// fired for `data_dir` — the lifetime, cross-session, cross-restart alarm
/// count exposed on `session.get_context_budget` as
/// `lifetime_cadence_floor_breach_count` (issue #3911).
///
/// What: `0` when the file is missing or unreadable (the common,
/// never-event case); otherwise the number of non-empty lines. Mirrors
/// [`lifetime_compaction_alarm_count`]'s identical read-fresh-from-disk
/// contract.
/// Test: `tests::lifetime_cadence_floor_breach_count_zero_when_missing`,
/// `tests::lifetime_cadence_floor_breach_count_matches_fire_count`.
/// Session-scoped working-context low-water mark, read fresh from the
/// durable `compression.jsonl` log (issue #3912).
///
/// Why: `session.get_context_budget` cached only the MOST RECENT
/// `ContextBudgetSnapshot` — a single point-in-time value that a coarse,
/// once-per-`task.run`-call poll can easily miss the real dip on (the
/// load-realistic soak, epic #3866, observed the RPC report 98-99% while
/// the durable JSONL recorded a 48-60% floor for the SAME run). Every
/// cadence/threshold fire already writes its `working_context_pct_after`
/// to this log (issue #3867) — this is the query that turns "every sample
/// this session ever produced" into the one number an operator actually
/// needs: how low did it REALLY get.
/// What: scans `<data_dir>/compression.jsonl` line by line (best-effort,
/// matching every other reader in this module — a missing file, an
/// unreadable line, or a record with no `working_context_pct_after` is
/// silently skipped, never an error), keeping only rows whose `session_id`
/// matches `session_id` exactly. Returns `(None, 0)` when the file is
/// missing or no matching sample carries a percentage; otherwise
/// `(Some(min), count)` — the lowest `working_context_pct_after` observed
/// for this session and how many samples that minimum was computed over.
/// Test: `tests::session_working_context_floor_missing_file_is_none`,
/// `tests::session_working_context_floor_tracks_minimum_for_session`,
/// `tests::session_working_context_floor_ignores_other_sessions`.
/// Derive `(working_context_pct, overhead_pct)` from a raw token measurement
/// against a model's context window, mirroring
/// `cadence::CadenceOutcome::working_context_pct`/`overhead_pct`'s own
/// saturating arithmetic (never a divide-by-zero, never > 100).
///
/// Why: shared by both `AgentLoop::maybe_compact_transcript` (which has no
/// `CadenceOutcome` to read these from) and callers that already have one,
/// so the two call sites' percentages can never drift apart from cadence's
/// own formula.
/// What: `(None, None)` for a zero `context_window` (percentages are
/// meaningless without a real window); otherwise `overhead_pct =
/// (tokens * 100 / context_window).min(100)`, `working_context_pct = 100 -
/// overhead_pct`.
/// Test: `tests::context_pcts_zero_window_is_none`,
/// `tests::context_pcts_matches_saturating_formula`.
/// Build and emit the [`SURFACE_TCODE_THRESHOLD`] telemetry record for one
/// `AgentLoop::maybe_compact_transcript` fire, and — when `cadence_enabled`
/// — the Slice B durable alarm line alongside it (issues #3867, #3868).
///
/// Why: keeps `AgentLoop::maybe_compact_transcript` a thin call rather than
/// inlining the event construction + percentage derivation at that call
/// site (this crate's 500-SLOC production file cap).
/// What: `compaction_event` is always `true` (issue #3867: `true` only for
/// `tcode-threshold` fires — this function is only ever called on one).
/// `cadence_enabled` gates the alarm line only — the JSONL record itself is
/// unconditional, per issue #3867's spec.
/// Test: `tests::record_threshold_event_writes_jsonl_and_alarm_when_cadence_enabled`,
/// `tests::record_threshold_event_no_alarm_when_cadence_disabled`.
/// Build and emit the [`SURFACE_TCODE_CADENCE`] telemetry record for one
/// `AgentLoop::maybe_cadence_compress` call whose `outcome.rounds > 0`
/// (issue #3867).
///
/// Why: same file-size rationale as [`record_threshold_event`].
/// What: `compaction_event` is always `false` (cadence fires are never the
/// Slice B alarm signal). Caller must only invoke this when
/// `outcome.rounds > 0` — see the issue's "only emit when something
/// actually happened" note.
/// Test: `tests::record_cadence_event_writes_jsonl`.
/// Build and emit the [`SURFACE_TCODE_CADENCE_FLOOR_BREACH`] telemetry
/// record plus the durable [`record_cadence_floor_breach_alarm`] line, for
/// one `AgentLoop::maybe_cadence_compress` call whose
/// `CadenceOutcome::within_budget` was `false` (issue #3911).
///
/// Why: `cadence::enforce_budget`'s own "documented floor" case (active
/// zone shrunk to zero, still over the overhead cap) previously only
/// logged `tracing::warn!` from deep inside that function — no durable
/// record, no counter, and critically NOT the same alarm the #2308
/// threshold compactor's OWN breach uses
/// (`record_threshold_event`/`lifetime_compaction_alarm_count`), because
/// that alarm is keyed to a MECHANICALLY INDEPENDENT trigger: threshold
/// fires only once the raw transcript crosses 75% of the context window
/// (`CompactionConfig::for_context_window`), a laxer bound than cadence's
/// own 40%-overhead enforcement cap — so by the time cadence has already
/// compacted as hard as it structurally can (`enforce_budget` shrinks the
/// active zone to zero, re-compacting at every step) and still exceeds
/// its OWN cap, the transcript is nowhere near threshold's separate,
/// higher bound. The load-realistic soak (epic #3866, PR #3909) proved
/// this empirically: a 48% floor breach produced zero threshold events,
/// zero alarm-count increments, and zero visible signal anywhere but a
/// stderr line. This function is the durable, countable trigger that
/// closes that gap — always called (unconditionally, unlike
/// `record_threshold_event`'s cadence-gated alarm) because this call site
/// only exists on the cadence-enabled path in the first place
/// (`AgentLoop::maybe_cadence_compress` already returns early when
/// `self.config.cadence` is `None`).
/// What: writes a `compaction_event: true` JSONL row (this genuinely IS an
/// alarm-worthy event — the same semantic `record_threshold_event` uses
/// `true` for) tagged `surface: "tcode-cadence-floor-breach"`, then
/// unconditionally appends the durable alarm line.
///
/// (post-review fix, issue #3911) `working_context_pct_after`/
/// `overhead_pct_after` are ALWAYS `None` on this row, deliberately — NOT
/// derived from `tokens_after`/`context_window` the way every other
/// surface's percentages are. Why: `AgentLoop::maybe_cadence_compress`
/// calls [`record_cadence_event`] unconditionally whenever `outcome.rounds
/// > 0` (which every floor breach satisfies — `enforce_budget` always ran
/// at least one round to reach `within_budget: false`) BEFORE this
/// function, for the exact same turn, with the exact same
/// `outcome.overhead_tokens`/`context_window`. Computing the percentage
/// here too would write a SECOND row carrying an IDENTICAL
/// `working_context_pct_after` for one real measurement — exactly the
/// double-count a code-review pass caught: `compression_report.py`'s
/// `compute_context_floor` (and this crate's own
/// `session_working_context_floor`, issue #3912) aggregate every row with
/// a non-`None` percentage with no surface-based dedup, so a single
/// breach was being counted TWICE toward the observed floor (measured: a
/// soak run with 21 real breaches reported 42 below-target samples).
/// Leaving these `None` here is the single-point fix: every existing and
/// future consumer that filters on "has a working_context_pct_after
/// sample" — not just this function's two current call sites — inherits
/// the fix for free, rather than requiring each one to separately learn to
/// exclude this surface. The paired `tcode-cadence` row is the ONE
/// authoritative percentage sample for this turn; this row's job is only
/// to durably flag THAT a breach happened (`compaction_event: true`,
/// `tokens_before`/`tokens_after`/`rounds` are still real and useful for
/// debugging), not to re-report the same number under a second surface.
/// Test: `tests::record_cadence_floor_breach_writes_jsonl_and_alarm`,
/// `tests::record_cadence_floor_breach_never_double_counts_the_floor`.
/// Test-only helper: run `f` with [`DATA_DIR_ENV_VAR`] pointed at `dir`,
/// serialized on [`DATA_DIR_ENV_LOCK`] so parallel `cargo test` threads never
/// race each other's env mutation — mirrors
/// `cadence_env_helper::with_cadence_env`'s identical rationale.
///
/// Why: production telemetry always writes/reads real `~/.trusty-code`; any
/// test exercising `AgentLoop::maybe_compact_transcript`/
/// `maybe_cadence_compress` or `SessionRegistry::record_context_budget` end
/// to end needs an isolated directory instead, without a second production
/// code path.
pub async
/// Async twin of [`with_data_dir_env`] for loop-level tests that must await
/// an `AgentLoop::run`/`run_with_transcript` call WHILE the env var is set
/// (a plain `FnOnce() -> T` closure cannot itself `.await`).
///
/// Why: without this, every loop-integration test needed to hand-inline the
/// lock/set/run/clear sequence, duplicating the `unsafe` env mutation at
/// each call site. Centralising it here keeps that `unsafe` block in exactly
/// one place, matching [`with_data_dir_env`]'s same rationale.
pub async
/// Test-only helper: a fresh, uniquely-named, already-created temp directory
/// under `std::env::temp_dir()`, for tests that need an isolated telemetry
/// write target.
///
/// Why: every loop-integration test that isolates its telemetry writes
/// previously duplicated this exact `process_id + nanosecond-timestamp`
/// naming scheme at its own call site (`compression_telemetry_tests.rs`,
/// `telemetry_tests.rs`, `tests/cadence.rs`'s `forced_degradation_*` test).
/// `pub(crate)` so every `agent_loop` test submodule can share ONE
/// implementation instead of re-deriving the same uniqueness scheme —
/// consolidating them is also what makes issue #3902's fix
/// (`AgentLoopConfig::telemetry_data_dir` injection replacing the raced
/// `TCODE_TELEMETRY_DATA_DIR` env var) a one-line call at each of the
/// newly-isolated call sites instead of a repeated inline block.
/// What: `label` only needs to distinguish this call site from sibling
/// calls in the same test binary — the pid + nanosecond timestamp already
/// guarantees cross-process and cross-call uniqueness on its own.
pub