beady-eye 0.9.0

A tree of work in flight: bead graphs annotated with the live agents working them
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
//! The snapshot, flattened into the lines the screen shows.
//!
//! One module for what a line that folds or holds the selection is known by,
//! and one for the lines a snapshot draws under those folds. What is left
//! here is the forest itself: the folds the user has set, and where the
//! selection sits.

mod facts;
mod handle;
mod layout;

use std::collections::{BTreeMap, BTreeSet};

use crate::model::join::BeadKey;
use crate::model::snapshot::{Filter, Snapshot, Tree};
use crate::view::lines::{beneath, links_below, quiet, root_key, Content, GroupKind, Line, Place};
use crate::view::{Action, Motion, Notch};

use facts::{Facts, TreeFacts};
use handle::{handle_of, selectable, Folds, Handle};
use layout::Rooted;

/// Where a search came to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Landed {
    /// Nothing any tree read holds matches the text searched for, so there
    /// was nowhere to go and the forest is left exactly as it was.
    ///
    /// Carries the text because the answer is about it — the foot says what
    /// found nothing — and because the forest is the only thing that still
    /// knows it once a walk rather than a fresh search has come to nothing.
    Nowhere(String),
    /// The selection is on `key`, the `at`th of `of` beads matching, counted
    /// from one and counted in the order the forest draws them.
    ///
    /// Screen order and not a ranking, so the ordinal is a fact about the
    /// forest rather than about the search: the reader can count it off the
    /// screen, and the same bead is the same number however they reached it.
    On { key: BeadKey, at: usize, of: usize },
}

/// Which of the beads drawn hold `query` in their id or their title, by where
/// they come in the drawing.
///
/// Letter case is neither side's: a title is prose, and a reader retyping a
/// word off a row is not reproducing the capitals it happened to carry.
fn matching(drawn: &[(BeadKey, String)], query: &str) -> Vec<usize> {
    let query = query.to_lowercase();
    drawn
        .iter()
        .enumerate()
        .filter(|(_, (key, title))| {
            key.id.to_lowercase().contains(&query) || title.to_lowercase().contains(&query)
        })
        .map(|(at, _)| at)
        .collect()
}

/// Walk one tree from `at` in the order it is drawn, listing every bead not
/// listed already.
///
/// `above` is the beads stepped through to reach `at`, which is what cuts a
/// way down that comes back on itself. A bead already listed is stepped over
/// rather than descended into: its children were reached under the first copy
/// of it, which is the copy this list stands for.
///
/// The children come from `Facts::split` and not from `links_below`, because
/// a parent with enough finished children to make a run draws the unfinished
/// ones first and the run after them — so the tracker's own order is not the
/// screen's, and `children_entries` is the only thing that says which is.
/// Both halves are walked: a bead inside a run is drawn nowhere until the run
/// is opened, and a search opens it, so leaving the run out would put beads
/// beyond reach of the key that exists to reach them.
fn step_down(
    tree: &Tree,
    facts: &TreeFacts,
    at: usize,
    above: &[usize],
    listed: &mut BTreeSet<BeadKey>,
    drawn: &mut Vec<(BeadKey, String)>,
) {
    let Some(node) = tree.beads.get(at) else {
        return;
    };
    let key = BeadKey {
        project: tree.project.clone(),
        id: node.id.clone(),
    };
    if !listed.insert(key.clone()) {
        return;
    }
    drawn.push((key, node.title.clone()));
    let mut way = above.to_vec();
    way.push(at);
    let (shown, elided) = facts.split(tree, at, above);
    for link in shown.into_iter().chain(elided) {
        step_down(tree, facts, link.bead, &way, listed, drawn);
    }
}

/// One snapshot's lines in render order, with the fold state and the selection
/// that decide which of them are visible and which one is current.
pub struct Forest {
    snapshot: Snapshot,
    /// What layout reads of the snapshot, answered when it was taken.
    facts: Facts,
    folds: Folds,
    cursor: Option<Handle>,
    /// The first line the last frame had room to draw, and how many it had
    /// room for.
    ///
    /// The room is the frame's to say and a scroll reads it off the last one
    /// drawn, exactly as the bead window's `Show` does. A frame is always
    /// drawn before a key or a notch is answered, so the first of either
    /// never reads a band nobody has measured.
    from: usize,
    room: usize,
    lines: Vec<Line>,
    selected: usize,
    /// The bead the forest is rooted at, where the reader has asked for one.
    ///
    /// The line they asked on rather than the bead standing on it, so a bead
    /// drawn more than once roots the forest at the copy they were on. Held
    /// rather than derived, because the selection moves afterwards and the
    /// mode does not move with it.
    focused: Option<Place>,
    /// What was last searched for, which `n` and `N` step through.
    ///
    /// The text and not the matches it found. A match set held between
    /// presses would be stale the moment a collection landed, and a place in
    /// one would be wrong the moment the reader moved by hand; the text is
    /// still true after both, and the matches are worked out again from where
    /// the selection has actually got to.
    searched: Option<String>,
}

/// Flatten a snapshot into its lines.
pub fn flatten(snapshot: Snapshot) -> Forest {
    let mut forest = Forest {
        facts: Facts::of(&snapshot),
        snapshot,
        folds: Folds::default(),
        cursor: None,
        from: 0,
        room: 0,
        lines: Vec::new(),
        selected: 0,
        focused: None,
        searched: None,
    };
    forest.lay_out();
    forest.select_first_root();
    forest
}

impl Forest {
    /// The visible lines, in render order.
    pub fn lines(&self) -> &[Line] {
        &self.lines
    }

    /// Open on the first root rather than on the project above it. A project
    /// is not a bead, so it has no pane, and a screen that opens with its tail
    /// band empty has spent it saying nothing.
    fn select_first_root(&mut self) {
        let first = self
            .lines
            .iter()
            .position(|line| matches!(line.content, Content::Bead(_) | Content::Unread(_)));
        if let Some(at) = first {
            self.selected = at;
            self.cursor = self.handle_at(at);
        }
    }

    /// Where the selection sits in `lines`.
    pub fn selected_line(&self) -> usize {
        self.selected
    }

    pub fn snapshot(&self) -> &Snapshot {
        &self.snapshot
    }

    /// The first line the viewport is showing.
    pub fn from(&self) -> usize {
        self.from
    }

    /// Take the measure of the band the last frame gave the forest, and come
    /// back inside the forest where a shorter band has left the viewport past
    /// its end. The renderer is the only thing that knows the band's height,
    /// so it says.
    pub fn fit(&mut self, room: usize) {
        self.room = room;
        self.from = self.from.min(self.furthest());
    }

    /// The furthest the viewport can be scrolled and still be full.
    fn furthest(&self) -> usize {
        self.lines.len().saturating_sub(self.room)
    }

    /// How far a half-screen motion moves: half the band the trees are in,
    /// rather than half a screen the key bar and the tail also sit in. Never
    /// nowhere, so the key does something on the shortest band there is.
    fn half_screen(&self) -> usize {
        (self.room / 2).max(1)
    }

    /// Move the viewport one notch of the wheel, leaving the selection where
    /// the reader put it, and report whether it moved. How far a notch goes
    /// is the config's, so the caller holding one says.
    pub fn scrolled(&mut self, notch: Notch, lines: usize) -> bool {
        let to = match notch {
            Notch::Up => self.from.saturating_sub(lines),
            Notch::Down => (self.from + lines).min(self.furthest()),
        };
        let moved = to != self.from;
        self.from = to;
        moved
    }

    /// Bring the selection inside the viewport, where the last frame left it
    /// above or below what there was room for, and report whether the view
    /// moved.
    ///
    /// By the least it can, rather than by putting the selection back in the
    /// middle. A reader who has wheeled the view somewhere and then steps one
    /// row keeps what they were looking at, and it is what the bead window
    /// already does with a row it has to reveal.
    ///
    /// Reported because a keystroke that moves the view and nothing else is a
    /// keystroke the screen has to be redrawn for: `g` on a selection the
    /// wheel has scrolled away from moves no row and changes every one of
    /// them.
    fn reveal(&mut self) -> bool {
        let was = self.from;
        if self.selected < self.from {
            self.from = self.selected;
        } else if self.room > 0 && self.selected >= self.from + self.room {
            self.from = self.selected + 1 - self.room;
        }
        self.from != was
    }

    /// Take a freshly collected snapshot, keeping the folds, the filter and
    /// the selection.
    pub fn refresh(&mut self, mut snapshot: Snapshot) {
        // Only the snapshot the cursor was found in knows what stood above
        // it, so where the new one has dropped the bead the cursor falls to
        // the nearest of its forebears that survived.
        let ancestry = self.ancestry();
        let folded_over = self.folded_over();
        // A collection carries the filter the command line asked for, which
        // is nobody's answer to `a`. So the one in hand goes on the new
        // snapshot, exactly as the folds and the cursor do.
        snapshot.refilter(self.snapshot.filter);
        self.take(snapshot);
        // The bead leaving the collection ends the mode, and the place it
        // stood on goes with it. Kept, it would take the next press of the
        // key and spend it putting back a forest that is already back.
        //
        // Found again by the bead rather than by the way down to it, because
        // a tracker that reparented it has moved the bead and not lost it.
        self.focused = self.focused.take().and_then(|place| self.rerooted(&place));
        self.spend_folds(&folded_over);
        self.cursor = ancestry.into_iter().find(|handle| self.present(handle));
        self.lay_out();
    }

    /// The live work each fold the user shut is currently shut over.
    fn folded_over(&self) -> BTreeMap<Handle, BTreeSet<BeadKey>> {
        self.folds
            .shut()
            .map(|handle| (handle.clone(), self.live_under(handle)))
            .collect()
    }

    /// Let go of a fold the user set once live work has arrived beneath it
    /// that was not there when they set it.
    ///
    /// A fold says *I have seen what is under here and do not want it*, and
    /// that stops being true the moment something new is under it. So what
    /// they folded away stays folded for as long as it lives, work that dies
    /// down re-opens nothing, and an agent arriving on a bead they never saw
    /// hands the node back to the default.
    fn spend_folds(&mut self, folded_over: &BTreeMap<Handle, BTreeSet<BeadKey>>) {
        let spent: Vec<Handle> = folded_over
            .iter()
            .filter(|(handle, over)| !self.live_under(handle).is_subset(over))
            .map(|(handle, _)| handle.clone())
            .collect();
        self.folds.spend(&spent);
    }

    /// The beads beneath `handle` carrying live work. Empty for anything but
    /// a bead: a run holds only finished branches, and a group's items are
    /// not beads at all.
    fn live_under(&self, handle: &Handle) -> BTreeSet<BeadKey> {
        let Handle::Bead(place) = handle else {
            return BTreeSet::new();
        };
        let Some((tree, way)) = self.locate(place) else {
            return BTreeSet::new();
        };
        let (at, above) = way.split_last().expect("a way down ends somewhere");
        beneath(tree, *at, above)
            .into_iter()
            .filter(|node| !quiet(&tree.beads[*node]))
            .map(|node| BeadKey {
                project: tree.project.clone(),
                id: tree.beads[node].id.clone(),
            })
            .collect()
    }

    /// What the cursor is on, then everything above it, nearest first: the
    /// beads above it in its tree, the group holding the tree where the
    /// filter has put it in one, and the project.
    fn ancestry(&self) -> Vec<Handle> {
        self.ancestry_of(self.cursor.as_ref())
    }

    /// The same chain above any line, so what a lost cursor falls back to and
    /// what has to be opened to reach a line are one answer rather than two
    /// that agree until the forest changes shape.
    fn ancestry_of(&self, from: Option<&Handle>) -> Vec<Handle> {
        let mut chain: Vec<Handle> = from.into_iter().cloned().collect();
        let place = match from {
            Some(Handle::Bead(place)) => place,
            // A run is only ever seen from the bead it hangs under, so that
            // bead is the first forebear a lost run falls back to.
            Some(Handle::Elided(place)) => {
                chain.push(Handle::Bead(place.clone()));
                place
            }
            // Only the snapshot a pane was found in still knows which group
            // held it, so a pane that goes away falls back to that group
            // rather than to the top of the forest — and to the project the
            // group is one of, where it is.
            Some(Handle::Item(key)) => {
                if let Some(group) = layout::group_holding(&self.snapshot, key) {
                    if let Handle::Group(_, Some(project)) = &group {
                        chain.push(Handle::Project(project.clone()));
                    }
                    chain.insert(1, group);
                }
                return chain;
            }
            Some(Handle::Group(_, Some(project))) => {
                chain.push(Handle::Project(project.clone()));
                return chain;
            }
            _ => return chain,
        };
        chain.extend(place.forebears().map(Handle::Bead));
        // A line the mode is holding back is behind the line it put it
        // behind, and the group the filter would have put its tree in is not
        // drawn at all while the forest is rooted at one bead.
        if self.held_back(place) {
            chain.push(Handle::Group(
                GroupKind::OutOfTheWay,
                Some(place.tree.project.clone()),
            ));
        } else if self.hidden(&place.tree) {
            chain.push(Handle::Group(
                GroupKind::HiddenTrees,
                Some(place.tree.project.clone()),
            ));
        }
        chain.push(Handle::Project(place.tree.project.clone()));
        chain
    }

    /// Whether the mode is holding a line back, which it is for every line but
    /// the bead the forest is rooted at and the ones beneath it.
    ///
    /// The rest of that bead's own root is held back as much as another root
    /// is: the mode draws the bead where a root is drawn and stops there, so
    /// the beads above it are behind the line the other roots are behind.
    fn held_back(&self, place: &Place) -> bool {
        self.focused.as_ref().is_some_and(|focused| {
            focused.tree != place.tree || !place.steps.starts_with(&focused.steps)
        })
    }

    /// Whether the filter is holding the tree a root names back.
    fn hidden(&self, root: &BeadKey) -> bool {
        self.snapshot
            .hidden_trees
            .iter()
            .any(|hidden| hidden.project == root.project && hidden.root == root.id)
    }

    /// The tree a place was drawn in and the way down it, as the beads
    /// stepped through from the root to the one its last step lands on.
    ///
    /// The steps are walked rather than the last of them looked up, because a
    /// bead reachable more than once is drawn more than once and only the way
    /// down to a copy tells it from its twins — and the way down is what
    /// every question about the copy is asked with.
    ///
    /// `links_below` here rather than `Facts::split`, and deliberately. The
    /// walks that decide *which* copy — `children_entries` drawing it,
    /// `step_down` enumerating it, `stepped_to` resolving into it — all read
    /// `split`, because for them first means first drawn. This one is handed
    /// the copy already, as the ids in `place.steps`, and finds each by name:
    /// same links, same bead, whatever order they arrive in. Putting it on
    /// `split` would couple a resolver to `Facts` and buy no property.
    fn locate(&self, place: &Place) -> Option<(&Tree, Vec<usize>)> {
        let tree = self.tree_of(place)?;
        let mut way = vec![(!tree.beads.is_empty()).then_some(0)?];
        for step in &place.steps {
            let (at, above) = way.split_last().expect("a way down ends somewhere");
            let next = links_below(tree, *at, above)
                .into_iter()
                .find(|link| tree.beads[link.bead].id == step.id)?
                .bead;
            way.push(next);
        }
        Some((tree, way))
    }

    fn tree_of(&self, place: &Place) -> Option<&Tree> {
        self.snapshot.tree(&place.tree)
    }

    /// Apply one action, reporting whether it changed anything.
    ///
    /// Focusing a pane, copying a bead's id, showing a bead or the key
    /// bindings and going back from them, re-collecting and quitting are the
    /// loop's to do, and none of them changes what is on screen here.
    pub fn apply(&mut self, action: Action) -> bool {
        let selected = self.selected;
        match action {
            Action::Move(motion) => self.move_to(motion),
            Action::CollapseOrParent => self.collapse_or_parent(),
            Action::ExpandOrChild => self.expand_or_child(),
            Action::ToggleFold => self.toggle_fold(),
            Action::ExpandSubtree => self.fold_subtree(true),
            Action::CollapseSubtree => self.fold_subtree(false),
            Action::RestoreDefault => self.folds.clear(),
            Action::ToggleFilter => self.toggle_filter(),
            Action::FocusForest => self.focus_forest(),
            Action::Focus
            | Action::ShowBead
            | Action::NextRelated
            | Action::Back
            | Action::CopyId
            | Action::ShowBindings
            | Action::Search
            | Action::NextMatch
            | Action::PreviousMatch
            | Action::Refresh
            | Action::Quit => return false,
        }
        let was = self.lay_out();
        let revealed = self.reveal();
        self.selected != selected || self.lines != was || revealed
    }

    /// Root the forest at the selected bead, or put it back where it is
    /// already rooted at one.
    ///
    /// Putting it back leaves the selection on the bead the reader rooted it
    /// at, wherever they had walked to under the mode: they asked to finish
    /// that bead, and the forest they came back to is the one they left.
    ///
    /// A line carrying no bead roots the forest at nothing. A root whose
    /// tracker refused holds a place but no node, and there is no tree to draw
    /// from a bead that is not there.
    fn focus_forest(&mut self) {
        if let Some(place) = self.focused.take() {
            let on = Handle::Bead(place.clone());
            // Drawn again first, so what is shut over the bead is asked of
            // the forest the reader is coming back to rather than of the one
            // they are leaving. The rows it drew go back afterwards, because
            // the press is read for whether the screen changed and these are
            // the rows it changed from.
            let rooted = self.lay_out();
            let on_screen = self
                .lines
                .iter()
                .any(|line| handle_of(line).as_ref() == Some(&on));
            self.lines = rooted;
            if !on_screen {
                // They shut something over it from inside the mode, and a
                // forest that comes back with the selection somewhere else
                // has not put them back where they were.
                self.open_over(&place);
            }
            self.cursor = Some(on);
            return;
        }
        let Some(Handle::Bead(place)) = self.cursor.clone() else {
            return;
        };
        if self.locate(&place).is_some() {
            self.focused = Some(place);
        }
    }

    /// Where the bead a place stood on is now, which is the place itself
    /// while nothing has moved. Nothing at all once the collection no longer
    /// holds that bead, which is what ends the mode.
    ///
    /// A place with no steps stands on the root of its tree, and a root filed
    /// under another root has moved as much as any other bead: it is looked
    /// for by the same name, which for that place is the tree's own.
    ///
    /// Asked for the bead rather than for the row: a root whose tracker has
    /// since refused keeps a row saying so, and there is no tree to draw from
    /// a bead that is not there.
    fn rerooted(&self, place: &Place) -> Option<Place> {
        if self.locate(place).is_some() {
            return Some(place.clone());
        }
        self.place_of(place.steps.last().unwrap_or(&place.tree))
    }

    /// Where the forest is rooted, where the reader has rooted it at a bead
    /// the snapshot in hand still draws.
    ///
    /// Resolved against that snapshot on every layout rather than kept, so a
    /// collection that moved the bead is followed and one that dropped it
    /// ends the mode.
    fn rooted(&self) -> Option<Rooted> {
        let place = self.focused.as_ref()?;
        let (_, way) = self.locate(place)?;
        Some(Rooted {
            place: place.clone(),
            way,
        })
    }

    fn toggle_filter(&mut self) {
        let next = match self.snapshot.filter {
            Filter::LiveAgents => Filter::All,
            Filter::All => Filter::LiveAgents,
        };
        self.snapshot.refilter(next);
        self.answer();
    }

    /// Take a snapshot as the one drawn.
    fn take(&mut self, snapshot: Snapshot) {
        self.snapshot = snapshot;
        self.answer();
    }

    /// Answer what layout reads of the snapshot in hand, here and not per
    /// keystroke.
    fn answer(&mut self) {
        self.facts = Facts::of(&self.snapshot);
    }

    /// `E` and `C`: point every fold in the selected node's subtree, at every
    /// depth, one way.
    ///
    /// The subtree and not the forest, because a reader who has navigated to
    /// one project, or to one bead with a deep subtree, is asking about that
    /// and would lose their place among rows they never asked to see. `D` is
    /// the key that still speaks for the whole forest.
    ///
    /// Opening a node draws children that were not there to be enumerated, so
    /// the subtree is opened a level at a time until a draw turns up nothing
    /// left shut. Shutting goes the same way round first: a fold the reader
    /// cannot see is still a fold, and one left open under a shut parent
    /// would spring its subtree back the moment that parent was opened again.
    /// That opening walk is scoped as well as the shutting one, or `C` on a
    /// node would throw the rest of the forest open on the way past.
    ///
    /// The scope is named once and reused, because the walk redraws between
    /// passes and a line's place in the draw moves under it. It is a handle
    /// rather than a bead, so a bead reachable more than once puts only the
    /// way down the selection took inside the scope.
    ///
    /// The walks draw without laying out, because `apply` tells the loop
    /// whether the screen moved by comparing against the lines its own
    /// lay-out displaced — one in here would leave it comparing the new lines
    /// with themselves.
    fn fold_subtree(&mut self, open: bool) {
        let Some(scope) = self.handle_at(self.selected) else {
            return;
        };
        self.fold_subtree_in(&scope, self.rounds_to_settle(), open);
    }

    /// The rounds a forest of this size can need, counted off the snapshot
    /// before the walk starts.
    ///
    /// A round points every fold on a drawn line, so the next one reaches
    /// the folds that round drew and no deeper: the walk spends a round per
    /// level of fold rather than one per fold, and a round that points none
    /// is the last. A fold nests inside another only where a bead hangs
    /// under a bead, with at most the run of quiet children between the two,
    /// so a tree holds two levels per bead it has — and the beads down one
    /// path are all different, because a way down that comes back to a bead
    /// it came through is cut there. The two left over are the fold a
    /// project or a group draws over what hangs beneath it, and the round
    /// that finds nothing left to point.
    ///
    /// Generous on purpose: a level too many costs one draw that finds
    /// nothing, a level too few stops a walk that was still working. Which is
    /// also what lets a walk over one subtree take it — a count for the whole
    /// snapshot is loose there and still an upper bound.
    ///
    /// Counted off the snapshot, and off nothing a fold or a drawn line
    /// says, so it still counts out where the walk is wrong about what it
    /// drew.
    fn rounds_to_settle(&self) -> usize {
        let beads: usize = self
            .snapshot
            .collected
            .iter()
            .map(|tree| tree.beads.len())
            .sum();
        2 * beads + 2
    }

    /// Point every fold in `scope`'s subtree at `open`, in at most `rounds`
    /// of them.
    ///
    /// A walk that runs out has set a fold and drawn it again unchanged,
    /// which is a defect: the subtree is left at the level it reached, and
    /// the folds it never got to are drawn shut like any other, so the
    /// screen still says truthfully which way every fold points.
    fn fold_subtree_in(&mut self, scope: &Handle, rounds: usize, open: bool) {
        for _ in 0..rounds {
            if !self.point_every_drawn_fold(scope, true) {
                break;
            }
        }
        if !open {
            self.point_every_drawn_fold(scope, false);
        }
    }

    /// Point every fold drawn in `scope`'s subtree at `open`, reporting
    /// whether any of them was pointing the other way.
    fn point_every_drawn_fold(&mut self, scope: &Handle, open: bool) -> bool {
        let rooted = self.rooted();
        let drawn = layout::draw(&self.snapshot, &self.facts, &self.folds, rooted.as_ref());
        let pointed: Vec<Handle> = subtree_of(&drawn, scope)
            .iter()
            .filter(|line| line.folded == Some(!open))
            .filter_map(handle_of)
            .collect();
        for handle in &pointed {
            self.folds.set(handle.clone(), open);
        }
        !pointed.is_empty()
    }

    fn toggle_fold(&mut self) {
        if let (Some(open), Some(handle)) =
            (self.fold_at(self.selected), self.handle_at(self.selected))
        {
            self.folds.set(handle, !open);
        }
    }

    /// `h`: shut an open node, and step out of one already shut.
    fn collapse_or_parent(&mut self) {
        match (self.fold_at(self.selected), self.handle_at(self.selected)) {
            (Some(true), Some(handle)) => {
                self.folds.set(handle, false);
            }
            _ => self.step_to(self.parent_of(self.selected)),
        }
    }

    /// `l`: open a shut node, and step into one already open.
    fn expand_or_child(&mut self) {
        match (self.fold_at(self.selected), self.handle_at(self.selected)) {
            (Some(false), Some(handle)) => {
                self.folds.set(handle, true);
            }
            _ => self.step_to(self.first_child_of(self.selected)),
        }
    }

    fn move_to(&mut self, motion: Motion) {
        let last = self.lines.len().saturating_sub(1);
        let target = match motion {
            Motion::PreviousRow => self.step(self.selected, false),
            Motion::NextRow => self.step(self.selected, true),
            Motion::FirstRow => self.scan(0, true),
            Motion::LastRow => self.scan(last, false),
            Motion::HalfScreenUp => {
                let at = self.selected.saturating_sub(self.half_screen());
                self.scan(at, false).or_else(|| self.scan(at, true))
            }
            Motion::HalfScreenDown => {
                let at = (self.selected + self.half_screen()).min(last);
                self.scan(at, true).or_else(|| self.scan(at, false))
            }
        };
        self.step_to(target);
    }

    /// Put the selection on the line at `at`, reporting whether the screen
    /// has changed.
    ///
    /// Named rather than stepped to, and that is the whole difference from a
    /// motion: a line the selection cannot rest on keeps none, because the
    /// pointer named that line and not the one below it. Which lines those
    /// are is the keyboard's question, asked here in the keyboard's words.
    pub fn select_line(&mut self, at: usize) -> bool {
        let was = self.selected;
        let mut revealed = false;
        if self.lines.get(at).is_some_and(selectable) {
            self.step_to(Some(at));
            revealed = self.reveal();
        }
        self.selected != was || revealed
    }

    /// Where the selection sits, where it sits on a bead at all.
    ///
    /// A place and not a key, because a bead drawn more than once is drawn
    /// once per way down to it, and a caller keeping this to come back to is
    /// keeping the copy the reader was looking at.
    pub fn place(&self) -> Option<&Place> {
        self.lines.get(self.selected)?.place.as_ref()
    }

    /// Put the selection on a bead the snapshot holds, wherever the forest
    /// draws it, opening whatever is folded over it. Reports whether the
    /// selection is on it now.
    pub fn go_to(&mut self, key: &BeadKey) -> bool {
        let Some(place) = self.place_of(key) else {
            return false;
        };
        self.go_to_place(&place)
    }

    /// Put the selection back on a line it held before, opening whatever has
    /// been folded over it since. Reports whether the selection is on it now,
    /// which it is not where the snapshot has stopped drawing that line.
    pub fn go_to_place(&mut self, place: &Place) -> bool {
        if !self.drawn(place) {
            return false;
        }
        self.open_over(place);
        self.cursor = Some(Handle::Bead(place.clone()));
        self.lay_out();
        self.reveal();
        self.cursor.as_ref() == Some(&Handle::Bead(place.clone()))
    }

    /// Put the selection on a bead matching what the reader typed, wherever
    /// the forest draws it, and report which of the matches it is. Nowhere
    /// where nothing matches, and the forest is left as it was.
    ///
    /// A match is a bead holding the text in its id or in its title, letter
    /// case aside. Part of either and not the whole of one, because a
    /// fragment is what the reader has: the forest row draws a *shortened*
    /// id and `row::abbreviate` is the only thing in `bdi` that draws one, so
    /// on a long screen it is the only spelling of a bead they have been
    /// shown — and a title is prose they are quoting a word out of.
    ///
    /// So a search no longer supplies the half of a key the reader did not
    /// type. It answers with beads, each already a whole `(project, id)`,
    /// and the reader steps through them.
    ///
    /// **Where it lands** is the one thing the whole id decides: on the bead
    /// whose id is exactly what was typed if one matched, and on the first
    /// match otherwise. An id is the one thing a reader can have meant
    /// exactly, and a row merely *titled* after a bead must not shadow it —
    /// that promise is older than this widening. The numbering below is not
    /// touched by it.
    pub fn seek(&mut self, query: &str) -> Landed {
        self.searched = Some(query.to_string());
        let drawn = self.beads_drawn();
        let matched = matching(&drawn, query);
        let lowered = query.to_lowercase();
        let at = matched
            .iter()
            .position(|at| drawn[*at].0.id.to_lowercase() == lowered)
            .unwrap_or(0);
        self.land_on(&drawn, &matched, at, query)
    }

    /// Step to the next bead matching what was last searched for, or to the
    /// one before it, coming round at either end.
    ///
    /// `None` before anything has been searched for: there is nothing to step
    /// through and nothing has gone wrong, which is the same answer `Focus`
    /// gives a row with no pane.
    pub fn next_match(&mut self, forward: bool) -> Option<Landed> {
        let query = self.searched.clone()?;
        let drawn = self.beads_drawn();
        let matched = matching(&drawn, &query);
        if matched.is_empty() {
            return Some(Landed::Nowhere(query));
        }
        let at = self.past_selection(&drawn, &matched, forward);
        Some(self.land_on(&drawn, &matched, at, &query))
    }

    /// Which match to step to: the first one drawn after the selection, or
    /// the last one drawn before it, coming round at either end.
    ///
    /// Asked of where the selection is *now* rather than of where the last
    /// step left it. So a reader who has moved by hand between presses
    /// carries on from where they are standing, and a collection that has
    /// moved every bead under them costs the walk nothing — there is no
    /// place in a list to have gone stale, only a question asked again.
    ///
    /// A selection on a row that is not a bead carries on from there too, and
    /// the bead it stands above is *included* going forwards: the reader is
    /// above it, not on it, so it is a match after them rather than the one
    /// they are already looking at. Going back needs no such care — a match
    /// drawn at that bead is below the selection either way.
    ///
    /// *After* is a bead's place in the order and not the row the reader is
    /// on, and for a bead the tree reaches twice those part company: the
    /// order holds it once, at the copy drawn first, because a match is a
    /// bead and `of` counts beads. So a reader who has walked to the second
    /// copy by hand steps on from where the first one sits, which can be
    /// above them. Not a slip in the anchor — the anchor has one place to
    /// find, and giving it two would make `k of n` count rows in a search
    /// that answers with beads. `bdi-7ao.136` holds what it would take.
    fn past_selection(
        &self,
        drawn: &[(BeadKey, String)],
        matched: &[usize],
        forward: bool,
    ) -> usize {
        let Some((here, past_it)) = self.standing_at(drawn) else {
            return if forward { 0 } else { matched.len() - 1 };
        };
        if forward {
            matched
                .iter()
                .position(|at| if past_it { *at >= here } else { *at > here })
                .unwrap_or(0)
        } else {
            matched
                .iter()
                .rposition(|at| *at < here)
                .unwrap_or(matched.len() - 1)
        }
    }

    /// Where the selection stands among the beads drawn, and whether it is
    /// standing *above* that bead rather than on it.
    ///
    /// A project's own line, a group, and a pane in one are not beads, and a
    /// reader can rest on any of them. Each still has a place in the order —
    /// the first bead drawn below it — so stepping from one carries on from
    /// where the reader is instead of starting the walk again.
    ///
    /// `None` where there is no such bead, and the walk comes round rather
    /// than carrying on. That is a reader resting under the last bead on the
    /// screen.
    fn standing_at(&self, drawn: &[(BeadKey, String)]) -> Option<(usize, bool)> {
        let on_a_bead = self.lines.get(self.selected).and_then(Line::bead);
        let (key, past_it) = match on_a_bead {
            Some(key) => (key.clone(), false),
            None => (self.first_bead_under()?, true),
        };
        let at = drawn.iter().position(|(drawn, _)| *drawn == key)?;
        Some((at, past_it))
    }

    /// The first bead a selection resting on a row that is not one stands
    /// above.
    ///
    /// Read off the rendered lines wherever there are lines to read. Every
    /// ordering defect this search has had came from deriving the screen's
    /// shape somewhere other than where it is drawn, and the lines are that
    /// shape rather than a second account of it.
    ///
    /// A group resting shut is where there are none: its trees' beads are in
    /// the order, because `beads_drawn` goes by the trees the screen would
    /// draw rather than by the folds set over them, but the fold has taken
    /// every one of them off the screen. The lines below the group are the
    /// rows *after* it, so reading them would step over everything it hides
    /// — so a shut group is asked what it holds instead. One that holds no
    /// beads has nothing to say and the lines answer as they always did.
    fn first_bead_under(&self) -> Option<BeadKey> {
        let resting_on = self.lines.get(self.selected)?;
        let shut_over = match &resting_on.content {
            Content::Group(group) if resting_on.folded == Some(false) => layout::first_bead_of(
                &self.snapshot,
                group.kind,
                group.project.as_deref(),
                self.rooted().as_ref(),
            ),
            _ => None,
        };
        shut_over.or_else(|| {
            self.lines[self.selected..]
                .iter()
                .find_map(Line::bead)
                .cloned()
        })
    }

    /// Put the selection on the `at`th match, counting from zero, and say
    /// where it went and how many there were. Nowhere where there is no such
    /// match, or where the forest cannot take the reader to it.
    fn land_on(
        &mut self,
        drawn: &[(BeadKey, String)],
        matched: &[usize],
        at: usize,
        query: &str,
    ) -> Landed {
        let Some((key, _)) = matched.get(at).map(|at| &drawn[*at]) else {
            return Landed::Nowhere(query.to_string());
        };
        let key = key.clone();
        if !self.go_to(&key) {
            return Landed::Nowhere(query.to_string());
        }
        Landed::On {
            key,
            at: at + 1,
            of: matched.len(),
        }
    }

    /// Every bead the forest holds, with its title, in the order the screen
    /// draws them.
    ///
    /// The order of the *trees* is asked of `layout`, which is what draws
    /// them, rather than worked out here.
    ///
    /// `place_of`'s rule — the trees the filter shows before the ones it hid
    /// — is not the whole of the screen's order, and reading it as if it were
    /// is what this used to get wrong. It is an ordering *within* a project:
    /// `place_of` takes a key, which carries its project, so it never has to
    /// sequence one project against another. This has to, and the screen goes
    /// project by project, putting each project's hidden trees under that
    /// project rather than after every visible one. The rule is true where it
    /// is written and silent about the question asked here.
    ///
    /// A bead reachable more than once is drawn more than once and listed
    /// once, at the first way down that reaches it: the copy a reader
    /// scanning down the screen would have found, which is the copy
    /// `place_of` takes them to.
    fn beads_drawn(&self) -> Vec<(BeadKey, String)> {
        let mut drawn = Vec::new();
        let mut listed = BTreeSet::new();
        for (tree, way) in layout::walked(&self.snapshot, self.rooted().as_ref()) {
            let (at, above) = way.split_last().expect("a way down ends somewhere");
            step_down(
                tree,
                self.facts.tree(&root_key(tree)),
                *at,
                above,
                &mut listed,
                &mut drawn,
            );
        }
        drawn
    }

    /// Whether the forest can take the reader to a bead: whether any tree it
    /// holds draws one.
    ///
    /// Asked of the snapshot rather than worked out from how roots are
    /// found, so it goes on being the same question when they are found
    /// another way.
    pub fn draws(&self, key: &BeadKey) -> bool {
        self.snapshot.locate(key).is_some()
    }

    /// Where the forest first draws a bead, going down the trees in the order
    /// the screen draws them: the trees the filter shows before the ones it
    /// hid, and within a tree the first way down that reaches it.
    ///
    /// The first copy rather than the shallowest, because that is the one a
    /// reader scanning down the screen would have found themselves — which
    /// means first *drawn*, and a parent with enough finished branches draws
    /// its children in an order their sort does not give. `way_to` is handed
    /// the tree's facts for that reason, and it is the same order the search
    /// enumerates in, so the copy a count named is the copy landed on.
    ///
    /// What the forest is rooted at is asked first, because a way down the
    /// tree answers with can be a row the mode draws nowhere.
    fn place_of(&self, key: &BeadKey) -> Option<Place> {
        self.drawn_at_the_root(key).or_else(|| {
            self.snapshot
                .trees
                .iter()
                .chain(&self.snapshot.collected)
                .filter(|tree| tree.project == key.project)
                .find_map(|tree| way_to(tree, self.facts.tree(&root_key(tree)), &key.id))
        })
    }

