runner-manager 0.4.44

Local-first autoscaling manager for ephemeral GitHub Actions self-hosted runners, with a CLI and a Ratatui TUI.
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
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
// owner: a1-command-accountability
//
// ----------------------------------------------------------------------------
// EVERY PUBLISHED COMMAND LEAF IS ACCOUNTED FOR, OR THE BUILD IS RED.
// ----------------------------------------------------------------------------
// `.taskflow/2026-09-10-cli-chains-acceptance/02-target-architecture.md` ¶4:
// the combinatorial chain generator deliberately does NOT execute `daemon run`,
// `service install`/`uninstall`, `update`, `tui`, hidden commands, or real WSL
// operations. That is only safe if the leaves it skips are skipped on purpose
// and are covered somewhere else, so this manifest maps every published leaf to
// exactly one of five coverage classes and names the tests that carry it.
//
// The manifest is not a second copy of clap's tree. The leaf inventory it is
// checked against is derived from `SURFACE` in `cli_command_surface.rs`, which
// that file already pins against the real `--help` in both directions, and
// `cli_command_surface.rs` also re-walks the live `--help` tree against this
// manifest. So a new clap leaf fails the surface tests; a new `SURFACE` entry
// fails here until somebody reviews it and writes its row.
//
// ----------------------------------------------------------------------------
// WHAT A ROW HAS TO PROVE.
// ----------------------------------------------------------------------------
// 1. Its leaf is published (not stale, not hidden) and appears once.
// 2. Every piece of evidence is a real `#[test]` function at a repository path,
//    found by reading the file rather than trusted from the row.
// 3. A row outside `Generated` names a typed safety boundary and a concrete
//    reason. "Not modelled" alone is not one (`03-coverage-model.md`,
//    "Command accountability").
// 4. A `Privileged` row cites an `#[ignore]`d test that a workflow runs by name
//    with `--ignored`; every other row cites at least one test that runs,
//    unconditionally, in the default `cargo nextest run --workspace`.
//
// ----------------------------------------------------------------------------
// FINAL CROSS-TRACK EVIDENCE.
// ----------------------------------------------------------------------------
// Every `Generated` row cites the default 256+ case real-process run plus the
// checked-in inventory and pairwise-witness contracts. Every `Scripted` row
// cites the default 32+ case WSL run plus its inventory contract. These shared
// constants keep a leaf from quietly retaining pre-corpus evidence after the
// corpus or its authoritative test is renamed.

use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;

/// Where a leaf's behaviour is proved, one class per published leaf.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Coverage {
    /// Modelled local chain: executed by the black-box chain generator against
    /// an isolated data root, through real `runner-manager` processes.
    Generated,
    /// Scripted WSL chain: driven through the private `Workstation` harness in
    /// `crates/app/src/cli/wsl_acceptance.rs` over `ScriptedRunner`.
    Scripted,
    /// An existing dedicated acceptance test outside the generator.
    Dedicated,
    /// A privileged CI test: `#[ignore]`d locally, run by name in a workflow.
    Privileged,
    /// An intentionally non-executable surface check (`--help`/parse only).
    SurfaceOnly,
}

impl Coverage {
    /// Whether the combinatorial local-chain generator executes this leaf.
    /// Every other class is an exclusion and must say why.
    pub const fn is_generated(self) -> bool {
        matches!(self, Self::Generated)
    }
}

/// The reason a leaf is kept out of generated execution. Typed on purpose: the
/// set is reviewed here, and "not modelled" cannot be spelled as one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Boundary {
    NonTerminating,
    HostServiceManager,
    SelfReplacingDownload,
    TerminalOwnership,
    WslPlatform,
    LivePermissionProbe,
    ProfileStateSpace,
    RunnerEnvironmentFile,
    HostConfiguration,
    DependencyCacheFile,
    DockerResourceJournal,
}

impl Boundary {
    pub const fn describe(self) -> &'static str {
        match self {
            Self::DockerResourceJournal => {
                "reads or changes an attempt-scoped Docker resource journal and local engine state outside the generated policy/workspace oracle"
            }
            Self::NonTerminating => {
                "runs until it is signalled, so a chain would never reach its next action"
            }
            Self::HostServiceManager => {
                "reads or changes the machine-wide service manager, outside every \
                 scenario's temporary roots"
            }
            Self::SelfReplacingDownload => {
                "downloads a release and replaces the executable under test"
            }
            Self::TerminalOwnership => {
                "takes over the controlling terminal and waits for operator input"
            }
            Self::WslPlatform => {
                "addresses real wsl.exe, distribution, and Task Scheduler state unless \
                 driven through the scripted WSL seam"
            }
            Self::LivePermissionProbe => {
                "queries live GitHub permission state rather than only local persisted state"
            }
            Self::ProfileStateSpace => {
                "creates and selects multiple PolicyIds for one repository, including execution and selector state absent from the single-policy chain oracle"
            }
            Self::RunnerEnvironmentFile => {
                "reads or rewrites the host's runner.env, a file outside the chain oracle's \
                 modelled state whose only effect is on a native runner's environment at launch"
            }
            Self::HostConfiguration => {
                "reads or changes machine-wide operating-system settings (registry, Defender, \
                 git's system configuration, Spotlight) outside every scenario's temporary roots"
            }
            Self::DependencyCacheFile => {
                "reads or rewrites the host's caches.toml, or measures the cache root, outside the chain oracle's modelled state; its only effect is on a native runner's environment at launch and on which idle cache directories exist"
            }
        }
    }
}

/// Why a leaf is excluded from generated execution.
#[derive(Clone, Copy, Debug)]
pub struct Exclusion {
    pub boundary: Boundary,
    /// The leaf-specific consequence of the boundary, in a sentence a reviewer
    /// can check against the code.
    pub reason: &'static str,
}

/// One test function, by repository-relative path and name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Evidence {
    pub file: &'static str,
    pub test: &'static str,
}

/// One published leaf's reviewed classification.
#[derive(Clone, Copy, Debug)]
pub struct Classification {
    /// `family` or `family subcommand`, exactly as `--help` spells it.
    pub leaf: &'static str,
    pub coverage: Coverage,
    pub evidence: &'static [Evidence],
    /// Required for every class except [`Coverage::Generated`], forbidden for it.
    pub exclusion: Option<Exclusion>,
}

const fn at(file: &'static str, test: &'static str) -> Evidence {
    Evidence { file, test }
}

