omh 0.5.0

Launch any coding harness, in a sandbox, with your setup already there.
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
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
//! Stacks — what a project needs installed, as data rather than as Rust.
//!
//! A stack answers one question: *what does this project need in order to be
//! worked on?* If the agent has just changed something and wants to check it,
//! what tool does it reach for, and is that tool here?
//!
//! It is therefore not a set of hooks. Hooks are automation — when something
//! runs, on which events. Conflating the two produced the original wrong fix:
//! treating a missing compiler as a hook that should be suppressed, which hides
//! the symptom and leaves the environment as broken as it was. A human opening
//! a shell in that sandbox and typing `cargo test` gets the same error.
//!
//! These ship with omh — embedded at compile time by `build.rs`, refreshed into
//! `~/.omh/stacks` by every `init`, exactly as adapters and the base set are.
//! That is deliberate: a local edit fixing Elixir on one laptop leaves omh
//! broken for every other Elixir user, and removes the pressure that would have
//! produced a real fix. What moving them out of a `const` buys is a lower
//! barrier to *contributing* — a few lines of TOML rather than Rust — not a
//! lower barrier to diverging.
//!
//! Commands live in hooks, and a hook says which ecosystem it belongs to. The
//! reference points that way round on purpose: a `hooks = [...]` key here would
//! make a stack file decide what automation an ecosystem gets, and the two
//! would then have to be edited together forever. As it is, contributing a
//! stack and contributing a hook for it are separate acts, and a stack with no
//! hooks is a perfectly good stack.
//!
//! The pair is held together by `every_shipped_hook_names_a_program_its_stack_provisions`,
//! which refuses a hook whose program no provide installs — the one thing
//! neither file can check about the other.

use anyhow::{Context, Result};
use serde::Deserialize;
use std::path::Path;

/// One ecosystem: how to tell a repo is one, and what such a repo needs.
///
/// No commands. A command belongs to a hook, and hooks already have two homes
/// with a defined precedence — `~/.omh/hooks/` for the ones you want
/// everywhere, `<repo>/.omh/hooks/` for the ones that belong to a project,
/// unioned by `render::merge_hooks` with the repo shadowing. A third copy here
/// would be the same string in a second place, free to disagree with the first.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Definition {
    pub name: String,
    /// The file whose presence says this repo is one of these.
    pub marker: String,
    #[serde(default, rename = "provide")]
    pub provides: Vec<Provide>,
}

/// One thing a stack puts in the image, and the case for it.
///
/// `needs` and `install` are deliberately separate fields. `install` is a
/// recipe; `needs` is the outcome to verify. That is not theoretical:
/// installing rustup produced a working `cargo` and still could not link
/// anything, because the image had no `cc`. The recipe succeeded and the
/// environment did not work. Kept paired *per provide*, the failure is
/// attributable — "the `linker` provide ran and `cc` still does not resolve" —
/// rather than a flat list of names with no idea which recipe owed them.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Provide {
    pub name: String,
    /// What must resolve in the sandbox once this has run. Never empty: a
    /// provide whose outcome is unstated is one nothing can verify.
    pub needs: Vec<String>,
    /// A shell predicate deciding whether this provide applies to this repo,
    /// evaluated **in the sandbox** with the repo mounted read-only. Absent
    /// means it always applies.
    #[serde(default)]
    pub when: Option<String>,
    /// How the image gets it. Absent means "the base image already ships
    /// this" — an assertion rather than a provision, which costs nothing to
    /// state and turns an unwritten assumption into a checked one.
    #[serde(default)]
    pub install: Option<String>,
    pub because: String,
    #[serde(default, rename = "measured")]
    pub measured: Vec<crate::base::Measured>,
}

/// Which of these stacks this repo is.
///
/// Marker presence and nothing cleverer. The finer question — *which variant*,
/// which package manager — is a provide's `when`, asked in the sandbox once a
/// stack is already in play. This one runs on the host on every launch, so it
/// stays a filename check: cheap enough that noticing a `package.json` that
/// appeared last week costs nothing.
///
/// Borrowed rather than cloned because the caller already owns the definitions
/// and a detected stack is a view of one, not a copy that could go stale.
pub fn detected<'a>(stacks: &'a [Definition], repo: &Path) -> Vec<&'a Definition> {
    stacks
        .iter()
        .filter(|s| repo.join(&s.marker).exists())
        .collect()
}

/// How a provide is named everywhere it is named: `[provision]` keys, the
/// probe's outcome names, the report. One speller, so those cannot drift.
///
/// Not the image tag — `image::stack_tag` hashes the recipe, which is what the
/// image actually contains, and two repos whose fired provides differ in name
/// but not in recipe should share a layer.
///
/// This spelling is part of a **committed file**, so it is pinned literally by
/// a test rather than only round-tripped: the opt-out somebody hand-writes is
/// a string in their `settings.toml`, and a speller that changed would leave
/// it matching nothing, in silence.
pub fn key(stack: &str, provide: &str) -> String {
    format!("{stack}/{provide}")
}

/// The `[provision]` table to write, given what this repo already recorded and
/// what just fired.
///
/// Three rules, and the asymmetry between them is the whole design:
///
/// - **omh writes only `true`.** It records what applied; it never records a
///   refusal, because a refusal it invented would be indistinguishable in a
///   committed file from one somebody made.
/// - **A `false` is never touched.** It can only have been typed, so it is a
///   decision, and re-running `init` is not consent to discard it.
/// - **A `true` that no longer applies is removed**, not kept and not flipped.
///   The table describes what is true now, which is what makes re-running
///   `init` the honest fix for a `yarn.lock` swapped for a `pnpm-lock.yaml`.
///
/// Takes the **shared layer's own table**, never the three-layer resolution. A
/// `false` in `settings.local.toml` is one laptop's decision; reading it here
/// would copy it into the committed file and export it to the team.
pub fn reconcile(
    shared: &std::collections::BTreeMap<String, bool>,
    fired: &std::collections::BTreeSet<String>,
) -> std::collections::BTreeMap<String, bool> {
    let mut out = std::collections::BTreeMap::new();
    for (key, on) in shared {
        if !on {
            out.insert(key.clone(), false);
        }
    }
    for key in fired {
        out.entry(key.clone()).or_insert(true);
    }
    out
}

/// What a predicate answered.
///
/// Three-valued over a mechanism that is two-valued: a shell command yields one
/// exit code, and *false* and *broken* both come back non-zero. Collapsing them
/// would make a `jq` choking on malformed JSON indistinguishable from a repo
/// that simply is not a pnpm project — and *cannot tell is never a licence to
/// act* is the rule the rest of this codebase runs on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
    /// Exit 0. This provide applies here.
    Applies,
    /// Exit 1. It does not.
    DoesNot,
    /// Anything above 1 — the predicate could not answer, with its code when
    /// that could be read. Reported and **not fired**: a provide omh skipped
    /// because it could not tell surfaces as its `needs` not resolving, which is
    /// loud — `init` reports it and every hook that names the program is held
    /// back by name — whereas installing on a coin-flip is silent.
    CouldNotAnswer(Option<i32>),
}

/// Read a probe outcome as a verdict.
///
/// The code is carried in `detail` rather than in a wider `Outcome`, so the one
/// wire format and the one parser serve both this and `doctor`'s checks. The
/// emitter below and this reader are round-tripped by the tests, so they cannot
/// drift into disagreeing about where the number is.
pub fn verdict(o: &crate::doctor::Outcome) -> Verdict {
    if o.ok {
        return Verdict::Applies;
    }
    match o
        .detail
        .split_whitespace()
        .next()
        .and_then(|c| c.parse().ok())
    {
        Some(1) => Verdict::DoesNot,
        code => Verdict::CouldNotAnswer(code),
    }
}

