anodizer 0.28.0

A Rust-native release automation tool inspired by GoReleaser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
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
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
//! What the audit scanners treat as test code.
//!
//! The scanners under `.claude/scripts/` share one test-region lexer
//! (`lib/test-regions.awk`) with two polarities: `audit-binary-name.sh` and
//! `audit-tag-family.sh` SKIP test code, `audit-test-isolation.sh` and
//! `audit-test-spawn-retry.sh` report only INSIDE it. A regression in that
//! lexer is silent — a scanner keeps exiting 0 while it has stopped looking at
//! half the tree — so each test here runs a scanner over a fixture tree
//! carrying the shapes that broke it before and asserts the whole hit list:
//!
//! * a raw read placed AFTER an inline `#[cfg(test)] mod … { … }` is
//!   production and is reported;
//! * a second attribute between `#[cfg(test)]` and `mod` still opens a region,
//!   so the reads inside it are not;
//! * a process-global mutation or a `git` spawn inside such a module is test
//!   code and is reported, while the same call after the module is not;
//! * a `crates/*/tests/**` integration file and a sibling `tests.rs` or
//!   `<name>_tests.rs` (no `#[cfg(test)]` of their own) are test code in
//!   their entirety.
//!
//! Treating those siblings as test code by NAME is sound only while every
//! such file really is declared under `#[cfg(test)]` by its parent module;
//! `every_named_test_source_is_declared_cfg_test` walks the real tree for that
//! premise.
#![cfg(unix)]

use std::path::Path;
use std::process::Command;

use anodizer_core::test_helpers::test_sources::{
    declared_under_test_cfg, is_test_only_cfg, is_test_source_path, test_sources,
};

use tempfile::TempDir;

const LIB_RS: &str = include_str!("fixtures/audit_scripts/lib.rs.txt");
const ATTR_GAP_RS: &str = include_str!("fixtures/audit_scripts/attr_gap.rs.txt");
const REGISTRY_RS: &str = include_str!("fixtures/audit_scripts/registry.rs.txt");
const INTEGRATION_RS: &str = include_str!("fixtures/audit_scripts/integration.rs.txt");
const TESTS_RS: &str = include_str!("fixtures/audit_scripts/tests.rs.txt");
const NAMED_TESTS_RS: &str = include_str!("fixtures/audit_scripts/named_tests.rs.txt");

/// The fixture sources are `.txt` so the workspace's own audits, which scan
/// `*.rs`, never read them as real source.
fn fixture_tree() -> TempDir {
    let dir = TempDir::new().expect("tempdir");
    for (rel, body) in [
        ("crates/demo/src/lib.rs", LIB_RS),
        ("crates/demo/src/attr_gap.rs", ATTR_GAP_RS),
        ("crates/demo/tests/spawn.rs", INTEGRATION_RS),
        ("crates/demo/src/tests.rs", TESTS_RS),
        ("crates/demo/src/named_tests.rs", NAMED_TESTS_RS),
        ("crates/core/src/artifact/registry.rs", REGISTRY_RS),
    ] {
        let path = dir.path().join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).expect("fixture dir");
        std::fs::write(&path, body).expect("fixture file");
    }
    dir
}

const LIVE_HOST_CONSTS_RS: &str = include_str!("fixtures/audit_scripts/live_host_consts.rs.txt");
const LIVE_HOST_TESTS_RS: &str = include_str!("fixtures/audit_scripts/live_host_tests.rs.txt");

/// `audit-test-live-host.sh` gets a tree of its own: its first scan fails on
/// any unregistered default-host constant, so a constant placed in the shared
/// fixture would stop the audit before its second scan ever ran.
fn live_host_tree(with_consts: bool) -> TempDir {
    let dir = TempDir::new().expect("tempdir");
    let mut files = vec![("crates/demo/src/tests.rs", LIVE_HOST_TESTS_RS)];
    if with_consts {
        files.push(("crates/demo/src/hosts.rs", LIVE_HOST_CONSTS_RS));
    }
    for (rel, body) in files {
        let path = dir.path().join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).expect("fixture dir");
        std::fs::write(&path, body).expect("fixture file");
    }
    dir
}

/// A compiled-in host nobody registered is a way to reach a live registry that
/// the second scan cannot see, so the first scan refuses the tree by name. A
/// loopback default needs no row, and a URL written in prose is not a
/// declaration.
#[test]
fn an_unregistered_default_host_constant_stops_the_audit() {
    let dir = live_host_tree(true);
    let (code, out) = run_audit("audit-test-live-host.sh", dir.path());

    assert_eq!(code, 1, "{out}");
    assert!(out.contains("DEMO_PUSH_SOURCE"), "{out}");
    assert!(!out.contains("DEMO_LOCAL_SOURCE"), "{out}");
    assert!(!out.contains("DEMO_DOC_SOURCE"), "{out}");
    assert!(!out.contains("COMMUNITY_PUSH_SOURCE"), "{out}");
}

/// A test proves it stays local by naming a loopback endpoint in its own body
/// or in a same-file fixture helper it calls, or by stating in a comment what
/// else keeps the run offline. A marker spelled inside a string literal is
/// code, not a comment, so it proves nothing; and a helper that is not itself
/// a `#[test]` never runs on its own.
#[test]
fn a_test_reaching_a_registry_is_reported_and_a_bounded_one_is_not() {
    let dir = live_host_tree(false);
    let (code, out) = run_audit("audit-test-live-host.sh", dir.path());

    let (forged_line, _) = at(LIVE_HOST_TESTS_RS, "fn a_forged_marker_in_a_string_literal");
    let (unbounded_line, _) = at(LIVE_HOST_TESTS_RS, "fn nothing_bounds_the_endpoint_here");
    assert_eq!(
        hits(&out),
        vec![
            format!(
                "crates/demo/src/tests.rs:{forged_line}: a_forged_marker_in_a_string_literal_bounds_nothing"
            ),
            format!("crates/demo/src/tests.rs:{unbounded_line}: nothing_bounds_the_endpoint_here"),
        ],
        "{out}"
    );
    assert_eq!(code, 1, "{out}");
}

const PROSE_VOICE_RS: &str = include_str!("fixtures/audit_scripts/prose_voice.rs.txt");
const PROSE_VOICE_SH: &str = include_str!("fixtures/audit_scripts/prose_voice.sh.txt");
const PROSE_VOICE_YML: &str = include_str!("fixtures/audit_scripts/prose_voice.yml.txt");
const PROSE_NAME_RS: &str = include_str!("fixtures/audit_scripts/prose_name.rs.txt");

/// `audit-prose.sh` reports both counts in one run, so each pin gets a tree
/// carrying only its own shapes; a shared tree would make either failure block
/// depend on the other's fixture.
fn prose_tree(files: &[(&str, &str)]) -> TempDir {
    let dir = TempDir::new().expect("tempdir");
    for (rel, body) in files {
        let path = dir.path().join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).expect("fixture dir");
        std::fs::write(&path, body).expect("fixture file");
    }
    dir
}

/// The author belongs in neither register: a rustdoc `we` ships to users who
/// do not know who that is, an inline one narrates a session. A pronoun in a
/// binding name or a string literal is code; inside a backtick span, a quoted
/// run or a URL it is someone else's text; and `us` inside `status` or
/// `us-east-1` is not a pronoun at all. Shell and workflow comments are scanned whole-line only,
/// because a `#` inside a string or a YAML scalar is data.
#[test]
fn first_person_in_a_comment_is_reported_and_code_or_quoted_prose_is_not() {
    let dir = prose_tree(&[
        ("crates/demo/src/lib.rs", PROSE_VOICE_RS),
        (".claude/scripts/demo.sh", PROSE_VOICE_SH),
        (".github/workflows/demo.yml", PROSE_VOICE_YML),
    ]);
    let (code, out) = run_audit("audit-prose.sh", dir.path());

    let (mirrored, _) = at(PROSE_VOICE_RS, "/// We mirror");
    let (narrated, _) = at(PROSE_VOICE_RS, "// Claude wrote");
    assert_eq!(
        hits(&out),
        vec![
            format!(
                "crates/demo/src/lib.rs:{narrated}: // Claude wrote the loop; the next reader was not there for it."
            ),
            format!("crates/demo/src/lib.rs:{mirrored}: /// We mirror the Cargo.toml branch here."),
        ],
        "{out}"
    );

    let (sh_line, sh_text) = at(PROSE_VOICE_SH, "# We keep the runner");
    let (yml_line, yml_text) = at(PROSE_VOICE_YML, "# Our release workflow");
    assert!(
        out.contains(&format!(".claude/scripts/demo.sh:{sh_line}: {sh_text}")),
        "{out}"
    );
    assert!(
        out.contains(&format!(
            ".github/workflows/demo.yml:{yml_line}: {yml_text}"
        )),
        "{out}"
    );
    assert!(
        !out.contains("trailing comment"),
        "a trailing `#` is not a whole-line comment: {out}"
    );
    assert_eq!(code, 1, "{out}");
}

/// The tree carries no misspelling today, so this pin holds the rule rather
/// than reporting a finding: the fixture supplies the hit, and the serde alias
/// that keeps an old config spelling loadable stays exempt because there the
/// spelling is data.
#[test]
fn the_misspelled_tool_name_is_reported_and_the_config_alias_is_not() {
    let dir = prose_tree(&[("crates/demo/src/lib.rs", PROSE_NAME_RS)]);
    let (code, out) = run_audit("audit-prose.sh", dir.path());

    let (misspelled, text) = at(PROSE_NAME_RS, "which is the misspelling");
    assert_eq!(
        hits(&out),
        vec![format!("crates/demo/src/lib.rs:{misspelled}:{text}")],
        "{out}"
    );
    let (aliased, _) = at(PROSE_NAME_RS, "serde(alias");
    assert!(
        !out.contains(&format!("crates/demo/src/lib.rs:{aliased}:")),
        "the config alias spells the old name as DATA: {out}"
    );
    assert_eq!(code, 1, "{out}");
}

