vivac 0.15.7

Provenance tree for work: every node knows which node it was born from
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
//! The operations that write. Every one goes through the redaction guard.
//!
//! All but one refuse outright when it finds something. The exception is the
//! session opening: it is written by a hook, with no author present to reword
//! anything, so it replaces the field with the name of the rule that refused
//! it and writes the seam anyway. Losing the seam would cost more than the
//! field is worth, and a refusal that is recorded is not a refusal in silence.
//!
//! Capture hangs off the seams of the work, never off a judgement of
//! relevance. That is the one thing actually measured: over 170 real minutes,
//! `push`/`pop` --which cannot be skipped without leaving the work half done--
//! were called nine times, and the operation that asked "is this worth
//! keeping?" was called zero times, under a protocol declared mandatory.

use crate::anchor::{self, Anchor};
use crate::event::{Against, Arm, Body, Event, Flag, Kind, State, VivacKind};
use crate::failure::{Failure, R};
use crate::model::{fold, Node, Tree};
use crate::outcome::{self, Outcome};
use crate::params;
use crate::store::Store;
use crate::{id, redact};
use std::path::{Path, PathBuf};

/// Whose thread the context answers from, decided by the caller because
/// only the caller knows where the command was run.
pub enum Whose<'a> {
    /// What `store::locate` answered for the folder the command ran in.
    Resolved(&'a crate::store::Located),
    /// No resolution to go on: another project's tree read from outside,
    /// or a test. Answers as the founding lane, which is what every tree
    /// that exists today is, and never writes from anywhere else.
    Founding,
    /// The caller already decided which lane this is, and signs with it
    /// outright: `setup`, declaring a lane from its own `repos::scan`
    /// rather than from what the log already says. `t594`:
    /// without this, the only way to have `setup` sign as the lane it
    /// just planned was to build with `Founding` and overwrite `lane`,
    /// `tree` and `store` by hand afterwards -- an invariant that held
    /// only because someone remembered to keep the three assignments in
    /// step with `finish`. Never pending, and exempt from ยง6.9
    /// (`lock_for_write`): a folder the caller already named outright has
    /// nothing left for that refusal to protect, and `setup` is precisely
    /// the command ยง6.9's own message sends you to.
    ///
    /// Carries the lane's own folder alongside its id: a lane `setup`
    /// declares outright is not always the tree's own root -- a lane
    /// joined from elsewhere keeps its repositories relative to where it
    /// was joined from, not to the tree it joined. A first declaration
    /// never reads this back (`resolve_whose`'s own doc), but a
    /// redeclaration does, once the lane already has repositories in
    /// `tree.lanes` for `where_to_write` to look up.
    Declared(String, PathBuf),
}

/// A linked worktree that is nobody's lane yet. It becomes one the first
/// time anything writes from it, and not before: a worktree the harness
/// created and will throw away should not leave a lane behind for having
/// been looked at.
pub struct PendingLane {
    /// The worktree's own root, where its `.vivac/lane` goes.
    pub dir: PathBuf,
    /// The folder's name, **raw**: the redaction guard runs in `emit`
    /// instead of here (`t594`), because only there does
    /// the id that `lane::name_for` decorates the fallback with already
    /// exist. Never written to disk unguarded -- `emit` is the only
    /// reader, and it never forwards this without checking it first.
    pub name: String,
    /// Always `{ path: ".", root }`: a worktree is one repository, itself.
    /// `root` is the root commit **the lane that holds this repository
    /// already declared**, never asked of git again -- the datum is in the
    /// log, and this runs on the write path.
    pub repo: crate::event::Repo,
}

/// The view a pending lane's own `Ctx` reads from until it joins: a key
/// that can never be a real lane's (`lane::MAIN`, or a ULID `lane::new_id`
/// mints), so `Tree::state` and everything built on it answers empty
/// rather than as whatever `main` happens to hold. `t594` ยง2.3, rule 3:
/// "its stack is empty, its focus does not exist and the brief has no
/// HERE" is exactly what `Tree::for_lane` already gives a lane nobody
/// wrote to; this only has to pick a key nobody ever will.
const PENDING_VIEW: &str = "";

pub struct Ctx {
    pub store: Store,
    /// The lane this context runs as: `Some(lane::MAIN)` for a tree's own
    /// folder, the lane's own id for any other, and `None` for a linked
    /// worktree that has not joined the tree yet (`pending_lane` is what
    /// tells the two apart -- the founding lane is never `None`, `t594`
    /// ยง2.3). Set by every constructor, and applied to `store` there too:
    /// the store is what signs every event, so a `Ctx` and the events it
    /// writes never disagree about whose thread they are.
    pub lane: Option<String>,
    /// The folder this lane's declared repositories are relative to:
    /// `Located.lane_dir` for a lane resolved from a folder, the store's
    /// own root for the founding lane, and whatever folder the caller
    /// named alongside it for a lane it already named outright (`setup`,
    /// `--join`) -- its own folder when that is not the tree's root
    /// either. Set once at construction, and updated only where a
    /// pending lane joins inside `emit` -- never re-resolved from a
    /// folder, and never asked of git. `where_to_write` is the only
    /// reader (`t594` tramo 4, task 3).
    pub lane_dir: PathBuf,
    pub tree: Tree,
    pub anchor: Box<dyn Anchor>,
    /// The log's fingerprint taken **before** it was read: a write that
    /// lands between that read and `lock_for_write` changes it, and a
    /// write that landed just before is folded in anyway and only costs
    /// one needless reload.
    pub seen: (u64, Option<std::time::SystemTime>),
    /// What the last `emit` wrote, so a caller keeping a resident tree
    /// never has to read the log back to learn where its own writes
    /// landed (`f599`).
    pub wrote: Option<crate::store::Appended>,
    /// The write lock, once `lock_for_write` has taken it. `None` until
    /// then, and set back to `None` by `unlock`.
    pub lock: Option<crate::store::WriteLock>,
    /// A linked worktree decided (`resolve_whose`) to be nobody's lane yet.
    /// Read and cleared inside `emit`, which mints the id, writes the
    /// file and declares it in the very same append -- and nowhere
    /// earlier: `lock_for_write` runs before an operation knows whether
    /// it has anything to write at all, and joining there left a lane
    /// file and a `lane.declared` behind a command that changed nothing
    /// (`t594`).
    pending_lane: Option<PendingLane>,
    /// Whether the caller already decided this lane (`Whose::Declared`)
    /// rather than it being resolved from a folder. ยง6.9's refusal
    /// (`lock_for_write`) exists for a folder that resolved to `main` on
    /// its own; it does not apply here, because the one caller that ever
    /// sets this is `setup`, the command ยง6.9's own message names as the
    /// way out (`t594`).
    caller_declared: bool,
    /// Whether `lane` is only a fallback -- no `.vivac/lane` file backs it
    /// up -- rather than read off one that actually names it.
    ///
    /// ยง6.9's own sentence is about the first case: "a folder that holds
    /// the tree, has no lane file of its own and answers as `main` only
    /// because nothing said otherwise". The check below used to ask a
    /// narrower question than that sentence -- whether `lane` spelled
    /// `main`, not whether anything was actually read -- and the two only
    /// ever agreed because, until `relocate` (`t594` ยง4.6), no folder's own
    /// `.vivac/lane` file had ever named `main`: the first one it writes,
    /// at the folder a tree moved out of, would have been refused by a
    /// check built to catch the folder with no file at all.
    lane_assumed: bool,
}

impl Ctx {
    /// The only place `self.tree` is ever replaced. Whatever rebuilt it --
    /// a fresh fold, a reload from the index, one folded from events
    /// already read -- the context keeps looking from its own lane:
    /// `self.lane` is the folder's and does not move just because the tree
    /// underneath it did. Two call sites used to assign `self.tree`
    /// directly and disagreed about this, one of them only under lock
    /// contention (`t594`): a reload nobody routed
    /// through here answers from `main` while the store keeps signing as
    /// whatever lane this context actually is.
    fn adopt(&mut self, tree: Tree) {
        self.tree = tree;
        match &self.lane {
            Some(l) => self.tree.for_lane(l),
            // A worktree waiting to join reads from a key nobody has ever
            // written to, not from `main`'s: `t594` ยง2.3 rule 3 wants its
            // stack empty and its brief without a HERE, and this is what
            // gives it that without inventing a second way to ask for it.
            None if self.pending_lane.is_some() => self.tree.for_lane(PENDING_VIEW),
            None => {}
        }
    }

    /// Finishes building a `Ctx` once its tree is already folded and
    /// `resolve_whose` has already decided whose lane it runs as. Shared by
    /// every constructor below. `store` carries no lane of its own to set
    /// here any more (`f608`, third time -- see `Store::append`'s own doc):
    /// `self.lane` is the only copy, and `emit` is what hands it to
    /// `append` on every write, so a `Ctx` and what it writes cannot drift
    /// apart the way a `Store` left holding a stale one could.
    fn finish(
        store: Store,
        tree: Tree,
        seen: (u64, Option<std::time::SystemTime>),
        whose_lane: WhoseLane,
    ) -> Ctx {
        let anchor = anchor::detect(&store.root);
        let mut ctx = Ctx {
            store,
            lane: whose_lane.lane,
            lane_dir: whose_lane.lane_dir,
            tree: Tree::default(),
            anchor,
            seen,
            wrote: None,
            lock: None,
            pending_lane: whose_lane.pending_lane,
            caller_declared: whose_lane.caller_declared,
            lane_assumed: whose_lane.lane_assumed,
        };
        ctx.adopt(tree);
        ctx
    }

    /// For a command that only ever reads. `LOADING.md` ยง4: this is a read,
    /// so it is free to refresh the derived index once its tail passes the
    /// threshold -- see `index::load`.
    pub fn load(store: Store, whose: Whose) -> Result<Ctx, Failure> {
        Ctx::load_opt(store, true, whose)
    }

    /// For a command that may append to the log. Still free to read a warm
    /// or stale index -- applying its tail is cheap enough for the write
    /// budget -- but it must never pay to rewrite the file itself
    /// (`LOADING.md` ยง4 "Cuรกndo se reescribe").
    pub fn load_for_write(store: Store, whose: Whose) -> Result<Ctx, Failure> {
        Ctx::load_opt(store, false, whose)
    }

    fn load_opt(store: Store, allow_index_refresh: bool, whose: Whose) -> Result<Ctx, Failure> {
        let seen = crate::store::fingerprint(&store.log());
        let tree = crate::index::load(&store, allow_index_refresh)?;
        // `t594` ยง2.3: whose lane a folder is needs the tree already
        // folded -- it depends on the repositories a lane declared, and
        // that is in the log -- so it is decided here, and nowhere else.
        // `t594`: read off the fold itself, not `config`'s
        // own sentence, which can say either more or less than the log
        // actually backs up (`Tree::has_a_declared_lane`'s own doc).
        let tree_has_lanes = tree.has_a_declared_lane();
        let whose_lane = resolve_whose(whose, &tree, tree_has_lanes, &store.root);
        Ok(Ctx::finish(store, tree, seen, whose_lane))
    }

    /// Same read `changes` and `why` need, handing back the events instead
    /// of dropping them. Both need the log's own fields -- `actor`, `lane`,
    /// the exact payload -- which the derived index does not carry, so this
    /// always folds the whole log rather than going through `index::load`:
    /// there is no tail to apply that would save the read those two need
    /// anyway.
    pub fn load_with_log(store: Store, whose: Whose) -> Result<(Ctx, Vec<Event>), Failure> {
        let seen = crate::store::fingerprint(&store.log());
        let (events, broken) = store.read_all()?;
        let tree = fold(&events, broken);
        let tree_has_lanes = tree.has_a_declared_lane();
        let whose_lane = resolve_whose(whose, &tree, tree_has_lanes, &store.root);
        let ctx = Ctx::finish(store, tree, seen, whose_lane);
        Ok((ctx, events))
    }

    /// A `Ctx` over events already read, for a caller that keeps them --
    /// `project.rs`'s resident tree among them. `t594`:
    /// this used to keep its own `Option<String>`, "answer as the founding
    /// lane" spelled as `None` rather than as `Whose::Founding` -- the
    /// exact ambiguity the enum exists to rule out -- and a worktree
    /// joined by the CLI kept answering as `main` the moment it was
    /// served by `vivac mcp` or `vivac web` instead. `Registry::open`
    /// decides the `Whose` for each root it opens, `Resolved` for the one
    /// the process started in and `Founding` for every other.
    pub fn from_events(
        store: Store,
        events: &[Event],
        broken: usize,
        seen: (u64, Option<std::time::SystemTime>),
        whose: Whose,
    ) -> Ctx {
        let tree = fold(events, broken);
        let tree_has_lanes = tree.has_a_declared_lane();
        let whose_lane = resolve_whose(whose, &tree, tree_has_lanes, &store.root);
        Ctx::finish(store, tree, seen, whose_lane)
    }

