vissue-cli 0.9.3

vissue command line: plain-text issue tracking over per-project orgmode files
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
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
//! Command-line behaviour, exercised through the built binary.

#![allow(missing_docs)]

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

#[cfg(not(unix))]
#[test]
fn serve_is_unix_only() {
    let out = vissue_cmd().arg("serve").output().expect("run vissue");
    assert!(!out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("Unix-only"),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

fn fixture_root() -> std::path::PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixture_vault")
}

fn vissue_cmd() -> Command {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_vissue"));
    cmd.env("VISSUE_NO_ROUTE", "1");
    cmd
}

fn vissue(args: &[&str]) -> std::process::Output {
    vissue_cmd()
        .args(["--root", fixture_root().to_str().unwrap()])
        .args(args)
        .output()
        .expect("run vissue")
}

fn stdout(out: &std::process::Output) -> String {
    String::from_utf8(out.stdout.clone()).unwrap()
}

#[test]
fn projects_lists_the_fixture_projects() {
    let out = vissue(&["projects"]);
    assert!(out.status.success());
    assert_eq!(stdout(&out), "atlas\nbeacon\n");
}

#[test]
fn count_and_list_accept_both_project_flags() {
    assert_eq!(stdout(&vissue(&["count", "-P", "atlas"])), "4\n");
    assert_eq!(stdout(&vissue(&["count", "-p", "atlas"])), "4\n");
    assert_eq!(stdout(&vissue(&["count", "--project", "atlas"])), "4\n");
    let listed = stdout(&vissue(&["list", "-P", "atlas"]));
    assert_eq!(listed.lines().count(), 4, "{listed}");
    assert!(listed.contains("atlas-1a2b"), "{listed}");
}

#[test]
fn export_emits_one_json_object_per_line() {
    let out = vissue(&["export", "-P", "beacon"]);
    assert!(out.status.success());
    let text = stdout(&out);
    assert_eq!(text.lines().count(), 2, "{text}");
    for line in text.lines() {
        let row: serde_json::Value = serde_json::from_str(line).unwrap();
        assert_eq!(row["project"], "beacon");
    }
}

#[test]
fn check_exits_zero_on_the_fixture() {
    let out = vissue(&["check"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(stdout(&out).contains("0 error(s), 0 warning(s)"));
}

/// A report written into a body quotes org, and quoted org is not a definition.
///
/// The loop this guards is the ordinary one: an agent is handed an issue,
/// works, and writes its report back with `append`. Reports quote the heading
/// they were given, ids and all. If a quoted `:ID:` counted, a `:PARENT:` that
/// points nowhere would resolve against the mention and `check` would go quiet
/// on the one class of damage it exists to catch.
#[test]
fn an_id_quoted_in_a_report_does_not_resolve_a_broken_parent() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };

    own(&["create", "-p", "atlas", "The child", "-q"]);
    let issues = dir.path().join("Software/atlas/issues.org");
    let planted = fs::read_to_string(&issues)
        .unwrap()
        .replace(":CREATED:", ":PARENT:     ghost-9999\n:CREATED:");
    fs::write(&issues, planted).unwrap();

    let broken = own(&["check"]);
    assert!(
        !broken.status.success() && stdout(&broken).contains("ghost-9999"),
        "a parent that names nothing is an error: {}",
        stdout(&broken)
    );

    let host = stdout(&own(&["create", "-p", "atlas", "The report", "-q"]))
        .trim()
        .to_string();
    own(&[
        "append",
        &host,
        "--text",
        "The heading I was handed reads:\n:PROPERTIES:\n:ID: ghost-9999\n:END:\n",
    ]);

    let after = own(&["check"]);
    assert!(
        !after.status.success() && stdout(&after).contains("ghost-9999"),
        "quoting the id in a report silenced the check: {}",
        stdout(&after)
    );
}

#[test]
fn show_json_returns_an_object() {
    let out = vissue(&["show", "atlas-2c3d", "--json"]);
    assert!(out.status.success());
    let row: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
    assert_eq!(row["id"], "atlas-2c3d");
    assert_eq!(row["parent"], "atlas-1a2b");
}

#[test]
fn mirror_writes_a_file_and_reports_the_path() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("nested/mirror.org");
    let out = vissue(&["mirror", "-P", "atlas", "--out", target.to_str().unwrap()]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(stdout(&out).starts_with("wrote "));
    let text = fs::read_to_string(&target).unwrap();
    assert!(
        text.contains("# MIRROR: generated by `vissue mirror`"),
        "{text}"
    );
    assert!(text.contains("* atlas"), "{text}");
    assert!(!text.contains("* beacon"), "{text}");
}

#[test]
fn mirror_writes_to_stdout_on_a_dash() {
    let out = vissue(&["mirror", "--out", "-", "--format", "markdown"]);
    assert!(out.status.success());
    let text = stdout(&out);
    assert!(text.starts_with("# vissue mirror"), "{text}");
    assert!(text.contains("## atlas"), "{text}");
    assert!(text.contains("## beacon"), "{text}");
}

#[test]
fn an_unknown_mirror_format_fails_loudly() {
    let out = vissue(&["mirror", "--out", "-", "--format", "pdf"]);
    assert!(!out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("unknown format"));
}

#[test]
fn whoami_prints_the_identity_a_claim_would_record() {
    let out = vissue(&["whoami"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(!text.trim().is_empty(), "no identity printed");
}

#[test]
fn tui_help_names_offline() {
    let out = vissue(&["tui", "--help"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.contains("--offline"), "{text}");
    assert!(text.contains("Never attach"), "{text}");
}

#[test]
fn hud_help_names_rofi_and_iced() {
    let out = vissue(&["hud", "--help"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.contains("--mode"), "{text}");
    assert!(text.contains("rofi"), "{text}");
    assert!(text.contains("--rofi"), "{text}");
    assert!(text.contains("--iced"), "{text}");
    assert!(text.contains("--toggle"), "{text}");
}

#[test]
fn iced_hud_without_binary_exits_127() {
    let out = vissue_cmd()
        .args(["--root", fixture_root().to_str().unwrap(), "hud"])
        .env("VISSUE_HUD_BIN", "/nonexistent/vissue-hud")
        .env("PATH", "/nonexistent")
        .output()
        .expect("run vissue hud --iced");
    assert_eq!(out.status.code(), Some(127));
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("cargo install vissue-hud"), "{err}");
}

#[test]
fn hud_missing_override_bin_exits_127() {
    let out = vissue_cmd()
        .args(["--root", fixture_root().to_str().unwrap(), "hud", "--iced"])
        .env("VISSUE_HUD_BIN", "/nonexistent/vissue-hud")
        .output()
        .expect("run vissue hud --iced");
    assert_eq!(out.status.code(), Some(127));
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("cargo install vissue-hud"), "{err}");
}

#[cfg(not(unix))]
#[test]
fn tui_without_offline_is_unix_only() {
    let out = vissue(&["tui"]);
    assert!(!out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("Unix-only"),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[cfg(not(unix))]
#[test]
fn hud_without_offline_is_unix_only() {
    let out = vissue(&["hud"]);
    assert!(!out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("Unix-only"),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn identity_reports_the_resolved_binary_root_and_prefix() {
    // `identity` answers the wrapper's old question, "which binary and which
    // tracker", and is distinct from `whoami`, which names the claimant.
    let text = stdout(&vissue(&["identity"]));
    assert!(text.contains("protocol: 1"), "{text}");
    assert!(text.contains("prefix: Software"), "{text}");
    assert!(text.contains("prefix=Software"), "{text}");
    assert!(text.contains("fixture_vault"), "{text}");
    assert!(text.contains("binary:"), "{text}");
}

#[test]
fn the_environment_can_name_the_claiming_identity() {
    let out = vissue_cmd()
        .args(["--root", fixture_root().to_str().unwrap()])
        .env("VISSUE_AGENT", "grind-worker-3")
        .arg("whoami")
        .output()
        .expect("run vissue");
    assert_eq!(
        String::from_utf8(out.stdout).unwrap().trim(),
        "grind-worker-3"
    );
}

#[test]
fn a_create_and_update_cycle_works_in_a_temporary_root() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().to_str().unwrap();
    let run = |args: &[&str]| {
        vissue_cmd()
            .args(["--root", root])
            .args(args)
            .output()
            .expect("run vissue")
    };

    let created = run(&["create", "-P", "demo", "--quiet", "first task"]);
    assert!(
        created.status.success(),
        "{}",
        String::from_utf8_lossy(&created.stderr)
    );
    let id = String::from_utf8(created.stdout)
        .unwrap()
        .trim()
        .to_string();
    assert!(id.starts_with("demo-"), "{id}");

    let updated = run(&["update", &id, "--state", "STARTED"]);
    assert!(updated.status.success());
    assert!(String::from_utf8_lossy(&updated.stdout).contains("state TODO -> STARTED"));

    let shown = run(&["show", &id]);
    assert!(String::from_utf8_lossy(&shown.stdout).contains("State:    STARTED"));
    assert_eq!(
        String::from_utf8_lossy(&run(&["count", "--ready"]).stdout),
        "1\n"
    );
}

#[test]
fn the_root_may_come_from_the_environment() {
    let out = vissue_cmd()
        .env("VISSUE_ROOT", fixture_root())
        .arg("projects")
        .output()
        .expect("run vissue");
    assert_eq!(String::from_utf8(out.stdout).unwrap(), "atlas\nbeacon\n");
}

#[test]
fn the_shared_issue_root_environment_is_supported() {
    let out = vissue_cmd()
        .env_remove("VISSUE_ROOT")
        .env("ISSUE_ROOT", fixture_root())
        .arg("projects")
        .output()
        .expect("run vissue");
    assert_eq!(String::from_utf8(out.stdout).unwrap(), "atlas\nbeacon\n");
}

// "Nothing here" is an answer about the corpus, not about a project's share of
// it. Over the fixture's two projects, claims printed atlas's claim and then
// beacon's "no live claims"; a corpus of six printed it above nine claims, and
// agenda printed its own sentinel five times above the dated rows.
#[test]
fn an_empty_project_does_not_say_nothing_here_next_to_another_project_rows() {
    let out = vissue(&["claims"]);
    let text = String::from_utf8(out.stdout).unwrap();
    assert!(text.contains("fixture-agent"), "{text}");
    assert!(
        !text.contains("no live claims"),
        "an empty project printed its sentinel beside another's rows: {text}"
    );

    let dated = String::from_utf8(vissue(&["agenda", "--days", "5000"]).stdout).unwrap();
    assert!(dated.contains("beacon-5j6k"), "{dated}");
    assert!(
        !dated.contains("nothing dated in range"),
        "the agenda sentinel survived beside dated rows: {dated}"
    );
}

// A title introduces the document, so a roadmap over every project carries one,
// not one per project. Concatenating whole roadmaps gives a corpus of six six
// titles, each with its own "generated from" line, sitting between the project
// sections the title is meant to introduce.
#[test]
fn the_roadmap_titles_the_document_once_however_many_projects_it_covers() {
    let text = String::from_utf8(vissue(&["roadmap"]).stdout).unwrap();
    assert_eq!(
        text.lines().filter(|l| *l == "# Roadmap").count(),
        1,
        "{text}"
    );
    assert_eq!(
        text.matches("Generated from `vissue roadmap`").count(),
        1,
        "{text}"
    );
    // Both projects are still in the one document, under their own headings.
    assert!(text.contains("## atlas"), "{text}");
    assert!(text.contains("## beacon"), "{text}");
}

// The ratchet for the whole class. Every machine-readable surface promises a
// consumer one document (or, for the line-oriented ones, one document per
// line). Routing a report per project breaks that promise without breaking the
// exit code, which is how a stream of arrays shipped: the flag worked on a
// one-project corpus and on any corpus where only the last project had rows.
// A new `--json` command lands in this table or its output is unparsed.
#[test]
fn every_machine_readable_surface_over_the_corpus_is_parseable() {
    // (args, one document per line rather than one document overall)
    let surfaces: &[(&[&str], bool)] = &[
        (&["list", "--json"], false),
        (&["ready", "--json"], false),
        (&["claims", "--json"], false),
        (&["digest", "--json"], false),
        (&["show", "atlas-2c3d", "--json"], false),
        (&["export"], true),
    ];
    for (args, by_line) in surfaces {
        let out = vissue(args);
        assert!(out.status.success(), "{args:?} exited {}", out.status);
        let text = String::from_utf8(out.stdout).unwrap();
        assert!(!text.trim().is_empty(), "{args:?} printed nothing");
        if *by_line {
            for (n, line) in text.lines().enumerate() {
                serde_json::from_str::<serde_json::Value>(line)
                    .unwrap_or_else(|e| panic!("{args:?} line {}: {e}: {line}", n + 1));
            }
        } else {
            serde_json::from_str::<serde_json::Value>(&text)
                .unwrap_or_else(|e| panic!("{args:?} is not one document: {e}: {text}"));
        }
    }
}

// `--json` promises a document a parser can read. A fragment per project makes
// it a stream of arrays: over the fixture's two projects, `[]` then the array
// holding atlas's claim, which `json.load` rejects at the second bracket.
#[test]
fn routed_claims_json_is_one_array_over_the_corpus() {
    let text = String::from_utf8(vissue(&["claims", "--json"]).stdout).unwrap();
    let rows: Vec<serde_json::Value> =
        serde_json::from_str(&text).unwrap_or_else(|e| panic!("not one document: {e}: {text}"));
    assert_eq!(rows.len(), 1, "{text}");
    assert_eq!(rows[0]["project"], "atlas", "{text}");
    assert_eq!(rows[0]["holder"], "fixture-agent", "{text}");
}

// Asked about one project, an empty array is the document.
#[test]
fn a_single_project_claims_json_is_still_a_document() {
    let text =
        String::from_utf8(vissue(&["claims", "--json", "--project", "beacon"]).stdout).unwrap();
    let rows: Vec<serde_json::Value> =
        serde_json::from_str(&text).unwrap_or_else(|e| panic!("not one document: {e}: {text}"));
    assert!(rows.is_empty(), "{text}");
}

// `vissue graph | dot -Tsvg` has to draw the corpus. Concatenating a whole DOT
// document per project gives dot a file of six graphs, all named the same, and
// it renders the first and exits zero: five projects leave the picture with no
// error anywhere. Cross-project edges are the other half, pointing at nodes
// declared inside a different `digraph` block.
#[test]
fn the_graph_is_one_dot_document_however_many_projects_it_covers() {
    let text = String::from_utf8(vissue(&["graph"]).stdout).unwrap();
    assert_eq!(
        text.lines().filter(|l| l.starts_with("digraph ")).count(),
        1,
        "{text}"
    );
    assert_eq!(text.lines().filter(|l| *l == "}").count(), 1, "{text}");
    assert!(text.starts_with("digraph vissue_graph {"), "{text}");
    assert!(text.trim_end().ends_with('}'), "{text}");
    // Both projects draw inside it.
    assert!(text.contains("\"atlas-"), "{text}");
    assert!(text.contains("\"beacon-"), "{text}");
}

// Asked about one project, the graph is still a document dot can render.
#[test]
fn a_single_project_graph_is_a_complete_dot_document() {
    let text = String::from_utf8(vissue(&["graph", "--project", "beacon"]).stdout).unwrap();
    assert!(text.starts_with("digraph vissue_graph {"), "{text}");
    assert!(text.trim_end().ends_with('}'), "{text}");
    assert!(text.contains("\"beacon-"), "{text}");
    assert!(!text.contains("\"atlas-"), "{text}");
}

// Asked about one project, the roadmap is still a document and keeps its title.
#[test]
fn a_single_project_roadmap_keeps_its_title() {
    let text = String::from_utf8(vissue(&["roadmap", "--project", "beacon"]).stdout).unwrap();
    assert!(text.starts_with("# Roadmap"), "{text}");
    assert!(text.contains("## beacon"), "{text}");
    assert!(!text.contains("## atlas"), "{text}");
}

// Asked about one project, the sentinel is the whole answer and stays.
#[test]
fn a_project_with_no_claims_still_says_so_when_it_is_the_question() {
    let text = String::from_utf8(vissue(&["claims", "--project", "beacon"]).stdout).unwrap();
    assert_eq!(text, "no live claims\n", "{text}");
}

#[test]
fn the_read_only_command_surface_dispatches_against_the_fixture() {
    let cases: &[(&[&str], &str)] = &[
        (&["list", "--json"], "\"id\": \"atlas-3e4f\""),
        (
            &["show", "atlas-1a2b"],
            "Title:    Parse the manifest header",
        ),
        (&["ready", "--json"], "\"id\": \"atlas-1a2b\""),
        (&["claims"], "fixture-agent"),
        (&["agenda", "--days", "5000"], "beacon-5j6k"),
        (&["hygiene", "--stale-days", "1"], "stale_claims=1"),
        (&["waiting-on", "atlas-1a2b"], "atlas-3e4f"),
        (
            &["body-excerpt", "atlas-1a2b"],
            "* STARTED [#A] Parse the manifest header",
        ),
        (&["search", "parser"], "atlas-1a2b"),
        (&["children", "atlas-1a2b"], "atlas-2c3d"),
        (&["ancestors", "atlas-3e4f", "--depth", "3"], "1 atlas-1a2b"),
        (&["impact", "atlas-1a2b", "--depth", "3"], "1 atlas-3e4f"),
        (
            &["related", "atlas-1a2b", "--format", "org"],
            "[[id:atlas-2c3d]",
        ),
        (&["stale", "--days", "1"], "beacon-5j6k"),
        (&["count", "--state", "TODO"], "2\n"),
        (
            &["tree", "atlas-1a2b", "--format", "dot"],
            "digraph vissue_tree",
        ),
        (&["cycles"], "no cycles"),
        (&["graph", "--project", "atlas"], "digraph vissue_graph"),
        (&["backlinks", "atlas-1a2b"], "atlas-2c3d"),
        (&["roadmap", "--project", "atlas"], "## atlas"),
        (&["digest", "--json"], "\"issues\": 6"),
    ];

    for (args, expected) in cases {
        let out = vissue(args);
        assert!(
            out.status.success(),
            "command {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let text = stdout(&out);
        assert!(
            text.contains(expected),
            "command {args:?} did not contain {expected:?}: {text}"
        );
    }

    // `gen` and `events` read a log the fixture does not carry in git, so
    // anything that writes one -- a `vissue ping` in a checkout, an earlier
    // test -- would decide the answer. They are asked of a tracker this test
    // owns instead.
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    assert_eq!(stdout(&own(&["gen"])), "0\n");
    assert!(
        stdout(&own(&["events", "--since", "0"])).contains("generation=0 since=0 count=0"),
        "{}",
        stdout(&own(&["events", "--since", "0"]))
    );
}

/// `vissue export | head` closes the pipe once it has enough. The output has
/// to be larger than a pipe buffer for the writer to still be writing when
/// that happens, so this builds a corpus rather than using the fixture.
#[test]
fn a_reader_that_closes_the_pipe_is_not_a_failure() {
    use std::io::Read as _;
    use std::process::Stdio;

    // A pipe holds 64 KiB on Linux by default. The writer has to still be mid-corpus
    // when the reader vanishes, so the corpus has to out-measure the buffer -- which
    // is a byte count rather than an issue count. Long bodies reach it in two dozen
    // writes where short titles need hundreds, and each create re-reads and rewrites
    // the whole project file, so the count is what the setup costs.
    const PIPE_BUFFER: usize = 64 * 1024;
    let body = "b".repeat(8 * 1024);

    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().to_str().unwrap().to_string();
    for i in 0..24 {
        let out = vissue_cmd()
            .args([
                "--root", &root, "create", "-p", "demo", "--quiet", "--body", &body,
            ])
            .arg(format!("issue {i} with a body long enough to fill a pipe"))
            .output()
            .expect("run vissue");
        assert!(out.status.success());
    }

    // Without this the test passes whatever the writer does: a corpus that fits the
    // buffer never blocks the writer, so dropping the reader proves nothing.
    let whole = vissue_cmd()
        .args(["--root", &root, "export"])
        .output()
        .expect("run vissue");
    assert!(
        whole.status.success(),
        "export failed: {}",
        String::from_utf8_lossy(&whole.stderr)
    );
    assert!(
        whole.stdout.len() > 2 * PIPE_BUFFER,
        "the corpus exports {} bytes, which a {PIPE_BUFFER}-byte pipe swallows without \
         ever blocking the writer, so this test would assert nothing",
        whole.stdout.len()
    );

    let mut child = vissue_cmd()
        .args(["--root", &root, "export"])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("run vissue");

    // Read one line, then drop the pipe while the writer is mid-corpus.
    let mut stdout = child.stdout.take().unwrap();
    let mut first = [0u8; 64];
    stdout.read_exact(&mut first).unwrap();
    drop(stdout);

    let out = child.wait_with_output().expect("wait for vissue");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(out.status.success(), "exited {:?}: {stderr}", out.status);
    assert!(stderr.is_empty(), "{stderr}");
}

/// The one command that replaces reading the file by hand.
///
/// Recovering an issue's text used to mean parsing `path:start-end` out of
/// `show` and running `sed` over the org file, because `show` printed the
/// range and stopped.
#[test]
fn show_org_writes_the_whole_heading() {
    let out = vissue(&["show", "--org", "atlas-1a2b"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.starts_with("* STARTED [#A]"), "{text}");
    assert!(text.contains(":ID:         atlas-1a2b"), "{text}");
    assert!(
        text.contains(":LOGBOOK:"),
        "the notes travel with it: {text}"
    );
    assert!(
        text.contains("Scope: read the header block"),
        "the body travels with it: {text}"
    );
    // Nothing but the heading, so the output can be redirected into a file.
    assert!(!text.contains("File:"), "{text}");
    assert!(!text.contains("excerpt"), "{text}");
}

#[test]
fn show_prints_the_body_and_json_carries_it() {
    let text = stdout(&vissue(&["show", "atlas-2c3d"]));
    assert!(text.contains("Body:"), "{text}");
    assert!(text.contains("Scope: one row per parsed record"), "{text}");

    let row: serde_json::Value =
        serde_json::from_str(&stdout(&vissue(&["show", "atlas-2c3d", "--json"]))).unwrap();
    assert!(
        row["body"]
            .as_str()
            .unwrap()
            .contains("one row per parsed record"),
        "{row}"
    );
}

#[test]
fn show_org_and_json_are_not_asked_for_together() {
    let out = vissue(&["show", "--org", "--json", "atlas-1a2b"]);
    assert!(!out.status.success(), "{}", stdout(&out));
}

/// Recording a worker's report, the return half of handing work out.
#[test]
fn append_reads_a_file_and_stdin() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    std::fs::create_dir_all(root.join("Software")).unwrap();
    let mk = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let id = String::from_utf8_lossy(
        &mk(&["create", "-p", "atlas", "--quiet", "Streaming exporter"]).stdout,
    )
    .trim()
    .to_string();

    let report = dir.path().join("SUMMARY.md");
    std::fs::write(&report, "## What changed\n\n* took a Read\n").unwrap();
    let out = mk(&["append", &id, "--file", report.to_str().unwrap()]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );

    let shown = String::from_utf8_lossy(&mk(&["show", &id]).stdout).to_string();
    assert!(shown.contains("## What changed"), "{shown}");
    assert!(shown.contains("took a Read"), "{shown}");

    // --text is the same thing without a file.
    assert!(
        mk(&["append", &id, "--text", "second pass"])
            .status
            .success()
    );
    let shown = String::from_utf8_lossy(&mk(&["show", &id]).stdout).to_string();
    assert!(shown.contains("second pass"), "{shown}");

    // The tracker still reads back cleanly after markdown went in.
    let check = mk(&["check"]);
    assert!(
        check.status.success(),
        "{}",
        String::from_utf8_lossy(&check.stdout)
    );

    // Neither source given is an error, not an empty append.
    assert!(!mk(&["append", &id]).status.success());
}

/// `vissue keys` in its three shapes, against a chosen overlay.
///
/// The overlay path comes from the environment, so each case runs in its own
/// process with its own value rather than reassigning one the whole suite
/// shares.
#[test]
fn keys_prints_the_catalog_and_checks_an_overlay() {
    let dir = tempfile::tempdir().unwrap();
    let keys = |overlay: Option<&str>, args: &[&str]| -> std::process::Output {
        let mut cmd = vissue_cmd();
        cmd.args(["--root", fixture_root().to_str().unwrap(), "keys"]);
        cmd.args(args);
        match overlay {
            Some(path) => cmd.env("VISSUE_KEYS", path),
            None => cmd.env_remove("VISSUE_KEYS"),
        };
        cmd.output().unwrap()
    };

    // The catalog names every action with the chord that is live for it.
    let table = keys(None, &[]);
    assert!(table.status.success());
    let text = stdout(&table);
    for action in ["list.down", "issue.claim", "board.help"] {
        assert!(text.contains(action), "{action} missing: {text}");
    }

    let taken = keys(None, &["--occupancy"]);
    assert!(taken.status.success());
    assert!(stdout(&taken).contains('\t'), "{}", stdout(&taken));

    // A sound overlay checks out, and the rebound chord is what shows.
    let good = dir.path().join("good.toml");
    fs::write(&good, "[board]\n\"list.down\" = \"e\"\n").unwrap();
    let checked = keys(Some(good.to_str().unwrap()), &["--check"]);
    assert!(
        checked.status.success(),
        "{}",
        String::from_utf8_lossy(&checked.stderr)
    );
    assert!(stdout(&checked).trim() == "ok", "{}", stdout(&checked));
    let listed = stdout(&keys(Some(good.to_str().unwrap()), &[]));
    let row = listed
        .lines()
        .find(|l| l.contains("list.down"))
        .unwrap_or_else(|| panic!("no list.down row: {listed}"));
    assert_eq!(
        row.split_whitespace().last(),
        Some("e"),
        "the rebound chord is not shown: {row}"
    );

    // A conflicting one fails the check and says why.
    let bad = dir.path().join("bad.toml");
    fs::write(&bad, "[board]\n\"list.down\" = \"enter\"\n").unwrap();
    let refused = keys(Some(bad.to_str().unwrap()), &["--check"]);
    assert!(!refused.status.success());
    assert!(
        String::from_utf8_lossy(&refused.stderr).contains("reserved"),
        "{}",
        String::from_utf8_lossy(&refused.stderr)
    );
}

/// `hud --iced` hands the board the tracker it was pointed at.
///
/// The binary is replaced by a script that records its arguments, so what is
/// checked is the command line the CLI builds rather than a window.
#[test]
fn the_iced_hud_is_given_the_root_prefix_and_flags() {
    use std::os::unix::fs::PermissionsExt;

    let dir = tempfile::tempdir().unwrap();
    let record = dir.path().join("argv");
    let fake = dir.path().join("fake-hud");
    // Staged and renamed: a file written here and exec'd immediately can hit
    // ETXTBSY when another test thread forks while the descriptor is open.
    let staging = fake.with_extension("staging");
    fs::write(
        &staging,
        format!("#!/bin/sh\nprintf '%s\\n' \"$@\" > {}\n", record.display()),
    )
    .unwrap();
    let mut perm = fs::metadata(&staging).unwrap().permissions();
    perm.set_mode(0o755);
    fs::set_permissions(&staging, perm).unwrap();
    fs::rename(&staging, &fake).unwrap();

    let out = vissue_cmd()
        .args([
            "--root",
            fixture_root().to_str().unwrap(),
            "hud",
            "--iced",
            "--offline",
            "--toggle",
        ])
        .env("VISSUE_HUD_BIN", &fake)
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );

    let argv = fs::read_to_string(&record).unwrap();
    let args: Vec<&str> = argv.lines().collect();
    assert!(args.contains(&"--root"), "{args:?}");
    assert!(args.contains(&"--prefix"), "{args:?}");
    assert!(args.contains(&"--offline"), "{args:?}");
    assert!(args.contains(&"--toggle"), "{args:?}");
    assert!(
        args.iter().any(|a| a.contains("fixture_vault")),
        "the board was not pointed at this tracker: {args:?}"
    );
}

#[test]
fn a_body_can_be_piped_in() {
    use std::io::Write;
    use std::process::Stdio;

    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join("Software")).unwrap();
    let mut child = vissue_cmd()
        .args([
            "--root",
            dir.path().to_str().unwrap(),
            "create",
            "-p",
            "atlas",
            "--quiet",
            "--body-file",
            "-",
            "Read from a pipe",
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"the body came down the pipe\n")
        .unwrap();
    let out = child.wait_with_output().unwrap();
    assert!(out.status.success());
    let id = String::from_utf8_lossy(&out.stdout).trim().to_string();

    let shown = vissue_cmd()
        .args(["--root", dir.path().to_str().unwrap(), "show", &id])
        .output()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&shown.stdout).contains("the body came down the pipe"),
        "{}",
        String::from_utf8_lossy(&shown.stdout)
    );
}

/// The reference documents every subcommand the binary offers, hidden ones included.
///
/// The command table is what a reader consults to find out what vissue can do, so a
/// verb missing from it is a verb that effectively does not exist.
///
/// Hidden counts. `--help` not listing a verb is a choice about what a person reading
/// help is looking for, and says nothing about whether the verb needs writing down:
/// `surface` is hidden and other tooling is expected to call it, so a reader who finds
/// it in a script has somewhere to look it up. Reading the parser's own list rather
/// than its help output is what makes the hidden ones visible here at all.
///
/// `help` is clap's, not this binary's.
#[test]
fn the_reference_lists_every_subcommand() {
    let reference = fs::read_to_string(
        Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/orgmode/reference.org"),
    )
    .expect("reference");

    let missing: Vec<&str> = cli_surface()
        .iter()
        .map(|verb| verb.name.as_str())
        .filter(|name| *name != "help")
        .filter(|name| !reference.contains(&format!("={name}=")))
        .collect();
    assert!(
        missing.is_empty(),
        "not in docs/orgmode/reference.org: {missing:?}"
    );
}

/// The change stream a poller lives on: `gen`, `wait`, `events`.
///
/// A tool that watches a tracker asks for the generation, blocks until it
/// moves, then reads what happened. The contract is in the exit code, so a
/// `wait` that returned the wrong one would send a poller into a spin or
/// leave it asleep through a change, and neither shows up as an error.
#[test]
fn the_change_stream_reports_and_blocks_the_way_a_poller_needs() {
    use std::time::Instant;

    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    fs::create_dir_all(root.join("Software")).unwrap();
    let run = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let gen_now = |run: &dyn Fn(&[&str]) -> std::process::Output| -> u64 {
        stdout(&run(&["gen"])).trim().parse().expect("a generation")
    };

    // An untouched tracker sits at zero and has nothing to report.
    assert_eq!(gen_now(&run), 0);
    let empty = stdout(&run(&["events", "--since", "0"]));
    assert!(empty.contains("count=0"), "{empty}");

    let id = stdout(&run(&["create", "-p", "atlas", "--quiet", "watch me"]))
        .trim()
        .to_string();
    let after_create = gen_now(&run);
    assert!(after_create > 0, "a write did not move the generation");

    // Already moved past --last: return at once rather than wait out the
    // timeout, or a poller that fell behind never catches up.
    let started = Instant::now();
    let caught_up = run(&["wait", "--last", "0", "--timeout-ms", "5000"]);
    assert!(
        caught_up.status.success(),
        "wait reported no change though the generation had moved"
    );
    assert!(
        started.elapsed() < std::time::Duration::from_secs(3),
        "wait sat out the timeout on a generation that had already moved"
    );
    assert_eq!(
        stdout(&caught_up).trim(),
        after_create.to_string(),
        "wait did not print the generation it woke at"
    );

    // Nothing changing is exit 2, which is how a poller tells a quiet
    // interval from a change it missed.
    let quiet = run(&[
        "wait",
        "--last",
        &after_create.to_string(),
        "--timeout-ms",
        "700",
    ]);
    assert_eq!(quiet.status.code(), Some(2), "{}", stdout(&quiet));

    // A write from another process wakes it.
    let mut poker = Command::new("sh")
        .arg("-c")
        .arg(format!(
            "sleep 1; {} --root {} note {id} poke >/dev/null 2>&1",
            env!("CARGO_BIN_EXE_vissue"),
            root.to_str().unwrap()
        ))
        .spawn()
        .unwrap();
    let woken = run(&[
        "wait",
        "--last",
        &after_create.to_string(),
        "--timeout-ms",
        "15000",
    ]);
    let _ = poker.wait();
    assert!(
        woken.status.success(),
        "wait slept through another process's write"
    );

    // The log says what happened, in both shapes it offers.
    let events = stdout(&run(&["events", "--since", "0"]));
    assert!(events.contains("issues_write"), "{events}");
    assert!(events.contains("atlas"), "{events}");
    let json = events
        .split("---json---")
        .nth(1)
        .unwrap_or_else(|| panic!("no json block: {events}"));
    let parsed: serde_json::Value = serde_json::from_str(json.trim()).expect("events JSON");
    let recorded = parsed["events"].as_array().expect("an events array");
    assert!(recorded.len() >= 2, "{parsed}");
    assert_eq!(recorded[0]["kind"], "issues_write", "{parsed}");
    assert_eq!(recorded[0]["project"], "atlas", "{parsed}");

    // Asking from the far end returns nothing rather than repeating.
    let tail = stdout(&run(&["events", "--since", &gen_now(&run).to_string()]));
    assert!(tail.contains("count=0"), "{tail}");
}

/// `mirror --check` answers by exit code, the part a script reads.
///
/// The core comparison is tested elsewhere. What a caller depends on is the
/// mapping onto an exit status: a stale copy that exits 0 is a shared backlog
/// everyone trusts and nobody regenerates.
#[test]
fn mirror_check_reports_freshness_in_its_exit_code() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    fs::create_dir_all(root.join("Software")).unwrap();
    let run = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };

    let id = stdout(&run(&["create", "-p", "atlas", "--quiet", "first"]))
        .trim()
        .to_string();
    run(&["create", "-p", "beacon", "--quiet", "second"]);

    let mirror = root.join("mirror.org");
    let written = run(&["mirror", "--out", mirror.to_str().unwrap()]);
    assert!(written.status.success(), "{}", stdout(&written));

    let fresh = run(&["mirror", "--check", mirror.to_str().unwrap()]);
    assert!(fresh.status.success(), "a new mirror read as stale");
    assert!(stdout(&fresh).contains("fresh:"), "{}", stdout(&fresh));

    // One note is enough to make the copy out of date.
    run(&["note", &id, "moved on"]);
    let stale = run(&["mirror", "--check", mirror.to_str().unwrap()]);
    assert_eq!(stale.status.code(), Some(1), "{}", stdout(&stale));
    let report = stdout(&stale);
    assert!(report.contains("stale:"), "{report}");
    // It names which project moved, so a regeneration is not a guess.
    assert!(report.contains("moved: atlas"), "{report}");

    // Regenerating settles it.
    run(&["mirror", "--out", mirror.to_str().unwrap()]);
    assert!(
        run(&["mirror", "--check", mirror.to_str().unwrap()])
            .status
            .success(),
        "a regenerated mirror still read as stale"
    );

    // A file that was never a mirror is stale rather than fresh: treating an
    // unstamped file as current is the failure worth avoiding.
    let prose = root.join("notes.org");
    fs::write(&prose, "just prose\n").unwrap();
    let unstamped = run(&["mirror", "--check", prose.to_str().unwrap()]);
    assert_eq!(unstamped.status.code(), Some(1), "{}", stdout(&unstamped));
    assert!(
        stdout(&unstamped).contains("no SYNC stamp"),
        "{}",
        stdout(&unstamped)
    );

    // So is one that is not there at all.
    let absent = run(&[
        "mirror",
        "--check",
        root.join("absent.org").to_str().unwrap(),
    ]);
    assert_eq!(absent.status.code(), Some(1));

    // A mirror of one project is checked against what it covered, not the
    // whole tracker, or it would read as stale the moment anything else moved.
    let atlas_only = root.join("atlas.org");
    run(&[
        "mirror",
        "-p",
        "atlas",
        "--out",
        atlas_only.to_str().unwrap(),
    ]);

    let beacon_id = stdout(&run(&["list", "-P", "beacon"]))
        .split_whitespace()
        .next()
        .expect("a beacon issue")
        .to_string();
    let elsewhere = run(&["note", &beacon_id, "elsewhere"]);
    assert!(
        elsewhere.status.success(),
        "the note that makes this test mean anything failed: {}",
        String::from_utf8_lossy(&elsewhere.stderr)
    );
    // The whole-tracker mirror does go stale, making the
    // atlas-only one staying fresh a scope check rather than a no-op.
    assert_eq!(
        run(&["mirror", "--check", mirror.to_str().unwrap()])
            .status
            .code(),
        Some(1),
        "the beacon note did not move the tracker at all"
    );
    assert!(
        run(&["mirror", "--check", atlas_only.to_str().unwrap()])
            .status
            .success(),
        "a change in another project staled an atlas-only mirror"
    );
}

/// Naming a project that does not exist creates it, and case folds.
///
/// This is what lets a tracker grow without a setup step, and it is also
/// why a typo files work somewhere real but unwatched, so it is worth
/// stating in a test as well as in the reference.
#[test]
fn a_project_comes_into_being_when_something_is_filed_there() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    fs::create_dir_all(root.join("Software")).unwrap();
    let run = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let projects = |run: &dyn Fn(&[&str]) -> std::process::Output| -> Vec<String> {
        stdout(&run(&["projects"]))
            .lines()
            .map(str::to_string)
            .collect()
    };

    let id = stdout(&run(&["create", "-p", "atlas", "--quiet", "one"]))
        .trim()
        .to_string();
    assert_eq!(projects(&run), ["atlas"]);

    // A different case reaches the project that is already there rather
    // than making a second one beside it.
    let folded = run(&["create", "-p", "Atlas", "--quiet", "two"]);
    assert!(folded.status.success(), "{}", stdout(&folded));
    assert!(
        stdout(&folded).trim().starts_with("atlas-"),
        "{}",
        stdout(&folded)
    );
    assert_eq!(
        projects(&run),
        ["atlas"],
        "a case variant split the project"
    );

    // An unknown name is filed rather than refused, by create and by refile.
    let elsewhere = run(&["create", "-p", "brandnew", "--quiet", "three"]);
    assert!(elsewhere.status.success());
    assert!(projects(&run).contains(&"brandnew".to_string()));

    let moved = run(&["refile", &id, "--to", "somewhere-else"]);
    assert!(moved.status.success(), "{}", stdout(&moved));
    assert!(projects(&run).contains(&"somewhere-else".to_string()));
    // The id does not follow the project, so edges pointing at it still hold.
    let detail: serde_json::Value =
        serde_json::from_str(&stdout(&run(&["show", &id, "--json"]))).unwrap();
    assert_eq!(detail["id"], id.as_str());
    assert_eq!(detail["project"], "somewhere-else");

    // Two projects differing only by case are refused rather than guessed at.
    for name in ["Beacon", "beacon"] {
        let path = root.join("Software").join(name);
        fs::create_dir_all(&path).unwrap();
        fs::write(path.join("issues.org"), "#+TITLE: x\n").unwrap();
    }
    let ambiguous = run(&["create", "-p", "BEACON", "--quiet", "which one"]);
    assert!(!ambiguous.status.success(), "{}", stdout(&ambiguous));
    let err = String::from_utf8_lossy(&ambiguous.stderr);
    assert!(err.contains("ambiguous"), "{err}");
    assert!(err.contains("Beacon") && err.contains("beacon"), "{err}");
}

/// The blocker graph stays acyclic, and a corrupt one degrades safely.
///
/// `ready` is what a dispatcher takes work from, and it is defined by
/// walking blocker edges. A ring in that graph could spin it or make it
/// answer with work nobody can start, so the tracker refuses to write one
/// and survives finding one that was written by hand.
#[test]
fn a_blocker_ring_is_refused_and_a_planted_one_does_not_spin() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    fs::create_dir_all(root.join("Software")).unwrap();
    let run = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let mk = |title: &str| {
        stdout(&run(&["create", "-p", "atlas", "--quiet", title]))
            .trim()
            .to_string()
    };

    let (a, b, c) = (mk("A"), mk("B"), mk("C"));

    // A legal chain: C waits on B waits on A, so only A is ready.
    assert!(run(&["update", &b, "--block", &a]).status.success());
    assert!(run(&["update", &c, "--block", &b]).status.success());
    assert!(stdout(&run(&["cycles"])).contains("no cycles"));
    let ready = stdout(&run(&["ready"]));
    assert_eq!(ready.lines().count(), 1, "{ready}");
    assert!(
        ready.contains(&a),
        "the root of the chain is the ready one: {ready}"
    );

    // Closing the ring is refused, and says what it would have made.
    let ring = run(&["update", &a, "--block", &c]);
    assert_eq!(ring.status.code(), Some(1), "{}", stdout(&ring));
    let err = String::from_utf8_lossy(&ring.stderr);
    assert!(err.contains("blocker cycle"), "{err}");

    // So is an issue blocking itself, and it reads differently.
    let own = run(&["update", &a, "--block", &a]);
    assert_eq!(own.status.code(), Some(1), "{}", stdout(&own));
    let err = String::from_utf8_lossy(&own.stderr);
    assert!(err.contains("cannot block itself"), "{err}");

    // Neither refusal left anything behind.
    assert!(stdout(&run(&["cycles"])).contains("no cycles"));
    assert!(run(&["check"]).status.success());

    // A ring written straight into the file, which nothing can prevent.
    let path = root.join("Software/atlas/issues.org");
    let text = fs::read_to_string(&path).unwrap();
    fs::write(
        &path,
        text.replace(
            &format!(":ID:         {a}\n"),
            &format!(":ID:         {a}\n:BLOCKED_BY: {c}\n"),
        ),
    )
    .unwrap();

    // The ring is named, not counted, so it can be repaired.
    let found = stdout(&run(&["cycles"]));
    for id in [&a, &b, &c] {
        assert!(found.contains(id.as_str()), "{found}");
    }
    // check refuses the corpus.
    let checked = run(&["check"]);
    assert_eq!(checked.status.code(), Some(1), "{}", stdout(&checked));

    // And the dispatcher gets nothing rather than a spin or phantom work.
    let ready = run(&["ready"]);
    assert!(
        ready.status.success(),
        "ready failed outright: {}",
        String::from_utf8_lossy(&ready.stderr)
    );
    assert!(
        stdout(&ready).trim().is_empty(),
        "a ring offered work anyway: {}",
        stdout(&ready)
    );
}