const AUTH_STATES: &str = "crates/app/tests/auth_states.rs";
const LOCAL_CHAIN_ACCEPTANCE: &str = "crates/app/tests/cli_chains_acceptance.rs";
const LOCAL_CHAIN_MODEL: &str = "crates/app/tests/cli_chains_model.rs";
const SURFACE_TESTS: &str = "crates/app/tests/cli_command_surface.rs";
const DAEMON_UNIT: &str = "crates/app/src/cli/daemon.rs";
const SERVICE_UNIT: &str = "crates/app/src/cli/service.rs";
const PRIVILEGED_SERVICE: &str = "crates/platform/tests/privileged_service_installer.rs";
const PRIVILEGED_WSL: &str = "crates/platform/tests/privileged_wsl_lifecycle.rs";
const TUI_SHELL: &str = "crates/app/src/tui/shell.rs";
const UPDATE: &str = "crates/app/tests/update_command.rs";
const WSL_ACCEPTANCE: &str = "crates/app/src/cli/wsl_acceptance.rs";
const PROFILE_COMMANDS: &str = "crates/app/tests/profile_commands.rs";
const RUNNER_ENV_COMMANDS: &str = "crates/app/tests/runner_env_commands.rs";
const HOST_DOCTOR_COMMANDS: &str = "crates/app/tests/host_doctor_commands.rs";
const DEPENDENCY_CACHE_COMMANDS: &str = "crates/app/tests/dependency_cache_commands.rs";
const POLL_INTERVAL_COMMANDS: &str = "crates/app/tests/poll_interval_commands.rs";

pub const LOCAL_CHAIN_EVIDENCE: &[Evidence] = &[
    at(
        LOCAL_CHAIN_ACCEPTANCE,
        "the_complete_local_corpus_agrees_with_the_model_through_real_processes",
    ),
    at(
        LOCAL_CHAIN_MODEL,
        "the_inventory_holds_at_least_256_meaningful_local_cases",
    ),
    at(
        LOCAL_CHAIN_MODEL,
        "case_identifiers_are_sequential_unique_and_round_trip",
    ),
    at(
        LOCAL_CHAIN_MODEL,
        "every_compatible_mutating_pair_has_a_named_witness",
    ),
];

pub const WSL_CHAIN_EVIDENCE: &[Evidence] = &[
    at(
        WSL_ACCEPTANCE,
        "the_inventory_holds_at_least_32_distinct_named_cases_covering_every_state",
    ),
    at(
        WSL_ACCEPTANCE,
        "every_case_in_the_inventory_runs_exactly_once_and_matches_its_transitions",
    ),
];

const fn generated(leaf: &'static str) -> Classification {
    Classification {
        leaf,
        coverage: Coverage::Generated,
        evidence: LOCAL_CHAIN_EVIDENCE,
        exclusion: None,
    }
}

const fn scripted(leaf: &'static str) -> Classification {
    Classification {
        leaf,
        coverage: Coverage::Scripted,
        evidence: WSL_CHAIN_EVIDENCE,
        exclusion: Some(Exclusion {
            boundary: Boundary::WslPlatform,
            reason: WSL_REASON,
        }),
    }
}

const WSL_REASON: &str = "Every `wsl` leaf drives `wsl.exe` on the host (and `install` also \
     Task Scheduler and a credential device flow). Ordinary CI legs have no provisioned \
     distribution, so these run only through the scripted `Workstation` seam, never as \
     real processes in a local chain.";

macro_rules! profile_row {
    ($leaf:literal, $test:literal) => {
        Classification {
            leaf: $leaf,
            coverage: Coverage::Dedicated,
            evidence: &[at(PROFILE_COMMANDS, $test)],
            exclusion: Some(Exclusion {
                boundary: Boundary::ProfileStateSpace,
                reason: "This command addresses one of several repository PolicyIds; dedicated real-process tests check selected mutations and sibling preservation while the existing generated oracle models single-policy repositories.",
            }),
        }
    };
}

macro_rules! runner_env_row {
    ($leaf:literal, $test:literal) => {
        Classification {
            leaf: $leaf,
            coverage: Coverage::Dedicated,
            evidence: &[at(RUNNER_ENV_COMMANDS, $test)],
            exclusion: Some(Exclusion {
                boundary: Boundary::RunnerEnvironmentFile,
                reason: "runner.env changes nothing the generated oracle observes: no policy, attempt, root or credential, only what a launched native runner inherits. Dedicated real-process tests drive set, unset and show against the file under --data-dir and pin the refusals.",
            }),
        }
    };
}

macro_rules! cache_row {
    ($leaf:literal, $test:literal) => {
        Classification {
            leaf: $leaf,
            coverage: Coverage::Dedicated,
            evidence: &[at(DEPENDENCY_CACHE_COMMANDS, $test)],
            exclusion: Some(Exclusion {
                boundary: Boundary::DependencyCacheFile,
                reason: "caches.toml changes nothing the generated oracle observes: no policy, attempt, root or credential, only the variables a launched native runner gets. Dedicated real-process tests drive every leaf against the file under --data-dir and pin the refusals; selection, leasing and pruning are unit-tested in the platform crate.",
            }),
        }
    };
}

macro_rules! host_doctor_row {
    ($leaf:literal, $test:literal, $reason:literal) => {
        Classification {
            leaf: $leaf,
            coverage: Coverage::Dedicated,
            evidence: &[at(HOST_DOCTOR_COMMANDS, $test)],
            exclusion: Some(Exclusion {
                boundary: Boundary::HostConfiguration,
                reason: $reason,
            }),
        }
    };
}

