vivac 0.15.5

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
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
//! What the maintainer reads.
//!
//! All ASCII and not one colour escape. The DX pillar is explicit: **meaning
//! is never encoded in colour alone**, and this has to degrade without
//! breaking --with no tty, over ssh, and in cmd.exe as well as Windows
//! Terminal--. `[x]`, `[~]`, `*` and `<== FALSE CLOSE` read in black and
//! white. Colour, when it lands, reinforces; it does not inform.
//!
//! Every render has its `--json` twin, which is the other half of the
//! audience: the agent needs parseable output, not a drawn tree.

use crate::anchor::AnchorRef;
use crate::args::Args;
use crate::brief::clip;
use crate::event::{Body, Event, Kind, State, WhereRepo};
use crate::failure::{Failure, R};
use crate::model::{Aggregates, Node, Tree, Vivac, Where};
use crate::output::outln;
use crate::style::{self, Stream};
use serde_json::json;
use std::collections::HashMap;
use std::path::Path;
use unicode_normalization::char::canonical_combining_class;
use unicode_normalization::UnicodeNormalization;

pub(crate) const WIDTH: usize = 62;

/// `d330`: how much of an ancestor's why/note/outcome survives in `why`
/// without `--full`. Matches `WIDTH` on purpose -- a clipped ancestor
/// collapses to roughly one wrapped line -- and it never applies to the
/// node actually asked about, which stays whole with or without `--full`.
const ANCESTOR_CLIP: usize = WIDTH;

/// `d771`: how many open siblings or open children `why` lists -- in prose
/// and in JSON alike -- before it points at `--full` for the rest. `f769`
/// measured `in_parallel` alone at 6.6 of an 8.3 KB `why --json` on a real
/// tree, paid on every step of orientation; this is the budget that keeps
/// it from growing without bound as a tree does.
const WHY_OPEN_CAP: usize = 8;

pub(crate) fn wrap(text: &str, width: usize, indent: &str) -> Vec<String> {
    if text.trim().is_empty() {
        return vec![];
    }
    let mut lines = Vec::new();
    let mut cur = String::new();
    for p in text.split_whitespace() {
        if !cur.is_empty() && cur.chars().count() + 1 + p.chars().count() > width {
            lines.push(format!("{indent}{cur}"));
            cur = p.to_string();
        } else {
            if !cur.is_empty() {
                cur.push(' ');
            }
            cur.push_str(p);
        }
    }
    if !cur.is_empty() {
        lines.push(format!("{indent}{cur}"));
    }
    lines
}

/// The `  [state]` suffix a title carries once it is not open any more --
/// empty for `State::Active`, since there is nothing to say about a node
/// still open.
fn state_suffix(n: &Node) -> String {
    match n.state {
        State::Active => String::new(),
        e => format!("  [{}]", e.word(n.kind)),
    }
}

/// `state_suffix`, coloured by state (`d795`): done green, parked yellow,
/// abandoned red, anything else -- today only superseded -- dim. Empty
/// for a node still open, the same as the text it colours.
fn state_suffix_styled(stream: Stream, n: &Node) -> String {
    let suffix = state_suffix(n);
    if suffix.is_empty() {
        return suffix;
    }
    match n.state {
        State::Active => suffix,
        State::Done => style::good(stream, &suffix),
        State::Suspended => style::change(stream, &suffix),
        State::Abandoned => style::gone(stream, &suffix),
        State::Superseded => style::dim(stream, &suffix),
    }
}

/// Already fully styled text that comes after a wrapped title -- on the
/// same line when `lead` plus the last chunk plus `len` still fits under
/// [`print_title_row`]'s own `cap`, on a continuation line of its own
/// otherwise. `len` is `text`'s plain width, since an escape code must
/// never count toward it. Empty for a row with nothing to say after the
/// title, `open`'s and most of `why`'s own rows among them.
pub(crate) struct TitleSuffix<'a> {
    pub(crate) text: &'a str,
    pub(crate) len: usize,
}

/// Prints an alias-and-title row that wraps `title` at the terminal's
/// width when one is known (`d795`), with every continuation line
/// indented back to the column the title started at. `first_line` is
/// everything already printed ahead of the title on line one -- already
/// styled, if at all -- and `lead` is its width in plain columns, since an
/// escape code must never count toward it. `cont_prefix` is the same
/// width in plain columns and printed literally ahead of every
/// continuation line -- spaces for `open` and `why`, a dim tree connector
/// for `tree`. `style_chunk` colours each wrapped piece of `title` itself
/// once wrapping has already decided where the breaks fall.
pub(crate) fn print_title_row(
    first_line: &str,
    cont_prefix: &str,
    lead: usize,
    title: &str,
    cap: Option<usize>,
    style_chunk: impl Fn(&str) -> String,
    suffix: TitleSuffix,
) {
    let mut chunks: Vec<String> = match cap {
        Some(w) => style::wrap_title(lead, title, w),
        None => vec![title.to_string()],
    };
    if chunks.is_empty() {
        chunks.push(String::new());
    }
    let suffix_own_line = match cap {
        None => false,
        Some(w) => {
            let last_len = chunks.last().unwrap().chars().count();
            !suffix.text.is_empty() && lead + last_len + suffix.len > w
        }
    };
    let last = chunks.len() - 1;
    for (i, chunk) in chunks.iter().enumerate() {
        let styled = style_chunk(chunk);
        let mut line = if i == 0 {
            format!("{first_line}{styled}")
        } else {
            format!("{cont_prefix}{styled}")
        };
        if i == last && !suffix_own_line {
            line.push_str(suffix.text);
        }
        outln!("{line}");
    }
    if suffix_own_line {
        outln!("{cont_prefix}{}", suffix.text);
    }
}

/// Colours the single leading `marker` character of a `why` note or
/// outcome line -- `!` or `=` -- leaving the rest of an already-wrapped
/// line untouched. Only the first line of a wrapped note or outcome
/// carries the marker at all; every other line is passed through as it
/// is, so calling this on those is harmless.
fn style_marker(line: &str, indent: &str, marker: char, styled: impl Fn(&str) -> String) -> String {
    let needle = format!("{indent}{marker}");
    match line.strip_prefix(&needle) {
        Some(rest) => format!("{indent}{}{rest}", styled(&marker.to_string())),
        None => line.to_string(),
    }
}

fn json_node(a: &Tree, ag: &Aggregates, n: &Node) -> serde_json::Value {
    let r = ag.counts(n.num);
    let mut v = json!({
        "id": n.id,
        "alias": n.alias(),
        "num": n.num,
        "kind": n.kind,
        "title": n.title(a),
        "why": n.why(a),
        "state": n.state,
        "blocks": n.blocks,
        "parent": n.parent.and_then(|p| a.node_by_num(p).map(|x| x.alias())),
        "note": n.note(a),
        "notes": n.notes(a)
            .iter()
            .map(|(at, text)| json!({"at": at, "note": text}))
            .collect::<Vec<_>>(),
        "outcome": n.outcome(a),
        "refs": n.refs(a),
        "governs": n.governs(a),
        // `d797`: `opened`/`closed` carry a date, not a full instant --
        // they always have -- so this is the same local date the text
        // shows, not the UTC instant `notes`'s own `at` above stays.
        "opened": crate::clock::date_of(n.opened(a)),
        "closed": n.closed(a).map(crate::clock::date_of),
        "false_close": n.state == State::Done && ag.blockers(n.num) > 0,
        "open_below": r.open_count,
        "total_below": r.total,
    });
    // `t411`: a rule gains `arms`, and no other kind gains anything -- the
    // JSON of every other kind stays byte for byte what it already was.
    // `arms` is **always** present on a rule, empty or not, so a reader can
    // tell "judged" apart from "not a rule" without a second lookup.
    if n.kind == Kind::Rule {
        v["arms"] = arms_json(a, n);
    }
    // `t426` §3.2: a decision gains `against` only when its `node.created`
    // carried the key, or a late declaration was folded into a birth that
    // never did. Everything else -- every other kind, and a decision with
    // neither -- stays byte for byte what it already was.
    if n.kind == Kind::Decision && (n.against_recorded || !n.against.is_empty()) {
        v["against"] = against_json(a, n);
    }
    v
}

pub(crate) fn print_json(v: serde_json::Value) -> R {
    outln!(
        "{}",
        serde_json::to_string_pretty(&v).map_err(std::io::Error::other)?
    );
    Ok(())
}

/// `why` — why we are here. It is the operation that defines the product.
///
/// It narrates the path from the root and then answers the three questions
/// that come next: what was left open in parallel, what was born here, and
/// what keeps each step of the path from closing.
///
/// `--full` adds three more, per step of the path and on `node` itself: the
/// anchor in force when that step was born, the decisions born there that
/// still stand, and the siblings that were still open at that moment. The
/// first two answer from `node`'s own birth (`Node::born_seq`,
/// `Node::born_lane`); the third cannot, because closing is folded away to
/// the final state, and this is a question about a moment in the past.
/// `Full` answers it from the log directly.
///
/// Only the log gives a moment a `seq`: `ts` alone ties within the same day,
/// and this project has had days with 23 stops on it, so a comparison by
/// date would be wrong on exactly the days it matters.
pub(crate) struct Full {
    /// Node id -> every `state.changed` it ever had, in log order. A node can
    /// be reopened, so this is not "the one time it closed": it is the whole
    /// history, searched for whatever it was at a given `seq`. This is the
    /// one thing a folded `Tree` cannot answer on its own -- closing folds
    /// away to the final state -- so it is the only thing left here
    /// (`t594` tramo 7: `created` and `born_lane` moved onto `Node` itself).
    state: HashMap<String, Vec<(u64, State)>>,
}

impl Full {
    pub(crate) fn from_log(log: &[Event]) -> Full {
        let mut state: HashMap<String, Vec<(u64, State)>> = HashMap::new();
        for e in log {
            if let Body::StateChanged { node, state: s, .. } = &e.payload {
                state.entry(node.clone()).or_default().push((e.seq, *s));
            }
        }
        Full { state }
    }

    /// What a node's state was at `seq`, inclusive. With no `state.changed`
    /// at or before it, the node was still in the one it is born with.
    fn state_at(&self, id: &str, seq: u64) -> State {
        self.state
            .get(id)
            .into_iter()
            .flatten()
            .rfind(|(s, _)| *s <= seq)
            .map(|(_, state)| *state)
            .unwrap_or(State::Active)
    }
}

/// The anchor in force when `n` was born: the most recent stop at or before
/// the `seq` of its `node.created`, and its anchor. Empty with nothing
/// earlier to point to -- there is no version control, or the node predates
/// every stop -- and that is a value, not a failure.
///
/// **Deliberately not filtered by lane**, unlike `reconcile::reference`
/// (`last_vivac`, `t594` task 6): `reconcile` compares *this folder's own*
/// git against the anchor of a stop, so that stop has to be this lane's;
/// asking any other lane's would compare against a commit this checkout
/// may not even have. `anchor_of` answers a different question -- what
/// commit was in `HEAD` when `n` itself was born, a property of the node,
/// not of whoever is asking -- and a node born in a lane other than the
/// reader's stays answered from that lane's own history. The answer can
/// name a commit this checkout does not have; that is honest, since the
/// node was born somewhere else, not a bug to filter away.
///
/// [`born_where`] asks the same question with a branch attached, and falls
/// back to this answer for a tree with no `where.changed` of its own
/// (`t594` §5.4): that is what keeps every stop written before this tranche
/// reading exactly as it did.
pub(crate) fn anchor_of(a: &Tree, n: &Node) -> AnchorRef {
    a.vivacs
        .iter()
        .rfind(|v| v.seq <= n.born_seq)
        .map(|v| v.anchor.clone())
        .unwrap_or_default()
}

/// Where `n` was born: the last `where.changed` of **its own lane** at or
/// before the `seq` of its `node.created`. With none -- a tree from before
/// lanes, or a lane with no repositories -- the answer falls back to the
/// anchor of the last stop, which is what [`anchor_of`] has always given.
/// Same mechanism, one question deeper.
pub(crate) fn born_where<'a>(a: &'a Tree, n: &Node) -> Option<&'a Where> {
    let lane = n.born_lane(a);
    a.wheres
        .iter()
        .rfind(|w| w.lane == lane && w.seq <= n.born_seq)
}

/// The decisions born from `n` that still stand: a filter over what
/// `born_here` already lists, kept to the ones that are a decision and still
/// open. Superseding one closes it, so a superseded decision drops out on
/// its own.
pub(crate) fn standing_of<'a>(a: &'a Tree, n: &Node) -> Vec<&'a Node> {
    a.children(n.num)
        .into_iter()
        .filter(|c| c.kind == Kind::Decision && c.state.is_open())
        .collect()
}

/// What `n` is waiting on: its open blockers, and only while `n` is itself
/// open. A closed node with open blockers is not a debt, it is a false
/// close, and `tree` reports that in those words instead.
///
/// It lives here rather than in either caller because both `why` and the
/// lineage page draw it, and `WEB.md` §2 is the reason: a page picks no
/// nodes of its own. Two implementations of this filter could disagree
/// about a node's debts, and nothing would catch it (`f380`).
pub(crate) fn blocking_of<'a>(a: &'a Tree, n: &Node) -> Vec<&'a Node> {
    if n.state.is_open() {
        a.open_blockers(n.num)
    } else {
        Vec::new()
    }
}

/// The siblings of `n`, born before it by `Node::num`, that were still open
/// at the `seq` `n` was born. Not by `closed`'s date: two siblings can open
/// and close on the day `n` was born, in an order the date cannot tell
/// apart.
pub(crate) fn open_then_of<'a>(a: &'a Tree, full: &Full, n: &Node) -> Vec<&'a Node> {
    let Some(parent) = n.parent else {
        return vec![];
    };
    a.children(parent)
        .into_iter()
        .filter(|c| c.id != n.id && c.num < n.num)
        .filter(|c| full.state_at(&c.id, n.born_seq).is_open())
        .collect()
}

