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