speccoder-runtime 0.5.0

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
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
//! `speccoder init`: detect a project's checks and write
//! `speccoder.toml`.
//!
//! Detection looks only at the project root's manifests and lockfiles (and
//! whether `cargo nextest` is installed); it runs nothing of the project's.
//! What it finds becomes a commented file the person reviews and commits.
//! The result is parsed back with speccoder's own parsers before it is
//! written, so `init` never leaves a file `run` would refuse.

use std::path::{Path, PathBuf};

use serde::Serialize;
use speccoder_core::{CommandData, CommandResult, CommandStatus};

use crate::git::Git;
use crate::verify::config::FILE;

/// What `init` saw at the project root.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Found {
    /// `Cargo.toml` exists.
    pub cargo: bool,
    /// `cargo nextest` is installed.
    pub nextest: bool,
    /// `package.json`'s scripts, by name.
    pub npm_scripts: Vec<String>,
    /// `npm`, `pnpm`, `yarn` or `bun`, from the lockfile; `None` without `package.json`.
    pub node_manager: Option<String>,
    /// `pyproject.toml`, `setup.cfg`, `setup.py` or `pytest.ini` exists.
    pub python: bool,
    /// How checks start the project's Python: `uv run --locked --offline
    /// python` for a uv project (uv makes the environment in whichever tree
    /// the check runs in — a run's worktree has no `.venv/`, which is never
    /// committed), else a project-local virtualenv's interpreter, else
    /// `python3`.
    pub python_run: Vec<String>,
    /// pytest runs with that interpreter (or `python3`).
    pub pytest: bool,
    /// `[tool.ruff]` (or `ruff.toml`) is configured.
    pub ruff: bool,
    /// `[tool.mypy]` (or `mypy.ini`) is configured.
    pub mypy: bool,
    /// `go.mod` exists.
    pub go: bool,
    /// A `Makefile` with a `test:` target exists.
    pub make_test: bool,
    /// The checkout's git-ignored `.env` files: proposed for `[worktree]
    /// include`.
    pub include: Vec<String>,
    /// A `.worktreeinclude` exists: runs read it already.
    pub worktreeinclude: bool,
}

impl Found {
    /// How checks start the project's Python (`python3` when nothing more
    /// specific was found).
    #[must_use]
    pub fn python_command(&self) -> Vec<String> {
        if self.python_run.is_empty() {
            vec!["python3".to_owned()]
        } else {
            self.python_run.clone()
        }
    }
}

/// One check `init` proposes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Proposed {
    /// `[checks.<name>]`.
    pub name: String,
    /// The command.
    pub argv: Vec<String>,
    /// `fast` or `full`.
    pub tier: String,
    /// A JUnit report the check writes.
    pub junit: Option<String>,
    /// Why this check.
    pub why: String,
}

fn check(name: &str, argv: &[&str], tier: &str, junit: Option<&str>, why: &str) -> Proposed {
    Proposed {
        name: name.to_owned(),
        argv: argv.iter().map(|a| (*a).to_owned()).collect(),
        tier: tier.to_owned(),
        junit: junit.map(str::to_owned),
        why: why.to_owned(),
    }
}

/// The checks for what was found (pure: no IO).
#[must_use]
pub fn propose(found: &Found) -> Vec<Proposed> {
    let mut out = Vec::new();
    if found.cargo {
        out.push(if found.nextest {
            check(
                "test",
                // A new project has no tests yet: warn, do not fail the baseline.
                &[
                    "cargo",
                    "nextest",
                    "run",
                    "--workspace",
                    "--profile",
                    "speccoder",
                    "--no-tests=warn",
                ],
                "fast",
                Some("target/nextest/speccoder/junit.xml"),
                "Cargo.toml; cargo-nextest is installed (its JUnit report names every test)",
            )
        } else {
            check(
                "test",
                &["cargo", "test", "--workspace"],
                "fast",
                None,
                "Cargo.toml (install cargo-nextest for per-test results)",
            )
        });
        out.push(check(
            "fmt",
            &["cargo", "fmt", "--all", "--check"],
            "fast",
            None,
            "Cargo.toml",
        ));
        out.push(check(
            "clippy",
            &[
                "cargo",
                "clippy",
                "--workspace",
                "--all-targets",
                "--",
                "-D",
                "warnings",
            ],
            "full",
            None,
            "Cargo.toml",
        ));
    }
    if let Some(pm) = &found.node_manager {
        let has = |s: &str| found.npm_scripts.iter().any(|x| x == s);
        // `<pm> run <script>`: the allowed prefix is that one script.
        let run = |script: &str| -> Vec<String> { vec![pm.clone(), "run".into(), script.into()] };
        let mut add = |name: &str, script: &str, tier: &str| {
            out.push(Proposed {
                name: name.to_owned(),
                argv: run(script),
                tier: tier.to_owned(),
                junit: None,
                why: format!("package.json script `{script}` ({pm})"),
            });
        };
        if has("test") {
            add(
                if found.cargo { "node-test" } else { "test" },
                "test",
                "fast",
            );
        }
        if has("typecheck") {
            add("typecheck", "typecheck", "fast");
        }
        if has("lint") {
            add("lint", "lint", "full");
        }
    }
    if found.python {
        let name = if found.cargo || found.node_manager.is_some() {
            "pytest"
        } else {
            "test"
        };
        let run = found.python_command();
        let python = run.join(" ");
        let uv = run.first().is_some_and(|p| p == "uv");
        let why = if found.pytest {
            format!("a Python project (pytest, {python})")
        } else if uv {
            "a Python project — pytest is not a dependency: `uv add --dev pytest`".to_owned()
        } else {
            format!(
                "a Python project — pytest is not installed for {python}: `{python} -m pip install pytest`"
            )
        };
        let argv: Vec<&str> = run
            .iter()
            .map(String::as_str)
            .chain(["-m", "pytest", "-q", "--junitxml=.speccoder/junit.xml"])
            .collect();
        out.push(check(
            name,
            &argv,
            "fast",
            Some(".speccoder/junit.xml"),
            &why,
        ));
        if found.ruff {
            out.push(check(
                "ruff",
                &["ruff", "check", "."],
                "fast",
                None,
                "ruff is configured",
            ));
        }
        if found.mypy {
            out.push(check(
                "mypy",
                &["mypy", "."],
                "full",
                None,
                "mypy is configured",
            ));
        }
    }
    if found.go {
        let name = if out.iter().any(|c| c.name == "test") {
            "go-test"
        } else {
            "test"
        };
        out.push(check(
            name,
            &["go", "test", "./..."],
            "fast",
            None,
            "go.mod",
        ));
        out.push(check(
            "vet",
            &["go", "vet", "./..."],
            "full",
            None,
            "go.mod",
        ));
    }
    if out.is_empty() && found.make_test {
        out.push(check(
            "test",
            &["make", "test"],
            "fast",
            None,
            "a Makefile `test` target",
        ));
    }
    out
}