/// Concurrent writers do not lose each other's work.
///
/// Every mutation is a read-modify-write of a whole `issues.org`, so two
/// processes that overlap without the advisory lock will each write a file
/// built from what they read before the other landed. The loser's issue is
/// gone, and nothing reports it: the tracker stays valid, just smaller.
///
/// Separate processes rather than threads, because that is the case the lock
/// exists for and the only one an in-process mutex cannot cover.
#[test]
fn concurrent_writers_all_land() {
    use std::process::Stdio;

    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    fs::create_dir_all(root.join("Software")).unwrap();

    const WRITERS: usize = 12;
    let mut kids = Vec::with_capacity(WRITERS);
    for i in 0..WRITERS {
        kids.push(
            vissue_cmd()
                .args([
                    "--root",
                    root.to_str().unwrap(),
                    "create",
                    "-p",
                    "atlas",
                    "--quiet",
                    &format!("writer {i}"),
                ])
                .stdout(Stdio::null())
                .stderr(Stdio::piped())
                .spawn()
                .unwrap(),
        );
    }
    for (i, kid) in kids.into_iter().enumerate() {
        let out = kid.wait_with_output().unwrap();
        assert!(
            out.status.success(),
            "writer {i} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    let run = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root.to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };

    // Every writer reported success, so every issue has to be there.
    let count: usize = stdout(&run(&["count"])).trim().parse().expect("a count");
    assert_eq!(count, WRITERS, "a write was lost: {count} of {WRITERS}");

    // Each one by title, so a count that happens to match cannot hide a
    // duplicate standing in for a loser.
    let listed = stdout(&run(&["list"]));
    for i in 0..WRITERS {
        assert!(
            listed.contains(&format!("writer {i}")),
            "writer {i} is missing: {listed}"
        );
    }

    // The file a race leaves behind is usually still valid, and that is what
    // makes the loss quiet. Check anyway.
    assert!(
        run(&["check"]).status.success(),
        "{}",
        stdout(&run(&["check"]))
    );
}

#[test]
fn reject_help_names_the_destination_flags() {
    let out = vissue(&["reject", "--help"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.contains("--to"), "{text}");
    assert!(text.contains("--project"), "{text}");
    assert!(text.contains("--reason"), "{text}");
}

#[test]
fn wait_help_names_until_terminal() {
    let out = vissue(&["wait", "--help"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.contains("--until-terminal"), "{text}");
    assert!(text.contains("--id"), "{text}");
    assert!(text.contains("--poll-ms"), "{text}");
    assert!(text.contains("--timeout-ms"), "{text}");
    assert!(text.contains("--last"), "{text}");
}

/// `--until-terminal` watches one issue's state, not the generation
/// counter. The printed token and the exit status are the contract, so a
/// poller can tell DONE from still-open without parsing the heading.
#[test]
fn wait_until_terminal_reports_done_cancelled_or_timeout() {
    let done = vissue(&[
        "wait",
        "--id",
        "atlas-4g5h",
        "--until-terminal",
        "--timeout-ms",
        "1000",
    ]);
    assert!(
        done.status.success(),
        "DONE issue should exit 0: {}",
        String::from_utf8_lossy(&done.stderr)
    );
    let done_line = stdout(&done).trim().to_string();
    assert!(
        done_line.starts_with("DONE "),
        "expected DONE <gen>, got {done_line:?}"
    );
    let done_gen: u64 = done_line
        .split_whitespace()
        .nth(1)
        .expect("DONE generation")
        .parse()
        .expect("generation is a number");
    let _ = done_gen;

    let timed = vissue(&[
        "wait",
        "--id",
        "atlas-1a2b",
        "--until-terminal",
        "--poll-ms",
        "50",
        "--timeout-ms",
        "200",
    ]);
    assert_eq!(
        timed.status.code(),
        Some(2),
        "open issue should time out: {}",
        stdout(&timed)
    );
    let timed_line = stdout(&timed).trim().to_string();
    assert!(
        timed_line.starts_with("TIMEOUT STARTED "),
        "expected TIMEOUT STARTED <gen>, got {timed_line:?}"
    );

    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let root = dir.path().to_str().unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let id = stdout(&own(&["create", "-p", "atlas", "--quiet", "close me"]))
        .trim()
        .to_string();
    let updated = own(&["update", &id, "--state", "CANCELLED"]);
    assert!(
        updated.status.success(),
        "{}",
        String::from_utf8_lossy(&updated.stderr)
    );
    let cancelled = own(&[
        "wait",
        "--id",
        &id,
        "--until-terminal",
        "--timeout-ms",
        "1000",
    ]);
    assert!(
        cancelled.status.success(),
        "CANCELLED issue should exit 0: {}",
        String::from_utf8_lossy(&cancelled.stderr)
    );
    let cancelled_line = stdout(&cancelled).trim().to_string();
    assert!(
        cancelled_line.starts_with("CANCELLED "),
        "expected CANCELLED <gen>, got {cancelled_line:?}"
    );
}

#[test]
fn wait_until_terminal_without_id_exits_one() {
    let out = vissue(&["wait", "--until-terminal", "--timeout-ms", "200"]);
    assert_eq!(
        out.status.code(),
        Some(1),
        "missing --id must be exit 1, not clap's 2: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("--id"), "{err}");
}

#[test]
fn wait_until_terminal_unknown_id_exits_one() {
    let out = vissue(&[
        "wait",
        "--id",
        "atlas-zzzz",
        "--until-terminal",
        "--timeout-ms",
        "200",
    ]);
    assert_eq!(out.status.code(), Some(1), "{}", stdout(&out));
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("atlas-zzzz"), "{err}");
}

/// `reject` closes the source and names a destination: an existing id, or
/// a heading created for the purpose. `--reason` is recorded on the source.
#[test]
fn reject_redirects_to_an_existing_issue_or_a_new_one() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let root = dir.path().to_str().unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };

    let src = stdout(&own(&["create", "-p", "atlas", "--quiet", "old plan"]))
        .trim()
        .to_string();
    let dst = stdout(&own(&["create", "-p", "atlas", "--quiet", "the rewrite"]))
        .trim()
        .to_string();
    let rejected = own(&[
        "reject",
        &src,
        "--to",
        &dst,
        "--reason",
        "duplicate of the rewrite",
    ]);
    assert!(
        rejected.status.success(),
        "{}",
        String::from_utf8_lossy(&rejected.stderr)
    );
    let shown = stdout(&own(&["show", "--org", &src]));
    assert!(shown.contains("CANCELLED"), "source not closed: {shown}");
    assert!(
        shown.contains("duplicate of the rewrite"),
        "reason missing: {shown}"
    );

    let src2 = stdout(&own(&[
        "create",
        "-p",
        "atlas",
        "--quiet",
        "another old plan",
    ]))
    .trim()
    .to_string();
    let created = own(&[
        "reject",
        &src2,
        "--project",
        "atlas",
        "Rewrite the old plan",
        "--reason",
        "superseded",
    ]);
    assert!(
        created.status.success(),
        "{}",
        String::from_utf8_lossy(&created.stderr)
    );
    let listed = stdout(&own(&["list", "-p", "atlas"]));
    assert!(
        listed.contains("Rewrite the old plan"),
        "replacement heading missing: {listed}"
    );
    let shown2 = stdout(&own(&["show", "--org", &src2]));
    assert!(shown2.contains("CANCELLED"), "source2 not closed: {shown2}");
}

#[test]
fn reject_without_a_destination_fails() {
    let out = vissue(&["reject", "atlas-2c3d"]);
    assert!(!out.status.success(), "reject with no dest must fail");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("--to") || err.contains("--project"), "{err}");
}

#[test]
fn update_if_state_refuses_a_stale_done_after_reject() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let root = dir.path().to_str().unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let src = stdout(&own(&["create", "-p", "atlas", "--quiet", "old"]))
        .trim()
        .to_string();
    let dst = stdout(&own(&["create", "-p", "atlas", "--quiet", "new"]))
        .trim()
        .to_string();
    assert!(own(&["reject", &src, "--to", &dst]).status.success());
    let stale = own(&["update", &src, "--state", "DONE", "--if-state", "STARTED"]);
    assert!(!stale.status.success(), "{}", stdout(&stale));
    let err = String::from_utf8_lossy(&stale.stderr);
    assert!(err.contains("CANCELLED"), "{err}");
    let shown = stdout(&own(&["show", "--org", &src]));
    assert!(shown.contains("CANCELLED"), "{shown}");
    assert!(!shown.contains("* DONE"), "{shown}");
}

