返回 CodeWhale
verifier.rs
根目录 / crates / engine / src / tools / verifier.rs
1 //! Parallel verifier ensemble tool: `run_verifiers`.
2 //!
3 //! This is the agent-facing path for "parallelize the verifier, not the
4 //! generator": one tool call fans out to independent project checks across
5 //! common ecosystems and returns a single structured verdict.
6
7 use std::collections::{BTreeSet, HashMap};
8 use std::fs;
9 use std::path::{Path, PathBuf};
10 use std::process::Stdio;
11 use std::time::{Duration, Instant};
12
13 use async_trait::async_trait;
14 use serde::{Deserialize, Serialize};
15 use serde_json::{Value, json};
16
17 use codewhale_dependencies::ExternalTool;
18
19 use super::shell::{ShellResult, ShellStatus};
20 use super::spec::{
21 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
22 };
23 use super::test_runner::{
24 DEFAULT_AUTO_BACKGROUND_TIMEOUT_MS, ForegroundJobGuard, background_job_metadata,
25 spawn_runner_job,
26 };
27
28 const DEFAULT_MAX_PYTHON_FILES: usize = 200;
29 /// Wall-clock bound for a foreground gate unless the call sets `timeout_ms`.
30 /// Background gates are shell jobs, which the shell manager does not bound;
31 /// they run until they finish or are cancelled through task state, so
32 /// `timeout_ms` is refused there.
33 const DEFAULT_GATE_TIMEOUT_MS: u64 = 600_000;
34 const MAX_GATE_TIMEOUT_MS: u64 = 1_800_000;
35
36 fn gate_timeout_ms(timeout_ms: Option<u64>) -> Result<u64, ToolError> {
37 let ms = timeout_ms.unwrap_or(DEFAULT_GATE_TIMEOUT_MS);
38 if (1..=MAX_GATE_TIMEOUT_MS).contains(&ms) {
39 Ok(ms)
40 } else {
41 Err(ToolError::invalid_input(format!(
42 "timeout_ms must be between 1 and {MAX_GATE_TIMEOUT_MS}"
43 )))
44 }
45 }
46 /// Bytes of a gate stream kept in memory from its start, and from its end,
47 /// once the stream is longer than both together. Every byte also goes to a
48 /// session artifact, so the middle stays readable (#6508). What the model
49 /// sees of the result is the engine's one recoverable budget.
50 const GATE_CAPTURE_HEAD_BYTES: usize = 512 * 1024;
51 const GATE_CAPTURE_TAIL_BYTES: usize = 512 * 1024;
52 /// After a gate's own process exits, how long a helper it started may keep
53 /// stdout/stderr open before the gate's process group is killed.
54 const GATE_PIPE_DRAIN_GRACE: Duration = Duration::from_secs(2);
55
56 /// Tool for running independent verifier gates concurrently.
57 pub struct RunVerifiersTool;
58
59 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
60 #[serde(rename_all = "snake_case")]
61 enum VerifierProfile {
62 Auto,
63 Rust,
64 Node,
65 Python,
66 Go,
67 }
68
69 impl VerifierProfile {
70 fn parse(raw: &str) -> Result<Self, ToolError> {
71 match raw {
72 "auto" => Ok(Self::Auto),
73 "rust" => Ok(Self::Rust),
74 "node" => Ok(Self::Node),
75 "python" => Ok(Self::Python),
76 "go" => Ok(Self::Go),
77 other => Err(ToolError::invalid_input(format!(
78 "Unsupported profile '{other}'. Expected one of: auto, rust, node, python, go"
79 ))),
80 }
81 }
82
83 fn as_str(self) -> &'static str {
84 match self {
85 Self::Auto => "auto",
86 Self::Rust => "rust",
87 Self::Node => "node",
88 Self::Python => "python",
89 Self::Go => "go",
90 }
91 }
92 }
93
94 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
95 #[serde(rename_all = "snake_case")]
96 enum VerifierLevel {
97 Quick,
98 Full,
99 }
100
101 impl VerifierLevel {
102 fn parse(raw: &str) -> Result<Self, ToolError> {
103 match raw {
104 "quick" => Ok(Self::Quick),
105 "full" => Ok(Self::Full),
106 other => Err(ToolError::invalid_input(format!(
107 "Unsupported level '{other}'. Expected one of: quick, full"
108 ))),
109 }
110 }
111
112 fn as_str(self) -> &'static str {
113 match self {
114 Self::Quick => "quick",
115 Self::Full => "full",
116 }
117 }
118 }
119
120 #[derive(Debug, Clone, Deserialize)]
121 #[serde(default, deny_unknown_fields)]
122 struct RunVerifiersInput {
123 profile: String,
124 level: String,
125 max_python_files: usize,
126 background: Option<bool>,
127 cwd: Option<String>,
128 timeout_ms: Option<u64>,
129 }
130
131 impl Default for RunVerifiersInput {
132 fn default() -> Self {
133 Self {
134 profile: "auto".to_string(),
135 level: "quick".to_string(),
136 max_python_files: DEFAULT_MAX_PYTHON_FILES,
137 background: None,
138 cwd: None,
139 timeout_ms: None,
140 }
141 }
142 }
143
144 #[derive(Debug, Clone)]
145 struct VerifierGate {
146 name: String,
147 ecosystem: String,
148 cwd: PathBuf,
149 program: Option<String>,
150 args: Vec<String>,
151 env: Vec<(String, String)>,
152 skipped_reason: Option<String>,
153 timeout: Duration,
154 }
155
156 impl VerifierGate {
157 fn result(&self, status: GateStatus) -> GateResult {
158 GateResult {
159 name: self.name.clone(),
160 ecosystem: self.ecosystem.clone(),
161 status,
162 command: render_command(self.program.as_deref(), &self.args),
163 cwd: self.cwd.display().to_string(),
164 exit_code: None,
165 duration_ms: 0,
166 stdout: String::new(),
167 stderr: String::new(),
168 stdout_truncated: false,
169 stderr_truncated: false,
170 stdout_log_ref: None,
171 stderr_log_ref: None,
172 skipped_reason: None,
173 zero_tests_matched: false,
174 warning: None,
175 }
176 }
177
178 fn skipped(&self, reason: impl Into<String>) -> GateResult {
179 GateResult {
180 skipped_reason: Some(reason.into()),
181 ..self.result(GateStatus::Skipped)
182 }
183 }
184
185 fn skipped_without_program(&self) -> GateResult {
186 self.skipped(
187 self.skipped_reason
188 .as_deref()
189 .unwrap_or("verifier has no executable program"),
190 )
191 }
192
193 fn failed(&self, stderr: impl Into<String>) -> GateResult {
194 GateResult {
195 stderr: stderr.into(),
196 ..self.result(GateStatus::Failed)
197 }
198 }
199 }
200
201 #[derive(Debug, Clone, Serialize, Deserialize)]
202 struct GateResult {
203 name: String,
204 ecosystem: String,
205 status: GateStatus,
206 command: String,
207 cwd: String,
208 exit_code: Option<i32>,
209 duration_ms: u64,
210 stdout: String,
211 stderr: String,
212 stdout_truncated: bool,
213 stderr_truncated: bool,
214 /// Session artifact (`art_<id>`) holding the whole stream when it was
215 /// longer than what the result keeps in memory (#6508).
216 #[serde(default, skip_serializing_if = "Option::is_none")]
217 stdout_log_ref: Option<String>,
218 #[serde(default, skip_serializing_if = "Option::is_none")]
219 stderr_log_ref: Option<String>,
220 skipped_reason: Option<String>,
221 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
222 zero_tests_matched: bool,
223 #[serde(default, skip_serializing_if = "Option::is_none")]
224 warning: Option<String>,
225 }
226
227 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
228 #[serde(rename_all = "snake_case")]
229 enum GateStatus {
230 Passed,
231 Failed,
232 Skipped,
233 }
234
235 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
236 #[serde(rename_all = "snake_case")]
237 enum VerifierVerdict {
238 Pass,
239 Partial,
240 Fail,
241 }
242
243 impl VerifierVerdict {
244 fn from_counts(gate_count: usize, failed: usize, skipped: usize) -> Self {
245 if failed > 0 {
246 Self::Fail
247 } else if skipped > 0 || gate_count == 0 {
248 Self::Partial
249 } else {
250 Self::Pass
251 }
252 }
253 }
254
255 #[derive(Debug, Clone, Serialize, Deserialize)]
256 struct RunVerifiersOutput {
257 success: bool,
258 profile: String,
259 level: String,
260 workspace: String,
261 gate_count: usize,
262 passed: usize,
263 failed: usize,
264 skipped: usize,
265 verifier_verdict: VerifierVerdict,
266 summary: String,
267 gates: Vec<GateResult>,
268 }
269
270 #[derive(Debug, Clone, Copy)]
271 struct GateCounts {
272 passed: usize,
273 failed: usize,
274 skipped: usize,
275 }
276
277 impl GateCounts {
278 fn of(results: &[GateResult]) -> Self {
279 let count = |status: GateStatus| {
280 results
281 .iter()
282 .filter(|result| result.status == status)
283 .count()
284 };
285 Self {
286 passed: count(GateStatus::Passed),
287 failed: count(GateStatus::Failed),
288 skipped: count(GateStatus::Skipped),
289 }
290 }
291
292 fn success(self) -> bool {
293 self.failed == 0 && self.skipped == 0
294 }
295 }
296
297 #[derive(Debug)]
298 struct GateJob {
299 gate: VerifierGate,
300 task_id: String,
301 }
302
303 impl GateJob {
304 fn finish(self, snapshot: ShellResult, metadata: &Value) -> GateResult {
305 let mut stderr = snapshot.stderr;
306 if snapshot.status == ShellStatus::Killed {
307 append_note(
308 &mut stderr,
309 "[verifier gate cancelled and its process group was killed]",
310 );
311 }
312 let completed = snapshot.status == ShellStatus::Completed;
313 let truncated = snapshot.stdout_truncated || snapshot.stderr_truncated;
314 let zero_tests = if completed && !truncated {
315 zero_test_warning(&snapshot.stdout, &mut stderr)
316 } else {
317 None
318 };
319 let zero_tests_matched = zero_tests.is_some();
320 let status = if completed && !zero_tests_matched {
321 GateStatus::Passed
322 } else {
323 GateStatus::Failed
324 };
325 GateResult {
326 exit_code: snapshot.exit_code.and_then(|code| i32::try_from(code).ok()),
327 duration_ms: snapshot.duration_ms,
328 stdout: snapshot.stdout,
329 stderr,
330 stdout_truncated: snapshot.stdout_truncated,
331 stderr_truncated: snapshot.stderr_truncated,
332 stdout_log_ref: metadata
333 .get("artifact_id")
334 .and_then(Value::as_str)
335 .map(str::to_string),
336 zero_tests_matched,
337 warning: if completed && truncated {
338 Some("Output was truncated; the zero-test check did not run.".to_string())
339 } else {
340 zero_tests
341 },
342 ..self.gate.result(status)
343 }
344 }
345 }
346
347 #[derive(Debug, Clone, Serialize, Deserialize)]
348 struct BackgroundGateJob {
349 name: String,
350 ecosystem: String,
351 status: String,
352 command: String,
353 cwd: String,
354 task_id: String,
355 }
356
357 #[derive(Debug, Clone, Serialize, Deserialize)]
358 struct RunVerifiersBackgroundOutput {
359 success: bool,
360 profile: String,
361 level: String,
362 workspace: String,
363 background: bool,
364 gate_count: usize,
365 started: usize,
366 passed: usize,
367 failed: usize,
368 skipped: usize,
369 verifier_verdict: VerifierVerdict,
370 summary: String,
371 #[serde(default, skip_serializing_if = "Vec::is_empty")]
372 completed_gates: Vec<GateResult>,
373 jobs: Vec<BackgroundGateJob>,
374 }
375
376 #[async_trait]
377 impl ToolSpec for RunVerifiersTool {
378 fn name(&self) -> &'static str {
379 "run_verifiers"
380 }
381
382 fn model_visible(&self) -> bool {
383 false
384 }
385
386 fn description(&self) -> &'static str {
387 "Run independent verifier gates in parallel across detected Rust, Node, Python, and Go projects."
388 }
389
390 fn input_schema(&self) -> Value {
391 json!({
392 "type": "object",
393 "properties": {
394 "profile": {
395 "type": "string",
396 "enum": ["auto", "rust", "node", "python", "go"],
397 "default": "auto",
398 "description": "Which ecosystem verifier set to run. 'auto' detects all supported project types in the workspace."
399 },
400 "level": {
401 "type": "string",
402 "enum": ["quick", "full"],
403 "default": "quick",
404 "description": "Quick runs Rust format and metadata checks, the Node format:check, check, typecheck and lint scripts that exist, a Python syntax check, and `go test ./...`; the auto profile also runs `git diff --check`. Full adds Rust cargo check, clippy and tests, the Node test script, pytest, and go vet."
405 },
406 "max_python_files": {
407 "type": "integer",
408 "minimum": 1,
409 "maximum": 1000,
410 "default": DEFAULT_MAX_PYTHON_FILES,
411 "description": "Maximum Python files to syntax-parse in the built-in python-syntax gate."
412 },
413 "background": {
414 "type": "boolean",
415 "description": "When true, start verifier gates immediately as background shell jobs and return task_ids. When omitted, wait up to 30000ms, return the gates that finished, and leave gates that are still running as background jobs; a call with timeout_ms runs in the foreground instead. When false, block until completion. Completion is tracked in task/status state, and `Bash` with action 'wait' / task_shell_wait are only for early output, final output, or true dependency barriers."
416 },
417 "cwd": {
418 "type": "string",
419 "description": "Optional working directory, relative to the workspace, to detect projects and run gates in. Must exist inside the workspace."
420 },
421 "timeout_ms": {
422 "type": "integer",
423 "minimum": 1,
424 "maximum": MAX_GATE_TIMEOUT_MS,
425 "description": format!("Wall-clock limit for each gate; setting it runs the call in the foreground (refused when background=true). When it elapses the gate's whole process tree is killed and the gate fails as timed out. Foreground gates default to {DEFAULT_GATE_TIMEOUT_MS}; background jobs have no limit. Raise it for a `full` run on a large workspace.")
426 }
427 },
428 "additionalProperties": false
429 })
430 }
431
432 fn capabilities(&self) -> Vec<ToolCapability> {
433 vec![ToolCapability::ExecutesCode, ToolCapability::Sandboxable]
434 }
435
436 fn approval_requirement(&self) -> ApprovalRequirement {
437 ApprovalRequirement::Required
438 }
439
440 fn starts_detached_for(&self, input: &Value) -> bool {
441 input.get("background").and_then(Value::as_bool) == Some(true)
442 }
443
444 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
445 crate::tools::execution_envelope::enforce_tool_denial(context, self.name(), &input)?;
446 let input: RunVerifiersInput = serde_json::from_value(input)
447 .map_err(|err| ToolError::invalid_input(err.to_string()))?;
448 // `cwd` scopes the whole call — project detection, gate roots, and
449 // reported paths — to an existing in-workspace subdirectory.
450 let scoped;
451 let context = match input
452 .cwd
453 .as_deref()
454 .map(str::trim)
455 .filter(|cwd| !cwd.is_empty())
456 {
457 None => context,
458 Some(raw) => {
459 let root = context.resolve_existing_dir(raw, "cwd")?;
460 let mut narrowed = context.clone();
461 narrowed.workspace = root;
462 scoped = narrowed;
463 &scoped
464 }
465 };
466 let profile = VerifierProfile::parse(input.profile.as_str())?;
467 let level = VerifierLevel::parse(input.level.as_str())?;
468 if input.max_python_files == 0 || input.max_python_files > 1000 {
469 return Err(ToolError::invalid_input(
470 "max_python_files must be between 1 and 1000",
471 ));
472 }
473
474 let background = if context
475 .child_host
476 .as_ref()
477 .is_some_and(|child| !child.can_collect_background_tests())
478 {
479 if input.background == Some(true) {
480 return Err(ToolError::invalid_input(
481 "This child cannot collect a background verifier job; run in the foreground",
482 ));
483 }
484 Some(false)
485 } else {
486 input.background
487 };
488
489 let explicit_timeout = input.timeout_ms.is_some();
490 if background == Some(true) && explicit_timeout {
491 return Err(ToolError::invalid_input(
492 "timeout_ms applies only to foreground gates; background gates run as shell jobs until they finish or are cancelled through task state",
493 ));
494 }
495 let timeout_ms = gate_timeout_ms(input.timeout_ms)?;
496 let gates = build_gate_plan(context, profile, level, input.max_python_files, timeout_ms);
497 if gates.is_empty() {
498 let verifier_verdict = VerifierVerdict::from_counts(0, 0, 0);
499 let output = RunVerifiersOutput {
500 success: false,
501 profile: profile.as_str().to_string(),
502 level: level.as_str().to_string(),
503 workspace: context.workspace.display().to_string(),
504 gate_count: 0,
505 passed: 0,
506 failed: 0,
507 skipped: 0,
508 verifier_verdict,
509 summary:
510 "No verifier gates were detected. Choose a profile that matches this workspace."
511 .to_string(),
512 gates: Vec::new(),
513 };
514 return verifier_tool_result(&output);
515 }
516
517 match background {
518 Some(true) => start_background_gates(context, profile, level, gates),
519 None if !explicit_timeout => {
520 run_gates_with_auto_background(
521 context,
522 profile,
523 level,
524 gates,
525 Duration::from_millis(DEFAULT_AUTO_BACKGROUND_TIMEOUT_MS),
526 )
527 .await
528 }
529 None | Some(false) => {
530 // Gates run as futures of this call, not detached blocking tasks: when
531 // Stop drops the tool future, every running gate's process group is
532 // killed with it instead of being orphaned.
533 let results = futures_util::future::join_all(
534 gates.into_iter().map(|gate| run_gate(gate, context)),
535 )
536 .await;
537 finish_foreground_gates(context, profile, level, results)
538 }
539 }
540 }
541 }
542
543 fn finish_foreground_gates(
544 context: &ToolContext,
545 profile: VerifierProfile,
546 level: VerifierLevel,
547 mut results: Vec<GateResult>,
548 ) -> Result<ToolResult, ToolError> {
549 results.sort_by(|a, b| a.name.cmp(&b.name));
550
551 let counts = GateCounts::of(&results);
552 let GateCounts {
553 passed,
554 failed,
555 skipped,
556 } = counts;
557 let success = counts.success();
558 let verifier_verdict = VerifierVerdict::from_counts(results.len(), failed, skipped);
559 let summary = if success {
560 format!("All {passed} verifier gates passed.")
561 } else {
562 format!("{passed} passed, {failed} failed, {skipped} skipped.")
563 };
564
565 let output = RunVerifiersOutput {
566 success,
567 profile: profile.as_str().to_string(),
568 level: level.as_str().to_string(),
569 workspace: context.workspace.display().to_string(),
570 gate_count: results.len(),
571 passed,
572 failed,
573 skipped,
574 verifier_verdict,
575 summary,
576 gates: results,
577 };
578
579 verifier_tool_result(&output)
580 }
581
582 async fn run_gates_with_auto_background(
583 context: &ToolContext,
584 profile: VerifierProfile,
585 level: VerifierLevel,
586 gates: Vec<VerifierGate>,
587 auto_background_wait: Duration,
588 ) -> Result<ToolResult, ToolError> {
589 let mut guard = ForegroundJobGuard::new(context);
590 let (jobs, mut results) = start_gate_jobs(context, gates, &mut guard)?;
591 let guard = if guard
592 .wait_unless_cancelled(context.cancel_token.as_ref(), auto_background_wait)
593 .await?
594 {
595 Some(guard)
596 } else {
597 guard.cancel().await?;
598 None
599 };
600 let (running, settled) = collect_gate_jobs(context, jobs).await?;
601 results.extend(settled);
602 let Some(guard) = guard else {
603 results.extend(running.into_iter().map(|job| {
604 job.gate.failed(format!(
605 "[verifier gate cancelled; its background job {} could not be stopped]",
606 job.task_id
607 ))
608 }));
609 return finish_foreground_gates(context, profile, level, results);
610 };
611 guard.hand_over();
612 if running.is_empty() {
613 return finish_foreground_gates(context, profile, level, results);
614 }
615 finish_background_gates(context, profile, level, running, results, false)
616 }
617
618 fn start_gate_jobs(
619 context: &ToolContext,
620 gates: Vec<VerifierGate>,
621 guard: &mut ForegroundJobGuard,
622 ) -> Result<(Vec<GateJob>, Vec<GateResult>), ToolError> {
623 if context
624 .cancel_token
625 .as_ref()
626 .is_some_and(tokio_util::sync::CancellationToken::is_cancelled)
627 {
628 return Err(ToolError::cancelled("run_verifiers cancelled"));
629 }
630 let mut jobs = Vec::with_capacity(gates.len());
631 let mut settled = Vec::new();
632 for gate in gates {
633 let Some(program) = gate.program.as_deref() else {
634 settled.push(gate.skipped_without_program());
635 continue;
636 };
637 match spawn_runner_job(
638 program,
639 &gate.args,
640 &gate.cwd,
641 gate.env.iter().cloned().collect(),
642 gate.name.clone(),
643 context,
644 ) {
645 Ok(task_id) => {
646 guard.track(task_id.clone());
647 jobs.push(GateJob { gate, task_id });
648 }
649 Err(ToolError::NotAvailable { message }) => settled.push(gate.skipped(message)),
650 Err(ToolError::ExecutionFailed { message, .. }) => settled.push(gate.failed(message)),
651 Err(error) => settled.push(gate.failed(error.to_string())),
652 }
653 }
654 Ok((jobs, settled))
655 }
656
657 async fn collect_gate_jobs(
658 context: &ToolContext,
659 jobs: Vec<GateJob>,
660 ) -> Result<(Vec<GateJob>, Vec<GateResult>), ToolError> {
661 let manager = context.shell_manager.clone();
662 let session_id = context.state_namespace.clone();
663 tokio::task::spawn_blocking(move || {
664 let mut manager = manager
665 .lock()
666 .map_err(|_| ToolError::execution_failed("shell manager lock poisoned"))?;
667 let mut running = Vec::new();
668 let mut settled = Vec::new();
669 for job in jobs {
670 match manager.test_output(&job.task_id, &session_id) {
671 Ok((snapshot, _)) if snapshot.status == ShellStatus::Running => running.push(job),
672 Ok((snapshot, metadata)) => {
673 manager.acknowledge_foreground_completion(&job.task_id);
674 settled.push(job.finish(snapshot, &metadata));
675 }
676 Err(_)
677 if manager
678 .poll_status(&job.task_id)
679 .is_ok_and(|status| status == ShellStatus::Running) =>
680 {
681 running.push(job);
682 }
683 Err(error) => settled.push(job.gate.failed(format!(
684 "[gate output read failed: {error}; retry task_shell_wait with task_id={}]",
685 job.task_id
686 ))),
687 }
688 }
689 Ok::<_, ToolError>((running, settled))
690 })
691 .await
692 .map_err(|err| ToolError::execution_failed(err.to_string()))?
693 }
694
695 /// Run quick auto verifier gates, and the Rust compile check, after a
696 /// successful workflow completion (#4013).
697 pub async fn run_workflow_completion_gates(context: &ToolContext) -> Result<Value, ToolError> {
698 crate::tools::execution_envelope::enforce_tool_denial(context, "run_verifiers", &json!({}))?;
699 let mut gates = build_gate_plan(
700 context,
701 VerifierProfile::Auto,
702 VerifierLevel::Quick,
703 DEFAULT_MAX_PYTHON_FILES,
704 DEFAULT_GATE_TIMEOUT_MS,
705 );
706 if context.workspace.join("Cargo.toml").exists() {
707 gates.push(rust_check_gate(&context.workspace));
708 }
709 if gates.is_empty() {
710 return Ok(json!({
711 "success": false,
712 "profile": "auto",
713 "level": "quick",
714 "gate_count": 0,
715 "summary": "No verifier gates detected for this workspace.",
716 "gates": [],
717 }));
718 }
719
720 let mut results =
721 futures_util::future::join_all(gates.into_iter().map(|gate| run_gate(gate, context))).await;
722 results.sort_by(|a, b| a.name.cmp(&b.name));
723
724 let counts = GateCounts::of(&results);
725 let GateCounts {
726 passed,
727 failed,
728 skipped,
729 } = counts;
730 if !counts.success() {
731 return Err(ToolError::execution_failed(format!(
732 "{passed} passed, {failed} failed, {skipped} skipped"
733 )));
734 }
735 Ok(json!({
736 "success": true,
737 "profile": "auto",
738 "level": "quick",
739 "gate_count": results.len(),
740 "passed": passed,
741 "failed": failed,
742 "skipped": skipped,
743 "summary": format!("All {passed} verifier gates passed."),
744 "gates": results,
745 }))
746 }
747
748 fn verifier_tool_result(output: &RunVerifiersOutput) -> Result<ToolResult, ToolError> {
749 let mut result =
750 ToolResult::json(output).map_err(|err| ToolError::execution_failed(err.to_string()))?;
751 result.success = output.success;
752 Ok(result.with_metadata(json!({
753 "verifier_verdict": output.verifier_verdict,
754 })))
755 }
756
757 fn start_background_gates(
758 context: &ToolContext,
759 profile: VerifierProfile,
760 level: VerifierLevel,
761 gates: Vec<VerifierGate>,
762 ) -> Result<ToolResult, ToolError> {
763 let mut guard = ForegroundJobGuard::new(context);
764 let (jobs, results) = start_gate_jobs(context, gates, &mut guard)?;
765 guard.hand_over();
766 if jobs.is_empty() {
767 return finish_foreground_gates(context, profile, level, results);
768 }
769 finish_background_gates(context, profile, level, jobs, results, true)
770 }
771
772 fn finish_background_gates(
773 context: &ToolContext,
774 profile: VerifierProfile,
775 level: VerifierLevel,
776 jobs: Vec<GateJob>,
777 mut completed_gates: Vec<GateResult>,
778 detached_start: bool,
779 ) -> Result<ToolResult, ToolError> {
780 let mut jobs: Vec<BackgroundGateJob> = jobs
781 .into_iter()
782 .map(|GateJob { gate, task_id }| BackgroundGateJob {
783 command: render_command(gate.program.as_deref(), &gate.args),
784 name: gate.name,
785 ecosystem: gate.ecosystem,
786 status: "running".to_string(),
787 cwd: gate.cwd.display().to_string(),
788 task_id,
789 })
790 .collect();
791 jobs.sort_by(|a, b| a.name.cmp(&b.name));
792 completed_gates.sort_by(|a, b| a.name.cmp(&b.name));
793
794 let counts = GateCounts::of(&completed_gates);
795 let GateCounts {
796 passed,
797 failed,
798 skipped,
799 } = counts;
800 let success = counts.success();
801 let started = jobs.len();
802 let verifier_verdict = if failed > 0 {
803 VerifierVerdict::Fail
804 } else {
805 VerifierVerdict::Partial
806 };
807 let running = format!(
808 "{started} verifier gate(s) running in the background. Completion is tracked in task/status state. Continue inspecting or implementing while they run."
809 );
810 let summary = if completed_gates.is_empty() {
811 running
812 } else {
813 format!("{passed} passed, {failed} failed, {skipped} skipped; {running}")
814 };
815 let task_ids: Vec<String> = jobs.iter().map(|job| job.task_id.clone()).collect();
816 let output = RunVerifiersBackgroundOutput {
817 success,
818 profile: profile.as_str().to_string(),
819 level: level.as_str().to_string(),
820 workspace: context.workspace.display().to_string(),
821 background: true,
822 gate_count: jobs.len() + completed_gates.len(),
823 started,
824 passed,
825 failed,
826 skipped,
827 verifier_verdict,
828 summary,
829 completed_gates,
830 jobs,
831 };
832
833 let mut result =
834 ToolResult::json(&output).map_err(|err| ToolError::execution_failed(err.to_string()))?;
835 result.success = success;
836 let mut metadata = background_job_metadata(context, &task_ids, detached_start);
837 metadata["verifier_background"] = json!(true);
838 metadata["verifier_verdict"] = json!(verifier_verdict);
839 Ok(result.with_metadata(metadata))
840 }
841
842 fn build_gate_plan(
843 context: &ToolContext,
844 profile: VerifierProfile,
845 level: VerifierLevel,
846 max_python_files: usize,
847 timeout_ms: u64,
848 ) -> Vec<VerifierGate> {
849 let workspace = &context.workspace;
850 let mut gates = Vec::new();
851
852 if profile == VerifierProfile::Auto && workspace.join(".git").exists() {
853 gates.push(gate(
854 "git-whitespace",
855 "git",
856 workspace,
857 "git",
858 ["diff", "--check"],
859 ));
860 }
861
862 if profile_matches(profile, VerifierProfile::Rust) && workspace.join("Cargo.toml").exists() {
863 add_rust_gates(&mut gates, workspace, level);
864 }
865 if profile_matches(profile, VerifierProfile::Node) && workspace.join("package.json").exists() {
866 add_node_gates(&mut gates, workspace, level);
867 }
868 if profile_matches(profile, VerifierProfile::Python) && has_python_project(workspace) {
869 add_python_gates(&mut gates, workspace, level, max_python_files);
870 }
871 if profile_matches(profile, VerifierProfile::Go) && workspace.join("go.mod").exists() {
872 add_go_gates(&mut gates, workspace, level);
873 }
874
875 let timeout = Duration::from_millis(timeout_ms);
876 for gate in &mut gates {
877 gate.timeout = timeout;
878 }
879 gates
880 }
881
882 fn profile_matches(selected: VerifierProfile, candidate: VerifierProfile) -> bool {
883 selected == VerifierProfile::Auto || selected == candidate
884 }
885
886 fn add_rust_gates(gates: &mut Vec<VerifierGate>, workspace: &Path, level: VerifierLevel) {
887 let locked = workspace.join("Cargo.lock").exists();
888 gates.push(gate(
889 "rust-fmt",
890 "rust",
891 workspace,
892 "cargo",
893 ["fmt", "--all", "--", "--check"],
894 ));
895
896 let metadata_args = if locked {
897 vec!["metadata", "--locked", "--format-version", "1", "--no-deps"]
898 } else {
899 vec!["metadata", "--format-version", "1", "--no-deps"]
900 };
901 gates.push(gate_vec(
902 "rust-metadata",
903 "rust",
904 workspace,
905 "cargo",
906 metadata_args,
907 ));
908
909 if level == VerifierLevel::Full {
910 gates.push(rust_check_gate(workspace));
911
912 let mut clippy_args = vec!["clippy", "--workspace", "--all-targets", "--all-features"];
913 if locked {
914 clippy_args.push("--locked");
915 }
916 clippy_args.extend(["--", "-D", "warnings"]);
917 gates.push(gate_vec(
918 "rust-clippy",
919 "rust",
920 workspace,
921 "cargo",
922 clippy_args,
923 ));
924
925 let mut test_args = vec!["test", "--workspace", "--all-features"];
926 if locked {
927 test_args.push("--locked");
928 }
929 gates.push(gate_vec("rust-test", "rust", workspace, "cargo", test_args));
930 }
931 }
932
933 fn rust_check_gate(workspace: &Path) -> VerifierGate {
934 let mut check_args = vec!["check", "--workspace", "--all-targets"];
935 if workspace.join("Cargo.lock").exists() {
936 check_args.push("--locked");
937 }
938 gate_vec("rust-check", "rust", workspace, "cargo", check_args)
939 }
940
941 fn add_node_gates(gates: &mut Vec<VerifierGate>, workspace: &Path, level: VerifierLevel) {
942 let scripts = package_json_scripts(workspace);
943 let Some(scripts) = scripts else {
944 gates.push(skipped_gate(
945 "node-package-json",
946 "node",
947 workspace,
948 "package.json is missing or could not be parsed",
949 ));
950 return;
951 };
952 let package_manager = detect_node_package_manager(workspace);
953 for script in ["format:check", "check", "typecheck", "lint"] {
954 if has_meaningful_script(&scripts, script) {
955 gates.push(node_script_gate(workspace, &package_manager, script));
956 }
957 }
958 if level == VerifierLevel::Full && has_meaningful_script(&scripts, "test") {
959 gates.push(node_script_gate(workspace, &package_manager, "test"));
960 }
961 }
962
963 fn add_python_gates(
964 gates: &mut Vec<VerifierGate>,
965 workspace: &Path,
966 level: VerifierLevel,
967 max_python_files: usize,
968 ) {
969 let python_files = collect_python_files(workspace, max_python_files);
970 match python_files {
971 PythonFiles::Files(files) if !files.is_empty() => {
972 gates.push(python_syntax_gate(workspace, &files));
973 }
974 PythonFiles::TooMany { limit, found } => gates.push(skipped_gate(
975 "python-syntax",
976 "python",
977 workspace,
978 format!(
979 "found more than {limit} Python files ({found}); raise max_python_files to verify them"
980 ),
981 )),
982 PythonFiles::Files(_) => {}
983 }
984
985 if level == VerifierLevel::Full && has_pytest_signal(workspace) {
986 gates.push(python_module_gate(
987 "python-pytest",
988 workspace,
989 ["-m", "pytest"],
990 ));
991 }
992 }
993
994 fn add_go_gates(gates: &mut Vec<VerifierGate>, workspace: &Path, level: VerifierLevel) {
995 gates.push(gate("go-test", "go", workspace, "go", ["test", "./..."]));
996 if level == VerifierLevel::Full {
997 gates.push(gate("go-vet", "go", workspace, "go", ["vet", "./..."]));
998 }
999 }
1000
1001 fn gate<const N: usize>(
1002 name: &str,
1003 ecosystem: &str,
1004 cwd: &Path,
1005 program: &str,
1006 args: [&str; N],
1007 ) -> VerifierGate {
1008 gate_vec(name, ecosystem, cwd, program, args)
1009 }
1010
1011 fn gate_vec<I, S>(name: &str, ecosystem: &str, cwd: &Path, program: &str, args: I) -> VerifierGate
1012 where
1013 I: IntoIterator<Item = S>,
1014 S: AsRef<str>,
1015 {
1016 VerifierGate {
1017 name: name.to_string(),
1018 ecosystem: ecosystem.to_string(),
1019 cwd: cwd.to_path_buf(),
1020 program: Some(program.to_string()),
1021 args: args
1022 .into_iter()
1023 .map(|arg| arg.as_ref().to_string())
1024 .collect(),
1025 env: Vec::new(),
1026 skipped_reason: None,
1027 timeout: Duration::from_millis(DEFAULT_GATE_TIMEOUT_MS),
1028 }
1029 }
1030
1031 fn skipped_gate(
1032 name: &str,
1033 ecosystem: &str,
1034 cwd: &Path,
1035 reason: impl Into<String>,
1036 ) -> VerifierGate {
1037 VerifierGate {
1038 name: name.to_string(),
1039 ecosystem: ecosystem.to_string(),
1040 cwd: cwd.to_path_buf(),
1041 program: None,
1042 args: Vec::new(),
1043 env: Vec::new(),
1044 skipped_reason: Some(reason.into()),
1045 timeout: Duration::from_millis(DEFAULT_GATE_TIMEOUT_MS),
1046 }
1047 }
1048
1049 fn node_script_gate(
1050 workspace: &Path,
1051 package_manager: &NodePackageManager,
1052 script: &str,
1053 ) -> VerifierGate {
1054 let (program, args) = package_manager.command_for_script(script);
1055 gate_vec(&format!("node-{script}"), "node", workspace, program, args)
1056 }
1057
1058 fn python_syntax_gate(workspace: &Path, files: &[PathBuf]) -> VerifierGate {
1059 let Some((program, mut args)) = python_command_parts() else {
1060 return skipped_gate(
1061 "python-syntax",
1062 "python",
1063 workspace,
1064 "Python interpreter is not installed or not in PATH",
1065 );
1066 };
1067 args.push("-c".to_string());
1068 args.push(PYTHON_SYNTAX_SCRIPT.to_string());
1069 args.extend(files.iter().map(|path| path.display().to_string()));
1070 let mut gate = gate_vec("python-syntax", "python", workspace, &program, args);
1071 gate.env
1072 .push(("PYTHONDONTWRITEBYTECODE".to_string(), "1".to_string()));
1073 gate
1074 }
1075
1076 fn python_module_gate<const N: usize>(
1077 name: &str,
1078 workspace: &Path,
1079 module_args: [&str; N],
1080 ) -> VerifierGate {
1081 let Some((program, mut args)) = python_command_parts() else {
1082 return skipped_gate(
1083 name,
1084 "python",
1085 workspace,
1086 "Python interpreter is not installed or not in PATH",
1087 );
1088 };
1089 args.extend(module_args.into_iter().map(str::to_string));
1090 gate_vec(name, "python", workspace, &program, args)
1091 }
1092
1093 fn python_command_parts() -> Option<(String, Vec<String>)> {
1094 let spec = codewhale_dependencies::Python::resolve()?;
1095 Some(codewhale_dependencies::split_interpreter_spec(&spec))
1096 }
1097
1098 const PYTHON_SYNTAX_SCRIPT: &str = r#"
1099 import ast
1100 import pathlib
1101 import sys
1102
1103 failures = []
1104 for raw in sys.argv[1:]:
1105 path = pathlib.Path(raw)
1106 try:
1107 source = path.read_text(encoding="utf-8")
1108 ast.parse(source, filename=raw)
1109 except Exception as exc:
1110 failures.append(f"{raw}: {exc.__class__.__name__}: {exc}")
1111
1112 if failures:
1113 print("\n".join(failures), file=sys.stderr)
1114 sys.exit(1)
1115
1116 print(f"parsed {len(sys.argv) - 1} Python file(s)")
1117 "#;
1118
1119 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1120 enum NodePackageManager {
1121 Npm,
1122 Pnpm,
1123 Yarn,
1124 Bun,
1125 }
1126
1127 impl NodePackageManager {
1128 fn command_for_script(self, script: &str) -> (&'static str, Vec<String>) {
1129 match self {
1130 Self::Npm => ("npm", vec!["run".to_string(), script.to_string()]),
1131 Self::Pnpm => ("pnpm", vec!["run".to_string(), script.to_string()]),
1132 Self::Yarn => ("yarn", vec!["run".to_string(), script.to_string()]),
1133 Self::Bun => ("bun", vec!["run".to_string(), script.to_string()]),
1134 }
1135 }
1136 }
1137
1138 fn detect_node_package_manager(workspace: &Path) -> NodePackageManager {
1139 if workspace.join("pnpm-lock.yaml").exists() {
1140 NodePackageManager::Pnpm
1141 } else if workspace.join("yarn.lock").exists() {
1142 NodePackageManager::Yarn
1143 } else if workspace.join("bun.lock").exists() || workspace.join("bun.lockb").exists() {
1144 NodePackageManager::Bun
1145 } else {
1146 NodePackageManager::Npm
1147 }
1148 }
1149
1150 fn package_json_scripts(workspace: &Path) -> Option<HashMap<String, String>> {
1151 let raw = fs::read_to_string(workspace.join("package.json")).ok()?;
1152 let parsed = serde_json::from_str::<serde_json::Value>(&raw).ok()?;
1153 let scripts = parsed.get("scripts")?.as_object()?;
1154 Some(
1155 scripts
1156 .iter()
1157 .filter_map(|(key, value)| {
1158 value
1159 .as_str()
1160 .map(|script| (key.clone(), script.to_string()))
1161 })
1162 .collect(),
1163 )
1164 }
1165
1166 fn has_meaningful_script(scripts: &HashMap<String, String>, name: &str) -> bool {
1167 let Some(script) = scripts.get(name).map(|value| value.trim()) else {
1168 return false;
1169 };
1170 !(script.is_empty()
1171 || name == "test"
1172 && script.contains("Error: no test specified")
1173 && script.contains("exit 1"))
1174 }
1175
1176 fn has_python_project(workspace: &Path) -> bool {
1177 workspace.join("pyproject.toml").exists()
1178 || workspace.join("setup.py").exists()
1179 || workspace.join("setup.cfg").exists()
1180 || workspace.join("requirements.txt").exists()
1181 || match collect_python_files(workspace, 1) {
1182 PythonFiles::Files(files) => !files.is_empty(),
1183 PythonFiles::TooMany { .. } => true,
1184 }
1185 }
1186
1187 fn has_pytest_signal(workspace: &Path) -> bool {
1188 if workspace.join("pytest.ini").exists()
1189 || workspace.join("tox.ini").exists()
1190 || workspace.join("tests").is_dir()
1191 {
1192 return true;
1193 }
1194 let pyproject = workspace.join("pyproject.toml");
1195 fs::read_to_string(pyproject)
1196 .map(|raw| raw.contains("pytest") || raw.contains("[tool.pytest"))
1197 .unwrap_or(false)
1198 }
1199
1200 #[derive(Debug, Clone, PartialEq, Eq)]
1201 enum PythonFiles {
1202 Files(Vec<PathBuf>),
1203 TooMany { limit: usize, found: usize },
1204 }
1205
1206 fn collect_python_files(workspace: &Path, limit: usize) -> PythonFiles {
1207 let mut files = BTreeSet::new();
1208 collect_python_files_inner(workspace, workspace, limit, &mut files);
1209 let found = files.len();
1210 if found > limit {
1211 PythonFiles::TooMany { limit, found }
1212 } else {
1213 PythonFiles::Files(files.into_iter().collect())
1214 }
1215 }
1216
1217 fn collect_python_files_inner(
1218 root: &Path,
1219 dir: &Path,
1220 limit: usize,
1221 files: &mut BTreeSet<PathBuf>,
1222 ) {
1223 if files.len() > limit {
1224 return;
1225 }
1226 let Ok(entries) = fs::read_dir(dir) else {
1227 return;
1228 };
1229 for entry in entries.flatten() {
1230 if files.len() > limit {
1231 return;
1232 }
1233 let path = entry.path();
1234 let name = entry.file_name();
1235 if path.is_dir() {
1236 if should_skip_dir_name(&name.to_string_lossy()) {
1237 continue;
1238 }
1239 collect_python_files_inner(root, &path, limit, files);
1240 } else if path.extension().and_then(|ext| ext.to_str()) == Some("py")
1241 && let Ok(relative) = path.strip_prefix(root)
1242 {
1243 files.insert(relative.to_path_buf());
1244 }
1245 }
1246 }
1247
1248 fn should_skip_dir_name(name: &str) -> bool {
1249 matches!(
1250 name,
1251 ".git"
1252 | ".hg"
1253 | ".svn"
1254 | ".venv"
1255 | "venv"
1256 | "env"
1257 | "__pycache__"
1258 | ".mypy_cache"
1259 | ".pytest_cache"
1260 | ".tox"
1261 | "node_modules"
1262 | "target"
1263 | "dist"
1264 | "build"
1265 )
1266 }
1267
1268 async fn run_gate(gate: VerifierGate, context: &ToolContext) -> GateResult {
1269 let session_id = context.state_namespace.as_str();
1270 let Some(program) = gate.program.as_deref() else {
1271 return gate.skipped_without_program();
1272 };
1273
1274 if context
1275 .cancel_token
1276 .as_ref()
1277 .is_some_and(tokio_util::sync::CancellationToken::is_cancelled)
1278 {
1279 return gate.failed("[verifier gate cancelled before start]");
1280 }
1281
1282 let started = Instant::now();
1283 let mut cmd = match crate::tools::shell::sandboxed_runner_command(
1284 context,
1285 program,
1286 gate.args.clone(),
1287 &gate.cwd,
1288 gate.timeout,
1289 ) {
1290 Ok(cmd) => cmd,
1291 Err(error) => return gate.skipped(error.to_string()),
1292 };
1293 // A gate never reads input; an inherited stdin could block it on the
1294 // Engine's own terminal or pipe.
1295 cmd.stdin(Stdio::null());
1296 // Gates run workspace code: the runner starts from the sanitized child
1297 // environment, and only the gate's own declared variables are layered on
1298 // top.
1299 cmd.envs(
1300 gate.env
1301 .iter()
1302 .map(|(key, value)| (key.as_str(), value.as_str())),
1303 );
1304
1305 let (mut child, tree) = match codewhale_runtime::process_tree::spawn_contained_tokio(&mut cmd) {
1306 Ok(contained) => contained,
1307 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
1308 return GateResult {
1309 duration_ms: started.elapsed().as_millis() as u64,
1310 ..gate.skipped(format!("{program} is not installed or not in PATH"))
1311 };
1312 }
1313 Err(err) => {
1314 return GateResult {
1315 duration_ms: started.elapsed().as_millis() as u64,
1316 ..gate.failed(format!("Failed to spawn verifier: {err}"))
1317 };
1318 }
1319 };
1320 let mut stdout = GateCapture::new(session_id, &gate.name, "stdout");
1321 let mut stderr = GateCapture::new(session_id, &gate.name, "stderr");
1322 let mut exited = false;
1323 let mut pipes_open = true;
1324 let mut timed_out = false;
1325 let mut cancelled = false;
1326 {
1327 let read_stdout = read_capped(child.stdout.take(), &mut stdout);
1328 let read_stderr = read_capped(child.stderr.take(), &mut stderr);
1329 let mut read_pipes = std::pin::pin!(async move {
1330 tokio::join!(read_stdout, read_stderr);
1331 });
1332 let deadline = tokio::time::sleep(gate.timeout);
1333 let mut deadline = std::pin::pin!(deadline);
1334 let mut drain_deadline: Option<std::pin::Pin<Box<tokio::time::Sleep>>> = None;
1335 let mut leader_exit = std::pin::pin!(tree.leader_exit(&mut child));
1336 let cancel_token = context.cancel_token.clone();
1337 loop {
1338 if exited && !pipes_open {
1339 break;
1340 }
1341 tokio::select! {
1342 () = async {
1343 if let Some(token) = cancel_token.as_ref() {
1344 token.cancelled().await;
1345 } else {
1346 std::future::pending::<()>().await;
1347 }
1348 } => {
1349 cancelled = true;
1350 break;
1351 }
1352 () = &mut leader_exit, if !exited => {
1353 exited = true;
1354 drain_deadline = Some(Box::pin(tokio::time::sleep(GATE_PIPE_DRAIN_GRACE)));
1355 }
1356 () = &mut read_pipes, if pipes_open => pipes_open = false,
1357 () = async { drain_deadline.as_mut().expect("guarded").await },
1358 if drain_deadline.is_some() => break,
1359 () = &mut deadline => {
1360 timed_out = true;
1361 break;
1362 }
1363 }
1364 }
1365 }
1366
1367 let mut notes = Vec::new();
1368 let kill_tree = cancelled || timed_out || pipes_open;
1369 let killed = kill_tree && tree.kill().is_ok();
1370 // If the group kill failed, the leader is killed but not reaped, so the
1371 // still-armed tree keeps its group id and kills it again on drop.
1372 // Otherwise the leader has exited or its tree was just killed; the reap is
1373 // bounded anyway so an uninterruptible child cannot wedge the verifier again.
1374 let exit = if cancelled && !killed {
1375 let _ = child.start_kill();
1376 None
1377 } else {
1378 let reap_grace = if cancelled {
1379 Duration::from_millis(100)
1380 } else {
1381 GATE_PIPE_DRAIN_GRACE
1382 };
1383 tokio::time::timeout(reap_grace, child.wait()).await.ok()
1384 };
1385 if !kill_tree {
1386 tree.release();
1387 } else if exit.is_some() {
1388 tree.disarm();
1389 }
1390 if cancelled && killed {
1391 notes.push("[verifier gate cancelled and its process group was killed]".to_string());
1392 } else if cancelled {
1393 notes.push("[verifier gate cancelled; killing its process group failed]".to_string());
1394 } else if timed_out {
1395 notes.push(format!(
1396 "[verifier gate timed out after {}s and its process group was killed; raise timeout_ms if it legitimately needs longer]",
1397 gate.timeout.as_secs_f64()
1398 ));
1399 } else if pipes_open {
1400 notes.push(
1401 "[the gate exited but a process it started kept stdout/stderr open; its process group was killed]"
1402 .to_string(),
1403 );
1404 }
1405
1406 let exit_status = match exit {
1407 Some(Ok(status)) => Some(status),
1408 Some(Err(err)) => {
1409 notes.push(format!("[failed to wait for verifier: {err}]"));
1410 None
1411 }
1412 None => None,
1413 };
1414 let stdout = stdout.finish().await;
1415 let stderr = stderr.finish().await;
1416 let mut stderr_text = stderr.text;
1417 for note in notes {
1418 append_note(&mut stderr_text, &note);
1419 }
1420 let completed = !cancelled
1421 && !timed_out
1422 && !stdout.read_failed
1423 && !stderr.read_failed
1424 && exit_status.is_some_and(|status| status.success());
1425 let warning = if completed {
1426 zero_test_warning(&stdout.text, &mut stderr_text)
1427 } else {
1428 None
1429 };
1430 let zero_tests_matched = warning.is_some();
1431 let status = if completed && !zero_tests_matched {
1432 GateStatus::Passed
1433 } else {
1434 GateStatus::Failed
1435 };
1436 GateResult {
1437 exit_code: exit_status.and_then(|status| status.code()),
1438 duration_ms: started.elapsed().as_millis() as u64,
1439 stdout: stdout.text,
1440 stderr: stderr_text,
1441 stdout_truncated: stdout.truncated,
1442 stderr_truncated: stderr.truncated,
1443 stdout_log_ref: stdout.log_ref,
1444 stderr_log_ref: stderr.log_ref,
1445 zero_tests_matched,
1446 warning,
1447 ..gate.result(status)
1448 }
1449 }
1450
1451 fn append_note(text: &mut String, note: &str) {
1452 if !text.is_empty() && !text.ends_with('\n') {
1453 text.push('\n');
1454 }
1455 text.push_str(note);
1456 }
1457
1458 fn zero_test_warning(stdout: &str, stderr: &mut String) -> Option<String> {
1459 let detection = super::test_runner::detect_zero_tests_matched(stdout, stderr, false);
1460 if !detection.zero_tests_matched {
1461 return None;
1462 }
1463 let message = detection.reason.unwrap_or_else(|| {
1464 "0 tests matched; verify your test filter — a 0-test run proves nothing".to_string()
1465 });
1466 append_note(
1467 stderr,
1468 &format!("[verifier gate matched 0 tests: {message}]"),
1469 );
1470 Some(message)
1471 }
1472
1473 /// Read a gate's pipe to EOF into `capture`.
1474 async fn read_capped<R>(pipe: Option<R>, capture: &mut GateCapture)
1475 where
1476 R: tokio::io::AsyncRead + Unpin,
1477 {
1478 use tokio::io::AsyncReadExt;
1479 let Some(mut pipe) = pipe else {
1480 return;
1481 };
1482 let mut chunk = [0u8; 8192];
1483 loop {
1484 match pipe.read(&mut chunk).await {
1485 Ok(0) => return,
1486 Ok(n) => capture.push(&chunk[..n]).await,
1487 Err(error) => {
1488 capture.read_failed = true;
1489 capture
1490 .push(format!("\n[gate output read failed: {error}]\n").as_bytes())
1491 .await;
1492 return;
1493 }
1494 }
1495 }
1496 }
1497
1498 /// One gate stream: every byte while it fits in memory, then its first
1499 /// [`GATE_CAPTURE_HEAD_BYTES`] and a rolling last [`GATE_CAPTURE_TAIL_BYTES`],
1500 /// with every byte teed to a session artifact so nothing is lost.
1501 struct GateCapture {
1502 head: Vec<u8>,
1503 tail: std::collections::VecDeque<u8>,
1504 total: u64,
1505 session_id: String,
1506 artifact_id: String,
1507 log: Option<tokio::fs::File>,
1508 /// Opening or writing the log failed; the middle is gone, and the result
1509 /// says so instead of naming a ref.
1510 log_failed: bool,
1511 read_failed: bool,
1512 }
1513
1514 /// What a gate stream contributes to its [`GateResult`].
1515 struct CapturedStream {
1516 text: String,
1517 truncated: bool,
1518 log_ref: Option<String>,
1519 read_failed: bool,
1520 }
1521
1522 impl GateCapture {
1523 fn new(session_id: &str, gate_name: &str, stream: &str) -> Self {
1524 let id = uuid::Uuid::new_v4().simple().to_string();
1525 Self {
1526 head: Vec::new(),
1527 tail: std::collections::VecDeque::new(),
1528 total: 0,
1529 session_id: session_id.to_string(),
1530 artifact_id: codewhale_runtime::artifacts::artifact_id_for_tool_call(&format!(
1531 "gate_{gate_name}_{stream}_{}",
1532 &id[..12]
1533 )),
1534 log: None,
1535 log_failed: false,
1536 read_failed: false,
1537 }
1538 }
1539
1540 fn overflowed(&self) -> bool {
1541 self.total > (GATE_CAPTURE_HEAD_BYTES + GATE_CAPTURE_TAIL_BYTES) as u64
1542 }
1543
1544 async fn push(&mut self, bytes: &[u8]) {
1545 use tokio::io::AsyncWriteExt;
1546 self.total += bytes.len() as u64;
1547 if !self.overflowed() {
1548 self.head.extend_from_slice(bytes);
1549 return;
1550 }
1551 if self.log.is_none() && !self.log_failed {
1552 // First overflow: everything so far is still in `head`. Save it,
1553 // then keep only the head window in memory.
1554 self.log = self.open_log().await;
1555 self.log_failed = self.log.is_none();
1556 let kept = std::mem::take(&mut self.head);
1557 if let Some(log) = self.log.as_mut()
1558 && log.write_all(&kept).await.is_err()
1559 {
1560 self.log = None;
1561 self.log_failed = true;
1562 }
1563 self.head = kept[..GATE_CAPTURE_HEAD_BYTES.min(kept.len())].to_vec();
1564 self.tail
1565 .extend(&kept[GATE_CAPTURE_HEAD_BYTES.min(kept.len())..]);
1566 }
1567 if let Some(log) = self.log.as_mut()
1568 && log.write_all(bytes).await.is_err()
1569 {
1570 self.log = None;
1571 self.log_failed = true;
1572 }
1573 if self.head.len() < GATE_CAPTURE_HEAD_BYTES {
1574 let room = GATE_CAPTURE_HEAD_BYTES - self.head.len();
1575 self.head.extend_from_slice(&bytes[..room.min(bytes.len())]);
1576 self.tail.extend(&bytes[room.min(bytes.len())..]);
1577 } else {
1578 self.tail.extend(bytes);
1579 }
1580 let excess = self.tail.len().saturating_sub(GATE_CAPTURE_TAIL_BYTES);
1581 self.tail.drain(..excess);
1582 }
1583
1584 async fn open_log(&self) -> Option<tokio::fs::File> {
1585 let relative =
1586 codewhale_runtime::artifacts::session_artifact_relative_path(&self.artifact_id);
1587 let path = codewhale_runtime::artifacts::session_artifact_absolute_path(
1588 &self.session_id,
1589 &relative,
1590 )?;
1591 if let Some(parent) = path.parent() {
1592 tokio::fs::create_dir_all(parent).await.ok()?;
1593 }
1594 tokio::fs::File::create(&path).await.ok()
1595 }
1596
1597 async fn finish(mut self) -> CapturedStream {
1598 use tokio::io::AsyncWriteExt;
1599 if !self.overflowed() {
1600 return CapturedStream {
1601 text: String::from_utf8_lossy(&self.head).into_owned(),
1602 truncated: false,
1603 log_ref: None,
1604 read_failed: self.read_failed,
1605 };
1606 }
1607 let saved = match self.log.as_mut() {
1608 Some(log) => log.flush().await.is_ok() && !self.log_failed,
1609 None => false,
1610 };
1611 let omitted = self.total - (self.head.len() + self.tail.len()) as u64;
1612 let middle = if saved {
1613 format!(
1614 "[{omitted} bytes omitted from the middle; the whole stream is artifact {}: read it with retrieve_tool_result]",
1615 self.artifact_id
1616 )
1617 } else {
1618 format!("[{omitted} bytes omitted from the middle; the full stream could not be saved]")
1619 };
1620 let tail: Vec<u8> = self.tail.into_iter().collect();
1621 CapturedStream {
1622 text: format!(
1623 "{}\n\n{middle}\n\n{}",
1624 String::from_utf8_lossy(&self.head),
1625 String::from_utf8_lossy(&tail)
1626 ),
1627 truncated: true,
1628 log_ref: saved.then_some(self.artifact_id),
1629 read_failed: self.read_failed,
1630 }
1631 }
1632 }
1633
1634 fn render_command(program: Option<&str>, args: &[String]) -> String {
1635 let mut parts = Vec::new();
1636 parts.push(program.unwrap_or("<unavailable>").to_string());
1637 parts.extend(args.iter().cloned());
1638 parts.join(" ")
1639 }
1640
1641 #[cfg(test)]
1642 mod tests {
1643 use super::*;
1644 use std::time::Duration;
1645 use tempfile::tempdir;
1646
1647 const BACKGROUND_COMPLETION_WAIT_MS: u64 = 30_000;
1648
1649 fn capture_stream(session_id: &str, content: &[u8]) -> CapturedStream {
1650 tokio::runtime::Builder::new_current_thread()
1651 .build()
1652 .expect("runtime")
1653 .block_on(async {
1654 let mut capture = GateCapture::new(session_id, "cargo test", "stdout");
1655 for chunk in content.chunks(8192) {
1656 capture.push(chunk).await;
1657 }
1658 capture.finish().await
1659 })
1660 }
1661
1662 #[test]
1663 fn gate_output_over_1mib_keeps_head_and_tail_and_writes_full_log() {
1664 // #6508: the verifier kept only the first 1 MiB of a stream and
1665 // dropped the end, where a failing gate reports its failure.
1666 let home = tempdir().expect("tempdir");
1667 crate::tools::truncate::with_test_home(home.path(), || {
1668 let content = format!(
1669 "FIRST LINE\n{}LAST LINE: test result: FAILED\n",
1670 "gate output line\n".repeat(100_000)
1671 );
1672 assert!(content.len() > GATE_CAPTURE_HEAD_BYTES + GATE_CAPTURE_TAIL_BYTES);
1673
1674 let captured = capture_stream("session-6508", content.as_bytes());
1675
1676 assert!(captured.truncated);
1677 assert!(captured.text.starts_with("FIRST LINE"));
1678 assert!(captured.text.ends_with("LAST LINE: test result: FAILED\n"));
1679 let reference = captured.log_ref.expect("full log ref");
1680 assert!(captured.text.contains(&reference));
1681 let path = codewhale_runtime::artifacts::session_artifact_absolute_path(
1682 "session-6508",
1683 &codewhale_runtime::artifacts::session_artifact_relative_path(&reference),
1684 )
1685 .expect("artifact path");
1686 let log = fs::read(path).expect("full log");
1687 assert_eq!(log.len(), content.len());
1688 assert_eq!(log, content.as_bytes());
1689 });
1690 }
1691
1692 #[test]
1693 fn gate_output_that_fits_is_kept_whole_without_a_log() {
1694 let content = "short gate output\n".repeat(1_000);
1695 let captured = capture_stream("session-6508", content.as_bytes());
1696 assert!(!captured.truncated);
1697 assert_eq!(captured.text, content);
1698 assert!(captured.log_ref.is_none());
1699 }
1700
1701 #[test]
1702 fn gate_output_whose_log_cannot_be_saved_says_so() {
1703 // An invalid session id has no artifact directory, so no ref is
1704 // promised; head and tail are still kept.
1705 let content = format!("HEAD\n{}TAIL\n", "x".repeat(1_200_000));
1706 let captured = capture_stream("", content.as_bytes());
1707 assert!(captured.truncated);
1708 assert!(captured.log_ref.is_none());
1709 assert!(captured.text.starts_with("HEAD"));
1710 assert!(captured.text.ends_with("TAIL\n"));
1711 assert!(captured.text.contains("the full stream could not be saved"));
1712 }
1713
1714 fn wait_for_completed_shell(
1715 manager: &mut crate::tools::shell::ShellManager,
1716 task_id: &str,
1717 ) -> crate::tools::shell::ShellResult {
1718 let deadline = Instant::now() + Duration::from_millis(BACKGROUND_COMPLETION_WAIT_MS);
1719
1720 loop {
1721 let result = manager
1722 .get_output(task_id, true, 1_000)
1723 .expect("background output");
1724 if result.status != ShellStatus::Running || Instant::now() >= deadline {
1725 return result;
1726 }
1727 std::thread::sleep(Duration::from_millis(50));
1728 }
1729 }
1730
1731 #[test]
1732 fn run_verifiers_requires_user_approval() {
1733 let tool = RunVerifiersTool;
1734 assert_eq!(
1735 tool.approval_requirement(),
1736 ApprovalRequirement::Required,
1737 "run_verifiers executes project code and must require approval"
1738 );
1739 }
1740
1741 #[test]
1742 fn run_verifiers_background_advertises_detached_start() {
1743 let tool = RunVerifiersTool;
1744 let schema = tool.input_schema();
1745 let background_description = schema["properties"]["background"]["description"]
1746 .as_str()
1747 .expect("background description");
1748
1749 assert!(background_description.contains("Bash"));
1750 assert!(background_description.contains("task_shell_wait"));
1751 assert!(
1752 !background_description.contains("exec_shell"),
1753 "live descriptions must not teach the retired exec_shell name"
1754 );
1755 assert!(tool.starts_detached_for(&json!({"background": true})));
1756 assert!(!tool.starts_detached_for(&json!({"profile": "auto"})));
1757 }
1758
1759 #[test]
1760 fn auto_profile_detects_multiple_ecosystems_without_bash() {
1761 let tmp = tempdir().expect("tempdir");
1762 fs::write(tmp.path().join("Cargo.toml"), "[workspace]\n").expect("cargo manifest");
1763 fs::write(
1764 tmp.path().join("package.json"),
1765 r#"{"scripts":{"lint":"eslint .","test":"echo ok"}}"#,
1766 )
1767 .expect("package json");
1768 fs::write(tmp.path().join("main.py"), "print('ok')\n").expect("python file");
1769 fs::write(tmp.path().join("go.mod"), "module example.com/app\n").expect("go mod");
1770
1771 let ctx = ToolContext::new(tmp.path());
1772 let gates = build_gate_plan(
1773 &ctx,
1774 VerifierProfile::Auto,
1775 VerifierLevel::Quick,
1776 DEFAULT_MAX_PYTHON_FILES,
1777 DEFAULT_GATE_TIMEOUT_MS,
1778 );
1779 let names: BTreeSet<&str> = gates.iter().map(|gate| gate.name.as_str()).collect();
1780
1781 assert!(names.contains("rust-fmt"));
1782 assert!(!names.contains("rust-check"));
1783 assert!(names.contains("node-lint"));
1784 assert!(names.contains("python-syntax"));
1785 assert!(names.contains("go-test"));
1786 assert!(
1787 gates
1788 .iter()
1789 .filter_map(|gate| gate.program.as_deref())
1790 .all(|program| program != "bash"),
1791 "built-in verifier gates must not require bash"
1792 );
1793 }
1794
1795 #[test]
1796 fn node_default_npm_init_test_script_is_not_a_verifier() {
1797 let mut scripts = HashMap::new();
1798 scripts.insert(
1799 "test".to_string(),
1800 "echo \"Error: no test specified\" && exit 1".to_string(),
1801 );
1802
1803 assert!(!has_meaningful_script(&scripts, "test"));
1804 }
1805
1806 #[tokio::test]
1807 async fn run_verifiers_emits_verdict_mapping() {
1808 let tmp = tempdir().expect("tempdir");
1809 let ctx = ToolContext::new(tmp.path());
1810 let tool = RunVerifiersTool;
1811
1812 let partial = tool
1813 .execute(json!({"profile": "auto"}), &ctx)
1814 .await
1815 .expect("execute partial verifier");
1816 assert_verdict(&partial, "partial");
1817 assert!(
1818 !partial.success,
1819 "partial verifier must not report success=true"
1820 );
1821
1822 #[cfg(unix)]
1823 {
1824 let pass = finish_foreground_gates(
1825 &ctx,
1826 VerifierProfile::Auto,
1827 VerifierLevel::Quick,
1828 vec![run_gate(shell_gate("pass", tmp.path(), "true"), &ctx).await],
1829 )
1830 .expect("passing verifier");
1831 assert_verdict(&pass, "pass");
1832 assert!(pass.success, "passing verifier must report success=true");
1833
1834 let fail = finish_foreground_gates(
1835 &ctx,
1836 VerifierProfile::Auto,
1837 VerifierLevel::Quick,
1838 vec![run_gate(shell_gate("fail", tmp.path(), "exit 3"), &ctx).await],
1839 )
1840 .expect("failing verifier");
1841 assert_verdict(&fail, "fail");
1842 assert!(
1843 !fail.success,
1844 "failing verifier must not report success=true"
1845 );
1846 }
1847 }
1848
1849 #[tokio::test]
1850 async fn run_verifiers_cwd_scopes_detection_to_subdir() {
1851 let tmp = tempdir().expect("tempdir");
1852 let sub = tmp.path().join("nested");
1853 std::fs::create_dir(&sub).expect("subdir");
1854 let ctx = ToolContext::new(tmp.path());
1855
1856 // Empty subdir: no gates detected, and the reported workspace is the
1857 // scoped root rather than the parent workspace.
1858 let result = RunVerifiersTool
1859 .execute(json!({"profile": "auto", "cwd": "nested"}), &ctx)
1860 .await
1861 .expect("cwd-scoped execute");
1862 let parsed: RunVerifiersOutput =
1863 serde_json::from_str(&result.content).expect("verifier output json");
1864 assert_eq!(parsed.gate_count, 0);
1865 assert_eq!(
1866 parsed.workspace,
1867 sub.canonicalize().expect("canonical").display().to_string()
1868 );
1869
1870 // Missing dir: refused with the fallback named.
1871 let err = RunVerifiersTool
1872 .execute(json!({"profile": "auto", "cwd": "no-such-dir"}), &ctx)
1873 .await
1874 .expect_err("missing dir must be refused");
1875 let message = err.to_string();
1876 assert!(message.contains("not an existing directory"), "{message}");
1877 assert!(message.contains("drop `cwd`"), "{message}");
1878 }
1879
1880 fn assert_verdict(result: &ToolResult, verifier: &str) {
1881 let parsed: Value = serde_json::from_str(&result.content).expect("verifier output json");
1882 assert_eq!(parsed["verifier_verdict"], verifier, "{}", result.content);
1883 assert!(parsed.get("hunt_verdict").is_none(), "{}", result.content);
1884 assert!(parsed.get("goal_status").is_none(), "{}", result.content);
1885 let metadata = result.metadata.as_ref().expect("verifier metadata");
1886 assert_eq!(metadata["verifier_verdict"], verifier, "{metadata}");
1887 assert!(metadata.get("hunt_verdict").is_none(), "{metadata}");
1888 assert!(metadata.get("task_updates").is_none(), "{metadata}");
1889 }
1890
1891 #[cfg(unix)]
1892 #[tokio::test]
1893 async fn verifier_gates_carry_the_agent_project_in_the_foreground_and_background() {
1894 let tmp = tempdir().expect("tempdir");
1895 let ctx = ToolContext::new(tmp.path());
1896 let marked = format!("MARK={}", tmp.path().display());
1897 let script = "printf 'MARK=%s' \"${CODEWHALE_AGENT_PROJECT-unset}\"";
1898
1899 let foreground = run_gate(shell_gate("agent-mark", tmp.path(), script), &ctx).await;
1900 assert!(foreground.stdout.contains(&marked), "{foreground:?}");
1901
1902 let background = start_background_gates(
1903 &ctx,
1904 VerifierProfile::Auto,
1905 VerifierLevel::Quick,
1906 vec![shell_gate("agent-mark", tmp.path(), script)],
1907 )
1908 .expect("background verifier");
1909 let parsed: RunVerifiersBackgroundOutput =
1910 serde_json::from_str(&background.content).expect("background output json");
1911 let output = wait_for_completed_shell(
1912 &mut ctx.shell_manager.lock().expect("shell manager"),
1913 &parsed.jobs[0].task_id,
1914 );
1915 assert!(output.stdout.contains(&marked), "{output:?}");
1916 }
1917
1918 #[tokio::test]
1919 async fn run_verifiers_background_starts_shell_jobs_and_returns_task_ids() {
1920 let tmp = tempdir().expect("tempdir");
1921 let ctx = ToolContext::new(tmp.path());
1922 let program = std::env::current_exe()
1923 .expect("test executable")
1924 .to_string_lossy()
1925 .into_owned();
1926 let result = start_background_gates(
1927 &ctx,
1928 VerifierProfile::Auto,
1929 VerifierLevel::Quick,
1930 vec![gate(
1931 "test-list",
1932 "rust",
1933 tmp.path(),
1934 &program,
1935 ["--list", "run_verifiers_background"],
1936 )],
1937 )
1938 .expect("execute");
1939
1940 let parsed: RunVerifiersBackgroundOutput =
1941 serde_json::from_str(&result.content).expect("background verifier output json");
1942 assert!(parsed.success, "result: {}", result.content);
1943 assert!(parsed.background);
1944 assert_eq!(parsed.started, 1);
1945 assert_eq!(parsed.failed, 0);
1946 assert_eq!(parsed.skipped, 0);
1947 assert!(parsed.summary.contains("Completion is tracked"));
1948 let metadata = result.metadata.as_ref().expect("metadata");
1949 assert!(
1950 metadata
1951 .get("verifier_background")
1952 .and_then(Value::as_bool)
1953 .unwrap_or(false),
1954 "metadata should mark verifier background start"
1955 );
1956 assert_eq!(
1957 metadata
1958 .get("auto_notify_on_completion")
1959 .and_then(Value::as_bool),
1960 None
1961 );
1962 assert_eq!(
1963 metadata
1964 .get("auto_resume_on_completion")
1965 .and_then(Value::as_bool),
1966 Some(true)
1967 );
1968 assert_eq!(
1969 metadata.get("completion_surface").and_then(Value::as_str),
1970 Some("runtime_event_and_task_status")
1971 );
1972 assert_eq!(
1973 metadata.get("background_policy").and_then(Value::as_str),
1974 Some("nonblocking")
1975 );
1976
1977 let output = wait_for_completed_shell(
1978 &mut ctx.shell_manager.lock().expect("shell manager"),
1979 &parsed.jobs[0].task_id,
1980 );
1981 assert_eq!(
1982 output.status,
1983 ShellStatus::Completed,
1984 "stdout: {:?} stderr: {:?}",
1985 output.stdout,
1986 output.stderr
1987 );
1988 assert!(
1989 output.stdout.lines().any(|line| line.ends_with(": test")),
1990 "stdout should include the test listing: {:?}",
1991 output.stdout
1992 );
1993 }
1994
1995 /// Headless Chrome (`--print-to-pdf` / `--dump-dom`) writes its output and
1996 /// then never exits while a helper keeps stdout/stderr open. This script
1997 /// reproduces that shape deterministically: a leader plus a background
1998 /// child, both holding the gate's pipes, neither ever exiting.
1999 #[cfg(unix)]
2000 fn hung_gate_script(pidfile: &Path) -> String {
2001 format!(
2002 "sleep 600 & echo $! > '{p}'; echo $$ >> '{p}'; echo started; wait",
2003 p = pidfile.display()
2004 )
2005 }
2006
2007 #[cfg(unix)]
2008 async fn read_gate_pids(pidfile: &Path) -> Vec<libc::pid_t> {
2009 let deadline = Instant::now() + Duration::from_secs(10);
2010 loop {
2011 let pids: Vec<libc::pid_t> = fs::read_to_string(pidfile)
2012 .unwrap_or_default()
2013 .lines()
2014 .filter_map(|line| line.trim().parse().ok())
2015 .collect();
2016 if pids.len() >= 2 {
2017 return pids;
2018 }
2019 assert!(Instant::now() < deadline, "hung gate never started");
2020 tokio::time::sleep(Duration::from_millis(20)).await;
2021 }
2022 }
2023
2024 #[cfg(unix)]
2025 async fn assert_pids_gone(pids: &[libc::pid_t]) {
2026 let deadline = Instant::now() + Duration::from_secs(5);
2027 loop {
2028 // SAFETY: signal 0 only probes for existence.
2029 let alive: Vec<_> = pids
2030 .iter()
2031 .copied()
2032 .filter(|pid| unsafe { libc::kill(*pid, 0) } == 0)
2033 .collect();
2034 if alive.is_empty() {
2035 return;
2036 }
2037 if Instant::now() >= deadline {
2038 for pid in &alive {
2039 // SAFETY: best-effort cleanup of the leaked test processes.
2040 unsafe {
2041 libc::kill(*pid, libc::SIGKILL);
2042 }
2043 }
2044 panic!("verifier gate processes still running: {alive:?}");
2045 }
2046 tokio::time::sleep(Duration::from_millis(20)).await;
2047 }
2048 }
2049
2050 #[cfg(unix)]
2051 #[tokio::test]
2052 async fn run_verifiers_hung_gate_times_out_and_kills_its_process_group() {
2053 let tmp = tempdir().expect("tempdir");
2054 let pidfile = tmp.path().join("pids");
2055 let ctx = ToolContext::new(tmp.path());
2056 let mut hung = shell_gate("hung", tmp.path(), &hung_gate_script(&pidfile));
2057 hung.timeout = Duration::from_millis(500);
2058 let started = Instant::now();
2059 let gate = tokio::time::timeout(Duration::from_secs(20), run_gate(hung, &ctx))
2060 .await
2061 .expect("a hung verifier gate must not hang run_verifiers");
2062 assert!(
2063 started.elapsed() < Duration::from_secs(10),
2064 "timed-out gate took {:?}",
2065 started.elapsed()
2066 );
2067
2068 assert_eq!(gate.status, GateStatus::Failed);
2069 assert!(
2070 gate.stderr.contains("timed out"),
2071 "stderr: {:?}",
2072 gate.stderr
2073 );
2074 assert!(
2075 gate.stdout.contains("started"),
2076 "partial stdout kept: {:?}",
2077 gate.stdout
2078 );
2079 assert_pids_gone(&read_gate_pids(&pidfile).await).await;
2080 }
2081
2082 #[cfg(unix)]
2083 #[tokio::test]
2084 async fn run_verifiers_dropped_on_stop_kills_running_gates() {
2085 let tmp = tempdir().expect("tempdir");
2086 let pidfile = tmp.path().join("pids");
2087 let ctx = ToolContext::new(tmp.path());
2088 let hung = shell_gate("hung", tmp.path(), &hung_gate_script(&pidfile));
2089 // Stop drops the active tool future (turn_loop's biased select on the
2090 // cancel token). That drop must take the gate's processes with it.
2091 let task = tokio::spawn(async move { run_gate(hung, &ctx).await });
2092 let pids = read_gate_pids(&pidfile).await;
2093 task.abort();
2094 let _ = task.await;
2095 assert_pids_gone(&pids).await;
2096 }
2097
2098 #[test]
2099 fn built_in_gates_take_the_call_timeout() {
2100 let tmp = tempdir().expect("tempdir");
2101 fs::write(tmp.path().join("Cargo.toml"), "[workspace]\n").expect("cargo manifest");
2102 let ctx = ToolContext::new(tmp.path());
2103 let long = MAX_GATE_TIMEOUT_MS;
2104 let gates = build_gate_plan(
2105 &ctx,
2106 VerifierProfile::Rust,
2107 VerifierLevel::Full,
2108 DEFAULT_MAX_PYTHON_FILES,
2109 gate_timeout_ms(Some(long)).expect("in range"),
2110 );
2111 assert!(!gates.is_empty(), "rust gates detected");
2112 // A `full` run on a large workspace is no longer capped at 600s.
2113 for gate in &gates {
2114 assert_eq!(gate.timeout, Duration::from_millis(long), "{}", gate.name);
2115 }
2116 assert_eq!(gate_timeout_ms(None).ok(), Some(DEFAULT_GATE_TIMEOUT_MS));
2117 assert!(gate_timeout_ms(Some(0)).is_err());
2118 assert!(gate_timeout_ms(Some(long + 1)).is_err());
2119 }
2120
2121 #[tokio::test]
2122 async fn run_verifiers_background_refuses_timeout_ms_it_cannot_enforce() {
2123 let tmp = tempdir().expect("tempdir");
2124 let ctx = ToolContext::new(tmp.path());
2125 let err = RunVerifiersTool
2126 .execute(json!({"background": true, "timeout_ms": 1000}), &ctx)
2127 .await
2128 .expect_err("background timeout_ms must be refused");
2129 assert!(err.to_string().contains("foreground"), "{err}");
2130 let jobs = ctx.shell_manager.lock().expect("shell manager").list_jobs();
2131 assert!(jobs.is_empty(), "nothing may start: {jobs:?}");
2132 }
2133
2134 #[cfg(unix)]
2135 #[tokio::test]
2136 async fn run_gate_does_not_inherit_parent_secret_env_but_keeps_gate_env() {
2137 use crate::test_support::{EnvVarGuard, lock_test_env};
2138 let _env_lock = lock_test_env();
2139 let _secret = EnvVarGuard::set("CODEWHALE_TEST_VERIFIER_SECRET", "verifier-secret-value");
2140 let tmp = tempdir().expect("tempdir");
2141 let gate = VerifierGate {
2142 name: "env-probe".to_string(),
2143 ecosystem: "rust".to_string(),
2144 cwd: tmp.path().to_path_buf(),
2145 program: Some("/bin/sh".to_string()),
2146 args: vec![
2147 "-c".to_string(),
2148 "printf '%s|%s' \"${CODEWHALE_TEST_VERIFIER_SECRET-unset}\" \"${GATE_DECLARED-missing}\""
2149 .to_string(),
2150 ],
2151 env: vec![("GATE_DECLARED".to_string(), "declared".to_string())],
2152 skipped_reason: None,
2153 timeout: Duration::from_secs(30),
2154 };
2155 let context = ToolContext::new(tmp.path().to_path_buf());
2156 let result = run_gate(gate, &context).await;
2157 assert_eq!(result.stdout.trim(), "unset|declared", "{result:?}");
2158 }
2159
2160 #[cfg(unix)]
2161 #[tokio::test]
2162 async fn run_gate_flags_a_zero_test_run_as_failed() {
2163 let tmp = tempdir().expect("tempdir");
2164 let ctx = ToolContext::new(tmp.path());
2165 let gate = run_gate(
2166 shell_gate(
2167 "rust-test",
2168 tmp.path(),
2169 "printf 'running 0 tests\\n\\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 26 filtered out; finished in 0.00s\\n'",
2170 ),
2171 &ctx,
2172 )
2173 .await;
2174 assert_eq!(gate.status, GateStatus::Failed, "{gate:?}");
2175 assert!(gate.zero_tests_matched);
2176 assert!(gate.warning.is_some());
2177 }
2178
2179 #[tokio::test]
2180 async fn read_capped_marks_read_failed_on_pipe_error() {
2181 struct FailingPipe {
2182 sent_first: bool,
2183 }
2184
2185 impl tokio::io::AsyncRead for FailingPipe {
2186 fn poll_read(
2187 mut self: std::pin::Pin<&mut Self>,
2188 _cx: &mut std::task::Context<'_>,
2189 buf: &mut tokio::io::ReadBuf<'_>,
2190 ) -> std::task::Poll<std::io::Result<()>> {
2191 if !self.sent_first {
2192 self.sent_first = true;
2193 buf.put_slice(b"partial output");
2194 return std::task::Poll::Ready(Ok(()));
2195 }
2196 std::task::Poll::Ready(Err(std::io::Error::other("simulated pipe eio")))
2197 }
2198 }
2199
2200 let mut capture = GateCapture::new("session-read-err", "test", "stderr");
2201 read_capped(Some(FailingPipe { sent_first: false }), &mut capture).await;
2202 let finished = capture.finish().await;
2203 assert!(finished.read_failed);
2204 assert!(finished.text.contains("partial output"));
2205 assert!(finished.text.contains("gate output read failed"));
2206 assert!(finished.text.contains("simulated pipe eio"));
2207 }
2208
2209 #[cfg(unix)]
2210 fn shell_gate(name: &str, cwd: &Path, script: &str) -> VerifierGate {
2211 gate(name, "rust", cwd, "/bin/sh", ["-c", script])
2212 }
2213
2214 #[cfg(unix)]
2215 #[tokio::test]
2216 async fn run_gates_with_auto_background_cancelled_incomplete_gate_fails() {
2217 let tmp = tempdir().expect("tempdir");
2218 let pidfile = tmp.path().join("pids");
2219 let cancel = tokio_util::sync::CancellationToken::new();
2220 let ctx = ToolContext::new(tmp.path()).with_cancel_token(cancel.clone());
2221 let (result, pids) = tokio::join!(
2222 run_gates_with_auto_background(
2223 &ctx,
2224 VerifierProfile::Auto,
2225 VerifierLevel::Quick,
2226 vec![shell_gate("slow", tmp.path(), &hung_gate_script(&pidfile))],
2227 Duration::from_secs(600),
2228 ),
2229 async {
2230 let pids = read_gate_pids(&pidfile).await;
2231 cancel.cancel();
2232 pids
2233 }
2234 );
2235 let result = result.expect("verifier result");
2236 let parsed: RunVerifiersOutput =
2237 serde_json::from_str(&result.content).expect("verifier output json");
2238 assert!(!result.success);
2239 assert!(!parsed.success);
2240 assert_eq!(parsed.gate_count, 1);
2241 assert_eq!(parsed.failed, 1);
2242 assert_eq!(parsed.gates[0].status, GateStatus::Failed);
2243 assert_pids_gone(&pids).await;
2244 }
2245
2246 #[cfg(unix)]
2247 #[tokio::test]
2248 async fn auto_background_hands_over_the_running_job_and_counts_settled_gates() {
2249 let tmp = tempdir().expect("tempdir");
2250 let starts = tmp.path().join("starts");
2251 let release = tmp.path().join("release");
2252 let ctx = ToolContext::new(tmp.path()).with_owner_agent("gate-child", "verifier");
2253 let script = format!(
2254 "echo start >> '{}'; while [ ! -e '{}' ]; do sleep 0.02; done; echo finished",
2255 starts.display(),
2256 release.display()
2257 );
2258 let result = run_gates_with_auto_background(
2259 &ctx,
2260 VerifierProfile::Auto,
2261 VerifierLevel::Quick,
2262 vec![
2263 shell_gate("slow", tmp.path(), &script),
2264 skipped_gate("absent", "python", tmp.path(), "not installed"),
2265 ],
2266 Duration::from_millis(50),
2267 )
2268 .await
2269 .expect("verifier result");
2270 let parsed: RunVerifiersBackgroundOutput =
2271 serde_json::from_str(&result.content).expect("background output json");
2272 assert!(!result.success, "{}", result.content);
2273 assert_eq!((parsed.started, parsed.skipped, parsed.failed), (1, 1, 0));
2274 assert_eq!(parsed.completed_gates[0].name, "absent");
2275 let metadata = result.metadata.as_ref().expect("metadata");
2276 assert_eq!(metadata["verifier_verdict"], "partial");
2277 assert_eq!(metadata["auto_resume_on_completion"], json!(false));
2278
2279 fs::write(&release, "").expect("release gate");
2280 let mut manager = ctx.shell_manager.lock().expect("shell manager");
2281 let output = wait_for_completed_shell(&mut manager, &parsed.jobs[0].task_id);
2282 assert_eq!(output.status, ShellStatus::Completed, "{output:?}");
2283 assert!(output.stdout.contains("finished"), "{output:?}");
2284 assert_eq!(fs::read_to_string(&starts).expect("starts"), "start\n");
2285 let job = manager
2286 .list_jobs()
2287 .into_iter()
2288 .find(|job| job.id == parsed.jobs[0].task_id)
2289 .expect("handed-over job");
2290 assert_eq!(job.owner_agent_id.as_deref(), Some("gate-child"));
2291 }
2292
2293 #[tokio::test]
2294 async fn workflow_completion_gates_fail_rust_that_does_not_compile() {
2295 let rustfmt_available = std::process::Command::new("cargo")
2296 .args(["fmt", "--version"])
2297 .output()
2298 .is_ok_and(|output| output.status.success());
2299 if !codewhale_dependencies::Cargo::available() || !rustfmt_available {
2300 return;
2301 }
2302 let tmp = tempdir().expect("tempdir");
2303 fs::write(
2304 tmp.path().join("Cargo.toml"),
2305 "[package]\nname = \"completion-gate-type-error\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
2306 )
2307 .expect("manifest");
2308 fs::create_dir(tmp.path().join("src")).expect("src");
2309 fs::write(
2310 tmp.path().join("src/lib.rs"),
2311 "pub fn broken() -> u32 {\n \"text\"\n}\n",
2312 )
2313 .expect("source");
2314 let err = run_workflow_completion_gates(&ToolContext::new(tmp.path()))
2315 .await
2316 .expect_err("a type error must fail the completion gates")
2317 .to_string();
2318 assert!(err.contains("2 passed, 1 failed, 0 skipped"), "{err}");
2319 }
2320 }
2321
2321 lines RUST