1use 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
20pub struct Found {
21 pub cargo: bool,
23 pub nextest: bool,
25 pub npm_scripts: Vec<String>,
27 pub node_manager: Option<String>,
29 pub python: bool,
31 pub python_run: Vec<String>,
37 pub pytest: bool,
39 pub ruff: bool,
41 pub mypy: bool,
43 pub go: bool,
45 pub make_test: bool,
47 pub include: Vec<String>,
50 pub worktreeinclude: bool,
52}
53
54impl Found {
55 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
69pub struct Proposed {
70 pub name: String,
72 pub argv: Vec<String>,
74 pub tier: String,
76 pub junit: Option<String>,
78 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#[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 &[
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 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#[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#[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#[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 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#[must_use]
385pub fn env_files(root: &Path) -> Vec<String> {
386 crate::include::matched(root, &[".env".to_owned(), ".env.*".to_owned()])
387}
388
389const INCLUDE_PROPOSED: &str = "# the git-ignored .env files here; to copy them, uncomment:";
392
393fn 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
422pub 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
447fn quote(s: &str) -> String {
449 serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_owned())
450}
451
452pub const BEDROCK_MODEL: &str = "global.anthropic.claude-sonnet-5-5";
455
456fn 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
490fn home(env: &dyn Fn(&str) -> Option<String>) -> PathBuf {
492 PathBuf::from(env("HOME").unwrap_or_default())
493}
494
495#[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 model may run besides the checks (argv prefixes); others need approval.\n",
570 about,
571 quote(provider),
572 quote(model),
573 region
574 ));
575 if let Some(argv) = format {
576 out.push_str(&format!(
577 "\n# The formatter speccoder runs after each attempt, before the checks.\n[format]\nargv = [{}]\n\n",
578 argv.iter().map(|a| quote(a)).collect::<Vec<_>>().join(", ")
579 ));
580 }
581 if allow.is_empty() {
582 out.push_str("# [commands]\n# allow = [[\"make\", \"check\"]]\n");
583 } else {
584 let lists: Vec<String> = allow
585 .iter()
586 .map(|a| {
587 format!(
588 "[{}]",
589 a.iter().map(|x| quote(x)).collect::<Vec<_>>().join(", ")
590 )
591 })
592 .collect();
593 out.push_str(&format!("[commands]\nallow = [{}]\n", lists.join(", ")));
594 }
595 out
596}
597
598pub 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";
600
601pub fn init_with(
605 path: &Path,
606 provider: Option<&str>,
607 model: Option<&str>,
608 region: Option<&str>,
609 force: bool,
610 found: Option<Found>,
611 env: &dyn Fn(&str) -> Option<String>,
612) -> CommandResult {
613 let refuse = |status, m: String| CommandResult::new("init", status, &m);
614 let root = match crate::inspect(path, None).data() {
616 Some(CommandData::Inspect(s)) => PathBuf::from(&s.root),
617 _ => path.to_path_buf(),
618 };
619 let file = root.join(FILE);
620 if file.exists() && !force {
621 return refuse(
623 CommandStatus::ConfigError,
624 format!("{} exists already", file.display()),
625 )
626 .with_code("CONFIG-EXISTS")
627 .with_fix(vec![
628 "speccoder config".to_owned(),
629 "speccoder init --force".to_owned(),
630 ]);
631 }
632 if let Some(p) = provider.filter(|p| !matches!(*p, "anthropic" | "openai" | "bedrock")) {
633 return refuse(
634 CommandStatus::UsageError,
635 format!("--provider {p}: anthropic, openai or bedrock"),
636 );
637 }
638 let (provider, model) = model_choice(provider, model, env);
639 let bedrock = provider == "bedrock";
640 if region.is_some() && !bedrock {
641 return refuse(
642 CommandStatus::UsageError,
643 format!("--region is for --provider bedrock, not {provider}"),
644 );
645 }
646 let region = bedrock
648 .then(|| {
649 region
650 .map(|r| r.trim().to_owned())
651 .filter(|r| !r.is_empty())
652 .or_else(|| crate::aws::region(env, &home(env)).map(|(r, _)| r))
653 })
654 .flatten();
655 let found = found.unwrap_or_else(|| detect(&root));
656 let checks = propose(&found);
657 let mut text = render(
658 &checks,
659 &allow(&found),
660 formatter(&found).as_deref(),
661 &provider,
662 &model,
663 region.as_deref(),
664 );
665 let instructions: Vec<String> = ["AGENTS.md", "CLAUDE.md"]
668 .iter()
669 .filter(|n| root.join(n).is_file())
670 .map(|n| (*n).to_owned())
671 .collect();
672 text.push_str(&worktree_section(&found.include, found.worktreeinclude));
673 if instructions == ["CLAUDE.md"] {
674 text.push_str(
675 "\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",
676 );
677 }
678 let key = if bedrock {
679 let source = crate::aws::detect(env, &home(env));
681 speccoder_core::InitKey {
682 variable: crate::aws::API_KEY.to_owned(),
683 set: source.is_some(),
684 source: source.map(|s| s.describe()),
685 }
686 } else {
687 let variable = if provider == "openai" {
688 "OPENAI_API_KEY"
689 } else {
690 "ANTHROPIC_API_KEY"
691 }
692 .to_owned();
693 speccoder_core::InitKey {
694 set: env(&variable).is_some_and(|v| !v.is_empty()),
695 variable,
696 source: None,
697 }
698 };
699 let model_parsed = crate::substrate::model_config::parse(&text)
702 .map(|_| ())
703 .or_else(|e| {
704 if bedrock && region.is_none() && e.contains("needs `region`") {
705 Ok(())
706 } else {
707 Err(e)
708 }
709 });
710 if let Err(e) = crate::verify::config::parse(&text)
711 .and(model_parsed)
712 .and_then(|()| crate::substrate::run_config::parse(&text).map(|_| ()))
713 {
714 return refuse(
715 CommandStatus::Error,
716 format!("generated configuration is invalid: {e}"),
717 );
718 }
719 let mut wrote = Vec::new();
720 if let Err(e) = std::fs::write(&file, &text) {
721 return refuse(CommandStatus::Error, format!("{}: {e}", file.display()));
722 }
723 wrote.push(FILE.to_owned());
724 if checks.iter().any(|c| c.argv.iter().any(|a| a == "nextest")) {
726 let nextest = root.join(".config/nextest.toml");
727 let existing = std::fs::read_to_string(&nextest).unwrap_or_default();
728 if !existing.contains("[profile.speccoder]") {
729 let _ = std::fs::create_dir_all(root.join(".config"));
730 if std::fs::write(&nextest, format!("{existing}{NEXTEST_PROFILE}")).is_ok() {
731 wrote.push(".config/nextest.toml".to_owned());
732 }
733 }
734 }
735 let mut output: Vec<&str> = Vec::new();
741 if checks
742 .iter()
743 .any(|c| c.argv.iter().any(|a| a.contains(".speccoder/")))
744 {
745 output.push(".speccoder/");
746 }
747 for c in &checks {
748 for dir in crate::worktree::build_output(&c.argv) {
749 if !output.contains(dir) {
750 output.push(dir);
751 }
752 }
753 }
754 let git = Git::at(&root);
755 let missing: Vec<&str> = output
756 .into_iter()
757 .filter(|d| {
758 !git.succeeds(&["check-ignore", "-q", "--no-index", d])
759 .unwrap_or(false)
760 })
761 .collect();
762 if !missing.is_empty() {
763 let ignore = root.join(".gitignore");
764 let existing = std::fs::read_to_string(&ignore).unwrap_or_default();
765 let clean = !ignore.exists()
766 || git
767 .line(&["status", "--porcelain", "--", ".gitignore"])
768 .is_ok_and(|l| l.trim().is_empty());
769 if clean {
770 let sep = if existing.is_empty() || existing.ends_with('\n') {
771 ""
772 } else {
773 "\n"
774 };
775 if std::fs::write(
776 &ignore,
777 format!(
778 "{existing}{sep}# what checks write (speccoder init)\n{}\n",
779 missing.join("\n")
780 ),
781 )
782 .is_ok()
783 {
784 wrote.push(".gitignore".to_owned());
785 }
786 }
787 }
788 let mut message = if checks.is_empty() {
789 format!("wrote {FILE} without checks — add one before `speccoder run`")
790 } else {
791 format!(
792 "wrote {} with {} check(s) and {provider}/{model}; review it, then commit it",
793 speccoder_core::words::listed(&wrote),
794 checks.len()
795 )
796 };
797 if bedrock && region.is_none() {
798 message.push_str("; no AWS region was found — speccoder config set model.region <region>");
799 }
800 CommandResult::new("init", CommandStatus::Ok, &message).with_data(CommandData::Init(Box::new(
801 speccoder_core::InitReport {
802 path: file.display().to_string(),
803 checks: checks
804 .iter()
805 .map(|c| speccoder_core::InitCheck {
806 name: c.name.clone(),
807 argv: c.argv.clone(),
808 tier: c.tier.clone(),
809 why: c.why.clone(),
810 })
811 .collect(),
812 model: format!("{provider}/{model}"),
813 wrote,
814 ran: Vec::new(),
815 instructions,
816 key,
817 region,
818 committed: None,
819 include: found.include.clone(),
820 include_active: false,
821 worktreeinclude: found.worktreeinclude,
822 },
823 )))
824}
825
826#[must_use]
831pub fn no_tests(argv: &[String], exit: Option<i32>, output: &str) -> bool {
832 let has = |w: &str| argv.iter().any(|a| a == w || a.ends_with(&format!("/{w}")));
833 let lower = output.to_lowercase();
834 if has("pytest") {
835 return exit == Some(5);
836 }
837 if has("go") && argv.iter().any(|a| a == "test") {
838 let said: Vec<&str> = output
839 .lines()
840 .map(str::trim)
841 .filter(|l| !l.is_empty())
842 .collect();
843 return exit == Some(0)
844 && !said.is_empty()
845 && said
846 .iter()
847 .all(|l| l.contains("no test files") || l.contains("matched no packages"));
848 }
849 if has("vitest") || has("jest") || argv.iter().any(|a| a == "test") && has("npm") {
852 return exit == Some(0)
853 && (lower.contains("no test files found") || lower.contains("no tests found"));
854 }
855 if has("nextest") {
856 return exit == Some(4) && lower.contains("no tests to run");
858 }
859 false
860}
861
862#[must_use]
865pub fn verify_written(root: &Path) -> Vec<speccoder_core::InitRun> {
866 use speccoder_core::verify::CheckStatus;
867 let Ok((runner, _)) = crate::sandbox::runner_at(root) else {
868 return Vec::new();
869 };
870 let Ok(report) =
871 crate::verify::run_checks(root, Some(crate::verify::config::Tier::Fast), &runner)
872 else {
873 return Vec::new();
874 };
875 report
876 .checks
877 .iter()
878 .map(|c| speccoder_core::InitRun {
879 name: c.name.clone(),
880 passed: matches!(c.status, CheckStatus::Passed | CheckStatus::Skipped),
881 status: if no_tests(
882 &c.argv,
883 c.exit_code,
884 &format!("{}\n{}", c.stdout_tail, c.stderr_tail),
885 ) {
886 "no_tests".to_owned()
887 } else {
888 serde_json::to_value(c.status)
889 .ok()
890 .and_then(|v| v.as_str().map(str::to_owned))
891 .unwrap_or_default()
892 },
893 duration_ms: c.duration_ms,
894 reason: (!matches!(c.status, CheckStatus::Passed | CheckStatus::Skipped))
895 .then(|| {
896 let said = |t: &str| {
897 t.lines()
898 .rev()
899 .map(str::trim)
900 .find(|l| !l.is_empty())
901 .map(str::to_owned)
902 };
903 said(&c.stderr_tail)
904 .or_else(|| said(&c.stdout_tail))
905 .or_else(|| c.note.clone())
906 .unwrap_or_else(|| {
907 format!(
908 "exit {}",
909 c.exit_code
910 .map_or_else(|| "?".to_owned(), |e| e.to_string())
911 )
912 })
913 })
914 .map(|r| r.chars().take(200).collect()),
915 })
916 .collect()
917}
918
919#[must_use]
921pub fn init(
922 path: &Path,
923 provider: Option<&str>,
924 model: Option<&str>,
925 region: Option<&str>,
926 force: bool,
927) -> CommandResult {
928 init_with(path, provider, model, region, force, None, &crate::aws::var)
929}
930
931#[derive(Debug, Clone)]
934pub struct Prepared {
935 pub written: CommandResult,
937 pub report: speccoder_core::InitReport,
939 pub root: PathBuf,
941 pub to_commit: Vec<String>,
944 pub failed: Vec<String>,
946}
947
948pub const COMMITTABLE: &[&str] = &[
950 FILE,
951 ".config/nextest.toml",
952 ".gitignore",
953 "Cargo.lock",
954 "package-lock.json",
955 "pnpm-lock.yaml",
956 "yarn.lock",
957 "uv.lock",
958 "poetry.lock",
959 "go.sum",
960];
961
962pub fn prepare(
969 path: &Path,
970 provider: Option<&str>,
971 model: Option<&str>,
972 region: Option<&str>,
973 force: bool,
974 no_verify: bool,
975) -> Result<Prepared, Box<CommandResult>> {
976 let written = init(path, provider, model, region, force);
977 let Some(CommandData::Init(report)) = written.data() else {
978 return Err(Box::new(written));
979 };
980 let mut report = (**report).clone();
981 let root = PathBuf::from(&report.path)
982 .parent()
983 .map(Path::to_path_buf)
984 .unwrap_or_default();
985 if !no_verify && !report.checks.is_empty() {
986 report.ran = verify_written(&root);
987 }
988 let failed = report
989 .ran
990 .iter()
991 .filter(|r| !r.passed && r.status != "no_tests")
992 .map(|r| r.name.clone())
993 .collect();
994 let mut to_commit: Vec<String> = report.wrote.clone();
995 let profile = ".config/nextest.toml";
996 if report
997 .checks
998 .iter()
999 .any(|c| c.argv.iter().any(|a| a == "nextest"))
1000 && root.join(profile).exists()
1001 && !to_commit.iter().any(|p| p == profile)
1002 && Git::at(&root)
1003 .line(&["status", "--porcelain", "--", profile])
1004 .is_ok_and(|l| !l.trim().is_empty())
1005 {
1006 to_commit.push(profile.to_owned());
1007 }
1008 for lock in crate::worktree::LOCKFILES {
1011 if root.join(lock).exists()
1012 && !to_commit.iter().any(|p| p == lock)
1013 && Git::at(&root)
1014 .line(&["status", "--porcelain", "--", lock])
1015 .is_ok_and(|l| l.starts_with("??"))
1016 {
1017 to_commit.push((*lock).to_owned());
1018 }
1019 }
1020 Ok(Prepared {
1021 written,
1022 report,
1023 root,
1024 to_commit,
1025 failed,
1026 })
1027}
1028
1029pub fn commit_written(root: &Path, paths: &[String]) -> Result<String, String> {
1036 commit_written_as(root, paths, "speccoder: config")
1037}
1038
1039pub fn commit_written_as(root: &Path, paths: &[String], subject: &str) -> Result<String, String> {
1045 if paths.is_empty() {
1046 return Err("nothing to commit".to_owned());
1047 }
1048 if let Some(p) = paths.iter().find(|p| !COMMITTABLE.contains(&p.as_str())) {
1049 return Err(format!("`{p}` is not a file init commits"));
1050 }
1051 let g = Git::at(root);
1052 let names: Vec<&str> = paths.iter().map(String::as_str).collect();
1053 let mut add = vec!["add", "--"];
1054 add.extend(&names);
1055 let mut commit = vec!["commit", "-q", "-m", subject, "--"];
1056 commit.extend(&names);
1057 g.run(&add).map_err(|e| e.0)?;
1058 let mut unchanged = vec!["diff", "--cached", "--quiet", "--"];
1060 unchanged.extend(&names);
1061 if g.succeeds(&unchanged).unwrap_or(false) {
1062 return Err(format!(
1063 "nothing to commit: {} is committed as it is",
1064 speccoder_core::words::listed(&names)
1065 ));
1066 }
1067 g.run(&commit)
1068 .and_then(|_| g.line(&["rev-parse", "--short", "HEAD"]))
1069 .map_err(|e| {
1070 if e.0.trim().is_empty() {
1071 "git commit failed without saying why".to_owned()
1072 } else {
1073 e.0
1074 }
1075 })
1076}
1077
1078#[must_use]
1081pub fn finish(p: Prepared) -> CommandResult {
1082 let Prepared {
1083 written,
1084 report,
1085 to_commit,
1086 failed,
1087 ..
1088 } = p;
1089 let mut message = match &report.committed {
1090 Some(id) => written.message().replace(
1091 "; review it, then commit it",
1092 &format!(" and committed it ({id})"),
1093 ),
1094 None => written.message().to_owned(),
1095 };
1096 if !failed.is_empty() {
1097 message = format!(
1098 "{message}; the check(s) {} fail on the untouched code: every task would be judged against a red baseline",
1099 failed.join(", ")
1100 );
1101 }
1102 let step = |command: String, why: &str| speccoder_core::next::NextStep {
1103 command,
1104 why: why.to_owned(),
1105 };
1106 let mut next = Vec::new();
1107 let root = PathBuf::from(&report.path)
1110 .parent()
1111 .map(Path::to_path_buf)
1112 .unwrap_or_default();
1113 let format = crate::format::at(&root);
1114 if format.detect(&root).is_none() {
1115 let (command, why) = format.messages().make_project;
1116 message = format!("{message}; there is no spec project here yet");
1117 next.push(step(command.to_owned(), why));
1118 }
1119 if report.committed.is_none() {
1120 let listed = to_commit.join(" ");
1121 next.push(step(
1122 format!("git add {listed} && git commit -m \"speccoder: config\" -- {listed}"),
1123 "speccoder reads committed files only",
1124 ));
1125 }
1126 if !report.key.set && report.model.starts_with("bedrock/") {
1127 next.push(step(
1128 format!("export {}=…", report.key.variable),
1129 "a Bedrock API key — or run aws login where you start speccoder",
1130 ));
1131 } else if !report.key.set {
1132 next.push(step(
1133 format!("export {}=…", report.key.variable),
1134 "the model key, from the environment only",
1135 ));
1136 }
1137 let features = match crate::current::list(&root, None).data() {
1139 Some(CommandData::Features(f)) => f.features.len(),
1140 _ => 0,
1141 };
1142 if features == 0 {
1143 next.push(step(
1144 "speccoder spec specify \"…\"".to_owned(),
1145 "describe the first feature; its spec, plan and tasks follow",
1146 ));
1147 } else {
1148 next.push(step(
1149 "speccoder run".to_owned(),
1150 "work through the ready tasks",
1151 ));
1152 }
1153 CommandResult::new("init", CommandStatus::Ok, &message)
1154 .with_data(CommandData::Init(Box::new(report)))
1155 .with_next(next)
1156}
1157
1158#[derive(Debug, Clone, Serialize)]
1160pub struct Preview {
1161 pub configured: bool,
1163 pub checks: Vec<Proposed>,
1165 pub allow: Vec<Vec<String>>,
1167 pub formatter: Option<Vec<String>>,
1169 pub keys: Vec<(String, bool)>,
1171 pub bedrock: BedrockPreview,
1173 pub include: Vec<String>,
1175}
1176
1177#[derive(Debug, Clone, Default, Serialize)]
1180pub struct BedrockPreview {
1181 pub source: Option<String>,
1183 pub region: Option<String>,
1185}
1186
1187#[must_use]
1189pub fn root_of(path: &Path) -> PathBuf {
1190 match crate::inspect(path, None).data() {
1191 Some(CommandData::Inspect(s)) => PathBuf::from(&s.root),
1192 _ => path.to_path_buf(),
1193 }
1194}
1195
1196#[must_use]
1198pub fn preview(path: &Path) -> Preview {
1199 let root = root_of(path);
1200 let found = detect(&root);
1201 let set = |v: &str| std::env::var_os(v).is_some_and(|x| !x.is_empty());
1202 Preview {
1203 configured: root.join(FILE).is_file(),
1204 checks: propose(&found),
1205 allow: allow(&found),
1206 formatter: formatter(&found),
1207 keys: ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"]
1208 .iter()
1209 .map(|v| ((*v).to_owned(), set(v)))
1210 .collect(),
1211 bedrock: BedrockPreview {
1212 source: crate::aws::detect_here().map(|s| s.describe()),
1213 region: crate::aws::region_here().map(|(r, _)| r),
1214 },
1215 include: found.include,
1216 }
1217}
1218
1219#[cfg(test)]
1220mod tests {
1221 use super::*;
1222
1223 #[test]
1224 fn a_uv_project_runs_its_checks_through_uv_never_an_uncommitted_venv() {
1225 let d = tempfile::tempdir().unwrap();
1226 std::fs::write(d.path().join("pyproject.toml"), "[project]\nname = \"p\"\n").unwrap();
1227 std::fs::write(d.path().join("uv.lock"), "version = 1\n").unwrap();
1228 std::fs::create_dir_all(d.path().join(".venv/bin")).unwrap();
1229 std::fs::write(d.path().join(".venv/bin/python"), "").unwrap();
1230 let found = detect(d.path());
1231 assert_eq!(
1232 found.python_run,
1233 ["uv", "run", "--locked", "--offline", "python"]
1234 );
1235 let test = &propose(&found)[0];
1236 assert_eq!(
1237 test.argv.join(" "),
1238 "uv run --locked --offline python -m pytest -q --junitxml=.speccoder/junit.xml"
1239 );
1240 std::fs::remove_file(d.path().join("uv.lock")).unwrap();
1242 assert_eq!(detect(d.path()).python_run, [".venv/bin/python"]);
1243 }
1244
1245 #[test]
1246 fn proposals_follow_what_was_found() {
1247 let rust = propose(&Found {
1248 cargo: true,
1249 nextest: true,
1250 ..Found::default()
1251 });
1252 let names: Vec<&str> = rust.iter().map(|c| c.name.as_str()).collect();
1253 assert_eq!(names, ["test", "fmt", "clippy"]);
1254 assert_eq!(
1255 rust[0].junit.as_deref(),
1256 Some("target/nextest/speccoder/junit.xml")
1257 );
1258 assert_eq!(rust[2].tier, "full");
1259 let plain = propose(&Found {
1260 cargo: true,
1261 ..Found::default()
1262 });
1263 assert_eq!(plain[0].argv, ["cargo", "test", "--workspace"]);
1264
1265 let node = propose(&Found {
1266 node_manager: Some("pnpm".to_owned()),
1267 npm_scripts: vec!["test".into(), "lint".into(), "build".into()],
1268 ..Found::default()
1269 });
1270 let shown: Vec<(String, String)> = node
1271 .iter()
1272 .map(|c| (c.name.clone(), c.argv.join(" ")))
1273 .collect();
1274 assert_eq!(
1275 shown,
1276 [
1277 ("test".into(), "pnpm run test".into()),
1278 ("lint".into(), "pnpm run lint".into())
1279 ]
1280 );
1281 let npm = propose(&Found {
1282 node_manager: Some("npm".to_owned()),
1283 npm_scripts: vec!["test".into()],
1284 ..Found::default()
1285 });
1286 assert_eq!(npm[0].argv, ["npm", "run", "test"]);
1287
1288 let py = propose(&Found {
1289 python: true,
1290 ruff: true,
1291 ..Found::default()
1292 });
1293 assert_eq!(
1294 py.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
1295 ["test", "ruff"]
1296 );
1297 let go = propose(&Found {
1298 go: true,
1299 ..Found::default()
1300 });
1301 assert_eq!(go[0].argv, ["go", "test", "./..."]);
1302 let make = propose(&Found {
1303 make_test: true,
1304 ..Found::default()
1305 });
1306 assert_eq!(make[0].argv, ["make", "test"]);
1307 assert!(propose(&Found::default()).is_empty());
1308 }
1309
1310 #[test]
1311 fn the_model_follows_the_key_that_is_set() {
1312 let none = |_: &str| None;
1313 let openai = |v: &str| (v == "OPENAI_API_KEY").then(|| "k".to_owned());
1314 assert_eq!(model_choice(None, None, &none).0, "anthropic");
1315 assert_eq!(
1316 model_choice(None, None, &openai),
1317 ("openai".to_owned(), "gpt-5.4-mini".to_owned())
1318 );
1319 assert_eq!(
1320 model_choice(Some("anthropic"), Some("m"), &openai),
1321 ("anthropic".to_owned(), "m".to_owned())
1322 );
1323 }
1324
1325 #[test]
1326 fn every_rendered_file_parses() {
1327 for found in [
1328 Found {
1329 cargo: true,
1330 nextest: true,
1331 ..Found::default()
1332 },
1333 Found {
1334 python: true,
1335 ruff: true,
1336 mypy: true,
1337 go: true,
1338 ..Found::default()
1339 },
1340 Found::default(),
1341 ] {
1342 let text = render(
1343 &propose(&found),
1344 &allow(&found),
1345 formatter(&found).as_deref(),
1346 "openai",
1347 "gpt-5.4-mini",
1348 None,
1349 );
1350 if found.cargo {
1351 assert!(
1352 text.contains("[format]\nargv = [\"cargo\", \"fmt\", \"--all\"]"),
1353 "{text}"
1354 );
1355 assert_eq!(
1356 crate::substrate::run_config::parse(&text)
1357 .ok()
1358 .and_then(|c| c.format),
1359 Some(vec![
1360 "cargo".to_owned(),
1361 "fmt".to_owned(),
1362 "--all".to_owned()
1363 ])
1364 );
1365 }
1366 let checks =
1367 crate::verify::config::parse(&text).unwrap_or_else(|e| panic!("{e}\n{text}"));
1368 assert_eq!(checks.len(), propose(&found).len());
1369 assert!(crate::substrate::model_config::parse(&text).is_ok_and(|m| m.is_some()));
1370 assert!(crate::substrate::run_config::parse(&text).is_ok());
1371 }
1372 }
1373
1374 #[test]
1375 fn an_empty_suite_on_a_fresh_scaffold_is_no_tests_yet() {
1376 let argv = |a: &[&str]| a.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
1377 assert!(no_tests(
1378 &argv(&["uv", "run", "pytest"]),
1379 Some(5),
1380 "no tests ran"
1381 ));
1382 assert!(!no_tests(
1383 &argv(&["uv", "run", "pytest"]),
1384 Some(1),
1385 "1 failed"
1386 ));
1387 assert!(no_tests(
1388 &argv(&["go", "test", "./..."]),
1389 Some(0),
1390 "go: warning: \"./...\" matched no packages\n"
1391 ));
1392 assert!(no_tests(
1393 &argv(&["go", "test", "./..."]),
1394 Some(0),
1395 "? \tx\t[no test files]\n"
1396 ));
1397 assert!(!no_tests(
1398 &argv(&["go", "test", "./..."]),
1399 Some(0),
1400 "ok \tx\t0.1s\n"
1401 ));
1402 assert!(no_tests(
1403 &argv(&["npm", "test"]),
1404 Some(0),
1405 "No test files found, exiting with code 0"
1406 ));
1407 assert!(no_tests(
1408 &argv(&["npx", "vitest", "run"]),
1409 Some(0),
1410 "No test files found"
1411 ));
1412 assert!(no_tests(
1413 &argv(&["cargo", "nextest", "run"]),
1414 Some(4),
1415 "error: no tests to run"
1416 ));
1417 assert!(!no_tests(
1418 &argv(&["cargo", "test"]),
1419 Some(0),
1420 "test result: ok. 1 passed"
1421 ));
1422 }
1423}