/// A handle: the four fields a reader needs to recognise a node and go ask
/// `why` about it, nothing more. `open_data` prints the same four (plus
/// `lineage`, which why has no use for: a path's siblings already share a
/// parent, and whatever is born here already hangs off the node itself).
/// `t465` put this everywhere `why`'s JSON used to hand back a whole
/// [`json_node`] for something the prose only ever names -- a sibling, a
/// child, a blocker, a standing decision.
fn handle_json(a: &Tree, n: &Node) -> serde_json::Value {
    json!({
        "alias": n.alias(),
        "kind": n.kind,
        "state": n.state,
        "title": n.title(a),
    })
}

/// `d771`'s own selection: which of `nodes` -- an open sibling list or an
/// open child list, already in birth order -- `why` actually prints, and how
/// many were left out. `full` skips the cap entirely, the escape hatch every
/// capped list in this file gives (`open`'s own `--all`, `tree`'s own).
///
/// Otherwise every one that blocks stays in no matter how many there are --
/// a blocker is never hidden -- and the remaining seats, up to
/// [`WHY_OPEN_CAP`] altogether, go to whichever are the most recently
/// opened. The result comes back in the same birth order the caller already
/// prints in, since which ones made the cut is the only thing this decides.
fn cap_open(nodes: Vec<&Node>, full: bool) -> (Vec<&Node>, usize) {
    if full || nodes.len() <= WHY_OPEN_CAP {
        return (nodes, 0);
    }
    let total = nodes.len();
    let (blockers, mut rest): (Vec<&Node>, Vec<&Node>) = nodes.into_iter().partition(|n| n.blocks);
    rest.sort_by_key(|n| std::cmp::Reverse(n.num));
    let room = WHY_OPEN_CAP.saturating_sub(blockers.len());
    let mut kept = blockers;
    kept.extend(rest.into_iter().take(room));
    let more = total - kept.len();
    kept.sort_by_key(|n| n.num);
    (kept, more)
}

/// Adds `lane` and `where` when [`born_where`] has an answer for `n` --
/// shared by [`json_node_full`] and [`path_step_json`]'s own `--full` half,
/// so the whole node and every step of the path gain the same two fields
/// the same way (`t594` §5.4). Absent, not `null`, with none: a tree with no
/// `where.changed` gains neither field, which is what keeps its JSON byte
/// for byte what it already was.
fn add_born_where(a: &Tree, n: &Node, v: &mut serde_json::Value) {
    if let Some(w) = born_where(a, n) {
        v["lane"] = json!(w.lane);
        v["where"] = json!(w.repos);
    }
}

/// `json_node`, with the three `--full` fields added -- `standing` and
/// `open_then` as handles now rather than whole nodes (`t465`): the prose
/// `print_full_of` prints only their aliases, and the JSON used to carry the
/// rest of each one for nothing.
fn json_node_full(a: &Tree, ag: &Aggregates, full: &Full, n: &Node) -> serde_json::Value {
    let mut v = json_node(a, ag, n);
    v["anchor"] = json!(anchor_of(a, n));
    v["standing"] = json!(standing_of(a, n)
        .iter()
        .map(|c| handle_json(a, c))
        .collect::<Vec<_>>());
    v["open_then"] = json!(open_then_of(a, full, n)
        .iter()
        .map(|c| handle_json(a, c))
        .collect::<Vec<_>>());
    add_born_where(a, n, &mut v);
    v
}

/// One step of `path`: an ancestor's handle plus the body the prose actually
/// reads out loud, clipped the same way and by the same `ANCESTOR_CLIP` the
/// text render of `why` uses, and whole under `--full`. Unlike a handle,
/// `notes` carries every one of them rather than only the latest, because
/// the prose does too -- but there is no `note` field here: it would only be
/// the last of `notes` again, and `f440` found most of a path's weight was
/// one note carried twice exactly that way.
///
/// `below` is `ag.counts`, the same three fields the prose folds into one
/// phrase after every step but the last: open, closed and parked, always all
/// three, because a zero here is an answer and not an absence.
///
/// What it deliberately drops: `id`, `num`, `blocks`, `parent`, `refs`,
/// `governs`, `opened`, `closed`, `false_close`, `total_below`. The prose
/// never prints any of them for an ancestor, and whoever wants them can ask
/// `why` about that alias directly.
///
/// Two fields depend on the kind of the step, and each follows the prose. A
/// rule carries `arms` with or without `--full`, because `why` prints a
/// rule's arms on every step of the path (`f549`). A decision carries
/// `against` only under `--full`, because that is the only time the prose
/// prints an ancestor's declarations (`d330`, `d469`). Both are built by
/// the same functions [`json_node`] uses, so a step and a node cannot read
/// either one differently.
///
/// `lane` and `where` answer from `p`'s own birth with or without `--full`
/// (`t594` §5.4); `full` only ever backs `open_then`, the one question a
/// folded `Tree` cannot answer on its own. `full_extra` is `--full` itself,
/// gating its own three fields -- `anchor`, `standing`, `open_then` -- and
/// whether a body prints whole or clipped.
fn path_step_json(
    a: &Tree,
    ag: &Aggregates,
    full: &Full,
    full_extra: bool,
    p: &Node,
) -> serde_json::Value {
    let body = |text: &str| {
        if full_extra {
            text.to_string()
        } else {
            clip(text, ANCESTOR_CLIP)
        }
    };
    let below = ag.counts(p.num);
    let mut v = json!({
        "alias": p.alias(),
        "kind": p.kind,
        "state": p.state,
        "title": p.title(a),
        "why": body(p.why(a)),
        "notes": p.notes(a)
            .iter()
            .map(|(at, text)| json!({"at": at, "note": body(text)}))
            .collect::<Vec<_>>(),
        "outcome": body(p.outcome(a)),
        "below": {
            "open": below.open_count,
            "closed": below.closed_count,
            "parked": below.parked_nodes,
        },
    });
    if p.kind == Kind::Rule {
        v["arms"] = arms_json(a, p);
    }
    if full_extra && p.kind == Kind::Decision && (p.against_recorded || !p.against.is_empty()) {
        v["against"] = against_json(a, p);
    }
    add_born_where(a, p, &mut v);
    if full_extra {
        v["anchor"] = json!(anchor_of(a, p));
        v["standing"] = json!(standing_of(a, p)
            .iter()
            .map(|c| handle_json(a, c))
            .collect::<Vec<_>>());
        v["open_then"] = json!(open_then_of(a, full, p)
            .iter()
            .map(|c| handle_json(a, c))
            .collect::<Vec<_>>());
    }
    v
}

/// `why` as data.
///
/// The builder and the printing are two functions, the way `brief.rs` has
/// always had them: `to_text` builds and `brief` prints one line lower. It
/// matters more than tidiness here, because a second reader --the MCP server--
/// speaks JSON-RPC over the same standard output. A `println!` in its path
/// does not look untidy, it corrupts the channel.
///
/// `full` is the whole log folded, always -- `t594` §5.4: `lane` and
/// `where` answer for the node in view whether or not `--full` was given,
/// the same as the prose. `full_extra` is `--full` itself, gating only its
/// own three fields: `anchor`, `standing`, `open_then`. `why_data` hands
/// this an empty [`Full`] and `full_extra: false` for a caller with no log
/// to give it, such as a foreign project's tree -- `lane` and `where` are
/// then absent too, since there is nothing to answer them from.
///
/// `node` is the one whole [`json_node`], the reason anybody asked. Every
/// other field the prose only ever names, so `t465` cut each down to match:
/// `path` to a clipped [`path_step_json`] per ancestor, `in_parallel` and
/// `born_here` to a [`handle_json`] each, and `blockers` to one entry per
/// path step -- node included -- naming what `blocking_of` says still keeps
/// it from closing. `f440` measured what the old shape cost on a real tree:
/// 86,894 bytes for one `why --json`, 89% of it `in_parallel` alone, against
/// 3,685 for the prose answering the same question. Over a copy of the same
/// tree, both numbers from the same harness, it is 7,139 now.
fn why_data_impl(
    a: &Tree,
    full: &Full,
    full_extra: bool,
    id: &str,
) -> Result<serde_json::Value, Failure> {
    let ag = &a.aggregates();
    // `id` can also name a stop, not only a node: `why` is the verb that
    // opens whatever an alias names, and the brief prints a stop's alias in
    // the same shape as a node's (`f547`). A stop that resolves stands on
    // its own, so it short-circuits here rather than falling through the
    // node-shaped body below.
    let n = match a.resolve(id) {
        Some(n) => n,
        None => {
            return a
                .vivac(id)
                .map(|v| vivac_json(a, v))
                .ok_or_else(|| Failure::usage(format!("No such node: {id}.")));
        }
    };
    let lineage = a.ancestors(n.num);
    let mut node_json = if full_extra {
        json_node_full(a, ag, full, n)
    } else {
        let mut v = json_node(a, ag, n);
        add_born_where(a, n, &mut v);
        v
    };
    // `t429`'s second fix: the JSON names the hidden claimants too, and
    // `t594` widens `hidden` to a list, since a hand-edited log can hand the
    // same `num` to more than two -- the same claimants the prose names, in
    // the same order.
    let hidden: Vec<&str> = a
        .repeated_nums
        .iter()
        .filter(|d| d.num == n.num)
        .map(|d| d.second.as_str())
        .collect();
    if !hidden.is_empty() {
        node_json["repeated"] = json!({"num": n.num, "hidden": hidden});
    }
    let open_siblings: Vec<&Node> = n
        .parent
        .map(|p| a.children(p))
        .unwrap_or_default()
        .into_iter()
        .filter(|c| c.id != n.id && c.state.is_open())
        .collect();
    let (siblings, in_parallel_more) = cap_open(open_siblings, full_extra);
    let siblings: Vec<_> = siblings.into_iter().map(|c| handle_json(a, c)).collect();
    let open_children: Vec<&Node> = a
        .children(n.num)
        .into_iter()
        .filter(|c| c.state.is_open())
        .collect();
    let (born_here, born_here_more) = cap_open(open_children, full_extra);
    let born_here: Vec<_> = born_here
        .into_iter()
        .map(|c| {
            let mut v = handle_json(a, c);
            v["blocks"] = json!(c.blocks);
            v
        })
        .collect();
    // Every step of the path, node included -- the same walk the prose's own
    // "does not close until" loop makes -- kept to the ones `blocking_of`
    // answers non-empty. A closed step drops out on its own: it is a false
    // close, not a debt, and `tree` and `triage` report it as one instead.
    let blockers: Vec<_> = lineage
        .iter()
        .filter_map(|p| {
            let until = blocking_of(a, p);
            (!until.is_empty()).then(|| {
                json!({
                    "blocked": p.alias(),
                    "until": until.iter().map(|c| handle_json(a, c)).collect::<Vec<_>>(),
                })
            })
        })
        .collect();
    Ok(json!({
        "node": node_json,
        "path": lineage[..lineage.len().saturating_sub(1)]
            .iter()
            .map(|p| path_step_json(a, ag, full, full_extra, p))
            .collect::<Vec<_>>(),
        "in_parallel": siblings,
        "in_parallel_more": in_parallel_more,
        "born_here": born_here,
        "born_here_more": born_here_more,
        "blockers": blockers,
    }))
}

/// The plain read, over whatever log the caller has: the MCP tool's local
/// path folds its resident one (`t594` §5.4, `lane` and `where`); its
/// foreign-project path hands back `&[]`, the same as `why --project`
/// always has, since a foreign log is never read that way.
///
/// `full` is `d771`'s own door: `vivac_why`'s own `full` argument, wired
/// straight to the same `full_extra` the CLI's `--full` sets, so the tool
/// answers exactly what `why --full --json` does with nothing of its own
/// to drift from it.
pub fn why_data(
    a: &Tree,
    log: &[Event],
    id: &str,
    full: bool,
) -> Result<serde_json::Value, Failure> {
    why_data_impl(a, &Full::from_log(log), full, id)
}

/// A front, identified by its alias and where it hangs, not the node itself:
/// `why` on the alias brings the rest.
///
/// This used to be `json_node`'s eighteen keys plus `lineage`: the shape
/// `why` gives the one node it is asked about, and until `t465` gave every
/// other node it named as well. The prose `open` prints was already the
/// right shape -- alias, title, path -- and the data was not; `d172` made the
/// same fix for `find` first, down to dropping `matched`, which has no
/// analogue here because there is no query.
/// Measured over the same 10,000-node tree, both numbers from the same
/// harness: the MCP payload was 1,993,053 bytes and is now 599,012, 30% of
/// what it cost before.
pub fn open_data(a: &Tree) -> serde_json::Value {
    let ag = a.aggregates();
    let mut leaves: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| n.is_front() && !a.children(n.num).iter().any(|c| c.is_front()))
        .collect();
    // `sort_by_cached_key` and not `sort_by_key`: the second calls the key
    // function O(n log n) times, and this key goes to the aggregate map every
    // time it is called. It was measured, and the difference did not come up
    // out of the noise on this machine -- so it is here for being the right
    // primitive against a key that costs a lookup, not for a number.
    leaves.sort_by_cached_key(|n| {
        (
            !n.blocks,
            std::cmp::Reverse(ag.counts(n.num).total),
            std::cmp::Reverse(n.num),
        )
    });
    json!(leaves
        .iter()
        .map(|n| json!({
            "alias": n.alias(),
            "kind": n.kind,
            "state": n.state,
            "title": n.title(a),
            "lineage": lineage_of(a, n),
        }))
        .collect::<Vec<_>>())
}

/// What a person reads for a lane that is not necessarily the one in view:
/// its own declared name when it has one, the lane's own id otherwise. The
/// same fallback `Tree::lane_name` uses for the lane currently in view,
/// generalised to any lane -- `born_where` can name one nobody is reading
/// from right now.
fn lane_display<'a>(a: &'a Tree, id: &'a str) -> &'a str {
    match a.lanes.get(id) {
        Some(s) if !s.name.is_empty() => s.name.as_str(),
        _ => id,
    }
}