/// The bash the scanners run under. Every scanner asserts the 4.4 floor
/// (`.claude/scripts/lib/require-bash.sh`), and macOS ships 3.2 at `/bin/bash`,
/// so a Homebrew bash is preferred wherever one is installed; elsewhere `PATH`
/// answers.
fn bash() -> Command {
    let homebrew = ["/opt/homebrew/bin/bash", "/usr/local/bin/bash"]
        .into_iter()
        .find(|candidate| Path::new(candidate).is_file());
    Command::new(homebrew.unwrap_or("bash"))
}

/// The awk the lexer agreement tests run the shared libraries under: gawk
/// from Homebrew where it is installed (macOS ships BSD awk), else `PATH`.
fn awk() -> Command {
    let gawk = [
        "/opt/homebrew/opt/gawk/libexec/gnubin/awk",
        "/usr/local/opt/gawk/libexec/gnubin/awk",
    ]
    .into_iter()
    .find(|candidate| Path::new(candidate).is_file());
    Command::new(gawk.unwrap_or("awk"))
}

fn run_audit(script: &str, root: &Path) -> (i32, String) {
    run_audit_with_path(script, root, None)
}

/// `shim`, when given, is prepended to `PATH` so a stubbed tool shadows the
/// real one.
fn run_audit_with_path(script: &str, root: &Path, shim: Option<&Path>) -> (i32, String) {
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join(".claude/scripts")
        .join(script);
    let mut command = bash();
    command.arg(&path).arg(root);
    if let Some(shim) = shim {
        let inherited = std::env::var("PATH").unwrap_or_default();
        command.env("PATH", format!("{}:{inherited}", shim.display()));
    }
    let out = command
        .output()
        .unwrap_or_else(|e| panic!("running {}: {e}", path.display()));
    let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
    text.push_str(&String::from_utf8_lossy(&out.stderr));
    (out.status.code().unwrap_or(-1), text)
}

/// Every scanner prints its findings as `<crate-relative path>:<line>…`; the
/// rest of the output is the shared remediation prose.
fn hits(output: &str) -> Vec<String> {
    let mut found: Vec<String> = output
        .lines()
        .filter(|l| l.starts_with("crates/") && l.contains(".rs:"))
        .map(str::to_string)
        .collect();
    found.sort();
    found
}

fn at(src: &str, needle: &str) -> (usize, String) {
    let (index, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains(needle))
        .unwrap_or_else(|| panic!("the fixture no longer contains `{needle}`"));
    (index + 1, line.trim().to_string())
}

#[test]
fn binary_name_audit_reads_production_after_an_inline_test_module() {
    let dir = fixture_tree();
    let (code, out) = run_audit("audit-binary-name.sh", dir.path());

    let (line, text) = at(LIB_RS, "let production_binary");
    assert_eq!(
        hits(&out),
        vec![format!(
            "crates/demo/src/lib.rs:{line} (fn after_the_inline_module): {text}"
        )],
        "{out}"
    );
    assert_eq!(code, 1, "{out}");
}

#[test]
fn tag_family_audit_reads_production_after_an_inline_test_module() {
    let dir = fixture_tree();
    let (code, out) = run_audit("audit-tag-family.sh", dir.path());

    let (line, text) = at(LIB_RS, "let _production_family");
    let (forged_line, forged_text) = at(LIB_RS, "tag-family-ok: fake");
    assert_eq!(
        hits(&out),
        vec![
            format!("crates/demo/src/lib.rs:{line} (fn after_the_inline_module): {text}"),
            format!("crates/demo/src/lib.rs:{forged_line} (fn forged_tag_family): {forged_text}"),
        ],
        "{out}"
    );
    assert_eq!(code, 1, "{out}");
}

#[test]
fn test_isolation_audit_reports_test_code_only() {
    let dir = fixture_tree();
    let (code, out) = run_audit("audit-test-isolation.sh", dir.path());

    let (inline_line, inline_text) = at(LIB_RS, "INLINE_ONLY");
    let (sibling_line, sibling_text) = at(TESTS_RS, "SIBLING_FILE");
    let (hand_line, hand_text) = at(TESTS_RS, "SIBLING_JUSTIFIED");
    let (named_line, named_text) = at(NAMED_TESTS_RS, "NAMED_SIBLING_FILE");
    let (file_line, file_text) = at(INTEGRATION_RS, "INTEGRATION_FILE");
    let (env_forge_line, env_forge_text) = at(TESTS_RS, "env-ok: fake");
    let (cwd_forge_line, cwd_forge_text) = at(TESTS_RS, "cwd-ok: fake");
    assert_eq!(
        hits(&out),
        vec![
            format!("crates/demo/src/lib.rs:{inline_line}: [env] {inline_text}"),
            format!("crates/demo/src/named_tests.rs:{named_line}: [env] {named_text}"),
            format!("crates/demo/src/tests.rs:{hand_line}: [env-guard] {hand_text}"),
            format!("crates/demo/src/tests.rs:{env_forge_line}: [env] {env_forge_text}"),
            format!("crates/demo/src/tests.rs:{cwd_forge_line}: [cwd] {cwd_forge_text}"),
            format!("crates/demo/src/tests.rs:{sibling_line}: [env] {sibling_text}"),
            format!("crates/demo/tests/spawn.rs:{file_line}: [env] {file_text}"),
        ],
        "{out}"
    );
    assert_eq!(code, 1, "{out}");
}

/// A marker justifies the RACE; it does not justify a restore written out by
/// hand, which a failing assertion between the two halves skips outright,
/// leaking the override into the next test in the process. So a marked
/// mutation is reported `[env-guard]` unless its function names `EnvGuard` —
/// the fixture's `sibling_env_guard`, whose raw call IS the guard's own body.
/// The distinction is what makes the class rule enforceable: it flags the
/// hand-paired shape without flagging the guard that replaces it.
#[test]
fn test_isolation_audit_demands_a_guard_behind_every_marked_env_mutation() {
    let dir = fixture_tree();
    let (_, out) = run_audit("audit-test-isolation.sh", dir.path());

    let (hand_line, _) = at(TESTS_RS, "SIBLING_JUSTIFIED");
    let (guarded_line, _) = at(TESTS_RS, "SIBLING_GUARDED");
    let reported: Vec<String> = hits(&out)
        .into_iter()
        .filter(|h| h.contains("[env-guard]"))
        .collect();
    assert_eq!(
        reported,
        vec![format!(
            "crates/demo/src/tests.rs:{hand_line}: [env-guard] unsafe {{ std::env::set_var(\"SIBLING_JUSTIFIED\", \"1\") }}; // env-ok: serialised by serial(sibling_env)"
        )],
        "only the hand-restored call is reported; line {guarded_line} binds a guard.\n{out}"
    );
}