/// The reviewed classification of every published leaf.
pub const MANIFEST: &[Classification] = &[
    Classification {
        leaf: "host docker-cleanup show",
        coverage: Coverage::Dedicated,
        evidence: &[at(
            "crates/app/tests/native_docker_cleanup.rs",
            "host_controls_default_to_report_and_do_not_walk_caches_or_workspaces",
        )],
        exclusion: Some(Exclusion {
            boundary: Boundary::DockerResourceJournal,
            reason: "Reports Docker cleanup support and configuration, which are outside the generated policy oracle; the dedicated cross-platform CLI test checks report defaults and Windows refusal without touching caches.",
        }),
    },
    Classification {
        leaf: "host docker-cleanup set-mode",
        coverage: Coverage::Dedicated,
        evidence: &[at(
            "crates/app/tests/native_docker_cleanup.rs",
            "host_controls_default_to_report_and_do_not_walk_caches_or_workspaces",
        )],
        exclusion: Some(Exclusion {
            boundary: Boundary::DockerResourceJournal,
            reason: "Changes docker-cleanup.json rather than policy state; dedicated CLI tests round-trip the modes on Linux and prove unsupported Windows commands write no configuration.",
        }),
    },
    Classification {
        leaf: "host docker-cleanup report",
        coverage: Coverage::Dedicated,
        evidence: &[
            at(
                "crates/app/tests/native_docker_cleanup.rs",
                "host_controls_default_to_report_and_do_not_walk_caches_or_workspaces",
            ),
            at(
                "crates/agent/src/docker_cleanup/tests.rs",
                "report_is_read_only_and_apply_deletes_owned_resources_in_dependency_order",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::DockerResourceJournal,
            reason: "Inventories exact attempt-owned Docker resources outside the generated filesystem oracle; dedicated CLI and engine-port tests prove read-only reporting and leave unrelated state untouched.",
        }),
    },
    Classification {
        leaf: "host docker-cleanup sweep",
        coverage: Coverage::Dedicated,
        evidence: &[
            at(
                "crates/app/tests/native_docker_cleanup.rs",
                "host_controls_default_to_report_and_do_not_walk_caches_or_workspaces",
            ),
            at(
                "crates/agent/src/docker_cleanup/tests.rs",
                "report_is_read_only_and_apply_deletes_owned_resources_in_dependency_order",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::DockerResourceJournal,
            reason: "Sweeps journalled Docker resources instead of policy workspaces; dedicated CLI and engine-port tests cover mode gating, dependency-order deletion and no host-wide prune, with explicit live Linux acceptance for actual engine effects.",
        }),
    },
    // -- auth: sign-in state is modelled as credential presence -------------
    generated("auth login"),
    Classification {
        leaf: "auth status",
        coverage: Coverage::Dedicated,
        evidence: &[
            at(
                AUTH_STATES,
                "a_machine_with_no_credential_reports_not_authenticated",
            ),
            at(
                AUTH_STATES,
                "an_accepted_credential_reports_what_it_can_reach",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::LivePermissionProbe,
            reason: "Unlike the local model's credential-presence setup, `auth status` performs \
                     live GitHub permission probes. Its dedicated loopback tests exercise those \
                     responses without making the generated local corpus depend on GitHub.",
        }),
    },
    generated("auth logout"),
    // -- host ----------------------------------------------------------------
    generated("host set-capacity"),
    Classification {
        leaf: "host set-auto-update",
        coverage: Coverage::Dedicated,
        evidence: &[
            at(
                "crates/app/tests/auto_update_commands.rs",
                "auto_update_defaults_and_explicit_preferences_round_trip",
            ),
            at(
                "crates/app/tests/auto_update_commands.rs",
                "invalid_auto_update_value_preserves_preference",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::HostConfiguration,
            reason: "Automatic updates configure application release installation, outside the generated policy and runner oracle. Dedicated process tests cover default opt-in, both boolean values, persistence and invalid-value refusal without networking or installing a release.",
        }),
    },
    Classification {
        leaf: "host set-poll-interval",
        coverage: Coverage::Dedicated,
        evidence: &[
            at(
                POLL_INTERVAL_COMMANDS,
                "host_set_poll_interval_round_trips_through_polling_toml_and_the_host_row",
            ),
            at(
                POLL_INTERVAL_COMMANDS,
                "host_set_poll_interval_refuses_what_the_daemon_would_refuse_and_writes_nothing",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::HostConfiguration,
            reason: "The intervals change only how often the daemon polls GitHub, which the \
                     generated oracle does not model: no policy, attempt, root or credential. \
                     Dedicated real-process tests drive both flags against polling.toml and the \
                     host row under --data-dir, read them back through status and host show, \
                     and pin every refusal and that it writes nothing.",
        }),
    },
    generated("host set-runtime-root"),
    generated("host reset-runtime-root"),
    generated("host show"),
    Classification {
        leaf: "host isolation status",
        coverage: Coverage::Dedicated,
        evidence: &[at(
            PROFILE_COMMANDS,
            "isolated_configuration_is_pinned_and_cannot_arm_without_provider",
        )],
        exclusion: Some(Exclusion {
            boundary: Boundary::ProfileStateSpace,
            reason: "Reports the execution providers for profiles; a dedicated JSON-schema test covers this new capability document outside the single-policy generated oracle.",
        }),
    },
    runner_env_row!(
        "host env show",
        "host_env_set_show_and_unset_round_trip_through_runner_env"
    ),
    runner_env_row!(
        "host env set",
        "host_env_refuses_what_the_daemon_would_refuse_and_writes_nothing"
    ),
    runner_env_row!(
        "host env unset",
        "host_env_set_show_and_unset_round_trip_through_runner_env"
    ),
    host_doctor_row!(
        "host doctor",
        "host_doctor_reports_the_versioned_document_and_exits_unfit_on_a_required_failure",
        "Its answer is a reading of this machine's registry, Defender, git and service account, \
         which the generated oracle does not model; a dedicated real-process test pins the JSON \
         document and the host_unfit exit against a required tool that cannot be on PATH."
    ),
    host_doctor_row!(
        "host prepare",
        "host_prepare_without_a_terminal_or_yes_changes_nothing",
        "Applying a fix changes machine-wide settings and asks for administrator rights, which \
         no CI leg may do to its host; a real-process test pins that nothing is applied without \
         consent, and the planner, elevation and revert logic are unit-tested against fakes."
    ),
    host_doctor_row!(
        "host required-tools",
        "host_required_tools_round_trip_under_the_data_dir",
        "The list lives in its own file under config/ and changes only what the doctor and the \
         daemon's preflight require; a real-process test drives set, show and clear and pins \
         the refusal of a path-like name."
    ),
    host_doctor_row!(
        "host forget-local",
        "host_forget_local_archives_the_configuration_and_deletes_nothing",
        "It renames this account's configuration directory's contents aside, which the \
         generated oracle does not model, and its refusals depend on the machine's service \
         manager; a real-process test pins the archive under --data-dir, and the refusals and \
         the untouched service root are unit-tested against recording controls."
    ),
    cache_row!(
        "host cache show",
        "host_cache_settings_round_trip_through_caches_toml"
    ),
    cache_row!(
        "host cache set-enabled",
        "host_cache_settings_round_trip_through_caches_toml"
    ),
    cache_row!(
        "host cache set-root",
        "host_cache_refuses_what_the_daemon_would_refuse_and_writes_nothing"
    ),
    cache_row!(
        "host cache reset-root",
        "host_cache_settings_round_trip_through_caches_toml"
    ),
    cache_row!(
        "host cache set-max-size",
        "host_cache_settings_round_trip_through_caches_toml"
    ),
    cache_row!(
        "host cache set-tool",
        "host_cache_settings_round_trip_through_caches_toml"
    ),
    cache_row!(
        "host cache prune",
        "host_cache_prune_measures_and_keeps_what_fits"
    ),
    // -- repo ----------------------------------------------------------------
    generated("repo add"),
    generated("repo list"),
    generated("repo set-capacity"),
    generated("repo set-scale"),
    generated("repo add-label"),
    generated("repo remove-label"),
    generated("repo set-workspace"),
    generated("repo remove"),
    profile_row!(
        "repo profile add",
        "named_profiles_select_one_policy_and_legacy_ambiguity_is_closed"
    ),
    profile_row!(
        "repo profile list",
        "profile_commands_mutate_and_remove_only_the_selected_sibling"
    ),
    profile_row!(
        "repo profile show",
        "profile_commands_mutate_and_remove_only_the_selected_sibling"
    ),
    profile_row!(
        "repo profile set-capacity",
        "named_profiles_select_one_policy_and_legacy_ambiguity_is_closed"
    ),
    profile_row!(
        "repo profile set-scale",
        "isolated_configuration_is_pinned_and_cannot_arm_without_provider"
    ),
    profile_row!(
        "repo profile add-label",
        "profile_commands_mutate_and_remove_only_the_selected_sibling"
    ),
    profile_row!(
        "repo profile remove-label",
        "profile_commands_mutate_and_remove_only_the_selected_sibling"
    ),
    profile_row!(
        "repo profile set-workspace",
        "profile_commands_mutate_and_remove_only_the_selected_sibling"
    ),
    profile_row!(
        "repo profile set-execution",
        "profile_commands_mutate_and_remove_only_the_selected_sibling"
    ),
    profile_row!(
        "repo profile remove",
        "profile_commands_mutate_and_remove_only_the_selected_sibling"
    ),
    cache_row!(
        "repo cache show",
        "repo_and_org_cache_settings_scope_one_target"
    ),
    cache_row!(
        "repo cache set-enabled",
        "repo_and_org_cache_settings_scope_one_target"
    ),
    cache_row!(
        "repo cache set-namespace",
        "repo_and_org_cache_settings_scope_one_target"
    ),
    cache_row!(
        "repo cache set-tool",
        "repo_and_org_cache_settings_scope_one_target"
    ),
    // -- org -----------------------------------------------------------------
    generated("org add"),
    generated("org list"),
    generated("org set-capacity"),
    generated("org set-scale"),
    generated("org add-label"),
    generated("org remove-label"),
    generated("org remove"),
    cache_row!(
        "org cache show",
        "repo_and_org_cache_settings_scope_one_target"
    ),
    cache_row!(
        "org cache set-enabled",
        "repo_and_org_cache_settings_scope_one_target"
    ),
    cache_row!(
        "org cache set-namespace",
        "repo_and_org_cache_settings_scope_one_target"
    ),
    cache_row!(
        "org cache set-tool",
        "repo_and_org_cache_settings_scope_one_target"
    ),
    // -- daemon --------------------------------------------------------------
    Classification {
        leaf: "daemon run",
        coverage: Coverage::Dedicated,
        evidence: &[
            at(
                SURFACE_TESTS,
                "daemon_run_refuses_a_second_instance_without_prompting",
            ),
            at(
                DAEMON_UNIT,
                "shutdown_loop_supervises_a_busy_child_to_completion_without_terminating_it",
            ),
            at(
                PRIVILEGED_SERVICE,
                "production_daemon_entrypoint_reaches_running_and_handles_scm_stop",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::NonTerminating,
            reason: "`daemon run` is the long-lived host agent: it takes the single-instance \
                     lock and supervises runners until a stop signal arrives, so it cannot be \
                     one step of a chain. Its supervision loop is tested in-process and its \
                     lock refusal through the real binary.",
        }),
    },
    // -- service -------------------------------------------------------------
    Classification {
        leaf: "service install",
        coverage: Coverage::Privileged,
        evidence: &[
            at(
                PRIVILEGED_SERVICE,
                "install_status_and_uninstall_round_trip_against_the_real_service_manager",
            ),
            at(
                SERVICE_UNIT,
                "the_service_binary_is_a_copy_this_product_owns_and_reinstalling_replaces_it",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::HostServiceManager,
            reason: "Registers the product with the machine's real service manager and copies \
                     the binary to an owned location; a generated run would leave a machine-wide \
                     registration behind. Only the Windows privileged job performs it, under \
                     fixture names with a leak check.",
        }),
    },
    Classification {
        leaf: "service uninstall",
        coverage: Coverage::Privileged,
        evidence: &[
            at(
                PRIVILEGED_SERVICE,
                "uninstall_leaves_configuration_sqlite_secrets_and_cache_byte_for_byte",
            ),
            at(
                PRIVILEGED_SERVICE,
                "install_status_and_uninstall_round_trip_against_the_real_service_manager",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::HostServiceManager,
            reason: "Removes a machine-wide service registration; under a generator it could \
                     remove the operator's own installation. It runs only against fixture \
                     registrations in the privileged job.",
        }),
    },
    Classification {
        leaf: "service status",
        coverage: Coverage::Dedicated,
        evidence: &[
            at(
                SURFACE_TESTS,
                "service_status_runs_unattended_and_reports_offline_honestly",
            ),
            at(
                SURFACE_TESTS,
                "the_suite_asks_about_a_disposable_registration_and_says_which_one",
            ),
            at(
                SERVICE_UNIT,
                "stale_binary_status_prints_the_diagnosis_and_returns_an_error",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::HostServiceManager,
            reason: "Queries the host's service manager, which `--data-dir` does not move, so \
                     its answer depends on what is installed on the machine. Its dedicated \
                     tests pin the fixture service-name tag that isolates it.",
        }),
    },
    // -- tui -----------------------------------------------------------------
    Classification {
        leaf: "tui",
        coverage: Coverage::Dedicated,
        evidence: &[
            at(
                TUI_SHELL,
                "tui_refuses_captured_or_redirected_stdio_instead_of_waiting_for_events",
            ),
            at(
                TUI_SHELL,
                "production_shell_routes_navigation_filter_activation_and_render_to_screen_model",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::TerminalOwnership,
            reason: "Enters raw mode and the alternate screen and runs an event loop until the \
                     operator quits; with captured stdio it refuses instead. Its reducer, input \
                     and render paths are tested in-process against recorded sessions.",
        }),
    },
    // -- status: the modelled readback ---------------------------------------
    generated("status"),
    // -- update --------------------------------------------------------------
    Classification {
        leaf: "update",
        coverage: Coverage::Dedicated,
        evidence: &[
            at(UPDATE, "a_newer_release_replaces_the_running_binary"),
            at(UPDATE, "check_reports_the_new_version_and_changes_nothing"),
            at(
                UPDATE,
                "a_substituted_archive_is_refused_and_nothing_is_installed",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::SelfReplacingDownload,
            reason: "Without `--check` it downloads a release archive and replaces the running \
                     executable; even `--check` resolves a release channel. The dedicated suite \
                     drives it against a loopback asset source and a disposable binary copy.",
        }),
    },
    // -- wsl: the scripted seam ----------------------------------------------
    scripted("wsl list"),
    Classification {
        leaf: "wsl install",
        coverage: Coverage::Scripted,
        evidence: &[
            at(
                WSL_ACCEPTANCE,
                "the_inventory_holds_at_least_32_distinct_named_cases_covering_every_state",
            ),
            at(
                WSL_ACCEPTANCE,
                "every_case_in_the_inventory_runs_exactly_once_and_matches_its_transitions",
            ),
            at(
                PRIVILEGED_WSL,
                "the_rendered_task_is_one_task_scheduler_accepts_reads_back_and_removes",
            ),
        ],
        exclusion: Some(Exclusion {
            boundary: Boundary::WslPlatform,
            reason: WSL_REASON,
        }),
    },
    scripted("wsl status"),
    scripted("wsl detach"),
];

