trusty_code/redundant_run.rs
1//! Redundant full-suite test re-run suppression (#2682).
2//!
3//! Why: (bake-off L1 diagnosis) The delegated engineer re-runs the full test
4//! suite 7-14x per run, typically framed as "one final run to confirm", even
5//! when NO code has changed since the last clean pass. Each redundant re-run
6//! burns a whole turn (and the suite's wall-clock cost), inflating tcode's
7//! turn count (~33-49) far above claude-code's (~15) on the same challenge.
8//! The sibling verify-before-finish gate (#2279) guarantees the suite runs at
9//! LEAST once; this module is its complement — it stops the suite running MORE
10//! than it needs to. Together they bracket the correct behaviour: exactly one
11//! clean full-suite pass after the last code change, no more and no less.
12//! What: [`is_redundant_test_rerun`] is a pure predicate over a loop's
13//! transcript. A proposed `bash` test invocation is redundant iff the most
14//! recent prior test invocation ran the BYTE-IDENTICAL command, already PASSED,
15//! and nothing that could have changed the tree (a `write_file`/`write_files`/
16//! `edit`, or any non-test `bash` command) has run since. Command identity is
17//! load-bearing (#2804 review): a narrow run passing (`cargo test -p a`) must
18//! never suppress a broader/different one (`cargo test --workspace`,
19//! `cargo test -p b`) that never actually ran, nor may a compile-only
20//! `cargo test --no-run` suppress the real subsequent run. The predicate reuses
21//! `verify_gate`'s `is_test_command` / `bash_command_from_call` so the two
22//! gates can never drift on what counts as a test invocation. `agent_loop::AgentLoop`'s
23//! dispatch loop consults it (when suppression is enabled via
24//! `AgentLoop::with_redundant_run_suppression`) and, on a match, short-circuits
25//! the dispatch with [`REDUNDANT_RERUN_MESSAGE`] instead of actually spawning
26//! the suite — saving the turn's wall-clock cost and nudging the model to
27//! proceed to finish.
28//! Test: `redundant_run::tests::*`, plus
29//! `agent_loop::tests::redundant_test_rerun_is_suppressed` and
30//! `agent_loop::tests::test_rerun_after_edit_is_not_suppressed`.
31
32use crate::llm::{ChatMessage, ToolCall};
33use crate::tools::BASH_TOOL_NAME;
34use crate::verify_gate::{bash_command_from_call, is_test_command};
35
36/// The `ToolResult` text returned in place of a suppressed redundant re-run.
37///
38/// Why: The model must understand WHY its test command produced no fresh
39/// output, so it stops retrying and moves on — a silent no-op would just
40/// invite another confirmation run. Phrasing it as a normal (non-error)
41/// result keeps the loop calm: nothing failed, the prior pass still stands.
42/// What: A fixed, model-facing sentence explaining the suppression and the
43/// invariant it relies on — the SAME command already passed and no code has
44/// changed since. It is only ever emitted for a byte-identical re-run (see
45/// [`is_redundant_test_rerun`]), so "this exact command" is always accurate.
46/// Test: `redundant_run::tests::suppression_message_is_informative`.
47pub const REDUNDANT_RERUN_MESSAGE: &str = "skipped: this exact test command already passed \
48earlier in this session and no code has changed since (no write_file/edit and no other shell \
49command ran between that passing run and this one). Re-running the identical command would \
50produce the same result and cost a turn. The prior clean pass still stands — proceed to finish \
51the task, or run a DIFFERENT (e.g. broader) command if you need to verify something the passing \
52run did not cover.";
53
54/// Tool names that are pure read-only discovery and therefore CANNOT
55/// invalidate a passing test baseline.
56///
57/// Why: Between a clean test pass and a redundant re-run the model typically
58/// does nothing, or merely re-reads files — none of which changes the tree, so
59/// none of which makes a re-run non-redundant. Anything NOT on this allowlist
60/// (a write, an edit, an arbitrary shell command, a skill load, a delegation)
61/// is treated as potentially state-changing, which errs toward RUNNING the
62/// suite — the conservative, correctness-first default the acceptance criteria
63/// demand ("the single final run must still occur after the last code change").
64/// What: The read-only file/discovery tools registered in the engineer's tool
65/// set. `bash` is deliberately absent — a `bash` call is classified by its
66/// command (a test command preserves the baseline; any other command is
67/// treated as potentially mutating).
68/// Test: `redundant_run::tests::read_only_activity_keeps_run_redundant`,
69/// `redundant_run::tests::non_test_bash_between_runs_defeats_suppression`.
70const READ_ONLY_TOOLS: &[&str] = &[
71 "read_file",
72 "grep",
73 "glob",
74 "list_dir",
75 "search_code",
76 "recall_session",
77];
78
79/// Whether a `bash` tool-result's captured output indicates the command exited
80/// 0 (the suite PASSED).
81///
82/// Why: Only a PASSING prior run makes a re-run redundant — re-running a suite
83/// that last FAILED is legitimate (the model may have fixed something, or may
84/// be re-reading the failure), so the gate must never suppress it. The bash
85/// tool always appends a final `exit_code: N` line to its captured output
86/// (`tools::bash`), which is the one reliable pass/fail signal available from
87/// the transcript.
88/// What: `true` iff the result text, trimmed of trailing whitespace, ends with
89/// exactly `exit_code: 0`. `exit_code: 10` / `exit_code: 1` and the
90/// suppression sentinel (which carries no `exit_code:` line) all read as "not
91/// a pass".
92/// Test: `redundant_run::tests::exit_zero_reads_as_pass`,
93/// `redundant_run::tests::nonzero_and_missing_exit_read_as_not_pass`.
94fn test_result_passed(result_content: &str) -> bool {
95 result_content.trim_end().ends_with("exit_code: 0")
96}
97
98/// Whether the `tool`-role result answering `call_id` in `messages` reports a
99/// passing exit.
100///
101/// Why: A test invocation only establishes a passing baseline once its result
102/// has actually been recorded and shows exit 0; a call whose result is not yet
103/// present (e.g. the proposed re-run itself, mid-dispatch) must not count.
104/// What: Finds the first `tool` message whose `tool_call_id == call_id` and
105/// applies [`test_result_passed`] to its content; `false` when absent.
106/// Test: exercised via `is_redundant_test_rerun` in
107/// `redundant_run::tests::passing_prior_run_makes_rerun_redundant`,
108/// `redundant_run::tests::failing_prior_run_is_not_redundant`.
109fn call_result_passed(messages: &[ChatMessage], call_id: &str) -> bool {
110 messages
111 .iter()
112 .find(|m| m.role == "tool" && m.tool_call_id.as_deref() == Some(call_id))
113 .and_then(|m| m.content.as_deref())
114 .map(test_result_passed)
115 .unwrap_or(false)
116}
117
118/// Fold one completed tool `call` into the running baseline: the exact command
119/// string of the most recent test run that PASSED with nothing state-changing
120/// since, or `None`.
121///
122/// Why: Centralises the single rule that decides, per tool call, whether a
123/// prior clean test pass survives it — and, critically (#2804 review),
124/// remembers WHICH command passed so a later re-run is only suppressed when it
125/// is byte-identical. A bare `bool` would wrongly suppress a broader/different
126/// command (`cargo test --workspace`) just because a narrower one
127/// (`cargo test -- foo`) passed.
128/// What: A passing `bash` test command SETS the baseline to `Some(command)`; a
129/// FAILING test command CLEARS it (`None`); any other `bash` command CLEARS it
130/// (a shell command may have mutated the tree); a [`READ_ONLY_TOOLS`] call
131/// leaves it unchanged; every other tool CLEARS it (conservative — treat
132/// unknown effects as state-changing).
133/// Test: exercised via `is_redundant_test_rerun` across
134/// `redundant_run::tests::*`.
135fn fold_call(baseline: &mut Option<String>, call: &ToolCall, messages: &[ChatMessage]) {
136 if let Some(command) = bash_command_from_call(call) {
137 *baseline = (is_test_command(&command) && call_result_passed(messages, &call.id))
138 .then_some(command);
139 return;
140 }
141 if READ_ONLY_TOOLS.contains(&call.function.name.as_str()) {
142 return;
143 }
144 *baseline = None;
145}
146
147/// Whether two shell command strings are the "same" test invocation for
148/// suppression purposes.
149///
150/// Why: Suppression must require command IDENTITY (#2804 review): re-running a
151/// DIFFERENT command — a broader scope, a different package, a previously
152/// compile-only `--no-run` now actually executing — is a genuinely-needed run,
153/// never redundant. Defaulting to exact match (not a fuzzy/normalized one)
154/// keeps the gate conservative: a false "same" verdict would suppress a real
155/// run, so anything short of certainty must read as "different".
156/// What: Exact string equality after trimming leading/trailing whitespace only
157/// — the sole normalization, so a stray surrounding space cannot force an
158/// otherwise-identical re-run to execute. Internal differences (flags, paths,
159/// package selectors, `--no-run`) are all preserved and therefore all count as
160/// a different command.
161/// Test: `redundant_run::tests::different_test_command_after_pass_is_not_redundant`,
162/// `redundant_run::tests::passing_prior_run_makes_rerun_redundant`.
163fn same_test_command(baseline: &str, pending: &str) -> bool {
164 baseline.trim() == pending.trim()
165}
166
167/// Whether the pending `bash` test call `current_call_id` would be a redundant
168/// re-run: the SAME command already passed with nothing changed since.
169///
170/// Why: This is the gate `agent_loop::AgentLoop::dispatch_all` consults before
171/// spawning a test suite — the whole point of #2682. It must be conservative:
172/// a `true` result suppresses a real execution, so a false positive would hide
173/// a genuinely-needed run. The predicate therefore only returns `true` when a
174/// prior run demonstrably PASSED, every tool call since is demonstrably
175/// non-mutating, AND (#2804 review) the pending command is byte-identical to
176/// that passing command — a broader or otherwise-different command is never
177/// suppressed.
178/// What: Folds every assistant tool call in `messages`, in order, up to (but
179/// excluding) the call identified by `current_call_id` — the proposed re-run
180/// itself, and anything after it, is irrelevant — tracking the exact command
181/// of the most recent still-valid passing test run (or `None`). On reaching
182/// the pending call, extracts ITS command and returns `true` only when a
183/// baseline command exists and [`same_test_command`] holds. Because the
184/// proposed call's own (not-yet-recorded) result is never consulted, and any
185/// same-turn write/edit BEFORE it clears the baseline, the answer reflects tree
186/// state exactly as of just before the re-run.
187/// Test: `redundant_run::tests::passing_prior_run_makes_rerun_redundant`,
188/// `redundant_run::tests::different_test_command_after_pass_is_not_redundant`,
189/// `redundant_run::tests::failing_prior_run_is_not_redundant`,
190/// `redundant_run::tests::edit_between_runs_defeats_suppression`,
191/// `redundant_run::tests::no_prior_run_is_not_redundant`,
192/// `redundant_run::tests::same_turn_edit_before_rerun_defeats_suppression`.
193pub fn is_redundant_test_rerun(messages: &[ChatMessage], current_call_id: &str) -> bool {
194 let mut baseline: Option<String> = None;
195 for message in messages {
196 if message.role != "assistant" {
197 continue;
198 }
199 let Some(calls) = message.tool_calls.as_ref() else {
200 continue;
201 };
202 for call in calls {
203 if call.id == current_call_id {
204 return match (baseline.as_deref(), bash_command_from_call(call)) {
205 (Some(passed), Some(pending)) => same_test_command(passed, &pending),
206 _ => false,
207 };
208 }
209 fold_call(&mut baseline, call, messages);
210 }
211 }
212 // The pending call was not found in the transcript — fail safe (never
213 // suppress a call we cannot locate). In practice `dispatch_all` always
214 // passes a `call.id` present in the just-pushed assistant turn.
215 false
216}
217
218/// Whether `call` is a `bash` invocation of a test command — the cheap
219/// pre-filter `dispatch_all` applies before the fuller
220/// [`is_redundant_test_rerun`] transcript scan.
221///
222/// Why: Only a `bash` test call can ever be a redundant re-run, so the dispatch
223/// loop should not pay for the transcript scan on every other tool call.
224/// What: `true` iff `call` names [`BASH_TOOL_NAME`] and its extracted command
225/// [`is_test_command`].
226/// Test: `redundant_run::tests::is_test_bash_call_true_only_for_test_bash`.
227pub fn is_test_bash_call(call: &ToolCall) -> bool {
228 call.function.name == BASH_TOOL_NAME
229 && bash_command_from_call(call).is_some_and(|c| is_test_command(&c))
230}
231
232// ── Tests ─────────────────────────────────────────────────────────────────────
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237 use crate::llm::FunctionCall;
238
239 /// Build a `bash` tool call with the given id and command.
240 fn bash_call(id: &str, command: &str) -> ToolCall {
241 ToolCall {
242 id: id.into(),
243 kind: "function".into(),
244 function: FunctionCall {
245 name: BASH_TOOL_NAME.into(),
246 arguments: serde_json::json!({ "command": command }).to_string(),
247 },
248 }
249 }
250
251 /// Build a non-`bash` tool call (e.g. `write_file`, `read_file`).
252 fn tool_call(id: &str, name: &str) -> ToolCall {
253 ToolCall {
254 id: id.into(),
255 kind: "function".into(),
256 function: FunctionCall {
257 name: name.into(),
258 arguments: "{}".into(),
259 },
260 }
261 }
262
263 /// An assistant turn carrying the given tool calls.
264 fn assistant(calls: Vec<ToolCall>) -> ChatMessage {
265 ChatMessage {
266 role: "assistant".into(),
267 content: None,
268 tool_calls: Some(calls),
269 tool_call_id: None,
270 name: None,
271 cache_control: None,
272 }
273 }
274
275 /// A `tool`-role result answering `call_id` with a bash-shaped body ending
276 /// in `exit_code: {code}`.
277 fn bash_result(call_id: &str, code: i32) -> ChatMessage {
278 ChatMessage::tool_result(
279 call_id,
280 BASH_TOOL_NAME,
281 format!("stdout:\nok\nexit_code: {code}"),
282 )
283 }
284
285 /// [`test_result_passed`] treats a trailing `exit_code: 0` as a pass.
286 ///
287 /// Why: Exit 0 is the one pass signal the bash tool guarantees.
288 /// What: Assert on a realistic passing bash body.
289 /// Test: this test.
290 #[test]
291 fn exit_zero_reads_as_pass() {
292 assert!(test_result_passed("stdout:\n5 passed\nexit_code: 0"));
293 assert!(test_result_passed("exit_code: 0\n"));
294 }
295
296 /// [`test_result_passed`] rejects non-zero and missing exit codes.
297 ///
298 /// Why: A failing or unknown run must never establish a passing baseline —
299 /// and `exit_code: 10` must not be mistaken for `exit_code: 0`.
300 /// What: Non-zero exits, the suppression sentinel, and empty text.
301 /// Test: this test.
302 #[test]
303 fn nonzero_and_missing_exit_read_as_not_pass() {
304 assert!(!test_result_passed("stderr:\nFAILED\nexit_code: 1"));
305 assert!(!test_result_passed("exit_code: 10"));
306 assert!(!test_result_passed(REDUNDANT_RERUN_MESSAGE));
307 assert!(!test_result_passed(""));
308 }
309
310 /// A passing prior run with nothing since makes an identical re-run
311 /// redundant.
312 ///
313 /// Why: This is the core acceptance behaviour — the exact "one final run to
314 /// confirm" loop the ticket eliminates.
315 /// What: Turn 1 runs `cargo test` and it passes (exit 0); turn 2 proposes
316 /// `cargo test` again with nothing in between; assert redundant.
317 /// Test: this test.
318 #[test]
319 fn passing_prior_run_makes_rerun_redundant() {
320 let messages = vec![
321 assistant(vec![bash_call("t1", "cargo test -p trusty-code")]),
322 bash_result("t1", 0),
323 assistant(vec![bash_call("t2", "cargo test -p trusty-code")]),
324 ];
325 assert!(is_redundant_test_rerun(&messages, "t2"));
326 }
327
328 /// A DIFFERENT test command after a pass is NOT redundant — suppression
329 /// requires command IDENTITY (#2804 review).
330 ///
331 /// Why: A narrow run passing (`cargo test -p a`) must never suppress a
332 /// broader/different run (`cargo test -p b`, `cargo test --workspace`) that
333 /// was never actually executed — that would silently skip real coverage.
334 /// What: Turn 1 runs `cargo test -p a` and passes; turn 2 proposes
335 /// `cargo test -p b`; assert NOT redundant. The reverse (same command) is
336 /// covered by `passing_prior_run_makes_rerun_redundant`.
337 /// Test: this test.
338 #[test]
339 fn different_test_command_after_pass_is_not_redundant() {
340 let messages = vec![
341 assistant(vec![bash_call("t1", "cargo test -p a")]),
342 bash_result("t1", 0),
343 assistant(vec![bash_call("t2", "cargo test -p b")]),
344 ];
345 assert!(!is_redundant_test_rerun(&messages, "t2"));
346 }
347
348 /// A `--no-run` compile-only pass does NOT suppress a subsequent REAL run
349 /// of the same suite — because the real run's command string differs
350 /// (#2804 review, secondary concern).
351 ///
352 /// Why: `cargo test --no-run` compiles but executes zero tests, then exits
353 /// 0. Command-identity matching already prevents it suppressing a genuine
354 /// `cargo test` run: the two command strings are not equal, so the gate
355 /// treats them as different runs — no special-casing of `--no-run` needed.
356 /// What: Turn 1 runs `cargo test --no-run` (exit 0); turn 2 proposes the
357 /// real `cargo test`; assert NOT redundant.
358 /// Test: this test.
359 #[test]
360 fn compile_only_pass_does_not_suppress_real_run() {
361 let messages = vec![
362 assistant(vec![bash_call("t1", "cargo test --no-run")]),
363 bash_result("t1", 0),
364 assistant(vec![bash_call("t2", "cargo test")]),
365 ];
366 assert!(!is_redundant_test_rerun(&messages, "t2"));
367 }
368
369 /// Surrounding whitespace does not defeat identity — a re-run of the SAME
370 /// command with a stray leading/trailing space is still redundant.
371 ///
372 /// Why: `same_test_command` trims outer whitespace only, so a trivially
373 /// re-emitted command is still recognised while every internal difference
374 /// (flags, scope) is preserved.
375 /// What: Turn 1 `cargo test` passes; turn 2 proposes ` cargo test ` (outer
376 /// spaces); assert redundant.
377 /// Test: this test.
378 #[test]
379 fn outer_whitespace_does_not_defeat_identity() {
380 let messages = vec![
381 assistant(vec![bash_call("t1", "cargo test")]),
382 bash_result("t1", 0),
383 assistant(vec![bash_call("t2", " cargo test ")]),
384 ];
385 assert!(is_redundant_test_rerun(&messages, "t2"));
386 }
387
388 /// A FAILING prior run makes a re-run NOT redundant.
389 ///
390 /// Why: The model may re-run a failing suite legitimately; suppressing it
391 /// would hide the failure and break the loop's self-correction.
392 /// What: Turn 1's `cargo test` exits 1; turn 2 proposes it again; assert
393 /// NOT redundant.
394 /// Test: this test.
395 #[test]
396 fn failing_prior_run_is_not_redundant() {
397 let messages = vec![
398 assistant(vec![bash_call("t1", "cargo test")]),
399 bash_result("t1", 1),
400 assistant(vec![bash_call("t2", "cargo test")]),
401 ];
402 assert!(!is_redundant_test_rerun(&messages, "t2"));
403 }
404
405 /// A `write_file`/`edit` between a passing run and a re-run defeats
406 /// suppression — the genuinely-needed post-change run still fires.
407 ///
408 /// Why: This is the correctness guarantee the acceptance criteria name:
409 /// "the single final run must still occur after the last code change".
410 /// What: pass → `edit` → propose re-run; assert NOT redundant.
411 /// Test: this test.
412 #[test]
413 fn edit_between_runs_defeats_suppression() {
414 let messages = vec![
415 assistant(vec![bash_call("t1", "cargo test")]),
416 bash_result("t1", 0),
417 assistant(vec![tool_call("e1", "edit")]),
418 ChatMessage::tool_result("e1", "edit", "edited"),
419 assistant(vec![bash_call("t2", "cargo test")]),
420 ];
421 assert!(!is_redundant_test_rerun(&messages, "t2"));
422 }
423
424 /// Read-only activity (read_file/grep/glob) between a passing run and a
425 /// re-run keeps the re-run redundant.
426 ///
427 /// Why: Re-reading files changes nothing on disk, so a re-run after only
428 /// reads is still a wasted confirmation.
429 /// What: pass → `read_file` + `grep` → propose re-run; assert redundant.
430 /// Test: this test.
431 #[test]
432 fn read_only_activity_keeps_run_redundant() {
433 let messages = vec![
434 assistant(vec![bash_call("t1", "pytest tests/ -v")]),
435 bash_result("t1", 0),
436 assistant(vec![tool_call("r1", "read_file"), tool_call("g1", "grep")]),
437 ChatMessage::tool_result("r1", "read_file", "..."),
438 ChatMessage::tool_result("g1", "grep", "..."),
439 assistant(vec![bash_call("t2", "pytest tests/ -v")]),
440 ];
441 assert!(is_redundant_test_rerun(&messages, "t2"));
442 }
443
444 /// A non-test `bash` command between runs defeats suppression.
445 ///
446 /// Why: An arbitrary shell command (`sed -i`, `git checkout`, a build) may
447 /// mutate the tree, so a subsequent test run is not provably redundant.
448 /// What: pass → `bash: git checkout .` → propose re-run; assert NOT
449 /// redundant.
450 /// Test: this test.
451 #[test]
452 fn non_test_bash_between_runs_defeats_suppression() {
453 let messages = vec![
454 assistant(vec![bash_call("t1", "cargo test")]),
455 bash_result("t1", 0),
456 assistant(vec![bash_call("b1", "git checkout .")]),
457 bash_result("b1", 0),
458 assistant(vec![bash_call("t2", "cargo test")]),
459 ];
460 assert!(!is_redundant_test_rerun(&messages, "t2"));
461 }
462
463 /// With no prior test run at all, the first run is never redundant.
464 ///
465 /// Why: The first execution is always genuinely needed — the gate must be
466 /// inert until a baseline exists.
467 /// What: A single proposed `cargo test` with empty history; assert NOT
468 /// redundant.
469 /// Test: this test.
470 #[test]
471 fn no_prior_run_is_not_redundant() {
472 let messages = vec![assistant(vec![bash_call("t1", "cargo test")])];
473 assert!(!is_redundant_test_rerun(&messages, "t1"));
474 }
475
476 /// A same-turn edit emitted BEFORE the re-run (batched) defeats
477 /// suppression.
478 ///
479 /// Why: The model can batch `edit` + `cargo test` in one turn; the edit
480 /// must invalidate the prior baseline even though it shares the proposed
481 /// run's turn.
482 /// What: pass → [turn: `edit` then `cargo test`]; propose the same-turn
483 /// `cargo test`; assert NOT redundant.
484 /// Test: this test.
485 #[test]
486 fn same_turn_edit_before_rerun_defeats_suppression() {
487 let messages = vec![
488 assistant(vec![bash_call("t1", "cargo test")]),
489 bash_result("t1", 0),
490 assistant(vec![tool_call("e1", "edit"), bash_call("t2", "cargo test")]),
491 ];
492 assert!(!is_redundant_test_rerun(&messages, "t2"));
493 }
494
495 /// [`is_test_bash_call`] is true only for a `bash` call whose command is a
496 /// test command.
497 ///
498 /// Why: The dispatch-loop pre-filter must not trip on a non-`bash` tool or
499 /// a non-test shell command.
500 /// What: A test bash call (true), a non-test bash call (false), a
501 /// `write_file` call (false).
502 /// Test: this test.
503 #[test]
504 fn is_test_bash_call_true_only_for_test_bash() {
505 assert!(is_test_bash_call(&bash_call("a", "cargo test")));
506 assert!(!is_test_bash_call(&bash_call("b", "git status")));
507 assert!(!is_test_bash_call(&tool_call("c", "write_file")));
508 }
509
510 /// The suppression message names the invariant it relies on so the model
511 /// can trust it.
512 ///
513 /// Why: A vague message would invite the very re-run it means to prevent.
514 /// What: Assert the sentinel mentions "already passed" and "proceed to
515 /// finish".
516 /// Test: this test.
517 #[test]
518 fn suppression_message_is_informative() {
519 assert!(REDUNDANT_RERUN_MESSAGE.contains("already passed"));
520 assert!(REDUNDANT_RERUN_MESSAGE.contains("proceed to finish"));
521 }
522}