speccoder-runtime 0.9.6

Application services of speccoder: the only crate that executes anything.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
//! The project's test layout, detected by code: the runners of
//! the checkout, each runner's collection rule as configured, where tests
//! live today, the naming habit, and where speccoder puts a task's
//! acceptance file. A fact handed to the implementer and every test author,
//! never a judge input; undeterminable parts are listed as unknown, never
//! guessed. Same checkout, same bytes.

use std::collections::BTreeMap;
use std::path::Path;

use serde::Serialize;
use speccoder_core::collection::{
    CollectionRule, JsRunner, Toolchain, defines_tests, go_rule, rust_reachable, rust_rule,
    rust_targets, strip_comments, toolchain_of,
};

use crate::collection::static_cfg;

/// Where tests live today.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Location {
    /// `inline_modules`, `tests_dir`, `beside_sources`, `package`.
    pub kind: String,
    /// The directory (or `*` for inline modules across the sources).
    pub path: String,
    /// How many test files.
    pub files: usize,
}

/// One runner's layout.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RunnerLayout {
    /// The toolchain.
    pub toolchain: Toolchain,
    /// The member or package root (`""` at the checkout's root).
    pub root: String,
    /// Its collection rule as configured.
    pub rule: CollectionRule,
    /// Where tests live today.
    pub locations: Vec<Location>,
    /// Test files present that nothing runs.
    pub not_run: Vec<String>,
    /// The project's naming habit.
    pub naming: Option<String>,
    /// Where speccoder puts acceptance files; `None`: no place the runner collects.
    pub story_dir: Option<String>,
    /// The file extension acceptance files take (JS/TS: the project's majority).
    pub extension: String,
    /// What could not be determined.
    pub unknown: Vec<String>,
}

/// The checkout's test layout.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TestLayout {
    /// Every runner found, in toolchain order.
    pub runners: Vec<RunnerLayout>,
    /// SHA-256 of the runners' canonical JSON.
    pub digest: String,
    /// How the project starts pytest: a check's words up to `pytest`
    /// (`uv run python -m pytest`), else `python3 -m pytest`.
    #[serde(skip)]
    pub pytest: Vec<String>,
}

fn parent(p: &str) -> &str {
    p.rsplit_once('/').map_or("", |(d, _)| d)
}

fn at(root: &str, rel: &str) -> String {
    if root.is_empty() {
        rel.to_owned()
    } else {
        format!("{root}/{rel}")
    }
}

