Skip to main content

trusty_code/llm/debug_capture/
mod.rs

1//! Opt-in wire-level LLM round-trip capture for orchestration debugging
2//! (#2264).
3//!
4//! Why: `run_task::recorder::RecordingLlmClient` already produces
5//! `tcode_report.json`'s lightweight transcript (role, assistant text, tool
6//! call NAMES, usage) — enough to render a human report, but not enough to
7//! root-cause WHY the model made a given decision. Debugging turn-count
8//! spikes or re-delegation loops needs the full wire-level exchange: the
9//! entire system prompt, tool schemas, and message history actually sent
10//! (including prompt-cache markers), the full assistant response (text AND
11//! every tool-call's arguments, not just its name), and — via the next
12//! request's own message history — the tool results fed back. This module
13//! is that capture, gated behind `TCODE_DEBUG_TRANSCRIPT` so it costs
14//! nothing when unset.
15//! What: [`DebugCaptureSink`] resolves the env var once per run and owns the
16//! output file + a monotonic turn counter shared across every wrapped
17//! client for that run; [`DebugCaptureLlmClient`] is a transparent
18//! `InferenceAdapter` decorator that appends one JSONL [`DebugCaptureRecord`]
19//! per `chat()` call (request verbatim, response verbatim including
20//! tool-call arguments, or the error, plus usage) before forwarding to the
21//! wrapped inner client; [`wrap_with_debug_capture`] is the single call-site
22//! helper — when no sink is configured it returns `inner` UNCHANGED (no
23//! allocation, no indirection), which is what makes the default (unset)
24//! path zero-overhead. Wrapping happens at the `InferenceAdapter::chat`
25//! boundary — the same object-safe seam `DispatchingLlmClient` (OpenRouter +
26//! Bedrock) and `RecordingLlmClient` already share across both the
27//! in-process CLI path (`run_task::execute_run_task`) and the daemon path
28//! (`task::executor::run_and_record`) — so this is the ONE place capture
29//! logic lives, never duplicated per-transport or per-run-path.
30//!
31//! SAFETY / SENSITIVITY NOTE: a capture file is a byte-for-byte dump of every
32//! prompt and response in a run — it WILL contain the full task description,
33//! any file contents the model read or wrote, and full tool-call arguments
34//! (e.g. `write_file` bodies). Treat capture files like source code / build
35//! logs, not something to paste into a chat or share casually. This module
36//! never serialises transport/auth headers or API keys — only the
37//! already-constructed `ChatRequest`/`ChatResponse` BODY types, which never
38//! carry credentials (see `llm::client::LlmClient::chat`, which injects the
39//! `Authorization` header separately, after the body is built).
40//! Test: `debug_capture::tests::*` — env-unset is a no-op (zero behaviour
41//! change), env-set produces a JSONL record with the full request messages,
42//! tool-call arguments, and tool results (visible in the NEXT turn's message
43//! history), directory-mode picks a fresh per-run file, and a failed inner
44//! `chat()` call is still recorded (with `error` set, `response: null`) — as
45//! is a failed `chat_stream()`, at BOTH the stream-open handshake and
46//! mid-flight, with the original error's classification intact (#4425).
47
48use std::fs::OpenOptions;
49use std::io::Write;
50use std::path::{Path, PathBuf};
51use std::sync::atomic::{AtomicU64, Ordering};
52use std::sync::{Arc, Mutex};
53
54use async_trait::async_trait;
55use serde::Serialize;
56
57use futures_util::StreamExt;
58
59use super::{
60    ChatRequest, ChatResponse, ChatStream, ChatStreamEvent, InferenceAdapter, InferenceError,
61    StreamAssembly,
62};
63use crate::perf::TokenUsage;
64
65#[cfg(test)]
66#[path = "tests.rs"]
67mod tests;
68
69/// Environment variable that turns capture on: a file path (records are
70/// appended) or a directory path (one fresh file per run).
71///
72/// Why: opt-in via env var (not a CLI flag) is the primary/required
73/// mechanism per #2264 — the bake-off runner sets env vars, not flags, and
74/// it must work identically whether `run-task` executes in-process
75/// (`--legacy-in-process`) or spawns the daemon subprocess (the default thin
76/// client) — a spawned child inherits the parent's environment automatically
77/// (`cli_client::stdio::StdioRpcClient::spawn` never clears it), so setting
78/// this once in the invoking shell covers every execution path with no
79/// extra plumbing.
80/// What: read once per run via [`DebugCaptureSink::from_env`].
81pub const ENV_VAR: &str = "TCODE_DEBUG_TRANSCRIPT";
82
83/// One recorded LLM round-trip: the full request, the full response (or the
84/// error), and per-turn metadata.
85///
86/// Why: This is the shape that closes the `tcode_report.json` gap (#2264) —
87/// unlike `run_task::recorder::TurnRecord` (role + text + tool-call NAMES),
88/// this carries the entire `ChatRequest` (system prompt, tool schemas, full
89/// message history, cache_control markers) and the entire `ChatResponse`
90/// (assistant text AND every tool-call's arguments), so a reader can see
91/// exactly what the model was shown and exactly what it decided, turn by
92/// turn.
93/// What: `turn_index` is a monotonic counter shared by every role in one run
94/// (so interleaved pm/engineer turns stay globally ordered); `role` is the
95/// delegation segment label (`"pm"` or the engineer's agent name, e.g.
96/// `"python-engineer"` — this crate delegates to exactly one engineer role
97/// per run today, so `role` doubles as the segment identifier); `request` is
98/// the verbatim `ChatRequest` serialised with its normal wire `Serialize`
99/// impl (so `ChatMessage`'s cache_control content-block shape round-trips
100/// exactly as sent); `response` is `Some` on success, `None` on failure (in
101/// which case `error` carries the `InferenceError`'s `Display` text and
102/// `error_retryable`/`error_alarm` carry its CLASSIFICATION); `usage` is
103/// the zero value on failure.
104///
105/// #4425: `error_retryable`/`error_alarm` exist because `error` is a `String`
106/// — the record cannot hold an `InferenceError` itself (the shared enum is not
107/// `Serialize`/`Deserialize`), so without them a reader would have to
108/// re-classify by pattern-matching Display text. They are the transcript's
109/// machine-readable copy of [`InferenceError::is_retryable`] /
110/// [`InferenceError::is_alarm`], recorded from the ORIGINAL error value.
111/// Test: `debug_capture::tests::record_serialises_full_request_and_response`,
112/// `debug_capture::tests::stream_error_preserves_the_original_error_classification`.
113#[derive(Debug, Clone, Serialize)]
114struct DebugCaptureRecord<'a> {
115    turn_index: u64,
116    role: &'a str,
117    timestamp: String,
118    request: &'a ChatRequest,
119    response: Option<ChatResponse>,
120    error: Option<String>,
121    error_retryable: Option<bool>,
122    error_alarm: Option<bool>,
123    usage: TokenUsage,
124}
125
126/// Shared, thread-safe sink for one run's debug-capture output.
127///
128/// Why: a directory-mode capture must produce ONE file per run shared by
129/// BOTH the pm and engineer recorders (mirroring
130/// `run_task::recorder::SharedTranscript`'s "one shared accumulator per
131/// run" shape) so the file's turn order reflects the true interleaving of
132/// pm/engineer calls, not two disjoint per-role files.
133/// What: Wraps a `Mutex<File>` (append-mode) and an `AtomicU64` turn
134/// counter. Constructed once per run via [`Self::from_env`] and cloned
135/// (`Arc`) into every [`DebugCaptureLlmClient`] wrapping that run's clients.
136/// Test: `debug_capture::tests::*`.
137pub struct DebugCaptureSink {
138    file: Mutex<std::fs::File>,
139    turn_counter: AtomicU64,
140}
141
142impl DebugCaptureSink {
143    /// Resolve [`ENV_VAR`] and open (or create) the capture file, if set.
144    ///
145    /// Why: the single per-run construction point every call site
146    /// (`run_task::execute_run_task`, `task::executor::run_and_record`)
147    /// invokes exactly once; a capture failure (bad path, permissions) must
148    /// degrade the run to "no capture" rather than abort it — this is
149    /// debugging tooling, not a correctness-critical dependency.
150    /// What: `None` when [`ENV_VAR`] is unset or empty (the zero-overhead
151    /// default). Otherwise resolves the path (directory → fresh per-run
152    /// file; anything else → literal file, appended) and opens it,
153    /// returning `Some(Arc<Self>)` on success or `None` (after printing an
154    /// actionable stderr warning — never stdout, which must stay clean for
155    /// MCP JSON-RPC framing) if the file could not be opened.
156    /// Test: `debug_capture::tests::from_env_none_when_unset`,
157    /// `debug_capture::tests::from_env_opens_literal_file_path`,
158    /// `debug_capture::tests::from_env_directory_gets_fresh_per_run_file`.
159    pub fn from_env() -> Option<Arc<Self>> {
160        let raw = std::env::var(ENV_VAR).ok().filter(|s| !s.is_empty())?;
161        match Self::open(Path::new(&raw)) {
162            Ok(sink) => Some(Arc::new(sink)),
163            Err(e) => {
164                eprintln!(
165                    "tcode: {ENV_VAR}='{raw}' but the debug-capture file could not be opened \
166                     ({e}) — continuing without capture"
167                );
168                None
169            }
170        }
171    }
172
173    /// Resolve `raw` to a concrete file path and open it for appending.
174    ///
175    /// Why: split from `from_env` so path resolution is independently
176    /// testable without touching the process environment.
177    /// What: creates any missing parent directories, then opens
178    /// (create-if-missing, append) the resolved path.
179    fn open(raw: &Path) -> std::io::Result<Self> {
180        let path = resolve_capture_path(raw);
181        if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
182            std::fs::create_dir_all(parent)?;
183        }
184        let file = OpenOptions::new().create(true).append(true).open(&path)?;
185        Ok(Self {
186            file: Mutex::new(file),
187            turn_counter: AtomicU64::new(0),
188        })
189    }
190
191    /// Claim the next monotonic turn index for this run.
192    ///
193    /// Why: `fetch_add` under one shared counter is what keeps pm/engineer
194    /// turns in one globally-ordered sequence, matching the ORDER they were
195    /// actually dispatched (not just the order each role's own calls ran
196    /// in).
197    /// What: Returns the previous counter value, then increments.
198    fn next_turn_index(&self) -> u64 {
199        self.turn_counter.fetch_add(1, Ordering::SeqCst)
200    }
201
202    /// Serialise and append one round-trip record.
203    ///
204    /// Why: centralises the "build the record, serialise, append a line"
205    /// sequence so [`DebugCaptureLlmClient::chat`] stays a thin dispatch
206    /// wrapper; failures here (serialisation, disk I/O) are logged to
207    /// stderr and otherwise swallowed — a debug-capture write must never
208    /// fail the underlying LLM call it is observing.
209    /// What: builds a [`DebugCaptureRecord`] from `req` and `result`
210    /// (cloning the `ChatResponse` on success; recording the ORIGINAL
211    /// `InferenceError`'s `Display` text AND its retryable/alarm
212    /// classification on failure), serialises it to one JSON line, and
213    /// appends it (with a trailing newline) to the sink's file under its
214    /// mutex.
215    ///
216    /// #4425: takes `Result<&ChatResponse, &InferenceError>` rather than
217    /// `&Result<..>` so a caller holding only a BORROWED error (the streaming
218    /// path, whose stream items are `&Result<ChatStreamEvent, InferenceError>`)
219    /// can record the error it actually observed. `InferenceError` is neither
220    /// `Clone` nor cheap to reconstruct, and the previous `&Result<..>`
221    /// signature forced that caller to synthesise a stand-in
222    /// `InferenceError::Transport(e.to_string())` — which silently rewrote
223    /// every error's variant, so `is_retryable`/`is_alarm` recorded below were
224    /// the WRAPPER's classification, not the real failure's.
225    fn record(
226        &self,
227        turn_index: u64,
228        role: &str,
229        req: &ChatRequest,
230        result: Result<&ChatResponse, &InferenceError>,
231    ) {
232        let (response, error, error_retryable, error_alarm, usage) = match result {
233            Ok(resp) => (
234                Some(resp.clone()),
235                None,
236                None,
237                None,
238                crate::llm::token_usage(resp),
239            ),
240            Err(e) => (
241                None,
242                Some(e.to_string()),
243                Some(e.is_retryable()),
244                Some(e.is_alarm()),
245                TokenUsage::default(),
246            ),
247        };
248        let record = DebugCaptureRecord {
249            turn_index,
250            role,
251            timestamp: chrono::Utc::now().to_rfc3339(),
252            request: req,
253            response,
254            error,
255            error_retryable,
256            error_alarm,
257            usage,
258        };
259        let line = match serde_json::to_string(&record) {
260            Ok(s) => s,
261            Err(e) => {
262                eprintln!("tcode: debug-capture record serialisation failed: {e}");
263                return;
264            }
265        };
266        // A poisoned lock must not abort the run; recover the inner file
267        // handle and keep writing (mirrors `RecordingLlmClient`'s "a
268        // poisoned lock is a no-op record, not a panic" convention).
269        let mut guard = match self.file.lock() {
270            Ok(g) => g,
271            Err(poisoned) => poisoned.into_inner(),
272        };
273        if let Err(e) = writeln!(guard, "{line}") {
274            eprintln!("tcode: debug-capture write failed: {e}");
275        }
276    }
277}
278
279/// Resolve the configured [`ENV_VAR`] value to a concrete capture file path.
280///
281/// Why: the env var doubles as either a literal file (append across the
282/// whole process lifetime) or a directory (one fresh file per run) per
283/// #2264's requirements; this is the single place that distinction is made.
284/// What: `raw` is treated as a directory when it already exists as one, OR
285/// its string form ends with the platform path separator (so a caller can
286/// force directory semantics for a not-yet-created directory, e.g.
287/// `TCODE_DEBUG_TRANSCRIPT=/tmp/captures/`). In that case returns
288/// `raw.join("tcode-debug-<uuid>.jsonl")`; otherwise returns `raw` unchanged
289/// (literal file path).
290/// Test: `debug_capture::tests::resolve_capture_path_*`.
291fn resolve_capture_path(raw: &Path) -> PathBuf {
292    let looks_like_dir = raw.is_dir() || raw.to_string_lossy().ends_with(std::path::MAIN_SEPARATOR);
293    if looks_like_dir {
294        raw.join(format!("tcode-debug-{}.jsonl", uuid::Uuid::new_v4()))
295    } else {
296        raw.to_path_buf()
297    }
298}
299
300/// A transparent `InferenceAdapter` decorator that appends a full wire-level
301/// record of each round-trip to a shared [`DebugCaptureSink`].
302///
303/// Why: the same "wrap, observe, forward unchanged" shape
304/// `run_task::recorder::RecordingLlmClient` already uses — this decorator
305/// sits at the identical `InferenceAdapter::chat` seam, so it is transport-
306/// and run-path-agnostic by construction (whatever `inner` resolves to —
307/// `DispatchingLlmClient` routing to OpenRouter or Bedrock, or a test mock —
308/// is invisible to this wrapper).
309/// What: Holds the inner client, a role label, and the shared sink. `chat`
310/// calls the inner client, records the request/response(or error) pair
311/// under the next turn index, and returns the inner result unchanged
312/// (including on error — the caller sees the exact same `Result` it would
313/// have without capture enabled).
314/// Test: `debug_capture::tests::*`.
315struct DebugCaptureLlmClient {
316    inner: Arc<dyn InferenceAdapter>,
317    role: String,
318    sink: Arc<DebugCaptureSink>,
319}
320
321#[async_trait]
322impl InferenceAdapter for DebugCaptureLlmClient {
323    // #4425: a transparent decorator must report the WRAPPED backend's identity,
324    // never its own.
325    crate::llm::delegating_adapter_identity!(inner);
326
327    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
328        let turn_index = self.sink.next_turn_index();
329        let result = self.inner.chat(req).await;
330        self.sink
331            .record(turn_index, &self.role, req, result.as_ref());
332        result
333    }
334
335    /// Forward the STREAMING call, capturing the assembled turn when it ends.
336    ///
337    /// Why (#4425): `wrap_with_debug_capture` sits between the agent loop and
338    /// the real transport on every production path, so inheriting the trait's
339    /// buffered default here would silently disable streaming for anyone who
340    /// turned `TCODE_DEBUG_TRANSCRIPT` on — i.e. exactly the person debugging a
341    /// streaming problem.
342    /// What: reserves the turn index UP FRONT (so a streamed turn keeps its
343    /// dispatch-order position even though it completes later), forwards every
344    /// event unchanged, and writes the capture record from the assembled
345    /// response at the terminal event. A stream that errors — whether at
346    /// stream-OPEN or mid-flight — records that error under the reserved index
347    /// and then propagates it, exactly as [`Self::chat`] does; the recorded
348    /// error is the ORIGINAL `InferenceError`, so its retryable/alarm
349    /// classification survives into the transcript.
350    /// Test: `debug_capture::tests::*` cover the blocking path;
351    /// `stream_open_failure_records_its_reserved_turn_index` and
352    /// `stream_error_preserves_the_original_error_classification` cover the two
353    /// streaming failure modes; the streaming pass-through is covered end to
354    /// end by `crate::agent_loop::tests`.
355    async fn chat_stream(&self, req: &ChatRequest) -> Result<ChatStream, InferenceError> {
356        let turn_index = self.sink.next_turn_index();
357        // #4425: the index is reserved BEFORE the handshake, so a failed
358        // stream-open must still occupy it — returning `?` here would leave a
359        // permanent GAP in the transcript's turn-index sequence and, worse,
360        // drop the only record of the request that failed. The blocking `chat`
361        // path records in ALL cases; this matches it.
362        let inner = match self.inner.chat_stream(req).await {
363            Ok(stream) => stream,
364            Err(e) => {
365                self.sink.record(turn_index, &self.role, req, Err(&e));
366                return Err(e);
367            }
368        };
369        let sink = Arc::clone(&self.sink);
370        let role = self.role.clone();
371        let req = req.clone();
372        let mut assembly = StreamAssembly::new();
373        Ok(Box::pin(inner.map(move |event| {
374            match &event {
375                Ok(ev) => {
376                    assembly.push(ev.clone());
377                    if matches!(ev, ChatStreamEvent::Done(_)) {
378                        let resp = std::mem::take(&mut assembly)
379                            .into_response(String::new(), req.model.clone());
380                        sink.record(turn_index, &role, &req, Ok(&resp));
381                    }
382                }
383                // #4425: record `e` ITSELF, never a re-wrapped
384                // `InferenceError::Transport(e.to_string())` — that flattened
385                // every mid-flight failure into the one variant that is always
386                // retryable and never an alarm, so a 401 or a missing-config
387                // failure was recorded as a transient network blip.
388                Err(e) => sink.record(turn_index, &role, &req, Err(e)),
389            }
390            event
391        })))
392    }
393}
394
395/// Wrap `inner` in debug capture when `sink` is configured; otherwise return
396/// `inner` UNCHANGED.
397///
398/// Why: this is the single call-site helper `run_task::execute_run_task` and
399/// `task::executor::run_and_record` both call (once per role: `"pm"` and the
400/// engineer's agent name) — returning `inner` verbatim when capture is off
401/// means the disabled path allocates no wrapper and adds no indirection,
402/// satisfying #2264's "zero overhead and no behavior change" requirement
403/// exactly.
404/// What: `Some(sink)` → wraps in a new `DebugCaptureLlmClient` cloning
405/// `sink`'s `Arc`; `None` → returns `inner`.
406/// Test: `debug_capture::tests::wrap_with_debug_capture_*`.
407pub fn wrap_with_debug_capture(
408    inner: Arc<dyn InferenceAdapter>,
409    role: impl Into<String>,
410    sink: Option<&Arc<DebugCaptureSink>>,
411) -> Arc<dyn InferenceAdapter> {
412    match sink {
413        Some(sink) => Arc::new(DebugCaptureLlmClient {
414            inner,
415            role: role.into(),
416            sink: Arc::clone(sink),
417        }),
418        None => inner,
419    }
420}