spec-spine-cli 0.17.0

The `spec-spine` command-line tool: compile a markdown spec corpus into a deterministic authority registry and query it. A thin wrapper over spec-spine-core.
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
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
//! End-to-end exit-code contract for the `spec-spine` binary.
//!
//! Exit codes: 0 ok, 1 validation failure / not found, 3 I/O / parse / schema.

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

fn bin() -> Command {
    Command::new(env!("CARGO_BIN_EXE_spec-spine"))
}

fn write_spec(root: &Path, dir: &str, id: &str, status: &str) {
    let spec_dir = root.join("specs").join(dir);
    fs::create_dir_all(&spec_dir).unwrap();
    let body = format!(
        "---\nid: \"{id}\"\ntitle: \"T\"\nstatus: {status}\ncreated: \"2026-06-08\"\nsummary: \"s\"\n---\n# {id}\n"
    );
    fs::write(spec_dir.join("spec.md"), body).unwrap();
}

fn code(out: &std::process::Output) -> i32 {
    out.status.code().unwrap_or(-1)
}

#[test]
fn index_slice_hashes_and_check() {
    let tmp = tempfile::tempdir().unwrap();
    write_spec(tmp.path(), "001-a", "001-a", "approved");
    fs::create_dir_all(tmp.path().join("conf")).unwrap();
    fs::write(tmp.path().join("conf/a.json"), "{\"a\":1}\n").unwrap();
    fs::write(tmp.path().join("conf/b.json"), "{\"b\":2}\n").unwrap();
    let run = |args: &[&str]| {
        let out = bin().arg("--repo").arg(tmp.path()).args(args).output();
        out.unwrap()
    };
    // Slices live in their own sidecar since spec 024 (no monolithic index.json).
    let slices_file = tmp.path().join(".derived/codebase-index/slices.json");

    // No slices configured: no sidecar; --slice is a config error (3).
    assert_eq!(code(&run(&["index"])), 0);
    assert!(
        !slices_file.exists(),
        "no slices configured -> no slices.json sidecar"
    );
    assert_eq!(
        code(&run(&["index", "check", "--slice", "agent-config"])),
        3,
        "unknown slice name -> 3"
    );

    // Slices configured AFTER the committed index: missing entry -> stale.
    fs::write(
        tmp.path().join("spec-spine.toml"),
        "[index.slices]\nzz-last = [\"conf/b.json\"]\nagent-config = [\"conf/a.json\", \"conf/missing.json\"]\n",
    )
    .unwrap();
    assert_eq!(
        code(&run(&["index", "check", "--slice", "agent-config"])),
        2,
        "an index predating the slice config is not vouching for it"
    );

    // Rebuild: entries emitted key-sorted; both slices fresh.
    assert_eq!(code(&run(&["index"])), 0);
    let raw = fs::read_to_string(&slices_file).unwrap();
    assert!(
        raw.find("agent-config").unwrap() < raw.find("zz-last").unwrap(),
        "slice hash keys are sorted"
    );
    assert_eq!(
        code(&run(&["index", "check", "--slice", "agent-config"])),
        0
    );
    assert_eq!(code(&run(&["index", "check", "--slice", "zz-last"])), 0);
    assert_eq!(code(&run(&["index", "check"])), 0);

    // Independence: a slice-only file's edit trips its slice, not the global
    // gate and not the other slice.
    fs::write(tmp.path().join("conf/a.json"), "{\"a\":99}\n").unwrap();
    assert_eq!(code(&run(&["index", "check"])), 0, "global gate unaffected");
    assert_eq!(
        code(&run(&["index", "check", "--slice", "agent-config"])),
        2
    );
    assert_eq!(code(&run(&["index", "check", "--slice", "zz-last"])), 0);

    // ...and vice versa: a global-input edit leaves the slices fresh.
    write_spec(tmp.path(), "001-a", "001-a", "draft");
    assert_eq!(
        code(&run(&["index", "check"])),
        2,
        "spec.md is global input"
    );
    assert_eq!(code(&run(&["index", "check", "--slice", "zz-last"])), 0);

    // Deletion of a guarded file is a hash change, not a config error.
    assert_eq!(code(&run(&["index"])), 0);
    fs::remove_file(tmp.path().join("conf/b.json")).unwrap();
    assert_eq!(code(&run(&["index", "check", "--slice", "zz-last"])), 2);

    // Unknown name with slices configured is still 3.
    assert_eq!(code(&run(&["index", "check", "--slice", "nope"])), 3);
}

#[test]
fn invalid_slice_config_exits_3() {
    let tmp = tempfile::tempdir().unwrap();
    write_spec(tmp.path(), "001-a", "001-a", "approved");

    // Name outside [a-z0-9][a-z0-9-]*.
    fs::write(
        tmp.path().join("spec-spine.toml"),
        "[index.slices]\n\"Bad_Name\" = [\"conf/*.json\"]\n",
    )
    .unwrap();
    assert_eq!(
        code(
            &bin()
                .arg("--repo")
                .arg(tmp.path())
                .arg("index")
                .output()
                .unwrap()
        ),
        3
    );

    // Empty glob list.
    fs::write(
        tmp.path().join("spec-spine.toml"),
        "[index.slices]\nok = []\n",
    )
    .unwrap();
    assert_eq!(
        code(
            &bin()
                .arg("--repo")
                .arg(tmp.path())
                .arg("index")
                .output()
                .unwrap()
        ),
        3
    );
}

#[test]
fn compile_ok_then_queries() {
    let tmp = tempfile::tempdir().unwrap();
    write_spec(tmp.path(), "001-a", "001-a", "approved");
    write_spec(tmp.path(), "002-b", "002-b", "approved");

    let compile = bin()
        .arg("--repo")
        .arg(tmp.path())
        .arg("compile")
        .output()
        .unwrap();
    assert_eq!(code(&compile), 0, "clean compile exits 0");
    // Sharded committed form (spec 024): one file per spec, no monolithic registry.json.
    assert!(
        tmp.path()
            .join(".derived/spec-registry/by-spec/001-a.json")
            .is_file()
    );
    assert!(
        !tmp.path()
            .join(".derived/spec-registry/registry.json")
            .exists()
    );

    let list = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["registry", "list"])
        .output()
        .unwrap();
    assert_eq!(code(&list), 0);
    assert!(String::from_utf8_lossy(&list.stdout).contains("001-a"));

    let show_missing = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["registry", "show", "999-nope"])
        .output()
        .unwrap();
    assert_eq!(code(&show_missing), 1, "not found exits 1");
}

#[test]
fn registry_list_ids_only_projection() {
    let tmp = tempfile::tempdir().unwrap();
    write_spec(tmp.path(), "001-a", "001-a", "approved");
    write_spec(tmp.path(), "002-b", "002-b", "approved");
    write_spec(tmp.path(), "003-c", "003-c", "draft");
    let compiled = bin()
        .arg("--repo")
        .arg(tmp.path())
        .arg("compile")
        .output()
        .unwrap();
    assert_eq!(code(&compiled), 0);

    // Text form: newline-delimited ids in id order, nothing else.
    let text = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["registry", "list", "--ids-only"])
        .output()
        .unwrap();
    assert_eq!(code(&text), 0);
    assert_eq!(
        String::from_utf8_lossy(&text.stdout),
        "001-a\n002-b\n003-c\n"
    );

    // JSON form: an array of id strings, same order.
    let json = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["registry", "list", "--ids-only", "--json"])
        .output()
        .unwrap();
    assert_eq!(code(&json), 0);
    let ids: Vec<String> = serde_json::from_slice(&json.stdout).unwrap();
    assert_eq!(ids, ["001-a", "002-b", "003-c"]);

    // --status filters first, then the projection applies.
    let filtered = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["registry", "list", "--ids-only", "--status", "approved"])
        .output()
        .unwrap();
    assert_eq!(code(&filtered), 0);
    assert_eq!(String::from_utf8_lossy(&filtered.stdout), "001-a\n002-b\n");

    let filtered_json = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args([
            "registry",
            "list",
            "--ids-only",
            "--status",
            "retired",
            "--json",
        ])
        .output()
        .unwrap();
    assert_eq!(code(&filtered_json), 0);
    let none: Vec<String> = serde_json::from_slice(&filtered_json.stdout).unwrap();
    assert!(none.is_empty());

    // Empty projection in text mode: empty output (no "(no specs)"), exit 0.
    let empty = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["registry", "list", "--ids-only", "--status", "retired"])
        .output()
        .unwrap();
    assert_eq!(code(&empty), 0);
    assert!(empty.stdout.is_empty());
}

#[test]
fn registry_status_report_nonzero_only_projection() {
    let tmp = tempfile::tempdir().unwrap();
    // approved + draft present; superseded + retired are the zero-count rows.
    write_spec(tmp.path(), "001-a", "001-a", "approved");
    write_spec(tmp.path(), "002-b", "002-b", "approved");
    write_spec(tmp.path(), "003-c", "003-c", "draft");
    let compiled = bin()
        .arg("--repo")
        .arg(tmp.path())
        .arg("compile")
        .output()
        .unwrap();
    assert_eq!(code(&compiled), 0);

    // Without the flag, output is byte-identical to pre-010 behavior.
    let plain = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["registry", "status-report"])
        .output()
        .unwrap();
    assert_eq!(code(&plain), 0);
    assert_eq!(
        String::from_utf8_lossy(&plain.stdout),
        "total:      3\ndraft:      1\napproved:   2\nsuperseded: 0\nretired:    0\n"
    );

    // Human form: zero-count rows omitted, total unaffected.
    let human = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["registry", "status-report", "--nonzero-only"])
        .output()
        .unwrap();
    assert_eq!(code(&human), 0);
    assert_eq!(
        String::from_utf8_lossy(&human.stdout),
        "total:      3\ndraft:      1\napproved:   2\n"
    );

    // JSON form: zero-count keys absent, total present.
    let json = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["registry", "status-report", "--nonzero-only", "--json"])
        .output()
        .unwrap();
    assert_eq!(code(&json), 0);
    let report: serde_json::Value = serde_json::from_slice(&json.stdout).unwrap();
    assert_eq!(report["total"], 3);
    assert_eq!(report["draft"], 1);
    assert_eq!(report["approved"], 2);
    assert!(report.get("superseded").is_none());
    assert!(report.get("retired").is_none());
}