/// Detects the layout of the checkout at `root`; `check_argvs` are the
/// checks' commands (they name the runners).
#[must_use]
pub fn detect(root: &Path, check_argvs: &[Vec<String>]) -> TestLayout {
    let files = static_cfg::files(root);
    let read = |p: &str| std::fs::read_to_string(root.join(p)).ok();
    let tests_in = |pred: &dyn Fn(&str) -> bool| -> Vec<&String> {
        files
            .iter()
            .filter(|f| pred(f))
            .filter(|f| {
                toolchain_of(f).is_some_and(|t| read(f).is_some_and(|s| defines_tests(t, &s)))
            })
            .collect()
    };
    let mut runners = Vec::new();

    for pkg in static_cfg::rust_packages(root, &files) {
        let targets = rust_targets(&pkg, &files);
        let reach = rust_reachable(&targets, &|p| read(p));
        let inside = |f: &str| {
            f.ends_with(".rs")
                && static_cfg::owner(std::slice::from_ref(&pkg), f).is_some()
                && !f.starts_with(&at(&pkg.root, "target/"))
        };
        let tests_dir = at(&pkg.root, "tests");
        let inline = tests_in(&|f| {
            inside(f)
                && !f.starts_with(&format!("{tests_dir}/"))
                && read(f).is_some_and(|s| strip_comments(&s).contains("#[cfg(test)]"))
        });
        let top = tests_in(&|f| {
            inside(f)
                && f.strip_prefix(&format!("{tests_dir}/"))
                    .is_some_and(|r| !r.contains('/'))
        });
        let not_run: Vec<String> =
            tests_in(&|f| inside(f) && f.starts_with(&format!("{tests_dir}/")))
                .into_iter()
                .filter(|f| !reach.contains_key(*f))
                .cloned()
                .collect();
        let mut locations = vec![
            Location {
                kind: "inline_modules".to_owned(),
                path: at(&pkg.root, "src"),
                files: inline.len(),
            },
            Location {
                kind: "tests_dir".to_owned(),
                path: format!("{tests_dir}/*.rs"),
                files: top.len(),
            },
        ];
        let mains = files
            .iter()
            .filter(|f| {
                f.strip_prefix(&format!("{tests_dir}/"))
                    .is_some_and(|r| r.matches('/').count() == 1 && r.ends_with("/main.rs"))
            })
            .count();
        if mains > 0 {
            locations.push(Location {
                kind: "tests_dir".to_owned(),
                path: format!("{tests_dir}/<dir>/main.rs"),
                files: mains,
            });
        }
        let mut unknown = Vec::new();
        let story_dir = if pkg.autotests {
            Some(tests_dir.clone())
        } else {
            unknown.push(format!(
                "{}: `autotests = false` — a new integration test needs a `[[test]]` entry, which speccoder does not add",
                at(&pkg.root, "Cargo.toml")
            ));
            None
        };
        runners.push(RunnerLayout {
            toolchain: Toolchain::Rust,
            root: pkg.root.clone(),
            rule: rust_rule(&pkg),
            locations,
            not_run,
            naming: Some(format!("{tests_dir}/<area>.rs")),
            story_dir,
            extension: "rs".to_owned(),
            unknown,
        });
    }

    if static_cfg::uses_pytest(root, &files, check_argvs) {
        let rule = static_cfg::pytest_rule(root);
        let py = tests_in(&|f| f.ends_with(".py"));
        let mut by_dir: BTreeMap<String, usize> = BTreeMap::new();
        for f in &py {
            *by_dir.entry(parent(f).to_owned()).or_default() += 1;
        }
        let exists = |d: &str| d.is_empty() || root.join(d).is_dir();
        let mut unknown = Vec::new();
        let story_dir = match rule.testpaths.first() {
            Some(t) if exists(t.trim_end_matches('/')) => Some(t.trim_end_matches('/').to_owned()),
            Some(t) => {
                unknown.push(format!(
                    "testpaths names `{t}`, which does not exist: no place pytest collects"
                ));
                None
            }
            None if exists("tests") => Some("tests".to_owned()),
            None => Some(String::new()),
        };
        let prefix = py
            .iter()
            .filter(|f| f.rsplit('/').next().is_some_and(|n| n.starts_with("test_")))
            .count();
        runners.push(RunnerLayout {
            toolchain: Toolchain::Python,
            root: String::new(),
            rule: rule.rule(),
            locations: by_dir
                .into_iter()
                .map(|(path, files)| Location {
                    kind: "tests_dir".to_owned(),
                    path,
                    files,
                })
                .collect(),
            not_run: py
                .iter()
                .filter(|f| rule.breaks(f).is_some())
                .map(|f| (*f).clone())
                .collect(),
            naming: Some(if prefix * 2 >= py.len() {
                "test_<name>.py".to_owned()
            } else {
                "<name>_test.py".to_owned()
            }),
            story_dir,
            extension: "py".to_owned(),
            unknown,
        });
    }

    for pkg in static_cfg::js_packages(root, &files, check_argvs) {
        let inside = |f: &str| pkg.root.is_empty() || f.starts_with(&format!("{}/", pkg.root));
        let js = tests_in(&|f| inside(f) && toolchain_of(f) == Some(Toolchain::JavaScript));
        let rel = |f: &str| {
            if pkg.root.is_empty() {
                f.to_owned()
            } else {
                f.trim_start_matches(&format!("{}/", pkg.root)).to_owned()
            }
        };
        let collected: Vec<&String> = js
            .iter()
            .copied()
            .filter(|f| {
                pkg.rule
                    .as_ref()
                    .map_or(true, |r| r.breaks(&rel(f)).is_none())
            })
            .collect();
        let mut by_dir: BTreeMap<String, usize> = BTreeMap::new();
        for f in &collected {
            *by_dir.entry(parent(f).to_owned()).or_default() += 1;
        }
        let ts = collected.iter().filter(|f| f.contains(".ts")).count();
        let extension = if collected.is_empty() {
            if files.iter().any(|f| inside(f) && f.ends_with(".ts")) {
                "ts"
            } else {
                "js"
            }
        } else if ts * 2 >= collected.len() {
            "ts"
        } else {
            "js"
        }
        .to_owned();
        let habit = by_dir
            .iter()
            .max_by_key(|(_, n)| **n)
            .map(|(d, _)| d.clone());
        let src = at(&pkg.root, "src");
        let story_dir = habit.clone().or_else(|| {
            Some(if root.join(&src).is_dir() {
                src.clone()
            } else {
                pkg.root.clone()
            })
        });
        let mut unknown = Vec::new();
        let rule = match &pkg.rule {
            Ok(r) => r.rule(),
            Err(why) => {
                unknown.push(why.clone());
                CollectionRule {
                    toolchain: Toolchain::JavaScript,
                    text: format!(
                        "{} collects the files its configuration includes (not read: {why})",
                        pkg.runner.name()
                    ),
                    source: at(&pkg.root, "package.json"),
                }
            }
        };
        runners.push(RunnerLayout {
            toolchain: Toolchain::JavaScript,
            root: pkg.root.clone(),
            rule,
            locations: by_dir
                .into_iter()
                .map(|(path, files)| Location {
                    kind: if path.contains("__tests__") {
                        "tests_dir"
                    } else {
                        "beside_sources"
                    }
                    .to_owned(),
                    path,
                    files,
                })
                .collect(),
            not_run: js
                .iter()
                .filter(|f| !collected.contains(f))
                .map(|f| (*f).clone())
                .collect(),
            naming: Some(match pkg.runner {
                JsRunner::Vitest | JsRunner::Jest => format!("<name>.test.{extension}"),
            }),
            story_dir,
            extension,
            unknown,
        });
    }

    for m in static_cfg::go_modules(root, &files) {
        let inside = |f: &str| m.root.is_empty() || f.starts_with(&format!("{}/", m.root));
        let go = tests_in(&|f| inside(f) && f.ends_with("_test.go"));
        let mut by_dir: BTreeMap<String, usize> = BTreeMap::new();
        for f in &go {
            *by_dir.entry(parent(f).to_owned()).or_default() += 1;
        }
        let tags = static_cfg::go_tags(check_argvs);
        runners.push(RunnerLayout {
            toolchain: Toolchain::Go,
            root: m.root.clone(),
            rule: go_rule(),
            locations: by_dir
                .into_iter()
                .map(|(path, files)| Location {
                    kind: "package".to_owned(),
                    path,
                    files,
                })
                .collect(),
            not_run: go
                .iter()
                .filter(|f| {
                    speccoder_core::collection::go_breaks(f, &read(f).unwrap_or_default(), &tags)
                        .is_some()
                })
                .map(|f| (*f).clone())
                .collect(),
            naming: Some("<name>_test.go beside the package's sources".to_owned()),
            story_dir: Some(m.root.clone()),
            extension: "go".to_owned(),
            unknown: Vec::new(),
        });
    }

    let canonical = serde_json::to_string(&runners).unwrap_or_default();
    TestLayout {
        digest: crate::integrity::sha256_hex(canonical.as_bytes()),
        runners,
        pytest: pytest_command(check_argvs),
    }
}