    /// Replaces what this context knows about the tree -- the store handle, the
    /// folded tree and the fingerprint it was folded at -- without replacing the
    /// context itself. The write lock, which belongs to the caller's turn and
    /// not to the fold, survives: replacing the whole context mid-write would
    /// drop the lock on the floor and leave the write running with nothing
    /// holding the tree (`f602`). `wrote` does not survive -- it is the record
    /// of one particular write, and a fold triggered by a read that happens to
    /// run between two writes must not leave a stale one behind for the next
    /// `emit` to append to.
    pub fn refold(
        &mut self,
        store: Store,
        events: &[Event],
        broken: usize,
        seen: (u64, Option<std::time::SystemTime>),
    ) {
        self.store = store;
        // `adopt`, not a direct assignment: `self.lane` is the context's
        // own and does not move just because the tree underneath it did.
        self.adopt(fold(events, broken));
        self.anchor = anchor::detect(&self.store.root);
        self.seen = seen;
        self.wrote = None;
    }

    /// Takes the tree's write lock (`d598`) and brings the tree up to date.
    /// **Idempotent**: a `Ctx` that already holds it returns without taking it
    /// again, so an operation that locks on its own inside a caller that
    /// already locked does not wait five seconds for itself (`f602`).
    ///
    /// Returns whether *this* call is the one that took it. An operation that
    /// locks on its own releases only what it took: releasing a lock somebody
    /// above it is still holding would leave that caller writing with nothing
    /// holding the tree, which is the same bug the argument to `append` exists
    /// to make impossible.
    pub fn lock_for_write(&mut self) -> Result<bool, Failure> {
        if self.lock.is_some() {
            return Ok(false);
        }
        // `t594` ยง2.3 rule 3, and ยง6.9: a folder that holds the tree, has
        // no lane file of its own and answers as `main` only because
        // nothing said otherwise is fine -- until some other folder has
        // claimed `main` for itself (`lane.claimed`, `d597`), at which
        // point this one can still be read but must not write. Checked
        // before the lock is even taken, so a read never pays for it and a
        // refusal never has to let go of one. `caller_declared` exempts a
        // lane the caller already named outright (`Whose::Declared`):
        // `setup` is the only caller that ever sets it, and it is the
        // very command ยง6.9's own message sends you to -- refusing it too
        // would be a message that answers itself (`t594`).
        //
        // `lane_assumed`, not just the word `main`: the sentence above is
        // about a folder with nothing on disk to back up its answer, and
        // until `relocate` (`t594` ยง4.6) that was the only way `lane` ever
        // came out as `main` once `main_claimed` was true, so checking the
        // word alone happened to agree with checking the file. `relocate`
        // is the first thing that writes a `.vivac/lane` naming `main`
        // itself, at the folder a tree moves out of, and that folder is
        // exactly one of the tree's lanes -- the sentence's own exception,
        // not its target.
        if !self.caller_declared
            && self.lane_assumed
            && self.lane.as_deref() == Some(crate::lane::MAIN)
            && self.tree.main_claimed
        {
            return Err(Failure::not_a_lane());
        }
        let lock = self.store.lock_for_write()?;
        let now = crate::store::fingerprint(&self.store.log());
        if now != self.seen {
            // `adopt`, not a direct assignment (`t594`):
            // this is the reload a second writer's append forces, and it
            // used to leave this context reading `main` while its store
            // kept signing as whatever lane it actually is.
            self.adopt(crate::index::load(&self.store, false)?);
            self.seen = now;
        }
        self.lock = Some(lock);
        Ok(true)
    }

    /// Whether this context currently holds the write lock. Only the tests
    /// read it, the same way only they read `Project::full_folds`: nothing
    /// else needs to ask, since every caller either took the lock itself or
    /// trusts the one that did.
    #[cfg(test)]
    pub fn holds_write_lock(&self) -> bool {
        self.lock.is_some()
    }

    /// Releases the write lock. The CLI never calls it -- the process ends and
    /// the operating system lets go -- and the resident server calls it after
    /// every write, because it outlives its own writes.
    pub fn unlock(&mut self) {
        self.lock = None;
    }

    /// Writes and **then applies in memory**, so that whatever gets printed
    /// next is the state after the operation and not the one before it.
    /// What is applied is what was written, stamp included, which is what a
    /// fresh fold of the log would apply (`f590`).
    fn emit(&mut self, bodies: Vec<Body>) -> R {
        let mut bodies = bodies;
        // `t594` ยง2.3 rule 3, step 3, moved here from where it
        // used to sit: a worktree joins the moment something actually
        // writes, never merely because the write lock was taken.
        // `lock_for_write` runs before an operation even knows whether it
        // has anything to write -- `pop` on an empty stack, a `note`
        // naming an id that does not resolve, the redaction guard
        // refusing -- and joining there left a lane file, a
        // `lane.declared` and a locked config behind a command that
        // changed nothing. `emit` is the one place that is only ever
        // reached once there is something real to append, so joining
        // here and declaring it happen in the very same call: the two
        // land together or neither does.
        if let Some(pending) = &self.pending_lane {
            let dir = pending.dir.clone();
            let folder_name = pending.name.clone();
            let repo = pending.repo.clone();
            let lock = self.lock.as_ref().ok_or_else(|| {
                Failure::Io(std::io::Error::other("write without the tree's lock"))
            })?;
            // `t594`: `pending_lane` was decided before
            // this lock was even taken, and `lock_for_write`'s own reload
            // re-plays the tree but never asks again whose folder this
            // is. Two processes that both resolve pending before either
            // writes -- the `SessionStart` hook and the first `push` an
            // MCP client sends, a very ordinary pair -- would otherwise
            // each mint an id of their own; the file keeps the second,
            // and everything the first wrote -- its stack, its focus,
            // its counters -- sits behind an id nobody ever reads again,
            // invisible to `check`. Reading the file again here, with
            // the lock already held, is the one place left that can
            // still catch the other writer: if it is there now, this
            // adopts it and signs with it, rather than declaring a
            // second lane for the same folder.
            if let Some(joined) = crate::lane::read(&dir.join(crate::store::DIR))? {
                self.lane = Some(joined.id.clone());
                self.lane_dir = dir.clone();
                self.tree.for_lane(&joined.id);
                self.pending_lane = None;
            } else {
                self.store.lock_lanes_in_config(lock)?;
                // `t594`: a worktree only ever gets this
                // far when the tree already has a lane declared
                // somewhere, which means at least one event already
                // exists -- so there is nothing left to seed here, and
                // the question of whether an empty `repos` list would
                // have lied about one does not arise either.
                //
                // This should be unreachable now that `tree_has_lanes`
                // reads `Tree::has_a_declared_lane`, the fold itself,
                // rather than `config`'s own sentence (`t594`):
                // a declared lane is an event, so a
                // pending worktree can only exist once there is a first
                // one to read here. It was reachable when `config` was
                // the question instead -- `config` outliving a log a
                // crash or a hand-deleted `events` left with nothing in
                // it, `main` still claiming lanes existed when nothing
                // any more said which one. A `Failure` and not another
                // `expect`, so the day something moves this gate again
                // without moving this along with it, the answer is a
                // sentence and not a panic with a backtrace.
                let Some(project) = crate::store::first_event_id(&self.store.root) else {
                    return Err(Failure::Io(std::io::Error::other(
                        "This tree says a lane was declared, but its log has no first \
                         event to found a new one on. Run this from the tree's own \
                         folder first: an ordinary write there recovers a log that was \
                         deleted or emptied, the same way it always has.",
                    )));
                };
                let id = crate::lane::new_id();
                let lane_file = crate::lane::Lane {
                    version: 1,
                    id: id.clone(),
                    project,
                };
                crate::lane::write(&dir.join(crate::store::DIR), &lane_file)?;
                self.lane = Some(id.clone());
                self.lane_dir = dir.clone();
                self.tree.for_lane(&id);
                self.pending_lane = None;
                // `t594`: redacted here, not when the
                // pending lane was first noticed, because only here does
                // the id exist to decorate the fallback with. Goes
                // through `lane::declared_name`, the one place this rule
                // is written (`t594`), the same as
                // `setup` already does, so two redacted lanes on the
                // same tree no longer share the bare word `lane`.
                let name = crate::lane::declared_name(&id, &folder_name);
                bodies.insert(
                    0,
                    Body::LaneDeclared {
                        lane: id,
                        name,
                        repos: vec![repo],
                    },
                );
            }
        }
        // `d444`: the one bit `Store::append`'s own write-lock needs and
        // cannot see for itself -- whether this tree already has a pillar
        // or a rule, from a write before this one.
        let already_governed = self.tree.has_governance;
        let lock = self
            .lock
            .as_ref()
            .ok_or_else(|| Failure::Io(std::io::Error::other("write without the tree's lock")))?;
        let lane = self.lane.as_deref().unwrap_or(crate::lane::MAIN);
        // Inside the lock and ahead of the operation's own events, so the
        // log reads in the order the work happened: the lane is declared,
        // then it says where it is, then it writes (ยง2.5).
        if let Some(w) = where_to_write(&self.tree, lane, &self.lane_dir) {
            bodies.insert(0, w);
        }
        let appended = self
            .store
            .append(lock, lane, bodies, self.tree.seq, already_governed)?;
        for e in &appended.events {
            self.tree.apply(e.seq, &e.ts, &e.lane, &e.payload);
        }
        self.seen = crate::store::fingerprint(&self.store.log());
        // Kept for a caller that maintains a resident tree (`f599`): more
        // than one `emit` can run under a single `Project::write`, so a
        // second append's events join the first's and its own offsets win.
        // An `emit` that wrote nothing -- `focus` and `restore` can, though
        // no MCP tool reaches either today -- leaves `wrote` exactly as it
        // was: there is nothing new to fold in, and an empty append's own
        // offsets would only overwrite a real one's with a no-op.
        if !appended.events.is_empty() {
            match self.wrote.take() {
                Some(mut w) => {
                    w.events.extend(appended.events);
                    w.last_line_offset = appended.last_line_offset;
                    w.end_offset = appended.end_offset;
                    self.wrote = Some(w);
                }
                None => self.wrote = Some(appended),
            }
        }
        Ok(())
    }

    fn resolve(&self, s: &str) -> Result<&crate::model::Node, Failure> {
        self.tree
            .resolve(s)
            .ok_or_else(|| Failure::usage(format!("No such node: {s}.")))
    }
}

/// What `resolve_whose` decided, bundled rather than a tuple: a fourth
/// element (`lane_assumed`) is one past what a tuple keeps readable as
/// which field is which.
struct WhoseLane {
    lane: Option<String>,
    pending_lane: Option<PendingLane>,
    /// See `Whose::Declared` and `Ctx::caller_declared`.
    caller_declared: bool,
    /// See `Ctx::lane_assumed`.
    lane_assumed: bool,
    /// See `Ctx::lane_dir`.
    lane_dir: PathBuf,
}

/// `t594` ยง2.3, step 1: decides whose lane a folder is, once its tree is
/// already folded, whether the caller already named it outright, and
/// whether `lane` is only a fallback with no `.vivac/lane` file behind it
/// (`WhoseLane::lane_assumed` -- `t594` ยง4.6, review round 1: the check this
/// used to feed `lock_for_write` a plain tuple for could not tell "answers
/// `main` because nothing said otherwise" apart from "answers `main`
/// because its own file says so", and only the first is what ยง6.9 is
/// about). `Whose::Founding` and `Whose::Declared` never have anything to
/// decide -- there is no `Located` to read a worktree off -- and never
/// leave a lane pending. `Founding` counts as assumed: it never had a
/// `Located` to read a lane file off in the first place. `Declared` is
/// exempt from ยง6.9 (`lock_for_write`) outright, regardless of
/// `lane_assumed`: it is the one case where the caller, not a resolved
/// folder, is the reason this answers as it does.
///
/// For `Whose::Resolved`, three cases:
///
/// 1. `Located.worktree` is `None`: the lane is `Located`'s, as it always
///    was before this task.
/// 2. It is `Some(w)` and `w` is one of the repositories the lane found
///    already declared: still `Located`'s lane. The worktree is that
///    lane's own repository at that path, and nothing more.
/// 3. It is `Some(w)`, it is not, **and `tree_has_lanes`**: `w` is another
///    lane, pending until it writes.
///
/// `tree_has_lanes` gates case 3 on purpose (`t594`): it
/// is the justification the task that built this already wrote down --
/// "only happens when the repository already declared a lane" -- and
/// never wired in. Without it, `session.started` alone -- a hook, not a
/// person, and one `.claude/settings.json` usually ships versioned so a
/// worktree the harness throws away can fire it before anyone runs
/// `setup` anywhere -- silently converts a tree nobody asked to convert.
/// With it, a worktree over a tree that has never had a lane declared
/// reads as `Located`'s lane, same as case 1, and writes nothing of its
/// own until a real lane exists to check it against.
///
/// `lane_assumed` is fixed once, from `located.lane.is_none()`, ahead of
/// all three cases: none of them touches whether `Located` itself carried
/// a lane file, only what a worktree underneath it is doing.
fn resolve_whose(whose: Whose, tree: &Tree, tree_has_lanes: bool, store_root: &Path) -> WhoseLane {
    let located = match whose {
        // Neither has a `Located` to read a lane's own folder off.
        Whose::Founding => {
            // The founding lane's folder is the tree's own root by
            // definition (`Located::lane_dir`'s own doc): there is no
            // other folder it could ever be.
            return WhoseLane {
                lane: Some(crate::lane::MAIN.to_string()),
                pending_lane: None,
                caller_declared: false,
                lane_assumed: true,
                lane_dir: store_root.to_path_buf(),
            };
        }
        Whose::Declared(id, lane_dir) => {
            // A redeclaration -- the lane already has repositories in
            // `tree.lanes` -- reads this back through `where_to_write`,
            // so it has to be the lane's own folder, not `store_root`:
            // for a lane joined from elsewhere the two are not the same,
            // and resolving its repositories against the tree root
            // instead of its own finds nothing there and reports every
            // one of them missing.
            return WhoseLane {
                lane: Some(id),
                pending_lane: None,
                caller_declared: true,
                lane_assumed: false,
                lane_dir,
            };
        }
        Whose::Resolved(l) => l,
    };
    let lane_assumed = located.lane.is_none();
    let lane_dir = located.lane_dir.clone();
    let found_lane = located
        .lane
        .as_ref()
        .map(|l| l.id.clone())
        .unwrap_or_else(|| crate::lane::MAIN.to_string());
    let Some(w) = located.worktree.as_ref() else {
        return WhoseLane {
            lane: Some(found_lane),
            pending_lane: None,
            caller_declared: false,
            lane_assumed,
            lane_dir,
        };
    };
    let declared: &[crate::event::Repo] = tree
        .lanes
        .get(&found_lane)
        .map(|s| s.repos.as_slice())
        .unwrap_or(&[]);
    if repo_at(declared, &located.lane_dir, w).is_some() {
        return WhoseLane {
            lane: Some(found_lane),
            pending_lane: None,
            caller_declared: false,
            lane_assumed,
            lane_dir,
        };
    }
    if !tree_has_lanes {
        return WhoseLane {
            lane: Some(found_lane),
            pending_lane: None,
            caller_declared: false,
            lane_assumed,
            lane_dir,
        };
    }
    // Step 4: the root commit is whatever the lane already declared for
    // the repository whose `.git` is this worktree's `commondir` -- never
    // asked of git again, since the datum is already in the log and this
    // runs on the write path.
    let root = anchor::main_copy_of(w).and_then(|main_root| {
        repo_at(declared, &located.lane_dir, &main_root).and_then(|r| r.root.clone())
    });
    let folder_name = w
        .file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default();
    WhoseLane {
        lane: None,
        pending_lane: Some(PendingLane {
            dir: w.clone(),
            // `d600`'s own guard runs in `emit`, not here (`t594`):
            // see `PendingLane::name`.
            name: folder_name,
            repo: crate::event::Repo {
                path: ".".to_string(),
                root,
            },
        }),
        caller_declared: false,
        lane_assumed,
        lane_dir,
    }
}

