vissue-core 0.9.2

Plain-text issue tracking over per-project orgmode files: model, store, queries, and org projection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
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
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
//! Mutating verbs: create, update, and move issues between projects.

use anyhow::{Context, anyhow};

use crate::error::Result;
use chrono::NaiveDate;
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};

use crate::config::{Layout, VissueConfig};
use crate::error::Error;
use crate::graph::DependencyGraph;
use crate::model::{IssueHeading, LogEntry, TODO_KEYWORDS, today_inactive_bracket};
use crate::store::{
    IssueDoc, collect_org_ids, detect_project_from_ctx, find_by_id, generate_id, load_all,
    resolve_existing_project_case, with_issues_lock, with_issues_locks,
};

/// Resolve the project to act on. An explicit name wins; otherwise walk up from
/// the current directory for `.project-ctx.toml` and read `[project].name`.
/// Neither available is an error, so nothing is ever guessed silently.
///
/// # Errors
///
/// Returns an error if the explicit project name is empty, no name can be
/// resolved, the current directory cannot be read, or the name matches more
/// than one project directory.
pub fn resolve_project(layout: &Layout, explicit: Option<&str>) -> Result<String> {
    if let Some(p) = explicit {
        if p.is_empty() {
            return Err(anyhow!("--project given but empty").into());
        }
        return resolve_existing_project_case(layout, p);
    }
    let cwd = std::env::current_dir()?;
    let detected = detect_project_from_ctx(&cwd).ok_or_else(|| {
        anyhow!(
            "no --project given and no .project-ctx.toml found walking up from {}",
            cwd.display()
        )
    })?;
    resolve_existing_project_case(layout, &detected)
}

/// Optional fields on a new issue.
#[derive(Debug, Default, Clone, Copy)]
pub struct CreateOpts<'a> {
    /// Priority cookie; the configured default is used when `None`.
    pub priority: Option<char>,
    /// `:TYPE:` property.
    pub issue_type: Option<&'a str>,
    /// Deadline as an org timestamp.
    pub deadline: Option<&'a str>,
    /// Scheduled date as an org timestamp.
    pub scheduled: Option<&'a str>,
    /// Comma- or colon-separated tags.
    pub tags: Option<&'a str>,
    /// `:PARENT:` id; must already exist somewhere under the prefix.
    pub parent: Option<&'a str>,
    /// Print only the new id.
    pub quiet: bool,
    /// Body prose written under the properties drawer.
    pub body: Option<&'a str>,
    /// Extra ids treated as taken when minting, so a twin file on another
    /// layout cannot share a suffix with this create.
    pub extra_ids: &'a [String],
    /// Twin files whose ids are read *inside* the lock and treated as taken.
    ///
    /// [`Self::extra_ids`] is a snapshot the caller took before calling, which
    /// is a read outside the lock that guards the write. Two creates for one
    /// project in two roots each read the other before either writes, hold
    /// different locks because locks are per file, and can mint one suffix
    /// twice. `find_by_id` then reports `DuplicateId` and neither issue is
    /// reachable by id.
    ///
    /// Paths given here are locked alongside the file being written and read
    /// after the lock is held, so a peer's create is either wholly before or
    /// wholly after this one.
    pub extra_id_paths: &'a [PathBuf],
}

/// Append a new TODO issue to the project's file and return the status text.
///
/// The first `[[id:XXX]]` in `body` that names a heading already in the
/// corpus becomes `:DISCOVERED_FROM:`, unless that property is already set.
/// Prose never writes `:BLOCKED_BY:`.
///
/// # Errors
///
/// Returns an error if the priority is not `A`/`B`/`C`, a date does not parse,
/// `parent` is not a known org id, the id space is exhausted, or the file
/// cannot be locked or rewritten.
pub fn create(layout: &Layout, project: &str, title: &str, opts: CreateOpts<'_>) -> Result<String> {
    let project = resolve_existing_project_case(layout, project)?;
    let cfg = VissueConfig::load(layout)?;
    let path = layout.project_issues_path(&project);
    let (spec, named) = match IssueDoc::parse_file(&project, &path) {
        Ok(doc) => (doc.priority_spec(), doc.priorities_are_named()),
        Err(_) => (crate::org::PrioritySpec::default(), false),
    };
    let house_new = !path.exists();
    let priority = opts.priority.unwrap_or(if named || house_new {
        spec.default
    } else {
        cfg.issues.default_priority
    });
    if !spec.contains(priority) {
        return Err(anyhow!(
            "invalid priority {priority:?}; file allows [#{}]..[#{}]",
            spec.highest,
            spec.lowest
        )
        .into());
    }

    // Parent and body [[id:]] both need the corpus id set; scan once.
    let known_ids = if opts.parent.is_some() || opts.body.is_some() {
        collect_org_ids(layout)?
    } else {
        std::collections::HashSet::new()
    };
    if let Some(p) = opts.parent
        && !known_ids.contains(p)
    {
        return Err(anyhow!("--parent {p} does not refer to any known id").into());
    }

    // Every file the mint consults is locked, not only the one it writes, so a
    // twin create in another root cannot land between the read and the write.
    // with_issues_locks sorts and dedups, so the write path appearing in
    // extra_id_paths is normal rather than a self-deadlock.
    let mut lock_paths: Vec<PathBuf> = vec![path.clone()];
    lock_paths.extend(opts.extra_id_paths.iter().cloned());
    let lock_refs: Vec<&Path> = lock_paths.iter().map(PathBuf::as_path).collect();
    with_issues_locks(&lock_refs, || {
        let mut doc = IssueDoc::parse_file(&project, &path)?;
        let mut taken = doc.known_ids();
        taken.extend(opts.extra_ids.iter().cloned());
        for twin in opts.extra_id_paths {
            if twin == &path {
                continue;
            }
            if let Ok(doc) = IssueDoc::parse_file(&project, twin) {
                taken.extend(doc.known_ids());
            }
        }
        let id = generate_id(&project, title, &taken, cfg.issues.id_length)?;

        let mut props = BTreeMap::new();
        props.insert("ID".into(), id.clone());
        props.insert("CREATED".into(), today_inactive_bracket());
        if crate::props::get(&props, crate::props::DISCOVERED_FROM).is_none()
            && let Some(body) = opts.body
            && let Some(origin) = first_existing_id_link(body, &known_ids)
        {
            crate::props::insert(&mut props, crate::props::DISCOVERED_FROM, origin);
        }
        let mut org_tags: Vec<String> = Vec::new();
        if let Some(t) = opts.issue_type {
            crate::props::insert(&mut props, crate::props::TYPE, t.into());
            // Type is an Org tag when the character class allows it, so
            // agenda tag search and C-c \ see `bug` / `feature` / `task`.
            if t.chars().all(crate::model::is_org_tag_char)
                && !t.is_empty()
                && !org_tags.iter().any(|seen| seen == t)
            {
                org_tags.push(t.to_string());
            }
        }
        if let Some(d) = opts.deadline {
            validate_org_date(d)?;
            props.insert("DEADLINE".into(), d.into());
        }
        if let Some(s) = opts.scheduled {
            validate_org_date(s)?;
            props.insert("SCHEDULED".into(), s.into());
        }
        // A tag Org can hold goes on the heading, where Org's own tag search
        // and agenda read it. One Org would not accept, `needs-review` say,
        // stays in the property so it survives instead of becoming title text.
        if let Some(tags) = opts.tags {
            let mut property_tags: Vec<String> = Vec::new();
            for tag in tags.split([',', ':']).map(str::trim) {
                if tag.is_empty() {
                    continue;
                }
                if tag.chars().all(crate::model::is_org_tag_char) {
                    if !org_tags.iter().any(|seen| seen == tag) {
                        org_tags.push(tag.to_string());
                    }
                } else if !property_tags.iter().any(|seen| seen == tag) {
                    property_tags.push(tag.to_string());
                }
            }
            if !property_tags.is_empty() {
                props.insert(crate::model::TAGS_PROPERTY.into(), property_tags.join(","));
            }
        }
        if let Some(p) = opts.parent {
            crate::props::insert(&mut props, crate::props::PARENT, p.into());
        }

        doc.headings.push(IssueHeading {
            id: id.clone(),
            title: title.to_string(),
            state: "TODO".into(),
            priority,
            properties: props,
            org_tags,
            statistics: None,
            property_order: Vec::new(),
            extra_drawers: Vec::new(),
            body: match opts.body {
                Some(b) if !b.trim().is_empty() => format!("{}\n", b.trim_end()),
                _ => String::new(),
            },
            logbook: Vec::new(),
            line_start: 0,
            line_end: 0,
        });
        doc.write()?;

        if opts.quiet {
            Ok(format!("{id}\n"))
        } else {
            Ok(format!(
                "{id}  TODO  [#{priority}]  {title}\nfile: {}\n",
                path.display()
            ))
        }
    })
}

pub(crate) fn validate_org_date(s: &str) -> Result<()> {
    let inner = s
        .trim_start_matches(['<', '['])
        .trim_end_matches(['>', ']']);
    let token = inner.split_whitespace().next().unwrap_or("");
    NaiveDate::parse_from_str(token, "%Y-%m-%d").with_context(|| {
        format!("expected org date like <YYYY-MM-DD> or [YYYY-MM-DD], got {s:?}")
    })?;
    Ok(())
}

/// Change state, priority, or blocker edges. Adding a blocker to an open issue
/// moves it to BLOCKED; clearing the last blocker moves it back to TODO.
///
/// # Errors
///
/// Returns an error if `id` is not in the corpus, the state or priority is
/// invalid, adding the blocker would cycle, or the file cannot be rewritten.
pub fn update(
    layout: &Layout,
    id: &str,
    new_state: Option<&str>,
    new_priority: Option<char>,
    block_add: Option<&str>,
    block_clear: Option<&str>,
) -> Result<UpdateOutcome> {
    let identity = crate::config::identity(layout);
    update_as(
        layout,
        id,
        new_state,
        new_priority,
        block_add,
        block_clear,
        &identity,
    )
}

/// Last-seen state or generation a write must still match.
///
/// This is the causal context on a PUT: the caller read the heading, then
/// writes only if nothing else closed or rewrote it.
#[derive(Debug, Default, Clone, Copy)]
pub struct UpdatePred<'a> {
    /// Refuse unless the heading is still this state.
    pub if_state: Option<&'a str>,
    /// Refuse unless the corpus generation is still this value.
    pub if_gen: Option<u64>,
}

/// [`update`] with a last-seen predicate.
///
/// # Errors
///
/// Same as [`update`], plus [`Error::StaleWrite`] when the predicate fails.
pub fn update_pred(
    layout: &Layout,
    id: &str,
    new_state: Option<&str>,
    new_priority: Option<char>,
    block_add: Option<&str>,
    block_clear: Option<&str>,
    pred: UpdatePred<'_>,
) -> Result<UpdateOutcome> {
    let identity = crate::config::identity(layout);
    update_as_pred(
        layout,
        id,
        new_state,
        new_priority,
        block_add,
        block_clear,
        &identity,
        pred,
    )
}

/// [`update`] with an explicit identity instead of [`crate::config::identity`].
///
/// # Errors
///
/// Returns an error if `id` is not in the corpus, the state or priority is
/// invalid, adding the blocker would cycle, or the file cannot be rewritten.
pub fn update_as(
    layout: &Layout,
    id: &str,
    new_state: Option<&str>,
    new_priority: Option<char>,
    block_add: Option<&str>,
    block_clear: Option<&str>,
    identity: &str,
) -> Result<UpdateOutcome> {
    update_as_pred(
        layout,
        id,
        new_state,
        new_priority,
        block_add,
        block_clear,
        identity,
        UpdatePred::default(),
    )
}