/// Commands the model (and the spec-derived acceptance tests) need besides
/// the checks: narrow prefixes per toolchain, written to `[commands] allow`.
#[must_use]
pub fn allow(found: &Found) -> Vec<Vec<String>> {
    let v = |a: &[&str]| a.iter().map(|x| (*x).to_owned()).collect::<Vec<String>>();
    let mut out = Vec::new();
    if found.cargo {
        out.extend([
            v(&["cargo", "test"]),
            v(&["cargo", "check"]),
            v(&["cargo", "build"]),
        ]);
    }
    if let Some(pm) = &found.node_manager {
        out.extend([v(&[pm, "test"]), v(&[pm, "run", "test"])]);
    }
    if found.python {
        let mut pytest = found.python_command();
        pytest.extend(["-m".to_owned(), "pytest".to_owned()]);
        out.push(pytest);
    }
    if found.go {
        out.extend([v(&["go", "test"]), v(&["go", "build"]), v(&["go", "vet"])]);
    }
    out
}

/// The formatter speccoder runs after each attempt, when the toolchain has one.
#[must_use]
pub fn formatter(found: &Found) -> Option<Vec<String>> {
    let v = |a: &[&str]| Some(a.iter().map(|x| (*x).to_owned()).collect());
    if found.cargo {
        v(&["cargo", "fmt", "--all"])
    } else if found.go {
        v(&["gofmt", "-w", "."])
    } else if found.python && found.ruff {
        v(&["ruff", "format", "."])
    } else {
        None
    }
}

/// Looks at `root` (and whether `cargo nextest` runs).
#[must_use]
pub fn detect(root: &Path) -> Found {
    let exists = |p: &str| root.join(p).exists();
    let read = |p: &str| std::fs::read_to_string(root.join(p)).unwrap_or_default();
    let cargo = exists("Cargo.toml");
    let nextest = cargo
        && std::process::Command::new("cargo")
            .args(["nextest", "--version"])
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|s| s.success());
    let (node_manager, npm_scripts) = if exists("package.json") {
        let manager = if exists("pnpm-lock.yaml") {
            "pnpm"
        } else if exists("yarn.lock") {
            "yarn"
        } else if exists("bun.lockb") || exists("bun.lock") {
            "bun"
        } else {
            "npm"
        };
        let scripts = serde_json::from_str::<serde_json::Value>(&read("package.json"))
            .ok()
            .and_then(|v| {
                v["scripts"]
                    .as_object()
                    .map(|o| o.keys().cloned().collect())
            })
            .unwrap_or_default();
        (Some(manager.to_owned()), scripts)
    } else {
        (None, Vec::new())
    };
    let pyproject = read("pyproject.toml");
    let makefile = read("Makefile");
    let python = ["pyproject.toml", "setup.cfg", "setup.py", "pytest.ini"]
        .iter()
        .any(|p| exists(p));
    // A uv project's environment is made by uv in the tree the check runs
    // in, from the committed lockfile and uv's cache; a plain virtualenv is
    // used by its interpreter's path.
    let words = |w: &[&str]| w.iter().map(|x| (*x).to_owned()).collect::<Vec<_>>();
    let python_run = if python && exists("uv.lock") {
        words(&["uv", "run", "--locked", "--offline", "python"])
    } else {
        [".venv/bin/python", "venv/bin/python"]
            .iter()
            .find(|p| python && exists(p))
            .map_or_else(|| words(&["python3"]), |p| words(&[p]))
    };
    Found {
        cargo,
        nextest,
        npm_scripts,
        node_manager,
        python,
        pytest: python && {
            let bin = python_run[0].as_str();
            std::process::Command::new(if root.join(bin).is_file() {
                root.join(bin)
            } else {
                bin.into()
            })
            .args(&python_run[1..])
            .args(["-m", "pytest", "--version"])
            .current_dir(root)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok_and(|s| s.success())
        },
        python_run,
        ruff: pyproject.contains("[tool.ruff") || exists("ruff.toml") || exists(".ruff.toml"),
        mypy: pyproject.contains("[tool.mypy") || exists("mypy.ini"),
        go: exists("go.mod"),
        make_test: makefile.lines().any(|l| l.starts_with("test:")),
        include: env_files(root),
        worktreeinclude: root.join(crate::include::FILE).is_file(),
    }
}

/// The checkout's git-ignored `.env` files (`.env`, `.env.local`, at any
/// depth): what checks often need and a worktree never has.
#[must_use]
pub fn env_files(root: &Path) -> Vec<String> {
    crate::include::matched(root, &[".env".to_owned(), ".env.*".to_owned()])
}