/// A shell script asking, for each provide, whether it applies to this repo.
///
/// Emits the same `ok|fail\t<key>\t<detail>` wire format as every other probe,
/// so `doctor::parse` reads it and there is one format and one parser.
///
/// The exit code leads `detail` because that is the only channel a two-valued
/// `Outcome` leaves for a three-valued answer — see [`Verdict`]. Each predicate
/// is its own `if`, so one that dies takes only its own line: a `set -e` or a
/// chain would let the first broken predicate silence every provide after it,
/// and a truncated report read as a complete one is a defect this codebase has
/// already paid for twice — see `main::fired_from`, which refuses a report
/// shorter than the question it asked.
pub fn predicate_script(candidates: &[(String, Option<&str>)]) -> String {
    let mut out = String::from("#!/bin/sh\n");
    for (key, when) in candidates {
        let k = crate::doctor::single_quote(key);
        match when {
            // No condition is not a failed condition.
            None => out.push_str(&format!("printf 'ok\\t%s\\tapplies\\n' {k}\n")),
            // `( … )` — a subshell, and load-bearing rather than tidy. A bare
            // `if exit 2; then` terminates the *script*, so every predicate
            // after it produces no line at all, and a truncated report read as
            // a complete one is the failure this design has already been fixed
            // for once. In a subshell the `exit` ends only that predicate and
            // the `if` sees its code.
            // `>/dev/null 2>&1` on the predicate itself, not just the subshell
            // for `exit`. Predicate output and omh's protocol share one stream,
            // and `doctor::parse` takes a well-formed line from anywhere in it —
            // so a predicate written without a redirect (`grep packageManager
            // package.json`) prints **repo-controlled text** into the channel.
            // `init` runs against repos you have just cloned, and a forged
            // `applies` line reaches a committed table and an image recipe that
            // runs as root. Every shipped predicate redirects; this stops that
            // being a matter of discipline.
            Some(pred) => out.push_str(&format!(
                "if ( {pred} ) >/dev/null 2>&1; then printf 'ok\\t%s\\tapplies\\n' {k}; \
                 else c=$?; if [ \"$c\" -eq 1 ]; then \
                 printf 'fail\\t%s\\t1 does not apply\\n' {k}; else \
                 printf 'fail\\t%s\\t%s could not answer\\n' {k} \"$c\"; fi; fi\n"
            )),
        }
    }
    out
}

/// Arguments that evaluate predicates inside the sandbox, against the repo.
///
/// A **second** builder, deliberately not `image::probe_args`. That one is
/// mountless and a test asserts it, which is what stops a program probe
/// answering about the host. This one must see the checkout — so it takes the
/// mount `base::index_args` already established, for the reason recorded there:
/// *read-only, because a thing that reads code and can write into the checkout
/// is a sandbox hole for no benefit.*
///
/// Running them in the sandbox rather than on the host is the point. `install`
/// is arbitrary shell too, but it runs in a container as root and is contained
/// by construction; a predicate evaluated on the host would mean a stack file
/// executing shell on somebody's laptop during `init`.
pub fn predicate_args(tag: &str, repo: &Path, script: &str) -> Vec<String> {
    // Never the literal — `only_one_place_spells_the_container_workdir` counts
    // the spellings across the source, because asserting that two sides are
    // equal passes just as well when both hold the same hardcoded string.
    let workdir = crate::container_workdir();
    vec![
        "run".into(),
        "--rm".into(),
        "-v".into(),
        format!("{}:{workdir}:ro", repo.display()),
        "-w".into(),
        workdir.into(),
        tag.into(),
        "sh".into(),
        "-c".into(),
        script.into(),
    ]
}

/// What serde cannot say about a stack file.
///
/// Here rather than in the curation test, and the difference is the whole
/// point: that test reads `CARGO_MANIFEST_DIR/stacks`, so it proves things
/// about this source tree. `load_dir` is what reads `~/.omh/stacks`, and a
/// rule enforced only on the four files in this repo is not a rule about
/// stacks — it is a rule about these four files.
fn validate(def: &Definition, path: &Path) -> Result<()> {
    let at = path.display();

    // A name is half a `[provision]` key, and `key` joins the halves with `/`.
    // A stack `a/b` with provide `c` and a stack `a` with provide `b/c` mint one
    // key, so one person's `false` switches off somebody else's install.
    ecosystem_name(&def.name, &at.to_string())?;

    // `Path::join` **discards the base** when handed an absolute path, so an
    // absolute marker does not look inside the repo at all — it matches every
    // repository on the machine, each of which then runs this stack's `install`
    // as root. `..` climbs out of the checkout, and a blank marker joins to the
    // repo root, which always exists.
    //
    // Shipped stack files are reviewed. A repo-local one is not: it arrives in
    // a checkout you have just cloned and not read, which is why this rule
    // lives in the loader both of them go through.
    let marker = Path::new(&def.marker);
    anyhow::ensure!(
        !def.marker.trim().is_empty(),
        "{at}: the stack has no marker, and an empty one matches every repo"
    );
    anyhow::ensure!(
        marker.components().count() == 1
            && marker
                .components()
                .all(|c| matches!(c, std::path::Component::Normal(_))),
        "{at}: marker `{}` must be one filename inside the repo — an absolute \
         path matches every repo on this machine, and `..` leaves the checkout",
        def.marker
    );

    let mut seen = std::collections::BTreeSet::new();
    for p in &def.provides {
        anyhow::ensure!(
            !p.name.trim().is_empty(),
            "{at}: a provide has no name, so it cannot be keyed or reported"
        );
        anyhow::ensure!(
            !p.name.contains('/'),
            "{at}: provide name `{}` contains `/`",
            p.name
        );
        // Two provides of one name are one `[provision]` key and two installs,
        // and they destroy the attribution the `needs`/`install` pairing exists
        // for: "the `linker` provide ran and `cc` still does not resolve".
        anyhow::ensure!(
            seen.insert(p.name.as_str()),
            "{at}: two provides are called `{}`",
            p.name
        );
        anyhow::ensure!(
            !p.because.trim().is_empty(),
            "{at}: provide `{}` states no case — `omh why` has nothing to read",
            p.name
        );
        // Every entry here is handed to `command -v` by the sandbox probe. A
        // blank one, or one carrying arguments, resolves nowhere — so it reports a gap for a
        // toolchain the user has, and keeps reporting it. `detect::program`
        // returns `None` rather than guess for exactly this reason; a stack
        // file is the other door into the same mistake.
        anyhow::ensure!(
            !p.needs.is_empty(),
            "{at}: provide `{}` needs nothing, so nothing can verify it ran",
            p.name
        );
        for need in &p.needs {
            anyhow::ensure!(
                !need.trim().is_empty(),
                "{at}: provide `{}` has a blank `needs` entry",
                p.name
            );
            // Through `detect::program` rather than a local re-spelling of the
            // rule. That function is the codebase's answer to "is this word a
            // program name", it uses an allowlist for reasons its own tests
            // record, and a second implementation here accepted `$(which`,
            // `cargo|tee` and a leading space — the exact shapes it refuses.
            anyhow::ensure!(
                crate::detect::program(need) == Some(need.as_str()),
                "{at}: provide `{}` needs `{need}`, which is not a program name \
                 — `needs` is what must resolve on PATH, not a command to run",
                p.name
            );
        }
    }
    Ok(())
}