/// The surface test that proves the hidden bridges stay reachable and hidden.
/// Hidden commands are kept out of [`MANIFEST`]; this is what covers them.
pub const HIDDEN_BRIDGE_EVIDENCE: Evidence = at(
    SURFACE_TESTS,
    "every_hidden_bridge_still_parses_and_is_still_absent_from_help",
);

/// The leaves `02-target-architecture.md` ¶4 names as never executed by the
/// generator, transcribed by hand like `SURFACE` and for the same reason: a row
/// flipped to `Generated` must contradict the design, not quietly redefine it.
pub const NEVER_GENERATED: [&str; 9] = [
    "daemon run",
    "service install",
    "service uninstall",
    "update",
    "tui",
    "wsl list",
    "wsl install",
    "wsl status",
    "wsl detach",
];

// ---------------------------------------------------------------------------
// Defects
// ---------------------------------------------------------------------------

/// One way the manifest can be wrong. Checks collect every defect rather than
/// stopping at the first, so one run shows a reviewer the whole correction.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Defect {
    /// A published leaf with no row.
    Unclassified { leaf: String },
    /// A row whose leaf is not published.
    Stale { leaf: String },
    /// A leaf with more than one row.
    Duplicate { leaf: String, rows: usize },
    /// A row for a command that is deliberately hidden.
    HiddenLeafClassified { leaf: String },
    /// A row that cites no evidence at all.
    NoEvidence { leaf: String },
    /// A cited test that does not exist as a test.
    MissingEvidence {
        leaf: String,
        evidence: Evidence,
        why: String,
    },
    /// An exclusion from generated execution with no stated boundary.
    UnjustifiedExclusion { leaf: String, coverage: Coverage },
    /// An exclusion whose reason says nothing concrete.
    VagueExclusion {
        leaf: String,
        boundary: Boundary,
        reason: String,
    },
    /// A generated leaf that also claims a safety exclusion.
    GeneratedLeafExcluded { leaf: String },
    /// A leaf the architecture keeps out of the generator, classified into it.
    GeneratedAgainstArchitecture { leaf: String },
    /// A non-privileged row with no test that runs by default on every OS.
    NoDefaultRunEvidence { leaf: String },
    /// A privileged row with no `#[ignore]`d test that a workflow runs.
    NoPrivilegedEvidence { leaf: String },
    /// An `#[ignore]`d test no workflow runs by name, so it runs nowhere.
    IgnoredEvidenceNotWired { leaf: String, evidence: Evidence },
}