/// The first check that runs pytest, cut after its `pytest` word (its own
/// flags and selection dropped); `python3 -m pytest` when none does.
fn pytest_command(check_argvs: &[Vec<String>]) -> Vec<String> {
    check_argvs
        .iter()
        .find_map(|a| {
            let at = a
                .iter()
                .position(|w| w == "pytest" || w.ends_with("/pytest"))?;
            Some(a[..=at].to_vec())
        })
        .unwrap_or_else(|| ["python3", "-m", "pytest"].map(str::to_owned).to_vec())
}

/// The layout's text for the project at `root`, its checks read from its
/// `speccoder.toml`.
#[must_use]
pub fn text_at(root: &Path) -> String {
    detect(root, &crate::verify::check_argvs(root)).text()
}

impl TestLayout {
    /// The runner speccoder's acceptance tests go to: the first with a
    /// collected place, else the first at all.
    #[must_use]
    pub fn primary(&self) -> Option<&RunnerLayout> {
        self.runners
            .iter()
            .find(|r| r.story_dir.is_some())
            .or_else(|| self.runners.first())
    }

    /// The acceptance file named after `name` (a task, `T005`) — for Go, in
    /// `package` (a directory). `None`: no place the runner collects.
    #[must_use]
    pub fn acceptance_file(&self, name: &str, package: Option<&str>) -> Option<String> {
        let r = self.primary()?;
        let dir = r.story_dir.as_ref()?;
        let s = name.to_ascii_lowercase();
        Some(match r.toolchain {
            Toolchain::Rust => at(dir, &format!("acceptance_{s}.rs")),
            Toolchain::Python => at(dir, &format!("test_acceptance_{s}.py")),
            Toolchain::JavaScript => at(dir, &format!("acceptance-{s}.test.{}", r.extension)),
            Toolchain::Go => at(package.unwrap_or(dir), &format!("acceptance_{s}_test.go")),
        })
    }