#[test]
fn compile_validation_failure_exits_1() {
    let tmp = tempfile::tempdir().unwrap();
    // Directory name != id -> V-001 (error tier).
    write_spec(tmp.path(), "001-folder", "001-mismatch", "approved");
    let out = bin()
        .arg("--repo")
        .arg(tmp.path())
        .arg("compile")
        .output()
        .unwrap();
    assert_eq!(code(&out), 1, "validation failure exits 1");
}

#[test]
fn missing_specs_dir_exits_3() {
    let tmp = tempfile::tempdir().unwrap();
    // No specs/ dir at all -> I/O error.
    let out = bin()
        .arg("--repo")
        .arg(tmp.path())
        .arg("compile")
        .output()
        .unwrap();
    assert_eq!(code(&out), 3, "I/O error exits 3");
}

#[test]
fn registry_query_before_compile_exits_3() {
    let tmp = tempfile::tempdir().unwrap();
    write_spec(tmp.path(), "001-a", "001-a", "approved");
    // No compile yet -> registry.json missing -> I/O error.
    let out = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["registry", "list"])
        .output()
        .unwrap();
    assert_eq!(code(&out), 3);
}

#[test]
fn index_then_check_fresh_then_stale() {
    let tmp = tempfile::tempdir().unwrap();
    write_spec(tmp.path(), "001-a", "001-a", "approved");

    let built = bin()
        .arg("--repo")
        .arg(tmp.path())
        .arg("index")
        .output()
        .unwrap();
    assert_eq!(code(&built), 0, "index writes -> 0");
    // Sharded committed form (spec 024): per-spec shard, no monolithic index.json.
    assert!(
        tmp.path()
            .join(".derived/codebase-index/by-spec/001-a.json")
            .is_file()
    );

    let fresh = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["index", "check"])
        .output()
        .unwrap();
    assert_eq!(code(&fresh), 0, "fresh -> 0");

    // Mutate a hashed input -> stale.
    write_spec(tmp.path(), "001-a", "001-a", "draft");
    let stale = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["index", "check"])
        .output()
        .unwrap();
    assert_eq!(code(&stale), 2, "stale -> 2");
}

#[test]
fn index_render_and_orphans_projections() {
    let tmp = tempfile::tempdir().unwrap();
    let write_claiming_spec = |id: &str, target: &str| {
        let dir = tmp.path().join("specs").join(id);
        fs::create_dir_all(&dir).unwrap();
        fs::write(
            dir.join("spec.md"),
            format!(
                "---\nid: \"{id}\"\ntitle: \"T\"\nstatus: approved\ncreated: \"2026-06-08\"\nsummary: \"s\"\nestablishes:\n  - \"{target}\"\n---\n# {id}\n"
            ),
        )
        .unwrap();
    };
    // 001-a claims a path that resolves -> mapped; 002-b claims a path that
    // resolves nowhere -> orphaned.
    fs::create_dir_all(tmp.path().join("src")).unwrap();
    fs::write(tmp.path().join("src/lib.rs"), "// Spec: 001-a\n").unwrap();
    write_claiming_spec("001-a", "src/lib.rs");
    write_claiming_spec("002-b", "src/missing.rs");

    // Projections before `index` has run: exit 3 (missing artifact).
    let early_render = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["index", "render"])
        .output()
        .unwrap();
    assert_eq!(code(&early_render), 3, "render without index -> 3");
    let early_orphans = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["index", "orphans"])
        .output()
        .unwrap();
    assert_eq!(code(&early_orphans), 3, "orphans without index -> 3");

    let built = bin()
        .arg("--repo")
        .arg(tmp.path())
        .arg("index")
        .output()
        .unwrap();
    assert_eq!(code(&built), 0);

    // Orphans, text and JSON forms.
    let orphans_text = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["index", "orphans"])
        .output()
        .unwrap();
    assert_eq!(code(&orphans_text), 0, "orphans is a query, not a gate");
    // Spec 059 §3.1: two named groups, not one flat list. This fixture indexes
    // without compiling, so no registry is committed and every orphan reads as
    // in flight, which is the "cannot say otherwise" rule rather than a
    // failure: a read verb that answered from the index alone must not start
    // failing because a different artifact is missing.
    let orphans_out = String::from_utf8_lossy(&orphans_text.stdout);
    assert!(orphans_out.contains("in flight"), "{orphans_out}");
    assert!(orphans_out.contains("002-b"), "{orphans_out}");

    let orphans_json = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["index", "orphans", "--json"])
        .output()
        .unwrap();
    assert_eq!(code(&orphans_json), 0);
    let partitioned: serde_json::Value = serde_json::from_slice(&orphans_json.stdout).unwrap();
    assert_eq!(partitioned["orphaned"], serde_json::json!([]));
    assert_eq!(partitioned["inFlight"], serde_json::json!(["002-b"]));

    // Render: exit 0 even with diagnostics in the artifact; contractual
    // sections present in order.
    let render = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["index", "render"])
        .output()
        .unwrap();
    assert_eq!(code(&render), 0, "diagnostics do not fail a render");
    let md = String::from_utf8_lossy(&render.stdout);
    let positions: Vec<usize> = [
        "# spec-spine codebase index",
        "## Packages",
        "## Traceability",
    ]
    .iter()
    .map(|s| md.find(s).unwrap_or_else(|| panic!("missing section {s}")))
    .collect();
    assert!(positions.windows(2).all(|w| w[0] < w[1]), "section order");
    assert!(md.contains("### Orphaned specs"));
    assert!(md.contains("- 002-b"));
    assert!(md.ends_with('\n'));

    // Empty orphans list -> empty output, still exit 0.
    fs::remove_dir_all(tmp.path().join("specs/002-b")).unwrap();
    let rebuilt = bin()
        .arg("--repo")
        .arg(tmp.path())
        .arg("index")
        .output()
        .unwrap();
    assert_eq!(code(&rebuilt), 0);
    let none = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["index", "orphans"])
        .output()
        .unwrap();
    assert_eq!(code(&none), 0);
    // Spec 059 §3.1: with both groups empty the verb stays silent, as it did
    // before the partition.
    assert!(
        none.stdout.is_empty(),
        "{}",
        String::from_utf8_lossy(&none.stdout)
    );
}

#[test]
fn lint_fail_on_warn_gating() {
    let tmp = tempfile::tempdir().unwrap();
    // An ordinary spec with no ownership edge -> L-001 (warning).
    write_spec(tmp.path(), "001-a", "001-a", "approved");

    let lenient = bin()
        .arg("--repo")
        .arg(tmp.path())
        .arg("lint")
        .output()
        .unwrap();
    assert_eq!(code(&lenient), 0, "warnings alone do not fail");

    let strict = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["lint", "--fail-on-warn"])
        .output()
        .unwrap();
    assert_eq!(code(&strict), 1, "--fail-on-warn fails on a warning");
}

#[test]
fn compile_check_exit_contract() {
    // Spec 031 3.2: 0 fresh, 1 validation failed, 2 stale. Validation outranks
    // staleness.
    let tmp = tempfile::tempdir().unwrap();
    write_spec(tmp.path(), "001-a", "001-a", "approved");
    let run = |args: &[&str]| {
        bin()
            .arg("--repo")
            .arg(tmp.path())
            .args(args)
            .output()
            .unwrap()
    };

    // Never compiled: the committed registry is not vouching for anything.
    assert_eq!(
        code(&run(&["compile", "--check"])),
        2,
        "unbuilt -> stale (2)"
    );

    assert_eq!(code(&run(&["compile"])), 0);
    assert_eq!(
        code(&run(&["compile", "--check"])),
        0,
        "just compiled -> fresh (0)"
    );

    // --check must not have written anything, so a second check still agrees
    // and no build-meta sidecar was produced by it.
    let meta = tmp.path().join(".derived/spec-registry/build-meta.json");
    let meta_before = fs::read(&meta).unwrap();
    assert_eq!(code(&run(&["compile", "--check"])), 0);
    assert_eq!(
        fs::read(&meta).unwrap(),
        meta_before,
        "--check must not restamp build-meta.json"
    );

    // Edit a spec.md without recompiling: the PR #61 regression.
    let spec_md = tmp.path().join("specs/001-a/spec.md");
    let edited = fs::read_to_string(&spec_md).unwrap() + "\nmore body\n";
    fs::write(&spec_md, edited).unwrap();
    let stale = run(&["compile", "--check"]);
    assert_eq!(code(&stale), 2, "edited spec, stale shard -> 2");
    assert!(
        String::from_utf8_lossy(&stale.stderr).contains("modified 001-a.json"),
        "stale detail belongs on stderr: {}",
        String::from_utf8_lossy(&stale.stderr)
    );

    // Break validation while the shard is ALSO stale: validation wins (1).
    fs::write(
        &spec_md,
        "---\nid: \"mismatched\"\ntitle: \"T\"\nstatus: approved\ncreated: \"2026-06-08\"\nsummary: \"s\"\n---\n",
    )
    .unwrap();
    assert_eq!(
        code(&run(&["compile", "--check"])),
        1,
        "validation outranks staleness"
    );
}