impl fmt::Display for Defect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unclassified { leaf } => write!(
                f,
                "`{leaf}` is published but has no classification; add a reviewed row to \
                 MANIFEST"
            ),
            Self::Stale { leaf } => write!(
                f,
                "`{leaf}` is classified but is not a published leaf; remove or rename the row"
            ),
            Self::Duplicate { leaf, rows } => {
                write!(f, "`{leaf}` has {rows} rows; a leaf has exactly one")
            }
            Self::HiddenLeafClassified { leaf } => write!(
                f,
                "`{leaf}` is a hidden command and must stay out of the public inventory"
            ),
            Self::NoEvidence { leaf } => write!(f, "`{leaf}` cites no evidence"),
            Self::MissingEvidence {
                leaf,
                evidence,
                why,
            } => write!(
                f,
                "`{leaf}` cites `{}::{}`, which is not existing evidence: {why}",
                evidence.file, evidence.test
            ),
            Self::UnjustifiedExclusion { leaf, coverage } => write!(
                f,
                "`{leaf}` is {coverage:?}, which excludes it from generated execution, but \
                 states no safety boundary"
            ),
            Self::VagueExclusion {
                leaf,
                boundary,
                reason,
            } => write!(
                f,
                "`{leaf}` is excluded because it {}, but its reason does not say what that \
                 means for this leaf: {reason:?}",
                boundary.describe()
            ),
            Self::GeneratedLeafExcluded { leaf } => write!(
                f,
                "`{leaf}` is Generated but also claims a safety exclusion; it is one or the other"
            ),
            Self::GeneratedAgainstArchitecture { leaf } => write!(
                f,
                "`{leaf}` is Generated, but `02-target-architecture.md` ¶4 keeps it out of \
                 the generator as long-lived, terminal-owning, self-replacing or host-mutating"
            ),
            Self::NoDefaultRunEvidence { leaf } => write!(
                f,
                "`{leaf}` cites no test that runs unconditionally in the default workspace \
                 test run"
            ),
            Self::NoPrivilegedEvidence { leaf } => write!(
                f,
                "`{leaf}` is Privileged but cites no `#[ignore]`d test that a workflow runs \
                 with `--ignored`"
            ),
            Self::IgnoredEvidenceNotWired { leaf, evidence } => write!(
                f,
                "`{leaf}` cites `{}::{}`, which is `#[ignore]`d and run by no workflow, so it \
                 verifies nothing",
                evidence.file, evidence.test
            ),
        }
    }
}

/// Renders a defect list for an assertion message.
pub fn report(defects: &[Defect]) -> String {
    defects
        .iter()
        .map(|defect| format!("  - {defect}"))
        .collect::<Vec<_>>()
        .join("\n")
}

// ---------------------------------------------------------------------------
// The inventory check: missing, stale, duplicate, hidden
// ---------------------------------------------------------------------------

/// Compares the rows with the published and hidden leaf sets.
pub fn inventory_defects(
    published: &[String],
    hidden: &[String],
    manifest: &[Classification],
) -> Vec<Defect> {
    let mut rows: BTreeMap<&str, usize> = BTreeMap::new();
    for row in manifest {
        *rows.entry(row.leaf).or_default() += 1;
    }

    let mut defects = Vec::new();
    for leaf in published {
        if !rows.contains_key(leaf.as_str()) {
            defects.push(Defect::Unclassified { leaf: leaf.clone() });
        }
    }
    for (leaf, count) in &rows {
        if hidden.iter().any(|hidden| hidden == leaf) {
            defects.push(Defect::HiddenLeafClassified {
                leaf: (*leaf).to_string(),
            });
        } else if !published.iter().any(|published| published == leaf) {
            defects.push(Defect::Stale {
                leaf: (*leaf).to_string(),
            });
        }
        if *count > 1 {
            defects.push(Defect::Duplicate {
                leaf: (*leaf).to_string(),
                rows: *count,
            });
        }
    }
    defects
}

/// Rows that classify a [`NEVER_GENERATED`] leaf as `Generated`. Such a row can
/// pass both other checks -- flipping the class and dropping the exclusion
/// leaves real evidence behind -- so the design's boundary is checked on its own.
pub fn architecture_defects(manifest: &[Classification]) -> Vec<Defect> {
    manifest
        .iter()
        .filter(|row| row.coverage.is_generated() && NEVER_GENERATED.contains(&row.leaf))
        .map(|row| Defect::GeneratedAgainstArchitecture {
            leaf: row.leaf.to_string(),
        })
        .collect()
}

// ---------------------------------------------------------------------------
// The justification check: evidence exists, exclusions are concrete
// ---------------------------------------------------------------------------

/// What the justification check reads. The repository in the real test; a
/// table of synthetic files in the controls that prove the check can fail.
pub trait EvidenceSource {
    /// A repository-relative file's text, or `None` when there is no such file.
    fn source(&self, file: &str) -> Option<String>;
    /// Every workflow under `.github/workflows/`, concatenated.
    fn workflows(&self) -> String;
}

/// The real repository, rooted at its top-level directory.
pub struct Repository {
    pub root: PathBuf,
}