    /// The command that runs only `file`, for the author's prompt.
    #[must_use]
    pub fn command_for(&self, file: &str) -> Option<String> {
        let r = self.primary()?;
        let stem = file.rsplit('/').next()?.split('.').next()?.to_owned();
        Some(match r.toolchain {
            Toolchain::Rust => format!("cargo test --test {stem}"),
            Toolchain::Python => format!("{} {file}", self.pytest.join(" ")),
            Toolchain::JavaScript => format!("npx vitest run {file}"),
            Toolchain::Go => format!("go test ./{}", parent(file)),
        })
    }

    /// Whether `argv` is the command that runs only one of `files` — the
    /// one the author's prompt names, which an exact `[commands] allow`
    /// (`cargo test`) would otherwise refuse.
    #[must_use]
    pub fn runs_only(&self, argv: &[String], files: &[&str]) -> bool {
        files.iter().any(|f| {
            self.command_for(f)
                .is_some_and(|c| c.split_whitespace().eq(argv.iter().map(String::as_str)))
        })
    }

    /// The part a model reads (contracts/prompts.md).
    #[must_use]
    pub fn text(&self) -> String {
        let mut out = String::from("# Test layout (detected by speccoder from this checkout)\n");
        if self.runners.is_empty() {
            out.push_str("\nNo test runner speccoder knows (Cargo, pytest, vitest/jest, go test) was found.\n");
        }
        for r in &self.runners {
            let name = match r.toolchain {
                Toolchain::Rust => "cargo (Rust)",
                Toolchain::Python => "pytest (Python)",
                Toolchain::JavaScript => "vitest/jest (JavaScript/TypeScript)",
                Toolchain::Go => "go test (Go)",
            };
            out.push_str(&format!(
                "\nRunner: {name}{}\nRule: {} — from {}\n",
                if r.root.is_empty() {
                    String::new()
                } else {
                    format!(", in `{}`", r.root)
                },
                r.rule.text,
                r.rule.source
            ));
            let today: Vec<String> = r
                .locations
                .iter()
                .map(|l| match l.kind.as_str() {
                    "inline_modules" => format!(
                        "inline `#[cfg(test)]` modules in {} file(s) under {}",
                        l.files, l.path
                    ),
                    _ => format!("{}: {} file(s)", l.path, l.files),
                })
                .collect();
            if !today.is_empty() {
                out.push_str(&format!("Tests today: {}\n", today.join("; ")));
            }
            if !r.not_run.is_empty() {
                out.push_str(&format!("Not run by anything: {}\n", r.not_run.join(", ")));
            }
            if let Some(n) = &r.naming {
                out.push_str(&format!("Naming: {n}\n"));
            }
            for u in &r.unknown {
                out.push_str(&format!("Not determined: {u}\n"));
            }
        }
        out.push_str(
            "\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",
        );
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn write(root: &Path, files: &[(&str, &str)]) {
        for (p, t) in files {
            let f = root.join(p);
            std::fs::create_dir_all(f.parent().unwrap_or(root)).ok();
            std::fs::write(f, t).ok();
        }
    }

    #[test]
    fn a_rust_crate_s_layout_names_its_rule_its_tests_and_its_dead_files() {
        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
        write(
            d.path(),
            &[
                (
                    "Cargo.toml",
                    "[package]\nname = \"greet\"\nversion = \"0.1.0\"\n",
                ),
                (
                    "src/lib.rs",
                    "pub fn greet() {}\n#[cfg(test)]\nmod tests { #[test] fn t() {} }\n",
                ),
                ("tests/unit/greet_name.rs", "#[test]\nfn a() {}\n"),
            ],
        );
        let l = detect(d.path(), &[]);
        assert_eq!(
            l.acceptance_file("US1", None).as_deref(),
            Some("tests/acceptance_us1.rs")
        );
        assert_eq!(
            l.command_for("tests/acceptance_us1.rs").as_deref(),
            Some("cargo test --test acceptance_us1")
        );
        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
        let file = ["tests/acceptance_us1.rs"];
        assert!(l.runs_only(&argv("cargo test --test acceptance_us1"), &file));
        assert!(!l.runs_only(&argv("cargo test --test acceptance_us2"), &file));
        assert!(!l.runs_only(&argv("cargo test"), &file));
        let text = l.text();
        assert!(text.contains("Rule: Cargo builds `tests/*.rs`"), "{text}");
        assert!(
            text.contains("inline `#[cfg(test)]` modules in 1 file(s)"),
            "{text}"
        );
        assert!(
            text.contains("Not run by anything: tests/unit/greet_name.rs"),
            "{text}"
        );
        // Same checkout, same bytes.
        assert_eq!(detect(d.path(), &[]), l);
    }

    #[test]
    fn a_python_acceptance_file_runs_with_the_project_s_pytest() {
        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
        write(
            d.path(),
            &[
                ("pytest.ini", "[pytest]\n"),
                ("tests/test_a.py", "def test_a(): pass\n"),
            ],
        );
        let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
        let file = "tests/test_acceptance_us1.py";
        let uv = detect(
            d.path(),
            &[argv(
                "uv run --locked --offline python -m pytest -q --junitxml=.speccoder/junit.xml",
            )],
        );
        assert_eq!(
            uv.command_for(file).as_deref(),
            Some("uv run --locked --offline python -m pytest tests/test_acceptance_us1.py")
        );
        assert!(uv.runs_only(
            &argv("uv run --locked --offline python -m pytest tests/test_acceptance_us1.py"),
            &[file]
        ));
        assert!(!uv.runs_only(
            &argv("python3 -m pytest tests/test_acceptance_us1.py"),
            &[file]
        ));
        assert_eq!(
            detect(d.path(), &[argv(".venv/bin/pytest -q")])
                .command_for(file)
                .as_deref(),
            Some(".venv/bin/pytest tests/test_acceptance_us1.py")
        );
        assert_eq!(
            detect(d.path(), &[]).command_for(file).as_deref(),
            Some("python3 -m pytest tests/test_acceptance_us1.py")
        );
    }

    #[test]
    fn no_collected_place_is_said_never_guessed() {
        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
        write(
            d.path(),
            &[
                (
                    "Cargo.toml",
                    "[package]\nname = \"g\"\nversion = \"0.1.0\"\nautotests = false\n",
                ),
                ("src/lib.rs", ""),
            ],
        );
        let l = detect(d.path(), &[]);
        assert_eq!(l.acceptance_file("US1", None), None);
        assert!(l.runners[0].unknown[0].contains("autotests = false"));
        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
        write(d.path(), &[("pytest.ini", "[pytest]\ntestpaths = spec\n")]);
        assert_eq!(detect(d.path(), &[]).acceptance_file("US1", None), None);
    }

    #[test]
    fn python_js_and_go_acceptance_files_follow_the_layout() {
        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
        write(
            d.path(),
            &[
                ("pytest.ini", "[pytest]\n"),
                ("tests/test_a.py", "def test_a():\n    pass\n"),
            ],
        );
        assert_eq!(
            detect(d.path(), &[])
                .acceptance_file("US2", None)
                .as_deref(),
            Some("tests/test_acceptance_us2.py")
        );
        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
        write(
            d.path(),
            &[
                (
                    "package.json",
                    "{ \"devDependencies\": { \"vitest\": \"3\" } }",
                ),
                ("src/a.test.ts", "it('a', () => {})\n"),
            ],
        );
        assert_eq!(
            detect(d.path(), &[])
                .acceptance_file("US1", None)
                .as_deref(),
            Some("src/acceptance-us1.test.ts")
        );
        let d = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
        write(
            d.path(),
            &[("go.mod", "module ex.com/m\n"), ("g/g.go", "package g\n")],
        );
        assert_eq!(
            detect(d.path(), &[])
                .acceptance_file("US1", Some("g"))
                .as_deref(),
            Some("g/acceptance_us1_test.go")
        );
    }
}

/// A command the project declares: what a person runs, and the words a
/// test that runs it names (the command, `-m` its module, its binary): an
/// import of the module behind it runs no command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Command {
    /// As a person types it: `md2csv`, `python -m pkg`.
    pub shown: String,
    /// Any of these in a test's text means it runs the command.
    pub runs: Vec<String>,
}