#[test]
fn update_if_gen_and_resolve_keep_the_first_terminal() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let root = dir.path().to_str().unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", root];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let id = stdout(&own(&["create", "-p", "atlas", "--quiet", "close me"]))
        .trim()
        .to_string();
    let seen: u64 = stdout(&own(&["gen"])).trim().parse().unwrap();
    assert!(own(&["update", &id, "--state", "DONE"]).status.success());
    let stale = own(&[
        "update",
        &id,
        "--state",
        "CANCELLED",
        "--if-gen",
        &seen.to_string(),
    ]);
    assert!(!stale.status.success(), "{}", stdout(&stale));
    assert!(
        own(&["update", &id, "--state", "CANCELLED"])
            .status
            .success()
    );
    let shown = stdout(&own(&["show", "--org", &id]));
    assert!(shown.contains("DONE"), "{shown}");
    assert!(shown.contains("SIBLING_TERMINAL"), "{shown}");
    assert!(
        own(&["resolve", &id, "--state", "CANCELLED"])
            .status
            .success()
    );
    let shown = stdout(&own(&["show", "--org", &id]));
    assert!(shown.contains("CANCELLED"), "{shown}");
    assert!(!shown.contains("SIBLING_TERMINAL"), "{shown}");
}

#[test]
fn a_user_config_route_wins_over_an_explicit_root() {
    let tmp = tempfile::tempdir().unwrap();
    let vault = tmp.path().join("vault");
    let work = tmp.path().join("work");
    std::fs::create_dir_all(vault.join("Software")).unwrap();
    std::fs::create_dir_all(work.join("Issues")).unwrap();
    let cfg = tmp.path().join("config.toml");
    std::fs::write(
        &cfg,
        format!(
            "[layouts.work]\nroot = \"{}\"\nprefix = \"Issues\"\n\n[routes]\nparser = \"work\"\n",
            work.display()
        ),
    )
    .unwrap();

    let run = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_vissue"))
            .env_remove("VISSUE_NO_ROUTE")
            .env("VISSUE_CONFIG", &cfg)
            .args(["--root", vault.to_str().unwrap()])
            .args(args)
            .output()
            .unwrap()
    };

    let created = run(&["create", "-p", "parser", "--quiet", "routed ticket"]);
    assert!(
        created.status.success(),
        "{}",
        String::from_utf8_lossy(&created.stderr)
    );
    let id = stdout(&created).trim().to_string();
    assert!(id.starts_with("parser-"), "{id}");
    assert!(
        work.join("Issues/parser/issues.org").exists(),
        "create must write the routed checkout"
    );
    assert!(
        !vault.join("Software/parser/issues.org").exists(),
        "create must not write the process-default checkout"
    );

    let shown = run(&["show", &id]);
    assert!(
        shown.status.success(),
        "{}",
        String::from_utf8_lossy(&shown.stderr)
    );
    assert!(
        stdout(&shown).contains("routed ticket"),
        "{}",
        stdout(&shown)
    );

    let projects = stdout(&run(&["projects"]));
    assert!(projects.contains("parser"), "{projects}");

    let skipped = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .env("VISSUE_CONFIG", &cfg)
        .args(["--root", vault.to_str().unwrap(), "--no-route"])
        .args(["create", "-p", "parser", "--quiet", "unrouted ticket"])
        .output()
        .unwrap();
    assert!(
        skipped.status.success(),
        "{}",
        String::from_utf8_lossy(&skipped.stderr)
    );
    assert!(vault.join("Software/parser/issues.org").exists());
}