impl EvidenceSource for Repository {
    fn source(&self, file: &str) -> Option<String> {
        std::fs::read_to_string(self.root.join(file))
            .ok()
            .map(|text| text.replace("\r\n", "\n"))
    }

    fn workflows(&self) -> String {
        let directory = self.root.join(".github").join("workflows");
        let Ok(entries) = std::fs::read_dir(&directory) else {
            return String::new();
        };
        let mut paths: Vec<PathBuf> = entries
            .filter_map(Result::ok)
            .map(|entry| entry.path())
            .filter(|path| {
                path.extension()
                    .is_some_and(|extension| extension == "yml" || extension == "yaml")
            })
            .collect();
        paths.sort();
        paths
            .iter()
            .filter_map(|path| std::fs::read_to_string(path).ok())
            .map(|text| text.replace("\r\n", "\n"))
            .collect::<Vec<_>>()
            .join("\n")
    }
}

/// What the attributes above a test function say about when it runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TestFunction {
    /// `#[ignore]`, or an `ignore` inside `cfg_attr`.
    pub ignored: bool,
    /// `#[cfg(...)]` or `cfg_attr(...)` on the function: it may not run on
    /// every CI leg.
    pub conditional: bool,
}

/// Finds `fn name(` in `source` and reads the attribute block above it.
///
/// The block is every contiguous line above the signature that is a comment or
/// an attribute (including the inside of a multi-line attribute); it ends at a
/// blank line or at a line that closes code (`}`, `;`, `{`). A function without
/// `#[test]` or `#[tokio::test]` in its block is not evidence, however its name
/// reads.
pub fn find_test(source: &str, name: &str) -> Result<TestFunction, String> {
    let lines: Vec<&str> = source.lines().collect();
    let signature = format!("fn {name}(");
    let mut found_a_function = false;
    for (index, line) in lines.iter().enumerate() {
        let trimmed = line.trim_start();
        let item = trimmed
            .strip_prefix("pub ")
            .unwrap_or(trimmed)
            .trim_start_matches("async ");
        if !item.starts_with(&signature) {
            continue;
        }
        found_a_function = true;

        let mut attributes: Vec<&str> = Vec::new();
        for above in lines[..index].iter().rev() {
            let above = above.trim();
            if above.starts_with("//") {
                continue;
            }
            if above.is_empty()
                || above.ends_with('}')
                || above.ends_with(';')
                || above.ends_with('{')
            {
                break;
            }
            attributes.push(above);
        }
        let is_test = attributes.iter().any(|attribute| {
            attribute.starts_with("#[test]") || attribute.starts_with("#[tokio::test")
        });
        if !is_test {
            continue;
        }
        let block = attributes.join(" ");
        return Ok(TestFunction {
            ignored: block.contains("#[ignore")
                || (block.contains("cfg_attr") && block.contains("ignore")),
            conditional: block.contains("#[cfg(") || block.contains("cfg_attr("),
        });
    }
    Err(if found_a_function {
        format!("`fn {name}` exists but carries no `#[test]` attribute")
    } else {
        format!("no `fn {name}` in the file")
    })
}

/// A path the manifest may cite: repository-relative, `/`-separated, `.rs`.
fn check_path(file: &str) -> Result<(), String> {
    let absolute = file.starts_with('/') || file.contains(':');
    let escapes = file
        .split('/')
        .any(|part| part.is_empty() || part == "." || part == "..");
    if file.contains('\\') || absolute || escapes {
        return Err("the path must be repository-relative and `/`-separated".to_string());
    }
    if !file.ends_with(".rs") {
        return Err("evidence must be a Rust test source".to_string());
    }
    Ok(())
}

/// Resolves one piece of evidence to the test it names.
///
/// A file-level `#![cfg(...)]` (the privileged suites carry `#![cfg(windows)]`)
/// makes every test in it conditional, whatever its own attributes say. A
/// `#[cfg]` on an enclosing inline `mod` is not seen; no cited test sits in
/// one, and a reviewer adding such a citation has the attribute in view.
pub fn check_evidence(
    evidence: &Evidence,
    source: &dyn EvidenceSource,
) -> Result<TestFunction, String> {
    check_path(evidence.file)?;
    let text = source
        .source(evidence.file)
        .ok_or_else(|| "the file does not exist".to_string())?;
    let mut test = find_test(&text, evidence.test)?;
    test.conditional |= text
        .lines()
        .any(|line| line.trim_start().starts_with("#![cfg("));
    Ok(test)
}

/// Whether some workflow runs this integration-test target by name with
/// `--ignored` on the same command line.
///
/// Comments and step names are not command lines: a `- name:` that mentions
/// `--ignored` over a step that no longer passes it must not count as wiring.
/// Nor does a line whose libtest filters leave this test out: a positional
/// filter or `--skip` after ` -- ` narrows the run by name.
pub fn is_wired(evidence: &Evidence, workflows: &str) -> bool {
    if !evidence.file.contains("/tests/") {
        // Only an integration-test target can be selected with `--test`.
        return false;
    }
    let stem = evidence
        .file
        .rsplit('/')
        .next()
        .and_then(|name| name.strip_suffix(".rs"))
        .unwrap_or_default();
    let flag = format!("--test {stem}");
    workflows.lines().any(|line| {
        let trimmed = line.trim_start().trim_start_matches("- ");
        if trimmed.starts_with('#') || trimmed.starts_with("name:") {
            return false;
        }
        line.contains("--ignored")
            && line.match_indices(&flag).any(|(offset, _)| {
                !line[offset + flag.len()..]
                    .starts_with(|next: char| next.is_ascii_alphanumeric() || next == '_')
            })
            && harness_selects(line, evidence.test)
    })
}

/// Whether the libtest arguments after ` -- ` on `line` keep `test` in the
/// run. A positional filter keeps only names containing it, `--skip` drops
/// names containing its value, and `--exact` makes both whole-name matches.
fn harness_selects(line: &str, test: &str) -> bool {
    let Some((_, harness)) = line.split_once(" -- ") else {
        return true;
    };
    let mut tokens = harness
        .split_whitespace()
        .take_while(|token| !matches!(*token, "&&" | "||" | ";" | "|"));
    let mut filters = Vec::new();
    let mut skips = Vec::new();
    let mut exact = false;
    while let Some(token) = tokens.next() {
        match token {
            "--exact" => exact = true,
            "--skip" => skips.extend(tokens.next()),
            // libtest options that take their value as the next word.
            "--test-threads" | "--logfile" | "--color" | "--format" | "--shuffle-seed" | "-Z" => {
                tokens.next();
            }
            "\\" => {}
            option if option.starts_with('-') => {}
            filter => filters.push(filter),
        }
    }
    let matches = |pattern: &&str| {
        let pattern = pattern.trim_matches(['\'', '"']);
        if exact {
            test == pattern
        } else {
            test.contains(pattern)
        }
    };
    (filters.is_empty() || filters.iter().any(matches)) && !skips.iter().any(matches)
}

/// Phrases that restate "not covered" rather than naming a boundary.
const NON_REASONS: [&str; 7] = [
    "not modelled",
    "not modeled",
    "unmodelled",
    "out of scope",
    "todo",
    "tbd",
    "n/a",
];