/// [`update_as`] with a last-seen predicate.
///
/// # Errors
///
/// Same as [`update_as`], plus [`Error::StaleWrite`] when the predicate fails.
#[allow(clippy::too_many_arguments)]
pub fn update_as_pred(
    layout: &Layout,
    id: &str,
    new_state: Option<&str>,
    new_priority: Option<char>,
    block_add: Option<&str>,
    block_clear: Option<&str>,
    identity: &str,
    pred: UpdatePred<'_>,
) -> Result<UpdateOutcome> {
    let (_h0, path, project) =
        find_by_id(layout, id)?.ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;

    let (transition, changed) = with_issues_lock(&path, || {
        // Read the graph inside the lock. Built before it, the check answers
        // for a corpus a peer may already have moved on from.
        let graph = if block_add.is_some() {
            Some(DependencyGraph::from_issues(&load_all(layout)?)?)
        } else {
            None
        };
        let mut doc = IssueDoc::parse_file(&project, &path)?;
        let spec = doc.priority_spec();
        let h = doc
            .headings
            .iter_mut()
            .find(|x| x.id == id)
            .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;

        let original = h.state.clone();
        let mut changed = Vec::new();

        if pred.if_state.is_some() || pred.if_gen.is_some() {
            let seen = crate::events::generation(layout);
            if let Some(want) = pred.if_state {
                if !TODO_KEYWORDS.contains(&want) {
                    return Err(
                        anyhow!("invalid --if-state {want:?}; allowed: {TODO_KEYWORDS:?}").into(),
                    );
                }
                if h.state != want {
                    return Err(Error::StaleWrite {
                        id: id.to_string(),
                        expected_state: Some(want.to_string()),
                        actual_state: h.state.clone(),
                        expected_gen: pred.if_gen,
                        actual_gen: Some(seen),
                    });
                }
            }
            if let Some(want_gen) = pred.if_gen
                && seen != want_gen
            {
                return Err(Error::StaleWrite {
                    id: id.to_string(),
                    expected_state: pred.if_state.map(str::to_string),
                    actual_state: h.state.clone(),
                    expected_gen: Some(want_gen),
                    actual_gen: Some(seen),
                });
            }
        }

        if let Some(s) = new_state {
            if !TODO_KEYWORDS.contains(&s) {
                return Err(anyhow!("invalid state {s:?}; allowed: {TODO_KEYWORDS:?}").into());
            }
            if h.state != s {
                if is_terminal(&h.state) && is_terminal(s) {
                    record_sibling_terminal(h, s);
                    changed.push(format!("sibling terminal {s} (held {})", h.state));
                } else {
                    let from = h.state.clone();
                    h.record_state_change(s);
                    changed.push(format!("state {from} -> {s}"));
                    for note in settle_claim(h, &from, s, identity) {
                        changed.push(note);
                    }
                }
            }
        }

        if let Some(p) = new_priority {
            if !spec.contains(p) {
                return Err(anyhow!(
                    "invalid priority {p:?}; file allows [#{}]..[#{}]",
                    spec.highest,
                    spec.lowest
                )
                .into());
            }
            if h.priority != p {
                h.priority = p;
                changed.push(format!("priority -> [#{p}]"));
            }
        }

        if let Some(blk) = block_add {
            let mut current = h.blocked_by();
            if !current.iter().any(|x| x == blk) {
                if let Some(graph) = &graph {
                    graph.accepts_edge(blk, id)?;
                }
                current.push(blk.to_string());
                crate::props::insert(
                    &mut h.properties,
                    crate::props::BLOCKED_BY,
                    current.join(" "),
                );
                if h.state == "TODO" || h.state == "STARTED" {
                    let from = h.state.clone();
                    h.record_state_change("BLOCKED");
                    changed.push(format!("state {from} -> BLOCKED (auto on block)"));
                }
                changed.push(format!("blocked_by += {blk}"));
            }
        }

        if let Some(blk) = block_clear {
            let mut current = h.blocked_by();
            let before = current.len();
            current.retain(|x| x != blk);
            if current.len() < before {
                if current.is_empty() {
                    crate::props::remove(&mut h.properties, crate::props::BLOCKED_BY);
                    if h.state == "BLOCKED" {
                        let from = h.state.clone();
                        h.record_state_change("TODO");
                        changed.push("state BLOCKED -> TODO (auto on unblock)".to_string());
                        for note in settle_claim(h, &from, "TODO", identity) {
                            changed.push(note);
                        }
                    }
                } else {
                    crate::props::insert(
                        &mut h.properties,
                        crate::props::BLOCKED_BY,
                        current.join(" "),
                    );
                }
                changed.push(format!("blocked_by -= {blk}"));
            }
        }

        if changed.is_empty() {
            return Ok((None, Vec::new()));
        }

        let final_state = h.state.clone();
        doc.write()?;
        let transition = (original != final_state).then_some((original, final_state));
        Ok((transition, changed))
    })?;

    if changed.is_empty() {
        return Ok(UpdateOutcome {
            report: format!("{id}: no change\n"),
            hints: Vec::new(),
        });
    }

    if let Some((from, to)) = &transition {
        let _ = crate::events::emit_state_change(layout, &project, id, from, to);
    }

    let mut hints = Vec::new();
    if matches!(
        transition.as_ref().map(|(_, to)| to.as_str()),
        Some("DONE") | Some("CANCELLED")
    ) {
        for (other_project, other) in load_all(layout)? {
            if !other.blocked_by().iter().any(|b| b == id) {
                continue;
            }
            if other.state == "DONE" || other.state == "CANCELLED" {
                continue;
            }
            hints.push(format!(
                "{} (in {}) lists this as a blocker; clear with `vissue update {} --unblock {}`",
                other.id, other_project, other.id, id
            ));
        }
    }
    Ok(UpdateOutcome {
        report: format!("{id}: {}\n", changed.join(", ")),
        hints,
    })
}

/// States that keep a claim: someone still holds the issue even when it is
/// waiting on something else. Leaving for TODO, DONE, or CANCELLED gives it up.
fn keeps_claim(state: &str) -> bool {
    matches!(state, "STARTED" | "BLOCKED")
}

fn is_terminal(state: &str) -> bool {
    matches!(state, "DONE" | "CANCELLED")
}

fn record_sibling_terminal(h: &mut IssueHeading, attempted: &str) {
    crate::props::insert(
        &mut h.properties,
        crate::props::SIBLING_TERMINAL,
        attempted.to_string(),
    );
}

/// Pick one terminal after a sibling close. Clears `:SIBLING_TERMINAL:`.
///
/// # Errors
///
/// Returns an error if `id` is missing, `state` is not DONE or CANCELLED, or
/// the file cannot be rewritten.
pub fn resolve_terminal(layout: &Layout, id: &str, state: &str) -> Result<String> {
    if !is_terminal(state) {
        return Err(anyhow!("resolve state must be DONE or CANCELLED, got {state:?}").into());
    }
    let identity = crate::config::identity(layout);
    let (_h0, path, project) =
        find_by_id(layout, id)?.ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
    let from = with_issues_lock(&path, || {
        let mut doc = IssueDoc::parse_file(&project, &path)?;
        let h = doc
            .headings
            .iter_mut()
            .find(|x| x.id == id)
            .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
        let from = h.state.clone();
        if from != state {
            h.record_state_change(state);
            settle_claim(h, &from, state, &identity);
        }
        crate::props::remove(&mut h.properties, crate::props::SIBLING_TERMINAL);
        doc.write()?;
        Ok(from)
    })?;
    if from != state {
        let _ = crate::events::emit_state_change(layout, &project, id, &from, state);
    }
    Ok(format!("resolved {id} -> {state}\n"))
}

/// Take or give up the claim as the state moves.
///
/// Entering STARTED unclaimed stamps the identity; leaving for a state that
/// holds no claim releases it, and the logbook keeps who held it and since
/// when.
fn settle_claim(h: &mut IssueHeading, from: &str, to: &str, identity: &str) -> Vec<String> {
    let mut notes = Vec::new();
    if to == "STARTED" && h.claimed_by().is_none() {
        h.set_claim(identity);
        notes.push(format!("claimed by {identity}"));
    } else if keeps_claim(from)
        && !keeps_claim(to)
        && let Some((who, _when)) = h.release_claim()
    {
        notes.push(format!("claim released ({who})"));
    }
    notes
}

/// Take an issue: move it to STARTED and stamp the claim.
///
/// A claim held by another identity is refused unless `force`, which records
/// the takeover in the logbook rather than losing it.
///
/// # Errors
///
/// Returns an error if `id` is not in the corpus, the issue is DONE or
/// CANCELLED, another identity holds it and `force` is false, or the file
/// cannot be rewritten.
pub fn claim(layout: &Layout, id: &str, force: bool) -> Result<String> {
    let identity = crate::config::identity(layout);
    claim_as(layout, id, force, &identity)
}

/// [`claim`] with an explicit identity instead of [`crate::config::identity`].
///
/// # Errors
///
/// Returns an error if `id` is not in the corpus, the issue is DONE or
/// CANCELLED, another identity holds it and `force` is false, or the file
/// cannot be rewritten.
pub fn claim_as(layout: &Layout, id: &str, force: bool, identity: &str) -> Result<String> {
    let (_h0, path, project) =
        find_by_id(layout, id)?.ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;

    let report = with_issues_lock(&path, || {
        let mut doc = IssueDoc::parse_file(&project, &path)?;
        let h = doc
            .headings
            .iter_mut()
            .find(|x| x.id == id)
            .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;

        if h.state == "DONE" || h.state == "CANCELLED" {
            return Err(Error::InvalidState {
                id: id.to_string(),
                state: h.state.clone(),
            });
        }
        if let Some(holder) = h.claimed_by() {
            if holder != identity && !force {
                return Err(Error::ClaimConflict {
                    id: id.to_string(),
                    holder: holder.to_string(),
                    claimed_at: h.claimed_at().map(str::to_string),
                });
            }
            if holder != identity {
                let previous = holder.to_string();
                let from = h.state.clone();
                h.release_claim();
                h.set_claim(identity);
                h.record_state_change("STARTED");
                doc.write()?;
                if from != "STARTED" {
                    let _ =
                        crate::events::emit_state_change(layout, &project, id, &from, "STARTED");
                }
                return Ok(format!("claimed {id} (taken over from {previous})\n"));
            }
        }

        let was = h.state.clone();
        h.record_state_change("STARTED");
        if h.claimed_by().is_none() {
            h.set_claim(identity);
        }
        // Read off the heading before the write releases the borrow on it.
        let standing = standing_on(h);
        doc.write()?;
        if was != "STARTED" {
            let _ = crate::events::emit_state_change(layout, &project, id, &was, "STARTED");
        }
        let mut out = if was == "STARTED" {
            format!("claimed {id} by {identity}\n")
        } else {
            format!("claimed {id} by {identity} ({was} -> STARTED)\n")
        };
        out.push_str(&standing);
        Ok(out)
    })?;
    Ok(report)
}

/// The line a claim adds when the issue has declared inputs.
///
/// A claim is where an agent starts working, and the working set is the next
/// thing it needs. Off the heading in hand rather than a corpus walk, so taking
/// a node costs no more than it did; `recall` does the walk when asked.
fn standing_on(h: &IssueHeading) -> String {
    let blockers = h.blocked_by().len();
    let bounced = crate::props::get(&h.properties, crate::props::DISCOVERED_FROM).is_some();
    if blockers == 0 && !bounced && h.parent().is_none() {
        return String::new();
    }
    let mut parts: Vec<String> = Vec::new();
    if blockers > 0 {
        parts.push(format!(
            "{blockers} declared input{}",
            if blockers == 1 { "" } else { "s" }
        ));
    }
    if bounced {
        parts.push("an origin it was bounced from".to_string());
    }
    if h.parent().is_some() {
        parts.push("a plan above it".to_string());
    }
    format!("  `recall {}` for {}\n", h.id, parts.join(", "))
}

/// What an update changed, plus advice about issues left dangling by it.
#[derive(Debug, Clone)]
pub struct UpdateOutcome {
    /// One-line change summary, or `{id}: no change`.
    pub report: String,
    /// Issues that still list this one as a blocker after it closed.
    pub hints: Vec<String>,
}

/// Add a dated note to the top of an issue's logbook. State, claim, and
/// properties stay untouched, so an agent can record progress without owning
/// the issue.
///
/// # Errors
///
/// Returns an error if `text` is empty, `id` is not in the corpus, or the
/// file cannot be rewritten.
pub fn note(layout: &Layout, id: &str, text: &str) -> Result<String> {
    // One line in the drawer: fold internal whitespace, and swap double
    // quotes for singles so the rendered `- Note: "..."` line re-parses.
    let text = text
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .replace('"', "'");
    if text.is_empty() {
        return Err(anyhow!("note text is empty").into());
    }
    let (_h0, path, project) =
        find_by_id(layout, id)?.ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
    with_issues_lock(&path, || {
        let mut doc = IssueDoc::parse_file(&project, &path)?;
        let h = doc
            .headings
            .iter_mut()
            .find(|x| x.id == id)
            .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
        // Newest first, matching state transitions and claim releases. A
        // drawer written from both ends reads as sorted by neither.
        h.logbook.insert(
            0,
            LogEntry {
                timestamp: LogEntry::now(),
                from_state: None,
                to_state: None,
                note: Some(text.clone()),
                raw: None,
            },
        );
        doc.write()?;
        Ok(format!("{id}: noted\n"))
    })
}

/// Append prose to an issue's body, stamped with the date and identity.
///
/// The logbook holds one line per event, so a written report does not fit in
/// it: [`note`] folds its text to a single line by design. Work that has been
/// done and needs recording belongs under the heading as prose, which is
/// where a reader looks for what the issue is about.
///
/// The text is kept as given. Lines that would end the issue are indented on
/// the way out, so markdown is safe to append.
///
/// # Errors
///
/// Returns an error if `text` is empty, `id` is not in the corpus, or the
/// file cannot be rewritten.
pub fn append_body(layout: &Layout, id: &str, text: &str) -> Result<String> {
    append_body_as(layout, id, text, &crate::config::identity(layout))
}

/// [`append_body`] with the recorded identity passed in.
///
/// # Errors
///
/// Returns an error if `text` is empty, `id` is not in the corpus, or the
/// file cannot be rewritten.
pub fn append_body_as(layout: &Layout, id: &str, text: &str, identity: &str) -> Result<String> {
    let text = text.trim_end();
    if text.trim().is_empty() {
        return Err(anyhow!("append text is empty").into());
    }
    let (_h0, path, project) =
        find_by_id(layout, id)?.ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
    with_issues_lock(&path, || {
        let mut doc = IssueDoc::parse_file(&project, &path)?;
        let h = doc
            .headings
            .iter_mut()
            .find(|x| x.id == id)
            .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
        let stamp = format!("{} {identity}", today_inactive_bracket());
        if !h.body.trim().is_empty() {
            h.body = h.body.trim_end().to_string();
            h.body.push_str("\n\n");
        } else {
            h.body.clear();
        }
        h.body.push_str(&stamp);
        h.body.push('\n');
        h.body.push_str(text);
        h.body.push('\n');
        doc.write()?;
        let lines = text.lines().count();
        Ok(format!("{id}: appended {lines} line(s)\n"))
    })
}

/// Name of the drawer votes live in.
const VOTES_DRAWER: &str = "VOTES";

/// One agent's ballot on one issue.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ballot {
    /// Identity that cast it, as [`crate::config::identity`] reports.
    pub agent: String,
    /// What was voted for, verbatim.
    pub choice: String,
    /// Inactive org date the vote was cast or last changed.
    pub stamp: String,
}