#[test]
fn spawn_retry_audit_reports_test_context_only() {
    let dir = fixture_tree();
    let (code, out) = run_audit("audit-test-spawn-retry.sh", dir.path());

    let (inline_line, inline_text) = at(LIB_RS, r#"arg("status")"#);
    let (file_line, file_text) = at(INTEGRATION_RS, r#"arg("init")"#);
    let (forged_line, forged_text) = at(TESTS_RS, "spawn-retry-ok: fake");
    assert_eq!(
        hits(&out),
        vec![
            format!("crates/demo/src/lib.rs:{inline_line}: {inline_text}"),
            format!("crates/demo/src/tests.rs:{forged_line}: {forged_text}"),
            format!("crates/demo/tests/spawn.rs:{file_line}: {file_text}"),
        ],
        "{out}"
    );
    assert_eq!(code, 1, "{out}");
}

/// `audit-test-exec-writer.sh` has to see EVERY spelling of an executable
/// mode — `PermissionsExt`'s `Permissions::from_mode(0o755)` argument and
/// `perms.set_mode(0o755)` mutation, and the `.mode(0o755)` builder call of
/// `OpenOptionsExt`/`DirBuilderExt` — because a call site picks any of them
/// freely and each one the audit could not see was a writer it waved through.
/// It must also stay off production chmods (a stage staging a real binary into
/// a package tree, a production `DirBuilder` mode) and off a mode carrying an
/// `exec-writer-ok:` marker. (Spelled without the comment slashes so this
/// sentence cannot arm the scanner's own marker rule.)
#[test]
fn exec_writer_audit_reports_every_mode_spelling_in_test_context_only() {
    let dir = fixture_tree();
    let (code, out) = run_audit("audit-test-exec-writer.sh", dir.path());

    let (set_mode_line, set_mode_text) = at(LIB_RS, "perms.set_mode");
    let (from_mode_line, from_mode_text) = at(TESTS_RS, r#""sibling-stub""#);
    let (builder_line, builder_text) = at(TESTS_RS, r#""opts-stub""#);
    let (forged_line, forged_text) = at(TESTS_RS, "exec-writer-ok: fake");
    assert_eq!(
        hits(&out),
        vec![
            format!("crates/demo/src/lib.rs:{set_mode_line}: {set_mode_text}"),
            format!("crates/demo/src/tests.rs:{from_mode_line}: {from_mode_text}"),
            format!("crates/demo/src/tests.rs:{builder_line}: {builder_text}"),
            format!("crates/demo/src/tests.rs:{forged_line}: {forged_text}"),
        ],
        "{out}"
    );
    assert_eq!(code, 1, "{out}");
}

/// The two audits whose whole surface is a marker: `audit-log-status.sh`'s
/// `status-ok:` and `audit-repo-identity.sh`'s `slug-ok:` / `token-ok:`. Each
/// fixture pairs one genuine marker with one spelled inside a string literal;
/// only the forged one is a hit, because a marker is read from the comment
/// half of its line and a string literal is code.
#[test]
fn log_status_audit_reads_its_marker_from_the_comment_half() {
    let dir = fixture_tree();
    let (code, out) = run_audit("audit-log-status.sh", dir.path());

    let (forged_line, forged_text) = at(LIB_RS, "status-ok: fake");
    assert_eq!(
        hits(&out),
        vec![format!(
            "crates/demo/src/lib.rs:{forged_line}: {forged_text}"
        )],
        "{out}"
    );
    assert_eq!(code, 1, "{out}");
}

#[test]
fn repo_identity_audit_reads_its_markers_from_the_comment_half() {
    let dir = fixture_tree();
    let (code, out) = run_audit("audit-repo-identity.sh", dir.path());

    let (slug_line, slug_text) = at(LIB_RS, "slug-ok: fake");
    let (token_line, token_text) = at(LIB_RS, "token-ok: fake");
    assert_eq!(
        hits(&out),
        vec![
            format!("crates/demo/src/lib.rs:{slug_line}:    {slug_text}"),
            format!("crates/demo/src/lib.rs:{token_line}:    {token_text}"),
        ],
        "{out}"
    );
    assert_eq!(code, 1, "{out}");
}

/// The collector's fail-loud direction, the half a permissive edit would
/// silently reopen: grep's own failure is never an empty result. Both a grep
/// that ran and failed and a grep that is not there stop the audit at exit 2,
/// the code reserved for "the scan did not run".
#[test]
fn a_collection_whose_grep_fails_stops_the_audit() {
    for status in [2, 127] {
        let dir = fixture_tree();
        let shim = dir.path().join("shim");
        std::fs::create_dir_all(&shim).expect("shim dir");
        anodizer_core::test_helpers::fake_tool::write_executable_script(
            &shim.join("grep"),
            &format!("#!/bin/sh\nprintf 'grep: unusable\\n' >&2\nexit {status}\n"),
        );

        let (code, out) = run_audit_with_path("audit-log-status.sh", dir.path(), Some(&shim));
        assert_eq!(code, 2, "grep exiting {status} must stop the audit: {out}");
        assert!(
            out.contains(&format!(
                "file collection exited {status}; the scan did not run."
            )),
            "{out}"
        );
    }
}

/// Drive `lib/scan.sh`'s collector directly. `body` runs from `dir` with the
/// real helper sourced, and `stdin` is fed to it so a helper that leaves grep
/// reading the caller's stdin is visible as a wrong result or a hang.
fn run_collector(dir: &Path, body: &str, stdin: &str) -> (i32, String) {
    use std::io::Write;

    let lib = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join(".claude/scripts/lib");
    let script = format!(
        "set -euo pipefail\nsource {}/require-bash.sh\nsource {}/scan.sh\n{body}\n",
        lib.display(),
        lib.display()
    );
    let mut child = bash()
        .arg("-c")
        .arg(&script)
        .current_dir(dir)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("spawning bash");
    // A collector that never reads stdin (a refused call, an absent root) can
    // exit before this write, and the write then fails with EPIPE. That is
    // the wanted outcome, so only another error is a harness failure.
    match child
        .stdin
        .take()
        .expect("stdin")
        .write_all(stdin.as_bytes())
    {
        Ok(()) => {}
        Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {}
        Err(e) => panic!("feeding stdin: {e}"),
    }
    let out = child.wait_with_output().expect("collector output");
    let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
    text.push_str(&String::from_utf8_lossy(&out.stderr));
    (out.status.code().unwrap_or(-1), text)
}

/// The collector's whole parse is the `--`: options reach grep verbatim, so an
/// option's argument may be detached (`--include '*.rs'`) without the helper
/// having to know which options take one. Classifying operands by shape
/// instead put the argument in the pattern slot and left grep with no file
/// operand at all.
#[test]
fn the_collector_reads_a_detached_option_argument_as_grep_does() {
    let dir = fixture_tree();
    let (code, out) = run_collector(
        dir.path(),
        "collect_files X -rl --include '*.rs' -- 'set_var' crates\nprintf 'n=%d\\n' \"${#X[@]}\"",
        "",
    );
    assert_eq!(code, 0, "{out}");
    assert!(
        out.contains("n=4"),
        "a detached option argument must reach grep as written: {out}"
    );
}

/// Without the separator the helper cannot tell an option's argument from the
/// pattern, and a guess produces an empty result from a grep that never ran.
#[test]
fn the_collector_refuses_a_call_without_the_separator() {
    let dir = fixture_tree();
    let (code, out) = run_collector(
        dir.path(),
        "collect_files X -rl 'set_var' crates\nprintf 'reached\\n'",
        "",
    );
    assert_eq!(code, 2, "{out}");
    assert!(out.contains("collect_files called without --"), "{out}");
    assert!(!out.contains("reached"), "the call must not return: {out}");
}

/// A collection with NO root at all still runs grep, which then has no file
/// operand; `< /dev/null` is what keeps it from reading the caller's stdin.
/// Spelled without `-r`, because a recursive grep with no operand walks the
/// working directory instead of reading stdin and would prove nothing here.
#[test]
fn the_collector_never_reads_the_callers_stdin() {
    let dir = fixture_tree();
    let (code, out) = run_collector(
        dir.path(),
        "collect_files X -- 'set_var'\nprintf 'n=%d\\n' \"${#X[@]}\"",
        "set_var from stdin\n",
    );
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("n=0"), "stdin is not a scan root: {out}");
}

/// Every NAMED root absent is an empty result decided before grep runs, not a
/// grep over the whole tree. A different mechanism from the stdin guard above:
/// this call never reaches grep at all.
#[test]
fn a_collection_whose_every_named_root_is_absent_returns_empty() {
    let dir = fixture_tree();
    let (code, out) = run_collector(
        dir.path(),
        "collect_files X -r -- 'set_var' crates/*/absent\nprintf 'n=%d\\n' \"${#X[@]}\"",
        "set_var from stdin\n",
    );
    assert_eq!(code, 0, "{out}");
    assert!(
        out.contains("n=0"),
        "an absent named root scans nothing: {out}"
    );
}

/// A recursive collection that names no root at all is refused, naming the
/// flag. `grep -r` with no file operand recurses the working directory, so the
/// call would scan the whole tree — `target/` and vendored sources included —
/// and report the findings as violations of the audited rule.
#[test]
fn a_rootless_recursive_collection_is_refused_naming_the_flag() {
    let dir = fixture_tree();
    for flag in ["-r", "-R", "-rl", "--recursive", "--dereference-recursive"] {
        let (code, out) = run_collector(
            dir.path(),
            &format!("collect_files X {flag} -- 'set_var'\nprintf 'n=%d\\n' \"${{#X[@]}}\""),
            "",
        );
        assert_eq!(code, 2, "{flag} with no root must not run: {out}");
        assert!(
            out.contains(&format!("called with {flag} and no root")),
            "the refusal must name {flag}: {out}"
        );
    }
}

/// A NON-recursive rootless collection keeps working: it reaches grep with
/// stdin on /dev/null and returns empty, which is what the stdin guard pins.
#[test]
fn a_rootless_non_recursive_collection_is_still_allowed() {
    let dir = fixture_tree();
    let (code, out) = run_collector(
        dir.path(),
        "collect_files X --include='*.rs' -- 'set_var'\nprintf 'n=%d\\n' \"${#X[@]}\"",
        "set_var from stdin\n",
    );
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("n=0"), "{out}");
}

/// `collect_files` is handed OPTIONAL roots — `crates/*/src crates/*/tests` —
/// and a glob that matches nothing stays literal. An absent optional root is
/// not a failed scan: the roots that do exist are still read.
#[test]
fn an_absent_optional_scan_root_is_not_a_failed_scan() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("crates/demo/src/tests.rs");
    std::fs::create_dir_all(path.parent().expect("parent")).expect("fixture dir");
    std::fs::write(&path, TESTS_RS).expect("fixture file");

    let (code, out) = run_audit("audit-test-isolation.sh", dir.path());
    assert_ne!(
        code, 2,
        "an absent crates/*/tests is not a scan failure: {out}"
    );
    assert!(!out.contains("the scan did not run"), "{out}");
    assert!(
        !hits(&out).is_empty(),
        "crates/*/src must still be scanned: {out}"
    );
}

/// Zero matches is a clean tree, not a failed scan. The keyed-attribute
/// collection feeds a `sed | sort | wc` pipeline, and a bare grep at its head
/// aborts the whole audit under `pipefail` when nothing matches.
#[test]
fn a_tree_with_no_serial_attribute_reports_a_clean_scan() {
    let dir = TempDir::new().expect("tempdir");
    let path = dir.path().join("crates/demo/src/lib.rs");
    std::fs::create_dir_all(path.parent().expect("parent")).expect("fixture dir");
    std::fs::write(&path, "pub fn f() -> u8 { 1 }\n").expect("fixture file");

    let (code, out) = run_audit("audit-serial-groups.sh", dir.path());
    assert_eq!(code, 0, "a tree with no #[serial] scans clean: {out}");
    assert!(
        out.contains("all 0 #[serial] attributes name a group (0 distinct groups)"),
        "{out}"
    );
}

/// Every audit scanner runs on bash >= 4.4 — `mapfile` arrived in 4.0 and 4.4
/// is where `set -u` stopped treating an empty array's `"${arr[@]}"` as an
/// unset expansion — and the floor is a property of the script SET, not of a
/// feature list: a scanner that uses no array today grows one tomorrow, and a
/// detection rule keyed on today's spellings (`mapfile `, `[@]}"`, `readarray
/// -t` with index-only expansion) silently stops covering it. So every
/// `audit-*.sh` sources `lib/require-bash.sh`, and no script restates the
/// check inline.
#[test]
fn every_audit_script_sources_the_bash_floor() {
    let mut walked = 0usize;
    let mut missing = Vec::new();
    let mut restated = Vec::new();
    for script in audit_scripts() {
        let name = script
            .file_name()
            .expect("file name")
            .to_string_lossy()
            .into_owned();
        let body = std::fs::read_to_string(&script).expect("script body");
        walked += 1;
        if !body.contains("source \"$LIB_DIR/require-bash.sh\"") {
            missing.push(name.clone());
        }
        if body.contains("BASH_VERSINFO") || body.contains("bash --version") {
            restated.push(name);
        }
    }
    assert!(
        missing.is_empty(),
        "every audit script sources lib/require-bash.sh; these do not: {missing:?}"
    );
    assert!(
        restated.is_empty(),
        "the bash floor is asserted once, in lib/require-bash.sh; these restate it: {restated:?}"
    );
    assert!(
        walked >= 14,
        "expected every audit script to be walked, found {walked}"
    );
}

/// A scanner that could not run must never read as a clean scan. Every audit
/// script that loads an awk library from `.claude/scripts/lib` is driven from
/// a copy whose sibling `lib/` is empty, so awk dies loading its source: the
/// script has to fail with that error visible instead of printing an empty hit
/// list and exiting 0.
#[test]
fn a_scanner_that_cannot_load_its_awk_library_fails_loudly() {
    let repo = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
    let dir = TempDir::new().expect("temp dir");
    let lib = dir.path().join("lib");
    std::fs::create_dir(&lib).expect("lib dir");
    // Only the awk sources are withheld: the shared bash libraries still have
    // to load, or the scripts would die before ever reaching a scanner.
    for shared in ["require-bash.sh", "scan.sh"] {
        std::fs::copy(
            repo.join(".claude/scripts/lib").join(shared),
            lib.join(shared),
        )
        .unwrap_or_else(|e| panic!("copy lib/{shared}: {e}"));
    }

    let mut checked = 0usize;
    for entry in std::fs::read_dir(repo.join(".claude/scripts")).expect("scripts dir") {
        let src = entry.expect("script entry").path();
        let name = src
            .file_name()
            .expect("file name")
            .to_string_lossy()
            .into_owned();
        if !name.starts_with("audit-") || !name.ends_with(".sh") {
            continue;
        }
        // `-f "$LIB_DIR/…"` is an awk source load; `source "$LIB_DIR/…"` is
        // the bash floor, which every script takes and no scanner depends on.
        if !std::fs::read_to_string(&src)
            .expect("script body")
            .contains("-f \"$LIB_DIR/")
        {
            continue;
        }
        checked += 1;
        let copy = dir.path().join(&name);
        std::fs::copy(&src, &copy).expect("copy the script beside an empty lib dir");
        let out = bash()
            .arg(&copy)
            .arg(&repo)
            .output()
            .unwrap_or_else(|e| panic!("running {name}: {e}"));
        let stdout = String::from_utf8_lossy(&out.stdout);
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert_eq!(
            out.status.code(),
            Some(2),
            "{name} must exit 2 (\"the scan did not run\"), never 0 or the \
             violations-found 1.\n{stdout}{stderr}"
        );
        assert!(
            stderr.contains(".awk"),
            "{name} must leave the awk error visible, got: {stderr}"
        );
        assert!(
            stderr.contains("the scan did not run"),
            "{name} must say the scan did not run, got: {stderr}"
        );
    }
    assert!(
        checked >= 8,
        "expected every awk-library scanner to be driven, found {checked}"
    );
}

/// The premise behind `is_test_file`'s name match: every test source the
/// scanner names under `crates/*/src` — a `tests.rs` file, a `<name>_tests.rs`
/// file, and a whole `tests/` module directory, which matches no name rule of
/// its own and is claimed by its directory name — is declared `mod <stem>;`
/// under a test-only `cfg` by its parent module (`mod.rs`/`lib.rs`/`main.rs`
/// beside it, or the 2018-layout `<dir>.rs`), with the attribute on the item's
/// line or in the contiguous run of attribute and comment lines directly above
/// it. A path that matches by name but is compiled into production would be
/// skipped by the production-only scanners and reported by the test-only
/// ones — both wrong.
#[test]
fn every_named_test_source_is_declared_cfg_test() {
    let mut undeclared = Vec::new();
    let mut seen = 0usize;
    for src in anodizer_core::test_helpers::test_sources::workspace_crate_dirs()
        .into_iter()
        .map(|krate| krate.join("src"))
        .filter(|src| src.is_dir())
    {
        for file in test_sources(&src) {
            seen += 1;
            if let Err(why) = declared_under_test_cfg(&file) {
                undeclared.push(why);
            }
        }
    }
    assert!(seen > 0, "no name-matched test file in the workspace");
    assert!(
        undeclared.is_empty(),
        "name-matched test files not declared `#[cfg(test)] mod …;` by their parent: {undeclared:?}"
    );
}

/// The awk lexer's `is_test_file` and the Rust `is_test_source_path` answer
/// the same question for two families of consumer — the shell scanners and
/// the crates' structural walks. Feed both the same paths and compare
/// verdicts: a rule changed on one side alone fails here.
const AGREEMENT_PATHS: &[&str] = &[
    "crates/demo/src/tests.rs",
    "crates/demo/src/foo_tests.rs",
    "crates/demo/src/_tests.rs",
    "crates/demo/src/mytests.rs",
    "crates/demo/src/Foo_tests.rs",
    "crates/demo/src/tests.rs.bak",
    "crates/demo/src/lib.rs",
    "crates/demo/src/process/tests/mod.rs",
    "crates/demo/tests/integration.rs",
    "crates/demo/tests/nested/case.rs",
    "crates/tests/tests/case.rs",
    "src/tests/helper.rs",
    "tests.rs",
    "foo_tests.rs",
];

#[test]
fn test_source_predicate_agrees_with_the_awk_lexer() {
    let lib = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join(".claude/scripts/lib");
    let dir = TempDir::new().expect("temp dir");
    let driver = dir.path().join("driver.awk");
    std::fs::write(&driver, "{ print (is_test_file($0) ? \"1\" : \"0\") }\n").expect("driver");
    let list = dir.path().join("paths.txt");
    std::fs::write(&list, format!("{}\n", AGREEMENT_PATHS.join("\n"))).expect("path list");

    let out = awk()
        .arg("-f")
        .arg(lib.join("rust-lex.awk"))
        .arg("-f")
        .arg(lib.join("test-regions.awk"))
        .arg("-f")
        .arg(&driver)
        .arg(&list)
        .output()
        .expect("running awk");
    assert!(
        out.status.success(),
        "awk failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let awk: Vec<&str> = std::str::from_utf8(&out.stdout)
        .expect("awk output is utf-8")
        .lines()
        .collect();
    assert_eq!(
        awk.len(),
        AGREEMENT_PATHS.len(),
        "awk answered {} of {} paths",
        awk.len(),
        AGREEMENT_PATHS.len()
    );
    let disagreements: Vec<String> = AGREEMENT_PATHS
        .iter()
        .zip(&awk)
        .map(|(path, verdict)| (path, *verdict == "1", is_test_source_path(Path::new(path))))
        .filter(|(_, awk_says, rust_says)| awk_says != rust_says)
        .map(|(path, awk_says, rust_says)| format!("{path}: awk={awk_says} rust={rust_says}"))
        .collect();
    assert!(
        disagreements.is_empty(),
        "is_test_file and is_test_source_path must agree: {disagreements:?}"
    );
}

/// The `cfg(…)` predicates whose test-only verdict both lexers must share.
/// Every accepted shape, every rejection the accepted ones are one token away
/// from, and the two non-attribute lines that must never be mistaken for a
/// gate.
const AGREEMENT_CFG_LINES: &[&str] = &[
    "#[cfg(test)]",
    "  #[cfg(test)] mod tests;",
    "#[cfg(all(test, unix))]",
    "#[cfg(all(test, not(windows)))]",
    "#[cfg(all(feature = \"x\", test))]",
    "#[cfg(all(all(test), unix))]",
    "#[cfg(any(test, feature = \"x\"))]",
    "#[cfg(all(any(test, unix), windows))]",
    "#[cfg(not(test))]",
    "#[cfg(not(all(test, unix)))]",
    "#[cfg(feature = \"testing\")]",
    "#[cfg(unix)]",
    "// gated by #[cfg(test)] somewhere else",
    "mod tests;",
];

/// The awk lexer's `is_test_only_cfg` and the Rust `is_test_only_cfg` decide
/// which `cfg(…)` predicates gate test code — the shell scanners bound their
/// test regions with one, the crates' structural walks check the premise
/// behind a name match with the other. A rule loosened on one side alone (an
/// `any(…)` counted as a gate, a `not(…)` term rejected beside a `test` one)
/// lets a production module be skipped as test code, or the reverse. Feed
/// both the same predicate lines and compare verdicts.
#[test]
fn test_only_cfg_predicate_agrees_with_the_awk_lexer() {
    let lib = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join(".claude/scripts/lib");
    let dir = TempDir::new().expect("temp dir");
    let driver = dir.path().join("driver.awk");
    std::fs::write(
        &driver,
        "{ print (is_test_only_cfg($0) ? \"1\" : \"0\") }\n",
    )
    .expect("driver");
    let list = dir.path().join("cfg-lines.txt");
    std::fs::write(&list, format!("{}\n", AGREEMENT_CFG_LINES.join("\n"))).expect("cfg lines");

    let out = awk()
        .arg("-f")
        .arg(lib.join("rust-lex.awk"))
        .arg("-f")
        .arg(&driver)
        .arg(&list)
        .output()
        .expect("running awk");
    assert!(
        out.status.success(),
        "awk failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let awk: Vec<&str> = std::str::from_utf8(&out.stdout)
        .expect("awk output is utf-8")
        .lines()
        .collect();
    assert_eq!(
        awk.len(),
        AGREEMENT_CFG_LINES.len(),
        "awk answered {} of {} predicate lines",
        awk.len(),
        AGREEMENT_CFG_LINES.len()
    );
    let disagreements: Vec<String> = AGREEMENT_CFG_LINES
        .iter()
        .zip(&awk)
        .map(|(line, verdict)| (line, *verdict == "1", is_test_only_cfg(line)))
        .filter(|(_, awk_says, rust_says)| awk_says != rust_says)
        .map(|(line, awk_says, rust_says)| format!("{line}: awk={awk_says} rust={rust_says}"))
        .collect();
    assert!(
        disagreements.is_empty(),
        "the two `is_test_only_cfg` spellings must agree: {disagreements:?}"
    );
}

/// A Taskfile line with any trailing `#…` comment removed. Only ever applied
/// to key lines, whose value is empty, so no quoted `#` can be lost.
fn strip_trailing_comment(line: &str) -> &str {
    match line.split_once(" #") {
        Some((before, _)) => before.trim_end(),
        None => line.trim_end(),
    }
}

/// Whether `line` opens a top-level Taskfile target: two spaces of indent, a
/// name, and a colon that ends the line once any trailing comment is stripped
/// (`  doc:  # rustdoc` opens a target just as `  doc:` does).
fn is_top_level_key(line: &str) -> bool {
    if !line.starts_with("  ") || line.starts_with("   ") {
        return false;
    }
    if !line
        .chars()
        .nth(2)
        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
    {
        return false;
    }
    strip_trailing_comment(line).ends_with(':')
}

/// The `cmds:` body of one top-level Taskfile target, or `None` when the file
/// declares no such target. The walk needs to tell a target that is absent
/// from one whose NAME it mis-parsed, so the fallible form is the primitive.
fn taskfile_block_opt(taskfile: &str, target: &str) -> Option<String> {
    let key = format!("  {target}:");
    let mut lines = taskfile
        .lines()
        .skip_while(|l| strip_trailing_comment(l) != key);
    let first = lines.next()?;
    let mut block = String::from(first);
    for line in lines {
        if is_top_level_key(line) {
            break;
        }
        block.push('\n');
        block.push_str(line);
    }
    Some(block)
}

/// The `cmds:` body of one top-level Taskfile target: from its key line to the
/// next top-level key, mirroring `task_block` in `audit-gate-mirror.sh`.
fn taskfile_block(taskfile: &str, target: &str) -> String {
    taskfile_block_opt(taskfile, target)
        .unwrap_or_else(|| panic!("no `  {target}:` in Taskfile.yml"))
}

/// The targets one target block names: every `- task: <name>` item, plus
/// every entry of a `deps:` list in either spelling (`deps: [a, b]` and a
/// block list). A dep runs the target just as a cmd does, so a walk that
/// followed only `- task:` edges would miss half the graph.
fn child_tasks(block: &str) -> Vec<String> {
    let mut children = Vec::new();
    let mut in_deps = false;
    for line in block.lines() {
        let code = strip_trailing_comment(line);
        let trimmed = code.trim();
        // A key at the target's own field level closes any open deps list.
        if code.starts_with("    ") && !code.starts_with("     ") && trimmed.contains(':') {
            in_deps = false;
            if let Some(rest) = trimmed.strip_prefix("deps:") {
                let rest = rest.trim();
                match rest.strip_prefix('[').and_then(|r| r.strip_suffix(']')) {
                    Some(inline) => children.extend(
                        inline
                            .split(',')
                            .map(|n| n.trim().to_string())
                            .filter(|n| !n.is_empty()),
                    ),
                    None => in_deps = rest.is_empty(),
                }
                continue;
            }
        }
        if let Some(item) = trimmed.strip_prefix("- ") {
            let item = item.trim();
            match item.strip_prefix("task: ") {
                Some(name) => children.push(name.trim().to_string()),
                None if in_deps => children.push(item.to_string()),
                None => {}
            }
        }
    }
    children
}

/// Every target reachable from `roots` through `child_tasks`, roots included.
/// The `seen` guard is what makes this terminate: the graph is a DAG only by
/// convention, and a diamond would otherwise re-walk a shared child.
fn reachable_tasks(taskfile: &str, roots: &[&str]) -> Vec<String> {
    let mut seen: Vec<String> = Vec::new();
    // Each queued child carries the parent whose block named it, so an edge
    // this parser did not understand can say where it came from.
    let mut queue: Vec<(String, Option<String>)> =
        roots.iter().map(|r| ((*r).to_string(), None)).collect();
    while let Some((name, parent)) = queue.pop() {
        if seen.contains(&name) {
            continue;
        }
        let block = match (taskfile_block_opt(taskfile, &name), &parent) {
            (Some(block), _) => block,
            // A child with no block is an edge whose text was mis-read, not a
            // missing target: reporting it as missing sends the reader hunting
            // for a target nobody ever wrote. A root, named by the caller, is
            // the other case and keeps the plain lookup panic.
            (None, Some(parent)) => {
                panic!("`task {parent}` has a dep the walk cannot resolve: `{name}`")
            }
            (None, None) => taskfile_block(taskfile, &name),
        };
        for child in child_tasks(&block) {
            queue.push((child, Some(name.clone())));
        }
        seen.push(name);
    }
    seen.sort();
    seen
}

/// Whether a Taskfile target block runs `target`, by cmd or by dep. Matching
/// whole names is what keeps `docs:validate-readme` from reading as `doc`.
fn runs_task(block: &str, target: &str) -> bool {
    child_tasks(block).iter().any(|child| child == target)
}

/// A target key may carry a trailing comment. Ending a block only on a bare
/// `…:` would swallow the next target whole, and every "the rustdoc gate is
/// not in this block" assertion below would then read one block too wide and
/// pass on a tree where it is.
#[test]
fn a_taskfile_key_with_a_trailing_comment_ends_the_previous_block() {
    let snippet = "tasks:\n  first:\n    cmds:\n      - echo one\n  second:  # trailing\n    cmds:\n      - echo two\n";
    let first = taskfile_block(snippet, "first");
    assert!(
        first.contains("echo one") && !first.contains("echo two"),
        "the commented key must end the first block, got:\n{first}"
    );
    let second = taskfile_block(snippet, "second");
    assert!(
        second.contains("echo two"),
        "a commented key must still open its own block, got:\n{second}"
    );
}

/// The terminator inspects the third character of a line; a multi-byte one
/// (a `—` opening an indented comment) must not split it.
#[test]
fn a_multibyte_char_at_the_key_column_is_not_a_key() {
    assert!(!is_top_level_key("  — a dashed comment line"));
    assert!(is_top_level_key("  doc:"));
    assert!(is_top_level_key("  doc:  # rustdoc"));
    assert!(!is_top_level_key("      - task: doc"));
}

/// The `seen` guard collapses a diamond to one visit. Kept acyclic so that
/// losing the guard fails as a duplicated name rather than as a hung run —
/// a named assertion is the failure a reader can act on.
#[test]
fn the_task_walk_visits_a_diamond_once() {
    let snippet = "tasks:\n  a:\n    cmds:\n      - task: b\n      - task: c\n  b:\n    deps: [d]\n  c:\n    cmds:\n      - task: d\n  d:\n    cmds:\n      - echo leaf\n";
    let walked = reachable_tasks(snippet, &["a"]);
    assert_eq!(
        walked,
        vec!["a", "b", "c", "d"],
        "the shared child `d` is walked once, not once per parent"
    );
}

/// The same guard is the only thing that terminates a cycle. Taskfile graphs
/// are acyclic by convention, not by construction, so pin the cycle too.
#[test]
fn the_task_walk_terminates_on_a_cycle() {
    let snippet = "tasks:\n  a:\n    cmds:\n      - task: b\n  b:\n    cmds:\n      - task: a\n";
    assert_eq!(reachable_tasks(snippet, &["a"]), vec!["a", "b"]);
}

/// A dep spelling this parser does not understand yields a child name that
/// names no target. Saying "no such target" would describe a Taskfile bug that
/// does not exist; the bug is in the walk, so the message says so and names
/// the parent and the raw text.
#[test]
fn an_unparsed_dep_names_its_parent_and_its_raw_text() {
    let snippet = "tasks:\n  t:\n    deps: [{task: x}]\n    cmds:\n      - echo hi\n";
    let panic = std::panic::catch_unwind(|| reachable_tasks(snippet, &["t"]))
        .expect_err("an unparsed dep must fail the walk");
    let message = panic
        .downcast_ref::<String>()
        .map(String::as_str)
        .or_else(|| panic.downcast_ref::<&str>().copied())
        .unwrap_or_default()
        .to_string();
    assert_eq!(
        message, "`task t` has a dep the walk cannot resolve: `{task: x}`",
        "the failure must name the walk's own gap, not a missing target"
    );
}

/// `deps:` runs a target as surely as `cmds:` does, in either spelling.
#[test]
fn a_dep_is_an_edge_in_both_spellings() {
    let inline = "tasks:\n  t:\n    deps: [one, two]\n    cmds:\n      - echo hi\n";
    assert_eq!(child_tasks(&taskfile_block(inline, "t")), ["one", "two"]);

    let block = "tasks:\n  t:\n    deps:\n      - one\n      - task: two\n    cmds:\n      - echo hi\n      - task: three\n";
    assert_eq!(
        child_tasks(&taskfile_block(block, "t")),
        ["one", "two", "three"]
    );

    // A bare `- item` outside a deps list is a shell command, not a target.
    let cmds_only = "tasks:\n  t:\n    cmds:\n      - cargo build\n";
    assert!(child_tasks(&taskfile_block(cmds_only, "t")).is_empty());

    // Whole names only: a longer sibling never reads as its prefix.
    let sibling = "tasks:\n  t:\n    cmds:\n      - task: docs:validate-readme\n";
    let block = taskfile_block(sibling, "t");
    assert!(!runs_task(&block, "doc"));
    assert!(runs_task(&block, "docs:validate-readme"));
}

/// Rustdoc over this workspace holds several GB, so it may not run on the
/// commit path; it is CI's job and `task gate`'s (and so `task push`'s). The
/// wiring spans four files that no compiler ties together — a rename or a
/// dropped line on one side leaves the gate silently ungated — so pin all of
/// them textually, with no dependency on a `task` binary being installed.
#[test]
fn rustdoc_gate_is_wired_into_gate_and_ci_never_commit() {
    let repo = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
    let taskfile = std::fs::read_to_string(repo.join("Taskfile.yml")).expect("Taskfile.yml");

    let doc = taskfile_block(&taskfile, "doc");
    assert!(
        doc.contains("_check:mem-headroom"),
        "the `doc:` target must refuse to start without memory headroom, got:\n{doc}"
    );
    assert!(
        doc.contains("cargo doc --workspace --no-deps --document-private-items"),
        "the `doc:` target must run the workspace rustdoc, got:\n{doc}"
    );

    // The floor is only sound in two legs: an unreadable /proc/meminfo makes
    // the numeric comparison a shell error, which go-task would report with the
    // floor's own message. Pin the shape, not the prose.
    let headroom = taskfile_block(&taskfile, "_check:mem-headroom");
    let legs: Vec<&str> = headroom
        .lines()
        .map(str::trim)
        .filter(|l| l.starts_with("- sh:"))
        .collect();
    assert_eq!(
        legs.len(),
        2,
        "the memory precondition is a digits guard followed by a floor test, got:\n{headroom}"
    );
    assert!(
        legs[0].contains("^[0-9]+$"),
        "the first leg must reject a non-numeric MemAvailable reading, got: {}",
        legs[0]
    );
    assert!(
        legs[1].contains("-ge 8388608"),
        "the second leg must test the 8 GB floor, got: {}",
        legs[1]
    );
    for leg in &legs {
        assert!(
            leg.contains("uname"),
            "every leg short-circuits off Linux, which alone publishes /proc/meminfo, got: {leg}"
        );
    }

    let gate = taskfile_block(&taskfile, "gate");
    assert!(
        runs_task(&gate, "doc"),
        "`task gate` must run the rustdoc gate, got:\n{gate}"
    );
    // Absent from `lint` alone proves nothing: `task commit` reaches the gate
    // through whatever it and `lint` chain, by cmd or by dep, so walk the whole
    // closure from the target a commit actually invokes.
    let commit_path = reachable_tasks(&taskfile, &["commit"]);
    for name in &commit_path {
        let block = taskfile_block(&taskfile, name);
        assert!(
            !runs_task(&block, "doc"),
            "`task {name}` is reachable from `task commit`, so it must not chain the rustdoc gate, got:\n{block}"
        );
    }
    assert_eq!(
        commit_path.len(),
        28,
        "the set of tasks `task commit` reaches changed; re-check that none of them runs the rustdoc gate and update the count: {commit_path:?}"
    );

    let ci = std::fs::read_to_string(repo.join(".github/workflows/ci.yml")).expect("ci.yml");
    assert!(
        ci.contains("\n  rustdoc:\n"),
        "ci.yml must carry a `rustdoc` job"
    );
    assert!(
        ci.contains("run: task doc"),
        "ci.yml's rustdoc job must run `task doc`"
    );

    let mirror = std::fs::read_to_string(repo.join(".claude/scripts/audit-gate-mirror.sh"))
        .expect("audit-gate-mirror.sh");
    assert!(
        mirror.contains(r#"[rustdoc]="doc""#),
        "the gate mirror must map ci.yml's rustdoc job to the local `doc` target"
    );
}

/// A directory holding an `awk` that reports a MemAvailable of 1024 kB and
/// delegates every other script to the real binary, so a walk of the task
/// graph runs against a host the 8 GB floor rejects.
fn low_memory_awk_shim() -> tempfile::TempDir {
    let real = Command::new("sh")
        .args(["-c", "command -v awk"])
        .output()
        .expect("locating awk");
    let real = String::from_utf8_lossy(&real.stdout).trim().to_string();
    assert!(!real.is_empty(), "awk must be on PATH for this pin");

    let dir = tempfile::tempdir().expect("shim dir");
    let shim = dir.path().join("awk");
    anodizer_core::test_helpers::fake_tool::write_executable_script(
        &shim,
        &format!(
            "#!/usr/bin/env bash\n\
             for a in \"$@\"; do\n\
             case \"$a\" in *MemAvailable*) echo 1024; exit 0 ;; esac\n\
             done\n\
             exec {real} \"$@\"\n"
        ),
    );
    dir
}

/// go-task evaluates `preconditions:` even under `-n`, so before the bypass
/// existed the gate-mirror audit exited 2 on a host under the memory floor —
/// a question it never asked, answered by a resource it never spends.
#[test]
fn the_gate_mirror_audit_walks_the_graph_on_a_host_under_the_memory_floor() {
    if Command::new("sh")
        .args([
            "-c",
            "command -v task >/dev/null && command -v yq >/dev/null",
        ])
        .status()
        .map(|s| !s.success())
        .unwrap_or(true)
    {
        eprintln!(
            "SKIP the_gate_mirror_audit_walks_the_graph_on_a_host_under_the_memory_floor: task or yq missing"
        );
        return;
    }
    let repo = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
    let shim = low_memory_awk_shim();
    let (code, out) = run_audit_with_path("audit-gate-mirror.sh", &repo, Some(shim.path()));
    assert_eq!(
        code, 0,
        "a structural walk of the task graph spawns no rustdoc, so the memory \
         floor must not decide it; got:\n{out}"
    );
}

/// The other direction: the bypass is scoped to the walk. A real `task gate`
/// on the same host still refuses, because that one would spawn rustdoc.
#[test]
#[cfg(target_os = "linux")]
fn the_memory_floor_still_refuses_a_gate_run_on_a_host_under_it() {
    if Command::new("sh")
        .args(["-c", "command -v task >/dev/null"])
        .status()
        .map(|s| !s.success())
        .unwrap_or(true)
    {
        eprintln!(
            "SKIP the_memory_floor_still_refuses_a_gate_run_on_a_host_under_it: task missing"
        );
        return;
    }
    let repo = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
    let shim = low_memory_awk_shim();
    let inherited = std::env::var("PATH").unwrap_or_default();
    let out = Command::new("task")
        .args(["-n", "gate"])
        .current_dir(&repo)
        .env("PATH", format!("{}:{inherited}", shim.path().display()))
        .env_remove("ANODIZER_STRUCTURAL_WALK")
        .output()
        .expect("task -n gate");
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        !out.status.success() && text.contains("8388608 kB (8 GB) floor"),
        "without the walk's own bypass the floor must still refuse; got:\n{text}"
    );
}

/// Every `audit-*.sh` under `.claude/scripts`.
fn audit_scripts() -> Vec<std::path::PathBuf> {
    let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join(".claude/scripts");
    let mut found: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
        .expect("scripts dir")
        .map(|e| e.expect("script entry").path())
        .filter(|p| {
            let name = p.file_name().unwrap_or_default().to_string_lossy();
            name.starts_with("audit-") && name.ends_with(".sh")
        })
        .collect();
    found.sort();
    found
}

/// Words that only prefix another command, so the command word is the next one
/// along. Matched on the BASENAME, the same half of the word the awk names are
/// matched on, so `/usr/bin/env awk` peels exactly as `env awk` does.
const COMMAND_WRAPPERS: &[&str] = &[
    "command", "exec", "env", "xargs", "nice", "time", "sudo", "busybox", "toybox",
];

/// Reserved words that introduce a command rather than being one.
const RESERVED_WORDS: &[&str] = &[
    "if", "then", "elif", "else", "while", "until", "do", "coproc", "{", "}", "!",
];

/// Builtins that answer whether a program EXISTS. The word after one is the
/// name being asked about, not a program being run.
const PROBES: &[&str] = &["type", "hash", "which"];

/// `find` options whose argument is a whole command line, so a command
/// position opens after one.
const EXEC_OPTIONS: &[&str] = &["-exec", "-execdir", "-ok", "-okdir"];

/// Every basename that runs an awk program.
const AWK_NAMES: &[&str] = &["awk", "gawk", "mawk", "nawk"];

/// The last `/`-separated component of `word`.
fn basename(word: &str) -> &str {
    word.rsplit('/').next().unwrap_or(word)
}

/// Whether `word` is a `VAR=value` assignment, which precedes a command
/// rather than being one.
fn is_assignment(word: &str) -> bool {
    match word.find('=') {
        None | Some(0) => false,
        Some(split) => {
            let name = &word[..split];
            name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
                && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
        }
    }
}

/// Whether `word` is a redirection (`2>/dev/null`, `&>`, `>>`, `<<<`) and, if
/// so, whether its target is attached to it. A redirection precedes the
/// command word exactly as an option does; a detached target is the word after.
fn redirection(word: &str) -> Option<bool> {
    let rest = word.trim_start_matches(|c: char| c.is_ascii_digit());
    let rest = rest.strip_prefix('&').unwrap_or(rest);
    let target = rest.trim_start_matches(['<', '>', '&']);
    (target.len() < rest.len()).then_some(!target.is_empty())
}

/// The command word `segment` starts, as `(word, basename)`. A leading `\`,
/// `VAR=value` assignments, redirections, option words and their numeric
/// arguments, reserved words and the wrappers above are peeled off first, so
/// `exec /usr/bin/gawk -f x` answers `("/usr/bin/gawk", "gawk")` and
/// `${AWK} -f x` answers itself twice. `None` when the segment runs nothing —
/// it starts no command, or it only asks whether a program exists.
fn command_word(segment: &str) -> Option<(&str, &str)> {
    let words: Vec<&str> = segment.split_whitespace().collect();
    let mut i = 0;
    while i < words.len() {
        let word = words[i].trim_start_matches('\\');
        let base = basename(word);
        if base == "command" && matches!(words.get(i + 1), Some(&"-v" | &"-V")) {
            return None;
        }
        if PROBES.contains(&base) {
            return None;
        }
        if let Some(target_attached) = redirection(word) {
            i += if target_attached { 1 } else { 2 };
            continue;
        }
        if base == "case" {
            // Every command position inside a `case` opens after a `)` pattern,
            // which the trailing-`)` rule below peels; the `case <subject> in`
            // header runs nothing itself. On one line the header is not its own
            // segment, so it has to be peeled here or the `case` word answers.
            i += words[i..]
                .iter()
                .position(|w| *w == "in")
                .map_or(words.len(), |p| p + 1);
            continue;
        }
        if word.is_empty()
            || word.starts_with('-')
            || word.chars().all(|c| c.is_ascii_digit())
            || RESERVED_WORDS.contains(&word)
            || is_assignment(word)
            || COMMAND_WRAPPERS.contains(&base)
            // A `case` branch's pattern. An unmatched `)` reaches a segment
            // only there: everywhere else it closes a context and separates.
            || word.ends_with(')')
        {
            i += 1;
            continue;
        }
        return Some((word, base));
    }
    None
}

/// One command position: where it starts, its text, and the two facts about
/// what preceded it that the classifier needs.
struct Segment {
    line: usize,
    text: String,
    /// Inside a `$(…)`, `<(…)` or `>(…)`. A collection run from there feeds a
    /// verdict without the shared collector's status handling.
    substituted: bool,
    /// Reached through `||`, so a `true` here swallows the failure before it.
    after_or: bool,
}

/// Why the command `segment` starts may not stand in an `audit-*.sh`, or
/// `None`. `eval` and a command word that is a variable expansion are refused
/// outright: an audit script has no business with either, and both put a
/// program the pin cannot read into command position.
fn forbidden_word(segment: &Segment) -> Option<String> {
    let mut rest = segment.text.as_str();
    // `find … -exec awk … {} +` runs awk as surely as a pipeline does — but
    // only inside a `find` command line. Quoting is erased when a segment is
    // built, so anywhere else the same word is a pattern or a literal argument
    // (`grep -rn -- '-exec awk' …` names one, it does not run one).
    let in_find = command_word(rest).is_some_and(|(_, base)| base == "find");
    loop {
        if let Some(why) = forbidden_at(rest, segment) {
            return Some(why);
        }
        if !in_find {
            return None;
        }
        let mut words = rest.split_whitespace();
        let opened = words.find(|w| EXEC_OPTIONS.contains(w))?;
        let offset = rest.find(opened)? + opened.len();
        rest = &rest[offset..];
    }
}

/// The classifier one command position at a time.
fn forbidden_at(text: &str, segment: &Segment) -> Option<String> {
    let (word, base) = command_word(text)?;
    if word.starts_with('$') && word.len() > 1 {
        return Some(format!("a variable in command position (`{word}`)"));
    }
    if base == "eval" {
        return Some("eval".to_string());
    }
    if AWK_NAMES.contains(&base) {
        return Some(format!("awk invoked directly (`{word}`)"));
    }
    if segment.after_or && base == "true" {
        return Some("a swallowed failure (`|| true`)".to_string());
    }
    if segment.substituted && base == "grep" {
        return Some(format!("a collection outside collect_files (`{word}`)"));
    }
    None
}

/// The first reason any command in `body` may not stand in an `audit-*.sh`.
fn forbidden_command(body: &str) -> Option<String> {
    command_segments(body).iter().find_map(forbidden_word)
}

/// Accumulates one command position at a time.
#[derive(Default)]
struct SegmentSink {
    segments: Vec<Segment>,
    current: String,
    /// Any of the segment being accumulated was the interior of a `[[ … ]]`
    /// test, which is not a command list.
    test_expr: bool,
    after_or: bool,
}

impl SegmentSink {
    /// Close the segment at `line` and open the next one.
    fn take(&mut self, line: usize, substituted: bool, next_after_or: bool) {
        let text = std::mem::take(&mut self.current);
        if !self.test_expr {
            self.segments.push(Segment {
                line,
                text,
                substituted,
                after_or: self.after_or,
            });
        }
        self.test_expr = false;
        self.after_or = next_after_or;
    }
}

/// Every command position in `body`. A command starts at a line, or after an
/// unquoted `|`, `;`, `&`, backtick, `$(`, `<(`, `>(` or a subshell's `(`, so
/// `x="$(gawk …)"`, `… | mawk …`, `mapfile -t f < <(awk …)` and `exec awk …`
/// all start one. What is NOT a command never reaches the classifier: a
/// heredoc body (an awk program is full of `$0`), a comment, `((…))`
/// arithmetic, and the interior of a `[[ … ]]` test, whose `||` joins
/// conditions rather than commands. A `\`-continued line carries its command
/// word forward instead of starting a new one.
fn command_segments(body: &str) -> Vec<Segment> {
    #[derive(PartialEq)]
    enum Quote {
        Bare,
        Single,
        Double,
    }

    let mut sink = SegmentSink::default();
    let mut stack = vec![Quote::Bare];
    // Aligned with `stack`: whether each open context is a substitution.
    let mut substituted = vec![false];
    let mut heredoc: Option<String> = None;
    let mut continued;
    let mut in_test_expr = false;

    for (index, line) in body.lines().enumerate() {
        if let Some(delimiter) = &heredoc {
            if line.trim() == delimiter.as_str() {
                heredoc = None;
            }
            continue;
        }
        continued = false;
        let chars: Vec<char> = line.chars().collect();
        let mut i = 0;
        while i < chars.len() {
            let c = chars[i];
            let inside = substituted.iter().any(|&s| s);
            if stack.last() == Some(&Quote::Single) {
                // A quoted word still contributes its characters: `'awk' -f x`
                // runs awk exactly as `awk -f x` does.
                if c == '\'' {
                    stack.pop();
                    substituted.pop();
                } else {
                    sink.current.push(c);
                }
                i += 1;
                continue;
            }
            sink.test_expr |= in_test_expr;
            let double = stack.last() == Some(&Quote::Double);
            if c == '\\' {
                match chars.get(i + 1) {
                    Some(&escaped) => sink.current.push(escaped),
                    None => continued = true,
                }
                i += 2;
            } else if c == '"' {
                if double {
                    stack.pop();
                    substituted.pop();
                } else {
                    stack.push(Quote::Double);
                    substituted.push(false);
                }
                i += 1;
            } else if c == '$' && chars.get(i + 1) == Some(&'(') {
                // Command substitution opens a command position even inside a
                // double-quoted word.
                stack.push(Quote::Bare);
                substituted.push(true);
                sink.take(index + 1, inside, false);
                i += 2;
            } else if !double && matches!(c, '<' | '>') && chars.get(i + 1) == Some(&'(') {
                stack.push(Quote::Bare);
                substituted.push(true);
                sink.take(index + 1, inside, false);
                i += 2;
            } else if double {
                sink.current.push(c);
                i += 1;
            } else if c == '\'' {
                stack.push(Quote::Single);
                substituted.push(false);
                i += 1;
            } else if c == '#' && (i == 0 || chars[i - 1].is_whitespace()) {
                break;
            } else if c == '(' && chars.get(i + 1) == Some(&'(') {
                i = arithmetic_end(&chars, i);
                sink.current.clear();
            } else if c == '(' && sink.current.trim().is_empty() {
                // A subshell, not the `(` of `arr+=(…)` or a `case` pattern:
                // only at a command position is the parenthesis itself one.
                stack.push(Quote::Bare);
                substituted.push(false);
                sink.take(index + 1, inside, false);
                i += 1;
            } else if c == ')' && stack.len() > 1 {
                stack.pop();
                substituted.pop();
                sink.take(index + 1, inside, false);
                i += 1;
            } else if matches!(c, '|' | '&') && chars.get(i + 1) == Some(&c) {
                sink.take(index + 1, inside, c == '|');
                i += 2;
            } else if matches!(c, '|' | ';' | '&' | '`') {
                sink.take(index + 1, inside, false);
                i += 1;
            } else {
                sink.current.push(c);
                if c == '[' && sink.current.ends_with("[[") {
                    in_test_expr = true;
                } else if c == ']' && sink.current.ends_with("]]") {
                    in_test_expr = false;
                }
                i += 1;
            }
        }
        // A newline ends a command only outside quotes and outside a `\`
        // continuation; otherwise the next line is more of the same command.
        if !continued && stack.len() == 1 && stack[0] == Quote::Bare {
            let inside = substituted.iter().any(|&s| s);
            // A line ending on `||` leaves nothing between it and the newline,
            // so the link to the next command survives the line break.
            let carry = sink.current.trim().is_empty() && sink.after_or;
            sink.take(index + 1, inside, carry);
            in_test_expr = false;
        }
        heredoc = heredoc_delimiter(line).map(str::to_string);
    }
    sink.segments
}

/// The index just past the `))` closing the `((` at `open`, or the end of the
/// line when it does not close there.
fn arithmetic_end(chars: &[char], open: usize) -> usize {
    let mut i = open + 2;
    while i + 1 < chars.len() {
        if chars[i] == ')' && chars[i + 1] == ')' {
            return i + 2;
        }
        i += 1;
    }
    chars.len()
}

/// The delimiter of the heredoc `line` opens, if it opens one. `<<<` is a
/// here-string, not a heredoc, and carries no delimiter.
fn heredoc_delimiter(line: &str) -> Option<&str> {
    let mut rest = line;
    while let Some(start) = rest.find("<<") {
        let after = &rest[start + 2..];
        if let Some(here_string) = after.strip_prefix('<') {
            rest = here_string;
            continue;
        }
        let after = after.strip_prefix('-').unwrap_or(after).trim_start();
        let (quote, word) = match after.chars().next() {
            Some(q @ ('\'' | '"')) => (Some(q), &after[1..]),
            _ => (None, after),
        };
        let end = match quote {
            Some(q) => word.find(q),
            None => Some(
                word.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
                    .unwrap_or(word.len()),
            ),
        };
        match end {
            Some(0) | None => rest = after,
            Some(end) => return Some(&word[..end]),
        }
    }
    None
}

/// A scan that could not run must not read as a clean scan, and two shared
/// helpers decide that: `lib/scan.sh`'s `run_scanner` captures awk's stdout,
/// leaves awk's stderr visible and exits 2 on any non-zero awk status, and its
/// `collect_files` does the same for the grep that feeds it. A bare
/// `var="$(awk …)"` under `set -e` instead exits 1 — the repo's
/// "violations found" code — with an empty findings block, and a
/// `grep … 2>/dev/null || true` collection hands the scanner an empty file
/// list, so a grep that never ran reads as a clean tree. Textual rather than
/// behavioural so a script added tomorrow with either shape is caught before
/// it ever runs.
#[test]
fn every_awk_invocation_goes_through_the_shared_runner() {
    let mut forbidden = Vec::new();
    let mut scanners = 0usize;
    for script in audit_scripts() {
        let name = script.file_name().expect("file name").to_string_lossy();
        let body = std::fs::read_to_string(&script).expect("script body");
        for segment in command_segments(&body) {
            if let Some(why) = forbidden_word(&segment) {
                forbidden.push(format!(
                    "{name}:{}: {why}: {}",
                    segment.line,
                    segment.text.trim()
                ));
            }
        }
        if body.contains("run_scanner ") || body.contains("collect_files ") {
            scanners += 1;
            assert!(
                body.contains("source \"$LIB_DIR/scan.sh\""),
                "{name} calls run_scanner/collect_files without sourcing lib/scan.sh"
            );
        }
        for (index, line) in logical_lines(&body) {
            if collect_without_separator(&line) {
                forbidden.push(format!(
                    "{name}:{index}: collect_files without a `--` separator: {}",
                    line.trim()
                ));
            }
        }
    }
    assert!(
        forbidden.is_empty(),
        "every awk program runs through lib/scan.sh's run_scanner and every collection through \
         collect_files; these do not: {forbidden:#?}"
    );
    assert!(
        scanners >= 15,
        "expected every scanning script to be walked, found {scanners}"
    );
}

/// Whether `line` calls the shared collector without the `--` its option
/// parsing requires. The collector cannot tell an option's detached argument
/// from the pattern without one, so it refuses to guess.
fn collect_without_separator(line: &str) -> bool {
    line.contains("collect_files ") && !line.contains(" -- ")
}

/// The collector's `--` is the whole of its option parsing, so a call without
/// one is refused rather than guessed at. Kept as its own table because the
/// separator rule is not part of `forbidden_command`: an accepted row there
/// once carried a call the collector would have exited 2 on.
#[test]
fn the_separator_rule_reads_both_spellings() {
    for line in [
        "collect_files FILES -rlE 'x' crates --include='*.rs'",
        "collect_files X -r 'set_var' crates",
    ] {
        assert!(collect_without_separator(line), "must be refused: {line}");
    }
    for line in [
        "collect_files FILES -rlE --include='*.rs' -- 'x' crates",
        "collect_files X -r -- 'set_var' crates/*/src",
        "run_scanner violations -f \"$LIB_DIR/rust-lex.awk\" -f - \"${FILES[@]}\"",
    ] {
        assert!(!collect_without_separator(line), "must be allowed: {line}");
    }
}

/// The script's lines with `\`-continuations joined, each paired with the
/// 1-based number of the line it starts on.
fn logical_lines(body: &str) -> Vec<(usize, String)> {
    let mut joined: Vec<(usize, String)> = Vec::new();
    let mut pending: Option<(usize, String)> = None;
    for (index, raw) in body.lines().enumerate() {
        let continued = raw.ends_with('\\');
        let piece = raw.strip_suffix('\\').unwrap_or(raw);
        match pending.as_mut() {
            Some((_, text)) => {
                text.push(' ');
                text.push_str(piece.trim_start());
            }
            None => pending = Some((index + 1, piece.to_string())),
        }
        if !continued {
            joined.push(pending.take().expect("a started line"));
        }
    }
    if let Some(last) = pending {
        joined.push(last);
    }
    joined
}

/// The spellings the runner pin has to recognise. Each ran awk while the pin
/// matched only the literal first word `awk`, so each is pinned by name here
/// rather than left to a reading of `command_word`. The allowed column is the
/// other half of the same rule: an `awk` in prose, a `.awk` path handed to
/// `run_scanner`, and a `grep`/`sed` command line stay legal.
#[test]
fn the_runner_pin_recognises_every_awk_spelling() {
    for line in [
        "awk -f prog.awk file",
        "gawk -f prog.awk file",
        "mawk -f prog.awk file",
        "nawk -f prog.awk file",
        "command awk -f prog.awk file",
        "exec awk -f prog.awk file",
        "env awk -f prog.awk file",
        "env LC_ALL=C awk -f prog.awk file",
        "xargs awk -f prog.awk",
        "nice -n 5 awk -f prog.awk file",
        "/usr/bin/awk -f prog.awk file",
        "\\awk -f prog.awk file",
        "violations=\"$(awk -f prog.awk file)\"",
        "printf '%s' \"$x\" | awk -f prog.awk",
        "hits=$(cat file | /usr/local/bin/gawk '{ print }')",
        "$AWK -f prog.awk file",
        "${AWK} -f prog.awk file",
        "eval \"$program\"",
        "/usr/bin/env awk -f prog.awk file",
        "/usr/bin/env -S awk -f prog.awk file",
        "mapfile -t FILES < <(awk -f prog.awk file)",
        "readarray -t FILES < <(gawk -f prog.awk file)",
        "2>/dev/null awk -f prog.awk file",
        "2> /dev/null awk -f prog.awk file",
        "( awk -f prog.awk file )",
        "if [ -f x ]; then awk -f prog.awk x; fi",
        "for f in *; do awk -f prog.awk \"$f\"; done",
        "'awk' -f prog.awk file",
        "mapfile -t FILES < <(grep -rl x crates)",
        "files=\"$(grep -rl x crates)\"",
        "hits=\"$(sed -n 1p file)\" || true",
        "case \"$mode\" in\n    scan) awk -f prog.awk file ;;\nesac",
        "case \"$mode\" in\n    scan|run) gawk -f prog.awk file ;;\nesac",
        "case \"$mode\" in scan) awk -f prog.awk file ;; esac",
        "find crates -name '*.rs' -exec awk -f prog.awk {} +",
        "find crates -name '*.rs' -execdir mawk -f prog.awk {} \\;",
        "find crates -name '*.rs' -ok nawk -f prog.awk {} \\;",
        "find crates -name '*.rs' -okdir awk -f prog.awk {} \\;",
        "sed -n 1p file ||\ntrue",
        "coproc awk -f prog.awk file",
        "busybox awk -f prog.awk file",
        "toybox awk -f prog.awk file",
    ] {
        assert!(
            forbidden_command(line).is_some(),
            "the runner pin must reject: {line}"
        );
    }

    for line in [
        "# awk is named in this comment",
        "run_scanner violations -f \"$LIB_DIR/rust-lex.awk\" -f - \"${FILES[@]}\"",
        "collect_files FILES -rlE --include='*.rs' -- 'x' crates",
        "grep -qE -- \"task: ${target}\" <<< \"$combined\"",
        "LIB_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/lib\"",
        "done <<< \"$mod_decls\"",
        "command -v awk > /dev/null 2>&1",
        "type gawk",
        "hash mawk 2>/dev/null",
        "which nawk",
        "# a swallowed failure looks like `|| true` — never write one",
        "arr+=(\"$f\")",
        "case \"$x\" in awk) ;; esac",
        "grep -rn -- '-exec awk' .claude/scripts",
    ] {
        assert!(
            forbidden_command(line).is_none(),
            "the runner pin must accept {line}, got {:?}",
            forbidden_command(line)
        );
    }
}

/// The companion to `a_scanner_that_cannot_load_its_awk_library_fails_loudly`
/// for the other half of a scanner: its own program text. The library
/// directory is copied whole here, so the libraries load and the ONLY breakage
/// is the inline program — the same failure a bad dynamic regex or a mistyped
/// function produces.
#[test]
fn a_scanner_whose_inline_program_is_broken_fails_loudly() {
    let repo = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
    let scripts = repo.join(".claude/scripts");
    let dir = TempDir::new().expect("temp dir");
    let lib = dir.path().join("lib");
    std::fs::create_dir(&lib).expect("lib dir");
    for entry in std::fs::read_dir(scripts.join("lib")).expect("lib dir") {
        let src = entry.expect("lib entry").path();
        std::fs::copy(&src, lib.join(src.file_name().expect("file name"))).expect("copy lib file");
    }

    const SCRIPT: &str = "audit-log-status.sh";
    let body = std::fs::read_to_string(scripts.join(SCRIPT)).expect("script body");
    let broken = body.replacen("<<'AWK'\n", "<<'AWK'\n(((\n", 1);
    assert_ne!(
        broken, body,
        "{SCRIPT} no longer opens its program with <<'AWK'"
    );
    let copy = dir.path().join(SCRIPT);
    std::fs::write(&copy, broken).expect("write the broken copy");

    let out = bash()
        .arg(&copy)
        .arg(&repo)
        .output()
        .expect("running the broken scanner");
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_eq!(
        out.status.code(),
        Some(2),
        "a syntax error in the program must exit 2, not the violations-found 1.\n{stdout}{stderr}"
    );
    assert!(
        stderr.contains("audit-log-status: awk scanner exited")
            && stderr.contains("the scan did not run"),
        "the runner must name the script and say the scan did not run, got: {stderr}"
    );
    assert!(
        stderr.contains("awk:"),
        "awk's own diagnostic must stay visible, got: {stderr}"
    );
}