impl Command {
    /// Whether `test` runs this command.
    #[must_use]
    pub fn run_by(&self, test: &str) -> bool {
        self.runs.iter().any(|w| test.contains(w.as_str()))
    }
}

/// The commands `root` declares: `[project.scripts]` and a package's
/// `__main__.py` (Python), a Cargo binary, a `package.json` `bin`.
#[must_use]
pub fn commands(root: &Path) -> Vec<Command> {
    let read = |p: &str| std::fs::read_to_string(root.join(p)).ok();
    let quoted = |w: &str| vec![format!("\"{w}\""), format!("'{w}'")];
    let mut out = Vec::new();
    if let Some(t) = read("pyproject.toml").and_then(|t| t.parse::<toml::Table>().ok()) {
        let scripts = t
            .get("project")
            .and_then(|p| p.get("scripts"))
            .and_then(toml::Value::as_table);
        for (name, target) in scripts.into_iter().flatten() {
            let module = target
                .as_str()
                .and_then(|s| s.split(':').next())
                .unwrap_or_default();
            let top = module.split('.').next().unwrap_or_default();
            let mut runs = quoted(name);
            if !top.is_empty() {
                runs.extend([
                    format!("-m {top}"),
                    format!("\"{top}\""),
                    format!("'{top}'"),
                ]);
            }
            out.push(Command {
                shown: name.clone(),
                runs,
            });
        }
    }
    for base in ["src", "."] {
        let Ok(dirs) = std::fs::read_dir(root.join(base)) else {
            continue;
        };
        for d in dirs.flatten() {
            let pkg = d.file_name().to_string_lossy().into_owned();
            if d.path().join("__main__.py").is_file()
                && !out.iter().any(|c| c.runs.contains(&format!("\"{pkg}\"")))
            {
                let mut runs = quoted(&pkg);
                runs.push(format!("-m {pkg}"));
                out.push(Command {
                    shown: format!("python -m {pkg}"),
                    runs,
                });
            }
        }
    }
    if let Some(t) = read("Cargo.toml").and_then(|t| t.parse::<toml::Table>().ok()) {
        let mut bins: Vec<String> = t
            .get("bin")
            .and_then(toml::Value::as_array)
            .into_iter()
            .flatten()
            .filter_map(|b| {
                b.get("name")
                    .and_then(toml::Value::as_str)
                    .map(str::to_owned)
            })
            .collect();
        if root.join("src/main.rs").is_file()
            && let Some(name) = t
                .get("package")
                .and_then(|p| p.get("name"))
                .and_then(toml::Value::as_str)
        {
            bins.push(name.to_owned());
        }
        for name in bins {
            let env = format!("CARGO_BIN_EXE_{name}");
            out.push(Command {
                shown: name.clone(),
                runs: vec![
                    env,
                    format!("cargo_bin(\"{name}\")"),
                    "\"cargo\", \"run\"".to_owned(),
                    "cargo run".to_owned(),
                ],
            });
        }
    }
    if let Some(v) =
        read("package.json").and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
    {
        let name = v["name"]
            .as_str()
            .unwrap_or_default()
            .rsplit('/')
            .next()
            .unwrap_or_default()
            .to_owned();
        let bins: Vec<(String, String)> = match &v["bin"] {
            serde_json::Value::String(path) => vec![(name, path.clone())],
            serde_json::Value::Object(m) => m
                .iter()
                .filter_map(|(k, p)| p.as_str().map(|p| (k.clone(), p.to_owned())))
                .collect(),
            _ => Vec::new(),
        };
        for (name, path) in bins {
            let path = path.trim_start_matches("./").to_owned();
            let mut runs = quoted(&name);
            runs.push(path.clone());
            runs.push(path.rsplit('/').next().unwrap_or(&path).to_owned());
            out.push(Command { shown: name, runs });
        }
    }
    out
}