    /// Where the forest draws a bead at the bead it is rooted at or beneath
    /// it, which is where a reader comes to it first: those rows are drawn
    /// above every root the mode is holding back.
    ///
    /// A bead its own tree reaches twice is drawn at the copy the reader
    /// pressed the key on, and every copy of it is left out of the root behind
    /// the line — so the first way down to that bead, and to everything only
    /// it reaches, is a way down to a row nothing draws.
    fn drawn_at_the_root(&self, key: &BeadKey) -> Option<Place> {
        let focused = self.focused.as_ref()?;
        if focused.steps.last().unwrap_or(&focused.tree) == key {
            return Some(focused.clone());
        }
        if focused.tree.project != key.project {
            return None;
        }
        let (tree, way) = self.locate(focused)?;
        let (at, above) = way.split_last()?;
        stepped_to(
            tree,
            self.facts.tree(&root_key(tree)),
            &key.id,
            *at,
            above,
            focused,
        )
    }

    /// Open everything shut over a line: everything the line hangs under, and
    /// the run of quiet children each forebear may be counting it in.
    ///
    /// The run is asked for beside each forebear rather than left to the
    /// ancestry, which answers for a line that is drawn — and a bead inside a
    /// run is not drawn at all, so nothing above it can name it.
    ///
    /// Set rather than let go of, because a fold the reader shut by hand
    /// stays shut until something asks otherwise, and asking to be taken to a
    /// bead underneath it is asking.
    fn open_over(&mut self, place: &Place) {
        let over = self.ancestry_of(Some(&Handle::Bead(place.clone())));
        // Past the line itself, whose own fold is about the children under it
        // rather than about reaching it.
        for above in over.into_iter().skip(1) {
            if let Handle::Bead(under) = &above {
                self.folds.set(Handle::Elided(under.clone()), true);
            }
            self.folds.set(above, true);
        }
    }

    fn step_to(&mut self, target: Option<usize>) {
        if let Some(target) = target {
            self.selected = target;
            self.cursor = self.handle_at(target);
        }
    }

    /// The first line at or beyond `from` that the selection can sit on.
    fn scan(&self, from: usize, forward: bool) -> Option<usize> {
        let range: Vec<usize> = if forward {
            (from..self.lines.len()).collect()
        } else {
            (0..=from.min(self.lines.len().checked_sub(1)?))
                .rev()
                .collect()
        };
        range.into_iter().find(|i| selectable(&self.lines[*i]))
    }

    /// The next line the selection can sit on, past `from`.
    fn step(&self, from: usize, forward: bool) -> Option<usize> {
        if forward {
            self.scan(from + 1, true)
        } else {
            self.scan(from.checked_sub(1)?, false)
        }
    }

    fn parent_of(&self, at: usize) -> Option<usize> {
        let depth = self.lines.get(at)?.depth;
        if depth == 0 {
            return None;
        }
        self.lines[..at]
            .iter()
            .rposition(|line| line.depth < depth && selectable(line))
    }

    fn first_child_of(&self, at: usize) -> Option<usize> {
        let depth = self.lines.get(at)?.depth;
        self.lines
            .iter()
            .enumerate()
            .skip(at + 1)
            .take_while(|(_, line)| line.depth > depth)
            .find(|(_, line)| line.depth == depth + 1 && selectable(line))
            .map(|(at, _)| at)
    }

    fn fold_at(&self, at: usize) -> Option<bool> {
        self.lines.get(at)?.folded
    }

    fn handle_at(&self, at: usize) -> Option<Handle> {
        handle_of(self.lines.get(at)?)
    }

    /// Redraw, and put the selection back on whatever it was holding, handing
    /// back the lines the redraw displaced.
    ///
    /// They are moved out rather than copied. This runs on every keystroke,
    /// and a caller asking whether the screen moved can compare the two sets
    /// without duplicating either.
    fn lay_out(&mut self) -> Vec<Line> {
        self.settle_cursor();
        let rooted = self.rooted();
        let drawn = layout::draw(&self.snapshot, &self.facts, &self.folds, rooted.as_ref());
        let was = std::mem::replace(&mut self.lines, drawn);
        if self.find_cursor().is_none() {
            // The line the cursor named is not drawn — an ancestor is folded
            // over it, or the tracker stopped reporting it. Take the nearest
            // line that is. Nothing needs drawing again for it: the fold
            // state no longer turns on where the selection sits.
            self.cursor = self
                .forebear_drawn_over_the_cursors_hidden_tree()
                .or_else(|| {
                    self.scan(self.selected, false)
                        .or_else(|| self.scan(self.selected, true))
                        .and_then(|at| self.handle_at(at))
                });
        }
        self.selected = self.find_cursor().unwrap_or(0);
        was
    }

    /// Where the filter has taken the cursor's tree into the group holding
    /// its project's hidden trees, the nearest of the cursor's forebears that
    /// is drawn: the tree's root, resting shut over the cursor, where the
    /// group is open, and the group's line where it is shut. Either is where
    /// the tree went, which is more than the nearest row can say.
    ///
    /// Only the cursor's own tree going into the group does this. A fold
    /// shutting over the selection in a tree still drawn leaves it on the
    /// nearest row, as it always has.
    fn forebear_drawn_over_the_cursors_hidden_tree(&self) -> Option<Handle> {
        let (Handle::Bead(place) | Handle::Elided(place)) = self.cursor.as_ref()? else {
            return None;
        };
        if !self.hidden(&place.tree) {
            return None;
        }
        self.ancestry()
            .into_iter()
            .skip(1)
            .find(|forebear| self.line_holding(forebear).is_some())
    }

    /// Which line carries a handle, where one does.
    fn line_holding(&self, handle: &Handle) -> Option<usize> {
        (0..self.lines.len()).find(|at| self.handle_at(*at).as_ref() == Some(handle))
    }

    fn settle_cursor(&mut self) {
        if self.cursor.as_ref().is_some_and(|held| self.present(held)) {
            return;
        }
        self.cursor = self.first_handle();
    }

    /// Which line the cursor is on. A bead reachable more than once is drawn
    /// once per way down to it, and the handle names the way down, so exactly
    /// one line carries it — which is what lets a step onto the lower copy
    /// survive the redraw that follows it.
    fn find_cursor(&self) -> Option<usize> {
        self.line_holding(self.cursor.as_ref()?)
    }

    fn first_handle(&self) -> Option<Handle> {
        if let Some(tree) = self.snapshot.trees.first() {
            return Some(Handle::Bead(Place::root(root_key(tree))));
        }
        let rooted = self.rooted();
        layout::every_group(&self.snapshot)
            .find(|(kind, project)| {
                layout::group_drawn(&self.snapshot, *kind, project.as_deref(), rooted.as_ref())
            })
            .map(|(kind, project)| Handle::Group(kind, project))
    }

    /// Whether the snapshot still holds what a handle names.
    fn present(&self, handle: &Handle) -> bool {
        match handle {
            Handle::Bead(place) | Handle::Elided(place) => self.drawn(place),
            Handle::Group(kind, project) => layout::group_drawn(
                &self.snapshot,
                *kind,
                project.as_deref(),
                self.rooted().as_ref(),
            ),
            Handle::Item(key) => layout::group_holding(&self.snapshot, key).is_some(),
            Handle::Project(project) => layout::project_drawn(&self.snapshot, project),
        }
    }

    /// Whether the snapshot still draws the line a place names.
    fn drawn(&self, place: &Place) -> bool {
        // A tracker that could not be read keeps its root and has no nodes,
        // so its header is drawn with nothing beneath it to walk to.
        if place.steps.is_empty() {
            return self.tree_of(place).is_some();
        }
        self.locate(place).is_some()
    }
}

/// The first way down a tree that reaches a bead, as the place the line at
/// the end of it stands on. Nothing where the tree holds no such bead.
///
/// The walk carries the beads it came through, which is what cuts a loop: a
/// way down that comes back to a bead it came through stops there, so a
/// cyclic tree is walked once rather than for ever.
fn way_to(tree: &Tree, facts: &TreeFacts, id: &str) -> Option<Place> {
    let root = Place::root(root_key(tree));
    if tree.beads.first()?.id == id {
        return Some(root);
    }
    stepped_to(tree, facts, id, 0, &[], &root)
}

/// The first way down from `at` that reaches a bead, given the beads stepped
/// through to reach `at` and the place it stands on.
///
/// The children come from `Facts::split` and not from `links_below`, for the
/// same reason `step_down` takes them from there: a parent with enough
/// finished branches draws the rest of its children first and the run after,
/// so *first* means first drawn rather than first sorted. Without it the copy
/// this lands on and the copy a search counted at could be two different
/// lines of the same bead.
fn stepped_to(
    tree: &Tree,
    facts: &TreeFacts,
    id: &str,
    at: usize,
    above: &[usize],
    place: &Place,
) -> Option<Place> {
    let mut way = above.to_vec();
    way.push(at);
    let (shown, elided) = facts.split(tree, at, above);
    shown.into_iter().chain(elided).find_map(|link| {
        let stepped = place.step_to(BeadKey {
            project: tree.project.clone(),
            id: tree.beads[link.bead].id.clone(),
        });
        if tree.beads[link.bead].id == id {
            return Some(stepped);
        }
        stepped_to(tree, facts, id, link.bead, &way, &stepped)
    })
}

/// The line `scope` names, and everything drawn beneath it.
///
/// Beneath is depth: the lines after it, up to the first one standing at its
/// own depth or shallower. A project is depth zero, the roots under it are
/// one, and a group's things are one under a group that is also zero, so the
/// scope of a project stops at the next project or the first group.
///
/// Nothing at all where `scope` is not drawn, which leaves the walk with no
/// fold to point and stops it.
fn subtree_of<'a>(drawn: &'a [Line], scope: &Handle) -> &'a [Line] {
    let Some(at) = drawn
        .iter()
        .position(|line| handle_of(line).as_ref() == Some(scope))
    else {
        return &[];
    };
    let depth = drawn[at].depth;
    let end = drawn[at + 1..]
        .iter()
        .position(|line| line.depth <= depth)
        .map_or(drawn.len(), |past| at + 1 + past);
    &drawn[at..end]
}

#[cfg(test)]
mod tests {
    use super::facts::TreeFacts;
    use super::*;
    use crate::collect::bd::parse_beads;
    use crate::collect::herdr::parse_agent_list;
    use crate::config::{Config, Scope};
    use crate::model::join::{self, Joined, Listed, ProjectRows};
    use crate::model::snapshot;
    use crate::model::snapshot::Counts;
    use crate::model::snapshot::{
        a_provider, build_tree, Collected, FailedProject, ProviderState, Readiness, TrackerFailure,
        TrackerState, A_PROVIDER,
    };
    use crate::model::tree::{self, Assembled, Nesting};
    use crate::model::types::testing::{key as pane_key, A_SESSION};
    use crate::model::types::{Bead, Pane};
    use crate::view::lines::{
        counts_beneath, facts_of, links_below, marker, prefix, progress_of, run_size, split,
        walks_on_this_thread, way_below, Group, Item, Note, ProjectLine, OPEN, SHUT,
    };
    use crate::view::phrase;
    use crate::view::row::{Progress, Row};
    use crate::view::walk::{self, Rows};
    use chrono::{DateTime, Utc};
    use pretty_assertions::assert_eq;
    use std::sync::Arc;