#[test]
fn index_coverage_reports_and_gates() {
    // Spec 032: `index coverage` is a freshness-guarded read verb over the
    // tree and the committed index; `--fail-on-untraced` is the whole-tree
    // "fully specified" assertion.
    let tmp = tempfile::tempdir().unwrap();
    let r = tmp.path();
    let write = |rel: &str, content: &str| {
        let p = r.join(rel);
        fs::create_dir_all(p.parent().unwrap()).unwrap();
        fs::write(p, content).unwrap();
    };
    write(
        "Cargo.toml",
        "[package]\nname = \"root\"\nversion = \"0.1.0\"\n",
    );
    write("src/lib.rs", "pub fn a() {}\n");
    write("src/other.rs", "pub fn b() {}\n");
    write(
        "specs/001-a/spec.md",
        "---\nid: \"001-a\"\ntitle: \"T\"\nstatus: approved\ncreated: \"2026-06-08\"\nsummary: \"s\"\nestablishes:\n  - \"src/lib.rs\"\n---\n# 001-a\n",
    );
    let run = |args: &[&str]| bin().arg("--repo").arg(r).args(args).output().unwrap();

    assert_eq!(
        code(&run(&["index", "coverage"])),
        3,
        "no committed index -> artifact missing (3)"
    );
    assert_eq!(code(&run(&["index"])), 0);

    let text = run(&["index", "coverage"]);
    assert_eq!(code(&text), 0, "a report, not a gate");
    let out = String::from_utf8_lossy(&text.stdout);
    assert!(
        out.contains(
            "coverage: 1/2 source files specifically claimed (50.0%); 0 floor-only, 1 unclaimed"
        ),
        "{out}"
    );
    assert!(
        out.contains("unclaimed (no owning spec):\n  src/other.rs"),
        "{out}"
    );

    let json = run(&["index", "coverage", "--json"]);
    assert_eq!(code(&json), 0);
    let report: serde_json::Value = serde_json::from_slice(&json.stdout).unwrap();
    assert_eq!(report["sourceFiles"], 2);
    assert_eq!(report["claimedFiles"], 1);
    assert_eq!(
        report["unclaimedFiles"],
        serde_json::json!(["src/other.rs"])
    );

    assert_eq!(
        code(&run(&["index", "coverage", "--fail-on-untraced"])),
        1,
        "an untraced file fails the assertion"
    );

    // Claim the file, re-index: fully specified.
    write(
        "specs/001-a/spec.md",
        "---\nid: \"001-a\"\ntitle: \"T\"\nstatus: approved\ncreated: \"2026-06-08\"\nsummary: \"s\"\nestablishes:\n  - \"src/\"\n---\n# 001-a\n",
    );
    assert_eq!(
        code(&run(&["index", "coverage"])),
        2,
        "stale index -> 2, never a report over the wrong ledger"
    );
    assert_eq!(code(&run(&["index"])), 0);
    let full = run(&["index", "coverage", "--fail-on-untraced"]);
    assert_eq!(code(&full), 0, "{}", String::from_utf8_lossy(&full.stderr));
    assert!(
        String::from_utf8_lossy(&full.stdout)
            .contains("coverage: 2/2 source files specifically claimed (100.0%)")
    );
}

// ===== spec 035: a reader that stops early is not an error =====

/// `println!` unwraps its write, so a closed reader panicked the process:
/// `spec-spine registry list --json | head` exited **101** with a backtrace,
/// outside the documented 0/1/2/3 contract. Piping into `head` or a pager is
/// ordinary use.
///
/// The fixture is deliberately oversized. The child must still be mid-write
/// when the reader goes away, so the output has to exceed the OS pipe buffer
/// (64 KiB on Linux, smaller on some platforms); 30 specs with an 8 KiB summary
/// each is comfortably past any of them.
#[test]
fn closed_reader_exits_cleanly_rather_than_panicking() {
    use std::io::Read;
    use std::process::Stdio;

    let tmp = tempfile::tempdir().unwrap();
    let filler = "x".repeat(8192);
    for i in 0..30 {
        let id = format!("{i:03}-spec");
        let dir = tmp.path().join("specs").join(&id);
        fs::create_dir_all(&dir).unwrap();
        fs::write(
            dir.join("spec.md"),
            format!(
                "---\nid: \"{id}\"\ntitle: \"T\"\nstatus: approved\ncreated: \"2026-06-08\"\nsummary: \"{filler}\"\n---\n# {id}\n"
            ),
        )
        .unwrap();
    }

    // `registry list` reads the committed shards, so the corpus has to exist.
    let compiled = bin()
        .arg("--repo")
        .arg(tmp.path())
        .arg("compile")
        .output()
        .unwrap();
    assert_eq!(code(&compiled), 0, "fixture must compile");

    let mut child = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["registry", "list", "--json"])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();

    // Read a little, then close the pipe: exactly what `| head -c 32` does.
    let mut stdout = child.stdout.take().unwrap();
    let mut buf = [0u8; 32];
    let _ = stdout.read(&mut buf);
    drop(stdout);

    let out = child.wait_with_output().unwrap();
    let stderr = String::from_utf8_lossy(&out.stderr);

    assert_ne!(
        out.status.code(),
        Some(101),
        "a closed reader must not panic the process; stderr: {stderr}"
    );
    assert!(
        !stderr.contains("panicked"),
        "no panic should reach stderr; stderr: {stderr}"
    );
    assert_eq!(
        out.status.code(),
        Some(0),
        "a reader that stops early is a normal end; stderr: {stderr}"
    );
}

/// Byte offsets of panicking **stdout** macro calls on one source line.
///
/// Every occurrence is examined, not just the first: `println!(` also occurs
/// inside `eprintln!(`, so a line carrying a stderr call before a real stdout
/// one would otherwise be cleared by its first match and the real call never
/// seen. A gate meant to be permanent proof cannot have a false negative.
fn panicking_stdout_macros(line: &str) -> Vec<usize> {
    let mut hits = Vec::new();
    if line.trim_start().starts_with("//") {
        return hits;
    }
    for mac in ["print!(", "println!("] {
        let mut from = 0;
        while let Some(rel) = line[from..].find(mac) {
            let at = from + rel;
            // Stderr keeps the panicking macros by design (spec 035 §3.3).
            let is_stderr = at > 0 && line.as_bytes()[at - 1] == b'e';
            if !is_stderr {
                hits.push(at);
            }
            from = at + mac.len();
        }
    }
    hits
}