/// The command line carries every verb the schema names.
///
/// Together with the socket and tool guards, this is what makes a verb impossible
/// to add to one surface and forget on the others: the schema states the set once,
/// and three tests in three crates each fail by name until their surface satisfies
/// it. Before this the docs tests checked that the reference listed what existed,
/// which is a different question and stayed green through every gap.
#[test]
fn the_command_line_offers_every_verb_the_schema_names() {
    let help = vissue(&["--help"]);
    let text = String::from_utf8_lossy(&help.stdout).to_string();
    let missing: Vec<String> = vissue_core::surface::mutating_cli_verbs()
        .into_iter()
        .filter(|verb| {
            // The verb has to appear as a subcommand, so a substring of prose does
            // not satisfy it: help lists them one per line, indented.
            !text
                .lines()
                .any(|line| line.split_whitespace().next() == Some(verb.as_str()))
        })
        .collect();
    assert!(
        missing.is_empty(),
        "the schema names these verbs and the command line does not offer them: {missing:?}"
    );
}

/// The command line's own account of itself, read once.
///
/// `vissue surface` walks the built `clap::Command` and prints every subcommand with
/// its aliases and long flags. Asking the parser is exact where reading its rendered
/// help is a guess: a flag reaches the JSON because the parser accepts it, not
/// because a line of help happened to spell it in a way a filter recognised. One
/// process answers for the whole surface, so the checks below cost one spawn between
/// them rather than one per verb.
fn cli_surface() -> &'static Vec<CliVerb> {
    static SURFACE: std::sync::OnceLock<Vec<CliVerb>> = std::sync::OnceLock::new();
    SURFACE.get_or_init(|| {
        let out = vissue(&["surface"]);
        assert!(
            out.status.success(),
            "vissue surface failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let verbs: Vec<CliVerb> = serde_json::from_slice(&out.stdout)
            .expect("vissue surface emits a JSON array of verbs");
        assert!(
            verbs.len() > 20,
            "the command line reports {} subcommands, which is too few to be the real surface",
            verbs.len()
        );
        verbs
    })
}

