Skip to main content

trusty_code/agent_loop/
telemetry.rs

1//! Durable compression-effectiveness telemetry (epic #3866, Slice A #3867 +
2//! Slice B #3868).
3//!
4//! Why: `cadence::CadenceOutcome` and the #2308 threshold compactor both
5//! compute real token/ratio numbers every time they fire, and — before this
6//! module — every one of those numbers was thrown away past a
7//! `tracing::info!`/`tracing::error!` line (stderr-only, never aggregated)
8//! or an in-memory-only cache that resets on session end. Owner directive:
9//! "measure compression effectiveness, and use logging to track it." This
10//! module is the durable, structured, cross-session, machine-aggregable
11//! third channel `crate::logging`'s own "logs vs. events" doc note says
12//! `tracing`/`crate::events` cannot serve — see `crates/trusty-code/src/
13//! logging/mod.rs`.
14//! What: [`CompressionEvent`] is one JSONL record per compression/
15//! summarization event, appended (best-effort, mirroring
16//! `trusty-agents::usage::append_usage`'s failure posture exactly) to
17//! `~/.trusty-code/compression.jsonl` via [`write_compression_event`].
18//! [`record_compaction_alarm`]/[`lifetime_compaction_alarm_count`] are
19//! Slice B's durable "has threshold compaction EVER fired under cadence"
20//! never-event alarm: a dedicated append-only log
21//! (`~/.trusty-code/compaction_alarm.log`), one line per fire, counted by
22//! line rather than read-modify-write so concurrent fires can never race
23//! each other into a lost increment.
24//! Test: `telemetry::tests::*`.
25
26use std::fs::OpenOptions;
27use std::io::{BufRead, Write as _};
28use std::path::{Path, PathBuf};
29
30/// [`CompressionEvent::surface`] value for the #2346 cadence compressor.
31pub const SURFACE_TCODE_CADENCE: &str = "tcode-cadence";
32/// [`CompressionEvent::surface`] value for the #2308 threshold compactor.
33pub const SURFACE_TCODE_THRESHOLD: &str = "tcode-threshold";
34/// [`CompressionEvent::surface`] value for a #3911 cadence floor-breach
35/// backstop fire — see [`record_cadence_floor_breach`].
36pub const SURFACE_TCODE_CADENCE_FLOOR_BREACH: &str = "tcode-cadence-floor-breach";
37
38/// `surface_detail` used for every [`SURFACE_TCODE_CADENCE`] record.
39pub const DETAIL_CADENCE: &str = "cadence";
40/// `surface_detail` used for every [`SURFACE_TCODE_THRESHOLD`] record.
41pub const DETAIL_THRESHOLD: &str = "threshold";
42/// `surface_detail` used for every [`SURFACE_TCODE_CADENCE_FLOOR_BREACH`]
43/// record.
44pub const DETAIL_CADENCE_FLOOR_BREACH: &str = "cadence-floor-breach";
45
46/// Filename of the durable compression-telemetry JSONL, under whatever data
47/// directory the caller resolves (production: `crate::workstreams::
48/// default_data_dir()`, i.e. `~/.trusty-code`).
49const COMPRESSION_LOG_FILENAME: &str = "compression.jsonl";
50
51/// Filename of Slice B's durable compaction-alarm log, one line per
52/// `cadence: Some(_)` threshold-compaction fire.
53const COMPACTION_ALARM_LOG_FILENAME: &str = "compaction_alarm.log";
54
55/// Filename of the #3911 durable cadence floor-breach alarm log, one line
56/// per turn `cadence::enforce_budget` exhausted every eligible entry and
57/// STILL exceeded the overhead cap (`CadenceOutcome::within_budget ==
58/// false`) — the never-event alarm for a cadence-level 60%-floor breach,
59/// mirroring [`COMPACTION_ALARM_LOG_FILENAME`]'s identical append-only
60/// design but for the cadence backstop rather than the threshold one.
61const CADENCE_FLOOR_BREACH_ALARM_LOG_FILENAME: &str = "cadence_floor_breach_alarm.log";
62
63/// Escape-hatch env var overriding [`default_data_dir`] for one process,
64/// mirroring `cadence::CADENCE_TURNS_ENV_VAR`'s precedent. Test-only in
65/// practice (production never sets it) — lets a test point every telemetry
66/// write/read at an isolated temp directory instead of the real
67/// `~/.trusty-code`.
68pub const DATA_DIR_ENV_VAR: &str = "TCODE_TELEMETRY_DATA_DIR";
69
70/// Serializes tests that mutate [`DATA_DIR_ENV_VAR`], mirroring
71/// `cadence_env_helper::CADENCE_ENV_LOCK`'s identical rationale. `pub(crate)`
72/// (not private) so other test modules mutating the SAME env var
73/// (`agent_loop::compression_telemetry_tests`) share ONE lock —
74/// `mode::MODE_ENV_LOCK`'s identical cross-module rationale. `#[cfg(test)]`
75/// since production never touches this var at all.
76#[cfg(test)]
77pub(crate) static DATA_DIR_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
78
79/// Resolve the data directory every telemetry read/write in this module
80/// uses: [`DATA_DIR_ENV_VAR`] when set (test isolation), otherwise
81/// `crate::workstreams::default_data_dir()` (`~/.trusty-code`, production).
82pub fn default_data_dir() -> PathBuf {
83    data_dir_override().unwrap_or_else(crate::workstreams::default_data_dir)
84}
85
86/// The directory [`DATA_DIR_ENV_VAR`] names, if it is set.
87///
88/// Why: #6999 gave `crate::workstreams::default_data_dir` a side effect — it
89/// creates and chmods `~/.trusty-code` — so a test that asserted on
90/// [`default_data_dir`] to check the UNSET branch did real I/O in whatever
91/// `$HOME` the run had. Reading the variable separately lets that branch be
92/// asserted without resolving, creating, or chmod'ing anything.
93/// What: the variable parsed as a `PathBuf`, or `None` when unset.
94/// Test: `agent_loop::telemetry_tests::default_data_dir_honors_env_override`,
95/// `agent_loop::telemetry_tests::default_data_dir_falls_back_to_workstreams_default_when_unset`.
96fn data_dir_override() -> Option<PathBuf> {
97    std::env::var(DATA_DIR_ENV_VAR).ok().map(PathBuf::from)
98}
99
100/// One JSONL line: a single compression/summarization event (issue #3867).
101///
102/// Why: a flat, all-primitive shape keeps the log trivially grep-able and
103/// loadable into jq/pandas/DuckDB for Slice C's report, and lets every field
104/// be asserted individually in tests without a custom deserializer.
105/// What: field names and semantics match issue #3867's schema exactly — see
106/// the issue body for the authoritative field-by-field spec. `ratio` is
107/// `tokens_after / tokens_before`, `0.0` when `tokens_before == 0` (never a
108/// divide-by-zero or NaN, mirroring `tm compress`'s `log_compression_stats`
109/// guard). `working_context_pct_after`/`overhead_pct_after` are `None` for
110/// surfaces with no `CadenceOutcome` to derive them from (`agents-ws-summary`
111/// per the issue; this crate never emits that surface).
112/// Test: `tests::compression_event_serializes_expected_schema`,
113/// `tests::ratio_guards_divide_by_zero`.
114#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
115pub struct CompressionEvent {
116    pub ts: String,
117    pub session_id: Option<String>,
118    pub surface: String,
119    pub surface_detail: String,
120    pub tokens_before: usize,
121    pub tokens_after: usize,
122    pub ratio: f64,
123    pub working_context_pct_after: Option<u8>,
124    pub overhead_pct_after: Option<u8>,
125    pub compaction_event: bool,
126    pub duration_ms: u64,
127    pub rounds: usize,
128}
129
130impl CompressionEvent {
131    /// Build a record with `ts` set to "now" (RFC3339 UTC, matching
132    /// `trusty-agents::usage::UsageRecord.ts`'s convention) and `ratio`
133    /// derived via [`compute_ratio`].
134    #[allow(clippy::too_many_arguments)]
135    pub fn new(
136        session_id: Option<String>,
137        surface: &str,
138        surface_detail: &str,
139        tokens_before: usize,
140        tokens_after: usize,
141        working_context_pct_after: Option<u8>,
142        overhead_pct_after: Option<u8>,
143        compaction_event: bool,
144        duration_ms: u64,
145        rounds: usize,
146    ) -> Self {
147        Self {
148            ts: chrono::Utc::now().to_rfc3339(),
149            session_id,
150            surface: surface.to_string(),
151            surface_detail: surface_detail.to_string(),
152            tokens_before,
153            tokens_after,
154            ratio: compute_ratio(tokens_before, tokens_after),
155            working_context_pct_after,
156            overhead_pct_after,
157            compaction_event,
158            duration_ms,
159            rounds,
160        }
161    }
162}
163
164/// `tokens_after / tokens_before`, `0.0` when `tokens_before == 0`.
165///
166/// Why: never divide by zero, never produce NaN — a JSONL consumer (Slice
167/// C's report, or a human `jq`-ing the file) must never have to guard
168/// against either.
169/// Test: `tests::ratio_guards_divide_by_zero`, `tests::ratio_is_after_over_before`.
170pub fn compute_ratio(tokens_before: usize, tokens_after: usize) -> f64 {
171    if tokens_before == 0 {
172        return 0.0;
173    }
174    tokens_after as f64 / tokens_before as f64
175}
176
177/// Resolve `<data_dir>/compression.jsonl`.
178pub fn compression_log_path(data_dir: &Path) -> PathBuf {
179    data_dir.join(COMPRESSION_LOG_FILENAME)
180}
181
182/// Resolve `<data_dir>/compaction_alarm.log`.
183pub fn compaction_alarm_log_path(data_dir: &Path) -> PathBuf {
184    data_dir.join(COMPACTION_ALARM_LOG_FILENAME)
185}
186
187/// Resolve `<data_dir>/cadence_floor_breach_alarm.log` (issue #3911).
188pub fn cadence_floor_breach_alarm_log_path(data_dir: &Path) -> PathBuf {
189    data_dir.join(CADENCE_FLOOR_BREACH_ALARM_LOG_FILENAME)
190}
191
192/// Append `event` as one JSONL line to `<data_dir>/compression.jsonl`.
193///
194/// Why: emission must never fail the compaction/cadence operation it
195/// instruments — this is observability, not control flow.
196/// What: best-effort `mkdir -p` of `data_dir`, then opens the file in
197/// `create + append` mode and writes one `serde_json::to_string(event)` line
198/// followed by `\n`, flushing so the bytes are visible to a concurrent
199/// reader. Any I/O or serialization failure logs at `debug!` and returns —
200/// mirrors `trusty-agents::usage::append_usage`'s failure posture exactly
201/// (issue #3867 acceptance criteria: "a broken/unwritable log directory must
202/// not fail the compression/summarization operation itself").
203/// Test: `tests::write_compression_event_creates_and_appends`,
204/// `tests::write_compression_event_unwritable_dir_does_not_panic`.
205pub fn write_compression_event(data_dir: &Path, event: &CompressionEvent) {
206    let _ = std::fs::create_dir_all(data_dir);
207    let line = match serde_json::to_string(event) {
208        Ok(s) => format!("{s}\n"),
209        Err(e) => {
210            tracing::debug!(error = %e, "compression telemetry: serialize failed");
211            return;
212        }
213    };
214    let path = compression_log_path(data_dir);
215    match OpenOptions::new().create(true).append(true).open(&path) {
216        Ok(mut f) => {
217            if let Err(e) = f.write_all(line.as_bytes()) {
218                tracing::debug!(error = %e, path = %path.display(), "compression telemetry: write failed");
219                return;
220            }
221            let _ = f.flush();
222        }
223        Err(e) => {
224            tracing::debug!(error = %e, path = %path.display(), "compression telemetry: open failed");
225        }
226    }
227}
228
229/// Append one line to `<data_dir>/compaction_alarm.log`, recording that a
230/// `cadence: Some(_)` threshold-compaction fire just happened (issue #3868).
231///
232/// Why: a durable, cross-session, cheap-to-query answer to "has threshold
233/// compaction ever fired under cadence" needs a signal that survives past
234/// the `tracing::error!` at the call site and the in-memory `Transcript`
235/// counter, both of which reset on session end. Append-only (one line per
236/// fire, never read-modify-write) so concurrent fires from different
237/// sessions can never race each other into a lost increment — the count is
238/// always "number of lines", never a stored integer that can be
239/// clobbered by two writers reading the same stale value.
240/// What: best-effort, matching [`write_compression_event`]'s failure
241/// posture. `cadence: None` runs must NEVER call this — see
242/// `agent_loop::AgentLoop::maybe_compact_transcript`'s call site, which only
243/// reaches this function inside its `self.config.cadence.is_some()` branch.
244/// Test: `tests::record_compaction_alarm_appends_one_line_per_call`,
245/// `tests::record_compaction_alarm_unwritable_dir_does_not_panic`.
246pub fn record_compaction_alarm(data_dir: &Path) {
247    let _ = std::fs::create_dir_all(data_dir);
248    let path = compaction_alarm_log_path(data_dir);
249    let line = format!("{}\n", chrono::Utc::now().to_rfc3339());
250    match OpenOptions::new().create(true).append(true).open(&path) {
251        Ok(mut f) => {
252            if let Err(e) = f.write_all(line.as_bytes()) {
253                tracing::debug!(error = %e, path = %path.display(), "compaction alarm: write failed");
254                return;
255            }
256            let _ = f.flush();
257        }
258        Err(e) => {
259            tracing::debug!(error = %e, path = %path.display(), "compaction alarm: open failed");
260        }
261    }
262}
263
264/// Count how many times [`record_compaction_alarm`] has ever fired for
265/// `data_dir` — the lifetime, cross-session, cross-restart alarm count
266/// exposed on `session.get_context_budget` as `lifetime_compaction_alarm_count`
267/// (issue #3868).
268///
269/// Why: reading a line count from disk on every query is cheap (this is
270/// meant to stay a NEVER-event — the file should almost always be empty or
271/// absent) and trivially correct — no separate stored counter that could
272/// drift from the log it's supposedly summarizing.
273/// What: `0` when the file is missing or unreadable (never an error — a
274/// fresh install with no alarm history is the common case, not a fault);
275/// otherwise the number of non-empty lines.
276/// Test: `tests::lifetime_compaction_alarm_count_zero_when_missing`,
277/// `tests::lifetime_compaction_alarm_count_matches_fire_count`.
278pub fn lifetime_compaction_alarm_count(data_dir: &Path) -> u64 {
279    let path = compaction_alarm_log_path(data_dir);
280    let Ok(file) = std::fs::File::open(&path) else {
281        return 0;
282    };
283    std::io::BufReader::new(file)
284        .lines()
285        .map_while(Result::ok)
286        .filter(|l| !l.trim().is_empty())
287        .count() as u64
288}
289
290/// Append one line to `<data_dir>/cadence_floor_breach_alarm.log`, recording
291/// that `cadence::enforce_budget` exhausted every eligible entry and STILL
292/// exceeded the overhead cap this turn (issue #3911's backstop).
293///
294/// Why: before this, a cadence-level 60%-floor breach produced only an
295/// in-process `tracing::warn!` inside `cadence::enforce_budget` — invisible
296/// outside stderr, never durable, never counted. The load-realistic soak
297/// (epic #3866, PR #3909) proved this breach can and does happen under
298/// heavy load (floor 48%) while EVERY other alarm signal
299/// (`lifetime_compaction_alarm_count`, `TranscriptRecord.compaction_events`)
300/// stayed at 0 — because those signals watch the THRESHOLD compactor, a
301/// mechanically independent trigger cadence's own floor breach never
302/// crosses (see [`record_cadence_floor_breach`]'s docs for why). This is
303/// the durable signal that closes that gap. Same append-only,
304/// count-by-lines design as [`record_compaction_alarm`] for the identical
305/// reason: concurrent fires from different sessions can never race each
306/// other into a lost increment.
307/// What: best-effort, matching [`write_compression_event`]'s failure
308/// posture.
309/// Test: `tests::record_cadence_floor_breach_alarm_appends_one_line_per_call`,
310/// `tests::record_cadence_floor_breach_alarm_unwritable_dir_does_not_panic`.
311pub fn record_cadence_floor_breach_alarm(data_dir: &Path) {
312    let _ = std::fs::create_dir_all(data_dir);
313    let path = cadence_floor_breach_alarm_log_path(data_dir);
314    let line = format!("{}\n", chrono::Utc::now().to_rfc3339());
315    match OpenOptions::new().create(true).append(true).open(&path) {
316        Ok(mut f) => {
317            if let Err(e) = f.write_all(line.as_bytes()) {
318                tracing::debug!(error = %e, path = %path.display(), "cadence floor-breach alarm: write failed");
319                return;
320            }
321            let _ = f.flush();
322        }
323        Err(e) => {
324            tracing::debug!(error = %e, path = %path.display(), "cadence floor-breach alarm: open failed");
325        }
326    }
327}
328
329/// Count how many times [`record_cadence_floor_breach_alarm`] has ever
330/// fired for `data_dir` — the lifetime, cross-session, cross-restart alarm
331/// count exposed on `session.get_context_budget` as
332/// `lifetime_cadence_floor_breach_count` (issue #3911).
333///
334/// What: `0` when the file is missing or unreadable (the common,
335/// never-event case); otherwise the number of non-empty lines. Mirrors
336/// [`lifetime_compaction_alarm_count`]'s identical read-fresh-from-disk
337/// contract.
338/// Test: `tests::lifetime_cadence_floor_breach_count_zero_when_missing`,
339/// `tests::lifetime_cadence_floor_breach_count_matches_fire_count`.
340pub fn lifetime_cadence_floor_breach_count(data_dir: &Path) -> u64 {
341    let path = cadence_floor_breach_alarm_log_path(data_dir);
342    let Ok(file) = std::fs::File::open(&path) else {
343        return 0;
344    };
345    std::io::BufReader::new(file)
346        .lines()
347        .map_while(Result::ok)
348        .filter(|l| !l.trim().is_empty())
349        .count() as u64
350}
351
352/// Session-scoped working-context low-water mark, read fresh from the
353/// durable `compression.jsonl` log (issue #3912).
354///
355/// Why: `session.get_context_budget` cached only the MOST RECENT
356/// `ContextBudgetSnapshot` — a single point-in-time value that a coarse,
357/// once-per-`task.run`-call poll can easily miss the real dip on (the
358/// load-realistic soak, epic #3866, observed the RPC report 98-99% while
359/// the durable JSONL recorded a 48-60% floor for the SAME run). Every
360/// cadence/threshold fire already writes its `working_context_pct_after`
361/// to this log (issue #3867) — this is the query that turns "every sample
362/// this session ever produced" into the one number an operator actually
363/// needs: how low did it REALLY get.
364/// What: scans `<data_dir>/compression.jsonl` line by line (best-effort,
365/// matching every other reader in this module — a missing file, an
366/// unreadable line, or a record with no `working_context_pct_after` is
367/// silently skipped, never an error), keeping only rows whose `session_id`
368/// matches `session_id` exactly. Returns `(None, 0)` when the file is
369/// missing or no matching sample carries a percentage; otherwise
370/// `(Some(min), count)` — the lowest `working_context_pct_after` observed
371/// for this session and how many samples that minimum was computed over.
372/// Test: `tests::session_working_context_floor_missing_file_is_none`,
373/// `tests::session_working_context_floor_tracks_minimum_for_session`,
374/// `tests::session_working_context_floor_ignores_other_sessions`.
375pub fn session_working_context_floor(data_dir: &Path, session_id: &str) -> (Option<u8>, usize) {
376    let Ok(file) = std::fs::File::open(compression_log_path(data_dir)) else {
377        return (None, 0);
378    };
379    let mut min_pct: Option<u8> = None;
380    let mut count = 0usize;
381    for line in std::io::BufReader::new(file).lines().map_while(Result::ok) {
382        let Ok(event) = serde_json::from_str::<CompressionEvent>(&line) else {
383            continue;
384        };
385        if event.session_id.as_deref() != Some(session_id) {
386            continue;
387        }
388        let Some(pct) = event.working_context_pct_after else {
389            continue;
390        };
391        count += 1;
392        min_pct = Some(min_pct.map_or(pct, |m| m.min(pct)));
393    }
394    (min_pct, count)
395}
396
397/// Derive `(working_context_pct, overhead_pct)` from a raw token measurement
398/// against a model's context window, mirroring
399/// `cadence::CadenceOutcome::working_context_pct`/`overhead_pct`'s own
400/// saturating arithmetic (never a divide-by-zero, never > 100).
401///
402/// Why: shared by both `AgentLoop::maybe_compact_transcript` (which has no
403/// `CadenceOutcome` to read these from) and callers that already have one,
404/// so the two call sites' percentages can never drift apart from cadence's
405/// own formula.
406/// What: `(None, None)` for a zero `context_window` (percentages are
407/// meaningless without a real window); otherwise `overhead_pct =
408/// (tokens * 100 / context_window).min(100)`, `working_context_pct = 100 -
409/// overhead_pct`.
410/// Test: `tests::context_pcts_zero_window_is_none`,
411/// `tests::context_pcts_matches_saturating_formula`.
412pub fn context_pcts(tokens: usize, context_window: usize) -> (Option<u8>, Option<u8>) {
413    if context_window == 0 {
414        return (None, None);
415    }
416    let overhead_pct = (tokens.saturating_mul(100) / context_window).min(100) as u8;
417    (Some(100 - overhead_pct), Some(overhead_pct))
418}
419
420/// Build and emit the [`SURFACE_TCODE_THRESHOLD`] telemetry record for one
421/// `AgentLoop::maybe_compact_transcript` fire, and — when `cadence_enabled`
422/// — the Slice B durable alarm line alongside it (issues #3867, #3868).
423///
424/// Why: keeps `AgentLoop::maybe_compact_transcript` a thin call rather than
425/// inlining the event construction + percentage derivation at that call
426/// site (this crate's 500-SLOC production file cap).
427/// What: `compaction_event` is always `true` (issue #3867: `true` only for
428/// `tcode-threshold` fires — this function is only ever called on one).
429/// `cadence_enabled` gates the alarm line only — the JSONL record itself is
430/// unconditional, per issue #3867's spec.
431/// Test: `tests::record_threshold_event_writes_jsonl_and_alarm_when_cadence_enabled`,
432/// `tests::record_threshold_event_no_alarm_when_cadence_disabled`.
433#[allow(clippy::too_many_arguments)]
434pub fn record_threshold_event(
435    data_dir: &Path,
436    session_id: Option<String>,
437    tokens_before: usize,
438    tokens_after: usize,
439    context_window: usize,
440    duration_ms: u64,
441    cadence_enabled: bool,
442) {
443    let (working_context_pct_after, overhead_pct_after) =
444        context_pcts(tokens_after, context_window);
445    write_compression_event(
446        data_dir,
447        &CompressionEvent::new(
448            session_id,
449            SURFACE_TCODE_THRESHOLD,
450            DETAIL_THRESHOLD,
451            tokens_before,
452            tokens_after,
453            working_context_pct_after,
454            overhead_pct_after,
455            true,
456            duration_ms,
457            1,
458        ),
459    );
460    if cadence_enabled {
461        record_compaction_alarm(data_dir);
462    }
463}
464
465/// Build and emit the [`SURFACE_TCODE_CADENCE`] telemetry record for one
466/// `AgentLoop::maybe_cadence_compress` call whose `outcome.rounds > 0`
467/// (issue #3867).
468///
469/// Why: same file-size rationale as [`record_threshold_event`].
470/// What: `compaction_event` is always `false` (cadence fires are never the
471/// Slice B alarm signal). Caller must only invoke this when
472/// `outcome.rounds > 0` — see the issue's "only emit when something
473/// actually happened" note.
474/// Test: `tests::record_cadence_event_writes_jsonl`.
475#[allow(clippy::too_many_arguments)]
476pub fn record_cadence_event(
477    data_dir: &Path,
478    session_id: Option<String>,
479    tokens_before: usize,
480    tokens_after: usize,
481    context_window: usize,
482    duration_ms: u64,
483    rounds: usize,
484) {
485    let (working_context_pct_after, overhead_pct_after) =
486        context_pcts(tokens_after, context_window);
487    write_compression_event(
488        data_dir,
489        &CompressionEvent::new(
490            session_id,
491            SURFACE_TCODE_CADENCE,
492            DETAIL_CADENCE,
493            tokens_before,
494            tokens_after,
495            working_context_pct_after,
496            overhead_pct_after,
497            false,
498            duration_ms,
499            rounds,
500        ),
501    );
502}
503
504/// Build and emit the [`SURFACE_TCODE_CADENCE_FLOOR_BREACH`] telemetry
505/// record plus the durable [`record_cadence_floor_breach_alarm`] line, for
506/// one `AgentLoop::maybe_cadence_compress` call whose
507/// `CadenceOutcome::within_budget` was `false` (issue #3911).
508///
509/// Why: `cadence::enforce_budget`'s own "documented floor" case (active
510/// zone shrunk to zero, still over the overhead cap) previously only
511/// logged `tracing::warn!` from deep inside that function — no durable
512/// record, no counter, and critically NOT the same alarm the #2308
513/// threshold compactor's OWN breach uses
514/// (`record_threshold_event`/`lifetime_compaction_alarm_count`), because
515/// that alarm is keyed to a MECHANICALLY INDEPENDENT trigger: threshold
516/// fires only once the raw transcript crosses 75% of the context window
517/// (`CompactionConfig::for_context_window`), a laxer bound than cadence's
518/// own 40%-overhead enforcement cap — so by the time cadence has already
519/// compacted as hard as it structurally can (`enforce_budget` shrinks the
520/// active zone to zero, re-compacting at every step) and still exceeds
521/// its OWN cap, the transcript is nowhere near threshold's separate,
522/// higher bound. The load-realistic soak (epic #3866, PR #3909) proved
523/// this empirically: a 48% floor breach produced zero threshold events,
524/// zero alarm-count increments, and zero visible signal anywhere but a
525/// stderr line. This function is the durable, countable trigger that
526/// closes that gap — always called (unconditionally, unlike
527/// `record_threshold_event`'s cadence-gated alarm) because this call site
528/// only exists on the cadence-enabled path in the first place
529/// (`AgentLoop::maybe_cadence_compress` already returns early when
530/// `self.config.cadence` is `None`).
531/// What: writes a `compaction_event: true` JSONL row (this genuinely IS an
532/// alarm-worthy event — the same semantic `record_threshold_event` uses
533/// `true` for) tagged `surface: "tcode-cadence-floor-breach"`, then
534/// unconditionally appends the durable alarm line.
535///
536/// (post-review fix, issue #3911) `working_context_pct_after`/
537/// `overhead_pct_after` are ALWAYS `None` on this row, deliberately — NOT
538/// derived from `tokens_after`/`context_window` the way every other
539/// surface's percentages are. Why: `AgentLoop::maybe_cadence_compress`
540/// calls [`record_cadence_event`] unconditionally whenever `outcome.rounds
541/// > 0` (which every floor breach satisfies — `enforce_budget` always ran
542/// at least one round to reach `within_budget: false`) BEFORE this
543/// function, for the exact same turn, with the exact same
544/// `outcome.overhead_tokens`/`context_window`. Computing the percentage
545/// here too would write a SECOND row carrying an IDENTICAL
546/// `working_context_pct_after` for one real measurement — exactly the
547/// double-count a code-review pass caught: `compression_report.py`'s
548/// `compute_context_floor` (and this crate's own
549/// `session_working_context_floor`, issue #3912) aggregate every row with
550/// a non-`None` percentage with no surface-based dedup, so a single
551/// breach was being counted TWICE toward the observed floor (measured: a
552/// soak run with 21 real breaches reported 42 below-target samples).
553/// Leaving these `None` here is the single-point fix: every existing and
554/// future consumer that filters on "has a working_context_pct_after
555/// sample" — not just this function's two current call sites — inherits
556/// the fix for free, rather than requiring each one to separately learn to
557/// exclude this surface. The paired `tcode-cadence` row is the ONE
558/// authoritative percentage sample for this turn; this row's job is only
559/// to durably flag THAT a breach happened (`compaction_event: true`,
560/// `tokens_before`/`tokens_after`/`rounds` are still real and useful for
561/// debugging), not to re-report the same number under a second surface.
562/// Test: `tests::record_cadence_floor_breach_writes_jsonl_and_alarm`,
563/// `tests::record_cadence_floor_breach_never_double_counts_the_floor`.
564#[allow(clippy::too_many_arguments)]
565pub fn record_cadence_floor_breach(
566    data_dir: &Path,
567    session_id: Option<String>,
568    tokens_before: usize,
569    tokens_after: usize,
570    _context_window: usize,
571    duration_ms: u64,
572    rounds: usize,
573) {
574    write_compression_event(
575        data_dir,
576        &CompressionEvent::new(
577            session_id,
578            SURFACE_TCODE_CADENCE_FLOOR_BREACH,
579            DETAIL_CADENCE_FLOOR_BREACH,
580            tokens_before,
581            tokens_after,
582            None,
583            None,
584            true,
585            duration_ms,
586            rounds,
587        ),
588    );
589    record_cadence_floor_breach_alarm(data_dir);
590}
591
592/// Test-only helper: run `f` with [`DATA_DIR_ENV_VAR`] pointed at `dir`,
593/// serialized on [`DATA_DIR_ENV_LOCK`] so parallel `cargo test` threads never
594/// race each other's env mutation — mirrors
595/// `cadence_env_helper::with_cadence_env`'s identical rationale.
596///
597/// Why: production telemetry always writes/reads real `~/.trusty-code`; any
598/// test exercising `AgentLoop::maybe_compact_transcript`/
599/// `maybe_cadence_compress` or `SessionRegistry::record_context_budget` end
600/// to end needs an isolated directory instead, without a second production
601/// code path.
602#[cfg(test)]
603pub(crate) async fn with_data_dir_env<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
604    let _guard = DATA_DIR_ENV_LOCK.lock().await;
605    // SAFETY: test-only env mutation, serialized by `DATA_DIR_ENV_LOCK`.
606    unsafe {
607        std::env::set_var(DATA_DIR_ENV_VAR, dir);
608    }
609    let result = f();
610    unsafe {
611        std::env::remove_var(DATA_DIR_ENV_VAR);
612    }
613    result
614}
615
616/// Async twin of [`with_data_dir_env`] for loop-level tests that must await
617/// an `AgentLoop::run`/`run_with_transcript` call WHILE the env var is set
618/// (a plain `FnOnce() -> T` closure cannot itself `.await`).
619///
620/// Why: without this, every loop-integration test needed to hand-inline the
621/// lock/set/run/clear sequence, duplicating the `unsafe` env mutation at
622/// each call site. Centralising it here keeps that `unsafe` block in exactly
623/// one place, matching [`with_data_dir_env`]'s same rationale.
624#[cfg(test)]
625pub(crate) async fn with_data_dir_env_fut<T>(
626    dir: &Path,
627    fut: impl std::future::Future<Output = T>,
628) -> T {
629    let _guard = DATA_DIR_ENV_LOCK.lock().await;
630    // SAFETY: test-only env mutation, serialized by `DATA_DIR_ENV_LOCK`.
631    unsafe {
632        std::env::set_var(DATA_DIR_ENV_VAR, dir);
633    }
634    let result = fut.await;
635    unsafe {
636        std::env::remove_var(DATA_DIR_ENV_VAR);
637    }
638    result
639}
640
641/// Test-only helper: a fresh, uniquely-named, already-created temp directory
642/// under `std::env::temp_dir()`, for tests that need an isolated telemetry
643/// write target.
644///
645/// Why: every loop-integration test that isolates its telemetry writes
646/// previously duplicated this exact `process_id + nanosecond-timestamp`
647/// naming scheme at its own call site (`compression_telemetry_tests.rs`,
648/// `telemetry_tests.rs`, `tests/cadence.rs`'s `forced_degradation_*` test).
649/// `pub(crate)` so every `agent_loop` test submodule can share ONE
650/// implementation instead of re-deriving the same uniqueness scheme —
651/// consolidating them is also what makes issue #3902's fix
652/// (`AgentLoopConfig::telemetry_data_dir` injection replacing the raced
653/// `TCODE_TELEMETRY_DATA_DIR` env var) a one-line call at each of the
654/// newly-isolated call sites instead of a repeated inline block.
655/// What: `label` only needs to distinguish this call site from sibling
656/// calls in the same test binary — the pid + nanosecond timestamp already
657/// guarantees cross-process and cross-call uniqueness on its own.
658#[cfg(test)]
659pub(crate) fn test_temp_dir(label: &str) -> PathBuf {
660    let dir = std::env::temp_dir().join(format!(
661        "tcode-telemetry-{label}-{}-{}",
662        std::process::id(),
663        std::time::SystemTime::now()
664            .duration_since(std::time::UNIX_EPOCH)
665            .unwrap()
666            .as_nanos()
667    ));
668    std::fs::create_dir_all(&dir).unwrap();
669    dir
670}
671
672#[cfg(test)]
673#[path = "telemetry_tests.rs"]
674mod tests;