#[test]
fn scanner_does_not_let_a_stderr_call_mask_a_stdout_one() {
    assert!(panicking_stdout_macros(r#"eprintln!("x");"#).is_empty());
    assert!(panicking_stdout_macros(r#"eprint!("x");"#).is_empty());
    assert!(panicking_stdout_macros("// println!(\"a comment\");").is_empty());
    assert!(!panicking_stdout_macros(r#"println!("x");"#).is_empty());
    assert!(!panicking_stdout_macros(r#"print!("x");"#).is_empty());
    // The regression: the stderr call comes first and must not clear the line.
    assert!(!panicking_stdout_macros(r#"eprintln!("{}", x); println!("{}", y);"#).is_empty());
    assert!(!panicking_stdout_macros(r#"eprint!("{}", x); print!("{}", y);"#).is_empty());
}

/// Spec 035 §3.5(3). The block path (`index render`, `index coverage`) cannot be
/// exercised by a pipe-breaking test: its output fits inside a pipe buffer on
/// any corpus small enough to build in one, so such a test could never fail.
/// The guarantee is asserted structurally instead. This is the check that would
/// have caught the two `print!` sites a line-only migration left behind.
#[test]
fn no_panicking_stdout_macro_remains_in_the_cli() {
    let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
    let mut offenders: Vec<String> = Vec::new();

    // Recursive: `src/` is flat today, but a future `src/util/` must not escape
    // the enforcement by being invisible to it.
    let mut dirs = vec![src.clone()];
    let mut files: Vec<std::path::PathBuf> = Vec::new();
    while let Some(dir) = dirs.pop() {
        for entry in fs::read_dir(&dir).unwrap() {
            let p = entry.unwrap().path();
            if p.is_dir() {
                dirs.push(p);
            } else {
                files.push(p);
            }
        }
    }

    for path in files {
        if path.extension().is_none_or(|e| e != "rs") {
            continue;
        }
        let text = fs::read_to_string(&path).unwrap();
        for (n, raw) in text.lines().enumerate() {
            let line = raw.trim_start();
            if !panicking_stdout_macros(line).is_empty() {
                offenders.push(format!(
                    "{}:{}: {line}",
                    path.strip_prefix(&src).unwrap_or(&path).display(),
                    n + 1
                ));
            }
        }
    }

    assert!(
        offenders.is_empty(),
        "CLI stdout must go through out.rs, not a panicking macro (spec 035):\n{}",
        offenders.join("\n")
    );
}

// ===== spec 037: machine-readable verdicts =====

/// A minimal governed repo the six adjudicating verbs all have something to say
/// about: one crate claimed by spec `001-a`, compiled and indexed.
fn verdict_fixture(root: &Path) {
    let w = |rel: &str, content: &str| {
        let p = root.join(rel);
        fs::create_dir_all(p.parent().unwrap()).unwrap();
        fs::write(p, content).unwrap();
    };
    w("Cargo.toml", "[workspace]\nmembers = [\"crate-a\"]\n");
    w(
        "crate-a/Cargo.toml",
        "[package]\nname = \"crate-a\"\nversion = \"0.1.0\"\n\
         [package.metadata.spec-spine]\nspec = \"001-a\"\n",
    );
    w("crate-a/src/lib.rs", "pub fn a() {}\n");
    w(
        "specs/001-a/spec.md",
        "---\nid: \"001-a\"\ntitle: \"A\"\nstatus: approved\ncreated: \"2026-06-09\"\n\
         summary: \"s\"\nestablishes:\n  - \"crate-a/src/lib.rs\"\n---\n# 001-a\n## body\n",
    );
    for verb in ["compile", "index"] {
        let out = bin().arg("--repo").arg(root).arg(verb).output().unwrap();
        assert_eq!(code(&out), 0, "fixture {verb}: {:?}", out.status);
    }
}

fn run_in(root: &Path, args: &[&str]) -> std::process::Output {
    bin()
        .arg("--repo")
        .arg(root)
        .args(args)
        .output()
        .expect("spawn spec-spine")
}

/// Write `paths` for `couple --paths-from` and return the argument.
fn changed_paths(root: &Path, paths: &[&str]) -> std::path::PathBuf {
    let p = root.join("changed.txt");
    fs::write(&p, format!("{}\n", paths.join("\n"))).unwrap();
    p
}

fn envelope(out: &std::process::Output) -> serde_json::Value {
    let stdout = String::from_utf8_lossy(&out.stdout);
    serde_json::from_str(&stdout).unwrap_or_else(|e| {
        panic!(
            "stdout is not one JSON document ({e}); stdout: {stdout}; stderr: {}",
            String::from_utf8_lossy(&out.stderr)
        )
    })
}

/// Spec 037 3.1: one envelope shape across all six adjudicating verbs, with a
/// `report` member and no `error` member on a corpus that passes.
#[test]
fn json_envelope_on_every_adjudicating_verb() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);
    let paths = changed_paths(root, &["crate-a/src/lib.rs", "specs/001-a/spec.md"]);
    let paths = paths.to_str().unwrap();

    let cases: [(&str, Vec<&str>); 6] = [
        ("compile.check", vec!["compile", "--check", "--json"]),
        ("index.check", vec!["index", "check", "--json"]),
        ("lint", vec!["lint", "--json"]),
        ("couple", vec!["couple", "--paths-from", paths, "--json"]),
        ("attest", vec!["attest", "--json"]),
        (
            "verify-attestation",
            vec!["verify-attestation", "--recompute", "--json"],
        ),
    ];

    for (verb, args) in cases {
        let out = run_in(root, &args);
        assert_eq!(
            code(&out),
            0,
            "{verb}: {:?}",
            String::from_utf8_lossy(&out.stderr)
        );
        let v = envelope(&out);
        // Spec 049 took the envelope to 0.2.0 by adding the `verify` verb. The
        // assertion tracks the constant rather than a literal so that a future
        // additive verb does not read as a change to these six verbs.
        assert_eq!(
            v["schemaVersion"],
            spec_spine_types::VERDICT_SCHEMA_VERSION,
            "{verb}"
        );
        assert_eq!(v["verb"], verb);
        assert_eq!(v["ok"], true, "{verb}");
        assert_eq!(v["exitCode"], 0, "{verb}");
        assert!(v.get("report").is_some(), "{verb} must carry a report");
        assert!(v.get("error").is_none(), "{verb} must carry no error");
    }
}

/// Spec 037 3.2: `--json` changes what is written, never what is decided. Every
/// failure mode returns the code the prose form returns, and `ok` agrees.
#[test]
fn json_exit_codes_match_the_prose_form() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);

    // Drift: a claimed path changed without its owning spec (exit 1).
    let paths = changed_paths(root, &["crate-a/src/lib.rs"]);
    let paths = paths.to_str().unwrap();
    let prose = run_in(root, &["couple", "--paths-from", paths]);
    let json = run_in(root, &["couple", "--paths-from", paths, "--json"]);
    assert_eq!(code(&prose), 1);
    assert_eq!(code(&json), code(&prose), "couple drift");
    let v = envelope(&json);
    assert_eq!(v["exitCode"], 1);
    assert_eq!(v["ok"], false);
    assert!(
        !v["report"]["violations"].as_array().unwrap().is_empty(),
        "the reasons ride in the report, not in prose"
    );

    // Staleness: edit a spec (a hashed input to both trees) without rerunning
    // `compile`/`index`, so one edit exercises both freshness gates (exit 2).
    let spec = root.join("specs/001-a/spec.md");
    let body = fs::read_to_string(&spec).unwrap();
    fs::write(&spec, body.replace("## body", "## body edited")).unwrap();

    for args in [
        ["index", "check"].as_slice(),
        ["compile", "--check"].as_slice(),
    ] {
        let prose = run_in(root, args);
        let mut json_args = args.to_vec();
        json_args.push("--json");
        let json = run_in(root, &json_args);
        assert_eq!(code(&prose), 2, "{args:?} prose");
        assert_eq!(code(&json), code(&prose), "{args:?} json");
        let v = envelope(&json);
        assert_eq!(v["ok"], false, "{args:?}");
        assert_eq!(v["report"]["fresh"], false, "{args:?}");
        assert!(
            v["report"]["expected"].is_string(),
            "{args:?}: the stale detail rides in the report"
        );
    }
}

/// Spec 037 3.1: `report` is the facade's payload, not a second CLI spelling of
/// it. Compared as documents rather than as strings: the envelope is canonical
/// (sorted, pretty) while the facade returns compact JSON, so the bytes of the
/// two encodings differ by construction and the claim that can hold, and that
/// the spec's own `"report": { }` example requires, is that the *payload* is one
/// shape. Any divergence in members, spelling or values fails here.
#[test]
fn json_report_equals_the_facade_payload() {
    use spec_spine_core::{
        attest_json, check_freshness_json, check_registry_freshness_json, couple_json, lint_json,
        verify_attestation_json,
    };

    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);
    let repo = root.to_str().unwrap();
    let parse = |s: String| serde_json::from_str::<serde_json::Value>(&s).unwrap();

    let cases: Vec<(&str, Vec<String>, serde_json::Value)> = vec![
        (
            "lint",
            vec!["lint".into(), "--json".into()],
            parse(lint_json("{}", repo).unwrap()),
        ),
        (
            "index.check",
            vec!["index".into(), "check".into(), "--json".into()],
            parse(check_freshness_json("{}", repo).unwrap()),
        ),
        (
            "compile.check",
            vec!["compile".into(), "--check".into(), "--json".into()],
            parse(check_registry_freshness_json("{}", repo).unwrap()),
        ),
        (
            "attest",
            vec!["attest".into(), "--json".into()],
            parse(attest_json("{}", repo, false).unwrap()),
        ),
    ];
    for (verb, args, expected) in cases {
        let args: Vec<&str> = args.iter().map(String::as_str).collect();
        let out = run_in(root, &args);
        assert_eq!(envelope(&out)["report"], expected, "{verb}");
    }

    // couple: the facade takes the diff in its request, so build the same one.
    let paths = changed_paths(root, &["crate-a/src/lib.rs"]);
    let out = run_in(
        root,
        &["couple", "--paths-from", paths.to_str().unwrap(), "--json"],
    );
    let request = serde_json::json!({
        "repoRoot": repo,
        "diff": { "files": [{ "path": "crate-a/src/lib.rs", "hunks": [], "deleted": false }] },
    });
    let expected = parse(couple_json(&request.to_string()).unwrap());
    assert_eq!(envelope(&out)["report"], expected, "couple");

    // verify-attestation: `--recompute` alone is the mode the facade models, so
    // its report is the facade's payload exactly. `--signature` has no facade
    // counterpart and contributes an additive `signature` member (spec 037 3.2
    // requires the envelope to report every verdict the prose reports).
    let attestation: serde_json::Value = serde_json::from_slice(
        &fs::read(root.join(".derived/attestation/attestation.json")).unwrap(),
    )
    .unwrap();
    let out = run_in(root, &["verify-attestation", "--recompute", "--json"]);
    let request = serde_json::json!({ "repoRoot": repo, "attestation": attestation });
    let expected = parse(verify_attestation_json(&request.to_string()).unwrap());
    assert_eq!(envelope(&out)["report"], expected, "verify-attestation");
}

/// Spec 037 3.3: a failure is an envelope on stdout with the mapped exit code,
/// a stable `kind`, and no `report`; stdout carries nothing else.
#[test]
fn json_error_path_is_an_envelope_on_stdout() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);

    // A malformed spec-spine.toml is Error::Config -> exit 3.
    fs::write(root.join("spec-spine.toml"), "[layout\n").unwrap();
    let out = run_in(root, &["lint", "--json"]);
    assert_eq!(code(&out), 3);
    let v = envelope(&out);
    assert_eq!(v["verb"], "lint");
    assert_eq!(v["exitCode"], 3);
    assert_eq!(v["ok"], false);
    assert_eq!(v["error"]["kind"], "config");
    assert!(v.get("report").is_none(), "error and report are exclusive");
    assert!(
        v["error"]["message"].as_str().unwrap().len() > 1,
        "the message is human text, present but unpromised"
    );

    // The writing form of `compile` has no machine-readable verdict (3 4), and
    // says so as an envelope rather than as an unparseable sentence.
    fs::remove_file(root.join("spec-spine.toml")).unwrap();
    let out = run_in(root, &["compile", "--json"]);
    assert_eq!(code(&out), 3);
    assert_eq!(envelope(&out)["error"]["kind"], "config");

    // A validation failure is the one error class with a structured payload,
    // and it must survive the generic error path: a consumer that reads
    // `lint --json`'s violation array on exit 1 gets the same data here rather
    // than a bare sentence and a fallback to parsing stderr.
    fs::write(
        root.join("specs/001-a/spec.md"),
        "---\nid: \"999-mismatched\"\ntitle: \"A\"\nstatus: approved\n\
         created: \"2026-06-09\"\nsummary: \"s\"\n---\n# x\n",
    )
    .unwrap();
    let prose = run_in(root, &["compile", "--check"]);
    let out = run_in(root, &["compile", "--check", "--json"]);
    assert_eq!(code(&prose), 1, "id must match the directory name");
    assert_eq!(code(&out), code(&prose), "the flag does not move the code");
    let v = envelope(&out);
    assert_eq!(v["error"]["kind"], "validation");
    let violations = v["error"]["violations"].as_array().unwrap();
    assert!(!violations.is_empty(), "{v}");
    assert!(
        violations[0]["code"].as_str().unwrap().starts_with("V-"),
        "{v}"
    );
    // ...and stdout is the only channel written, since the envelope already
    // carries what the prose form puts on stderr.
    assert!(
        out.stderr.is_empty(),
        "no second channel under --json: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        !prose.stderr.is_empty(),
        "the prose form still reports each violation on stderr"
    );
}

/// Spec 037 3.5: the envelope goes through the closed-reader write, on every
/// verb. `spec-spine <verb> --json | head` is a `0`, not a `101`.
#[test]
fn json_survives_a_closed_reader_on_every_verb() {
    use std::io::Read;
    use std::process::Stdio;

    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);
    let paths = changed_paths(root, &["crate-a/src/lib.rs"]);
    let paths = paths.to_string_lossy().into_owned();

    let cases: [Vec<&str>; 6] = [
        vec!["compile", "--check", "--json"],
        vec!["index", "check", "--json"],
        vec!["lint", "--json"],
        vec!["couple", "--paths-from", &paths, "--json"],
        vec!["attest", "--json"],
        vec!["verify-attestation", "--recompute", "--json"],
    ];

    for args in cases {
        let mut child = bin()
            .arg("--repo")
            .arg(root)
            .args(&args)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        let mut stdout = child.stdout.take().unwrap();
        let mut buf = [0u8; 8];
        let _ = stdout.read(&mut buf);
        drop(stdout);
        let out = child.wait_with_output().unwrap();
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            !stderr.contains("panicked"),
            "{args:?} panicked on a closed reader: {stderr}"
        );
        assert_ne!(out.status.code(), Some(101), "{args:?}");
    }
}

/// Spec 037 3.3: without the flag nothing moves. The prose forms keep their
/// stdout text, so no existing consumer is disturbed by this spec.
#[test]
fn prose_output_is_unchanged_without_the_flag() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);

    let compile = run_in(root, &["compile", "--check"]);
    assert!(
        String::from_utf8_lossy(&compile.stdout).starts_with("spec-registry is fresh:"),
        "{}",
        String::from_utf8_lossy(&compile.stdout)
    );
    let index = run_in(root, &["index", "check"]);
    // Spec 057 §3.3 adds one line under the verdict when the ledger has a gap,
    // so the assertion is on the verdict line rather than on the whole stream.
    // The fixture has one claimed-but-unwitnessed path, which is what that line
    // reports; the verdict itself is untouched, which is what 037 §3.3 is about.
    let index_out = String::from_utf8_lossy(&index.stdout);
    assert_eq!(
        index_out.lines().next(),
        Some("index is fresh"),
        "{index_out}"
    );
    assert!(index_out.contains("unwitnessed claims: 1"), "{index_out}");
    let lint = run_in(root, &["lint"]);
    assert!(
        String::from_utf8_lossy(&lint.stdout).contains("lint: 0 error(s)"),
        "{}",
        String::from_utf8_lossy(&lint.stdout)
    );
    let paths = changed_paths(root, &["crate-a/src/lib.rs", "specs/001-a/spec.md"]);
    let couple = run_in(root, &["couple", "--paths-from", paths.to_str().unwrap()]);
    assert!(
        String::from_utf8_lossy(&couple.stdout).contains("no drift"),
        "{}",
        String::from_utf8_lossy(&couple.stdout)
    );
    let attest = run_in(root, &["attest"]);
    assert!(
        String::from_utf8_lossy(&attest.stdout).contains("attestationHash:"),
        "{}",
        String::from_utf8_lossy(&attest.stdout)
    );
    let verify = run_in(root, &["verify-attestation", "--recompute"]);
    assert!(
        String::from_utf8_lossy(&verify.stdout).contains("recompute: MATCH"),
        "{}",
        String::from_utf8_lossy(&verify.stdout)
    );
}

/// Spec 037 D-2: `--signature` is the mode the facade does not model, and the
/// additive `signature` member is the only payload shape in this spec with no
/// facade counterpart to pin it. Exercised end to end so a rename is caught.
///
/// The public key is recovered from the seal's own `keyId`, which spec 023
/// defines as the hex public key, so the test needs no key derivation of its
/// own and stays a pure round-trip through the two commands.
#[test]
fn json_verify_attestation_reports_the_signature_mode() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);

    let seed = root.join("signing.key");
    fs::write(&seed, [7u8; 32]).unwrap();
    let signed = run_in(root, &["attest", "--sign", "--key", seed.to_str().unwrap()]);
    assert_eq!(
        code(&signed),
        0,
        "{}",
        String::from_utf8_lossy(&signed.stderr)
    );

    let seal: serde_json::Value = serde_json::from_slice(
        &fs::read(root.join(".derived/attestation/attestation.sig")).unwrap(),
    )
    .unwrap();
    let key_id = seal["keyId"].as_str().unwrap().to_string();
    let public = root.join("public.hex");
    fs::write(&public, &key_id).unwrap();

    // Both modes at once: the report carries the facade's `outcome` and the
    // additive `signature` member side by side.
    let out = run_in(
        root,
        &[
            "verify-attestation",
            "--recompute",
            "--signature",
            "--public-key",
            public.to_str().unwrap(),
            "--json",
        ],
    );
    assert_eq!(code(&out), 0, "{}", String::from_utf8_lossy(&out.stderr));
    let v = envelope(&out);
    assert_eq!(v["ok"], true);
    assert_eq!(v["report"]["outcome"], "match");
    assert_eq!(v["report"]["signature"]["valid"], true);
    assert_eq!(v["report"]["signature"]["keyId"], key_id.as_str());

    // Signature-only: no `outcome`, because recompute did not run.
    let out = run_in(
        root,
        &[
            "verify-attestation",
            "--signature",
            "--public-key",
            public.to_str().unwrap(),
            "--json",
        ],
    );
    assert_eq!(code(&out), 0);
    let v = envelope(&out);
    assert!(v["report"].get("outcome").is_none(), "{v}");
    assert_eq!(v["report"]["signature"]["valid"], true);

    // A wrong key is a failed verification: exit 1, and the envelope says so
    // rather than merely omitting the good news.
    fs::write(&public, "00".repeat(32)).unwrap();
    let out = run_in(
        root,
        &[
            "verify-attestation",
            "--signature",
            "--public-key",
            public.to_str().unwrap(),
            "--json",
        ],
    );
    assert_eq!(code(&out), 1);
    let v = envelope(&out);
    assert_eq!(v["ok"], false);
    assert_eq!(v["exitCode"], 1);
    assert_eq!(v["report"]["signature"]["valid"], false);
}