/// Cast or change one agent's vote, or read the tally when `choice` is `None`.
///
/// Consensus among several agents is not the same question as what one agent
/// concluded, and the tracker had no way to hold the difference: an agent could
/// append prose saying what it thought, and a reader had to read every append
/// and count by hand.
///
/// One ballot per identity, and casting again replaces it. That is last write
/// wins *per agent*, which is the right rule here and is not the bug the id
/// reservation had: an agent changing its mind should not leave two ballots, and
/// two different agents must never overwrite each other. The first is why a
/// recast replaces, the second is why the whole read-modify-write runs under the
/// file lock.
///
/// Stored as a `:VOTES:` drawer on the heading rather than in the event log,
/// because a tally a person can read in the file is worth more than one that
/// needs a scan, and drawers already survive a rewrite untouched.
///
/// # Errors
///
/// Returns an error if `id` is not in the corpus, `choice` is blank, or the file
/// cannot be rewritten.
pub fn vote(layout: &Layout, id: &str, choice: Option<&str>, identity: &str) -> Result<String> {
    let (_h, path, project) =
        find_by_id(layout, id)?.ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
    let Some(choice) = choice else {
        let doc = IssueDoc::parse_file(&project, &path)?;
        let h = doc
            .headings
            .iter()
            .find(|x| x.id == id)
            .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
        let (ballots, _) = read_ballots(h);
        return Ok(tally_text(id, &ballots));
    };
    let choice = choice.trim();
    if choice.is_empty() {
        return Err(anyhow!("vote needs something to vote for").into());
    }
    if choice.contains('\n') {
        return Err(anyhow!("a vote is one line").into());
    }
    // A ballot line is `[date] agent: choice` and the choice may hold ": ", which
    // is the point, so the split takes the first one. An identity holding ": "
    // would be read back as a shorter name with the rest of itself prepended to
    // the choice: the ballot filed under the wrong agent, and nothing saying so.
    // Refused rather than mangled, and the message says what to change, because
    // an identity is configuration.
    if identity.contains(": ") {
        return Err(anyhow!(
            "the identity {identity:?} contains a colon and a space, which a ballot line \
             cannot hold unambiguously; set VISSUE_AGENT or `agent` in the config to a \
             name without one"
        )
        .into());
    }
    if identity.trim().is_empty() {
        return Err(anyhow!("a ballot needs an identity to file it under").into());
    }
    with_issues_lock(&path, || {
        let mut doc = IssueDoc::parse_file(&project, &path)?;
        let h = doc
            .headings
            .iter_mut()
            .find(|x| x.id == id)
            .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
        let (mut ballots, foreign) = read_ballots(h);
        let stamp = today_inactive_bracket();
        let previous = ballots.iter().position(|b| b.agent == identity);
        let changed_from = previous.map(|i| ballots[i].choice.clone());
        let ballot = Ballot {
            agent: identity.to_string(),
            choice: choice.to_string(),
            stamp,
        };
        match previous {
            Some(i) => ballots[i] = ballot,
            None => ballots.push(ballot),
        }
        write_ballots(h, &ballots, &foreign);
        doc.write()?;
        let mut out = match changed_from {
            Some(old) if old == choice => format!("{id}: {identity} already voted {choice}\n"),
            Some(old) => format!("{id}: {identity} changed {old} to {choice}\n"),
            None => format!("{id}: {identity} voted {choice}\n"),
        };
        out.push_str(&tally_text(id, &ballots));
        Ok(out)
    })
}

/// The ballots cast on one issue, in the order the drawer holds them.
///
/// Exposed because a tally is not the only question worth asking of them:
/// [`crate::consensus`] weighs the same ballots by who the group listens to.
///
/// # Errors
///
/// Returns an error if `id` is not in the corpus or the file cannot be read.
pub fn ballots(layout: &Layout, id: &str) -> Result<Vec<Ballot>> {
    let (h, _path, _project) =
        find_by_id(layout, id)?.ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
    Ok(read_ballots(&h).0)
}

/// Ballots on a heading, plus any line of the drawer this does not understand.
///
/// The foreign lines are carried rather than dropped. The drawer is org a person
/// can edit, and a rewrite keeping only what the parser recognised would eat a
/// comment somebody left there, silently, on the next vote.
fn read_ballots(h: &IssueHeading) -> (Vec<Ballot>, Vec<String>) {
    let Some(drawer) = h
        .extra_drawers
        .iter()
        .find(|d| drawer_name_is(d, VOTES_DRAWER))
    else {
        return (Vec::new(), Vec::new());
    };
    let mut ballots: Vec<Ballot> = Vec::new();
    let mut foreign: Vec<String> = Vec::new();
    for line in drawer.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        // The drawer's own delimiters are structure rather than content.
        if trimmed.eq_ignore_ascii_case(&format!(":{VOTES_DRAWER}:"))
            || trimmed.eq_ignore_ascii_case(":END:")
        {
            continue;
        }
        match parse_ballot(trimmed) {
            // One ballot per agent is the invariant the tally counts on, and a
            // hand-edited drawer can hold two lines for one name. Collapsed on
            // read, last line winning, so a duplicate cannot make one agent
            // count twice and the recast path cannot leave the older line
            // behind by replacing only the first.
            Some(b) => match ballots.iter_mut().find(|x| x.agent == b.agent) {
                Some(existing) => *existing = b,
                None => ballots.push(b),
            },
            None => foreign.push(trimmed.to_string()),
        }
    }
    (ballots, foreign)
}

/// `[date] agent: choice`. The choice may hold ": ", so the first one delimits
/// and the agent may not contain it; [`vote`] refuses an identity that does.
fn parse_ballot(line: &str) -> Option<Ballot> {
    let (stamp, rest) = line.strip_prefix('[')?.split_once("] ")?;
    let (agent, choice) = rest.split_once(": ")?;
    let agent = agent.trim();
    let choice = choice.trim();
    if agent.is_empty() || choice.is_empty() {
        return None;
    }
    Some(Ballot {
        agent: agent.to_string(),
        choice: choice.to_string(),
        stamp: format!("[{stamp}]"),
    })
}

fn drawer_name_is(drawer: &str, name: &str) -> bool {
    drawer
        .lines()
        .next()
        .map(str::trim)
        .and_then(|first| first.strip_prefix(':'))
        .and_then(|rest| rest.strip_suffix(':'))
        .is_some_and(|n| n.eq_ignore_ascii_case(name))
}

/// Replace the heading's votes drawer in place, dropping it when it would be empty.
///
/// In place, because `retain` then `push` moves the drawer past every other one on
/// the heading, so each vote would also reorder unrelated org.
fn write_ballots(h: &mut IssueHeading, ballots: &[Ballot], foreign: &[String]) {
    let at = h
        .extra_drawers
        .iter()
        .position(|d| drawer_name_is(d, VOTES_DRAWER));
    if ballots.is_empty() && foreign.is_empty() {
        if let Some(i) = at {
            h.extra_drawers.remove(i);
        }
        return;
    }
    let mut drawer = format!(":{VOTES_DRAWER}:\n");
    for b in ballots {
        drawer.push_str(&format!("{} {}: {}\n", b.stamp, b.agent, b.choice));
    }
    for line in foreign {
        drawer.push_str(line);
        drawer.push('\n');
    }
    drawer.push_str(":END:\n");
    match at {
        Some(i) => h.extra_drawers[i] = drawer,
        None => h.extra_drawers.push(drawer),
    }
}

/// The tally, and whether it is a consensus.
///
/// A plurality is reported as a plurality and not as agreement. Two agents for
/// one option and two for another is the case a tally exists to make visible, so
/// it says so rather than picking the first.
fn tally_text(id: &str, ballots: &[Ballot]) -> String {
    if ballots.is_empty() {
        return format!("{id}: no votes\n");
    }
    let mut counts: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for b in ballots {
        counts
            .entry(b.choice.as_str())
            .or_default()
            .push(b.agent.as_str());
    }
    let total = ballots.len();
    let mut rows: Vec<(&&str, &Vec<&str>)> = counts.iter().collect();
    rows.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then(a.0.cmp(b.0)));
    let mut out = format!(
        "{id}: {total} vote{} from {} option{}\n",
        if total == 1 { "" } else { "s" },
        counts.len(),
        if counts.len() == 1 { "" } else { "s" }
    );
    for (choice, who) in &rows {
        let _ = writeln!(out, "  {:<24} {} ({})", choice, who.len(), who.join(", "));
    }
    let top = rows[0].1.len();
    let tied = rows.iter().filter(|(_, who)| who.len() == top).count();
    if tied > 1 {
        let _ = writeln!(out, "  no consensus: {tied} options tied at {top}");
    } else if total < 2 {
        // One agent agreeing with itself is not a consensus, and calling it one
        // is how a single unreviewed opinion gets acted on as though it had been
        // checked. This is the whole failure the tally exists to prevent.
        let _ = writeln!(
            out,
            "  one ballot only: {}, which nobody has agreed with yet",
            rows[0].0
        );
    } else if top * 2 > total {
        let _ = writeln!(out, "  consensus: {} ({top} of {total})", rows[0].0);
    } else {
        let _ = writeln!(
            out,
            "  plurality only: {} ({top} of {total}), which is not a majority",
            rows[0].0
        );
    }
    out
}

/// Prefixes a deed accession can open with.
///
/// deedar mints `deed-<kind>-<slug>` and answers `get` for a `sha256:` of the
/// canonical deed or of one product path. Those two forms are the whole
/// vocabulary, so a value in neither is a title, a path, or a note that landed
/// in the wrong field, and storing it would leave a citation nothing resolves.
const DEED_PREFIXES: &[&str] = &["deed-", "sha256:"];

/// Whether `value` looks like something deedar can be asked for.
///
/// The shape rather than the store: vissue cites deeds and never opens one, so
/// this cannot ask whether the deed exists, only whether the id could name one.
#[must_use]
pub fn is_deed_accession(value: &str) -> bool {
    let value = value.trim();
    if value.contains(|c: char| c.is_whitespace() || c == ',') {
        return false;
    }
    DEED_PREFIXES.iter().any(|prefix| {
        value
            .strip_prefix(*prefix)
            .is_some_and(|rest| !rest.is_empty())
    })
}

/// Cite, drop, or list the deeds an issue's work produced.
///
/// A claim says who is working and a note says what happened; neither says what
/// the work *made*, so the next unit had to reread a transcript to find out. A
/// deed is deedar's name for the product, and the accession is the whole handoff:
/// `deedar get <id>` returns the frozen record, `deedar trail <id>` walks what it
/// was built from. The tracker stores the id and nothing else, because the deed
/// store owns the bytes and duplicating them here would give the corpus a second
/// copy to drift.
///
/// With neither `add` nor `remove`, this reads: the citations on the heading, in
/// the order they were cited.
///
/// # Errors
///
/// Returns an error if `id` is not in the corpus, an added value is not a deed
/// accession, or the file cannot be rewritten.
pub fn deed(layout: &Layout, id: &str, add: &[String], remove: &[String]) -> Result<String> {
    let (h, path, project) =
        find_by_id(layout, id)?.ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
    if add.is_empty() && remove.is_empty() {
        return Ok(deed_list_text(id, &h.deeds()));
    }
    for value in add {
        if !is_deed_accession(value) {
            return Err(anyhow!(
                "{value:?} is not a deed accession; deedar mints `deed-<kind>-<slug>` \
                 and answers `get` for a `sha256:` of the deed or of one product path"
            )
            .into());
        }
    }
    with_issues_lock(&path, || {
        let mut doc = IssueDoc::parse_file(&project, &path)?;
        let h = doc
            .headings
            .iter_mut()
            .find(|x| x.id == id)
            .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
        let mut cited = h.deeds();
        let mut changed: Vec<String> = Vec::new();
        for value in add {
            let value = value.trim();
            // Citing twice is what a retried step does, and a second copy of the
            // id would make `trail` walk the same deed twice for no reason.
            if cited.iter().any(|x| x == value) {
                continue;
            }
            cited.push(value.to_string());
            changed.push(format!("deeds += {value}"));
        }
        for value in remove {
            let value = value.trim();
            let before = cited.len();
            cited.retain(|x| x != value);
            if cited.len() != before {
                changed.push(format!("deeds -= {value}"));
            }
        }
        if changed.is_empty() {
            return Ok(format!("{id}: no change\n{}", deed_list_text(id, &cited)));
        }
        if cited.is_empty() {
            crate::props::remove(&mut h.properties, crate::props::DEEDS);
        } else {
            crate::props::insert(&mut h.properties, crate::props::DEEDS, cited.join(" "));
        }
        doc.write()?;
        Ok(format!(
            "{id}: {}\n{}",
            changed.join(", "),
            deed_list_text(id, &cited)
        ))
    })
}

/// The citations on one heading, one per line.
fn deed_list_text(id: &str, cited: &[String]) -> String {
    if cited.is_empty() {
        return format!("{id}: no deeds cited\n");
    }
    let mut out = format!(
        "{id}: {} deed{}\n",
        cited.len(),
        if cited.len() == 1 { "" } else { "s" }
    );
    for value in cited {
        let _ = writeln!(out, "  {value}");
    }
    out
}

