trusty_code/verify_gate/detect.rs
1//! #8206: project-side detection of a runnable test command, the precondition
2//! the #2279 verify-before-finish trigger was missing.
3//!
4//! Why: [`super::names_test_command`] is a pure text match over the task
5//! prompt and project context. On an EMPTY project root — a projectless
6//! `tcode tui` run whose work root is a fresh scratch dir (#8205) — a prompt
7//! that merely says "run `cargo test`" tripped the gate even though no
8//! command could possibly have satisfied it, and the run wedged: the agent
9//! was refused, could not comply, and was refused again. This module answers
10//! the question the gate should have asked first — "is there anything here a
11//! test command could run against?".
12//! What: [`detect_test_command`] probes the bound project root for a manifest
13//! that implies a specific test command (`Cargo.toml`, a `package.json` with
14//! a `test` script, a pytest config, `go.mod`), falling back to the
15//! prompt-named command when the root is non-empty but carries no recognised
16//! manifest. A missing root, or an empty one, yields an
17//! [`UndetectableReason`] instead — the gate turns that into an accepted
18//! finish carrying a note, never a refusal.
19//! Test: `verify_gate::tests::detect_*`.
20
21use std::path::Path;
22
23/// What a runnable test command was detected FROM, for the bound project.
24///
25/// Why: The refusal message must name the evidence so the agent knows what to
26/// run — #8206's second closure condition. Carrying the manifest/command
27/// through the detection result is what makes that message specific rather
28/// than the pre-#8206 generic "a pytest/cargo/npm/pnpm/go test invocation".
29/// What: `Manifest` when a root manifest implies a command; `PromptNamed`
30/// when the root is non-empty but only the prompt names one.
31/// Test: `verify_gate::tests::detect_manifest_names_each_ecosystem`,
32/// `verify_gate::tests::detect_falls_back_to_prompt_named_on_non_empty_root`.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum TestCommandTarget {
35 /// A manifest at the project root implies this test command.
36 Manifest {
37 /// The manifest's filename, e.g. `Cargo.toml`.
38 manifest: String,
39 /// The command it implies, e.g. `cargo test`.
40 command: String,
41 },
42 /// No recognised manifest, but the root is non-empty and the prompt names
43 /// a command — the matched prompt text.
44 PromptNamed {
45 /// The command text matched in the prompt/project context.
46 command: String,
47 },
48}
49
50impl TestCommandTarget {
51 /// The evidence phrase embedded in a refusal message.
52 ///
53 /// Why: #8206 closure condition 2 — a refusal must name the detected
54 /// manifest or command.
55 /// What: A clause reading naturally after "finish_task rejected: ".
56 /// Test: `verify_gate::tests::default_gate_refusal_names_the_manifest`.
57 pub fn evidence(&self) -> String {
58 match self {
59 Self::Manifest { manifest, command } => format!(
60 "the project root's `{manifest}` implies a runnable test command (`{command}`)"
61 ),
62 Self::PromptNamed { command } => format!(
63 "the task prompt or project context names a runnable test command (`{command}`)"
64 ),
65 }
66 }
67}
68
69/// Why no test command could be detected — the reason the accepted finish
70/// records instead of a refusal.
71///
72/// Why: #8206 closure condition 3 — `finish_task` is accepted in this arm and
73/// the report states WHY no test command ran.
74/// What: The three unsatisfiable states: no bound project, an empty root, or
75/// an agent whose registry carries no `bash` tool to run anything with.
76/// Test: `verify_gate::tests::detect_undetectable_without_root_or_on_empty_root`.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum UndetectableReason {
79 /// No project is bound to this run at all.
80 NoProjectBound,
81 /// A root is bound, but it holds no files.
82 EmptyProjectRoot,
83 /// The agent's tool registry carries no `bash` tool.
84 NoBashTool,
85}
86
87impl UndetectableReason {
88 /// One clause explaining this reason, for the accepted finish's note.
89 ///
90 /// Test: `verify_gate::tests::default_gate_accepts_on_empty_project_root`,
91 /// `verify_gate::tests::default_gate_accepts_without_bash_tool`.
92 pub fn explain(self) -> &'static str {
93 match self {
94 Self::NoProjectBound => {
95 "no project is bound to this session, so no test command could run"
96 }
97 Self::EmptyProjectRoot => {
98 "the bound project root is empty, so there is no test suite to run"
99 }
100 Self::NoBashTool => {
101 "this agent's tool registry carries no `bash` tool, so no shell command \
102 could be run at all"
103 }
104 }
105 }
106}
107
108/// Whether `root` holds a manifest implying a specific test command.
109///
110/// Why: A manifest is the strongest evidence a test command is actually
111/// runnable here, and it names the command precisely enough to put in the
112/// refusal.
113/// What: First match wins, in the order Rust → Node → Python → Go. A
114/// `package.json` counts only when it declares a non-empty `scripts.test`;
115/// the command it implies is `pnpm test` when a `pnpm-lock.yaml` sits beside
116/// it, `npm test` otherwise.
117/// Test: `verify_gate::tests::detect_manifest_names_each_ecosystem`,
118/// `verify_gate::tests::detect_package_json_without_test_script_is_not_a_manifest`.
119fn manifest_command(root: &Path) -> Option<(String, String)> {
120 if root.join("Cargo.toml").is_file() {
121 return Some(("Cargo.toml".to_string(), "cargo test".to_string()));
122 }
123 if package_json_has_test_script(root) {
124 let command = if root.join("pnpm-lock.yaml").is_file() {
125 "pnpm test"
126 } else {
127 "npm test"
128 };
129 return Some(("package.json".to_string(), command.to_string()));
130 }
131 for config in ["pyproject.toml", "pytest.ini"] {
132 if root.join(config).is_file() {
133 return Some((config.to_string(), "pytest".to_string()));
134 }
135 }
136 if root.join("go.mod").is_file() {
137 return Some(("go.mod".to_string(), "go test ./...".to_string()));
138 }
139 None
140}
141
142/// Whether `root/package.json` declares a non-empty `scripts.test`.
143///
144/// Why: A `package.json` with no `test` script implies no runnable command —
145/// `npm test` there exits non-zero with "Missing script", which is not a
146/// suite the agent can reconcile.
147/// What: Unreadable or unparsable JSON is `false` — fail toward accepting the
148/// finish, never toward a refusal the agent cannot satisfy.
149/// Test: `verify_gate::tests::detect_package_json_without_test_script_is_not_a_manifest`.
150fn package_json_has_test_script(root: &Path) -> bool {
151 let Ok(text) = std::fs::read_to_string(root.join("package.json")) else {
152 return false;
153 };
154 let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&text) else {
155 return false;
156 };
157 parsed
158 .get("scripts")
159 .and_then(|s| s.get("test"))
160 .and_then(|t| t.as_str())
161 .is_some_and(|t| !t.trim().is_empty())
162}
163
164/// Whether `root` holds no entries at all (or cannot be read).
165///
166/// Why: An unreadable root is treated as empty for the same reason an empty
167/// one is — the gate must not refuse a finish over a suite it cannot show is
168/// there.
169/// Test: `verify_gate::tests::detect_undetectable_without_root_or_on_empty_root`.
170fn is_empty_dir(root: &Path) -> bool {
171 match std::fs::read_dir(root) {
172 Ok(mut entries) => entries.next().is_none(),
173 Err(_) => true,
174 }
175}
176
177/// Detect the test command the gate would require, for the bound project.
178///
179/// Why: The missing half of #2279's trigger — the gate may only refuse a
180/// finish over a command that could actually have been run here (#8206).
181/// What: `Err(UndetectableReason)` when no root is bound or the root is
182/// empty; otherwise `Ok` with the manifest-implied command, or the
183/// `prompt_named` text when the non-empty root carries no recognised
184/// manifest. `prompt_named` is the substring `super::named_test_command`
185/// matched in the task prompt / project context.
186/// Test: `verify_gate::tests::detect_manifest_names_each_ecosystem`,
187/// `verify_gate::tests::detect_undetectable_without_root_or_on_empty_root`,
188/// `verify_gate::tests::detect_falls_back_to_prompt_named_on_non_empty_root`.
189pub fn detect_test_command(
190 root: Option<&Path>,
191 prompt_named: &str,
192) -> Result<TestCommandTarget, UndetectableReason> {
193 let Some(root) = root else {
194 return Err(UndetectableReason::NoProjectBound);
195 };
196 if let Some((manifest, command)) = manifest_command(root) {
197 return Ok(TestCommandTarget::Manifest { manifest, command });
198 }
199 if is_empty_dir(root) {
200 return Err(UndetectableReason::EmptyProjectRoot);
201 }
202 Ok(TestCommandTarget::PromptNamed {
203 command: prompt_named.to_string(),
204 })
205}