/// One repository's piece of a "born in lane" line: `path@branch`, falling
/// back to the sha when there is no branch to name and to the bare path
/// when neither survived. A branch the redaction guard withheld reads with
/// the phrase `d600` and §2.4 give it.
fn describe_repo(r: &WhereRepo) -> String {
    if r.withheld {
        return format!("{} (branch name withheld: it looked like a secret)", r.path);
    }
    match (&r.branch, &r.sha) {
        (Some(b), _) => format!("{}@{b}", r.path),
        (None, Some(sha)) => format!("{}@{}", r.path, &sha[..sha.len().min(7)]),
        (None, None) => r.path.clone(),
    }
}

/// The one branch every repository shares, if there is one -- what collapses
/// several repositories into "N repos on `<branch>`" rather than naming each.
fn same_branch(repos: &[WhereRepo]) -> Option<&str> {
    let first = repos.first()?.branch.as_deref()?;
    repos
        .iter()
        .all(|r| r.branch.as_deref() == Some(first))
        .then_some(first)
}

/// How a lane's repositories read on one line: one repository names itself;
/// several on the same branch collapse to a count; several on different
/// branches name up to three and count the rest, the same truncation
/// `brief.rs` already uses for a long list. The three shapes `t594` §5.4
/// gives.
fn describe_repos(repos: &[WhereRepo]) -> String {
    if let [one] = repos {
        return describe_repo(one);
    }
    if let Some(branch) = same_branch(repos) {
        return format!("{} repos on {branch}", repos.len());
    }
    let mut pieces: Vec<String> = repos.iter().take(3).map(describe_repo).collect();
    if repos.len() > 3 {
        pieces.push(format!("and {} more", repos.len() - 3));
    }
    pieces.join(", ")
}

/// The label `d596` asks for: what was decided on a branch the reader's own
/// lane has since left behind is not hidden, only marked. Compared only
/// within the born lane's own history -- never against another lane's,
/// which needs a repository's identity matched across lanes and is what
/// `t594`'s own task 6 builds.
fn branch_moved_since_birth(a: &Tree, born: &Where) -> bool {
    if born.lane != a.lane() {
        return false;
    }
    let Some(latest) = a.wheres.iter().rfind(|w| w.lane == born.lane) else {
        return false;
    };
    born.repos.iter().any(|b| {
        latest
            .repos
            .iter()
            .find(|l| l.path == b.path)
            .is_some_and(|l| l.branch != b.branch)
    })
}

/// The "born in lane" line §5.4 adds ahead of `anchor:` below, or nothing at
/// all for a tree with no `where.changed` -- `anchor_of` alone answers
/// those, exactly as it always has.
fn born_line(a: &Tree, n: &Node) -> Option<String> {
    let w = born_where(a, n)?;
    let mut line = format!(
        "born in lane {} · {}",
        lane_display(a, &w.lane),
        describe_repos(&w.repos)
    );
    if branch_moved_since_birth(a, w) {
        line.push_str(" (not the branch you are on)");
    }
    Some(line)
}

/// The `--full` lines for one step of the path, printed the way the JSON
/// twin carries the same three fields: the anchor, the decisions still
/// standing, and the siblings still open at that moment. The "born in lane"
/// line is not one of them: `t594` §5.4 has it print with or without
/// `--full`, so the caller prints it on its own, ahead of these.
fn print_full_of(a: &Tree, full: &Full, n: &Node) {
    let anchor = anchor_of(a, n);
    if anchor.is_empty_tree() {
        outln!("        anchor: none");
    } else {
        outln!("        anchor: {} ({})", anchor.short(), anchor.kind);
    }
    let out = Stream::Out;
    let standing = standing_of(a, n);
    if !standing.is_empty() {
        outln!(
            "        standing ({}): {}",
            standing.len(),
            standing
                .iter()
                .map(|d| style::kind_id(out, d.kind, &d.alias()))
                .collect::<Vec<_>>()
                .join(", ")
        );
    }
    let open_then = open_then_of(a, full, n);
    if !open_then.is_empty() {
        outln!(
            "        open then ({}): {}",
            open_then.len(),
            open_then
                .iter()
                .map(|d| style::kind_id(out, d.kind, &d.alias()))
                .collect::<Vec<_>>()
                .join(", ")
        );
    }
}

/// `why` on a stop's own alias: the whole stop, prose-shaped the way `why`
/// shapes a node -- same header, same rule below it, `Safe stop` where a
/// node says `Why we are here` (`f547`, `d651`). Unlike the brief's own
/// `next_intent`, nothing here is clipped: the clip is exactly what sends a
/// reader here to begin with.
fn safe_stop(a: &Tree, v: &Vivac, args: &Args) -> R {
    if args.has("json") {
        return print_json(vivac_json(a, v));
    }
    outln!();
    outln!("  Safe stop  ->  {}", v.alias());
    outln!("  {}", "-".repeat(66));
    outln!();
    let mut header = format!(
        "  {} · {} · {}",
        v.alias(),
        v.kind.word(),
        crate::clock::date_of(&v.ts)
    );
    if let Some(anchor) = crate::model::anchoring(&v.anchor, &v.anchors) {
        header.push_str(&format!(" · {anchor}"));
    }
    outln!("{header}");
    if let Some(node) = v.node_ref.as_deref().and_then(|r| a.node(r)) {
        outln!("         written at {:<6}{}", node.alias(), node.title(a));
    }
    if !v.label.is_empty() {
        outln!("         \"{}\"", v.label);
    }
    if !v.next_intent.is_empty() {
        outln!("         you were about to: {}", v.next_intent);
    }
    outln!();
    outln!("  The stack it carried");
    if v.stack.is_empty() {
        outln!("    empty stack");
    } else {
        for (alias, title) in &v.stack {
            outln!("    {:<6} {}", alias, title);
        }
    }
    if !v.working_set.is_empty() {
        outln!();
        outln!("  Working set");
        for w in &v.working_set {
            outln!("    {w}");
        }
    }
    outln!();
    outln!("  vivac restore {}  rebuilds this stack", v.alias());
    outln!();
    Ok(())
}

pub fn why(a: &Tree, log: &[Event], args: &Args) -> R {
    let ag = &a.aggregates();
    let s = args
        .positional(0)
        .ok_or_else(|| Failure::usage("usage: vivac why <id>"))?;
    // `id` can also name a stop the brief printed (`f547`): `why` is the
    // verb that opens whatever an alias names, and a stop's alias reads the
    // same shape as a node's. A stop wins whenever a node does not resolve;
    // it never shares a prefix with any `Kind`, so the two cannot collide.
    let n = match a.resolve(s) {
        Some(n) => n,
        None => {
            return match a.vivac(s) {
                Some(v) => safe_stop(a, v, args),
                None => Err(Failure::usage(format!("No such node: {s}."))),
            };
        }
    };
    let lineage = a.ancestors(n.num);
    // `t594` §5.4: "born in lane" answers for the node in view whether or
    // not `--full` was given, straight off its own birth -- `log` is only
    // for `Full`'s own `state`, which nothing here touches unless
    // `full_extra` asks `open_then_of` for it, so `log` is empty exactly
    // when the caller had no reason to read past the derived index
    // (`t594` tramo 7). `full_extra` is `--full` itself, gating only its
    // own three fields per step.
    let full_data = Full::from_log(log);
    let full_extra = args.has("full");

    if args.has("json") {
        return print_json(why_data_impl(a, &full_data, full_extra, s)?);
    }

    let out = Stream::Out;
    outln!();
    outln!(
        "  {}  {}  {}",
        style::bold(out, "Why we are here"),
        style::dim(out, "->"),
        style::kind_id(out, n.kind, &n.alias())
    );
    outln!("  {}", style::dim(out, &"-".repeat(66)));
    // A hand-edited log can hand the same `num` to more than two claimants;
    // every one but the first is hidden the same way, so all of them are
    // named here, not just whichever the fold met second.
    let hidden: Vec<&str> = a
        .repeated_nums
        .iter()
        .filter(|d| d.num == n.num)
        .map(|d| d.second.as_str())
        .collect();
    if !hidden.is_empty() {
        let (noun, pronoun) = if hidden.len() == 1 {
            ("another node", "it")
        } else {
            ("other nodes", "them")
        };
        outln!(
            "  {} also names {noun}, {}, which this tree cannot show. vivac check lists {pronoun}.",
            n.alias(),
            hidden.join(", ")
        );
    }
    outln!();
    let cap = style::width(out).map(|w| w.saturating_sub(1));
    for (i, p) in lineage.iter().enumerate() {
        let is_last = i == lineage.len() - 1;
        // The node actually asked about prints whole either way; an
        // ancestor's body only survives whole under `--full`.
        let clip_body = !is_last && !full_extra;
        // `f715`: a clipped ancestor is only one wrapped line if the clip
        // itself leaves room for whatever gets printed in front of it --
        // `ANCESTOR_CLIP` alone is only correct for a bare line, and three
        // of the four lines below carry a prefix.
        let body = |text: &str, prefix: usize| {
            if clip_body {
                clip(text, ANCESTOR_CLIP.saturating_sub(prefix))
            } else {
                text.to_string()
            }
        };
        let alias = p.alias();
        let alias_field = format!(
            "{}{}",
            style::kind_id(out, p.kind, &alias),
            " ".repeat(6usize.saturating_sub(alias.chars().count()))
        );
        let suffix = state_suffix_styled(out, p);
        let suffix_len = state_suffix(p).chars().count();
        print_title_row(
            &format!("  {alias_field}"),
            &" ".repeat(8),
            8,
            p.title(a),
            cap,
            |chunk| style::bold(out, chunk),
            TitleSuffix {
                text: &suffix,
                len: suffix_len,
            },
        );
        // `t411` §6: a rule shows its arms, in the same words `rules` prints
        // them with.
        if p.kind == Kind::Rule {
            print_arms(a, p, "        ", true, false);
        }
        // `t426` §3.1: a decision shows its declarations right where a rule
        // shows its arms -- behind the alias line, ahead of the body.
        // `d330`'s own rule: they show for the node actually asked about,
        // and for an ancestor only under `--full`.
        if p.kind == Kind::Decision && (is_last || full_extra) {
            print_against(a, p, "        ");
        }
        for l in wrap(&body(p.why(a), 0), WIDTH, "        ") {
            outln!("{l}");
        }
        let notes = p.notes(a);
        if notes.len() > 1 {
            // Two or more: each one gets its own line and its own date, or
            // there would be no way to tell which correction landed when.
            // With exactly one, a date says nothing a lone note does not
            // already say by being there -- `f186`'s own argument for
            // dropping the lineage's empty anchor.
            for (at, text) in &notes {
                let date = crate::clock::date_of(at);
                let prefix = format!("! [{date}] ");
                let prefix_len = prefix.chars().count();
                for (li, l) in wrap(
                    &format!("{prefix}{}", body(text, prefix_len)),
                    WIDTH,
                    "        ",
                )
                .iter()
                .enumerate()
                {
                    if li == 0 {
                        outln!(
                            "{}",
                            style_marker(l, "        ", '!', |s| style::bold(
                                out,
                                &style::warn(out, s)
                            ))
                        );
                    } else {
                        outln!("{l}");
                    }
                }
            }
        } else {
            let note = p.note(a);
            let prefix = "! ";
            for (li, l) in wrap(
                &format!("{prefix}{}", body(note, prefix.chars().count())),
                WIDTH,
                "        ",
            )
            .iter()
            .enumerate()
            {
                if !note.is_empty() {
                    if li == 0 {
                        outln!(
                            "{}",
                            style_marker(l, "        ", '!', |s| style::bold(
                                out,
                                &style::warn(out, s)
                            ))
                        );
                    } else {
                        outln!("{l}");
                    }
                }
            }
        }
        let outcome = p.outcome(a);
        let prefix = "= ";
        for (li, l) in wrap(
            &format!("{prefix}{}", body(outcome, prefix.chars().count())),
            WIDTH,
            "        ",
        )
        .iter()
        .enumerate()
        {
            if !outcome.is_empty() {
                if li == 0 {
                    outln!(
                        "{}",
                        style_marker(l, "        ", '=', |s| style::bold(
                            out,
                            &style::good(out, s)
                        ))
                    );
                } else {
                    outln!("{l}");
                }
            }
        }
        // `t594` §5.4: prints with or without `--full`, unlike the rest of
        // `print_full_of` below it.
        if let Some(line) = born_line(a, p) {
            outln!("        {}", style::dim(out, &line));
        }
        if full_extra {
            print_full_of(a, &full_data, p);
        }
        if !is_last {
            let f = ag.counts(p.num).phrase();
            if !f.is_empty() {
                outln!("        {}", style::dim(out, &format!("({f} below)")));
            }
            outln!("        {}", style::dim(out, "|"));
            outln!("        {}", style::dim(out, "v"));
        } else {
            outln!();
            outln!(
                "        {}",
                style::bold(out, &style::warn(out, "^^^ you are here"))
            );
        }
    }
    outln!();

    // "we had ten things to review, we are on the first"
    if let Some(parent) = n.parent {
        let siblings: Vec<_> = a
            .children(parent)
            .into_iter()
            .filter(|c| c.id != n.id && c.state.is_open())
            .collect();
        if !siblings.is_empty() {
            outln!(
                "  {}",
                style::bold(
                    out,
                    &format!("In parallel, still open ({}):", siblings.len())
                )
            );
            let (shown, more) = cap_open(siblings, full_extra);
            for c in shown {
                print_why_list_row(out, "      ", c, a, cap);
            }
            // `d771`: never silent about what the cap left out -- the same
            // rule `open --all` and `tree --all` already give their own cut
            // lists, spelled out for this one instead of assumed.
            if more > 0 {
                outln!(
                    "      {}",
                    style::dim(
                        out,
                        &format!("+ {more} more:  vivac why {} --full", n.alias())
                    )
                );
            }
            outln!();
        }
    }

    let kids: Vec<_> = a
        .children(n.num)
        .into_iter()
        .filter(|c| c.state.is_open())
        .collect();
    if !kids.is_empty() {
        outln!(
            "  {}",
            style::bold(out, &format!("Born here and still open ({}):", kids.len()))
        );
        let (shown, more) = cap_open(kids, full_extra);
        for c in shown {
            let marker = if c.blocks {
                style::bold(out, &style::gone(out, "*"))
            } else {
                " ".to_string()
            };
            print_why_list_row(out, &format!("    {marker} "), c, a, cap);
        }
        if more > 0 {
            outln!(
                "      {}",
                style::dim(
                    out,
                    &format!("+ {more} more:  vivac why {} --full", n.alias())
                )
            );
        }
        outln!();
    }

    for p in &lineage {
        let pending_count = blocking_of(a, p);
        if !pending_count.is_empty() {
            outln!(
                "  {}",
                style::bold(
                    out,
                    &format!(
                        "{} does not close until these close ({}):",
                        p.alias(),
                        pending_count.len()
                    )
                )
            );
            for c in pending_count {
                print_why_list_row(out, "      ", c, a, cap);
            }
            outln!();
        }
    }
    Ok(())
}

