Skip to main content

speccoder_runtime/
layout.rs

1//! The project's test layout, detected by code: the runners of
2//! the checkout, each runner's collection rule as configured, where tests
3//! live today, the naming habit, and where speccoder puts a story's
4//! acceptance file. A fact handed to the implementer and every test author,
5//! never a judge input; undeterminable parts are listed as unknown, never
6//! guessed. Same checkout, same bytes.
7
8use std::collections::BTreeMap;
9use std::path::Path;
10
11use serde::Serialize;
12use speccoder_core::collection::{
13    CollectionRule, JsRunner, Toolchain, defines_tests, go_rule, rust_reachable, rust_rule,
14    rust_targets, strip_comments, toolchain_of,
15};
16
17use crate::collection::static_cfg;
18
19/// Where tests live today.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
21pub struct Location {
22    /// `inline_modules`, `tests_dir`, `beside_sources`, `package`.
23    pub kind: String,
24    /// The directory (or `*` for inline modules across the sources).
25    pub path: String,
26    /// How many test files.
27    pub files: usize,
28}
29
30/// One runner's layout.
31#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
32pub struct RunnerLayout {
33    /// The toolchain.
34    pub toolchain: Toolchain,
35    /// The member or package root (`""` at the checkout's root).
36    pub root: String,
37    /// Its collection rule as configured.
38    pub rule: CollectionRule,
39    /// Where tests live today.
40    pub locations: Vec<Location>,
41    /// Test files present that nothing runs.
42    pub not_run: Vec<String>,
43    /// The project's naming habit.
44    pub naming: Option<String>,
45    /// Where speccoder puts story files; `None`: no place the runner collects.
46    pub story_dir: Option<String>,
47    /// The file extension story files take (JS/TS: the project's majority).
48    pub extension: String,
49    /// What could not be determined.
50    pub unknown: Vec<String>,
51}
52
53/// The checkout's test layout.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
55pub struct TestLayout {
56    /// Every runner found, in toolchain order.
57    pub runners: Vec<RunnerLayout>,
58    /// SHA-256 of the runners' canonical JSON.
59    pub digest: String,
60    /// How the project starts pytest: a check's words up to `pytest`
61    /// (`uv run python -m pytest`), else `python3 -m pytest`.
62    #[serde(skip)]
63    pub pytest: Vec<String>,
64}
65
66fn parent(p: &str) -> &str {
67    p.rsplit_once('/').map_or("", |(d, _)| d)
68}
69
70fn at(root: &str, rel: &str) -> String {
71    if root.is_empty() {
72        rel.to_owned()
73    } else {
74        format!("{root}/{rel}")
75    }
76}
77
78/// Detects the layout of the checkout at `root`; `check_argvs` are the
79/// checks' commands (they name the runners).
80#[must_use]
81pub fn detect(root: &Path, check_argvs: &[Vec<String>]) -> TestLayout {
82    let files = static_cfg::files(root);
83    let read = |p: &str| std::fs::read_to_string(root.join(p)).ok();
84    let tests_in = |pred: &dyn Fn(&str) -> bool| -> Vec<&String> {
85        files
86            .iter()
87            .filter(|f| pred(f))
88            .filter(|f| {
89                toolchain_of(f).is_some_and(|t| read(f).is_some_and(|s| defines_tests(t, &s)))
90            })
91            .collect()
92    };
93    let mut runners = Vec::new();
94
95    for pkg in static_cfg::rust_packages(root, &files) {
96        let targets = rust_targets(&pkg, &files);
97        let reach = rust_reachable(&targets, &|p| read(p));
98        let inside = |f: &str| {
99            f.ends_with(".rs")
100                && static_cfg::owner(std::slice::from_ref(&pkg), f).is_some()
101                && !f.starts_with(&at(&pkg.root, "target/"))
102        };
103        let tests_dir = at(&pkg.root, "tests");
104        let inline = tests_in(&|f| {
105            inside(f)
106                && !f.starts_with(&format!("{tests_dir}/"))
107                && read(f).is_some_and(|s| strip_comments(&s).contains("#[cfg(test)]"))
108        });
109        let top = tests_in(&|f| {
110            inside(f)
111                && f.strip_prefix(&format!("{tests_dir}/"))
112                    .is_some_and(|r| !r.contains('/'))
113        });
114        let not_run: Vec<String> =
115            tests_in(&|f| inside(f) && f.starts_with(&format!("{tests_dir}/")))
116                .into_iter()
117                .filter(|f| !reach.contains_key(*f))
118                .cloned()
119                .collect();
120        let mut locations = vec![
121            Location {
122                kind: "inline_modules".to_owned(),
123                path: at(&pkg.root, "src"),
124                files: inline.len(),
125            },
126            Location {
127                kind: "tests_dir".to_owned(),
128                path: format!("{tests_dir}/*.rs"),
129                files: top.len(),
130            },
131        ];
132        let mains = files
133            .iter()
134            .filter(|f| {
135                f.strip_prefix(&format!("{tests_dir}/"))
136                    .is_some_and(|r| r.matches('/').count() == 1 && r.ends_with("/main.rs"))
137            })
138            .count();
139        if mains > 0 {
140            locations.push(Location {
141                kind: "tests_dir".to_owned(),
142                path: format!("{tests_dir}/<dir>/main.rs"),
143                files: mains,
144            });
145        }
146        let mut unknown = Vec::new();
147        let story_dir = if pkg.autotests {
148            Some(tests_dir.clone())
149        } else {
150            unknown.push(format!(
151                "{}: `autotests = false` — a new integration test needs a `[[test]]` entry, which speccoder does not add",
152                at(&pkg.root, "Cargo.toml")
153            ));
154            None
155        };
156        runners.push(RunnerLayout {
157            toolchain: Toolchain::Rust,
158            root: pkg.root.clone(),
159            rule: rust_rule(&pkg),
160            locations,
161            not_run,
162            naming: Some(format!("{tests_dir}/<area>.rs")),
163            story_dir,
164            extension: "rs".to_owned(),
165            unknown,
166        });
167    }
168
169    if static_cfg::uses_pytest(root, &files, check_argvs) {
170        let rule = static_cfg::pytest_rule(root);
171        let py = tests_in(&|f| f.ends_with(".py"));
172        let mut by_dir: BTreeMap<String, usize> = BTreeMap::new();
173        for f in &py {
174            *by_dir.entry(parent(f).to_owned()).or_default() += 1;
175        }
176        let exists = |d: &str| d.is_empty() || root.join(d).is_dir();
177        let mut unknown = Vec::new();
178        let story_dir = match rule.testpaths.first() {
179            Some(t) if exists(t.trim_end_matches('/')) => Some(t.trim_end_matches('/').to_owned()),
180            Some(t) => {
181                unknown.push(format!(
182                    "testpaths names `{t}`, which does not exist: no place pytest collects"
183                ));
184                None
185            }
186            None if exists("tests") => Some("tests".to_owned()),
187            None => Some(String::new()),
188        };
189        let prefix = py
190            .iter()
191            .filter(|f| f.rsplit('/').next().is_some_and(|n| n.starts_with("test_")))
192            .count();
193        runners.push(RunnerLayout {
194            toolchain: Toolchain::Python,
195            root: String::new(),
196            rule: rule.rule(),
197            locations: by_dir
198                .into_iter()
199                .map(|(path, files)| Location {
200                    kind: "tests_dir".to_owned(),
201                    path,
202                    files,
203                })
204                .collect(),
205            not_run: py
206                .iter()
207                .filter(|f| rule.breaks(f).is_some())
208                .map(|f| (*f).clone())
209                .collect(),
210            naming: Some(if prefix * 2 >= py.len() {
211                "test_<name>.py".to_owned()
212            } else {
213                "<name>_test.py".to_owned()
214            }),
215            story_dir,
216            extension: "py".to_owned(),
217            unknown,
218        });
219    }
220
221    for pkg in static_cfg::js_packages(root, &files, check_argvs) {
222        let inside = |f: &str| pkg.root.is_empty() || f.starts_with(&format!("{}/", pkg.root));
223        let js = tests_in(&|f| inside(f) && toolchain_of(f) == Some(Toolchain::JavaScript));
224        let rel = |f: &str| {
225            if pkg.root.is_empty() {
226                f.to_owned()
227            } else {
228                f.trim_start_matches(&format!("{}/", pkg.root)).to_owned()
229            }
230        };
231        let collected: Vec<&String> = js
232            .iter()
233            .copied()
234            .filter(|f| {
235                pkg.rule
236                    .as_ref()
237                    .map_or(true, |r| r.breaks(&rel(f)).is_none())
238            })
239            .collect();
240        let mut by_dir: BTreeMap<String, usize> = BTreeMap::new();
241        for f in &collected {
242            *by_dir.entry(parent(f).to_owned()).or_default() += 1;
243        }
244        let ts = collected.iter().filter(|f| f.contains(".ts")).count();
245        let extension = if collected.is_empty() {
246            if files.iter().any(|f| inside(f) && f.ends_with(".ts")) {
247                "ts"
248            } else {
249                "js"
250            }
251        } else if ts * 2 >= collected.len() {
252            "ts"
253        } else {
254            "js"
255        }
256        .to_owned();
257        let habit = by_dir
258            .iter()
259            .max_by_key(|(_, n)| **n)
260            .map(|(d, _)| d.clone());
261        let src = at(&pkg.root, "src");
262        let story_dir = habit.clone().or_else(|| {
263            Some(if root.join(&src).is_dir() {
264                src.clone()
265            } else {
266                pkg.root.clone()
267            })
268        });
269        let mut unknown = Vec::new();
270        let rule = match &pkg.rule {
271            Ok(r) => r.rule(),
272            Err(why) => {
273                unknown.push(why.clone());
274                CollectionRule {
275                    toolchain: Toolchain::JavaScript,
276                    text: format!(
277                        "{} collects the files its configuration includes (not read: {why})",
278                        pkg.runner.name()
279                    ),
280                    source: at(&pkg.root, "package.json"),
281                }
282            }
283        };
284        runners.push(RunnerLayout {
285            toolchain: Toolchain::JavaScript,
286            root: pkg.root.clone(),
287            rule,
288            locations: by_dir
289                .into_iter()
290                .map(|(path, files)| Location {
291                    kind: if path.contains("__tests__") {
292                        "tests_dir"
293                    } else {
294                        "beside_sources"
295                    }
296                    .to_owned(),
297                    path,
298                    files,
299                })
300                .collect(),
301            not_run: js
302                .iter()
303                .filter(|f| !collected.contains(f))
304                .map(|f| (*f).clone())
305                .collect(),
306            naming: Some(match pkg.runner {
307                JsRunner::Vitest | JsRunner::Jest => format!("<name>.test.{extension}"),
308            }),
309            story_dir,
310            extension,
311            unknown,
312        });
313    }
314
315    for m in static_cfg::go_modules(root, &files) {
316        let inside = |f: &str| m.root.is_empty() || f.starts_with(&format!("{}/", m.root));
317        let go = tests_in(&|f| inside(f) && f.ends_with("_test.go"));
318        let mut by_dir: BTreeMap<String, usize> = BTreeMap::new();
319        for f in &go {
320            *by_dir.entry(parent(f).to_owned()).or_default() += 1;
321        }
322        let tags = static_cfg::go_tags(check_argvs);
323        runners.push(RunnerLayout {
324            toolchain: Toolchain::Go,
325            root: m.root.clone(),
326            rule: go_rule(),
327            locations: by_dir
328                .into_iter()
329                .map(|(path, files)| Location {
330                    kind: "package".to_owned(),
331                    path,
332                    files,
333                })
334                .collect(),
335            not_run: go
336                .iter()
337                .filter(|f| {
338                    speccoder_core::collection::go_breaks(f, &read(f).unwrap_or_default(), &tags)
339                        .is_some()
340                })
341                .map(|f| (*f).clone())
342                .collect(),
343            naming: Some("<name>_test.go beside the package's sources".to_owned()),
344            story_dir: Some(m.root.clone()),
345            extension: "go".to_owned(),
346            unknown: Vec::new(),
347        });
348    }
349
350    let canonical = serde_json::to_string(&runners).unwrap_or_default();
351    TestLayout {
352        digest: crate::integrity::sha256_hex(canonical.as_bytes()),
353        runners,
354        pytest: pytest_command(check_argvs),
355    }
356}
357
358/// The first check that runs pytest, cut after its `pytest` word (its own
359/// flags and selection dropped); `python3 -m pytest` when none does.
360fn pytest_command(check_argvs: &[Vec<String>]) -> Vec<String> {
361    check_argvs
362        .iter()
363        .find_map(|a| {
364            let at = a
365                .iter()
366                .position(|w| w == "pytest" || w.ends_with("/pytest"))?;
367            Some(a[..=at].to_vec())
368        })
369        .unwrap_or_else(|| ["python3", "-m", "pytest"].map(str::to_owned).to_vec())
370}
371
372/// The layout's text for the project at `root`, its checks read from its
373/// `speccoder.toml`.
374#[must_use]
375pub fn text_at(root: &Path) -> String {
376    detect(root, &crate::verify::check_argvs(root)).text()
377}
378
379impl TestLayout {
380    /// The runner speccoder's acceptance tests go to: the first with a
381    /// collected place, else the first at all.
382    #[must_use]
383    pub fn primary(&self) -> Option<&RunnerLayout> {
384        self.runners
385            .iter()
386            .find(|r| r.story_dir.is_some())
387            .or_else(|| self.runners.first())
388    }
389
390    /// The story file for `story` (`US1`) — for Go, in `package` (a
391    /// directory). `None`: no place the runner collects.
392    #[must_use]
393    pub fn story_file(&self, story: &str, package: Option<&str>) -> Option<String> {
394        let r = self.primary()?;
395        let dir = r.story_dir.as_ref()?;
396        let s = story.to_ascii_lowercase();
397        Some(match r.toolchain {
398            Toolchain::Rust => at(dir, &format!("acceptance_{s}.rs")),
399            Toolchain::Python => at(dir, &format!("test_acceptance_{s}.py")),
400            Toolchain::JavaScript => at(dir, &format!("acceptance-{s}.test.{}", r.extension)),
401            Toolchain::Go => at(package.unwrap_or(dir), &format!("acceptance_{s}_test.go")),
402        })
403    }
404
405    /// The command that runs only `file`, for the author's prompt.
406    #[must_use]
407    pub fn command_for(&self, file: &str) -> Option<String> {
408        let r = self.primary()?;
409        let stem = file.rsplit('/').next()?.split('.').next()?.to_owned();
410        Some(match r.toolchain {
411            Toolchain::Rust => format!("cargo test --test {stem}"),
412            Toolchain::Python => format!("{} {file}", self.pytest.join(" ")),
413            Toolchain::JavaScript => format!("npx vitest run {file}"),
414            Toolchain::Go => format!("go test ./{}", parent(file)),
415        })
416    }
417
418    /// Whether `argv` is the command that runs only one of `files` — the
419    /// one the author's prompt names, which an exact `[commands] allow`
420    /// (`cargo test`) would otherwise refuse.
421    #[must_use]
422    pub fn runs_only(&self, argv: &[String], files: &[&str]) -> bool {
423        files.iter().any(|f| {
424            self.command_for(f)
425                .is_some_and(|c| c.split_whitespace().eq(argv.iter().map(String::as_str)))
426        })
427    }
428
429    /// The part a model reads (contracts/prompts.md).
430    #[must_use]
431    pub fn text(&self) -> String {
432        let mut out = String::from("# Test layout (detected by speccoder from this checkout)\n");
433        if self.runners.is_empty() {
434            out.push_str("\nNo test runner speccoder knows (Cargo, pytest, vitest/jest, go test) was found.\n");
435        }
436        for r in &self.runners {
437            let name = match r.toolchain {
438                Toolchain::Rust => "cargo (Rust)",
439                Toolchain::Python => "pytest (Python)",
440                Toolchain::JavaScript => "vitest/jest (JavaScript/TypeScript)",
441                Toolchain::Go => "go test (Go)",
442            };
443            out.push_str(&format!(
444                "\nRunner: {name}{}\nRule: {} — from {}\n",
445                if r.root.is_empty() {
446                    String::new()
447                } else {
448                    format!(", in `{}`", r.root)
449                },
450                r.rule.text,
451                r.rule.source
452            ));
453            let today: Vec<String> = r
454                .locations
455                .iter()
456                .map(|l| match l.kind.as_str() {
457                    "inline_modules" => format!(
458                        "inline `#[cfg(test)]` modules in {} file(s) under {}",
459                        l.files, l.path
460                    ),
461                    _ => format!("{}: {} file(s)", l.path, l.files),
462                })
463                .collect();
464            if !today.is_empty() {
465                out.push_str(&format!("Tests today: {}\n", today.join("; ")));
466            }
467            if !r.not_run.is_empty() {
468                out.push_str(&format!("Not run by anything: {}\n", r.not_run.join(", ")));
469            }
470            if let Some(n) = &r.naming {
471                out.push_str(&format!("Naming: {n}\n"));
472            }
473            for u in &r.unknown {
474                out.push_str(&format!("Not determined: {u}\n"));
475            }
476        }
477        out.push_str(
478            "\nPut new tests where the runner collects them. A path the task names that the runner would not\ncollect is a mistake in the plan — use the nearest collected place and say so in your report.\nA test file that never runs fails the verdict.\n",
479        );
480        out
481    }
482}
483
484#[cfg(test)]
485mod tests {
486    use super::*;
487
488    fn write(root: &Path, files: &[(&str, &str)]) {
489        for (p, t) in files {
490            let f = root.join(p);
491            std::fs::create_dir_all(f.parent().unwrap_or(root)).ok();
492            std::fs::write(f, t).ok();
493        }
494    }
495
496    #[test]
497    fn a_rust_crate_s_layout_names_its_rule_its_tests_and_its_dead_files() {
498        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
499        write(
500            d.path(),
501            &[
502                (
503                    "Cargo.toml",
504                    "[package]\nname = \"greet\"\nversion = \"0.1.0\"\n",
505                ),
506                (
507                    "src/lib.rs",
508                    "pub fn greet() {}\n#[cfg(test)]\nmod tests { #[test] fn t() {} }\n",
509                ),
510                ("tests/unit/greet_name.rs", "#[test]\nfn a() {}\n"),
511            ],
512        );
513        let l = detect(d.path(), &[]);
514        assert_eq!(
515            l.story_file("US1", None).as_deref(),
516            Some("tests/acceptance_us1.rs")
517        );
518        assert_eq!(
519            l.command_for("tests/acceptance_us1.rs").as_deref(),
520            Some("cargo test --test acceptance_us1")
521        );
522        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
523        let file = ["tests/acceptance_us1.rs"];
524        assert!(l.runs_only(&argv("cargo test --test acceptance_us1"), &file));
525        assert!(!l.runs_only(&argv("cargo test --test acceptance_us2"), &file));
526        assert!(!l.runs_only(&argv("cargo test"), &file));
527        let text = l.text();
528        assert!(text.contains("Rule: Cargo builds `tests/*.rs`"), "{text}");
529        assert!(
530            text.contains("inline `#[cfg(test)]` modules in 1 file(s)"),
531            "{text}"
532        );
533        assert!(
534            text.contains("Not run by anything: tests/unit/greet_name.rs"),
535            "{text}"
536        );
537        // Same checkout, same bytes.
538        assert_eq!(detect(d.path(), &[]), l);
539    }
540
541    #[test]
542    fn a_python_acceptance_file_runs_with_the_project_s_pytest() {
543        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
544        write(
545            d.path(),
546            &[
547                ("pytest.ini", "[pytest]\n"),
548                ("tests/test_a.py", "def test_a(): pass\n"),
549            ],
550        );
551        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
552        let file = "tests/test_acceptance_us1.py";
553        let uv = detect(
554            d.path(),
555            &[argv(
556                "uv run --locked --offline python -m pytest -q --junitxml=.speccoder/junit.xml",
557            )],
558        );
559        assert_eq!(
560            uv.command_for(file).as_deref(),
561            Some("uv run --locked --offline python -m pytest tests/test_acceptance_us1.py")
562        );
563        assert!(uv.runs_only(
564            &argv("uv run --locked --offline python -m pytest tests/test_acceptance_us1.py"),
565            &[file]
566        ));
567        assert!(!uv.runs_only(
568            &argv("python3 -m pytest tests/test_acceptance_us1.py"),
569            &[file]
570        ));
571        assert_eq!(
572            detect(d.path(), &[argv(".venv/bin/pytest -q")])
573                .command_for(file)
574                .as_deref(),
575            Some(".venv/bin/pytest tests/test_acceptance_us1.py")
576        );
577        assert_eq!(
578            detect(d.path(), &[]).command_for(file).as_deref(),
579            Some("python3 -m pytest tests/test_acceptance_us1.py")
580        );
581    }
582
583    #[test]
584    fn no_collected_place_is_said_never_guessed() {
585        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
586        write(
587            d.path(),
588            &[
589                (
590                    "Cargo.toml",
591                    "[package]\nname = \"g\"\nversion = \"0.1.0\"\nautotests = false\n",
592                ),
593                ("src/lib.rs", ""),
594            ],
595        );
596        let l = detect(d.path(), &[]);
597        assert_eq!(l.story_file("US1", None), None);
598        assert!(l.runners[0].unknown[0].contains("autotests = false"));
599        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
600        write(d.path(), &[("pytest.ini", "[pytest]\ntestpaths = spec\n")]);
601        assert_eq!(detect(d.path(), &[]).story_file("US1", None), None);
602    }
603
604    #[test]
605    fn python_js_and_go_story_files_follow_the_layout() {
606        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
607        write(
608            d.path(),
609            &[
610                ("pytest.ini", "[pytest]\n"),
611                ("tests/test_a.py", "def test_a():\n    pass\n"),
612            ],
613        );
614        assert_eq!(
615            detect(d.path(), &[]).story_file("US2", None).as_deref(),
616            Some("tests/test_acceptance_us2.py")
617        );
618        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
619        write(
620            d.path(),
621            &[
622                (
623                    "package.json",
624                    "{ \"devDependencies\": { \"vitest\": \"3\" } }",
625                ),
626                ("src/a.test.ts", "it('a', () => {})\n"),
627            ],
628        );
629        assert_eq!(
630            detect(d.path(), &[]).story_file("US1", None).as_deref(),
631            Some("src/acceptance-us1.test.ts")
632        );
633        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
634        write(
635            d.path(),
636            &[("go.mod", "module ex.com/m\n"), ("g/g.go", "package g\n")],
637        );
638        assert_eq!(
639            detect(d.path(), &[])
640                .story_file("US1", Some("g"))
641                .as_deref(),
642            Some("g/acceptance_us1_test.go")
643        );
644    }
645}