/// The comment over an `[worktree] include` proposal (what
/// [`activate_include`] finds).
const INCLUDE_PROPOSED: &str = "# the git-ignored .env files here; to copy them, uncomment:";

/// The `[worktree]` part of the file: the files `include` is proposed
/// with, commented; else both keys commented with their meaning.
fn worktree_section(include: &[String], worktreeinclude: bool) -> String {
    if worktreeinclude {
        return "\n# A run's worktree gets the git-ignored files .worktreeinclude names copied from this\n\
                # checkout (never committed, secret-named values masked); `include` adds patterns.\n\
                # [worktree]\n# prepare = \"auto\"           # \"off\": never install Node or uv dependencies\n\
                # include = [\".env\"]\n"
            .to_owned();
    }
    if include.is_empty() {
        return "\n# A run's worktree gets Node and uv dependencies by their locked, offline install\n\
                # before the baseline. `include` copies git-ignored files from this checkout.\n\
                # [worktree]\n# prepare = \"auto\"           # \"off\": never prepare\n\
                # include = [\".env\"]          # never committed, secret-named values masked\n"
            .to_owned();
    }
    format!(
        "\n# Git-ignored files a run's worktree gets copied from this checkout: their values are\n\
         # never committed, and secret-named values masked in what speccoder shows and journals.\n\
         {INCLUDE_PROPOSED}\n# [worktree]\n# include = [{}]\n",
        include
            .iter()
            .map(|l| quote(l))
            .collect::<Vec<_>>()
            .join(", ")
    )
}

/// Turns the commented `[worktree] include` proposal `init` wrote in
/// `root`'s configuration into the setting (a person confirmed it, or
/// `--yes`).
///
/// # Errors
///
/// No proposal in the file, or a file speccoder's parsers would refuse.
pub fn activate_include(root: &Path) -> Result<(), String> {
    let file = root.join(FILE);
    let text = std::fs::read_to_string(&file).map_err(|e| format!("{}: {e}", file.display()))?;
    let from = format!("{INCLUDE_PROPOSED}\n# [worktree]\n# include = ");
    let Some(at) = text.find(&from) else {
        return Err("no [worktree] include proposal in the configuration".to_owned());
    };
    let next = format!(
        "{}{}\n[worktree]\ninclude = {}",
        &text[..at],
        "# the git-ignored .env files here",
        &text[at + from.len()..]
    );
    crate::prepare::parse(&next)?;
    crate::verify::config::parse(&next)?;
    std::fs::write(&file, next).map_err(|e| format!("{}: {e}", file.display()))
}

/// A TOML basic string (JSON's escapes are valid TOML).
fn quote(s: &str) -> String {
    serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_owned())
}

/// The model `init` writes for Bedrock unless `--model` names another: a
/// Claude inference profile every commercial region offers.
pub const BEDROCK_MODEL: &str = "global.anthropic.claude-sonnet-5-5";

/// The provider and model `init` writes: the flag, else the provider whose
/// key variable is set (presence only — the value is never read), else
/// Bedrock when an AWS credential source is found, else Anthropic.
fn model_choice(
    provider: Option<&str>,
    model: Option<&str>,
    env: &dyn Fn(&str) -> Option<String>,
) -> (String, String) {
    let set = |v: &str| env(v).is_some_and(|x| !x.is_empty());
    let provider = provider.map_or_else(
        || {
            if set("ANTHROPIC_API_KEY") {
                "anthropic".to_owned()
            } else if set("OPENAI_API_KEY") {
                "openai".to_owned()
            } else if crate::aws::detect(env, &home(env)).is_some() {
                "bedrock".to_owned()
            } else {
                "anthropic".to_owned()
            }
        },
        str::to_owned,
    );
    let model = model.map_or_else(
        || match provider.as_str() {
            "openai" => "gpt-5.4-mini".to_owned(),
            "bedrock" => BEDROCK_MODEL.to_owned(),
            _ => "claude-sonnet-5-5".to_owned(),
        },
        str::to_owned,
    );
    (provider, model)
}

/// The home the AWS files are found under, as `env` names it.
fn home(env: &dyn Fn(&str) -> Option<String>) -> PathBuf {
    PathBuf::from(env("HOME").unwrap_or_default())
}