/// The shortest reason that can name a consequence rather than a label.
const MINIMUM_REASON: usize = 40;

/// Checks every row's exclusion and evidence against `source`.
pub fn justification_defects(
    manifest: &[Classification],
    source: &dyn EvidenceSource,
) -> Vec<Defect> {
    let workflows = source.workflows();
    let mut defects = Vec::new();
    for row in manifest {
        let leaf = row.leaf.to_string();

        match (row.coverage.is_generated(), row.exclusion) {
            (true, Some(_)) => defects.push(Defect::GeneratedLeafExcluded { leaf: leaf.clone() }),
            (false, None) => defects.push(Defect::UnjustifiedExclusion {
                leaf: leaf.clone(),
                coverage: row.coverage,
            }),
            (false, Some(exclusion)) => {
                let reason = exclusion.reason.trim();
                let lowered = reason.to_lowercase();
                let restates = NON_REASONS.iter().any(|phrase| lowered.contains(phrase));
                if reason.chars().count() < MINIMUM_REASON || restates {
                    defects.push(Defect::VagueExclusion {
                        leaf: leaf.clone(),
                        boundary: exclusion.boundary,
                        reason: reason.to_string(),
                    });
                }
            }
            (true, None) => {}
        }

        if row.evidence.is_empty() {
            defects.push(Defect::NoEvidence { leaf: leaf.clone() });
            continue;
        }

        let mut runs_by_default = false;
        let mut runs_privileged = false;
        for evidence in row.evidence {
            match check_evidence(evidence, source) {
                Err(why) => defects.push(Defect::MissingEvidence {
                    leaf: leaf.clone(),
                    evidence: *evidence,
                    why,
                }),
                Ok(test) if test.ignored => {
                    if is_wired(evidence, &workflows) {
                        runs_privileged = true;
                    } else {
                        defects.push(Defect::IgnoredEvidenceNotWired {
                            leaf: leaf.clone(),
                            evidence: *evidence,
                        });
                    }
                }
                Ok(test) => runs_by_default |= !test.conditional,
            }
        }

        if row.coverage == Coverage::Privileged {
            if !runs_privileged {
                defects.push(Defect::NoPrivilegedEvidence { leaf });
            }
        } else if !runs_by_default {
            defects.push(Defect::NoDefaultRunEvidence { leaf });
        }
    }
    defects
}

// ---------------------------------------------------------------------------
// Controls: the justification check fails on every defect it names
// ---------------------------------------------------------------------------
// The real manifest passes, so on its own it proves nothing about the check.
// These rows run against a synthetic repository, where each defect can be
// planted without touching a real test file, and the first control shows the
// well-formed version of every class passing.

mod controls {
    use super::*;

    const FIXTURE: &str = "crates/app/tests/fixture.rs";
    const GATED_FILE: &str = "crates/platform/tests/gated.rs";
    const UNIT: &str = "crates/app/src/cli/fixture.rs";

    const FIXTURE_SOURCE: &str = r#"
use std::path::Path;

/// Runs on every leg.
#[test]
fn runs_everywhere() {}

#[test]
#[cfg(windows)]
fn runs_on_windows_only() {}

#[cfg_attr(
    not(windows),
    ignore = "needs the service manager"
)]
#[test]
fn ignored_off_windows() {}

#[test]
#[ignore = "privileged: run by name in CI"]
fn privileged_case() {}

fn helper_named_like_a_test(path: &Path) -> bool {
    path.exists()
}

#[tokio::test(flavor = "current_thread")]
async fn runs_everywhere_async() {}
"#;

    const GATED_SOURCE: &str = r#"
#![cfg(windows)]

#[test]
fn looks_unconditional() {}
"#;

    const WIRED: &str = r#"
      - name: privileged suite
        run: |
          cargo test -p runner-manager \
            --test fixture -- --ignored --test-threads=1