/// One row of `why`'s three closing lists: `In parallel`, `Born here` and
/// `X does not close until these close`. `row_prefix` is everything
/// printed ahead of the alias, already styled if at all -- six plain
/// columns either way, whether that is six bare spaces or four spaces, a
/// blocks marker and one more.
fn print_why_list_row(out: Stream, row_prefix: &str, c: &Node, a: &Tree, cap: Option<usize>) {
    const LEAD: usize = 13;
    let alias = c.alias();
    let alias_field = format!(
        "{}{}",
        style::kind_id(out, c.kind, &alias),
        " ".repeat(6usize.saturating_sub(alias.chars().count()))
    );
    let first_line = format!("{row_prefix}{alias_field} ");
    print_title_row(
        &first_line,
        &" ".repeat(LEAD),
        LEAD,
        c.title(a),
        cap,
        |chunk| chunk.to_string(),
        TitleSuffix { text: "", len: 0 },
    );
}

fn branch(a: &Tree, ag: &Aggregates, n: &Node, prefix: &str, is_last: bool, show_all: bool) {
    let out = Stream::Out;
    let f = ag.counts(n.num).phrase();
    let pending_count = ag.blockers(n.num);
    let false_close = n.state == State::Done && pending_count > 0;
    let mut tail_plain = if f.is_empty() {
        String::new()
    } else {
        format!("   ({f})")
    };
    if false_close {
        tail_plain.push_str(&format!(
            "   <== FALSE CLOSE: {pending_count} open condition(s)"
        ));
    }
    let mut tail_styled = String::new();
    if !f.is_empty() {
        tail_styled.push_str(&style::dim(out, &format!("   ({f})")));
    }
    if false_close {
        tail_styled.push_str(&style::bold(
            out,
            &style::gone(
                out,
                &format!("   <== FALSE CLOSE: {pending_count} open condition(s)"),
            ),
        ));
    }

    let blocks_marker = if n.blocks { "* " } else { "" };
    let marker_styled = if n.blocks {
        style::bold(out, &style::gone(out, blocks_marker))
    } else {
        String::new()
    };
    let connector = if is_last { "`-- " } else { "|-- " };
    let alias = n.alias();
    let closed = n.state != State::Active;

    // Everything printed ahead of the title on line one: `prefix`,
    // `connector`, `[<mark>] `, the alias padded to six columns, then the
    // blocks marker. `15` is `connector`'s own four columns plus
    // `[X] ` (four) plus the alias field's trailing space (one), plus the
    // six the alias itself always takes.
    let lead = prefix.chars().count() + 15 + blocks_marker.chars().count();
    let alias_field = format!(
        "{}{}",
        style::kind_id(out, n.kind, &alias),
        " ".repeat(6usize.saturating_sub(alias.chars().count()))
    );
    let first_line = format!(
        "{}{}{} {alias_field} {marker_styled}",
        style::dim(out, prefix),
        style::dim(out, connector),
        style::mark(out, n.state),
    );

    let sig = format!("{prefix}{}", if is_last { "    " } else { "|   " });
    let children: Vec<_> = a
        .children(n.num)
        .into_iter()
        .filter(|h| show_all || h.state.is_open() || ag.counts(h.num).open_count > 0)
        .collect();
    let cont_char = if children.is_empty() { " " } else { "|" };
    let cont_prefix = style::dim(out, &format!("{sig}{cont_char}"));
    let cont_pad = " ".repeat(10 + blocks_marker.chars().count());
    let cont_line = format!("{cont_prefix}{cont_pad}");

    print_title_row(
        &first_line,
        &cont_line,
        lead,
        n.title(a),
        style::width(out).map(|w| w.saturating_sub(1)),
        |chunk| {
            if closed {
                style::dim(out, chunk)
            } else {
                chunk.to_string()
            }
        },
        TitleSuffix {
            text: &tail_styled,
            len: tail_plain.chars().count(),
        },
    );

    for (i, h) in children.iter().enumerate() {
        branch(a, ag, h, &sig, i == children.len() - 1, show_all);
    }
}

/// `t429`'s second fix, by `d423`'s rule: a number two nodes share is
/// something this tree can only show one half of, so it says which half.
fn repeated_lines(a: &Tree) -> Vec<String> {
    a.repeated_nums
        .iter()
        .map(|d| {
            format!(
                "  {} is repeated: {} is shown and {} is not. vivac check lists every one.",
                d.num, d.first, d.second
            )
        })
        .collect()
}

fn subtree_json(a: &Tree, ag: &Aggregates, n: &Node) -> serde_json::Value {
    let mut v = json_node(a, ag, n);
    v["children"] = json!(a
        .children(n.num)
        .iter()
        .map(|h| subtree_json(a, ag, h))
        .collect::<Vec<_>>());
    v
}

pub fn tree(a: &Tree, args: &Args) -> R {
    let ag = &a.aggregates();
    let roots: Vec<&Node> = match args.positional(0) {
        Some(s) => vec![a
            .resolve(s)
            .ok_or_else(|| Failure::usage(format!("No such node: {s}.")))?],
        None => a.roots(),
    };
    if args.has("json") {
        return print_json(json!(roots
            .iter()
            .map(|n| subtree_json(a, ag, n))
            .collect::<Vec<_>>()));
    }
    if a.is_empty_tree() {
        outln!("  Empty tree.  vivac push \"<title>\" --why \"<reason>\"");
        return Ok(());
    }
    let show_all = args.has("all");
    outln!();
    for (i, n) in roots.iter().enumerate() {
        branch(a, ag, n, "  ", i == roots.len() - 1, show_all);
    }
    outln!();
    let repeated = repeated_lines(a);
    if !repeated.is_empty() {
        for l in &repeated {
            outln!("{l}");
        }
        outln!();
    }
    if !show_all {
        outln!(
            "  {}",
            style::dim(
                Stream::Out,
                "(closed nodes with no open descendants hidden; --all shows them)"
            )
        );
        outln!();
    }
    Ok(())
}

/// Fronts printed before the list gives way to the tail line. Each front
/// costs two lines, so ten of them plus the header and the tail still fit
/// one screen with nothing to scroll -- and a list that has to scroll
/// already broke the promise of "right now".
const MAX_FRONTS_SHOWN: usize = 10;

/// `open` — what is waiting for you right now, and what has been open so
/// long you are not actually working it any more (`d383`). The order below
/// is deduced from that sentence, not chosen and explained after: a
/// blocker sorts first, because a blocker is exactly something waiting on
/// you; among the rest, whichever holds up more tree; at a tie, the newest.
pub fn open(a: &Tree, args: &Args) -> R {
    let ag = a.aggregates();
    let mut leaves: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| n.is_front() && !a.children(n.num).iter().any(|c| c.is_front()))
        .collect();
    // `sort_by_cached_key` and not `sort_by_key`: the second calls the key
    // function O(n log n) times, and this key goes to the aggregate map every
    // time it is called. It was measured, and the difference did not come up
    // out of the noise on this machine -- so it is here for being the right
    // primitive against a key that costs a lookup, not for a number.
    leaves.sort_by_cached_key(|n| {
        (
            !n.blocks,
            std::cmp::Reverse(ag.counts(n.num).total),
            std::cmp::Reverse(n.num),
        )
    });
    let standing = a
        .nodes_iter()
        .filter(|n| n.kind == Kind::Decision && n.state.is_open())
        .count();
    if args.has("json") {
        return print_json(open_data(a));
    }
    if leaves.is_empty() && standing == 0 {
        outln!("  Nothing open.");
        return Ok(());
    }
    let out = Stream::Out;
    outln!();
    outln!(
        "  {}",
        style::bold(
            out,
            &format!(
                "{} open front{}",
                leaves.len(),
                if leaves.len() == 1 { "" } else { "s" },
            )
        )
    );
    outln!();
    let show_all = args.has("all");
    let shown = if show_all {
        leaves.len()
    } else {
        leaves.len().min(MAX_FRONTS_SHOWN)
    };
    let cap = style::width(out).map(|w| w.saturating_sub(1));
    for n in &leaves[..shown] {
        let alias = n.alias();
        let alias_field = format!(
            "{}{}",
            style::kind_id(out, n.kind, &alias),
            " ".repeat(6usize.saturating_sub(alias.chars().count()))
        );
        print_title_row(
            &format!("  {alias_field} "),
            &" ".repeat(9),
            9,
            n.title(a),
            cap,
            |chunk| chunk.to_string(),
            TitleSuffix { text: "", len: 0 },
        );
        let lineage = a.ancestors(n.num);
        if lineage.len() > 1 {
            let sep = style::dim(out, " > ");
            let v: Vec<String> = lineage[..lineage.len() - 1]
                .iter()
                .map(|p| style::kind_id(out, p.kind, &p.alias()))
                .collect();
            outln!("         {} {}", style::dim(out, "via"), v.join(&sep));
        }
    }
    let hidden = leaves.len() - shown;
    if hidden > 0 {
        // The oldest of the ones left out, never of the whole set: a front
        // that made the cut is being worked, and its age is not the gap
        // `--all` closes.
        let oldest = leaves[shown..].iter().map(|n| n.opened(a)).min();
        let age = oldest.and_then(|d| crate::clock::days_between(d, &crate::clock::now_rfc3339()));
        // The same three arms the project index uses for a project that has
        // not moved. A count of days is the wrong shape at zero and at one,
        // and "open for 0 days" is a sentence nobody says.
        match age {
            Some(d) if d <= 0 => {
                outln!("  {hidden} more, the oldest opened today -- vivac open --all")
            }
            Some(1) => {
                outln!("  {hidden} more, the oldest open since yesterday -- vivac open --all")
            }
            Some(days) => {
                outln!("  {hidden} more, the oldest open for {days} days -- vivac open --all")
            }
            None => outln!("  {hidden} more -- vivac open --all"),
        }
    }
    // They are not fronts, but making them vanish without saying so would be
    // omitting in silence: they get counted and located.
    if standing > 0 {
        let phrase = if standing == 1 {
            "1 standing decision, which is not work".to_string()
        } else {
            format!("{standing} standing decisions, which are not work")
        };
        outln!();
        outln!(
            "  {}",
            style::dim(out, &format!("+ {phrase}   vivac brief"))
        );
    }
    outln!();
    Ok(())
}

/// The nearest ancestor of kind `Pillar`, climbing one parent at a time and
/// stopping at the first match. `None` when nothing above `n` is a pillar --
/// the climb still ends, at the root.
///
/// `rules`'s own performance budget (§5): a pass over the nodes plus this
/// climb for each rule, never a walk of the whole tree per rule.
fn nearest_pillar<'a>(a: &'a Tree, n: &Node) -> Option<&'a Node> {
    let mut cur = n.parent;
    while let Some(p) = cur {
        let node = a.node_by_num(p)?;
        if node.kind == Kind::Pillar {
            return Some(node);
        }
        cur = node.parent;
    }
    None
}

/// One pillar with the open rules that answer to it.
struct PillarSection<'a> {
    pillar: &'a Node,
    rules: Vec<&'a Node>,
}

/// The pull's own shape (`t411` §5): every pillar that still governs --
/// open, or closed with an open rule still hanging off it -- each with its
/// own open rules; the open rules that answer to no pillar; and every open
/// invariant. Built in one pass over the nodes plus the parent climb of
/// each rule, never a second walk of the tree.
struct RulesView<'a> {
    pillars: Vec<PillarSection<'a>>,
    orphan_rules: Vec<&'a Node>,
    invariants: Vec<&'a Node>,
}

fn rules_view(a: &Tree) -> RulesView<'_> {
    let mut under: HashMap<u64, Vec<&Node>> = HashMap::new();
    let mut orphan_rules: Vec<&Node> = Vec::new();
    for n in a.nodes_iter() {
        if n.kind == Kind::Rule && n.state.is_open() {
            match nearest_pillar(a, n) {
                Some(p) => under.entry(p.num).or_default().push(n),
                None => orphan_rules.push(n),
            }
        }
    }
    for v in under.values_mut() {
        v.sort_by_key(|n| n.num);
    }
    orphan_rules.sort_by_key(|n| n.num);

    let mut pillars: Vec<PillarSection> = a
        .nodes_iter()
        .filter(|n| n.kind == Kind::Pillar)
        .filter(|n| n.state.is_open() || under.get(&n.num).is_some_and(|v| !v.is_empty()))
        .map(|n| PillarSection {
            pillar: n,
            rules: under.get(&n.num).cloned().unwrap_or_default(),
        })
        .collect();
    pillars.sort_by_key(|s| s.pillar.num);

    let mut invariants: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| n.kind == Kind::Constraint && n.state.is_open())
        .collect();
    invariants.sort_by_key(|n| n.num);

    RulesView {
        pillars,
        orphan_rules,
        invariants,
    }
}

/// `rules --json` and `vivac_rules`'s own payload: the same builder, so the
/// two can never drift apart.
pub fn rules_data(a: &Tree) -> serde_json::Value {
    let ag = &a.aggregates();
    let view = rules_view(a);
    json!({
        "pillars": view.pillars.iter().map(|s| {
            let mut v = json_node(a, ag, s.pillar);
            v["rules"] = json!(s.rules.iter().map(|r| json_node(a, ag, r)).collect::<Vec<_>>());
            v
        }).collect::<Vec<_>>(),
        "rules": view.orphan_rules.iter().map(|r| json_node(a, ag, r)).collect::<Vec<_>>(),
        "invariants": view.invariants.iter().map(|n| json_node(a, ag, n)).collect::<Vec<_>>(),
    })
}

