Skip to main content

trusty_code/run_task/
recorder.rs

1//! Transcript-recording `InferenceAdapter` 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 `InferenceAdapter` 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 InferenceAdapter>`, 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 futures_util::StreamExt;
22use serde::{Deserialize, Serialize};
23
24use crate::llm::{
25    ChatRequest, ChatResponse, ChatStream, ChatStreamEvent, InferenceAdapter, InferenceError,
26    StreamAssembly,
27};
28use crate::perf::TokenUsage;
29
30/// One recorded assistant turn for the run transcript.
31///
32/// Why: The transcript output needs a machine- and human-renderable shape that
33/// captures who spoke (role), with which model, what text, and which tools it
34/// invoked — enough to reconstruct the PM→engineer interaction without leaking
35/// the full raw message history.
36/// What: `role` is the agent label; `model` is the resolved slug for that turn;
37/// `text` is the assistant prose (empty for tool-only turns); `tool_calls` lists
38/// the invoked tool names in order; `ran_test_command` (#2279) is a summarized
39/// signal — `true` iff this turn's tool calls included a `bash` invocation
40/// matching `crate::verify_gate::is_test_command` — the delegating PM's own
41/// `verify_gate::pm_finish_gate` consults this instead of the engineer's full
42/// transcript, since the PM never calls `bash` itself; `usage` is the token
43/// usage the provider reported for this turn (the per-turn unit the run
44/// aggregates over both PM and engineer turns, since the engineer's usage is
45/// otherwise lost when its output flows back to the PM as a tool-result
46/// string). `Deserialize` (#2060) lets `tcode`'s CLI thin client parse a
47/// `session.get_transcript` JSON-RPC result straight back into
48/// `Vec<TurnRecord>`.
49/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`,
50/// `verify_gate::tests::pm_gate_satisfied_when_engineer_ran_tests`.
51#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
52pub struct TurnRecord {
53    /// Agent label that produced this turn (e.g. `"pm"`, `"python-engineer"`).
54    pub role: String,
55    /// Resolved model slug used for this turn.
56    pub model: String,
57    /// Assistant prose for the turn (empty string for tool-only turns).
58    pub text: String,
59    /// Names of tools the assistant called this turn, in order.
60    pub tool_calls: Vec<String>,
61    /// Whether this turn ran a `bash` command matching #2279's verify-before-
62    /// finish test-command pattern. `#[serde(default)]` keeps a pre-#2279
63    /// persisted transcript deserialising cleanly with this flag `false`.
64    #[serde(default)]
65    pub ran_test_command: bool,
66    /// Token usage the provider reported for this turn.
67    pub usage: TokenUsage,
68}
69
70/// Shared, thread-safe transcript accumulator.
71///
72/// Why: The PM and engineer recorders run on the same tokio runtime and both
73/// append to one ordered transcript; an `Arc<Mutex<…>>` is the minimal shared
74/// sink that keeps turn order without global state.
75/// What: A type alias for the shared vector of `TurnRecord`s.
76/// Test: Exercised by every `run_task` end-to-end test.
77pub type SharedTranscript = Arc<Mutex<Vec<TurnRecord>>>;
78
79/// A transparent `InferenceAdapter` that records each turn into a shared transcript.
80///
81/// Why: Captures the conversation for the run report without modifying the agent
82/// loop. Wrapping the shared client means PM and engineer turns land in one
83/// ordered transcript while usage still accrues on the inner client.
84/// What: Forwards `chat` to the inner client, then appends a `TurnRecord` tagged
85/// with this wrapper's `role` and the request's model. A poisoned transcript
86/// lock is treated as a no-op record (the run must not panic mid-flight).
87/// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`.
88///
89/// `Clone` is cheap (an `Arc`, a `String`, and an `Arc`) and exists so
90/// [`Self::chat_stream`]'s `'static` stream closure can carry the recorder's
91/// transcript handle past the borrow of `&self` (#4425).
92#[derive(Clone)]
93pub struct RecordingLlmClient {
94    inner: Arc<dyn InferenceAdapter>,
95    role: String,
96    transcript: SharedTranscript,
97}
98
99impl RecordingLlmClient {
100    /// Wrap `inner`, tagging recorded turns with `role`.
101    ///
102    /// Why: Each agent (PM, engineer) needs its own labelled recorder sharing the
103    /// same transcript sink so the report can distinguish their turns.
104    /// What: Stores the inner client, the role label, and the shared transcript.
105    /// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`.
106    pub fn new(
107        inner: Arc<dyn InferenceAdapter>,
108        role: impl Into<String>,
109        transcript: SharedTranscript,
110    ) -> Self {
111        Self {
112            inner,
113            role: role.into(),
114            transcript,
115        }
116    }
117
118    /// Append one completed turn to the shared transcript.
119    ///
120    /// Why (#4425): the recorder now decorates BOTH the blocking and the
121    /// streaming call. Extracting the recording step means a streamed turn is
122    /// recorded by the same code — and therefore identically — rather than by a
123    /// second copy that could drift (e.g. one of them forgetting the #2279
124    /// test-command flag).
125    /// What: derives the record from `req`/`resp` and pushes it. A poisoned
126    /// transcript lock drops the record rather than aborting the run.
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    fn record_turn(&self, req: &ChatRequest, resp: &ChatResponse) {
131        let calls = resp.first_tool_calls();
132        let ran_test_command = calls
133            .iter()
134            .filter_map(crate::verify_gate::bash_command_from_call)
135            .any(|cmd| crate::verify_gate::is_test_command(&cmd));
136        let tool_calls = calls.iter().map(|c| c.function.name.clone()).collect();
137        let record = TurnRecord {
138            role: self.role.clone(),
139            model: crate::llm::resolved_model(resp, &req.model).to_string(),
140            text: resp.first_text().unwrap_or_default(),
141            tool_calls,
142            ran_test_command,
143            usage: crate::llm::token_usage(resp),
144        };
145
146        // A poisoned lock must not abort the run; drop the record rather than panic.
147        if let Ok(mut guard) = self.transcript.lock() {
148            guard.push(record);
149        }
150    }
151}
152
153#[async_trait]
154impl InferenceAdapter for RecordingLlmClient {
155    // #4425: a transparent decorator must report the WRAPPED backend's identity,
156    // never its own.
157    crate::llm::delegating_adapter_identity!(inner);
158
159    /// Forward the chat call and record the resulting turn.
160    ///
161    /// Why: The transcript must reflect exactly what the model returned; recording
162    /// after the call (on success) keeps the report faithful and never fabricates
163    /// turns for failed requests.
164    /// What: Calls the inner client; on `Ok`, appends a `TurnRecord` with the
165    /// RESOLVED model slug (#1475 bug 2 — `resp.resolved_model(&req.model)`,
166    /// which prefers the provider-reported model and falls back to the
167    /// requested slug when the response omits one), the response's first
168    /// text, its tool-call names, and (#2279) whether any of those calls was
169    /// a matching `bash` test invocation (`ran_test_command`, computed via
170    /// `crate::verify_gate::bash_command_from_call` +
171    /// `crate::verify_gate::is_test_command` — the SAME predicate the
172    /// engineer's own in-transcript gate uses); returns the response
173    /// unchanged. Errors propagate untouched (and are not recorded).
174    /// Test: `run_task::tests::end_to_end_pm_delegates_to_engineer`,
175    /// `run_task::tests::transcript_records_resolved_model_not_requested_slug`,
176    /// `run_task::tests::recorder_flags_ran_test_command_on_matching_bash_call`.
177    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
178        let resp = self.inner.chat(req).await?;
179        self.record_turn(req, &resp);
180        Ok(resp)
181    }
182
183    /// Forward the STREAMING chat call, recording the turn once it completes.
184    ///
185    /// Why (#4425): without this override the trait's default would buffer via
186    /// [`Self::chat`] — and since `run_task` and `task::executor` wrap EVERY
187    /// production client in this recorder, inheriting the default would have
188    /// silently disabled streaming on exactly the paths that matter, leaving
189    /// streaming working only in tests. The transcript must still be recorded,
190    /// which is why this wraps the stream rather than merely forwarding it.
191    /// What: delegates to the inner adapter's `chat_stream`, then re-emits every
192    /// event unchanged while folding it into a [`StreamAssembly`]; when the
193    /// stream ends the assembled turn is recorded exactly as the blocking path
194    /// records it. A stream dropped early (cancellation) records nothing —
195    /// matching `chat`, which records nothing on error. One difference is
196    /// inherent to the wire: a streamed turn carries no resolved-model field
197    /// (the SSE terminal event reports finish reason + usage only), so the
198    /// recorded model is the REQUESTED slug — the same value
199    /// [`crate::llm::resolved_model`] falls back to whenever a provider omits
200    /// it, so the record's shape is unchanged.
201    /// Test: `run_task::tests` cover the blocking path;
202    /// `crate::agent_loop::tests::sink_events` covers the streamed path.
203    async fn chat_stream(&self, req: &ChatRequest) -> Result<ChatStream, InferenceError> {
204        let inner = self.inner.chat_stream(req).await?;
205        let this = self.clone();
206        let req = req.clone();
207        let mut assembly = StreamAssembly::new();
208        Ok(Box::pin(inner.map(move |event| {
209            if let Ok(ev) = &event {
210                assembly.push(ev.clone());
211                if matches!(ev, ChatStreamEvent::Done(_)) {
212                    let resp = std::mem::take(&mut assembly)
213                        .into_response(String::new(), req.model.clone());
214                    this.record_turn(&req, &resp);
215                }
216            }
217            event
218        })))
219    }
220}