/// The declared repository, if any, whose path resolves to `target` once
/// joined to `lane_dir`: `anchor::main_copy_of`'s own criterion (`t594`
/// task 4). `anchor::same_folder` is what decides it -- this is the
/// comparison `f612` was first found in, between a path this process
/// joined by hand and one read out of files git itself wrote, so a case
/// difference or an 8.3 alias (what a Windows CI runner's own temp
/// directory actually handed out) makes the two disagree textually while
/// still naming the same folder.
fn repo_at<'a>(
    declared: &'a [crate::event::Repo],
    lane_dir: &Path,
    target: &Path,
) -> Option<&'a crate::event::Repo> {
    declared
        .iter()
        .find(|r| anchor::same_folder(&lane_dir.join(&r.path), target))
}

/// The `where.changed` this write has to carry, if any. A complete
/// photograph of the lane's declared repositories, compared against the
/// last one the lane wrote: a branch that differs, a detached sha that
/// differs with no rebase under way, or a repository that appeared or
/// vanished (ยง2.5). A new commit on the same branch is not a difference --
/// the sha inside a branch is what the stops anchor (ยง4.4).
fn where_to_write(tree: &Tree, lane: &str, lane_dir: &Path) -> Option<Body> {
    let declared = &tree.lanes.get(lane)?.repos;
    if declared.is_empty() {
        return None;
    }
    let now: Vec<crate::event::WhereRepo> =
        declared.iter().map(|r| snapshot_of(lane_dir, r)).collect();
    let last = tree.wheres.iter().rfind(|w| w.lane == lane);
    match last {
        Some(w) if !moved(&w.repos, &now) => None,
        _ => Some(Body::WhereChanged { repos: now }),
    }
}

/// Whether two photographs say the lane is somewhere else. Compares what
/// the lane is *on* -- the branch, the repository's presence, and the sha
/// only where there is no branch to name and no rebase moving it.
fn moved(before: &[crate::event::WhereRepo], now: &[crate::event::WhereRepo]) -> bool {
    if before.len() != now.len() {
        return true;
    }
    before.iter().zip(now).any(|(b, n)| {
        b.path != n.path
            || b.branch != n.branch
            || b.missing != n.missing
            || b.withheld != n.withheld
            || (b.branch.is_none() && !n.rebasing && b.sha != n.sha)
    })
}

/// One repository's line in the photograph, with the branch name run past
/// the redaction guard. A name the guard refuses is withheld rather than
/// refused: the pillar's "in doubt, refuse the write" was written for
/// prose somebody can rephrase, and a branch name is not ours to rewrite.
/// Withholding keeps both halves of it -- the secret stays out and the
/// write goes through (`d600`).
fn snapshot_of(lane_dir: &Path, r: &crate::event::Repo) -> crate::event::WhereRepo {
    let mut out = crate::event::WhereRepo {
        path: r.path.clone(),
        ..Default::default()
    };
    match anchor::where_of(&lane_dir.join(&r.path)) {
        anchor::Where::Missing => out.missing = true,
        anchor::Where::Head(h) => {
            out.sha = h.sha;
            out.rebasing = h.rebasing;
            match h.branch {
                Some(b) if redact::check_field("branch", &b).is_some() => out.withheld = true,
                b => out.branch = b,
            }
        }
    }
    out
}

/// One `RepoAnchor` per repository the lane has declared and that has a
/// commit to anchor to: this is `f613`'s own fix, replacing "is this
/// folder a repository?" -- `Ctx.anchor`'s own question, still `Null` at a
/// root that holds no git of its own -- with "what has the lane declared
/// underneath it?" A repository with no commit yet, or whose folder is
/// gone, contributes nothing: there is no commit to point at. A lane with
/// no declared repositories -- a tree nobody ran `setup` in, or a
/// worktree still pending -- gets the empty list, and the vivac keeps
/// reading as `anchor` alone (ยง4.4, `f25`).
fn anchors_of(ctx: &Ctx) -> Vec<crate::event::RepoAnchor> {
    let Some(lane) = ctx.lane.as_deref() else {
        return vec![];
    };
    let Some(state) = ctx.tree.lanes.get(lane) else {
        return vec![];
    };
    state
        .repos
        .iter()
        .filter_map(|r| {
            let anchor::Where::Head(h) = anchor::where_of(&ctx.lane_dir.join(&r.path)) else {
                return None;
            };
            let sha = h.sha?;
            // A branch name the redaction guard refuses is left out rather
            // than kept under a flag `RepoAnchor` has no room for (ยง4.4):
            // the sha alone still anchors the vivac, and the write is
            // never blocked over a name that was never ours to reword.
            let branch = match h.branch {
                Some(b) if redact::check_field("branch", &b).is_some() => None,
                b => b,
            };
            Some(crate::event::RepoAnchor {
                path: r.path.clone(),
                branch,
                sha,
            })
        })
        .collect()
}

/// Builds a vivac out of the stack as it stands right now.
///
/// The `working_set` is **not measured**: measuring which files the pitch
/// touched would need a `post_tool` hook, which is not in Tier 0. It is
/// derived from the `governs` the stack declares, which is what there is, and
/// the `brief` says so rather than pretending it observed it.
fn vivac(
    ctx: &Ctx,
    kind: VivacKind,
    next_intent: &str,
    node_ref: Option<String>,
    label: &str,
) -> Body {
    let stack: Vec<(String, String)> = ctx
        .tree
        .stack()
        .iter()
        .filter_map(|&num| ctx.tree.node_by_num(num))
        .map(|n| (n.alias(), n.title(&ctx.tree).to_string()))
        .collect();
    let mut working_set: Vec<String> = ctx
        .tree
        .stack()
        .iter()
        .filter_map(|&num| ctx.tree.node_by_num(num))
        .flat_map(|n| n.governs(&ctx.tree).into_iter().map(str::to_string))
        .collect();
    working_set.sort();
    working_set.dedup();
    Body::VivacCreated {
        vivac: id::ulid(),
        num: ctx.tree.next_vivac_num.max(1),
        kind,
        stack,
        working_set,
        next_intent: next_intent.to_string(),
        anchor: ctx.anchor.snapshot(),
        anchors: anchors_of(ctx),
        node_ref,
        label: label.to_string(),
    }
}

/// No text reaches the log without coming through here.
fn guard_text(fields: &[(&str, &str)]) -> R {
    match redact::check_fields(fields) {
        Some(h) => Err(Failure::Redaction(Box::new(h))),
        None => Ok(()),
    }
}

/// Text off an untrusted payload, made safe to store without failing the
/// write. What the guard objected to never gets in; what replaces it names
/// the rule and nothing else, so the log shows that a refusal happened
/// without repeating what caused it.
fn guarded_or_refused(field: &str, text: &str) -> String {
    match redact::check_field(field, text) {
        Some(f) => format!("refused: {}", f.rule),
        None => text.to_string(),
    }
}

/// `--root` given together with `--parent` on `add`, `decide` or `push`:
/// both name where a node is born, and a node is born in one place. `t533`
/// ยง1.1, `d757` for `push`.
fn root_and_parent_error() -> Failure {
    Failure::usage(
        "--root and --parent both say where it is born, and a node is born in one place.\n  \
         Keep the one you mean.",
    )
}

/// The node `push --parent` names, resolved and checked open. Opening under
/// a closed or abandoned node would silently reopen a claim nobody made;
/// opening under a parked one would silently take back what somebody put
/// off. `d757`.
fn open_parent(ctx: &Ctx, id: &str) -> Result<crate::model::Node, Failure> {
    let n = ctx.resolve(id)?.clone();
    if n.state == State::Suspended {
        return Err(Failure::Model(format!(
            "  {} is parked. New work does not open under it until someone takes it back.\n\n  \
             To take it back:  vivac focus {}",
            n.alias(),
            n.num
        )));
    }
    if !n.state.is_open() {
        return Err(Failure::Model(format!(
            "  {} is {}. New work does not open under it.\n\n  \
             If it really was not finished:  vivac focus {} --reopen",
            n.alias(),
            n.state.word(n.kind),
            n.num
        )));
    }
    Ok(n)
}

/// The stack's own nodes not on `num`'s path, and that path's own nodes not
/// yet on the stack -- each kept in its source's own order, so a caller
/// decides for itself how a `Popped` or a `Pushed` per node reads in the
/// log. Shared by `focus`, stepping back onto an existing node, and `push
/// --parent`, opening new work under one instead (`d757`).
fn stack_to(ctx: &Ctx, num: u64) -> (Vec<u64>, Vec<(u64, String)>) {
    let lineage: Vec<(u64, String)> = ctx
        .tree
        .ancestors(num)
        .iter()
        .map(|n| (n.num, n.id.clone()))
        .collect();
    let to_pop: Vec<u64> = ctx
        .tree
        .stack()
        .iter()
        .copied()
        .filter(|n| !lineage.iter().any(|(lineage_num, _)| lineage_num == n))
        .collect();
    let to_push: Vec<(u64, String)> = lineage
        .into_iter()
        .filter(|(n, _)| !ctx.tree.stack().contains(n))
        .collect();
    (to_pop, to_push)
}

fn kind_of(raw: Option<&str>, fallback: Kind) -> Result<Kind, Failure> {
    match raw {
        None => Ok(fallback),
        Some(s) => Kind::parse(s)
            .ok_or_else(|| Failure::usage(format!("Unknown type: {s}. They are: {}", Kind::ALL))),
    }
}

/// The same guard `note` is held to: one line, not empty. `d415`.
fn validate_arm_text(s: &str) -> Result<(), Failure> {
    if s.trim().is_empty() {
        return Err(Failure::usage("An arm cannot be empty."));
    }
    if s.contains('\n') {
        return Err(Failure::usage(
            "An arm is one line: write it the way it would be typed.",
        ));
    }
    Ok(())
}

/// Is this slashed-and-unnormalized folder absolute? Checked on every
/// system regardless of which one is running, per `d441`: the log travels,
/// and a path only Windows would call absolute still carries this machine's
/// layout once it lands somewhere else.
fn is_absolute_arm_dir(slashed: &str) -> bool {
    if slashed.starts_with('/') || slashed.starts_with('~') {
        return true;
    }
    let mut chars = slashed.chars();
    matches!(
        (chars.next(), chars.next()),
        (Some(letter), Some(':')) if letter.is_ascii_alphabetic()
    )
}

/// `./vivac/` -> `vivac`; `vivac\src` (already slashed to `vivac/src`) stays
/// `vivac/src`; `.`, `./` or `.\` (slashed to `./`) -> `.`. `d441`.
fn normalize_arm_dir(slashed: &str) -> String {
    let parts: Vec<&str> = slashed
        .split('/')
        .filter(|c| !c.is_empty() && *c != ".")
        .collect();
    if parts.is_empty() {
        ".".to_string()
    } else {
        parts.join("/")
    }
}