/// Fold an inbox-convention org file into tracked issues.
///
/// Each top-level `* TODO <title>` heading that does not already carry a
/// `:VISSUE_ID:` line becomes an issue in `project` (body = the heading's
/// text up to the next heading). The heading is then flipped to DONE and
/// stamped with the assigned id in place, so a second run is a no-op:
/// stamped headings are skipped, and folding is idempotent.
///
/// # Errors
///
/// Returns an error if the inbox cannot be read or written, `project` cannot
/// be resolved, or creating a folded issue fails. Headings already stamped
/// before a failure stay stamped.
pub fn fold(layout: &Layout, inbox: &std::path::Path, project: &str) -> Result<String> {
    let project = resolve_existing_project_case(layout, project)?;
    let text = std::fs::read_to_string(inbox)
        .with_context(|| format!("read inbox {}", inbox.display()))?;
    let lines: Vec<String> = text.lines().map(str::to_string).collect();

    struct Entry {
        line: usize,
        title: String,
        body: String,
        stamped: bool,
    }
    let mut entries: Vec<Entry> = Vec::new();
    let mut i = 0;
    let mut nest = crate::org::OrgScan::new();
    while i < lines.len() {
        if nest.observe(&lines[i]) {
            i += 1;
            continue;
        }
        if let Some(title) = lines[i].strip_prefix("* TODO ") {
            let start = i + 1;
            let mut end_nest = crate::org::OrgScan::new();
            let end = {
                let mut j = start;
                while j < lines.len() {
                    if !end_nest.observe(&lines[j]) && lines[j].starts_with("* ") {
                        break;
                    }
                    j += 1;
                }
                j
            };
            let stamped = lines[start..end]
                .iter()
                .any(|l| l.trim_start().starts_with(":VISSUE_ID:"));
            let body = lines[start..end].join("\n").trim().to_string();
            entries.push(Entry {
                line: i,
                title: title.trim().to_string(),
                body,
                stamped,
            });
            i = end;
        } else {
            i += 1;
        }
    }

    // Stamping inserts lines, so rewrite from the bottom up to keep the
    // recorded line numbers valid.
    let mut out = lines.clone();
    let mut created: Vec<String> = Vec::new();
    let mut failure = None;
    for e in entries.iter().rev() {
        if e.stamped {
            continue;
        }
        let printed = create(
            layout,
            &project,
            &e.title,
            CreateOpts {
                quiet: true,
                body: if e.body.is_empty() {
                    None
                } else {
                    Some(&e.body)
                },
                ..CreateOpts::default()
            },
        );
        let id = match printed {
            Ok(printed) => printed.trim().to_string(),
            Err(e) => {
                // Stop, but stamp what already exists below. Returning here
                // with the inbox untouched would leave every issue created so
                // far unstamped, and the next run would create them again.
                failure = Some(e);
                break;
            }
        };
        out[e.line] = format!("* DONE {}", e.title);
        out.insert(e.line + 1, format!(":VISSUE_ID: {id}"));
        created.push(id);
    }
    created.reverse();

    if !created.is_empty() {
        let mut rendered = out.join("\n");
        if text.ends_with('\n') {
            rendered.push('\n');
        }
        std::fs::write(inbox, rendered)
            .with_context(|| format!("write inbox {}", inbox.display()))?;
    }
    if let Some(error) = failure {
        return Err(crate::error::Error::Other(
            anyhow::Error::from(error).context(format!(
                "folded {} before failing: {}",
                created.len(),
                created.join(" ")
            )),
        ));
    }
    if created.is_empty() {
        return Ok("folded 0 (nothing unstamped)\n".into());
    }
    Ok(format!("folded {}: {}\n", created.len(), created.join(" ")))
}

/// Move one issue's heading to another project's file. The id is not
/// regenerated, so cross-project blocker edges keep resolving.
///
/// # Errors
///
/// Returns an error if `id` is not in the corpus, `to_project` cannot be
/// resolved, or either file cannot be locked or rewritten.
pub fn refile(layout: &Layout, id: &str, to_project: &str) -> Result<String> {
    refile_to(layout, id, layout, to_project)
}

/// Move one issue's heading onto a destination that may live on another
/// tracker layout. A router resolves the destination project name before
/// calling this, so a routed name lands on its own checkout instead of
/// growing a shadow directory under the source root.
///
/// # Errors
///
/// Same as [`refile`].
pub fn refile_to(
    layout: &Layout,
    id: &str,
    dst_layout: &Layout,
    to_project: &str,
) -> Result<String> {
    let to_project = resolve_existing_project_case(dst_layout, to_project)?;
    let target_path = dst_layout.project_issues_path(&to_project);
    let (_heading, src_path, src_project) =
        find_by_id(layout, id)?.ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
    if src_path == target_path {
        return Ok(format!("{id} already in {to_project}; nothing to do\n"));
    }
    with_issues_locks(&[&src_path, &target_path], || {
        let mut src_doc = IssueDoc::parse_file(&src_project, &src_path)?;
        let heading = src_doc
            .remove(id)
            .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;

        // Two files cannot be replaced in one atomic step, so choose which
        // half-finished state a failure leaves behind. Writing the target
        // first means a failed source write duplicates the id, which `check`
        // reports and a person can resolve; the other order deletes the issue
        // with nothing left naming it.
        let mut tgt_doc = IssueDoc::parse_file(&to_project, &target_path)?;
        tgt_doc.upsert(heading);
        tgt_doc.write()?;
        src_doc.write()?;
        Ok(())
    })?;
    Ok(format!("{id}: {src_project} -> {to_project}\n"))
}

/// Optional fields on [`reject`].
#[derive(Debug, Default, Clone, Copy)]
pub struct RejectOpts<'a> {
    /// Existing destination id. When set, that heading is the successor.
    pub to: Option<&'a str>,
    /// Project to create the destination in when [`Self::to`] is absent.
    pub project: Option<&'a str>,
    /// Title of a created destination. The source title is used when omitted.
    pub title: Option<&'a str>,
    /// Prose appended to the cancelled source.
    pub reason: Option<&'a str>,
    /// Tracker that holds the destination. `None` keeps the source's.
    pub dst_layout: Option<&'a Layout>,
    /// Twin files read under the lock when minting a successor, so a twin on
    /// another layout cannot share a suffix with it. Paths and not ids, because
    /// ids the caller read before the lock can be stale by the time it is held.
    pub dst_extra_id_paths: &'a [PathBuf],
}

/// Cancel `src` and point it at a successor in one graph edit.
///
/// Writes `src` to CANCELLED, sets `:PIVOTED_TO:` to the destination, and
/// settles any claim on `src`. A created destination, or an existing one
/// whose `:DISCOVERED_FROM:` is empty, records `src` as its origin. A
/// non-empty `:DISCOVERED_FROM:` is left alone.
///
/// # Errors
///
/// Returns an error if `src` is not in the corpus, `--to` names no heading,
/// neither a destination nor a create project is given, or a file cannot be
/// rewritten.
pub fn reject(layout: &Layout, src: &str, opts: RejectOpts<'_>) -> Result<String> {
    let identity = crate::config::identity(layout);
    let (src0, src_path, src_project) =
        find_by_id(layout, src)?.ok_or_else(|| Error::IssueNotFound {
            id: src.to_string(),
        })?;

    let dst_layout = opts.dst_layout.unwrap_or(layout);
    let existing_dst = if let Some(to) = opts.to {
        if to == src {
            return Err(anyhow!("reject destination cannot be the source {src}").into());
        }
        Some(
            find_by_id(dst_layout, to)?
                .ok_or_else(|| Error::IssueNotFound { id: to.to_string() })?,
        )
    } else {
        None
    };

    let creating = existing_dst.is_none();
    if creating && opts.project.is_none() {
        return Err(anyhow!("reject needs --to DST or --project to create a successor").into());
    }

    let dst_project = if let Some((_, _, ref project)) = existing_dst {
        project.clone()
    } else {
        resolve_existing_project_case(dst_layout, opts.project.unwrap_or(&src_project))?
    };
    let dst_path = dst_layout.project_issues_path(&dst_project);
    let dst_title = opts.title.unwrap_or(src0.title.as_str());
    let cfg = VissueConfig::load(layout)?;

    // The twins the mint consults are locked too, or the reservation is read
    // outside the lock that guards the write and a peer can mint the same id.
    let mut lock_paths: Vec<PathBuf> = vec![src_path.clone(), dst_path.clone()];
    lock_paths.extend(opts.dst_extra_id_paths.iter().cloned());
    let lock_refs: Vec<&Path> = lock_paths.iter().map(PathBuf::as_path).collect();
    let (dst_id, old_state, new_state) = with_issues_locks(&lock_refs, || {
        if src_path == dst_path {
            let mut doc = IssueDoc::parse_file(&src_project, &src_path)?;
            let dst_id = if creating {
                push_successor(
                    &mut doc,
                    &dst_project,
                    dst_title,
                    src,
                    &cfg,
                    opts.dst_extra_id_paths,
                )?
            } else {
                let to = reject_to(opts)?;
                set_discovered_from_if_empty(&mut doc, to, src)?;
                to.to_string()
            };
            let (old_state, new_state) =
                cancel_and_pivot(&mut doc, src, &dst_id, opts.reason, &identity)?;
            doc.write()?;
            Ok((dst_id, old_state, new_state))
        } else {
            let mut src_doc = IssueDoc::parse_file(&src_project, &src_path)?;
            let mut dst_doc = IssueDoc::parse_file(&dst_project, &dst_path)?;
            let dst_id = if creating {
                push_successor(
                    &mut dst_doc,
                    &dst_project,
                    dst_title,
                    src,
                    &cfg,
                    opts.dst_extra_id_paths,
                )?
            } else {
                let to = reject_to(opts)?;
                set_discovered_from_if_empty(&mut dst_doc, to, src)?;
                to.to_string()
            };
            let (old_state, new_state) =
                cancel_and_pivot(&mut src_doc, src, &dst_id, opts.reason, &identity)?;
            dst_doc.write()?;
            src_doc.write()?;
            Ok((dst_id, old_state, new_state))
        }
    })?;

    if old_state != new_state {
        let _ = crate::events::emit_state_change(layout, &src_project, src, &old_state, &new_state);
    }
    Ok(format!("rejected {src} -> {dst_id}\n"))
}

fn reject_to(opts: RejectOpts<'_>) -> Result<&str> {
    opts.to
        .ok_or_else(|| anyhow!("reject destination missing after --to was required").into())
}

fn push_successor(
    doc: &mut IssueDoc,
    project: &str,
    title: &str,
    src: &str,
    cfg: &VissueConfig,
    extra_id_paths: &[PathBuf],
) -> Result<String> {
    let mut taken = doc.known_ids();
    // Read here rather than by the caller, because here is inside the lock set.
    for twin in extra_id_paths {
        if twin == &doc.path {
            continue;
        }
        if let Ok(other) = IssueDoc::parse_file(project, twin) {
            taken.extend(other.known_ids());
        }
    }
    let id = generate_id(project, title, &taken, cfg.issues.id_length)?;
    let mut props = BTreeMap::new();
    props.insert("ID".into(), id.clone());
    props.insert("CREATED".into(), today_inactive_bracket());
    crate::props::insert(&mut props, crate::props::DISCOVERED_FROM, src.to_string());
    doc.headings.push(IssueHeading {
        id: id.clone(),
        title: title.to_string(),
        state: "TODO".into(),
        priority: doc.default_create_priority(cfg.issues.default_priority),
        properties: props,
        org_tags: Vec::new(),
        statistics: None,
        property_order: Vec::new(),
        extra_drawers: Vec::new(),
        body: String::new(),
        logbook: Vec::new(),
        line_start: 0,
        line_end: 0,
    });
    Ok(id)
}

fn set_discovered_from_if_empty(doc: &mut IssueDoc, id: &str, src: &str) -> Result<()> {
    let h = doc
        .headings
        .iter_mut()
        .find(|h| h.id == id)
        .ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
    let empty = crate::props::get(&h.properties, crate::props::DISCOVERED_FROM)
        .is_none_or(|s| s.trim().is_empty());
    if empty {
        crate::props::insert(
            &mut h.properties,
            crate::props::DISCOVERED_FROM,
            src.to_string(),
        );
    }
    Ok(())
}

fn cancel_and_pivot(
    doc: &mut IssueDoc,
    src: &str,
    dst: &str,
    reason: Option<&str>,
    identity: &str,
) -> Result<(String, String)> {
    let h = doc
        .headings
        .iter_mut()
        .find(|h| h.id == src)
        .ok_or_else(|| Error::IssueNotFound {
            id: src.to_string(),
        })?;
    let old_state = h.state.clone();
    if is_terminal(&old_state) && old_state != "CANCELLED" {
        record_sibling_terminal(h, "CANCELLED");
    } else if old_state != "CANCELLED" {
        h.record_state_change("CANCELLED");
        settle_claim(h, &old_state, "CANCELLED", identity);
    }
    crate::props::insert(&mut h.properties, crate::props::PIVOTED_TO, dst.to_string());
    if let Some(reason) = reason {
        append_reason(h, reason, identity);
    }
    Ok((old_state, h.state.clone()))
}

fn append_reason(h: &mut IssueHeading, text: &str, identity: &str) {
    let text = text.trim_end();
    if text.trim().is_empty() {
        return;
    }
    let stamp = format!("{} {identity}", today_inactive_bracket());
    if !h.body.trim().is_empty() {
        h.body = h.body.trim_end().to_string();
        h.body.push_str("\n\n");
    } else {
        h.body.clear();
    }
    h.body.push_str(&stamp);
    h.body.push('\n');
    h.body.push_str(text);
    h.body.push('\n');
}

/// First `[[id:XXX]]` (optionally `[[id:XXX][label]]`) whose id is in `known`.
fn first_existing_id_link(body: &str, known: &std::collections::HashSet<String>) -> Option<String> {
    let mut rest = body;
    while let Some(start) = rest.find("[[") {
        let after_start = &rest[start + 2..];
        let end = after_start.find("]]")?;
        let raw = &after_start[..end];
        let target = raw.split_once("][").map_or(raw, |(target, _)| target);
        let target = target.trim();
        if let Some(id) = target.strip_prefix("id:") {
            let id = id.trim();
            if known.contains(id) {
                return Some(id.to_string());
            }
        }
        rest = &after_start[end + 2..];
    }
    None
}