/// A rule's own arms, one per line. `indent` is whatever column the rule's
/// own title started at, so the line under it lines up. `show_judged`
/// prints `judged: no command verifies it` for a rule with none; `rules`
/// (`d421`) passes `false`, because there the line only repeats what the
/// rule's absent `armed:` lines already say by not being there, and `why`
/// (`t411` §6) passes `true`, because there it is the only line and it does
/// inform.
///
/// `dim` styles every line here as secondary text: `rules` passes `true`,
/// since its own aliases already carry the eye with `kind_id`; `why`
/// passes `false`, so its own already-styled prose stays exactly what
/// `d795` left it.
fn print_arms(a: &Tree, r: &Node, indent: &str, show_judged: bool, dim: bool) {
    let line = |s: String| {
        if dim {
            style::dim(Stream::Out, &s)
        } else {
            s
        }
    };
    let arms = r.arms(a);
    if arms.is_empty() {
        if show_judged {
            outln!(
                "{}",
                line(format!("{indent}judged: no command verifies it"))
            );
        }
    } else {
        for (dir, command) in arms {
            outln!("{}", line(format!("{indent}armed in {dir}/: {command}")));
        }
    }
}

/// The JSON for a rule's arms: the folder and the command of each one, in
/// the same order [`print_arms`] prints them, present even when empty so a
/// reader can tell a judged rule apart from a step that is not a rule at
/// all. Shared by [`json_node`] and [`path_step_json`] so a rule's arms read
/// the same value wherever `why` carries them (`f549`).
fn arms_json(a: &Tree, r: &Node) -> serde_json::Value {
    json!(r
        .arms(a)
        .into_iter()
        .map(|(dir, command)| json!({"dir": dir, "command": command}))
        .collect::<Vec<_>>())
}

/// A decision's own declarations, one per line, wrapped the same way its
/// body is: `judged against <alias>: <why>`, with `(declared <date>)`
/// appended for a late one. `t426` §3.1.
///
/// A pillar or rule that is no longer open is marked right after its alias
/// with the word `label()` puts behind a title, `[abandoned]` or `[closed]`,
/// so a reader does not have to go and look whether what was named still
/// governs (`d551`). An open one, and a dangling reference, carry no mark.
fn print_against(a: &Tree, n: &Node, indent: &str) {
    for e in n.against(a) {
        let mark = match e.target {
            Some((kind, state)) if !state.is_open() => format!(" [{}]", state.word(kind)),
            _ => String::new(),
        };
        let suffix = match e.declared {
            // `d797`: `declared` is a date, not a full instant -- the local
            // one, the same as everywhere else a bare date is shown.
            Some(ts) => format!("  (declared {})", crate::clock::date_of(ts)),
            None => String::new(),
        };
        let line = format!("judged against {}{mark}: {}{suffix}", e.alias, e.why);
        for l in wrap(&line, WIDTH, indent) {
            outln!("{l}");
        }
    }
}

/// A decision's declarations as JSON, one entry for each one
/// [`print_against`] prints and in the same order. `state` is there on every
/// entry, open or not, serialized the way a node's own `state` is and `null`
/// for a dangling reference: what the data carries cannot depend on what the
/// prose leaves unsaid (`d551`). Shared by [`json_node`] and
/// [`path_step_json`], so the two cannot read a declaration differently.
fn against_json(a: &Tree, n: &Node) -> serde_json::Value {
    json!(n
        .against(a)
        .into_iter()
        .map(|e| json!({
            "node": e.alias,
            "state": e.target.map(|(_, state)| state),
            "why": e.why,
            // `d797`: the same local date `print_against` shows, not the
            // full UTC instant -- `declared` was never a full instant.
            "declared": e.declared.map(crate::clock::date_of),
        }))
        .collect::<Vec<_>>())
}

/// `d422`: nobody hunting for what governs this project should have to
/// guess that a second, unread map exists. Printed once, after whichever of
/// `rules`'s two shapes just ran, and only when there was no open pillar and
/// no open rule for it to find.
fn print_second_map_hint() {
    let out = Stream::Out;
    outln!(
        "  {}",
        style::dim(
            out,
            "Rules kept in CLAUDE.md, AGENTS.md or a memory file are a second map, and"
        )
    );
    outln!(
        "  {}",
        style::dim(
            out,
            "vivac never reads them: bring them in with vivac add --type pillar|rule."
        )
    );
}

/// An alias, coloured by kind and padded to six columns -- the pillar and
/// rule field `rules` prints ahead of a title, on its own since `rules`
/// carries no trailing suffix or wrapped title to share `print_title_row`'s
/// machinery with.
fn rules_alias_field(out: Stream, n: &Node) -> String {
    let alias = n.alias();
    format!(
        "{}{}",
        style::kind_id(out, n.kind, &alias),
        " ".repeat(6usize.saturating_sub(alias.chars().count()))
    )
}

/// `rules` — the pull: everything that governs this project, read whether
/// or not the push ever carried it into a brief. `t411` §5.
pub fn rules(a: &Tree, args: &Args) -> R {
    if args.has("json") {
        return print_json(rules_data(a));
    }
    let view = rules_view(a);
    let total_rules: usize =
        view.pillars.iter().map(|s| s.rules.len()).sum::<usize>() + view.orphan_rules.len();
    let armed_rules = view
        .pillars
        .iter()
        .flat_map(|s| &s.rules)
        .chain(&view.orphan_rules)
        .filter(|r| !r.arms.is_empty())
        .count();
    let judged_rules = total_rules - armed_rules;
    // `d422`: true whenever there is no open pillar and no open rule for
    // this read to find, whether or not an invariant is still around.
    let nothing_governs = view.pillars.is_empty() && total_rules == 0;

    if nothing_governs && view.invariants.is_empty() {
        outln!("  Nothing governs this project yet: no pillars, rules or invariants.");
        outln!();
        print_second_map_hint();
        return Ok(());
    }

    let out = Stream::Out;
    outln!();
    if !view.pillars.is_empty() {
        outln!("  {}", style::bold(out, "PILLARS"));
        for s in &view.pillars {
            let closed = s.pillar.state != State::Active;
            let title = if closed {
                style::dim(out, s.pillar.title(a))
            } else {
                s.pillar.title(a).to_string()
            };
            outln!(
                "  {}{}{}",
                rules_alias_field(out, s.pillar),
                title,
                state_suffix_styled(out, s.pillar)
            );
            for r in &s.rules {
                outln!("    {}{}", rules_alias_field(out, r), r.title(a));
                print_arms(a, r, "          ", false, true);
            }
        }
    }
    if !view.orphan_rules.is_empty() {
        outln!();
        outln!("  {}", style::bold(out, "RULES WITHOUT A PILLAR"));
        for r in &view.orphan_rules {
            outln!("  {}{}", rules_alias_field(out, r), r.title(a));
            print_arms(a, r, "        ", false, true);
        }
    }
    if !view.invariants.is_empty() {
        outln!();
        outln!("  {}", style::bold(out, "INVARIANTS"));
        for n in &view.invariants {
            outln!("  {}{}", rules_alias_field(out, n), n.title(a));
        }
    }
    outln!();
    outln!(
        "  {}",
        style::dim(
            out,
            &format!(
                "{} pillar{} \u{b7} {} rule{}: {} armed, {} judged \u{b7} {} invariant{}",
                view.pillars.len(),
                if view.pillars.len() == 1 { "" } else { "s" },
                total_rules,
                if total_rules == 1 { "" } else { "s" },
                armed_rules,
                judged_rules,
                view.invariants.len(),
                if view.invariants.len() == 1 { "" } else { "s" },
            )
        )
    );
    outln!();
    if nothing_governs {
        print_second_map_hint();
    }
    Ok(())
}

/// `triage` — what can be pruned, and with which command.
///
/// A brief over budget **must not lie by omission** (`BRIEF-SPEC.md` §4):
/// the signal is that the graph needs pruning, and this is the view that says
/// where. `MODEL.md` §6.1 also sends it the deep nodes, because a chain that
/// long is almost never lack of discipline: it is that the goal moved and
/// nobody re-rooted.
pub fn triage(a: &Tree, args: &Args) -> R {
    let ag = &a.aggregates();

    let mut parked_nodes: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| n.state == State::Suspended)
        .collect();

    // `MODEL.md` §6.1: from 6 on it shows up here, and it never blocks. The
    // distance is to the goal the node answers to, not to the root: `promote`
    // is the way out this section prints, and a count from the root is one
    // `promote` cannot move (`f156`).
    let mut deep: Vec<(&Node, usize)> = a
        .nodes_iter()
        .filter(|n| n.is_front())
        .map(|n| (n, a.under_goal(n.num).len()))
        .filter(|(_, d)| *d >= 6)
        .collect();

    // Alive, hanging off something discarded. `abandon`'s rescue produces
    // them, and it does **not** reparent on purpose (`d33`): the node stays
    // where it was born. That is why they need revisiting now and then, and
    // why they are here and not in `check`: it is not store corruption, it is
    // work that lost the reason it was born for.
    let mut orphaned: Vec<(&Node, &Node)> = a
        .nodes_iter()
        .filter(|n| n.is_front())
        .filter_map(|n| {
            let p = a.node_by_num(n.parent?)?;
            (p.state == State::Abandoned).then_some((n, p))
        })
        .collect();

    // Invariant 10. `check` reports them for CI; here they get acted on, and
    // with the same exemption: a **forced** close was a decision, it has its
    // trace and the tree marks it. Repeating it here every day would be asking
    // for what was already decided to be decided again. What does land here is
    // the close that turned false later, when a blocker got hung on something
    // already closed: that is the case that took 26 days to spot.
    let mut false_closes: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| n.state == State::Done && !n.forced_close && ag.blockers(n.num) > 0)
        .collect();

    parked_nodes.sort_by_key(|n| n.num);
    deep.sort_by_key(|(n, _)| n.num);
    orphaned.sort_by_key(|(n, _)| n.num);
    false_closes.sort_by_key(|n| n.num);

    if args.has("json") {
        return print_json(json!({
            "parked": parked_nodes.iter().map(|n| json_node(a, ag, n)).collect::<Vec<_>>(),
            "deep": deep.iter().map(|(n, d)| {
                let mut v = json_node(a, ag, n);
                // Named for what it counts. `stats` reports a `depth` measured
                // from the root, and one key meaning two distances would be
                // read wrong exactly once.
                v["depth_from_goal"] = json!(d);
                v
            }).collect::<Vec<_>>(),
            "orphaned_by_discard": orphaned.iter().map(|(n, p)| {
                let mut v = json_node(a, ag, n);
                v["discarded"] = json!(p.alias());
                v["discarded_because"] = json!(p.outcome(a));
                v
            }).collect::<Vec<_>>(),
            "false_closes": false_closes.iter().map(|n| json_node(a, ag, n)).collect::<Vec<_>>(),
        }));
    }

    let total = parked_nodes.len() + deep.len() + orphaned.len() + false_closes.len();
    if total == 0 {
        outln!("  Nothing to prune.");
        return Ok(());
    }
    let out = Stream::Out;
    let cap = style::width(out).map(|w| w.saturating_sub(1));
    outln!();
    outln!(
        "  {}",
        style::bold(out, &format!("TRIAGE - {total} thing(s) to look at"))
    );

    if !parked_nodes.is_empty() {
        outln!();
        print_triage_heading(
            out,
            &format!("PARKED ({})", parked_nodes.len()),
            "focus <id>  |  abandon <id>",
        );
        for n in &parked_nodes {
            let alias = n.alias();
            let alias_field = format!(
                "{}{}",
                style::kind_id(out, n.kind, &alias),
                " ".repeat(6usize.saturating_sub(alias.chars().count()))
            );
            print_title_row(
                &format!("    {alias_field} "),
                &" ".repeat(11),
                11,
                n.title(a),
                cap,
                |chunk| chunk.to_string(),
                TitleSuffix { text: "", len: 0 },
            );
            for l in wrap(n.outcome(a), WIDTH, "           ") {
                outln!("{}", style::dim(out, &l));
            }
        }
    }

    if !deep.is_empty() {
        outln!();
        print_triage_heading(
            out,
            &format!("6 OR MORE FROM ITS GOAL ({})", deep.len()),
            "promote <id>",
        );
        for (n, d) in &deep {
            let alias = n.alias();
            outln!(
                "    {}{} {:<40} depth {d}",
                style::kind_id(out, n.kind, &alias),
                " ".repeat(6usize.saturating_sub(alias.chars().count())),
                clip(n.title(a), 40)
            );
            // The lineage starts where the number does. Drawing it from the
            // root beside a distance to the goal would say two things at once.
            let path = a.under_goal(n.num);
            let sep = style::dim(out, " > ");
            let v: Vec<String> = path[..path.len().saturating_sub(1)]
                .iter()
                .map(|p| style::kind_id(out, p.kind, &p.alias()))
                .collect();
            outln!("           {} {}", style::dim(out, "via"), v.join(&sep));
        }
    }

    if !orphaned.is_empty() {
        outln!();
        print_triage_heading(
            out,
            &format!("SURVIVED A DISCARD ({})", orphaned.len()),
            "abandon <id>  |  promote <id>",
        );
        for (n, p) in &orphaned {
            let alias = n.alias();
            let alias_field = format!(
                "{}{}",
                style::kind_id(out, n.kind, &alias),
                " ".repeat(6usize.saturating_sub(alias.chars().count()))
            );
            print_title_row(
                &format!("    {alias_field} "),
                &" ".repeat(11),
                11,
                n.title(a),
                cap,
                |chunk| chunk.to_string(),
                TitleSuffix { text: "", len: 0 },
            );
            outln!(
                "{}",
                style::dim(
                    out,
                    &format!(
                        "           born from {}, discarded: {}",
                        p.alias(),
                        clip(p.outcome(a), 36)
                    )
                )
            );
        }
    }

    if !false_closes.is_empty() {
        outln!();
        print_triage_heading(
            out,
            &format!("FALSE CLOSES ({})", false_closes.len()),
            "close what is left, or --force",
        );
        for n in &false_closes {
            let alias = n.alias();
            outln!(
                "    {}{} {} {}",
                style::kind_id(out, n.kind, &alias),
                " ".repeat(6usize.saturating_sub(alias.chars().count())),
                style::dim(out, &format!("{:<40}", clip(n.title(a), 40))),
                style::bold(
                    out,
                    &style::gone(out, &format!("{} blocker(s)", ag.blockers(n.num)))
                )
            );
        }
    }
    outln!();
    Ok(())
}