/// Checks 3 through 6 of `d441`'s six, shared by `--arm-dir` (`add`, `push`)
/// and `--dir` (`arm`): once a folder is known to have been given at all --
/// check 1 or 2, which differ in wording by caller -- absolute, `..`,
/// redaction and existence are the same check regardless of which flag
/// named it.
fn validate_arm_dir(raw: &str, tree_root: &Path) -> Result<String, Failure> {
    let slashed = raw.replace('\\', "/");
    if is_absolute_arm_dir(&slashed) {
        return Err(Failure::usage(
            "An arm's folder is relative to the one that holds .vivac: an \
             absolute path would write this machine's layout into the log.",
        ));
    }
    if slashed.split('/').any(|c| c == "..") {
        return Err(Failure::usage(
            "An arm's folder has to be inside the one that holds .vivac.",
        ));
    }
    let normalized = normalize_arm_dir(&slashed);
    guard_text(&[("dir", &normalized)])?;
    if !tree_root.join(&normalized).is_dir() {
        return Err(Failure::usage(format!(
            "There is no folder {normalized} inside the one that holds .vivac."
        )));
    }
    Ok(normalized)
}

/// The wording of the missing-folder and folder-without-arm messages, in the
/// two vocabularies a flag can be named in: the CLI's own `--flag`, and
/// MCP's bare argument name. ยง21: "the same texts, with `arm_dir` in place
/// of `--arm-dir`, `dir` in place of `--dir` and `arm` in place of `--arm`."
fn needs_arm_dir_message(via_mcp: bool) -> String {
    let flag = if via_mcp { "arm_dir" } else { "--arm-dir" };
    format!(
        "An arm needs {flag}: the folder it runs in, relative to the one \
         that holds .vivac. Use . for that folder itself."
    )
}

fn arm_dir_without_arm_message(via_mcp: bool) -> String {
    let (dir_flag, arm_flag) = if via_mcp {
        ("arm_dir", "arm")
    } else {
        ("--arm-dir", "--arm")
    };
    format!("{dir_flag} says where an arm runs, and no {arm_flag} was given.")
}

fn needs_dir_message(via_mcp: bool) -> String {
    let flag = if via_mcp { "dir" } else { "--dir" };
    format!(
        "An arm needs {flag}: the folder it runs in, relative to the one \
         that holds .vivac. Use . for that folder itself."
    )
}

/// `--arm`/`--arm-dir`, checked against the type it is born with. `d415`:
/// only a rule may carry one, and it may carry none -- a rule with no arm is
/// judged. `d441`: whenever one or more `--arm` are given, `--arm-dir` is
/// mandatory and names the one folder every arm in this call runs in.
/// `via_mcp` only ever changes which vocabulary the missing-folder messages
/// use, never the check itself.
fn arms_of(
    ctx: &Ctx,
    raw: Vec<String>,
    dir: Option<String>,
    kind: Kind,
    via_mcp: bool,
) -> Result<Vec<Arm>, Failure> {
    if !raw.is_empty() && kind != Kind::Rule {
        return Err(Failure::usage(format!(
            "Only a rule has an arm; this would be {}.",
            kind.with_article()
        )));
    }
    if raw.is_empty() {
        if dir.is_some() {
            return Err(Failure::usage(arm_dir_without_arm_message(via_mcp)));
        }
        return Ok(vec![]);
    }
    let dir = match dir {
        Some(d) if !d.trim().is_empty() => d,
        _ => return Err(Failure::usage(needs_arm_dir_message(via_mcp))),
    };
    let normalized = validate_arm_dir(&dir, &ctx.store.root)?;
    for (i, a) in raw.iter().enumerate() {
        validate_arm_text(a)?;
        if raw[..i].contains(a) {
            return Err(Failure::usage(format!("The same arm is given twice: {a}")));
        }
    }
    Ok(raw
        .into_iter()
        .map(|command| Arm {
            dir: normalized.clone(),
            command,
        })
        .collect())
}

/// Splits one `--against` entry on the **first** `:`: the id to its left,
/// the sentence to its right, both trimmed. `t426` ยง2.1: the sentence may
/// carry more colons of its own.
fn split_against_entry(raw: &str) -> Result<(&str, &str), Failure> {
    let form_error =
        || Failure::usage("--against needs an id and a sentence: --against \"r12: why it holds\"");
    let (id, why) = raw.split_once(':').ok_or_else(form_error)?;
    let (id, why) = (id.trim(), why.trim());
    if id.is_empty() || why.is_empty() {
        return Err(form_error());
    }
    Ok((id, why))
}

/// `--against`, checked against what it points at. `t426` ยง2.1 and ยง2.2:
/// shared by `decide`, `push`, `add` and `declare`, since every one of them
/// judges an entry by the same questions -- only `push` and `add` ever
/// call it with a `kind` that is not already `Kind::Decision`, since a
/// decision is the only kind that may carry one.
///
/// Every check runs **before** anything is written, in order: the form of
/// each entry, that the id exists, that it names a pillar or a rule, that
/// it still governs, and that no id repeats within this one call.
fn against_of(ctx: &Ctx, raw: Vec<String>, kind: Kind) -> Result<Vec<Against>, Failure> {
    if !raw.is_empty() && kind != Kind::Decision {
        return Err(Failure::usage(format!(
            "--against goes on a decision, and this is {}",
            kind.with_article()
        )));
    }
    let mut out = Vec::with_capacity(raw.len());
    let mut seen: Vec<u64> = Vec::with_capacity(raw.len());
    for entry in &raw {
        let (id, why) = split_against_entry(entry)?;
        let n = ctx
            .tree
            .resolve(id)
            .ok_or_else(|| Failure::usage(format!("No such node: {id}.")))?;
        if !matches!(n.kind, Kind::Pillar | Kind::Rule) {
            return Err(Failure::usage(format!(
                "--against points at a pillar or a rule, and {} is {}",
                n.alias(),
                n.kind.with_article()
            )));
        }
        if !n.state.is_open() {
            return Err(Failure::usage(format!(
                "--against points at what still governs, and {} is {}: vivac rules lists what does",
                n.alias(),
                n.state.word(n.kind)
            )));
        }
        if seen.contains(&n.num) {
            return Err(Failure::usage(format!(
                "--against names {} twice",
                n.alias()
            )));
        }
        seen.push(n.num);
        out.push(Against {
            node: n.id.clone(),
            why: why.to_string(),
        });
    }
    Ok(out)
}

/// What it takes to create a node, named rather than positional.
///
/// `title` and `why` stay borrowed rather than owned: every caller still
/// needs its own copy afterwards (a title goes into the vivac, `add`'s
/// `where_at` reads the parent, not this), so taking a slice costs nothing
/// and asking for an owned `String` here would just make each caller clone
/// one it already had.
struct Born<'a> {
    title: &'a str,
    why: &'a str,
    kind: Kind,
    parent: Option<String>,
    refs: Vec<String>,
    governs: Vec<String>,
    blocks: bool,
    arms: Vec<Arm>,
    /// Already validated by `against_of`. Empty for every kind that is not
    /// a decision, since only a decision may carry one.
    against: Vec<Against>,
}

/// Creates a node. Returns the event, the alias number assigned, and
/// whether the `against` key was written empty -- `d445`'s `no_against`,
/// which `push`, `add` and `decide` each fold into their own `Outcome`.
///
/// Takes a `Born` already extracted rather than `&Args`: the three ops that
/// call this (`push`, `add`, `decide`) do not all read the fields the same
/// way (`add` defaults `why` with `.opt_or`, `push` demands it), so the
/// reading stays with each caller and only the shared write comes here.
fn born(ctx: &Ctx, b: Born) -> Result<(Body, u64, String, bool), Failure> {
    let mut fields: Vec<(&str, &str)> = vec![("title", b.title), ("why", b.why)];
    fields.extend(b.refs.iter().map(|r| ("ref", r.as_str())));
    fields.extend(b.governs.iter().map(|g| ("governs", g.as_str())));
    fields.extend(b.arms.iter().map(|a| ("arm", a.command.as_str())));
    fields.extend(b.against.iter().map(|a| ("against", a.why.as_str())));
    guard_text(&fields)?;

    let node = id::ulid();
    let num = ctx.tree.next_num.max(1);
    // `t426` ยง1.1: `Some` only for a decision born while at least one
    // pillar or rule is open -- the same predicate `vivac rules` lists
    // under -- and `Some(vec![])` when nothing was declared. Every other
    // node keeps writing exactly the bytes it always has.
    let against = (b.kind == Kind::Decision && ctx.tree.has_open_governance()).then_some(b.against);
    let no_against = against.as_ref().is_some_and(Vec::is_empty);
    Ok((
        Body::NodeCreated {
            node: node.clone(),
            num,
            kind: b.kind,
            title: b.title.to_string(),
            why: b.why.to_string(),
            parent: b.parent,
            blocks: b.blocks,
            refs: b.refs,
            governs: b.governs,
            arms: b.arms,
            against,
        },
        num,
        node,
        no_against,
    ))
}

/// `push` โ€” open a detour. It is **the** operation: the provenance edge is
/// created here on its own, with nobody having to remember to declare it.
///
/// `--root` (`t533` ยง1) means born with no parent, nothing more: the kind
/// still defaults the way it always has for a parentless node (`Kind::Goal`),
/// and `add`/`decide`'s own stacks never move either way. On `push`, it also
/// leaves the stack holding only the new node -- what was on it stays open in
/// the tree, and the events that record it are the same ones `focus` already
/// writes crossing branches: a `stack.popped` per node that leaves, top to
/// bottom, then the `stack.pushed` of the new one.
///
/// `--parent` (`d757`) opens under a node other than the focus instead: the
/// stack is rebuilt to that node's own path, the way `focus` rebuilds it,
/// and the new node lands on top in the same move. Refused together with
/// `--root` -- a node is born in one place -- and on a node that is closed,
/// abandoned or parked (`open_parent`), so this never revives in silence
/// what somebody closed or put off.
pub fn push(ctx: &mut Ctx, p: params::Push) -> Result<Outcome, Failure> {
    if p.root && p.parent.is_some() {
        return Err(root_and_parent_error());
    }
    let target = match &p.parent {
        Some(id) => Some(open_parent(ctx, id)?),
        None => None,
    };
    let parent = if p.root {
        None
    } else if let Some(t) = &target {
        Some(t.id.clone())
    } else {
        ctx.tree.focus().map(|n| n.id.clone())
    };
    let kind = kind_of(
        p.kind.as_deref(),
        if parent.is_none() {
            Kind::Goal
        } else {
            Kind::Task
        },
    )?;
    let arms = arms_of(ctx, p.arms, p.arm_dir, kind, p.via_mcp)?;
    let against = against_of(ctx, p.against, kind)?;
    let (ev, num, node, no_against) = born(
        ctx,
        Born {
            title: &p.title,
            why: &p.why,
            kind,
            parent: parent.clone(),
            refs: p.refs,
            governs: p.governs,
            blocks: p.blocks,
            arms,
            against,
        },
    )?;
    // What leaves the stack, and what joins it to reach the target's own
    // path: `--root` clears it outright and nothing joins; `--parent`
    // rebuilds it the way `focus` would; a plain push moves neither. Bottom
    // to top, kept for `left_stack` below and for what the vivac freezes.
    let (to_pop, to_push): (Vec<u64>, Vec<(u64, String)>) = if p.root {
        (ctx.tree.stack().to_vec(), Vec::new())
    } else if let Some(t) = &target {
        stack_to(ctx, t.num)
    } else {
        (Vec::new(), Vec::new())
    };
    // The vivac goes **before** the push: it freezes the stack at the moment
    // of the fork, which is the belay where you make yourself safe before
    // setting off. The `next_intent` is the child being opened, because that
    let v = vivac(ctx, VivacKind::Push, &p.title, parent, "");
    let mut evs = vec![v, ev];
    for &n in to_pop.iter().rev() {
        if let Some(left) = ctx.tree.node_by_num(n) {
            evs.push(Body::Popped {
                node: left.id.clone(),
            });
        }
    }
    for (_, id) in &to_push {
        evs.push(Body::Pushed { node: id.clone() });
    }
    evs.push(Body::Pushed { node });
    ctx.emit(evs)?;

    let left_stack: Vec<String> = to_pop
        .iter()
        .filter_map(|&n| ctx.tree.node_by_num(n))
        .map(|n| n.alias())
        .collect();
    // The deepest of what left that is still open or parked: the one worth
    // naming to get back to. Depth here means position in the old stack, top
    // first, not how far it is from any root.
    let back_to: Option<String> = to_pop
        .iter()
        .rev()
        .filter_map(|&n| ctx.tree.node_by_num(n))
        .find(|n| matches!(n.state, State::Active | State::Suspended))
        .map(|n| n.alias());

    // `emit` already applied the push in memory, so the stack includes the
    // new node and there is no need to add one.
    let depth_of = ctx.tree.stack_depth();
    // ยง6.1: intervene, never block. A deep stack is almost never lack of
    // discipline: the root goal moved and nobody re-rooted. `--root` always
    // leaves the stack one level deep, so this never fires for it, and
    // `--parent` rebuilds the stack to the node the agent chose, so a depth
    // reached that way was picked on purpose, not drifted into -- measured
    // twice, a push under a level-3 node came back with this advice although
    // the node was exactly where it belonged (`d796`, `f758`).
    let advice = if depth_of >= 4 && target.is_none() {
        // The node named is the **bottom of this stack**, never the tree's
        // first root: the number measures the stack (`f156`), so taking the
        // number from one place and the node from another gives a true count
        // pointing at the wrong goal. It showed up as soon as there was more
        // than one root -- which is what `promote` exists to make -- and the
        // advice named whichever root was written first, closed or not
        // (`f331`).
        ctx.tree.stack_bottom().map(|root| outcome::DepthAdvice {
            depth: depth_of,
            root_alias: root.alias(),
            root_title: root.title(&ctx.tree).to_string(),
            // `t533` ยง2.5: the bottom can now be closed or parked, since
            // `done`/`park` no longer unstack a node that is not the top.
            root_mark: (!root.state.is_open()).then(|| root.state.word(root.kind).to_string()),
        })
    } else {
        None
    };
    Ok(Outcome::Pushed {
        alias: format!("{}{}", kind.prefix(), num),
        title: p.title,
        blocks: p.blocks,
        advice,
        no_against,
        left_stack,
        back_to,
        under: target.map(|t| t.alias()),
    })
}

