trusty_code/verify_gate/mod.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//! What (#8206): naming a test command is necessary but no longer
35//! sufficient. Both gates additionally require that a test command be
36//! DETECTABLE for the bound project ([`detect::detect_test_command`]) and —
37//! for the engineer gate — that the agent's own registry carry `bash` to run
38//! it with. When either fails, `finish_task` is ACCEPTED and the completion
39//! report records that no test command ran and why; only a detectable,
40//! runnable, unrun suite still produces a refusal, and that refusal names the
41//! manifest or command it detected.
42//! Test: `verify_gate::tests::*`.
43//!
44//! [`names_test_command`]: crate::verify_gate::names_test_command
45//! [`is_test_command`]: crate::verify_gate::is_test_command
46//! [`default_finish_gate`]: crate::verify_gate::default_finish_gate
47//! [`pm_finish_gate`]: crate::verify_gate::pm_finish_gate
48//! [`detect::detect_test_command`]: crate::verify_gate::detect::detect_test_command
49
50pub mod detect;
51
52#[cfg(test)]
53mod tests;
54
55use std::path::PathBuf;
56use std::sync::Arc;
57
58use regex::Regex;
59use serde_json::Value;
60
61use crate::agent_loop::{FinishGate, Transcript};
62use crate::llm::{ChatMessage, ToolCall};
63use crate::run_task::SharedTranscript;
64use crate::tools::BASH_TOOL_NAME;
65
66use detect::{TestCommandTarget, UndetectableReason, detect_test_command};
67
68/// Recoverable-retry message fed back to a delegated engineer's own loop
69/// when its `finish_task` call is rejected.
70///
71/// Why (#8206): built per call rather than held as a `const`, so the refusal
72/// names the detected manifest or command — an agent told only that "a
73/// pytest/cargo/npm/pnpm/go test invocation" was named cannot tell WHICH
74/// suite to run.
75/// What: `target.evidence()` is the detection clause; the rest is the
76/// unchanged #2279 nudge, including the "Run the named test suite" phrase
77/// `agent_loop::tests::gate_intercept` asserts on.
78/// Test: `tests::default_gate_refusal_names_the_manifest`.
79fn gate_reason_engineer(target: &TestCommandTarget) -> String {
80 format!(
81 "finish_task rejected: {}, but no matching command has been run yet in this session. \
82 Run the named test suite via the bash tool, reconcile any failures, and only then \
83 call finish_task again.",
84 target.evidence()
85 )
86}
87
88/// Recoverable-retry message fed back to the delegating PM's own loop when
89/// its `finish_task` call is rejected because the delegated engineer never
90/// ran the named tests.
91///
92/// Why: The PM-side twin of [`gate_reason_engineer`], carrying the same
93/// #8206 evidence clause so the PM's follow-up delegation can name the suite.
94/// Test: `tests::pm_gate_trips_when_engineer_never_ran_tests`.
95fn gate_reason_pm(target: &TestCommandTarget) -> String {
96 format!(
97 "finish_task rejected: {}, but the delegated engineer's transcript shows no matching \
98 invocation yet. Delegate a follow-up task instructing the engineer to run the named \
99 test suite and reconcile any failures before finishing.",
100 target.evidence()
101 )
102}
103
104/// The note appended to an ACCEPTED completion report when the gate was
105/// triggered but could not be satisfied here (#8206).
106///
107/// Why: Closure condition 3 — the accepted finish must record that no test
108/// command ran, and why, rather than silently looking like a verified one.
109/// What: One sentence naming [`UndetectableReason::explain`]'s clause.
110/// Test: `tests::default_gate_accepts_on_empty_project_root`,
111/// `tests::default_gate_accepts_without_bash_tool`.
112fn unverified_finish_note(reason: UndetectableReason) -> String {
113 format!(
114 "Note (#8206): no test command was run in this session — {}.",
115 reason.explain()
116 )
117}
118
119/// What a [`FinishGate`] decided about a successful `finish_task` call.
120///
121/// Why (#8206): before this enum the gate could only accept or reject. An
122/// accepted finish that the gate WOULD have policed, but could not (no
123/// detectable test suite, no `bash` tool to run one with), must not read as a
124/// verified one — so a third outcome carries the reason into the recorded
125/// report instead of silently accepting.
126/// What: `Accept` leaves the report untouched; `AcceptWithNote` appends the
127/// note to the model's own `summary` before it becomes the run's output;
128/// `Reject` downgrades the call to a recoverable tool error.
129/// Test: `agent_loop::tests::finish_gate_*`,
130/// `verify_gate::tests::default_gate_accepts_on_empty_project_root`.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub enum FinishGateOutcome {
133 /// Nothing to say — the finish stands as reported.
134 Accept,
135 /// The finish stands, but the report records this note.
136 AcceptWithNote(String),
137 /// The finish is refused; the string is the recoverable retry reason.
138 Reject(String),
139}
140
141/// The project/tooling facts the engineer gate needs beyond the prompt text.
142///
143/// Why (#8206): the pre-#8206 gate was a pure text match, so it refused a
144/// finish on an empty project root, and refused an agent that had no `bash`
145/// tool to comply with — the run wedged, because nothing the agent could do
146/// would satisfy the refusal.
147/// What: `project_root` is the directory the agent's fs/bash tools are scoped
148/// to (`None` when nothing is bound); `has_bash` is whether THIS agent's
149/// gated registry carries the `bash` tool.
150/// Test: `tests::default_gate_accepts_without_bash_tool`,
151/// `tests::default_gate_accepts_on_empty_project_root`.
152#[derive(Debug, Clone, Default)]
153pub struct VerifyGateContext {
154 project_root: Option<PathBuf>,
155 has_bash: bool,
156}
157
158impl VerifyGateContext {
159 /// Construct from the bound project root and this agent's `bash`
160 /// availability.
161 ///
162 /// Test: `tests::default_gate_trips_when_named_and_unrun`.
163 pub fn new(project_root: Option<PathBuf>, has_bash: bool) -> Self {
164 Self {
165 project_root,
166 has_bash,
167 }
168 }
169}
170
171/// Build the regex alternation matching the six test-invocation shapes named
172/// in #2279's finalized trigger heuristic.
173///
174/// Why: A single compiled pattern, rather than six separate `Regex`es, keeps
175/// [`names_test_command`] and [`is_test_command`] identical in shape — "does
176/// this text contain a recognizable test-command invocation" — the only
177/// difference between the two call sites is WHICH text they scan. Compiled
178/// fresh per call rather than cached in a `once_cell`/`lazy_static` global
179/// (project convention reserves those for the tracing subscriber only); this
180/// is not a hot path — at most once per `finish_task` dispatch attempt, or
181/// once per recorded turn — so the recompilation cost is immaterial next to
182/// the LLM round-trip it sits beside.
183/// What: `pytest\s+\S+` (a pytest invocation naming a path/module),
184/// `cargo test`, `npm test`, `pnpm test`, `go test`, `python -m pytest` —
185/// exactly the six patterns #2279's finalized decision comment named.
186/// Test: covered indirectly by every `tests::*` case below.
187fn test_command_pattern() -> Regex {
188 Regex::new(
189 r"(?:pytest\s+\S+)|(?:cargo\s+test)|(?:npm\s+test)|(?:pnpm\s+test)|(?:go\s+test)|(?:python\s+-m\s+pytest)",
190 )
191 .expect("test_command_pattern: hardcoded regex literal must compile")
192}
193
194/// Whether `text` textually names a runnable test command (the gate's
195/// TRIGGER half).
196///
197/// Why: The gate must stay inert when nothing in the task/project context
198/// ever asked for a specific test command.
199/// What: `true` iff [`test_command_pattern`] finds a match anywhere in
200/// `text`.
201/// Test: `tests::names_test_command_detects_each_pattern`,
202/// `tests::names_test_command_false_on_unrelated_text`.
203pub fn names_test_command(text: &str) -> bool {
204 named_test_command(text).is_some()
205}
206
207/// The test command `text` names, as the matched substring (#8206).
208///
209/// Why: [`names_test_command`]'s boolean answer cannot name the command in a
210/// refusal message, and `detect::TestCommandTarget::PromptNamed` needs the
211/// literal text the prompt used when no manifest was found.
212/// What: The FIRST [`test_command_pattern`] match in `text`, e.g.
213/// `"cargo test"` out of "then run cargo test before finishing".
214/// Test: `tests::named_test_command_returns_the_matched_text`.
215pub fn named_test_command(text: &str) -> Option<String> {
216 test_command_pattern()
217 .find(text)
218 .map(|m| m.as_str().to_string())
219}
220
221/// Whether `command` (a `bash` tool call's shell command) IS a matching test
222/// invocation (the gate's VERIFY half).
223///
224/// Why: Reused by both [`default_finish_gate`]'s own-transcript scan and
225/// `run_task::recorder`'s per-turn `ran_test_command` signal, so the two
226/// gate sites can never independently drift on what counts as "the named
227/// tests actually ran".
228/// What: Same predicate as [`names_test_command`], applied to a single
229/// command string rather than free-form prose.
230/// Test: `tests::is_test_command_matches_each_pattern`,
231/// `tests::is_test_command_false_on_unrelated_command`.
232pub fn is_test_command(command: &str) -> bool {
233 test_command_pattern().is_match(command)
234}
235
236/// Extract the shell command from a `bash` tool call's arguments, if `call`
237/// names the `bash` tool at all.
238///
239/// Why: Shared by [`default_finish_gate`]'s own-transcript scan and
240/// `run_task::recorder::RecordingLlmClient`'s per-turn signal, so the two
241/// gate sites parse the SAME wire shape (`{"command": "..."}`) identically.
242/// What: `None` when `call.function.name != BASH_TOOL_NAME` or the
243/// arguments do not parse as a JSON object with a string `command` field.
244/// Test: `tests::bash_command_from_call_extracts_command`,
245/// `tests::bash_command_from_call_ignores_other_tools`.
246pub fn bash_command_from_call(call: &ToolCall) -> Option<String> {
247 if call.function.name != BASH_TOOL_NAME {
248 return None;
249 }
250 let parsed: Value = serde_json::from_str(&call.function.arguments).ok()?;
251 parsed.get("command")?.as_str().map(str::to_string)
252}
253
254/// Whether any `bash` call in `messages` invoked a matching test command.
255///
256/// Why: The core predicate [`default_finish_gate`] applies to a delegated
257/// engineer's own `Transcript` — factored out as a free function so it is
258/// independently unit-testable against a plain `&[ChatMessage]` without
259/// constructing a full `Transcript`.
260/// What: Flattens every assistant turn's `tool_calls`, extracts each `bash`
261/// call's command via [`bash_command_from_call`], and checks
262/// [`is_test_command`].
263/// Test: `tests::transcript_ran_test_command_detects_match`,
264/// `tests::transcript_ran_test_command_false_without_bash`.
265fn transcript_ran_test_command(messages: &[ChatMessage]) -> bool {
266 messages
267 .iter()
268 .filter_map(|m| m.tool_calls.as_ref())
269 .flatten()
270 .filter_map(bash_command_from_call)
271 .any(|cmd| is_test_command(&cmd))
272}
273
274/// Join the seeded `system` + `user` message text into one haystack for
275/// [`names_test_command`].
276///
277/// Why: `Transcript::seed` is the ONLY place raw history ever gets a
278/// `system`- or `user`-role entry, and it seeds exactly one of each — the
279/// assembled system prompt (BASE + agent prompt + project `CLAUDE.md`
280/// context) and the task text. Scanning by role (not position) stays
281/// correct even if `Transcript`'s internal layout ever changes.
282/// What: Concatenates the `content` of every `system`/`user` entry with
283/// newlines.
284/// Test: `tests::seed_text_joins_system_and_user`.
285fn seed_text(messages: &[ChatMessage]) -> String {
286 messages
287 .iter()
288 .filter(|m| m.role == "system" || m.role == "user")
289 .filter_map(|m| m.content.as_deref())
290 .collect::<Vec<_>>()
291 .join("\n")
292}
293
294/// Build the default verify-before-finish gate: scans the SAME loop's own
295/// transcript for both the trigger and the verification.
296///
297/// Why: This is the shape a delegated engineer's sub-agent loop needs — its
298/// own `bash` calls land directly in its own `Transcript`, so no external
299/// state is required.
300/// What: Returns a [`FinishGate`] closure that is inert unless
301/// [`seed_text`] of the transcript [`names_test_command`] and
302/// [`transcript_ran_test_command`] finds no match. Past that (#8206) it
303/// rejects ONLY when the agent's registry carries `bash` AND
304/// [`detect_test_command`] finds a runnable suite for `ctx`'s project root;
305/// otherwise it accepts the finish with an [`unverified_finish_note`],
306/// because no refusal the agent could act on exists.
307/// Test: `tests::default_gate_trips_when_named_and_unrun`,
308/// `tests::default_gate_inert_when_not_named`,
309/// `tests::default_gate_satisfied_when_run`,
310/// `tests::default_gate_accepts_without_bash_tool`,
311/// `tests::default_gate_accepts_on_empty_project_root`,
312/// `agent_loop::tests::finish_gate_trips_and_recovers`.
313pub fn default_finish_gate(ctx: VerifyGateContext) -> FinishGate {
314 Arc::new(move |transcript: &Transcript| {
315 let messages = transcript.messages();
316 let Some(named) = named_test_command(&seed_text(&messages)) else {
317 return FinishGateOutcome::Accept;
318 };
319 if transcript_ran_test_command(&messages) {
320 return FinishGateOutcome::Accept;
321 }
322 // #8206: a refusal the agent cannot act on wedges the run — it was
323 // refused twice in the live transcript and had no `bash` tool to
324 // comply with. Accept and record why instead.
325 if !ctx.has_bash {
326 return FinishGateOutcome::AcceptWithNote(unverified_finish_note(
327 UndetectableReason::NoBashTool,
328 ));
329 }
330 match detect_test_command(ctx.project_root.as_deref(), &named) {
331 Ok(target) => FinishGateOutcome::Reject(gate_reason_engineer(&target)),
332 Err(reason) => FinishGateOutcome::AcceptWithNote(unverified_finish_note(reason)),
333 }
334 })
335}
336
337/// Build the delegating PM's verify-before-finish gate: the trigger comes
338/// from the PM's own transcript, but the verification scans the externally
339/// shared engineer transcript instead.
340///
341/// Why: The PM's own tool registry never includes `bash` (`run_task::
342/// execute_run_task` registers only `delegate_to_agent` and `finish_task`),
343/// so scanning the PM's own `Transcript` for a `bash` call would ALWAYS
344/// report "not run" — wrongly tripping the gate even when the delegated
345/// engineer ran the named tests correctly. `shared` is the SAME
346/// `run_task::SharedTranscript` the engineer's `RecordingLlmClient` records
347/// into, so this closure sees the engineer's turns too.
348/// What: Returns a [`FinishGate`] closure inert unless the PM transcript's
349/// [`seed_text`] [`names_test_command`]; when it does, trips (returning
350/// [`gate_reason_pm`]) unless any `TurnRecord` in `shared` has
351/// `ran_test_command == true`. A poisoned lock is treated as "not run" —
352/// fail toward asking the model to verify, not toward silently finishing —
353/// and (#2857) logs `tracing::warn!` when this happens, since a poisoned
354/// lock means some other turn's code already panicked; silently folding
355/// that into an ordinary gate trip would hide the real failure.
356/// (#8206) `project_root` gets the same detectability precondition the
357/// engineer gate has: an empty or unbound root can satisfy no test command,
358/// so the PM's finish is accepted with an [`unverified_finish_note`] rather
359/// than refused. The bash half of that check is NOT mirrored here — the
360/// delegated engineer's registry is built per delegation and is not knowable
361/// at PM-loop construction; its own [`default_finish_gate`] applies it.
362/// Test: `tests::pm_gate_trips_when_engineer_never_ran_tests`,
363/// `tests::pm_gate_satisfied_when_engineer_ran_tests`,
364/// `tests::pm_gate_inert_when_not_named`,
365/// `tests::pm_gate_accepts_on_empty_project_root`,
366/// `tests::pm_gate_poisoned_lock_warns_and_trips`.
367pub fn pm_finish_gate(shared: SharedTranscript, project_root: Option<PathBuf>) -> FinishGate {
368 Arc::new(move |transcript: &Transcript| {
369 let messages = transcript.messages();
370 let Some(named) = named_test_command(&seed_text(&messages)) else {
371 return FinishGateOutcome::Accept;
372 };
373 // (#2857) A poisoned lock (some other turn's code panicked while
374 // holding it) is treated as "tests not run" — fail toward asking the
375 // model to verify, per this function's own doc. That fallback is
376 // itself a decision worth surfacing: silently swallowing the
377 // poisoning would hide a real prior panic behind an ordinary-looking
378 // gate trip.
379 let ran = shared
380 .lock()
381 .map(|turns| turns.iter().any(|t| t.ran_test_command))
382 .unwrap_or_else(|_| {
383 tracing::warn!(
384 "verify_gate: shared transcript lock poisoned (a prior turn likely \
385 panicked) — treating as tests-not-run and tripping the PM finish gate"
386 );
387 false
388 });
389 if ran {
390 return FinishGateOutcome::Accept;
391 }
392 // #8206: same detectability precondition as the engineer gate.
393 match detect_test_command(project_root.as_deref(), &named) {
394 Ok(target) => FinishGateOutcome::Reject(gate_reason_pm(&target)),
395 Err(reason) => FinishGateOutcome::AcceptWithNote(unverified_finish_note(reason)),
396 }
397 })
398}