1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Opt-in wire-level LLM round-trip capture for orchestration debugging
//! (#2264).
//!
//! Why: `run_task::recorder::RecordingLlmClient` already produces
//! `tcode_report.json`'s lightweight transcript (role, assistant text, tool
//! call NAMES, usage) — enough to render a human report, but not enough to
//! root-cause WHY the model made a given decision. Debugging turn-count
//! spikes or re-delegation loops needs the full wire-level exchange: the
//! entire system prompt, tool schemas, and message history actually sent
//! (including prompt-cache markers), the full assistant response (text AND
//! every tool-call's arguments, not just its name), and — via the next
//! request's own message history — the tool results fed back. This module
//! is that capture, gated behind `TCODE_DEBUG_TRANSCRIPT` so it costs
//! nothing when unset.
//! What: [`DebugCaptureSink`] resolves the env var once per run and owns the
//! output file + a monotonic turn counter shared across every wrapped
//! client for that run; [`DebugCaptureLlmClient`] is a transparent
//! `InferenceAdapter` decorator that appends one JSONL [`DebugCaptureRecord`]
//! per `chat()` call (request verbatim, response verbatim including
//! tool-call arguments, or the error, plus usage) before forwarding to the
//! wrapped inner client; [`wrap_with_debug_capture`] is the single call-site
//! helper — when no sink is configured it returns `inner` UNCHANGED (no
//! allocation, no indirection), which is what makes the default (unset)
//! path zero-overhead. Wrapping happens at the `InferenceAdapter::chat`
//! boundary — the same object-safe seam `DispatchingLlmClient` (OpenRouter +
//! Bedrock) and `RecordingLlmClient` already share across both the
//! in-process CLI path (`run_task::execute_run_task`) and the daemon path
//! (`task::executor::run_and_record`) — so this is the ONE place capture
//! logic lives, never duplicated per-transport or per-run-path.
//!
//! SAFETY / SENSITIVITY NOTE: a capture file is a byte-for-byte dump of every
//! prompt and response in a run — it WILL contain the full task description,
//! any file contents the model read or wrote, and full tool-call arguments
//! (e.g. `write_file` bodies). Treat capture files like source code / build
//! logs, not something to paste into a chat or share casually. This module
//! never serialises transport/auth headers or API keys — only the
//! already-constructed `ChatRequest`/`ChatResponse` BODY types, which never
//! carry credentials (see `llm::client::LlmClient::chat`, which injects the
//! `Authorization` header separately, after the body is built).
//! Test: `debug_capture::tests::*` — env-unset is a no-op (zero behaviour
//! change), env-set produces a JSONL record with the full request messages,
//! tool-call arguments, and tool results (visible in the NEXT turn's message
//! history), directory-mode picks a fresh per-run file, and a failed inner
//! `chat()` call is still recorded (with `error` set, `response: null`) — as
//! is a failed `chat_stream()`, at BOTH the stream-open handshake and
//! mid-flight, with the original error's classification intact (#4425).
use OpenOptions;
use Write;
use ;
use ;
use ;
use async_trait;
use Serialize;
use StreamExt;
use ;
use crateTokenUsage;
/// Environment variable that turns capture on: a file path (records are
/// appended) or a directory path (one fresh file per run).
///
/// Why: opt-in via env var (not a CLI flag) is the primary/required
/// mechanism per #2264 — the bake-off runner sets env vars, not flags, and
/// it must work identically whether `run-task` executes in-process
/// (`--legacy-in-process`) or spawns the daemon subprocess (the default thin
/// client) — a spawned child inherits the parent's environment automatically
/// (`cli_client::stdio::StdioRpcClient::spawn` never clears it), so setting
/// this once in the invoking shell covers every execution path with no
/// extra plumbing.
/// What: read once per run via [`DebugCaptureSink::from_env`].
pub const ENV_VAR: &str = "TCODE_DEBUG_TRANSCRIPT";
/// One recorded LLM round-trip: the full request, the full response (or the
/// error), and per-turn metadata.
///
/// Why: This is the shape that closes the `tcode_report.json` gap (#2264) —
/// unlike `run_task::recorder::TurnRecord` (role + text + tool-call NAMES),
/// this carries the entire `ChatRequest` (system prompt, tool schemas, full
/// message history, cache_control markers) and the entire `ChatResponse`
/// (assistant text AND every tool-call's arguments), so a reader can see
/// exactly what the model was shown and exactly what it decided, turn by
/// turn.
/// What: `turn_index` is a monotonic counter shared by every role in one run
/// (so interleaved pm/engineer turns stay globally ordered); `role` is the
/// delegation segment label (`"pm"` or the engineer's agent name, e.g.
/// `"python-engineer"` — this crate delegates to exactly one engineer role
/// per run today, so `role` doubles as the segment identifier); `request` is
/// the verbatim `ChatRequest` serialised with its normal wire `Serialize`
/// impl (so `ChatMessage`'s cache_control content-block shape round-trips
/// exactly as sent); `response` is `Some` on success, `None` on failure (in
/// which case `error` carries the `InferenceError`'s `Display` text and
/// `error_retryable`/`error_alarm` carry its CLASSIFICATION); `usage` is
/// the zero value on failure.
///
/// #4425: `error_retryable`/`error_alarm` exist because `error` is a `String`
/// — the record cannot hold an `InferenceError` itself (the shared enum is not
/// `Serialize`/`Deserialize`), so without them a reader would have to
/// re-classify by pattern-matching Display text. They are the transcript's
/// machine-readable copy of [`InferenceError::is_retryable`] /
/// [`InferenceError::is_alarm`], recorded from the ORIGINAL error value.
/// Test: `debug_capture::tests::record_serialises_full_request_and_response`,
/// `debug_capture::tests::stream_error_preserves_the_original_error_classification`.
/// Shared, thread-safe sink for one run's debug-capture output.
///
/// Why: a directory-mode capture must produce ONE file per run shared by
/// BOTH the pm and engineer recorders (mirroring
/// `run_task::recorder::SharedTranscript`'s "one shared accumulator per
/// run" shape) so the file's turn order reflects the true interleaving of
/// pm/engineer calls, not two disjoint per-role files.
/// What: Wraps a `Mutex<File>` (append-mode) and an `AtomicU64` turn
/// counter. Constructed once per run via [`Self::from_env`] and cloned
/// (`Arc`) into every [`DebugCaptureLlmClient`] wrapping that run's clients.
/// Test: `debug_capture::tests::*`.
/// Resolve the configured [`ENV_VAR`] value to a concrete capture file path.
///
/// Why: the env var doubles as either a literal file (append across the
/// whole process lifetime) or a directory (one fresh file per run) per
/// #2264's requirements; this is the single place that distinction is made.
/// What: `raw` is treated as a directory when it already exists as one, OR
/// its string form ends with the platform path separator (so a caller can
/// force directory semantics for a not-yet-created directory, e.g.
/// `TCODE_DEBUG_TRANSCRIPT=/tmp/captures/`). In that case returns
/// `raw.join("tcode-debug-<uuid>.jsonl")`; otherwise returns `raw` unchanged
/// (literal file path).
/// Test: `debug_capture::tests::resolve_capture_path_*`.
/// A transparent `InferenceAdapter` decorator that appends a full wire-level
/// record of each round-trip to a shared [`DebugCaptureSink`].
///
/// Why: the same "wrap, observe, forward unchanged" shape
/// `run_task::recorder::RecordingLlmClient` already uses — this decorator
/// sits at the identical `InferenceAdapter::chat` seam, so it is transport-
/// and run-path-agnostic by construction (whatever `inner` resolves to —
/// `DispatchingLlmClient` routing to OpenRouter or Bedrock, or a test mock —
/// is invisible to this wrapper).
/// What: Holds the inner client, a role label, and the shared sink. `chat`
/// calls the inner client, records the request/response(or error) pair
/// under the next turn index, and returns the inner result unchanged
/// (including on error — the caller sees the exact same `Result` it would
/// have without capture enabled).
/// Test: `debug_capture::tests::*`.
/// Wrap `inner` in debug capture when `sink` is configured; otherwise return
/// `inner` UNCHANGED.
///
/// Why: this is the single call-site helper `run_task::execute_run_task` and
/// `task::executor::run_and_record` both call (once per role: `"pm"` and the
/// engineer's agent name) — returning `inner` verbatim when capture is off
/// means the disabled path allocates no wrapper and adds no indirection,
/// satisfying #2264's "zero overhead and no behavior change" requirement
/// exactly.
/// What: `Some(sink)` → wraps in a new `DebugCaptureLlmClient` cloning
/// `sink`'s `Arc`; `None` → returns `inner`.
/// Test: `debug_capture::tests::wrap_with_debug_capture_*`.