Skip to main content

trusty_code/logging/
mod.rs

1//! Tracing and logging initialisation for tcode.
2//!
3//! Why: All tcode binaries and the library's test harness need consistent
4//! tracing initialisation that writes to stderr (never stdout — stdout is the
5//! API transport channel). Centralising it here prevents duplicated setup and
6//! ensures the `try_init` pattern is used everywhere so test binaries remain
7//! idempotent.
8//! What: `init_tracing` initialises the global tracing subscriber from the
9//! `RUST_LOG` env var. `init_tracing_for_test` is a lightweight variant for
10//! test binaries that silently drops duplicate init errors.
11//! Test: `init_tracing_for_test_is_idempotent` calls the function twice and
12//! asserts no panic.
13//!
14//! ## Log-level convention (#2857)
15//!
16//! trusty-code makes control-flow decisions that change a run's outcome —
17//! caps tripping, retries, delegation refusals, fallbacks, truncations,
18//! skips, gate interceptions. Every such decision point MUST log at the
19//! level below when it fires; the organising principle is:
20//!
21//! - **`warn!`** — the decision silently changes the run's outcome (a cap
22//!   trips, a retry budget is exhausted, a gate refuses/intercepts an
23//!   action, a floor is exceeded). Minimum level for anything that could
24//!   otherwise only be diagnosed via cross-run forensics (the #2852 class
25//!   of bug this ticket exists to prevent).
26//! - **`info!`** — a degradation the model or user acts on, but the run
27//!   proceeds normally (a fallback lane serves results, a redundant
28//!   re-run is suppressed, a budget truncation drops lowest-scored
29//!   content, cadence compression fires on schedule).
30//! - **`debug!`** — detail useful for tracing a run's mechanics but not
31//!   itself a decision that changes the outcome (byte-level truncation of
32//!   a single tool's output, already surfaced in-band to the model).
33//! - **`error!`** — reserved for regression signals: a safeguard fired
34//!   under conditions where it should have been structurally unreachable
35//!   (e.g. threshold compaction firing while the cadence compressor is
36//!   supposed to keep the transcript under budget at all times).
37//!
38//! All logs go to **stderr** via `tracing` (never stdout — see the module
39//! doc above) and are filtered by `RUST_LOG`, falling back to `info` when it
40//! is unset or invalid.
41//!
42//! **Logs vs. events:** structured [`crate::events`] are telemetry for the
43//! UI (a typed, machine-consumed fact stream); `tracing` logs here are for
44//! an operator reading stderr while debugging a run. Both may describe the
45//! same underlying fact, but one must never substitute for the other — an
46//! event emission does not excuse a silent decision point from also logging.
47
48use std::path::PathBuf;
49
50use tracing_subscriber::EnvFilter;
51use tracing_subscriber::Layer as _;
52use tracing_subscriber::layer::SubscriberExt as _;
53use tracing_subscriber::util::SubscriberInitExt as _;
54
55/// Build the tracing filter, falling back to [`DEFAULT_LOG_LEVEL`].
56///
57/// Why: `EnvFilter::from_default_env` yields an EMPTY directive set when
58/// `RUST_LOG` is unset or malformed, which filters everything below `error`
59/// and silences the `warn!` decision points this module's convention requires.
60/// What: parses `RUST_LOG`; on any parse failure builds a filter from
61/// [`DEFAULT_LOG_LEVEL`] instead.
62/// Test: `tests/logging_e2e.rs`.
63fn env_filter() -> EnvFilter {
64    EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(DEFAULT_LOG_LEVEL))
65}
66
67/// Initialise the global tracing subscriber.
68///
69/// Why: All daemons and CLI entry points call this once at startup to ensure
70/// log output is consistently routed to stderr with the `RUST_LOG` filter.
71/// What: Installs a stderr-bound fmt subscriber with [`env_filter`].
72/// Panics if called twice (use `init_tracing_for_test` in test binaries).
73/// Test: Called in `main.rs`; correctness is verified by observing log output.
74pub fn init_tracing() {
75    tracing_subscriber::fmt()
76        .with_env_filter(env_filter())
77        .with_writer(std::io::stderr)
78        .init();
79}
80
81/// Initialise the global tracing subscriber, silently ignoring duplicate inits.
82///
83/// Why: Test binaries may link multiple test modules that all call setup code.
84/// `try_init` returns an error on the second call instead of panicking, so
85/// test runs remain stable regardless of execution order.
86/// What: Calls `try_init()`; swallows the error if already initialised.
87/// Test: `init_tracing_for_test_is_idempotent`.
88pub fn init_tracing_for_test() {
89    let _ = tracing_subscriber::fmt()
90        .with_env_filter(env_filter())
91        .with_writer(std::io::stderr)
92        .try_init();
93}
94
95/// Log level used when no `RUST_LOG` env var is set.
96///
97/// Why: Documents and centralises the default so operators know what to expect
98/// without reading source.
99/// What: A static string literal used by [`env_filter`] as its real fallback.
100/// Test: `tests/logging_e2e.rs` covers unset and invalid `RUST_LOG` values.
101pub const DEFAULT_LOG_LEVEL: &str = "info";
102
103/// Basename `tracing_appender::rolling::daily` rotates:
104/// `tcode.log.YYYY-MM-DD` (#6537).
105pub const FILE_LOG_BASENAME: &str = "tcode.log";
106
107/// Directory tcode's own rotating file log is written to: `~/.trusty-code/logs`.
108///
109/// Why (#6537): before this, `init_tracing` wrote to stderr only, which
110/// nothing durable ever collects — the epic's whole point (cloud log drain,
111/// #6533) needs a file to drain. This mirrors trusty-mpm's own
112/// `~/.trusty-mpm/logs` layout, under the private-state directory
113/// [`crate::paths::private_state`] already established rather than a new
114/// root.
115/// What: `crate::paths::private_state::private_state_dir().join("logs")`.
116/// Test: `tests::file_log_dir_is_under_private_state`.
117pub fn file_log_dir() -> PathBuf {
118    crate::paths::private_state::private_state_dir().join("logs")
119}
120
121/// Initialise tracing for `tcode serve`: stderr (unchanged, MCP-framing-safe)
122/// PLUS a daily-rotating file layer under [`file_log_dir`] (#6537).
123///
124/// Why: only the long-running `serve` daemon accumulates enough log volume to
125/// be worth draining — mirrors trusty-mpm's own daemon/CLI split
126/// (`bin/tm/tracing_setup.rs`), where a short-lived CLI invocation gets the
127/// lighter [`init_tracing`] instead. A file-directory creation failure (a
128/// read-only home, a full disk) degrades to stderr-only rather than failing
129/// daemon startup. A prior version created the directory with a raw
130/// `create_dir_all`, which applies the process umask and commonly leaves
131/// `0755`/`0644` — code-review fix (#6537): this now routes through the same
132/// private-state hardening every other writer under `~/.trusty-code` uses
133/// (#6999), so the directory is `0700` and each rolled file `0600`.
134/// What: builds a `tracing_subscriber::registry()` with a stderr `fmt` layer
135/// and, when the log directory is creatable, a non-blocking daily file `fmt`
136/// layer (`with_ansi(false)`, since a rotated file is read by tooling, not a
137/// terminal). The directory is created and tightened via
138/// [`crate::paths::private_state::ensure_private_state_dir`] (the
139/// `~/.trusty-code` root) then
140/// [`crate::paths::private_state::ensure_dir`] (the `logs` subdirectory
141/// itself); [`chmod_log_files_owner_only`] then tightens whichever file
142/// `tracing_appender::rolling::daily` just opened for today. Returns the
143/// file layer's `WorkerGuard` — the caller MUST hold it for the process
144/// lifetime; dropping it early silently discards buffered log records.
145/// Test: `tests::file_log_dir_is_under_private_state` covers the path
146/// computation this function depends on; installing a second GLOBAL
147/// subscriber in-process (this function's own behavior) cannot itself run in
148/// the shared `--lib` test binary alongside `begin_capture`'s `try_init` —
149/// see that test's own doc comment. The directory/file mode guarantee is
150/// covered by `tests/logging_e2e.rs::file_log_dir_and_current_file_are_owner_only`
151/// (a subprocess with `HOME` pointed at a tempdir, for the same reason).
152pub fn init_tracing_with_file_log() -> Option<tracing_appender::non_blocking::WorkerGuard> {
153    let stderr_layer = tracing_subscriber::fmt::layer()
154        .with_writer(std::io::stderr)
155        .with_filter(env_filter());
156
157    let log_dir = file_log_dir();
158    let create_result = crate::paths::private_state::ensure_private_state_dir()
159        .and_then(|_| crate::paths::private_state::ensure_dir(&log_dir));
160    let (file_layer, guard) = match create_result {
161        Ok(()) => {
162            let appender = tracing_appender::rolling::daily(&log_dir, FILE_LOG_BASENAME);
163            chmod_log_files_owner_only(&log_dir);
164            let (non_blocking, guard) = tracing_appender::non_blocking(appender);
165            let layer = tracing_subscriber::fmt::layer()
166                .with_writer(non_blocking)
167                .with_ansi(false)
168                .with_filter(env_filter());
169            (Some(layer), Some(guard))
170        }
171        Err(e) => {
172            eprintln!(
173                "tcode: cannot create log directory {}: {e} (stderr-only for this run)",
174                log_dir.display()
175            );
176            (None, None)
177        }
178    };
179
180    tracing_subscriber::registry()
181        .with(stderr_layer)
182        .with(file_layer)
183        .init();
184
185    guard
186}
187
188/// Tighten every regular file already in `log_dir` to owner-only (#6537).
189///
190/// Why: `tracing_appender::rolling::daily` opens today's file the moment the
191/// appender is constructed — before this function runs — with whatever mode
192/// the process umask leaves (commonly `0644`). Chmod'ing every entry
193/// currently in the directory, rather than computing tomorrow's filename
194/// itself, stays correct regardless of `tracing_appender`'s internal naming.
195/// KNOWN LIMITATION: a file this appender creates on a LATER day's rotation,
196/// after this function has already returned, is never chmod'd by it — this
197/// daemon is expected to restart at least daily in practice, and each
198/// restart re-tightens whatever file is current at that point.
199/// What: on Unix, chmod every regular file directly under `log_dir` to
200/// `0600`, logging a `warn` (never failing) on any entry it cannot stat or
201/// chmod. No-op on non-Unix targets, which have no comparable mode bits.
202/// Test: `tests/logging_e2e.rs::file_log_dir_and_current_file_are_owner_only`.
203#[cfg(unix)]
204fn chmod_log_files_owner_only(log_dir: &std::path::Path) {
205    use std::os::unix::fs::PermissionsExt;
206    let Ok(entries) = std::fs::read_dir(log_dir) else {
207        return;
208    };
209    for entry in entries.flatten() {
210        let path = entry.path();
211        let Ok(metadata) = entry.metadata() else {
212            continue;
213        };
214        if !metadata.is_file() {
215            continue;
216        }
217        if let Err(e) = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)) {
218            tracing::warn!(
219                path = %path.display(),
220                error = %e,
221                "could not tighten a tcode log file to 0600; its contents may \
222                 be readable by other users on this machine"
223            );
224        }
225    }
226}
227
228#[cfg(not(unix))]
229fn chmod_log_files_owner_only(_log_dir: &std::path::Path) {}
230
231// ── Tests ─────────────────────────────────────────────────────────────────────
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    /// `init_tracing_for_test` must be idempotent across multiple calls.
238    ///
239    /// Why: Test binaries are often multi-crate and may call init from several
240    /// setup functions; a panic on re-init would break the test suite. (#2857)
241    /// This is the ONLY other site in this crate's `--lib` test binary that
242    /// installs a GLOBAL tracing subscriber via `try_init`. Calling
243    /// `crate::test_support::begin_capture()` first guarantees the #2857
244    /// capture module's own `set_global_default` call always wins that
245    /// one-shot race — this test's own `try_init()` then simply no-ops
246    /// (already documented/expected behaviour), regardless of which test the
247    /// harness happens to schedule first.
248    /// What: Calls `init_tracing_for_test` twice; asserts no panic.
249    /// Test: This test.
250    #[test]
251    fn init_tracing_for_test_is_idempotent() {
252        crate::test_support::begin_capture();
253        init_tracing_for_test();
254        init_tracing_for_test(); // second call must not panic
255    }
256
257    /// The default log level constant is non-empty.
258    ///
259    /// Why: Guard against accidental empty string.
260    /// What: Asserts `DEFAULT_LOG_LEVEL` is non-empty.
261    /// Test: This test.
262    #[test]
263    fn default_log_level_is_non_empty() {
264        assert!(!DEFAULT_LOG_LEVEL.is_empty());
265    }
266
267    /// `file_log_dir` sits under the crate's own private-state directory,
268    /// never a bespoke root (#6537).
269    ///
270    /// Why: `init_tracing_with_file_log` installs a GLOBAL subscriber, so it
271    /// cannot itself be called from this shared test binary without racing
272    /// `begin_capture`'s own `try_init` — this test covers the path
273    /// computation, which is what the log-drain source (`crate::log_drain`)
274    /// actually depends on.
275    #[test]
276    fn file_log_dir_is_under_private_state() {
277        let dir = file_log_dir();
278        assert!(dir.ends_with("logs"), "{}", dir.display());
279        assert!(
280            dir.to_string_lossy().contains(".trusty-code"),
281            "{}",
282            dir.display()
283        );
284    }
285}