/// One triage section's heading: a bold label, padded to the column every
/// heading's own hint starts at in the plain text (36, the widest label
/// plus its own gap), then the hint dimmed. The padding is measured on
/// `label` alone, never on the styled span, so an escape code never counts
/// toward it.
fn print_triage_heading(out: Stream, label: &str, hint: &str) {
    let left = format!("  {label}");
    let pad = " ".repeat(36usize.saturating_sub(left.chars().count()));
    outln!("{}{pad}{}", style::bold(out, &left), style::dim(out, hint));
}

/// `parked` — DO NOT TOUCH NOW. It is the section no other tool emits: every
/// memory tool dumps what is relevant, and the problem in agentic development
/// is the opposite one, bounding.
pub fn parked(a: &Tree, args: &Args) -> R {
    let ag = &a.aggregates();
    let mut ps: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| n.state == State::Suspended)
        .collect();
    ps.sort_by_key(|n| n.num);
    if args.has("json") {
        return print_json(json!(ps
            .iter()
            .map(|n| json_node(a, ag, n))
            .collect::<Vec<_>>()));
    }
    if ps.is_empty() {
        outln!("  Nothing parked.");
        return Ok(());
    }
    let out = Stream::Out;
    outln!();
    outln!(
        "  {}",
        style::bold(out, &format!("DO NOT TOUCH NOW ({})", ps.len()))
    );
    outln!();
    let cap = style::width(out).map(|w| w.saturating_sub(1));
    for n in ps {
        let alias = n.alias();
        let alias_field = format!(
            "{}{}",
            style::kind_id(out, n.kind, &alias),
            " ".repeat(6usize.saturating_sub(alias.chars().count()))
        );
        print_title_row(
            &format!("  {alias_field} "),
            &" ".repeat(9),
            9,
            n.title(a),
            cap,
            |chunk| chunk.to_string(),
            TitleSuffix { text: "", len: 0 },
        );
        for l in wrap(n.outcome(a), WIDTH, "         ") {
            outln!("{}", style::dim(out, &l));
        }
    }
    outln!();
    Ok(())
}

/// `stack` — where you are right now, from the root to the focus. With
/// `--lanes` (`t594` §5.5), every lane's own stack instead of only this
/// folder's.
pub fn stack(a: &Tree, root: &Path, args: &Args) -> R {
    let ag = &a.aggregates();
    if args.has("lanes") {
        return stack_lanes(a, root, args, ag);
    }
    let stack: Vec<&Node> = a
        .stack()
        .iter()
        .filter_map(|&num| a.node_by_num(num))
        .collect();
    if args.has("json") {
        return print_json(json!({
            "depth": stack.len(),
            "stack": stack.iter().map(|n| json_node(a, ag, n)).collect::<Vec<_>>(),
        }));
    }
    if stack.is_empty() {
        outln!("  Empty stack.  vivac push \"<title>\" --why \"<reason>\"");
        return Ok(());
    }
    let out = Stream::Out;
    outln!();
    let cap = style::width(out).map(|w| w.saturating_sub(1));
    for (i, n) in stack.iter().enumerate() {
        let is_focus = i == stack.len() - 1;
        let margin = format!("  {}", "  ".repeat(i));
        let lead = margin.chars().count() + 7;
        let alias = n.alias();
        let alias_field = format!(
            "{}{}",
            style::kind_id(out, n.kind, &alias),
            " ".repeat(6usize.saturating_sub(alias.chars().count()))
        );
        let suffix_plain = if is_focus { "   <- focus" } else { "" };
        let suffix_styled = if is_focus {
            style::bold(out, &style::warn(out, suffix_plain))
        } else {
            String::new()
        };
        print_title_row(
            &format!("{margin}{alias_field} "),
            &" ".repeat(lead),
            lead,
            n.title(a),
            cap,
            |chunk| chunk.to_string(),
            TitleSuffix {
                text: &suffix_styled,
                len: suffix_plain.chars().count(),
            },
        );
    }
    outln!();
    if stack.len() >= 6 {
        outln!(
            "  {}",
            style::dim(
                out,
                &format!(
                    "Stack {} levels deep. Almost never lack of discipline: usually",
                    stack.len()
                )
            )
        );
        outln!(
            "  {}",
            style::dim(
                out,
                "the root goal moved and nobody re-rooted.  vivac promote"
            )
        );
        outln!();
    }
    Ok(())
}

/// `stack --lanes`'s own rows: every lane the tree knows of, this
/// folder's included, whether it has a front of its own or not (`f668`,
/// `brief::all_lanes`). The ones with a front sort first, the same way
/// OTHER LANES orders its own -- the most recent write first, `id`
/// breaking a tie -- and the ones without follow, sorted by name; a lane
/// that has never pushed has no `seq` of its own to sort by. Marked
/// `(folder gone)` rather than dropped: unlike OTHER LANES, this list
/// exists to name every lane, not only the ones still reachable
/// (decision 2 of `t594` §5.5).
///
/// `exists()` runs at most once per lane the registry knows of for this
/// project, and only when there is at least one row to check it against
/// (`f623`); without `--lanes`, `stack` never reaches this function at
/// all.
fn stack_lanes(a: &Tree, root: &Path, args: &Args, ag: &Aggregates) -> R {
    let mut rows = crate::brief::all_lanes(a);
    rows.sort_by(|x, y| {
        // A lane with a front sorts before one without, regardless of
        // `seq` or name: `bool`'s own order puts `false` (has a front)
        // ahead of `true` (does not).
        x.focus
            .is_none()
            .cmp(&y.focus.is_none())
            .then_with(|| match (x.focus, y.focus) {
                (Some(_), Some(_)) => y.seq.cmp(&x.seq).then_with(|| x.id.cmp(y.id)),
                _ => x.name.cmp(y.name),
            })
    });
    let gone = if rows.is_empty() {
        Vec::new()
    } else {
        crate::brief::gone_lane_ids(root).unwrap_or_default()
    };
    if args.has("json") {
        return print_json(json!({
            "lanes": rows
                .iter()
                .map(|r| json!({
                    "id": r.id,
                    "name": r.name,
                    "focus": match r.focus {
                        Some(focus) => json_node(a, ag, focus),
                        None => serde_json::Value::Null,
                    },
                    "folder_gone": gone.iter().any(|g| g == r.id),
                }))
                .collect::<Vec<_>>(),
        }));
    }
    if rows.is_empty() {
        outln!("  No lanes yet.  vivac init plants one.");
        return Ok(());
    }
    let out = Stream::Out;
    outln!();
    // A fixed-column table, name/alias/title/date each in its own field: a
    // title wrapped at the terminal's width would have to drag the date
    // along with it onto whichever line the wrap left it on, and that is a
    // second table underneath this one, not a styled version of it. What
    // stays fixed still gains the alias's own kind colour, and the two
    // tails that are not a lane's own data.
    for r in &rows {
        let tail = if gone.iter().any(|g| g == r.id) {
            style::dim(out, "  (folder gone)")
        } else {
            String::new()
        };
        match r.focus {
            Some(focus) => {
                let alias = focus.alias();
                let alias_field = format!(
                    "{}{}",
                    style::kind_id(out, focus.kind, &alias),
                    " ".repeat(6usize.saturating_sub(alias.chars().count()))
                );
                outln!(
                    "  {:<11} {alias_field} {:<45} {}{tail}",
                    r.name,
                    focus.title(a),
                    crate::clock::date_of(focus.opened(a))
                )
            }
            None => outln!(
                "  {:<11} {}{tail}",
                r.name,
                style::dim(out, "(nothing pushed yet)")
            ),
        }
    }
    outln!();
    Ok(())
}

pub fn stats(a: &Tree, args: &Args) -> R {
    let ag = &a.aggregates();
    let mut by_state = std::collections::BTreeMap::new();
    let mut orphans = 0usize;
    let mut false_closes = Vec::new();
    for n in a.nodes_iter() {
        *by_state.entry(n.state.word(n.kind)).or_insert(0usize) += 1;
        if n.parent.is_some_and(|p| a.node_by_num(p).is_none()) {
            orphans += 1;
        }
        if n.state == State::Done && ag.blockers(n.num) > 0 {
            false_closes.push(n);
        }
    }
    let depth_of = ag.max_depth;
    false_closes.sort_by_key(|n| n.num);
    if args.has("json") {
        return print_json(json!({
            "nodes": a.total(),
            "by_state": by_state,
            "depth": depth_of,
            "roots": a.roots().len(),
            "stack": a.stack_depth(),
            "orphans": orphans,
            "broken_lines": a.broken_lines,
            "false_closes": false_closes.iter().map(|n| json_node(a, ag, n)).collect::<Vec<_>>(),
        }));
    }
    let out = Stream::Out;
    outln!();
    outln!(
        "  nodes          {}",
        style::bold(out, &a.total().to_string())
    );
    for (k, v) in &by_state {
        outln!("  {k:<14} {}", style::bold(out, &v.to_string()));
    }
    outln!(
        "  depth          {}",
        style::bold(out, &depth_of.to_string())
    );
    outln!(
        "  roots          {}",
        style::bold(out, &a.roots().len().to_string())
    );
    outln!(
        "  stack          {}",
        style::bold(out, &a.stack_depth().to_string())
    );
    if orphans > 0 {
        outln!(
            "  ORPHANS        {}  <- broken provenance",
            style::bold(out, &orphans.to_string())
        );
    }
    if a.broken_lines > 0 {
        outln!(
            "  broken lines   {}  <- in .vivac/events",
            style::bold(out, &a.broken_lines.to_string())
        );
    }
    if !false_closes.is_empty() {
        outln!();
        outln!(
            "  {}",
            style::bold(out, &format!("FALSE CLOSES ({})", false_closes.len()))
        );
        for n in false_closes {
            let alias = n.alias();
            outln!(
                "      {}{}{}",
                style::kind_id(out, n.kind, &alias),
                " ".repeat(6usize.saturating_sub(alias.chars().count())),
                style::dim(out, n.title(a))
            );
        }
    }
    outln!();
    Ok(())
}

/// One stop's own JSON shape: what `vivacs --json` gives per entry, and what
/// `why` on a stop's own alias gives loose, since the two answer the same
/// question about the same stop and cannot be let drift apart from one
/// another.
fn vivac_json(a: &Tree, v: &Vivac) -> serde_json::Value {
    json!({
        "id": v.id,
        "alias": v.alias(),
        "node_ref": v.node_ref.as_ref().and_then(|r| a.node(r).map(|n| n.alias())),
        "kind": v.kind.word(),
        "ts": v.ts,
        "label": v.label,
        "next_intent": v.next_intent,
        "anchor": v.anchor,
        "anchors": v.anchors,
        "stack": v.stack.iter().map(|(al, t)| json!({"alias": al, "title": t}))
            .collect::<Vec<_>>(),
        "working_set": v.working_set,
    })
}

/// `vivacs` — the safe stops, latest first.
pub fn vivacs(a: &Tree, args: &Args) -> R {
    if args.has("json") {
        return print_json(json!(a
            .vivacs
            .iter()
            .rev()
            .map(|v| vivac_json(a, v))
            .collect::<Vec<_>>()));
    }
    if a.vivacs.is_empty() {
        outln!("  No stops yet.  vivac save \"<label>\"");
        return Ok(());
    }
    let out = Stream::Out;
    let cap = style::width(out).map(|w| w.saturating_sub(1));
    outln!();
    // The whole tree's catalogue, on purpose: `restore`/`--since` accept
    // any vivac by `num` (`model.rs`'s own `Tree::vivac`), not only the
    // lane's own, and filtering this list would hide a stop those commands
    // still take. With more than one lane, an active neighbour can still
    // push a lane's own stops out of the last twenty before it gets here,
    // and no row says which lane a stop belongs to -- both are `t594` §5,
    // not fixed here, only written down so it is not forgotten by omission
    // (`t594`).
    for v in a.vivacs.iter().rev().take(20) {
        let alias_field = format!("{:<5}", v.alias());
        let kind_field = format!("{:<7}", v.kind.word());
        let date = crate::clock::date_of(&v.ts);
        // Measured on the plain fields, never on `style::bold`'s own
        // escape codes: the same rule every wrapped row in this file
        // follows so a line that wraps still wraps at the right column.
        let plain_prefix_len = format!("  {alias_field} {kind_field} {date}  ")
            .chars()
            .count();
        let styled_prefix = format!("  {} {kind_field} {date}  ", style::bold(out, &alias_field));
        match v.stack.last() {
            Some((focus_alias, focus_title)) => {
                let lead = plain_prefix_len + focus_alias.chars().count() + 2;
                print_title_row(
                    &format!("{styled_prefix}{focus_alias}  "),
                    &" ".repeat(lead),
                    lead,
                    focus_title,
                    cap,
                    |chunk| chunk.to_string(),
                    TitleSuffix { text: "", len: 0 },
                );
            }
            None => outln!("{styled_prefix}empty stack"),
        }
        if !v.label.is_empty() {
            outln!("           {}", v.label);
        }
        if !v.next_intent.is_empty() {
            const INTENT_PREFIX: &str = "you were about to: ";
            let lead = 11 + INTENT_PREFIX.chars().count();
            print_title_row(
                &format!("           {}", style::dim(out, INTENT_PREFIX)),
                &" ".repeat(lead),
                lead,
                &v.next_intent,
                cap,
                |chunk| style::dim(out, chunk),
                TitleSuffix { text: "", len: 0 },
            );
        }
    }
    if a.vivacs.len() > 20 {
        outln!();
        outln!(
            "  {}",
            style::dim(out, &format!("... and {} more", a.vivacs.len() - 20))
        );
    }
    outln!();
    Ok(())
}