/// `pop` โ€” close the focus and come back to the parent with context.
///
/// `f552` (`t533` ยง2.2): the focus can now be something `done` or `park`
/// closed while it sat below the top of the stack, and the path only reached
/// it once everything above it was popped in turn. Popping it does not undo
/// that: nothing is open to close, so no `state.changed` is written, the
/// closure rule is never consulted, and `--force` changes nothing. The
/// `stack.popped` and the vivac are written exactly as they always are.
pub fn pop(ctx: &mut Ctx, p: params::Pop) -> Result<Outcome, Failure> {
    let focus = ctx
        .tree
        .focus()
        .ok_or_else(|| {
            Failure::usage(
                "The stack is empty. Open something:  vivac push \"<title>\" --why \"<reason>\"",
            )
        })?
        .clone();
    let outcome_text = p.outcome.as_str();
    let next = p.next.as_deref().unwrap_or(outcome_text);
    guard_text(&[("outcome", outcome_text), ("next", next)])?;
    let v = vivac(ctx, VivacKind::Pop, next, Some(focus.id.clone()), "");
    // Trap: two separate `emit`s in a row, not one lot like `push` -- one
    // inside `close_node` (or the bare pop below), one here for the vivac --
    // and the parent's counts below have to be read only after both, or the
    // number comes out wrong.
    let closed = if focus.state.is_open() {
        close_node(ctx, &focus, outcome_text, p.force, true)?
    } else {
        ctx.emit(vec![Body::Popped {
            node: focus.id.clone(),
        }])?;
        outcome::Closed {
            alias: focus.alias(),
            title: focus.title(&ctx.tree).to_string(),
            force: p.force,
            already: Some(focus.state.word(focus.kind).to_string()),
        }
    };
    ctx.emit(vec![v])?;
    let parent = match focus.parent.and_then(|p| ctx.tree.node_by_num(p)) {
        Some(parent) => Some(outcome::PoppedTo {
            alias: parent.alias(),
            title: parent.title(&ctx.tree).to_string(),
            counts: ctx.tree.counts(parent.num),
        }),
        None => None,
    };
    Ok(Outcome::Popped { closed, parent })
}

/// `park` โ€” what produces DO NOT TOUCH NOW; without it that section always
/// comes out empty. The closure rule does not stop it: parking claims nothing
/// finished, and if parking cost more than ignoring, nobody would park.
/// Whether a word is shaped like the name of a node.
///
/// A bare number, or one character of type prefix and a number: `25`, `f25`.
/// Prose never looks like that, so a word that does and resolves to nothing is
/// a typo rather than a reason, and saying so beats guessing.
fn looks_like_an_id(s: &str) -> bool {
    let s = s.trim().trim_start_matches('#');
    let mut c = s.chars();
    let Some(first) = c.next() else {
        return false;
    };
    let rest = c.as_str();
    if first.is_ascii_digit() {
        return rest.chars().all(|c| c.is_ascii_digit());
    }
    !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit())
}

/// The node an operation acts on where naming it is optional, and the reason
/// written beside it.
///
/// **Two words are not ambiguous**: the first is an id and it has to resolve.
/// `park f74 "<reason>"` used to fall through to the focus when `f74` named
/// nothing, parking a node nobody had written down, filing `f74` itself as the
/// reason, dropping the reason actually typed, and exiting 0. The hole was
/// `and_then`, which flattens "did not resolve" into the same `None` as "was
/// not given" (`f74`).
///
/// One word **is** ambiguous by the grammar, because a reason is as good a
/// word as an alias. So it is resolved, and only a word shaped like an id has
/// to succeed.
fn named_or_focus(
    ctx: &Ctx,
    node: Option<&str>,
    reason: Option<&str>,
    usage: &'static str,
) -> Result<(Node, String), Failure> {
    let focus = || {
        ctx.tree
            .focus()
            .cloned()
            .ok_or_else(|| Failure::usage(usage))
    };
    match (node, reason) {
        (Some(s), Some(r)) => Ok((ctx.resolve(s)?.clone(), r.to_string())),
        (Some(w), None) => match ctx.tree.resolve(w) {
            Some(n) => Ok((n.clone(), String::new())),
            None if looks_like_an_id(w) => Err(Failure::usage(format!("No such node: {w}."))),
            None => Ok((focus()?, w.to_string())),
        },
        _ => Ok((focus()?, String::new())),
    }
}

pub fn park(ctx: &mut Ctx, p: params::Park) -> Result<Outcome, Failure> {
    let (node, reason) = named_or_focus(
        ctx,
        p.node.as_deref(),
        p.reason.as_deref(),
        "usage: vivac park [<id>] [\"<reason>\"]",
    )?;
    let reason = reason.as_str();
    guard_text(&[("reason", reason)])?;
    let mut evs = vec![vivac(
        ctx,
        VivacKind::Park,
        reason,
        Some(node.id.clone()),
        "",
    )];
    evs.push(Body::StateChanged {
        node: node.id.clone(),
        state: State::Suspended,
        outcome: reason.to_string(),
        forced: false,
    });
    // `t533` ยง2.1: only when it is the stack's own top. Anywhere else, the
    // path still runs through it and the spine marks it parked instead.
    if ctx.tree.stack().last() == Some(&node.num) {
        evs.push(Body::Popped {
            node: node.id.clone(),
        });
    }
    ctx.emit(evs)?;
    Ok(Outcome::Parked {
        alias: node.alias(),
        title: node.title(&ctx.tree).to_string(),
    })
}

/// The closure rule. `MODEL.md` ยง7, and the **only** rule in the model that
/// refuses a user operation.
///
/// It earns that privilege because the case it prevents is measured: an
/// audit marked DONE with its findings open took 26 days to be spotted.
/// Without this, the model lets the same mistake happen again.
fn close_node(
    ctx: &mut Ctx,
    n: &crate::model::Node,
    outcome: &str,
    force: bool,
    unstack: bool,
) -> Result<crate::outcome::Closed, Failure> {
    if !force {
        let pending_count = ctx.tree.open_blockers(n.num);
        if !pending_count.is_empty() {
            let mut m = format!(
                "  {} CANNOT close: {} open closure condition(s)\n",
                n.alias(),
                pending_count.len()
            );
            for c in &pending_count {
                m.push_str(&format!("\n      {:<6} {}", c.alias(), c.title(&ctx.tree)));
            }
            m.push_str(&format!(
                "\n\n  A run closes with its findings, not with its report.\n  \
                 Closing it anyway leaves a trace:  vivac done {} --force",
                n.num
            ));
            return Err(Failure::Model(m));
        }
    }
    let mut evs = vec![Body::StateChanged {
        node: n.id.clone(),
        state: State::Done,
        outcome: outcome.to_string(),
        forced: force,
    }];
    // `t533` ยง2.1: only when it is the stack's own top. Anywhere else, the
    // path still runs through it and the spine marks it closed instead.
    if unstack && ctx.tree.stack().last() == Some(&n.num) {
        evs.push(Body::Popped { node: n.id.clone() });
    }
    ctx.emit(evs)?;
    Ok(crate::outcome::Closed {
        alias: n.alias(),
        title: n.title(&ctx.tree).to_string(),
        force,
        already: None,
    })
}

pub fn done(ctx: &mut Ctx, p: params::Done) -> Result<Outcome, Failure> {
    let n = ctx.resolve(&p.id)?.clone();
    guard_text(&[("outcome", &p.outcome)])?;
    let closed = close_node(ctx, &n, &p.outcome, p.force, true)?;
    Ok(Outcome::Done { closed })
}

/// `add` โ€” a node without touching the stack. It is how a tree that already
/// existed elsewhere gets in, and how a finding hangs off something that is
pub fn add(ctx: &mut Ctx, p: params::Add) -> Result<Outcome, Failure> {
    if p.root && p.parent.is_some() {
        return Err(root_and_parent_error());
    }
    let parent = if p.root {
        None
    } else {
        match &p.parent {
            Some(s) => Some(ctx.resolve(s)?.id.clone()),
            None => ctx.tree.focus().map(|n| n.id.clone()),
        }
    };
    let kind = kind_of(
        p.kind.as_deref(),
        if parent.is_none() {
            Kind::Goal
        } else {
            Kind::Task
        },
    )?;
    let arms = arms_of(ctx, p.arms, p.arm_dir, kind, p.via_mcp)?;
    let against = against_of(ctx, p.against, kind)?;
    let (ev, num, _, no_against) = born(
        ctx,
        Born {
            title: &p.title,
            why: &p.why,
            kind,
            parent: parent.clone(),
            refs: p.refs,
            governs: p.governs,
            blocks: p.blocks,
            arms,
            against,
        },
    )?;
    ctx.emit(vec![ev])?;
    let parent_info = parent
        .and_then(|id| ctx.tree.node(&id))
        .map(|n| outcome::AddedUnder {
            alias: n.alias(),
            title: n.title(&ctx.tree).to_string(),
        });
    Ok(Outcome::Added {
        alias: format!("{}{}", kind.prefix(), num),
        title: p.title,
        parent: parent_info,
        blocks: p.blocks,
        no_against,
    })
}

pub fn note(ctx: &mut Ctx, p: params::Note) -> Result<Outcome, Failure> {
    let (n, note) = match (p.node.as_deref(), p.note.as_deref()) {
        (Some(s), Some(t)) => (ctx.resolve(s)?.clone(), t.to_string()),
        (Some(t), None) => {
            let f = ctx
                .tree
                .focus()
                .ok_or_else(|| Failure::usage("usage: vivac note [<id>] \"<note>\""))?;
            (f.clone(), t.to_string())
        }
        _ => return Err(Failure::usage("usage: vivac note [<id>] \"<note>\"")),
    };
    guard_text(&[("note", &note)])?;
    ctx.emit(vec![Body::NodeNoted {
        node: n.id.clone(),
        note,
    }])?;
    Ok(Outcome::Noted { alias: n.alias() })
}

pub fn block(ctx: &mut Ctx, p: params::Block) -> Result<Outcome, Failure> {
    let n = ctx.resolve(&p.id)?.clone();
    let Some(parent) = n.parent.and_then(|p| ctx.tree.node_by_num(p)) else {
        return Err(Failure::usage(format!(
            "{} is the root: there is no parent to block.",
            n.alias()
        )));
    };
    let blocks = !p.off;
    let (pa, pt) = (parent.alias(), parent.title(&ctx.tree).to_string());
    ctx.emit(vec![Body::BlockChanged {
        node: n.id.clone(),
        blocks,
    }])?;
    Ok(Outcome::Blocked {
        alias: n.alias(),
        blocks,
        parent_alias: pa,
        parent_title: pt,
    })
}

/// `promote` โ€” the focus becomes a goal of its own and the stack is cut there.
///
/// The provenance chain is **kept**: where it was born does not change just
/// because its rank did. Without this operation, the depth warning has no way
/// out and ends up being ignored.
pub fn promote(ctx: &mut Ctx, p: params::Promote) -> Result<Outcome, Failure> {
    let n = match p.id {
        Some(s) => ctx.resolve(&s)?.clone(),
        None => ctx
            .tree
            .focus()
            .ok_or_else(|| Failure::usage("usage: vivac promote [<id>]"))?
            .clone(),
    };
    ctx.emit(vec![Body::Promoted { node: n.id.clone() }])?;
    let parent = n
        .parent
        .and_then(|id| ctx.tree.node_by_num(id))
        .map(|parent| outcome::StillBornFrom {
            alias: parent.alias(),
            title: parent.title(&ctx.tree).to_string(),
        });
    Ok(Outcome::Promoted {
        alias: n.alias(),
        title: n.title(&ctx.tree).to_string(),
        parent,
    })
}