#[derive(serde::Deserialize)]
struct CliVerb {
    name: String,
    hidden: bool,
    aliases: Vec<String>,
    flags: Vec<String>,
}

/// Each verb offers the flags the schema names for it.
///
/// Naming a verb on each surface stops the verb going missing. It does not stop the
/// surfaces disagreeing about what to call a field, which is the next way this
/// drifts: a socket method taking `body` where the subcommand takes `--text` is two
/// spellings of one idea and nothing would notice.
#[test]
fn each_verb_offers_the_flags_the_schema_names() {
    let surface = cli_surface();
    let mut wrong = Vec::new();
    for op in vissue_core::surface::operations() {
        if op.cli.is_empty() || op.fields.is_empty() {
            continue;
        }
        let Some(verb) = surface.iter().find(|v| v.name == op.cli) else {
            continue; // every_subcommand_appears_in_the_schema owns the other direction
        };
        for field in &op.fields {
            if field.cli.is_empty() {
                continue;
            }
            if !verb.flags.contains(&field.cli) {
                wrong.push(format!("{} has no --{}", op.cli, field.cli));
            }
        }
    }
    assert!(
        wrong.is_empty(),
        "the schema names flags these verbs do not take: {wrong:?}"
    );
}

/// Every subcommand appears in the schema.
///
/// This is the check that makes a *new* verb impossible to add unnoticed. Without
/// it the schema constrains only the verbs it already mentions: a brand-new
/// subcommand fails nothing, because nothing asks whether the schema knows about it,
/// which is how the earlier gaps arrived. `vote` reached the command line and no
/// test anywhere had an opinion.
///
/// Shell-completion variants are excluded because clap generates one subcommand per
/// shell from a single `completions` verb, and they are not separate operations.
/// Hidden subcommands describe the binary rather than the tracker, so a schema of
/// tracker operations is the wrong place to enumerate them.
#[test]
fn every_subcommand_appears_in_the_schema() {
    const SHELLS: &[&str] = &["bash", "zsh", "fish", "elvish", "powershell"];

    let known = vissue_core::surface::cli_verbs();
    let unknown: Vec<&str> = cli_surface()
        .iter()
        .filter(|v| !v.hidden && v.name != "help" && !SHELLS.contains(&v.name.as_str()))
        .map(|v| v.name.as_str())
        .filter(|name| !known.iter().any(|k| k == name))
        .collect();
    assert!(
        unknown.is_empty(),
        "these subcommands are in no schema row, so no surface check can see them: {unknown:?}"
    );
}