/// Spec 037 3.3: a `verify-attestation` with no mode selected is a config
/// error, not an affirmative `ok: true` over an empty report.
#[test]
fn json_verify_attestation_with_no_mode_is_an_error_envelope() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);
    let out = run_in(root, &["verify-attestation", "--json"]);
    assert_eq!(code(&out), 3);
    let v = envelope(&out);
    assert_eq!(v["ok"], false);
    assert_eq!(v["error"]["kind"], "config");
    assert!(v.get("report").is_none());
}

// ===== spec 038: `registry plan` =====

/// The scheduling projection, end to end: prose lists the ready set and counts
/// the rest, `--json` carries every blocker with the state that made it one.
///
/// Emitted **bare**, like every other `registry` projection: spec 037's verdict
/// envelope wraps the adjudicating verbs, and 037 4 keeps it off the read verbs,
/// so `plan` joins them rather than splitting the group into two output shapes.
#[test]
fn registry_plan_partitions_the_corpus() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    let spec = |id: &str, body: &str| {
        let dir = root.join("specs").join(id);
        fs::create_dir_all(&dir).unwrap();
        fs::write(
            dir.join("spec.md"),
            format!(
                "---\nid: \"{id}\"\ntitle: \"T\"\nstatus: approved\ncreated: \"2026-09-06\"\n\
                 summary: \"s\"\n{body}---\n# {id}\n"
            ),
        )
        .unwrap();
    };
    spec("001-done", "implementation: complete\n");
    spec(
        "002-now",
        "implementation: pending\ndepends_on: [\"001-done\"]\n",
    );
    spec(
        "003-later",
        "implementation: pending\ndepends_on: [\"002-now\"]\n",
    );
    assert_eq!(code(&run_in(root, &["compile"])), 0);

    let prose = run_in(root, &["registry", "plan"]);
    assert_eq!(
        code(&prose),
        0,
        "{}",
        String::from_utf8_lossy(&prose.stderr)
    );
    let text = String::from_utf8_lossy(&prose.stdout);
    // Spec 060 §3.1: the prose renders what the structure holds. Titles on both
    // sets, each blocked spec's reasons rather than a count, and the
    // not-schedulable remainder so the figures add up to the corpus.
    assert!(text.contains("ready (1):"), "{text}");
    assert!(text.contains("002-now  T"), "{text}");
    assert!(text.contains("blocked (1):"), "{text}");
    assert!(text.contains("blocked by 002-now (pending)"), "{text}");
    assert!(
        text.contains("3 specs: 1 ready, 1 blocked, 1 not schedulable"),
        "{text}"
    );
    assert!(
        !text.contains("001-done"),
        "a finished spec is not offered: {text}"
    );

    let out = run_in(root, &["registry", "plan", "--json"]);
    assert_eq!(code(&out), 0);
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    // Bare report, not a spec 037 envelope.
    assert!(v.get("schemaVersion").is_none(), "{v}");
    // Spec 060 §3.3: ready entries are objects carrying the title, and blocked
    // entries gain one additively. The breaking half is deliberate: a parallel
    // titles array to be zipped by position is the shape that generates the
    // join code this spec exists to delete.
    assert_eq!(
        v["ready"],
        serde_json::json!([{ "id": "002-now", "title": "T" }])
    );
    assert_eq!(
        v["blocked"],
        serde_json::json!([
            {
                "id": "003-later",
                "title": "T",
                "blockedBy": [{ "id": "002-now", "state": "pending" }]
            }
        ])
    );
    assert_eq!(v["notSchedulable"], 1);

    // §3.2: `--next` is the single pick, and the object rather than a
    // one-element array.
    let next = run_in(root, &["registry", "plan", "--next", "--json"]);
    assert_eq!(code(&next), 0);
    let n: serde_json::Value = serde_json::from_slice(&next.stdout).unwrap();
    assert_eq!(n, serde_json::json!({ "id": "002-now", "title": "T" }));

    // A corpus with nothing schedulable says so rather than printing an empty
    // page: the prose form has a reader, and "(nothing ready)" is an answer.
    let empty = tempfile::tempdir().unwrap();
    let dir = empty.path().join("specs/001-done");
    fs::create_dir_all(&dir).unwrap();
    fs::write(
        dir.join("spec.md"),
        "---\nid: \"001-done\"\ntitle: \"T\"\nstatus: approved\ncreated: \"2026-09-06\"\n\
         summary: \"s\"\nimplementation: complete\n---\n# 001-done\n",
    )
    .unwrap();
    assert_eq!(code(&run_in(empty.path(), &["compile"])), 0);
    let out = run_in(empty.path(), &["registry", "plan"]);
    assert_eq!(code(&out), 0);
    let text = String::from_utf8_lossy(&out.stdout);
    assert_eq!(
        text.trim(),
        "(nothing ready), blocked: 0\n\n1 specs: 0 ready, 0 blocked, 1 not schedulable",
        "the `(nothing ready)` line is unchanged (spec 060 §3.1) and the \
         remainder follows it: on a finished corpus that figure is the whole \
         answer, and without it `blocked: 0` reads as though the specs vanished"
    );
}
// ===== spec 042: per-spec attestation =====