/// The file `init` writes.
#[must_use]
pub fn render(
    checks: &[Proposed],
    allow: &[Vec<String>],
    format: Option<&[String]>,
    provider: &str,
    model: &str,
    region: Option<&str>,
) -> String {
    let mut out = String::from(
        "# speccoder configuration — written by `speccoder init`; review it, then commit it\n\
         # (runs read the committed file in their worktree).\n\n\
         # Checks: speccoder runs them before and after every attempt and decides the\n\
         # verdict from them. `fast` runs per task; `full` at phase ends and `verify --tier full`.\n",
    );
    if checks.is_empty() {
        out.push_str(
            "# No checks were detected. Add at least one, e.g.:\n\
             # [checks.test]\n# argv = [\"make\", \"test\"]\n",
        );
    }
    for c in checks {
        out.push_str(&format!("\n# {}\n[checks.{}]\nargv = [", c.why, c.name));
        out.push_str(
            &c.argv
                .iter()
                .map(|a| quote(a))
                .collect::<Vec<_>>()
                .join(", "),
        );
        out.push_str("]\n");
        if c.tier != "fast" {
            out.push_str(&format!("tier = {}\n", quote(&c.tier)));
        }
        if let Some(j) = &c.junit {
            out.push_str(&format!("junit = {}\n", quote(j)));
        }
    }
    let (about, region) = if provider == "bedrock" {
        (
            "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(),
            region.map_or_else(
                || "# region = \"…\"  # required: set it\n".to_owned(),
                |r| format!("region = {}\n", quote(r)),
            ),
        )
    } else {
        (
            format!(
                "The API key comes only from the environment ({}).",
                if provider == "openai" {
                    "OPENAI_API_KEY"
                } else {
                    "ANTHROPIC_API_KEY"
                }
            ),
            String::new(),
        )
    };
    out.push_str(&format!(
        "\n# The model. {}\n\
         [model]\nprovider = {}\nmodel = {}\n{}\
         # price_input_per_mtok = 0.0       # USD per million tokens, for `speccoder report --cost`\n\
         # price_output_per_mtok = 0.0\n\
         # price_cache_read_per_mtok = 0.0\n\
         \n# Limits per attempt, and attempts per task (a failed verdict is retried once).\n\
         # [budget]\n# max_turns = 30\n# max_tool_calls = 100\n# max_attempts = 2\n\
         \n# Test files that existed before an attempt: \"ask\" before any change (default), or\n\
         # \"additions\" to let new tests be added without asking (changed lines still ask).\n\
         # [tests]\n# frozen = \"additions\"\n\
         \n# Commands run in an OS sandbox: writes only to the worktree, credentials unreadable,\n\
         # no network beyond loopback. Give commands that fetch the network, or switch it off.\n\
         # [sandbox]\n# network_allow = [[\"cargo\", \"fetch\"]]\n# mode = \"auto\"           # \"required\" refuses to run unsandboxed; \"off\"\n\
         \n# Commands the model may run besides the checks (argv prefixes); others need approval.\n",
        about,
        quote(provider),
        quote(model),
        region
    ));
    if let Some(argv) = format {
        out.push_str(&format!(
            "\n# The formatter speccoder runs after each attempt, before the checks.\n[format]\nargv = [{}]\n\n",
            argv.iter().map(|a| quote(a)).collect::<Vec<_>>().join(", ")
        ));
    }
    if allow.is_empty() {
        out.push_str("# [commands]\n# allow = [[\"make\", \"check\"]]\n");
    } else {
        let lists: Vec<String> = allow
            .iter()
            .map(|a| {
                format!(
                    "[{}]",
                    a.iter().map(|x| quote(x)).collect::<Vec<_>>().join(", ")
                )
            })
            .collect();
        out.push_str(&format!("[commands]\nallow = [{}]\n", lists.join(", ")));
    }
    out
}

/// The nextest profile speccoder's JUnit report path expects.
pub 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";