/// The manifests a stack is planned in, by the language each says.
pub const STACKS: &[(&str, &str)] = &[
    ("Cargo.toml", "Rust"),
    ("pyproject.toml", "Python"),
    ("package.json", "JavaScript/TypeScript"),
    ("go.mod", "Go"),
    ("pom.xml", "Java"),
];

/// The checkout's stack, as planning is told it: its manifests and the
/// checks that test it — so a plan is made in it, never invented. No
/// manifest: `None`, the plan chooses.
#[must_use]
pub fn stack_text(root: &Path) -> Option<String> {
    let found: Vec<String> = STACKS
        .iter()
        .filter(|(m, _)| root.join(m).is_file())
        .map(|(m, lang)| format!("- {lang}: `{m}`"))
        .collect();
    if found.is_empty() {
        return None;
    }
    let checks: Vec<String> = crate::verify::check_argvs(root)
        .iter()
        .map(|a| format!("- check: `{}`", a.join(" ")))
        .collect();
    Some(format!(
        "# The project as it is (read by speccoder from this checkout)\n\nPlan in this stack — its language, its manifest, its test runner — never another:\n\n{}\n",
        [found, checks].concat().join("\n")
    ))
}

/// Whether a story's *Independent Test* (its line in the story's text) or
/// a scenario's *When* (what the person does) is about a command line, by
/// whole words: the interface is then the project's command, never an
/// internal module.
#[must_use]
pub fn via_command(story: &str) -> bool {
    story.lines().any(|l| {
        if l.contains("Independent Test") {
            command_words(l)
        } else {
            // The action alone: what is given, or follows, is no interface.
            l.split_once("**When**").is_some_and(|(_, when)| {
                command_words(when.split("**Then**").next().unwrap_or(when))
            })
        }
    })
}