/// `attest --spec` writes `by-spec/<id>.json`, `--sign` seals it beside itself,
/// and `verify-attestation --spec` checks both modes back.
#[test]
fn attest_spec_writes_signs_and_verifies_one_spec() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);

    let out = run_in(root, &["attest", "--spec", "001-a"]);
    assert_eq!(code(&out), 0, "{}", String::from_utf8_lossy(&out.stderr));
    let path = root.join(".derived/attestation/by-spec/001-a.json");
    assert!(path.is_file(), "the payload lands under by-spec/");
    // The corpus-scoped artifact is untouched: the two scopes do not collide.
    assert!(!root.join(".derived/attestation/attestation.json").exists());

    let payload: serde_json::Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
    assert_eq!(payload["specId"], "001-a");
    assert_eq!(payload["schemaVersion"], "0.1.0");
    assert_eq!(payload["lifecycle"]["status"], "approved");
    assert_eq!(payload["verdicts"]["resolution"]["ok"], true);
    assert_eq!(
        payload["units"][0]["unit"]["path"], "crate-a/src/lib.rs",
        "the owning unit, with the hash of what it resolved to"
    );
    assert!(payload["units"][0]["contentHash"].is_string());

    // Sign, then verify both modes. The public key is the seal's own keyId.
    let seed = root.join("signing.key");
    fs::write(&seed, [3u8; 32]).unwrap();
    let signed = run_in(
        root,
        &[
            "attest",
            "--spec",
            "001-a",
            "--sign",
            "--key",
            seed.to_str().unwrap(),
        ],
    );
    assert_eq!(
        code(&signed),
        0,
        "{}",
        String::from_utf8_lossy(&signed.stderr)
    );
    let seal_path = root.join(".derived/attestation/by-spec/001-a.sig");
    assert!(seal_path.is_file(), "the seal is the payload's sibling");

    let seal: serde_json::Value = serde_json::from_slice(&fs::read(&seal_path).unwrap()).unwrap();
    let public = root.join("public.hex");
    fs::write(&public, seal["keyId"].as_str().unwrap()).unwrap();
    let verified = run_in(
        root,
        &[
            "verify-attestation",
            "--spec",
            "001-a",
            "--recompute",
            "--signature",
            "--public-key",
            public.to_str().unwrap(),
        ],
    );
    assert_eq!(
        code(&verified),
        0,
        "{}",
        String::from_utf8_lossy(&verified.stderr)
    );
    let text = String::from_utf8_lossy(&verified.stdout);
    assert!(text.contains("recompute: MATCH"), "{text}");
    assert!(text.contains("signature: VALID"), "{text}");

    // Editing an owned file breaks recompute with a named outcome, not silently.
    fs::write(
        root.join("crate-a/src/lib.rs"),
        "pub fn a() {}\npub fn b() {}\n",
    )
    .unwrap();
    let stale = run_in(
        root,
        &["verify-attestation", "--spec", "001-a", "--recompute"],
    );
    assert_eq!(code(&stale), 1);
    assert!(
        String::from_utf8_lossy(&stale.stderr).contains("MISMATCH"),
        "{}",
        String::from_utf8_lossy(&stale.stderr)
    );
}

/// Spec 042 3.1: **`attest`'s exit code is not a verdict.** `0` means an
/// attestation was written and nothing about what it says, for both scopes.
///
/// This is the one verb in the tool where that is true, so it is tested rather
/// than assumed: `lint`, `couple`, `index check` and `compile --check` all put
/// their verdict in the exit code. The rule reaches the corpus-scoped verb by
/// this spec's amendment to 023, so both are exercised.
#[test]
fn attest_exits_zero_on_a_false_verdict_in_both_scopes() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);

    // A spec claiming a file that was never written: resolution.ok is false.
    fs::write(
        root.join("specs/001-a/spec.md"),
        "---\nid: \"001-a\"\ntitle: \"A\"\nstatus: approved\ncreated: \"2026-06-09\"\n\
         summary: \"s\"\nestablishes:\n  - \"crate-a/src/lib.rs\"\n  - \"crate-a/src/never.rs\"\n\
         ---\n# 001-a\n## body\n",
    )
    .unwrap();
    assert_eq!(code(&run_in(root, &["compile"])), 0);
    assert_eq!(code(&run_in(root, &["index"])), 0);

    let scoped = run_in(root, &["attest", "--spec", "001-a"]);
    assert_eq!(
        code(&scoped),
        0,
        "a record is written whatever it says: {}",
        String::from_utf8_lossy(&scoped.stderr)
    );
    let payload: serde_json::Value = serde_json::from_slice(
        &fs::read(root.join(".derived/attestation/by-spec/001-a.json")).unwrap(),
    )
    .unwrap();
    assert_eq!(
        payload["verdicts"]["resolution"]["ok"], false,
        "the false verdict is recorded, not suppressed"
    );

    // The corpus scope too, which is 023's territory and reaches this rule by
    // amendment: it exits 0 even with a failing verdict inside.
    let corpus = run_in(root, &["attest"]);
    assert_eq!(
        code(&corpus),
        0,
        "{}",
        String::from_utf8_lossy(&corpus.stderr)
    );
}

/// An unknown spec id is `NotFound` (exit 1) and writes nothing, rather than a
/// payload over a spec that does not exist.
#[test]
fn attest_spec_refuses_an_unknown_id() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);
    let out = run_in(root, &["attest", "--spec", "999-nope"]);
    assert_eq!(code(&out), 1);
    assert!(!root.join(".derived/attestation/by-spec").exists());
}

/// `attest --spec --json` carries the same `{ attestation, attestationHash }`
/// payload the facade returns, inside spec 037's envelope.
#[test]
fn attest_spec_json_rides_in_the_verdict_envelope() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);

    let out = run_in(root, &["attest", "--spec", "001-a", "--json"]);
    assert_eq!(code(&out), 0);
    let v = envelope(&out);
    assert_eq!(v["verb"], "attest");
    assert_eq!(v["ok"], true);
    assert_eq!(v["report"]["attestation"]["specId"], "001-a");
    assert!(v["report"]["attestationHash"].is_string());

    // The library call passes `"{}"` (so, `Config::default()`) while the CLI
    // loads whatever config is on disk. They agree only because the fixture
    // writes none; asserted rather than assumed, so extending `verdict_fixture`
    // with a `spec-spine.toml` fails here saying why instead of as a puzzling
    // payload mismatch.
    assert!(
        !root.join("spec-spine.toml").exists(),
        "this comparison assumes the fixture is on the default config"
    );
    let expected: serde_json::Value = serde_json::from_str(
        &spec_spine_core::attest_spec_json("{}", root.to_str().unwrap(), "001-a").unwrap(),
    )
    .unwrap();
    assert_eq!(v["report"], expected, "one payload shape per verb");
}

/// Spec 042 3.1: there is no per-spec coupling verdict, so `--with-coupling`
/// combined with `--spec` is refused rather than accepted and ignored.
///
/// Accepting it would return exit 0 and a payload silently missing the verdict
/// the caller asked for, which is the skip-as-pass shape spec 023 FR-006 rules
/// out for every mode in this verb.
#[test]
fn attest_refuses_with_coupling_scoped_to_one_spec() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);

    let out = run_in(root, &["attest", "--spec", "001-a", "--with-coupling"]);
    assert_eq!(code(&out), 3, "a mode that cannot run fails visibly");
    let message = String::from_utf8_lossy(&out.stderr);
    assert!(message.contains("--with-coupling"), "{message}");
    assert!(message.contains("--spec"), "{message}");
    assert!(
        !root.join(".derived/attestation/by-spec").exists(),
        "and writes nothing"
    );

    // Each flag alone still works.
    assert_eq!(code(&run_in(root, &["attest", "--spec", "001-a"])), 0);
    assert_eq!(code(&run_in(root, &["attest", "--with-coupling"])), 0);
}