/// The schema and the parser agree about which names are aliases.
///
/// An alias is one verb under two names, so it takes the flags of the verb it
/// aliases. A separate subcommand that merely does a similar job takes its own, and
/// calling it an alias overstates what a caller can pass: the schema recorded `q` as
/// an alias of `create`, and `q` rejects `--body` and `--priority`, so a row that
/// listed create's ten fields answered for a verb that accepts three.
///
/// Both directions matter. An alias the parser accepts and the schema omits is a
/// verb no surface check can see; a name the schema calls an alias and the parser
/// treats as its own subcommand needs its own row.
#[test]
fn the_schema_and_the_parser_agree_about_aliases() {
    let surface = cli_surface();
    let ops = vissue_core::surface::operations();

    let mut wrong = Vec::new();
    for op in &ops {
        for alias in &op.aliases {
            if surface.iter().any(|v| &v.name == alias) {
                wrong.push(format!(
                    "the schema calls {alias} an alias of {} and the parser makes it a \
                     subcommand of its own, which takes its own flags",
                    op.cli
                ));
            } else if !surface
                .iter()
                .any(|v| v.name == op.cli && v.aliases.contains(alias))
            {
                wrong.push(format!(
                    "the schema calls {alias} an alias of {} and the parser does not",
                    op.cli
                ));
            }
        }
    }
    for verb in surface {
        if verb.hidden {
            continue;
        }
        for alias in &verb.aliases {
            if !ops
                .iter()
                .any(|o| o.cli == verb.name && o.aliases.contains(alias))
            {
                wrong.push(format!(
                    "{} answers to {alias} and no schema row says so",
                    verb.name
                ));
            }
        }
    }
    assert!(
        wrong.is_empty(),
        "the schema and the command line disagree about aliases: {wrong:?}"
    );
}

/// Every flag a verb takes is in the schema.
///
/// The flag checks run schema to surface: a flag the schema names has to exist. A
/// flag that exists and the schema omits is the same asymmetry as at the verb level,
/// one level down, and this is the direction that catches it.
///
/// Global flags are subtracted from `globalFlags` in the schema rather than repeated
/// on forty rows, so a per-verb row stays about what the verb actually takes. A verb
/// with no schema row at all is caught by `every_subcommand_appears_in_the_schema`,
/// so this only reports flags on verbs the schema knows.
#[test]
fn every_flag_a_verb_takes_is_in_the_schema() {
    let globals = vissue_core::surface::global_flags();
    let surface = cli_surface();

    let mut unknown = Vec::new();
    for op in vissue_core::surface::operations() {
        // A local verb's flags are about this process rather than about an
        // operation: the HUD's nine are window management, `serve --detach` is a
        // lifecycle choice. Enumerating them in a schema of operations buys nothing
        // and would bury the flags that do describe a surface.
        if op.cli.is_empty() || op.local {
            continue;
        }
        let Some(verb) = surface.iter().find(|v| v.name == op.cli) else {
            continue;
        };
        let named: Vec<&str> = op.fields.iter().map(|f| f.cli.as_str()).collect();
        for flag in &verb.flags {
            if globals.contains(flag) || named.contains(&flag.as_str()) {
                continue;
            }
            unknown.push(format!("{} --{flag}", op.cli));
        }
    }
    assert!(
        unknown.is_empty(),
        "these flags exist and no schema field mentions them: {unknown:?}"
    );
}

/// The loop the three layers exist for, end to end: a plan is split, the first
/// node is worked and names what it made, and the second node's working set
/// hands that product to whoever picks it up.
///
/// Through the built binary rather than the library, because the handoff is
/// between two processes that share nothing but the file, which is the whole
/// claim.
#[test]
fn a_finished_node_hands_its_product_to_the_next_one() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let id = |args: &[&str]| -> String { stdout(&own(args)).trim().to_string() };

    let epic = id(&["create", "-p", "keys", "--type", "plan", "Epic", "-q"]);
    let first = id(&[
        "create",
        "-p",
        "keys",
        "--parent",
        &epic,
        "Catalog the actions",
        "-q",
    ]);
    let second = id(&[
        "create",
        "-p",
        "keys",
        "--parent",
        &epic,
        "Write the schema",
        "-q",
    ]);
    own(&["update", &second, "--block", &first]);

    // The first node finishes and names its product.
    let cited = own(&["deed", &first, "--add", "deed-file-catalog"]);
    assert!(cited.status.success(), "{}", stdout(&cited));
    own(&["update", &first, "--state", "DONE"]);

    let recalled = stdout(&own(&["recall", &second]));
    assert!(recalled.contains(&epic), "the plan is missing: {recalled}");
    assert!(
        recalled.contains(&first) && recalled.contains("blocked-by"),
        "the input is missing: {recalled}"
    );
    assert!(
        recalled.contains("deed-file-catalog"),
        "the input's product is the point: {recalled}"
    );

    // The form a shell substitutes into `deedar get`.
    assert_eq!(
        stdout(&own(&["recall", &second, "--deeds-only"])),
        "deed-file-catalog\n"
    );

    // And the structure a remote surface answers with.
    let json: serde_json::Value =
        serde_json::from_str(&stdout(&own(&["recall", &second, "--json"]))).expect("json");
    assert_eq!(json["inputs"][0]["deeds"][0], "deed-file-catalog");
    assert_eq!(json["inputs"][0]["relation"], "blocked-by");
}