/// `speccoder init [--provider] [--model] [--region] [--force]` with an
/// explicit view of the environment (a variable's value when it is set)
/// and of what is installed.
pub fn init_with(
    path: &Path,
    provider: Option<&str>,
    model: Option<&str>,
    region: Option<&str>,
    force: bool,
    found: Option<Found>,
    env: &dyn Fn(&str) -> Option<String>,
) -> CommandResult {
    let refuse = |status, m: String| CommandResult::new("init", status, &m);
    // The Spec Kit root when there is one; else the path itself.
    let root = match crate::inspect(path, None).data() {
        Some(CommandData::Inspect(s)) => PathBuf::from(&s.root),
        _ => path.to_path_buf(),
    };
    let file = root.join(FILE);
    if file.exists() && !force {
        // It exists: change it, or start it over — never `init` again.
        return refuse(
            CommandStatus::ConfigError,
            format!("{} exists already", file.display()),
        )
        .with_code("CONFIG-EXISTS")
        .with_fix(vec![
            "speccoder config".to_owned(),
            "speccoder init --force".to_owned(),
        ]);
    }
    if let Some(p) = provider.filter(|p| !matches!(*p, "anthropic" | "openai" | "bedrock")) {
        return refuse(
            CommandStatus::UsageError,
            format!("--provider {p}: anthropic, openai or bedrock"),
        );
    }
    let (provider, model) = model_choice(provider, model, env);
    let bedrock = provider == "bedrock";
    if region.is_some() && !bedrock {
        return refuse(
            CommandStatus::UsageError,
            format!("--region is for --provider bedrock, not {provider}"),
        );
    }
    // Bedrock's region: the flag, else where the AWS tools find it.
    let region = bedrock
        .then(|| {
            region
                .map(|r| r.trim().to_owned())
                .filter(|r| !r.is_empty())
                .or_else(|| crate::aws::region(env, &home(env)).map(|(r, _)| r))
        })
        .flatten();
    let found = found.unwrap_or_else(|| detect(&root));
    let checks = propose(&found);
    let mut text = render(
        &checks,
        &allow(&found),
        formatter(&found).as_deref(),
        &provider,
        &model,
        region.as_deref(),
    );
    // The repository's instructions for agents: AGENTS.md is read by
    // default; a repository that only has CLAUDE.md gets it named too.
    let instructions: Vec<String> = ["AGENTS.md", "CLAUDE.md"]
        .iter()
        .filter(|n| root.join(n).is_file())
        .map(|n| (*n).to_owned())
        .collect();
    text.push_str(&worktree_section(&found.include, found.worktreeinclude));
    if instructions == ["CLAUDE.md"] {
        text.push_str(
            "\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",
        );
    }
    let key = if bedrock {
        // Where the AWS chain will take credentials from, by kind and name.
        let source = crate::aws::detect(env, &home(env));
        speccoder_core::InitKey {
            variable: crate::aws::API_KEY.to_owned(),
            set: source.is_some(),
            source: source.map(|s| s.describe()),
        }
    } else {
        let variable = if provider == "openai" {
            "OPENAI_API_KEY"
        } else {
            "ANTHROPIC_API_KEY"
        }
        .to_owned();
        speccoder_core::InitKey {
            set: env(&variable).is_some_and(|v| !v.is_empty()),
            variable,
            source: None,
        }
    };
    // Never write what speccoder itself would refuse — but Bedrock without
    // a region found, which every command then names with its fix.
    let model_parsed = crate::substrate::model_config::parse(&text)
        .map(|_| ())
        .or_else(|e| {
            if bedrock && region.is_none() && e.contains("needs `region`") {
                Ok(())
            } else {
                Err(e)
            }
        });
    if let Err(e) = crate::verify::config::parse(&text)
        .and(model_parsed)
        .and_then(|()| crate::substrate::run_config::parse(&text).map(|_| ()))
    {
        return refuse(
            CommandStatus::Error,
            format!("generated configuration is invalid: {e}"),
        );
    }
    let mut wrote = Vec::new();
    if let Err(e) = std::fs::write(&file, &text) {
        return refuse(CommandStatus::Error, format!("{}: {e}", file.display()));
    }
    wrote.push(FILE.to_owned());
    // The nextest profile the `test` check names, unless one is there.
    if checks.iter().any(|c| c.argv.iter().any(|a| a == "nextest")) {
        let nextest = root.join(".config/nextest.toml");
        let existing = std::fs::read_to_string(&nextest).unwrap_or_default();
        if !existing.contains("[profile.speccoder]") {
            let _ = std::fs::create_dir_all(root.join(".config"));
            if std::fs::write(&nextest, format!("{existing}{NEXTEST_PROFILE}")).is_ok() {
                wrote.push(".config/nextest.toml".to_owned());
            }
        }
    }
    // What checks write — speccoder's reports under .speccoder/, the
    // toolchains' build output — is output, not source: kept out of git, or
    // every run would find it in the worktree and set it aside. Added to
    // .gitignore only when that file is new or has no other uncommitted
    // change (so committing it commits nothing else).
    let mut output: Vec<&str> = Vec::new();
    if checks
        .iter()
        .any(|c| c.argv.iter().any(|a| a.contains(".speccoder/")))
    {
        output.push(".speccoder/");
    }
    for c in &checks {
        for dir in crate::worktree::build_output(&c.argv) {
            if !output.contains(dir) {
                output.push(dir);
            }
        }
    }
    let git = Git::at(&root);
    let missing: Vec<&str> = output
        .into_iter()
        .filter(|d| {
            !git.succeeds(&["check-ignore", "-q", "--no-index", d])
                .unwrap_or(false)
        })
        .collect();
    if !missing.is_empty() {
        let ignore = root.join(".gitignore");
        let existing = std::fs::read_to_string(&ignore).unwrap_or_default();
        let clean = !ignore.exists()
            || git
                .line(&["status", "--porcelain", "--", ".gitignore"])
                .is_ok_and(|l| l.trim().is_empty());
        if clean {
            let sep = if existing.is_empty() || existing.ends_with('\n') {
                ""
            } else {
                "\n"
            };
            if std::fs::write(
                &ignore,
                format!(
                    "{existing}{sep}# what checks write (speccoder init)\n{}\n",
                    missing.join("\n")
                ),
            )
            .is_ok()
            {
                wrote.push(".gitignore".to_owned());
            }
        }
    }
    let mut message = if checks.is_empty() {
        format!("wrote {FILE} without checks — add one before `speccoder run`")
    } else {
        format!(
            "wrote {} with {} check(s) and {provider}/{model}; review it, then commit it",
            speccoder_core::words::listed(&wrote),
            checks.len()
        )
    };
    if bedrock && region.is_none() {
        message.push_str("; no AWS region was found — speccoder config set model.region <region>");
    }
    CommandResult::new("init", CommandStatus::Ok, &message).with_data(CommandData::Init(Box::new(
        speccoder_core::InitReport {
            path: file.display().to_string(),
            checks: checks
                .iter()
                .map(|c| speccoder_core::InitCheck {
                    name: c.name.clone(),
                    argv: c.argv.clone(),
                    tier: c.tier.clone(),
                    why: c.why.clone(),
                })
                .collect(),
            model: format!("{provider}/{model}"),
            wrote,
            ran: Vec::new(),
            instructions,
            key,
            region,
            committed: None,
            include: found.include.clone(),
            include_active: false,
            worktreeinclude: found.worktreeinclude,
        },
    )))
}

/// Whether a test check found no tests to run — an empty suite on a fresh
/// scaffold: pytest's exit 5, `go test` with only packages
/// without test files, vitest, jest or nextest reporting nothing to run.
/// Neither passing nor failing: *no tests yet*.
#[must_use]
pub fn no_tests(argv: &[String], exit: Option<i32>, output: &str) -> bool {
    let has = |w: &str| argv.iter().any(|a| a == w || a.ends_with(&format!("/{w}")));
    let lower = output.to_lowercase();
    if has("pytest") {
        return exit == Some(5);
    }
    if has("go") && argv.iter().any(|a| a == "test") {
        let said: Vec<&str> = output
            .lines()
            .map(str::trim)
            .filter(|l| !l.is_empty())
            .collect();
        return exit == Some(0)
            && !said.is_empty()
            && said
                .iter()
                .all(|l| l.contains("no test files") || l.contains("matched no packages"));
    }
    // Only a run that ended as an empty suite ends: a failure that also
    // says "no tests" somewhere stays a failure.
    if has("vitest") || has("jest") || argv.iter().any(|a| a == "test") && has("npm") {
        return exit == Some(0)
            && (lower.contains("no test files found") || lower.contains("no tests found"));
    }
    if has("nextest") {
        // nextest's own exit status for "no tests to run".
        return exit == Some(4) && lower.contains("no tests to run");
    }
    false
}