/// The fields of a node that carry meaning, in the order a reader wants them.
///
/// The title is a label; the reason, the notes and the outcome are where the
/// thinking is. A search that read only titles would find the folder and miss
/// what is inside it.
///
/// `f389`: every note lives here, not only the latest, or the search that
/// reads this misses the same 37 percent `why` used to.
fn searchable<'t>(a: &'t Tree, n: &Node) -> Vec<(&'static str, &'t str)> {
    let mut fields = vec![("title", n.title(a)), ("why", n.why(a))];
    fields.extend(n.notes(a).into_iter().map(|(_, text)| ("note", text)));
    fields.push(("outcome", n.outcome(a)));
    fields
}

/// The five Unicode blocks of combining diacritical marks: what [`fold`]
/// drops once `.nfd()` has split every precomposed letter into its base and
/// its marks. `ñ` folds to `n` and `ç` folds to `c` this way. A mark from a
/// script where it is not a diacritic -- a Hebrew point, a Devanagari matra
/// -- carries meaning of its own rather than decorating a Latin letter, sits
/// outside all five blocks, and stays.
fn is_diacritic(c: char) -> bool {
    matches!(c as u32,
        0x0300..=0x036F
            | 0x1AB0..=0x1AFF
            | 0x1DC0..=0x1DFF
            | 0x20D0..=0x20FF
            | 0xFE20..=0xFE2F
    )
}

/// Folds text so search stops caring about case or accent: `dueno` finds
/// `dueño`, `arbol` finds `árbol`, and a decomposed `e` + acute finds a
/// precomposed `é`.
///
/// Lower cases first -- `İ` (U+0130) lower cases to `i` followed by a
/// combining dot above, and that dot has to fall out with the rest of the
/// marks, not survive as a leftover -- then decomposes canonically and drops
/// every [`is_diacritic`] mark. `terms_of` and `hits_for` fold the query and
/// the fields it searches through this one function, so the two sides of a
/// `contains` check can never fold differently.
///
/// [`fold_with_origin`] is the same recipe with a map back to the original
/// text alongside it, for `snippet`, which needs to point at a byte of this
/// output and say which character of the source it came from. Both are
/// [`fold_into`], so they cannot disagree either.
pub(crate) fn fold(text: &str) -> String {
    let mut folded = String::with_capacity(text.len());
    fold_into(text, &mut folded, None);
    folded
}

/// [`fold`], plus a map from each byte of the folded string to the char
/// index of `text` it descends from.
pub(crate) fn fold_with_origin(text: &str) -> (String, Vec<usize>) {
    let mut folded = String::with_capacity(text.len());
    let mut origin = Vec::with_capacity(text.len());
    fold_into(text, &mut folded, Some(&mut origin));
    (folded, origin)
}

/// The one implementation of [`fold`], one segment at a time.
///
/// Not built by decomposing one character at a time: NFD's canonical
/// reordering can move a mark past another mark, but only within the run it
/// belongs to, and that run is anchored by the nearest starter before it (a
/// character of combining class zero) -- never further back and never past
/// the next one. Decomposing a character in isolation cannot reorder it
/// against its neighbours at all, so the two can disagree the moment a
/// source already carries two marks in a non-canonical order. Segmenting the
/// lower-cased text at each starter first, and folding one segment at a
/// time, reorders exactly the characters whole-string NFD would have
/// reordered, because canonical reordering never crosses a starter either.
/// A leading run of marks with no starter before it -- text that opens on a
/// combining character -- is a run with nothing to anchor it and is folded
/// as its own segment, the same as `.nfd()` on the whole string would treat
/// it.
///
/// Segments are also what makes this cheap, because most of what a tree
/// holds is ASCII. An ASCII character is a starter that decomposes to
/// itself, so a run of them is copied and lower cased in one go, the way
/// `str::to_lowercase` treats it, and only what is not ASCII is segmented
/// and pays for the tables. A mark that follows a run of ASCII opens a
/// segment of its own: the letter before it is never reordered, so the
/// marks after it reorder among themselves exactly as they would with it.
/// Measured on 10 000 nodes, sending every character through the tables
/// made `find` over MCP five times slower than lower casing had been, and
/// a loop that still went one character at a time left it twice as slow.
fn fold_into(text: &str, folded: &mut String, mut origin: Option<&mut Vec<usize>>) {
    let mut segment = String::new();
    let mut segment_at = 0;
    // The char index of `rest`'s first char in `text`.
    let mut at = 0;
    let mut rest = text;
    while !rest.is_empty() {
        let ascii = rest
            .bytes()
            .position(|b| !b.is_ascii())
            .unwrap_or(rest.len());
        if ascii > 0 {
            if !segment.is_empty() {
                fold_segment(&segment, segment_at, folded, origin.as_deref_mut());
                segment.clear();
            }
            let (run, tail) = rest.split_at(ascii);
            let start = folded.len();
            folded.push_str(run);
            folded[start..].make_ascii_lowercase();
            if let Some(origin) = origin.as_deref_mut() {
                origin.extend(at..at + ascii);
            }
            at += ascii;
            rest = tail;
            continue;
        }
        let c = rest.chars().next().expect("rest is not empty");
        // Lower casing one char can produce more than one -- `İ` becomes
        // two -- and both descend from that char's index.
        for lc in c.to_lowercase() {
            if canonical_combining_class(lc) == 0 && !segment.is_empty() {
                fold_segment(&segment, segment_at, folded, origin.as_deref_mut());
                segment.clear();
            }
            if segment.is_empty() {
                segment_at = at;
            }
            segment.push(lc);
        }
        at += 1;
        rest = &rest[c.len_utf8()..];
    }
    if !segment.is_empty() {
        fold_segment(&segment, segment_at, folded, origin);
    }
}

/// One segment of [`fold_into`], every byte it emits mapped to `at`.
fn fold_segment(
    segment: &str,
    at: usize,
    folded: &mut String,
    mut origin: Option<&mut Vec<usize>>,
) {
    // One byte is one ASCII character, already lower cased, and NFD leaves
    // it as it is: the KELVIN SIGN, say, which lower cases to `k`.
    if segment.len() == 1 {
        folded.push_str(segment);
        if let Some(origin) = origin {
            origin.push(at);
        }
        return;
    }
    for c in segment.nfd().filter(|c| !is_diacritic(*c)) {
        if let Some(origin) = origin.as_deref_mut() {
            origin.extend(std::iter::repeat_n(at, c.len_utf8()));
        }
        folded.push(c);
    }
}