/// A plurality that the group's own weighting reverses, over the command line.
/// `vote` reports the count and `consensus` reports where the weight actually
/// sits, so an agent acting on either can see the other.
#[test]
fn the_consensus_weighs_the_ballots_the_tally_counts() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    fs::write(
        dir.path().join("vissue.toml"),
        "[consensus.trust]\nalice = { carol = 1.0 }\nbob = { carol = 1.0 }\n\
         carol = { carol = 4.0, alice = 1.0 }\n",
    )
    .unwrap();
    let own = |agent: &str, args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd()
            .env("VISSUE_AGENT", agent)
            .args(argv)
            .output()
            .unwrap()
    };

    let id = stdout(&own("alice", &["create", "-p", "api", "Ship it?", "-q"]))
        .trim()
        .to_string();
    own("alice", &["vote", &id, "--for", "ship"]);
    own("bob", &["vote", &id, "--for", "ship"]);
    own("carol", &["vote", &id, "--for", "hold"]);

    let tally = stdout(&own("alice", &["vote", &id]));
    assert!(tally.contains("consensus: ship (2 of 3)"), "{tally}");

    let weighed = stdout(&own("alice", &["consensus", &id]));
    assert!(weighed.contains("holds: hold"), "{weighed}");
    assert!(
        weighed.contains("the count leads with ship"),
        "the difference is the reason to run it: {weighed}"
    );
    assert!(weighed.contains("social power"), "{weighed}");
}

/// With no trust configured the weighted answer is the count as a fraction, so
/// the verb is safe on a tracker nobody has set up.
#[test]
fn an_unconfigured_tracker_gets_the_tally_back_as_shares() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |agent: &str, args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd()
            .env("VISSUE_AGENT", agent)
            .args(argv)
            .output()
            .unwrap()
    };

    let id = stdout(&own("alice", &["create", "-p", "api", "Ship it?", "-q"]))
        .trim()
        .to_string();
    own("alice", &["vote", &id, "--for", "ship"]);
    own("bob", &["vote", &id, "--for", "ship"]);
    own("carol", &["vote", &id, "--for", "hold"]);

    let weighed = stdout(&own("alice", &["consensus", &id]));
    assert!(weighed.contains("trust default"), "{weighed}");
    assert!(
        weighed.contains("ship                     0.667"),
        "{weighed}"
    );
    assert!(
        weighed.contains("hold                     0.333"),
        "{weighed}"
    );
    assert!(
        !weighed.contains("the count leads with"),
        "nothing was reweighted, so there is nothing to point out: {weighed}"
    );
}

/// Work that continues on the product it was handed cites the same deed as its
/// input. The accession list is a shell substitution, so a repeat would fetch
/// or check the same deed twice.
#[test]
fn the_accession_list_names_each_deed_once() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let id = |args: &[&str]| -> String { stdout(&own(args)).trim().to_string() };

    let first = id(&["create", "-p", "keys", "The groundwork", "-q"]);
    let second = id(&["create", "-p", "keys", "More of the same", "-q"]);
    own(&["update", &second, "--block", &first]);
    own(&["deed", &first, "--add", "deed-file-shared"]);
    own(&["deed", &second, "--add", "deed-file-shared"]);

    assert_eq!(
        stdout(&own(&["recall", &second, "--deeds-only"])),
        "deed-file-shared\n"
    );
}

/// Two review groups that cite only each other never converge, and the report
/// has to say what each of them settled on. Naming the groups without naming
/// their positions leaves a reader knowing there is a disagreement and not what
/// it is about.
#[test]
fn a_split_report_says_what_each_group_holds() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    fs::write(
        dir.path().join("vissue.toml"),
        "[consensus.trust]\nalice = { bob = 1.0 }\nbob = { alice = 1.0 }\n\
         carol = { dave = 1.0 }\ndave = { carol = 1.0 }\n",
    )
    .unwrap();
    let own = |agent: &str, args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd()
            .env("VISSUE_AGENT", agent)
            .args(argv)
            .output()
            .unwrap()
    };

    let id = stdout(&own("alice", &["create", "-p", "api", "Ship it?", "-q"]))
        .trim()
        .to_string();
    for (agent, choice) in [
        ("alice", "ship"),
        ("bob", "ship"),
        ("carol", "hold"),
        ("dave", "hold"),
    ] {
        own(agent, &["vote", &id, "--for", choice]);
    }

    let split = stdout(&own("alice", &["consensus", &id]));
    assert!(split.contains("no consensus"), "{split}");
    assert!(split.contains("2 group(s)"), "{split}");
    assert!(split.contains("alice, bob"), "{split}");
    assert!(
        split.contains("ship 1.000") && split.contains("hold 1.000"),
        "each group has to say what it settled on: {split}"
    );
}

/// A plan whose children each reached agreement, and disagree with each other.
/// That is the case the roll-up exists for, and the case an average would hide
/// by reporting a number in between two positions nobody holds.
#[test]
fn a_plan_roll_up_reports_the_children_rather_than_averaging_them() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |agent: &str, args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd()
            .env("VISSUE_AGENT", agent)
            .args(argv)
            .output()
            .unwrap()
    };
    let id =
        |agent: &str, args: &[&str]| -> String { stdout(&own(agent, args)).trim().to_string() };

    let plan = id(
        "a",
        &[
            "create",
            "-p",
            "api",
            "--type",
            "plan",
            "Ship the release",
            "-q",
        ],
    );
    let one = id(
        "a",
        &[
            "create",
            "-p",
            "api",
            "--parent",
            &plan,
            "The exporter",
            "-q",
        ],
    );
    let two = id(
        "a",
        &[
            "create",
            "-p",
            "api",
            "--parent",
            &plan,
            "The importer",
            "-q",
        ],
    );
    let three = id(
        "a",
        &["create", "-p", "api", "--parent", &plan, "The docs", "-q"],
    );

    // Each child is internally agreed, and they point different ways.
    for agent in ["a", "b"] {
        own(agent, &["vote", &one, "--for", "ship"]);
        own(agent, &["vote", &two, "--for", "hold"]);
    }

    let rolled = stdout(&own("a", &["consensus", &plan, "--children"]));
    assert!(rolled.contains("3 children, 2 with ballots"), "{rolled}");
    assert!(
        rolled.contains("the children disagree with each other: 2 positions"),
        "the whole point of the row-by-row report: {rolled}"
    );
    assert!(
        rolled.contains("1 child(ren) carry no ballots") && rolled.contains(&three),
        "an unvoted child is named, not folded in as a neutral vote: {rolled}"
    );
    assert!(rolled.contains("no ballots"), "{rolled}");

    // And the structured form carries the same rows.
    let json: serde_json::Value = serde_json::from_str(&stdout(&own(
        "a",
        &["consensus", &plan, "--children", "--json"],
    )))
    .expect("json");
    assert_eq!(json["plan"], serde_json::json!(plan));
    assert_eq!(json["children"].as_array().unwrap().len(), 3);
}

/// The roll-up over an issue with no children says so rather than reporting an
/// agreement over an empty set.
#[test]
fn a_plan_with_no_children_has_nothing_to_roll_up() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let alone = stdout(&own(&["create", "-p", "api", "On its own", "-q"]))
        .trim()
        .to_string();
    let rolled = stdout(&own(&["consensus", &alone, "--children"]));
    assert!(rolled.contains("no children"), "{rolled}");
}

/// What an input concluded is in its body, not in the deed it named. The deed
/// is the product; the reasoning is the prose, and the next unit usually wants
/// both.
#[test]
fn recall_can_splice_in_what_the_inputs_concluded() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let id = |args: &[&str]| -> String { stdout(&own(args)).trim().to_string() };

    let first = id(&[
        "create",
        "-p",
        "keys",
        "--body",
        "Landed without the modifier table; the xkbcommon names win over the Emacs ones.",
        "The groundwork",
        "-q",
    ]);
    let second = id(&["create", "-p", "keys", "The next step", "-q"]);
    own(&["update", &second, "--block", &first]);

    let plain = stdout(&own(&["recall", &second]));
    assert!(
        !plain.contains("xkbcommon names win"),
        "off unless asked, since most callers want the accessions: {plain}"
    );

    let spliced = stdout(&own(&["recall", &second, "--excerpts"]));
    assert!(
        spliced.contains("xkbcommon names win"),
        "the input's own reasoning: {spliced}"
    );

    // And the structured form carries it, since the remote surfaces answer there.
    let json: serde_json::Value =
        serde_json::from_str(&stdout(&own(&["recall", &second, "--excerpts", "--json"])))
            .expect("json");
    assert!(
        json["inputs"][0]["excerpt"]
            .as_str()
            .unwrap_or_default()
            .contains("xkbcommon"),
        "{json}"
    );
    let without: serde_json::Value =
        serde_json::from_str(&stdout(&own(&["recall", &second, "--json"]))).expect("json");
    assert!(
        without["inputs"][0].get("excerpt").is_none(),
        "the field is absent rather than null when it was not asked for: {without}"
    );
}

/// An input whose body looks like credential material is suppressed here for
/// the same reason `body-excerpt` suppresses it. A working set is pasted into a
/// model's context, which is the last place a key should be spliced.
#[test]
fn a_credential_shaped_input_is_suppressed_in_the_working_set() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let id = |args: &[&str]| -> String { stdout(&own(args)).trim().to_string() };

    let leaky = id(&[
        "create",
        "-p",
        "ops",
        "--body",
        "the runner needs access_token=abcd1234 to reach the registry",
        "Wire up the runner",
        "-q",
    ]);
    let next = id(&["create", "-p", "ops", "Use the runner", "-q"]);
    own(&["update", &next, "--block", &leaky]);

    let spliced = stdout(&own(&["recall", &next, "--excerpts"]));
    assert!(
        !spliced.contains("abcd1234"),
        "a credential must not reach a working set: {spliced}"
    );
    assert!(
        spliced.contains("excerpt suppressed"),
        "and the reader has to know something was withheld: {spliced}"
    );
}