/// Every stack in a directory.
///
/// The `Adapter::load_dir` shape, not `Manifest::load_dir`'s: a directory of
/// stacks is a set, and a polyglot repo is genuinely several of them at once.
/// A missing directory is no stacks rather than an error, because a fresh
/// install has not seeded one yet and that is not a reason to refuse to work.
/// What an ecosystem may be called — the one rule, applied at **both** ends.
///
/// A `Definition::name` and a `Marker::stack` are the same name: the marker is
/// the question, the definition is the answer, and `ask::how_is_it_installed`
/// turns one into the other by writing `stacks/<stack>.toml`. The rule was
/// enforced only where definitions are *read*, so a marker could name something
/// no definition may be called — and omh would then write a file it declines to
/// load, or write it into a subdirectory nothing reads.
///
/// Three things it must not be:
///
/// - **blank**, which names nothing
/// - **`/`-bearing**, because a name is half a `[provision]` key and `key`
///   joins the halves with `/`: a stack `a/b` with provide `c` and a stack `a`
///   with provide `b/c` mint one key, so one person's `false` switches off
///   somebody else's install
/// - **a path component** — `.` or `..` or a separator — because the name is
///   interpolated into a filename, and `..` climbs out of the directory the
///   answer belongs in
fn ecosystem_name(name: &str, at: &str) -> Result<()> {
    anyhow::ensure!(!name.trim().is_empty(), "{at}: an ecosystem has no name");
    anyhow::ensure!(
        !name.contains('/') && !name.contains('\\'),
        "{at}: ecosystem name `{name}` contains a separator, which is what \
         divides a stack from a provide in a `[provision]` key — and what would \
         put its file somewhere nothing reads"
    );
    anyhow::ensure!(
        !name.starts_with('.'),
        "{at}: ecosystem name `{name}` starts with `.`, so it is a path rather \
         than a name"
    );
    Ok(())
}

/// A file omh recognises as naming an ecosystem it cannot yet set up.
///
/// The one case where `init` has nothing to fall back on: the repo plainly *is*
/// something, no stack claims it, and no lockfile or runner says how to test
/// it. So omh asks — which is tier 3 of `docs/design/adoption.md`'s table, and
/// the only question left in `init`.
///
/// Deliberately **not** a stack file with no provides. The answer to the
/// question is written as `<repo>/.omh/stacks/<name>.toml`, and a shipped stack
/// of that name is one a repo may not answer to — so the question and its
/// answer would collide. A marker is a question; a stack is an answer.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Marker {
    /// The filename whose presence names the ecosystem.
    pub file: String,
    /// What to call it — the name the repo's own stack file will take.
    pub stack: String,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Markers {
    #[serde(default, rename = "marker")]
    markers: Vec<Marker>,
}

/// Every marker omh recognises without being able to provision it.
pub fn markers(dir: &Path) -> Result<Vec<Marker>> {
    let mut out = Vec::new();
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e).with_context(|| format!("reading {}", dir.display())),
    };
    for entry in entries {
        let path = entry
            .with_context(|| format!("reading {}", dir.display()))?
            .path();
        if path.extension().is_none_or(|e| e != "toml") {
            continue;
        }
        let raw = std::fs::read_to_string(&path)
            .with_context(|| format!("reading {}", path.display()))?;
        let parsed: Markers =
            toml::from_str(&raw).with_context(|| format!("parsing {}", path.display()))?;
        for m in &parsed.markers {
            let at = path.display().to_string();
            anyhow::ensure!(!m.file.trim().is_empty(), "{at}: a marker needs a `file`");
            // The same rule a `Definition::name` gets, because it is the same
            // name: `ask::how_is_it_installed` writes the answer as
            // `stacks/<stack>.toml`, so a marker that names something no
            // definition may be called produces a file omh then cannot load.
            ecosystem_name(&m.stack, &at)?;
            // The same rule a stack's own marker gets, for the same reason: an
            // absolute path matches every repo on the machine.
            let p = Path::new(&m.file);
            anyhow::ensure!(
                p.components().count() == 1
                    && p.components()
                        .all(|c| matches!(c, std::path::Component::Normal(_))),
                "{}: marker `{}` must be one filename inside the repo",
                path.display(),
                m.file
            );
        }
        out.extend(parsed.markers);
    }
    out.sort_by(|a, b| a.stack.cmp(&b.stack));
    Ok(out)
}

/// Which recognised-but-unprovisionable ecosystems this repo turns out to be.
///
/// A marker whose stack is now in play is not unclaimed — that is what makes
/// contributing `stacks/elixir.toml` turn the elixir question off, in the same
/// release, without anybody remembering to edit a second file. The curation
/// test refuses the contradiction outright, so this filter is a belt to that
/// braces: a repo-local stack answers the question too, and no test can iterate
/// those.
pub fn unclaimed<'a>(markers: &'a [Marker], stacks: &[Definition], repo: &Path) -> Vec<&'a Marker> {
    markers
        .iter()
        .filter(|m| repo.join(&m.file).exists())
        .filter(|m| !stacks.iter().any(|s| s.name == m.stack))
        .collect()
}

/// Every stack in play: what omh ships, plus what this repo taught it.
///
/// A repo writes `<repo>/.omh/stacks/<name>.toml` to describe an ecosystem omh
/// has never heard of — a proprietary internal toolchain that will never be
/// upstreamed, and still has to be installable. That is the escape hatch
/// `docs/design/adoption.md` §1.2 reserves, scoped to the project that needs it
/// so shared opinion stays versioned.
///
/// **It adds; it never shadows.** A repo file answering to a name omh ships is
/// an error naming both paths. `merge_hooks` applies the same rule to a hook
/// answering to a manifest name, and here the reason is stronger: a stack
/// decides what goes into the image somebody's agent runs in, so a repo that
/// could redefine `rust` could point its `install` at anything and the only
/// symptom would be a sandbox that built successfully.
///
/// In the loader, so `init`, launch, `doctor` and `why` all inherit it. A guard
/// only `init` applied is a guard any repo bypasses by never being `init`ed.
pub fn load_all(catalogue: &Path, repo: &Path) -> Result<Vec<Definition>> {
    let mut out = load_dir(catalogue)?;
    for def in load_dir(repo)? {
        if out.iter().any(|d| d.name == def.name) {
            anyhow::bail!(
                "{}: `{}` is a stack omh ships, so this file answers to nothing — \
                 it is not read, and it does not override omh's ({}). Rename it, \
                 or open a pull request against the one omh ships if it is wrong.",
                repo.join(format!("{}.toml", def.name)).display(),
                def.name,
                catalogue.join(format!("{}.toml", def.name)).display()
            );
        }
        out.push(def);
    }
    out.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(out)
}

pub fn load_dir(dir: &Path) -> Result<Vec<Definition>> {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e).with_context(|| format!("reading {}", dir.display())),
    };

    let mut out = Vec::new();
    for entry in entries {
        let path = entry
            .with_context(|| format!("reading {}", dir.display()))?
            .path();
        // `.toml` and nothing else: a `.yours` backup is somebody's replaced
        // edit, kept on purpose by `install_bundled`, and reading it as a stack
        // would turn a saved file into a parse error on every command.
        if path.extension().is_none_or(|e| e != "toml") {
            continue;
        }
        let raw = std::fs::read_to_string(&path)
            .with_context(|| format!("reading {}", path.display()))?;
        let def: Definition =
            toml::from_str(&raw).with_context(|| format!("parsing {}", path.display()))?;
        validate(&def, &path)?;
        out.push(def);
    }
    out.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(out)
}

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

    fn dir_with(files: &[(&str, &str)]) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        for (name, body) in files {
            std::fs::write(dir.path().join(name), body).unwrap();
        }
        dir
    }

    const MINIMAL: &str = r#"