/// A window of `width` characters around the first term that hit.
///
/// The offsets come out of the folded copy `fold_with_origin` builds, and
/// folding can change how many bytes --and even how many characters-- a
/// string takes, so the map back to the original travels with it rather
/// than being assumed. A snippet that lands two characters off is not a
/// defect worth a wrong answer.
fn snippet(text: &str, terms: &[String], width: usize) -> String {
    let chars: Vec<char> = text.chars().collect();
    if chars.len() <= width {
        return text.split_whitespace().collect::<Vec<_>>().join(" ");
    }
    let (lower, origin) = fold_with_origin(text);
    let at = terms
        .iter()
        .filter_map(|t| lower.find(t.as_str()))
        .min()
        .map(|b| origin[b])
        .unwrap_or(0);
    let end = (at + width * 2 / 3).clamp(width, chars.len());
    let start = end - width;
    // `f716`: a raw offset usually lands inside a word on both sides.
    // `start` moves forward to the next boundary and `end` moves back to
    // the previous one, but neither is allowed to lose the hit that picked
    // this window in the first place: `start` never passes `at`, and `end`
    // never drops below `at + 1`. Where no boundary sits in that room, the
    // side stays at its raw cut -- a split word beats an empty window.
    let is_start = |i: usize| i == 0 || chars[i - 1].is_whitespace();
    let is_end = |i: usize| i == chars.len() || chars[i].is_whitespace();
    let mut s = start;
    while s < at && !is_start(s) {
        s += 1;
    }
    let start = if is_start(s) { s } else { start };
    let mut e = end;
    while e > at + 1 && !is_end(e) {
        e -= 1;
    }
    let end = if is_end(e) { e } else { end };
    let mut out = String::new();
    if start > 0 {
        out.push_str("...");
    }
    out.extend(chars[start..end].iter());
    if end < chars.len() {
        out.push_str("...");
    }
    out.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Text search over the tree.
///
/// `PILLARS.md` gives text search a ceiling of 100 ms and nothing ever
/// implemented it: a budget with no floor under it, the same class of
/// unchecked claim as the test count that lied for a day.
///
/// Two rules it does not bend. **Every term has to appear**, or a second word
/// would widen the search instead of narrowing it, which is the opposite of
/// what typing more means. And **closed nodes are searched too**: what you
/// look for months later is usually finished, and a search that stopped at
/// the open fronts would be a to-do list rather than a memory.
///
/// Order is not recency. Newest-first was the first answer, and it is the
/// wrong one for the search a memory is actually asked to do: the hits that
/// founded a subject are the oldest of them, and they were arriving last.
/// `d362` orders by what a hit is about first, by how much tree it holds up
/// second, and by recency only as the last tiebreak.
fn terms_of(query: &str) -> Result<Vec<String>, Failure> {
    let terms: Vec<String> = query.split_whitespace().map(fold).collect();
    if terms.is_empty() {
        return Err(Failure::usage("usage: vivac find \"<text>\"".to_string()));
    }
    Ok(terms)
}

/// Where a field lands in the order [`hits_for`] sorts by: title first, why
/// second, note and outcome tied for last. A function rather than the
/// position `searchable` returns the field at, because note and outcome tie
/// and a position has no room for one.
fn field_order(field: &str) -> u8 {
    match field {
        "title" => 0,
        "why" => 1,
        _ => 2,
    }
}

/// Every node that matches, best first, each with the fields it hit on.
///
/// Three keys, read in order, with no weights and no tunable constants.
///
/// **What the hit is about.** A term in the title is what the node is
/// called; a term in the reason is what the node argued; a term in a note
/// or an outcome is what happened along the way. The first of those
/// answers "where was this decided" better than the last, so the field of
/// the best hit dominates everything else. The note and the outcome tie:
/// both are what came after the argument.
///
/// **How much tree it holds up.** Among nodes that hit on the same field
/// the question is which one founded the subject, and the tree already
/// knows: the one everything else hangs off. `Aggregates` has the subtree
/// total of every node from a pass that is already linear, so this costs
/// a lookup.
///
/// **Recency**, last. It was the whole order before `d362` and it is a
/// tiebreak now: a search over a tree that has run for months is answered
/// from the end often enough to be worth keeping, and never often enough
/// to outrank what the hit is about.
///
/// What is deliberately absent is a relevance score. Term frequency, IDF
/// and length normalization are what BM25 would add, and here IDF is inert
/// -- every term has to appear, so every hit contains all of them -- while
/// length normalization is inverted: it penalizes long fields as diluted,
/// and in this corpus a long reason is the reasoning.
fn hits_for<'t>(
    a: &'t Tree,
    ag: &Aggregates,
    terms: &[String],
) -> Vec<(&'t Node, Vec<&'static str>)> {
    let mut hits: Vec<(&Node, Vec<&'static str>)> = Vec::new();
    for n in a.nodes_iter() {
        let lowered: Vec<(&'static str, String)> = searchable(a, n)
            .iter()
            .filter(|(_, v)| !v.is_empty())
            .map(|(k, v)| (*k, fold(v)))
            .collect();
        if !terms
            .iter()
            .all(|t| lowered.iter().any(|(_, v)| v.contains(t.as_str())))
        {
            continue;
        }
        // `d390`: `note` can now appear more than once in `lowered`, one
        // entry per note. Deduped here, or a term two notes both carry would
        // print the same `note:` line once per note that hit rather than
        // once per field, the way `field_order` already assumes a hit names
        // each field at most once.
        let mut seen_fields = std::collections::HashSet::new();
        let matched: Vec<&'static str> = lowered
            .iter()
            .filter(|(_, v)| terms.iter().any(|t| v.contains(t.as_str())))
            .map(|(k, _)| *k)
            .filter(|k| seen_fields.insert(*k))
            .collect();
        hits.push((n, matched));
    }
    hits.sort_by_key(|(n, matched)| {
        (
            field_order(matched[0]),
            std::cmp::Reverse(ag.counts(n.num).total),
            std::cmp::Reverse(n.num),
        )
    });
    hits
}

fn lineage_of(a: &Tree, n: &Node) -> Vec<String> {
    let line = a.ancestors(n.num);
    line[..line.len().saturating_sub(1)]
        .iter()
        .map(|p| p.alias())
        .collect()
}

/// A handle to a hit, not the node itself: `why` on the alias brings the rest.
///
/// Returning the whole node paid for `why`, `note` and `outcome` in full on
/// every hit, plus twelve bookkeeping fields nobody asked for. Measured over
/// the real tree with one query, both numbers from the same run: the JSON
/// cost 8.7 times its own prose and now costs 1.7. `matched` carries the
/// fragment `snippet` would print rather than the whole field, for the same
/// reason.
///
/// The six fields a hit carries, shared with [`find_data_everywhere`] so the
/// shape stays in exactly one place: `d273` adds a `project` field beside
/// this one rather than widening it.
fn hit_json(a: &Tree, n: &Node, matched: &[&'static str], terms: &[String]) -> serde_json::Value {
    let fragments: serde_json::Map<String, serde_json::Value> = matched
        .iter()
        .map(|field| {
            let text = searchable(a, n)
                .iter()
                .find(|(k, _)| k == field)
                .map(|(_, v)| *v)
                .unwrap_or_default();
            (field.to_string(), json!(snippet(text, terms, WIDTH)))
        })
        .collect();
    json!({
        "alias": n.alias(),
        "kind": n.kind,
        "state": n.state,
        "title": n.title(a),
        "lineage": lineage_of(a, n),
        "matched": fragments,
    })
}

pub fn find_data(a: &Tree, query: &str) -> Result<serde_json::Value, Failure> {
    let terms = terms_of(query)?;
    let ag = &a.aggregates();
    Ok(json!(hits_for(a, ag, &terms)
        .iter()
        .map(|(n, matched)| hit_json(a, n, matched, &terms))
        .collect::<Vec<_>>()))
}

/// One hit's alias-and-title row, styled the same way `open`'s own leaves
/// are (`d795`): the alias coloured by kind, the title dimmed once the node
/// is not open any more and wrapped at the terminal's width when one is
/// known. `lead_spaces` is the row's own left margin -- two for `find`,
/// four for `find --everywhere`, which indents once more for the project
/// name above it.
fn print_find_row(out: Stream, n: &Node, a: &Tree, cap: Option<usize>, lead_spaces: usize) {
    let alias = n.alias();
    let alias_field = format!(
        "{}{}",
        style::kind_id(out, n.kind, &alias),
        " ".repeat(6usize.saturating_sub(alias.chars().count()))
    );
    let closed = n.state != State::Active;
    let margin = " ".repeat(lead_spaces);
    print_title_row(
        &format!("{margin}{alias_field} "),
        &" ".repeat(lead_spaces + 7),
        lead_spaces + 7,
        n.title(a),
        cap,
        |chunk| {
            if closed {
                style::dim(out, chunk)
            } else {
                chunk.to_string()
            }
        },
        TitleSuffix { text: "", len: 0 },
    );
}

/// The `via <lineage>` line under a hit, each ancestor's alias coloured by
/// its own kind the same way `open`'s own via-line already is. `[]` when
/// `n` is a root, the same as `lineage_of` answers for the JSON twin.
fn print_find_lineage(out: Stream, a: &Tree, n: &Node, lead_spaces: usize) {
    let lineage = a.ancestors(n.num);
    if lineage.len() > 1 {
        let sep = style::dim(out, " > ");
        let v: Vec<String> = lineage[..lineage.len() - 1]
            .iter()
            .map(|p| style::kind_id(out, p.kind, &p.alias()))
            .collect();
        let margin = " ".repeat(lead_spaces + 7);
        outln!("{margin}{} {}", style::dim(out, "via"), v.join(&sep));
    }
}

pub fn find(a: &Tree, args: &Args) -> R {
    let query = args
        .positional(0)
        .ok_or_else(|| Failure::usage("usage: vivac find \"<text>\"".to_string()))?;
    let terms = terms_of(query)?;
    if args.has("json") {
        return print_json(find_data(a, query)?);
    }
    let ag = &a.aggregates();
    let hits = hits_for(a, ag, &terms);

    if hits.is_empty() {
        outln!("  Nothing matches \"{query}\".");
        return Ok(());
    }
    let out = Stream::Out;
    outln!();
    outln!(
        "  {}",
        style::bold(
            out,
            &format!(
                "{} match{} for \"{}\"",
                hits.len(),
                if hits.len() == 1 { "" } else { "es" },
                query,
            )
        )
    );
    outln!();
    let cap = style::width(out).map(|w| w.saturating_sub(1));
    for (n, matched) in hits.iter().take(20) {
        print_find_row(out, n, a, cap, 2);
        print_find_lineage(out, a, n, 2);
        // The title is already on the line above it. Repeating it as the
        // reason the hit came back would say nothing.
        for field in matched.iter().filter(|f| **f != "title") {
            let text = searchable(a, n)
                .iter()
                .find(|(k, _)| k == field)
                .map(|(_, v)| *v)
                .unwrap_or_default();
            outln!(
                "         {}",
                style::dim(out, &format!("{}: {}", field, snippet(text, &terms, WIDTH)))
            );
        }
    }
    if hits.len() > 20 {
        outln!();
        outln!(
            "  {}",
            style::dim(
                out,
                &format!(
                    "... and {} more   vivac find \"...\" --json",
                    hits.len() - 20
                )
            )
        );
    }
    outln!();
    Ok(())
}

/// This project's own name, as `d146` first defined it and `t640` amends:
/// the one saved on purpose with `--name`, when there is one, or the
/// directory's own name otherwise -- never the path it sits under, because
/// an absolute path names the account and the machine it runs on and the
/// security pillar allows neither into a result. `"-"` is what a root with
/// no name at all falls back to, the withheld-by-the-guard case included:
/// `registry::effective_name` carries no path-free way to say more than
/// that once it has withheld one.
///
/// `pub(crate)` rather than private since `d273`'s second half: `registry`
/// resolves `--project`'s value against the same bare name this hands back,
/// so a hit `find --everywhere` prints is exactly what `why --project` then
/// takes -- and `--join`'s own resolution reads through the very same
/// name (`t640`, point 10).
pub(crate) fn project_name(root: &std::path::Path) -> String {
    crate::store::store_dir()
        .and_then(|store_dir| crate::registry::effective_name(&store_dir, root))
        .unwrap_or_else(|| "-".into())
}

/// The JSON twin of [`find_everywhere`]: every hit [`hit_json`] already
/// knows how to build, plus the project it came from. A separate builder
/// rather than a wider `find_data`, the same call `d172` made when `find`
/// stopped sharing `json_node`.
fn find_data_everywhere(projects: &[(String, Tree)], terms: &[String]) -> serde_json::Value {
    let mut hits = Vec::new();
    for (name, tree) in projects {
        let ag = &tree.aggregates();
        for (n, matched) in hits_for(tree, ag, terms) {
            let mut hit = hit_json(tree, n, &matched, terms);
            if let serde_json::Value::Object(fields) = &mut hit {
                fields.insert("project".to_string(), json!(name));
            }
            hits.push(hit);
        }
    }
    json!(hits)
}

/// [`find_everywhere`]'s JSON, with no `Args` to read it from: what
/// `vivac_find`'s `everywhere` argument calls through the MCP server. The
/// same read `find --everywhere --json` runs, so the two can never drift
/// apart -- `d172`'s tie, carried past one project.
pub fn find_everywhere_data(query: &str) -> Result<serde_json::Value, Failure> {
    let terms = terms_of(query)?;
    let known_roots = crate::store::store_dir()
        .map(|d| crate::registry::roots(&d))
        .unwrap_or_default();
    let mut projects: Vec<(String, Tree)> = Vec::new();
    for root in known_roots {
        let name = project_name(&root);
        if let Ok(tree) =
            crate::store::Store::open(root).and_then(|s| crate::index::load(&s, false))
        {
            projects.push((name, tree));
        }
    }
    projects.sort_by(|x, y| x.0.cmp(&y.0));
    Ok(find_data_everywhere(&projects, &terms))
}

/// `find`, fanned out over every project the registry knows about instead
/// of only the one under foot. `d273`'s first half.
///
/// Each tree loads through the local index with `allow_persist: false`:
/// searching from one project must never write inside another project's
/// `.vivac/`. A root that fails to open -- moved, deleted, unreadable -- is
/// not skipped: `d201` settled that a vanished root going quiet loses
/// exactly the answer somebody came for, so it is counted and named instead.
///
/// A bare alias means nothing across trees -- `d100` exists in three of them
/// and names three different decisions -- so text output groups hits by
/// project rather than running them together.
pub fn find_everywhere(a: &Args) -> R {
    let query = a
        .positional(0)
        .ok_or_else(|| Failure::usage("usage: vivac find \"<text>\"".to_string()))?;
    let terms = terms_of(query)?;

    let known_roots = crate::store::store_dir()
        .map(|d| crate::registry::roots(&d))
        .unwrap_or_default();

    let mut projects: Vec<(String, Tree)> = Vec::new();
    let mut unreachable: Vec<String> = Vec::new();
    for root in known_roots {
        let name = project_name(&root);
        match crate::store::Store::open(root).and_then(|s| crate::index::load(&s, false)) {
            Ok(tree) => projects.push((name, tree)),
            Err(_) => unreachable.push(name),
        }
    }
    projects.sort_by(|x, y| x.0.cmp(&y.0));
    unreachable.sort();

    if a.has("json") {
        return print_json(find_data_everywhere(&projects, &terms));
    }

    type ProjectHits<'t> = (&'t str, &'t Tree, Vec<(&'t Node, Vec<&'static str>)>);
    let sections: Vec<ProjectHits> = projects
        .iter()
        .filter_map(|(name, tree)| {
            let ag = &tree.aggregates();
            let hits = hits_for(tree, ag, &terms);
            (!hits.is_empty()).then_some((name.as_str(), tree, hits))
        })
        .collect();
    let total: usize = sections.iter().map(|(_, _, hits)| hits.len()).sum();

    let out = Stream::Out;
    if total == 0 {
        outln!("  Nothing matches \"{query}\".");
    } else {
        outln!();
        outln!(
            "  {}",
            style::bold(
                out,
                &format!(
                    "{} match{} for \"{}\" across {} project{}",
                    total,
                    if total == 1 { "" } else { "es" },
                    query,
                    sections.len(),
                    if sections.len() == 1 { "" } else { "s" },
                )
            )
        );
        let cap = style::width(out).map(|w| w.saturating_sub(1));
        for (name, tree, hits) in &sections {
            outln!();
            outln!("  {}", style::bold(out, name));
            for (n, matched) in hits.iter().take(20) {
                print_find_row(out, n, tree, cap, 4);
                print_find_lineage(out, tree, n, 4);
                for field in matched.iter().filter(|f| **f != "title") {
                    let text = searchable(tree, n)
                        .iter()
                        .find(|(k, _)| k == field)
                        .map(|(_, v)| *v)
                        .unwrap_or_default();
                    outln!(
                        "           {}",
                        style::dim(out, &format!("{}: {}", field, snippet(text, &terms, WIDTH)))
                    );
                }
            }
            if hits.len() > 20 {
                outln!(
                    "    {}",
                    style::dim(
                        out,
                        &format!(
                            "... and {} more   vivac find \"...\" --everywhere --json",
                            hits.len() - 20
                        )
                    )
                );
            }
        }
        outln!();
    }

    if !unreachable.is_empty() {
        outln!(
            "  {}",
            style::dim(
                out,
                &format!(
                    "{} project{} unreachable: {}",
                    unreachable.len(),
                    if unreachable.len() == 1 { "" } else { "s" },
                    unreachable.join(", ")
                )
            )
        );
        outln!();
    }

    Ok(())
}

#[cfg(test)]
mod fold_tests {
    use super::{fold, fold_with_origin};
    use unicode_normalization::UnicodeNormalization;

    #[test]
    fn folds_spanish_diacritics_away() {
        assert_eq!(fold("dueño"), fold("dueno"));
        assert_eq!(fold("árbol"), fold("arbol"));
        assert_eq!(fold("ÁRBOL"), fold("arbol"));
    }

    #[test]
    fn folds_decomposed_and_precomposed_the_same_way() {
        let decomposed = "e\u{0301}"; // e + combining acute accent
        assert_eq!(fold(decomposed), fold("é"));
    }

    #[test]
    fn a_lower_cased_combining_mark_still_drops() {
        // U+0130, LATIN CAPITAL LETTER I WITH DOT ABOVE, lower cases to
        // `i` followed by U+0307, COMBINING DOT ABOVE.
        assert_eq!(fold("\u{0130}"), fold("i"));
    }

    /// What [`fold`] has to equal, written the plain way: lower case the
    /// whole text, run the whole of it through NFD, drop the marks. Slower,
    /// and independent of the segmenting [`super::fold_into`] does, which is
    /// the point: a test that compared the two public functions would be
    /// comparing one implementation with itself.
    fn reference(text: &str) -> String {
        text.chars()
            .flat_map(char::to_lowercase)
            .collect::<String>()
            .nfd()
            .filter(|c| !super::is_diacritic(*c))
            .collect()
    }

    /// A fixed, varied corpus: Spanish and French accents, Vietnamese with
    /// stacked marks, Hebrew points, Devanagari, marks in non-canonical
    /// order, a string that opens on a combining mark, an emoji and CJK.
    /// For each one, both [`fold`] and the folded half of
    /// [`fold_with_origin`] have to equal [`reference`], the map has to hold
    /// one entry per byte, and every entry has to name a real char index of
    /// the source.
    #[test]
    fn the_fold_agrees_with_whole_string_nfd() {
        let cases = [
            "dueño",
            "café",
            "garçon",
            "\u{1ec7}", // Vietnamese ệ, e with circumflex and dot below
            "Vi\u{1ec7}t Nam",
            "\u{5e9}\u{5b8}\u{5dc}\u{5d5}\u{5b9}\u{5dd}", // Hebrew, with points
            "\u{928}\u{940}\u{932}",                      // Devanagari
            "e\u{0301}\u{0323}", // acute (230) before dot below (220): not canonical
            // Shin, dagesh (21), qamats (18): marks that stay, in an order
            // NFD has to swap.
            "\u{5e9}\u{5bc}\u{5b8}",
            "\u{0301}bc", // opens on a combining acute
            // ASCII, then marks that stay, out of canonical order: the run
            // of ASCII is copied whole and the marks open their own segment.
            "sha\u{5bc}\u{5b8}lom",
            "Ab\u{0301}\u{0323}C \u{212a}elvin", // stacked marks after ASCII; KELVIN SIGN
            "ÁRBOL \u{0130}stanbul",
            "🌳 tree",
            "\u{6a39}\u{6728}", // CJK: tree, wood
        ];
        for text in cases {
            let expected = reference(text);
            assert_eq!(fold(text), expected, "fold disagrees on {text:?}");
            let (mapped, origin) = fold_with_origin(text);
            assert_eq!(mapped, expected, "fold_with_origin disagrees on {text:?}");
            assert_eq!(
                origin.len(),
                mapped.len(),
                "one origin per byte of {text:?}"
            );
            let char_count = text.chars().count();
            for (byte, idx) in origin.iter().enumerate() {
                assert!(
                    *idx < char_count,
                    "byte {byte} of {text:?} maps to char index {idx}, past its {char_count} chars"
                );
            }
        }
    }
}