/// Whether a task's tests run the project's command: its title, or a
/// scenario it cites, is about a command line.
#[must_use]
pub fn task_via_command<'a>(title: &str, mut scenarios: impl Iterator<Item = &'a str>) -> bool {
    command_words(title) || scenarios.any(via_command)
}

fn command_words(text: &str) -> bool {
    let line = text.to_ascii_lowercase();
    let words: Vec<&str> = line.split(|c: char| !c.is_alphanumeric()).collect();
    let pair = |a: &str, b: &str| words.windows(2).any(|p| p[0] == a && p[1] == b);
    ["command", "cli", "stdin", "stdout", "stderr", "terminal"]
        .iter()
        .any(|w| words.contains(w))
        || pair("standard", "input")
        || pair("standard", "output")
        || pair("exit", "code")
        || pair("exit", "status")
}

#[cfg(test)]
mod command_tests {
    use super::{commands, stack_text, task_via_command, via_command};

    /// The example's plan (2026-11-03) left its language open in a uv
    /// project and its tasks then built a Rust crate.
    #[test]
    fn planning_is_told_the_checkout_s_stack() {
        let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
        assert_eq!(stack_text(dir.path()), None);
        std::fs::write(
            dir.path().join("pyproject.toml"),
            "[project]\nname = \"m\"\n",
        )
        .unwrap_or_else(|e| panic!("{e}"));
        let t = stack_text(dir.path()).unwrap_or_default();
        assert!(
            t.contains("- Python: `pyproject.toml`") && t.contains("never another"),
            "{t}"
        );
    }