/// Runs the fast-tier checks of the configuration `init` just wrote on the
/// untouched code, confined like in a run.
#[must_use]
pub fn verify_written(root: &Path) -> Vec<speccoder_core::InitRun> {
    use speccoder_core::verify::CheckStatus;
    let Ok((runner, _)) = crate::sandbox::runner_at(root) else {
        return Vec::new();
    };
    let Ok(report) =
        crate::verify::run_checks(root, Some(crate::verify::config::Tier::Fast), &runner)
    else {
        return Vec::new();
    };
    report
        .checks
        .iter()
        .map(|c| speccoder_core::InitRun {
            name: c.name.clone(),
            passed: matches!(c.status, CheckStatus::Passed | CheckStatus::Skipped),
            status: if no_tests(
                &c.argv,
                c.exit_code,
                &format!("{}\n{}", c.stdout_tail, c.stderr_tail),
            ) {
                "no_tests".to_owned()
            } else {
                serde_json::to_value(c.status)
                    .ok()
                    .and_then(|v| v.as_str().map(str::to_owned))
                    .unwrap_or_default()
            },
            duration_ms: c.duration_ms,
            reason: (!matches!(c.status, CheckStatus::Passed | CheckStatus::Skipped))
                .then(|| {
                    let said = |t: &str| {
                        t.lines()
                            .rev()
                            .map(str::trim)
                            .find(|l| !l.is_empty())
                            .map(str::to_owned)
                    };
                    said(&c.stderr_tail)
                        .or_else(|| said(&c.stdout_tail))
                        .or_else(|| c.note.clone())
                        .unwrap_or_else(|| {
                            format!(
                                "exit {}",
                                c.exit_code
                                    .map_or_else(|| "?".to_owned(), |e| e.to_string())
                            )
                        })
                })
                .map(|r| r.chars().take(200).collect()),
        })
        .collect()
}

/// [`init_with`] for this machine.
#[must_use]
pub fn init(
    path: &Path,
    provider: Option<&str>,
    model: Option<&str>,
    region: Option<&str>,
    force: bool,
) -> CommandResult {
    init_with(path, provider, model, region, force, None, &crate::aws::var)
}

/// `init` written and its checks run on the untouched code: what a person
/// then decides to commit.
#[derive(Debug, Clone)]
pub struct Prepared {
    /// `init`'s own result.
    pub written: CommandResult,
    /// Its report, with the checks' runs.
    pub report: speccoder_core::InitReport,
    /// The project root the file was written in.
    pub root: PathBuf,
    /// Everything the checks need committed: the file, and the nextest
    /// profile it names when that is not committed yet.
    pub to_commit: Vec<String>,
    /// Checks that fail on the untouched code.
    pub failed: Vec<String>,
}

/// The files `init` may commit: nothing else, whatever a caller asks.
pub const COMMITTABLE: &[&str] = &[
    FILE,
    ".config/nextest.toml",
    ".gitignore",
    "Cargo.lock",
    "package-lock.json",
    "pnpm-lock.yaml",
    "yarn.lock",
    "uv.lock",
    "poetry.lock",
    "go.sum",
];

/// Writes the configuration and (unless `no_verify`) runs its checks on the
/// untouched code. A refusal comes back as `Err`.
///
/// # Errors
///
/// `init`'s refusal (a file exists, no project, …).
pub fn prepare(
    path: &Path,
    provider: Option<&str>,
    model: Option<&str>,
    region: Option<&str>,
    force: bool,
    no_verify: bool,
) -> Result<Prepared, Box<CommandResult>> {
    let written = init(path, provider, model, region, force);
    let Some(CommandData::Init(report)) = written.data() else {
        return Err(Box::new(written));
    };
    let mut report = (**report).clone();
    let root = PathBuf::from(&report.path)
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_default();
    if !no_verify && !report.checks.is_empty() {
        report.ran = verify_written(&root);
    }
    let failed = report
        .ran
        .iter()
        .filter(|r| !r.passed && r.status != "no_tests")
        .map(|r| r.name.clone())
        .collect();
    let mut to_commit: Vec<String> = report.wrote.clone();
    let profile = ".config/nextest.toml";
    if report
        .checks
        .iter()
        .any(|c| c.argv.iter().any(|a| a == "nextest"))
        && root.join(profile).exists()
        && !to_commit.iter().any(|p| p == profile)
        && Git::at(&root)
            .line(&["status", "--porcelain", "--", profile])
            .is_ok_and(|l| !l.trim().is_empty())
    {
        to_commit.push(profile.to_owned());
    }
    // A lockfile the checks just wrote, never committed: every run would
    // find it in the worktree, so it goes with the configuration.
    for lock in crate::worktree::LOCKFILES {
        if root.join(lock).exists()
            && !to_commit.iter().any(|p| p == lock)
            && Git::at(&root)
                .line(&["status", "--porcelain", "--", lock])
                .is_ok_and(|l| l.starts_with("??"))
        {
            to_commit.push((*lock).to_owned());
        }
    }
    Ok(Prepared {
        written,
        report,
        root,
        to_commit,
        failed,
    })
}

/// Commits exactly `paths` — each one of [`COMMITTABLE`] — as
/// `speccoder: config`; the short id.
///
/// # Errors
///
/// A path `init` does not commit, or git's complaint.
pub fn commit_written(root: &Path, paths: &[String]) -> Result<String, String> {
    commit_written_as(root, paths, "speccoder: config")
}