/// `abandon` โ€” discard. It costs the same as `pop` on purpose: if abandoning
/// were dearer than ignoring, nobody would abandon and in three months the
/// tree would be noise.
///
/// The cascade is **not** the default. `MODEL.md` ยง6 wants it with a
/// confirmation and the list up front, and a non-interactive CLI cannot
/// confirm anything: it shows what would fall and asks for an explicit
///
/// **Rescue does not reparent** (`d33`). `MODEL.md` ยง6 said to re-parent the
/// descendant onto a living ancestor; that rewrites the birth, and invariant
/// 11 says a thing is born in one place. A rescued node stays where it was
/// born: alive, under an abandoned parent. It is the same shape as an open
/// finding under a closed batch, which the tree already knows how to show and
/// the brief already knows how to count.
pub fn abandon(ctx: &mut Ctx, p: params::Abandon) -> Result<Outcome, Failure> {
    let (n, reason) = named_or_focus(
        ctx,
        p.node.as_deref(),
        p.reason.as_deref(),
        "usage: vivac abandon [<id>] \"<reason>\"",
    )?;
    let reason = reason.as_str();
    guard_text(&[("reason", reason)])?;

    // Rescuing a node rescues its descendants. Saving the parent and letting
    // the children die would be a half rescue nobody asked for, and would
    // orphan exactly what was meant to be kept.
    let mut rescued: std::collections::HashSet<String> = Default::default();
    for s in p.rescue {
        let r = ctx
            .tree
            .resolve(&s)
            .ok_or_else(|| Failure::usage(format!("no such node: {s}")))?;
        let (rid, r_num, ralias) = (r.id.clone(), r.num, r.alias());
        if rid == n.id {
            return Err(Failure::usage(format!(
                "{ralias} is the one being abandoned; it cannot be rescued from itself"
            )));
        }
        if !ctx.tree.descendants(n.num).iter().any(|d| d.id == rid) {
            return Err(Failure::usage(format!(
                "{ralias} does not hang off {}: there is nothing to rescue it from",
                n.alias()
            )));
        }
        rescued.insert(rid.clone());
        for d in ctx.tree.descendants(r_num) {
            rescued.insert(d.id.clone());
        }
    }

    let (falling, saved): (Vec<&Node>, Vec<&Node>) = ctx
        .tree
        .descendants(n.num)
        .into_iter()
        .filter(|d| d.state.is_open())
        .partition(|d| !rescued.contains(&d.id));

    // Only what falls unnamed needs confirming. If everything was rescued,
    // there is nothing left to confirm.
    if !falling.is_empty() && !p.cascade {
        let mut m = format!(
            "  {}  {}\n  has {} open descendant(s) with no rescue:\n",
            n.alias(),
            n.title(&ctx.tree),
            falling.len()
        );
        for d in &falling {
            m.push_str(&format!("\n      {:<6} {}", d.alias(), d.title(&ctx.tree)));
        }
        m.push_str("\n\n  Abandon all of it:     vivac abandon ");
        m.push_str(&n.num.to_string());
        m.push_str(" --cascade");
        m.push_str("\n  Save some of it:       vivac abandon ");
        m.push_str(&n.num.to_string());
        m.push_str(" --rescue <id>");
        m.push_str("\n  Save it as a goal:     vivac promote <id>");
        return Err(Failure::Model(m));
    }

    let mut evs = vec![Body::StateChanged {
        node: n.id.clone(),
        state: State::Abandoned,
        outcome: reason.to_string(),
        forced: false,
    }];
    let falling_count = falling.len();
    let saved_lines: Vec<(String, String)> = saved
        .iter()
        .map(|d| (d.alias(), d.title(&ctx.tree).to_string()))
        .collect();
    for d in falling {
        evs.push(Body::StateChanged {
            node: d.id.clone(),
            state: State::Abandoned,
            outcome: format!("cascaded from {}", n.alias()),
            forced: false,
        });
    }
    // The stack is the path to the focus and cannot cross an abandoned node,
    // so everything hanging off the abandoned one leaves it --the rescued
    // included, which stays alive but stops being on the path--.
    let mut out_of_scope: Vec<(u64, String)> = vec![(n.num, n.id.clone())];
    out_of_scope.extend(
        ctx.tree
            .descendants(n.num)
            .iter()
            .map(|d| (d.num, d.id.clone())),
    );
    for (num, id) in out_of_scope {
        if ctx.tree.stack().contains(&num) {
            evs.push(Body::Popped { node: id });
        }
    }

    ctx.emit(evs)?;
    Ok(Outcome::Abandoned {
        alias: n.alias(),
        title: n.title(&ctx.tree).to_string(),
        cascaded: (falling_count > 0).then_some(falling_count),
        rescued: saved_lines
            .into_iter()
            .map(|(alias, title)| outcome::RescuedNode { alias, title })
            .collect(),
    })
}

/// `focus` โ€” step back into a node that already exists.
///
/// Without this the stack only works inside one session: the next day the log
/// holds the whole tree and the stack is empty, and there is no way to say "I
/// am on this" without opening a new node, which is exactly the litter to be
/// avoided. The stack becomes the path from the root down to the node, which
/// is what working on it means.
pub fn focus(ctx: &mut Ctx, p: params::Focus) -> Result<Outcome, Failure> {
    let n = ctx.resolve(&p.id)?.clone();

    if !n.state.is_open() && !p.reopen {
        // Parking says "maybe I will be back", so returning is the normal
        // operation and asks no permission. Closing claims something finished:
        // undoing that has to be deliberate.
        if n.state != State::Suspended {
            return Err(Failure::Model(format!(
                "  {} is {}. Going back into it undoes that claim.\n\n  \
                 If it really was not finished:  vivac focus {} --reopen",
                n.alias(),
                n.state.word(n.kind),
                n.num
            )));
        }
    }

    // `stack_to` (`d757`): shared with `push --parent`, which rebuilds the
    // stack the same way to open new work under a node other than the
    // focus.
    let (to_pop, to_push) = stack_to(ctx, n.num);
    let mut evs: Vec<Body> = to_pop
        .iter()
        .filter_map(|&num| ctx.tree.node_by_num(num))
        .map(|n| Body::Popped { node: n.id.clone() })
        .collect();
    if !n.state.is_open() {
        evs.push(Body::StateChanged {
            node: n.id.clone(),
            state: State::Active,
            outcome: String::new(),
            forced: false,
        });
    }
    evs.extend(
        to_push
            .iter()
            .map(|(_, id)| Body::Pushed { node: id.clone() }),
    );
    let revived = !n.state.is_open();
    ctx.emit(evs)?;
    // Trap: `render::stack` used to be called from here, reading `a` for its
    // own `--json` on its own. `main.rs` calls it separately now, after this
    // `Outcome` is printed -- `render.rs` is not touched, and the flag never
    // reached this call site from the CLI anyway (`focus` is not allowed
    // `--json` in `main.rs`'s table).
    Ok(Outcome::Focused {
        alias: n.alias(),
        revived,
    })
}

/// `flag <id> <flag> --why <reason>` โ€” raise or clear a flag.
///
/// The reason is **mandatory** when raising it. `BRIEF-SPEC.md` ยง10 tests it
/// as a contract: a flag with no reason informs nobody, it only adds noise to
/// the brief, and within a week they all get ignored.
pub fn flag(ctx: &mut Ctx, p: params::Flag) -> Result<Outcome, Failure> {
    let n = ctx.resolve(&p.id)?.clone();
    let flag = Flag::parse(&p.flag).ok_or_else(|| {
        Failure::usage(format!("Unknown flag: {}. They are: {}", p.flag, Flag::ALL))
    })?;

    if p.off {
        ctx.emit(vec![Body::FlagCleared {
            node: n.id.clone(),
            flag,
        }])?;
        return Ok(Outcome::Flagged {
            alias: n.alias(),
            flag: flag.word().to_string(),
            change: outcome::FlagChange::Off,
        });
    }
    let reason = p.why.ok_or_else(|| {
        Failure::usage(
            "Missing --why. A flag with no reason informs nobody: in two weeks\n  \
             nobody will know what needed looking at, and they all get ignored.",
        )
    })?;
    guard_text(&[("reason", &reason)])?;
    ctx.emit(vec![Body::FlagRaised {
        node: n.id.clone(),
        flag,
        reason: reason.clone(),
    }])?;
    Ok(Outcome::Flagged {
        alias: n.alias(),
        flag: flag.word().to_string(),
        change: outcome::FlagChange::Raised {
            title: n.title(&ctx.tree).to_string(),
            reason,
        },
    })
}

/// `arm <id> "<command>" [--off]` โ€” record or remove what verifies a rule.
///
/// Vivac never runs it: `d415`. Shaped like `flag`, and like `flag` it
/// arms or disarms a closed node. Where it parts from `flag` is the
/// repeat: a flag folds into a set, so raising it twice changes nothing,
/// but arms fold into a list, so a repeated arm would show twice and the
/// removal of an absent one would write a line that changes no answer.
/// Both are refused before anything is written.
pub fn arm(ctx: &mut Ctx, p: params::Arm) -> Result<Outcome, Failure> {
    let n = ctx.resolve(&p.id)?.clone();
    if n.kind != Kind::Rule {
        return Err(Failure::usage(format!(
            "Only a rule has an arm; {} is {}.",
            n.alias(),
            n.kind.with_article()
        )));
    }
    let dir = match &p.dir {
        Some(d) if !d.trim().is_empty() => d.clone(),
        _ => return Err(Failure::usage(needs_dir_message(p.via_mcp))),
    };
    let dir = validate_arm_dir(&dir, &ctx.store.root)?;
    validate_arm_text(&p.command)?;
    let has = n
        .arms(&ctx.tree)
        .contains(&(dir.as_str(), p.command.as_str()));
    if p.off && !has {
        return Err(Failure::usage(format!(
            "{0} has no such arm; vivac why {0} lists the ones it has.",
            n.alias()
        )));
    }
    if !p.off && has {
        return Err(Failure::usage(format!(
            "{} already has that arm.",
            n.alias()
        )));
    }
    guard_text(&[("arm", &p.command)])?;
    let body = if p.off {
        Body::ArmRemoved {
            node: n.id.clone(),
            dir: dir.clone(),
            command: p.command.clone(),
        }
    } else {
        Body::ArmAdded {
            node: n.id.clone(),
            dir: dir.clone(),
            command: p.command.clone(),
        }
    };
    ctx.emit(vec![body])?;
    Ok(Outcome::Armed {
        alias: n.alias(),
        dir,
        arm: p.command,
        change: if p.off {
            outcome::ArmChange::Removed
        } else {
            outcome::ArmChange::Added
        },
    })
}

/// `decide` โ€” record a decision.
///
/// The discarded alternatives are optional in the schema and mandatory in
/// practice: without them, in a month the agent proposes again what you
/// already rejected.
pub fn decide(ctx: &mut Ctx, p: params::Decide) -> Result<Outcome, Failure> {
    if p.root && p.parent.is_some() {
        return Err(root_and_parent_error());
    }
    let superseded = match &p.supersedes {
        Some(s) => Some(ctx.resolve(s)?.clone()),
        None => None,
    };

    let mut body = p.reason.clone();
    if !p.alternatives.is_empty() {
        body.push_str(&format!("  |  discarded: {}", p.alternatives.join("; ")));
    }
    let parent = if p.root {
        None
    } else {
        match &p.parent {
            Some(s) => Some(ctx.resolve(s)?.id.clone()),
            None => ctx.tree.focus().map(|n| n.id.clone()),
        }
    };
    let against = against_of(ctx, p.against, Kind::Decision)?;
    let (ev, num, _, no_against) = born(
        ctx,
        Born {
            title: &p.title,
            why: &body,
            kind: Kind::Decision,
            parent,
            refs: p.refs,
            governs: p.governs,
            blocks: p.blocks,
            arms: vec![],
            against,
        },
    )?;

    let mut evs = vec![ev];
    if let Some(v) = &superseded {
        // `supersedes` forms a chain: the old one becomes superseded, not deleted.
        evs.push(Body::StateChanged {
            node: v.id.clone(),
            state: State::Superseded,
            outcome: format!("superseded by d{num}"),
            forced: false,
        });
    }
    ctx.emit(evs)?;
    Ok(Outcome::Decided {
        alias: format!("d{num}"),
        title: p.title,
        superseded: superseded.map(|v| outcome::SupersededNode { alias: v.alias() }),
        no_alternatives: p.alternatives.is_empty(),
        no_against,
    })
}