"#;

    struct Table {
        workflows: &'static str,
    }

    impl EvidenceSource for Table {
        fn source(&self, file: &str) -> Option<String> {
            match file {
                FIXTURE | UNIT => Some(FIXTURE_SOURCE.to_string()),
                GATED_FILE => Some(GATED_SOURCE.to_string()),
                _ => None,
            }
        }

        fn workflows(&self) -> String {
            self.workflows.to_string()
        }
    }

    const WIRED_REPOSITORY: Table = Table { workflows: WIRED };

    const CONCRETE: &str = "Takes the single-instance lock and never exits on its own, so a \
                            chain would block on it forever.";

    const LEAF: &str = "host show";

    /// A row for [`LEAF`]. Rows in `MANIFEST` borrow `'static` evidence, so a
    /// control's evidence is leaked; a test process's lifetime is the point.
    fn row(
        coverage: Coverage,
        evidence: &[Evidence],
        exclusion: Option<Exclusion>,
    ) -> Classification {
        Classification {
            leaf: LEAF,
            coverage,
            evidence: Box::leak(evidence.to_vec().into_boxed_slice()),
            exclusion,
        }
    }

    fn excluded(boundary: Boundary, reason: &'static str) -> Option<Exclusion> {
        Some(Exclusion { boundary, reason })
    }

    fn defects_of(row: Classification, source: &dyn EvidenceSource) -> Vec<Defect> {
        justification_defects(&[row], source)
    }

    #[test]
    fn a_well_formed_row_of_every_class_is_accepted() {
        let rows = [
            row(Coverage::Generated, &[at(FIXTURE, "runs_everywhere")], None),
            row(
                Coverage::Scripted,
                &[at(UNIT, "runs_everywhere_async")],
                excluded(Boundary::WslPlatform, CONCRETE),
            ),
            row(
                Coverage::Dedicated,
                &[
                    at(FIXTURE, "runs_on_windows_only"),
                    at(FIXTURE, "runs_everywhere"),
                ],
                excluded(Boundary::NonTerminating, CONCRETE),
            ),
            row(
                Coverage::Privileged,
                &[at(FIXTURE, "privileged_case")],
                excluded(Boundary::HostServiceManager, CONCRETE),
            ),
            row(
                Coverage::SurfaceOnly,
                &[at(FIXTURE, "runs_everywhere")],
                excluded(Boundary::TerminalOwnership, CONCRETE),
            ),
        ];
        for row in rows {
            let defects = defects_of(row, &WIRED_REPOSITORY);
            assert!(
                defects.is_empty(),
                "a well-formed {:?} row must pass, or every rejection below is \
                 meaningless:\n{}",
                row.coverage,
                report(&defects)
            );
        }
    }

    #[test]
    fn evidence_that_names_no_real_test_is_rejected() {
        let cases = [
            (
                at("crates/app/tests/absent.rs", "runs_everywhere"),
                "does not exist",
            ),
            (at(FIXTURE, "renamed_away"), "no `fn renamed_away`"),
            (at(FIXTURE, "helper_named_like_a_test"), "no `#[test]`"),
            (at(FIXTURE, "runs_everywhere_async_"), "no `fn"),
            (
                at("/crates/app/tests/fixture.rs", "runs_everywhere"),
                "repository-relative",
            ),
            (
                at("crates\\app\\tests\\fixture.rs", "runs_everywhere"),
                "repository-relative",
            ),
            (
                at("crates/app/../app/tests/fixture.rs", "runs_everywhere"),
                "repository-relative",
            ),
            (
                at("crates/app/tests/fixture.md", "runs_everywhere"),
                "Rust test source",
            ),
        ];
        for (evidence, why) in cases {
            let defects = defects_of(
                row(Coverage::Generated, &[evidence], None),
                &WIRED_REPOSITORY,
            );
            assert!(
                defects.iter().any(|defect| matches!(
                    defect,
                    Defect::MissingEvidence { why: reason, .. } if reason.contains(why)
                )),
                "{evidence:?} must be rejected as missing evidence ({why}); got:\n{}",
                report(&defects)
            );
        }

        let defects = defects_of(row(Coverage::Generated, &[], None), &WIRED_REPOSITORY);
        assert_eq!(
            defects,
            [Defect::NoEvidence {
                leaf: LEAF.to_string()
            }],
            "a row with no evidence at all must be rejected"
        );
    }

    #[test]
    fn an_exclusion_must_name_a_concrete_boundary_and_a_generated_row_none() {
        let evidence = &[at(FIXTURE, "runs_everywhere")];

        for coverage in [
            Coverage::Scripted,
            Coverage::Dedicated,
            Coverage::Privileged,
            Coverage::SurfaceOnly,
        ] {
            let defects = defects_of(row(coverage, evidence, None), &WIRED_REPOSITORY);
            assert!(
                defects.contains(&Defect::UnjustifiedExclusion {
                    leaf: LEAF.to_string(),
                    coverage,
                }),
                "{coverage:?} without a boundary must be rejected; got:\n{}",
                report(&defects)
            );
        }

        for reason in [
            "Not modelled.",
            "Not modelled by the generator yet; revisit this row after the corpus lands.",
            "Out of scope for the local chain generator and its reference model.",
            "TODO: explain why this leaf is kept out of generated execution.",
            "   ",
            "Long-running.",
        ] {
            let defects = defects_of(
                row(
                    Coverage::Dedicated,
                    evidence,
                    excluded(Boundary::NonTerminating, reason),
                ),
                &WIRED_REPOSITORY,
            );
            assert!(
                defects
                    .iter()
                    .any(|defect| matches!(defect, Defect::VagueExclusion { .. })),
                "{reason:?} is not a concrete safety boundary; got:\n{}",
                report(&defects)
            );
        }

        let defects = defects_of(
            row(
                Coverage::Generated,
                evidence,
                excluded(Boundary::NonTerminating, CONCRETE),
            ),
            &WIRED_REPOSITORY,
        );
        assert_eq!(
            defects,
            [Defect::GeneratedLeafExcluded {
                leaf: LEAF.to_string()
            }],
            "a generated row that also claims an exclusion must be rejected"
        );
    }

    #[test]
    fn only_an_unconditional_test_counts_as_default_run_evidence() {
        for evidence in [
            at(FIXTURE, "runs_on_windows_only"),
            at(FIXTURE, "ignored_off_windows"),
            at(FIXTURE, "privileged_case"),
            at(GATED_FILE, "looks_unconditional"),
        ] {
            for (coverage, exclusion) in [
                (Coverage::Generated, None),
                (
                    Coverage::Dedicated,
                    excluded(Boundary::NonTerminating, CONCRETE),
                ),
            ] {
                let defects = defects_of(row(coverage, &[evidence], exclusion), &WIRED_REPOSITORY);
                assert!(
                    defects.contains(&Defect::NoDefaultRunEvidence {
                        leaf: LEAF.to_string()
                    }),
                    "{coverage:?} citing only {evidence:?} has nothing that runs on every \
                     leg of the default test run; got:\n{}",
                    report(&defects)
                );
            }
        }
    }

    #[test]
    fn privileged_evidence_must_be_run_by_name_by_a_workflow() {
        let privileged = &[at(FIXTURE, "privileged_case")];
        let exclusion = excluded(Boundary::HostServiceManager, CONCRETE);

        for workflows in [
            // No workflow at all.
            "",
            // The target runs, but not its ignored tests.
            "        run: cargo test -p runner-manager --test fixture\n",
            // Only a step name or a comment still mentions it.
            "      - name: cargo test --test fixture -- --ignored\n        run: cargo test\n",
            "        # cargo test --test fixture -- --ignored\n",
            // A different target whose name merely starts with this one.
            "        run: cargo test --test fixture_other -- --ignored\n",
            // The target runs, but a libtest filter leaves this test out.
            "        run: cargo test --test fixture -- --ignored another_case\n",
            "        run: cargo test --test fixture -- --ignored --skip privileged\n",
            "        run: cargo test --test fixture -- --ignored --exact privileged\n",
        ] {
            let defects = defects_of(
                row(Coverage::Privileged, privileged, exclusion),
                &Table { workflows },
            );
            assert_eq!(
                defects,
                [
                    Defect::IgnoredEvidenceNotWired {
                        leaf: LEAF.to_string(),
                        evidence: privileged[0],
                    },
                    Defect::NoPrivilegedEvidence {
                        leaf: LEAF.to_string()
                    },
                ],
                "with workflows {workflows:?} the privileged test runs nowhere"
            );
        }

        // Filters that keep the test in the run are still wiring.
        for workflows in [
            "        run: cargo test --test fixture -- --ignored privileged\n",
            "        run: cargo test --test fixture -- --ignored --exact privileged_case --test-threads 1\n",
            "        run: cargo test --test fixture -- --ignored --skip another_case\n",
        ] {
            let defects = defects_of(
                row(Coverage::Privileged, privileged, exclusion),
                &Table { workflows },
            );
            assert!(
                defects.is_empty(),
                "with workflows {workflows:?} the privileged test runs; got:\n{}",
                report(&defects)
            );
        }

        // A privileged row whose only evidence runs by default is not privileged,
        // and a unit test inside `src/` cannot be selected with `--test` at all.
        for evidence in [at(FIXTURE, "runs_everywhere"), at(UNIT, "privileged_case")] {
            let defects = defects_of(
                row(Coverage::Privileged, &[evidence], exclusion),
                &WIRED_REPOSITORY,
            );
            assert!(
                defects.contains(&Defect::NoPrivilegedEvidence {
                    leaf: LEAF.to_string()
                }),
                "a Privileged row citing only {evidence:?} is run by no privileged job; \
                 got:\n{}",
                report(&defects)
            );
        }
    }

    #[test]
    fn every_boundary_describes_a_consequence() {
        for boundary in [
            Boundary::NonTerminating,
            Boundary::HostServiceManager,
            Boundary::SelfReplacingDownload,
            Boundary::TerminalOwnership,
            Boundary::WslPlatform,
        ] {
            assert!(
                boundary.describe().chars().count() >= MINIMUM_REASON,
                "{boundary:?} must describe what it does to a chain, not name itself"
            );
        }
    }
}