/// [`commit_written`] with its own subject.
///
/// # Errors
///
/// A path `init` does not commit, or git's complaint.
pub fn commit_written_as(root: &Path, paths: &[String], subject: &str) -> Result<String, String> {
    if paths.is_empty() {
        return Err("nothing to commit".to_owned());
    }
    if let Some(p) = paths.iter().find(|p| !COMMITTABLE.contains(&p.as_str())) {
        return Err(format!("`{p}` is not a file init commits"));
    }
    let g = Git::at(root);
    let names: Vec<&str> = paths.iter().map(String::as_str).collect();
    let mut add = vec!["add", "--"];
    add.extend(&names);
    let mut commit = vec!["commit", "-q", "-m", subject, "--"];
    commit.extend(&names);
    g.run(&add).map_err(|e| e.0)?;
    // Nothing differs from the last commit: say that, not an empty failure.
    let mut unchanged = vec!["diff", "--cached", "--quiet", "--"];
    unchanged.extend(&names);
    if g.succeeds(&unchanged).unwrap_or(false) {
        return Err(format!(
            "nothing to commit: {} is committed as it is",
            speccoder_core::words::listed(&names)
        ));
    }
    g.run(&commit)
        .and_then(|_| g.line(&["rev-parse", "--short", "HEAD"]))
        .map_err(|e| {
            if e.0.trim().is_empty() {
                "git commit failed without saying why".to_owned()
            } else {
                e.0
            }
        })
}

/// The result of an `init` the person has decided about: the message, the
/// report, and what comes next.
#[must_use]
pub fn finish(p: Prepared) -> CommandResult {
    let Prepared {
        written,
        report,
        to_commit,
        failed,
        ..
    } = p;
    let mut message = match &report.committed {
        Some(id) => written.message().replace(
            "; review it, then commit it",
            &format!(" and committed it ({id})"),
        ),
        None => written.message().to_owned(),
    };
    if !failed.is_empty() {
        message = format!(
            "{message}; the check(s) {} fail on the untouched code: every task would be judged against a red baseline",
            failed.join(", ")
        );
    }
    let step = |command: String, why: &str| speccoder_core::next::NextStep {
        command,
        why: why.to_owned(),
    };
    let mut next = Vec::new();
    // No spec project yet: the format's tool makes one — first, before the
    // commit and the key matter.
    let root = PathBuf::from(&report.path)
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_default();
    let format = crate::format::at(&root);
    if format.detect(&root).is_none() {
        let (command, why) = format.messages().make_project;
        message = format!("{message}; there is no spec project here yet");
        next.push(step(command.to_owned(), why));
    }
    if report.committed.is_none() {
        let listed = to_commit.join(" ");
        next.push(step(
            format!("git add {listed} && git commit -m \"speccoder: config\" -- {listed}"),
            "speccoder reads committed files only",
        ));
    }
    if !report.key.set && report.model.starts_with("bedrock/") {
        next.push(step(
            format!("export {}=…", report.key.variable),
            "a Bedrock API key — or run aws login where you start speccoder",
        ));
    } else if !report.key.set {
        next.push(step(
            format!("export {}=…", report.key.variable),
            "the model key, from the environment only",
        ));
    }
    // Something to run, or something to write first.
    let features = match crate::current::list(&root, None).data() {
        Some(CommandData::Features(f)) => f.features.len(),
        _ => 0,
    };
    if features == 0 {
        next.push(step(
            "speccoder spec specify \"…\"".to_owned(),
            "describe the first feature; its spec, plan and tasks follow",
        ));
    } else {
        next.push(step(
            "speccoder run".to_owned(),
            "work through the ready tasks",
        ));
    }
    CommandResult::new("init", CommandStatus::Ok, &message)
        .with_data(CommandData::Init(Box::new(report)))
        .with_next(next)
}

/// What `init` would write here, without writing: for the setup assistant.
#[derive(Debug, Clone, Serialize)]
pub struct Preview {
    /// Whether the project already has a `speccoder.toml`.
    pub configured: bool,
    /// The checks it would declare.
    pub checks: Vec<Proposed>,
    /// Commands the model could run without asking.
    pub allow: Vec<Vec<String>>,
    /// The formatter it would configure.
    pub formatter: Option<Vec<String>>,
    /// The model key variables, and whether each is set.
    pub keys: Vec<(String, bool)>,
    /// Amazon Bedrock's credential source and region, as found here.
    pub bedrock: BedrockPreview,
    /// The git-ignored files proposed for `[worktree] include`.
    pub include: Vec<String>,
}

/// Where Bedrock's credentials and region would come from: named, never a
/// value.
#[derive(Debug, Clone, Default, Serialize)]
pub struct BedrockPreview {
    /// The source, as `doctor` describes it (`aws login session (profile dev)`).
    pub source: Option<String>,
    /// The region `init` would write.
    pub region: Option<String>,
}

/// Where `init` writes for `path`: the spec project's root, else `path`.
#[must_use]
pub fn root_of(path: &Path) -> PathBuf {
    match crate::inspect(path, None).data() {
        Some(CommandData::Inspect(s)) => PathBuf::from(&s.root),
        _ => path.to_path_buf(),
    }
}