/// `declare <decision> --against "<id>: <why>"` โ€” record, after the fact,
/// what a decision was judged against. `t426` ยง2.2: unlike `--against` at
/// birth, the decision may be in any state -- it declares a fact about the
/// past, not a claim about what it still governs.
pub fn declare(ctx: &mut Ctx, p: params::Declare) -> Result<Outcome, Failure> {
    let (Some(id), false) = (p.id.as_deref(), p.against.is_empty()) else {
        return Err(Failure::usage(
            "usage: vivac declare <decision> --against \"r12: <why>\"",
        ));
    };
    let n = ctx.resolve(id)?.clone();
    if n.kind != Kind::Decision {
        return Err(Failure::usage(format!(
            "vivac declare takes a decision, and {} is {}",
            n.alias(),
            n.kind.with_article()
        )));
    }
    let entries = against_of(ctx, p.against, Kind::Decision)?;
    // `d783`: a later `declare` on a pillar or rule the decision already
    // declares does not get refused any more -- it substitutes the
    // sentence. `against_of` already refused the same pillar or rule named
    // twice inside this one call, which is the only repeat that still is.
    // What each entry is replacing, if anything, is read here against the
    // tree as it stood before this write, so `Outcome::Declared` can show
    // it.
    let existing = n.against(&ctx.tree);
    let before: Vec<Option<String>> = entries
        .iter()
        .map(|e| {
            let num = ctx.tree.node(&e.node).map(|x| x.num);
            n.against
                .iter()
                .zip(existing.iter())
                .find(|(span, _)| Some(span.node) == num)
                .map(|(_, resolved)| resolved.why.to_string())
        })
        .collect();
    guard_text(
        &entries
            .iter()
            .map(|a| ("against", a.why.as_str()))
            .collect::<Vec<_>>(),
    )?;
    ctx.emit(vec![Body::AgainstAdded {
        node: n.id.clone(),
        against: entries.clone(),
    }])?;
    Ok(Outcome::Declared {
        alias: n.alias(),
        against: entries
            .into_iter()
            .zip(before)
            .map(|(a, before)| outcome::DeclaredPair {
                node: ctx.tree.node(&a.node).map(|x| x.alias()).unwrap_or(a.node),
                why: a.why,
                before,
            })
            .collect(),
    })
}

/// `save [label]` โ€” a safe stop on purpose.
pub fn save(ctx: &mut Ctx, p: params::Save) -> Result<Outcome, Failure> {
    guard_text(&[("label", &p.label), ("next", &p.next)])?;
    let v = vivac(ctx, VivacKind::Manual, &p.next, None, &p.label);
    let num = ctx.tree.next_vivac_num.max(1);
    // Read off the event rather than resolved a second time: `vivac` has
    // already been to every repository's `HEAD`, and asking again would
    // pay those reads twice for an answer that cannot have changed inside
    // the lock.
    let anchors = match &v {
        Body::VivacCreated { anchors, .. } => anchors.clone(),
        _ => vec![],
    };
    ctx.emit(vec![v])?;
    // With no VCS no precision is faked: the vivac is worth the same, but
    // restoring it will only give plain age, not a diff.
    let anchor = ctx.anchor.snapshot();
    Ok(Outcome::Saved {
        num,
        label: p.label,
        anchor,
        anchors,
        next: p.next,
    })
}

/// A saved entry resolved against the live tree once, up front: `num`,
/// whether it is still open, and the word for when it is not -- `None` when
/// a hand edit or an old bug left the alias resolving to nothing at all.
type MatchedEntry = Option<(u64, bool, String)>;

/// The word for a saved entry that fell out of the rebuilt path: its state,
/// or `"gone"` when it no longer resolves at all.
fn lost_state(matched: &MatchedEntry) -> String {
    matched
        .as_ref()
        .map(|(_, _, word)| word.clone())
        .unwrap_or_else(|| "gone".to_string())
}

/// What `restore` rebuilds from a vivac's saved stack: the real lineage to
/// put back (bottom to top), what stays on it despite not being open
/// (`kept`), and everything the saved stack named that fell out of the
/// rebuilt path entirely (`lost`), bottom to top itself.
///
/// `t533` ยง2.3: the stack it rebuilds is always a contiguous stretch of the
/// real tree's lineage, even when the vivac itself was saved by a version
/// whose own stack could skip over a closed ancestor. `N` is the saved
/// entry's own **deepest still-open node**; `B` is the first saved entry, from
/// the bottom, that is `N` or one of its ancestors. The new stack is the real
/// lineage from `B` to `N` -- contiguous by construction, never the saved
/// list itself. Every node from `B` to `N` that is not open is still on the
/// path, and says so rather than pretending it is open. Everything else
/// named by the saved stack is lost: above `N` as always, and below `B` too
/// -- a saved stack that is a subsequence of its top's lineage, which is what
/// every version has ever written, can only leave something unresolved down
/// there, but `restore` never drops what it leaves out in silence.
///
/// Split out from `restore` itself so this can be tested against a folded
/// `Tree` and a hand-built saved stack alone, with no store to write through.
fn restore_path(
    tree: &Tree,
    saved_stack: &[(String, String)],
) -> (
    Vec<(u64, String)>,
    Vec<outcome::KeptNode>,
    Vec<outcome::LostNode>,
) {
    let matched: Vec<MatchedEntry> = saved_stack
        .iter()
        .map(|(alias, _)| {
            tree.resolve(alias)
                .map(|n| (n.num, n.state.is_open(), n.state.word(n.kind).to_string()))
        })
        .collect();
    // `N`: the deepest (closest to the old top) saved entry that is still
    // open.
    let deepest_open = matched
        .iter()
        .rposition(|m| m.as_ref().is_some_and(|(_, open, _)| *open));

    let mut kept: Vec<outcome::KeptNode> = Vec::new();
    let mut lost: Vec<outcome::LostNode> = Vec::new();
    let mut lineage: Vec<(u64, String)> = Vec::new();

    match deepest_open {
        None => {
            // Nothing saved is still open: the whole point is lost, exactly
            // as it always has been.
            for (i, (alias, title)) in saved_stack.iter().enumerate() {
                lost.push(outcome::LostNode {
                    alias: alias.clone(),
                    title: title.clone(),
                    state: lost_state(&matched[i]),
                });
            }
        }
        Some(deepest_open) => {
            let (deepest_num, _, _) = matched[deepest_open].clone().unwrap();
            // The real lineage of `N`, root first: contiguous by
            // construction, unlike the saved list it may have come from.
            let full_lineage = tree.ancestors(deepest_num);
            // `B`: the first saved entry, from the bottom, that is `N` or one
            // of its ancestors.
            let bottom_index = (0..=deepest_open)
                .find(|&i| {
                    matched[i]
                        .as_ref()
                        .is_some_and(|(num, _, _)| full_lineage.iter().any(|a| a.num == *num))
                })
                .unwrap_or(deepest_open);
            let (bottom_num, _, _) = matched[bottom_index].clone().unwrap();
            let start = full_lineage
                .iter()
                .position(|a| a.num == bottom_num)
                .unwrap_or(0);
            for n in &full_lineage[start..] {
                lineage.push((n.num, n.id.clone()));
                if !n.state.is_open() {
                    kept.push(outcome::KeptNode {
                        alias: n.alias(),
                        title: n.title(tree).to_string(),
                        state: n.state.word(n.kind).to_string(),
                    });
                }
            }
            // Below `B`: never reached the lineage at all, and still named.
            for (i, (alias, title)) in saved_stack.iter().enumerate().take(bottom_index) {
                lost.push(outcome::LostNode {
                    alias: alias.clone(),
                    title: title.clone(),
                    state: lost_state(&matched[i]),
                });
            }
            // Above `N`: as always.
            for (i, (alias, title)) in saved_stack.iter().enumerate().skip(deepest_open + 1) {
                lost.push(outcome::LostNode {
                    alias: alias.clone(),
                    title: title.clone(),
                    state: lost_state(&matched[i]),
                });
            }
        }
    }
    (lineage, kept, lost)
}

/// `restore <v>` โ€” go back to a vivac.
///
/// **It never touches the working tree.** Mixing context navigation with tree
/// manipulation turns a tool for attention into a branch manager worse than
/// git. It rebuilds the stack and presents the diff; `restore_path` above
/// does the rebuilding.
pub fn restore(ctx: &mut Ctx, p: params::Restore) -> Result<Outcome, Failure> {
    let v = ctx
        .tree
        .vivac(&p.vivac)
        .ok_or_else(|| Failure::usage(format!("No such vivac: {}.", p.vivac)))?
        .clone();

    // `d598`: git runs before the lock. A saved vivac never changes, so
    // what changed since its anchor is the same either side of the lock;
    // only the stack is decided under it, on the tree as it is then.
    let changes = ctx.anchor.changed_since(&v.anchor);
    let mine = ctx.lock_for_write()?;

    let (lineage, kept, lost) = restore_path(&ctx.tree, &v.stack);

    let mut evs: Vec<Body> = ctx
        .tree
        .stack()
        .iter()
        .filter(|num| !lineage.iter().any(|(lineage_num, _)| lineage_num == *num))
        .filter_map(|&num| ctx.tree.node_by_num(num))
        .map(|n| Body::Popped { node: n.id.clone() })
        .collect();
    for (num, id) in &lineage {
        if !ctx.tree.stack().contains(num) {
            evs.push(Body::Pushed { node: id.clone() });
        }
    }
    ctx.emit(evs)?;
    // The write is done and nothing after this reads or writes the tree
    // under the lock: `main.rs` still renders the stack before it returns,
    // and holding the lock through that would be a window nobody asked
    // for. Only released if this call is the one that took it: releasing a
    // lock a caller above is still holding would leave that caller writing
    // with nothing holding the tree (`f602`).
    if mine {
        ctx.unlock();
    }

    let anchor = if v.anchor.is_empty_tree() {
        outcome::RestoreAnchor::Empty
    } else if changes.is_empty() {
        outcome::RestoreAnchor::NoChanges {
            anchor_short: v.anchor.short().to_string(),
        }
    } else {
        outcome::RestoreAnchor::Changed {
            anchor_short: v.anchor.short().to_string(),
            changes: changes
                .iter()
                .map(|c| outcome::ChangeLine {
                    file_path: c.file_path.clone(),
                    times: c.times,
                })
                .collect(),
            working_set: v.working_set.clone(),
        }
    };
    // Trap: `render::stack` used to be called from here too, on the same `a`
    // it read `--json` from on its own. `main.rs` calls it separately now,
    // after this `Outcome` is printed -- `restore` is allowed no flags at all
    // in `main.rs`'s table, so `--json` never reached this call site either.
    Ok(Outcome::Restored {
        alias: v.alias(),
        kind: v.kind.word().to_string(),
        ts: v.ts,
        label: v.label,
        next_intent: v.next_intent,
        kept,
        lost,
        anchor,
    })
}

/// An automatic stop, for the end-of-session hook.
pub fn auto_vivac(
    ctx: &mut Ctx,
    kind: VivacKind,
    next: &str,
    label: &str,
) -> Result<Outcome, Failure> {
    guard_text(&[("next", next), ("label", label)])?;
    let v = vivac(ctx, kind, next, None, label);
    ctx.emit(vec![v])?;
    Ok(Outcome::AutoStopped)
}

/// The opening of a session, for the start hook.
///
/// It records **what the brief claimed** --the focus it named and the stop it
/// showed as the last one-- so that *was the brief followed?* can be answered
/// by comparing that against the first node touched afterwards, instead of by
/// somebody's judgement.
///
/// These are inputs and never a verdict: what counts as *following* the brief
/// lives in whoever reads, not in the log. Storing the comparison instead of
/// its terms would freeze a definition that may well turn out to be wrong.
///
/// `source` and `session` come off a payload this program did not write, so
/// they go through the guard like any other text. Unlike everywhere else, a
/// finding does not stop the write: the field is replaced by the rule that
/// refused it and the opening is recorded regardless. The rest of the guard
/// can afford to refuse because somebody is there to reword the sentence; a
/// hook has nobody, and a hook that fails is a hook that gets switched off.
///
/// `focus` and `vivac` are handed in rather than read off `ctx.tree`: the
/// caller takes them from what the brief actually painted, before
/// `lock_for_write` could have reloaded the tree out from under it.
pub fn session_started(
    ctx: &mut Ctx,
    source: &str,
    session: Option<String>,
    focus: Option<String>,
    vivac: Option<String>,
) -> Result<Outcome, Failure> {
    let source = guarded_or_refused("source", source);
    let session = session.map(|s| guarded_or_refused("session", &s));
    ctx.emit(vec![Body::SessionStarted {
        source,
        focus,
        vivac,
        session,
    }])?;
    Ok(Outcome::SessionOpened)
}