/// The gate is an exit status a shell hook can act on, and it prints the report
/// either way. A gate that swallowed the reason it failed would send a reader
/// back to run the command again without it.
#[test]
fn the_consensus_gate_carries_the_verdict_in_the_exit_status() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |agent: &str, args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd()
            .env("VISSUE_AGENT", agent)
            .args(argv)
            .output()
            .unwrap()
    };
    let id =
        |agent: &str, args: &[&str]| -> String { stdout(&own(agent, args)).trim().to_string() };

    let issue = id("a", &["create", "-p", "api", "Ship it?", "-q"]);

    // No ballots at all is not something to act on.
    let empty = own("a", &["consensus", &issue, "--gate"]);
    assert!(
        !empty.status.success(),
        "no votes is not a settled question"
    );

    // A tie is agreement on nothing, and the gate has to say so.
    own("a", &["vote", &issue, "--for", "ship"]);
    own("b", &["vote", &issue, "--for", "hold"]);
    let tied = own("a", &["consensus", &issue, "--gate"]);
    assert!(!tied.status.success(), "{}", stdout(&tied));
    assert!(
        stdout(&tied).contains("no lead"),
        "the report still prints, so the reason is on screen: {}",
        stdout(&tied)
    );

    // A majority the group's weight agrees with passes.
    own("c", &["vote", &issue, "--for", "ship"]);
    let led = own("a", &["consensus", &issue, "--gate"]);
    assert!(led.status.success(), "{}", stdout(&led));
    assert!(stdout(&led).contains("holds: ship"), "{}", stdout(&led));
}

/// Over a plan the rule is different and the design note says why: a split
/// child has no position to fold in and an unvoted child is absent rather than
/// neutral, so either one is a row a person has to read.
#[test]
fn the_plan_gate_fails_on_an_unvoted_or_split_child() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |agent: &str, args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd()
            .env("VISSUE_AGENT", agent)
            .args(argv)
            .output()
            .unwrap()
    };
    let id =
        |agent: &str, args: &[&str]| -> String { stdout(&own(agent, args)).trim().to_string() };

    let plan = id(
        "a",
        &["create", "-p", "api", "--type", "plan", "The release", "-q"],
    );
    let one = id(
        "a",
        &["create", "-p", "api", "--parent", &plan, "First", "-q"],
    );
    let two = id(
        "a",
        &["create", "-p", "api", "--parent", &plan, "Second", "-q"],
    );

    for agent in ["a", "b"] {
        own(agent, &["vote", &one, "--for", "ship"]);
    }
    let unvoted = own("a", &["consensus", &plan, "--children", "--gate"]);
    assert!(
        !unvoted.status.success(),
        "one child carries no ballots: {}",
        stdout(&unvoted)
    );

    for agent in ["a", "b"] {
        own(agent, &["vote", &two, "--for", "ship"]);
    }
    let settled = own("a", &["consensus", &plan, "--children", "--gate"]);
    assert!(settled.status.success(), "{}", stdout(&settled));
}

/// Forward, the join is fine: an issue names its accessions. Backwards, from a
/// product to everything depending on it, is the question you have exactly when
/// the product turns out to be wrong.
#[test]
fn backlinks_answers_for_a_deed_as_well_as_an_issue() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let id = |args: &[&str]| -> String { stdout(&own(args)).trim().to_string() };

    let one = id(&["create", "-p", "keys", "Built the overlay", "-q"]);
    let two = id(&["create", "-p", "api", "Used the overlay", "-q"]);
    let other = id(&["create", "-p", "api", "Unrelated", "-q"]);
    own(&["deed", &one, "--add", "deed-patch-overlay"]);
    own(&["deed", &two, "--add", "deed-patch-overlay"]);
    own(&["deed", &other, "--add", "deed-file-something-else"]);

    let cites = stdout(&own(&["backlinks", "deed-patch-overlay"]));
    assert!(cites.contains(&one) && cites.contains(&two), "{cites}");
    assert!(!cites.contains(&other), "only what cites this one: {cites}");
    assert!(cites.contains("(cites)"), "the evidence is named: {cites}");

    // The structured shape answers the same question, since a hook reading the
    // rows and a person reading the table must not disagree.
    let rows: serde_json::Value = serde_json::from_str(&stdout(&own(&[
        "backlinks",
        "deed-patch-overlay",
        "--json",
    ])))
    .unwrap();
    let rows = rows.as_array().unwrap();
    assert_eq!(rows.len(), 2, "{rows:?}");
    assert!(
        rows.iter().all(|r| r["relation"] == "cites"),
        "the relation names the evidence: {rows:?}"
    );

    // An accession nobody cited is an empty answer, not an error: the deed may
    // be real and simply unused.
    assert_eq!(stdout(&own(&["backlinks", "deed-quote-nobody-cited"])), "");
    assert!(
        own(&["backlinks", "deed-quote-nobody-cited"])
            .status
            .success()
    );

    // An id nobody minted and that is not accession-shaped is still an error.
    assert!(!own(&["backlinks", "keys-zzzz"]).status.success());
}

/// Answering "none" out of a directory that holds no tracker is a wrong
/// answer, not a small one. A caller cannot tell it from a tracker with
/// nothing in it, and the two mean opposite things.
#[test]
fn a_directory_that_is_not_a_tracker_says_so_rather_than_answering_none() {
    let dir = tempfile::tempdir().unwrap();
    let run = |args: &[&str], cwd: &std::path::Path| {
        Command::new(env!("CARGO_BIN_EXE_vissue"))
            .env("VISSUE_NO_ROUTE", "1")
            .env_remove("VISSUE_ROOT")
            .env_remove("ISSUE_ROOT")
            .current_dir(cwd)
            .args(args)
            .output()
            .unwrap()
    };

    let out = run(&["count"], dir.path());
    assert!(!out.status.success(), "counted anyway: {}", stdout(&out));
    let complaint = String::from_utf8(out.stderr).unwrap();
    assert!(complaint.contains("is not a tracker"), "{complaint}");

    // The prefix directory alone makes it one, empty or not: a tracker with
    // nothing in it is a real answer and has to stay countable.
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let out = run(&["count"], dir.path());
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(stdout(&out).trim(), "0");
}

/// A root somebody named is trusted whether or not it holds anything, because
/// they said which one they meant.
#[test]
fn a_named_root_is_not_second_guessed() {
    let dir = tempfile::tempdir().unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .env("VISSUE_NO_ROUTE", "1")
        .env_remove("VISSUE_ROOT")
        .args(["--root", dir.path().to_str().unwrap(), "count"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(stdout(&out).trim(), "0");

    let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .env("VISSUE_NO_ROUTE", "1")
        .env("VISSUE_ROOT", dir.path())
        .current_dir(dir.path())
        .args(["count"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

/// Describing the program is not reading a corpus, and a shell sourcing
/// completions is not standing in a tracker.
#[test]
fn man_and_completions_work_from_anywhere() {
    let dir = tempfile::tempdir().unwrap();
    for args in [vec!["man"], vec!["completions", "bash"]] {
        let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
            .env("VISSUE_NO_ROUTE", "1")
            .env_remove("VISSUE_ROOT")
            .env_remove("ISSUE_ROOT")
            .current_dir(dir.path())
            .args(&args)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(!out.stdout.is_empty(), "{args:?} wrote nothing");
    }
}

/// A corpus fault must not be answered as a citation list.
///
/// The accession walk exists because an accession has no heading of its own.
/// An id that has one in two routed trackers is a different thing, and
/// answering it with the empty scan of a deed would report the fault as "no
/// issue cites this" for as long as nobody looked the id up by another route.
#[test]
fn a_duplicated_accession_shaped_id_is_reported_rather_than_walked_as_a_deed() {
    let tmp = tempfile::tempdir().unwrap();
    let vault = tmp.path().join("vault");
    let work = tmp.path().join("work");
    fs::create_dir_all(vault.join("Software/keys")).unwrap();
    fs::create_dir_all(work.join("Issues/api")).unwrap();
    let cfg = tmp.path().join("config.toml");
    fs::write(
        &cfg,
        format!(
            "[layouts.work]\nroot = \"{}\"\nprefix = \"Issues\"\n\n[routes]\napi = \"work\"\n",
            work.display()
        ),
    )
    .unwrap();

    // One accession-shaped id, a heading of that id in each tracker.
    let heading = |title: &str| {
        format!(
            "#+TITLE: sample\n#+TODO: TODO STARTED BLOCKED | DONE CANCELLED\n\n\
             * TODO [#B] {title}\n:PROPERTIES:\n:ID:         deed-patch-overlay\n:END:\n"
        )
    };
    fs::write(
        vault.join("Software/keys/issues.org"),
        heading("Built the overlay"),
    )
    .unwrap();
    fs::write(
        work.join("Issues/api/issues.org"),
        heading("Used the overlay"),
    )
    .unwrap();

    let out = Command::new(env!("CARGO_BIN_EXE_vissue"))
        .env_remove("VISSUE_NO_ROUTE")
        .env("VISSUE_CONFIG", &cfg)
        .args(["--root", vault.to_str().unwrap()])
        .args(["backlinks", "deed-patch-overlay"])
        .output()
        .unwrap();
    assert!(!out.status.success(), "{}", stdout(&out));
    let complaint = String::from_utf8(out.stderr).unwrap();
    assert!(
        complaint.contains("more than one tracker"),
        "the duplicate is named: {complaint}"
    );
}

/// A project named `deed` mints ids that look exactly like accessions. The
/// corpus decides, so a real id keeps its own meaning.
#[test]
fn a_known_issue_id_wins_over_the_accession_shape() {
    let dir = tempfile::tempdir().unwrap();
    fs::create_dir_all(dir.path().join("Software")).unwrap();
    let own = |args: &[&str]| -> std::process::Output {
        let mut argv = vec!["--root", dir.path().to_str().unwrap()];
        argv.extend_from_slice(args);
        vissue_cmd().args(argv).output().unwrap()
    };
    let id = |args: &[&str]| -> String { stdout(&own(args)).trim().to_string() };

    let target = id(&[
        "create",
        "-p",
        "deed",
        "A heading in a project called deed",
        "-q",
    ]);
    assert!(
        target.starts_with("deed-"),
        "the collision this guards is real: {target}"
    );
    let child = id(&["create", "-p", "deed", "Waits on it", "-q"]);
    own(&["update", &child, "--block", &target]);

    let links = stdout(&own(&["backlinks", &target]));
    assert!(
        links.contains("(blocked-by)"),
        "a known id is an issue whatever it looks like: {links}"
    );
}