/// A `--spec` id is one path segment, so it cannot walk out of the attestation
/// directory into an unrelated file.
#[test]
fn verify_attestation_refuses_a_traversing_spec_id() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);

    for id in ["../../etc/passwd", "..", "a/b", ""] {
        let out = run_in(root, &["verify-attestation", "--spec", id, "--recompute"]);
        assert_eq!(code(&out), 3, "id {id:?} must be refused");
        assert!(
            String::from_utf8_lossy(&out.stderr).contains("not a spec id"),
            "id {id:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    // A real id still works, so the guard is not simply refusing everything.
    assert_eq!(code(&run_in(root, &["attest", "--spec", "001-a"])), 0);
    assert_eq!(
        code(&run_in(
            root,
            &["verify-attestation", "--spec", "001-a", "--recompute"]
        )),
        0
    );
}

/// The seal is derived from the attestation's own filename, not a fixed name.
///
/// Spec 023 resolved a missing `--seal` to `attestation.sig` beside the payload.
/// A per-spec attestation lives at `by-spec/<id>.json`, so a fixed name would
/// give every spec in a corpus the same seal path and each signing would
/// overwrite the last (spec 042 D-5).
#[test]
fn the_seal_path_follows_the_attestation_it_signs() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    verdict_fixture(root);
    let seed = root.join("signing.key");
    fs::write(&seed, [5u8; 32]).unwrap();
    let key = seed.to_str().unwrap();

    // The corpus default is unchanged: attestation.json -> attestation.sig.
    assert_eq!(code(&run_in(root, &["attest", "--sign", "--key", key])), 0);
    assert!(root.join(".derived/attestation/attestation.sig").is_file());

    // Two specs seal to two distinct paths rather than overwriting each other.
    fs::write(root.join("crate-a/src/other.rs"), "pub fn b() {}\n").unwrap();
    fs::create_dir_all(root.join("specs/002-b")).unwrap();
    fs::write(
        root.join("specs/002-b/spec.md"),
        "---\nid: \"002-b\"\ntitle: \"B\"\nstatus: approved\ncreated: \"2026-06-09\"\n\
         summary: \"s\"\nestablishes:\n  - \"crate-a/src/other.rs\"\n---\n# 002-b\n## body\n",
    )
    .unwrap();
    for id in ["001-a", "002-b"] {
        assert_eq!(
            code(&run_in(
                root,
                &["attest", "--spec", id, "--sign", "--key", key]
            )),
            0,
            "sign {id}"
        );
        assert!(
            root.join(format!(".derived/attestation/by-spec/{id}.sig"))
                .is_file(),
            "{id} seals beside its own payload"
        );
    }
}

// --- `verify` (spec 049) --------------------------------------------------

/// Write a spec whose `## Verification` section holds `section` verbatim.
fn write_verify_spec(root: &Path, dir: &str, section: &str) {
    let spec_dir = root.join("specs").join(dir);
    fs::create_dir_all(&spec_dir).unwrap();
    let body = format!(
        "---\nid: \"{dir}\"\ntitle: \"T\"\nstatus: approved\ncreated: \"2026-09-06\"\nsummary: \"s\"\n---\n# {dir}\n\n## Verification\n\n{section}\n"
    );
    fs::write(spec_dir.join("spec.md"), body).unwrap();
}

#[test]
fn verify_runs_commands_and_reports_outcomes() {
    let tmp = tempfile::tempdir().unwrap();
    write_verify_spec(tmp.path(), "001-pass", "```verify:cli\ntrue\ntrue\n```");
    write_verify_spec(
        tmp.path(),
        "002-fail",
        "```verify:cli\ntrue\nexit 7\ntrue\n```",
    );
    write_verify_spec(tmp.path(), "003-prose", "- a prose bullet only");
    let run = |args: &[&str]| {
        bin()
            .arg("--repo")
            .arg(tmp.path())
            .args(args)
            .output()
            .unwrap()
    };

    // Every command exits 0 -> passed, exit 0.
    let out = run(&["verify", "001-pass"]);
    assert_eq!(code(&out), 0);
    assert!(
        String::from_utf8_lossy(&out.stdout).contains("passed (2 command(s))"),
        "{}",
        String::from_utf8_lossy(&out.stdout)
    );

    // A failure is exit 1, NOT the command's own 7 (spec 049 3.3): the
    // documented exit contract has no entry for 7.
    let out = run(&["verify", "002-fail"]);
    assert_eq!(code(&out), 1, "a failing command is a drift-tier 1");

    // Nothing declared is an honest zero.
    assert_eq!(code(&run(&["verify", "003-prose"])), 0);

    // A missing spec is 1 (not found), never 2 (stale).
    assert_eq!(code(&run(&["verify", "404-gone"])), 1);
}

#[test]
fn verify_json_is_a_verdict_envelope_that_agrees_with_the_exit_code() {
    let tmp = tempfile::tempdir().unwrap();
    write_verify_spec(tmp.path(), "001-pass", "```verify:cli\ntrue\n```");
    write_verify_spec(
        tmp.path(),
        "002-fail",
        "```verify:cli\ntrue\nexit 7\n```\n\n```verify:browser\nclick\n```",
    );
    write_verify_spec(tmp.path(), "003-prose", "- prose");
    let json = |id: &str| -> (i32, serde_json::Value) {
        let out = bin()
            .arg("--repo")
            .arg(tmp.path())
            .args(["verify", id, "--json"])
            .output()
            .unwrap();
        (
            code(&out),
            serde_json::from_slice(&out.stdout).expect("stdout is one JSON envelope"),
        )
    };

    let (c, v) = json("001-pass");
    assert_eq!(c, 0);
    assert_eq!(v["verb"], "verify");
    // The constant, not a literal: an additive verb elsewhere is not a change
    // to this one's envelope (spec 056 bumped it to 0.3.0 for `compile.spec`).
    assert_eq!(v["schemaVersion"], spec_spine_types::VERDICT_SCHEMA_VERSION);
    assert_eq!(v["ok"], true);
    assert_eq!(v["exitCode"], 0);
    assert_eq!(v["report"]["outcome"], "passed");
    assert_eq!(v["report"]["declared"], true);
    assert_eq!(v["report"]["ran"], 1);
    assert_eq!(v["report"]["total"], 1);

    // The failing command's own code lives in the payload, and `ran` stops at it.
    let (c, v) = json("002-fail");
    assert_eq!(c, 1);
    assert_eq!(v["exitCode"], 1, "the envelope never advertises 7");
    assert_eq!(
        v["report"]["failure"]["exitCode"], 7,
        "but the payload keeps it"
    );
    assert_eq!(v["report"]["failure"]["index"], 2);
    assert_eq!(v["report"]["failure"]["command"], "exit 7");
    assert_eq!(v["report"]["ran"], 2);
    assert_eq!(v["report"]["total"], 2);
    assert_eq!(v["report"]["skipped"][0]["tag"], "verify:browser");

    // not-declared is distinguishable from a pass without parsing prose.
    let (c, v) = json("003-prose");
    assert_eq!(c, 0);
    assert_eq!(v["ok"], true);
    assert_eq!(v["report"]["outcome"], "not-declared");
    assert_eq!(v["report"]["declared"], false);
}

#[test]
fn verify_runs_from_the_repo_root_and_stops_at_the_first_failure() {
    let tmp = tempfile::tempdir().unwrap();
    // Each command appends to a file, so the transcript is checkable on disk.
    write_verify_spec(
        tmp.path(),
        "001-order",
        "```verify:cli\nprintf a >> log.txt\nfalse\nprintf c >> log.txt\n```",
    );
    let out = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["verify", "001-order"])
        .output()
        .unwrap();
    assert_eq!(code(&out), 1);
    // `a` ran (relative path resolved against the repo root); `c` never did.
    let log = fs::read_to_string(tmp.path().join("log.txt")).unwrap();
    assert_eq!(log, "a", "later commands must not run after a failure");
}

#[test]
fn verify_plan_reads_without_running() {
    let tmp = tempfile::tempdir().unwrap();
    write_verify_spec(
        tmp.path(),
        "001-p",
        "```verify:cli\nprintf ran >> side_effect.txt\n# a comment\nsecond\n```",
    );
    let out = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["verify", "001-p", "--plan"])
        .output()
        .unwrap();
    assert_eq!(code(&out), 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(
        stdout.lines().collect::<Vec<_>>(),
        ["printf ran >> side_effect.txt", "second"],
        "comments are stripped, both commands listed"
    );
    assert!(
        !tmp.path().join("side_effect.txt").exists(),
        "--plan must run nothing"
    );
}

#[test]
fn verify_refuses_to_re_enter_itself() {
    let tmp = tempfile::tempdir().unwrap();
    // The spec's own block runs `verify` on itself: without the spec 049 3.7
    // guard this forks without bound.
    write_verify_spec(
        tmp.path(),
        "001-loop",
        "```verify:cli\nSELF --repo REPO verify 001-loop\n```",
    );
    let spec = tmp.path().join("specs/001-loop/spec.md");
    let body = fs::read_to_string(&spec)
        .unwrap()
        .replace("SELF", env!("CARGO_BIN_EXE_spec-spine"))
        .replace("REPO", tmp.path().to_str().unwrap());
    fs::write(&spec, body).unwrap();

    let out = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["verify", "001-loop"])
        .output()
        .unwrap();
    // The inner call is refused, so the outer command exits non-zero and the
    // outer run reports a failure. The point is that it terminates at all.
    assert_eq!(code(&out), 1);

    // The refusal itself, observed directly: an id already on the stack.
    let out = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["verify", "001-loop"])
        .env("SPEC_SPINE_VERIFY_STACK", "001-loop")
        .output()
        .unwrap();
    assert_eq!(code(&out), 1);
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("validation"),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );

    // A stack that does not contain this id runs normally.
    let out = bin()
        .arg("--repo")
        .arg(tmp.path())
        .args(["verify", "001-loop", "--plan"])
        .env("SPEC_SPINE_VERIFY_STACK", "002-other")
        .output()
        .unwrap();
    assert_eq!(code(&out), 0, "only a cycle is refused, not any depth");
}

// --- `index check` diagnostics + `index diagnostics` (spec 050) -----------