    /// Orbital's tree as bd writes it. `orb-7.7` waits on a bead no row holds,
    /// so the tree reports it; `orb-7.1.2` is a node bd stopped at; `orb-7.4`
    /// is closed with a pane still on it, and the other three closed siblings
    /// are finished.
    const ORBITAL: &str = r#"[
      {"id":"orb-7","title":"lift the ground station","status":"in_progress",
       "priority":1,"issue_type":"epic","updated_at":"2026-08-29T12:00:00Z",
       "metadata":{"agent_pane":"w:p1"}},
      {"id":"orb-7.1","title":"re-point the dish","status":"open",
       "dependencies":[{"depends_on_id":"orb-7","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"orb-7.1.1","title":"true the mount","status":"open",
       "dependencies":[{"depends_on_id":"orb-7.1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"orb-7.1.2","title":"seal the feed horn","status":"open",
       "dependencies":[{"depends_on_id":"orb-7.1","type":"parent-child"}],
       "priority":3,"issue_type":"task"},
      {"id":"orb-7.2","title":"survey the mast","status":"closed",
       "dependencies":[{"depends_on_id":"orb-7","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-28T09:00:00Z"},
      {"id":"orb-7.3","title":"pour the pad","status":"closed",
       "dependencies":[{"depends_on_id":"orb-7","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-27T09:00:00Z"},
      {"id":"orb-7.4","title":"clear the access road","status":"closed",
       "dependencies":[{"depends_on_id":"orb-7","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-26T09:00:00Z",
       "metadata":{"agent_pane":"w:p2"}},
      {"id":"orb-7.5","title":"set the guard rail","status":"closed",
       "dependencies":[{"depends_on_id":"orb-7","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-25T09:00:00Z"},
      {"id":"orb-7.7","title":"log the survey marks","status":"open",
       "priority":2,"issue_type":"task",
       "dependencies":[{"depends_on_id":"orb-7","type":"parent-child"},
                       {"depends_on_id":"orb-6","type":"blocks"}]}
    ]"#;

    /// Harbour's tree. Nobody is working in it, so the live-agent filter hides
    /// it.
    const HARBOUR: &str = r#"[
      {"id":"hbr-3","title":"dredge the channel","status":"open",
       "priority":2,"issue_type":"epic"},
      {"id":"hbr-3.1","title":"survey the silt","status":"open",
       "dependencies":[{"depends_on_id":"hbr-3","type":"parent-child"}],
       "priority":2,"issue_type":"task"}
    ]"#;

    /// A second root, nobody working in it either, holding a bead that waits
    /// on a row the tracker never returned. Whichever project files it, the
    /// tree is hidden with a finding still in it.
    /// The harbour and the slipway as one tree, which is what the tracker
    /// answers once somebody files the second root as a child of the first.
    /// Two roots become one, and the bead a reader was finishing is where it
    /// always was in their head and somewhere else in the answer.
    const SLIPWAY_UNDER_HARBOUR: &str = r#"[
      {"id":"hbr-3","title":"dredge the channel","status":"open",
       "priority":2,"issue_type":"epic"},
      {"id":"hbr-3.1","title":"survey the silt","status":"open",
       "dependencies":[{"depends_on_id":"hbr-3","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"hbr-9","title":"re-deck the slipway","status":"open",
       "dependencies":[{"depends_on_id":"hbr-3","type":"parent-child"}],
       "priority":2,"issue_type":"epic"},
      {"id":"hbr-9.1","title":"strip the planking","status":"open",
       "dependencies":[{"depends_on_id":"hbr-9","type":"parent-child"},
                       {"depends_on_id":"hbr-4","type":"blocks"}],
       "priority":2,"issue_type":"task"}
    ]"#;

    const SLIPWAY: &str = r#"[
      {"id":"hbr-9","title":"re-deck the slipway","status":"open",
       "priority":2,"issue_type":"epic"},
      {"id":"hbr-9.1","title":"strip the planking","status":"open",
       "dependencies":[{"depends_on_id":"hbr-9","type":"parent-child"},
                       {"depends_on_id":"hbr-4","type":"blocks"}],
       "priority":2,"issue_type":"task"}
    ]"#;

    /// A tree whose run of finished siblings has a finished run of its own, so
    /// an opened run still has something left to count inside it. Three at each
    /// level, which is what it takes to make a run.
    const DEPOT: &str = r#"[
      {"id":"dep-1","title":"re-lay the sidings","status":"in_progress",
       "priority":1,"issue_type":"epic"},
      {"id":"dep-1.1","title":"grade the bed","status":"open",
       "dependencies":[{"depends_on_id":"dep-1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"dep-1.2","title":"lift the old rail","status":"closed",
       "dependencies":[{"depends_on_id":"dep-1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-28T09:00:00Z"},
      {"id":"dep-1.2.1","title":"cut the fishplates","status":"closed",
       "dependencies":[{"depends_on_id":"dep-1.2","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-27T09:00:00Z"},
      {"id":"dep-1.2.2","title":"stack the chairs","status":"closed",
       "dependencies":[{"depends_on_id":"dep-1.2","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-27T09:00:00Z"},
      {"id":"dep-1.2.3","title":"draw the spikes","status":"closed",
       "dependencies":[{"depends_on_id":"dep-1.2","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-27T09:00:00Z"},
      {"id":"dep-1.3","title":"clear the ballast","status":"closed",
       "dependencies":[{"depends_on_id":"dep-1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-26T09:00:00Z"},
      {"id":"dep-1.4","title":"burn the sleepers","status":"closed",
       "dependencies":[{"depends_on_id":"dep-1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-25T09:00:00Z"}
    ]"#;

    /// The shape `bdi-4av` was raised on, with the stale-pane case beside it.
    /// `rly-2.2` and `rly-2.4` are both closed and unmanned, so a rule that
    /// asks its question of the sibling alone sweeps both into the run —
    /// burying a working agent two levels under one of them and a stale-pane
    /// warning under the other. `rly-2.3`, `rly-2.5` and `rly-2.6` are
    /// finished all the way down, and are what a run may honestly hold.
    const RELAY: &str = r#"[
      {"id":"rly-2","title":"re-site the relay","status":"in_progress",
       "priority":1,"issue_type":"epic"},
      {"id":"rly-2.1","title":"trench the run","status":"open",
       "dependencies":[{"depends_on_id":"rly-2","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"rly-2.2","title":"strike the old mast","status":"closed",
       "dependencies":[{"depends_on_id":"rly-2","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-28T09:00:00Z"},
      {"id":"rly-2.2.1","title":"drop the guys","status":"closed",
       "dependencies":[{"depends_on_id":"rly-2.2","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-27T09:00:00Z"},
      {"id":"rly-2.2.1.1","title":"cut the stays","status":"in_progress",
       "dependencies":[{"depends_on_id":"rly-2.2.1","type":"parent-child"}],
       "priority":2,"issue_type":"task","updated_at":"2026-08-29T12:00:00Z",
       "metadata":{"agent_pane":"w:p1"}},
      {"id":"rly-2.3","title":"back-fill the pad","status":"closed",
       "dependencies":[{"depends_on_id":"rly-2","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-26T09:00:00Z"},
      {"id":"rly-2.4","title":"lift the feeder","status":"closed",
       "dependencies":[{"depends_on_id":"rly-2","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-26T09:00:00Z"},
      {"id":"rly-2.4.1","title":"coil the heliax","status":"closed",
       "dependencies":[{"depends_on_id":"rly-2.4","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-25T09:00:00Z",
       "metadata":{"agent_pane":"w:p2"}},
      {"id":"rly-2.5","title":"seed the spoil","status":"closed",
       "dependencies":[{"depends_on_id":"rly-2","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-25T09:00:00Z"},
      {"id":"rly-2.5.1","title":"rake the batter","status":"closed",
       "dependencies":[{"depends_on_id":"rly-2.5","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-24T09:00:00Z"},
      {"id":"rly-2.6","title":"sign the handover","status":"closed",
       "dependencies":[{"depends_on_id":"rly-2","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-24T09:00:00Z"}
    ]"#;

    /// A spine four beads deep, with a quiet branch of its own beside it.
    /// Nothing in it is closed, in progress or staffed, so the only thing
    /// that can open a fold in it is a pane the test puts on a bead.
    const TOWER: &str = r#"[
      {"id":"tow-1","title":"raise the tower","status":"open",
       "priority":1,"issue_type":"epic"},
      {"id":"tow-1.1","title":"stand the mast","status":"open",
       "dependencies":[{"depends_on_id":"tow-1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"tow-1.1.1","title":"bolt the sections","status":"open",
       "dependencies":[{"depends_on_id":"tow-1.1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"tow-1.1.1.1","title":"dress the cables","status":"open",
       "dependencies":[{"depends_on_id":"tow-1.1.1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"tow-1.2","title":"pour the base","status":"open",
       "dependencies":[{"depends_on_id":"tow-1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"tow-1.2.1","title":"tie the rebar","status":"open",
       "dependencies":[{"depends_on_id":"tow-1.2","type":"parent-child"}],
       "priority":2,"issue_type":"task"}
    ]"#;

    /// A closed bead standing over work that is still to do. A blocker is
    /// drawn beneath the bead it blocks, so `sdg-4.1`'s descendants are the
    /// work closing it unblocked — the ordinary shape of this tree, not a
    /// malformed one. Nobody is on any of them and nothing is wrong with
    /// them, so the branch rests shut under a row whose own glyph says done.
    /// `sdg-4.2` is finished all the way down. `sdg-4.3` carries the only
    /// pane, which is what opens the root, and rests shut over unfinished
    /// work of its own without ever claiming to be done.
    const SIDING: &str = r#"[
      {"id":"sdg-4","title":"re-point the crossover","status":"in_progress",
       "priority":1,"issue_type":"epic"},
      {"id":"sdg-4.1","title":"slew the up line","status":"closed",
       "dependencies":[{"depends_on_id":"sdg-4","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-28T09:00:00Z"},
      {"id":"sdg-4.1.1","title":"key the switch","status":"closed",
       "dependencies":[{"depends_on_id":"sdg-4.1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-27T09:00:00Z"},
      {"id":"sdg-4.1.1.1","title":"gauge the check rail","status":"open",
       "dependencies":[{"depends_on_id":"sdg-4.1.1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"sdg-4.1.1.2","title":"pack the timbers","status":"open",
       "dependencies":[{"depends_on_id":"sdg-4.1.1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"sdg-4.1.2","title":"weld the closure rail","status":"open",
       "dependencies":[{"depends_on_id":"sdg-4.1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"sdg-4.1.3","title":"lift the old chairs","status":"closed",
       "dependencies":[{"depends_on_id":"sdg-4.1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-26T09:00:00Z"},
      {"id":"sdg-4.2","title":"clip the down line","status":"closed",
       "dependencies":[{"depends_on_id":"sdg-4","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-26T09:00:00Z"},
      {"id":"sdg-4.2.1","title":"torque the fishbolts","status":"closed",
       "dependencies":[{"depends_on_id":"sdg-4.2","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-25T09:00:00Z"},
      {"id":"sdg-4.3","title":"re-signal the box","status":"in_progress",
       "dependencies":[{"depends_on_id":"sdg-4","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"sdg-4.3.1","title":"prove the interlocking","status":"open",
       "dependencies":[{"depends_on_id":"sdg-4.3","type":"parent-child"}],
       "priority":2,"issue_type":"task"}
    ]"#;

    /// A configured root that is a leaf. `[roots]` names a bead and nothing
    /// requires that bead to have children, so a tracker whose root is one
    /// bead deep draws a line that is a root and holds no fold. It is the
    /// only shape here where being a root and having children come apart,
    /// and every other fixture answers both questions the same way.
    ///
    /// It names no pane, like Depot, Tower and Siding, so a test staffs it by
    /// naming the bead and one that does not gets the quiet shape.
    const BEACON: &str = r#"[
      {"id":"bcn-6","title":"re-lamp the beacon","status":"in_progress",
       "priority":1,"issue_type":"task","updated_at":"2026-08-29T12:00:00Z"}
    ]"#;

    /// One epic whose two halves are each held up by the same survey. Under
    /// the rule that a bead's descendants are what must finish before it,
    /// `orb-9` is drawn beneath both of them: under `orb-8.1` as its child,
    /// and under `orb-8.2` as what it waits on.
    const TWICE: &str = r#"[
      {"id":"orb-8","title":"lift the gantry","status":"in_progress",
       "priority":1,"issue_type":"epic"},
      {"id":"orb-8.1","title":"pour the pad","status":"in_progress",
       "dependencies":[{"depends_on_id":"orb-8","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"orb-8.2","title":"rail the crane","status":"in_progress",
       "dependencies":[{"depends_on_id":"orb-8","type":"parent-child"},
                       {"depends_on_id":"orb-9","type":"blocks"}],
       "priority":2,"issue_type":"task"},
      {"id":"orb-9","title":"survey the ground","status":"in_progress",
       "dependencies":[{"depends_on_id":"orb-8.1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"orb-9.1","title":"drill the cores","status":"in_progress",
       "dependencies":[{"depends_on_id":"orb-9","type":"parent-child"}],
       "priority":2,"issue_type":"task"}
    ]"#;

    /// A closed bead holding unfinished work, drawn twice in one tree: under
    /// `orb-5.1` as its child, and under `orb-5.2` as what it waits on. Both
    /// copies rest shut, because nothing under either is live or ready, so
    /// what each of them says about the work it is shut over is all that
    /// tells them apart.
    ///
    /// `orb-5.1.1` and `orb-5.2.1` are here to be worked on: they are what
    /// holds the two halves open, so both copies of `orb-4` are on the
    /// screen at once.
    const CLOSED_TWICE: &str = r#"[
      {"id":"orb-5","title":"re-deck the bridge","status":"in_progress",
       "priority":1,"issue_type":"epic"},
      {"id":"orb-5.1","title":"strip the north span","status":"in_progress",
       "dependencies":[{"depends_on_id":"orb-5","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"orb-5.1.1","title":"cut the north deck","status":"in_progress",
       "dependencies":[{"depends_on_id":"orb-5.1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"orb-4","title":"close the towpath","status":"closed",
       "dependencies":[{"depends_on_id":"orb-5.1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-28T09:00:00Z"},
      {"id":"orb-4.1","title":"post the diversion","status":"open",
       "dependencies":[{"depends_on_id":"orb-4","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"orb-5.2","title":"strip the south span","status":"in_progress",
       "dependencies":[{"depends_on_id":"orb-5","type":"parent-child"},
                       {"depends_on_id":"orb-4","type":"blocks"}],
       "priority":2,"issue_type":"task"},
      {"id":"orb-5.2.1","title":"cut the south deck","status":"in_progress",
       "dependencies":[{"depends_on_id":"orb-5.2","type":"parent-child"}],
       "priority":2,"issue_type":"task"}
    ]"#;

    /// One tree drawing one bead twice, which is the shape a blocker nested
    /// under each bead it holds up gives: same root, same key, two lines.
    fn drawn_twice_in_one_tree() -> Snapshot {
        alone("orbital", TWICE, &panes_on(&["orb-9.1"]))
    }

    /// The same, over a closed bead that still holds unfinished work.
    fn closed_bead_drawn_twice_in_one_tree() -> Snapshot {
        alone(
            "orbital",
            CLOSED_TWICE,
            &panes_on(&["orb-5.1.1", "orb-5.2.1"]),
        )
    }

    /// A run whose branches share a blocker. `lck-2` holds up both halves of
    /// the refit, so it is drawn beneath each of them, and the four branches
    /// that are closed and unmanned collapse into one run — five beads drawn
    /// on six rows.
    ///
    /// The only shape where counting beads and counting rows disagree: every
    /// other fixture's runs draw each of their beads once. `lck-1.5` is the
    /// work still to do, and is what holds the root open so the run is on
    /// the screen at all.
    const SHARED_IN_A_RUN: &str = r#"[
      {"id":"lck-1","title":"refit the lock gates","status":"in_progress",
       "priority":1,"issue_type":"epic"},
      {"id":"lck-1.5","title":"hang the new gates","status":"in_progress",
       "dependencies":[{"depends_on_id":"lck-1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"lck-1.1","title":"drain the upper chamber","status":"closed",
       "dependencies":[{"depends_on_id":"lck-1","type":"parent-child"},
                       {"depends_on_id":"lck-2","type":"blocks"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-28T09:00:00Z"},
      {"id":"lck-1.2","title":"drain the lower chamber","status":"closed",
       "dependencies":[{"depends_on_id":"lck-1","type":"parent-child"},
                       {"depends_on_id":"lck-2","type":"blocks"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-27T09:00:00Z"},
      {"id":"lck-1.3","title":"scarf the mitre posts","status":"closed",
       "dependencies":[{"depends_on_id":"lck-1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-26T09:00:00Z"},
      {"id":"lck-1.4","title":"re-seat the paddles","status":"closed",
       "dependencies":[{"depends_on_id":"lck-1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-25T09:00:00Z"},
      {"id":"lck-2","title":"stop off the pound","status":"closed",
       "priority":2,"issue_type":"task","closed_at":"2026-08-24T09:00:00Z"}
    ]"#;

    /// Two of one project's roots whose trees overlap. `qua-1.2` blocks both
    /// epics, and a blocker is drawn beneath every bead it blocks, so it
    /// comes back under each of them. Roots are found by climbing the parent
    /// chain and trees by walking dependents, so a bead standing in two trees
    /// is the ordinary shape of shared work, not a malformed tracker.
    const QUARRY: &str = r#"[
      {"id":"qua-1","title":"re-open the quarry","status":"in_progress",
       "priority":1,"issue_type":"epic"},
      {"id":"qua-1.2","title":"cut the haul road","status":"in_progress",
       "dependencies":[{"depends_on_id":"qua-1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"qua-1.2.1","title":"strip the overburden","status":"in_progress",
       "dependencies":[{"depends_on_id":"qua-1.2","type":"parent-child"}],
       "priority":2,"issue_type":"task"}
    ]"#;

    /// The second of the pair, drawn below Quarry, so the shared bead's lower
    /// copy sits here with more rows under it. Those are the bottom of the
    /// whole list, and are what a selection sprung back up to the upper copy
    /// never reaches.
    ///
    /// The shared bead has a child in each tree, and not the same one, so
    /// each copy is a line that folds over a list of its own.
    const WHARF: &str = r#"[
      {"id":"wha-2","title":"re-face the wharf","status":"in_progress",
       "priority":1,"issue_type":"epic"},
      {"id":"wha-2.1","title":"drive the piles","status":"in_progress",
       "dependencies":[{"depends_on_id":"wha-2","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"qua-1.2","title":"cut the haul road","status":"in_progress",
       "dependencies":[{"depends_on_id":"wha-2","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"wha-2.2","title":"grout the cope","status":"in_progress",
       "dependencies":[{"depends_on_id":"qua-1.2","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"wha-2.3","title":"bed the fenders","status":"in_progress",
       "dependencies":[{"depends_on_id":"wha-2","type":"parent-child"}],
       "priority":2,"issue_type":"task"}
    ]"#;

    /// `w:p3` and `w:p4` both name `orb-7.1`, so neither holds it; `w:p9` is
    /// working in the project whose tracker refused; `w:pF` is under no
    /// configured project at all.
    const PANES: &str = r#"{"result":{"agents":[
      {"pane_id":"w:p1","cwd":"/srv/work/orbital","agent_status":"working"},
      {"pane_id":"w:p2","cwd":"/srv/work/orbital","agent_status":"idle"},
      {"pane_id":"w:p3","cwd":"/srv/work/orbital","agent_status":"working",
       "display_agent":"orb-7.1"},
      {"pane_id":"w:p4","cwd":"/srv/work/orbital","agent_status":"idle",
       "display_agent":"orb-7.1"},
      {"pane_id":"w:p9","cwd":"/srv/work/ferry","agent_status":"blocked"},
      {"pane_id":"w:pF","cwd":"/srv/spike","agent_status":"idle"}
    ]}}"#;

    fn cfg() -> Config {
        Config::from_toml(
            r#"
[[projects]]
name = "orbital"
path = "/srv/work/orbital"
credential_command = "secret orbital"

[[projects]]
name = "ferry"
path = "/srv/work/ferry"
credential_command = "secret ferry"

[[projects]]
name = "harbour"
path = "/srv/work/harbour"
credential_command = "secret harbour"
"#,
        )
        .expect("the config parses")
    }

    fn now() -> DateTime<Utc> {
        "2026-08-30T12:00:00Z".parse().expect("the instant parses")
    }

    /// One tree with a row edited, where the edit is required to land.
    ///
    /// `str::replace` says nothing when it matches nothing, so a pattern that
    /// drifts from the const it edits leaves the test asserting against the
    /// untouched tree and still passing.
    fn edited(json: &str, from: &str, to: &str) -> String {
        let out = json.replace(from, to);
        assert_ne!(out, json, "no row matched {from:?}");
        out
    }

    /// The root of a hand-written tree: the one row that depends on nothing.
    fn root_row(beads: &[crate::model::types::Bead]) -> String {
        beads
            .iter()
            .find(|b| b.dependencies.is_empty())
            .expect("a root row")
            .id
            .clone()
    }

    fn assembled(json: &str) -> Assembled {
        let beads = parse_beads(json).expect("the rows parse");
        let root = root_row(&beads);
        Nesting::of(&beads)
            .assemble(&root)
            .expect("the rows assemble")
    }

    fn panes() -> Vec<Pane> {
        parse_agent_list(A_SESSION, PANES).expect("the panes parse")
    }

    /// One working pane and one idle one, both in Orbital's tree. Enough to
    /// staff a fixture without the conflicting and unconfigured panes the
    /// shared snapshot carries to exercise its groups.
    const TWO_PANES: &str = r#"{"result":{"agents":[
      {"pane_id":"w:p1","cwd":"/srv/work/orbital","agent_status":"working"},
      {"pane_id":"w:p2","cwd":"/srv/work/orbital","agent_status":"idle"}
    ]}}"#;

    fn two_panes() -> Vec<Pane> {
        parse_agent_list(A_SESSION, TWO_PANES).expect("the panes parse")
    }

    fn joined(orbital: &Assembled, harbour: &Assembled, panes: &[Pane]) -> Joined {
        let cfg = cfg();
        join::resolve(
            &[
                ProjectRows {
                    project: "orbital",
                    rows: &orbital.beads,
                },
                ProjectRows {
                    project: "harbour",
                    rows: &harbour.beads,
                },
            ],
            Listed::all(panes),
            &cfg,
        )
    }

    fn tree_of(project: &str, json: &str) -> Tree {
        let orbital = assembled(ORBITAL);
        let harbour = assembled(HARBOUR);
        let panes = panes();
        let joined = joined(&orbital, &harbour, &panes);
        build_tree(
            project,
            &assembled(json),
            &joined,
            &Readiness::default(),
            &BTreeMap::new(),
            ProviderState::Answering,
            &cfg(),
            now(),
        )
    }

    /// The first way down to bead `at`: the beads above it on the way the
    /// walk first reached it, the root first.
    fn above(tree: &Tree, at: usize) -> Vec<usize> {
        let mut way = Vec::new();
        let mut reached = at;
        while reached != 0 {
            reached = (0..tree.beads.len())
                .find(|from| {
                    tree.children[*from]
                        .iter()
                        .any(|link| link.bead == reached && link.first)
                })
                .expect("every bead but the root was first reached under one");
            way.push(reached);
        }
        way.reverse();
        way
    }

    /// A bead by id, and the first way down to it.
    fn way_to(tree: &Tree, id: &str) -> (usize, Vec<usize>) {
        let at = tree
            .beads
            .iter()
            .position(|bead| bead.id == id)
            .unwrap_or_else(|| panic!("{id} is in the tree"));
        (at, above(tree, at))
    }

    /// Every configured project, read at `now`.
    ///
    /// These fixtures are collections that have come back, so every project
    /// has been read whether or not its tracker had a root to show for it.
    /// That is what tells them from the first frame of a run, where nothing
    /// has been read and every project is still waiting on one.
    fn every_project_read() -> std::collections::BTreeMap<String, chrono::DateTime<chrono::Utc>> {
        cfg()
            .projects
            .iter()
            .map(|project| (project.name.clone(), now()))
            .collect()
    }

    fn gather(trees: Vec<Tree>, failed: Vec<FailedProject>, filter: Filter) -> Snapshot {
        let orbital = assembled(ORBITAL);
        let harbour = assembled(HARBOUR);
        let panes = panes();
        let joined = joined(&orbital, &harbour, &panes);
        snapshot::build(
            Collected {
                trees,
                failed_projects: failed,
                read_at: every_project_read(),
            },
            &panes,
            &joined,
            &cfg(),
            a_provider(ProviderState::Answering),
            filter,
            now(),
        )
    }

    /// Three roots: one read and staffed, one whose tracker refused, one read
    /// and quiet. Plus a project that failed before its roots were known.
    fn built(filter: Filter) -> Snapshot {
        gather(
            vec![
                tree_of("orbital", ORBITAL),
                Tree::tracker_unreachable("ferry", "fer-2", TrackerFailure::Auth),
                tree_of("harbour", HARBOUR),
            ],
            vec![FailedProject {
                project: "lunar".into(),
                tracker: TrackerFailure::Unstartable,
            }],
            filter,
        )
    }

    fn snapshot() -> Snapshot {
        built(Filter::LiveAgents)
    }

    /// One line as its prefix plus enough of its content to read the shape.
    fn sketch(forest: &Forest) -> Vec<String> {
        forest
            .lines()
            .iter()
            .map(|line| format!("{}{}", line.prefix, said(&line.content)))
            .collect()
    }

    fn said(content: &Content) -> String {
        match content {
            Content::Project(line) => line.project.clone(),
            Content::Unread(unread) => format!("{} unread", unread.root),
            Content::Bead(row) => format!("{} {} {}", row.glyph, row.id, row.title),
            Content::Elided { count, .. } => format!("{count} more"),
            Content::Note(note) => format!("! {note:?}"),
            Content::Group(group) => format!(
                "[{:?}{}] {}",
                group.kind,
                group
                    .project
                    .as_ref()
                    .map(|project| format!(" {project}"))
                    .unwrap_or_default(),
                group.count
            ),
            Content::Item(item) => format!("- {item:?}"),
            Content::Scoped { project } => format!("~ reading {project}"),
        }
    }

    /// The drawn row for one bead, found by the whole id its line carries
    /// rather than the abbreviated one it shows.
    fn row_of<'a>(forest: &'a Forest, id: &str) -> &'a Row {
        forest
            .lines()
            .iter()
            .find_map(|line| match (line.bead(), &line.content) {
                (Some(bead), Content::Bead(row)) if bead.id == id => Some(row),
                _ => None,
            })
            .unwrap_or_else(|| panic!("{id} is not drawn"))
    }

    /// Every line drawn for one bead, by index. A bead reachable from two
    /// roots is drawn under each, so this answers with more than one.
    fn lines_of(forest: &Forest, id: &str) -> Vec<usize> {
        forest
            .lines()
            .iter()
            .enumerate()
            .filter(|(_, line)| line.bead().is_some_and(|bead| bead.id == id))
            .map(|(at, _)| at)
            .collect()
    }

    /// Step down from the top to the last row, reporting where the selection
    /// sat at each step.
    fn walk_down(forest: &mut Forest) -> Vec<usize> {
        forest.apply(Action::Move(Motion::FirstRow));
        let mut visited = vec![forest.selected_line()];
        walk::until(
            forest,
            |forest| forest.selected_line() + 1 == forest.rows(),
            |forest| {
                forest.apply(Action::Move(Motion::NextRow));
                visited.push(forest.selected_line());
            },
            |forest| {
                format!(
                    "stepping down stopped at row {} of {}: {:#?}",
                    forest.selected_line(),
                    forest.rows(),
                    sketch(forest)
                )
            },
        );
        visited
    }

    /// A bead reachable from two roots is drawn in both their trees, and the
    /// selection has to be able to sit on either copy. `find_cursor` took the
    /// first line carrying the handle, so the redraw that follows every
    /// action pulled a step onto the lower copy back up to the upper one, and
    /// the list below it could not be walked into at all.
    #[test]
    fn stepping_down_past_a_bead_drawn_twice_reaches_the_bottom_of_the_list() {
        let mut forest = flatten(overlapping(&panes_on(&["qua-1.2", "wha-2.1"])));
        assert_eq!(
            lines_of(&forest, "qua-1.2").len(),
            2,
            "{:#?}",
            sketch(&forest)
        );
        let drawn = forest.lines().len();

        assert_eq!(
            walk_down(&mut forest),
            (0..drawn).collect::<Vec<usize>>(),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// A tracker that refused keeps its root and reports no nodes, so there
    /// is no way down from its header to walk. The header is a line all the
    /// same, and holding the selection on it across a refresh is what says
    /// the forest knows a tree by its root rather than by a node.
    #[test]
    fn the_selection_holds_the_line_of_a_root_whose_tracker_refused() {
        let mut forest = flatten(snapshot());
        let header = forest
            .lines()
            .iter()
            .position(
                |line| matches!(&line.content, Content::Unread(unread) if unread.root == "fer-2"),
            )
            .expect("the shared snapshot draws a tree whose tracker refused");

        step_onto(&mut forest, header);
        forest.refresh(snapshot());

        assert_eq!(forest.selected_line(), header, "{:#?}", sketch(&forest));
    }

    /// The forest holds the trees it was handed, not copies of them. A
    /// collection landing while the reader moves is a stall on top of the
    /// keystroke it arrives beside, and copying every tree into the forest
    /// was most of that stall.
    #[test]
    fn the_forest_holds_the_trees_it_was_handed_rather_than_copies() {
        let handed = snapshot();
        let trees = handed.trees.clone();
        let mut forest = flatten(handed);
        assert_held_exactly(&forest, &trees);

        let again = snapshot();
        let trees = again.trees.clone();
        forest.refresh(again);
        assert_held_exactly(&forest, &trees);
    }

    fn assert_held_exactly(forest: &Forest, trees: &[Arc<Tree>]) {
        assert_eq!(forest.snapshot().trees.len(), trees.len());
        for (held, was) in forest.snapshot().trees.iter().zip(trees) {
            assert!(Arc::ptr_eq(held, was), "{} was copied", was.root);
            assert_eq!(
                Arc::strong_count(was),
                3,
                "{} is held by collected, trees and this test, and nothing else",
                was.root
            );
        }
    }

    /// Each copy of a bead drawn twice folds over a list of its own, so
    /// shutting one says nothing about the other. Both carried the same
    /// handle, so one keystroke shut them both and the reader lost a list
    /// they had never been looking at.
    #[test]
    fn folding_one_copy_of_a_bead_drawn_twice_leaves_the_other_open() {
        let mut forest = flatten(overlapping(&panes_on(&["qua-1.2", "wha-2.1"])));
        let [upper, lower] = copies_of(&forest, "qua-1.2");

        step_onto(&mut forest, lower);
        forest.apply(Action::ToggleFold);

        assert_eq!(
            forest.lines()[upper].folded,
            Some(true),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// The same bead under two parents in one tree, which is what a `blocks`
    /// edge drawn as nesting gives: the copies share a root as well as a key,
    /// so nothing but the way down to them tells them apart.
    ///
    /// Each copy is opened against the way the other one rests, so a fold
    /// remembered against the bead rather than against the line would have to
    /// give one of them the other's answer.
    #[test]
    fn folding_one_copy_of_a_bead_drawn_twice_in_one_tree_leaves_the_other_alone() {
        let mut forest = flatten(drawn_twice_in_one_tree());
        let [_, lower] = copies_of(&forest, "orb-9");

        step_onto(&mut forest, lower);
        forest.apply(Action::ToggleFold);
        let [upper, _] = copies_of(&forest, "orb-9");
        step_onto(&mut forest, upper);
        forest.apply(Action::ToggleFold);

        let [upper, lower] = copies_of(&forest, "orb-9");
        assert_eq!(
            (forest.lines()[upper].folded, forest.lines()[lower].folded),
            (Some(false), Some(true)),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// A bead reached more than one way down is one piece of work with a line
    /// each, and the first line is the one that stands for it. The rest are
    /// shut, so the subtree is drawn once however many ways there are into it.
    #[test]
    fn a_bead_drawn_twice_in_one_tree_rests_open_on_the_first_line_and_shut_on_the_second() {
        let forest = flatten(drawn_twice_in_one_tree());
        let [upper, lower] = copies_of(&forest, "orb-9");

        assert_eq!(
            (forest.lines()[upper].folded, forest.lines()[lower].folded),
            (Some(true), Some(false)),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// Shut, never absent: the later line is a way into the same subtree, and
    /// opening it draws the subtree there too.
    #[test]
    fn the_second_line_of_a_bead_drawn_twice_opens_onto_the_same_subtree() {
        let mut forest = flatten(drawn_twice_in_one_tree());
        let [_, lower] = copies_of(&forest, "orb-9");
        assert_eq!(
            lines_of(&forest, "orb-9.1").len(),
            1,
            "{:#?}",
            sketch(&forest)
        );

        step_onto(&mut forest, lower);
        forest.apply(Action::ToggleFold);

        assert_eq!(
            lines_of(&forest, "orb-9.1").len(),
            2,
            "{:#?}",
            sketch(&forest)
        );
    }

    /// `D` lets go of every fold set by hand, so a reader who opened a later
    /// line gets it back the way `bdi` would have drawn it.
    #[test]
    fn letting_go_of_the_folds_shuts_a_second_line_a_reader_opened() {
        let mut forest = flatten(drawn_twice_in_one_tree());
        let [_, lower] = copies_of(&forest, "orb-9");
        step_onto(&mut forest, lower);
        forest.apply(Action::ToggleFold);

        forest.apply(Action::RestoreDefault);

        let [upper, lower] = copies_of(&forest, "orb-9");
        assert_eq!(
            (forest.lines()[upper].folded, forest.lines()[lower].folded),
            (Some(true), Some(false)),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// A shut closed line says what unfinished work it is shut over, because
    /// those beads are then nowhere else on the screen. On a later line of the
    /// same bead they are somewhere else on the screen — on the first line —
    /// so it says nothing, and the count a reader reads is the work rather
    /// than the ways down to it.
    #[test]
    fn only_the_first_line_of_a_bead_drawn_twice_says_what_it_is_shut_over() {
        let forest = flatten(closed_bead_drawn_twice_in_one_tree());
        let [upper, lower] = copies_of(&forest, "orb-4");

        assert_eq!(
            (notes_at(&forest, upper), notes_at(&forest, lower)),
            (vec![phrase::unfinished_beneath(1)], Vec::new()),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// What a bead row says beyond its own fields, on one line.
    fn notes_at(forest: &Forest, at: usize) -> Vec<String> {
        match &forest.lines()[at].content {
            Content::Bead(row) => row.notes.clone(),
            content => panic!("line {at} is not a bead row: {content:?}"),
        }
    }

    /// The two lines a bead is drawn on, asserted to be exactly two so a
    /// fixture that stopped overlapping fails here rather than further down.
    fn copies_of(forest: &Forest, id: &str) -> [usize; 2] {
        let copies = lines_of(forest, id);
        let [upper, lower] = copies[..] else {
            panic!(
                "{id} is drawn {} times: {:#?}",
                copies.len(),
                sketch(forest)
            );
        };
        [upper, lower]
    }

    /// Put the selection on a line by stepping down onto it, which is the
    /// only road a reader has to it.
    fn step_onto(forest: &mut Forest, at: usize) {
        forest.apply(Action::Move(Motion::FirstRow));
        walk::until(
            forest,
            |forest| forest.selected_line() == at,
            |forest| {
                forest.apply(Action::Move(Motion::NextRow));
            },
            |forest| {
                format!(
                    "the selection never reached line {at}: {:#?}",
                    sketch(forest)
                )
            },
        );
    }

    /// The tracker is written while the list is being read, so a refresh can
    /// land between any two keystrokes. It re-derives the selection from the
    /// handle it holds, and must settle on the copy the selection was on
    /// rather than on that copy's twin higher up the list.
    #[test]
    fn a_refresh_between_steps_does_not_pull_the_selection_back_to_a_twin() {
        let panes = panes_on(&["qua-1.2", "wha-2.1"]);
        let mut forest = flatten(overlapping(&panes));
        let drawn = forest.lines().len();

        forest.apply(Action::Move(Motion::FirstRow));
        let mut visited = vec![forest.selected_line()];
        for _ in 1..drawn {
            forest.apply(Action::Move(Motion::NextRow));
            forest.refresh(overlapping(&panes));
            visited.push(forest.selected_line());
        }

        assert_eq!(
            visited,
            (0..drawn).collect::<Vec<usize>>(),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// Where the cursor is, by the bead its line carries. A tree's header
    /// line carries its root, so this answers for a header as readily as for
    /// a bead — which is the question these tests ask, and why nothing in
    /// production may ask it this way: `tail::target` has to tell a header
    /// from a bead before it reads the key.
    fn cursor(forest: &Forest) -> Option<&BeadKey> {
        forest.lines()[forest.selected_line()].bead()
    }

    fn key(project: &str, id: &str) -> BeadKey {
        BeadKey {
            project: project.into(),
            id: id.into(),
        }
    }

    /// Depot with someone on `dep-1.1`, which is what opens its root: every
    /// other bead in it is finished, and a tree with nothing live in it rests
    /// as its header.
    fn depot() -> Snapshot {
        alone("orbital", DEPOT, &panes_on(&["dep-1.1"]))
    }

    /// One project's tree, joined against its own rows so that a pane the
    /// fixture names lands on the bead that names it. `tree_of` joins every
    /// fixture against Orbital's rows, which is what the shared snapshot
    /// needs and what leaves any other fixture's beads unstaffed.
    fn alone(project: &str, json: &str, panes: &[Pane]) -> Snapshot {
        ready_alone(project, json, panes, &[])
    }

    /// The same tree, with the beads `bd` answers `ready` with named. Every
    /// other fixture is built with an empty ready set, so a default that
    /// opens on readiness draws exactly the same screen under all of them and
    /// a green suite would say nothing about it.
    fn ready_alone(project: &str, json: &str, panes: &[Pane], ready: &[&str]) -> Snapshot {
        ready_together(project, &[json], panes, ready)
    }

    /// Several roots of one project, joined together so that a pane the
    /// fixture names lands on whichever root's bead names it.
    fn together(project: &str, jsons: &[&str], panes: &[Pane]) -> Snapshot {
        ready_together(project, jsons, panes, &[])
    }

    fn ready_together(project: &str, jsons: &[&str], panes: &[Pane], ready: &[&str]) -> Snapshot {
        let roots: Vec<Assembled> = jsons.iter().map(|json| assembled(json)).collect();
        let rows: Vec<Bead> = roots
            .iter()
            .flat_map(|root| root.beads.iter().cloned())
            .collect();
        let cfg = cfg();
        let joined = join::resolve(
            &[ProjectRows {
                project,
                rows: &rows,
            }],
            Listed::all(panes),
            &cfg,
        );
        let readiness = Readiness {
            ready: ready.iter().map(|id| (*id).to_string()).collect(),
            ..Readiness::default()
        };
        let trees = roots
            .iter()
            .map(|root| {
                build_tree(
                    project,
                    root,
                    &joined,
                    &readiness,
                    &BTreeMap::new(),
                    ProviderState::Answering,
                    &cfg,
                    now(),
                )
            })
            .collect();
        snapshot::build(
            Collected {
                trees,
                failed_projects: Vec::new(),
                read_at: every_project_read(),
            },
            panes,
            &joined,
            &cfg,
            a_provider(ProviderState::Answering),
            Filter::All,
            now(),
        )
    }

    /// Put the selection on the first elided run, by moving down to it. It
    /// carries no bead, so `select` cannot reach it.
    fn select_run(forest: &mut Forest) {
        forest.apply(Action::Move(Motion::FirstRow));
        walk::until(
            forest,
            |forest| {
                matches!(
                    forest.lines()[forest.selected_line()].content,
                    Content::Elided { .. }
                )
            },
            |forest| {
                forest.apply(Action::Move(Motion::NextRow));
            },
            |_| "no elided run is reachable by moving down".to_string(),
        );
    }

    fn select(forest: &mut Forest, bead: &BeadKey) {
        forest.apply(Action::Move(Motion::FirstRow));
        walk::until(
            forest,
            |forest| cursor(forest) == Some(bead),
            |forest| {
                forest.apply(Action::Move(Motion::NextRow));
            },
            |_| format!("{bead:?} is not reachable by moving down"),
        );
    }

    #[test]
    fn a_snapshot_flattens_to_the_lines_the_design_draws() {
        let forest = flatten(snapshot());

        assert_eq!(
            sketch(&forest),
            vec![
                "▾ orbital",
                "  ├── ◐ orb-7 lift the ground station",
                "  │   ├── ! Dangling(1)",
                "  │   ├─▸ ○ .1 re-point the dish",
                "  │   ├── ○ .7 log the survey marks",
                "  │   ├── ✓ .4 clear the access road",
                "  │   └─▸ … 3 more",
                "  └── [Unattributed orbital] 2",
                "      ├── - Loose(LoosePane { pane: PaneKey { session: \"default\", id: \"w:p3\" }, project: \"orbital\", cwd: \"/srv/work/orbital\", pane_status: Working, display_agent: Some(\"orb-7.1\"), title: None, claim_refused: true })",
                "      └── - Loose(LoosePane { pane: PaneKey { session: \"default\", id: \"w:p4\" }, project: \"orbital\", cwd: \"/srv/work/orbital\", pane_status: Idle, display_agent: Some(\"orb-7.1\"), title: None, claim_refused: true })",
                "▾ ferry",
                "  ├── ⚠ fer-2 unread",
                "  └── [Unattributed ferry] 1",
                "      └── - Loose(LoosePane { pane: PaneKey { session: \"default\", id: \"w:p9\" }, project: \"ferry\", cwd: \"/srv/work/ferry\", pane_status: Blocked, display_agent: None, title: None, claim_refused: false })",
                "▾ harbour",
                "  └─▸ [HiddenTrees harbour] 1",
                "▸ [FailedProjects] 1",
                "▾ [Unconfigured] 1",
                "  └── - Unconfigured(UnconfiguredPane { pane: PaneKey { session: \"default\", id: \"w:pF\" }, cwd: \"/srv/spike\", pane_status: Idle })",
                "▾ [Conflicts] 1",
                "  └── - Conflict(SeveralPanesNameOneBead { bead: BeadKey { project: \"orbital\", id: \"orb-7.1\" }, panes: [PaneKey { session: \"default\", id: \"w:p3\" }, PaneKey { session: \"default\", id: \"w:p4\" }] })",
            ]
        );
    }

    /// The selection starts on the first root and not on the project line
    /// above it: a project has no pane, so opening there would spend the tail
    /// band saying there is nothing to show.
    #[test]
    fn the_selection_starts_on_the_first_root() {
        let forest = flatten(snapshot());

        assert_eq!(forest.selected_line(), 1);
        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7")));
    }

    /// The fold state is the user's and the live work's, and moving is
    /// neither: walking out of a tree leaves it exactly as it was drawn.
    #[test]
    fn a_root_stays_as_it_was_when_the_selection_walks_out_of_it() {
        let mut forest = flatten(snapshot());
        let was = sketch(&forest);

        forest.apply(Action::Move(Motion::LastRow));

        assert_eq!(sketch(&forest), was);
    }

    /// Compared on content alone: folding also redraws the header's marker
    /// and the elbow on what is now the last line under it, and neither of
    /// those is a line the fold removed.
    #[test]
    fn folding_a_root_removes_exactly_its_subtree() {
        let mut forest = flatten(snapshot());
        let before = contents(&forest);

        assert!(forest.apply(Action::ToggleFold));

        let after = contents(&forest);
        let gone: Vec<&String> = before.iter().filter(|said| !after.contains(said)).collect();

        assert_eq!(
            gone,
            vec![
                "○ .1 re-point the dish",
                "○ .7 log the survey marks",
                "✓ .4 clear the access road",
                "… 3 more",
            ]
        );
    }

    fn contents(forest: &Forest) -> Vec<String> {
        forest
            .lines()
            .iter()
            .map(|line| said(&line.content))
            .collect()
    }

    /// Folding is where a finding is easiest to lose, so a folded tree keeps
    /// every one of them.
    #[test]
    fn a_trees_findings_are_drawn_whether_it_is_folded_or_not() {
        let mut forest = flatten(snapshot());
        forest.apply(Action::ToggleFold);

        assert_eq!(
            sketch(&forest)[..3],
            [
                "▾ orbital",
                "  ├─▸ ◐ orb-7 lift the ground station",
                "  │   └── ! Dangling(1)",
            ]
        );
    }

    #[test]
    fn a_fold_made_by_hand_outlives_moving_away_from_it() {
        let mut forest = flatten(snapshot());
        forest.apply(Action::ToggleFold);
        forest.apply(Action::Move(Motion::LastRow));
        forest.apply(Action::Move(Motion::FirstRow));

        assert!(
            !sketch(&forest).iter().any(|line| line.contains(".1.1")),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// A working pane in Orbital on each of `on`. Each pane names its bead,
    /// which is how a bead carrying no configured key gets its agent, so a
    /// fixture is staffed by naming the beads someone is on.
    fn panes_on(on: &[&str]) -> Vec<Pane> {
        let agents: Vec<String> = on
            .iter()
            .map(|id| {
                format!(
                    r#"{{"pane_id":"w:{id}","cwd":"/srv/work/orbital",
                       "agent_status":"working","display_agent":"{id}"}}"#
                )
            })
            .collect();
        parse_agent_list(
            A_SESSION,
            &format!(r#"{{"result":{{"agents":[{}]}}}}"#, agents.join(",")),
        )
        .expect("the panes parse")
    }

    fn tower_staffed(on: &[&str]) -> Snapshot {
        alone("orbital", TOWER, &panes_on(on))
    }

    /// The same tree with nobody on it and the named beads ready, so the two
    /// halves of the fold default can be asked the same question.
    fn tower_ready(on: &[&str]) -> Snapshot {
        ready_alone("orbital", TOWER, &[], on)
    }

    /// Two of one project's trees in one snapshot, joined against both so a
    /// pane naming a bead reaches it whichever tree draws it. `alone` takes a
    /// single tree, and the overlap these tests are about needs two.
    fn overlapping(panes: &[Pane]) -> Snapshot {
        let cfg = cfg();
        let quarry = assembled(QUARRY);
        let wharf = assembled(WHARF);
        let mut rows = quarry.beads.clone();
        rows.extend(wharf.beads.clone());
        let joined = join::resolve(
            &[ProjectRows {
                project: "orbital",
                rows: &rows,
            }],
            Listed::all(panes),
            &cfg,
        );
        let tree = |rows: &Assembled| {
            build_tree(
                "orbital",
                rows,
                &joined,
                &Readiness::default(),
                &BTreeMap::new(),
                ProviderState::Answering,
                &cfg,
                now(),
            )
        };
        snapshot::build(
            Collected {
                trees: vec![tree(&quarry), tree(&wharf)],
                failed_projects: Vec::new(),
                read_at: every_project_read(),
            },
            panes,
            &joined,
            &cfg,
            a_provider(ProviderState::Answering),
            Filter::All,
            now(),
        )
    }

    /// Open one node by hand, the way a user reaching past the default does.
    fn open(forest: &mut Forest, bead: &BeadKey) {
        select(forest, bead);
        if fold_of(forest, &bead.id) == Some(false) {
            forest.apply(Action::ToggleFold);
        }
    }

    /// Whether the line for one bead is open, shut, or has no fold at all.
    fn fold_of(forest: &Forest, id: &str) -> Option<bool> {
        forest
            .lines()
            .iter()
            .find(|line| line.bead().is_some_and(|key| key.id == id))
            .unwrap_or_else(|| panic!("{id} is not drawn"))
            .folded
    }

    /// The default the bead is about: the first screen is the work a reader
    /// needs next and the path down to it. Four quiet forebears open because
    /// of one bead at the bottom; the branch beside them, holding neither an
    /// agent nor ready work, stays shut.
    ///
    /// Two kinds of bead earn that opening and no third does. An agent on one
    /// says the work is happening; `bd` calling one ready says it can start.
    /// Both are asked of the same tree here, because the claim is that the
    /// screen cannot tell them apart — and either way the bead that earned
    /// the fold does not open its own, and the unfinished work `bd` will not
    /// start is still folded away.
    #[test]
    fn the_default_opens_every_forebear_of_a_live_agent_or_of_ready_work_and_nothing_else() {
        let opened = vec![
            "▾ orbital",
            "  └── ○ tow-1 raise the tower",
            "      ├── ○ .1 stand the mast",
            "      │   └── ○ .1 bolt the sections",
            "      │       └── ○ .1 dress the cables",
            "      └─▸ ○ .2 pour the base",
        ];

        let staffed = flatten(tower_staffed(&["tow-1.1.1.1"]));
        let ready = flatten(tower_ready(&["tow-1.1.1.1"]));

        assert_eq!(sketch(&staffed), opened);
        assert_eq!(sketch(&ready), opened);
        for forest in [&staffed, &ready] {
            for forebear in ["tow-1", "tow-1.1", "tow-1.1.1"] {
                assert_eq!(fold_of(forest, forebear), Some(true), "{forebear} is shut");
            }
            assert_eq!(fold_of(forest, "tow-1.2"), Some(false));
        }
    }

    /// The third case, and the one a claim makes: a seat has taken the bead
    /// and no pane has joined it yet. `bd ready` drops a bead the moment it
    /// goes `in_progress`, so nothing here is ready and nobody is staffed,
    /// and the forebears open anyway.
    ///
    /// They open on the anomaly. A claim with no pane behind it is an
    /// `orphan-claim` from the first collection, and that is what `quiet`
    /// answers to — so the rule keeping a booting seat's bead on screen lives
    /// in `model/anomaly.rs`, not in this file. Narrow that rule and this
    /// goes red, which is the whole reason it is written down here.
    #[test]
    fn the_default_opens_every_forebear_of_a_bead_someone_has_claimed() {
        let claimed = edited(
            TOWER,
            r#"{"id":"tow-1.1.1.1","title":"dress the cables","status":"open","#,
            r#"{"id":"tow-1.1.1.1","title":"dress the cables","status":"in_progress",
       "updated_at":"2026-08-30T11:00:00Z","#,
        );
        let forest = flatten(ready_alone("orbital", &claimed, &[], &[]));

        assert_eq!(
            sketch(&forest),
            vec![
                "▾ orbital",
                "  └── ○ tow-1 raise the tower",
                "      ├── ○ .1 stand the mast",
                "      │   └── ○ .1 bolt the sections",
                "      │       └── ◐ .1 dress the cables",
                "      └─▸ ○ .2 pour the base",
            ]
        );
        for forebear in ["tow-1", "tow-1.1", "tow-1.1.1"] {
            assert_eq!(fold_of(&forest, forebear), Some(true), "{forebear} is shut");
        }
    }

    /// The other half of the same rule. A tree nobody is working holds no
    /// spine to open, so it rests as the one line saying it is there.
    #[test]
    fn a_tree_with_nothing_live_in_it_rests_as_its_header() {
        let forest = flatten(tower_staffed(&[]));

        assert_eq!(
            sketch(&forest),
            vec!["▾ orbital", "  └─▸ ○ tow-1 raise the tower"]
        );
    }

    /// A default, not a lock: the user shuts a node holding an agent and it
    /// stays shut, refresh after refresh, for as long as what is under there
    /// is what they folded away.
    #[test]
    fn a_fold_set_by_hand_survives_a_refresh_that_brings_nothing_new_under_it() {
        let mut forest = flatten(tower_staffed(&["tow-1.1.1.1"]));
        select(&mut forest, &key("orbital", "tow-1.1"));
        forest.apply(Action::ToggleFold);

        forest.refresh(tower_staffed(&["tow-1.1.1.1"]));

        assert_eq!(fold_of(&forest, "tow-1.1"), Some(false));
        assert!(
            !sketch(&forest).iter().any(|line| line.contains(".1.1")),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// Work dying down is not news, so it re-opens nothing the user shut.
    /// The agent moves to the other branch, which is what keeps the tree
    /// open for the shut one to still be drawn under.
    #[test]
    fn a_fold_set_by_hand_outlives_the_work_it_was_shut_over_going_away() {
        let mut forest = flatten(tower_staffed(&["tow-1.1.1.1"]));
        select(&mut forest, &key("orbital", "tow-1.1"));
        forest.apply(Action::ToggleFold);

        forest.refresh(tower_staffed(&["tow-1.2.1"]));

        assert_eq!(fold_of(&forest, "tow-1.1"), Some(false));
    }

    /// The hard half. A fold says *I have seen what is under here and do not
    /// want it*, which stops being true the moment something new is under it,
    /// so an agent arriving on a bead the user never folded away hands the
    /// node back to the default.
    #[test]
    fn a_fold_set_by_hand_is_spent_when_live_work_arrives_beneath_it() {
        let mut forest = flatten(tower_staffed(&["tow-1.1.1.1"]));
        select(&mut forest, &key("orbital", "tow-1.1"));
        forest.apply(Action::ToggleFold);

        forest.refresh(tower_staffed(&["tow-1.1.1.1", "tow-1.1.1"]));

        assert_eq!(fold_of(&forest, "tow-1.1"), Some(true));
        assert!(
            sketch(&forest)
                .iter()
                .any(|line| line.contains(".1 dress the cables")),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// The default reads the agents, not which trees are drawn, so dropping
    /// the filter adds trees below and changes no fold above.
    #[test]
    fn dropping_the_filter_leaves_the_default_fold_state_alone() {
        let mut forest = flatten(snapshot());
        let staffed: Vec<String> = sketch(&forest)
            .into_iter()
            .take_while(|line| !line.contains("ferry"))
            .collect();

        forest.apply(Action::ToggleFilter);

        assert_eq!(sketch(&forest)[..staffed.len()], staffed[..]);
    }

    /// A group over live panes is a fold `bdi` chose, and a count is not a
    /// view of what it holds: it says they exist and nothing about which they
    /// are. What collection and the filter did is a report, and rests shut.
    /// In the order the groups are drawn: orbital's and ferry's loose panes,
    /// harbour's hidden tree, then the failed project, the unconfigured pane
    /// and the conflict below the trees.
    #[test]
    fn a_group_rests_open_when_what_it_holds_is_live() {
        let forest = flatten(snapshot());
        let markers: Vec<&str> = forest
            .lines()
            .iter()
            .filter_map(|line| match &line.content {
                Content::Group(_) => Some(marker(line.folded == Some(true))),
                _ => None,
            })
            .collect();

        assert_eq!(markers, vec![OPEN, OPEN, SHUT, SHUT, OPEN, OPEN]);
    }

    #[test]
    fn a_run_of_quiet_closed_siblings_collapses_to_a_count() {
        let forest = flatten(snapshot());

        assert!(sketch(&forest).contains(&"  │   └─▸ … 3 more".to_string()));
    }

    /// The count is the only account the screen gives of the beads it stands
    /// for, so the line has to be reachable to be worth anything.
    #[test]
    fn an_elided_run_can_hold_the_selection() {
        let mut forest = flatten(snapshot());

        select_run(&mut forest);

        assert_eq!(
            sketch(&forest)[forest.selected_line()],
            "  │   └─▸ … 3 more"
        );
    }

    #[test]
    fn opening_an_elided_run_draws_the_beads_it_counted() {
        let mut forest = flatten(snapshot());
        select_run(&mut forest);

        forest.apply(Action::ToggleFold);

        let drawn = sketch(&forest);
        let from_the_run: Vec<&String> = drawn
            .iter()
            .skip_while(|line| !line.contains("… 3 more"))
            .collect();

        assert_eq!(
            from_the_run[..4],
            [
                "  │   └── … 3 more",
                "  │       ├── ✓ .2 survey the mast",
                "  │       ├── ✓ .3 pour the pad",
                "  │       └── ✓ .5 set the guard rail",
            ]
        );
    }

    #[test]
    fn shutting_an_open_elided_run_puts_the_count_back() {
        let mut forest = flatten(snapshot());
        let was = sketch(&forest);
        select_run(&mut forest);

        forest.apply(Action::ExpandOrChild);
        forest.apply(Action::CollapseOrParent);

        assert_eq!(sketch(&forest), was);
    }

    /// A line that stands for more than itself says how much of that is done,
    /// which is the question a root's `35/51` answers — asked here one level
    /// down. `orb-7.1` is open and holds two open children, so its subtree is
    /// three beads with none of them closed.
    ///
    /// Counted including the bead's own line, because that is what a root
    /// already does: `snapshot` sets `total` to `nodes.len()`, and the root is
    /// one of those nodes. One rule at every depth.
    #[test]
    fn a_bead_with_children_says_how_much_of_its_own_subtree_is_done() {
        let forest = flatten(snapshot());

        assert_eq!(
            row_of(&forest, "orb-7.1").progress,
            Some(Progress {
                closed: 0,
                total: 3
            })
        );
    }

    /// Both halves of the fraction have to count. `dep-1.2` is closed with two
    /// closed beads under it, so a subtree that is finished says so — an epic
    /// stuck at `0/3` whatever its children did would be worse than no count.
    #[test]
    fn a_finished_subtree_counts_its_closed_beads_and_not_only_its_size() {
        let tree = tree_of("orbital", DEPOT);
        let (at, above) = way_to(&tree, "dep-1.2");

        assert_eq!(
            progress_of(&tree, at, &above),
            Some(Progress {
                closed: 4,
                total: 4
            })
        );
    }

    /// A fraction says how much of what a bead is waiting on is done, and
    /// that is a count of beads. A blocker two of its descendants share is one
    /// piece of work whether it is drawn once or twice.
    #[test]
    fn a_fraction_counts_beads_rather_than_the_rows_they_are_drawn_on() {
        const SHARED: &str = r#"[
          {"id":"shr-1","title":"root","status":"open"},
          {"id":"shr-1.1","title":"one","status":"open",
           "dependencies":[{"depends_on_id":"shr-1","type":"parent-child"},
                           {"depends_on_id":"shr-1.9","type":"blocks"}]},
          {"id":"shr-1.2","title":"two","status":"open",
           "dependencies":[{"depends_on_id":"shr-1","type":"parent-child"},
                           {"depends_on_id":"shr-1.9","type":"blocks"}]},
          {"id":"shr-1.9","title":"what both wait on","status":"closed",
           "dependencies":[{"depends_on_id":"shr-1","type":"parent-child"}]}
        ]"#;
        let tree = tree_of("orbital", SHARED);

        assert_eq!(
            progress_of(&tree, 0, &[]),
            Some(Progress {
                closed: 1,
                total: 4
            })
        );
    }

    /// A closed bead's descendants are what had to finish before it, so beads
    /// that merely waited on it are not among them and cannot be counted into
    /// its fraction.
    #[test]
    fn a_closed_blocker_reports_no_fraction_over_the_beads_that_waited_on_it() {
        const WAITED: &str = r#"[
          {"id":"wtd-1","title":"root","status":"open"},
          {"id":"wtd-1.1","title":"waiting","status":"open",
           "dependencies":[{"depends_on_id":"wtd-1","type":"parent-child"},
                           {"depends_on_id":"wtd-1.9","type":"blocks"}]},
          {"id":"wtd-1.9","title":"done","status":"closed",
           "dependencies":[{"depends_on_id":"wtd-1","type":"parent-child"}]}
        ]"#;
        let tree = tree_of("orbital", WAITED);
        let (at, above) = way_to(&tree, "wtd-1.9");

        assert_eq!(progress_of(&tree, at, &above), None);
    }

    /// A leaf stands for itself alone, so there is nothing to be part-way
    /// through and a fraction over one bead would only repeat its glyph.
    #[test]
    fn a_bead_with_no_children_has_no_progress_to_report() {
        let forest = flatten(snapshot());

        assert_eq!(row_of(&forest, "orb-7.7").progress, None);
    }

    /// Everything a line says of the tree beneath it — how far along it is,
    /// what it is shut over, whether it rests open, what a run stands for —
    /// depends on the snapshot alone. So it is answered once, when the forest
    /// takes the snapshot, and a keystroke asks nothing of the tree.
    #[test]
    fn a_keystroke_walks_no_subtree() {
        let mut forest = flatten(built(Filter::All));
        assert!(
            forest
                .lines()
                .iter()
                .any(|line| matches!(line.content, Content::Elided { .. })),
            "the fixture draws no run, so a keystroke had no run to size"
        );
        let before = walks_on_this_thread();

        forest.apply(Action::Move(Motion::NextRow));

        assert_eq!(walks_on_this_thread() - before, 0);
    }

    /// `cyc-1.1` hangs under `cyc-1` and is blocked by it, so the walk comes
    /// back to `cyc-1` beneath `cyc-1.1` and cuts the loop there.
    const LOOPED: &str = r#"[
      {"id":"cyc-1","title":"root","status":"open"},
      {"id":"cyc-1.1","title":"one","status":"open",
       "dependencies":[{"depends_on_id":"cyc-1","type":"parent-child"},
                       {"depends_on_id":"cyc-1","type":"blocks"}]},
      {"id":"cyc-1.2","title":"two","status":"closed",
       "dependencies":[{"depends_on_id":"cyc-1.1","type":"parent-child"}]}
    ]"#;

    /// What `cyc-1.1` stands over is `cyc-1.2` alone: its forebear is above
    /// it, not beneath, and only the way down to it can say so. A bead the
    /// tree holds once can be answered once only where no way down is cut.
    #[test]
    fn a_bead_on_a_loop_counts_what_the_way_down_leaves_beneath_it() {
        let forest = flatten(alone("orbital", LOOPED, &panes_on(&["cyc-1.1"])));

        assert_eq!(
            row_of(&forest, "cyc-1.1").progress,
            Some(Progress {
                closed: 1,
                total: 2
            })
        );
    }

    /// Where no loop is cut, nothing beneath a bead can be above it, so the
    /// way down changes no answer and every copy of a bead gets the one the
    /// tree keeps for it.
    #[test]
    fn where_no_loop_is_cut_every_way_down_to_a_bead_gets_the_same_answer() {
        let fixtures = [
            ORBITAL,
            DEPOT,
            RELAY,
            SIDING,
            TOWER,
            BEACON,
            SLUICE,
            TWICE,
            CLOSED_TWICE,
            SHARED_IN_A_RUN,
        ];
        let staffed = panes_on(&[
            "orb-7.1", "dep-1.1", "rly-2.1", "sdg-4.3", "tow-1.1", "bcn-6", "slu-1.1",
        ]);
        for json in fixtures {
            let tree = alone("orbital", json, &staffed).collected.remove(0);
            assert!(tree.cycles.is_empty(), "{} has a loop", tree.root);
            let facts = TreeFacts::of(&tree);

            for (at, above) in every_way_down(&tree) {
                assert_eq!(
                    facts.bead(&tree, at, &above),
                    facts_of(&tree, at, &above),
                    "{} reached by {above:?}",
                    tree.beads[at].id
                );
            }
        }
    }

    /// Every way down the walk takes, as the bead it lands on and the beads
    /// above it.
    fn every_way_down(tree: &Tree) -> Vec<(usize, Vec<usize>)> {
        let mut ways = Vec::new();
        let mut going = vec![(0, Vec::new())];
        while let Some((at, above)) = going.pop() {
            let below = way_below(&above, at);
            going.extend(
                links_below(tree, at, &above)
                    .into_iter()
                    .map(|link| (link.bead, below.clone())),
            );
            ways.push((at, above));
        }
        ways
    }

    /// A run is drawn with one status glyph standing for every bead it hides,
    /// which is only honest while a run is closed beads and nothing else.
    /// `dep-1.1` is open beside the two closed siblings that make the run, so
    /// widening the predicate sweeps it in and fails here — rather than
    /// leaving the glyph to say `closed` over a bead that is not.
    #[test]
    fn a_run_holds_closed_beads_and_nothing_else_which_is_what_lets_one_glyph_stand_for_it() {
        let tree = tree_of("orbital", DEPOT);

        let mut runs = 0;
        for at in 0..tree.beads.len() {
            let (_, run) = split(&tree, at, &above(&tree, at));
            runs += usize::from(!run.is_empty());
            for member in run {
                let bead = &tree.beads[member.bead];
                assert!(
                    bead.status.is_closed(),
                    "{} is in a run and is {:?}",
                    bead.id,
                    bead.status
                );
            }
        }

        assert!(runs > 0, "the fixture built no run to check");
    }

    /// The run rule is a property of the forest, not of a place in it, so it
    /// holds inside an open run as it does everywhere else. Nothing
    /// disappears; it is counted one level down. Two folds to reach it now:
    /// the run, and then the finished branch that rests shut inside it.
    #[test]
    fn an_open_run_elides_again_inside_itself() {
        let mut forest = flatten(depot());
        select_run(&mut forest);
        forest.apply(Action::ToggleFold);

        select(&mut forest, &key("orbital", "dep-1.2"));
        forest.apply(Action::ToggleFold);

        assert_eq!(
            sketch(&forest)[..7],
            [
                "▾ orbital",
                "  └── ◐ dep-1 re-lay the sidings",
                "      ├── ○ .1 grade the bed",
                "      └── … 6 more",
                "          ├── ✓ .2 lift the old rail",
                "          │   └─▸ … 3 more",
                "          ├── ✓ .3 clear the ballast",
            ]
        );
    }

    /// A run is a fold like any other, so a collection that lands under an
    /// open one leaves it open and leaves the cursor on it.
    #[test]
    fn an_open_elided_run_survives_a_refresh() {
        let mut forest = flatten(snapshot());
        select_run(&mut forest);
        forest.apply(Action::ToggleFold);

        let reordered = edited(ORBITAL, r#""priority":3"#, r#""priority":1"#);
        forest.refresh(gather(
            vec![tree_of("orbital", &reordered)],
            Vec::new(),
            Filter::LiveAgents,
        ));

        let drawn = sketch(&forest);
        assert!(
            drawn.contains(&"  │       └── ✓ .5 set the guard rail".to_string()),
            "{drawn:#?}"
        );
        assert_eq!(drawn[forest.selected_line()], "  │   └── … 3 more");
    }

    /// A run has no bead of its own, so a line the cursor is holding must not
    /// report one: the loop picks the tail's pane from that field.
    #[test]
    fn a_selected_elided_run_stands_for_no_bead_of_its_own() {
        let mut forest = flatten(snapshot());

        select_run(&mut forest);

        let line = &forest.lines()[forest.selected_line()];
        assert!(matches!(line.content, Content::Elided { .. }));
        assert_eq!(line.bead(), None);
    }

    /// A closed bead with a pane still on it is the stale-pane anomaly, and
    /// eliding it would hide a live agent.
    #[test]
    fn a_closed_bead_with_a_live_agent_is_drawn_rather_than_elided() {
        let forest = flatten(snapshot());

        assert!(sketch(&forest)
            .iter()
            .any(|line| line.contains("clear the access road")));
    }

    #[test]
    fn a_single_quiet_closed_sibling_is_drawn_rather_than_said_as_a_count() {
        let one_closed = edited(
            ORBITAL,
            r#"{"id":"orb-7.3","title":"pour the pad","status":"closed"#,
            r#"{"id":"orb-7.3","title":"pour the pad","status":"open"#,
        );
        let snapshot = gather(
            vec![tree_of("orbital", &one_closed)],
            Vec::new(),
            Filter::LiveAgents,
        );

        let drawn = sketch(&flatten(snapshot));

        assert!(
            drawn.iter().any(|line| line.contains("survey the mast")),
            "{drawn:#?}"
        );
        assert!(
            !drawn.iter().any(|line| line.contains("more")),
            "{drawn:#?}"
        );
    }

    /// The invariant this bead exists to restore: nothing `bdi` folds of its
    /// own accord closes over a live agent or over an anomaly. Asked of the
    /// forest at rest, before any fold is set by hand, because that is the
    /// only state `bdi` chooses for itself.
    #[test]
    fn nothing_the_forest_folds_by_itself_hides_a_live_agent_or_an_anomaly() {
        let mut worth_drawing = 0;
        for json in [ORBITAL, DEPOT, RELAY] {
            let snapshot = alone("orbital", json, &two_panes());
            let forest = flatten(snapshot.clone());
            let drawn: Vec<&str> = forest
                .lines()
                .iter()
                .filter_map(|line| line.bead().map(|key| key.id.as_str()))
                .collect();

            for node in &snapshot.trees[0].beads {
                if node.agent.is_none() && node.anomalies.is_empty() {
                    continue;
                }
                worth_drawing += 1;
                assert!(
                    drawn.contains(&node.id.as_str()),
                    "{} carries an agent or an anomaly and is not on screen: {:#?}",
                    node.id,
                    sketch(&forest)
                );
            }
        }

        assert!(worth_drawing > 0, "the fixtures staffed nothing to check");
    }

    /// The same invariant for the half `bdi-wt0` added, asked one bead at a
    /// time so a screen that happened to be open cannot answer for a rule
    /// that is not there. Every unfinished bead in every fixture takes its
    /// turn as the only ready one, and each turn is a whole forest whose
    /// default has to reach it.
    ///
    /// Position is the point. A bead behind three closed forebears, or in the
    /// run a branch collapses to, is where a fold that opens one level would
    /// still lose it.
    #[test]
    fn nothing_the_forest_folds_by_itself_hides_work_bd_would_start() {
        let mut asked = 0;
        for json in [ORBITAL, DEPOT, RELAY, SIDING, TOWER, BEACON] {
            let unstaffed = alone("orbital", json, &[]);
            let unfinished: Vec<String> = unstaffed.trees[0]
                .beads
                .iter()
                .filter(|node| !node.status.is_closed())
                .map(|node| node.id.clone())
                .collect();

            for id in unfinished {
                asked += 1;
                let forest = flatten(ready_alone("orbital", json, &[], &[&id]));
                let drawn: Vec<&str> = forest
                    .lines()
                    .iter()
                    .filter_map(|line| line.bead().map(|key| key.id.as_str()))
                    .collect();

                assert!(
                    drawn.contains(&id.as_str()),
                    "{id} is the one bead bd would start and is not on screen: {:#?}",
                    sketch(&forest)
                );
            }
        }

        assert!(asked > 0, "the fixtures held no unfinished bead to ready");
    }

    /// The shape `bdi-4av` was raised on: a closed parent, a closed child, and
    /// a live agent under both of them. The run asked its question of the
    /// child alone, swept it in, and printed a sentence saying nobody was on
    /// the beads it had just hidden the agent among.
    #[test]
    fn a_run_never_closes_over_a_subtree_with_a_live_agent_in_it() {
        let forest = flatten(alone("orbital", RELAY, &two_panes()));

        assert_eq!(
            sketch(&forest),
            vec![
                "▾ orbital",
                "  └── ◐ rly-2 re-site the relay",
                "      ├── ○ .1 trench the run",
                "      ├── ✓ .2 strike the old mast",
                "      │   └── ✓ .1 drop the guys",
                "      │       └── ◐ .1 cut the stays",
                "      ├── ✓ .4 lift the feeder",
                "      │   └── ✓ .1 coil the heliax",
                "      └─▸ … 4 more",
            ]
        );
    }

    /// A run's phrase says nobody is on the beads it counts, so it has to be
    /// true of every bead it counts — not merely of the siblings it names.
    /// The count and the set it describes are checked together, because it was
    /// their disagreement that let the sentence lie.
    ///
    /// The set is of beads rather than of rows, so `SHARED_IN_A_RUN` is here:
    /// it is the only fixture whose run reaches one bead two ways, and under
    /// every other one the two answers are the same number.
    #[test]
    fn a_run_counts_exactly_the_beads_its_phrase_is_true_of() {
        let mut runs = 0;
        for json in [ORBITAL, DEPOT, RELAY, SHARED_IN_A_RUN] {
            let tree = alone("orbital", json, &two_panes()).trees.remove(0);

            for at in 0..tree.beads.len() {
                let above = above(&tree, at);
                let (_, run) = split(&tree, at, &above);
                if run.is_empty() {
                    continue;
                }
                runs += 1;

                let below = way_below(&above, at);
                let mut behind = BTreeSet::new();
                let mut walking: Vec<usize> = run.iter().map(|link| link.bead).collect();
                while let Some(node) = walking.pop() {
                    let bead = &tree.beads[node];
                    behind.insert(bead.id.clone());
                    assert!(
                        bead.status.is_closed()
                            && bead.agent.is_none()
                            && bead.anomalies.is_empty(),
                        "{} is behind a run that says nobody is on it",
                        bead.id
                    );
                    walking.extend(
                        tree::links_from(&tree.children, node, &below)
                            .into_iter()
                            .map(|link| link.bead),
                    );
                }

                assert_eq!(run_size(&tree, &run, &below), behind.len());
            }
        }

        assert!(runs > 0, "the fixtures built no run to check");
    }

    /// A run says how many beads it holds, and a blocker two of its branches
    /// share is one bead however many ways down there are to it. The count
    /// stands in for beads that are not on the screen, so counting the rows
    /// it saved would say the run holds work that does not exist.
    ///
    /// `SHARED_IN_A_RUN` draws five beads on six rows, and the expected
    /// number is written out here rather than walked, because a count taken
    /// from the tree the count is about cannot disagree with it.
    #[test]
    fn a_run_counts_a_blocker_two_of_its_branches_share_once() {
        let forest = flatten(alone("orbital", SHARED_IN_A_RUN, &[]));

        assert_eq!(
            sketch(&forest),
            vec![
                "▾ orbital",
                "  └── ◐ lck-1 refit the lock gates",
                "      ├── ◐ .5 hang the new gates",
                "      └─▸ … 5 more",
            ]
        );
    }

    /// A branch that is finished all the way down is one line saying so: the
    /// glyph is its own closed status, the fraction says every bead beneath it
    /// is closed too, and the shut marker says it still holds them.
    #[test]
    fn a_wholly_finished_subtree_rests_as_one_line_that_says_it_is_finished() {
        let forest = flatten(finished_branches());

        assert_eq!(
            sketch(&forest),
            vec![
                "▾ orbital",
                "  └── ◐ dep-1 re-lay the sidings",
                "      ├── ○ .1 grade the bed",
                "      ├── ○ .3 clear the ballast",
                "      ├─▸ ✓ .2 lift the old rail",
                "      └── ✓ .4 burn the sleepers",
            ]
        );
        assert_eq!(
            row_of(&forest, "dep-1.2").progress,
            Some(Progress {
                closed: 4,
                total: 4
            })
        );
    }

    /// A blocker is drawn beneath the bead it blocks, so a bead's children
    /// are the work closing it unblocked. A closed bead standing over open ones is
    /// therefore the healthy shape of this tree, and where nobody is on them
    /// and `bd` will start none of them the branch rests shut under a row
    /// whose glyph says done. What it holds is out of sight either way, so
    /// the line says how much.
    #[test]
    fn a_closed_branch_resting_over_unfinished_work_says_how_much_it_holds() {
        let forest = flatten(siding());

        assert_eq!(
            sketch(&forest),
            vec![
                "▾ orbital",
                "  └── ◐ sdg-4 re-point the crossover",
                "      ├─▸ ◐ .3 re-signal the box",
                "      ├─▸ ✓ .1 slew the up line",
                "      └─▸ ✓ .2 clip the down line",
            ]
        );
        assert_eq!(
            row_of(&forest, "sdg-4.1").notes,
            vec![phrase::unfinished_beneath(3)]
        );
    }

    /// The common case, and the reason the sentence is not on every closed
    /// row: a branch that is done all the way down has nothing further to
    /// say, and a count on it would be noise wherever the eye landed.
    #[test]
    fn a_closed_branch_that_is_finished_all_the_way_down_says_nothing_extra() {
        let forest = flatten(siding());

        assert_eq!(row_of(&forest, "sdg-4.2").notes, Vec::<String>::new());
    }

    /// Asked of the branch, not of the bead: `sdg-4.3` is unfinished itself
    /// and holds one unfinished bead, and a walk that counted the bead it was
    /// asked about would say two. Only closed nodes reach the note from the
    /// renderer, where a self that is closed adds nothing and the difference
    /// cannot show — but the same walk answers the agent count, which every
    /// shut line asks whatever its own status is.
    #[test]
    fn what_a_branch_holds_never_counts_the_bead_it_was_asked_about() {
        let tree = tree_of("orbital", SIDING);
        let (at, above) = way_to(&tree, "sdg-4.3");

        assert_eq!(counts_beneath(&tree, at, &above).unfinished(), 1);
    }

    /// Only a line whose own glyph says done. An unfinished bead resting shut
    /// over unfinished work is not hiding anything its status did not already
    /// admit, and a sentence on every such row is the noise that would stop
    /// the closed ones being read.
    #[test]
    fn an_unfinished_branch_resting_shut_over_its_own_work_says_nothing_extra() {
        let forest = flatten(siding());

        assert_eq!(row_of(&forest, "sdg-4.3").notes, Vec::<String>::new());
    }

    /// Counted at every depth. With the open bead directly under `sdg-4.1`
    /// closed, everything unfinished is two levels down, and a count of the
    /// immediate children would leave the row silent over both of them.
    #[test]
    fn unfinished_work_two_levels_under_a_closed_branch_is_still_counted() {
        let deep = edited(
            SIDING,
            r#""status":"open",
       "dependencies":[{"depends_on_id":"sdg-4.1","type":"parent-child"}]"#,
            r#""status":"closed","closed_at":"2026-08-26T09:00:00Z",
       "dependencies":[{"depends_on_id":"sdg-4.1","type":"parent-child"}]"#,
        );
        let forest = flatten(alone("orbital", &deep, &panes_on(&["sdg-4.3"])));

        assert_eq!(
            row_of(&forest, "sdg-4.1").notes,
            vec![phrase::unfinished_beneath(2)]
        );
    }

    /// The sentence and the fraction are two readings of one walk, so they
    /// can never disagree: a row saying `2/5` and `3 unfinished beads` is the
    /// same fact twice, once as arithmetic and once in words.
    #[test]
    fn the_count_a_closed_branch_gives_is_the_remainder_of_its_own_fraction() {
        let forest = flatten(siding());
        let row = row_of(&forest, "sdg-4.1");
        let progress = row.progress.expect("a branch has a fraction");

        assert_eq!(
            row.notes,
            vec![phrase::unfinished_beneath(progress.total - progress.closed)]
        );
    }

    /// Opened, the beads are on screen and counting them again above would be
    /// noise. The sentence is what the shut line is hiding, not a standing
    /// property of the bead.
    #[test]
    fn a_closed_branch_opened_over_its_work_stops_counting_it() {
        let mut forest = flatten(siding());
        select(&mut forest, &key("orbital", "sdg-4.1"));

        forest.apply(Action::ToggleFold);

        assert_eq!(row_of(&forest, "sdg-4.1").notes, Vec::<String>::new());
    }

    // ---- what a fold hides -----------------------------------------------

    /// The bead this is for. A row shut over a branch is the only thing on
    /// the screen standing for it, and until now it said its own fraction
    /// and its own agent and nothing about the seats inside it.
    ///
    /// A fold `bdi` set itself never closes over an agent, so the row that
    /// needs this is one the reader shut by hand — which is exactly when
    /// they have stopped looking at the branch and most need to be told
    /// somebody is still in it.
    #[test]
    fn a_branch_shut_over_a_working_agent_says_how_many_are_inside_it() {
        let mut forest = flatten(alone("orbital", SIDING, &panes_on(&["sdg-4.3.1"])));
        select(&mut forest, &key("orbital", "sdg-4.3"));

        forest.apply(Action::ToggleFold);

        assert_eq!(fold_of(&forest, "sdg-4.3"), Some(false));
        assert_eq!(
            row_of(&forest, "sdg-4.3")
                .shut_over
                .as_ref()
                .map(|c| c.live_agents),
            Some(1)
        );
    }

    /// One rule at every depth, which is the principle the bead is about. A
    /// root is a bead row like any other since `bdi-2bb.25`, and the aggregate
    /// it lost went to the project line and widened over every root there. So
    /// the root asks the same question a branch three levels down asks, and
    /// gets the same answer about its own tree.
    #[test]
    fn a_root_shut_over_a_working_agent_says_it_exactly_as_a_branch_does() {
        let mut forest = flatten(alone("orbital", SIDING, &panes_on(&["sdg-4.3.1"])));
        select(&mut forest, &key("orbital", "sdg-4"));

        forest.apply(Action::ToggleFold);

        assert_eq!(fold_of(&forest, "sdg-4"), Some(false));
        assert_eq!(
            row_of(&forest, "sdg-4")
                .shut_over
                .as_ref()
                .map(|c| c.live_agents),
            Some(1)
        );
    }

    /// Opened, the seats are on their own rows and counting them again above
    /// would be the same fact twice. What a line says here is what it is
    /// hiding, not a standing property of the bead.
    #[test]
    fn a_branch_opened_over_its_agents_stops_counting_them() {
        let forest = flatten(alone("orbital", SIDING, &panes_on(&["sdg-4.3.1"])));

        assert_eq!(fold_of(&forest, "sdg-4.3"), Some(true));
        assert_eq!(row_of(&forest, "sdg-4.3").shut_over, None);
    }

    /// Counted over what the fold hides and not over the bead asking. The
    /// row already says its own agent by name, and a count taking that one in
    /// would have a reader add the name to the number and come out with one
    /// agent too many.
    #[test]
    fn the_agents_a_line_counts_are_the_ones_it_hides_and_never_its_own() {
        let mut forest = flatten(alone(
            "orbital",
            SIDING,
            &panes_on(&["sdg-4.3", "sdg-4.3.1"]),
        ));
        select(&mut forest, &key("orbital", "sdg-4.3"));

        forest.apply(Action::ToggleFold);

        let row = row_of(&forest, "sdg-4.3");
        assert!(row.agent.is_some(), "the row names its own agent");
        assert_eq!(row.shut_over.as_ref().map(|c| c.live_agents), Some(1));
    }

    /// The other half of what a fold hides, and the reason it is not agents
    /// alone: `lines::live_beneath` — the whole of the fold default — is an
    /// agent on a bead *or* an anomaly against it, so a row saying one and
    /// not the other would leave a fresh exception where two were closed.
    ///
    /// A pane still on a closed bead is the stale-pane anomaly, and it
    /// carries an agent too, so the two counts are read off the one bead and
    /// cannot be answering with each other.
    #[test]
    fn a_branch_shut_over_a_bead_wanting_looking_at_says_how_many_are_inside_it() {
        let stale = edited(
            SIDING,
            r#"{"id":"sdg-4.3.1","title":"prove the interlocking","status":"open"#,
            r#"{"id":"sdg-4.3.1","title":"prove the interlocking","closed_at":"2026-08-28T09:00:00Z","status":"closed"#,
        );
        let mut forest = flatten(alone("orbital", &stale, &panes_on(&["sdg-4.3.1"])));
        select(&mut forest, &key("orbital", "sdg-4.3"));

        forest.apply(Action::ToggleFold);

        let shut_over = row_of(&forest, "sdg-4.3")
            .shut_over
            .clone()
            .expect("a shut branch says what it hides");
        assert_eq!(shut_over.anomalies, 1);
        assert_eq!(shut_over.live_agents, 1);
    }

    /// Work, not rows — the rule every other count on this screen follows. A
    /// blocker two of a branch's descendants share is drawn beneath each of
    /// them and is one seat, and a line adding its rows would send a reader
    /// hunting for a second agent that is not there.
    #[test]
    fn one_agent_reached_two_ways_down_is_counted_once() {
        let mut forest = flatten(alone("orbital", SHARED_IN_A_RUN, &panes_on(&["lck-2"])));
        assert_eq!(
            lines_of(&forest, "lck-2").len(),
            2,
            "{:#?}",
            sketch(&forest)
        );
        select(&mut forest, &key("orbital", "lck-1"));

        forest.apply(Action::ToggleFold);

        assert_eq!(
            row_of(&forest, "lck-1")
                .shut_over
                .as_ref()
                .map(|c| c.live_agents),
            Some(1)
        );
    }

    /// The second depth exception the bead names, in the same place as the
    /// first: a root shut over unfinished work said nothing, while a closed
    /// branch one line down in the same state said how much. One rule, two
    /// answers, and nothing about a root that earns the difference.
    #[test]
    fn a_closed_root_shut_over_unfinished_work_says_how_much_like_any_other_row() {
        // `sdg-4.3` opens too: `in_progress` with no pane is an orphan claim,
        // and no fold `bdi` sets itself closes over one.
        let done = edited(
            &edited(
                SIDING,
                r#"{"id":"sdg-4.3","title":"re-signal the box","status":"in_progress"#,
                r#"{"id":"sdg-4.3","title":"re-signal the box","status":"open"#,
            ),
            r#"{"id":"sdg-4","title":"re-point the crossover","status":"in_progress"#,
            r#"{"id":"sdg-4","title":"re-point the crossover","closed_at":"2026-08-29T09:00:00Z","status":"closed"#,
        );
        let forest = flatten(alone("orbital", &done, &[]));

        assert_eq!(fold_of(&forest, "sdg-4"), Some(false));
        assert_eq!(
            row_of(&forest, "sdg-4").notes,
            vec![phrase::unfinished_beneath(5)]
        );
    }

    fn siding() -> Snapshot {
        alone("orbital", SIDING, &panes_on(&["sdg-4.3"]))
    }

    /// The case Graeme chose this default for. `sdg-4.1` is closed and its
    /// glyph says so, but `bd` will start `sdg-4.1.2` today, and a reader
    /// looking for what to pick up should not have to press a key to find it.
    ///
    /// Down the spine and no wider: `sdg-4.1` opens because the ready bead is
    /// under it, `sdg-4.1.1` stays shut because none is under that, and the
    /// count moves down to the line that is now the one doing the hiding.
    #[test]
    fn a_closed_branch_over_ready_work_rests_open_down_the_spine_to_it() {
        let forest = flatten(ready_alone(
            "orbital",
            SIDING,
            &panes_on(&["sdg-4.3"]),
            &["sdg-4.1.2"],
        ));

        assert_eq!(
            sketch(&forest),
            vec![
                "▾ orbital",
                "  └── ◐ sdg-4 re-point the crossover",
                "      ├─▸ ◐ .3 re-signal the box",
                "      ├── ✓ .1 slew the up line",
                "      │   ├── ○ .2 weld the closure rail",
                "      │   ├─▸ ✓ .1 key the switch",
                "      │   └── ✓ .3 lift the old chairs",
                "      └─▸ ✓ .2 clip the down line",
            ]
        );
        assert_eq!(row_of(&forest, "sdg-4.1").notes, Vec::<String>::new());
        assert_eq!(
            row_of(&forest, "sdg-4.1.1").notes,
            vec![phrase::unfinished_beneath(2)]
        );
    }

    /// The other half of the widened rule, and the reason it is `bd ready`
    /// and not a status test: work that is unfinished but blocked or deferred
    /// is not what a reader needs next, so it earns no fold. The statuses
    /// here are the ones that most look like work in hand, and the branch
    /// rests shut over all three exactly as it does over open ones.
    #[test]
    fn a_closed_branch_over_work_bd_will_not_start_rests_shut_and_says_how_much() {
        let waiting = edited(
            &edited(
                SIDING,
                r#""status":"open",
       "dependencies":[{"depends_on_id":"sdg-4.1.1","type":"parent-child"}]"#,
                r#""status":"blocked",
       "dependencies":[{"depends_on_id":"sdg-4.1.1","type":"parent-child"}]"#,
            ),
            r#""status":"open",
       "dependencies":[{"depends_on_id":"sdg-4.1","type":"parent-child"}]"#,
            r#""status":"deferred",
       "dependencies":[{"depends_on_id":"sdg-4.1","type":"parent-child"}]"#,
        );
        let forest = flatten(alone("orbital", &waiting, &panes_on(&["sdg-4.3"])));

        assert_eq!(fold_of(&forest, "sdg-4.1"), Some(false));
        assert_eq!(
            row_of(&forest, "sdg-4.1").notes,
            vec![phrase::unfinished_beneath(3)]
        );
    }

    /// Collapsed, not dropped: it is the existing fold, and opening it draws
    /// what it held under the same rules as anywhere else.
    #[test]
    fn opening_a_finished_subtree_draws_what_it_holds() {
        let mut forest = flatten(finished_branches());
        select(&mut forest, &key("orbital", "dep-1.2"));

        forest.apply(Action::ToggleFold);

        assert_eq!(
            sketch(&forest),
            vec![
                "▾ orbital",
                "  └── ◐ dep-1 re-lay the sidings",
                "      ├── ○ .1 grade the bed",
                "      ├── ○ .3 clear the ballast",
                "      ├── ✓ .2 lift the old rail",
                "      │   └─▸ … 3 more",
                "      └── ✓ .4 burn the sleepers",
            ]
        );
    }

    /// Depot with one of its closed siblings re-opened, leaving two finished
    /// branches — under the threshold, so each keeps its own name rather than
    /// becoming a share of a count.
    fn finished_branches() -> Snapshot {
        let json = edited(
            DEPOT,
            r#"{"id":"dep-1.3","title":"clear the ballast","status":"closed"#,
            r#"{"id":"dep-1.3","title":"clear the ballast","status":"open"#,
        );
        alone("orbital", &json, &panes_on(&["dep-1.1"]))
    }

    #[test]
    fn the_selection_survives_a_refresh_that_reorders_the_nodes() {
        let mut forest = flatten(snapshot());
        open(&mut forest, &key("orbital", "orb-7.1"));
        select(&mut forest, &key("orbital", "orb-7.1.2"));
        let was = forest.selected_line();

        let reordered = edited(ORBITAL, r#""priority":3"#, r#""priority":1"#);
        forest.refresh(gather(
            vec![tree_of("orbital", &reordered)],
            Vec::new(),
            Filter::LiveAgents,
        ));

        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1.2")));
        assert_ne!(forest.selected_line(), was);
    }

    /// Closing a bead under the cursor is the ordinary way for one to go, and
    /// the tree it was in is still on screen. The cursor stays in that tree,
    /// on the parent, rather than going back to the top of the forest.
    #[test]
    fn a_refresh_that_drops_the_selected_bead_falls_back_to_its_parent() {
        let mut forest = flatten(snapshot());
        open(&mut forest, &key("orbital", "orb-7.1"));
        select(&mut forest, &key("orbital", "orb-7.1.2"));

        let without = edited(
            ORBITAL,
            r#"{"id":"orb-7.1.2","title":"seal the feed horn","status":"open",
       "dependencies":[{"depends_on_id":"orb-7.1","type":"parent-child"}],
       "priority":3,"issue_type":"task"},"#,
            "",
        );
        forest.refresh(gather(
            vec![tree_of("orbital", &without)],
            Vec::new(),
            Filter::LiveAgents,
        ));

        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1")));
    }

    /// The bead the selection was on is gone with its whole tree, and the
    /// nearest of its forebears the new snapshot still draws is its
    /// project's line: orbital still has panes working in it that no bead
    /// claims, so the line is still there to fall back to.
    #[test]
    fn a_refresh_that_drops_the_selected_bead_leaves_the_selection_somewhere_real() {
        let mut forest = flatten(snapshot());
        open(&mut forest, &key("orbital", "orb-7.1"));
        select(&mut forest, &key("orbital", "orb-7.1.2"));
        // Harbour has no live agent, so it is a tree only a reader showing
        // every tree can be left standing on.
        forest.apply(Action::ToggleFilter);

        forest.refresh(gather(
            vec![tree_of("harbour", HARBOUR)],
            Vec::new(),
            Filter::LiveAgents,
        ));

        assert!(
            matches!(
                &forest.lines()[forest.selected_line()].content,
                Content::Project(line) if line.project == "orbital"
            ),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// `a` is a display choice over what was already collected, so what it
    /// renders is the answer the trackers already gave.
    #[test]
    fn dropping_the_filter_re_renders_rather_than_re_collecting() {
        let mut forest = flatten(snapshot());
        let generated_at = forest.snapshot().generated_at;

        assert!(forest.apply(Action::ToggleFilter));

        assert_eq!(forest.snapshot().filter, Filter::All);
        assert_eq!(forest.snapshot().generated_at, generated_at);
        assert!(sketch(&forest).iter().any(|line| line == "▾ harbour"));
        assert!(sketch(&forest).iter().any(|line| line.contains("hbr-3")));
        assert!(!sketch(&forest)
            .iter()
            .any(|line| line.contains("[HiddenTrees]")));
    }

    #[test]
    fn collapsing_an_expanded_node_and_then_collapsing_again_moves_to_its_parent() {
        let mut forest = flatten(snapshot());
        open(&mut forest, &key("orbital", "orb-7.1"));

        assert!(forest.apply(Action::CollapseOrParent));
        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1")));
        assert!(!sketch(&forest).iter().any(|line| line.contains(".1.1")));

        assert!(forest.apply(Action::CollapseOrParent));
        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7")));
    }

    #[test]
    fn expanding_a_collapsed_node_and_then_expanding_again_moves_to_its_first_child() {
        let mut forest = flatten(snapshot());
        open(&mut forest, &key("orbital", "orb-7.1"));
        forest.apply(Action::CollapseOrParent);

        assert!(forest.apply(Action::ExpandOrChild));
        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1")));

        assert!(forest.apply(Action::ExpandOrChild));
        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1.1")));
    }

    #[test]
    fn a_leaf_has_no_child_to_move_to_and_no_fold_to_collapse() {
        let mut forest = flatten(snapshot());
        open(&mut forest, &key("orbital", "orb-7.1"));
        select(&mut forest, &key("orbital", "orb-7.1.1"));

        assert!(!forest.apply(Action::ExpandOrChild));
        assert!(forest.apply(Action::CollapseOrParent));
        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1")));
    }

    #[test]
    fn moving_stops_at_the_ends() {
        let mut forest = flatten(snapshot());
        forest.apply(Action::Move(Motion::FirstRow));

        assert!(!forest.apply(Action::Move(Motion::PreviousRow)));
        assert_eq!(forest.selected_line(), 0);

        forest.apply(Action::Move(Motion::LastRow));
        let last = forest.selected_line();

        assert!(!forest.apply(Action::Move(Motion::NextRow)));
        assert_eq!(forest.selected_line(), last);
    }

    /// `^D` and `^U` move by half the band the trees are in, which the
    /// renderer measured for the last frame — not half a screen the key bar
    /// and the tail also sit in.
    #[test]
    fn a_half_screen_moves_as_far_as_the_renderer_says_it_should() {
        let mut forest = flatten(snapshot());
        forest.fit(6);

        forest.apply(Action::Move(Motion::HalfScreenDown));

        assert_eq!(forest.selected_line(), 4);

        forest.apply(Action::Move(Motion::HalfScreenUp));

        assert_eq!(forest.selected_line(), 1);
    }

    /// A band with no room to halve still moves the selection, so `^D` on the
    /// shortest screen there is does something rather than nothing.
    #[test]
    fn a_half_screen_of_a_band_too_short_to_halve_is_one_row() {
        let mut forest = flatten(snapshot());
        forest.fit(1);
        let mut stepped = flatten(snapshot());
        stepped.fit(1);

        assert!(forest.apply(Action::Move(Motion::HalfScreenDown)));
        stepped.apply(Action::Move(Motion::NextRow));

        assert_eq!(forest.selected_line(), stepped.selected_line());
    }

    // ---- the viewport ----------------------------------------------------

    /// How far a notch is told to go here. The forest is told rather than
    /// knowing, so what three means is settled in the config and its tests.
    const A_NOTCH: usize = 3;

    /// A band with room for every line has nowhere to scroll to, whichever
    /// way the wheel turns.
    #[test]
    fn a_forest_the_band_has_room_for_never_scrolls() {
        let mut forest = flatten(snapshot());
        forest.fit(forest.lines().len());

        assert!(!forest.scrolled(Notch::Down, A_NOTCH));
        assert!(!forest.scrolled(Notch::Up, A_NOTCH));
        assert_eq!(forest.from(), 0);
    }

    /// A notch travels the distance it is handed, and no other.
    #[test]
    fn a_notch_moves_the_view_as_far_as_it_is_told() {
        let mut forest = flatten(snapshot());
        forest.fit(2);

        assert!(forest.scrolled(Notch::Down, A_NOTCH));
        assert_eq!(forest.from(), A_NOTCH);

        assert!(forest.scrolled(Notch::Down, A_NOTCH));
        assert_eq!(forest.from(), A_NOTCH * 2);

        assert!(forest.scrolled(Notch::Up, A_NOTCH));
        assert_eq!(forest.from(), A_NOTCH);
    }

    /// Scrolling past the end would draw blank rows under the last line,
    /// which reads as a forest that has run out rather than one that has
    /// ended. The top is the same promise the other way up.
    #[test]
    fn the_wheel_stops_at_either_end_of_the_forest() {
        let mut forest = flatten(snapshot());
        forest.fit(4);
        let furthest = forest.lines().len() - 4;

        for _ in 0..40 {
            forest.scrolled(Notch::Down, A_NOTCH);
        }
        assert_eq!(forest.from(), furthest);
        assert!(!forest.scrolled(Notch::Down, A_NOTCH));

        for _ in 0..40 {
            forest.scrolled(Notch::Up, A_NOTCH);
        }
        assert_eq!(forest.from(), 0);
        assert!(!forest.scrolled(Notch::Up, A_NOTCH));
    }

    /// The wheel leaves the selection where the reader put it, including
    /// where that takes it off the screen — which is the whole difference
    /// from the motion the same direction names.
    #[test]
    fn the_wheel_leaves_the_selection_alone() {
        let mut forest = flatten(snapshot());
        forest.fit(2);
        let was = forest.selected_line();

        forest.scrolled(Notch::Down, A_NOTCH);

        assert_eq!(forest.selected_line(), was);
        assert!(
            was < forest.from(),
            "the selection is still inside the band, so this says nothing \
             about one the notch took off it"
        );
    }

    /// A motion brings the selection back into the band by the least it can,
    /// rather than by putting it back in the middle: a reader who wheeled to
    /// somewhere and then stepped one row keeps what they were looking at.
    ///
    /// Walked the whole way down rather than asserted at one place. Every
    /// step that pushes the selection past the last row of the band leaves
    /// the band starting exactly where that step asked and no further, and a
    /// band that recentred instead would be wrong at the first of them.
    #[test]
    fn a_motion_reveals_the_selection_by_the_least_it_can() {
        let room = 4;
        let last = an_end(Motion::LastRow);
        let mut forest = flatten(snapshot());
        forest.fit(room);
        forest.apply(Action::Move(Motion::FirstRow));
        let mut scrolled = false;

        walk::until(
            &mut forest,
            |forest| forest.selected_line() == last,
            |forest| {
                forest.apply(Action::Move(Motion::NextRow));
                let (from, at) = (forest.from(), forest.selected_line());
                if from > 0 {
                    assert_eq!(
                        from,
                        at + 1 - room,
                        "the band travelled further down than the row leaving it asked for"
                    );
                    scrolled = true;
                }
            },
            |forest| format!("a walk down stopped at row {}", forest.selected_line()),
        );

        assert!(scrolled, "the fixture never outgrew a band of {room}");
    }

    /// And the same going up, which the arithmetic that reveals downwards
    /// cannot answer for: there the band starts on the selection itself.
    #[test]
    fn a_motion_upwards_reveals_the_selection_by_the_least_it_can() {
        let first = an_end(Motion::FirstRow);
        let mut forest = flatten(snapshot());
        forest.fit(4);
        forest.apply(Action::Move(Motion::LastRow));
        let mut was = forest.from();
        let mut scrolled = false;

        walk::until(
            &mut forest,
            |forest| forest.selected_line() == first,
            |forest| {
                forest.apply(Action::Move(Motion::PreviousRow));
                let (from, at) = (forest.from(), forest.selected_line());
                if from != was {
                    assert_eq!(
                        from, at,
                        "the band travelled further up than the row leaving it asked for"
                    );
                    scrolled = true;
                }
                was = from;
            },
            |forest| format!("a walk up stopped at row {}", forest.selected_line()),
        );

        assert!(scrolled, "the fixture never outgrew a band of four");
    }

    /// Which line one end of the forest is, so a walk towards it knows what
    /// it is walking to. Asked of a forest of its own, because the answer is
    /// where the walk finishes rather than anywhere it passes through.
    fn an_end(motion: Motion) -> usize {
        let mut forest = flatten(snapshot());
        forest.apply(Action::Move(motion));
        forest.selected_line()
    }

    /// Every keyboard motion leaves the selection somewhere the band is
    /// showing, however far the wheel had taken the view from it.
    #[test]
    fn every_motion_leaves_the_selection_inside_the_band() {
        let room = 4;
        for motion in [
            Motion::PreviousRow,
            Motion::NextRow,
            Motion::HalfScreenUp,
            Motion::HalfScreenDown,
            Motion::FirstRow,
            Motion::LastRow,
        ] {
            let mut forest = flatten(snapshot());
            forest.fit(room);
            forest.scrolled(Notch::Down, A_NOTCH);
            forest.scrolled(Notch::Down, A_NOTCH);

            forest.apply(Action::Move(motion));

            let (from, at) = (forest.from(), forest.selected_line());
            assert!(
                (from..from + room).contains(&at),
                "{motion:?} left the selection on line {at}, outside {from}..{}",
                from + room
            );
        }
    }

    /// A motion that moves the band without moving the selection is still a
    /// change. The wheel put the band somewhere the selection is not, so `g`
    /// on a selection already on the first row brings the band back and
    /// nothing else — and a screen not redrawn for that goes on showing the
    /// rows the wheel left it on, under an offset the next click reads
    /// against.
    #[test]
    fn a_motion_that_only_brings_the_band_back_is_a_change() {
        let mut forest = flatten(snapshot());
        forest.fit(4);
        forest.apply(Action::Move(Motion::FirstRow));
        let first = forest.selected_line();
        forest.scrolled(Notch::Down, A_NOTCH);
        assert!(forest.from() > first, "the wheel has to take the band away");

        assert!(forest.apply(Action::Move(Motion::FirstRow)));

        assert_eq!(
            forest.selected_line(),
            first,
            "the selection was already on the first row"
        );
        assert_eq!(forest.from(), first);
    }

    /// A click selects a row the band is showing, so it never moves the view
    /// — including when the wheel has taken the band away from the top.
    #[test]
    fn a_click_on_a_row_the_band_is_showing_leaves_the_view_where_it_is() {
        let mut forest = flatten(snapshot());
        forest.fit(4);
        forest.scrolled(Notch::Down, A_NOTCH);
        let scrolled = forest.from();

        assert!(forest.select_line(scrolled + 1));
        assert_eq!(forest.from(), scrolled);
    }

    /// A collection keeps the reader's scroll rather than throwing it away:
    /// what a shorter forest costs it is the distance past its end and no
    /// more.
    #[test]
    fn a_collection_keeps_the_scroll_the_reader_set() {
        let mut forest = flatten(snapshot());
        forest.fit(4);
        forest.scrolled(Notch::Down, A_NOTCH);
        let scrolled = forest.from();

        forest.refresh(snapshot());
        forest.fit(4);

        assert_eq!(forest.from(), scrolled);
    }

    /// And a band that has shrunk under it brings the view back inside the
    /// forest, rather than leaving it drawing blank rows past the last line.
    #[test]
    fn a_shorter_band_brings_the_view_back_inside_the_forest() {
        let mut forest = flatten(snapshot());
        let lines = forest.lines().len();
        forest.fit(2);
        for _ in 0..40 {
            forest.scrolled(Notch::Down, A_NOTCH);
        }
        assert_eq!(forest.from(), lines - 2);

        forest.fit(lines);

        assert_eq!(forest.from(), 0);
    }

    /// A keystroke asks whether the screen moved by comparing the lines, so a
    /// line that carries anything the screen does not show makes that question
    /// answerable by data no reader can see. Retitling a node no line draws
    /// must leave the lines identical.
    #[test]
    fn a_line_carries_nothing_the_screen_does_not_show() {
        let drawn: BTreeSet<BeadKey> = flatten(snapshot())
            .lines()
            .iter()
            .filter_map(|line| line.bead().cloned())
            .collect();

        let mut altered = snapshot();
        let mut retitled = 0;
        for tree in &mut altered.trees {
            let tree = Arc::make_mut(tree);
            for node in &mut tree.beads {
                let key = BeadKey {
                    project: tree.project.clone(),
                    id: node.id.clone(),
                };
                if !drawn.contains(&key) {
                    node.title = format!("{} (retitled)", node.title);
                    retitled += 1;
                }
            }
        }
        assert!(
            retitled > 0,
            "every node in the fixture is drawn, so nothing here is undrawn to hide"
        );

        assert_eq!(flatten(snapshot()).lines(), flatten(altered).lines());
    }

    /// The forest cannot focus a pane, re-collect or quit; the loop does all
    /// three, and none of them changes what is on screen.
    #[test]
    fn focus_refresh_and_quit_change_nothing_in_the_forest() {
        let mut forest = flatten(snapshot());
        let before = sketch(&forest);

        for action in [Action::Focus, Action::Refresh, Action::Quit] {
            assert!(!forest.apply(action), "{action:?}");
        }

        assert_eq!(sketch(&forest), before);
    }

    /// A pane working in a project's paths that no bead claims is the
    /// project's, so it is drawn under the project's own line rather than in
    /// a group below the trees: one place to look for everything beneath a
    /// project, whether or not its roots read.
    #[test]
    fn every_loose_pane_hangs_under_its_own_projects_line() {
        let forest = flatten(snapshot());
        let loose: Vec<(&str, String)> = forest
            .lines()
            .iter()
            .enumerate()
            .filter_map(|(at, line)| match &line.content {
                Content::Item(Item::Loose(pane)) => {
                    Some((pane.project.as_str(), project_above(&forest, at)))
                }
                _ => None,
            })
            .collect();

        assert_eq!(
            loose.len(),
            forest.snapshot().unattributed.len(),
            "{:#?}",
            sketch(&forest)
        );
        for (project, above) in loose {
            assert_eq!(project, above, "{:#?}", sketch(&forest));
        }
    }

    /// The project whose line is the nearest one above `at`.
    fn project_above(forest: &Forest, at: usize) -> String {
        forest.lines()[..at]
            .iter()
            .rev()
            .find_map(|line| match &line.content {
                Content::Project(line) => Some(line.project.clone()),
                _ => None,
            })
            .expect("a line under a project has one above it")
    }

    /// A root that would not read says so on a line of its own under its
    /// project. The failure is that root's and not the project's — the
    /// project answered, and this one root did not — so it rides where the
    /// root's row would have been rather than on the line above.
    #[test]
    fn a_root_that_could_not_be_read_says_so_where_its_row_would_have_been() {
        let forest = flatten(snapshot());
        let at = forest
            .lines()
            .iter()
            .position(
                |line| matches!(&line.content, Content::Project(line) if line.project == "ferry"),
            )
            .expect("ferry has a line");

        assert!(
            matches!(
                &forest.lines()[at + 1].content,
                Content::Unread(unread)
                    if unread.root == "fer-2"
                        && unread.tracker == TrackerState::Unreachable(TrackerFailure::Auth)
            ),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// A project with no loose pane draws no line saying so: a group's line
    /// on every healthy project buries the one where it matters.
    #[test]
    fn a_project_with_no_loose_pane_draws_no_line_for_them() {
        let forest = flatten(snapshot());

        assert!(
            !forest.lines().iter().any(|line| matches!(
                &line.content,
                Content::Group(group)
                    if group.kind == GroupKind::Unattributed
                        && group.project.as_deref() == Some("harbour")
            )),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// The defect: a root drew as a tree header, which is not a bead row, so
    /// nothing that reads a bead row could see the agent on it. What is the
    /// project's — its name, and the panes recovered for it — is the project's
    /// own line, and the root beneath it is a bead like any other.
    #[test]
    fn a_project_owns_its_own_line_and_its_roots_are_ordinary_bead_rows() {
        let forest = flatten(snapshot());
        let lines = forest.lines();

        assert!(
            matches!(&lines[0].content, Content::Project(line) if line.project == "orbital"),
            "{:#?}",
            sketch(&forest)
        );
        assert!(
            matches!(&lines[1].content, Content::Bead(row) if row.id == "orb-7"),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// `bdi-2bb.25`: the root carries a pane of its own while `orb-7.4`
    /// beneath it carries another, so a count over the subtree and the root's
    /// own agent cannot come out the same by chance.
    #[test]
    fn a_staffed_root_says_what_its_agent_is_doing_like_any_other_row() {
        let forest = flatten(snapshot());

        assert_eq!(
            row_of(&forest, "orb-7").agent.as_deref(),
            Some("◍ w:p1 · working")
        );
    }

    /// A root is a bead row, so the tail reaches its pane by the road every
    /// other bead row takes. Before this it was the one staffed row on the
    /// screen where the tail said there was no bead to show.
    #[test]
    fn the_tail_follows_a_staffed_root_as_it_follows_any_other_bead() {
        let mut forest = flatten(snapshot());
        forest.apply(Action::Move(Motion::FirstRow));
        forest.apply(Action::Move(Motion::NextRow));

        assert_eq!(
            crate::view::tail::target(&forest).pane(),
            Some(&pane_key("w:p1")),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// A project's line counts the beads of its own trees and no other's.
    /// `built` puts a tree under orbital and one under harbour, so a count
    /// taken over the wrong run of trees shows on one line or the other.
    #[test]
    fn a_project_line_counts_its_own_trees_and_no_others() {
        let forest = flatten(built(Filter::All));

        assert_eq!(
            header_of(&forest, "orbital").counts,
            tree_of("orbital", ORBITAL).counts
        );
        assert_eq!(
            header_of(&forest, "harbour").counts,
            tree_of("harbour", HARBOUR).counts
        );
    }

    fn header_of<'a>(forest: &'a Forest, project: &str) -> &'a ProjectLine {
        forest
            .lines()
            .iter()
            .find_map(|line| match &line.content {
                Content::Project(line) if line.project == project => Some(line),
                _ => None,
            })
            .unwrap_or_else(|| panic!("{project} has a line"))
    }

    /// The defect: a group's lines were drawn and could not be reached, so
    /// nothing the forest holds in a group could be looked at or acted on.
    #[test]
    fn the_selection_can_walk_onto_a_line_under_a_group() {
        let mut forest = flatten(snapshot());
        let panes: Vec<usize> = forest
            .lines()
            .iter()
            .enumerate()
            .filter(|(_, line)| matches!(line.content, Content::Item(Item::Loose(_))))
            .map(|(at, _)| at)
            .collect();

        assert_eq!(panes.len(), 3, "{:#?}", sketch(&forest));
        for at in panes {
            forest.apply(Action::Move(Motion::FirstRow));
            walk::until(
                &mut forest,
                |forest| forest.selected_line() >= at,
                |forest| {
                    forest.apply(Action::Move(Motion::NextRow));
                },
                |forest| format!("line {at} cannot be reached: {:#?}", sketch(forest)),
            );
            assert_eq!(
                forest.selected_line(),
                at,
                "line {at} cannot be reached: {:#?}",
                sketch(&forest)
            );
        }
    }

    /// The identity has to be the pane itself and never where it sat, or a
    /// refresh that reorders a group moves the selection to another pane
    /// while everything on screen still looks right.
    #[test]
    fn a_selected_pane_survives_a_refresh_that_reorders_its_group() {
        let mut forest = flatten(snapshot());
        select_item(&mut forest, "w:p4");

        forest.refresh(reordered_groups());

        assert_eq!(selected_item(&forest), Some("w:p4".to_string()));
    }

    /// Every group's items, so no kind is selectable by accident and none is
    /// left behind: a group whose lines cannot be reached is the defect.
    #[test]
    fn every_kind_of_thing_a_group_holds_can_hold_the_selection() {
        let mut forest = flatten(built(Filter::LiveAgents));
        let groups: Vec<(GroupKind, Option<String>)> =
            layout::every_group(forest.snapshot()).collect();
        for (kind, project) in groups {
            forest.folds.set(Handle::Group(kind, project), true);
        }
        forest.refresh(built(Filter::LiveAgents));

        let items: Vec<usize> = forest
            .lines()
            .iter()
            .enumerate()
            .filter(|(_, line)| matches!(line.content, Content::Item(_)))
            .map(|(at, _)| at)
            .collect();

        assert_eq!(items.len(), 6, "{:#?}", sketch(&forest));
        for at in items {
            assert!(
                selectable(&forest.lines()[at]),
                "{:?} cannot hold the selection",
                forest.lines()[at].content
            );
        }
    }

    /// A pane that goes away leaves the selection on the group it was in,
    /// rather than at the top of the forest. Work ending should not look
    /// like the screen jumping.
    #[test]
    fn a_selection_on_a_pane_that_goes_away_falls_back_to_its_group() {
        let mut forest = flatten(snapshot());
        select_item(&mut forest, "w:p4");

        forest.refresh(built_without_the_conflicting_panes());

        assert!(
            matches!(
                forest.lines()[forest.selected_line()].content,
                Content::Group(Group {
                    kind: GroupKind::Unattributed,
                    ..
                })
            ),
            "{:#?}",
            forest.lines()[forest.selected_line()]
        );
    }

    /// A project's group that empties leaves the selection on the project's
    /// line, which is where the group hung: the project is still there, and
    /// the top of the forest is not where the reader was.
    #[test]
    fn a_selection_on_a_pane_whose_group_empties_falls_back_to_its_project() {
        let mut forest = flatten(snapshot());
        select_item(&mut forest, "w:p9");

        forest.refresh(built_without_ferrys_panes());

        assert!(
            matches!(
                &forest.lines()[forest.selected_line()].content,
                Content::Project(line) if line.project == "ferry"
            ),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// The same from the group's own line.
    #[test]
    fn a_selection_on_a_projects_group_that_empties_falls_back_to_the_project() {
        let mut forest = flatten(snapshot());
        let group = forest
            .lines()
            .iter()
            .position(|line| {
                matches!(&line.content, Content::Group(group)
                    if group.kind == GroupKind::Unattributed
                        && group.project.as_deref() == Some("ferry"))
            })
            .expect("ferry has a pane no bead claims");
        assert!(forest.select_line(group));

        forest.refresh(built_without_ferrys_panes());

        assert!(
            matches!(
                &forest.lines()[forest.selected_line()].content,
                Content::Project(line) if line.project == "ferry"
            ),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// The same snapshot with the one pane working in ferry gone, which
    /// empties the group ferry's line holds it in.
    fn built_without_ferrys_panes() -> Snapshot {
        let mut snapshot = snapshot();
        snapshot.unattributed.retain(|pane| pane.project != "ferry");
        snapshot
    }

    /// The handle a project's group is held by carries the project, so a
    /// reader opening one project's quiet trees opens nobody else's.
    #[test]
    fn opening_one_projects_hidden_trees_leaves_another_projects_shut() {
        let colliding = edited(SLIPWAY, "hbr-9", "hbr-3");
        let mut forest = flatten(gather(
            vec![tree_of("harbour", HARBOUR), tree_of("orbital", &colliding)],
            Vec::new(),
            Filter::LiveAgents,
        ));
        select_hidden_tree(&mut forest);
        assert_eq!(cursor(&forest), Some(&key("orbital", "hbr-3")));

        let harbours = forest
            .lines()
            .iter()
            .find(|line| {
                matches!(&line.content, Content::Group(group)
                    if group.kind == GroupKind::HiddenTrees
                        && group.project.as_deref() == Some("harbour"))
            })
            .expect("harbour's quiet trees have a line");
        assert_eq!(harbours.folded, Some(false), "{:#?}", sketch(&forest));
    }

    /// A project with quiet trees and loose panes both: opening the line over
    /// its quiet trees draws them one level in, and the line over its loose
    /// panes still follows at the depth it started at, hanging under the
    /// project and not under the trees just opened.
    #[test]
    fn a_projects_loose_panes_follow_its_opened_quiet_trees_at_their_own_depth() {
        let mut quiet = alone("orbital", TOWER, &panes_on(&["nobody"]));
        quiet.refilter(Filter::LiveAgents);
        let mut forest = flatten(quiet);
        assert_eq!(
            sketch(&forest)[..4],
            [
                "▾ orbital",
                "  ├─▸ [HiddenTrees orbital] 1",
                "  └── [Unattributed orbital] 1",
                "      └── - Loose(LoosePane { pane: PaneKey { session: \"default\", id: \"w:nobody\" }, project: \"orbital\", cwd: \"/srv/work/orbital\", pane_status: Working, display_agent: Some(\"nobody\"), title: None, claim_refused: false })",
            ]
        );

        select_hidden_tree(&mut forest);

        assert_eq!(
            sketch(&forest)[..5],
            [
                "▾ orbital",
                "  ├── [HiddenTrees orbital] 1",
                "  │   └─▸ ○ tow-1 raise the tower",
                "  └── [Unattributed orbital] 1",
                "      └── - Loose(LoosePane { pane: PaneKey { session: \"default\", id: \"w:nobody\" }, project: \"orbital\", cwd: \"/srv/work/orbital\", pane_status: Working, display_agent: Some(\"nobody\"), title: None, claim_refused: false })",
            ]
        );
    }

    /// The filter decides where a project's trees are drawn and not whether
    /// the project holds them, so its line counts every bead of every tree
    /// and `a` moves nothing on it.
    #[test]
    fn a_projects_line_counts_the_trees_the_filter_holds_back() {
        let mut forest = flatten(snapshot());
        let counted = header_of(&forest, "harbour").counts.clone();
        assert_eq!(counted.total, 2, "{:#?}", sketch(&forest));

        forest.apply(Action::ToggleFilter);

        assert_eq!(forest.snapshot().filter, Filter::All);
        assert_eq!(header_of(&forest, "harbour").counts, counted);
    }

    /// A project whose tracker could not be read at all can still have panes
    /// working in its paths, and they are the project's: its line is drawn
    /// for them, and the failure stays where it is reported, in the group
    /// below the trees.
    #[test]
    fn a_failed_projects_loose_panes_hang_under_its_own_line() {
        let forest = flatten(gather(
            vec![tree_of("orbital", ORBITAL)],
            vec![FailedProject {
                project: "ferry".into(),
                tracker: TrackerFailure::Unstartable,
            }],
            Filter::LiveAgents,
        ));
        let drawn = sketch(&forest);
        let ferry = drawn
            .iter()
            .position(|line| line == "▾ ferry")
            .unwrap_or_else(|| panic!("ferry has a line: {drawn:#?}"));

        assert_eq!(
            drawn[ferry..ferry + 4],
            [
                "▾ ferry",
                "  └── [Unattributed ferry] 1",
                "      └── - Loose(LoosePane { pane: PaneKey { session: \"default\", id: \"w:p9\" }, project: \"ferry\", cwd: \"/srv/work/ferry\", pane_status: Blocked, display_agent: None, title: None, claim_refused: false })",
                "▸ [FailedProjects] 1",
            ]
        );
    }

    /// A forest of projects drawn only for the panes working in their paths
    /// holds no root, so there is nothing for `select_first_root` to open on.
    /// The selection still settles somewhere and stays: `lay_out` runs before
    /// it and leaves the cursor on the first thing the forest holds, so a key
    /// that lays the forest out again and says nothing about the selection
    /// finds it already held.
    #[test]
    fn a_project_drawn_only_for_its_loose_panes_keeps_the_line_it_opened_on() {
        let mut forest = flatten(gather(
            Vec::new(),
            vec![FailedProject {
                project: "ferry".into(),
                tracker: TrackerFailure::Unstartable,
            }],
            Filter::LiveAgents,
        ));
        let drawn = sketch(&forest);
        assert!(
            !drawn
                .iter()
                .any(|line| line.contains('') || line.contains('')),
            "no root is drawn, which is what leaves nothing to open on: {drawn:#?}"
        );
        let opened_on = forest.selected_line();
        assert_eq!(
            drawn[opened_on], "  └── [Unattributed orbital] 2",
            "the selection settles on the first thing drawn, not on nothing: {drawn:#?}"
        );

        for action in [Action::ToggleFilter, Action::RestoreDefault] {
            forest.apply(action);
            assert_eq!(
                sketch(&forest)[forest.selected_line()],
                drawn[opened_on],
                "{action:?}"
            );
        }
    }

    /// The pane id on the line the selection sits on, where it sits on one.
    fn selected_item(forest: &Forest) -> Option<String> {
        match &forest.lines()[forest.selected_line()].content {
            Content::Item(Item::Loose(pane)) => Some(pane.pane.id.clone()),
            Content::Item(Item::Unconfigured(pane)) => Some(pane.pane.id.clone()),
            _ => None,
        }
    }

    /// Put the selection on the line for one pane, by moving down to it.
    fn select_item(forest: &mut Forest, pane: &str) {
        forest.apply(Action::Move(Motion::FirstRow));
        walk::until(
            forest,
            |forest| selected_item(forest).as_deref() == Some(pane),
            |forest| {
                forest.apply(Action::Move(Motion::NextRow));
            },
            |_| format!("{pane} is not reachable by moving down"),
        );
    }

    /// The same snapshot with every group's items in the other order, which
    /// is what a collect that re-read them may hand over.
    fn reordered_groups() -> Snapshot {
        let mut snapshot = snapshot();
        snapshot.unattributed.reverse();
        snapshot.conflicts.reverse();
        snapshot.hidden_trees.reverse();
        snapshot
    }

    /// A group the collect empties puts the selection back on the first root,
    /// not on whatever line happened to sit above where the group was. The
    /// two answers only differ once the forest is more than a row tall, which
    /// is every forest a reader has.
    ///
    /// This is the only one of `group_drawn`'s two callers that can tell you
    /// it is wrong. `first_handle` cannot: `lay_out` looks the handle it
    /// returns up, does not find it drawn, and repairs the cursor from the
    /// selected index — so a `group_drawn` that said yes to every kind would
    /// go unnoticed down that road.
    #[test]
    fn a_selection_on_a_group_that_empties_goes_back_to_the_first_root() {
        let mut forest = flatten(snapshot());
        let group = forest
            .lines()
            .iter()
            .position(|line| {
                matches!(&line.content, Content::Group(group)
                    if group.kind == GroupKind::FailedProjects)
            })
            .expect("the shared snapshot draws a group for the project that failed");
        step_onto(&mut forest, group);

        forest.refresh(built_without_the_failed_project());

        assert_eq!(
            forest.lines()[forest.selected_line()]
                .bead()
                .map(|bead| bead.id.clone()),
            Some("orb-7".to_string()),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// The same snapshot with the project that failed before its roots were
    /// known now reading, which empties the group it was the only member of.
    fn built_without_the_failed_project() -> Snapshot {
        let mut snapshot = snapshot();
        snapshot.failed_projects.clear();
        snapshot
    }

    /// The same snapshot with the two panes that were fighting over `orb-7.1`
    /// gone, which empties the unattributed group of the one the tests hold.
    fn built_without_the_conflicting_panes() -> Snapshot {
        let mut snapshot = snapshot();
        snapshot.unattributed.retain(|pane| pane.pane.id == "w:p3");
        snapshot
    }

    #[test]
    fn an_empty_group_draws_nothing() {
        let orbital = assembled(ORBITAL);
        let harbour = assembled(HARBOUR);
        let joined = joined(&orbital, &harbour, &panes());
        let snapshot = snapshot::build(
            Collected {
                trees: vec![tree_of("orbital", ORBITAL)],
                failed_projects: Vec::new(),
                read_at: every_project_read(),
            },
            &[],
            &Joined {
                agents: joined.agents,
                refused: BTreeMap::new(),
                out_of_reach: BTreeSet::new(),
                conflicts: Vec::new(),
            },
            &cfg(),
            a_provider(ProviderState::Answering),
            Filter::LiveAgents,
            now(),
        );

        assert!(!sketch(&flatten(snapshot))
            .iter()
            .any(|line| line.contains('[')));
    }

    #[test]
    fn a_group_draws_one_line_for_each_thing_it_holds_when_it_is_opened() {
        let mut forest = flatten(snapshot());
        let loose = |forest: &Forest| {
            sketch(forest)
                .iter()
                .filter(|line| line.contains("Loose"))
                .count()
        };
        let group = forest
            .lines()
            .iter()
            .position(|line| {
                matches!(&line.content, Content::Group(group)
                    if group.kind == GroupKind::Unattributed
                        && group.project.as_deref() == Some("orbital"))
            })
            .expect("orbital has panes no bead claims");
        forest.select_line(group);

        // Ferry's one loose pane is under ferry's own line, and stays.
        assert!(forest.apply(Action::ToggleFold));
        assert_eq!(loose(&forest), 1, "{:#?}", sketch(&forest));

        assert!(forest.apply(Action::ToggleFold));
        assert_eq!(loose(&forest), 3, "{:#?}", sketch(&forest));
    }

    /// The panes under no configured project open into their own directories,
    /// which is the whole use of the group: the line says a `[[projects]]`
    /// entry is missing and opening it says which one.
    #[test]
    fn opening_the_unconfigured_group_names_the_directories() {
        let mut forest = flatten(snapshot());
        forest
            .folds
            .set(Handle::Group(GroupKind::Unconfigured, None), true);
        forest.refresh(snapshot());

        let drawn = sketch(&forest);

        assert!(
            drawn
                .iter()
                .any(|line| line.contains("Unconfigured") && line.contains("/srv/spike")),
            "{drawn:#?}"
        );
    }

    /// The filter's choice holds — a hidden tree is not drawn — but a group
    /// that says only how many trees it hides reads like "nothing to see"
    /// when one of them is waiting on work bd never returned.
    #[test]
    fn the_hidden_trees_group_says_how_many_of_them_have_findings() {
        let broken = edited(
            HARBOUR,
            r#"{"depends_on_id":"hbr-3","type":"parent-child"}"#,
            r#"{"depends_on_id":"hbr-3","type":"parent-child"},
                       {"depends_on_id":"hbr-9","type":"blocks"}"#,
        );
        let snapshot = gather(
            vec![tree_of("orbital", ORBITAL), tree_of("harbour", &broken)],
            Vec::new(),
            Filter::LiveAgents,
        );

        let group = hidden_trees_group(&flatten(snapshot), "harbour");

        assert_eq!(group.count, 1);
        assert_eq!(group.with_findings, 1);
    }

    #[test]
    fn a_hidden_tree_with_nothing_wrong_in_it_is_only_counted_as_hidden() {
        let group = hidden_trees_group(&flatten(snapshot()), "harbour");

        assert_eq!(group.count, 1);
        assert_eq!(group.with_findings, 0);
    }

    /// What the group says of the trees it hides was settled when the filter
    /// hid them. A count that had to go back to `collected` for it would
    /// cost every press a walk over the whole forest, and a forest of
    /// thousands of hidden trees was paying half its keystroke for that.
    #[test]
    fn the_hidden_trees_group_does_not_go_back_to_the_collected_trees_for_its_count() {
        let broken = edited(
            HARBOUR,
            r#"{"depends_on_id":"hbr-3","type":"parent-child"}"#,
            r#"{"depends_on_id":"hbr-3","type":"parent-child"},
                       {"depends_on_id":"hbr-9","type":"blocks"}"#,
        );
        let mut snapshot = gather(
            vec![tree_of("orbital", ORBITAL), tree_of("harbour", &broken)],
            Vec::new(),
            Filter::LiveAgents,
        );
        snapshot.collected.clear();

        let group = hidden_trees_group(&flatten(snapshot), "harbour");

        assert_eq!(group.count, 1);
        assert_eq!(group.with_findings, 1);
    }

    /// A hidden tree's findings are the ones in its own tree. Harbour hides
    /// two roots and only the slipway has anything wrong in it, so a match
    /// that asked the project alone would report the channel as hiding a
    /// finding that is not in it.
    #[test]
    fn a_hidden_tree_does_not_take_a_finding_from_another_root_in_its_project() {
        let snapshot = gather(
            vec![tree_of("harbour", HARBOUR), tree_of("harbour", SLIPWAY)],
            Vec::new(),
            Filter::LiveAgents,
        );

        let group = hidden_trees_group(&flatten(snapshot), "harbour");

        assert_eq!(group.count, 2);
        assert_eq!(group.with_findings, 1);
    }

    /// Bead ids are numbered per tracker and the trackers do not coordinate,
    /// so two projects can each hold a root called `hbr-3` and they are
    /// different beads. Each is hidden under its own project, and a match
    /// that asked the root alone would report harbour as hiding the finding
    /// that is in orbital's.
    #[test]
    fn a_hidden_tree_does_not_take_a_finding_from_the_same_root_in_another_project() {
        let colliding = edited(SLIPWAY, "hbr-9", "hbr-3");
        let forest = flatten(gather(
            vec![tree_of("harbour", HARBOUR), tree_of("orbital", &colliding)],
            Vec::new(),
            Filter::LiveAgents,
        ));

        let harbour = hidden_trees_group(&forest, "harbour");
        let orbital = hidden_trees_group(&forest, "orbital");

        assert_eq!((harbour.count, harbour.with_findings), (1, 0));
        assert_eq!((orbital.count, orbital.with_findings), (1, 1));
    }

    /// The line over one project's hidden trees.
    fn hidden_trees_group(forest: &Forest, project: &str) -> Group {
        forest
            .lines()
            .iter()
            .find_map(|line| match &line.content {
                Content::Group(group)
                    if group.kind == GroupKind::HiddenTrees
                        && group.project.as_deref() == Some(project) =>
                {
                    Some(group.clone())
                }
                _ => None,
            })
            .unwrap_or_else(|| panic!("the filter hid a tree of {project}"))
    }

    /// Put the selection on the first hidden tree's row: open the group,
    /// which rests shut, and step into it.
    fn select_hidden_tree(forest: &mut Forest) {
        let group = forest
            .lines()
            .iter()
            .position(|line| {
                matches!(&line.content, Content::Group(group) if group.kind == GroupKind::HiddenTrees)
            })
            .expect("the filter hid a tree");
        forest.select_line(group);
        assert_eq!(forest.selected_line(), group);
        forest.apply(Action::ExpandOrChild);
        forest.apply(Action::ExpandOrChild);
        assert!(
            matches!(
                forest.lines()[forest.selected_line()].content,
                Content::Bead(_)
            ),
            "{:#?}",
            sketch(forest)
        );
    }

    /// The selected line and everything drawn beneath it, sketched.
    fn beneath_the_selection(forest: &Forest) -> Vec<String> {
        let scope = forest
            .handle_at(forest.selected_line())
            .expect("the selection is on a line it can hold");
        subtree_of(forest.lines(), &scope)
            .iter()
            .map(|line| format!("{}{}", line.prefix, said(&line.content)))
            .collect()
    }

    /// A hidden tree's row is its root's row, so it stands for that bead as
    /// a tree's header does: the show key and `y` have a bead to work on.
    #[test]
    fn a_hidden_trees_row_stands_for_its_root() {
        let mut forest = flatten(snapshot());
        select_hidden_tree(&mut forest);

        assert_eq!(cursor(&forest), Some(&key("harbour", "hbr-3")));
    }

    /// A hidden tree is a tree, and the group is only where the filter put
    /// it: it is drawn there as its project would draw it, one level further
    /// in under the group's line, and opens onto the same rows.
    #[test]
    fn a_hidden_tree_is_drawn_in_the_group_as_its_project_would_draw_it() {
        let mut forest = flatten(snapshot());
        select_hidden_tree(&mut forest);
        assert_eq!(
            beneath_the_selection(&forest),
            ["      └─▸ ○ hbr-3 dredge the channel"],
            "a hidden tree rests shut"
        );

        assert!(forest.apply(Action::ExpandOrChild));

        let in_the_group = beneath_the_selection(&forest);
        assert_eq!(
            in_the_group,
            [
                "      └── ○ hbr-3 dredge the channel",
                "          └── ○ .1 survey the silt"
            ]
        );
        forest.apply(Action::ToggleFilter);
        assert_eq!(forest.snapshot().filter, Filter::All);
        select(&mut forest, &key("harbour", "hbr-3"));
        assert_eq!(
            beneath_the_selection(&forest),
            [
                "  └── ○ hbr-3 dredge the channel",
                "      └── ○ .1 survey the silt"
            ],
            "the same rows under its project, the fold the reader opened included"
        );
    }

    /// Graeme: *"the top-level trees with no live agent should not be
    /// expanded by default"*. A hidden tree rests shut whatever is beneath
    /// it, where the same tree shown under its project rests open onto the
    /// work a reader could start; it is the one thing about a hidden tree
    /// that differs from the same tree shown.
    #[test]
    fn a_hidden_tree_rests_shut_even_over_work_that_would_open_it_shown() {
        let ready = ready_alone("orbital", HARBOUR, &[], &["hbr-3.1"]);
        assert_eq!(
            lines_of(&flatten(ready.clone()), "hbr-3.1").len(),
            1,
            "shown, the tree rests open onto its ready work"
        );

        let mut hidden = ready;
        hidden.refilter(Filter::LiveAgents);
        let mut forest = flatten(hidden);
        select_hidden_tree(&mut forest);

        assert_eq!(forest.lines()[forest.selected_line()].folded, Some(false));
        assert_eq!(
            lines_of(&forest, "hbr-3.1").len(),
            0,
            "{:#?}",
            sketch(&forest)
        );
    }

    /// Opening a hidden tree is the reader's choice and not the filter's, so
    /// letting go of the folds shuts it again: the group is shut with the
    /// rest, and opened once more by hand it holds the row shut over its
    /// tree, as the filter left it.
    #[test]
    fn the_default_puts_an_opened_hidden_tree_back() {
        let mut forest = flatten(snapshot());
        select_hidden_tree(&mut forest);
        let shut = beneath_the_selection(&forest);
        forest.apply(Action::ExpandOrChild);
        assert_ne!(beneath_the_selection(&forest), shut, "the tree opened");

        forest.apply(Action::RestoreDefault);

        assert_eq!(
            hidden_trees_group(&forest, "harbour").count,
            1,
            "the group is drawn shut: {:#?}",
            sketch(&forest)
        );
        select_hidden_tree(&mut forest);
        assert_eq!(beneath_the_selection(&forest), shut);
    }

    /// A tree that is only its root has nothing to open onto, and a fold
    /// over nothing would be a key that does nothing.
    #[test]
    fn a_hidden_tree_with_nothing_beneath_its_root_offers_no_fold() {
        let lone = r#"[{"id":"hbr-1","title":"moor the lightship","status":"open"}]"#;
        let mut forest = flatten(gather(
            vec![tree_of("harbour", lone)],
            Vec::new(),
            Filter::LiveAgents,
        ));
        select_hidden_tree(&mut forest);
        let row = forest.selected_line();

        assert_eq!(forest.lines()[row].folded, None);
        assert_eq!(
            beneath_the_selection(&forest),
            ["      └── ○ hbr-1 moor the lightship"]
        );
        assert!(!forest.apply(Action::ExpandOrChild), "nothing to open onto");
    }

    /// A hidden tree's facts are a tree's facts, answered when the forest
    /// takes the snapshot: drawing it, opening it and moving through it ask
    /// nothing of the tree.
    #[test]
    fn a_keystroke_in_the_hidden_trees_group_walks_no_subtree() {
        let mut forest = flatten(snapshot());
        let before = walks_on_this_thread();

        select_hidden_tree(&mut forest);
        forest.apply(Action::ExpandOrChild);
        forest.apply(Action::Move(Motion::NextRow));

        assert_eq!(walks_on_this_thread() - before, 0);
    }

    /// A hidden tree's findings are drawn under its root as any tree's are,
    /// whether the root is folded or not. The group holding it shut is what
    /// keeps them off the screen, and the group's line admits to them.
    #[test]
    fn a_hidden_trees_findings_are_drawn_under_its_root_as_any_trees_are() {
        let mut forest = flatten(gather(
            vec![tree_of("orbital", ORBITAL), tree_of("harbour", SLIPWAY)],
            Vec::new(),
            Filter::LiveAgents,
        ));
        select_hidden_tree(&mut forest);

        assert_eq!(
            beneath_the_selection(&forest),
            [
                "      └─▸ ○ hbr-9 re-deck the slipway",
                "          └── ! Dangling(1)"
            ]
        );
    }

    /// `E` on the hidden-trees group opens every hidden tree to the bottom.
    /// The walk's budget is counted off the beads, and a hidden tree's beads
    /// are as much of the forest as a shown tree's: a budget counted off the
    /// shown trees alone runs out on a forest that shows none.
    #[test]
    fn expanding_the_hidden_trees_group_reaches_the_bottom_of_a_deep_hidden_tree() {
        let chain = r#"[
          {"id":"hbr-5","title":"root","status":"open"},
          {"id":"hbr-5.1","title":"one","status":"open",
           "dependencies":[{"depends_on_id":"hbr-5","type":"parent-child"}]},
          {"id":"hbr-5.1.1","title":"two","status":"open",
           "dependencies":[{"depends_on_id":"hbr-5.1","type":"parent-child"}]},
          {"id":"hbr-5.1.1.1","title":"three","status":"open",
           "dependencies":[{"depends_on_id":"hbr-5.1.1","type":"parent-child"}]}
        ]"#;
        let mut forest = flatten(gather(
            vec![tree_of("harbour", chain)],
            Vec::new(),
            Filter::LiveAgents,
        ));
        assert!(forest.snapshot().trees.is_empty(), "every tree is hidden");
        let group = forest
            .lines()
            .iter()
            .position(|line| {
                matches!(&line.content, Content::Group(group) if group.kind == GroupKind::HiddenTrees)
            })
            .expect("the group is drawn");
        forest.select_line(group);
        assert_eq!(forest.selected_line(), group);

        forest.apply(Action::ExpandSubtree);

        assert_eq!(
            lines_of(&forest, "hbr-5.1.1.1").len(),
            1,
            "{:#?}",
            sketch(&forest)
        );
    }

    fn on_the_hidden_trees_group(forest: &Forest) -> bool {
        matches!(
            &forest.lines()[forest.selected_line()].content,
            Content::Group(group) if group.kind == GroupKind::HiddenTrees
        )
    }

    /// A tree the filter takes from under the selection goes into the
    /// hidden-trees group, and so does the selection: with the group shut
    /// over it, the group's line is where the tree went, which is more than
    /// whatever row happened to be nearest can say.
    #[test]
    fn putting_the_filter_back_over_the_selected_tree_moves_the_selection_to_the_group() {
        let mut forest = flatten(built(Filter::All));
        select(&mut forest, &key("harbour", "hbr-3"));

        forest.apply(Action::ToggleFilter);

        assert_eq!(forest.snapshot().filter, Filter::LiveAgents);
        assert!(on_the_hidden_trees_group(&forest), "{:#?}", sketch(&forest));
    }

    /// The same where a refresh is what hides it: the agent that kept the
    /// tree on the screen has gone, and the selection was on a bead inside.
    /// A pane on no bead keeps a group drawn below the hidden trees, so the
    /// nearest row to where the selection was is not the group's line.
    #[test]
    fn a_refresh_that_hides_the_selected_tree_moves_the_selection_to_the_group() {
        let mut staffed = alone("orbital", TOWER, &panes_on(&["tow-1.1", "nobody"]));
        staffed.refilter(Filter::LiveAgents);
        let mut forest = flatten(staffed);
        select(&mut forest, &key("orbital", "tow-1.1"));

        forest.refresh(alone("orbital", TOWER, &panes_on(&["nobody"])));

        assert_eq!(forest.snapshot().hidden_trees.len(), 1);
        assert_eq!(forest.snapshot().unattributed.len(), 1);
        assert!(on_the_hidden_trees_group(&forest), "{:#?}", sketch(&forest));
    }

    /// With the group open, the tree's root is drawn there under the same
    /// handle, so the selection simply follows the tree into the group.
    #[test]
    fn with_the_group_open_the_selection_follows_the_tree_the_filter_hides() {
        let mut forest = flatten(built(Filter::All));
        forest.folds.set(
            Handle::Group(GroupKind::HiddenTrees, Some("harbour".into())),
            true,
        );
        select(&mut forest, &key("harbour", "hbr-3"));

        forest.apply(Action::ToggleFilter);

        assert_eq!(cursor(&forest), Some(&key("harbour", "hbr-3")));
    }

    /// With the group open and the selection on a bead inside a tree that
    /// rested open on its own account, the root the tree now rests shut
    /// under is where the tree went, which is more than the nearest row can
    /// say. A fold the reader had opened by hand would have kept the bead
    /// drawn, and the selection with it.
    #[test]
    fn with_the_group_open_a_bead_inside_the_hidden_tree_falls_back_to_its_root() {
        let mut forest = flatten(ready_alone("orbital", HARBOUR, &[], &["hbr-3.1"]));
        forest.folds.set(
            Handle::Group(GroupKind::HiddenTrees, Some("orbital".into())),
            true,
        );
        select(&mut forest, &key("orbital", "hbr-3.1"));

        forest.apply(Action::ToggleFilter);

        assert_eq!(forest.snapshot().filter, Filter::LiveAgents);
        assert_eq!(cursor(&forest), Some(&key("orbital", "hbr-3")));
    }

    /// Only the cursor's own tree going into the group takes the selection
    /// there. Letting go of the folds shuts one over a bead in a tree that is
    /// still drawn, and the selection takes the nearest row as it always has,
    /// however many other trees of the same project the group is shut over.
    #[test]
    fn a_fold_shutting_over_the_selection_keeps_it_out_of_the_hidden_trees_group() {
        let mut staffed = together("orbital", &[TOWER, HARBOUR], &panes_on(&["tow-1.1"]));
        staffed.refilter(Filter::LiveAgents);
        let mut forest = flatten(staffed);
        assert_eq!(forest.snapshot().hidden_trees.len(), 1);
        select(&mut forest, &key("orbital", "tow-1.1"));
        forest.apply(Action::ToggleFold);
        forest.apply(Action::Move(Motion::NextRow));
        assert_eq!(cursor(&forest), Some(&key("orbital", "tow-1.1.1")));

        forest.apply(Action::RestoreDefault);

        assert_eq!(
            cursor(&forest),
            Some(&key("orbital", "tow-1.2")),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// Only a hidden tree takes findings out of the forest with it. Every
    /// other group holds its own subject in full, so none of them has
    /// anything undrawn to admit to.
    #[test]
    fn no_other_group_claims_to_be_hiding_findings() {
        let forest = flatten(snapshot());
        let others: Vec<Group> = forest
            .lines()
            .iter()
            .filter_map(|line| match &line.content {
                Content::Group(group) if group.kind != GroupKind::HiddenTrees => {
                    Some(group.clone())
                }
                _ => None,
            })
            .collect();

        assert_eq!(others.len(), 5);
        assert!(
            others.iter().all(|group| group.with_findings == 0),
            "{others:#?}"
        );
    }

    /// Every fold state over every root, every group the snapshot draws and
    /// one interior node: a few hundred of them, which is small enough to
    /// visit rather than sample.
    #[test]
    fn nothing_reported_disappears_under_any_fold_state() {
        let snapshot = snapshot();
        let mut handles = vec![
            Handle::Bead(Place::root(key("orbital", "orb-7"))),
            Handle::Bead(Place::root(key("ferry", "fer-2"))),
            Handle::Bead(Place::root(key("orbital", "orb-7")).step_to(key("orbital", "orb-7.1"))),
        ];
        handles.extend(
            layout::every_group(&snapshot)
                .filter(|(kind, project)| {
                    layout::group_drawn(&snapshot, *kind, project.as_deref(), None)
                })
                .map(|(kind, project)| Handle::Group(kind, project)),
        );
        assert_eq!(handles.len(), 9, "{handles:#?}");
        for state in 0..1 << handles.len() {
            let mut forest = flatten(snapshot.clone());
            for (bit, handle) in handles.iter().enumerate() {
                forest.folds.set(handle.clone(), state & (1 << bit) == 0);
            }
            forest.refresh(snapshot.clone());

            let hidden_trees_open = forest.lines().iter().any(|line| {
                matches!(&line.content, Content::Group(group) if group.kind == GroupKind::HiddenTrees)
                    && line.folded == Some(true)
            });
            assert_eq!(
                on_screen(&forest),
                in_the_snapshot(&snapshot, hidden_trees_open),
                "fold state {state:b}"
            );
        }
    }

    /// The five degraded kinds, plus the two sorts of loose pane — the ones
    /// drawn under their project, and the ones no configured project covers.
    #[derive(Debug, Default, PartialEq, Eq)]
    struct Reported {
        dangling: usize,
        cycles: usize,
        conflicts: usize,
        failed_projects: usize,
        loose_panes: usize,
        unconfigured_panes: usize,
    }

    /// What the screen owes the reader: everything in the shown trees, and
    /// the hidden trees' findings too once the group holding them is open —
    /// shut, that group's line admits to them as a count instead.
    fn in_the_snapshot(snapshot: &Snapshot, hidden_trees_open: bool) -> Reported {
        let drawn: Vec<&Tree> = snapshot
            .trees
            .iter()
            .map(Arc::as_ref)
            .chain(
                snapshot
                    .hidden_trees
                    .iter()
                    .filter(|_| hidden_trees_open)
                    .filter_map(|hidden| snapshot.tree(&key(&hidden.project, &hidden.root))),
            )
            .collect();
        Reported {
            dangling: drawn.iter().map(|t| t.dangling.len()).sum(),
            cycles: drawn.iter().map(|t| t.cycles.len()).sum(),
            conflicts: snapshot.conflicts.len(),
            failed_projects: snapshot.failed_projects.len(),
            loose_panes: snapshot.unattributed.len(),
            unconfigured_panes: snapshot.unconfigured.len(),
        }
    }

    fn on_screen(forest: &Forest) -> Reported {
        let mut found = Reported::default();
        for line in forest.lines() {
            match &line.content {
                // Matched variant by variant so a note added later has to
                // be decided here rather than fall through as nothing.
                Content::Note(note) => match note {
                    Note::Dangling(n) => found.dangling += n,
                    Note::Cycle(n) => found.cycles += n,
                    // A property of the drawing rather than a finding in the
                    // snapshot, so there is no count for it to reach.
                    Note::NoRoots => {}
                },
                Content::Group(Group { kind, count, .. }) => match kind {
                    GroupKind::Conflicts => found.conflicts += count,
                    GroupKind::FailedProjects => found.failed_projects += count,
                    GroupKind::Unattributed => found.loose_panes += count,
                    GroupKind::Unconfigured => found.unconfigured_panes += count,
                    // Neither holds a finding of its own: each stands over
                    // whole roots, and what is wrong inside one of those is
                    // the root's to report when the group is opened.
                    GroupKind::HiddenTrees | GroupKind::OutOfTheWay => {}
                },
                _ => {}
            }
        }
        found
    }

    // ---- the column a line's content starts in ----------------------------

    /// How wide a prefix is on screen. Every glyph a prefix is drawn from is
    /// one column, so counting them is the column its content starts in.
    fn columns(prefix: &str) -> usize {
        prefix.chars().count()
    }

    /// The line drawn for one bead, by the whole id it carries.
    fn line_of<'a>(forest: &'a Forest, id: &str) -> &'a Line {
        forest
            .lines()
            .iter()
            .find(|line| line.bead().is_some_and(|bead| bead.id == id))
            .unwrap_or_else(|| panic!("{id} is not drawn"))
    }

    /// `sdg-4.3` rests shut over work of its own and `sdg-4.1` rests open
    /// beside it, both children of the root. A reader runs down the column
    /// the ids are in, and a line pushed right of its siblings is out of the
    /// column that was drawn to be read.
    ///
    /// Asked in columns rather than of a substring: every prefix here holds
    /// the elbow the other one does, so a test that looked for one found it
    /// on both and said nothing about where they started.
    #[test]
    fn a_shut_node_starts_in_the_same_column_as_an_open_sibling() {
        let forest = flatten(ready_alone(
            "orbital",
            SIDING,
            &panes_on(&["sdg-4.3"]),
            &["sdg-4.1.2"],
        ));
        let shut = line_of(&forest, "sdg-4.3");
        let open = line_of(&forest, "sdg-4.1");

        assert_eq!(shut.folded, Some(false), "sdg-4.3 is the one resting shut");
        assert_eq!(open.folded, Some(true), "sdg-4.1 is the one resting open");
        assert_eq!(shut.depth, open.depth, "they are siblings");
        assert_eq!(
            columns(&shut.prefix),
            columns(&open.prefix),
            "a shut node and an open sibling start in different columns:\n{}",
            sketch(&forest).join("\n")
        );
    }

    /// `slu-1.1` is a child of the root and holds up its sibling `slu-1.2`,
    /// so the tree draws it under each: once as part of the root, once as
    /// what `slu-1.2` cannot finish until. The same nesting is saying two
    /// different things, and the arm of the elbow is where it says which —
    /// dashed under the bead it blocks, solid under the bead it is part of.
    /// `slu-1.1.1` hangs under both copies on a solid arm, because it is a
    /// child of `slu-1.1` wherever `slu-1.1` is drawn.
    const SLUICE: &str = r#"[
      {"id":"slu-1","title":"rehang the sluice","status":"in_progress",
       "priority":1,"issue_type":"epic"},
      {"id":"slu-1.1","title":"forge the new pintles","status":"in_progress",
       "dependencies":[{"depends_on_id":"slu-1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"slu-1.1.1","title":"cast the pintle blanks","status":"open",
       "dependencies":[{"depends_on_id":"slu-1.1","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"slu-1.2","title":"hang the gate","status":"open",
       "dependencies":[{"depends_on_id":"slu-1","type":"parent-child"},
                       {"depends_on_id":"slu-1.1","type":"blocks"}],
       "priority":2,"issue_type":"task"}
    ]"#;

    /// A bead drawn under one it blocks is drawn on a dashed arm, and under
    /// its parent on the solid one every child gets. Otherwise the two copies
    /// are the same row twice, and a reader takes the tree for having
    /// duplicated it.
    ///
    /// The arm is the elbow's, so it holds whether the line rests shut or
    /// open: the fold marker takes the arm's last column exactly as it does
    /// on a child, and the width is the four columns a level every line has.
    #[test]
    fn a_bead_drawn_under_one_it_blocks_hangs_on_a_dashed_arm() {
        let mut forest = flatten(alone("orbital", SLUICE, &panes_on(&["slu-1.1"])));

        assert_eq!(
            sketch(&forest),
            vec![
                "▾ orbital",
                "  └── ◐ slu-1 rehang the sluice",
                "      ├─▸ ◐ .1 forge the new pintles",
                "      └── ○ .2 hang the gate",
                "          └┄▸ ◐ slu-1.1 forge the new pintles",
            ]
        );

        forest.apply(Action::ExpandSubtree);

        assert_eq!(
            sketch(&forest),
            vec![
                "▾ orbital",
                "  └── ◐ slu-1 rehang the sluice",
                "      ├── ◐ .1 forge the new pintles",
                "      │   └── ○ .1 cast the pintle blanks",
                "      └── ○ .2 hang the gate",
                "          └┄┄ ◐ slu-1.1 forge the new pintles",
                "              └── ○ .1 cast the pintle blanks",
            ]
        );
    }

    /// A column of short ids is only readable if a reader can rebuild the
    /// whole one from it: they put what the row above says in front of what
    /// this row says, and stop at a row that reads whole because there is
    /// nothing left to put in front of it. Over every bead these fixtures
    /// draw, that walk gives back the id `bd` holds it under.
    #[test]
    fn walking_up_the_rows_and_joining_the_ids_gives_a_beads_whole_id_back() {
        let fixtures = [
            flatten(snapshot()),
            flatten(tower_staffed(&["tow-1.1.1.1"])),
            flatten(alone("orbital", SLUICE, &panes_on(&["slu-1.1"]))),
            flatten(alone("orbital", RELAY, &two_panes())),
            flatten(alone("orbital", SIDING, &panes_on(&["sdg-4.3"]))),
        ];

        let mut shortened = 0;
        for mut forest in fixtures {
            forest.apply(Action::ExpandSubtree);
            let mut above: Vec<String> = Vec::new();
            for line in forest.lines() {
                let (Some(place), Content::Bead(row)) = (&line.place, &line.content) else {
                    continue;
                };
                above.truncate(place.steps.len());
                let rebuilt = match above.last() {
                    Some(parent) if row.id.starts_with('.') => format!("{parent}{}", row.id),
                    _ => row.id.clone(),
                };

                assert_eq!(rebuilt, place.key().id, "{:#?}", sketch(&forest));

                shortened += usize::from(row.id.starts_with('.'));
                above.push(rebuilt);
            }
        }

        assert!(shortened > 0, "no row was drawn short to walk up from");
    }

    /// Four columns a level, every line in a forest with trees in it,
    /// whatever that line is doing.
    ///
    /// Stated once over whole screens rather than shape by shape. What went
    /// wrong was a span appended to the prefix of one kind of line, and the
    /// next such span will be appended by someone reading a rule about the
    /// kind of line they happen to be drawing.
    ///
    /// The one line outside the rule is the forest with nothing in it, which
    /// stands for the whole screen rather than for a place in a tree and has
    /// no prefix at all.
    #[test]
    fn every_prefix_is_four_columns_a_level() {
        for json in [ORBITAL, DEPOT, RELAY, SIDING, TOWER, BEACON, SLUICE] {
            let staffed = panes_on(&[
                "orb-7.1", "dep-1.1", "rly-2.1", "sdg-4.3", "tow-1.1", "bcn-6", "slu-1.1",
            ]);
            let mut forest = flatten(alone("orbital", json, &staffed));
            four_columns_a_level(&forest);
            forest.apply(Action::ExpandSubtree);
            four_columns_a_level(&forest);
        }
    }

    fn four_columns_a_level(forest: &Forest) {
        for line in forest.lines() {
            assert_eq!(
                columns(&line.prefix),
                2 + 4 * line.depth as usize,
                "a prefix at depth {} is not four columns a level:\n{}",
                line.depth,
                sketch(forest).join("\n")
            );
        }
    }

    /// A root that would not read has nothing under it, so it draws no marker
    /// and holds no fold state either. The two say the same thing about the
    /// same line, and a line offering a fold nothing could act on is how the
    /// marker got there in the first place.
    #[test]
    fn an_unread_root_holds_no_fold_to_set() {
        let forest = flatten(snapshot());
        let header = forest
            .lines()
            .iter()
            .find(|line| matches!(&line.content, Content::Unread(unread) if unread.root == "fer-2"))
            .expect("the shared snapshot draws a tree whose tracker refused");

        assert_eq!(header.folded, None, "{:#?}", sketch(&forest));
        assert_eq!(
            columns(&header.prefix),
            columns(&prefix(&[], true, false, None))
        );
    }

    /// A root that read fine and has nothing under it holds no fold either.
    /// The unread root above takes `draw_tree`'s arm for a tree with no nodes
    /// and never reaches the fold, so this is the only place a bead that is
    /// drawn and has no children is asked whether it offers one.
    ///
    /// The `folded` assertion is the one carrying the weight. A marker is
    /// drawn off `!kids.is_empty() && !open`, which stays false here however
    /// the fold state is decided, so the sketch reads the same whether this
    /// line holds no fold or holds one pointing shut — and a line that holds
    /// one pointing shut is a fold every walk over the forest keeps trying to
    /// open. The screen is where that is invisible, which is why it is asked
    /// of the state instead.
    #[test]
    fn a_root_with_no_children_holds_no_fold_to_set() {
        let forest = flatten(alone("orbital", BEACON, &panes_on(&["bcn-6"])));

        assert_eq!(
            sketch(&forest),
            vec!["▾ orbital", "  └── ◐ bcn-6 re-lamp the beacon"]
        );

        let root = forest
            .lines()
            .iter()
            .find(|line| matches!(&line.content, Content::Bead(row) if row.id == "bcn-6"))
            .expect("the fixture draws its root");

        assert_eq!(root.folded, None, "{:#?}", sketch(&forest));
        assert_eq!(
            columns(&root.prefix),
            columns(&prefix(&[], true, false, None))
        );
    }

    // ---- a forest with nothing in it --------------------------------------

    /// A pane working in a configured project, with no tracker answering for
    /// it, so it reaches the forest as a loose one.
    const WORKING_IN_ORBITAL: &str = r#"{"result":{"agents":[
      {"pane_id":"w:p1","cwd":"/srv/work/orbital","agent_status":"working"}
    ]}}"#;

    /// A pane working in a directory no configured project covers.
    const WORKING_NOWHERE: &str = r#"{"result":{"agents":[
      {"pane_id":"w:pF","cwd":"/srv/spike","agent_status":"idle"}
    ]}}"#;

    fn one_pane(json: &str) -> Vec<Pane> {
        parse_agent_list(A_SESSION, json).expect("the panes parse")
    }

    /// A snapshot built out of exactly what it is handed, with no other
    /// project's trees or panes standing behind it.
    ///
    /// Everything the forest draws a line from arrives through one of these:
    /// the trees and failed projects `Collected` carries, and the panes a
    /// join resolves. Handed one of them alone the forest draws that one
    /// thing, which is what it takes to ask whether anything else is quietly
    /// supplying a line.
    fn only(collected: Collected, panes: &[Pane]) -> Snapshot {
        let cfg = cfg();
        let joined = join::resolve(&[], Listed::all(panes), &cfg);
        snapshot::build(
            Collected {
                read_at: every_project_read(),
                ..collected
            },
            panes,
            &joined,
            &cfg,
            a_provider(ProviderState::Answering),
            Filter::LiveAgents,
            now(),
        )
    }

    fn says_it_holds_nothing(forest: &Forest) -> bool {
        forest
            .lines()
            .iter()
            .any(|line| matches!(line.content, Content::Note(Note::NoRoots)))
    }

    /// The first frame of a run. Nothing has been read, so every project is
    /// drawn from the name the config gave it and holds nothing yet — which
    /// is the point: the reader sees the shape of their work in the time it
    /// takes to draw a frame, rather than a blank terminal for as long as the
    /// trackers take.
    #[test]
    fn a_run_that_has_read_nothing_yet_draws_a_line_for_every_configured_project() {
        let awaiting = Snapshot::awaiting(
            vec!["orbital".to_string(), "ferry".to_string()],
            Vec::new(),
            A_PROVIDER,
            Scope::Everything,
            Filter::LiveAgents,
            now(),
        );

        assert_eq!(sketch(&flatten(awaiting)), vec!["▾ orbital", "▾ ferry"]);
    }

    /// A scope the reader did not type is said on the screen: a reader who
    /// sees one project could think the others vanished. It is the last
    /// line, below the groups, where the hidden trees say what the filter
    /// took away.
    #[test]
    fn a_scope_the_directory_chose_is_said_below_the_groups() {
        let chosen = Snapshot {
            scope: Scope::Directory {
                project: "orbital".to_string(),
                widened: Vec::new(),
            },
            ..built(Filter::LiveAgents)
        };

        let drawn = sketch(&flatten(chosen));

        assert_eq!(
            drawn.last().map(String::as_str),
            Some("  ~ reading orbital")
        );
        let last_group = drawn.iter().rposition(|line| line.contains('['));
        assert!(
            last_group.is_some_and(|at| at + 1 < drawn.len()),
            "the line is not below the groups: {drawn:#?}"
        );
    }

    /// Said from the first frame, before any tracker has answered: the
    /// projects the run is about are on the screen, and so is why.
    #[test]
    fn the_first_frame_already_says_the_directory_chose() {
        let chosen = Snapshot::awaiting(
            vec!["orbital".to_string()],
            Vec::new(),
            A_PROVIDER,
            Scope::Directory {
                project: "orbital".to_string(),
                widened: Vec::new(),
            },
            Filter::LiveAgents,
            now(),
        );

        assert_eq!(
            sketch(&flatten(chosen)),
            vec!["▾ orbital", "  ~ reading orbital"]
        );
    }

    /// Scoping by `--project` is silent because the reader typed it, and a
    /// run reading everything has nothing to say.
    #[test]
    fn a_scope_the_reader_typed_is_silent() {
        for scope in [Scope::Everything, Scope::Asked(vec!["orbital".to_string()])] {
            let awaiting = Snapshot::awaiting(
                vec!["orbital".to_string()],
                Vec::new(),
                A_PROVIDER,
                scope,
                Filter::LiveAgents,
                now(),
            );

            assert_eq!(sketch(&flatten(awaiting)), vec!["▾ orbital"]);
        }
    }

    /// A project whose tracker answered and held nothing draws no line, as it
    /// always has.
    ///
    /// Only a project nothing has read is drawn empty, and `read_at` is the
    /// whole of what tells the two apart. Without it a tracker that answered
    /// with no roots would sit there looking forever about to produce some,
    /// and the forest would never say what it says here instead.
    #[test]
    fn a_project_read_and_holding_nothing_draws_no_line() {
        let read = Snapshot {
            read_at: std::collections::BTreeMap::from([("orbital".to_string(), now())]),
            ..Snapshot::awaiting(
                vec!["orbital".to_string()],
                Vec::new(),
                A_PROVIDER,
                Scope::Everything,
                Filter::LiveAgents,
                now(),
            )
        };

        assert_eq!(sketch(&flatten(read)), vec!["! NoRoots"]);
    }

    /// Every tree a snapshot holds belongs to a project it names.
    ///
    /// The forest walks the projects and takes the trees that follow each
    /// one, so a tree whose project is missing from the list is a tree that
    /// vanishes off the screen with nothing said. Both come from the same
    /// `cfg.projects` inside `build`, which is what makes it true — and this
    /// is what says so, because nothing about the types does.
    #[test]
    fn every_tree_belongs_to_a_project_the_snapshot_names() {
        let snapshot = built(Filter::All);

        for tree in &snapshot.trees {
            assert!(
                snapshot.projects.contains(&tree.project),
                "{} is not among {:?}",
                tree.project,
                snapshot.projects
            );
        }
        // The config's three, and not the fixture's fourth: `lunar` is a
        // failed project no `[[projects]]` entry names, so it is reported
        // among the failures and has no line of its own to be drawn on.
        assert_eq!(snapshot.projects, ["orbital", "ferry", "harbour"]);
    }

    /// Every tracker answered and none of them had a root. The screen has to
    /// carry the reason, because a pane drawn blank reads as a crash.
    #[test]
    fn a_forest_with_nothing_in_it_says_so_rather_than_drawing_nothing() {
        let forest = flatten(only(Collected::default(), &[]));

        assert_eq!(sketch(&forest), vec!["! NoRoots"]);
    }

    /// The fold keys reach a forest that holds nothing, and a walk over it is
    /// given a count of rounds taken from beads there are none of. It has no
    /// fold to point either way, so the screen does not move and still says
    /// what it holds.
    #[test]
    fn the_fold_keys_on_a_forest_with_nothing_in_it_leave_it_saying_so() {
        for action in [Action::ExpandSubtree, Action::CollapseSubtree] {
            let mut forest = flatten(only(Collected::default(), &[]));

            assert!(!forest.apply(action), "{:#?}", sketch(&forest));
            assert_eq!(sketch(&forest), vec!["! NoRoots"]);
        }
    }

    /// Everything that can stand alone in a forest. A conflict is not among
    /// them: a pane can only conflict over a bead a tracker answered for, so
    /// it never arrives without the tree that bead is in.
    #[test]
    fn a_forest_holding_any_one_thing_does_not_say_it_holds_nothing() {
        let cases = [
            (
                "a tree",
                only(
                    Collected {
                        trees: vec![tree_of("orbital", ORBITAL)],
                        failed_projects: Vec::new(),
                        read_at: every_project_read(),
                    },
                    &[],
                ),
            ),
            (
                "a hidden tree",
                only(
                    Collected {
                        trees: vec![tree_of("harbour", HARBOUR)],
                        failed_projects: Vec::new(),
                        read_at: every_project_read(),
                    },
                    &[],
                ),
            ),
            (
                "a failed project",
                only(
                    Collected {
                        trees: Vec::new(),
                        failed_projects: vec![FailedProject {
                            project: "lunar".into(),
                            tracker: TrackerFailure::Unstartable,
                        }],
                        read_at: every_project_read(),
                    },
                    &[],
                ),
            ),
            (
                "a loose pane",
                only(Collected::default(), &one_pane(WORKING_IN_ORBITAL)),
            ),
            (
                "an unconfigured pane",
                only(Collected::default(), &one_pane(WORKING_NOWHERE)),
            ),
        ];

        for (held, snapshot) in cases {
            let forest = flatten(snapshot);

            assert!(
                !forest.lines().is_empty(),
                "a forest holding {held} drew nothing at all"
            );
            assert!(
                !says_it_holds_nothing(&forest),
                "a forest holding {held} said it holds nothing: {:?}",
                sketch(&forest)
            );
        }
    }

    #[test]
    fn a_forest_holding_trees_and_every_group_does_not_say_it_holds_nothing() {
        assert!(!says_it_holds_nothing(&flatten(snapshot())));
    }

    // ---- naming a line rather than stepping to it -------------------------

    #[test]
    fn selecting_a_line_puts_the_selection_on_it() {
        let mut forest = flatten(snapshot());
        let reachable = walk_down(&mut forest);

        for at in reachable {
            assert!(
                forest.select_line(at) || forest.selected_line() == at,
                "line {at} would not take the selection: {:#?}",
                sketch(&forest)
            );
            assert_eq!(forest.selected_line(), at, "{:#?}", sketch(&forest));
        }
    }

    /// The keyboard never rests on a note or an elided run, because every
    /// motion filters through the same predicate. A pointer names one line
    /// and no other, so a line the keyboard cannot rest on takes no selection
    /// from a click either — sliding to the neighbour would select something
    /// the reader did not point at.
    #[test]
    fn selecting_a_line_the_selection_cannot_rest_on_leaves_it_where_it_was() {
        let mut forest = flatten(snapshot());
        let unreachable: Vec<usize> = (0..forest.lines().len())
            .filter(|at| !selectable(&forest.lines()[*at]))
            .collect();

        assert!(!unreachable.is_empty(), "{:#?}", sketch(&forest));
        for at in unreachable {
            forest.apply(Action::Move(Motion::FirstRow));
            let was = forest.selected_line();

            assert!(
                !forest.select_line(at),
                "line {at} took the selection: {:#?}",
                sketch(&forest)
            );
            assert_eq!(forest.selected_line(), was);
        }
    }

    #[test]
    fn selecting_a_line_that_is_not_drawn_leaves_the_selection_where_it_was() {
        let mut forest = flatten(snapshot());
        forest.apply(Action::Move(Motion::FirstRow));

        assert!(!forest.select_line(forest.lines().len()));
        assert!(!forest.select_line(usize::MAX));
        assert_eq!(forest.selected_line(), 0);
    }

    #[test]
    fn selecting_the_line_already_selected_changes_nothing() {
        let mut forest = flatten(snapshot());
        forest.apply(Action::Move(Motion::FirstRow));
        let at = forest.selected_line();

        assert!(!forest.select_line(at));
        assert_eq!(forest.selected_line(), at);
    }

    /// A bead reachable from two roots is drawn under each, so a click names
    /// one of two rows carrying the same handle. The refresh that follows
    /// re-derives the selection from that handle, and has to settle on the
    /// copy the pointer landed on rather than on its twin higher up.
    #[test]
    fn selecting_the_lower_copy_of_a_twin_keeps_the_selection_on_it_across_a_refresh() {
        let panes = panes_on(&["qua-1.2", "wha-2.1"]);
        let mut forest = flatten(overlapping(&panes));
        let copies = lines_of(&forest, "qua-1.2");

        assert_eq!(copies.len(), 2, "{:#?}", sketch(&forest));
        let lower = copies[1];

        assert!(forest.select_line(lower), "{:#?}", sketch(&forest));
        forest.refresh(overlapping(&panes));

        assert_eq!(forest.selected_line(), lower, "{:#?}", sketch(&forest));
    }

    // ---- expand all, collapse all, and back to the default ---------------

    /// Every bead on screen, by id, in render order. A bead reachable more
    /// than once is here once per copy drawn.
    fn drawn_beads(forest: &Forest) -> Vec<String> {
        forest
            .lines()
            .iter()
            .filter_map(|line| line.bead().map(|key| key.id.clone()))
            .collect()
    }

    /// Opening a node draws children that were not there to be enumerated
    /// when the key was pressed, so one pass over the lines stops at the
    /// first level it opened. Tower is a spine four deep with nothing live
    /// in it, so every level below the header is a fold no reader could see.
    #[test]
    fn expanding_reaches_a_fold_that_was_not_drawn_when_it_was_pressed() {
        let mut forest = flatten(tower_staffed(&[]));
        assert_eq!(drawn_beads(&forest), ["tow-1"], "{:#?}", sketch(&forest));

        forest.apply(Action::ExpandSubtree);

        assert_eq!(
            drawn_beads(&forest),
            [
                "tow-1",
                "tow-1.1",
                "tow-1.1.1",
                "tow-1.1.1.1",
                "tow-1.2",
                "tow-1.2.1"
            ],
            "{:#?}",
            sketch(&forest)
        );
    }

    /// A walk that runs out of rounds leaves the folds it never reached, so a
    /// subtree that will not settle disagrees with the key that was pressed
    /// instead of never coming back. Tower is a spine four deep, and one
    /// round reaches the level it drew and no further.
    #[test]
    fn a_walk_out_of_rounds_leaves_the_folds_it_did_not_reach() {
        let mut forest = flatten(tower_staffed(&[]));
        assert_eq!(drawn_beads(&forest), ["tow-1"], "{:#?}", sketch(&forest));
        let scope = forest.handle_at(forest.selected).expect("a selected line");

        forest.fold_subtree_in(&scope, 1, true);
        forest.lay_out();

        assert_eq!(
            drawn_beads(&forest),
            ["tow-1", "tow-1.1", "tow-1.2"],
            "{:#?}",
            sketch(&forest)
        );
    }

    /// The lines the selection stands over, and itself: everything from it to
    /// the first line drawn at its own depth or shallower.
    ///
    /// Read off the screen rather than asked of the forest, so a walk that
    /// pointed the folds of the wrong lines is answered by the drawing and
    /// not by the same reckoning that misplaced them.
    fn from_the_selection_down(forest: &Forest) -> impl Iterator<Item = &Line> {
        let at = forest.selected_line();
        let depth = forest.lines()[at].depth;
        forest.lines()[at..].iter().take(1).chain(
            forest.lines()[at + 1..]
                .iter()
                .take_while(move |line| line.depth > depth),
        )
    }

    /// Six shapes of tree, each of them the one tree of its project, so the
    /// root the selection opens on stands over every fold that tree has.
    #[test]
    fn expanding_from_a_root_leaves_no_fold_shut_under_it() {
        for json in [ORBITAL, DEPOT, RELAY, SIDING, TOWER, BEACON] {
            let mut forest = flatten(alone("orbital", json, &two_panes()));
            forest.apply(Action::ExpandSubtree);

            assert!(
                from_the_selection_down(&forest).all(|line| line.folded != Some(false)),
                "{:#?}",
                sketch(&forest)
            );
        }
    }

    /// The mirror, and the project's own line is what says where the scope
    /// stopped: `C` shuts the root it was pressed on and everything that root
    /// stands over, and leaves the project above it as the reader had it.
    #[test]
    fn collapsing_from_a_root_shuts_it_and_leaves_the_project_above_it_open() {
        for json in [ORBITAL, DEPOT, RELAY, SIDING, TOWER, BEACON] {
            let mut forest = flatten(alone("orbital", json, &two_panes()));
            forest.apply(Action::CollapseSubtree);

            assert!(
                from_the_selection_down(&forest).all(|line| line.folded != Some(true)),
                "{:#?}",
                sketch(&forest)
            );
            assert_eq!(
                forest.lines()[0].folded,
                Some(true),
                "{:#?}",
                sketch(&forest)
            );
        }
    }

    /// A run is the one line whose fold draws lines that are not its own
    /// children by any other reckoning, so it is the one where opening the
    /// scope could plausibly lose it. It does not: the run keeps its line
    /// when it opens, and the beads it stood for hang a level under it.
    #[test]
    fn a_run_keeps_its_scope_through_being_opened_and_shut_again() {
        let mut forest = flatten(snapshot());
        select_run(&mut forest);
        let shut = drawn_beads(&forest);

        assert!(
            forest.apply(Action::ExpandSubtree),
            "{:#?}",
            sketch(&forest)
        );
        let opened = drawn_beads(&forest);
        assert!(
            opened.len() > shut.len(),
            "the run drew nothing when it opened: {:#?}",
            sketch(&forest)
        );
        assert!(
            matches!(
                forest.lines()[forest.selected_line()].content,
                Content::Elided { .. }
            ),
            "the selection came off the run: {:#?}",
            sketch(&forest)
        );

        assert!(
            forest.apply(Action::CollapseSubtree),
            "{:#?}",
            sketch(&forest)
        );

        assert_eq!(drawn_beads(&forest), shut, "{:#?}", sketch(&forest));
    }

    /// A project's line takes the scope as a bead's does, and a project is
    /// the widest thing a reader can press these keys on. The others keep
    /// what they had, which is what a reader who navigated to one project is
    /// asking for.
    #[test]
    fn collapsing_from_a_project_leaves_the_other_projects_where_they_were() {
        let mut forest = flatten(built(Filter::All));
        forest.apply(Action::ExpandSubtree);
        select_project(&mut forest, "orbital");
        let elsewhere: Vec<String> = drawn_beads(&forest)
            .into_iter()
            .filter(|id| !id.starts_with("orb-"))
            .collect();
        assert!(
            !elsewhere.is_empty(),
            "nothing outside orbital to be left alone: {:#?}",
            sketch(&forest)
        );

        forest.apply(Action::CollapseSubtree);

        assert_eq!(
            drawn_beads(&forest)
                .into_iter()
                .filter(|id| !id.starts_with("orb-"))
                .collect::<Vec<_>>(),
            elsewhere,
            "{:#?}",
            sketch(&forest)
        );
        assert!(
            !drawn_beads(&forest).iter().any(|id| id.starts_with("orb-")),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// Put the selection on a project's own line, the way a reader would with
    /// the keys they have.
    fn select_project(forest: &mut Forest, project: &str) {
        let at = forest
            .lines()
            .iter()
            .position(
                |line| matches!(&line.content, Content::Project(line) if line.project == project),
            )
            .unwrap_or_else(|| panic!("{project} is not drawn: {:#?}", sketch(forest)));
        step_onto(forest, at);
    }

    /// Put the selection on a bead and fold it, the way a reader would with
    /// the keys they have.
    fn select_bead(forest: &mut Forest, id: &str) {
        let at = *lines_of(forest, id)
            .first()
            .unwrap_or_else(|| panic!("{id} is not drawn: {:#?}", sketch(forest)));
        step_onto(forest, at);
    }

    fn toggle_fold_of(forest: &mut Forest, id: &str) {
        select_bead(forest, id);
        forest.apply(Action::ToggleFold);
    }

    /// `E` folds from the selected node, so a sibling subtree keeps whatever
    /// the reader left it at. `tow-1.2` is shut here and stays shut, which is
    /// the assertion that tells a scoped fold from a global one.
    ///
    /// The scope is a `Handle`, and a handle names the way down to a line
    /// rather than the bead standing on it, so exactly one line carries it —
    /// which is what stops a fold set inside the window from also reaching a
    /// second copy of that bead outside it.
    #[test]
    fn expanding_from_a_node_leaves_a_sibling_subtree_where_it_was() {
        let mut forest = flatten(tower_staffed(&[]));
        toggle_fold_of(&mut forest, "tow-1");
        select_bead(&mut forest, "tow-1.1");

        forest.apply(Action::ExpandSubtree);

        assert_eq!(
            drawn_beads(&forest),
            ["tow-1", "tow-1.1", "tow-1.1.1", "tow-1.1.1.1", "tow-1.2"],
            "{:#?}",
            sketch(&forest)
        );
    }

    /// `C` the same way round: `tow-1.1` shuts over its subtree, `tow-1.2`
    /// keeps the one the reader opened, and the node the selection sits on
    /// is shut rather than left open over shut children.
    #[test]
    fn collapsing_from_a_node_leaves_a_sibling_subtree_where_it_was() {
        let mut forest = flatten(tower_staffed(&[]));
        forest.apply(Action::ExpandSubtree);
        select_bead(&mut forest, "tow-1.1");

        forest.apply(Action::CollapseSubtree);

        assert_eq!(
            drawn_beads(&forest),
            ["tow-1", "tow-1.1", "tow-1.2", "tow-1.2.1"],
            "{:#?}",
            sketch(&forest)
        );
    }

    /// Collapsing opens the subtree first, so that every fold in it lands on
    /// a drawn line and one pass can shut them all. That opening walk is
    /// scoped too: a sibling the reader left shut is not thrown open on the
    /// way past and shut again a frame later.
    ///
    /// `tow-1.2` rests shut here and is never selected, so a walk that opened
    /// the forest and narrowed only the shutting pass would leave `tow-1.2.1`
    /// on screen.
    #[test]
    fn collapsing_from_a_node_does_not_open_a_sibling_on_the_way() {
        let mut forest = flatten(tower_staffed(&[]));
        toggle_fold_of(&mut forest, "tow-1");
        toggle_fold_of(&mut forest, "tow-1.1");
        select_bead(&mut forest, "tow-1.1");

        forest.apply(Action::CollapseSubtree);

        assert_eq!(
            drawn_beads(&forest),
            ["tow-1", "tow-1.1", "tow-1.2"],
            "{:#?}",
            sketch(&forest)
        );
    }

    /// `E` on a shut node opens the node itself and not only what hangs
    /// beneath it, which is the ordinary case for `E`: a key that opened only
    /// the children of a node the reader cannot see inside would leave the
    /// screen exactly as it found it.
    #[test]
    fn expanding_from_a_shut_node_opens_that_node_too() {
        let mut forest = flatten(tower_staffed(&[]));
        toggle_fold_of(&mut forest, "tow-1");
        select_bead(&mut forest, "tow-1.2");
        assert_eq!(
            forest.fold_at(forest.selected_line()),
            Some(false),
            "the node this is about has to start shut: {:#?}",
            sketch(&forest)
        );

        assert!(
            forest.apply(Action::ExpandSubtree),
            "{:#?}",
            sketch(&forest)
        );

        assert_eq!(
            drawn_beads(&forest),
            ["tow-1", "tow-1.1", "tow-1.2", "tow-1.2.1"],
            "{:#?}",
            sketch(&forest)
        );
    }

    /// A row carrying no fold has nothing drawn beneath it — a note, an
    /// unread root, a thing in a group and a leaf bead are all of them — so
    /// the scope taken from such a row is the row alone, and both keys find
    /// nothing to point. The screen does not move and nothing is said.
    ///
    /// The implication runs one way only. A fold with nothing under it is
    /// ordinary: a project waiting on its first collection draws a header
    /// that folds over no trees at all.
    #[test]
    fn the_fold_keys_on_a_row_with_no_fold_leave_the_screen_where_it_was() {
        for action in [Action::ExpandSubtree, Action::CollapseSubtree] {
            let mut forest = flatten(tower_staffed(&[]));
            forest.apply(Action::ExpandSubtree);
            select_bead(&mut forest, "tow-1.1.1.1");
            assert_eq!(
                forest.fold_at(forest.selected_line()),
                None,
                "the row this is about has to carry no fold: {:#?}",
                sketch(&forest)
            );
            let before = sketch(&forest);

            assert!(!forest.apply(action), "{action:?}: {:#?}", sketch(&forest));

            assert_eq!(sketch(&forest), before, "{action:?}");
        }
    }

    /// A fold shut over another fold hides it without settling it, so
    /// shutting only what is on screen leaves that one resting open. The
    /// reader then opens their way back down and a subtree springs at them
    /// from a forest they were told was collapsed.
    ///
    /// `tow-1.1` is shut by hand first, which puts `tow-1.1.1` out of sight
    /// still resting open over the agent beneath it. `C` from the root above
    /// has to reach it there.
    #[test]
    fn collapsing_shuts_a_fold_the_reader_cannot_see() {
        let mut forest = flatten(tower_staffed(&["tow-1.1.1.1"]));
        toggle_fold_of(&mut forest, "tow-1.1");
        select_bead(&mut forest, "tow-1");

        forest.apply(Action::CollapseSubtree);
        toggle_fold_of(&mut forest, "tow-1");
        toggle_fold_of(&mut forest, "tow-1.1");

        assert_eq!(
            drawn_beads(&forest),
            ["tow-1", "tow-1.1", "tow-1.1.1", "tow-1.2"],
            "{:#?}",
            sketch(&forest)
        );
    }

    /// The default is derived from what is live rather than stored, so
    /// restoring it after an agent has gone home opens the spine to the work
    /// that is left and not to where the work was.
    ///
    /// The agent on `tow-1.1.1.1` goes and the one on `tow-1.2.1` stays, so
    /// nothing new arrives under any fold and every fold collapse-all set
    /// survives the refresh. What is restored is therefore the whole of what
    /// the key did, and not something the refresh had already undone.
    #[test]
    fn restoring_the_default_recomputes_it_rather_than_replaying_the_old_one() {
        let mut forest = flatten(tower_staffed(&["tow-1.1.1.1", "tow-1.2.1"]));
        forest.apply(Action::CollapseSubtree);
        forest.refresh(tower_staffed(&["tow-1.2.1"]));

        forest.apply(Action::RestoreDefault);

        assert_eq!(
            sketch(&forest),
            sketch(&flatten(tower_staffed(&["tow-1.2.1"])))
        );
    }

    /// A fold these keys set is a fold the user set, so it keeps the standing
    /// rule: it survives a refresh that brings nothing new beneath it.
    #[test]
    fn the_folds_these_keys_set_survive_a_refresh() {
        for action in [Action::ExpandSubtree, Action::CollapseSubtree] {
            let mut forest = flatten(tower_staffed(&["tow-1.1.1.1"]));
            forest.apply(action);
            let before = sketch(&forest);

            forest.refresh(tower_staffed(&["tow-1.1.1.1"]));

            assert_eq!(sketch(&forest), before, "{action:?}");
        }
    }

    /// No fold `bdi` chooses hides a live agent. `C` is the one place a
    /// reader may override that, because they asked for it by name — and
    /// restoring the default is how they get the agent back.
    #[test]
    fn collapsing_may_shut_a_fold_over_a_live_agent_because_the_reader_asked() {
        let mut forest = flatten(tower_staffed(&["tow-1.1.1.1"]));
        let staffed = "tow-1.1.1.1".to_string();
        assert!(
            drawn_beads(&forest).contains(&staffed),
            "{:#?}",
            sketch(&forest)
        );

        forest.apply(Action::CollapseSubtree);
        assert!(
            !drawn_beads(&forest).contains(&staffed),
            "{:#?}",
            sketch(&forest)
        );

        forest.apply(Action::RestoreDefault);
        assert!(
            drawn_beads(&forest).contains(&staffed),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// These three keys are about folds. Which trees are drawn at all is the
    /// filter's, with its own key and its own word for what it does, so a
    /// reader who pressed `a` deliberately does not lose it to a fold key.
    #[test]
    fn the_fold_keys_leave_the_filter_where_the_reader_put_it() {
        for action in [
            Action::ExpandSubtree,
            Action::CollapseSubtree,
            Action::RestoreDefault,
        ] {
            let mut forest = flatten(built(Filter::LiveAgents));
            forest.apply(Action::ToggleFilter);

            forest.apply(action);

            assert_eq!(forest.snapshot().filter, Filter::All, "{action:?}");
        }
    }

    /// The filter is the reader's too, and a collection landing under them is
    /// not them changing their mind. The one line that offers the key is the
    /// hidden-trees group header, so a refresh that puts the filter back reads
    /// on screen as that group shutting itself.
    #[test]
    fn a_refresh_leaves_the_filter_where_the_reader_put_it() {
        let mut forest = flatten(built(Filter::LiveAgents));
        forest.apply(Action::ToggleFilter);
        let before = sketch(&forest);

        forest.refresh(built(Filter::LiveAgents));

        assert_eq!(forest.snapshot().filter, Filter::All);
        assert_eq!(sketch(&forest), before);
    }

    /// `apply` reports whether the screen moved, and a subtree already open
    /// has nowhere to go. The loop redraws on that answer.
    #[test]
    fn expanding_from_a_node_already_open_moves_nothing() {
        let mut forest = flatten(tower_staffed(&[]));

        assert!(
            forest.apply(Action::ExpandSubtree),
            "{:#?}",
            sketch(&forest)
        );
        assert!(
            !forest.apply(Action::ExpandSubtree),
            "{:#?}",
            sketch(&forest)
        );
    }

    // ---- going to a bead the reader has not walked to --------------------

    /// The forest can say where the selection is, as a place: a bead drawn
    /// under two parents is drawn twice, and a caller keeping this to come
    /// back to is keeping the copy the reader was looking at.
    #[test]
    fn the_forest_says_where_the_selection_is() {
        let forest = flatten(snapshot());

        assert_eq!(
            forest.place().map(|place| place.key().clone()),
            Some(key("orbital", "orb-7"))
        );
    }

    /// Nothing where the selection is not on a bead at all, which is a line
    /// with nowhere to come back to rather than a line with no name.
    #[test]
    fn a_line_that_is_not_a_bead_is_nowhere_to_come_back_to() {
        let mut forest = flatten(snapshot());
        forest.apply(Action::Move(Motion::FirstRow));

        assert_eq!(forest.place(), None, "{:#?}", sketch(&forest));
    }

    /// A bead the trees hold is one the forest can go to, whether or not it
    /// is drawn this instant; one no tree holds is not. The question is asked
    /// of the snapshot, so it goes on being the same question when roots are
    /// found another way.
    #[test]
    fn the_forest_draws_the_beads_its_trees_hold_and_no_others() {
        let forest = flatten(snapshot());

        assert!(forest.draws(&key("orbital", "orb-7.1.1")));
        assert!(!forest.draws(&key("orbital", "orb-404")));
        assert!(
            !forest.draws(&key("ferry", "orb-7")),
            "a bead is (project, id), so one project's id is not another's"
        );
    }

    /// The whole point: `orb-7.1` is drawn shut, so `orb-7.1.1` is on no line
    /// at all. Going to it opens what is over it and lands on it.
    #[test]
    fn going_to_a_bead_under_a_shut_fold_opens_it_and_lands_there() {
        let mut forest = flatten(snapshot());
        assert!(
            !drawn_here(&forest, "true the mount"),
            "the bead is drawn already, so this would test nothing: {:#?}",
            sketch(&forest)
        );

        assert!(forest.go_to(&key("orbital", "orb-7.1.1")));

        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1.1")));
        assert!(
            drawn_here(&forest, "true the mount"),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// A tree the filter took out of the forest is drawn in the group below
    /// its project, and that group has a fold of its own. Both open, and the
    /// project's with them.
    #[test]
    fn going_to_a_bead_in_a_tree_the_filter_hid_opens_the_group_over_it() {
        let mut forest = flatten(snapshot());

        assert!(forest.go_to(&key("harbour", "hbr-3.1")));

        assert_eq!(cursor(&forest), Some(&key("harbour", "hbr-3.1")));
    }

    /// A fold the reader shut by hand stays shut until something asks
    /// otherwise, and asking to be taken to a bead underneath it is asking.
    #[test]
    fn going_to_a_bead_opens_a_fold_the_reader_shut_by_hand() {
        let mut forest = flatten(snapshot());
        forest.go_to(&key("orbital", "orb-7.1"));
        forest.apply(Action::CollapseSubtree);
        assert!(
            !drawn_here(&forest, "true the mount"),
            "{:#?}",
            sketch(&forest)
        );

        assert!(forest.go_to(&key("orbital", "orb-7.1.1")));

        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1.1")));
    }

    /// A bead no tree holds is nowhere to go, and the forest is left exactly
    /// as it was rather than half-opened on the way to nothing.
    #[test]
    fn going_to_a_bead_no_tree_holds_moves_nothing() {
        let mut forest = flatten(snapshot());
        let was = sketch(&forest);
        let selected = forest.selected_line();

        assert!(!forest.go_to(&key("orbital", "orb-404")));

        assert_eq!(sketch(&forest), was);
        assert_eq!(forest.selected_line(), selected);
    }

    /// A bead drawn under two parents is two lines, and coming back means the
    /// one the reader was on. A key could not say which; a place does.
    #[test]
    fn coming_back_to_a_place_lands_on_the_copy_that_was_left() {
        let mut forest = flatten(drawn_twice_in_one_tree());
        forest.apply(Action::ExpandSubtree);
        let twice: Vec<Place> = forest
            .lines()
            .iter()
            .filter_map(|line| line.place.clone())
            .filter(|place| *place.key() == key("orbital", "orb-9.1"))
            .collect();
        assert_eq!(
            twice.len(),
            2,
            "the fixture draws it twice: {:#?}",
            sketch(&forest)
        );

        forest.apply(Action::Move(Motion::FirstRow));
        assert!(forest.go_to_place(&twice[1]));

        assert_eq!(forest.place(), Some(&twice[1]));
        assert_ne!(forest.place(), Some(&twice[0]), "the other copy of it");
    }

    /// The reader types what they have, and what they have is a fragment:
    /// part of an id, a word out of a title, or a whole id copied with `y`.
    /// A bead holding it in either field is a match.
    #[test]
    fn a_search_matches_part_of_an_id() {
        let mut forest = flatten(snapshot());

        assert_eq!(forest.seek("7.1.1"), went_to("orbital", "orb-7.1.1", 1, 1));

        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1.1")));
        assert!(
            drawn_here(&forest, "true the mount"),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// The forest row is the one place `bdi` ever prints a shortened id —
    /// `row::abbreviate` has no other caller — so on a long screen the short
    /// id is the only spelling the reader has been shown, and what they type
    /// has to reach the bead they read it off. The query is taken from the row
    /// rather than written out here, because a search matches on the whole id
    /// and a query spelled by hand would pass on that alone.
    ///
    /// A substring is what reaches it: the drawn form is a prefix of nothing.
    #[test]
    fn a_search_matches_the_shortened_id_the_row_draws() {
        let mut forest = flatten(snapshot());
        let drawn = row_of(&forest, "orb-7.1").id.clone();

        assert_eq!(forest.seek(&drawn), went_to("orbital", "orb-7.1", 1, 4));
    }

    #[test]
    fn a_search_matches_part_of_a_title() {
        let mut forest = flatten(snapshot());

        assert_eq!(forest.seek("mount"), went_to("orbital", "orb-7.1.1", 1, 1));
    }

    /// A title is prose and the reader is retyping a word they read off a
    /// row, so the capitals the row happened to carry are not theirs to
    /// reproduce.
    #[test]
    fn a_search_ignores_letter_case() {
        let mut forest = flatten(snapshot());

        assert_eq!(forest.seek("MoUnT"), went_to("orbital", "orb-7.1.1", 1, 1));
    }

    /// Matches are numbered in the order the forest draws them, which is the
    /// order a reader scrolling would have met them — `place_of` names the
    /// same doctrine for a single jump. So the ordinal is a fact about the
    /// forest, and a reader who doubts it can count it off the screen.
    #[test]
    fn matches_are_numbered_in_the_order_the_forest_draws_them() {
        let mut forest = flatten(snapshot());

        assert_eq!(forest.seek("7.1"), went_to("orbital", "orb-7.1", 1, 3));
        assert_eq!(
            forest.next_match(true),
            Some(went_to("orbital", "orb-7.1.1", 2, 3))
        );
        assert_eq!(
            forest.next_match(true),
            Some(went_to("orbital", "orb-7.1.2", 3, 3))
        );
    }

    /// Stepping past the last comes round to the first, so a reader walking
    /// the set is never stopped at an end they cannot see.
    #[test]
    fn stepping_past_the_last_match_comes_round_to_the_first() {
        let mut forest = flatten(snapshot());
        forest.seek("7.1");
        forest.next_match(true);
        forest.next_match(true);

        assert_eq!(
            forest.next_match(true),
            Some(went_to("orbital", "orb-7.1", 1, 3))
        );
    }

    #[test]
    fn stepping_back_walks_the_matches_the_other_way() {
        let mut forest = flatten(snapshot());
        forest.seek("7.1");

        assert_eq!(
            forest.next_match(false),
            Some(went_to("orbital", "orb-7.1.2", 3, 3))
        );
    }

    /// Stepping asks where the selection is now rather than where the last
    /// step left it, so a reader who has moved by hand between presses
    /// carries on from where they are standing.
    #[test]
    fn stepping_carries_on_from_where_the_reader_has_moved_to() {
        let mut forest = flatten(snapshot());
        forest.seek("7.1");
        assert!(forest.go_to(&key("orbital", "orb-7.1.1")));

        assert_eq!(
            forest.next_match(true),
            Some(went_to("orbital", "orb-7.1.2", 3, 3))
        );
    }

    /// A whole id lands on its own bead however many rows above it match. An
    /// id is the one thing the reader can have meant exactly, and that is
    /// what `bdi-2bb.37` shipped — a substring match that let a row merely
    /// titled after a bead shadow the bead would take it back.
    ///
    /// The numbering is untouched by it: `orb-6.1` is drawn first and holds
    /// the id in its title, so the bead landed on is the second of two. The
    /// landing is the only thing the whole id decides.
    #[test]
    fn a_whole_id_lands_on_its_own_bead_however_many_rows_above_it_match() {
        let mut forest = flatten(alone("orbital", NAMED_IN_A_TITLE, &[]));

        assert_eq!(forest.seek("orb-6.2"), went_to("orbital", "orb-6.2", 2, 2));

        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-6.2")));
    }

    /// A bead reachable more than once is drawn more than once and matched
    /// once, at the first way down to it: the copy a reader scanning the
    /// screen would have found, which is the rule `place_of` already keeps
    /// for a single jump.
    #[test]
    fn a_bead_drawn_twice_is_one_match() {
        let mut forest = flatten(drawn_twice_in_one_tree());

        // `orb-9` is drawn under `orb-8.1` and again under `orb-8.2`, and
        // `orb-9.1` holds the same characters. Three lines, two matches.
        assert_eq!(forest.seek("orb-9"), went_to("orbital", "orb-9", 1, 2));
        assert_eq!(
            forest.next_match(true),
            Some(went_to("orbital", "orb-9.1", 2, 2))
        );
    }

    /// A tree the filter hid is drawn in its project's hidden-trees group
    /// rather than taken off the screen, so a bead the filter hid is one a
    /// search still reaches — after the shown ones, which is the order
    /// `place_of` already documents.
    #[test]
    fn a_bead_the_filter_hid_is_one_a_search_still_reaches() {
        let mut forest = flatten(snapshot());

        assert_eq!(forest.seek("hbr-3.1"), went_to("harbour", "hbr-3.1", 1, 1));

        assert_eq!(cursor(&forest), Some(&key("harbour", "hbr-3.1")));
    }

    /// Nothing matching is nowhere to go, and the forest is left exactly as
    /// it was rather than half-opened on the way to nothing.
    #[test]
    fn a_search_matching_nothing_leaves_the_forest_as_it_was() {
        let mut forest = flatten(snapshot());
        let was = sketch(&forest);
        let selected = forest.selected_line();

        assert_eq!(forest.seek("orb-404"), Landed::Nowhere("orb-404".into()));

        assert_eq!(sketch(&forest), was);
        assert_eq!(forest.selected_line(), selected);
    }

    /// Bead prefixes are per-tracker and uncoordinated, so one id can name a
    /// bead in more than one project. That is two matches now rather than one
    /// landing and a sentence about the other: the reader steps to the second
    /// and looks at it, instead of being told about a bead they cannot see.
    #[test]
    fn one_id_two_trackers_hold_is_two_matches() {
        let mut forest = flatten(two_trackers_holding_one_id());

        assert_eq!(
            forest.seek("orb-7.1.1"),
            went_to("orbital", "orb-7.1.1", 1, 2)
        );
        assert_eq!(
            forest.next_match(true),
            Some(went_to("ferry", "orb-7.1.1", 2, 2))
        );
    }

    /// A reader can rest on a row that is not a bead — a project's own line,
    /// a group, a pane in one — and stepping from there carries on from where
    /// they are, rather than starting the walk again at the top.
    ///
    /// The row has to have matches *above* it or the question cannot be
    /// asked: from the top of the forest, carrying on and starting again are
    /// the same answer, and a test taken there passes whichever the code
    /// does. So the walk stops on the second project's own line, which is
    /// drawn below every bead of the first.
    ///
    /// Both projects read a tracker using the same prefix, so every bead
    /// matches once in each. From `ferry`'s line, carrying on reaches
    /// `ferry`'s first bead — and starting again would reach `orbital`'s,
    /// which is what this used to do.
    ///
    /// **The match asked for is the anchor itself, which is the one position
    /// that says where the boundary sits.** The bead below the row counts as
    /// *after* it, because the reader is above that bead rather than on it —
    /// so `ferry`'s root is a match the walk should reach, not one it should
    /// step over. Ask for a match further down and the two readings return
    /// the same bead and this proves only that the anchor was consulted:
    /// `orb-7.1.1` was the first thing tried here and it could not tell them
    /// apart, because the root is drawn above it.
    ///
    /// **The anchor is the first bead drawn below the selection, so a row
    /// with none below it has nothing to carry on from and the walk comes
    /// round.**
    #[test]
    fn stepping_from_a_row_that_is_not_a_bead_carries_on_from_there() {
        let mut forest = flatten(two_trackers_holding_one_id());
        forest.seek("orb-7");
        walk::until(
            &mut forest,
            |forest| {
                matches!(
                    &forest.lines()[forest.selected_line()].content,
                    Content::Project(line) if line.project == "ferry"
                )
            },
            |forest| {
                forest.apply(Action::Move(Motion::NextRow));
            },
            |forest| format!("no second project line to rest on: {:#?}", sketch(forest)),
        );

        assert_eq!(
            forest.next_match(true),
            Some(went_to("ferry", "orb-7", 10, 18)),
            "stepping from the project line either started the walk again \
             or stepped over the bead the reader is standing above"
        );
    }

    /// One project holding a tree the filter draws and a tree it hides, with
    /// six matches for `"the"` in the first and two in the second.
    ///
    /// The two blocks are separated by exactly one row — the group's own
    /// line — so a walk anchored anywhere but inside the group answers with a
    /// bead from the other block, whichever way it steps.
    fn a_group_shut_over_matches() -> Snapshot {
        let mut staffed = together("orbital", &[TOWER, HARBOUR], &panes_on(&["tow-1.1"]));
        staffed.refilter(Filter::LiveAgents);
        staffed
    }

    /// Rest the selection on the hidden-trees group with the group shut, and
    /// say which line that is.
    ///
    /// The fold is asserted rather than assumed. A group drawn open draws its
    /// beads on lines below it, and the walk reads its anchor off those — so
    /// a fixture that drifted open would take the path these tests are not
    /// about and pass without exercising anything.
    fn rest_on_the_shut_group(forest: &mut Forest) {
        let at = forest
            .lines()
            .iter()
            .position(|line| {
                matches!(&line.content, Content::Group(group) if group.kind == GroupKind::HiddenTrees)
            })
            .expect("the hidden-trees group is drawn");
        assert_eq!(
            forest.lines()[at].folded,
            Some(false),
            "the group is drawn open, so its beads are on lines of their own: {:#?}",
            sketch(forest)
        );
        forest.select_line(at);
        assert!(on_the_hidden_trees_group(forest), "{:#?}", sketch(forest));
    }

    /// A group resting shut hides beads that are still in the search's order,
    /// so a reader standing on its line is standing above them and stepping
    /// on reaches them rather than the block beyond.
    ///
    /// `hbr-3` is the first of them and the one match that tells the two
    /// readings apart: the beads above the group are the six the drawn lines
    /// would anchor on, and the come-round would answer with the first of
    /// those. Ask for a match further inside the group and both wrong answers
    /// still land outside it, but so would an anchor one bead off.
    ///
    /// **Anchoring on the lines below has two answers and this pair sees only
    /// one of them.** Nothing bead-bearing is drawn below the group here, so
    /// there is no anchor to find and the walk comes round. A screen with
    /// another project under the group gives the other answer — an anchor on
    /// a bead drawn *after* everything the group hides, which steps over all
    /// of it — and these two tests would be red for that as well without
    /// telling it from the come-round. Adding a project below this fixture
    /// would not separate them.
    #[test]
    fn stepping_from_a_shut_group_goes_into_the_matches_it_hides() {
        let mut forest = flatten(a_group_shut_over_matches());
        forest.seek("the");
        rest_on_the_shut_group(&mut forest);

        assert_eq!(
            forest.next_match(true),
            Some(went_to("orbital", "hbr-3", 7, 8)),
            "stepping on from the shut group left the beads it hides behind: {:#?}",
            sketch(&forest)
        );
    }

    /// And stepping back from it reaches the match above the group rather
    /// than coming round to the last one inside it, which is the bead the
    /// reader would have to walk the whole screen to get back from.
    #[test]
    fn stepping_back_from_a_shut_group_reaches_the_match_above_it() {
        let mut forest = flatten(a_group_shut_over_matches());
        forest.seek("the");
        rest_on_the_shut_group(&mut forest);

        assert_eq!(
            forest.next_match(false),
            Some(went_to("orbital", "tow-1.2.1", 6, 8)),
            "stepping back from the shut group came round instead: {:#?}",
            sketch(&forest)
        );
    }

    /// Stepping before anything has been searched for has nothing to step
    /// through, which is not a failure: nothing has gone wrong, nothing
    /// moves, and there is nothing to say about it.
    #[test]
    fn stepping_before_a_search_has_nothing_to_step_through() {
        let mut forest = flatten(snapshot());
        let was = sketch(&forest);

        assert_eq!(forest.next_match(true), None);

        assert_eq!(sketch(&forest), was);
    }

    /// Going to a bead a tree reaches twice lands on the copy the screen
    /// draws first, which is not the copy its siblings sort first.
    ///
    /// `twn-9` hangs under `twn-1.1` and again under `twn-1.4`. All four of
    /// `twn-1`'s children are closed, so the sort puts `.1` above `.4`; but
    /// `.4` has a pane working it, so it is not a *finished* branch, and the
    /// screen draws it above the run that `.1`, `.2` and `.3` collapse into.
    /// The copy under `.4` is on screen; the copy under `.1` is inside a shut
    /// run.
    ///
    /// This is `Forest::go_to`, which is every jump: the search's landing and
    /// Enter on a reference in the bead window both come through here. Taking
    /// the reader into a run when a drawn copy of the same bead was above it
    /// is the wrong one either way — and until this, nothing said so.
    ///
    /// **The three quiet children are the run, not three of them.** `MANY` is
    /// the fewest finished siblings that make one, and below it `split_by`
    /// hands back the links untouched — so a fixture one child smaller puts
    /// the two orders back into agreement, and this passes whichever one it
    /// is walking. The run is asserted before the jump rather than left to
    /// the fixture, so trimming it fails here instead of quietly proving
    /// nothing.
    #[test]
    fn going_to_a_bead_drawn_twice_lands_on_the_copy_drawn_above_a_run() {
        let mut forest = flatten(alone("orbital", TWIN_BESIDE_A_RUN, &panes_on(&["twn-1.4"])));

        // Four, not three: a run counts the work it stands over, and `twn-9`
        // hangs under one of the three.
        assert!(
            drawn_here(&forest, "… 4 more"),
            "no run formed, so the two orders agree and this test cannot \
             tell them apart: {:#?}",
            sketch(&forest)
        );

        assert!(forest.go_to(&key("orbital", "twn-9")));

        assert_eq!(
            forest.place().map(|place| place.steps.clone()),
            Some(vec![key("orbital", "twn-1.4"), key("orbital", "twn-9")]),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// A tree whose root has four closed children, one of them staffed. The
    /// three quiet ones make a run; the staffed one is drawn above it. A
    /// fifth bead hangs under one of each, so the two orders reach it by
    /// different ways down.
    const TWIN_BESIDE_A_RUN: &str = r#"[
      {"id":"twn-1","title":"re-roof the shed","status":"in_progress",
       "priority":1,"issue_type":"epic"},
      {"id":"twn-1.1","title":"strip the felt","status":"closed",
       "dependencies":[{"depends_on_id":"twn-1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-28T09:00:00Z"},
      {"id":"twn-1.2","title":"clear the gutters","status":"closed",
       "dependencies":[{"depends_on_id":"twn-1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-27T09:00:00Z"},
      {"id":"twn-1.3","title":"sweep the yard","status":"closed",
       "dependencies":[{"depends_on_id":"twn-1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-26T09:00:00Z"},
      {"id":"twn-1.4","title":"lay the new felt","status":"closed",
       "dependencies":[{"depends_on_id":"twn-1","type":"parent-child"},
                       {"depends_on_id":"twn-9","type":"blocks"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-25T09:00:00Z"},
      {"id":"twn-9","title":"borrow the ladder","status":"closed",
       "dependencies":[{"depends_on_id":"twn-1.1","type":"parent-child"}],
       "priority":2,"issue_type":"task","closed_at":"2026-08-24T09:00:00Z"}
    ]"#;

    /// A parent with enough finished children draws the rest of them first
    /// and the run after, so the order siblings are *sorted* into is not the
    /// order they are drawn in — and a walk taking `links_below` alone gets
    /// the difference wrong.
    ///
    /// The difference is not open against closed, which the sibling sort
    /// already handles. It is that a run is of *finished branches*, and
    /// `lines::finished` is every bead in the branch closed **and no agent on
    /// it** — a stricter thing than the status the sort reads. `orb-7.4` is
    /// closed with a pane working it, so it is not finished, and it stays
    /// drawn among its siblings while `.2`, `.3` and `.5` elide beneath them.
    /// Sorted it is fifth of its siblings; drawn it is third.
    ///
    /// A bead inside a run is drawn nowhere until the run is opened, and a
    /// search opens it, so the run's members are matches like any others —
    /// after the siblings drawn above them.
    #[test]
    fn a_run_of_finished_children_is_walked_where_the_screen_draws_it() {
        let mut forest = flatten(snapshot());

        assert_eq!(forest.seek("orb-7."), went_to("orbital", "orb-7.1", 1, 8));
        // `.1`'s own children, drawn under it and above its siblings, then
        // `.7`, which the sibling sort already puts above the closed ones.
        forest.next_match(true);
        forest.next_match(true);
        forest.next_match(true);

        // The staffed closed bead, drawn above the run rather than in it.
        // Walked from `links_below` alone this is `orb-7.2`.
        assert_eq!(
            forest.next_match(true),
            Some(went_to("orbital", "orb-7.4", 5, 8))
        );
    }

    /// The screen draws projects in the order the config names them, and
    /// `snapshot.trees` is in the order they were *read* — which is why
    /// `snapshot.projects` exists. So a search cannot take its order from the
    /// trees: a project read second and drawn first would be walked in the
    /// wrong place, and the ordinal at the foot would count rows the reader
    /// cannot count to.
    #[test]
    fn matches_are_numbered_by_the_order_projects_are_drawn_not_read() {
        let mut forest = flatten(read_in_reverse());

        // `orbital` is named first by the config and read second here.
        assert_eq!(
            forest.seek("orb-7.1.1"),
            went_to("orbital", "orb-7.1.1", 1, 2)
        );
        assert_eq!(
            forest.next_match(true),
            Some(went_to("harbour", "orb-7.1.1", 2, 2))
        );
    }

    /// Two projects whose trees were read in the opposite order to the one
    /// the config names them in.
    fn read_in_reverse() -> Snapshot {
        gather(
            vec![tree_of("harbour", ORBITAL), tree_of("orbital", ORBITAL)],
            Vec::new(),
            Filter::All,
        )
    }

    /// Two projects reading trackers that use the same prefix, which nothing
    /// coordinates and nothing forbids.
    fn two_trackers_holding_one_id() -> Snapshot {
        gather(
            vec![tree_of("orbital", ORBITAL), tree_of("ferry", ORBITAL)],
            Vec::new(),
            Filter::All,
        )
    }

    /// A tree where one bead's title names another bead's whole id, and is
    /// drawn above it. A search for that id matches both of them.
    const NAMED_IN_A_TITLE: &str = r#"[
      {"id":"orb-6","title":"re-site the mast","status":"in_progress",
       "priority":1,"issue_type":"epic"},
      {"id":"orb-6.1","title":"wait on orb-6.2 before pouring","status":"open",
       "dependencies":[{"depends_on_id":"orb-6","type":"parent-child"}],
       "priority":2,"issue_type":"task"},
      {"id":"orb-6.2","title":"cure the base","status":"open",
       "dependencies":[{"depends_on_id":"orb-6","type":"parent-child"}],
       "priority":2,"issue_type":"task"}
    ]"#;

    fn went_to(project: &str, id: &str, at: usize, of: usize) -> Landed {
        Landed::On {
            key: key(project, id),
            at,
            of,
        }
    }

    fn drawn_here(forest: &Forest, said: &str) -> bool {
        sketch(forest).iter().any(|row| row.contains(said))
    }

    /// Put the selection on a bead and focus the forest there, the way a
    /// reader would with the keys they have.
    fn focus_on(forest: &mut Forest, id: &str) {
        select_bead(forest, id);
        assert!(
            forest.apply(Action::FocusForest),
            "focusing {id} changed nothing: {:#?}",
            sketch(forest)
        );
    }

    /// Every root but the one focused goes, and so does every other project's
    /// tree. The project lines stay, because what is holding their roots back
    /// hangs under them.
    #[test]
    fn focusing_a_root_leaves_it_the_only_one_drawn() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7");

        assert_eq!(
            // Without the things in the groups, which say nothing about where
            // the trees went and are long enough to bury the rows that do.
            sketch(&forest)
                .into_iter()
                .filter(|row| !row.contains("── - "))
                .collect::<Vec<String>>(),
            vec![
                "▾ orbital",
                "  ├── ◐ orb-7 lift the ground station",
                "  │   ├── ! Dangling(1)",
                "  │   ├─▸ ○ .1 re-point the dish",
                "  │   ├── ○ .7 log the survey marks",
                "  │   ├── ✓ .4 clear the access road",
                "  │   └─▸ … 3 more",
                "  └── [Unattributed orbital] 2",
                "▾ ferry",
                "  ├─▸ [OutOfTheWay ferry] 1",
                "  └── [Unattributed ferry] 1",
                "▾ harbour",
                "  └─▸ [OutOfTheWay harbour] 1",
                "▸ [FailedProjects] 1",
                "▾ [Unconfigured] 1",
                "▾ [Conflicts] 1",
            ]
        );
    }

    /// Every other root is one line away rather than gone, under the project
    /// it belongs to. Orbital's own root is behind that line too, for the part
    /// of it the mode stopped drawing: the beads above the focused bead.
    #[test]
    fn the_roots_the_mode_stops_drawing_go_behind_one_line_per_project() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");

        assert_eq!(
            sketch(&forest)
                .into_iter()
                .filter(|row| !row.contains("── - "))
                .collect::<Vec<String>>(),
            vec![
                "▾ orbital",
                "  ├─▸ ○ orb-7.1 re-point the dish",
                "  │   └── ! Dangling(1)",
                "  ├─▸ [OutOfTheWay orbital] 1",
                "  └── [Unattributed orbital] 2",
                "▾ ferry",
                "  ├─▸ [OutOfTheWay ferry] 1",
                "  └── [Unattributed ferry] 1",
                "▾ harbour",
                "  └─▸ [OutOfTheWay harbour] 1",
                "▸ [FailedProjects] 1",
                "▾ [Unconfigured] 1",
                "▾ [Conflicts] 1",
            ]
        );
    }

    /// One line away means the line opens onto them. They rest shut inside it,
    /// as the trees the filter is holding back do.
    ///
    /// Ferry's root was on the screen and harbour's was behind the filter, and
    /// the line opens onto either, because one line stands for both sets.
    #[test]
    fn opening_the_line_over_the_held_back_roots_draws_them() {
        for (project, root) in [
            ("ferry", "fer-2 unread"),
            ("harbour", "hbr-3 dredge the channel"),
        ] {
            let mut forest = flatten(snapshot());
            focus_on(&mut forest, "orb-7.1");

            open_the_line_holding_roots_back(&mut forest, project);

            assert!(drawn_here(&forest, root), "{:#?}", sketch(&forest));
        }
    }

    /// Which row one project's held-back roots are behind.
    fn the_line_holding_roots_back(forest: &Forest, project: &str) -> usize {
        forest
            .lines()
            .iter()
            .position(|line| {
                matches!(&line.content, Content::Group(group)
                if group.kind == GroupKind::OutOfTheWay
                    && group.project.as_deref() == Some(project))
            })
            .unwrap_or_else(|| panic!("no line holds {project} back: {:#?}", sketch(forest)))
    }

    /// Step onto that line and open it, with the keys a reader has.
    fn open_the_line_holding_roots_back(forest: &mut Forest, project: &str) {
        let at = the_line_holding_roots_back(forest, project);
        step_onto(forest, at);
        assert!(forest.apply(Action::ExpandOrChild));
    }

    /// What the line holding one project's roots back says it stands over.
    fn held_by_the_line(forest: &Forest, project: &str) -> Counts {
        forest
            .lines()
            .iter()
            .find_map(|line| match &line.content {
                Content::Group(group)
                    if group.kind == GroupKind::OutOfTheWay
                        && group.project.as_deref() == Some(project) =>
                {
                    group.held.clone()
                }
                _ => None,
            })
            .unwrap_or_else(|| panic!("no counts on {project}'s line: {:#?}", sketch(forest)))
    }

    /// The line stands over open work with seats and anomalies on it, which is
    /// the whole reason the reader pressed the key, so it counts them rather
    /// than saying a number of roots and leaving them unsaid.
    #[test]
    fn the_line_over_the_held_back_roots_counts_the_seats_and_anomalies_in_them() {
        let mut forest = flatten(snapshot());
        select_hidden_tree(&mut forest);
        assert!(forest.apply(Action::FocusForest));

        let held = held_by_the_line(&forest, "orbital");

        assert_eq!(held, counts_of(&forest, "orbital", "orb-7"));
        assert!(held.live_agents > 0, "orbital is where the agents are");
    }

    /// What one of a project's trees adds up to, by its root.
    fn counts_of(forest: &Forest, project: &str, root: &str) -> Counts {
        forest
            .snapshot()
            .tree(&key(project, root))
            .unwrap_or_else(|| panic!("{project} has no tree at {root}"))
            .counts
            .clone()
    }

    /// The reader asked to finish the bead they pressed the key on, so that is
    /// the bead the forest they come back to is standing on, wherever they had
    /// walked to underneath it.
    #[test]
    fn putting_the_forest_back_leaves_the_selection_on_the_bead_it_was_rooted_at() {
        let mut forest = flatten(snapshot());
        let was = sketch(&forest);
        focus_on(&mut forest, "orb-7.1");
        forest.apply(Action::Move(Motion::LastRow));

        assert!(forest.apply(Action::FocusForest));

        assert_eq!(sketch(&forest), was);
        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1")));
    }

    /// `bdi` runs on the live-agent filter unless told otherwise, and the
    /// group of trees it is holding back is where a reader meets a quiet one.
    /// Rooting the forest at a bead in one of those draws it like any other,
    /// rather than finding no tree to root at.
    #[test]
    fn rooting_the_forest_at_a_bead_the_filter_holds_back_draws_its_tree() {
        let mut forest = flatten(snapshot());
        select_hidden_tree(&mut forest);
        assert_eq!(cursor(&forest), Some(&key("harbour", "hbr-3")));

        assert!(forest.apply(Action::FocusForest));

        let hbr = forest
            .lines()
            .iter()
            .find(|line| line.bead().is_some_and(|bead| bead.id == "hbr-3"))
            .unwrap_or_else(|| panic!("hbr-3 is not drawn: {:#?}", sketch(&forest)));
        assert_eq!(hbr.depth, 1, "drawn where a root is drawn");
        assert!(
            !drawn_here(&forest, "HiddenTrees"),
            "the group draws whole trees: {:#?}",
            sketch(&forest)
        );
    }

    /// The mode stands on the bead named at the keystroke, so walking about
    /// under it does not move it.
    #[test]
    fn moving_the_selection_leaves_the_forest_rooted_where_it_was() {
        let mut forest = flatten(snapshot());
        toggle_fold_of(&mut forest, "orb-7.1");
        focus_on(&mut forest, "orb-7.1");
        let rooted = sketch(&forest);

        forest.apply(Action::Move(Motion::LastRow));
        forest.apply(Action::Move(Motion::FirstRow));

        assert_eq!(sketch(&forest), rooted);
    }

    /// The bead going out of the collection is the one thing that ends the
    /// mode on its own: there is nothing left to root the forest at.
    #[test]
    fn a_collection_that_has_lost_the_focused_bead_puts_the_forest_back() {
        let mut forest = flatten(snapshot());
        toggle_fold_of(&mut forest, "orb-7.1");
        focus_on(&mut forest, "orb-7.1.1");
        assert!(!drawn_here(&forest, "fer-2"), "rooted at one bead");

        let renamed = edited(ORBITAL, r#""id":"orb-7.1.1""#, r#""id":"orb-7.1.9""#);
        forest.refresh(gather(
            vec![
                tree_of("orbital", &renamed),
                Tree::tracker_unreachable("ferry", "fer-2", TrackerFailure::Auth),
                tree_of("harbour", HARBOUR),
            ],
            Vec::new(),
            Filter::LiveAgents,
        ));

        assert!(
            drawn_here(&forest, "fer-2"),
            "every root is back: {:#?}",
            sketch(&forest)
        );
    }

    /// And the next press roots the forest at the bead the reader is on,
    /// rather than being spent putting back a forest that is already back.
    #[test]
    fn the_key_roots_the_forest_afresh_once_the_focused_bead_has_gone() {
        let mut forest = flatten(snapshot());
        toggle_fold_of(&mut forest, "orb-7.1");
        focus_on(&mut forest, "orb-7.1.1");
        let renamed = edited(ORBITAL, r#""id":"orb-7.1.1""#, r#""id":"orb-7.1.9""#);
        forest.refresh(gather(
            vec![
                tree_of("orbital", &renamed),
                Tree::tracker_unreachable("ferry", "fer-2", TrackerFailure::Auth),
                tree_of("harbour", HARBOUR),
            ],
            Vec::new(),
            Filter::LiveAgents,
        ));

        focus_on(&mut forest, "orb-7.1");

        assert!(
            !drawn_here(&forest, "fer-2"),
            "rooted at the bead just asked for: {:#?}",
            sketch(&forest)
        );
    }

    /// A tracker that stops answering for the focused root has taken that bead
    /// out of the collection as surely as one that dropped it, so the mode
    /// ends. The root keeps a row saying it would not read, and a mode reading
    /// that row as the bead still being there would spend the next press
    /// putting back a forest that is already back.
    #[test]
    fn the_key_roots_the_forest_afresh_once_the_focused_root_stopped_reading() {
        let mut forest = flatten(built(Filter::All));
        focus_on(&mut forest, "orb-7");
        forest.refresh(gather(
            vec![
                Tree::tracker_unreachable("orbital", "orb-7", TrackerFailure::Auth),
                tree_of("harbour", HARBOUR),
            ],
            Vec::new(),
            Filter::All,
        ));
        assert!(
            drawn_here(&forest, "hbr-3 dredge the channel"),
            "every root is back: {:#?}",
            sketch(&forest)
        );

        focus_on(&mut forest, "hbr-3");

        assert!(
            !drawn_here(&forest, "⚠ orb-7 unread"),
            "rooted at the bead just asked for: {:#?}",
            sketch(&forest)
        );
    }

    /// Going to a bead opens what is shut over it, and under this mode what is
    /// shut over every other root is the line the mode put them behind. A
    /// search that found a bead it cannot reach is a search that failed.
    #[test]
    fn going_to_a_held_back_bead_opens_the_line_holding_its_root() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");

        assert!(
            forest.go_to(&key("harbour", "hbr-3")),
            "cannot reach harbour: {:#?}",
            sketch(&forest)
        );
        assert_eq!(cursor(&forest), Some(&key("harbour", "hbr-3")));
    }

    /// A root the filter was showing as much as one it was not. The mode holds
    /// both back behind the one line, so that line is what is shut over either.
    #[test]
    fn going_to_a_bead_in_a_root_the_filter_was_showing_opens_it_as_well() {
        let mut forest = flatten(snapshot());
        select_hidden_tree(&mut forest);
        assert!(forest.apply(Action::FocusForest));

        assert!(
            forest.go_to(&key("orbital", "orb-7.1")),
            "cannot reach orbital: {:#?}",
            sketch(&forest)
        );
        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1")));
    }

    /// The reader is put back on the bead they were finishing even where they
    /// shut something over it while they were down there. A forest that comes
    /// back with the selection somewhere else has not put them back.
    #[test]
    fn putting_the_forest_back_opens_what_has_been_shut_over_the_bead() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");
        forest.folds.set(Handle::Project("orbital".into()), false);

        assert!(forest.apply(Action::FocusForest));

        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7.1")));
    }

    /// A bead that moved is still the bead. What ends the mode is the bead
    /// going out of the collection, and a tracker that reparented it has done
    /// nothing of the kind.
    #[test]
    fn a_collection_that_moved_the_focused_bead_stays_rooted_at_it() {
        let mut forest = flatten(snapshot());
        toggle_fold_of(&mut forest, "orb-7.1");
        focus_on(&mut forest, "orb-7.1.2");
        let moved = edited(
            ORBITAL,
            r#""seal the feed horn","status":"open",
       "dependencies":[{"depends_on_id":"orb-7.1""#,
            r#""seal the feed horn","status":"open",
       "dependencies":[{"depends_on_id":"orb-7""#,
        );

        forest.refresh(gather(
            vec![
                tree_of("orbital", &moved),
                Tree::tracker_unreachable("ferry", "fer-2", TrackerFailure::Auth),
                tree_of("harbour", HARBOUR),
            ],
            Vec::new(),
            Filter::LiveAgents,
        ));

        assert!(
            !drawn_here(&forest, "fer-2"),
            "still rooted at one bead: {:#?}",
            sketch(&forest)
        );
        assert!(drawn_here(&forest, "seal the feed horn"));
    }

    /// Pressing the key to come back out changes what is on the screen, so the
    /// press says so. A press the loop reads as changing nothing leaves the
    /// rooted forest drawn over a forest that has been put back.
    #[test]
    fn putting_the_forest_back_says_the_screen_changed() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7");

        assert!(forest.apply(Action::FocusForest));
    }

    /// A search counts the matches it can take the reader to. Under this mode
    /// the beads above the focused one are drawn nowhere, so a search that
    /// counted them would step onto one and report it as nothing found.
    #[test]
    fn every_match_a_search_counts_under_the_mode_can_be_landed_on() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");

        let first = forest.seek("the");
        let Landed::On { of, .. } = first else {
            panic!("nothing matched: {first:?}")
        };
        for step in 1..=of {
            let landed = forest.next_match(true);
            assert!(
                matches!(landed, Some(Landed::On { .. })),
                "match {step} of {of} cannot be landed on: {landed:#?}",
            );
        }
    }

    /// A bead closing is not the bead leaving. `bdi` reads every bead a
    /// tracker holds, so a closed one stays in the collection and the forest
    /// stays rooted at it.
    #[test]
    fn the_focused_bead_closing_leaves_the_forest_rooted_at_it() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");

        let closed = edited(
            ORBITAL,
            r#"{"id":"orb-7.1","title":"re-point the dish","status":"open"#,
            r#"{"id":"orb-7.1","title":"re-point the dish","status":"closed"#,
        );
        forest.refresh(gather(
            vec![
                tree_of("orbital", &closed),
                Tree::tracker_unreachable("ferry", "fer-2", TrackerFailure::Auth),
                tree_of("harbour", HARBOUR),
            ],
            Vec::new(),
            Filter::LiveAgents,
        ));

        assert!(
            !drawn_here(&forest, "fer-2"),
            "still rooted at one bead: {:#?}",
            sketch(&forest)
        );
        assert!(drawn_here(&forest, "re-point the dish"));
    }

    /// A project, a line standing over a stretch of finished beads, and a root
    /// whose tracker refused are all lines a reader can sit on and none of
    /// them is a bead with a tree under it.
    #[test]
    fn asking_to_root_the_forest_at_a_line_that_is_not_a_bead_does_nothing() {
        let mut forest = flatten(snapshot());
        let was = sketch(&forest);

        select_project(&mut forest, "orbital");
        assert!(!forest.apply(Action::FocusForest));
        assert_eq!(sketch(&forest), was);

        select_run(&mut forest);
        assert!(!forest.apply(Action::FocusForest));
        assert_eq!(sketch(&forest), was);

        select_bead(&mut forest, "fer-2");
        assert!(!forest.apply(Action::FocusForest));
        assert_eq!(sketch(&forest), was);
    }

    /// A bead deep in a tree is drawn where a root is drawn, and what hangs
    /// under it is what hangs under it anywhere else.
    ///
    /// It reads whole the way a root does, and the beads under it read against
    /// it. A column of ids is read by putting the drawn root in front of each
    /// one, so a suffix cut against a root that is behind the line names a
    /// bead that is not there.
    #[test]
    fn focusing_a_bead_under_a_root_draws_it_where_that_root_was() {
        let mut forest = flatten(snapshot());
        toggle_fold_of(&mut forest, "orb-7.1");
        focus_on(&mut forest, "orb-7.1");

        assert_eq!(
            sketch(&forest)
                .into_iter()
                .take_while(|row| !row.contains("Unattributed"))
                .collect::<Vec<String>>(),
            vec![
                "▾ orbital",
                "  ├── ○ orb-7.1 re-point the dish",
                "  │   ├── ! Dangling(1)",
                "  │   ├── ○ .1 true the mount",
                "  │   └── ○ .2 seal the feed horn",
                "  ├─▸ [OutOfTheWay orbital] 1",
            ]
        );
    }

    /// The mode stops drawing the beads above the focused one, and *degrade,
    /// never disappear* binds over them as it does over a whole root: they go
    /// behind the same line, under the project they are in, and the root they
    /// hang from rests shut there as a held-back root does.
    #[test]
    fn the_beads_above_the_focused_bead_go_behind_the_line_as_a_root_does() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");

        open_the_line_holding_roots_back(&mut forest, "orbital");

        assert_eq!(
            sketch(&forest)
                .into_iter()
                .take_while(|row| !row.contains("Unattributed"))
                .collect::<Vec<String>>(),
            vec![
                "▾ orbital",
                "  ├─▸ ○ orb-7.1 re-point the dish",
                "  │   └── ! Dangling(1)",
                "  ├── [OutOfTheWay orbital] 1",
                "  │   └─▸ ◐ orb-7 lift the ground station",
                "  │       └── ! Dangling(1)",
            ]
        );
    }

    /// What is behind the line reads against the root it is drawn under, as it
    /// does with the mode off. Only the drawing rooted at one bead shortens
    /// against that bead, and the roots behind the line are not that drawing.
    #[test]
    fn a_bead_behind_the_line_reads_against_the_root_it_hangs_under() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");
        open_the_line_holding_roots_back(&mut forest, "orbital");

        toggle_fold_of(&mut forest, "orb-7");

        assert!(
            drawn_here(&forest, "○ .7 log the survey marks"),
            "{:#?}",
            sketch(&forest)
        );
    }

    /// The focused bead is drawn where a root is drawn, so the line the rest
    /// of its root is behind leaves it there rather than drawing it twice.
    #[test]
    fn the_line_leaves_the_focused_bead_to_the_root_of_the_forest() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");

        open_the_line_holding_roots_back(&mut forest, "orbital");

        assert_eq!(
            sketch(&forest)
                .iter()
                .filter(|row| row.contains("re-point the dish"))
                .count(),
            1,
            "{:#?}",
            sketch(&forest)
        );
    }

    /// A seat on a bead above the focused one is a seat nothing else on the
    /// screen says is there, so the line standing over that bead counts it.
    #[test]
    fn the_line_counts_the_seats_above_the_focused_bead() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");

        let held = held_by_the_line(&forest, "orbital");

        assert_eq!(
            held.live_agents,
            counts_of(&forest, "orbital", "orb-7").live_agents,
            "every seat in orbital is on a bead the mode stopped drawing"
        );
        assert!(held.live_agents > 0, "orbital is where the agents are");
    }

    /// It counts what it is standing over rather than the whole root the beads
    /// came from. The focused bead and what hangs beneath it are on the screen,
    /// and a line counting those sends a reader looking for rows they are
    /// already reading.
    #[test]
    fn the_line_counts_only_the_beads_the_mode_stopped_drawing() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");

        let held = held_by_the_line(&forest, "orbital");

        assert_eq!(
            held.total,
            counts_of(&forest, "orbital", "orb-7").total - 3,
            "orb-7.1 and the two beads beneath it are drawn at the root"
        );
    }

    /// Going to a bead opens what is shut over it, and what is shut over a
    /// bead above the focused one is the line the rest of its root is behind.
    #[test]
    fn going_to_a_bead_above_the_focused_one_opens_the_line_it_is_behind() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");

        assert!(
            forest.go_to(&key("orbital", "orb-7")),
            "cannot reach the bead above: {:#?}",
            sketch(&forest)
        );
        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-7")));
    }

    /// A run says what opening it would draw. Where the bead the forest is
    /// rooted at came out of one, the run behind the line stands for the
    /// siblings it left there rather than counting a bead drawn at the root of
    /// the forest.
    #[test]
    fn a_run_behind_the_line_leaves_the_focused_bead_out_of_its_count() {
        let mut forest = flatten(snapshot());
        assert!(forest.go_to(&key("orbital", "orb-7.2")), "no such bead");
        assert!(forest.apply(Action::FocusForest));

        assert!(
            forest.go_to(&key("orbital", "orb-7.3")),
            "cannot reach a bead in the run: {:#?}",
            sketch(&forest)
        );

        assert!(
            drawn_here(&forest, "… 2 more"),
            "the run stands for the siblings left in it: {:#?}",
            sketch(&forest)
        );
    }

    /// And a run with the focused bead somewhere beneath one of its members
    /// stands for one bead fewer for the same reason, rather than for what the
    /// whole tree would have put behind it.
    #[test]
    fn a_run_behind_the_line_leaves_out_a_focused_bead_beneath_a_member() {
        let mut forest = flatten(depot());
        assert!(forest.go_to(&key("orbital", "dep-1.2.1")), "no such bead");
        assert!(forest.apply(Action::FocusForest));

        assert!(
            forest.go_to(&key("orbital", "dep-1.3")),
            "cannot reach the run: {:#?}",
            sketch(&forest)
        );

        assert!(drawn_here(&forest, "… 5 more"), "{:#?}", sketch(&forest));
    }

    /// A bead reachable more than once is drawn once for every way down to it,
    /// and the key roots the forest at the copy the reader pressed it on. The
    /// mode draws none of the others, so going to that bead goes to the copy
    /// it is drawn at rather than to the first way down to it.
    #[test]
    fn going_to_the_focused_bead_reaches_the_copy_it_is_rooted_at() {
        let mut forest = flatten(drawn_twice_in_one_tree());
        let [_, lower] = copies_of(&forest, "orb-9");
        step_onto(&mut forest, lower);
        assert!(forest.apply(Action::FocusForest));

        assert!(
            forest.go_to(&key("orbital", "orb-9")),
            "cannot reach the bead the forest is rooted at: {:#?}",
            sketch(&forest)
        );
    }

    /// And everything only that copy reaches. The first way down to one of
    /// those beads goes through the copy the mode draws nowhere, so a search
    /// answering with it would count a bead it could not land on.
    #[test]
    fn going_to_a_bead_under_the_focused_copy_reaches_it() {
        let mut forest = flatten(drawn_twice_in_one_tree());
        let [_, lower] = copies_of(&forest, "orb-9");
        step_onto(&mut forest, lower);
        assert!(forest.apply(Action::FocusForest));

        assert!(
            forest.go_to(&key("orbital", "orb-9.1")),
            "cannot reach the bead beneath it: {:#?}",
            sketch(&forest)
        );
        assert_eq!(cursor(&forest), Some(&key("orbital", "orb-9.1")));
    }

    /// A root the tracker files under another root is still the bead the
    /// reader was finishing. Its place stops being a root's, so the mode goes
    /// looking for the bead, exactly as it does for a bead moved further down.
    #[test]
    fn a_collection_that_filed_the_focused_root_under_another_stays_rooted_at_it() {
        let staffed = panes_on(&["hbr-9.1"]);
        let mut forest = flatten(together("orbital", &[HARBOUR, SLIPWAY], &staffed));
        focus_on(&mut forest, "hbr-9");
        assert!(
            !drawn_here(&forest, "dredge the channel"),
            "rooted at one bead: {:#?}",
            sketch(&forest)
        );

        forest.refresh(together("orbital", &[SLIPWAY_UNDER_HARBOUR], &staffed));

        assert!(
            drawn_here(&forest, "re-deck the slipway"),
            "the bead is still where a root is drawn: {:#?}",
            sketch(&forest)
        );
        assert!(
            drawn_here(&forest, "[OutOfTheWay orbital]"),
            "still rooted at one bead: {:#?}",
            sketch(&forest)
        );
    }

    /// A search counts in the order the rows are drawn, and the bead the
    /// forest is rooted at is the first row on the screen however its tree
    /// came in its project's own order.
    #[test]
    fn a_search_counts_from_the_bead_the_forest_is_rooted_at() {
        let mut forest = flatten(together(
            "orbital",
            &[HARBOUR, SLIPWAY],
            &panes_on(&["hbr-9.1"]),
        ));
        assert!(forest.go_to(&key("orbital", "hbr-3.1")), "no such bead");
        assert!(forest.apply(Action::FocusForest));

        let landed = forest.seek("the");

        let Landed::On { key: found, at, .. } = landed else {
            panic!("nothing matched: {landed:?}")
        };
        assert_eq!((found, at), (key("orbital", "hbr-3.1"), 1));
    }

    /// Stepping through matches from a row that is not a bead carries on from
    /// where the reader is standing, and a shut line is asked what it holds
    /// rather than read past. This line holds beads exactly as the filter's
    /// does, so a reader standing on it steps into what is behind it.
    #[test]
    fn stepping_from_the_shut_line_carries_on_into_the_roots_behind_it() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");
        forest.seek("the");
        let at = the_line_holding_roots_back(&forest, "orbital");
        step_onto(&mut forest, at);
        assert_eq!(
            forest.lines()[at].folded,
            Some(false),
            "the line rests shut"
        );

        let landed = forest.next_match(true);

        let Some(Landed::On { key: found, .. }) = landed else {
            panic!("nothing matched: {landed:?}")
        };
        assert_eq!(found, key("orbital", "orb-7"));
    }

    /// A root whose tracker refused leads its project whatever the filter
    /// says, and it holds no bead. The line has to look past it for the bead
    /// it stands on, or a reader stepping off it walks past everything it
    /// holds and wraps round to the top of the screen.
    #[test]
    fn stepping_from_the_shut_line_reaches_past_a_root_holding_no_bead() {
        let mut forest = flatten(gather(
            vec![
                tree_of("orbital", ORBITAL),
                Tree::tracker_unreachable("orbital", "orb-0", TrackerFailure::Auth),
                tree_of("harbour", HARBOUR),
            ],
            Vec::new(),
            Filter::LiveAgents,
        ));
        focus_on(&mut forest, "orb-7.1");
        forest.seek("the");
        let at = the_line_holding_roots_back(&forest, "orbital");
        step_onto(&mut forest, at);

        let landed = forest.next_match(true);

        let Some(Landed::On { key: found, .. }) = landed else {
            panic!("nothing matched: {landed:?}")
        };
        assert_eq!(found, key("orbital", "orb-7"));
    }

    /// Open every fold on the screen, with the keys a reader has, until the
    /// rows are the whole of what the forest holds.
    ///
    /// Counted out before it starts like any other walk here. Each press opens
    /// one fold and draws what it was over, so a screen with a fold left shut
    /// after a press per row it started with is one the walk says it never
    /// got to the end of.
    fn open_everything(forest: &mut Forest) {
        walk::until(
            forest,
            |forest| shut_fold(forest).is_none(),
            |forest| {
                let at = shut_fold(forest).expect("a fold to open");
                forest.select_line(at);
                forest.apply(Action::ExpandOrChild);
            },
            |forest| format!("a fold would not open: {:#?}", sketch(forest)),
        );
    }

    /// The first row on the screen resting shut over something.
    fn shut_fold(forest: &Forest) -> Option<usize> {
        forest
            .lines()
            .iter()
            .position(|line| line.folded == Some(false))
    }

    /// The order a search counts in and the order the rows come out are the
    /// same order, and both are the drawing's answer rather than two accounts
    /// of it that agree because they were written to. Under the mode as
    /// without it, because the mode is what moves the rows.
    #[test]
    fn a_search_enumerates_the_beads_in_the_order_the_rows_draw_them() {
        for rooted in [None, Some("orb-7.1")] {
            let mut forest = flatten(snapshot());
            if let Some(bead) = rooted {
                focus_on(&mut forest, bead);
            }
            open_everything(&mut forest);
            let mut met = BTreeSet::new();
            // A root whose tracker refused has a row and no bead on it, and a
            // search offers beads. It is named on its line rather than left
            // out, which is the one row here that stands for no bead.
            let on_screen: Vec<BeadKey> = forest
                .lines()
                .iter()
                .filter(|line| matches!(line.content, Content::Bead(_)))
                .filter_map(Line::bead)
                .filter(|key| met.insert((*key).clone()))
                .cloned()
                .collect();

            let counted: Vec<BeadKey> = forest
                .beads_drawn()
                .into_iter()
                .map(|(key, _)| key)
                .collect();

            assert_eq!(counted, on_screen, "rooted at {rooted:?}");
        }
    }

    /// A search counts the matches it can take the reader to, and a line it
    /// can open is a match it can take them to.
    #[test]
    fn a_search_counts_a_bead_above_the_focused_one() {
        let mut forest = flatten(snapshot());
        focus_on(&mut forest, "orb-7.1");

        let landed = forest.seek("lift the ground station");

        let Landed::On { key: found, .. } = landed else {
            panic!("nothing matched: {landed:?}")
        };
        assert_eq!(found, key("orbital", "orb-7"));
    }
}