name   = "rust"
marker = "Cargo.toml"

[[provide]]
name    = "toolchain"
needs   = ["cargo"]
because = "cargo is how a rust project is built and tested"
"#;

    fn shipped() -> Vec<Definition> {
        load_dir(Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/stacks")))
            .expect("the shipped stacks must load")
    }

    // ── markers omh cannot answer for ───────────────────────────────────────

    fn shipped_markers() -> Vec<Marker> {
        markers(Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/markers")))
            .expect("the shipped markers must load")
    }

    /// **A marker omh ships a stack for is a contradiction**, and shipping the
    /// stack is what removing the marker means.
    ///
    /// The two files say opposite things: `markers/` means *omh recognises this
    /// and cannot set it up*, `stacks/` means *omh sets this up*. Left in both,
    /// `init` would ask how to install an ecosystem it had just provisioned —
    /// a question with a right answer already on disk, which is the most
    /// expensive kind to be asked.
    ///
    /// Enforced rather than documented, because the two files are edited by
    /// different people at different times: whoever contributes
    /// `stacks/elixir.toml` has no reason to know `markers/markers.toml`
    /// exists, and this is how they find out in the same commit.
    #[test]
    fn no_marker_names_an_ecosystem_omh_already_ships() {
        let stacks = shipped();
        for m in shipped_markers() {
            assert!(
                !stacks.iter().any(|s| s.name == m.stack),
                "`{}` is listed as unclaimed and omh ships a `{}` stack — \
                 delete the marker, or `init` will ask how to install what it \
                 just installed",
                m.file,
                m.stack
            );
            assert!(
                !stacks.iter().any(|s| s.marker == m.file),
                "`{}` is listed as unclaimed and a shipped stack already \
                 detects it",
                m.file
            );
        }
    }

    /// **A marker's `stack` becomes a filename and a `[provision]` key**, so it
    /// takes the same rule a stack's own name does.
    ///
    /// The rule was enforced at the read end and not the write end, and the two
    /// ends are the same name. `ask::how_is_it_installed` interpolates this
    /// straight into `stacks/<stack>.toml`, so `elixir/otp` writes
    /// `<repo>/.omh/stacks/elixir/otp.toml` — which `load_dir` is not recursive
    /// enough to find. The question is answered, the file exists, `init` says
    /// `stack elixir/otp — from what you told it`, and nothing ever reads it.
    /// Had it landed in the right directory, `validate` would have *refused* it
    /// for the same `/`, so omh would have written a file omh then declines to
    /// load.
    ///
    /// A leading `.` is the milder variant: `..` climbs out of `stacks/`
    /// entirely, into `<repo>/.omh/`.
    #[test]
    fn a_marker_names_an_ecosystem_the_way_a_stack_does() {
        for (stack, why) in [
            (
                "elixir/otp",
                "a `/` separates a stack from a provide in a key",
            ),
            (
                "../evil",
                "and climbs out of the directory the answer belongs in",
            ),
            (".hidden", "a leading dot is not a name"),
        ] {
            let d = dir_with(&[(
                "m.toml",
                &format!("[[marker]]\nfile  = \"mix.exs\"\nstack = \"{stack}\"\n"),
            )]);
            assert!(
                markers(d.path()).is_err(),
                "`{stack}` must be refused — {why}"
            );
        }

        // And a real one still loads, or the rule is only a wall.
        let good = dir_with(&[(
            "m.toml",
            "[[marker]]\nfile = \"mix.exs\"\nstack = \"elixir\"\n",
        )]);
        assert_eq!(markers(good.path()).unwrap().len(), 1);
    }
    /// halves are checked here because a blank one matches nothing and an
    /// absolute one matches every repo on the machine — the same rule a stack's
    /// own marker gets, for the same reason.
    #[test]
    fn every_shipped_marker_names_a_file_and_an_ecosystem() {
        let all = shipped_markers();
        assert!(all.len() >= 5, "a list this short proves nothing: {all:?}");
        for m in &all {
            assert!(!m.file.trim().is_empty() && !m.stack.trim().is_empty());
            assert_eq!(
                Path::new(&m.file).components().count(),
                1,
                "`{}` is not one filename inside the repo",
                m.file
            );
        }
        let names: std::collections::BTreeSet<&str> =
            all.iter().map(|m| m.stack.as_str()).collect();
        assert_eq!(names.len(), all.len(), "two markers claim one ecosystem");
    }

    /// Unclaimed means *here, and unanswered*. A marker for an ecosystem this
    /// repo is not asks nothing, and neither does one a stack now claims —
    /// including a stack the **repo itself** added, which is how answering the
    /// question stops it being asked again.
    #[test]
    fn a_marker_a_stack_now_claims_is_no_longer_unclaimed() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path();
        std::fs::write(repo.join("mix.exs"), "").unwrap();

        let all = shipped_markers();
        let asked: Vec<&str> = unclaimed(&all, &[], repo)
            .iter()
            .map(|m| m.stack.as_str())
            .collect();
        assert_eq!(asked, ["elixir"], "only the marker this repo actually has");

        let answered: Vec<Definition> = toml::from_str::<Definition>(
            "name = \"elixir\"\nmarker = \"mix.exs\"\n\n[[provide]]\n\
             name    = \"toolchain\"\nneeds   = [\"mix\"]\n\
             install = \"apt-get install -y elixir\"\nbecause = \"it builds\"\n",
        )
        .map(|d| vec![d])
        .unwrap();
        assert!(
            unclaimed(&all, &answered, repo).is_empty(),
            "a stack answering the question turns it off, whoever wrote it"
        );
    }

    // ── a repo's own stacks ─────────────────────────────────────────────────

    /// A repo may teach omh an ecosystem omh has never heard of, and that is
    /// the whole point of letting it write a stack file at all: a proprietary
    /// internal toolchain will never be upstreamed, and it still has to be
    /// installable.
    #[test]
    fn a_repo_may_add_an_ecosystem_omh_does_not_ship() {
        let catalogue = dir_with(&[("rust.toml", MINIMAL)]);
        let repo = dir_with(&[(
            "acme.toml",
            "name = \"acme\"\nmarker = \"acme.yaml\"\n\n\
             [[provide]]\nname    = \"toolchain\"\nneeds   = [\"acmec\"]\n\
             install = \"install-acme\"\nbecause = \"the internal compiler\"\n",
        )]);

        let all = load_all(catalogue.path(), repo.path()).unwrap();
        let names: Vec<&str> = all.iter().map(|d| d.name.as_str()).collect();
        assert_eq!(names, ["acme", "rust"], "both, sorted, from both places");
    }

    /// **It adds; it never shadows.** A repo file answering to a name omh ships
    /// is an error naming **both paths**, not a silent override.
    ///
    /// The same rule `merge_hooks` applies to a hook answering to a manifest
    /// name, for a stronger reason: a stack decides what goes into the image
    /// somebody's agent runs in. A repo that could redefine `rust` could point
    /// `rust/toolchain`'s `install` at anything, and the only sign would be a
    /// sandbox that built successfully.
    ///
    /// Enforced in the loader rather than at `init`, so launch, `doctor` and
    /// `why` inherit it — a guard only `init` applied would be a guard a repo
    /// bypasses by never being `init`ed.
    #[test]
    fn a_repo_may_not_answer_to_a_name_omh_ships() {
        let catalogue = dir_with(&[("rust.toml", MINIMAL)]);
        let repo = dir_with(&[("rust.toml", &MINIMAL.replace("Cargo.toml", "evil.toml"))]);

        let err = format!(
            "{:#}",
            load_all(catalogue.path(), repo.path())
                .expect_err("a repo may not redefine an ecosystem omh ships")
        );
        assert!(err.contains("rust"), "must name it: {err}");
        assert!(
            err.contains(&catalogue.path().display().to_string())
                && err.contains(&repo.path().display().to_string()),
            "and both files, or the fix is a guess: {err}"
        );
    }

    /// **Every shipped hook names a program its stack provisions.**
    ///
    /// The join between omh's hook opinion and the environment it builds, and
    /// the point is that neither side knows about the other: a hook file names
    /// a stack and a command, a stack file names what it installs, and nothing
    /// but this walks both. A disagreement is silent and expensive — omh ships
    /// a `gofmt -w .` hook while no provide installs `gofmt`, so the image
    /// builds, the measurement says `gofmt` is missing, and the hook a rust-shaped
    /// repo never wanted is held back for a reason nobody can fix from the repo.
    ///
    /// It also fixes the direction of the old guard. That one read
    /// `detect::conventional`, a `match` in Rust, so a contributor adding a
    /// stack had to edit code to give it hooks. Now both halves are data and
    /// this checks the data.
    ///
    /// **Node ships no hook on purpose**, which is why this iterates hooks
    /// rather than stacks: `npm test` is only a real command if a `test` script
    /// exists, and asserting one per stack would force a hook that fails on
    /// every turn in every node repo without one. Node's commands come from its
    /// own `scripts`, read by `derive` and written as repo hooks.
    #[test]
    fn every_shipped_hook_names_a_program_its_stack_provisions() {
        let defs = shipped();
        let mut checked = 0;
        for file in crate::bundled::Shipped::Hooks.files() {
            let hook = crate::hook::Hook::parse(file.contents, file.name)
                .unwrap_or_else(|e| panic!("{}: {e:#}", file.name));

            let Some(stack) = hook.stack.as_deref() else {
                // A hook that belongs to no ecosystem is claiming nothing about
                // one, so there is nothing here to check against.
                continue;
            };
            let def = defs
                .iter()
                .find(|d| d.name == stack)
                .unwrap_or_else(|| panic!("{}: names stack `{stack}`, which omh does not ship — it could never apply anywhere", file.name));
            let provisioned: Vec<&str> = def
                .provides
                .iter()
                .flat_map(|p| p.needs.iter().map(String::as_str))
                .collect();

            for command in hook.runs() {
                let Some(needed) = crate::detect::program(command) else {
                    panic!("{}: `{command}` names no program", file.name);
                };
                assert!(
                    provisioned.contains(&needed),
                    "{}: runs `{command}`, and no provide of `{stack}` installs \
                     `{needed}` — the hook would be held back in every repo that \
                     takes it. provisioned: {provisioned:?}",
                    file.name
                );
                checked += 1;
            }
        }
        assert!(
            checked >= 4,
            "only {checked} commands were checked — a hook catalogue this small \
             proves nothing about the join"
        );
    }

    /// Every provide states its case, and any cost it claims is one somebody
    /// could have taken.
    ///
    /// Deliberately **weaker** than `every_base_set_entry_states_its_case` in
    /// one place and exactly as strong in another. `measured` is optional here,
    /// because a stack can be contributed by somebody who works in that
    /// ecosystem and has no way to run an image build — demanding a number
    /// would either block the contribution or invite an invented one, and the
    /// second is worse.
    ///
    /// What is *not* relaxed: a measurement that is present must be true. The
    /// base set shipped fabricated dates once — every `on` read `2026-08-04`,
    /// one day before this repository existed, typed rather than taken — and
    /// the rule that catches that is shared with the base set rather than
    /// spelled again here.
    #[test]
    fn every_provide_states_its_case() {
        let stacks = shipped();
        assert!(!stacks.is_empty(), "omh ships no stacks at all");

        for s in &stacks {
            assert!(!s.marker.trim().is_empty(), "{}: no marker", s.name);
            assert!(
                !s.provides.is_empty(),
                "{}: provides nothing, so detecting it does nothing",
                s.name
            );
            for p in &s.provides {
                let label = format!("{}/{}", s.name, p.name);
                assert!(!p.because.trim().is_empty(), "{label}: no `because`");
                // Without this there is nothing for the probe to check, so the
                // provide's claim to have worked can never be tested — which is
                // the difference between an environment and a hope.
                assert!(
                    !p.needs.is_empty(),
                    "{label}: needs nothing, so nothing can verify it ran"
                );
                crate::base::assert_measured_states_its_case(&label, &p.measured);
            }
        }
    }

    /// A stack is one whose marker is on disk — and it is that stack and not a
    /// neighbour.
    ///
    /// Iterated over every shipped definition rather than over this repo's own
    /// `Cargo.toml`: a rust-shaped implementation passes a rust-only guard, and
    /// three quarters of what detection does would go unexercised. That is not
    /// hypothetical — the comment `detect::KNOWN` carried said exactly this
    /// about the guard it replaced.
    #[test]
    fn a_repo_is_the_stack_whose_marker_it_holds() {
        let stacks = shipped();
        for s in &stacks {
            let d = tempfile::tempdir().unwrap();
            std::fs::write(d.path().join(&s.marker), "").unwrap();

            let found: Vec<&str> = detected(&stacks, d.path())
                .iter()
                .map(|f| f.name.as_str())
                .collect();
            assert_eq!(
                found,
                [s.name.as_str()],
                "a repo holding only {} is {} and nothing else",
                s.marker,
                s.name
            );
        }
    }

    /// Guessing a stack writes hooks that fail on every turn. Detecting nothing
    /// is the correct outcome for a repo omh does not recognise.
    #[test]
    fn no_marker_is_no_stack_rather_than_a_guess() {
        let d = tempfile::tempdir().unwrap();
        std::fs::write(d.path().join("README.md"), "hello").unwrap();
        assert!(detected(&shipped(), d.path()).is_empty());
    }

    /// A polyglot repo is genuinely several stacks at once — which is why
    /// `load_dir` returns a set rather than picking a winner.
    #[test]
    fn a_repo_can_be_more_than_one_stack() {
        let stacks = shipped();
        let d = tempfile::tempdir().unwrap();
        for s in stacks.iter().take(2) {
            std::fs::write(d.path().join(&s.marker), "").unwrap();
        }
        assert_eq!(detected(&stacks, d.path()).len(), 2);
    }

    /// A marker claimed twice is two stacks fighting over one repo, and which
    /// wins would come down to filename order.
    #[test]
    fn no_two_shipped_stacks_claim_the_same_name_or_marker() {
        let stacks = shipped();
        for (i, a) in stacks.iter().enumerate() {
            for b in &stacks[i + 1..] {
                assert_ne!(a.name, b.name, "two stacks called {}", a.name);
                assert_ne!(
                    a.marker, b.marker,
                    "{} and {} both claim {}",
                    a.name, b.name, a.marker
                );
            }
        }
    }

    // ── recording the resolution ────────────────────────────────────────────

    fn shared(entries: &[(&str, bool)]) -> std::collections::BTreeMap<String, bool> {
        entries.iter().map(|(k, v)| (k.to_string(), *v)).collect()
    }

    fn fired(keys: &[&str]) -> std::collections::BTreeSet<String> {
        keys.iter().map(|k| k.to_string()).collect()
    }

    /// The one spelling, asserted literally — because it is a **committed file
    /// format**, not an internal detail.
    ///
    /// Every other test here computes both sides through `key`, so the suite
    /// stays self-consistent under any spelling: `"{provide}/{stack}"` and
    /// `"{stack}:{provide}"` both pass. But somebody who writes
    /// `"rust/linker" = false` into `.omh/settings.toml` — the opt-out
    /// `[provision]` exists for — has a literal in a file omh does not own.
    /// Change the speller and that line stops matching anything and is
    /// silently ignored: the provide is installed anyway, exit 0, no
    /// diagnostic. `docs/configuration.md` and every repo already using it
    /// spell it this way.
    #[test]
    fn a_provision_key_is_stack_slash_provide() {
        assert_eq!(key("rust", "linker"), "rust/linker");
    }

    /// **Only a person writes `false`.** omh records what applied, so a `false`
    /// can only have been typed — it is a decision, and re-running `init` is not
    /// consent to discard it. The predicate may say pnpm applies every time;
    /// somebody wrote down that this repo supplies it another way.
    #[test]
    fn a_recorded_false_survives_re_resolution() {
        let out = reconcile(&shared(&[("node/pnpm", false)]), &fired(&["node/pnpm"]));
        assert_eq!(out.get("node/pnpm"), Some(&false));
    }

    #[test]
    fn a_newly_fired_provide_is_recorded_true() {
        let out = reconcile(&shared(&[]), &fired(&["rust/toolchain"]));
        assert_eq!(out.get("rust/toolchain"), Some(&true));
    }

    /// The resolution describes what is true **now**, so a provide that stopped
    /// applying loses its entry rather than keeping a stale `true`.
    ///
    /// This is what makes the drift story honest: swap a `yarn.lock` for a
    /// `pnpm-lock.yaml`, re-run `init`, and the yarn entry goes. Left behind, it
    /// would keep yarn in the image for ever and the file would describe a repo
    /// that no longer exists.
    #[test]
    fn a_provide_that_stopped_applying_loses_its_entry() {
        let out = reconcile(&shared(&[("node/yarn", true)]), &fired(&["node/pnpm"]));
        assert_eq!(
            out.get("node/yarn"),
            None,
            "the stale entry is gone: {out:?}"
        );
        assert_eq!(out.get("node/pnpm"), Some(&true));
    }

    /// A provide that did not fire is not written at all — not `false`, which
    /// would be omh recording a decision nobody made, in a committed file,
    /// where it then looks exactly like one somebody did make.
    #[test]
    fn nothing_is_invented_for_a_provide_that_never_fired() {
        let out = reconcile(&shared(&[]), &fired(&[]));
        assert!(out.is_empty(), "invented: {out:?}");
    }

    // ── predicates ──────────────────────────────────────────────────────────

    fn ask(candidates: &[(&str, Option<&str>)], cwd: &Path) -> Vec<(String, Verdict)> {
        let owned: Vec<(String, Option<&str>)> = candidates
            .iter()
            .map(|(k, w)| ((*k).to_string(), *w))
            .collect();
        let out = crate::doctor::run_probe_in(&predicate_script(&owned), cwd);
        crate::doctor::parse(&out)
            .iter()
            .map(|o| (o.name.clone(), verdict(o)))
            .collect()
    }

    /// Exit zero applies, exit one does not. The two ordinary answers, run
    /// through a real `/bin/sh` and parsed back through the shared wire format
    /// — because a predicate is a program, and asserting on the script's text
    /// would prove only that it mentions the right words.
    #[test]
    fn exit_zero_applies_and_exit_one_does_not() {
        let d = tempfile::tempdir().unwrap();
        let got = ask(&[("x/a", Some("true")), ("x/b", Some("false"))], d.path());

        assert_eq!(
            got,
            vec![
                ("x/a".to_string(), Verdict::Applies),
                ("x/b".to_string(), Verdict::DoesNot),
            ]
        );
    }

    /// The third answer, and the one a shell cannot give directly: a command
    /// yields **one** exit code, and "false" and "broken" both come back
    /// non-zero. Reading anything above 1 as *could not answer* is what lets a
    /// two-valued mechanism carry the three-valued rule the rest of omh runs
    /// on — *cannot tell is never a licence to act*.
    ///
    /// The code travels with the verdict so a stack author can fix their
    /// predicate; a bare "did not apply" would send them looking at the repo.
    #[test]
    fn an_exit_above_one_could_not_answer_and_says_with_what_code() {
        let d = tempfile::tempdir().unwrap();
        let got = ask(
            &[("x/misuse", Some("exit 2")), ("x/odd", Some("exit 7"))],
            d.path(),
        );

        assert_eq!(
            got,
            vec![
                ("x/misuse".to_string(), Verdict::CouldNotAnswer(Some(2))),
                ("x/odd".to_string(), Verdict::CouldNotAnswer(Some(7))),
            ]
        );
    }

    /// A predicate that ends the shell must end only itself.
    ///
    /// Found by writing the test above with `exit 2` and getting **no output at
    /// all**: a bare `if exit 2; then` terminates the script, so every provide
    /// after it goes unanswered. That is a truncated report read as a complete
    /// one — the failure `main::fired_from` refuses at the other end of this
    /// same wire — arriving through a stack file rather than through a dying
    /// container.
    #[test]
    fn a_predicate_that_ends_the_shell_does_not_silence_the_rest() {
        let d = tempfile::tempdir().unwrap();
        let got = ask(
            &[("x/dies", Some("exit 3")), ("x/after", Some("true"))],
            d.path(),
        );

        assert_eq!(
            got,
            vec![
                ("x/dies".to_string(), Verdict::CouldNotAnswer(Some(3))),
                ("x/after".to_string(), Verdict::Applies),
            ]
        );
    }

    /// No condition is not a failed condition. A provide that always applies —
    /// `rust/toolchain`, every apt recipe — must not need a `when = "true"`
    /// incantation to say so.
    #[test]
    fn a_provide_with_no_condition_applies() {
        let d = tempfile::tempdir().unwrap();
        let got = ask(&[("x/always", None)], d.path());
        assert_eq!(got, vec![("x/always".to_string(), Verdict::Applies)]);
    }

    /// Predicates run against the repo, so they are written relative to it.
    #[test]
    fn a_predicate_reads_the_repo_it_runs_in() {
        let d = tempfile::tempdir().unwrap();
        std::fs::write(d.path().join("pnpm-lock.yaml"), "").unwrap();
        let got = ask(
            &[
                ("node/pnpm", Some("test -f pnpm-lock.yaml")),
                ("node/yarn", Some("test -f yarn.lock")),
            ],
            d.path(),
        );

        assert_eq!(got[0].1, Verdict::Applies, "the lockfile is here");
        assert_eq!(got[1].1, Verdict::DoesNot, "and this one is not");
    }

    /// Every shipped predicate, against a repo that is that stack and a repo
    /// that is empty — asserting only that each gives one of the three answers
    /// and writes nothing. What it *should* answer for a given repo is the
    /// stack author's business; that it answers at all, in the protocol, is
    /// omh's.
    #[test]
    fn every_shipped_predicate_answers_in_the_protocol() {
        for def in shipped() {
            let candidates: Vec<(String, Option<&str>)> = def
                .provides
                .iter()
                .map(|p| (key(&def.name, &p.name), p.when.as_deref()))
                .collect();
            if candidates.is_empty() {
                continue;
            }

            for populated in [false, true] {
                let d = tempfile::tempdir().unwrap();
                if populated {
                    std::fs::write(d.path().join(&def.marker), "{}").unwrap();
                }
                let before = std::fs::read_dir(d.path()).unwrap().flatten().count();

                let out = crate::doctor::run_probe_in(&predicate_script(&candidates), d.path());
                let answered = crate::doctor::parse(&out);
                assert_eq!(
                    answered.len(),
                    candidates.len(),
                    "{} answered {} of {} predicates: {out}",
                    def.name,
                    answered.len(),
                    candidates.len()
                );

                let after = std::fs::read_dir(d.path()).unwrap().flatten().count();
                assert_eq!(
                    before, after,
                    "{}'s predicates wrote into the repo — they are mounted \
                     read-only in the sandbox, so this would fail there instead",
                    def.name
                );
            }
        }
    }

    /// Predicates must see the checkout, and must not be able to change it.
    ///
    /// The counterpart to `image::probe_args`' mountless guard, and the reason
    /// these are two builders rather than one with a flag: a program probe that
    /// could see the host would answer about the wrong machine, and a predicate
    /// that could not see the repo could not answer at all. Each has an
    /// invariant the other would violate.
    ///
    /// Read-only for the reason `base::index_args` already records: something
    /// that reads code and can write into the checkout is a sandbox hole for no
    /// benefit.
    #[test]
    fn predicates_see_the_repo_and_can_only_read_it() {
        let args = predicate_args("omh/x:latest", Path::new("/host/wt"), "#!/bin/sh\ntrue\n");

        let mounts: Vec<&String> = args
            .iter()
            .zip(args.iter().skip(1))
            .filter(|(f, _)| *f == "-v")
            .map(|(_, spec)| spec)
            .collect();
        assert_eq!(mounts.len(), 1, "exactly one mount: {args:?}");
        assert!(
            mounts[0].starts_with("/host/wt:") && mounts[0].ends_with(":ro"),
            "and it is the repo, read-only: {}",
            mounts[0]
        );
        assert!(
            args.windows(2)
                .any(|w| w[0] == "-w" && w[1] == crate::container_workdir()),
            "a predicate written `test -f pnpm-lock.yaml` needs the repo as its \
             working directory: {args:?}"
        );
        assert!(args.contains(&"--rm".to_string()), "{args:?}");
        assert_eq!(args.last().map(String::as_str), Some("#!/bin/sh\ntrue\n"));
    }

    /// A predicate's own output must never reach the report channel.
    ///
    /// Predicate stdout and omh's protocol share one stream, and `doctor::parse`
    /// accepts a well-formed line from anywhere in it. So a predicate written
    /// without a redirect — `grep packageManager package.json`, no `-q` — prints
    /// **repo-controlled text** into the protocol. `omh init` runs against
    /// repositories you have just cloned and not read, and a fabricated
    /// `applies` line is written into a committed `[provision]` table and into
    /// an image recipe that runs as root.
    ///
    /// The shipped predicates all redirect, but that is discipline; this makes
    /// it structural. `a_hostile_key_cannot_corrupt_the_run` covers a hostile
    /// key from a stack file — this covers hostile content from the repo.
    #[test]
    fn a_predicate_that_prints_cannot_fabricate_a_verdict() {
        let d = tempfile::tempdir().unwrap();
        // A predicate that echoes repo content, and a repo whose content is a
        // forged protocol line for a provide nobody asked about.
        let forged = "ok\trust/toolchain\tapplies";
        std::fs::write(d.path().join("package.json"), forged).unwrap();

        let got = ask(&[("node/pnpm", Some("cat package.json"))], d.path());

        assert_eq!(
            got.len(),
            1,
            "the repo's content became a verdict of its own: {got:?}"
        );
        assert_eq!(
            got[0].0, "node/pnpm",
            "and it is the one omh asked: {got:?}"
        );
    }

    /// A key reaches the script from a stack file, so it is not omh's to trust.
    /// Same rule, same reason, and the same shape of assertion as
    /// `doctor::a_program_name_with_a_quote_cannot_corrupt_the_probe`: the key
    /// comes back exactly as it went in, which no expansion survives.
    #[test]
    fn a_hostile_key_cannot_corrupt_the_run() {
        let d = tempfile::tempdir().unwrap();
        let hostile = "x/$(echo pwned)";
        let owned = vec![
            (hostile.to_string(), Some("true")),
            ("x/after".to_string(), Some("true")),
        ];
        let out = crate::doctor::run_probe_in(&predicate_script(&owned), d.path());

        assert!(
            !out.lines().any(|l| l.trim() == "pwned"),
            "a key was expanded as shell: {out}"
        );
        let answered = crate::doctor::parse(&out);
        assert!(
            answered.iter().any(|o| o.name == hostile),
            "the key came back changed: {answered:?}"
        );
        assert!(
            answered.iter().any(|o| o.name == "x/after"),
            "and one hostile key must not cost the rest: {answered:?}"
        );
    }

    /// A marker is one filename inside the repo, and nothing else.
    ///
    /// `Path::join` **discards the base when given an absolute path**, so
    /// `marker = "/etc/hostname"` does not look inside the repo — it matches
    /// every repository on the machine, and every one of them then runs that
    /// stack's `install` as root in an image build. `..` escapes the checkout
    /// the same way, and a blank marker joins to the repo root itself, which
    /// always exists.
    ///
    /// The shipped files are reviewed; a repo-local one is not. It arrives in a
    /// checkout you have just cloned and never opened, and `load_all` reads it
    /// through this same validator — which is why the rule closed before the
    /// door it guards was opened, rather than after.
    #[test]
    fn a_marker_that_is_not_one_filename_inside_the_repo_is_refused() {
        for (marker, why) in [
            ("/etc/hostname", "absolute — `join` throws the repo away"),
            ("../../etc/hostname", "climbs out of the checkout"),
            ("", "joins to the repo root, which always exists"),
            ("a/b", "is a path rather than a marker"),
        ] {
            let body = MINIMAL.replace("Cargo.toml", marker);
            let d = dir_with(&[("rust.toml", &body)]);
            let Err(e) = load_dir(d.path()) else {
                panic!("accepted a marker that {why}: {marker:?}");
            };
            let err = format!("{e:#}");
            assert!(err.contains("rust.toml"), "must name the file: {err}");
        }
    }

    /// A name is half a `[provision]` key, and `key` joins the two with `/`.
    /// A stack `a/b` with provide `c` and a stack `a` with provide `b/c` mint
    /// the same key — so one person's `false` silently switches off somebody
    /// else's install, and `reconcile` cannot express one without the other.
    #[test]
    fn a_name_that_would_collide_in_a_provision_key_is_refused() {
        for (field, value) in [
            ("name   = \"rust\"", "name   = \"ru/st\""),
            ("name   = \"rust\"", "name   = \"\""),
        ] {
            let body = MINIMAL.replacen(field, value, 1);
            let d = dir_with(&[("rust.toml", &body)]);
            assert!(
                load_dir(d.path()).is_err(),
                "accepted a stack name that cannot key a provide: {value}"
            );
        }
    }

    /// Two provides of one name are one `[provision]` key and two installs.
    /// The whole case for pairing `needs` with `install` per provide is
    /// attribution — *"the `linker` provide ran and `cc` still does not
    /// resolve"* — and two `toolchain`s make that sentence ambiguous.
    #[test]
    fn two_provides_cannot_share_a_name() {
        let body = format!(
            "{MINIMAL}\n[[provide]]\nname    = \"toolchain\"\nneeds   = [\"rustc\"]\nbecause = \"again\"\n"
        );
        let d = dir_with(&[("rust.toml", &body)]);
        let Err(e) = load_dir(d.path()) else {
            panic!("accepted two provides called `toolchain`");
        };
        assert!(format!("{e:#}").contains("toolchain"), "must name it");
    }

    /// A `needs` entry is a program name — what the sandbox probe looks for
    /// with `command -v`.
    /// A blank one, or one carrying arguments, resolves nowhere — so it reports
    /// a permanent gap for a toolchain the user has, which is the expensive
    /// failure direction and the one `detect::program` returns `None` to avoid.
    ///
    /// Checked in `load_dir` rather than in the curation test, because the
    /// curation test only ever reads this source tree. Once `~/.omh/stacks`
    /// exists and can be edited, `load_dir` is the only thing standing between
    /// a typo and a sandbox that reports a missing compiler for ever.
    ///
    /// The bad provide is always the **second** one, and where the list can
    /// hold two, the bad entry is the second entry. A fixture with one provide
    /// carrying one need cannot tell a validator that checks everything from
    /// one that checks only the first of each — and `stacks/node.toml` ships
    /// four provides, `stacks/rust.toml` a provide with four needs, so the
    /// difference is the difference between a guard and a decoration.
    #[test]
    fn a_needs_entry_that_is_not_a_program_name_is_refused() {
        for (needs, why) in [
            (r#"[""]"#, "blank"),
            (r#"["cargo test"]"#, "carries arguments"),
            ("[]", "empty, so nothing can verify the provide"),
            (r#"["cc", ""]"#, "blank, in second position"),
            (
                r#"["cc", "cargo test"]"#,
                "carries arguments, in second position",
            ),
        ] {
            let body = format!(
                "{MINIMAL}\n[[provide]]\nname    = \"linker\"\nneeds   = {needs}\n\
                 because = \"rustc emits objects and something has to link them\"\n"
            );
            let d = dir_with(&[("rust.toml", &body)]);
            let Err(e) = load_dir(d.path()) else {
                panic!("a {why} `needs` was accepted: {body}");
            };
            let err = format!("{e:#}");
            assert!(err.contains("rust.toml"), "must name the file: {err}");
            assert!(
                err.contains("linker"),
                "and the provide, so the fix is findable: {err}"
            );
        }
    }

    /// Stacks are a **set**, not a versioned document. `Manifest::load_dir`
    /// picks a single winner by version and is right to — there is one base
    /// set. There are many stacks, and a repo may be more than one of them, so
    /// this follows `Adapter::load_dir` instead: every file, sorted, all of
    /// them real.
    #[test]
    fn every_file_in_the_directory_is_a_stack() {
        let d = dir_with(&[
            ("zebra.toml", &MINIMAL.replace("rust", "zebra")),
            ("alpha.toml", &MINIMAL.replace("rust", "alpha")),
        ]);
        let found = load_dir(d.path()).unwrap();

        let names: Vec<&str> = found.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(
            names,
            ["alpha", "zebra"],
            "every file, in a stable order — a stack directory is not a contest"
        );
    }

    /// A fresh install, or somebody who deleted the directory. Adapters answer
    /// this with an empty list rather than an error, and a repo with no stacks
    /// is a repo omh can still set up.
    #[test]
    fn a_missing_directory_is_no_stacks_rather_than_an_error() {
        let d = tempfile::tempdir().unwrap();
        let found = load_dir(&d.path().join("nothing-here")).unwrap();
        assert!(found.is_empty(), "got {found:?}");
    }

    /// A misspelled key must not be silently a stack that provisions nothing.
    /// The failure it would otherwise cause is invisible until somebody's
    /// sandbox is missing a compiler, which is the whole failure this module
    /// exists to end. `Adapter` and `Manifest` both deny unknown fields for the
    /// same reason.
    ///
    /// The stray key is **added** rather than substituted for `marker`.
    /// Renaming one reads the same on the surface and tests something else
    /// entirely: serde answers `missing field `marker`` first, which satisfies
    /// every assertion below while `deny_unknown_fields` is never reached —
    /// deleting the attribute left this green. Keeping the file otherwise
    /// valid means only the unknown key can refuse it.
    #[test]
    fn a_key_omh_does_not_understand_is_refused_by_name() {
        let d = dir_with(&[("rust.toml", &format!("mark = \"Cargo.toml\"\n{MINIMAL}"))]);
        let err = format!("{:#}", load_dir(d.path()).unwrap_err());

        assert!(err.contains("mark"), "must name the key: {err}");
        assert!(err.contains("rust.toml"), "and the file: {err}");
    }

    /// Anything that is not a `.toml` is somebody's editor swap file, or a
    /// `.yours` backup `install_bundled` wrote when it replaced a managed file.
    /// Reading one as a stack would turn a saved edit into a parse error on
    /// every command.
    #[test]
    fn only_toml_files_are_read() {
        let d = dir_with(&[
            ("rust.toml", MINIMAL),
            ("rust.toml.yours", "this is not toml at all {{{"),
            ("notes.md", "nor is this"),
        ]);
        let found = load_dir(d.path()).unwrap();
        assert_eq!(found.len(), 1, "got {found:?}");
    }

    // ── candidate guards (mutation testing) ─────────────────────────────────

    /// A marker needs **both** halves and a **relative** file. An empty `stack`
    /// names nothing to write; an absolute `file` exists in every repo on the
    /// machine, so every project on it would be asked the same question.
    ///
    /// The same rule a stack's own marker gets, and it had the same reason and
    /// none of the coverage.
    #[test]
    fn a_marker_needs_both_halves_and_a_file_inside_the_repo() {
        for (why, body) in [
            (
                "no stack to name the file omh would write",
                "[[marker]]\nfile = \"mix.exs\"\nstack = \"\"\n",
            ),
            (
                "no file to look for",
                "[[marker]]\nfile = \"\"\nstack = \"elixir\"\n",
            ),
            (
                "an absolute path is in every repo on the machine",
                "[[marker]]\nfile = \"/etc/passwd\"\nstack = \"elixir\"\n",
            ),
            (
                "a path is not one filename inside the repo",
                "[[marker]]\nfile = \"../mix.exs\"\nstack = \"elixir\"\n",
            ),
        ] {
            let dir = dir_with(&[("m.toml", body)]);
            assert!(markers(dir.path()).is_err(), "{why}: accepted {body:?}");
        }
    }

    /// **The order the questions come in is stable.** One decline stops the
    /// exchange, so the order decides which single question a polyglot repo is
    /// ever asked — and `read_dir` order is neither stable nor meaningful.
    #[test]
    fn markers_are_returned_in_a_stable_order() {
        let dir = dir_with(&[
            (
                "z.toml",
                "[[marker]]\nfile = \"mix.exs\"\nstack = \"elixir\"\n",
            ),
            (
                "a.toml",
                "[[marker]]\nfile = \"Gemfile\"\nstack = \"ruby\"\n\n\
                 [[marker]]\nfile = \"composer.json\"\nstack = \"php\"\n",
            ),
        ]);
        let got: Vec<String> = markers(dir.path())
            .unwrap()
            .into_iter()
            .map(|m| m.stack)
            .collect();
        assert_eq!(
            got,
            ["elixir", "php", "ruby"],
            "sorted by stack, whatever order the files were read in"
        );
    }
}