    /// The sample's project (2026-11-02): its oracle tests imported
    /// `src.services…`, never the command its stories name.
    #[test]
    fn a_project_s_commands_and_what_runs_them() {
        let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
        let r = dir.path();
        let write = |p: &str, t: &str| {
            std::fs::create_dir_all(r.join(p).parent().unwrap_or(r))
                .unwrap_or_else(|e| panic!("{e}"));
            std::fs::write(r.join(p), t).unwrap_or_else(|e| panic!("{e}"));
        };
        write(
            "pyproject.toml",
            "[project]\nname = \"speccoder-poc\"\n\n[project.scripts]\nspeccoder-poc = \"speccoder_poc:main\"\n",
        );
        write(
            "src/speccoder_poc/__main__.py",
            "from . import main\nmain()\n",
        );
        let c = commands(r);
        assert_eq!(
            c.iter().map(|c| c.shown.as_str()).collect::<Vec<_>>(),
            ["speccoder-poc"]
        );
        assert!(
            c[0].run_by("subprocess.run([sys.executable, \"-m\", \"speccoder_poc\"], input=t)")
        );
        assert!(c[0].run_by("subprocess.run([\"speccoder-poc\", \"in.md\"])"));
        // In-process, the installed command's own errors never show.
        assert!(!c[0].run_by("from speccoder_poc import main\nmain([\"in.md\"])"));
        assert!(!c[0].run_by("from speccoder_poc.cli import CLI\nCLI.run(content=t)"));
        assert!(!c[0].run_by("from src.services.table_parser import parse_markdown_table"));

        let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
        let r = dir.path();
        std::fs::create_dir_all(r.join("src")).unwrap_or_else(|e| panic!("{e}"));
        std::fs::write(r.join("Cargo.toml"), "[package]\nname = \"md2csv\"\n")
            .unwrap_or_else(|e| panic!("{e}"));
        std::fs::write(r.join("src/main.rs"), "fn main() {}\n").unwrap_or_else(|e| panic!("{e}"));
        std::fs::write(
            r.join("package.json"),
            "{\"name\": \"@x/tables\", \"bin\": {\"tables\": \"./bin/tables.js\"}}",
        )
        .unwrap_or_else(|e| panic!("{e}"));
        let c = commands(r);
        assert_eq!(
            c.iter().map(|c| c.shown.as_str()).collect::<Vec<_>>(),
            ["md2csv", "tables"]
        );
        assert!(c[0].run_by("Command::new(env!(\"CARGO_BIN_EXE_md2csv\"))"));
        assert!(c[1].run_by("execFileSync('node', ['bin/tables.js'])"));
        assert!(!c[0].run_by("use md2csv::parse;"));

        assert!(via_command(
            "**Independent Test**: Can be tested by piping a valid Markdown table into the command"
        ));
        assert!(!via_command(
            "**Independent Test**: Can be tested by calling parse() with a table"
        ));
        // Whole words of that line only: a client, a recommendation, the
        // scenarios' words are no command line.
        assert!(!via_command(
            "**Independent Test**: the client follows the recommended flow"
        ));
        assert!(!via_command("1. **Given** the command, **Then** CSV"));
        // What the person does: the sample's US3, whose Independent Test
        // names only the input.
        assert!(via_command(
            "**Independent Test**: providing invalid Markdown table input\n1. **Given** malformed input, **When** the user runs the command, **Then** the tool reports it"
        ));
        assert!(!via_command(
            "1. **Given** a table, **When** parse() is called, **Then** the command prints CSV"
        ));
        // The sample's T038 and T037: a gap in the CLI path, one in the parser.
        assert!(task_via_command(
            "Thread the parser through the CLI execution path",
            std::iter::empty()
        ));
        assert!(!task_via_command(
            "Update Markdown cell splitting so it preserves in-cell whitespace",
            std::iter::empty()
        ));
        assert!(task_via_command(
            "Escape pipes in cells",
            ["**Given** `a \\| b`, **When** the user runs the command, **Then** `a | b`"]
                .into_iter()
        ));
    }
}