Skip to main content

trusty_code/
verify_gate.rs

1//! Verify-before-finish gate (#2279): a recoverable retry, not a hard block,
2//! that keeps a coding agent from calling `finish_task` before it has run a
3//! test suite it was explicitly told about.
4//!
5//! Why: (bake-off L2 diagnosis) tcode's delegated engineer authored 81 tests
6//! validating the wrong contract and never ran the visible, prompt-named
7//! test suite the L2 challenge instructed it to run before submitting. The
8//! task prompt and `challenges/README.md` (folded into project context)
9//! named a runnable test command (`pytest challenges/level-2-git-analyzer/
10//! test_suite/ -v`); the transcript never shows it being invoked. This
11//! module is the structural fix: at the `finish_task` turn boundary
12//! (`agent_loop::AgentLoop::dispatch_all`), if the task/project-context text
13//! names a runnable test command AND no matching `bash` invocation appears
14//! in the relevant transcript, `finish_task` is rejected with a recoverable
15//! error — the SAME `ToolResult::err` retry path every other tool failure
16//! uses — instead of terminating the loop. If no test command is named at
17//! all, the gate is INERT: #2279 explicitly defers general polyglot
18//! test-suite discovery (the "(b2)" follow-up) rather than inventing one
19//! here.
20//! What: [`names_test_command`] and [`is_test_command`] are pure,
21//! independently unit-testable regex predicates — Improvement 2's own
22//! testability principle applied to its sibling Improvement 1. Two
23//! `agent_loop::FinishGate` constructors build on them: [`default_finish_gate`]
24//! scans a single loop's OWN `Transcript` — what a delegated engineer's
25//! sub-agent loop attaches (`runner::in_process::InProcessAgentRunner`),
26//! since its own `bash` calls land directly in that transcript.
27//! [`pm_finish_gate`] is for the delegating PM's loop, which never calls
28//! `bash` itself — it scans the externally shared `run_task::SharedTranscript`
29//! of `TurnRecord`s the delegated engineer's turns are recorded into
30//! instead, via each record's `ran_test_command` flag (set by
31//! `run_task::recorder::RecordingLlmClient` using the SAME [`is_test_command`]
32//! predicate this module owns, so the two paths can never independently
33//! drift on what counts as a matching invocation).
34//! Test: `verify_gate::tests::*`.
35
36use std::sync::Arc;
37
38use regex::Regex;
39use serde_json::Value;
40
41use crate::agent_loop::{FinishGate, Transcript};
42use crate::llm::{ChatMessage, ToolCall};
43use crate::run_task::SharedTranscript;
44use crate::tools::BASH_TOOL_NAME;
45
46/// Recoverable-retry message fed back to a delegated engineer's own loop
47/// when its `finish_task` call is rejected.
48const GATE_REASON_ENGINEER: &str = "finish_task rejected: the task prompt or project context \
49names a runnable test command (a pytest/cargo/npm/pnpm/go test invocation), but no matching \
50command has been run yet in this session. Run the named test suite via the bash tool, \
51reconcile any failures, and only then call finish_task again.";
52
53/// Recoverable-retry message fed back to the delegating PM's own loop when
54/// its `finish_task` call is rejected because the delegated engineer never
55/// ran the named tests.
56const GATE_REASON_PM: &str = "finish_task rejected: the task prompt or project context names a \
57runnable test command (a pytest/cargo/npm/pnpm/go test invocation), but the delegated \
58engineer's transcript shows no matching invocation yet. Delegate a follow-up task instructing \
59the engineer to run the named test suite and reconcile any failures before finishing.";
60
61/// Build the regex alternation matching the six test-invocation shapes named
62/// in #2279's finalized trigger heuristic.
63///
64/// Why: A single compiled pattern, rather than six separate `Regex`es, keeps
65/// [`names_test_command`] and [`is_test_command`] identical in shape — "does
66/// this text contain a recognizable test-command invocation" — the only
67/// difference between the two call sites is WHICH text they scan. Compiled
68/// fresh per call rather than cached in a `once_cell`/`lazy_static` global
69/// (project convention reserves those for the tracing subscriber only); this
70/// is not a hot path — at most once per `finish_task` dispatch attempt, or
71/// once per recorded turn — so the recompilation cost is immaterial next to
72/// the LLM round-trip it sits beside.
73/// What: `pytest\s+\S+` (a pytest invocation naming a path/module),
74/// `cargo test`, `npm test`, `pnpm test`, `go test`, `python -m pytest` —
75/// exactly the six patterns #2279's finalized decision comment named.
76/// Test: covered indirectly by every `tests::*` case below.
77fn test_command_pattern() -> Regex {
78    Regex::new(
79        r"(?:pytest\s+\S+)|(?:cargo\s+test)|(?:npm\s+test)|(?:pnpm\s+test)|(?:go\s+test)|(?:python\s+-m\s+pytest)",
80    )
81    .expect("test_command_pattern: hardcoded regex literal must compile")
82}
83
84/// Whether `text` textually names a runnable test command (the gate's
85/// TRIGGER half).
86///
87/// Why: The gate must stay inert when nothing in the task/project context
88/// ever asked for a specific test command.
89/// What: `true` iff [`test_command_pattern`] finds a match anywhere in
90/// `text`.
91/// Test: `tests::names_test_command_detects_each_pattern`,
92/// `tests::names_test_command_false_on_unrelated_text`.
93pub fn names_test_command(text: &str) -> bool {
94    test_command_pattern().is_match(text)
95}
96
97/// Whether `command` (a `bash` tool call's shell command) IS a matching test
98/// invocation (the gate's VERIFY half).
99///
100/// Why: Reused by both [`default_finish_gate`]'s own-transcript scan and
101/// `run_task::recorder`'s per-turn `ran_test_command` signal, so the two
102/// gate sites can never independently drift on what counts as "the named
103/// tests actually ran".
104/// What: Same predicate as [`names_test_command`], applied to a single
105/// command string rather than free-form prose.
106/// Test: `tests::is_test_command_matches_each_pattern`,
107/// `tests::is_test_command_false_on_unrelated_command`.
108pub fn is_test_command(command: &str) -> bool {
109    test_command_pattern().is_match(command)
110}
111
112/// Extract the shell command from a `bash` tool call's arguments, if `call`
113/// names the `bash` tool at all.
114///
115/// Why: Shared by [`default_finish_gate`]'s own-transcript scan and
116/// `run_task::recorder::RecordingLlmClient`'s per-turn signal, so the two
117/// gate sites parse the SAME wire shape (`{"command": "..."}`) identically.
118/// What: `None` when `call.function.name != BASH_TOOL_NAME` or the
119/// arguments do not parse as a JSON object with a string `command` field.
120/// Test: `tests::bash_command_from_call_extracts_command`,
121/// `tests::bash_command_from_call_ignores_other_tools`.
122pub fn bash_command_from_call(call: &ToolCall) -> Option<String> {
123    if call.function.name != BASH_TOOL_NAME {
124        return None;
125    }
126    let parsed: Value = serde_json::from_str(&call.function.arguments).ok()?;
127    parsed.get("command")?.as_str().map(str::to_string)
128}
129
130/// Whether any `bash` call in `messages` invoked a matching test command.
131///
132/// Why: The core predicate [`default_finish_gate`] applies to a delegated
133/// engineer's own `Transcript` — factored out as a free function so it is
134/// independently unit-testable against a plain `&[ChatMessage]` without
135/// constructing a full `Transcript`.
136/// What: Flattens every assistant turn's `tool_calls`, extracts each `bash`
137/// call's command via [`bash_command_from_call`], and checks
138/// [`is_test_command`].
139/// Test: `tests::transcript_ran_test_command_detects_match`,
140/// `tests::transcript_ran_test_command_false_without_bash`.
141fn transcript_ran_test_command(messages: &[ChatMessage]) -> bool {
142    messages
143        .iter()
144        .filter_map(|m| m.tool_calls.as_ref())
145        .flatten()
146        .filter_map(bash_command_from_call)
147        .any(|cmd| is_test_command(&cmd))
148}
149
150/// Join the seeded `system` + `user` message text into one haystack for
151/// [`names_test_command`].
152///
153/// Why: `Transcript::seed` is the ONLY place raw history ever gets a
154/// `system`- or `user`-role entry, and it seeds exactly one of each — the
155/// assembled system prompt (BASE + agent prompt + project `CLAUDE.md`
156/// context) and the task text. Scanning by role (not position) stays
157/// correct even if `Transcript`'s internal layout ever changes.
158/// What: Concatenates the `content` of every `system`/`user` entry with
159/// newlines.
160/// Test: `tests::seed_text_joins_system_and_user`.
161fn seed_text(messages: &[ChatMessage]) -> String {
162    messages
163        .iter()
164        .filter(|m| m.role == "system" || m.role == "user")
165        .filter_map(|m| m.content.as_deref())
166        .collect::<Vec<_>>()
167        .join("\n")
168}
169
170/// Build the default verify-before-finish gate: scans the SAME loop's own
171/// transcript for both the trigger and the verification.
172///
173/// Why: This is the shape a delegated engineer's sub-agent loop needs — its
174/// own `bash` calls land directly in its own `Transcript`, so no external
175/// state is required.
176/// What: Returns a [`FinishGate`] closure that is inert unless
177/// [`seed_text`] of the transcript [`names_test_command`]; when it does,
178/// trips (returning [`GATE_REASON_ENGINEER`]) unless
179/// [`transcript_ran_test_command`] finds a match.
180/// Test: `tests::default_gate_trips_when_named_and_unrun`,
181/// `tests::default_gate_inert_when_not_named`,
182/// `tests::default_gate_satisfied_when_run`,
183/// `agent_loop::tests::finish_gate_trips_and_recovers`.
184pub fn default_finish_gate() -> FinishGate {
185    Arc::new(|transcript: &Transcript| {
186        let messages = transcript.messages();
187        if !names_test_command(&seed_text(&messages)) {
188            return None;
189        }
190        if transcript_ran_test_command(&messages) {
191            return None;
192        }
193        Some(GATE_REASON_ENGINEER.to_string())
194    })
195}
196
197/// Build the delegating PM's verify-before-finish gate: the trigger comes
198/// from the PM's own transcript, but the verification scans the externally
199/// shared engineer transcript instead.
200///
201/// Why: The PM's own tool registry never includes `bash` (`run_task::
202/// execute_run_task` registers only `delegate_to_agent` and `finish_task`),
203/// so scanning the PM's own `Transcript` for a `bash` call would ALWAYS
204/// report "not run" — wrongly tripping the gate even when the delegated
205/// engineer ran the named tests correctly. `shared` is the SAME
206/// `run_task::SharedTranscript` the engineer's `RecordingLlmClient` records
207/// into, so this closure sees the engineer's turns too.
208/// What: Returns a [`FinishGate`] closure inert unless the PM transcript's
209/// [`seed_text`] [`names_test_command`]; when it does, trips (returning
210/// [`GATE_REASON_PM`]) unless any `TurnRecord` in `shared` has
211/// `ran_test_command == true`. A poisoned lock is treated as "not run" —
212/// fail toward asking the model to verify, not toward silently finishing.
213/// Test: `tests::pm_gate_trips_when_engineer_never_ran_tests`,
214/// `tests::pm_gate_satisfied_when_engineer_ran_tests`,
215/// `tests::pm_gate_inert_when_not_named`.
216pub fn pm_finish_gate(shared: SharedTranscript) -> FinishGate {
217    Arc::new(move |transcript: &Transcript| {
218        let messages = transcript.messages();
219        if !names_test_command(&seed_text(&messages)) {
220            return None;
221        }
222        let ran = shared
223            .lock()
224            .map(|turns| turns.iter().any(|t| t.ran_test_command))
225            .unwrap_or(false);
226        if ran {
227            return None;
228        }
229        Some(GATE_REASON_PM.to_string())
230    })
231}
232
233// ── Tests ─────────────────────────────────────────────────────────────────────
234
235#[cfg(test)]
236mod tests {
237    use std::sync::Mutex;
238
239    use super::*;
240    use crate::llm::FunctionCall;
241    use crate::run_task::TurnRecord;
242
243    fn bash_call(id: &str, command: &str) -> ToolCall {
244        ToolCall {
245            id: id.into(),
246            kind: "function".into(),
247            function: FunctionCall {
248                name: BASH_TOOL_NAME.into(),
249                arguments: serde_json::json!({"command": command}).to_string(),
250            },
251        }
252    }
253
254    fn assistant_with_tool_calls(calls: Vec<ToolCall>) -> ChatMessage {
255        ChatMessage {
256            role: "assistant".into(),
257            content: None,
258            tool_calls: Some(calls),
259            tool_call_id: None,
260            name: None,
261            cache_control: None,
262        }
263    }
264
265    /// [`names_test_command`] detects each of the six finalized patterns.
266    ///
267    /// Why: Guards the exact pattern set #2279's decision comment named.
268    /// What: One assertion per pattern, embedded in surrounding prose.
269    /// Test: this test.
270    #[test]
271    fn names_test_command_detects_each_pattern() {
272        for text in [
273            "please run pytest tests/test_basic.py -v before submitting",
274            "then run cargo test",
275            "run npm test after building",
276            "use pnpm test to check",
277            "run go test ./... first",
278            "invoke python -m pytest as the final step",
279        ] {
280            assert!(names_test_command(text), "expected a match in {text:?}");
281        }
282    }
283
284    /// [`names_test_command`] is `false` on prose naming no test command.
285    ///
286    /// Why: The gate must stay inert for ordinary tasks that never mention a
287    /// runnable test suite.
288    /// What: Free-form task text with no recognizable pattern.
289    /// Test: this test.
290    #[test]
291    fn names_test_command_false_on_unrelated_text() {
292        assert!(!names_test_command(
293            "implement a git log parser and make sure it builds cleanly"
294        ));
295    }
296
297    /// [`is_test_command`] matches each pattern as a standalone command
298    /// string (not embedded in prose).
299    ///
300    /// Why: This is the shape a `bash` tool call's `command` argument
301    /// actually takes.
302    /// What: One assertion per pattern.
303    /// Test: this test.
304    #[test]
305    fn is_test_command_matches_each_pattern() {
306        for cmd in [
307            "pytest challenges/level-2-git-analyzer/test_suite/ -v",
308            "cargo test -p trusty-code",
309            "npm test",
310            "pnpm test --run",
311            "go test ./...",
312            "python -m pytest -x",
313        ] {
314            assert!(is_test_command(cmd), "expected a match in {cmd:?}");
315        }
316    }
317
318    /// [`is_test_command`] is `false` on an unrelated shell command.
319    ///
320    /// Why: Ordinary bash calls (`ls`, `git status`, a build command) must
321    /// not be mistaken for a test invocation.
322    /// What: A handful of common non-test commands.
323    /// Test: this test.
324    #[test]
325    fn is_test_command_false_on_unrelated_command() {
326        for cmd in ["ls -la", "git status", "cargo build --release", "echo ok"] {
327            assert!(!is_test_command(cmd), "unexpected match in {cmd:?}");
328        }
329    }
330
331    /// [`bash_command_from_call`] extracts the command from a real `bash`
332    /// call's JSON arguments.
333    ///
334    /// Why: This is the exact wire shape `BashTool::schema` declares.
335    /// What: Build a `bash` call, assert the extracted command.
336    /// Test: this test.
337    #[test]
338    fn bash_command_from_call_extracts_command() {
339        let call = bash_call("c1", "cargo test -p trusty-code");
340        assert_eq!(
341            bash_command_from_call(&call).as_deref(),
342            Some("cargo test -p trusty-code")
343        );
344    }
345
346    /// [`bash_command_from_call`] returns `None` for a non-`bash` tool call.
347    ///
348    /// Why: The gate must only ever consider `bash` calls a test invocation
349    /// — a `write_file` or `delegate_to_agent` call must never match.
350    /// What: A `write_file`-named call with an unrelated argument shape.
351    /// Test: this test.
352    #[test]
353    fn bash_command_from_call_ignores_other_tools() {
354        let call = ToolCall {
355            id: "c1".into(),
356            kind: "function".into(),
357            function: FunctionCall {
358                name: "write_file".into(),
359                arguments: serde_json::json!({"path": "x", "content": "y"}).to_string(),
360            },
361        };
362        assert_eq!(bash_command_from_call(&call), None);
363    }
364
365    /// [`seed_text`] joins the `system` and `user` entries, skipping any
366    /// `assistant`/`tool` entries in between.
367    ///
368    /// Why: The trigger check must only ever consider the ORIGINAL task
369    /// prompt/project context, never text that later shows up in tool
370    /// output.
371    /// What: Build a small message list; assert the join.
372    /// Test: this test.
373    #[test]
374    fn seed_text_joins_system_and_user() {
375        let messages = vec![
376            ChatMessage::system("SYSTEM_TEXT"),
377            ChatMessage::user("USER_TEXT"),
378            ChatMessage {
379                role: "assistant".into(),
380                content: Some("mentions cargo test in passing".into()),
381                tool_calls: None,
382                tool_call_id: None,
383                name: None,
384                cache_control: None,
385            },
386        ];
387        let joined = seed_text(&messages);
388        assert!(joined.contains("SYSTEM_TEXT"));
389        assert!(joined.contains("USER_TEXT"));
390        assert!(!joined.contains("mentions cargo test"));
391    }
392
393    /// [`transcript_ran_test_command`] finds a match inside an assistant
394    /// turn's `bash` tool calls.
395    ///
396    /// Why: This is the exact shape the engineer's own transcript takes
397    /// after it runs the named suite.
398    /// What: An assistant turn with one matching `bash` call.
399    /// Test: this test.
400    #[test]
401    fn transcript_ran_test_command_detects_match() {
402        let messages = vec![assistant_with_tool_calls(vec![bash_call(
403            "c1",
404            "pytest tests/ -v",
405        )])];
406        assert!(transcript_ran_test_command(&messages));
407    }
408
409    /// [`transcript_ran_test_command`] is `false` when no `bash` call is
410    /// present at all.
411    ///
412    /// Why: Guards the common "nothing ran yet" case.
413    /// What: An empty message list.
414    /// Test: this test.
415    #[test]
416    fn transcript_ran_test_command_false_without_bash() {
417        assert!(!transcript_ran_test_command(&[]));
418    }
419
420    /// [`default_finish_gate`] trips when the task names a test command and
421    /// no matching `bash` call appears in the transcript.
422    ///
423    /// Why: This is the core acceptance behaviour — a `finish_task` call
424    /// must be rejected with a recoverable reason under exactly this
425    /// condition.
426    /// What: Seed a transcript whose task names `pytest`, with no tool
427    /// calls at all; assert the gate returns `Some`.
428    /// Test: this test.
429    #[test]
430    fn default_gate_trips_when_named_and_unrun() {
431        let transcript = Transcript::seed("system prompt", "run pytest tests/ -v before finishing");
432        let gate = default_finish_gate();
433        assert!(gate(&transcript).is_some());
434    }
435
436    /// [`default_finish_gate`] is inert when the task never names a test
437    /// command.
438    ///
439    /// Why: #2279 explicitly defers general polyglot test-suite discovery —
440    /// the gate must not invent a requirement that was never stated.
441    /// What: Seed a transcript with an unrelated task; assert `None`.
442    /// Test: this test.
443    #[test]
444    fn default_gate_inert_when_not_named() {
445        let transcript = Transcript::seed("system prompt", "implement a widget");
446        let gate = default_finish_gate();
447        assert!(gate(&transcript).is_none());
448    }
449
450    /// [`default_finish_gate`] is satisfied once a matching `bash` call has
451    /// been pushed onto the transcript.
452    ///
453    /// Why: Proves the "recover" half of the recoverable-retry contract —
454    /// after the agent runs the named tests, a second gate check must pass.
455    /// What: Seed, push an assistant turn with a matching `bash` call;
456    /// assert `None`.
457    /// Test: this test.
458    #[test]
459    fn default_gate_satisfied_when_run() {
460        let mut transcript = Transcript::seed("system prompt", "run cargo test before finishing");
461        transcript.push_assistant(None, &[bash_call("c1", "cargo test -p trusty-code")]);
462        let gate = default_finish_gate();
463        assert!(gate(&transcript).is_none());
464    }
465
466    /// [`pm_finish_gate`] trips when the PM's task names a test command but
467    /// the shared (engineer) transcript never records a matching invocation.
468    ///
469    /// Why: This is the PM-symmetric half of the acceptance criterion — the
470    /// PM must not be able to `finish_task` while its delegated engineer's
471    /// transcript shows no verification either.
472    /// What: An empty `SharedTranscript`; assert the gate trips.
473    /// Test: this test.
474    #[test]
475    fn pm_gate_trips_when_engineer_never_ran_tests() {
476        let shared: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
477        let transcript = Transcript::seed("pm system prompt", "run pytest tests/ -v");
478        let gate = pm_finish_gate(shared);
479        assert!(gate(&transcript).is_some());
480    }
481
482    /// [`pm_finish_gate`] is satisfied when a `TurnRecord` in the shared
483    /// transcript (recorded from the delegated engineer's own turns) has
484    /// `ran_test_command == true`.
485    ///
486    /// Why: Proves the PM-side gate correctly consults EXTERNAL state
487    /// (the engineer's recorded turns) rather than its own (bash-less)
488    /// transcript.
489    /// What: Seed the shared transcript with one `python-engineer` turn
490    /// carrying `ran_test_command: true`; assert `None`.
491    /// Test: this test.
492    #[test]
493    fn pm_gate_satisfied_when_engineer_ran_tests() {
494        let shared: SharedTranscript = Arc::new(Mutex::new(vec![TurnRecord {
495            role: "python-engineer".into(),
496            model: "test-model".into(),
497            text: String::new(),
498            tool_calls: vec!["bash".into()],
499            ran_test_command: true,
500            usage: crate::perf::TokenUsage::default(),
501        }]));
502        let transcript = Transcript::seed("pm system prompt", "run pytest tests/ -v");
503        let gate = pm_finish_gate(shared);
504        assert!(gate(&transcript).is_none());
505    }
506
507    /// [`pm_finish_gate`] is inert when the PM's own task never names a test
508    /// command, regardless of the shared transcript's contents.
509    ///
510    /// Why: Mirrors [`default_gate_inert_when_not_named`] for the PM path.
511    /// What: An unrelated PM task with an empty shared transcript.
512    /// Test: this test.
513    #[test]
514    fn pm_gate_inert_when_not_named() {
515        let shared: SharedTranscript = Arc::new(Mutex::new(Vec::new()));
516        let transcript = Transcript::seed("pm system prompt", "coordinate the widget build");
517        let gate = pm_finish_gate(shared);
518        assert!(gate(&transcript).is_none());
519    }
520}