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//! `LlmClientTrait` 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 `LlmClientTrait::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`).
45
46use std::fs::OpenOptions;
47use std::io::Write;
48use std::path::{Path, PathBuf};
49use std::sync::atomic::{AtomicU64, Ordering};
50use std::sync::{Arc, Mutex};
51
52use async_trait::async_trait;
53use serde::Serialize;
54
55use super::{ChatRequest, ChatResponse, LlmClientTrait, LlmError};
56use crate::perf::TokenUsage;
57
58#[cfg(test)]
59#[path = "tests.rs"]
60mod tests;
61
62/// Environment variable that turns capture on: a file path (records are
63/// appended) or a directory path (one fresh file per run).
64///
65/// Why: opt-in via env var (not a CLI flag) is the primary/required
66/// mechanism per #2264 — the bake-off runner sets env vars, not flags, and
67/// it must work identically whether `run-task` executes in-process
68/// (`--legacy-in-process`) or spawns the daemon subprocess (the default thin
69/// client) — a spawned child inherits the parent's environment automatically
70/// (`cli_client::stdio::StdioRpcClient::spawn` never clears it), so setting
71/// this once in the invoking shell covers every execution path with no
72/// extra plumbing.
73/// What: read once per run via [`DebugCaptureSink::from_env`].
74pub const ENV_VAR: &str = "TCODE_DEBUG_TRANSCRIPT";
75
76/// One recorded LLM round-trip: the full request, the full response (or the
77/// error), and per-turn metadata.
78///
79/// Why: This is the shape that closes the `tcode_report.json` gap (#2264) —
80/// unlike `run_task::recorder::TurnRecord` (role + text + tool-call NAMES),
81/// this carries the entire `ChatRequest` (system prompt, tool schemas, full
82/// message history, cache_control markers) and the entire `ChatResponse`
83/// (assistant text AND every tool-call's arguments), so a reader can see
84/// exactly what the model was shown and exactly what it decided, turn by
85/// turn.
86/// What: `turn_index` is a monotonic counter shared by every role in one run
87/// (so interleaved pm/engineer turns stay globally ordered); `role` is the
88/// delegation segment label (`"pm"` or the engineer's agent name, e.g.
89/// `"python-engineer"` — this crate delegates to exactly one engineer role
90/// per run today, so `role` doubles as the segment identifier); `request` is
91/// the verbatim `ChatRequest` serialised with its normal wire `Serialize`
92/// impl (so `ChatMessage`'s cache_control content-block shape round-trips
93/// exactly as sent); `response` is `Some` on success, `None` on failure (in
94/// which case `error` carries the `LlmError`'s `Display` text); `usage` is
95/// the zero value on failure.
96/// Test: `debug_capture::tests::record_serialises_full_request_and_response`.
97#[derive(Debug, Clone, Serialize)]
98struct DebugCaptureRecord<'a> {
99 turn_index: u64,
100 role: &'a str,
101 timestamp: String,
102 request: &'a ChatRequest,
103 response: Option<ChatResponse>,
104 error: Option<String>,
105 usage: TokenUsage,
106}
107
108/// Shared, thread-safe sink for one run's debug-capture output.
109///
110/// Why: a directory-mode capture must produce ONE file per run shared by
111/// BOTH the pm and engineer recorders (mirroring
112/// `run_task::recorder::SharedTranscript`'s "one shared accumulator per
113/// run" shape) so the file's turn order reflects the true interleaving of
114/// pm/engineer calls, not two disjoint per-role files.
115/// What: Wraps a `Mutex<File>` (append-mode) and an `AtomicU64` turn
116/// counter. Constructed once per run via [`Self::from_env`] and cloned
117/// (`Arc`) into every [`DebugCaptureLlmClient`] wrapping that run's clients.
118/// Test: `debug_capture::tests::*`.
119pub struct DebugCaptureSink {
120 file: Mutex<std::fs::File>,
121 turn_counter: AtomicU64,
122}
123
124impl DebugCaptureSink {
125 /// Resolve [`ENV_VAR`] and open (or create) the capture file, if set.
126 ///
127 /// Why: the single per-run construction point every call site
128 /// (`run_task::execute_run_task`, `task::executor::run_and_record`)
129 /// invokes exactly once; a capture failure (bad path, permissions) must
130 /// degrade the run to "no capture" rather than abort it — this is
131 /// debugging tooling, not a correctness-critical dependency.
132 /// What: `None` when [`ENV_VAR`] is unset or empty (the zero-overhead
133 /// default). Otherwise resolves the path (directory → fresh per-run
134 /// file; anything else → literal file, appended) and opens it,
135 /// returning `Some(Arc<Self>)` on success or `None` (after printing an
136 /// actionable stderr warning — never stdout, which must stay clean for
137 /// MCP JSON-RPC framing) if the file could not be opened.
138 /// Test: `debug_capture::tests::from_env_none_when_unset`,
139 /// `debug_capture::tests::from_env_opens_literal_file_path`,
140 /// `debug_capture::tests::from_env_directory_gets_fresh_per_run_file`.
141 pub fn from_env() -> Option<Arc<Self>> {
142 let raw = std::env::var(ENV_VAR).ok().filter(|s| !s.is_empty())?;
143 match Self::open(Path::new(&raw)) {
144 Ok(sink) => Some(Arc::new(sink)),
145 Err(e) => {
146 eprintln!(
147 "tcode: {ENV_VAR}='{raw}' but the debug-capture file could not be opened \
148 ({e}) — continuing without capture"
149 );
150 None
151 }
152 }
153 }
154
155 /// Resolve `raw` to a concrete file path and open it for appending.
156 ///
157 /// Why: split from `from_env` so path resolution is independently
158 /// testable without touching the process environment.
159 /// What: creates any missing parent directories, then opens
160 /// (create-if-missing, append) the resolved path.
161 fn open(raw: &Path) -> std::io::Result<Self> {
162 let path = resolve_capture_path(raw);
163 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
164 std::fs::create_dir_all(parent)?;
165 }
166 let file = OpenOptions::new().create(true).append(true).open(&path)?;
167 Ok(Self {
168 file: Mutex::new(file),
169 turn_counter: AtomicU64::new(0),
170 })
171 }
172
173 /// Claim the next monotonic turn index for this run.
174 ///
175 /// Why: `fetch_add` under one shared counter is what keeps pm/engineer
176 /// turns in one globally-ordered sequence, matching the ORDER they were
177 /// actually dispatched (not just the order each role's own calls ran
178 /// in).
179 /// What: Returns the previous counter value, then increments.
180 fn next_turn_index(&self) -> u64 {
181 self.turn_counter.fetch_add(1, Ordering::SeqCst)
182 }
183
184 /// Serialise and append one round-trip record.
185 ///
186 /// Why: centralises the "build the record, serialise, append a line"
187 /// sequence so [`DebugCaptureLlmClient::chat`] stays a thin dispatch
188 /// wrapper; failures here (serialisation, disk I/O) are logged to
189 /// stderr and otherwise swallowed — a debug-capture write must never
190 /// fail the underlying LLM call it is observing.
191 /// What: builds a [`DebugCaptureRecord`] from `req` and `result`
192 /// (cloning the `ChatResponse` on success; recording `LlmError`'s
193 /// `Display` text on failure), serialises it to one JSON line, and
194 /// appends it (with a trailing newline) to the sink's file under its
195 /// mutex.
196 fn record(
197 &self,
198 turn_index: u64,
199 role: &str,
200 req: &ChatRequest,
201 result: &Result<ChatResponse, LlmError>,
202 ) {
203 let (response, error, usage) = match result {
204 Ok(resp) => (Some(resp.clone()), None, resp.clone().token_usage()),
205 Err(e) => (None, Some(e.to_string()), TokenUsage::default()),
206 };
207 let record = DebugCaptureRecord {
208 turn_index,
209 role,
210 timestamp: chrono::Utc::now().to_rfc3339(),
211 request: req,
212 response,
213 error,
214 usage,
215 };
216 let line = match serde_json::to_string(&record) {
217 Ok(s) => s,
218 Err(e) => {
219 eprintln!("tcode: debug-capture record serialisation failed: {e}");
220 return;
221 }
222 };
223 // A poisoned lock must not abort the run; recover the inner file
224 // handle and keep writing (mirrors `RecordingLlmClient`'s "a
225 // poisoned lock is a no-op record, not a panic" convention).
226 let mut guard = match self.file.lock() {
227 Ok(g) => g,
228 Err(poisoned) => poisoned.into_inner(),
229 };
230 if let Err(e) = writeln!(guard, "{line}") {
231 eprintln!("tcode: debug-capture write failed: {e}");
232 }
233 }
234}
235
236/// Resolve the configured [`ENV_VAR`] value to a concrete capture file path.
237///
238/// Why: the env var doubles as either a literal file (append across the
239/// whole process lifetime) or a directory (one fresh file per run) per
240/// #2264's requirements; this is the single place that distinction is made.
241/// What: `raw` is treated as a directory when it already exists as one, OR
242/// its string form ends with the platform path separator (so a caller can
243/// force directory semantics for a not-yet-created directory, e.g.
244/// `TCODE_DEBUG_TRANSCRIPT=/tmp/captures/`). In that case returns
245/// `raw.join("tcode-debug-<uuid>.jsonl")`; otherwise returns `raw` unchanged
246/// (literal file path).
247/// Test: `debug_capture::tests::resolve_capture_path_*`.
248fn resolve_capture_path(raw: &Path) -> PathBuf {
249 let looks_like_dir = raw.is_dir() || raw.to_string_lossy().ends_with(std::path::MAIN_SEPARATOR);
250 if looks_like_dir {
251 raw.join(format!("tcode-debug-{}.jsonl", uuid::Uuid::new_v4()))
252 } else {
253 raw.to_path_buf()
254 }
255}
256
257/// A transparent `LlmClientTrait` decorator that appends a full wire-level
258/// record of each round-trip to a shared [`DebugCaptureSink`].
259///
260/// Why: the same "wrap, observe, forward unchanged" shape
261/// `run_task::recorder::RecordingLlmClient` already uses — this decorator
262/// sits at the identical `LlmClientTrait::chat` seam, so it is transport-
263/// and run-path-agnostic by construction (whatever `inner` resolves to —
264/// `DispatchingLlmClient` routing to OpenRouter or Bedrock, or a test mock —
265/// is invisible to this wrapper).
266/// What: Holds the inner client, a role label, and the shared sink. `chat`
267/// calls the inner client, records the request/response(or error) pair
268/// under the next turn index, and returns the inner result unchanged
269/// (including on error — the caller sees the exact same `Result` it would
270/// have without capture enabled).
271/// Test: `debug_capture::tests::*`.
272struct DebugCaptureLlmClient {
273 inner: Arc<dyn LlmClientTrait>,
274 role: String,
275 sink: Arc<DebugCaptureSink>,
276}
277
278#[async_trait]
279impl LlmClientTrait for DebugCaptureLlmClient {
280 async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
281 let turn_index = self.sink.next_turn_index();
282 let result = self.inner.chat(req).await;
283 self.sink.record(turn_index, &self.role, req, &result);
284 result
285 }
286}
287
288/// Wrap `inner` in debug capture when `sink` is configured; otherwise return
289/// `inner` UNCHANGED.
290///
291/// Why: this is the single call-site helper `run_task::execute_run_task` and
292/// `task::executor::run_and_record` both call (once per role: `"pm"` and the
293/// engineer's agent name) — returning `inner` verbatim when capture is off
294/// means the disabled path allocates no wrapper and adds no indirection,
295/// satisfying #2264's "zero overhead and no behavior change" requirement
296/// exactly.
297/// What: `Some(sink)` → wraps in a new `DebugCaptureLlmClient` cloning
298/// `sink`'s `Arc`; `None` → returns `inner`.
299/// Test: `debug_capture::tests::wrap_with_debug_capture_*`.
300pub fn wrap_with_debug_capture(
301 inner: Arc<dyn LlmClientTrait>,
302 role: impl Into<String>,
303 sink: Option<&Arc<DebugCaptureSink>>,
304) -> Arc<dyn LlmClientTrait> {
305 match sink {
306 Some(sink) => Arc::new(DebugCaptureLlmClient {
307 inner,
308 role: role.into(),
309 sink: Arc::clone(sink),
310 }),
311 None => inner,
312 }
313}