Skip to main content

speccoder_runtime/
init.rs

1//! `speccoder init`: detect a project's checks and write
2//! `speccoder.toml`.
3//!
4//! Detection looks only at the project root's manifests and lockfiles (and
5//! whether `cargo nextest` is installed); it runs nothing of the project's.
6//! What it finds becomes a commented file the person reviews and commits.
7//! The result is parsed back with speccoder's own parsers before it is
8//! written, so `init` never leaves a file `run` would refuse.
9
10use std::path::{Path, PathBuf};
11
12use serde::Serialize;
13use speccoder_core::{CommandData, CommandResult, CommandStatus};
14
15use crate::git::Git;
16use crate::verify::config::FILE;
17
18/// What `init` saw at the project root.
19#[derive(Debug, Clone, Default, PartialEq, Eq)]
20pub struct Found {
21    /// `Cargo.toml` exists.
22    pub cargo: bool,
23    /// `cargo nextest` is installed.
24    pub nextest: bool,
25    /// `package.json`'s scripts, by name.
26    pub npm_scripts: Vec<String>,
27    /// `npm`, `pnpm`, `yarn` or `bun`, from the lockfile; `None` without `package.json`.
28    pub node_manager: Option<String>,
29    /// `pyproject.toml`, `setup.cfg`, `setup.py` or `pytest.ini` exists.
30    pub python: bool,
31    /// How checks start the project's Python: `uv run --locked --offline
32    /// python` for a uv project (uv makes the environment in whichever tree
33    /// the check runs in — a run's worktree has no `.venv/`, which is never
34    /// committed), else a project-local virtualenv's interpreter, else
35    /// `python3`.
36    pub python_run: Vec<String>,
37    /// pytest runs with that interpreter (or `python3`).
38    pub pytest: bool,
39    /// `[tool.ruff]` (or `ruff.toml`) is configured.
40    pub ruff: bool,
41    /// `[tool.mypy]` (or `mypy.ini`) is configured.
42    pub mypy: bool,
43    /// `go.mod` exists.
44    pub go: bool,
45    /// A `Makefile` with a `test:` target exists.
46    pub make_test: bool,
47    /// The checkout's git-ignored `.env` files: proposed for `[worktree]
48    /// include`.
49    pub include: Vec<String>,
50    /// A `.worktreeinclude` exists: runs read it already.
51    pub worktreeinclude: bool,
52}
53
54impl Found {
55    /// How checks start the project's Python (`python3` when nothing more
56    /// specific was found).
57    #[must_use]
58    pub fn python_command(&self) -> Vec<String> {
59        if self.python_run.is_empty() {
60            vec!["python3".to_owned()]
61        } else {
62            self.python_run.clone()
63        }
64    }
65}
66
67/// One check `init` proposes.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
69pub struct Proposed {
70    /// `[checks.<name>]`.
71    pub name: String,
72    /// The command.
73    pub argv: Vec<String>,
74    /// `fast` or `full`.
75    pub tier: String,
76    /// A JUnit report the check writes.
77    pub junit: Option<String>,
78    /// Why this check.
79    pub why: String,
80}
81
82fn check(name: &str, argv: &[&str], tier: &str, junit: Option<&str>, why: &str) -> Proposed {
83    Proposed {
84        name: name.to_owned(),
85        argv: argv.iter().map(|a| (*a).to_owned()).collect(),
86        tier: tier.to_owned(),
87        junit: junit.map(str::to_owned),
88        why: why.to_owned(),
89    }
90}
91
92/// The checks for what was found (pure: no IO).
93#[must_use]
94pub fn propose(found: &Found) -> Vec<Proposed> {
95    let mut out = Vec::new();
96    if found.cargo {
97        out.push(if found.nextest {
98            check(
99                "test",
100                // A new project has no tests yet: warn, do not fail the baseline.
101                &[
102                    "cargo",
103                    "nextest",
104                    "run",
105                    "--workspace",
106                    "--profile",
107                    "speccoder",
108                    "--no-tests=warn",
109                ],
110                "fast",
111                Some("target/nextest/speccoder/junit.xml"),
112                "Cargo.toml; cargo-nextest is installed (its JUnit report names every test)",
113            )
114        } else {
115            check(
116                "test",
117                &["cargo", "test", "--workspace"],
118                "fast",
119                None,
120                "Cargo.toml (install cargo-nextest for per-test results)",
121            )
122        });
123        out.push(check(
124            "fmt",
125            &["cargo", "fmt", "--all", "--check"],
126            "fast",
127            None,
128            "Cargo.toml",
129        ));
130        out.push(check(
131            "clippy",
132            &[
133                "cargo",
134                "clippy",
135                "--workspace",
136                "--all-targets",
137                "--",
138                "-D",
139                "warnings",
140            ],
141            "full",
142            None,
143            "Cargo.toml",
144        ));
145    }
146    if let Some(pm) = &found.node_manager {
147        let has = |s: &str| found.npm_scripts.iter().any(|x| x == s);
148        // `<pm> run <script>`: the allowed prefix is that one script.
149        let run = |script: &str| -> Vec<String> { vec![pm.clone(), "run".into(), script.into()] };
150        let mut add = |name: &str, script: &str, tier: &str| {
151            out.push(Proposed {
152                name: name.to_owned(),
153                argv: run(script),
154                tier: tier.to_owned(),
155                junit: None,
156                why: format!("package.json script `{script}` ({pm})"),
157            });
158        };
159        if has("test") {
160            add(
161                if found.cargo { "node-test" } else { "test" },
162                "test",
163                "fast",
164            );
165        }
166        if has("typecheck") {
167            add("typecheck", "typecheck", "fast");
168        }
169        if has("lint") {
170            add("lint", "lint", "full");
171        }
172    }
173    if found.python {
174        let name = if found.cargo || found.node_manager.is_some() {
175            "pytest"
176        } else {
177            "test"
178        };
179        let run = found.python_command();
180        let python = run.join(" ");
181        let uv = run.first().is_some_and(|p| p == "uv");
182        let why = if found.pytest {
183            format!("a Python project (pytest, {python})")
184        } else if uv {
185            "a Python project — pytest is not a dependency: `uv add --dev pytest`".to_owned()
186        } else {
187            format!(
188                "a Python project — pytest is not installed for {python}: `{python} -m pip install pytest`"
189            )
190        };
191        let argv: Vec<&str> = run
192            .iter()
193            .map(String::as_str)
194            .chain(["-m", "pytest", "-q", "--junitxml=.speccoder/junit.xml"])
195            .collect();
196        out.push(check(
197            name,
198            &argv,
199            "fast",
200            Some(".speccoder/junit.xml"),
201            &why,
202        ));
203        if found.ruff {
204            out.push(check(
205                "ruff",
206                &["ruff", "check", "."],
207                "fast",
208                None,
209                "ruff is configured",
210            ));
211        }
212        if found.mypy {
213            out.push(check(
214                "mypy",
215                &["mypy", "."],
216                "full",
217                None,
218                "mypy is configured",
219            ));
220        }
221    }
222    if found.go {
223        let name = if out.iter().any(|c| c.name == "test") {
224            "go-test"
225        } else {
226            "test"
227        };
228        out.push(check(
229            name,
230            &["go", "test", "./..."],
231            "fast",
232            None,
233            "go.mod",
234        ));
235        out.push(check(
236            "vet",
237            &["go", "vet", "./..."],
238            "full",
239            None,
240            "go.mod",
241        ));
242    }
243    if out.is_empty() && found.make_test {
244        out.push(check(
245            "test",
246            &["make", "test"],
247            "fast",
248            None,
249            "a Makefile `test` target",
250        ));
251    }
252    out
253}
254
255/// Commands the model (and the spec-derived acceptance tests) need besides
256/// the checks: narrow prefixes per toolchain, written to `[commands] allow`.
257#[must_use]
258pub fn allow(found: &Found) -> Vec<Vec<String>> {
259    let v = |a: &[&str]| a.iter().map(|x| (*x).to_owned()).collect::<Vec<String>>();
260    let mut out = Vec::new();
261    if found.cargo {
262        out.extend([
263            v(&["cargo", "test"]),
264            v(&["cargo", "check"]),
265            v(&["cargo", "build"]),
266        ]);
267    }
268    if let Some(pm) = &found.node_manager {
269        out.extend([v(&[pm, "test"]), v(&[pm, "run", "test"])]);
270    }
271    if found.python {
272        let mut pytest = found.python_command();
273        pytest.extend(["-m".to_owned(), "pytest".to_owned()]);
274        out.push(pytest);
275    }
276    if found.go {
277        out.extend([v(&["go", "test"]), v(&["go", "build"]), v(&["go", "vet"])]);
278    }
279    out
280}
281
282/// The formatter speccoder runs after each attempt, when the toolchain has one.
283#[must_use]
284pub fn formatter(found: &Found) -> Option<Vec<String>> {
285    let v = |a: &[&str]| Some(a.iter().map(|x| (*x).to_owned()).collect());
286    if found.cargo {
287        v(&["cargo", "fmt", "--all"])
288    } else if found.go {
289        v(&["gofmt", "-w", "."])
290    } else if found.python && found.ruff {
291        v(&["ruff", "format", "."])
292    } else {
293        None
294    }
295}
296
297/// Looks at `root` (and whether `cargo nextest` runs).
298#[must_use]
299pub fn detect(root: &Path) -> Found {
300    let exists = |p: &str| root.join(p).exists();
301    let read = |p: &str| std::fs::read_to_string(root.join(p)).unwrap_or_default();
302    let cargo = exists("Cargo.toml");
303    let nextest = cargo
304        && std::process::Command::new("cargo")
305            .args(["nextest", "--version"])
306            .stdin(std::process::Stdio::null())
307            .stdout(std::process::Stdio::null())
308            .stderr(std::process::Stdio::null())
309            .status()
310            .is_ok_and(|s| s.success());
311    let (node_manager, npm_scripts) = if exists("package.json") {
312        let manager = if exists("pnpm-lock.yaml") {
313            "pnpm"
314        } else if exists("yarn.lock") {
315            "yarn"
316        } else if exists("bun.lockb") || exists("bun.lock") {
317            "bun"
318        } else {
319            "npm"
320        };
321        let scripts = serde_json::from_str::<serde_json::Value>(&read("package.json"))
322            .ok()
323            .and_then(|v| {
324                v["scripts"]
325                    .as_object()
326                    .map(|o| o.keys().cloned().collect())
327            })
328            .unwrap_or_default();
329        (Some(manager.to_owned()), scripts)
330    } else {
331        (None, Vec::new())
332    };
333    let pyproject = read("pyproject.toml");
334    let makefile = read("Makefile");
335    let python = ["pyproject.toml", "setup.cfg", "setup.py", "pytest.ini"]
336        .iter()
337        .any(|p| exists(p));
338    // A uv project's environment is made by uv in the tree the check runs
339    // in, from the committed lockfile and uv's cache; a plain virtualenv is
340    // used by its interpreter's path.
341    let words = |w: &[&str]| w.iter().map(|x| (*x).to_owned()).collect::<Vec<_>>();
342    let python_run = if python && exists("uv.lock") {
343        words(&["uv", "run", "--locked", "--offline", "python"])
344    } else {
345        [".venv/bin/python", "venv/bin/python"]
346            .iter()
347            .find(|p| python && exists(p))
348            .map_or_else(|| words(&["python3"]), |p| words(&[p]))
349    };
350    Found {
351        cargo,
352        nextest,
353        npm_scripts,
354        node_manager,
355        python,
356        pytest: python && {
357            let bin = python_run[0].as_str();
358            std::process::Command::new(if root.join(bin).is_file() {
359                root.join(bin)
360            } else {
361                bin.into()
362            })
363            .args(&python_run[1..])
364            .args(["-m", "pytest", "--version"])
365            .current_dir(root)
366            .stdin(std::process::Stdio::null())
367            .stdout(std::process::Stdio::null())
368            .stderr(std::process::Stdio::null())
369            .status()
370            .is_ok_and(|s| s.success())
371        },
372        python_run,
373        ruff: pyproject.contains("[tool.ruff") || exists("ruff.toml") || exists(".ruff.toml"),
374        mypy: pyproject.contains("[tool.mypy") || exists("mypy.ini"),
375        go: exists("go.mod"),
376        make_test: makefile.lines().any(|l| l.starts_with("test:")),
377        include: env_files(root),
378        worktreeinclude: root.join(crate::include::FILE).is_file(),
379    }
380}
381
382/// The checkout's git-ignored `.env` files (`.env`, `.env.local`, at any
383/// depth): what checks often need and a worktree never has.
384#[must_use]
385pub fn env_files(root: &Path) -> Vec<String> {
386    crate::include::matched(root, &[".env".to_owned(), ".env.*".to_owned()])
387}
388
389/// The comment over an `[worktree] include` proposal (what
390/// [`activate_include`] finds).
391const INCLUDE_PROPOSED: &str = "# the git-ignored .env files here; to copy them, uncomment:";
392
393/// The `[worktree]` part of the file: the files `include` is proposed
394/// with, commented; else both keys commented with their meaning.
395fn worktree_section(include: &[String], worktreeinclude: bool) -> String {
396    if worktreeinclude {
397        return "\n# A run's worktree gets the git-ignored files .worktreeinclude names copied from this\n\
398                # checkout (never committed, secret-named values masked); `include` adds patterns.\n\
399                # [worktree]\n# prepare = \"auto\"           # \"off\": never install Node or uv dependencies\n\
400                # include = [\".env\"]\n"
401            .to_owned();
402    }
403    if include.is_empty() {
404        return "\n# A run's worktree gets Node and uv dependencies by their locked, offline install\n\
405                # before the baseline. `include` copies git-ignored files from this checkout.\n\
406                # [worktree]\n# prepare = \"auto\"           # \"off\": never prepare\n\
407                # include = [\".env\"]          # never committed, secret-named values masked\n"
408            .to_owned();
409    }
410    format!(
411        "\n# Git-ignored files a run's worktree gets copied from this checkout: their values are\n\
412         # never committed, and secret-named values masked in what speccoder shows and journals.\n\
413         {INCLUDE_PROPOSED}\n# [worktree]\n# include = [{}]\n",
414        include
415            .iter()
416            .map(|l| quote(l))
417            .collect::<Vec<_>>()
418            .join(", ")
419    )
420}
421
422/// Turns the commented `[worktree] include` proposal `init` wrote in
423/// `root`'s configuration into the setting (a person confirmed it, or
424/// `--yes`).
425///
426/// # Errors
427///
428/// No proposal in the file, or a file speccoder's parsers would refuse.
429pub fn activate_include(root: &Path) -> Result<(), String> {
430    let file = root.join(FILE);
431    let text = std::fs::read_to_string(&file).map_err(|e| format!("{}: {e}", file.display()))?;
432    let from = format!("{INCLUDE_PROPOSED}\n# [worktree]\n# include = ");
433    let Some(at) = text.find(&from) else {
434        return Err("no [worktree] include proposal in the configuration".to_owned());
435    };
436    let next = format!(
437        "{}{}\n[worktree]\ninclude = {}",
438        &text[..at],
439        "# the git-ignored .env files here",
440        &text[at + from.len()..]
441    );
442    crate::prepare::parse(&next)?;
443    crate::verify::config::parse(&next)?;
444    std::fs::write(&file, next).map_err(|e| format!("{}: {e}", file.display()))
445}
446
447/// A TOML basic string (JSON's escapes are valid TOML).
448fn quote(s: &str) -> String {
449    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_owned())
450}
451
452/// The model `init` writes for Bedrock unless `--model` names another: a
453/// Claude inference profile every commercial region offers.
454pub const BEDROCK_MODEL: &str = "global.anthropic.claude-sonnet-5-5";
455
456/// The provider and model `init` writes: the flag, else the provider whose
457/// key variable is set (presence only — the value is never read), else
458/// Bedrock when an AWS credential source is found, else Anthropic.
459fn model_choice(
460    provider: Option<&str>,
461    model: Option<&str>,
462    env: &dyn Fn(&str) -> Option<String>,
463) -> (String, String) {
464    let set = |v: &str| env(v).is_some_and(|x| !x.is_empty());
465    let provider = provider.map_or_else(
466        || {
467            if set("ANTHROPIC_API_KEY") {
468                "anthropic".to_owned()
469            } else if set("OPENAI_API_KEY") {
470                "openai".to_owned()
471            } else if crate::aws::detect(env, &home(env)).is_some() {
472                "bedrock".to_owned()
473            } else {
474                "anthropic".to_owned()
475            }
476        },
477        str::to_owned,
478    );
479    let model = model.map_or_else(
480        || match provider.as_str() {
481            "openai" => "gpt-5.4-mini".to_owned(),
482            "bedrock" => BEDROCK_MODEL.to_owned(),
483            _ => "claude-sonnet-5-5".to_owned(),
484        },
485        str::to_owned,
486    );
487    (provider, model)
488}
489
490/// The home the AWS files are found under, as `env` names it.
491fn home(env: &dyn Fn(&str) -> Option<String>) -> PathBuf {
492    PathBuf::from(env("HOME").unwrap_or_default())
493}
494
495/// The file `init` writes.
496#[must_use]
497pub fn render(
498    checks: &[Proposed],
499    allow: &[Vec<String>],
500    format: Option<&[String]>,
501    provider: &str,
502    model: &str,
503    region: Option<&str>,
504) -> String {
505    let mut out = String::from(
506        "# speccoder configuration — written by `speccoder init`; review it, then commit it\n\
507         # (runs read the committed file in their worktree).\n\n\
508         # Checks: speccoder runs them before and after every attempt and decides the\n\
509         # verdict from them. `fast` runs per task; `full` at phase ends and `verify --tier full`.\n",
510    );
511    if checks.is_empty() {
512        out.push_str(
513            "# No checks were detected. Add at least one, e.g.:\n\
514             # [checks.test]\n# argv = [\"make\", \"test\"]\n",
515        );
516    }
517    for c in checks {
518        out.push_str(&format!("\n# {}\n[checks.{}]\nargv = [", c.why, c.name));
519        out.push_str(
520            &c.argv
521                .iter()
522                .map(|a| quote(a))
523                .collect::<Vec<_>>()
524                .join(", "),
525        );
526        out.push_str("]\n");
527        if c.tier != "fast" {
528            out.push_str(&format!("tier = {}\n", quote(&c.tier)));
529        }
530        if let Some(j) = &c.junit {
531            out.push_str(&format!("junit = {}\n", quote(j)));
532        }
533    }
534    let (about, region) = if provider == "bedrock" {
535        (
536            "Bedrock's credentials come from AWS — a Bedrock API key in\n# AWS_BEARER_TOKEN_BEDROCK, or a profile (aws login, SSO) — never from this file.".to_owned(),
537            region.map_or_else(
538                || "# region = \"…\"  # required: set it\n".to_owned(),
539                |r| format!("region = {}\n", quote(r)),
540            ),
541        )
542    } else {
543        (
544            format!(
545                "The API key comes only from the environment ({}).",
546                if provider == "openai" {
547                    "OPENAI_API_KEY"
548                } else {
549                    "ANTHROPIC_API_KEY"
550                }
551            ),
552            String::new(),
553        )
554    };
555    out.push_str(&format!(
556        "\n# The model. {}\n\
557         [model]\nprovider = {}\nmodel = {}\n{}\
558         # price_input_per_mtok = 0.0       # USD per million tokens, for `speccoder report --cost`\n\
559         # price_output_per_mtok = 0.0\n\
560         # price_cache_read_per_mtok = 0.0\n\
561         \n# Limits per attempt, and attempts per task (a failed verdict is retried once).\n\
562         # [budget]\n# max_turns = 30\n# max_tool_calls = 100\n# max_attempts = 2\n\
563         \n# Test files that existed before an attempt: \"ask\" before any change (default), or\n\
564         # \"additions\" to let new tests be added without asking (changed lines still ask).\n\
565         # [tests]\n# frozen = \"additions\"\n\
566         \n# Commands run in an OS sandbox: writes only to the worktree, credentials unreadable,\n\
567         # no network beyond loopback. Give commands that fetch the network, or switch it off.\n\
568         # [sandbox]\n# network_allow = [[\"cargo\", \"fetch\"]]\n# mode = \"auto\"           # \"required\" refuses to run unsandboxed; \"off\"\n\
569         \n# Commands the OS sandbox confines (writes only here, no network beyond loopback)\n\
570         # run without asking; \"ask\" asks for each.\n\
571         [approvals]\ncontained = \"allow\"\n\
572         \n# Commands the model may run besides the checks, exactly as written; what the\n\
573         # sandbox confines runs anyway, the rest needs approval.\n",
574        about,
575        quote(provider),
576        quote(model),
577        region
578    ));
579    if let Some(argv) = format {
580        out.push_str(&format!(
581            "\n# The formatter speccoder runs after each attempt, before the checks.\n[format]\nargv = [{}]\n\n",
582            argv.iter().map(|a| quote(a)).collect::<Vec<_>>().join(", ")
583        ));
584    }
585    if allow.is_empty() {
586        out.push_str("# [commands]\n# allow = [[\"make\", \"check\"]]\n");
587    } else {
588        let lists: Vec<String> = allow
589            .iter()
590            .map(|a| {
591                format!(
592                    "[{}]",
593                    a.iter().map(|x| quote(x)).collect::<Vec<_>>().join(", ")
594                )
595            })
596            .collect();
597        out.push_str(&format!("[commands]\nallow = [{}]\n", lists.join(", ")));
598    }
599    out
600}
601
602/// The nextest profile speccoder's JUnit report path expects.
603pub const NEXTEST_PROFILE: &str = "\n# Written by `speccoder init`: speccoder reads this JUnit report.\n[profile.speccoder]\nfail-fast = false\n\n[profile.speccoder.junit]\npath = \"junit.xml\"\n";
604
605/// `speccoder init [--provider] [--model] [--region] [--force]` with an
606/// explicit view of the environment (a variable's value when it is set)
607/// and of what is installed.
608pub fn init_with(
609    path: &Path,
610    provider: Option<&str>,
611    model: Option<&str>,
612    region: Option<&str>,
613    force: bool,
614    found: Option<Found>,
615    env: &dyn Fn(&str) -> Option<String>,
616) -> CommandResult {
617    let refuse = |status, m: String| CommandResult::new("init", status, &m);
618    // The Spec Kit root when there is one; else the path itself.
619    let root = match crate::inspect(path, None).data() {
620        Some(CommandData::Inspect(s)) => PathBuf::from(&s.root),
621        _ => path.to_path_buf(),
622    };
623    let file = root.join(FILE);
624    if file.exists() && !force {
625        // It exists: change it, or start it over — never `init` again.
626        return refuse(
627            CommandStatus::ConfigError,
628            format!("{} exists already", file.display()),
629        )
630        .with_code("CONFIG-EXISTS")
631        .with_fix(vec![
632            "speccoder config".to_owned(),
633            "speccoder init --force".to_owned(),
634        ]);
635    }
636    if let Some(p) = provider.filter(|p| !matches!(*p, "anthropic" | "openai" | "bedrock")) {
637        return refuse(
638            CommandStatus::UsageError,
639            format!("--provider {p}: anthropic, openai or bedrock"),
640        );
641    }
642    let (provider, model) = model_choice(provider, model, env);
643    let bedrock = provider == "bedrock";
644    if region.is_some() && !bedrock {
645        return refuse(
646            CommandStatus::UsageError,
647            format!("--region is for --provider bedrock, not {provider}"),
648        );
649    }
650    // Bedrock's region: the flag, else where the AWS tools find it.
651    let region = bedrock
652        .then(|| {
653            region
654                .map(|r| r.trim().to_owned())
655                .filter(|r| !r.is_empty())
656                .or_else(|| crate::aws::region(env, &home(env)).map(|(r, _)| r))
657        })
658        .flatten();
659    let found = found.unwrap_or_else(|| detect(&root));
660    let checks = propose(&found);
661    let mut text = render(
662        &checks,
663        &allow(&found),
664        formatter(&found).as_deref(),
665        &provider,
666        &model,
667        region.as_deref(),
668    );
669    // The repository's instructions for agents: AGENTS.md is read by
670    // default; a repository that only has CLAUDE.md gets it named too.
671    let instructions: Vec<String> = ["AGENTS.md", "CLAUDE.md"]
672        .iter()
673        .filter(|n| root.join(n).is_file())
674        .map(|n| (*n).to_owned())
675        .collect();
676    text.push_str(&worktree_section(&found.include, found.worktreeinclude));
677    if instructions == ["CLAUDE.md"] {
678        text.push_str(
679            "\n# The repository's instructions for agents, given to every attempt: CLAUDE.md\n# here, AGENTS.md wherever a directory has one.\n[context]\ninstructions = [\"AGENTS.md\", \"CLAUDE.md\"]\n",
680        );
681    }
682    let key = if bedrock {
683        // Where the AWS chain will take credentials from, by kind and name.
684        let source = crate::aws::detect(env, &home(env));
685        speccoder_core::InitKey {
686            variable: crate::aws::API_KEY.to_owned(),
687            set: source.is_some(),
688            source: source.map(|s| s.describe()),
689        }
690    } else {
691        let variable = if provider == "openai" {
692            "OPENAI_API_KEY"
693        } else {
694            "ANTHROPIC_API_KEY"
695        }
696        .to_owned();
697        speccoder_core::InitKey {
698            set: env(&variable).is_some_and(|v| !v.is_empty()),
699            variable,
700            source: None,
701        }
702    };
703    // Never write what speccoder itself would refuse — but Bedrock without
704    // a region found, which every command then names with its fix.
705    let model_parsed = crate::substrate::model_config::parse(&text)
706        .map(|_| ())
707        .or_else(|e| {
708            if bedrock && region.is_none() && e.contains("needs `region`") {
709                Ok(())
710            } else {
711                Err(e)
712            }
713        });
714    if let Err(e) = crate::verify::config::parse(&text)
715        .and(model_parsed)
716        .and_then(|()| crate::substrate::run_config::parse(&text).map(|_| ()))
717    {
718        return refuse(
719            CommandStatus::Error,
720            format!("generated configuration is invalid: {e}"),
721        );
722    }
723    let mut wrote = Vec::new();
724    if let Err(e) = std::fs::write(&file, &text) {
725        return refuse(CommandStatus::Error, format!("{}: {e}", file.display()));
726    }
727    wrote.push(FILE.to_owned());
728    // The nextest profile the `test` check names, unless one is there.
729    if checks.iter().any(|c| c.argv.iter().any(|a| a == "nextest")) {
730        let nextest = root.join(".config/nextest.toml");
731        let existing = std::fs::read_to_string(&nextest).unwrap_or_default();
732        if !existing.contains("[profile.speccoder]") {
733            let _ = std::fs::create_dir_all(root.join(".config"));
734            if std::fs::write(&nextest, format!("{existing}{NEXTEST_PROFILE}")).is_ok() {
735                wrote.push(".config/nextest.toml".to_owned());
736            }
737        }
738    }
739    // What checks write — speccoder's reports under .speccoder/, the
740    // toolchains' build output — is output, not source: kept out of git, or
741    // every run would find it in the worktree and set it aside. Added to
742    // .gitignore only when that file is new or has no other uncommitted
743    // change (so committing it commits nothing else).
744    let mut output: Vec<&str> = Vec::new();
745    if checks
746        .iter()
747        .any(|c| c.argv.iter().any(|a| a.contains(".speccoder/")))
748    {
749        output.push(".speccoder/");
750    }
751    for c in &checks {
752        for dir in crate::worktree::build_output(&c.argv) {
753            if !output.contains(dir) {
754                output.push(dir);
755            }
756        }
757    }
758    let git = Git::at(&root);
759    let missing: Vec<&str> = output
760        .into_iter()
761        .filter(|d| {
762            !git.succeeds(&["check-ignore", "-q", "--no-index", d])
763                .unwrap_or(false)
764        })
765        .collect();
766    if !missing.is_empty() {
767        let ignore = root.join(".gitignore");
768        let existing = std::fs::read_to_string(&ignore).unwrap_or_default();
769        let clean = !ignore.exists()
770            || git
771                .line(&["status", "--porcelain", "--", ".gitignore"])
772                .is_ok_and(|l| l.trim().is_empty());
773        if clean {
774            let sep = if existing.is_empty() || existing.ends_with('\n') {
775                ""
776            } else {
777                "\n"
778            };
779            if std::fs::write(
780                &ignore,
781                format!(
782                    "{existing}{sep}# what checks write (speccoder init)\n{}\n",
783                    missing.join("\n")
784                ),
785            )
786            .is_ok()
787            {
788                wrote.push(".gitignore".to_owned());
789            }
790        }
791    }
792    let mut message = if checks.is_empty() {
793        format!("wrote {FILE} without checks — add one before `speccoder run`")
794    } else {
795        format!(
796            "wrote {} with {} check(s) and {provider}/{model}; review it, then commit it",
797            speccoder_core::words::listed(&wrote),
798            checks.len()
799        )
800    };
801    if bedrock && region.is_none() {
802        message.push_str("; no AWS region was found — speccoder config set model.region <region>");
803    }
804    CommandResult::new("init", CommandStatus::Ok, &message).with_data(CommandData::Init(Box::new(
805        speccoder_core::InitReport {
806            path: file.display().to_string(),
807            checks: checks
808                .iter()
809                .map(|c| speccoder_core::InitCheck {
810                    name: c.name.clone(),
811                    argv: c.argv.clone(),
812                    tier: c.tier.clone(),
813                    why: c.why.clone(),
814                })
815                .collect(),
816            model: format!("{provider}/{model}"),
817            wrote,
818            ran: Vec::new(),
819            instructions,
820            key,
821            region,
822            committed: None,
823            include: found.include.clone(),
824            include_active: false,
825            worktreeinclude: found.worktreeinclude,
826        },
827    )))
828}
829
830/// Whether a test check found no tests to run — an empty suite on a fresh
831/// scaffold: pytest's exit 5, `go test` with only packages
832/// without test files, vitest, jest or nextest reporting nothing to run.
833/// Neither passing nor failing: *no tests yet*.
834#[must_use]
835pub fn no_tests(argv: &[String], exit: Option<i32>, output: &str) -> bool {
836    let has = |w: &str| argv.iter().any(|a| a == w || a.ends_with(&format!("/{w}")));
837    let lower = output.to_lowercase();
838    if has("pytest") {
839        return exit == Some(5);
840    }
841    if has("go") && argv.iter().any(|a| a == "test") {
842        let said: Vec<&str> = output
843            .lines()
844            .map(str::trim)
845            .filter(|l| !l.is_empty())
846            .collect();
847        return exit == Some(0)
848            && !said.is_empty()
849            && said
850                .iter()
851                .all(|l| l.contains("no test files") || l.contains("matched no packages"));
852    }
853    // Only a run that ended as an empty suite ends: a failure that also
854    // says "no tests" somewhere stays a failure.
855    if has("vitest") || has("jest") || argv.iter().any(|a| a == "test") && has("npm") {
856        return exit == Some(0)
857            && (lower.contains("no test files found") || lower.contains("no tests found"));
858    }
859    if has("nextest") {
860        // nextest's own exit status for "no tests to run".
861        return exit == Some(4) && lower.contains("no tests to run");
862    }
863    false
864}
865
866/// Runs the fast-tier checks of the configuration `init` just wrote on the
867/// untouched code, confined like in a run.
868#[must_use]
869pub fn verify_written(root: &Path) -> Vec<speccoder_core::InitRun> {
870    use speccoder_core::verify::CheckStatus;
871    let Ok((runner, _)) = crate::sandbox::runner_at(root) else {
872        return Vec::new();
873    };
874    let Ok(report) =
875        crate::verify::run_checks(root, Some(crate::verify::config::Tier::Fast), &runner)
876    else {
877        return Vec::new();
878    };
879    report
880        .checks
881        .iter()
882        .map(|c| speccoder_core::InitRun {
883            name: c.name.clone(),
884            passed: matches!(c.status, CheckStatus::Passed | CheckStatus::Skipped),
885            status: if no_tests(
886                &c.argv,
887                c.exit_code,
888                &format!("{}\n{}", c.stdout_tail, c.stderr_tail),
889            ) {
890                "no_tests".to_owned()
891            } else {
892                serde_json::to_value(c.status)
893                    .ok()
894                    .and_then(|v| v.as_str().map(str::to_owned))
895                    .unwrap_or_default()
896            },
897            duration_ms: c.duration_ms,
898            reason: (!matches!(c.status, CheckStatus::Passed | CheckStatus::Skipped))
899                .then(|| {
900                    let said = |t: &str| {
901                        t.lines()
902                            .rev()
903                            .map(str::trim)
904                            .find(|l| !l.is_empty())
905                            .map(str::to_owned)
906                    };
907                    said(&c.stderr_tail)
908                        .or_else(|| said(&c.stdout_tail))
909                        .or_else(|| c.note.clone())
910                        .unwrap_or_else(|| {
911                            format!(
912                                "exit {}",
913                                c.exit_code
914                                    .map_or_else(|| "?".to_owned(), |e| e.to_string())
915                            )
916                        })
917                })
918                .map(|r| r.chars().take(200).collect()),
919        })
920        .collect()
921}
922
923/// [`init_with`] for this machine.
924#[must_use]
925pub fn init(
926    path: &Path,
927    provider: Option<&str>,
928    model: Option<&str>,
929    region: Option<&str>,
930    force: bool,
931) -> CommandResult {
932    init_with(path, provider, model, region, force, None, &crate::aws::var)
933}
934
935/// `init` written and its checks run on the untouched code: what a person
936/// then decides to commit.
937#[derive(Debug, Clone)]
938pub struct Prepared {
939    /// `init`'s own result.
940    pub written: CommandResult,
941    /// Its report, with the checks' runs.
942    pub report: speccoder_core::InitReport,
943    /// The project root the file was written in.
944    pub root: PathBuf,
945    /// Everything the checks need committed: the file, and the nextest
946    /// profile it names when that is not committed yet.
947    pub to_commit: Vec<String>,
948    /// Checks that fail on the untouched code.
949    pub failed: Vec<String>,
950}
951
952/// The files `init` may commit: nothing else, whatever a caller asks.
953pub const COMMITTABLE: &[&str] = &[
954    FILE,
955    ".config/nextest.toml",
956    ".gitignore",
957    "Cargo.lock",
958    "package-lock.json",
959    "pnpm-lock.yaml",
960    "yarn.lock",
961    "uv.lock",
962    "poetry.lock",
963    "go.sum",
964];
965
966/// Writes the configuration and (unless `no_verify`) runs its checks on the
967/// untouched code. A refusal comes back as `Err`.
968///
969/// # Errors
970///
971/// `init`'s refusal (a file exists, no project, …).
972pub fn prepare(
973    path: &Path,
974    provider: Option<&str>,
975    model: Option<&str>,
976    region: Option<&str>,
977    force: bool,
978    no_verify: bool,
979) -> Result<Prepared, Box<CommandResult>> {
980    let written = init(path, provider, model, region, force);
981    let Some(CommandData::Init(report)) = written.data() else {
982        return Err(Box::new(written));
983    };
984    let mut report = (**report).clone();
985    let root = PathBuf::from(&report.path)
986        .parent()
987        .map(Path::to_path_buf)
988        .unwrap_or_default();
989    if !no_verify && !report.checks.is_empty() {
990        report.ran = verify_written(&root);
991    }
992    let failed = report
993        .ran
994        .iter()
995        .filter(|r| !r.passed && r.status != "no_tests")
996        .map(|r| r.name.clone())
997        .collect();
998    let mut to_commit: Vec<String> = report.wrote.clone();
999    let profile = ".config/nextest.toml";
1000    if report
1001        .checks
1002        .iter()
1003        .any(|c| c.argv.iter().any(|a| a == "nextest"))
1004        && root.join(profile).exists()
1005        && !to_commit.iter().any(|p| p == profile)
1006        && Git::at(&root)
1007            .line(&["status", "--porcelain", "--", profile])
1008            .is_ok_and(|l| !l.trim().is_empty())
1009    {
1010        to_commit.push(profile.to_owned());
1011    }
1012    // A lockfile the checks just wrote, never committed: every run would
1013    // find it in the worktree, so it goes with the configuration.
1014    for lock in crate::worktree::LOCKFILES {
1015        if root.join(lock).exists()
1016            && !to_commit.iter().any(|p| p == lock)
1017            && Git::at(&root)
1018                .line(&["status", "--porcelain", "--", lock])
1019                .is_ok_and(|l| l.starts_with("??"))
1020        {
1021            to_commit.push((*lock).to_owned());
1022        }
1023    }
1024    Ok(Prepared {
1025        written,
1026        report,
1027        root,
1028        to_commit,
1029        failed,
1030    })
1031}
1032
1033/// Commits exactly `paths` — each one of [`COMMITTABLE`] — as
1034/// `speccoder: config`; the short id.
1035///
1036/// # Errors
1037///
1038/// A path `init` does not commit, or git's complaint.
1039pub fn commit_written(root: &Path, paths: &[String]) -> Result<String, String> {
1040    commit_written_as(root, paths, "speccoder: config")
1041}
1042
1043/// [`commit_written`] with its own subject.
1044///
1045/// # Errors
1046///
1047/// A path `init` does not commit, or git's complaint.
1048pub fn commit_written_as(root: &Path, paths: &[String], subject: &str) -> Result<String, String> {
1049    if paths.is_empty() {
1050        return Err("nothing to commit".to_owned());
1051    }
1052    if let Some(p) = paths.iter().find(|p| !COMMITTABLE.contains(&p.as_str())) {
1053        return Err(format!("`{p}` is not a file init commits"));
1054    }
1055    let g = Git::at(root);
1056    let names: Vec<&str> = paths.iter().map(String::as_str).collect();
1057    let mut add = vec!["add", "--"];
1058    add.extend(&names);
1059    let mut commit = vec!["commit", "-q", "-m", subject, "--"];
1060    commit.extend(&names);
1061    g.run(&add).map_err(|e| e.0)?;
1062    // Nothing differs from the last commit: say that, not an empty failure.
1063    let mut unchanged = vec!["diff", "--cached", "--quiet", "--"];
1064    unchanged.extend(&names);
1065    if g.succeeds(&unchanged).unwrap_or(false) {
1066        return Err(format!(
1067            "nothing to commit: {} is committed as it is",
1068            speccoder_core::words::listed(&names)
1069        ));
1070    }
1071    g.run(&commit)
1072        .and_then(|_| g.line(&["rev-parse", "--short", "HEAD"]))
1073        .map_err(|e| {
1074            if e.0.trim().is_empty() {
1075                "git commit failed without saying why".to_owned()
1076            } else {
1077                e.0
1078            }
1079        })
1080}
1081
1082/// The result of an `init` the person has decided about: the message, the
1083/// report, and what comes next.
1084#[must_use]
1085pub fn finish(p: Prepared) -> CommandResult {
1086    let Prepared {
1087        written,
1088        report,
1089        to_commit,
1090        failed,
1091        ..
1092    } = p;
1093    let mut message = match &report.committed {
1094        Some(id) => written.message().replace(
1095            "; review it, then commit it",
1096            &format!(" and committed it ({id})"),
1097        ),
1098        None => written.message().to_owned(),
1099    };
1100    if !failed.is_empty() {
1101        message = format!(
1102            "{message}; the check(s) {} fail on the untouched code: every task would be judged against a red baseline",
1103            failed.join(", ")
1104        );
1105    }
1106    let step = |command: String, why: &str| speccoder_core::next::NextStep {
1107        command,
1108        why: why.to_owned(),
1109    };
1110    let mut next = Vec::new();
1111    // No spec project yet: the format's tool makes one — first, before the
1112    // commit and the key matter.
1113    let root = PathBuf::from(&report.path)
1114        .parent()
1115        .map(Path::to_path_buf)
1116        .unwrap_or_default();
1117    let format = crate::format::at(&root);
1118    if format.detect(&root).is_none() {
1119        let (command, why) = format.messages().make_project;
1120        message = format!("{message}; there is no spec project here yet");
1121        next.push(step(command.to_owned(), why));
1122    }
1123    if report.committed.is_none() {
1124        let listed = to_commit.join(" ");
1125        next.push(step(
1126            format!("git add {listed} && git commit -m \"speccoder: config\" -- {listed}"),
1127            "speccoder reads committed files only",
1128        ));
1129    }
1130    if !report.key.set && report.model.starts_with("bedrock/") {
1131        next.push(step(
1132            format!("export {}=…", report.key.variable),
1133            "a Bedrock API key — or run aws login where you start speccoder",
1134        ));
1135    } else if !report.key.set {
1136        next.push(step(
1137            format!("export {}=…", report.key.variable),
1138            "the model key, from the environment only",
1139        ));
1140    }
1141    // Something to run, or something to write first.
1142    let features = match crate::current::list(&root, None).data() {
1143        Some(CommandData::Features(f)) => f.features.len(),
1144        _ => 0,
1145    };
1146    if features == 0 {
1147        next.push(step(
1148            "speccoder spec specify \"…\"".to_owned(),
1149            "describe the first feature; its spec, plan and tasks follow",
1150        ));
1151    } else {
1152        next.push(step(
1153            "speccoder run".to_owned(),
1154            "work through the ready tasks",
1155        ));
1156    }
1157    CommandResult::new("init", CommandStatus::Ok, &message)
1158        .with_data(CommandData::Init(Box::new(report)))
1159        .with_next(next)
1160}
1161
1162/// What `init` would write here, without writing: for the setup assistant.
1163#[derive(Debug, Clone, Serialize)]
1164pub struct Preview {
1165    /// Whether the project already has a `speccoder.toml`.
1166    pub configured: bool,
1167    /// The checks it would declare.
1168    pub checks: Vec<Proposed>,
1169    /// Commands the model could run without asking.
1170    pub allow: Vec<Vec<String>>,
1171    /// The formatter it would configure.
1172    pub formatter: Option<Vec<String>>,
1173    /// The model key variables, and whether each is set.
1174    pub keys: Vec<(String, bool)>,
1175    /// Amazon Bedrock's credential source and region, as found here.
1176    pub bedrock: BedrockPreview,
1177    /// The git-ignored files proposed for `[worktree] include`.
1178    pub include: Vec<String>,
1179}
1180
1181/// Where Bedrock's credentials and region would come from: named, never a
1182/// value.
1183#[derive(Debug, Clone, Default, Serialize)]
1184pub struct BedrockPreview {
1185    /// The source, as `doctor` describes it (`aws login session (profile dev)`).
1186    pub source: Option<String>,
1187    /// The region `init` would write.
1188    pub region: Option<String>,
1189}
1190
1191/// Where `init` writes for `path`: the spec project's root, else `path`.
1192#[must_use]
1193pub fn root_of(path: &Path) -> PathBuf {
1194    match crate::inspect(path, None).data() {
1195        Some(CommandData::Inspect(s)) => PathBuf::from(&s.root),
1196        _ => path.to_path_buf(),
1197    }
1198}
1199
1200/// [`Preview`] of `path`.
1201#[must_use]
1202pub fn preview(path: &Path) -> Preview {
1203    let root = root_of(path);
1204    let found = detect(&root);
1205    let set = |v: &str| std::env::var_os(v).is_some_and(|x| !x.is_empty());
1206    Preview {
1207        configured: root.join(FILE).is_file(),
1208        checks: propose(&found),
1209        allow: allow(&found),
1210        formatter: formatter(&found),
1211        keys: ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"]
1212            .iter()
1213            .map(|v| ((*v).to_owned(), set(v)))
1214            .collect(),
1215        bedrock: BedrockPreview {
1216            source: crate::aws::detect_here().map(|s| s.describe()),
1217            region: crate::aws::region_here().map(|(r, _)| r),
1218        },
1219        include: found.include,
1220    }
1221}
1222
1223#[cfg(test)]
1224mod tests {
1225    use super::*;
1226
1227    #[test]
1228    fn a_uv_project_runs_its_checks_through_uv_never_an_uncommitted_venv() {
1229        let d = tempfile::tempdir().unwrap();
1230        std::fs::write(d.path().join("pyproject.toml"), "[project]\nname = \"p\"\n").unwrap();
1231        std::fs::write(d.path().join("uv.lock"), "version = 1\n").unwrap();
1232        std::fs::create_dir_all(d.path().join(".venv/bin")).unwrap();
1233        std::fs::write(d.path().join(".venv/bin/python"), "").unwrap();
1234        let found = detect(d.path());
1235        assert_eq!(
1236            found.python_run,
1237            ["uv", "run", "--locked", "--offline", "python"]
1238        );
1239        let test = &propose(&found)[0];
1240        assert_eq!(
1241            test.argv.join(" "),
1242            "uv run --locked --offline python -m pytest -q --junitxml=.speccoder/junit.xml"
1243        );
1244        // Without a lockfile, a project-local virtualenv's interpreter.
1245        std::fs::remove_file(d.path().join("uv.lock")).unwrap();
1246        assert_eq!(detect(d.path()).python_run, [".venv/bin/python"]);
1247    }
1248
1249    #[test]
1250    fn proposals_follow_what_was_found() {
1251        let rust = propose(&Found {
1252            cargo: true,
1253            nextest: true,
1254            ..Found::default()
1255        });
1256        let names: Vec<&str> = rust.iter().map(|c| c.name.as_str()).collect();
1257        assert_eq!(names, ["test", "fmt", "clippy"]);
1258        assert_eq!(
1259            rust[0].junit.as_deref(),
1260            Some("target/nextest/speccoder/junit.xml")
1261        );
1262        assert_eq!(rust[2].tier, "full");
1263        let plain = propose(&Found {
1264            cargo: true,
1265            ..Found::default()
1266        });
1267        assert_eq!(plain[0].argv, ["cargo", "test", "--workspace"]);
1268
1269        let node = propose(&Found {
1270            node_manager: Some("pnpm".to_owned()),
1271            npm_scripts: vec!["test".into(), "lint".into(), "build".into()],
1272            ..Found::default()
1273        });
1274        let shown: Vec<(String, String)> = node
1275            .iter()
1276            .map(|c| (c.name.clone(), c.argv.join(" ")))
1277            .collect();
1278        assert_eq!(
1279            shown,
1280            [
1281                ("test".into(), "pnpm run test".into()),
1282                ("lint".into(), "pnpm run lint".into())
1283            ]
1284        );
1285        let npm = propose(&Found {
1286            node_manager: Some("npm".to_owned()),
1287            npm_scripts: vec!["test".into()],
1288            ..Found::default()
1289        });
1290        assert_eq!(npm[0].argv, ["npm", "run", "test"]);
1291
1292        let py = propose(&Found {
1293            python: true,
1294            ruff: true,
1295            ..Found::default()
1296        });
1297        assert_eq!(
1298            py.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
1299            ["test", "ruff"]
1300        );
1301        let go = propose(&Found {
1302            go: true,
1303            ..Found::default()
1304        });
1305        assert_eq!(go[0].argv, ["go", "test", "./..."]);
1306        let make = propose(&Found {
1307            make_test: true,
1308            ..Found::default()
1309        });
1310        assert_eq!(make[0].argv, ["make", "test"]);
1311        assert!(propose(&Found::default()).is_empty());
1312    }
1313
1314    #[test]
1315    fn the_model_follows_the_key_that_is_set() {
1316        let none = |_: &str| None;
1317        let openai = |v: &str| (v == "OPENAI_API_KEY").then(|| "k".to_owned());
1318        assert_eq!(model_choice(None, None, &none).0, "anthropic");
1319        assert_eq!(
1320            model_choice(None, None, &openai),
1321            ("openai".to_owned(), "gpt-5.4-mini".to_owned())
1322        );
1323        assert_eq!(
1324            model_choice(Some("anthropic"), Some("m"), &openai),
1325            ("anthropic".to_owned(), "m".to_owned())
1326        );
1327    }
1328
1329    #[test]
1330    fn every_rendered_file_parses() {
1331        for found in [
1332            Found {
1333                cargo: true,
1334                nextest: true,
1335                ..Found::default()
1336            },
1337            Found {
1338                python: true,
1339                ruff: true,
1340                mypy: true,
1341                go: true,
1342                ..Found::default()
1343            },
1344            Found::default(),
1345        ] {
1346            let text = render(
1347                &propose(&found),
1348                &allow(&found),
1349                formatter(&found).as_deref(),
1350                "openai",
1351                "gpt-5.4-mini",
1352                None,
1353            );
1354            if found.cargo {
1355                assert!(
1356                    text.contains("[format]\nargv = [\"cargo\", \"fmt\", \"--all\"]"),
1357                    "{text}"
1358                );
1359                assert_eq!(
1360                    crate::substrate::run_config::parse(&text)
1361                        .ok()
1362                        .and_then(|c| c.format),
1363                    Some(vec![
1364                        "cargo".to_owned(),
1365                        "fmt".to_owned(),
1366                        "--all".to_owned()
1367                    ])
1368                );
1369            }
1370            let checks =
1371                crate::verify::config::parse(&text).unwrap_or_else(|e| panic!("{e}\n{text}"));
1372            assert_eq!(checks.len(), propose(&found).len());
1373            assert!(crate::substrate::model_config::parse(&text).is_ok_and(|m| m.is_some()));
1374            assert!(crate::substrate::run_config::parse(&text).is_ok());
1375        }
1376    }
1377
1378    #[test]
1379    fn an_empty_suite_on_a_fresh_scaffold_is_no_tests_yet() {
1380        let argv = |a: &[&str]| a.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
1381        assert!(no_tests(
1382            &argv(&["uv", "run", "pytest"]),
1383            Some(5),
1384            "no tests ran"
1385        ));
1386        assert!(!no_tests(
1387            &argv(&["uv", "run", "pytest"]),
1388            Some(1),
1389            "1 failed"
1390        ));
1391        assert!(no_tests(
1392            &argv(&["go", "test", "./..."]),
1393            Some(0),
1394            "go: warning: \"./...\" matched no packages\n"
1395        ));
1396        assert!(no_tests(
1397            &argv(&["go", "test", "./..."]),
1398            Some(0),
1399            "?   \tx\t[no test files]\n"
1400        ));
1401        assert!(!no_tests(
1402            &argv(&["go", "test", "./..."]),
1403            Some(0),
1404            "ok  \tx\t0.1s\n"
1405        ));
1406        assert!(no_tests(
1407            &argv(&["npm", "test"]),
1408            Some(0),
1409            "No test files found, exiting with code 0"
1410        ));
1411        assert!(no_tests(
1412            &argv(&["npx", "vitest", "run"]),
1413            Some(0),
1414            "No test files found"
1415        ));
1416        assert!(no_tests(
1417            &argv(&["cargo", "nextest", "run"]),
1418            Some(4),
1419            "error: no tests to run"
1420        ));
1421        assert!(!no_tests(
1422            &argv(&["cargo", "test"]),
1423            Some(0),
1424            "test result: ok. 1 passed"
1425        ));
1426    }
1427}