/// Rewrite project files onto the Org / ELPA / vissue property split.
///
/// Folds typos (`BLOCKEDBY`, drawer `TAGS`) and a bare `:BLOCKER:` id
/// list into `:BLOCKED_BY:`. A real org-edna condition stays. Puts legal
/// types on the heading and inserts a missing `#+CATEGORY:`. Does not
/// mint `:BLOCKER: ids(...)`.
///
/// # Errors
///
/// Returns an error if a project file cannot be read or rewritten.
pub fn normalize(layout: &Layout, project: Option<&str>, dry_run: bool) -> Result<String> {
    let projects = match project {
        Some(name) => vec![resolve_existing_project_case(layout, name)?],
        None => crate::store::list_projects(layout)?,
    };
    let mut out = String::new();
    let mut files = 0usize;
    let mut headings = 0usize;
    let mut changed = 0usize;
    for project in projects {
        let path = layout.project_issues_path(&project);
        if !path.exists() {
            continue;
        }
        files += 1;
        let before =
            std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
        let report = with_issues_lock(&path, || {
            let mut doc = IssueDoc::parse_file(&project, &path)?;
            let mut moved = 0usize;
            for h in &mut doc.headings {
                moved += crate::props::settle(&mut h.org_tags, &mut h.properties);
            }
            let after = doc.render_string();
            if after != before {
                if !dry_run {
                    doc.write()?;
                }
                Ok(Some((moved, after.len())))
            } else {
                Ok(None)
            }
        })?;
        headings += IssueDoc::parse(&project, path.clone(), &before)
            .map(|d| d.headings.len())
            .unwrap_or(0);
        if let Some((moved, _)) = report {
            changed += 1;
            let verb = if dry_run { "would rewrite" } else { "rewrote" };
            writeln!(out, "{verb} {project} ({moved} key move(s))")?;
        }
    }
    let mode = if dry_run { "dry-run" } else { "wrote" };
    writeln!(
        out,
        "normalize {mode}: {changed}/{files} file(s) changed, {headings} heading(s) scanned"
    )?;
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::DEFAULT_PREFIX;
    use std::fs;
    use std::path::Path;

    fn fresh_layout(dir: &Path) -> Layout {
        fs::create_dir_all(dir.join(DEFAULT_PREFIX)).unwrap();
        Layout::new(dir, DEFAULT_PREFIX)
    }

    fn issue_at(layout: &Layout, project: &str, id: &str) -> IssueHeading {
        IssueDoc::parse_file(project, &layout.project_issues_path(project))
            .unwrap()
            .headings
            .into_iter()
            .find(|h| h.id == id)
            .expect("issue not found")
    }

    fn only_id(layout: &Layout, project: &str) -> String {
        IssueDoc::parse_file(project, &layout.project_issues_path(project))
            .unwrap()
            .headings[0]
            .id
            .clone()
    }

    /// A claim is where an agent starts working, so it is where the working set
    /// has to be findable from. A verb nothing points at is a verb nobody runs.
    #[test]
    fn a_claim_points_at_the_working_set_when_there_is_one() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "the groundwork", CreateOpts::default()).unwrap();
        let first = only_id(&layout, "sample");
        create(&layout, "sample", "the next step", CreateOpts::default()).unwrap();
        let second = IssueDoc::parse_file("sample", &layout.project_issues_path("sample"))
            .unwrap()
            .headings
            .into_iter()
            .find(|h| h.id != first)
            .unwrap()
            .id;
        update(&layout, &second, None, None, Some(&first), None).unwrap();

        let claimed = claim_as(&layout, &second, false, "impl").unwrap();
        assert!(
            claimed.contains(&format!("`recall {second}`")),
            "the claim has to say where the working set is: {claimed}"
        );
        assert!(claimed.contains("1 declared input"), "{claimed}");

        // A node that stands on nothing gets no line, because there is nothing
        // for recall to hand over and a pointer to an empty answer is noise.
        let alone = claim_as(&layout, &first, false, "impl").unwrap();
        assert!(!alone.contains("recall"), "{alone}");
    }

    /// The citation is the handoff, so it has to survive the round trip through
    /// the file rather than living in the process that wrote it.
    #[test]
    fn a_cited_deed_is_readable_back_off_the_heading() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "name the note", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        let out = deed(&layout, &id, &["deed-patch-note".to_string()], &[]).unwrap();
        assert!(out.contains("deeds += deed-patch-note"), "{out}");
        assert_eq!(
            issue_at(&layout, "sample", &id).deeds(),
            vec!["deed-patch-note".to_string()]
        );
    }

    /// Two citations, and the order they were cited in is the order they read
    /// back: a trail is walked from the first product to the last.
    #[test]
    fn citations_keep_the_order_they_were_added_in() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "two products", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        deed(&layout, &id, &["deed-file-note".to_string()], &[]).unwrap();
        deed(&layout, &id, &["deed-patch-note".to_string()], &[]).unwrap();
        assert_eq!(
            issue_at(&layout, "sample", &id).deeds(),
            vec!["deed-file-note".to_string(), "deed-patch-note".to_string()]
        );
    }

    /// A retried step cites the same deed twice. Two copies would make a trail
    /// walk one deed twice and say nothing by doing it.
    #[test]
    fn citing_the_same_deed_twice_leaves_one_citation() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "retried", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        deed(&layout, &id, &["deed-file-note".to_string()], &[]).unwrap();
        let again = deed(&layout, &id, &["deed-file-note".to_string()], &[]).unwrap();
        assert!(again.contains("no change"), "{again}");
        assert_eq!(issue_at(&layout, "sample", &id).deeds().len(), 1);
    }

    /// Dropping the last citation drops the property rather than leaving an
    /// empty one, which `normalize` would otherwise have to clean up.
    #[test]
    fn removing_the_last_citation_removes_the_property() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "mistaken", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        deed(&layout, &id, &["deed-file-oops".to_string()], &[]).unwrap();
        deed(&layout, &id, &[], &["deed-file-oops".to_string()]).unwrap();
        let h = issue_at(&layout, "sample", &id);
        assert!(h.deeds().is_empty());
        assert!(
            !h.properties.contains_key(crate::props::DEEDS),
            "an empty citation list is not a citation list: {:?}",
            h.properties
        );
    }

    /// A path, a title, or a sentence in this field is a citation that resolves
    /// to nothing, and the failure would only show up in whatever tried to open
    /// it much later.
    #[test]
    fn a_value_deedar_could_not_be_asked_for_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "bad citation", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        let err = deed(&layout, &id, &["/tmp/note.md".to_string()], &[]).unwrap_err();
        assert!(err.to_string().contains("not a deed accession"), "{err}");
        assert!(
            issue_at(&layout, "sample", &id).deeds().is_empty(),
            "a refused citation must not land"
        );
    }

    /// Both accession forms deedar answers `get` for.
    #[test]
    fn both_deed_forms_are_accessions() {
        assert!(is_deed_accession("deed-quote-rfc2094-nll"));
        assert!(is_deed_accession(
            "sha256:0e1f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f7"
        ));
        assert!(!is_deed_accession("deed-"), "a prefix alone names nothing");
        assert!(
            !is_deed_accession("sha256:"),
            "a prefix alone names nothing"
        );
        assert!(!is_deed_accession(""));
        // Whitespace and commas separate the list, so a value holding one would
        // read back as two citations neither of which was cited.
        assert!(!is_deed_accession("deed-file a"));
        assert!(!is_deed_accession("deed-file,a"));
    }

    /// Reading is a read: `deed` with nothing to add or drop must not rewrite.
    #[test]
    fn listing_citations_does_not_touch_the_file() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "read only", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        deed(&layout, &id, &["deed-file-note".to_string()], &[]).unwrap();

        let path = layout.project_issues_path("sample");
        let before = fs::read_to_string(&path).unwrap();
        let out = deed(&layout, &id, &[], &[]).unwrap();
        assert!(out.contains("deed-file-note"), "{out}");
        assert_eq!(before, fs::read_to_string(&path).unwrap());
    }

    #[test]
    fn create_rejects_a_parent_that_does_not_exist() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        let err = create(
            &layout,
            "sample",
            "child without parent",
            CreateOpts {
                parent: Some("sample-zzz9"),
                ..Default::default()
            },
        )
        .unwrap_err();
        assert!(err.to_string().contains("does not refer to any known id"));
    }

    #[test]
    fn create_accepts_a_parent_defined_in_a_design_document() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        let parent_id = "sample-spec-20260615";
        let project_dir = layout.projects_dir().join("sample");
        fs::create_dir_all(&project_dir).unwrap();
        fs::write(
            project_dir.join("design.org"),
            format!("#+TITLE: sample design\n\n* Design\n:PROPERTIES:\n:ID:         {parent_id}\n:END:\n"),
        )
        .unwrap();

        create(
            &layout,
            "sample",
            "child under design",
            CreateOpts {
                parent: Some(parent_id),
                ..Default::default()
            },
        )
        .unwrap();
        assert!(only_id(&layout, "sample").starts_with("sample-"));
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        assert_eq!(doc.headings[0].parent(), Some(parent_id));
    }

    #[test]
    fn a_state_update_writes_a_logbook_entry() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "first", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        update(&layout, &id, Some("STARTED"), None, None, None).unwrap();
        let h = issue_at(&layout, "sample", &id);
        assert_eq!(h.state, "STARTED");
        assert_eq!(h.logbook[0].from_state.as_deref(), Some("TODO"));
        assert_eq!(h.logbook[0].to_state.as_deref(), Some("STARTED"));
    }

    #[test]
    fn blocking_and_unblocking_drive_the_state() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "first", CreateOpts::default()).unwrap();
        create(&layout, "sample", "blocker", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let first = doc.headings[0].id.clone();
        let blocker = doc.headings[1].id.clone();

        update(&layout, &first, None, None, Some(&blocker), None).unwrap();
        let h = issue_at(&layout, "sample", &first);
        assert_eq!(h.state, "BLOCKED");
        assert!(h.blocked_by().contains(&blocker));

        update(&layout, &first, None, None, None, Some(&blocker)).unwrap();
        let h = issue_at(&layout, "sample", &first);
        assert_eq!(h.state, "TODO");
        assert!(h.blocked_by().is_empty());
    }

    #[test]
    fn auto_unblock_to_todo_releases_the_claim() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "first", CreateOpts::default()).unwrap();
        create(&layout, "sample", "blocker", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let first = doc.headings[0].id.clone();
        let blocker = doc.headings[1].id.clone();

        crate::agent::claim(&layout, &first, false).unwrap();
        update(&layout, &first, None, None, Some(&blocker), None).unwrap();
        assert!(issue_at(&layout, "sample", &first).claimed_by().is_some());

        update(&layout, &first, None, None, None, Some(&blocker)).unwrap();
        let h = issue_at(&layout, "sample", &first);
        assert_eq!(h.state, "TODO");
        assert!(h.claimed_by().is_none(), "claim stuck on TODO: {h:?}");
    }

    #[test]
    fn blocker_cycle_is_rejected_before_writing() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "first", CreateOpts::default()).unwrap();
        create(&layout, "sample", "second", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let first = doc.headings[0].id.clone();
        let second = doc.headings[1].id.clone();

        update(&layout, &first, None, None, Some(&second), None).unwrap();
        let err = update(&layout, &second, None, None, Some(&first), None).unwrap_err();
        assert!(err.to_string().contains("blocker cycle"), "{err}");
        assert!(issue_at(&layout, "sample", &second).blocked_by().is_empty());
    }

    #[test]
    fn closing_a_blocker_reports_the_issues_still_pointing_at_it() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "first", CreateOpts::default()).unwrap();
        create(&layout, "sample", "blocker", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let first = doc.headings[0].id.clone();
        let blocker = doc.headings[1].id.clone();
        update(&layout, &first, None, None, Some(&blocker), None).unwrap();

        let outcome = update(&layout, &blocker, Some("DONE"), None, None, None).unwrap();
        assert_eq!(outcome.hints.len(), 1, "{:?}", outcome.hints);
        assert!(outcome.hints[0].contains(&first), "{:?}", outcome.hints);
    }

    #[test]
    fn refile_moves_the_heading_between_projects() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "source", "the issue", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "source");
        refile(&layout, &id, "target").unwrap();

        let src = IssueDoc::parse_file("source", &layout.project_issues_path("source")).unwrap();
        let tgt = IssueDoc::parse_file("target", &layout.project_issues_path("target")).unwrap();
        assert!(src.headings.is_empty());
        assert_eq!(tgt.headings[0].id, id);
    }

    #[test]
    fn deadlines_must_parse_as_org_dates() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        let err = create(
            &layout,
            "sample",
            "bad date",
            CreateOpts {
                deadline: Some("not-a-date"),
                ..Default::default()
            },
        )
        .unwrap_err();
        assert!(err.to_string().contains("expected org date"));

        for (i, d) in ["<2026-05-15 Fri>", "[2026-05-15]"].iter().enumerate() {
            create(
                &layout,
                "sample",
                &format!("issue {i}"),
                CreateOpts {
                    deadline: Some(d),
                    ..Default::default()
                },
            )
            .unwrap();
        }
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        assert_eq!(doc.headings.len(), 2);
        assert!(doc.headings.iter().all(|h| h.deadline().is_some()));
    }

    #[test]
    fn org_safe_tags_go_on_the_heading_and_the_rest_stay_in_the_property() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(
            &layout,
            "sample",
            "tagged",
            CreateOpts {
                tags: Some("rust: perf ,, scaling, needs-review"),
                ..Default::default()
            },
        )
        .unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let h = &doc.headings[0];
        assert_eq!(h.org_tags, vec!["rust", "perf", "scaling"]);
        assert_eq!(
            h.properties
                .get(crate::model::TAGS_PROPERTY)
                .map(|s| s.as_str()),
            Some("needs-review"),
            "a tag Org cannot hold keeps the property"
        );
        // Whichever half a tag landed in, a query sees all of them.
        assert_eq!(
            h.tags(),
            vec!["needs-review", "rust", "perf", "scaling"],
            "{h:?}"
        );
    }

    #[test]
    fn create_puts_a_legal_type_on_the_heading() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(
            &layout,
            "sample",
            "a bug",
            CreateOpts {
                issue_type: Some("bug"),
                ..Default::default()
            },
        )
        .unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let h = &doc.headings[0];
        assert_eq!(
            crate::props::get(&h.properties, crate::props::TYPE),
            Some("bug")
        );
        assert_eq!(h.org_tags, vec!["bug"]);
        let written = std::fs::read_to_string(layout.project_issues_path("sample")).unwrap();
        assert!(written.contains("#+CATEGORY: sample"), "{written}");
        assert!(written.contains(":bug:"), "{written}");
    }

    #[test]
    fn resolve_project_needs_a_name_from_somewhere() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        assert_eq!(
            resolve_project(&layout, Some("fromcli")).unwrap(),
            "fromcli"
        );
        assert!(
            resolve_project(&layout, Some(""))
                .unwrap_err()
                .to_string()
                .contains("empty")
        );
    }

    /// Parallel creates must not lose headings or fail the temporary rename.
    #[test]
    fn concurrent_creates_preserve_every_heading() {
        use std::sync::Arc;
        use std::thread;

        let dir = tempfile::tempdir().unwrap();
        let layout = Arc::new(fresh_layout(dir.path()));
        let n = 24usize;
        let handles: Vec<_> = (0..n)
            .map(|i| {
                let layout = Arc::clone(&layout);
                thread::spawn(move || {
                    create(
                        &layout,
                        "sample",
                        &format!("parallel title {i}"),
                        CreateOpts {
                            quiet: true,
                            ..Default::default()
                        },
                    )
                })
            })
            .collect();
        let mut ids: Vec<String> = handles
            .into_iter()
            .map(|h| {
                h.join()
                    .expect("thread panicked")
                    .expect("create failed")
                    .trim()
                    .to_string()
            })
            .collect();
        ids.sort();
        ids.dedup();
        assert_eq!(ids.len(), n, "expected {n} unique ids, got {ids:?}");

        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let mut on_disk: Vec<String> = doc.headings.iter().map(|h| h.id.clone()).collect();
        on_disk.sort();
        assert_eq!(on_disk, ids);
    }

    #[test]
    fn note_appends_to_the_logbook_and_leaves_state_alone() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "carries a note", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        let out = note(&layout, &id, "first pass done,\n  \"quoted\" bit next").unwrap();
        assert_eq!(out, format!("{id}: noted\n"));

        let h = issue_at(&layout, "sample", &id);
        assert_eq!(h.state, "TODO");
        assert!(h.claimed_by().is_none());
        let notes: Vec<&str> = h.logbook.iter().filter_map(|e| e.note.as_deref()).collect();
        // Whitespace collapses to single spaces; double quotes become single.
        assert_eq!(notes, vec!["first pass done, 'quoted' bit next"]);
    }

    #[test]
    fn the_logbook_reads_newest_first_however_an_entry_arrived() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "ordered", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        note(&layout, &id, "first note").unwrap();
        update(&layout, &id, Some("STARTED"), None, None, None).unwrap();
        note(&layout, &id, "second note").unwrap();

        let h = issue_at(&layout, "sample", &id);
        let summary: Vec<String> = h
            .logbook
            .iter()
            .map(|e| match (&e.note, &e.to_state) {
                (Some(note), _) => note.clone(),
                (_, Some(to)) => format!("state:{to}"),
                _ => "?".into(),
            })
            .collect();
        assert_eq!(
            summary,
            vec!["second note", "state:STARTED", "first note"],
            "{h:?}"
        );
    }

    #[test]
    fn note_rejects_empty_text_and_unknown_ids() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "target", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        assert!(note(&layout, &id, "   ").is_err());
        assert!(note(&layout, "sample-zzz9", "text").is_err());
    }

    #[test]
    fn fold_creates_issues_and_stamps_the_inbox_idempotently() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "seed", CreateOpts::default()).unwrap();

        let inbox = dir.path().join("inbox.org");
        fs::write(
            &inbox,
            "#+TITLE: inbox\n\n\
             * TODO first discovered thing\nSome body line.\nAnother line.\n\
             * DONE already handled elsewhere\n\
             * TODO second discovered thing\n",
        )
        .unwrap();

        let out = fold(&layout, &inbox, "sample").unwrap();
        assert!(out.starts_with("folded 2: "), "got: {out}");

        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let titles: Vec<&str> = doc.headings.iter().map(|h| h.title.as_str()).collect();
        assert!(titles.contains(&"first discovered thing"));
        assert!(titles.contains(&"second discovered thing"));
        let folded = doc
            .headings
            .iter()
            .find(|h| h.title == "first discovered thing")
            .unwrap();
        assert!(folded.body.contains("Some body line."));

        // Headings flipped to DONE and stamped with the assigned id.
        let stamped = fs::read_to_string(&inbox).unwrap();
        assert_eq!(stamped.matches("* DONE ").count(), 3);
        assert_eq!(stamped.matches(":VISSUE_ID: sample-").count(), 2);
        assert!(!stamped.contains("* TODO "));

        // Second fold finds nothing unstamped and creates nothing.
        let again = fold(&layout, &inbox, "sample").unwrap();
        assert_eq!(again, "folded 0 (nothing unstamped)\n");
        let doc2 = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        assert_eq!(doc2.headings.len(), doc.headings.len());
    }

    #[test]
    fn refile_to_moves_across_two_layouts_and_leaves_no_shadow() {
        let src_dir = tempfile::tempdir().unwrap();
        let dst_dir = tempfile::tempdir().unwrap();
        let src_layout = fresh_layout(src_dir.path());
        let dst_layout = fresh_layout(dst_dir.path());
        create(&src_layout, "misc", "wrong board", CreateOpts::default()).unwrap();
        let id = IssueDoc::parse_file("misc", &src_layout.project_issues_path("misc"))
            .unwrap()
            .headings[0]
            .id
            .clone();

        let out = refile_to(&src_layout, &id, &dst_layout, "surf").unwrap();
        assert!(out.contains("misc -> surf"), "{out}");

        // The heading is on the destination tracker, and the source root has
        // no `surf` directory standing in for it.
        let moved = IssueDoc::parse_file("surf", &dst_layout.project_issues_path("surf")).unwrap();
        assert_eq!(moved.headings.len(), 1);
        assert_eq!(moved.headings[0].id, id);
        assert!(!src_layout.project_issues_path("surf").exists());
        let left = IssueDoc::parse_file("misc", &src_layout.project_issues_path("misc")).unwrap();
        assert!(left.headings.is_empty());
    }

    #[test]
    fn reject_creates_the_successor_on_the_destination_layout() {
        let src_dir = tempfile::tempdir().unwrap();
        let dst_dir = tempfile::tempdir().unwrap();
        let src_layout = fresh_layout(src_dir.path());
        let dst_layout = fresh_layout(dst_dir.path());
        create(&src_layout, "misc", "old approach", CreateOpts::default()).unwrap();
        let src = IssueDoc::parse_file("misc", &src_layout.project_issues_path("misc"))
            .unwrap()
            .headings[0]
            .id
            .clone();

        // A twin id the destination file does not hold yet: the successor must
        // not mint it, because the routed board already uses it. Handed over as
        // the file that holds it rather than as the id, so the reservation is
        // read under the lock that guards the write.
        let twin_dir = tempfile::tempdir().unwrap();
        let twin_layout = fresh_layout(twin_dir.path());
        let twin_path = twin_layout.project_issues_path("surf");
        std::fs::create_dir_all(twin_path.parent().unwrap()).unwrap();
        std::fs::write(
            &twin_path,
            "#+TITLE: surf issues\n\n* TODO taken elsewhere\n:PROPERTIES:\n             :ID:         surf-aaaa\n:END:\n",
        )
        .unwrap();
        let twins = vec![twin_path.clone()];
        let out = reject(
            &src_layout,
            &src,
            RejectOpts {
                project: Some("surf"),
                title: Some("new approach"),
                dst_layout: Some(&dst_layout),
                dst_extra_id_paths: &twins,
                ..Default::default()
            },
        )
        .unwrap();

        assert!(!src_layout.project_issues_path("surf").exists());
        let made = IssueDoc::parse_file("surf", &dst_layout.project_issues_path("surf")).unwrap();
        assert_eq!(made.headings.len(), 1);
        assert_ne!(made.headings[0].id, "surf-aaaa");
        assert!(out.contains(&made.headings[0].id), "{out}");
        assert_eq!(issue_at(&src_layout, "misc", &src).state, "CANCELLED");
    }

    #[test]
    fn reject_to_an_existing_issue_cancels_and_wires_the_pair() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "old approach", CreateOpts::default()).unwrap();
        create(&layout, "sample", "new approach", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let src = doc.headings[0].id.clone();
        let dst = doc.headings[1].id.clone();

        let out = reject(
            &layout,
            &src,
            RejectOpts {
                to: Some(&dst),
                ..Default::default()
            },
        )
        .unwrap();
        assert!(out.contains(&src) && out.contains(&dst), "{out}");

        let src_h = issue_at(&layout, "sample", &src);
        assert_eq!(src_h.state, "CANCELLED");
        assert_eq!(
            src_h.properties.get("PIVOTED_TO").map(String::as_str),
            Some(dst.as_str())
        );
        let dst_h = issue_at(&layout, "sample", &dst);
        assert_eq!(
            dst_h.properties.get("DISCOVERED_FROM").map(String::as_str),
            Some(src.as_str())
        );
    }

    #[test]
    fn reject_creates_the_destination_in_another_project() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "old approach", CreateOpts::default()).unwrap();
        let src = only_id(&layout, "sample");

        let out = reject(
            &layout,
            &src,
            RejectOpts {
                project: Some("other"),
                title: Some("new approach"),
                ..Default::default()
            },
        )
        .unwrap();

        let dst_doc = IssueDoc::parse_file("other", &layout.project_issues_path("other")).unwrap();
        assert_eq!(dst_doc.headings.len(), 1);
        let dst = &dst_doc.headings[0];
        assert_eq!(dst.title, "new approach");
        assert_eq!(
            dst.properties.get("DISCOVERED_FROM").map(String::as_str),
            Some(src.as_str())
        );
        assert!(out.contains(&src) && out.contains(&dst.id), "{out}");

        let src_h = issue_at(&layout, "sample", &src);
        assert_eq!(src_h.state, "CANCELLED");
        assert_eq!(
            src_h.properties.get("PIVOTED_TO").map(String::as_str),
            Some(dst.id.as_str())
        );
    }

    #[test]
    fn reject_refuses_an_unknown_source_or_destination() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "only", CreateOpts::default()).unwrap();
        let src = only_id(&layout, "sample");

        let missing_src = reject(
            &layout,
            "sample-zzzz",
            RejectOpts {
                to: Some(&src),
                ..Default::default()
            },
        )
        .unwrap_err();
        assert!(
            matches!(missing_src, Error::IssueNotFound { .. }),
            "{missing_src}"
        );

        let missing_dst = reject(
            &layout,
            &src,
            RejectOpts {
                to: Some("sample-zzzz"),
                ..Default::default()
            },
        )
        .unwrap_err();
        assert!(
            matches!(missing_dst, Error::IssueNotFound { .. }),
            "{missing_dst}"
        );
    }

    #[test]
    fn reject_does_not_overwrite_a_nonempty_discovered_from() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "origin", CreateOpts::default()).unwrap();
        create(&layout, "sample", "old approach", CreateOpts::default()).unwrap();
        create(&layout, "sample", "already sourced", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let origin = doc.headings[0].id.clone();
        let src = doc.headings[1].id.clone();
        let dst = doc.headings[2].id.clone();

        let path = layout.project_issues_path("sample");
        let mut doc = IssueDoc::parse_file("sample", &path).unwrap();
        doc.headings
            .iter_mut()
            .find(|h| h.id == dst)
            .unwrap()
            .properties
            .insert("DISCOVERED_FROM".into(), origin.clone());
        doc.write().unwrap();

        reject(
            &layout,
            &src,
            RejectOpts {
                to: Some(&dst),
                ..Default::default()
            },
        )
        .unwrap();
        let dst_h = issue_at(&layout, "sample", &dst);
        assert_eq!(
            dst_h.properties.get("DISCOVERED_FROM").map(String::as_str),
            Some(origin.as_str()),
            "a filled DISCOVERED_FROM stays put"
        );
    }

    #[test]
    fn create_sets_discovered_from_from_the_first_known_id_link() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "source", CreateOpts::default()).unwrap();
        let known = only_id(&layout, "sample");
        create(
            &layout,
            "sample",
            "fell out of it",
            CreateOpts {
                body: Some(&format!("See [[id:{known}]] for the parent finding.")),
                ..Default::default()
            },
        )
        .unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let child = doc
            .headings
            .iter()
            .find(|h| h.title == "fell out of it")
            .unwrap();
        assert_eq!(
            child.properties.get("DISCOVERED_FROM").map(String::as_str),
            Some(known.as_str())
        );
    }

    #[test]
    fn create_ignores_an_id_link_that_is_not_in_the_corpus() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(
            &layout,
            "sample",
            "orphan mention",
            CreateOpts {
                body: Some("See [[id:sample-zzzz]] which does not exist."),
                ..Default::default()
            },
        )
        .unwrap();
        let h = issue_at(&layout, "sample", &only_id(&layout, "sample"));
        assert!(
            !h.properties.contains_key("DISCOVERED_FROM"),
            "unknown [[id:]] must not mint DISCOVERED_FROM: {h:?}"
        );
        assert!(
            !h.properties.contains_key("BLOCKED_BY"),
            "prose must not mint BLOCKED_BY: {h:?}"
        );
    }

    #[test]
    fn related_after_reject_names_the_successor_without_a_body_link() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "old approach", CreateOpts::default()).unwrap();
        create(&layout, "sample", "new approach", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let src = doc.headings[0].id.clone();
        let dst = doc.headings[1].id.clone();
        reject(
            &layout,
            &src,
            RejectOpts {
                to: Some(&dst),
                ..Default::default()
            },
        )
        .unwrap();

        assert!(
            !issue_at(&layout, "sample", &src).body.contains(&dst),
            "the pair is wired by PIVOTED_TO, not prose"
        );
        let from_src = crate::related::related(&layout, &src, 1, 10, "text").unwrap();
        assert!(from_src.contains(&dst), "{from_src}");
        assert!(from_src.contains("pivoted_to"), "{from_src}");

        let from_dst = crate::related::related(&layout, &dst, 1, 10, "text").unwrap();
        assert!(from_dst.contains(&src), "{from_dst}");
        assert!(from_dst.contains("successor_of"), "{from_dst}");

        let waiting = crate::report::backlinks(&layout, &dst).unwrap();
        assert!(waiting.contains(&src), "{waiting}");
    }

    #[test]
    fn update_to_cancelled_emits_state_change_with_the_id() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "first", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        let before = crate::events::generation(&layout);
        update(&layout, &id, Some("CANCELLED"), None, None, None).unwrap();
        let events = crate::events::since(&layout, before, 50).unwrap();
        assert!(
            events.iter().any(|e| {
                e.kind == "state_change"
                    && e.id.as_deref() == Some(id.as_str())
                    && e.detail.as_deref() == Some("TODO->CANCELLED")
            }),
            "{events:?}"
        );
    }

    #[test]
    fn a_stale_done_after_reject_is_refused_and_the_source_stays_cancelled() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "old plan", CreateOpts::default()).unwrap();
        create(&layout, "sample", "rewrite", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let src = doc.headings[0].id.clone();
        let dst = doc.headings[1].id.clone();
        reject(
            &layout,
            &src,
            RejectOpts {
                to: Some(&dst),
                ..Default::default()
            },
        )
        .unwrap();

        let err = update_pred(
            &layout,
            &src,
            Some("DONE"),
            None,
            None,
            None,
            UpdatePred {
                if_state: Some("STARTED"),
                if_gen: None,
            },
        )
        .unwrap_err();
        assert!(
            matches!(
                err,
                Error::StaleWrite {
                    ref actual_state,
                    ref expected_state,
                    ..
                } if actual_state == "CANCELLED" && expected_state.as_deref() == Some("STARTED")
            ),
            "{err:?}"
        );
        assert_eq!(issue_at(&layout, "sample", &src).state, "CANCELLED");
    }

    #[test]
    fn if_gen_refuses_when_the_corpus_moved() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "first", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        let seen = crate::events::generation(&layout);
        update(&layout, &id, Some("STARTED"), None, None, None).unwrap();
        let err = update_pred(
            &layout,
            &id,
            Some("DONE"),
            None,
            None,
            None,
            UpdatePred {
                if_state: None,
                if_gen: Some(seen),
            },
        )
        .unwrap_err();
        assert!(matches!(err, Error::StaleWrite { .. }), "{err:?}");
        assert_eq!(issue_at(&layout, "sample", &id).state, "STARTED");
    }

    #[test]
    fn a_second_terminal_does_not_drop_the_first() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "first", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        update(&layout, &id, Some("DONE"), None, None, None).unwrap();
        update(&layout, &id, Some("CANCELLED"), None, None, None).unwrap();
        let h = issue_at(&layout, "sample", &id);
        assert_eq!(h.state, "DONE", "first terminal must stay");
        assert_eq!(
            crate::props::get(&h.properties, crate::props::SIBLING_TERMINAL),
            Some("CANCELLED")
        );

        resolve_terminal(&layout, &id, "CANCELLED").unwrap();
        let h = issue_at(&layout, "sample", &id);
        assert_eq!(h.state, "CANCELLED");
        assert!(crate::props::get(&h.properties, crate::props::SIBLING_TERMINAL).is_none());
    }

    #[test]
    fn check_warns_on_reject_prose_done_and_a_mention_without_an_edge() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "shipped", CreateOpts::default()).unwrap();
        create(&layout, "sample", "other", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let shipped = doc.headings[0].id.clone();
        let other = doc.headings[1].id.clone();
        update(&layout, &shipped, Some("DONE"), None, None, None).unwrap();
        append_body(&layout, &shipped, "superseded by the other one, bounced").unwrap();
        append_body(
            &layout,
            &other,
            &format!("discovered while reading [[id:{shipped}]]"),
        )
        .unwrap();

        let report = crate::report::check(&layout).unwrap();
        assert!(
            report.text.contains(&shipped)
                && report.text.contains("DONE but the body reads as a reject"),
            "{}",
            report.text
        );
        assert!(
            report.text.contains(&other)
                && report
                    .text
                    .contains("as discovered or pivoted with no edge"),
            "{}",
            report.text
        );
        assert!(report.warnings >= 2, "{}", report.text);
    }

    // The word is not the finding. Every bug about input validation says
    // "rejected", and three issues in one corpus were flagged for sentences
    // about what the software does to bad input.
    #[test]
    fn check_is_quiet_about_a_done_issue_that_merely_uses_the_word_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "validation", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let id = doc.headings[0].id.clone();
        update(&layout, &id, Some("DONE"), None, None, None).unwrap();
        append_body(
            &layout,
            &id,
            "A compound spec is silently corrupted rather than rejected, and the \
             alternative parser was rejected as strictly dominated.",
        )
        .unwrap();

        let report = crate::report::check(&layout).unwrap();
        assert!(
            !report.text.contains("reads as a reject"),
            "the word alone was read as an outcome: {}",
            report.text
        );
    }

    // A "Supersedes" section rolls up issues this one did not close, which is the
    // opposite of being superseded, and the two differ by one letter.
    #[test]
    fn check_reads_supersedes_as_a_roll_up_and_superseded_by_as_an_outcome() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "umbrella", CreateOpts::default()).unwrap();
        create(&layout, "sample", "replaced", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let rollup = doc.headings[0].id.clone();
        let replaced = doc.headings[1].id.clone();
        update(&layout, &rollup, Some("DONE"), None, None, None).unwrap();
        update(&layout, &replaced, Some("DONE"), None, None, None).unwrap();
        append_body(&layout, &rollup, "** Supersedes\nrolls up the pieces").unwrap();
        append_body(&layout, &replaced, "superseded by the umbrella").unwrap();

        let report = crate::report::check(&layout).unwrap();
        let flagged: Vec<&str> = report
            .text
            .lines()
            .filter(|l| l.contains("reads as a reject"))
            .collect();

        assert!(
            flagged.iter().any(|l| l.contains(&replaced)),
            "an issue that says it was superseded was not flagged: {}",
            report.text
        );
        assert!(
            !flagged.iter().any(|l| l.contains(&rollup)),
            "a Supersedes roll-up was read as its own rejection: {}",
            report.text
        );
    }

    // A body links other issues for every reason there is. Only the reason the
    // properties name is a finding.
    #[test]
    fn check_is_quiet_about_a_mention_that_claims_no_relation() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "umbrella", CreateOpts::default()).unwrap();
        create(&layout, "sample", "piece", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let umbrella = doc.headings[0].id.clone();
        let piece = doc.headings[1].id.clone();
        append_body(
            &layout,
            &umbrella,
            &format!("** Supersedes\nRolls up [[id:{piece}]], which it does not close."),
        )
        .unwrap();

        let report = crate::report::check(&layout).unwrap();
        assert!(
            !report.text.contains("as discovered or pivoted"),
            "a roll-up was read as a discovery: {}",
            report.text
        );
    }

    // And the claim has to be near the link: a long issue says many things.
    #[test]
    fn check_reads_a_discovery_claim_only_near_the_link_it_belongs_to() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "long", CreateOpts::default()).unwrap();
        create(&layout, "sample", "elsewhere", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let long = doc.headings[0].id.clone();
        let elsewhere = doc.headings[1].id.clone();
        let filler = "prose ".repeat(120);
        append_body(
            &layout,
            &long,
            &format!("discovered while auditing the loader.\n{filler}\nsee [[id:{elsewhere}]]"),
        )
        .unwrap();

        let report = crate::report::check(&layout).unwrap();
        assert!(
            !report.text.contains("as discovered or pivoted"),
            "a claim in another section was attached to this link: {}",
            report.text
        );
    }

    // A parent naming its child is a stated relation the tracker already holds.
    #[test]
    fn check_is_quiet_about_a_mention_that_a_parent_edge_already_explains() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "umbrella", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let parent = doc.headings[0].id.clone();
        create(
            &layout,
            "sample",
            "piece",
            CreateOpts {
                parent: Some(parent.as_str()),
                ..CreateOpts::default()
            },
        )
        .unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let child = doc
            .headings
            .iter()
            .find(|h| h.id != parent)
            .map(|h| h.id.clone())
            .unwrap();
        // The prose claims a discovery, so the warning would fire on this pair
        // if the parent edge were not recognised. Without the claim the test
        // would pass whatever edge_connects does, and asserting the absence of
        // the old wording would pass even with the fix reverted.
        append_body(
            &layout,
            &parent,
            &format!("discovered while reading [[id:{child}]]"),
        )
        .unwrap();
        create(&layout, "sample", "unrelated", CreateOpts::default()).unwrap();
        let doc = IssueDoc::parse_file("sample", &layout.project_issues_path("sample")).unwrap();
        let stranger = doc
            .headings
            .iter()
            .find(|h| h.id != parent && h.id != child)
            .map(|h| h.id.clone())
            .unwrap();
        append_body(
            &layout,
            &stranger,
            &format!("discovered while reading [[id:{parent}]]"),
        )
        .unwrap();

        let report = crate::report::check(&layout).unwrap();
        let flagged: Vec<&str> = report
            .text
            .lines()
            .filter(|l| l.contains("as discovered or pivoted"))
            .collect();
        assert!(
            flagged.iter().any(|l| l.contains(&stranger)),
            "the control pair with no edge was not flagged, so this test proves nothing: {}",
            report.text
        );
        assert!(
            !flagged
                .iter()
                .any(|l| l.contains(&parent) && l.contains(&child)),
            "a parent edge did not count as a relation: {}",
            report.text
        );
    }

    #[test]
    fn check_names_a_file_missing_category_and_a_type_not_on_the_heading() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        let path = layout.project_issues_path("sample");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(
            &path,
            "#+TITLE: sample issues\n#+TODO: TODO STARTED BLOCKED | DONE CANCELLED\n\n* TODO [#A] Untagged type\n:PROPERTIES:\n:ID:         sample-aaaa\n:TYPE:       bug\n:END:\n",
        )
        .unwrap();
        let report = crate::report::check(&layout).unwrap();
        assert!(
            report.text.contains("sample: preamble has no #+CATEGORY:"),
            "{}",
            report.text
        );
        assert!(
            report
                .text
                .contains("have :TYPE: that is a legal Org tag but is not on the heading"),
            "{}",
            report.text
        );
        assert!(
            report
                .text
                .contains("preamble has no #+VISSUE: protocol stamp"),
            "{}",
            report.text
        );
        assert!(
            report.text.contains("preamble has no #+PRIORITIES:"),
            "{}",
            report.text
        );
    }

    #[test]
    fn check_errors_on_a_newer_protocol_stamp() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        let path = layout.project_issues_path("sample");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(
            &path,
            "#+TITLE: sample issues\n#+VISSUE: 99\n#+CATEGORY: sample\n#+FILETAGS: :issues:sample:noexport:\n#+TAGS: docs\n#+TODO: TODO | DONE\n\n* TODO [#A] Future\n:PROPERTIES:\n:ID:         sample-aaaa\n:END:\n",
        )
        .unwrap();
        let report = crate::report::check(&layout).unwrap();
        assert!(report.errors >= 1, "{}", report.text);
        assert!(
            report
                .text
                .contains("#+VISSUE: 99 is newer than this vissue"),
            "{}",
            report.text
        );
    }

    #[test]
    fn normalize_rewrites_legacy_keys_and_keeps_edna() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        let path = layout.project_issues_path("sample");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(
            &path,
            "#+TITLE: sample issues\n#+TODO: TODO STARTED BLOCKED | DONE CANCELLED\n\n* TODO [#A] Legacy\n:PROPERTIES:\n:ID:         sample-aaaa\n:TYPE:       bug\n:PARENT:     sample-root\n:BLOCKEDBY:  sample-bbbb\n:END:\n\n* TODO [#A] Edna condition\n:PROPERTIES:\n:ID:         sample-cccc\n:BLOCKER:    prev-sibling\n:END:\n",
        )
        .unwrap();
        let dry = normalize(&layout, Some("sample"), true).unwrap();
        assert!(dry.contains("would rewrite"), "{dry}");
        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert!(on_disk.contains(":TYPE:"), "{on_disk}");
        let wrote = normalize(&layout, Some("sample"), false).unwrap();
        assert!(wrote.contains("rewrote"), "{wrote}");
        let after = std::fs::read_to_string(&path).unwrap();
        assert!(after.contains("#+CATEGORY: sample"), "{after}");
        assert!(after.contains("#+PRIORITIES: A C C"), "{after}");
        assert!(after.contains(":TYPE:       bug"), "{after}");
        assert!(after.contains(":PARENT:"), "{after}");
        assert!(after.contains(":BLOCKED_BY:"), "{after}");
        assert!(
            !after.contains("ids(sample-bbbb)"),
            "normalize must not mint edna ids(): {after}"
        );
        assert!(after.contains("prev-sibling"), "{after}");
    }
    /// The reservation has to be read after the lock is taken, not before.
    ///
    /// Deterministic rather than a stress test, because a stress test has no
    /// power here: the suffix space is 36^n and two racing creates almost never
    /// collide by luck, so a run that passes proves nothing. This forces the
    /// question instead. With `id_length = 2` the space is 1296 suffixes; the
    /// twin layout is handed 1295 of them, so exactly one is free and a mint
    /// that reads the twin has no choice but to return it.
    ///
    /// A mint that trusts a caller's snapshot, which is what `extra_ids` is,
    /// picks from the whole space and returns that one suffix with probability
    /// 1/1296.
    #[test]
    fn the_reservation_is_read_after_the_lock_is_held() {
        let dir = tempfile::tempdir().unwrap();
        let own_root = dir.path().join("own");
        let twin_root = dir.path().join("twin");
        std::fs::create_dir_all(&own_root).unwrap();
        std::fs::create_dir_all(&twin_root).unwrap();
        std::fs::write(own_root.join("vissue.toml"), "[issues]\nid_length = 2\n").unwrap();
        let own = fresh_layout(&own_root);
        let twin = fresh_layout(&twin_root);

        // Every suffix but "zz", written straight to the twin file.
        let mut body = String::from("#+TITLE: sample issues\n\n");
        let alphabet = b"0123456789abcdefghijklmnopqrstuvwxyz";
        for a in alphabet {
            for b in alphabet {
                if *a == b'z' && *b == b'z' {
                    continue;
                }
                let id = format!("sample-{}{}", *a as char, *b as char);
                body.push_str(&format!(
                    "* TODO filler {id}\n:PROPERTIES:\n:ID:         {id}\n:END:\n\n"
                ));
            }
        }
        let twin_path = twin.project_issues_path("sample");
        std::fs::create_dir_all(twin_path.parent().unwrap()).unwrap();
        std::fs::write(&twin_path, body).unwrap();

        let twins = vec![twin_path.clone()];
        let id = create(
            &own,
            "sample",
            "the only suffix left",
            CreateOpts {
                quiet: true,
                extra_id_paths: &twins,
                ..Default::default()
            },
        )
        .expect("create failed")
        .trim()
        .to_string();

        assert_eq!(
            id, "sample-zz",
            "the mint did not treat the twin file as taken, so it read the reservation \
             before the lock rather than after"
        );
    }

    /// And the twin being the file under write is ordinary, not a deadlock.
    /// `extra_id_paths_for` returns every layout for the project including this
    /// one, so the write path arrives in its own reservation list on every
    /// routed create.
    #[test]
    fn the_written_file_appearing_in_its_own_reservation_is_not_a_deadlock() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        let own_path = layout.project_issues_path("sample");
        let twins = vec![own_path.clone(), own_path.clone()];
        let id = create(
            &layout,
            "sample",
            "self referential reservation",
            CreateOpts {
                quiet: true,
                extra_id_paths: &twins,
                ..Default::default()
            },
        )
        .expect("create deadlocked or failed")
        .trim()
        .to_string();
        assert!(id.starts_with("sample-"), "{id}");
    }
    // ------------------------------------------------------------------ votes

    fn voted(layout: &Layout, id: &str, who: &str, choice: &str) -> String {
        vote(layout, id, Some(choice), who).expect("vote failed")
    }

    #[test]
    fn one_agent_one_ballot_and_a_recast_replaces_it() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        voted(&layout, &id, "agent-a", "ship");
        let out = voted(&layout, &id, "agent-a", "hold");
        assert!(out.contains("changed ship to hold"), "{out}");

        let tally = vote(&layout, &id, None, "reader").unwrap();
        assert!(tally.contains("1 vote from 1 option"), "{tally}");
        assert!(tally.contains("hold"), "{tally}");
        assert!(!tally.contains("ship"), "{tally}");
    }

    #[test]
    fn two_agents_do_not_overwrite_each_other() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        voted(&layout, &id, "agent-a", "ship");
        voted(&layout, &id, "agent-b", "ship");
        let out = voted(&layout, &id, "agent-c", "hold");

        assert!(out.contains("3 votes from 2 options"), "{out}");
        assert!(out.contains("consensus: ship (2 of 3)"), "{out}");
    }

    /// A tie is the case a tally exists to surface, so it must not report the
    /// first option as though the agents agreed.
    #[test]
    fn a_tie_is_reported_as_no_consensus() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        voted(&layout, &id, "agent-a", "ship");
        let out = voted(&layout, &id, "agent-b", "hold");

        assert!(out.contains("no consensus: 2 options tied at 1"), "{out}");
        assert!(!out.contains("consensus: ship"), "{out}");
    }

    /// And a lead that is not a majority is a plurality, which is a different
    /// claim from agreement.
    #[test]
    fn a_lead_short_of_a_majority_is_not_called_consensus() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        voted(&layout, &id, "agent-a", "ship");
        voted(&layout, &id, "agent-b", "ship");
        voted(&layout, &id, "agent-c", "hold");
        let out = voted(&layout, &id, "agent-d", "rework");

        // 2 of 4 leads but does not carry.
        assert!(out.contains("plurality only: ship (2 of 4)"), "{out}");
        assert!(!out.contains("consensus: ship"), "{out}");
    }

    #[test]
    fn votes_survive_a_rewrite_and_are_readable_in_the_file() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        voted(&layout, &id, "agent-a", "ship");

        // An unrelated edit rewrites the file; the drawer has to come back.
        append_body(&layout, &id, "some prose").unwrap();
        let text = std::fs::read_to_string(layout.project_issues_path("sample")).unwrap();
        assert!(text.contains(":VOTES:"), "{text}");
        assert!(text.contains("agent-a: ship"), "{text}");

        let tally = vote(&layout, &id, None, "reader").unwrap();
        assert!(tally.contains("agent-a"), "{tally}");
    }

    #[test]
    fn an_issue_with_no_votes_says_so_rather_than_showing_an_empty_table() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        assert!(
            vote(&layout, &id, None, "reader")
                .unwrap()
                .contains("no votes")
        );
    }

    #[test]
    fn a_blank_or_multiline_vote_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        assert!(vote(&layout, &id, Some("   "), "agent-a").is_err());
        assert!(vote(&layout, &id, Some("ship\nhold"), "agent-a").is_err());
    }

    /// A choice may hold a colon, because "ship: after the audit" is a thing an
    /// agent will vote for and the line format has to survive it.
    #[test]
    fn a_choice_containing_a_colon_round_trips() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        voted(&layout, &id, "agent-a", "ship: after the audit");
        let tally = vote(&layout, &id, None, "reader").unwrap();
        assert!(tally.contains("ship: after the audit"), "{tally}");
    }

    /// Concurrent voters are the point of the feature, so they are tested the
    /// way the id reservation is: every ballot has to land.
    #[test]
    fn concurrent_voters_all_land() {
        use std::sync::Arc;
        use std::thread;

        let dir = tempfile::tempdir().unwrap();
        let layout = Arc::new(fresh_layout(dir.path()));
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        let n = 16usize;
        let handles: Vec<_> = (0..n)
            .map(|i| {
                let layout = Arc::clone(&layout);
                let id = id.clone();
                thread::spawn(move || vote(&layout, &id, Some("ship"), &format!("agent-{i:02}")))
            })
            .collect();
        for h in handles {
            h.join().expect("thread panicked").expect("vote failed");
        }

        let tally = vote(&layout, &id, None, "reader").unwrap();
        assert!(
            tally.contains(&format!("{n} votes from 1 option")),
            "a ballot was lost: {tally}"
        );
    }
    /// One agent agreeing with itself is not a consensus. Calling it one is how a
    /// single unreviewed opinion gets acted on as though it had been checked.
    #[test]
    fn a_single_ballot_is_not_called_a_consensus() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        let out = voted(&layout, &id, "agent-a", "ship");
        assert!(out.contains("one ballot only: ship"), "{out}");
        assert!(!out.contains("consensus: ship"), "{out}");

        // A second agent agreeing makes it one.
        let out = voted(&layout, &id, "agent-b", "ship");
        assert!(out.contains("consensus: ship (2 of 2)"), "{out}");
    }

    /// The ballot line splits on the first ": " so a choice may contain one. An
    /// identity containing one would therefore come back as a shorter name with
    /// the rest of itself glued to the choice, filing the vote under an agent
    /// that never voted. Refused, because silently misattributing is worse.
    #[test]
    fn an_identity_that_the_line_format_cannot_hold_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");

        let err = vote(&layout, &id, Some("ship"), "team: alpha").unwrap_err();
        assert!(err.to_string().contains("colon"), "{err}");
        assert!(vote(&layout, &id, Some("ship"), "   ").is_err());

        // And the tally is untouched by the refusal.
        assert!(
            vote(&layout, &id, None, "reader")
                .unwrap()
                .contains("no votes")
        );
    }

    /// The drawer is org a person can edit. A rewrite that kept only the lines
    /// this parser understands would eat a comment left there, on the next vote,
    /// without saying anything.
    #[test]
    fn a_hand_written_line_in_the_drawer_survives_a_vote() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        voted(&layout, &id, "agent-a", "ship");

        // Someone edits the drawer by hand.
        let path = layout.project_issues_path("sample");
        let text = std::fs::read_to_string(&path).unwrap();
        let edited = text.replace(
            ":VOTES:\n",
            ":VOTES:\n# decided at the Tuesday review, do not clear\n",
        );
        std::fs::write(&path, edited).unwrap();

        voted(&layout, &id, "agent-b", "hold");

        let after = std::fs::read_to_string(&path).unwrap();
        assert!(
            after.contains("# decided at the Tuesday review, do not clear"),
            "the hand-written line was eaten: {after}"
        );
        assert!(after.contains("agent-a: ship"), "{after}");
        assert!(after.contains("agent-b: hold"), "{after}");
    }

    /// Two spellings of one file must lock it once. The process mutex is keyed on
    /// the canonical path, so a second lock on the same mutex is a self-deadlock
    /// and a second advisory lock on the same file blocks too. A mint locks every
    /// twin file now, so two roots that are links to one tree reach this.
    ///
    /// Written as a create rather than a unit test of the helper because the hang
    /// is what is being ruled out, and it has to be ruled out on the path callers
    /// take.
    ///
    /// Through a symlink, and that detail is the test. A first attempt used
    /// `dir/./PREFIX/...` against `dir/PREFIX/...` and passed with the bug still
    /// in, because `Path` compares by components and drops `.`, so the plain
    /// dedup already collapsed them. Only a link makes two paths that differ by
    /// components and name one file.
    #[cfg(unix)]
    #[test]
    fn one_file_named_two_ways_is_locked_once() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        let direct = layout.project_issues_path("sample");
        create(&layout, "sample", "first", CreateOpts::default()).unwrap();

        // A second name for the same tree, the way two configured roots can be.
        let link = dir.path().join("linked");
        std::os::unix::fs::symlink(dir.path().join(DEFAULT_PREFIX), &link).unwrap();
        let indirect = link.join("sample").join("issues.org");
        assert!(indirect.exists(), "the link does not reach the file");
        assert_ne!(
            direct.components().count(),
            0,
            "the two paths must differ by components or this proves nothing"
        );
        assert!(
            direct != indirect,
            "the two paths compare equal, so the plain dedup would already collapse them"
        );

        let twins = vec![direct.clone(), indirect];
        let id = create(
            &layout,
            "sample",
            "second",
            CreateOpts {
                quiet: true,
                extra_id_paths: &twins,
                ..Default::default()
            },
        )
        .expect("create hung or failed on an aliased lock path")
        .trim()
        .to_string();
        assert!(id.starts_with("sample-"), "{id}");
    }

    /// A drawer edited by hand can hold two lines for one agent. The tally counts
    /// on one ballot per agent, so the duplicate has to collapse rather than let
    /// one voter count twice.
    #[test]
    fn two_hand_written_lines_for_one_agent_collapse_to_the_last() {
        let dir = tempfile::tempdir().unwrap();
        let layout = fresh_layout(dir.path());
        create(&layout, "sample", "what to do", CreateOpts::default()).unwrap();
        let id = only_id(&layout, "sample");
        voted(&layout, &id, "agent-b", "hold");

        let path = layout.project_issues_path("sample");
        let text = std::fs::read_to_string(&path).unwrap();
        let edited = text.replace(
            ":VOTES:\n",
            ":VOTES:\n[2026-01-01 Thu] agent-a: ship\n[2026-02-02 Mon] agent-a: rework\n",
        );
        std::fs::write(&path, edited).unwrap();

        let tally = vote(&layout, &id, None, "reader").unwrap();
        // agent-a counts once, as rework, so two agents and two options.
        assert!(tally.contains("2 votes from 2 options"), "{tally}");
        assert!(tally.contains("rework"), "{tally}");
        assert!(!tally.contains("ship"), "{tally}");

        // And the rewrite leaves one line for that agent, not two.
        voted(&layout, &id, "agent-c", "hold");
        let after = std::fs::read_to_string(&path).unwrap();
        assert_eq!(after.matches("agent-a:").count(), 1, "{after}");
    }
}