trusty_code/run_task/recorder.rs
1//! Transcript-recording `LlmClientTrait` decorator (#1034).
2//!
3//! Why: `AgentLoop::run` returns only the final `AgentOutput` (content + usage);
4//! it does not expose the per-turn conversation. The `run-task` command must
5//! emit a structured transcript of every PM and engineer turn (model + assistant
6//! text + tool calls). Rather than change the loop's signature, we wrap the
7//! shared `LlmClientTrait` in a recorder that observes each request/response
8//! pair and appends a `TurnRecord`. The wrapper is transparent — it forwards to
9//! the inner client unchanged — so the real OpenRouter client and the offline
10//! mock both work behind it.
11//! What: `RecordingLlmClient` holds an inner `Arc<dyn LlmClientTrait>`, a role
12//! label (`"pm"` / `"python-engineer"`), and a shared `Arc<Mutex<Vec<TurnRecord>>>`.
13//! Each `chat` call records the resolved model and the resulting assistant text
14//! plus tool-call names, then returns the inner response verbatim.
15//! Test: `run_task::tests` assert the recorded transcript carries both roles, and
16//! the per-run engineer model slug.
17
18use std::sync::{Arc, Mutex};
19
20use async_trait::async_trait;
21use serde::{Deserialize, Serialize};
22
23use crate::llm::{ChatRequest, ChatResponse, LlmClientTrait, LlmError};
24use crate::perf::TokenUsage;
25
26/// One recorded assistant turn for the run transcript.
27///
28/// Why: The transcript output needs a machine- and human-renderable shape that
29/// captures who spoke (role), with which model, what text, and which tools it
30/// invoked — enough to reconstruct the PM→engineer interaction without leaking
31/// the full raw message history.
32/// What: `role` is the agent label; `model` is the resolved slug for that turn;
33/// `text` is the assistant prose (empty for tool-only turns); `tool_calls` lists
34/// the invoked tool names in order; `ran_test_command` (#2279) is a summarized
35/// signal — `true` iff this turn's tool calls included a `bash` invocation
36/// matching `crate::verify_gate::is_test_command` — the delegating PM's own
37/// `verify_gate::pm_finish_gate` consults this instead of the engineer's full
38/// transcript, since the PM never calls `bash` itself; `usage` is the token
39/// usage the provider reported for this turn (the per-turn unit the run
40/// aggregates over both PM and engineer turns, since the engineer's usage is
41/// otherwise lost when its output flows back to the PM as a tool-result
42/// string). `Deserialize` (#2060) lets `tcode`'s CLI thin client parse a
43/// `session.get_transcript` JSON-RPC result straight back into
44/// `Vec<TurnRecord>`.
45/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`,
46/// `verify_gate::tests::pm_gate_satisfied_when_engineer_ran_tests`.
47#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
48pub struct TurnRecord {
49 /// Agent label that produced this turn (e.g. `"pm"`, `"python-engineer"`).
50 pub role: String,
51 /// Resolved model slug used for this turn.
52 pub model: String,
53 /// Assistant prose for the turn (empty string for tool-only turns).
54 pub text: String,
55 /// Names of tools the assistant called this turn, in order.
56 pub tool_calls: Vec<String>,
57 /// Whether this turn ran a `bash` command matching #2279's verify-before-
58 /// finish test-command pattern. `#[serde(default)]` keeps a pre-#2279
59 /// persisted transcript deserialising cleanly with this flag `false`.
60 #[serde(default)]
61 pub ran_test_command: bool,
62 /// Token usage the provider reported for this turn.
63 pub usage: TokenUsage,
64}
65
66/// Shared, thread-safe transcript accumulator.
67///
68/// Why: The PM and engineer recorders run on the same tokio runtime and both
69/// append to one ordered transcript; an `Arc<Mutex<…>>` is the minimal shared
70/// sink that keeps turn order without global state.
71/// What: A type alias for the shared vector of `TurnRecord`s.
72/// Test: Exercised by every `run_task` end-to-end test.
73pub type SharedTranscript = Arc<Mutex<Vec<TurnRecord>>>;
74
75/// A transparent `LlmClientTrait` that records each turn into a shared transcript.
76///
77/// Why: Captures the conversation for the run report without modifying the agent
78/// loop. Wrapping the shared client means PM and engineer turns land in one
79/// ordered transcript while usage still accrues on the inner client.
80/// What: Forwards `chat` to the inner client, then appends a `TurnRecord` tagged
81/// with this wrapper's `role` and the request's model. A poisoned transcript
82/// lock is treated as a no-op record (the run must not panic mid-flight).
83/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`.
84pub struct RecordingLlmClient {
85 inner: Arc<dyn LlmClientTrait>,
86 role: String,
87 transcript: SharedTranscript,
88}
89
90impl RecordingLlmClient {
91 /// Wrap `inner`, tagging recorded turns with `role`.
92 ///
93 /// Why: Each agent (PM, engineer) needs its own labelled recorder sharing the
94 /// same transcript sink so the report can distinguish their turns.
95 /// What: Stores the inner client, the role label, and the shared transcript.
96 /// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`.
97 pub fn new(
98 inner: Arc<dyn LlmClientTrait>,
99 role: impl Into<String>,
100 transcript: SharedTranscript,
101 ) -> Self {
102 Self {
103 inner,
104 role: role.into(),
105 transcript,
106 }
107 }
108}
109
110#[async_trait]
111impl LlmClientTrait for RecordingLlmClient {
112 /// Forward the chat call and record the resulting turn.
113 ///
114 /// Why: The transcript must reflect exactly what the model returned; recording
115 /// after the call (on success) keeps the report faithful and never fabricates
116 /// turns for failed requests.
117 /// What: Calls the inner client; on `Ok`, appends a `TurnRecord` with the
118 /// RESOLVED model slug (#1475 bug 2 — `resp.resolved_model(&req.model)`,
119 /// which prefers the provider-reported model and falls back to the
120 /// requested slug when the response omits one), the response's first
121 /// text, its tool-call names, and (#2279) whether any of those calls was
122 /// a matching `bash` test invocation (`ran_test_command`, computed via
123 /// `crate::verify_gate::bash_command_from_call` +
124 /// `crate::verify_gate::is_test_command` — the SAME predicate the
125 /// engineer's own in-transcript gate uses); returns the response
126 /// unchanged. Errors propagate untouched (and are not recorded).
127 /// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`,
128 /// `run_task::tests::transcript_records_resolved_model_not_requested_slug`,
129 /// `run_task::tests::recorder_flags_ran_test_command_on_matching_bash_call`.
130 async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, LlmError> {
131 let resp = self.inner.chat(req).await?;
132
133 let calls = resp.first_tool_calls();
134 let ran_test_command = calls
135 .iter()
136 .filter_map(crate::verify_gate::bash_command_from_call)
137 .any(|cmd| crate::verify_gate::is_test_command(&cmd));
138 let tool_calls = calls.iter().map(|c| c.function.name.clone()).collect();
139 let record = TurnRecord {
140 role: self.role.clone(),
141 model: resp.resolved_model(&req.model).to_string(),
142 text: resp.first_text().unwrap_or_default(),
143 tool_calls,
144 ran_test_command,
145 usage: resp.clone().token_usage(),
146 };
147
148 // A poisoned lock must not abort the run; drop the record rather than panic.
149 if let Ok(mut guard) = self.transcript.lock() {
150 guard.push(record);
151 }
152
153 Ok(resp)
154 }
155}