/// A corpus whose only spec is in flight and claims one file that exists and
/// one that does not, so the committed index records exactly one `W-001`.
fn write_unresolved_corpus(root: &Path) {
    fs::create_dir_all(root.join("crates/a/src")).unwrap();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/a\"]\n",
    )
    .unwrap();
    fs::write(
        root.join("crates/a/Cargo.toml"),
        "[package]\nname = \"a\"\nversion = \"0.1.0\"\n\n[package.metadata.spec-spine]\nspec = \"001-flight\"\n",
    )
    .unwrap();
    fs::write(
        root.join("crates/a/src/lib.rs"),
        "// Spec: specs/001-flight/spec.md\npub fn a() {}\n",
    )
    .unwrap();
    let spec_dir = root.join("specs/001-flight");
    fs::create_dir_all(&spec_dir).unwrap();
    fs::write(
        spec_dir.join("spec.md"),
        "---\nid: \"001-flight\"\ntitle: \"T\"\nstatus: draft\ncreated: \"2026-09-06\"\nimplementation: pending\nsummary: \"s\"\nestablishes:\n  - \"crates/a/src/lib.rs\"\n  - \"crates/a/src/not_yet.rs\"\n---\n# 001\n",
    )
    .unwrap();
}

#[test]
fn index_check_reports_diagnostics_and_fails_only_when_asked() {
    let tmp = tempfile::tempdir().unwrap();
    write_unresolved_corpus(tmp.path());
    let run = |args: &[&str]| {
        bin()
            .arg("--repo")
            .arg(tmp.path())
            .args(args)
            .output()
            .unwrap()
    };
    assert_eq!(code(&run(&["index"])), 0);

    // Fresh, but the ledger records an unresolved unit: reported, not refused.
    let out = run(&["index", "check"]);
    assert_eq!(code(&out), 0, "a warning must not fail the default gate");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("is fresh"), "{stdout}");
    assert!(stdout.contains("1 W-001"), "{stdout}");

    // Opt in, and the same tree is refused with 1.
    let out = run(&["index", "check", "--fail-on-unresolved"]);
    assert_eq!(code(&out), 1);

    // The refusal is said once, on one stream. Asserted because it was not:
    // an earlier round printed the reason on stdout and repeated it on stderr,
    // and these tests checked only exit codes, so nothing caught it.
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stdout.contains("--fail-on-unresolved refuses"), "{stdout}");
    assert!(
        stderr.trim().is_empty(),
        "the refusal belongs on one stream, got stderr: {stderr}"
    );
    // And a line that reads as a pass must not be the whole of what is said
    // when the process exits 1.
    assert!(
        stdout.lines().all(|l| l.trim() != "index is fresh"),
        "a bare pass line while exiting 1: {stdout}"
    );
}

#[test]
fn a_clean_corpus_keeps_the_bare_verdict_line() {
    let tmp = tempfile::tempdir().unwrap();
    write_spec(tmp.path(), "001-a", "001-a", "approved");
    let run = |args: &[&str]| {
        bin()
            .arg("--repo")
            .arg(tmp.path())
            .args(args)
            .output()
            .unwrap()
    };
    assert_eq!(code(&run(&["index"])), 0);

    let out = run(&["index", "check"]);
    assert_eq!(code(&out), 0);
    assert_eq!(
        String::from_utf8_lossy(&out.stdout).trim(),
        "index is fresh",
        "no diagnostics -> the line reads exactly as it did before spec 050"
    );
    // And the strict flag passes, because there is nothing unresolved.
    assert_eq!(code(&run(&["index", "check", "--fail-on-unresolved"])), 0);
}

#[test]
fn staleness_outranks_unresolution() {
    let tmp = tempfile::tempdir().unwrap();
    write_unresolved_corpus(tmp.path());
    let run = |args: &[&str]| {
        bin()
            .arg("--repo")
            .arg(tmp.path())
            .args(args)
            .output()
            .unwrap()
    };
    assert_eq!(code(&run(&["index"])), 0);
    assert_eq!(code(&run(&["index", "check", "--fail-on-unresolved"])), 1);

    // Make the ledger stale. The spec's own `spec.md` is a hashed shard input;
    // editing the claimed *source* file would not restale it, because only
    // section/symbol/module units put their backing file in the shard hash
    // (`index.rs::span_files_for_mapping`). The title changes, the units do
    // not, so the `W-001` survives and both conditions hold at once.
    let spec = tmp.path().join("specs/001-flight/spec.md");
    let body = fs::read_to_string(&spec)
        .unwrap()
        .replace("\"T\"", "\"T2\"");
    fs::write(&spec, body).unwrap();

    // Spec 050 3.3: 2, not 1. A stale ledger's warnings describe a tree that no
    // longer exists, so refusing for them would name the wrong problem.
    assert_eq!(
        code(&run(&["index", "check", "--fail-on-unresolved"])),
        2,
        "staleness must outrank unresolution"
    );
}

#[test]
fn index_check_json_carries_counts_without_disturbing_the_freshness_shape() {
    let tmp = tempfile::tempdir().unwrap();
    write_unresolved_corpus(tmp.path());
    let run = |args: &[&str]| {
        bin()
            .arg("--repo")
            .arg(tmp.path())
            .args(args)
            .output()
            .unwrap()
    };
    assert_eq!(code(&run(&["index"])), 0);

    let out = run(&["index", "check", "--json"]);
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(v["verb"], "index.check");
    assert_eq!(
        v["report"]["fresh"], true,
        "the freshness member is untouched"
    );
    assert_eq!(v["report"]["diagnostics"]["warnings"], 1);
    assert_eq!(v["report"]["diagnostics"]["errors"], 0);
    assert_eq!(v["report"]["diagnostics"]["byCode"]["W-001"], 1);

    // Spec 050 3.6: a payload addition does not move the envelope version.
    assert_eq!(v["schemaVersion"], spec_spine_types::VERDICT_SCHEMA_VERSION);

    // Spec 050 3.1: `compile --check` shares `freshness_report` and must not
    // have acquired a permanently-zero diagnostics member.
    let out = run(&["compile", "--check", "--json"]);
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(v["verb"], "compile.check");
    assert!(
        v["report"].get("diagnostics").is_none(),
        "the registry verdict must not carry index diagnostics: {}",
        v["report"]
    );
}

#[test]
fn index_diagnostics_lists_them_and_never_refuses() {
    let tmp = tempfile::tempdir().unwrap();
    write_unresolved_corpus(tmp.path());
    let run = |args: &[&str]| {
        bin()
            .arg("--repo")
            .arg(tmp.path())
            .args(args)
            .output()
            .unwrap()
    };
    assert_eq!(code(&run(&["index"])), 0);

    let out = run(&["index", "diagnostics", "--json"]);
    assert_eq!(code(&out), 0);
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(v.as_array().unwrap().len(), 1);
    assert_eq!(v[0]["code"], "W-001");
    assert_eq!(v[0]["specId"], "001-flight", "attributed to its spec");
    assert_eq!(v[0]["severity"], "warning");

    // The read verb reports; it does not gate, even for the strict case.
    let out = run(&["index", "diagnostics"]);
    assert_eq!(code(&out), 0);
    assert!(String::from_utf8_lossy(&out.stdout).contains("W-001"));
}

// ── spec 063: a stale binary is not a stale ledger ────────────────────────

/// §3.1: a command line clap cannot parse is exit 3, never 2. Clap's default
/// is 2, which this tool spends on staleness, so an unknown flag used to be
/// indistinguishable from a stale ledger except by matching clap's English.
#[test]
fn a_usage_error_is_exit_three_not_stale() {
    let tmp = tempfile::tempdir().unwrap();
    for args in [
        vec!["compile", "--no-such-flag"],
        vec!["no-such-verb"],
        vec!["registry", "show"],          // a required argument is missing
        vec!["index", "check", "--slice"], // a flag with no value
    ] {
        let out = run_in(tmp.path(), &args);
        assert_eq!(
            code(&out),
            3,
            "{args:?} must be a usage error, not staleness: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }
}

/// §3.1: an incomplete invocation is a usage error too. It prints help, but
/// nobody asked for help, and a script that dropped its verb must still fail.
#[test]
fn a_missing_subcommand_is_a_usage_error() {
    let tmp = tempfile::tempdir().unwrap();
    let out = run_in(tmp.path(), &[]);
    assert_eq!(code(&out), 3, "nothing was asked for, so nothing succeeded");
}

/// §3.1: help and version are asked for, so they succeed, on stdout.
#[test]
fn help_and_version_stay_exit_zero_on_stdout() {
    let tmp = tempfile::tempdir().unwrap();
    for args in [vec!["--help"], vec!["--version"], vec!["compile", "--help"]] {
        let out = run_in(tmp.path(), &args);
        assert_eq!(code(&out), 0, "{args:?}");
        assert!(!out.stdout.is_empty(), "{args:?} writes to stdout");
    }
}

/// §3.1: and exit 2 still means staleness, from the verb that means it. The
/// property this spec buys is that 2 now means only that.
#[test]
fn exit_two_still_means_a_stale_ledger() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    let dir = root.join("specs/001-a");
    fs::create_dir_all(&dir).unwrap();
    fs::write(
        dir.join("spec.md"),
        "---\nid: \"001-a\"\ntitle: \"T\"\nstatus: approved\ncreated: \"2026-09-07\"\n\
         summary: \"s\"\nestablishes:\n  - \"specs/001-a/spec.md\"\n---\n# 001-a\n## body\n",
    )
    .unwrap();
    assert_eq!(code(&run_in(root, &["compile"])), 0);
    // Mutate the hashed input without recompiling.
    fs::write(
        dir.join("spec.md"),
        "---\nid: \"001-a\"\ntitle: \"T2\"\nstatus: approved\ncreated: \"2026-09-07\"\n\
         summary: \"s\"\nestablishes:\n  - \"specs/001-a/spec.md\"\n---\n# 001-a\n## body\n",
    )
    .unwrap();
    assert_eq!(
        code(&run_in(root, &["compile", "--check"])),
        2,
        "the one condition exit 2 is for"
    );
}