/// Declares this folder a lane of the tree, and locks the tree's config so
/// that a vivac too old to know lanes stops instead of reading half of it
/// (`d444`, ยง2.6).
///
/// `ctx` already holds the write lock and already runs as the lane being
/// declared (`Ctx::load_for_write`, then `lock_for_write`): this only ever
/// locks the config and then emits, in that order, never the other way.
/// A process that dies between the two leaves the config asking for a
/// vivac that knows lanes with no `lane.declared` to back it up yet, and
/// that is nothing to worry about -- the sentence it wrote is already
/// true, and the next `setup` writes the event that is still missing.
///
/// **Not** where this folder's own `.vivac/lane` gets written, when this
/// is a brand new lane: the caller (`write_lane`, `setup/claude_code.rs`)
/// puts that file down *before* this is even called, never after. The
/// reverse -- an event with no file behind it -- would leave this very
/// folder not knowing whose thread it is, and it would keep signing as
/// `main` while the tree it just wrote to says otherwise, which is the one
/// ordering nothing here is allowed to permit.
pub fn declare_lane(ctx: &mut Ctx, name: String, repos: Vec<crate::event::Repo>) -> R {
    let lock = ctx
        .lock
        .as_ref()
        .ok_or_else(|| Failure::Io(std::io::Error::other("write without the tree's lock")))?;
    ctx.store.lock_lanes_in_config(lock)?;
    let lane = ctx
        .lane
        .clone()
        .unwrap_or_else(|| crate::lane::MAIN.to_string());
    ctx.emit(vec![Body::LaneDeclared { lane, name, repos }])
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::Event;
    use crate::model::fold;

    fn created(seq: u64, num: u64, kind: Kind, parent: Option<&str>) -> Event {
        Event {
            seq,
            id: format!("e{seq}"),
            ts: "2026-09-13T00:00:00Z".to_string(),
            actor: "a".to_string(),
            lane: "main".to_string(),
            payload: Body::NodeCreated {
                node: format!("n{num}"),
                num,
                kind,
                title: format!("Node {num}"),
                why: "it is needed".to_string(),
                parent: parent.map(str::to_string),
                blocks: false,
                refs: vec![],
                governs: vec![],
                arms: vec![],
                against: None,
            },
        }
    }

    /// `t533` ยง2.3, the hole a ruling caught: a saved entry sitting below `B`
    /// that does not resolve at all used to vanish from the report -- not
    /// `kept`, since it never reaches the rebuilt path, and not `lost`
    /// either, because that loop only ever looked above `N`. A saved stack
    /// that is a subsequence of its top's lineage -- what every version has
    /// ever written -- can only leave something unresolved in that slot, but
    /// `restore` still has to say so.
    #[test]
    fn a_saved_entry_below_the_path_that_does_not_resolve_is_reported_lost() {
        let events = vec![
            created(1, 1, Kind::Goal, None),
            created(2, 2, Kind::Task, Some("n1")),
            created(3, 3, Kind::Task, Some("n2")),
            created(4, 4, Kind::Task, Some("n3")),
        ];
        let tree = fold(&events, 0);
        let saved_stack = vec![
            ("f9".to_string(), "Nothing here resolves".to_string()),
            ("g1".to_string(), "Node 1".to_string()),
            ("t2".to_string(), "Node 2".to_string()),
            ("t3".to_string(), "Node 3".to_string()),
            ("t4".to_string(), "Node 4".to_string()),
        ];

        let (lineage, kept, lost) = restore_path(&tree, &saved_stack);

        assert_eq!(lineage.len(), 4, "the whole open lineage rebuilds");
        assert!(kept.is_empty(), "nothing on this path is closed");
        assert_eq!(
            lost.len(),
            1,
            "the entry below B must not vanish from the report: {lost:?}"
        );
        assert_eq!(lost[0].alias, "f9");
        assert_eq!(lost[0].state, "gone");
    }

    /// A directory removed when this value drops, whether the test that
    /// made it passed or panicked -- the same promise `tests/relocate.rs`'s
    /// own `Owned` and `tests/lanes.rs`'s own `RemoveOnDrop` already make.
    /// `an_inner_release_does_not_take_the_lock_from_the_caller_above`
    /// below discarded its own path into `_tmp` and never cleaned it up at
    /// all, on every run, not only a failing one.
    struct TmpDir(std::path::PathBuf);

    impl Drop for TmpDir {
        fn drop(&mut self) {
            std::fs::remove_dir_all(&self.0).ok();
        }
    }

    fn seeded_ctx(name: &str) -> (TmpDir, Ctx) {
        let tmp = std::env::temp_dir().join(format!("vivac-ops-{name}-{}", id::ulid()));
        let store = Store::create(&tmp).unwrap();
        (TmpDir(tmp), Ctx::load(store, Whose::Founding).unwrap())
    }

    #[test]
    fn taking_the_write_lock_twice_does_not_deadlock() {
        let (_tmp, mut ctx) = seeded_ctx("relock");
        ctx.lock_for_write().unwrap();
        ctx.lock_for_write()
            .expect("a second take blocked on the first");
        ctx.unlock();
    }

    #[test]
    fn an_inner_release_does_not_take_the_lock_from_the_caller_above() {
        let (_tmp, mut ctx) = seeded_ctx("inner-release");
        assert!(
            ctx.lock_for_write().unwrap(),
            "the first take should be the one that locks"
        );
        let mine = ctx.lock_for_write().unwrap();
        assert!(
            !mine,
            "a second take must not claim the lock it already holds"
        );
        if mine {
            ctx.unlock();
        }
        assert!(
            ctx.holds_write_lock(),
            "an inner release dropped the caller's lock"
        );
        ctx.unlock();
    }

    /// `t594`: `lock_for_write` used to reload the tree by
    /// assigning `self.tree` directly, the one call site `adopt` did not
    /// yet cover, so a context on a lane other than `main` that reloaded
    /// under the lock -- because a second writer appended while it
    /// waited, exactly the two-writer scenario this whole stretch of work
    /// exists for -- came back reading `main` while its own store signed
    /// as the lane it actually is.
    #[test]
    fn a_reload_under_the_lock_keeps_answering_from_its_own_lane() {
        let tmp = std::env::temp_dir().join(format!("vivac-ops-lane-reload-{}", id::ulid()));
        let store = Store::create(&tmp).unwrap();
        let located = crate::store::Located {
            root: tmp.clone(),
            lane_dir: tmp.clone(),
            lane: Some(crate::lane::Lane {
                version: 1,
                id: "b".to_string(),
                project: String::new(),
            }),
            worktree: None,
        };
        let mut ctx = Ctx::load(store, Whose::Resolved(&located)).unwrap();

        // A second writer, signing as `main`, appends underneath: the
        // seam `lock_for_write` reloads for.
        let mut other = Store::open(tmp.clone()).unwrap();
        let lock = other.lock_for_write().unwrap();
        other
            .append(
                &lock,
                crate::lane::MAIN,
                vec![Body::Pushed {
                    node: "ghost".to_string(),
                }],
                0,
                false,
            )
            .unwrap();
        drop(lock);

        ctx.lock_for_write().unwrap();
        assert_eq!(
            ctx.tree.lane(),
            "b",
            "the reload under the lock forgot which lane this context is"
        );
        ctx.unlock();
        std::fs::remove_dir_all(&tmp).ok();
    }

    // -----------------------------------------------------------------
    // `t594` tramo 4, task 3: when `where.changed` gets written (ยง9.1.4).
    // -----------------------------------------------------------------

    fn where_tmp(name: &str) -> PathBuf {
        std::env::temp_dir().join(format!("vivac-ops-where-{name}-{}", id::ulid()))
    }

    fn where_git(dir: &Path, args: &[&str]) {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    fn where_git_repo_with_one_commit(at: &Path) {
        std::fs::create_dir_all(at).unwrap();
        where_git(at, &["init", "-q"]);
        where_git(at, &["config", "user.email", "t@example.com"]);
        where_git(at, &["config", "user.name", "t"]);
        std::fs::write(at.join("f.txt"), "x").unwrap();
        where_git(at, &["add", "."]);
        where_git(at, &["commit", "-q", "-m", "first"]);
    }

    fn where_head_sha(dir: &Path) -> String {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(["rev-parse", "HEAD"])
            .output()
            .unwrap();
        assert!(out.status.success());
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    /// A tree whose only lane declares one repository at `path`.
    fn tree_with_repo(lane: &str, path: &str) -> Tree {
        let mut tree = Tree::default();
        tree.lanes.insert(
            lane.to_string(),
            crate::model::LaneState {
                repos: vec![crate::event::Repo {
                    path: path.to_string(),
                    root: None,
                }],
                ..Default::default()
            },
        );
        tree
    }

    fn push_where(tree: &mut Tree, seq: u64, lane: &str, repos: Vec<crate::event::WhereRepo>) {
        tree.wheres.push(crate::model::Where {
            seq,
            lane: lane.to_string(),
            repos,
        });
    }

    #[test]
    fn the_first_write_of_a_lane_with_repositories_always_carries_its_where() {
        let t = where_tmp("first-write");
        where_git_repo_with_one_commit(&t);
        where_git(&t, &["checkout", "-q", "-b", "develop"]);
        let tree = tree_with_repo("main", ".");

        let Some(Body::WhereChanged { repos }) = where_to_write(&tree, "main", &t) else {
            panic!("the first write of a lane with repositories must carry a where")
        };

        assert_eq!(repos[0].branch.as_deref(), Some("develop"));
        std::fs::remove_dir_all(&t).ok();
    }

    #[test]
    fn another_branch_writes_a_where() {
        let t = where_tmp("another-branch");
        where_git_repo_with_one_commit(&t);
        where_git(&t, &["checkout", "-q", "-b", "feature"]);
        let mut tree = tree_with_repo("main", ".");
        push_where(
            &mut tree,
            1,
            "main",
            vec![crate::event::WhereRepo {
                path: ".".into(),
                branch: Some("develop".into()),
                ..Default::default()
            }],
        );

        assert!(matches!(
            where_to_write(&tree, "main", &t),
            Some(Body::WhereChanged { .. })
        ));
        std::fs::remove_dir_all(&t).ok();
    }

    #[test]
    fn a_new_commit_on_the_same_branch_writes_nothing() {
        // The sha inside a branch is what the stops anchor (ยง4.4). Writing a
        // where per commit would put one event per commit in the log.
        let t = where_tmp("same-branch");
        where_git_repo_with_one_commit(&t);
        where_git(&t, &["checkout", "-q", "-b", "develop"]);
        let mut tree = tree_with_repo("main", ".");
        push_where(
            &mut tree,
            1,
            "main",
            vec![crate::event::WhereRepo {
                path: ".".into(),
                branch: Some("develop".into()),
                ..Default::default()
            }],
        );
        std::fs::write(t.join("g.txt"), "y").unwrap();
        where_git(&t, &["add", "."]);
        where_git(&t, &["commit", "-q", "-m", "second"]);

        assert!(where_to_write(&tree, "main", &t).is_none());
        std::fs::remove_dir_all(&t).ok();
    }

    #[test]
    fn a_rebase_in_progress_does_not_write_one_per_commit() {
        let t = where_tmp("rebase-progress");
        where_git_repo_with_one_commit(&t);
        let gitdir = t.join(".git");
        std::fs::create_dir_all(gitdir.join("rebase-merge")).unwrap();
        std::fs::write(
            gitdir.join("rebase-merge").join("head-name"),
            "refs/heads/side\n",
        )
        .unwrap();
        let mut tree = tree_with_repo("main", ".");
        push_where(
            &mut tree,
            1,
            "main",
            vec![crate::event::WhereRepo {
                path: ".".into(),
                branch: Some("side".into()),
                rebasing: true,
                ..Default::default()
            }],
        );

        assert!(where_to_write(&tree, "main", &t).is_none());
        std::fs::remove_dir_all(&t).ok();
    }

    #[test]
    fn a_different_detached_sha_writes_a_where() {
        let t = where_tmp("detached-sha");
        where_git_repo_with_one_commit(&t);
        let head = where_head_sha(&t);
        where_git(&t, &["checkout", "-q", &head]);
        let mut tree = tree_with_repo("main", ".");
        push_where(
            &mut tree,
            1,
            "main",
            vec![crate::event::WhereRepo {
                path: ".".into(),
                sha: Some("a".repeat(40)),
                ..Default::default()
            }],
        );

        let Some(Body::WhereChanged { repos }) = where_to_write(&tree, "main", &t) else {
            panic!("a different detached sha must carry a where")
        };

        assert_eq!(repos[0].sha.as_deref(), Some(head.as_str()));
        std::fs::remove_dir_all(&t).ok();
    }

    #[test]
    fn a_repository_that_appeared_or_vanished_writes_a_where() {
        let t = where_tmp("vanished");
        std::fs::create_dir_all(&t).unwrap();
        let mut tree = tree_with_repo("main", ".");
        push_where(
            &mut tree,
            1,
            "main",
            vec![crate::event::WhereRepo {
                path: ".".into(),
                branch: Some("develop".into()),
                ..Default::default()
            }],
        );

        let Some(Body::WhereChanged { repos }) = where_to_write(&tree, "main", &t) else {
            panic!("a repository that vanished must carry a where")
        };

        assert!(repos[0].missing);
        std::fs::remove_dir_all(&t).ok();
    }

    #[test]
    fn a_lane_with_no_declared_repositories_never_writes_one() {
        // This is ยง2.6 itself: a tree where nobody ran `setup` has no
        // declared repositories, so it keeps receiving exactly what 0.11
        // wrote.
        let t = where_tmp("no-repos");
        where_git_repo_with_one_commit(&t);
        let tree = Tree::default();

        assert!(where_to_write(&tree, "main", &t).is_none());
        std::fs::remove_dir_all(&t).ok();
    }

    #[test]
    fn a_branch_name_the_guard_refuses_is_withheld_and_its_sha_kept() {
        let t = where_tmp("withheld-branch");
        where_git_repo_with_one_commit(&t);
        let secret_branch = format!("ghp_{}", "a".repeat(30));
        where_git(&t, &["checkout", "-q", "-b", &secret_branch]);
        let tree = tree_with_repo("main", ".");

        let Some(Body::WhereChanged { repos }) = where_to_write(&tree, "main", &t) else {
            panic!("a branch the guard refuses still has to carry its sha")
        };

        assert!(
            repos[0].withheld,
            "a secret-looking branch name must be withheld"
        );
        assert!(
            repos[0].branch.is_none(),
            "a withheld name is not written down"
        );
        assert!(repos[0].sha.is_some(), "the sha survives (d600)");
        std::fs::remove_dir_all(&t).ok();
    }
}