/// [`Preview`] of `path`.
#[must_use]
pub fn preview(path: &Path) -> Preview {
    let root = root_of(path);
    let found = detect(&root);
    let set = |v: &str| std::env::var_os(v).is_some_and(|x| !x.is_empty());
    Preview {
        configured: root.join(FILE).is_file(),
        checks: propose(&found),
        allow: allow(&found),
        formatter: formatter(&found),
        keys: ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"]
            .iter()
            .map(|v| ((*v).to_owned(), set(v)))
            .collect(),
        bedrock: BedrockPreview {
            source: crate::aws::detect_here().map(|s| s.describe()),
            region: crate::aws::region_here().map(|(r, _)| r),
        },
        include: found.include,
    }
}

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

    #[test]
    fn a_uv_project_runs_its_checks_through_uv_never_an_uncommitted_venv() {
        let d = tempfile::tempdir().unwrap();
        std::fs::write(d.path().join("pyproject.toml"), "[project]\nname = \"p\"\n").unwrap();
        std::fs::write(d.path().join("uv.lock"), "version = 1\n").unwrap();
        std::fs::create_dir_all(d.path().join(".venv/bin")).unwrap();
        std::fs::write(d.path().join(".venv/bin/python"), "").unwrap();
        let found = detect(d.path());
        assert_eq!(
            found.python_run,
            ["uv", "run", "--locked", "--offline", "python"]
        );
        let test = &propose(&found)[0];
        assert_eq!(
            test.argv.join(" "),
            "uv run --locked --offline python -m pytest -q --junitxml=.speccoder/junit.xml"
        );
        // Without a lockfile, a project-local virtualenv's interpreter.
        std::fs::remove_file(d.path().join("uv.lock")).unwrap();
        assert_eq!(detect(d.path()).python_run, [".venv/bin/python"]);
    }

    #[test]
    fn proposals_follow_what_was_found() {
        let rust = propose(&Found {
            cargo: true,
            nextest: true,
            ..Found::default()
        });
        let names: Vec<&str> = rust.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, ["test", "fmt", "clippy"]);
        assert_eq!(
            rust[0].junit.as_deref(),
            Some("target/nextest/speccoder/junit.xml")
        );
        assert_eq!(rust[2].tier, "full");
        let plain = propose(&Found {
            cargo: true,
            ..Found::default()
        });
        assert_eq!(plain[0].argv, ["cargo", "test", "--workspace"]);

        let node = propose(&Found {
            node_manager: Some("pnpm".to_owned()),
            npm_scripts: vec!["test".into(), "lint".into(), "build".into()],
            ..Found::default()
        });
        let shown: Vec<(String, String)> = node
            .iter()
            .map(|c| (c.name.clone(), c.argv.join(" ")))
            .collect();
        assert_eq!(
            shown,
            [
                ("test".into(), "pnpm run test".into()),
                ("lint".into(), "pnpm run lint".into())
            ]
        );
        let npm = propose(&Found {
            node_manager: Some("npm".to_owned()),
            npm_scripts: vec!["test".into()],
            ..Found::default()
        });
        assert_eq!(npm[0].argv, ["npm", "run", "test"]);

        let py = propose(&Found {
            python: true,
            ruff: true,
            ..Found::default()
        });
        assert_eq!(
            py.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
            ["test", "ruff"]
        );
        let go = propose(&Found {
            go: true,
            ..Found::default()
        });
        assert_eq!(go[0].argv, ["go", "test", "./..."]);
        let make = propose(&Found {
            make_test: true,
            ..Found::default()
        });
        assert_eq!(make[0].argv, ["make", "test"]);
        assert!(propose(&Found::default()).is_empty());
    }

    #[test]
    fn the_model_follows_the_key_that_is_set() {
        let none = |_: &str| None;
        let openai = |v: &str| (v == "OPENAI_API_KEY").then(|| "k".to_owned());
        assert_eq!(model_choice(None, None, &none).0, "anthropic");
        assert_eq!(
            model_choice(None, None, &openai),
            ("openai".to_owned(), "gpt-5.4-mini".to_owned())
        );
        assert_eq!(
            model_choice(Some("anthropic"), Some("m"), &openai),
            ("anthropic".to_owned(), "m".to_owned())
        );
    }

    #[test]
    fn every_rendered_file_parses() {
        for found in [
            Found {
                cargo: true,
                nextest: true,
                ..Found::default()
            },
            Found {
                python: true,
                ruff: true,
                mypy: true,
                go: true,
                ..Found::default()
            },
            Found::default(),
        ] {
            let text = render(
                &propose(&found),
                &allow(&found),
                formatter(&found).as_deref(),
                "openai",
                "gpt-5.4-mini",
                None,
            );
            if found.cargo {
                assert!(
                    text.contains("[format]\nargv = [\"cargo\", \"fmt\", \"--all\"]"),
                    "{text}"
                );
                assert_eq!(
                    crate::substrate::run_config::parse(&text)
                        .ok()
                        .and_then(|c| c.format),
                    Some(vec![
                        "cargo".to_owned(),
                        "fmt".to_owned(),
                        "--all".to_owned()
                    ])
                );
            }
            let checks =
                crate::verify::config::parse(&text).unwrap_or_else(|e| panic!("{e}\n{text}"));
            assert_eq!(checks.len(), propose(&found).len());
            assert!(crate::substrate::model_config::parse(&text).is_ok_and(|m| m.is_some()));
            assert!(crate::substrate::run_config::parse(&text).is_ok());
        }
    }

    #[test]
    fn an_empty_suite_on_a_fresh_scaffold_is_no_tests_yet() {
        let argv = |a: &[&str]| a.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
        assert!(no_tests(
            &argv(&["uv", "run", "pytest"]),
            Some(5),
            "no tests ran"
        ));
        assert!(!no_tests(
            &argv(&["uv", "run", "pytest"]),
            Some(1),
            "1 failed"
        ));
        assert!(no_tests(
            &argv(&["go", "test", "./..."]),
            Some(0),
            "go: warning: \"./...\" matched no packages\n"
        ));
        assert!(no_tests(
            &argv(&["go", "test", "./..."]),
            Some(0),
            "?   \tx\t[no test files]\n"
        ));
        assert!(!no_tests(
            &argv(&["go", "test", "./..."]),
            Some(0),
            "ok  \tx\t0.1s\n"
        ));
        assert!(no_tests(
            &argv(&["npm", "test"]),
            Some(0),
            "No test files found, exiting with code 0"
        ));
        assert!(no_tests(
            &argv(&["npx", "vitest", "run"]),
            Some(0),
            "No test files found"
        ));
        assert!(no_tests(
            &argv(&["cargo", "nextest", "run"]),
            Some(4),
            "error: no tests to run"
        ));
        assert!(!no_tests(
            &argv(&["cargo", "test"]),
            Some(0),
            "test result: ok. 1 passed"
        ));
    }
}