repon-core 0.30.1

Rendering-agnostic core for Repon: computes git state, knows nothing about terminals
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
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
//! `Core::start` and the threads and clocks it owns.
//!
//! See `docs/spec/core-api.md`'s "Threads and lifecycle" and "The entry points",
//! [ADR 0006](https://github.com/paulchiu/repon/blob/main/docs/adr/0006-no-git-state-cache-session-state-by-name.md)
//! and [ADR 0015](https://github.com/paulchiu/repon/blob/main/docs/adr/0015-the-core-owns-the-table.md).
//!
//! One dedicated thread runs the two second metadata poll and the thirty second
//! Generation deadline sweep on a shared interval loop; probes go on rayon's global
//! pool, one task per entity, which is infrastructure this crate already shares
//! rather than a thread `Core` itself owns. `Core::start` is the only thing that
//! spawns the dedicated thread, and `Drop` joins it, so a consumer never spawns one
//! of its own. The dedicated thread's ticking source is an injected channel rather
//! than a bare `thread::sleep`, which is what lets a test drive the poll and
//! deadline cadence deterministically instead of sleeping and hoping.
//!
//! Discovery, both halves, re-runs at the head of every Generation
//! ([refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md),
//! [discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)):
//! an Entity a later walk does not find goes [`crate::entity::Presence::Vanished`]
//! rather than disappearing, and one an abandoned walk cannot finish in time takes
//! its Set out of this automatic path until a fresh `Core` starts over different
//! roots. Phase C, status, is later work; this module already dispatches identity
//! (`branch`), `default_branch`, Phase B's own comparison (`sync`) and Phase D's
//! landing pass (`state`), the reads [`crate::git::head_shape`],
//! [`crate::default_branch::resolve`], [`crate::git::resolve_sync`] and
//! [`crate::landing::probe`] already do correctly, so the threading and
//! supersession machinery has a real payload to move rather than a stub. Nothing
//! here is written to or read from disk, so
//! every `start` recomputes from scratch; the consequence is that first-frame
//! speed has to come from progressive loading rather than a cache, which is
//! future work this crate does not yet do (`start` blocks on its one discovery
//! walk, at 20ms for the measured population).

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, OnceLock, RwLock};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use crossbeam_channel::{Receiver, Sender, select};
use rayon::iter::{IntoParallelIterator, ParallelIterator};

use crate::base;
use crate::cell::{Cell, Generation, Settled, Timestamp, Unknown};
use crate::default_branch;
use crate::discovery::{self, SetSpec};
use crate::entity::{
    ActionReceipt, DefaultBranch, DeleteRisk, DirtyCounts, EntityKey, EntityState, Head, Kind,
    OwnWork, Presence, RunningStep, Skip, StepOutcome, StepResult, SyncState, WorktreeState,
};
use crate::environment;
use crate::executor;
use crate::filter::{Applicability, Filter, Partition};
use crate::git;
use crate::landing;
#[cfg(any(test, feature = "test-util"))]
use crate::liveness;
use crate::patch_equivalence;
use crate::poll;
use crate::snapshot::Snapshot;

/// Budget within which rows with names must be on screen at first frame
/// (`docs/spec/refresh.md`'s "The first frame"). Nothing reads this yet; discovery's own
/// wall time is the thing that would have to stay under it once first-frame timing is
/// enforced rather than merely stated. Read only by
/// `first_frame_budget_constants_match_the_spec_of_record`.
#[allow(dead_code)] // read only by first_frame_budget_constants_match_the_spec_of_record
const FIRST_FRAME_NAMES_BUDGET_MS: u64 = 50;

/// Budget within which every cheap column (phase A/B) must be filled at first frame
/// (`docs/spec/refresh.md`'s "The first frame"). Nothing reads this yet; the identity and
/// comparison probes' combined wall time is what would have to stay under it. Read only by
/// `first_frame_budget_constants_match_the_spec_of_record`.
#[allow(dead_code)] // read only by first_frame_budget_constants_match_the_spec_of_record
const FIRST_FRAME_CHEAP_COLUMNS_BUDGET_MS: u64 = 200;

/// One Repo's config-level override, crossing from the consumer as plain data: no
/// TOML type, no `~` expansion left undone. [config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)
/// owns parsing it; the core only ever receives the result, and resolves `path` to
/// the git common dir itself, since opening a repository is the core's own work.
///
/// Keyed on `path` rather than the common dir `docs/spec/core-api.md` first named,
/// which this amends: a Worktree and its parent Repo share one common dir, so only
/// the entry's own path can outrank an entry reached by inheritance.
#[derive(Debug, Clone)]
pub struct RepoOverride {
    pub path: PathBuf,
    pub default_branch: Option<String>,
    pub excluded: bool,
}

/// One command in an Action's ordered list, crossing from the consumer as plain data:
/// `from_env` already resolved, so this crate never learns what that means
/// ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
/// "Actions", "Launchers" carries the same split for a Launcher's own argv). `shell`
/// crosses over unresolved, because resolving it is `executor::run_step`'s own job,
/// the same convention the `repon` crate's Launcher `shell = true` uses: with
/// `shell` set, `argv` holds exactly one element, the whole command string, per
/// [config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
/// "Launchers". `env`'s pairs are applied after
/// [`environment::environment`]'s own set-or-unset pairs, so a step's own `env` table
/// overrides the guaranteed set exactly as [config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
/// Launcher `env` field already does.
#[derive(Debug, Clone)]
pub struct Step {
    pub argv: Vec<String>,
    pub shell: bool,
    /// Runs `argv` through `$SHELL -ic` rather than `$SHELL -c`, sourcing the user's own rc
    /// file first ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
    /// `interactive` key). Meaningless, and always `false`, unless `shell` is also set; the
    /// consumer rejects `interactive` without `shell` at config load rather than this crate
    /// silently ignoring it.
    pub interactive: bool,
    pub env: Vec<(String, String)>,
}

/// One Action fan-out, crossing from the consumer as plain data: no TOML type, no
/// confirm gate, no palette. `label` is what a receipt's own label carries: the
/// Action's name, or the ad hoc command string typed into the palette. `name` is
/// `REPON_ACTION`'s own value and is `None` for an ad hoc run, exactly as
/// [config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
/// environment contract already treats a Launcher's absent `REPON_ACTION`. `when` is
/// `None` for a built-in, a typed command or a configured entry that declares none, in
/// which case every operable row runs; `Some` is what [`Core::run_action`] itself now
/// decides the fan-out by, not only what a palette reports about it
/// ([`docs/spec/actions.md`](https://github.com/paulchiu/repon/blob/main/docs/spec/actions.md)'s
/// "The Selection and the gate").
#[derive(Debug, Clone)]
pub struct ActionSpec {
    pub label: Arc<str>,
    pub name: Option<Arc<str>>,
    pub steps: Vec<Step>,
    pub concurrency: u32,
    pub when: Option<Filter>,
}

/// A [`RepoOverride`]'s probe-input half with its common dir already resolved, built
/// once at `Core::start` and frozen for this `Core`'s life: `default_branch` is read
/// while probing, so moving it needs the rediscovery a rebuild does
/// ([repo-management.md](https://github.com/paulchiu/repon/blob/main/docs/spec/repo-management.md)'s
/// "Writing config").
#[derive(Debug, Clone)]
struct ResolvedOverride {
    path: PathBuf,
    common_dir: PathBuf,
    default_branch: Option<String>,
}

/// A [`RepoOverride`]'s `exclude` with its common dir already resolved, held apart from
/// [`ResolvedOverride`] because it re-applies live: `exclude` decides only whether an
/// operation may reach a row that is discovered, probed and listed either way
/// ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s "listed,
/// never operated on"), so [`Core::set_exclusions`] replaces it with no rebuild at all.
#[derive(Debug, Clone)]
struct ResolvedExclusion {
    path: PathBuf,
    common_dir: PathBuf,
    excluded: bool,
}

/// The two path fields [`find_entry`]'s match rule reads, so the rule itself is written
/// once for both halves a `[[repo]]` entry resolves into.
trait ResolvedEntry {
    fn path(&self) -> &Path;
    fn common_dir(&self) -> &Path;
}

impl ResolvedEntry for ResolvedOverride {
    fn path(&self) -> &Path {
        &self.path
    }

    fn common_dir(&self) -> &Path {
        &self.common_dir
    }
}

impl ResolvedEntry for ResolvedExclusion {
    fn path(&self) -> &Path {
        &self.path
    }

    fn common_dir(&self) -> &Path {
        &self.common_dir
    }
}

/// Opens every override's own `path` to learn its common dir, once, and splits the result
/// into the half frozen for this `Core`'s life and the half [`Core::set_exclusions`] can
/// replace live. Silently drops an entry that will not even open: a path that matches no
/// discovered entity already gets its own warning on the consumer's side
/// ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md#cross-key-validity)),
/// and the core raises no second one for the same fact.
fn resolve_entries(overrides: &[RepoOverride]) -> (Vec<ResolvedOverride>, Vec<ResolvedExclusion>) {
    overrides
        .iter()
        .filter_map(|entry| {
            let common_dir = git::common_dir_of(&entry.path).ok()?;
            Some((
                ResolvedOverride {
                    path: entry.path.clone(),
                    common_dir: common_dir.to_path_buf(),
                    default_branch: entry.default_branch.clone(),
                },
                ResolvedExclusion {
                    path: entry.path.clone(),
                    common_dir: common_dir.to_path_buf(),
                    excluded: entry.excluded,
                },
            ))
        })
        .unzip()
}

/// The entry that applies to an entity at `path` sharing `common_dir`: one naming
/// `path` itself, or else the first declared entry sharing `common_dir`, which is
/// what lets one entry cover a Repo and every Worktree attached to it while a
/// Worktree named directly by its own path still beats the entry it would
/// otherwise inherit ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md#per-repo-entries)).
///
/// A consequence worth stating rather than working around here: a Submodule's own
/// common dir (`<parent common dir>/modules/<name>`, per `discovery.rs`'s
/// `resolve`) is never equal to its parent's, so one entry naming the parent's path
/// can never also exclude the parent's Submodules. The documented workaround is a
/// Set's own `exclude` glob over the subtree, which keeps the Submodule out of
/// discovery entirely rather than merely marking it excluded here.
fn find_entry<'a, T: ResolvedEntry>(
    entries: &'a [T],
    path: &Path,
    common_dir: &Path,
) -> Option<&'a T> {
    entries
        .iter()
        .find(|entry| entry.path() == path)
        .or_else(|| {
            entries
                .iter()
                .find(|entry| entry.common_dir() == common_dir)
        })
}

/// Whether an entity at `path` sharing `common_dir` is excluded by `exclusions`: the one
/// place the table's own [`EntityState::excluded`] is derived, read at entity creation, at
/// [`Core::probe_now`] and again whenever [`Core::set_exclusions`] replaces the list.
fn excluded_by(exclusions: &[ResolvedExclusion], path: &Path, common_dir: &Path) -> bool {
    find_entry(exclusions, path, common_dir).is_some_and(|entry| entry.excluded)
}

/// Whether a Generation's dispatch probes `kind` at all: always for a Repo or a
/// Worktree, only while `show_submodules` is on for a Submodule
/// ([discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)'s
/// "Showing Submodules": "the flag decides... whether they are probed"). Exhaustive over
/// `Kind`, so a fourth variant added later must be named here rather than silently
/// falling into either branch.
fn dispatches_kind(kind: Kind, show_submodules: bool) -> bool {
    match kind {
        Kind::Repo | Kind::Worktree => true,
        Kind::Submodule => show_submodules,
    }
}

/// The periodic fetch's own crossing data
/// ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
/// `[fetch]` table): whether it runs at all, its cadence, and how many run at once.
/// Plain bounding data, not the mutating mechanism itself: `enabled: false` here is
/// what keeps the cycle from running, not the absence of any machinery to run it.
#[derive(Debug, Clone)]
pub struct FetchSpec {
    pub enabled: bool,
    pub interval: Duration,
    pub concurrency: usize,
}

/// The fast-forward-only auto-update's own crossing data
/// ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
/// `[auto_update]` table): whether it runs at all.
///
/// Plain bounding data, not the mutating mechanism, for the same reason [`FetchSpec`]
/// is. Carries no interval or concurrency of its own, because it never ticks on its
/// own clock; it rides the periodic fetch cycle [`FetchSpec`] already schedules, so
/// `enabled: true` here is inert while `FetchSpec::enabled` is false.
#[derive(Debug, Clone, Copy)]
pub struct AutoUpdateSpec {
    pub enabled: bool,
}

/// The most recent periodic-fetch cycle's own failures, read fresh through
/// [`Core::fetch_failures`] the same way [`Core::discovery_warning`] and
/// [`Core::vanished_count`] are: never latched, so a cycle where every fetch
/// succeeds leaves this empty rather than carrying a stale failure forward from an
/// earlier one. Per-repository independence is unaffected: one entry here is one
/// repository `run_fetch_cycle` could not reach, never a reason another repository's
/// own fetch was skipped.
///
/// Carries the path and the underlying `FetchError`'s own text, for
/// a consumer's log; a consumer's own screen-facing warning is expected to surface
/// only `failed.len()`, the precedent `warnings.rs`'s `OnRefreshFailed` already sets
/// for never putting remote-supplied text on screen.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FetchFailures {
    pub failed: Vec<(PathBuf, String)>,
}

/// One [`Core::attempt_auto_update`] result on a single Repo: the fast-forward-only
/// auto-update's own five eligibility rules
/// ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
/// eligibility rule), flattened into one return type so the built-in `sync` action
/// ([repo-management.md](https://github.com/paulchiu/repon/blob/main/docs/spec/repo-management.md))
/// can report every ineligible reason to the user rather than a bare "did nothing".
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AutoUpdateAttempt {
    /// The working tree or index carried a change of its own.
    NotClean,
    /// No branch, no remote, or a branch with no upstream configured.
    NoUpstream,
    /// Already level with its upstream: nothing to move.
    NotBehind,
    /// The local branch has a commit its upstream does not, so no fast-forward exists.
    NotFastForward,
    /// The branch fast-forwarded to its upstream.
    Updated,
    /// A git read or write failed partway through.
    Failed(String),
}

/// Everything `Core::start` needs, handed as plain data. The core reads no file, no
/// path and no environment variable: this is the whole crossing, per
/// `docs/spec/core-api.md`'s "What crosses from config".
#[derive(Debug, Clone)]
pub struct CoreSpec {
    pub set: SetSpec,
    pub overrides: Vec<RepoOverride>,
    pub poll_interval: Duration,
    pub status_stale_after: Duration,
    pub generation_deadline: Duration,
    /// The initial reading of the show-submodules preference
    /// ([discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)'s
    /// "Showing Submodules"): whether a dispatched Generation probes a Submodule at all.
    /// Live-updatable afterwards through [`Core::set_show_submodules`], which is what lets
    /// toggling it skip a Core rebuild and the rediscovery that would come with one.
    pub show_submodules: bool,
    /// The periodic fetch's own bounding data. See [`FetchSpec`].
    pub fetch: FetchSpec,
    /// The fast-forward-only auto-update's own bounding data. See [`AutoUpdateSpec`]:
    /// inert while `fetch.enabled` is itself `false`
    /// (`Warning::AutoUpdateWithoutFetch` is what tells a config author that
    /// combination can never fire).
    pub auto_update: AutoUpdateSpec,
}

/// One entity's in-flight probe: which Generation dispatched it, and the flag that
/// generation owns to cancel it. [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)
/// fixes one `Arc<AtomicBool>` per in-flight entity, passed as `should_interrupt`;
/// `gix::interrupt::IS_INTERRUPTED` is a process-global static and is never used.
struct InFlight {
    generation: u64,
    cancel: Arc<AtomicBool>,
}

/// The assembled entity table `Core` owns: the only place a Generation's per-cell
/// supersession check happens, per ADR 0015.
struct Table {
    generation: u64,
    discovered_at: Timestamp,
    entities: Vec<EntityState>,
    index: HashMap<EntityKey, usize>,
    in_flight: HashMap<EntityKey, InFlight>,
    /// When each still-live Generation's dispatch started, for the deadline sweep.
    /// Pruned once nothing is left in flight for a Generation.
    generation_started_at: HashMap<u64, Instant>,
    /// Each entity's thread-safe repository handle, opened once by discovery.
    /// A probe task clones the `Arc` (cheap, a refcount bump) and derives its own
    /// `Repository` from it via `to_thread_local`, so no task ever shares a
    /// `Repository` with another one; a missing entry (a Submodule, or a boundary
    /// that would not open) falls back to opening fresh at probe time.
    repos: HashMap<EntityKey, Arc<gix::ThreadSafeRepository>>,
    /// Each entity's gitdir reading as of the previous metadata poll sweep, so the
    /// next sweep can tell whether any of [`poll::POLLED_GITDIR_ENTRIES`] moved
    /// ([refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
    /// "The poll"). Absent for an entity the sweep has never yet reached, which is
    /// what lets a first sweep record a baseline rather than reporting the whole
    /// population as having just moved.
    poll_fingerprints: HashMap<EntityKey, poll::GitdirFingerprint>,
}

/// A message the dedicated thread's control channel carries; distinct from a tick.
enum ClockControl {
    Pause,
    Resume,
    Shutdown,
}

/// A running core: its own table, its own dedicated thread, and the rayon pool it
/// shares with the rest of the process for probes.
///
/// Construction is `start`, never a plain constructor, because it spawns; `Drop`
/// joins every thread it spawned. The public entry points are exactly `start`,
/// `refresh`, `probe_now`, `snapshot`, `try_settle`, `dismiss`, `pause`, `resume`,
/// `discovery_warning` and `run_action` (see its own doc comment).
pub struct Core {
    table: Arc<RwLock<Table>>,
    /// Resolved once at `start` and never mutated afterwards: `default_branch` is a probe
    /// input, so moving it needs the rediscovery a rebuilt `Core` does
    /// ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md#reload)).
    overrides: Arc<Vec<ResolvedOverride>>,
    /// The live `exclude` half of the same `[[repo]]` entries, replaced wholesale by
    /// [`Core::set_exclusions`] with no rebuild and no rediscovery, the same shape
    /// `show_submodules` already has: `exclude` decides only whether an operation may reach
    /// a row that is discovered and listed either way, so it is an operate-time filter over
    /// a table that is already correct
    /// ([repo-management.md](https://github.com/paulchiu/repon/blob/main/docs/spec/repo-management.md)'s
    /// "Writing config").
    exclusions: Arc<RwLock<Vec<ResolvedExclusion>>>,
    /// The Set `start` was given, retained so `refresh` can re-run discovery over
    /// the same bounding specification at the head of every Generation
    /// ([discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md),
    /// [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)).
    /// Immutable for the same reason `overrides` is: a Set's `roots` or globs
    /// changing is a config reload, which re-derives a whole new `Core` rather
    /// than mutating this one in place.
    set: SetSpec,
    /// Set once discovery abandons a walk, and never cleared for the life of this
    /// `Core`: it takes the Set out of the automatic refresh path, since
    /// re-running a thirty-second walk at the head of every Generation is not a
    /// degraded mode worth paying for.
    discovery_manual: Arc<AtomicBool>,
    /// How long a re-run discovery walk may run before the still-walking warning
    /// fires; real value is one second outside a test.
    discovery_warn_after: Duration,
    /// How long a re-run discovery walk may run before it is abandoned, in nanoseconds;
    /// real value is [`discovery::ABANDON_AFTER`] outside a test. Shared and atomic so a
    /// test can tighten it after `start`, rather than racing one deadline against both a
    /// walk that must survive and a walk that must not.
    discovery_abandon_after: Arc<AtomicU64>,
    /// The live show-submodules preference a dispatched Generation reads: `true` once
    /// [`Core::set_show_submodules`] last set it that way, `CoreSpec::show_submodules` until
    /// then. Atomic and shared with every `RefreshHandles` clone so toggling it needs no
    /// rebuild and dispatches nothing of its own
    /// ([discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)'s
    /// "Showing Submodules": "toggling is instant, because nothing needs discovering").
    show_submodules: Arc<AtomicBool>,
    settle_gate: Arc<SettleGate>,
    control: Sender<ClockControl>,
    clock_thread: Option<JoinHandle<()>>,
    /// Set by the dedicated thread's discovery-slow watcher if `start`'s one walk
    /// ran a full second without finishing, and by a later re-run's own abandon
    /// path. Read through [`Core::discovery_warning`], the UI's shared warning
    /// slot's one entry point onto discovery, per
    /// [discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md).
    discovery_warning: Arc<Mutex<Option<String>>>,
    /// Reset to zero at the start of every `refresh`, then incremented once per
    /// distinct common dir among that Generation's dispatched entities whose
    /// default-branch chain facts are actually computed, as opposed to reused from
    /// another entity sharing the same common dir. Never persisted across
    /// Generations, per [ADR 0006](https://github.com/paulchiu/repon/blob/main/docs/adr/0006-no-git-state-cache-session-state-by-name.md):
    /// the memo cache itself lives only for the lifetime of one `refresh` call.
    /// Read only by `default_branch_chain_reads_for_test`, which is what proves
    /// [default-branch.md](https://github.com/paulchiu/repon/blob/main/docs/spec/default-branch.md)'s
    /// per-common-dir memoisation actually ran rather than merely agreeing by
    /// coincidence.
    #[allow(dead_code)] // read only by default_branch_chain_reads_for_test
    default_branch_chain_reads: Arc<AtomicUsize>,
    /// The same counter as `default_branch_chain_reads`, for patch equivalence's
    /// own expensive half ([`patch_equivalence::scan_default_branch`]) instead of
    /// the default-branch chain's: reset to zero at the start of every `refresh`,
    /// incremented once per distinct common dir whose default-branch commit
    /// history is actually scanned, as opposed to reused from another entity
    /// sharing the same common dir this Generation. Never persisted across
    /// Generations, per [ADR 0006](https://github.com/paulchiu/repon/blob/main/docs/adr/0006-no-git-state-cache-session-state-by-name.md).
    /// Read only by `patch_identity_reads_for_test`.
    #[allow(dead_code)] // read only by patch_identity_reads_for_test
    patch_identity_reads: Arc<AtomicUsize>,
    /// The bound each actually-run [`patch_equivalence::scan_default_branch`] call
    /// this Generation was passed, one entry per common dir it ran for, in the
    /// order those scans ran; cleared at the start of every `refresh`. Recorded
    /// from inside `patch_identities_for`'s `compute` closure, so this is the value
    /// the production call site used, not a value a test recomputes independently.
    /// Read only by `patch_scan_bounds_for_test`.
    #[allow(dead_code)] // read only by patch_scan_bounds_for_test
    patch_scan_bounds: Arc<Mutex<Vec<Option<gix::ObjectId>>>>,
    /// `true` while one Action fan-out's steps are running, `false` otherwise. Guards
    /// [`Core::run_action`]'s own entry rather than anything a probe touches: only one
    /// fan-out runs at a time, per [ADR 0018](https://github.com/paulchiu/repon/blob/main/docs/adr/0018-an-action-is-a-fanout-of-pty-backed-steps.md)'s
    /// "One Action runs at a time".
    action_running: Arc<AtomicBool>,
    /// The current fan-out's own reach into its steps' children while `action_running` is
    /// true, `None` otherwise: what [`Core::hold_action`], [`Core::continue_action`] and
    /// [`Core::stop_action`] each look up before doing anything, so all three are no-ops
    /// with no fan-out live. Deliberately its own field rather than folded into `pause`/
    /// `resume`'s machinery, per [ADR 0018](https://github.com/paulchiu/repon/blob/main/docs/adr/0018-an-action-is-a-fanout-of-pty-backed-steps.md)'s
    /// own hold and stop verbs: the core is contractually not told why background
    /// work stopped, and a step's child needs SIGSTOP/SIGTERM/SIGKILL, information `pause`
    /// must never carry.
    action_control: Arc<Mutex<Option<Arc<executor::RunControl>>>>,
    /// Every key `refresh`'s own sequential dispatch loop iterated, in the order it iterated
    /// them, cleared at the start of every call: this is dispatch order, not completion
    /// order, recorded synchronously in the loop that decides it, before any `rayon::spawn`
    /// closure ever runs. [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
    /// "Scope and order" fixes dispatch order as the one dial phase C has; completion order
    /// on a concurrent pool is a different, non-deterministic fact this field does not claim
    /// to answer. Read only by `dispatch_log_for_test`.
    #[allow(dead_code)] // read only by dispatch_log_for_test
    dispatch_log: Arc<Mutex<Vec<EntityKey>>>,
    /// Test-only synchronisation points, keyed by entity, letting a test hold the
    /// dispatch loop's state and dirty probes open after that same entity's cheap
    /// outcomes (branch, sync, default branch) have already landed on the table,
    /// so [`refresh`]'s two applies can be proven independent with a blocking wait
    /// rather than a sleep. Always present and normally empty: a Generation reads it
    /// once per entity as it dispatches that entity, and one never registered here
    /// resolves to nothing and proceeds exactly as if this field did not exist.
    /// Registered and read only by the `_for_test` methods below.
    #[allow(dead_code)] // populated and read only by tests
    phase_c_gates: Arc<Mutex<HashMap<EntityKey, PhaseCGateHandle>>>,
    /// The age past which a `Known` `dirty` or `state` cell reads Stale even though
    /// nothing probed it again: `CoreSpec::status_stale_after`'s own copy, applied
    /// inside [`Core::snapshot`] rather than by a background sweep, since
    /// [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
    /// "Staleness" rules out a global clock-driven one.
    status_stale_after: Duration,
    /// Every key the metadata poll's most recent sweep actually re-ran phases A
    /// and B for, in the order it found them moved, cleared at the start of every
    /// sweep. Read only by `poll_reprobed_for_test`, which is what proves a
    /// sweep re-probes the moved entity alone rather than the whole population.
    #[allow(dead_code)] // read only by poll_reprobed_for_test
    poll_reprobed: Arc<Mutex<Vec<EntityKey>>>,
    /// How many metadata-poll sweeps have run in total, whether or not any entity
    /// had moved. Read only by `poll_sweep_count_for_test`, which is what proves a
    /// real tick sent through the dedicated thread's own channel reaches the
    /// sweep at all, distinct from `poll_reprobed` proving what a sweep that found
    /// movement then did.
    #[allow(dead_code)] // read only by poll_sweep_count_for_test
    poll_sweep_count: Arc<AtomicUsize>,
    /// How many periodic-fetch cycles have run in total, whether or not any
    /// repository had a remote to fetch: the immediate first cycle plus one per
    /// `fetch.interval` tick since. Read only by `fetch_cycle_count_for_test`,
    /// which is what proves the immediate cycle ran without waiting on the
    /// recurring cadence at all.
    #[allow(dead_code)] // read only by fetch_cycle_count_for_test
    fetch_cycle_count: Arc<AtomicUsize>,
    /// The network's advertised default branch, per common dir, read from a fetch
    /// handshake's own advertised HEAD alone
    /// ([default-branch.md](https://github.com/paulchiu/repon/blob/main/docs/spec/default-branch.md)'s
    /// "The network"): present only once the periodic fetch or
    /// [`Core::rederive_default_branches`] has actually reached that remote.
    /// Superseded there, never here on read; consulted by every default-branch
    /// probe this crate runs, so an answer landed by one persists across every
    /// later Generation for the life of this `Core`, which is what "supersedes
    /// the local one for that session" means: never written back to any
    /// reference, and gone the moment this `Core` is dropped, per ADR 0012.
    network_default_branch: Arc<Mutex<HashMap<PathBuf, Arc<str>>>>,
    /// The most recently completed periodic-fetch cycle's own failures, replaced
    /// wholesale by [`run_fetch_cycle`] every time it runs. Read through
    /// [`Core::fetch_failures`].
    fetch_failures: Arc<Mutex<FetchFailures>>,
    /// Orders every spawned dispatch body this `Core` starts; see
    /// [`DispatchTurnstile`].
    turnstile: Arc<DispatchTurnstile>,
    /// See [`DiscoveryGate`]. `None` on every production path.
    discovery_gate: Option<DiscoveryGate>,
}

/// One entity's phase C test gate state, guarded by the paired [`Condvar`] stored
/// alongside it in [`Core::phase_c_gates`].
#[derive(Default)]
struct PhaseCGate {
    /// Set once this entity's cheap outcomes have been applied to the table.
    cheap_landed: bool,
    /// Set by a test once it has observed `cheap_landed` and wants phase C (and
    /// D) to proceed.
    may_proceed: bool,
    /// Set once this entity's phase C/D outcomes have been applied to the table
    /// and the settle gate decremented for it.
    finished: bool,
}

/// A [`PhaseCGate`] shared between the dispatch loop and the `_for_test` methods
/// that register, wait on and release it.
type PhaseCGateHandle = Arc<(Mutex<PhaseCGate>, Condvar)>;

impl Core {
    /// Spawns the dedicated thread, starts the first discovery walk on a thread of
    /// its own, and returns a running core at once.
    ///
    /// The table it returns is empty: discovery lands its rows afterwards, which is what
    /// lets a consumer claim the terminal and draw a first frame without waiting out a
    /// walk (refresh.md's "The first frame"). That walk is refresh.md's "Startup"
    /// Generation as well, dispatched over what it found, so a consumer probes its rows
    /// by starting a `Core` and never by asking for a second walk of the same tree.
    /// [`Self::try_settle`] waits for it the way it waits for any other Generation.
    pub fn start(spec: CoreSpec) -> Core {
        Self::start_watched(spec).core
    }

    /// [`Self::start`], keeping the handles `start_internal` hands back.
    fn start_watched(spec: CoreSpec) -> StartForTest {
        let interval = spec.poll_interval.max(Duration::from_nanos(1));
        let ticks = crossbeam_channel::tick(interval);
        let alive = Arc::new(AtomicBool::new(true));
        let fetch_start = FetchStart {
            enabled: spec.fetch.enabled,
            concurrency: spec.fetch.concurrency.max(1),
            ticks: if spec.fetch.enabled {
                crossbeam_channel::tick(spec.fetch.interval.max(Duration::from_nanos(1)))
            } else {
                crossbeam_channel::never()
            },
        };
        start_internal(
            spec,
            Duration::from_secs(1),
            discovery::ABANDON_AFTER,
            ticks,
            fetch_start,
            alive,
            None,
        )
    }

    /// [`Self::start`], blocked until the first discovery has landed on the table.
    ///
    /// For a test, and for nothing else: `start` returns against an empty table
    /// now, so a test that reads the table straight afterwards needs this
    /// rendezvous. It is a join on the discovery thread rather than a poll or a
    /// sleep, so it carries no deadline of its own.
    ///
    /// Gated behind `test-util` (on by default under `cfg(test)` for this crate's own
    /// tests) so a test-only affordance never ships on the default published surface,
    /// per [ADR 0021](https://github.com/paulchiu/repon/blob/main/docs/adr/0021-a-release-is-what-the-tag-pipeline-publishes.md).
    #[cfg(any(test, feature = "test-util"))]
    pub fn start_discovered(spec: CoreSpec) -> Core {
        let mut started = Self::start_watched(spec);
        if let Some(handle) = started.initial_discovery.take() {
            handle
                .join()
                .expect("the first discovery thread should not panic");
        }
        started.core
    }

    /// Starts a new Generation, dispatching a probe for every key in `order` that
    /// the table already knows, in that order. An empty or unknown-only `order`
    /// dispatches nothing and carries no other meaning. Returns immediately: the
    /// probes run on rayon's global pool.
    pub fn refresh(&self, order: &[EntityKey]) -> Generation {
        self.refresh_handles().dispatch(order)
    }

    /// Starts a new Generation over every entity this Generation's own discovery
    /// leaves in the table, in discovery order.
    ///
    /// A Set switch's Generation, per
    /// [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
    /// "Switching Set": the caller has just discarded the old Set's rows, so it has no
    /// order to compute and no keys to name. Unlike [`Self::refresh`], which resolves
    /// the order the caller handed it, this resolves the order after discovery has run,
    /// which is what lets it cover rows the caller could not have named. Startup needs
    /// none of this: [`Self::start`]'s own walk is that Generation. Returns
    /// immediately, the same way `refresh` does.
    pub fn refresh_all(&self) -> Generation {
        self.refresh_handles().dispatch_over_everything()
    }

    /// Re-derives `default_branch` alone for every key in `keys` already known to
    /// the table, in a fresh Generation, per
    /// [default-branch.md](https://github.com/paulchiu/repon/blob/main/docs/spec/default-branch.md)'s
    /// "A user-triggered re-derive over the Selection ... on demand" and
    /// [keybindings.md](https://github.com/paulchiu/repon/blob/main/docs/spec/keybindings.md)'s
    /// `b`. Unlike [`Self::refresh`], this never re-runs discovery and never
    /// touches any other cell on any entity, known or not: a key outside `keys`
    /// is left exactly as it was, and so is every cell but `default_branch` on a
    /// key inside it.
    ///
    /// Runs the local chain exactly as any other refresh would, then a
    /// handshake-only network probe per distinct common dir among `keys`
    /// (`fetch::probe_remote_head`): no pack requested and no ref updated, which is
    /// "without fetching". Its answer, once landed on `network_default_branch`, is
    /// what `supersede_with_network` applies here and on every later probe of that
    /// common dir for the life of this `Core`.
    ///
    /// Returns immediately, which is also why a stalled remote has nothing to end
    /// it here: the deadline sweep is per entity, not per cell, so this is on the
    /// open-questions register rather than closed. The probes run on a plain thread, never rayon's
    /// global pool, for the reason `fetch::run_bounded`'s own doc comment gives
    /// the periodic fetch's identical choice: a remote blocked on the network
    /// for seconds must never take a worker away from the pool every other
    /// probe shares.
    pub fn rederive_default_branches(&self, keys: &[EntityKey]) -> Generation {
        let generation = {
            let mut table = self.table.write().unwrap();
            table.generation += 1;
            Generation::new(table.generation)
        };

        let dispatched: Vec<RederiveCandidate> = {
            let mut table = self.table.write().unwrap();
            let mut dispatched = Vec::new();
            for key in keys {
                let Some(&idx) = table.index.get(key) else {
                    continue;
                };
                table.entities[idx].default_branch.begin_probe();
                let common_dir = Arc::clone(&table.entities[idx].common_dir);
                let override_branch = find_entry(&self.overrides, key.path(), &common_dir)
                    .and_then(|entry| entry.default_branch.clone());
                let repo = table.repos.get(key).cloned();
                let kind = table.entities[idx].kind;
                dispatched.push(RederiveCandidate {
                    key: key.clone(),
                    path: key.path().to_path_buf(),
                    common_dir,
                    repo,
                    override_branch,
                    kind,
                });
            }
            dispatched
        };

        if dispatched.is_empty() {
            return generation;
        }

        begin_probes_owed(&self.settle_gate, dispatched.len());

        let table = Arc::clone(&self.table);
        let settle_gate = Arc::clone(&self.settle_gate);
        let network_default_branch = Arc::clone(&self.network_default_branch);
        thread::spawn(move || {
            let common_dirs: HashSet<Arc<Path>> = dispatched
                .iter()
                .map(|candidate| Arc::clone(&candidate.common_dir))
                .collect();
            probe_network_default_branches(&common_dirs, &network_default_branch);

            // Scoped to this one call, never shared with a concurrent `refresh`'s own
            // memo: the local chain's own per-common-dir facts are cheap enough
            // (`default-branch.md`'s "about 20ms") that a fresh cache here costs this
            // call nothing a shared one would have saved.
            let chain_cache: ChainFactsCache = Mutex::new(HashMap::new());
            let chain_reads = AtomicUsize::new(0);
            let never_cancelled = AtomicBool::new(false);

            for candidate in dispatched {
                let RederiveCandidate {
                    key,
                    path,
                    common_dir,
                    repo,
                    override_branch,
                    kind,
                } = candidate;
                let network_branch = network_branch_for(&network_default_branch, &common_dir);
                let resolution = probe_default_branch_memoised(
                    &path,
                    repo.as_deref(),
                    &common_dir,
                    DefaultBranchHints {
                        override_branch: override_branch.as_deref(),
                        network_branch: network_branch.as_deref(),
                    },
                    kind,
                    &never_cancelled,
                    &ChainFactsMemo {
                        cache: &chain_cache,
                        reads: &chain_reads,
                    },
                );
                {
                    let mut table = table.write().unwrap();
                    if let (Some(&idx), Some(resolution)) = (table.index.get(&key), resolution) {
                        table.entities[idx].apply_default_branch_resolution(generation, resolution);
                    }
                }
                complete_one(&settle_gate);
            }
        });

        generation
    }

    /// Clones out every `Arc` a Generation's dispatch reads, plus the plain data
    /// ([`SetSpec`], the two durations) it cannot share by reference: a handful of
    /// refcount bumps, never a copy of the table itself. This is what lets
    /// [`run_action`](Core::run_action)'s completion, which runs on a plain thread
    /// this `Core` does not own and outlives the `&self` borrow that started it,
    /// start the one normal Generation `docs/spec/actions.md`'s "Refreshing around a
    /// run" promises through the exact same [`RefreshHandles::dispatch`] `refresh`
    /// itself calls, rather than a second, drifting copy of its body.
    fn refresh_handles(&self) -> RefreshHandles {
        RefreshHandles {
            table: Arc::clone(&self.table),
            overrides: Arc::clone(&self.overrides),
            exclusions: Arc::clone(&self.exclusions),
            set: self.set.clone(),
            discovery_manual: Arc::clone(&self.discovery_manual),
            discovery_warn_after: self.discovery_warn_after,
            discovery_abandon_after: Arc::clone(&self.discovery_abandon_after),
            discovery_warning: Arc::clone(&self.discovery_warning),
            show_submodules: Arc::clone(&self.show_submodules),
            settle_gate: Arc::clone(&self.settle_gate),
            default_branch_chain_reads: Arc::clone(&self.default_branch_chain_reads),
            patch_identity_reads: Arc::clone(&self.patch_identity_reads),
            patch_scan_bounds: Arc::clone(&self.patch_scan_bounds),
            dispatch_log: Arc::clone(&self.dispatch_log),
            phase_c_gates: Arc::clone(&self.phase_c_gates),
            network_default_branch: Arc::clone(&self.network_default_branch),
            turnstile: Arc::clone(&self.turnstile),
            discovery_gate: self.discovery_gate.clone(),
        }
    }

    /// Re-probes one entity synchronously against the table's current Generation,
    /// which is what a Launcher return needs before a normal Generation starts.
    /// Inserts a fresh entity for an unknown key rather than panicking, since a
    /// caller can otherwise only reach this with a key `snapshot` just handed it.
    pub fn probe_now(&self, key: &EntityKey) -> EntityState {
        // An `Arc` rather than a bare flag: [`probe_status`] hands gix an owned clone of
        // its cancel token the way `refresh`'s own dispatch does, and every other probe
        // below still takes it as `&AtomicBool` through the same deref coercion.
        let never_cancelled = Arc::new(AtomicBool::new(false));
        let (cached_repo, common_dir_hint, probes_state, probes_base, kind) = {
            let table = self.table.read().unwrap();
            let repo = table.repos.get(key).cloned();
            let common_dir = table
                .index
                .get(key)
                .map(|&idx| Arc::clone(&table.entities[idx].common_dir));
            // An unknown key has no entity yet to ask, and falls back to `false`,
            // matching the fallback insert below: a freshly inserted `Kind::Repo`
            // entity's `state` is `NotApplicable` from construction too, and its
            // `base` is not (only a Submodule's is).
            let probes_state = table
                .index
                .get(key)
                .map(|&idx| table.entities[idx].probes_state())
                .unwrap_or(false);
            let probes_base = table
                .index
                .get(key)
                .map(|&idx| table.entities[idx].probes_base())
                .unwrap_or(true);
            // Same fallback as `probes_state`/`probes_base`: an unknown key falls back to
            // the `Kind::Repo` the insert below actually gives it.
            let kind = table
                .index
                .get(key)
                .map(|&idx| table.entities[idx].kind)
                .unwrap_or(Kind::Repo);
            (repo, common_dir, probes_state, probes_base, kind)
        };
        let common_dir_hint = common_dir_hint.unwrap_or_else(|| Arc::from(key.path().join(".git")));
        let override_branch = find_entry(&self.overrides, key.path(), &common_dir_hint)
            .and_then(|entry| entry.default_branch.clone());
        let excluded = excluded_by(
            &self.exclusions.read().unwrap(),
            key.path(),
            &common_dir_hint,
        );

        let branch_outcome =
            probe_branch(key.path(), cached_repo.as_deref(), kind, &never_cancelled);
        let sync_outcome = probe_sync(
            key.path(),
            cached_repo.as_deref(),
            branch_outcome.as_ref().map(|(settled, ..)| settled),
            kind,
            &never_cancelled,
        );
        let default_branch_outcome = probe_default_branch(
            key.path(),
            cached_repo.as_deref(),
            DefaultBranchHints {
                override_branch: override_branch.as_deref(),
                network_branch: network_branch_for(&self.network_default_branch, &common_dir_hint)
                    .as_deref(),
            },
            kind,
            &never_cancelled,
        );
        let base_outcome = if probes_base {
            probe_base(
                key.path(),
                cached_repo.as_deref(),
                branch_outcome.as_ref().map(|(settled, ..)| settled),
                default_branch_outcome.as_ref().map(|r| &r.settled),
                &never_cancelled,
            )
        } else {
            None
        };
        let state_outcome = if probes_state {
            // A single synchronous re-probe shares nothing with any Generation's
            // dispatch, so a throwaway cache is exactly as much sharing as this
            // one call needs. Its bound gate has exactly one entity to hear
            // from: itself, so it never actually waits.
            let patch_cache: PatchIdentityCache = Mutex::new(HashMap::new());
            let patch_reads = AtomicUsize::new(0);
            let patch_scan_bounds = Mutex::new(Vec::new());
            let gate = BoundGate::new(1);
            let mut report = GateReport::new(&gate);
            let memo = PatchEquivalenceMemo {
                cache: &patch_cache,
                reads: &patch_reads,
                scan_bounds: &patch_scan_bounds,
            };
            probe_worktree_state(
                key.path(),
                cached_repo.as_deref(),
                default_branch_outcome.as_ref().map(|r| &r.settled),
                &common_dir_hint,
                &never_cancelled,
                &memo,
                &mut report,
            )
        } else {
            None
        };
        let dirty_outcome =
            probe_status(key.path(), cached_repo.as_deref(), kind, &never_cancelled);

        let mut table = self.table.write().unwrap();
        let generation = Generation::new(table.generation);
        let idx = match table.index.get(key).copied() {
            Some(idx) => idx,
            None => {
                let name = display_name(key.path());
                table.entities.push(EntityState::new(
                    key.clone(),
                    name,
                    common_dir_hint,
                    Kind::Repo,
                ));
                let idx = table.entities.len() - 1;
                table.index.insert(key.clone(), idx);
                idx
            }
        };
        table.entities[idx].excluded = excluded;
        if let Some((settled, in_progress, recent)) = branch_outcome {
            table.entities[idx].apply_branch_probe(generation, settled, in_progress, recent);
        }
        if let Some(settled) = sync_outcome {
            table.entities[idx].sync.settle(generation, settled);
        }
        if let Some(settled) = base_outcome {
            table.entities[idx].base.settle(generation, settled);
        }
        if let Some(resolution) = default_branch_outcome {
            table.entities[idx].apply_default_branch_resolution(generation, resolution);
        }
        if let Some(settled) = state_outcome {
            table.entities[idx].state.settle(generation, settled);
        }
        if let Some(settled) = dirty_outcome {
            table.entities[idx].dirty.settle(generation, settled);
        }
        table.entities[idx].clone()
    }

    /// Clones the whole table now, without waiting for anything in flight. Ages
    /// every entity's `dirty` and `state` cells into Stale here, on the clone
    /// rather than the stored table, so a snapshot stays a pure read: the other
    /// staleness writer, poll evidence, does mutate the stored table, because a
    /// detected move is itself a fact worth keeping, but elapsed time is not.
    pub fn snapshot(&self) -> Snapshot {
        let table = self.table.read().unwrap();
        let mut entities = table.entities.clone();
        for entity in &mut entities {
            entity.age_status_cells(self.status_stale_after);
        }
        Snapshot {
            generation: Generation::new(table.generation),
            discovered_at: table.discovered_at,
            entities,
        }
    }

    /// Blocks until nothing is in flight or `within` elapses, then returns a snapshot.
    /// The machine-readable consumer's whole loop.
    ///
    /// `Ok` is a table that actually settled. `Err` is the wait giving up, carrying the
    /// snapshot as it stood at that moment so a caller that means to degrade still has
    /// something to degrade with. The two are separate arms rather than one return value
    /// because they are separate facts: a half-populated table read as a settled one is a
    /// wrong answer, not a late one, and it reads as a defect several steps downstream with
    /// nothing left naming the wait.
    pub fn try_settle(&self, within: Duration) -> Result<Snapshot, Snapshot> {
        let (lock, cvar) = &*self.settle_gate;
        let guard = lock.lock().unwrap();
        let (guard, timeout) = cvar
            .wait_timeout_while(guard, within, |counts| !counts.is_settled())
            .unwrap();
        // Released before the snapshot below, which takes the table lock: holding both at
        // once is a lock order nothing else in this file takes.
        drop(guard);
        let snapshot = self.snapshot();
        if timeout.timed_out() {
            Err(snapshot)
        } else {
            Ok(snapshot)
        }
    }

    /// Blocks until nothing is in flight, panicking once [`liveness::BACKSTOP`] expires.
    /// For a test.
    ///
    /// Takes no deadline, unlike [`Self::try_settle`], because every deadline this ever
    /// took was a number guessed against the machine its author had: the wait is on a
    /// liveness property ("the Generation I just dispatched lands"), which carries no
    /// wall-clock bound of its own, so the only honest bound is the shared backstop.
    /// A wait whose *number* is the claim ("nothing arrives within 200ms") is a different
    /// wait and belongs on [`Self::try_settle`], which reports an expiry rather than
    /// panicking on one.
    #[cfg(any(test, feature = "test-util"))]
    pub fn settle(&self) -> Snapshot {
        self.settle_within(liveness::BACKSTOP)
    }

    /// [`Self::settle`] against an explicit deadline, so this crate's own tests can
    /// exercise the expiry path without waiting out a real backstop. The same seam
    /// `liveness::wait_within` gives its module.
    #[cfg(any(test, feature = "test-util"))]
    fn settle_within(&self, deadline: Duration) -> Snapshot {
        self.try_settle(deadline).unwrap_or_else(|_| {
            // Read out and released before the panic below: unwinding out of a held guard
            // poisons the gate, and every later `lock().unwrap()` on it, `Drop`'s included,
            // then panics on the way out and turns a named report into an abort.
            let (probes, dispatches) = {
                let counts = self.settle_gate.0.lock().unwrap();
                (counts.probes, counts.dispatches)
            };
            liveness::expired(
                deadline,
                "everything this Core has in flight to land",
                &format!("{probes} probe(s) and {dispatches} dispatch(es) still outstanding"),
            )
        })
    }

    /// What deleting `key`'s working tree destroys, read fresh right now
    /// ([repo-management.md](https://github.com/paulchiu/repon/blob/main/docs/spec/repo-management.md)'s
    /// "The confirm gate"). Every one of the three is a git read rather than a fold over this
    /// entity's Cells or over the table: the gate is answering "what will accepting this
    /// destroy", a Cell carries whatever the last Generation left there, and the table is
    /// bounded by the active Set's roots, so a linked Worktree outside them would go
    /// unnamed. Both are the wrong tense, or the wrong scope, for a question with no undo.
    ///
    /// `uncommitted` is both halves of "not in a commit": the index against the working tree
    /// (`git::dirty_counts`) and `HEAD` against the index (`git::staged_changes`). The
    /// second is the one a `git add` with no commit lands in, and the one the dirty column
    /// deliberately never asks about.
    ///
    /// Errors rather than reporting zero when any read fails, so a gate never says "nothing
    /// to lose" because it could not look.
    pub fn delete_risk(&self, key: &EntityKey) -> Result<DeleteRisk, git::ProbeError> {
        let repo = git::open_thread_safe(key.path())?.to_thread_local();
        let dirty = git::dirty_counts(&repo, Arc::new(AtomicBool::new(false)))?;
        let staged = git::staged_changes(&repo)?;
        let (unpushed_commits, unpushed_branches) = git::unpushed(&repo)?;
        let linked_worktrees = git::linked_worktrees(&repo)?;
        Ok(DeleteRisk {
            uncommitted: dirty.total() > 0 || staged,
            unpushed_commits,
            unpushed_branches,
            linked_worktrees,
        })
    }

    /// The administrative directory `git worktree remove` deletes for `key`'s own linked
    /// Worktree, read fresh right now. `Err` when `key`'s own path cannot even be opened as
    /// a git repository, which is what "the parent Repo is gone or unreadable" means for a
    /// `delete` on a Worktree row
    /// ([repo-management.md](https://github.com/paulchiu/repon/blob/main/docs/spec/repo-management.md)'s
    /// "What `delete` does to a Worktree"): the caller falls back to removing the working
    /// directory alone.
    pub fn worktree_admin_dir(&self, key: &EntityKey) -> Result<PathBuf, git::ProbeError> {
        let repo = git::open_thread_safe(key.path())?.to_thread_local();
        Ok(git::worktree_admin_dir(&repo))
    }

    /// Every linked Worktree's own working directory pointing into `key`'s Repo, read
    /// fresh right now: what deleting a Repo needs to also remove, since each linked
    /// Worktree's directory sits outside the Repo's own and is untouched by removing that
    /// alone
    /// ([repo-management.md](https://github.com/paulchiu/repon/blob/main/docs/spec/repo-management.md)'s
    /// "Deleting a Repo also takes its linked Worktrees with it").
    pub fn linked_worktree_paths(&self, key: &EntityKey) -> Result<Vec<PathBuf>, git::ProbeError> {
        let repo = git::open_thread_safe(key.path())?.to_thread_local();
        git::linked_worktree_paths(&repo)
    }

    /// `delete`'s phase 1: the ignored directories inside the working tree at `path`, read
    /// fresh right now
    /// ([repo-management.md](https://github.com/paulchiu/repon/blob/main/docs/spec/repo-management.md)'s
    /// "Deleting a working tree"). `path` rather than an [`EntityKey`] because a Repo
    /// `delete` runs this once for its own working tree and once more for each linked
    /// Worktree [`Self::linked_worktree_paths`] names, and only the first of those has a Set
    /// row of its own.
    pub fn ignored_directories_for_deletion(
        &self,
        path: &Path,
    ) -> Result<Vec<PathBuf>, git::ProbeError> {
        let repo = git::open_thread_safe(path)?.to_thread_local();
        git::ignored_directories_for_deletion(&repo)
    }

    /// Attempts the fast-forward-only auto-update on `key`'s own Repo, on demand: exactly
    /// `crate::auto_update::attempt`'s own five rules and its own fast-forward, reused
    /// rather than a second implementation for the built-in `sync` action to call by hand
    /// ([repo-management.md](https://github.com/paulchiu/repon/blob/main/docs/spec/repo-management.md)).
    /// Read fresh right now, the same tense [`Self::delete_risk`] reads in: eligibility can
    /// change between the gate and the run, so this is never answered from a Cell.
    pub fn attempt_auto_update(&self, key: &EntityKey) -> AutoUpdateAttempt {
        match crate::auto_update::attempt(key.path()) {
            crate::auto_update::Outcome::Ineligible(crate::auto_update::Ineligible::NotClean) => {
                AutoUpdateAttempt::NotClean
            }
            crate::auto_update::Outcome::Ineligible(crate::auto_update::Ineligible::NoUpstream) => {
                AutoUpdateAttempt::NoUpstream
            }
            crate::auto_update::Outcome::Ineligible(crate::auto_update::Ineligible::NotBehind) => {
                AutoUpdateAttempt::NotBehind
            }
            crate::auto_update::Outcome::Ineligible(
                crate::auto_update::Ineligible::NotFastForward,
            ) => AutoUpdateAttempt::NotFastForward,
            crate::auto_update::Outcome::Updated { .. } => AutoUpdateAttempt::Updated,
            crate::auto_update::Outcome::Failed(error) => AutoUpdateAttempt::Failed(error),
        }
    }

    /// Runs `action`'s own steps against one Entity, on the calling thread, blocking until
    /// they finish rather than handing the run off the way [`Core::run_action`]'s async
    /// fan-out does. A pre or post hook wrapping a built-in ([0032](https://github.com/paulchiu/repon/blob/main/docs/adr/0032-hooks-around-a-built-in-fire-on-its-own-confirm-gate-never-its-completion.md))
    /// needs the outcome before the built-in can proceed or report, which nothing running
    /// off this thread can give in time. Reuses `run_action_for_entity`, the identical
    /// per-step execution `run_action`'s fan-out gives every entity, so a hook and a
    /// configured `[[action]]` never diverge in what a step means; writes nothing to the
    /// table and touches none of `run_action`'s own state (`action_running`, `action_control`),
    /// since a hook is a distinct concern from the one fan-out the palette tracks.
    ///
    /// `None` when `key` names no Entity this table currently knows.
    pub fn run_action_for_entity_blocking(
        &self,
        action: &ActionSpec,
        key: &EntityKey,
    ) -> Option<ActionReceipt> {
        let entity = {
            let table = self.table.read().unwrap();
            let idx = *table.index.get(key)?;
            table.entities[idx].clone()
        };
        let control = executor::RunControl::new();
        Some(run_action_for_entity(&entity, action, &control, &|_| {}))
    }

    /// Vends a [`ManagementHandle`]: the `Send + 'static` seam a management run's own
    /// per-row work moves onto a background thread through, so it stops blocking the caller
    /// the way [`Self::run_action`]'s own fan-out already moves an `Arc<RwLock<Table>>`
    /// clone onto its own thread
    /// ([0033](https://github.com/paulchiu/repon/blob/main/docs/adr/0033-a-management-run-moves-off-the-calling-thread-and-cancels-between-rows.md)).
    pub fn management_handle(&self) -> ManagementHandle {
        ManagementHandle {
            table: Arc::clone(&self.table),
        }
    }

    /// Drops one entity from the table, cancelling any probe in flight against it.
    pub fn dismiss(&self, key: &EntityKey) {
        let mut table = self.table.write().unwrap();
        if let Some(idx) = table.index.remove(key) {
            table.entities.remove(idx);
            for position in table.index.values_mut() {
                if *position > idx {
                    *position -= 1;
                }
            }
        }
        table.poll_fingerprints.remove(key);
        if let Some(in_flight) = table.in_flight.remove(key) {
            in_flight.cancel.store(true, Ordering::Release);
            drop(table);
            complete_one(&self.settle_gate);
        }
    }

    /// Resolves `order` against the table this instant and splits it into the entities
    /// that will actually run and the ones a matching `[[repo]]` `exclude = true`
    /// override sweeps in and skips
    /// ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md#per-repo-entries)).
    /// [`Self::run_action`] and [`Self::operable_count`] both call this rather than
    /// each keeping its own copy of the `!entity.excluded` test, so a consumer's confirm
    /// gate or palette border can never show a count a real run then contradicts
    /// ([`docs/spec/actions.md`](https://github.com/paulchiu/repon/blob/main/docs/spec/actions.md)'s
    /// "The Selection and the gate": "a wrong count would lie twice"). A key `order`
    /// names that no longer resolves (already dismissed, or never discovered) is
    /// silently dropped from both halves.
    fn partition_operable(&self, order: &[EntityKey]) -> (Vec<EntityState>, Vec<EntityState>) {
        let table = self.table.read().unwrap();
        order
            .iter()
            .filter_map(|key| table.index.get(key).map(|&idx| table.entities[idx].clone()))
            .partition(|entity| !entity.excluded)
    }

    /// How many of `order` are operable, i.e. not excluded: [`Self::run_action`]'s own
    /// first move is the identical partition this method itself calls, so this is the one
    /// number a confirm gate and a palette border can both read without either ever
    /// drifting from what that first move keeps. Not the final count a run acts on once
    /// `action.when` is `Some`: [`Self::applicability`] narrows this same set further, and
    /// [`Self::run_action`] itself only ever runs the rows that narrowing proves.
    pub fn operable_count(&self, order: &[EntityKey]) -> usize {
        self.partition_operable(order).0.len()
    }

    /// How many Entities in the live table are Vanished. Reads the table in place rather
    /// than through [`Self::snapshot`], so a caller needing only the count does not pay for
    /// a clone of the whole table and its staleness pass on every frame.
    pub fn vanished_count(&self) -> usize {
        self.table
            .read()
            .unwrap()
            .entities
            .iter()
            .filter(|entity| entity.presence == Presence::Vanished)
            .count()
    }

    /// How an Action's `when` predicate divides the very rows [`Self::operable_count`]
    /// counts: the identical partition runs first, so an excluded row is subtracted before
    /// the predicate ever sees it and `when` narrows what is left rather than replacing that
    /// subtraction
    /// ([`docs/spec/actions.md`](https://github.com/paulchiu/repon/blob/main/docs/spec/actions.md)'s
    /// "The Selection and the gate"). A palette calls this ahead of time, to report a count
    /// before a choice is even made; [`Self::run_action`] runs the identical classification
    /// against the identical rows once a choice is confirmed, over `ActionSpec::when` rather
    /// than an argument of its own, so a preview and a real run can never disagree.
    ///
    /// The tally lives here rather than in the consumer for that reason alone:
    /// `partition_operable` is this type's own, so a caller cannot count applicability over
    /// a set the run would not act on.
    pub fn applicability(&self, order: &[EntityKey], when: &Filter) -> Applicability {
        when.applicability(self.partition_operable(order).0.iter())
    }

    /// `true` while one Action fan-out's steps are still running, the consumer-facing read
    /// of `action_running` ([ADR 0018](https://github.com/paulchiu/repon/blob/main/docs/adr/0018-an-action-is-a-fanout-of-pty-backed-steps.md)'s
    /// "One Action runs at a time"): what a TUI gates `;`, `s`, `1` to `9` and `Ctrl+R`
    /// against while a run is in flight
    /// ([ADR 0023](https://github.com/paulchiu/repon/blob/main/docs/adr/0023-an-unbuilt-binding-is-not-advertised-and-an-unavailable-one-answers-on-press.md)).
    pub fn action_running(&self) -> bool {
        self.action_running.load(Ordering::Acquire)
    }

    /// `true` while any refresh-shaped dispatch this `Core` started still owes the table
    /// work: a Generation reserved and not yet raised the probes it dispatches, or probes
    /// raised and not yet landed, cancelled or timed out. The same gate [`Core::try_settle`]
    /// blocks on, read here without blocking, so a consumer can report a Refresh's own
    /// progress on screen while it runs rather than waiting for it to finish
    /// ([refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)).
    /// Covers `refresh`, `refresh_all`, `rederive_default_branches`, `probe_now` and the
    /// startup walk alike; an Action's own fan-out never touches this gate, which is what
    /// `action_running` reads instead.
    pub fn refresh_running(&self) -> bool {
        let (lock, _cvar) = &*self.settle_gate;
        !lock.lock().unwrap().is_settled()
    }

    /// Runs `action` across every key in `order` that the table currently knows: each
    /// entity's own steps run in order and stop at that entity's first failure, exactly
    /// as [config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
    /// "Actions" fixes, with later steps recorded `NotRun` rather than silently skipped.
    /// Cross-entity concurrency is bounded by `action.concurrency`, on a
    /// `rayon::ThreadPool` this call builds and owns for the run alone, never rayon's
    /// global pool the probe fan-out shares: a step blocked in `wait()` removes a
    /// worker from whichever pool holds it, and the global pool has none to spare
    /// without starving a refresh in flight
    /// ([`docs/spec/actions.md`](https://github.com/paulchiu/repon/blob/main/docs/spec/actions.md)'s
    /// "The fan-out"). Returns immediately; every step's own child, and this run's
    /// completion, run off the calling thread.
    ///
    /// Returns `false` and touches nothing if a fan-out is already running: only one
    /// runs at a time
    /// ([ADR 0018](https://github.com/paulchiu/repon/blob/main/docs/adr/0018-an-action-is-a-fanout-of-pty-backed-steps.md)'s
    /// "One Action runs at a time"), but the spec settles only that the *palette* goes
    /// inert while one is live, never what a second, concurrent call to this seam itself
    /// should do. Rejecting outright, rather than queuing, is this call's own choice: a
    /// queue needs its own ordering and cancellation story that no acceptance criterion
    /// here asks for.
    ///
    /// An entity in `order` carrying a matching `[[repo]]` `exclude = true`
    /// ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md#per-repo-entries))
    /// never runs a step: it receives a [`Skip::Excluded`] receipt with an empty step list
    /// immediately, the one legitimate producer of `Not applicable`
    /// ([`docs/spec/actions.md`](https://github.com/paulchiu/repon/blob/main/docs/spec/actions.md)'s
    /// "The Selection and the gate"). An unknown key in `order` (already dismissed, or
    /// never discovered) is silently skipped, the same fallback `refresh` gives one.
    ///
    /// `action.when`, once every excluded row is already subtracted, decides what runs
    /// rather than only what a palette reported about it: a row it proves is handed a
    /// step, a row it disproves gets a [`Skip::Inapplicable`] receipt instead, and a row it
    /// cannot settle (a Cell it reads has not settled) gets [`Skip::Unresolved`], since an
    /// unprovable row is not a provable one and a run has no basis to touch it either
    /// (`docs/spec/actions.md`'s "The Selection and the gate", reversing what that
    /// paragraph originally decided). `None` runs every operable row, exactly as before
    /// `when` reached this call.
    ///
    /// Starting a run cancels any in-flight Generation outright rather than sharing
    /// execution with it, and completion starts exactly one normal Generation over
    /// every entity the table currently knows, not only the ones this run touched.
    /// Explicitly not done, for the same reason: re-probing each affected entity
    /// synchronously first, the way a Launcher return does with [`Core::probe_now`].
    /// Both choices, and their measured cost, are
    /// [ADR 0018](https://github.com/paulchiu/repon/blob/main/docs/adr/0018-an-action-is-a-fanout-of-pty-backed-steps.md)'s
    /// ("Refreshing around a run").
    pub fn run_action(&self, action: ActionSpec, order: &[EntityKey]) -> bool {
        if self
            .action_running
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return false;
        }

        // Criterion 3's first half: starting a run cancels any in-flight Generation
        // outright, never sharing the machine with it.
        cancel_in_flight(&self.table, &self.settle_gate);

        let (operable, excluded) = self.partition_operable(order);

        let write_skip_receipts = |entities: &[EntityState], skip: Skip| {
            if entities.is_empty() {
                return;
            }
            let finished_at = Timestamp::now();
            let mut table = self.table.write().unwrap();
            for entity in entities {
                if let Some(&idx) = table.index.get(&entity.key) {
                    table.entities[idx].last_action = Some(ActionReceipt {
                        label: Arc::clone(&action.label),
                        steps: Arc::from(Vec::new()),
                        skip: Some(skip),
                        finished_at,
                        running: None,
                    });
                }
            }
        };

        write_skip_receipts(&excluded, Skip::Excluded);

        let included = match &action.when {
            Some(when) => {
                let Partition {
                    applicable,
                    inapplicable,
                    unresolved,
                } = when.partition(operable);
                write_skip_receipts(&inapplicable, Skip::Inapplicable);
                write_skip_receipts(&unresolved, Skip::Unresolved);
                applicable
            }
            None => operable,
        };

        let table_handle = Arc::clone(&self.table);
        let action_running = Arc::clone(&self.action_running);
        let refresh_handles = self.refresh_handles();
        // Built synchronously here, before this method ever returns, so a caller that
        // calls `stop_action`/`hold_action` the instant `run_action` returns `true` never
        // races an empty `action_control` against the fan-out thread below setting it.
        let control = executor::RunControl::new();
        *self.action_control.lock().unwrap() = Some(Arc::clone(&control));
        let action_control = Arc::clone(&self.action_control);
        // At least one worker regardless of what `action.concurrency` says: 0 has no
        // sensible reading as "run nothing" here (the schema has no floor, only an
        // explicit absence of a *ceiling*, `docs/spec/actions.md`'s "The fan-out"), and
        // `rayon::ThreadPoolBuilder::num_threads(0)` means "let rayon choose" rather
        // than zero workers, which would silently hand this run back to a pool sized by
        // something other than `concurrency`.
        let concurrency = action.concurrency.max(1) as usize;

        // A plain OS thread, never a job on either rayon pool: `RefreshHandles::dispatch`
        // below calls `rayon::spawn`, which targets whichever pool the *calling* thread
        // already belongs to, so running this orchestration from inside the dedicated
        // pool built below would misroute the completion Generation's own probes onto
        // it instead of the global pool every other probe uses.
        thread::spawn(move || {
            let pool = rayon::ThreadPoolBuilder::new()
                .num_threads(concurrency)
                .build()
                .expect("build the Action fan-out's own dedicated pool");

            // Caught rather than left to unwind straight out of this thread: a poisoned
            // `RwLock` from an unrelated earlier panic is enough to panic the
            // `table_handle.write().unwrap()` below, and without `catch_unwind` that
            // would skip the flag reset just past it, leaving `action_running` stuck
            // true for the life of this `Core`.
            let fan_out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                pool.install(|| {
                    included.into_par_iter().for_each(|entity| {
                        let write_receipt = |receipt: ActionReceipt| {
                            let mut table = table_handle.write().unwrap();
                            if let Some(&idx) = table.index.get(&entity.key) {
                                table.entities[idx].last_action = Some(receipt);
                            }
                        };
                        let receipt =
                            run_action_for_entity(&entity, &action, &control, &write_receipt);
                        write_receipt(receipt);
                    });
                });
            }));

            // scan: action-completion-path begin -- criterion 4: nothing from here to the
            // matching end marker below may re-probe an affected entity synchronously the
            // way a Launcher return does with `probe_now`; scoped this narrowly (rather
            // than a whole-crate scan) because a legitimate Launcher-return caller lives
            // in an unrelated call site the same absence claim must not forbid.
            // Criterion 6: the fan-out itself ends the moment every entity's own steps
            // have finished, panic or not; a second `run_action` racing in from here on
            // is racing the completion Generation below, never another fan-out.
            action_running.store(false, Ordering::Release);
            // This run's own `RunControl` is done being reachable: `hold_action`,
            // `continue_action` and `stop_action` all become no-ops again until the next
            // `run_action` replaces this with a fresh one.
            *action_control.lock().unwrap() = None;

            // A panicked fan-out never finished cleanly, so it earns no completion
            // Generation once the flag above is safely reset. Swallowed rather than
            // resumed: the default panic hook already printed it to stderr before
            // `catch_unwind` returned, and this crate carries no logger to hand it to
            // instead.
            let Ok(()) = fan_out else {
                return;
            };

            // Criterion 3's second half: completion starts one normal Generation over
            // every entity currently known, not only the ones this run acted on.
            let all_keys: Vec<EntityKey> = table_handle
                .read()
                .unwrap()
                .entities
                .iter()
                .map(|entity| entity.key.clone())
                .collect();
            refresh_handles.dispatch(&all_keys);
            // scan: action-completion-path end
        });

        true
    }

    /// SIGSTOPs every currently live step's process group in the fan-out `run_action`
    /// started, reversible with [`Self::continue_action`]: suspending a run is reversible,
    /// where cancelling one is not
    /// ([`docs/spec/actions.md`](https://github.com/paulchiu/repon/blob/main/docs/spec/actions.md)'s
    /// "Cancellation and quit"). A no-op while no fan-out is running. Its own verb,
    /// kept apart from [`Self::pause`], which stays ignorant of why background work stopped.
    pub fn hold_action(&self) {
        if let Some(control) = self.action_control.lock().unwrap().as_ref() {
            control.hold();
        }
    }

    /// SIGCONTs every currently live step's process group, undoing [`Self::hold_action`]. A
    /// no-op while no fan-out is running.
    pub fn continue_action(&self) {
        if let Some(control) = self.action_control.lock().unwrap().as_ref() {
            control.continue_run();
        }
    }

    /// Cancels the fan-out `run_action` started: SIGTERM now to every step's process group
    /// still live, SIGKILL after a grace to whichever of those have not exited by then,
    /// because SIGTERM is trappable and SIGKILL is not. A step already running when this is
    /// called becomes `Cancelled`; so does a step, or a whole entity's run, that had not
    /// started, which stays distinct from `NotRun`
    /// ([`docs/spec/actions.md`](https://github.com/paulchiu/repon/blob/main/docs/spec/actions.md)'s
    /// "Cancellation and quit"). A no-op while no fan-out is running. Its own verb,
    /// kept apart from [`Self::pause`] for the same reason [`Self::hold_action`] is.
    pub fn stop_action(&self) {
        if let Some(control) = self.action_control.lock().unwrap().as_ref() {
            control.cancel();
        }
    }

    /// Stops all background work: the dedicated thread stops ticking and every
    /// probe currently in flight is cancelled. The core is never told why.
    pub fn pause(&self) {
        let _ = self.control.send(ClockControl::Pause);
    }

    /// Restarts the dedicated thread's ticking. Nothing is queued to fire on
    /// resume; a normal Generation is the consumer's decision, not this call's.
    pub fn resume(&self) {
        let _ = self.control.send(ClockControl::Resume);
    }

    /// The persistent warning a re-run discovery walk leaves behind once it abandons, or
    /// `None` while none has. Never cleared once set, the same as `discovery_manual`: the
    /// Set stays out of the automatic refresh path for the life of this `Core`. The UI's
    /// shared warning slot polls this every frame, since it can turn from `None` to `Some`
    /// at any point in the run with no reload involved.
    pub fn discovery_warning(&self) -> Option<String> {
        self.discovery_warning.lock().unwrap().clone()
    }

    /// The most recently completed periodic-fetch cycle's own failures, or an
    /// empty [`FetchFailures`] once every fetch in that cycle succeeded, or the
    /// cycle has never run. The UI's shared warning slot polls this every frame,
    /// the same way it polls [`Self::discovery_warning`] and
    /// [`Self::vanished_count`], since a later cycle can replace this at any point
    /// in the run with no reload involved.
    pub fn fetch_failures(&self) -> FetchFailures {
        self.fetch_failures.lock().unwrap().clone()
    }

    /// Sets the live show-submodules preference a Generation's dispatch reads from this
    /// point on: whether a Kind::Submodule entity is probed at all
    /// ([discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)'s
    /// "Showing Submodules"). Takes effect on the next `refresh`, dispatches nothing of its
    /// own and starts no Generation, which is what makes toggling this instant rather than a
    /// rebuild: `CoreSpec`'s own `show_submodules` is only this flag's starting value.
    pub fn set_show_submodules(&self, show_submodules: bool) {
        self.show_submodules
            .store(show_submodules, Ordering::Release);
    }

    /// Writes one receipt per row for work Repon did itself, with no child process anywhere
    /// in it: what a Management operation leaves behind
    /// ([repo-management.md](https://github.com/paulchiu/repon/blob/main/docs/spec/repo-management.md)'s
    /// "Receipts", [`docs/spec/actions.md`](https://github.com/paulchiu/repon/blob/main/docs/spec/actions.md)'s
    /// `OwnWork`).
    ///
    /// The receipt is built here rather than handed in whole, so a consumer supplies only
    /// what Repon did and the words for it: `skip` stays `None`, since a refusal is a row
    /// that was operated on rather than one of the three ways a row is skipped, `running`
    /// stays `None`, since the work is already done, and the step count stays one, since the
    /// operation is one act rather than an ordered list.
    /// `label` is the operation's own name and doubles as the single step's label; the step's
    /// captured output is empty, there being no other program's screen to quote.
    ///
    /// Starts no Generation and dispatches nothing, for the same reason
    /// [`Core::set_exclusions`] does not: a receipt is something Repon did rather than a
    /// reading of the world, so nothing here can make a cell any more or less true. A key the
    /// table no longer holds is skipped, the same fallback every key-addressed entry point
    /// here gives one.
    pub fn record_own_work(&self, label: &str, results: &[(EntityKey, OwnWork, Duration)]) {
        let label: Arc<str> = Arc::from(label);
        let finished_at = Timestamp::now();
        let mut table = self.table.write().unwrap();
        for (key, work, elapsed) in results {
            let Some(&idx) = table.index.get(key) else {
                continue;
            };
            table.entities[idx].last_action = Some(ActionReceipt {
                label: Arc::clone(&label),
                steps: Arc::from(vec![StepResult {
                    label: Arc::clone(&label),
                    outcome: StepOutcome::OwnWork(work.clone()),
                    output: Arc::from(&b""[..]),
                    elapsed: *elapsed,
                    elision: None,
                    shell: false,
                    interactive: false,
                }]),
                skip: None,
                finished_at,
                running: None,
            });
        }
    }

    /// Replaces the live `exclude` half of `[[repo]]` and re-applies it over every row the
    /// table already holds, so the next [`Core::snapshot`] answers with the new reading
    /// ([repo-management.md](https://github.com/paulchiu/repon/blob/main/docs/spec/repo-management.md)'s
    /// "Writing config": an `ignore` takes effect as soon as this call returns).
    ///
    /// Starts no Generation, dispatches nothing and rediscovers nothing, for the same reason
    /// [`Core::set_show_submodules`] does not: `exclude` decides only whether an operation
    /// may reach a row, never what discovery finds or what a probe reads. `default_branch`,
    /// the other key a `[[repo]]` entry may carry, is a probe input and is deliberately not
    /// moved here; it still needs a rebuilt `Core`.
    pub fn set_exclusions(&self, overrides: &[RepoOverride]) {
        let (_, resolved) = resolve_entries(overrides);
        // Written and released before the table lock is taken, never held across it:
        // `rerun_discovery` reads these two in the opposite order.
        {
            let mut exclusions = self.exclusions.write().unwrap();
            *exclusions = resolved.clone();
        }
        let mut table = self.table.write().unwrap();
        for entity in &mut table.entities {
            entity.excluded = excluded_by(&resolved, entity.key.path(), &entity.common_dir);
        }
    }
}

/// The read-only, path-driven operations a management run's per-row work needs
/// (`crates/repon/src/management.rs`'s own `run_one_record`), cloned out of
/// [`Core::management_handle`] rather than borrowed from a live `Core`: `Send + 'static`, so
/// a caller can move it onto a background thread the way [`Core::run_action`]'s own fan-out
/// thread already moves its `Arc<RwLock<Table>>` clone there. Grants none of `Core`'s other
/// state (`action_running`, `action_control`, the clock thread): a management run is a
/// distinct concern from the one fan-out those track, and this handle's own methods touch
/// only the table, exactly as [`Core::run_action_for_entity_blocking`] already does.
#[derive(Clone)]
pub struct ManagementHandle {
    table: Arc<RwLock<Table>>,
}

impl ManagementHandle {
    /// Identical to [`Core::worktree_admin_dir`], against this handle's own table clone.
    pub fn worktree_admin_dir(&self, key: &EntityKey) -> Result<PathBuf, git::ProbeError> {
        let repo = git::open_thread_safe(key.path())?.to_thread_local();
        Ok(git::worktree_admin_dir(&repo))
    }

    /// Identical to [`Core::linked_worktree_paths`], against this handle's own table clone.
    pub fn linked_worktree_paths(&self, key: &EntityKey) -> Result<Vec<PathBuf>, git::ProbeError> {
        let repo = git::open_thread_safe(key.path())?.to_thread_local();
        git::linked_worktree_paths(&repo)
    }

    /// Identical to [`Core::ignored_directories_for_deletion`], against this handle's own
    /// table clone.
    pub fn ignored_directories_for_deletion(
        &self,
        path: &Path,
    ) -> Result<Vec<PathBuf>, git::ProbeError> {
        let repo = git::open_thread_safe(path)?.to_thread_local();
        git::ignored_directories_for_deletion(&repo)
    }

    /// Identical to [`Core::attempt_auto_update`].
    pub fn attempt_auto_update(&self, key: &EntityKey) -> AutoUpdateAttempt {
        match crate::auto_update::attempt(key.path()) {
            crate::auto_update::Outcome::Ineligible(crate::auto_update::Ineligible::NotClean) => {
                AutoUpdateAttempt::NotClean
            }
            crate::auto_update::Outcome::Ineligible(crate::auto_update::Ineligible::NoUpstream) => {
                AutoUpdateAttempt::NoUpstream
            }
            crate::auto_update::Outcome::Ineligible(crate::auto_update::Ineligible::NotBehind) => {
                AutoUpdateAttempt::NotBehind
            }
            crate::auto_update::Outcome::Ineligible(
                crate::auto_update::Ineligible::NotFastForward,
            ) => AutoUpdateAttempt::NotFastForward,
            crate::auto_update::Outcome::Updated { .. } => AutoUpdateAttempt::Updated,
            crate::auto_update::Outcome::Failed(error) => AutoUpdateAttempt::Failed(error),
        }
    }

    /// Identical to [`Core::run_action_for_entity_blocking`], against this handle's own
    /// table clone rather than a live `Core`.
    pub fn run_action_for_entity_blocking(
        &self,
        action: &ActionSpec,
        key: &EntityKey,
    ) -> Option<ActionReceipt> {
        let entity = {
            let table = self.table.read().unwrap();
            let idx = *table.index.get(key)?;
            table.entities[idx].clone()
        };
        let control = executor::RunControl::new();
        Some(run_action_for_entity(&entity, action, &control, &|_| {}))
    }
}

/// Every `Arc` and plain-data field a Generation's dispatch reads, owned rather than
/// borrowed: [`Core::refresh_handles`] is the only constructor once a `Core` exists,
/// and its own doc comment carries the reason this exists at all. `start_internal`
/// builds one directly, since the periodic fetch's own completion Generation needs
/// this before there is a `Core` to ask; `Clone` is what lets that one value serve
/// both the recurring cadence and the immediate first cycle without a second,
/// drifting construction. Field names and types mirror `Core`'s own exactly, so
/// [`Self::dispatch`] and [`Self::rerun_discovery`] are `refresh` and
/// `rerun_discovery`'s bodies moved verbatim, `self.field` unchanged.
#[derive(Clone)]
struct RefreshHandles {
    table: Arc<RwLock<Table>>,
    overrides: Arc<Vec<ResolvedOverride>>,
    /// [`Core::exclusions`]'s own clone, so a re-run discovery's newly found rows take
    /// whatever `exclude` says right now rather than whatever it said at `start`.
    exclusions: Arc<RwLock<Vec<ResolvedExclusion>>>,
    set: SetSpec,
    discovery_manual: Arc<AtomicBool>,
    discovery_warn_after: Duration,
    discovery_abandon_after: Arc<AtomicU64>,
    discovery_warning: Arc<Mutex<Option<String>>>,
    show_submodules: Arc<AtomicBool>,
    settle_gate: Arc<SettleGate>,
    default_branch_chain_reads: Arc<AtomicUsize>,
    patch_identity_reads: Arc<AtomicUsize>,
    patch_scan_bounds: Arc<Mutex<Vec<Option<gix::ObjectId>>>>,
    dispatch_log: Arc<Mutex<Vec<EntityKey>>>,
    phase_c_gates: Arc<Mutex<HashMap<EntityKey, PhaseCGateHandle>>>,
    /// [`Core::network_default_branch`]'s own clone: [`run_fetch_cycle`] writes
    /// into it once a fetch's own handshake advertises a HEAD, and this
    /// dispatch's own default-branch probes read it back the same Generation.
    network_default_branch: Arc<Mutex<HashMap<PathBuf, Arc<str>>>>,
    /// [`Core::turnstile`]'s own clone, so every dispatch this `Core` starts,
    /// wherever it is called from, queues in the one order.
    turnstile: Arc<DispatchTurnstile>,
    /// [`Core::discovery_gate`]'s own clone; `None` on every production path.
    discovery_gate: Option<DiscoveryGate>,
}

/// Runs the spawned dispatch bodies in the order their Generations were reserved.
///
/// Reserving the number is what a caller waits for; everything after it happens on
/// a thread of its own, and two of those threads reaching the table out of order
/// would let an older Generation cancel a newer one's in-flight entries and then
/// record itself as the live one, which is refresh.md's supersession rule read
/// backwards. A ticket taken under the same lock that mints the Generation, and
/// served in ticket order, is what stops that.
#[derive(Default)]
struct DispatchTurnstile {
    /// The ticket whose body may run, and the [`Condvar`] every waiting body sleeps on.
    serving: Mutex<u64>,
    ready: Condvar,
    /// The next ticket to hand out. Only ever read under the table write lock
    /// [`RefreshHandles::reserve_generation`] holds, so tickets and Generations
    /// are issued in the one order.
    next: AtomicU64,
}

impl DispatchTurnstile {
    fn reserve(&self) -> u64 {
        self.next.fetch_add(1, Ordering::AcqRel)
    }

    /// Blocks until `ticket` is the one being served. The returned guard releases
    /// the next ticket when it drops, panic included, so one body that unwinds
    /// cannot wedge every dispatch after it.
    fn take(&self, ticket: u64) -> DispatchTurn<'_> {
        let serving = self.serving.lock().unwrap();
        drop(
            self.ready
                .wait_while(serving, |serving| *serving != ticket)
                .unwrap(),
        );
        DispatchTurn {
            turnstile: self,
            ticket,
        }
    }
}

/// One body's turn at the [`DispatchTurnstile`], held for as long as that body runs.
struct DispatchTurn<'a> {
    turnstile: &'a DispatchTurnstile,
    ticket: u64,
}

impl Drop for DispatchTurn<'_> {
    fn drop(&mut self) {
        let mut serving = self.turnstile.serving.lock().unwrap();
        *serving = self.ticket + 1;
        self.turnstile.ready.notify_all();
    }
}

impl RefreshHandles {
    /// `Core::refresh`'s whole body, moved here so `run_action`'s completion can call
    /// the identical dispatch from a thread that owns no reference to `Core` itself.
    ///
    /// Reserves this Generation's number and its turnstile place on the calling
    /// thread and does everything else, discovery's own walk included, on a thread
    /// of its own, the shape [`Core::rederive_default_branches`] already takes: no
    /// caller waits out a walk, and every one of them is fire and forget past the
    /// number this returns.
    fn dispatch(&self, order: &[EntityKey]) -> Generation {
        let (generation, ticket) = self.reserve_generation();
        begin_dispatch(&self.settle_gate);
        let handles = self.clone();
        let order = order.to_vec();
        thread::spawn(move || {
            let _turn = handles.turnstile.take(ticket);
            handles.run_generation(&order, generation);
            finish_dispatch(&handles.settle_gate);
        });
        generation
    }

    /// [`Core::refresh_all`]'s whole body: the same reservation and the same spawned
    /// shape as [`Self::dispatch`], with the order read off the table this
    /// Generation's own discovery just reconciled rather than taken from a caller.
    fn dispatch_over_everything(&self) -> Generation {
        let (generation, ticket) = self.reserve_generation();
        begin_dispatch(&self.settle_gate);
        let handles = self.clone();
        thread::spawn(move || {
            let _turn = handles.turnstile.take(ticket);
            handles.rediscover();
            let order: Vec<EntityKey> = handles
                .table
                .read()
                .unwrap()
                .entities
                .iter()
                .map(|entity| entity.key.clone())
                .collect();
            handles.dispatch_probes(&order, generation);
            finish_dispatch(&handles.settle_gate);
        });
        generation
    }

    /// Takes this Generation's number and its turnstile ticket under one hold of
    /// the table lock, so the two orders can never disagree.
    fn reserve_generation(&self) -> (Generation, u64) {
        let mut table = self.table.write().unwrap();
        table.generation += 1;
        (Generation::new(table.generation), self.turnstile.reserve())
    }

    /// [`Self::dispatch`]'s spawned body: both halves of discovery, then the probe
    /// fan-out for `order`.
    fn run_generation(&self, order: &[EntityKey], generation: Generation) {
        self.rediscover();
        self.dispatch_probes(order, generation);
    }

    /// Both halves of discovery at the head of one Generation, per refresh.md and
    /// discovery.md: an entity no longer found becomes Vanished, and one found again
    /// (new, or previously Vanished) is Present. Skipped once an earlier walk has
    /// abandoned, which takes the Set out of this automatic path until a fresh `Core`
    /// starts over different roots.
    fn rediscover(&self) {
        if !self.discovery_manual.load(Ordering::Acquire) {
            self.rerun_discovery();
        }
    }

    /// The probe fan-out alone, against the table as it stands: one rayon task per
    /// dispatched entity, exactly as before this Generation's discovery moved off
    /// the calling thread. Split out from [`Self::run_generation`] so
    /// [`Self::dispatch_over_everything`], which has to resolve its order between the walk
    /// and the fan-out, shares this body rather than keeping a second copy of it.
    fn dispatch_probes(&self, order: &[EntityKey], generation: Generation) {
        // Scoped to this one Generation, per default-branch.md's "memoised per
        // common dir within a single refresh generation": a fresh cache every
        // call, never carried over, never touched by the previous Generation's
        // still-finishing tasks holding their own clone of the old one.
        self.default_branch_chain_reads.store(0, Ordering::Release);
        self.patch_identity_reads.store(0, Ordering::Release);
        self.patch_scan_bounds.lock().unwrap().clear();
        self.dispatch_log.lock().unwrap().clear();

        let generation_number = generation.value();
        let mut table = self.table.write().unwrap();
        table
            .generation_started_at
            .insert(generation_number, Instant::now());

        let show_submodules = self.show_submodules.load(Ordering::Acquire);
        let mut dispatched = Vec::new();
        for key in order {
            let Some(&idx) = table.index.get(key) else {
                continue;
            };
            if !dispatches_kind(table.entities[idx].kind, show_submodules) {
                // Narrows the work, not merely the view: a hidden Submodule's Cells are
                // left exactly as this Generation found them, so a normal Generation pays
                // nothing for it (`docs/spec/discovery.md`'s "Showing Submodules").
                continue;
            }
            if let Some(previous) = table.in_flight.remove(key) {
                previous.cancel.store(true, Ordering::Release);
            }
            let cancel = Arc::new(AtomicBool::new(false));
            table.in_flight.insert(
                key.clone(),
                InFlight {
                    generation: generation_number,
                    cancel: Arc::clone(&cancel),
                },
            );
            begin_probes(&mut table.entities[idx]);
            dispatched.push((key.clone(), cancel));
        }

        if dispatched.is_empty() {
            return;
        }

        begin_probes_owed(&self.settle_gate, dispatched.len());
        let repos: Vec<Option<Arc<gix::ThreadSafeRepository>>> = dispatched
            .iter()
            .map(|(key, _)| table.repos.get(key).cloned())
            .collect();
        let override_branches: Vec<Option<String>> = dispatched
            .iter()
            .map(|(key, _)| {
                let idx = table.index[key];
                let common_dir = &table.entities[idx].common_dir;
                find_entry(&self.overrides, key.path(), common_dir)
                    .and_then(|entry| entry.default_branch.clone())
            })
            .collect();
        let network_branches: Vec<Option<Arc<str>>> = dispatched
            .iter()
            .map(|(key, _)| {
                let idx = table.index[key];
                let common_dir = &table.entities[idx].common_dir;
                network_branch_for(&self.network_default_branch, common_dir)
            })
            .collect();
        let common_dirs: Vec<Arc<Path>> = dispatched
            .iter()
            .map(|(key, _)| Arc::clone(&table.entities[table.index[key]].common_dir))
            .collect();
        let probes_state: Vec<bool> = dispatched
            .iter()
            .map(|(key, _)| table.entities[table.index[key]].probes_state())
            .collect();
        let probes_base: Vec<bool> = dispatched
            .iter()
            .map(|(key, _)| table.entities[table.index[key]].probes_base())
            .collect();
        let kinds: Vec<Kind> = dispatched
            .iter()
            .map(|(key, _)| table.entities[table.index[key]].kind)
            .collect();
        drop(table);

        // Scoped to this dispatch alone: every task below gets its own clone of
        // this `Arc`, and once they all finish and drop it, the cache and every
        // `ChainFacts` it holds are freed. Nothing here outlives one Generation.
        let chain_cache: Arc<ChainFactsCache> = Arc::new(Mutex::new(HashMap::new()));
        // Same lifetime as `chain_cache`, one dispatch's worth: patch
        // equivalence's own per-common-dir memo, per default-branch.md's "Two
        // passes on screen".
        let patch_cache: Arc<PatchIdentityCache> = Arc::new(Mutex::new(HashMap::new()));
        // One gate per common dir with at least one entity that will run
        // `landing::probe` this Generation, sized up front so it is known
        // exactly how many entities owe it a report before any of them run;
        // see `BoundGate`.
        let bound_gates: Arc<HashMap<Arc<Path>, BoundGate>> = Arc::new({
            let mut counts: HashMap<Arc<Path>, usize> = HashMap::new();
            for (common_dir, probes_state) in common_dirs.iter().zip(&probes_state) {
                if *probes_state {
                    *counts.entry(Arc::clone(common_dir)).or_insert(0) += 1;
                }
            }
            counts
                .into_iter()
                .map(|(dir, count)| (dir, BoundGate::new(count)))
                .collect()
        });

        for (
            (
                (
                    (((((key, cancel), repo), override_branch), network_branch), common_dir),
                    probes_state,
                ),
                probes_base,
            ),
            kind,
        ) in dispatched
            .into_iter()
            .zip(repos)
            .zip(override_branches)
            .zip(network_branches)
            .zip(common_dirs)
            .zip(probes_state)
            .zip(probes_base)
            .zip(kinds)
        {
            // Recorded here, in this loop's own sequential iteration, rather than in the
            // one above: this is the loop whose order a future change (a sort by predicted
            // cost, say) would actually be tempted to touch, since it is the one that decides
            // each entity's `rayon::spawn` call, not merely which entities were dispatched.
            self.dispatch_log.lock().unwrap().push(key.clone());
            let path = key.path().to_path_buf();
            let table_handle = Arc::clone(&self.table);
            let settle_gate = Arc::clone(&self.settle_gate);
            let chain_cache = Arc::clone(&chain_cache);
            let chain_reads = Arc::clone(&self.default_branch_chain_reads);
            let patch_cache = Arc::clone(&patch_cache);
            let patch_reads = Arc::clone(&self.patch_identity_reads);
            let patch_scan_bounds = Arc::clone(&self.patch_scan_bounds);
            let bound_gates = Arc::clone(&bound_gates);
            // Resolved once here and moved into the task, which holds no handle on the
            // map itself: a probe signals the gate its own Generation was dispatched
            // against, so one still running from an earlier Generation can never signal a
            // gate registered after that Generation dispatched.
            let held_gate = self.phase_c_gates.lock().unwrap().get(&key).cloned();
            // scan: probe-fanout-pool begin -- rayon's global pool, not a dedicated one:
            // docs/adr/0013's sweep found the width a dedicated pool would need to pick is
            // a broad plateau that the global pool's own free default already sits inside
            // at every corpus size tried, and is the only width that stayed competitive
            // across idle, fetch-sized and Action-sized concurrent load. A dedicated pool
            // would cost a second idle thread pool's worth of memory and startup time to
            // land somewhere this measurement found no better than free.
            rayon::spawn(move || {
                let branch_outcome = probe_branch(&path, repo.as_deref(), kind, &cancel);
                let sync_outcome = probe_sync(
                    &path,
                    repo.as_deref(),
                    branch_outcome.as_ref().map(|(settled, ..)| settled),
                    kind,
                    &cancel,
                );
                let default_branch_outcome = probe_default_branch_memoised(
                    &path,
                    repo.as_deref(),
                    &common_dir,
                    DefaultBranchHints {
                        override_branch: override_branch.as_deref(),
                        network_branch: network_branch.as_deref(),
                    },
                    kind,
                    &cancel,
                    &ChainFactsMemo {
                        cache: &chain_cache,
                        reads: &chain_reads,
                    },
                );
                let base_outcome = if probes_base {
                    probe_base(
                        &path,
                        repo.as_deref(),
                        branch_outcome.as_ref().map(|(settled, ..)| settled),
                        default_branch_outcome.as_ref().map(|r| &r.settled),
                        &cancel,
                    )
                } else {
                    None
                };

                // Phases A and B land the moment they answer, per refresh.md's "The
                // first frame": every cheap column filled within 200ms, never gated
                // on phase C or D's much slower answers below. `default_branch_outcome`
                // is cloned here rather than moved, since phase D's landing probe
                // below still needs to read it.
                apply_cheap_probe_outcomes(
                    &table_handle,
                    &key,
                    generation,
                    CheapProbeOutcomes {
                        branch: branch_outcome,
                        sync: sync_outcome,
                        base: base_outcome,
                        default_branch: default_branch_outcome.clone(),
                    },
                );

                // Test-only: let a test hold phase C and D open here, after the cheap
                // outcomes above are already visible on the table, so the two applies'
                // independence can be proven by blocking on a Condvar rather than by racing
                // a sleep against a probe.
                if let Some(gate) = &held_gate {
                    let (lock, cvar) = &**gate;
                    let mut state = lock.lock().unwrap();
                    state.cheap_landed = true;
                    cvar.notify_all();
                    state = cvar.wait_while(state, |state| !state.may_proceed).unwrap();
                    drop(state);
                }

                let state_outcome = if probes_state {
                    let gate = bound_gates
                        .get(&common_dir)
                        .expect("every probes_state entity's common dir has a gate sized for it");
                    let mut report = GateReport::new(gate);
                    let memo = PatchEquivalenceMemo {
                        cache: &patch_cache,
                        reads: &patch_reads,
                        scan_bounds: &patch_scan_bounds,
                    };
                    probe_worktree_state(
                        &path,
                        repo.as_deref(),
                        default_branch_outcome.as_ref().map(|r| &r.settled),
                        &common_dir,
                        &cancel,
                        &memo,
                        &mut report,
                    )
                } else {
                    None
                };
                let dirty_outcome = probe_status(&path, repo.as_deref(), kind, &cancel);
                apply_probe_outcome(
                    &table_handle,
                    &settle_gate,
                    &key,
                    generation,
                    ProbeOutcomes {
                        state: state_outcome,
                        dirty: dirty_outcome,
                    },
                );

                // The same handle the cheap gate above blocked on, never a second lookup:
                // see where it is resolved.
                if let Some(gate) = &held_gate {
                    let (lock, cvar) = &**gate;
                    let mut state = lock.lock().unwrap();
                    state.finished = true;
                    cvar.notify_all();
                }
            });
            // scan: probe-fanout-pool end
        }
    }

    /// Re-runs both halves of discovery over `self.set` and reconciles the
    /// result into the live table, per [discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)
    /// and [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md).
    /// The walk and resolve run outside the table lock, since an abandoned walk
    /// can take up to thirty seconds; only reconciling the result briefly holds
    /// the write lock. Already-known boundaries reuse their cached repository
    /// handle rather than reopening it, which is what keeps re-running discovery
    /// every Generation from paying every entity's open cost again.
    fn rerun_discovery(&self) {
        let repos_cache: HashMap<EntityKey, Arc<gix::ThreadSafeRepository>> =
            self.table.read().unwrap().repos.clone();

        wait_for_discovery_gate(self.discovery_gate.as_ref());
        // The watcher is left detached, as it always has been here: nothing on this
        // path reads its handle.
        let (watch, _watcher) = spawn_discovery_watcher(
            self.set.roots.clone(),
            &self.discovery_warning,
            self.discovery_warn_after,
        );
        let discovery = run_watched_discovery(
            &watch,
            &self.set,
            &self.discovery_warning,
            Duration::from_nanos(self.discovery_abandon_after.load(Ordering::Acquire)),
        );
        if discovery.abandoned {
            self.discovery_manual.store(true, Ordering::Release);
        }

        let (discovered, gitmodules_failures) =
            discovery::resolve_with_cache(&self.set, &discovery.entities, &repos_cache);

        // Copied out before the table lock is taken, never read through it: `set_exclusions`
        // takes these two locks in the opposite order, and holding one while asking for the
        // other is what would let the two deadlock.
        let exclusions = self.exclusions.read().unwrap().clone();
        let mut table = self.table.write().unwrap();
        table.discovered_at = Timestamp::now();
        let cancelled = merge_discovery(&mut table, &exclusions, discovered, gitmodules_failures);
        drop(table);
        if cancelled > 0 {
            complete_many(&self.settle_gate, cancelled);
        }
    }
}

impl Drop for Core {
    /// Cancels whatever this `Core` still has in flight, then joins the dedicated thread.
    ///
    /// The cancel is what [`Core::pause`] already does, for the same reason
    /// [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
    /// "Cancellation" gives: an abandoned Generation is cancelled rather than left to
    /// finish, since a Set switch rebuilds the `Core` and the outgoing one's fan-out
    /// would otherwise contend for the same cores as the incoming one's. A probe already
    /// past its own cancel check still runs to completion on rayon's global pool, which
    /// is shared process-wide infrastructure rather than a thread this core spawned, so
    /// it is not joined here.
    fn drop(&mut self) {
        cancel_in_flight(&self.table, &self.settle_gate);
        let _ = self.control.send(ClockControl::Shutdown);
        if let Some(handle) = self.clock_thread.take() {
            let _ = handle.join();
        }
    }
}

/// `start_internal`'s result: the running core, plus the three handles a test needs
/// to make its threading deterministic instead of sleeping. `Core::start` only
/// ever reads `core` out of it; the other three fields exist for
/// `Core::start_for_test`.
pub(crate) struct StartForTest {
    pub core: Core,
    #[allow(dead_code)] // read only by tests; the plain lib target never builds them
    pub clock_alive: Arc<AtomicBool>,
    #[allow(dead_code)] // read only by tests; the plain lib target never builds them
    pub discovery_watcher: JoinHandle<()>,
    /// The thread the first discovery runs on. Joining it is the rendezvous that
    /// says the walk finished and its rows reached the table, with no sleep and no
    /// poll anywhere in the wait.
    #[allow(dead_code)] // read only by tests; the plain lib target never builds them
    pub initial_discovery: Option<JoinHandle<()>>,
}

#[cfg(test)]
impl StartForTest {
    /// Blocks until the first discovery has landed on the table, then hands this
    /// back so a test reads a populated table rather than the empty one `start`
    /// itself returns.
    fn discovered(mut self) -> Self {
        if let Some(handle) = self.initial_discovery.take() {
            handle
                .join()
                .expect("the first discovery thread should not panic");
        }
        self
    }
}

impl Core {
    /// Puts one already-known entity into the in-flight state a real `refresh`
    /// dispatch would, without spawning anything to complete it, so a test can
    /// drive the deadline sweep through the tick channel alone and prove the sweep
    /// runs on a tick rather than on a clock of its own, or prove that `pause`
    /// cancels a real in-flight entry from outside this crate.
    ///
    /// Gated behind `test-util` (on by default under `cfg(test)` for this crate's own
    /// tests) so a test-only affordance never ships on the default published surface,
    /// per [ADR 0021](https://github.com/paulchiu/repon/blob/main/docs/adr/0021-a-release-is-what-the-tag-pipeline-publishes.md),
    /// the same reason `Timestamp::at` is gated.
    #[cfg(any(test, feature = "test-util"))]
    pub fn begin_untracked_probe_for_test(&self, key: &EntityKey) -> Arc<AtomicBool> {
        let mut table = self.table.write().unwrap();
        table.generation += 1;
        let generation_number = table.generation;
        table
            .generation_started_at
            .insert(generation_number, Instant::now());
        if let Some(&idx) = table.index.get(key) {
            begin_probes(&mut table.entities[idx]);
        }
        let cancel = Arc::new(AtomicBool::new(false));
        table.in_flight.insert(
            key.clone(),
            InFlight {
                generation: generation_number,
                cancel: Arc::clone(&cancel),
            },
        );
        begin_probes_owed(&self.settle_gate, 1);
        cancel
    }
}

/// One simulated in-flight Generation, as [`Core::begin_shared_generation_for_test`]
/// left it: the Generation itself, and one interrupt flag per key it covers.
#[cfg(test)]
pub(crate) struct SharedGeneration {
    /// The Generation this simulation minted, so a test can name it and its successor
    /// rather than the counter values they happen to hold.
    pub generation: Generation,
    /// One `cancel` flag per covered key, the same handle a real dispatch would hold.
    pub cancels: HashMap<EntityKey, Arc<AtomicBool>>,
}

#[cfg(test)]
impl Core {
    /// The cached thread-safe repository handle discovery left for `key`, if any,
    /// so a test can prove the cache was actually populated and, by comparing
    /// `Arc::ptr_eq` across two reads, that a probe reused it rather than
    /// replacing it with a freshly opened one.
    pub(crate) fn cached_repo_handle_for_test(
        &self,
        key: &EntityKey,
    ) -> Option<Arc<gix::ThreadSafeRepository>> {
        self.table.read().unwrap().repos.get(key).cloned()
    }

    /// How many times the most recent `refresh` actually computed the
    /// default-branch chain's per-common-dir facts, as opposed to reusing an
    /// already-computed answer for a common dir another dispatched entity already
    /// paid for. What proves the per-common-dir memoisation ran at all: two
    /// entities agreeing on their resolved default branch proves nothing on its
    /// own, since two distinct common dirs can legitimately agree too.
    pub(crate) fn default_branch_chain_reads_for_test(&self) -> usize {
        self.default_branch_chain_reads.load(Ordering::Acquire)
    }

    /// How many times the most recent `refresh` actually scanned a common dir's
    /// default-branch commit history for patch equivalence, as opposed to
    /// reusing an already-computed scan for a common dir another dispatched
    /// entity already paid for. The same proof `default_branch_chain_reads_for_test`
    /// gives the default-branch chain, for patch equivalence's own memo.
    pub(crate) fn patch_identity_reads_for_test(&self) -> usize {
        self.patch_identity_reads.load(Ordering::Acquire)
    }

    /// The bound each actually-run `scan_default_branch` call this Generation
    /// used, one entry per common dir it ran for, in run order. Unlike
    /// `patch_identity_reads_for_test`, which only proves a scan ran once per
    /// common dir, this proves *what* it was bounded by: the deepest merge base
    /// among the dispatched siblings, per `BoundGate::deepest`, rather than
    /// whichever entity's own merge base happened to reach the scan first.
    pub(crate) fn patch_scan_bounds_for_test(&self) -> Vec<Option<gix::ObjectId>> {
        self.patch_scan_bounds.lock().unwrap().clone()
    }

    /// Every key the most recent `refresh` call's own sequential dispatch loop iterated,
    /// in that order: dispatch order, proven directly rather than inferred from completion,
    /// which a concurrent pool never guarantees (criterion 5's honest half).
    pub(crate) fn dispatch_log_for_test(&self) -> Vec<EntityKey> {
        self.dispatch_log.lock().unwrap().clone()
    }

    /// Runs one metadata-poll sweep synchronously on the calling thread: the exact
    /// work the dedicated thread's tick arm performs, called directly so a test can
    /// prove the sweep's own effects without racing the injected tick channel's
    /// delivery to that other thread.
    pub(crate) fn poll_once_for_test(&self) {
        run_poll_sweep(
            &self.table,
            &self.overrides,
            &self.show_submodules,
            &self.poll_reprobed,
            &self.poll_sweep_count,
            &self.network_default_branch,
        );
    }

    /// Every key the most recent `poll_once_for_test` call actually re-ran phases A
    /// and B for, in the order it found them moved: proves "for that entity only"
    /// by naming exactly which entities were touched, not merely that one of them
    /// was.
    pub(crate) fn poll_reprobed_for_test(&self) -> Vec<EntityKey> {
        self.poll_reprobed.lock().unwrap().clone()
    }

    /// How many metadata-poll sweeps have run in total, so a test driving the real
    /// dedicated thread through its injected tick channel can prove a tick reached
    /// the sweep at all, not only what the sweep did once it ran.
    pub(crate) fn poll_sweep_count_for_test(&self) -> usize {
        self.poll_sweep_count.load(Ordering::Acquire)
    }

    /// Registers a closed phase C/D gate for `key`, so the next `refresh` that
    /// dispatches it will land its cheap outcomes, then block before touching
    /// phase C or D until [`Core::release_phase_c_for_test`] opens the gate.
    /// Must be called before the dispatching `refresh`, since a Generation resolves
    /// each entity's gate as it dispatches it and its probes signal that one alone.
    pub(crate) fn hold_phase_c_for_test(&self, key: &EntityKey) {
        self.phase_c_gates.lock().unwrap().insert(
            key.clone(),
            Arc::new((Mutex::new(PhaseCGate::default()), Condvar::new())),
        );
    }

    /// Blocks the calling thread, with no sleep or poll, until `key`'s cheap
    /// outcomes have landed on the table. Panics if `key` has no gate
    /// registered, since that means the test forgot [`Core::hold_phase_c_for_test`].
    pub(crate) fn wait_phase_c_landed_for_test(&self, key: &EntityKey) {
        let gate = self
            .phase_c_gates
            .lock()
            .unwrap()
            .get(key)
            .cloned()
            .expect("hold_phase_c_for_test must be called before waiting on its gate");
        let (lock, cvar) = &*gate;
        let guard = lock.lock().unwrap();
        drop(cvar.wait_while(guard, |state| !state.cheap_landed).unwrap());
    }

    /// Lets `key`'s held phase C and D proceed. Does not itself wait for them to
    /// finish; pair with [`Core::wait_phase_c_finished_for_test`].
    pub(crate) fn release_phase_c_for_test(&self, key: &EntityKey) {
        let gate = self
            .phase_c_gates
            .lock()
            .unwrap()
            .get(key)
            .cloned()
            .expect("hold_phase_c_for_test must be called before releasing its gate");
        let (lock, cvar) = &*gate;
        let mut state = lock.lock().unwrap();
        state.may_proceed = true;
        cvar.notify_all();
    }

    /// Blocks the calling thread, with no sleep or poll, until `key`'s phase C/D
    /// outcome has been applied and the settle gate decremented for it.
    pub(crate) fn wait_phase_c_finished_for_test(&self, key: &EntityKey) {
        let gate = self
            .phase_c_gates
            .lock()
            .unwrap()
            .get(key)
            .cloned()
            .expect("hold_phase_c_for_test must be called before waiting on its gate");
        let (lock, cvar) = &*gate;
        let guard = lock.lock().unwrap();
        drop(cvar.wait_while(guard, |state| !state.finished).unwrap());
    }

    /// Blocks the calling thread, with no sleep and no poll, until every Generation
    /// reserved so far has finished dispatching: what a test waits on before reading
    /// a count a dispatch raises, now that a Generation reserves its number on the
    /// calling thread and raises that count on one of its own.
    pub(crate) fn wait_dispatched_for_test(&self) {
        let (lock, cvar) = &*self.settle_gate;
        let guard = lock.lock().unwrap();
        drop(
            cvar.wait_while(guard, |counts| counts.dispatches > 0)
                .unwrap(),
        );
    }

    /// The settle gate's raw outstanding count, so a test can prove a single
    /// dispatched entity's split write decrements it exactly once overall,
    /// neither twice (an early `settle`) nor zero times (a `settle` that hangs).
    pub(crate) fn settle_gate_count_for_test(&self) -> usize {
        self.settle_gate.0.lock().unwrap().probes
    }

    /// `start`, with the tick source and the discovery-slow warning's threshold
    /// injected rather than real, so a test drives the dedicated thread's cadence
    /// through a channel it controls and never waits out a real second.
    pub(crate) fn start_for_test(
        spec: CoreSpec,
        warn_after: Duration,
        ticks: Receiver<Instant>,
    ) -> StartForTest {
        Self::start_for_test_with_discovery_abandon(
            spec,
            warn_after,
            discovery::ABANDON_AFTER,
            ticks,
        )
    }

    /// `start_for_test`, with the discovery abandon deadline also injected, so a
    /// test can force a walk to abandon deterministically instead of running one
    /// for the real thirty seconds. The periodic fetch is always off here: a test
    /// that wants it runs [`Core::start_for_test_with_fetch`] instead, which is
    /// what keeps this constructor's own signature free of a feature-gated
    /// parameter.
    pub(crate) fn start_for_test_with_discovery_abandon(
        spec: CoreSpec,
        warn_after: Duration,
        discovery_abandon_after: Duration,
        ticks: Receiver<Instant>,
    ) -> StartForTest {
        Self::start_for_test_gated(spec, warn_after, discovery_abandon_after, ticks, None)
    }

    /// `start_for_test_with_discovery_abandon`, with the discovery gate injected: with a
    /// closed one, every walk this `Core` starts blocks before it begins, so a caller's own
    /// return is observed against a walk that provably has not run.
    pub(crate) fn start_for_test_gated(
        spec: CoreSpec,
        warn_after: Duration,
        discovery_abandon_after: Duration,
        ticks: Receiver<Instant>,
        discovery_gate: Option<DiscoveryGate>,
    ) -> StartForTest {
        let alive = Arc::new(AtomicBool::new(true));
        start_internal(
            spec,
            warn_after,
            discovery_abandon_after,
            ticks,
            FetchStart {
                enabled: false,
                concurrency: 1,
                ticks: crossbeam_channel::never(),
            },
            alive,
            discovery_gate,
        )
    }

    /// `start_for_test_with_discovery_abandon`, with the periodic fetch's own tick
    /// channel injected too, so a test can prove the recurring cadence without
    /// waiting out a real `fetch.interval`. `spec.fetch.enabled` still governs
    /// whether the immediate first cycle fires; `fetch_ticks` governs every cycle
    /// after that.
    pub(crate) fn start_for_test_with_fetch(
        spec: CoreSpec,
        warn_after: Duration,
        ticks: Receiver<Instant>,
        fetch_ticks: Receiver<Instant>,
    ) -> StartForTest {
        let alive = Arc::new(AtomicBool::new(true));
        let fetch_start = FetchStart {
            enabled: spec.fetch.enabled,
            concurrency: spec.fetch.concurrency.max(1),
            ticks: fetch_ticks,
        };
        start_internal(
            spec,
            warn_after,
            discovery::ABANDON_AFTER,
            ticks,
            fetch_start,
            alive,
            None,
        )
    }

    /// How many periodic-fetch cycles have run in total: the immediate first one
    /// plus one per `fetch.interval` tick since, whether or not any repository had
    /// a remote to fetch.
    pub(crate) fn fetch_cycle_count_for_test(&self) -> usize {
        self.fetch_cycle_count.load(Ordering::Acquire)
    }

    /// Whether an abandoned discovery has already taken this `Core` out of the
    /// automatic refresh path, so a test can assert the precondition explicitly
    /// rather than infer it from a later refresh's behaviour alone.
    /// Tightens the abandon deadline after `start`, so a test can let the first walk
    /// finish under a deadline it cannot lose against and still force a later walk to
    /// abandon.
    #[cfg(test)]
    pub(crate) fn set_discovery_abandon_after_for_test(&self, after: Duration) {
        self.discovery_abandon_after
            .store(after.as_nanos() as u64, Ordering::Release);
    }

    pub(crate) fn discovery_manual_for_test(&self) -> bool {
        self.discovery_manual.load(Ordering::Acquire)
    }

    /// Puts several already-known entities into the in-flight state of one shared
    /// Generation, without spawning anything to complete them and without
    /// touching the settle gate, so a test can drive per-entity supersession
    /// directly: which keys a later real `refresh` does and does not cover, and
    /// what happens to each one's own cancel flag and eventual result.
    ///
    /// Hands back the Generation it minted rather than only the flags, so the test
    /// names that Generation and its successor instead of the counter values they
    /// happen to hold.
    pub(crate) fn begin_shared_generation_for_test(&self, keys: &[EntityKey]) -> SharedGeneration {
        let mut table = self.table.write().unwrap();
        table.generation += 1;
        let generation_number = table.generation;
        table
            .generation_started_at
            .insert(generation_number, Instant::now());
        let mut cancels = HashMap::new();
        for key in keys {
            if let Some(&idx) = table.index.get(key) {
                table.entities[idx].branch.begin_probe();
            }
            let cancel = Arc::new(AtomicBool::new(false));
            table.in_flight.insert(
                key.clone(),
                InFlight {
                    generation: generation_number,
                    cancel: Arc::clone(&cancel),
                },
            );
            cancels.insert(key.clone(), cancel);
        }
        SharedGeneration {
            generation: Generation::new(generation_number),
            cancels,
        }
    }

    /// Lands one branch probe result for `key` at `generation` through the exact
    /// same path a real dispatched probe's cheap outcomes take
    /// ([`apply_cheap_probe_outcomes`]), so a test can simulate a result arriving
    /// late, out of Generation order, without a second, weaker implementation of
    /// the write-time supersession check.
    pub(crate) fn apply_probe_result_for_test(
        &self,
        key: &EntityKey,
        generation: Generation,
        settled: Settled<Head>,
    ) {
        apply_cheap_probe_outcomes(
            &self.table,
            key,
            generation,
            CheapProbeOutcomes {
                branch: Some((settled, None, Vec::new())),
                sync: None,
                base: None,
                default_branch: None,
            },
        );
    }

    /// Writes `receipt` directly onto `key`'s `last_action`, bypassing `run_action`
    /// entirely: lets a test put an exact, hand-built receipt on a live `Core`'s table
    /// without spawning any real child process.
    pub(crate) fn set_last_action_for_test(
        &self,
        key: &EntityKey,
        receipt: crate::entity::ActionReceipt,
    ) {
        let mut table = self.table.write().unwrap();
        if let Some(&idx) = table.index.get(key) {
            table.entities[idx].last_action = Some(receipt);
        }
    }
}

/// One entity's whole Action run: every step in `action.steps`, in order, stopping at
/// the first failure, with every step after it recorded `NotRun` rather than silently
/// skipped ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
/// "Actions", `docs/spec/actions.md`'s "Step outcomes"). Never called for an excluded,
/// inapplicable or unresolved entity: [`Core::run_action`] gives those their own `Skip`
/// receipt itself and never reaches this function for them.
///
/// `control` is the same `RunControl` every other entity's run in this fan-out shares:
/// checked before every step starts, so a step not yet reached when `control.cancel` fires
/// becomes `Cancelled` rather than ever spawning, and again the instant a spawned step's
/// `run_step` call returns, so a step that was actually running when cancellation fired
/// becomes `Cancelled` regardless of the exit `run_step` itself observed (a signalled child
/// has no clean outcome of its own to report). `Cancelled` and `NotRun` are deliberately
/// kept apart here: once cancellation is seen, every remaining step (including a step
/// already past the "before it starts" check but not yet run) is `Cancelled`, never
/// `NotRun`, which stays reserved for being blocked by an earlier failure
/// (`docs/spec/actions.md`'s "Step outcomes").
///
/// `report` is called once per step, immediately before that step starts, with a receipt
/// whose `running` names it: the caller writes this straight onto the table, which is what
/// lets a still-running step's own label and elapsed time reach a reader before the whole
/// entity's run has finished (`docs/spec/actions.md`'s "The run on screen"). The final
/// return value is the same shape with `running: None`, the caller's job to write once more.
fn run_action_for_entity(
    entity: &EntityState,
    action: &ActionSpec,
    control: &Arc<executor::RunControl>,
    report: &dyn Fn(ActionReceipt),
) -> ActionReceipt {
    let base_env = environment::environment(entity, action.name.as_deref());
    let mut failed = false;
    let mut cancelled = false;
    let mut results: Vec<StepResult> = Vec::with_capacity(action.steps.len());
    for step in &action.steps {
        if failed || cancelled || control.is_cancelled() {
            cancelled = cancelled || control.is_cancelled();
            results.push(StepResult {
                label: Arc::from(step.argv.join(" ")),
                outcome: if cancelled {
                    StepOutcome::Cancelled
                } else {
                    StepOutcome::NotRun
                },
                output: Arc::from(&b""[..]),
                elapsed: Duration::ZERO,
                elision: None,
                shell: step.shell,
                interactive: step.interactive,
            });
            continue;
        }
        let label: Arc<str> = Arc::from(step.argv.join(" "));
        report(ActionReceipt {
            label: Arc::clone(&action.label),
            steps: Arc::from(results.clone()),
            skip: None,
            finished_at: Timestamp::now(),
            running: Some(RunningStep {
                label: Arc::clone(&label),
                started_at: Timestamp::now(),
                shell: step.shell,
                interactive: step.interactive,
            }),
        });
        // The step's own `env` table is applied after the environment contract's
        // set-or-unset pairs, so it overrides the guaranteed set exactly as a
        // Launcher's own `env` field already does (`docs/spec/config.md`'s
        // "Launchers").
        let mut env = base_env.clone();
        env.extend(
            step.env
                .iter()
                .map(|(name, value)| (name.clone(), Some(value.clone()))),
        );
        let mut result = executor::run_step(
            &step.argv,
            step.shell,
            step.interactive,
            entity.key.path(),
            &env,
            control,
        );
        if control.is_cancelled() {
            result.outcome = StepOutcome::Cancelled;
            cancelled = true;
        } else {
            failed = result.outcome.is_failure();
        }
        results.push(result);
    }
    ActionReceipt {
        label: Arc::clone(&action.label),
        steps: Arc::from(results),
        skip: None,
        finished_at: Timestamp::now(),
        running: None,
    }
}

/// A gate a test closes to hold every discovery walk this `Core` starts, at the
/// point before the walk begins, so a caller's own return can be observed against a
/// walk that provably has not run. `None` on every production path, the same way
/// `Core::phase_c_gates` is empty on one.
type DiscoveryGate = Arc<(Mutex<bool>, Condvar)>;

/// Blocks while `gate` is closed, and returns at once when there is none, which is
/// every production path.
fn wait_for_discovery_gate(gate: Option<&DiscoveryGate>) {
    let Some(gate) = gate else {
        return;
    };
    let (lock, cvar) = &**gate;
    let open = lock.lock().unwrap();
    drop(cvar.wait_while(open, |open| !*open).unwrap());
}

/// Opens or closes a [`DiscoveryGate`], waking whatever walk is held on it.
#[cfg(test)]
fn set_discovery_gate(gate: &DiscoveryGate, open: bool) {
    let (lock, cvar) = &**gate;
    *lock.lock().unwrap() = open;
    cvar.notify_all();
}

/// What one watched discovery walk and the thread watching it share: the counter
/// the walk bumps as it goes, and the flag it sets on finishing.
struct DiscoveryWatch {
    progress: Arc<AtomicUsize>,
    finished: Arc<AtomicBool>,
}

/// Arms the still-walking watcher for a walk that has not started yet, leaving the
/// still-walking warning behind in `discovery_warning` if that walk outruns
/// `warn_after`. Separate from [`run_watched_discovery`] so `start_internal` can arm
/// it on the calling thread, and hand a test its handle, while the walk it watches
/// runs on a thread of its own.
fn spawn_discovery_watcher(
    roots: Vec<PathBuf>,
    discovery_warning: &Arc<Mutex<Option<String>>>,
    warn_after: Duration,
) -> (DiscoveryWatch, JoinHandle<()>) {
    let progress = Arc::new(AtomicUsize::new(0));
    let finished = Arc::new(AtomicBool::new(false));
    let watcher = thread::spawn({
        let progress = Arc::clone(&progress);
        let finished = Arc::clone(&finished);
        let warning_slot = Arc::clone(discovery_warning);
        move || {
            if let Some(message) = watch_for_slow_discovery(progress, finished, roots, warn_after) {
                *warning_slot.lock().unwrap() = Some(message);
            }
        }
    });
    (DiscoveryWatch { progress, finished }, watcher)
}

/// Runs one discovery boundary walk against `set` under an already-armed `watch`,
/// leaving the abandoned-discovery warning in `discovery_warning` if the walk
/// abandons past `abandon_after`. Shared by `start_internal`'s first walk and
/// `rerun_discovery`'s later ones, so a refresh-triggered abandon runs the same
/// wiring `start`'s own walk does, never a parallel copy of it.
fn run_watched_discovery(
    watch: &DiscoveryWatch,
    set: &SetSpec,
    discovery_warning: &Arc<Mutex<Option<String>>>,
    abandon_after: Duration,
) -> discovery::Discovery {
    let discovery =
        discovery::discover_watched_with_deadline(set, Arc::clone(&watch.progress), abandon_after);
    watch.finished.store(true, Ordering::Release);

    if discovery.abandoned {
        *discovery_warning.lock().unwrap() =
            Some(abandoned_discovery_message(discovery.directories_visited));
    }

    discovery
}

/// Shared body of `start` and `start_for_test`: builds the empty table, spawns the
/// dedicated thread, and starts the first discovery on a thread of its own.
fn start_internal(
    spec: CoreSpec,
    warn_after: Duration,
    discovery_abandon_after: Duration,
    ticks: Receiver<Instant>,
    fetch_start: FetchStart,
    alive: Arc<AtomicBool>,
    discovery_gate: Option<DiscoveryGate>,
) -> StartForTest {
    let FetchStart {
        enabled: fetch_enabled,
        concurrency: fetch_concurrency,
        ticks: fetch_ticks,
    } = fetch_start;
    let discovery_warning = Arc::new(Mutex::new(None));
    let discovery_manual = Arc::new(AtomicBool::new(false));

    let (overrides, resolved_exclusions) = resolve_entries(&spec.overrides);
    let overrides = Arc::new(overrides);
    let exclusions = Arc::new(RwLock::new(resolved_exclusions));
    let show_submodules = Arc::new(AtomicBool::new(spec.show_submodules));

    let table = Arc::new(RwLock::new(Table {
        generation: 0,
        discovered_at: Timestamp::now(),
        entities: Vec::new(),
        index: HashMap::new(),
        in_flight: HashMap::new(),
        generation_started_at: HashMap::new(),
        repos: HashMap::new(),
        poll_fingerprints: HashMap::new(),
    }));

    let settle_gate: Arc<SettleGate> =
        Arc::new((Mutex::new(SettleCounts::default()), Condvar::new()));
    let poll_reprobed = Arc::new(Mutex::new(Vec::new()));
    let poll_sweep_count = Arc::new(AtomicUsize::new(0));
    let network_default_branch = Arc::new(Mutex::new(HashMap::new()));
    let (control, control_rx) = crossbeam_channel::unbounded();
    let poll_handles = PollHandles {
        overrides: Arc::clone(&overrides),
        show_submodules: Arc::clone(&show_submodules),
        poll_reprobed: Arc::clone(&poll_reprobed),
        poll_sweep_count: Arc::clone(&poll_sweep_count),
        network_default_branch: Arc::clone(&network_default_branch),
    };

    // Hoisted out of the `Core` struct literal below, rather than built inline
    // there as before this field existed: `RefreshHandles` needs its own clone of
    // each of these, constructed before `Core` takes ownership of the originals.
    let discovery_abandon_after_atomic =
        Arc::new(AtomicU64::new(discovery_abandon_after.as_nanos() as u64));
    let default_branch_chain_reads = Arc::new(AtomicUsize::new(0));
    let patch_identity_reads = Arc::new(AtomicUsize::new(0));
    let patch_scan_bounds = Arc::new(Mutex::new(Vec::new()));
    let dispatch_log = Arc::new(Mutex::new(Vec::new()));
    let phase_c_gates = Arc::new(Mutex::new(HashMap::new()));
    let fetch_cycle_count = Arc::new(AtomicUsize::new(0));
    let fetch_failures = Arc::new(Mutex::new(FetchFailures::default()));
    let turnstile = Arc::new(DispatchTurnstile::default());

    let fetch_refresh_handles = RefreshHandles {
        table: Arc::clone(&table),
        overrides: Arc::clone(&overrides),
        exclusions: Arc::clone(&exclusions),
        set: spec.set.clone(),
        discovery_manual: Arc::clone(&discovery_manual),
        discovery_warn_after: warn_after,
        discovery_abandon_after: Arc::clone(&discovery_abandon_after_atomic),
        discovery_warning: Arc::clone(&discovery_warning),
        show_submodules: Arc::clone(&show_submodules),
        settle_gate: Arc::clone(&settle_gate),
        default_branch_chain_reads: Arc::clone(&default_branch_chain_reads),
        patch_identity_reads: Arc::clone(&patch_identity_reads),
        patch_scan_bounds: Arc::clone(&patch_scan_bounds),
        dispatch_log: Arc::clone(&dispatch_log),
        phase_c_gates: Arc::clone(&phase_c_gates),
        network_default_branch: Arc::clone(&network_default_branch),
        turnstile: Arc::clone(&turnstile),
        discovery_gate: discovery_gate.clone(),
    };
    let auto_update_enabled = spec.auto_update.enabled;
    let fetch_schedule = FetchSchedule {
        concurrency: fetch_concurrency,
        ticks: fetch_ticks,
        refresh: fetch_refresh_handles.clone(),
        cycle_count: Arc::clone(&fetch_cycle_count),
        failures: Arc::clone(&fetch_failures),
        auto_update_enabled,
    };

    let clock_thread = spawn_clock_thread(
        Arc::clone(&table),
        poll_handles,
        fetch_schedule,
        Arc::clone(&settle_gate),
        spec.generation_deadline,
        ClockChannels {
            control: control_rx,
            ticks,
            alive: Arc::clone(&alive),
        },
    );

    // Discovery runs here rather than on the calling thread, so `Core::start`
    // returns against the empty table above and the consumer can claim the terminal
    // and draw before the walk has finished (ADR 0015's "a constructor that spawns
    // threads is not a surprise"). This walk is also refresh.md's "Startup"
    // Generation, so a launch walks the tree once: the number and the turnstile place
    // are reserved here on the calling thread, exactly as every later Generation
    // reserves its own, and the walk and the fan-out it orders both run on the
    // spawned thread. The debt is recorded before the spawn, so a `settle` called in
    // between waits for this Generation rather than returning on an empty table.
    let (startup_generation, startup_ticket) = fetch_refresh_handles.reserve_generation();
    begin_dispatch(&settle_gate);
    let (watch, discovery_watcher) =
        spawn_discovery_watcher(spec.set.roots.clone(), &discovery_warning, warn_after);
    let initial_discovery = thread::spawn({
        let set = spec.set.clone();
        let discovery_warning = Arc::clone(&discovery_warning);
        let discovery_manual = Arc::clone(&discovery_manual);
        let exclusions = Arc::clone(&exclusions);
        let table = Arc::clone(&table);
        let settle_gate = Arc::clone(&settle_gate);
        let fetch_refresh_handles = fetch_refresh_handles.clone();
        let fetch_cycle_count = Arc::clone(&fetch_cycle_count);
        let fetch_failures = Arc::clone(&fetch_failures);
        let discovery_gate = discovery_gate.clone();
        move || {
            let turn = fetch_refresh_handles.turnstile.take(startup_ticket);
            wait_for_discovery_gate(discovery_gate.as_ref());
            let discovery =
                run_watched_discovery(&watch, &set, &discovery_warning, discovery_abandon_after);
            if discovery.abandoned {
                discovery_manual.store(true, Ordering::Release);
            }

            // Discovery's second half: every boundary the walk just found becomes a
            // Repo or a Worktree, and each one's own `.gitmodules` (never recursed
            // into) names its Submodules. One combined list, with nothing recording
            // which half produced a given entry.
            let (discovered, gitmodules_failures) = discovery::resolve(&set, &discovery.entities);
            let resolved_exclusions = exclusions.read().unwrap().clone();
            let order: Vec<EntityKey> = {
                let mut table = table.write().unwrap();
                // A fresh table has nothing in flight yet, so nothing here is ever
                // cancelled: the same reconciliation `refresh` uses later, run once
                // against an empty starting point.
                merge_discovery(
                    &mut table,
                    &resolved_exclusions,
                    discovered,
                    gitmodules_failures,
                );
                table.discovered_at = Timestamp::now();
                table
                    .entities
                    .iter()
                    .map(|entity| entity.key.clone())
                    .collect()
            };
            // Read off the table this walk just reconciled, the same way
            // `dispatch_over_everything` resolves its own order: nobody holding the
            // empty table `start` returned has a key to name yet.
            fetch_refresh_handles.dispatch_probes(&order, startup_generation);
            finish_dispatch(&settle_gate);
            // Released here rather than at thread exit: the first fetch cycle spawned
            // below is not part of this Generation's body.
            drop(turn);

            // "Fires immediately on being enabled rather than waiting for the first
            // tick" ([refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
            // "The periodic fetch"): the recurring cadence only ever fires after a full
            // `fetch.interval` has elapsed, so the first cycle is dispatched here, once,
            // on its own plain thread rather than on the dedicated clock thread, which
            // must stay free to keep polling and sweeping deadlines while this cycle
            // runs. From inside this thread rather than beside it, because a cycle reads
            // the table to know what to fetch and the walk above is what puts anything
            // in it.
            if fetch_enabled {
                let table = Arc::clone(&table);
                thread::spawn(move || {
                    run_fetch_cycle(
                        &table,
                        fetch_concurrency,
                        &fetch_refresh_handles,
                        &fetch_cycle_count,
                        &fetch_failures,
                        auto_update_enabled,
                    );
                });
            }
        }
    });

    StartForTest {
        core: Core {
            table,
            overrides,
            exclusions,
            set: spec.set,
            discovery_manual,
            discovery_warn_after: warn_after,
            discovery_abandon_after: discovery_abandon_after_atomic,
            show_submodules,
            settle_gate,
            control,
            clock_thread: Some(clock_thread),
            discovery_warning,
            default_branch_chain_reads,
            patch_identity_reads,
            patch_scan_bounds,
            action_running: Arc::new(AtomicBool::new(false)),
            action_control: Arc::new(Mutex::new(None)),
            dispatch_log,
            phase_c_gates,
            status_stale_after: spec.status_stale_after,
            poll_reprobed,
            poll_sweep_count,
            fetch_cycle_count,
            network_default_branch,
            fetch_failures,
            turnstile,
            discovery_gate,
        },
        clock_alive: alive,
        discovery_watcher,
        initial_discovery: Some(initial_discovery),
    }
}

/// Everything the dedicated thread's tick arm needs for [`run_poll_sweep`] beyond
/// the table it already takes, bundled so `spawn_clock_thread` stays within
/// clippy's argument limit.
struct PollHandles {
    overrides: Arc<Vec<ResolvedOverride>>,
    show_submodules: Arc<AtomicBool>,
    poll_reprobed: Arc<Mutex<Vec<EntityKey>>>,
    poll_sweep_count: Arc<AtomicUsize>,
    /// [`Core::network_default_branch`]'s own clone, so a poll-triggered re-probe
    /// still reflects an already-superseded default branch rather than reverting
    /// to the local chain's own answer until the next full refresh.
    network_default_branch: Arc<Mutex<HashMap<PathBuf, Arc<str>>>>,
}

/// What [`start_internal`] needs from `CoreSpec::fetch` to schedule the periodic fetch,
/// bundled into one argument rather than three so this crate's own `clippy::too_many_arguments`
/// budget has room for it: extracted once at each of `Core::start`'s two callers.
struct FetchStart {
    enabled: bool,
    concurrency: usize,
    ticks: Receiver<Instant>,
}

/// The periodic fetch's own scheduling inputs, threaded through [`start_internal`]
/// and [`spawn_clock_thread`] as plain values rather than reading `CoreSpec::fetch`
/// directly: extracted once at each of the two callers. Carries no `enabled` flag
/// of its own: `ticks` is [`crossbeam_channel::never`] whenever the periodic fetch
/// is off, so the arm that reads it simply never fires, the same way the poll's
/// own `ticks` does when a test has no interest in it.
struct FetchSchedule {
    concurrency: usize,
    ticks: Receiver<Instant>,
    refresh: RefreshHandles,
    cycle_count: Arc<AtomicUsize>,
    failures: Arc<Mutex<FetchFailures>>,
    /// `CoreSpec::auto_update`'s own `enabled` flag, read once at `start` like every
    /// other field on [`FetchSchedule`]: the fast-forward-only update carries no
    /// interval of its own, so there is no separate tick to gate it on, only this.
    auto_update_enabled: bool,
}

/// The dedicated thread's own control-plane wiring, bundled into one argument so
/// [`spawn_clock_thread`] stays within clippy's argument limit: `control` is the
/// pause/resume/shutdown channel every `Core` method sends into, `ticks` drives the
/// poll and deadline sweep, and `alive` is the flag the thread clears on its way out
/// (both for a test to observe and for nothing else, since `Drop` joins the handle
/// directly rather than polling this).
struct ClockChannels {
    control: Receiver<ClockControl>,
    ticks: Receiver<Instant>,
    alive: Arc<AtomicBool>,
}

/// The dedicated thread: the metadata poll tick, the Generation deadline sweep and
/// the periodic fetch's own tick share this one interval loop, separate from the
/// probe pool and from any render loop, so suspending the terminal reschedules
/// none of it. Driven by `ticks` and `fetch.ticks` rather than a bare
/// `thread::sleep`, which is what a test replaces to make the cadence
/// deterministic. The poll and deadline sweep run first on every `ticks` tick,
/// both while `!paused`; a fetch cycle runs on every `fetch.ticks` tick, also only
/// while `!paused`, so a suspended Repon neither sweeps nor fetches while the user
/// is in a Launcher.
fn spawn_clock_thread(
    table: Arc<RwLock<Table>>,
    poll: PollHandles,
    fetch: FetchSchedule,
    settle_gate: Arc<SettleGate>,
    generation_deadline: Duration,
    channels: ClockChannels,
) -> JoinHandle<()> {
    let ClockChannels {
        control,
        ticks,
        alive,
    } = channels;
    thread::spawn(move || {
        let mut paused = false;
        loop {
            select! {
                recv(control) -> message => match message {
                    Ok(ClockControl::Pause) => {
                        paused = true;
                        cancel_in_flight(&table, &settle_gate);
                    }
                    Ok(ClockControl::Resume) => paused = false,
                    Ok(ClockControl::Shutdown) | Err(_) => break,
                },
                recv(ticks) -> tick => {
                    if tick.is_err() {
                        break;
                    }
                    if !paused {
                        run_poll_sweep(
                            &table,
                            &poll.overrides,
                            &poll.show_submodules,
                            &poll.poll_reprobed,
                            &poll.poll_sweep_count,
                            &poll.network_default_branch,
                        );
                        sweep_deadline(&table, &settle_gate, generation_deadline);
                    }
                }
                recv(fetch.ticks) -> tick => {
                    if tick.is_err() {
                        break;
                    }
                    if !paused {
                        run_fetch_cycle(
                            &table,
                            fetch.concurrency,
                            &fetch.refresh,
                            &fetch.cycle_count,
                            &fetch.failures,
                            fetch.auto_update_enabled,
                        );
                    }
                }
            }
        }
        alive.store(false, Ordering::Release);
    })
}

/// One periodic-fetch cycle: every distinct git common dir this table currently
/// knows, not excluded, fetched with pruning, bounded to `concurrency` at once,
/// then one normal Generation over every entity the table now knows
/// ([refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
/// "The periodic fetch": "a finished fetch starts a normal generation"), the exact
/// completion path [`Core::run_action`] already uses. `cycle_count` counts every
/// call, whether or not any repository had a remote to fetch, so a test driving
/// the dedicated thread's own tick channel can prove a tick reached this function
/// at all, the same proof [`Core::poll_sweep_count_for_test`] gives the poll.
///
/// Two things worth recording beside this scheduler rather than only in
/// [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md):
/// `Gone` is systematically under-reported without this cycle running, because a
/// remote-tracking ref only disappears once a prune removes it
/// ([`crate::landing`]'s `classify_unmerged_branch` doc comment), so a Repo with
/// `fetch.enabled = false` can carry a stale upstream indefinitely and never show
/// it. And the cadence itself is unresolved: `fetch.interval`'s default of five
/// minutes is [config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
/// stated number, not one this crate has measured against a real population the
/// way the poll interval and the generation deadline were.
fn run_fetch_cycle(
    table: &Arc<RwLock<Table>>,
    concurrency: usize,
    refresh: &RefreshHandles,
    cycle_count: &Arc<AtomicUsize>,
    failures: &Arc<Mutex<FetchFailures>>,
    auto_update_enabled: bool,
) {
    cycle_count.fetch_add(1, Ordering::Release);

    let common_dirs = distinct_fetchable_common_dirs(table);
    let failed: Mutex<Vec<(PathBuf, String)>> = Mutex::new(Vec::new());
    crate::fetch::run_bounded(common_dirs, concurrency.max(1), |common_dir| {
        let cancel = AtomicBool::new(false);
        // Every repository's own fetch result is independent: one credential
        // failure or one unreachable remote must never stop the rest of the
        // cycle from running, so a per-repository error is swallowed here
        // rather than aborting the whole cycle. It is still counted below,
        // which is the count this cycle's own [`FetchFailures`] carries.
        match crate::fetch::fetch_and_prune(&common_dir, &cancel) {
            Ok(outcome) => {
                // The handshake this fetch already paid for is what
                // [default-branch.md](https://github.com/paulchiu/repon/blob/main/docs/spec/default-branch.md)'s
                // "The network" means by "arrives inside a round trip already being
                // paid for": landed here, before `refresh.dispatch` below re-runs
                // the local chain, so the local answer always computes first and
                // this only ever supersedes it. `Unborn` and a missing answer both
                // leave any earlier session answer for this common dir untouched,
                // since neither is itself a fact worth overwriting one with.
                if let Some(crate::fetch::AdvertisedDefaultBranch::Branch(name)) =
                    outcome.advertised_default_branch
                {
                    refresh
                        .network_default_branch
                        .lock()
                        .unwrap()
                        .insert(common_dir.clone(), Arc::from(name));
                }
            }
            Err(error) => {
                failed
                    .lock()
                    .unwrap()
                    .push((common_dir.clone(), error.to_string()));
            }
        }
    });
    *failures.lock().unwrap() = FetchFailures {
        failed: failed.into_inner().unwrap(),
    };

    // The fast-forward-only auto-update rides this cycle rather than a timer of its
    // own, per `docs/spec/config.md`'s "Refresh, fetch and auto-update": it can only
    // ever act on what the fetch just above learned, so it runs here, after every
    // fetch has settled and before the one Generation below reports the result.
    // Sequential rather than `fetch::run_bounded`'s own concurrency, since this is a
    // mutating pass over a Repo's own working tree and index, not a read against a
    // remote: ADR 0002's narrowest-safe-operation rule favours a simple, serial pass
    // over throughput a mutation has no need of.
    if auto_update_enabled {
        for repo_path in repos_eligible_for_auto_update_attempt(table) {
            // One Repo's ineligibility or failure never stops another's: the same
            // independence the fetch loop above already gives each repository.
            let _ = crate::auto_update::attempt(&repo_path);
        }
    }

    let all_keys: Vec<EntityKey> = table
        .read()
        .unwrap()
        .entities
        .iter()
        .map(|entity| entity.key.clone())
        .collect();
    refresh.dispatch(&all_keys);
}

/// Every non-excluded Repo's own working directory, one per distinct common dir the
/// table currently knows: the auto-update acts on a Repo's own row, per
/// `docs/spec/config.md`'s "acts only on a Repo", so a Worktree sharing that common
/// dir is never a candidate here even though it is `distinct_fetchable_common_dirs`'s
/// own definition of "fetchable" for the read-only fetch above. Listed, never
/// operated on, mirrors the same `excluded` rule the fetch loop's own common-dir
/// filter applies, checked here against the Repo entity's own flag rather than any
/// Worktree that happens to share its common dir.
fn repos_eligible_for_auto_update_attempt(table: &Arc<RwLock<Table>>) -> Vec<PathBuf> {
    table
        .read()
        .unwrap()
        .entities
        .iter()
        .filter(|entity| entity.kind == Kind::Repo && !entity.excluded)
        .map(|entity| entity.key.path().to_path_buf())
        .collect()
}

/// Every distinct git common dir a fetch cycle should fetch: deduplicated across
/// every entity sharing one (a Repo and its linked Worktrees), and skipped only
/// when every entity sharing that common dir is excluded
/// ([config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md#per-repo-entries)'s
/// "listed, never operated on"), since a Worktree named directly by its own path
/// can carry a different `excluded` than an entry it would otherwise inherit.
fn distinct_fetchable_common_dirs(table: &Arc<RwLock<Table>>) -> Vec<PathBuf> {
    let table = table.read().unwrap();
    let mut seen: HashMap<PathBuf, bool> = HashMap::new();
    for entity in &table.entities {
        let common_dir = entity.common_dir.to_path_buf();
        let operable = seen.entry(common_dir).or_insert(false);
        *operable = *operable || !entity.excluded;
    }
    seen.into_iter()
        .filter(|(_, operable)| *operable)
        .map(|(common_dir, _)| common_dir)
        .collect()
}

/// [`Core::rederive_default_branches`]'s own network half: a handshake-only probe
/// per `common_dir`, landing a `Branch` answer on `network_default_branch` for
/// [`supersede_with_network`] to read back. `Unborn` and a probe failure both
/// leave any earlier session answer for that common dir untouched, the same
/// convention [`run_fetch_cycle`] already follows.
fn probe_network_default_branches(
    common_dirs: &HashSet<Arc<Path>>,
    network_default_branch: &Mutex<HashMap<PathBuf, Arc<str>>>,
) {
    for common_dir in common_dirs {
        if let Ok(Some(crate::fetch::AdvertisedDefaultBranch::Branch(name))) =
            crate::fetch::probe_remote_head(common_dir)
        {
            network_default_branch
                .lock()
                .unwrap()
                .insert(common_dir.to_path_buf(), Arc::from(name));
        }
    }
}

/// One entity [`Core::rederive_default_branches`] gathered under the table lock,
/// everything its own spawned thread needs to re-run the default-branch chain
/// without holding that lock while it does: a plain struct rather than a tuple,
/// per this crate's own `clippy::type_complexity` budget.
struct RederiveCandidate {
    key: EntityKey,
    path: PathBuf,
    common_dir: Arc<Path>,
    repo: Option<Arc<gix::ThreadSafeRepository>>,
    override_branch: Option<String>,
    kind: Kind,
}

/// One entity as the metadata poll sweep found it, everything gathered under one
/// read lock so the filesystem stats and any re-probe below run outside it.
struct PollCandidate {
    key: EntityKey,
    path: PathBuf,
    common_dir: Arc<Path>,
    kind: Kind,
    cached_repo: Option<Arc<gix::ThreadSafeRepository>>,
    probes_base: bool,
}

/// One metadata-poll sweep ([refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
/// "The poll"): for every entity a Generation's dispatch would also cover (a
/// hidden Submodule is skipped by the same [`dispatches_kind`] rule), stats
/// [`poll::POLLED_GITDIR_ENTRIES`] in its own gitdir. That gitdir is the cached
/// [`gix::ThreadSafeRepository`] handle's own `git_dir()` where discovery cached
/// one (the per-worktree location a linked Worktree's `HEAD` and `index` actually
/// live at), or else a fresh open's `git_dir()`, the same fallback every other
/// probe in this module already takes for a Submodule, which discovery never
/// opens. A first sweep for a newly discovered entity has nothing to compare
/// against yet, so it only records a baseline and reports no movement.
///
/// On movement it force-stales `dirty` and `state`, the two cells with no cheap
/// detector, then re-runs phases A and B for that entity alone and lets their own
/// supersession land the fresh values; it never starts a status probe of its own.
/// `poll_reprobed` is cleared and refilled with exactly the keys this call
/// actually re-ran, in the order it found them moved. `poll_sweep_count` counts
/// every call, whether or not anything moved, so a test can prove a real tick
/// reached this function at all.
fn run_poll_sweep(
    table: &Arc<RwLock<Table>>,
    overrides: &Arc<Vec<ResolvedOverride>>,
    show_submodules: &Arc<AtomicBool>,
    poll_reprobed: &Arc<Mutex<Vec<EntityKey>>>,
    poll_sweep_count: &Arc<AtomicUsize>,
    network_default_branch: &Mutex<HashMap<PathBuf, Arc<str>>>,
) {
    poll_sweep_count.fetch_add(1, Ordering::Release);
    poll_reprobed.lock().unwrap().clear();
    let show_submodules = show_submodules.load(Ordering::Acquire);

    let candidates: Vec<PollCandidate> = {
        let table = table.read().unwrap();
        table
            .entities
            .iter()
            .filter(|entity| dispatches_kind(entity.kind, show_submodules))
            .map(|entity| PollCandidate {
                key: entity.key.clone(),
                path: entity.key.path().to_path_buf(),
                common_dir: Arc::clone(&entity.common_dir),
                kind: entity.kind,
                cached_repo: table.repos.get(&entity.key).cloned(),
                probes_base: entity.probes_base(),
            })
            .collect()
    };

    for candidate in candidates {
        // A fresh open, never cached across sweeps: this is the same cost every
        // other probe in this module already pays for an entity discovery left
        // no handle for (always true of a Submodule), and reusing the handle it
        // returns for the re-probe below saves a second open on the one path
        // that actually detected movement.
        let opened;
        let repo = match candidate.cached_repo.as_deref() {
            Some(repo) => Some(repo),
            None => match git::open_thread_safe(&candidate.path) {
                Ok(repo) => {
                    opened = repo;
                    Some(&opened)
                }
                Err(_) => None,
            },
        };
        let gitdir = repo
            .map(|repo| repo.git_dir().to_path_buf())
            .unwrap_or_else(|| candidate.common_dir.to_path_buf());

        let current = poll::fingerprint(&gitdir);
        let moved = {
            let mut table = table.write().unwrap();
            let previous = table
                .poll_fingerprints
                .insert(candidate.key.clone(), current);
            previous.is_some_and(|previous| poll::moved(&previous, &current))
        };
        if !moved {
            continue;
        }

        {
            let mut table = table.write().unwrap();
            if let Some(&idx) = table.index.get(&candidate.key) {
                table.entities[idx].force_stale_status_cells();
            }
        }

        let override_branch = find_entry(overrides, &candidate.path, &candidate.common_dir)
            .and_then(|entry| entry.default_branch.clone());
        let never_cancelled = AtomicBool::new(false);
        let chain_cache: ChainFactsCache = Mutex::new(HashMap::new());
        let chain_reads = AtomicUsize::new(0);

        let branch_outcome = probe_branch(&candidate.path, repo, candidate.kind, &never_cancelled);
        let sync_outcome = probe_sync(
            &candidate.path,
            repo,
            branch_outcome.as_ref().map(|(settled, ..)| settled),
            candidate.kind,
            &never_cancelled,
        );
        let default_branch_outcome = probe_default_branch_memoised(
            &candidate.path,
            repo,
            &candidate.common_dir,
            DefaultBranchHints {
                override_branch: override_branch.as_deref(),
                network_branch: network_branch_for(network_default_branch, &candidate.common_dir)
                    .as_deref(),
            },
            candidate.kind,
            &never_cancelled,
            &ChainFactsMemo {
                cache: &chain_cache,
                reads: &chain_reads,
            },
        );
        let base_outcome = if candidate.probes_base {
            probe_base(
                &candidate.path,
                repo,
                branch_outcome.as_ref().map(|(settled, ..)| settled),
                default_branch_outcome.as_ref().map(|r| &r.settled),
                &never_cancelled,
            )
        } else {
            None
        };

        let generation = {
            let mut table = table.write().unwrap();
            table.generation += 1;
            Generation::new(table.generation)
        };
        apply_cheap_probe_outcomes(
            table,
            &candidate.key,
            generation,
            CheapProbeOutcomes {
                branch: branch_outcome,
                sync: sync_outcome,
                base: base_outcome,
                default_branch: default_branch_outcome,
            },
        );
        poll_reprobed.lock().unwrap().push(candidate.key);
    }
}

/// Cancels every probe currently in flight and drops the table's record of them,
/// which is what suspension does: the in-flight Generation is cancelled outright
/// rather than left to finish. Releases a pending `settle` too, since nothing is
/// now going to finish it.
fn cancel_in_flight(table: &Arc<RwLock<Table>>, settle_gate: &Arc<SettleGate>) {
    let mut table = table.write().unwrap();
    let cancelled = table.in_flight.len();
    for in_flight in table.in_flight.values() {
        in_flight.cancel.store(true, Ordering::Release);
    }
    table.in_flight.clear();
    table.generation_started_at.clear();
    drop(table);
    if cancelled > 0 {
        complete_many(settle_gate, cancelled);
    }
}

/// A `Cell<T>`'s in-flight and timeout behaviour, uniform across every payload
/// type `EntityState` carries, so [`sweep_deadline`] can sweep every cell
/// through one array rather than one hand-written branch per cell: a cell only
/// ever times out if it was actually marked in flight, which is what lets the
/// sweep apply to all of them without asking what `Kind` owns them.
trait TimeoutableCell {
    fn is_in_flight(&self) -> bool;
    /// Settles this cell `Unknown(TimedOut)` for `generation`, subject to the
    /// same supersession `Cell::settle` already enforces.
    fn time_out(&mut self, generation: Generation);
}

impl<T> TimeoutableCell for Cell<T> {
    fn is_in_flight(&self) -> bool {
        Cell::is_in_flight(self)
    }

    fn time_out(&mut self, generation: Generation) {
        self.settle(generation, Settled::Unknown(Unknown::TimedOut));
    }
}

/// Marks every cell still in flight past its own Generation's deadline `Unknown`,
/// per [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md):
/// there is no per-cell timeout, only this sweep, and it never interrupts the
/// underlying probe, which keeps running; the sweep only stops waiting on it.
fn sweep_deadline(table: &Arc<RwLock<Table>>, settle_gate: &Arc<SettleGate>, deadline: Duration) {
    let mut table = table.write().unwrap();
    let now = Instant::now();
    let mut timed_out = Vec::new();
    for (key, in_flight) in table.in_flight.iter() {
        let started = table
            .generation_started_at
            .get(&in_flight.generation)
            .copied()
            .unwrap_or(now);
        if now.duration_since(started) >= deadline {
            timed_out.push((key.clone(), Generation::new(in_flight.generation)));
        }
    }
    for (key, generation) in &timed_out {
        if let Some(&idx) = table.index.get(key) {
            // Exhaustive: a Cell added to `EntityState` later must be named here
            // or this fails to compile, so it cannot silently time out never.
            let EntityState {
                key: _,
                name: _,
                common_dir: _,
                kind: _,
                branch,
                sync,
                base,
                dirty,
                state,
                default_branch,
                diagnostics: _,
                last_action: _,
                presence: _,
                excluded: _,
                in_progress_operation: _,
                recent_commits: _,
            } = &mut table.entities[idx];
            let cells: [&mut dyn TimeoutableCell; 6] =
                [branch, sync, base, dirty, state, default_branch];
            for cell in cells {
                // Only a cell actually marked in flight times out: a Repo's or a
                // Submodule's `state` (never probed, by `EntityState::probes_state`)
                // and any cell no probe yet reaches (`sync`, `base`) are never in
                // flight, so this never overwrites them with a lie.
                if cell.is_in_flight() {
                    cell.time_out(*generation);
                }
            }
        }
        table.in_flight.remove(key);
    }
    let live_generations: std::collections::HashSet<u64> =
        table.in_flight.values().map(|f| f.generation).collect();
    table
        .generation_started_at
        .retain(|generation, _| live_generations.contains(generation));
    drop(table);
    if !timed_out.is_empty() {
        complete_many(settle_gate, timed_out.len());
    }
}

/// Marks the cells this Generation's dispatch is about to probe as in flight,
/// via an exhaustive destructure of `EntityState`'s cells: a cell added later
/// must be named here (`_` if it is not yet probed) or this fails to compile,
/// which is what stops a cell [`apply_probe_outcome`] settles from going
/// in-flight silently forgotten, and reading wrong on `is_in_flight` for the
/// whole dispatch.
fn begin_probes(entity: &mut EntityState) {
    let probes_state = entity.probes_state();
    let EntityState {
        key: _,
        name: _,
        common_dir: _,
        kind: _,
        branch,
        sync: _,
        base: _,
        dirty,
        state,
        default_branch,
        diagnostics: _,
        last_action: _,
        presence: _,
        excluded: _,
        in_progress_operation: _,
        recent_commits: _,
    } = entity;
    branch.begin_probe();
    default_branch.begin_probe();
    // Phase C runs against every dispatched entity, Repo, Worktree or Submodule alike:
    // refresh.md's "Scope and order" makes scope never a partial dial, so `dirty` carries
    // no `probes_state`-style condition of its own.
    dirty.begin_probe();
    // Only a Worktree's `state` is ever (re)probed: a Repo's is `NotApplicable`
    // and a Submodule's is `Unknown` from construction, neither ever revisited
    // (`EntityState::probes_state`), and marking either in flight here would
    // leave it in-flight forever, since nothing would ever call `settle` on it.
    if probes_state {
        state.begin_probe();
    }
}

/// What [`Core::try_settle`] waits on, and the one lock every count it waits on lives
/// under, so a settle can never observe one of them without the other.
type SettleGate = (Mutex<SettleCounts>, Condvar);

/// The two outstanding counts [`Core::try_settle`] blocks on.
///
/// `dispatches` exists because a Generation reserves its number on the calling
/// thread and does everything else on one of its own: between those two moments
/// `probes` has not been raised yet, so a settle reading `probes` alone would
/// return on a table nothing has started writing to.
#[derive(Default)]
struct SettleCounts {
    /// Dispatched entities that have yet to land a phase C/D outcome, be cancelled
    /// or time out.
    probes: usize,
    /// Generations whose number is reserved and whose own dispatch body has not
    /// finished raising `probes` for what it dispatches.
    dispatches: usize,
}

impl SettleCounts {
    /// Whether nothing this `Core` has started is still owed to the table.
    ///
    /// An exhaustive destructure: a third count added to this struct must be named here
    /// or this fails to compile, rather than being silently left out of what a settle
    /// waits for.
    fn is_settled(&self) -> bool {
        let SettleCounts { probes, dispatches } = self;
        *probes == 0 && *dispatches == 0
    }
}

/// Records one reserved Generation as owed, before the thread that will dispatch
/// it has started. Paired with exactly one [`finish_dispatch`].
fn begin_dispatch(settle_gate: &SettleGate) {
    let (lock, _cvar) = settle_gate;
    lock.lock().unwrap().dispatches += 1;
}

/// Releases the debt [`begin_dispatch`] recorded, once that Generation's own
/// dispatch has raised `probes` for everything it dispatched.
fn finish_dispatch(settle_gate: &SettleGate) {
    let (lock, cvar) = settle_gate;
    let mut counts = lock.lock().unwrap();
    counts.dispatches = counts.dispatches.saturating_sub(1);
    drop(counts);
    // Unconditionally, unlike `complete_many`: a waiter watching `dispatches` alone
    // would never be woken by a change that leaves `probes` outstanding.
    cvar.notify_all();
}

fn begin_probes_owed(settle_gate: &SettleGate, owed: usize) {
    let (lock, _cvar) = settle_gate;
    lock.lock().unwrap().probes += owed;
}

fn complete_one(settle_gate: &SettleGate) {
    complete_many(settle_gate, 1);
}

fn complete_many(settle_gate: &SettleGate, finished: usize) {
    let (lock, cvar) = settle_gate;
    let mut counts = lock.lock().unwrap();
    counts.probes = counts.probes.saturating_sub(finished);
    if counts.is_settled() {
        cvar.notify_all();
    }
}

/// Reads one entity's HEAD shape, or `None` if `cancel` was already set before the
/// read started. The one check this crate makes today: `git::head_shape` itself has
/// no interruption point to check `cancel` against mid-read, unlike the later
/// phases [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)
/// describes gix taking it through directly.
///
/// `repo` is the entity's cached thread-safe handle when discovery already opened
/// one; this task derives its own `Repository` from it via `to_thread_local`
/// rather than sharing that derived handle with any other task. `None` (a
/// Submodule, or a boundary discovery could not open) falls back to opening fresh,
/// which is where an unreadable repository's `ProbeError::Open` still surfaces.
///
/// Also reads the entity's in-progress git operation and recent commits off the
/// same open handle, since both ride along at negligible extra cost
/// ([ADR 0019](https://github.com/paulchiu/repon/blob/main/docs/adr/0019-a-detached-head-is-a-shape-of-head-not-a-worktree-state.md)).
/// Neither is a Cell in its own right, so both travel with the branch read they
/// were taken alongside rather than getting independent supersession of their
/// own; [`EntityState::apply_branch_probe`] is where that pairing lands.
const RECENT_COMMITS_LIMIT: usize = 5;

/// What an open-repository failure means for `kind`: a genuine Probe error for a Repo or a
/// Worktree, but for a Submodule the far more common, expected shape of "never `git
/// submodule update --init`-ed" ([discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)'s
/// "The Submodule row": "An uninitialised Submodule is a row with every cell blank and `?`
/// in the gutter"). Exhaustive over `Kind` rather than a wildcard, so a fourth variant added
/// later must decide which grade it gets rather than silently inheriting one.
fn submodule_open_failure<T>(kind: Kind, error: git::ProbeError) -> Settled<T> {
    match kind {
        Kind::Repo | Kind::Worktree => Settled::Failed(error),
        Kind::Submodule => Settled::Unknown(Unknown::SubmoduleUninitialized),
    }
}

fn probe_branch(
    path: &Path,
    repo: Option<&gix::ThreadSafeRepository>,
    kind: Kind,
    cancel: &AtomicBool,
) -> Option<(
    Settled<Head>,
    Option<git::InProgressOperation>,
    Vec<git::RecentCommit>,
)> {
    if cancel.load(Ordering::Acquire) {
        return None;
    }
    let opened;
    let repo = match repo {
        Some(repo) => repo,
        None => match git::open_thread_safe(path) {
            Ok(repo) => {
                opened = repo;
                &opened
            }
            Err(error) => return Some((submodule_open_failure(kind, error), None, Vec::new())),
        },
    };
    let local = repo.to_thread_local();
    let settled = match git::head_shape(&local) {
        Ok(head) => Settled::Known {
            value: head,
            at: Timestamp::now(),
            stale: false,
        },
        Err(error) => Settled::Failed(error),
    };
    let in_progress = git::in_progress_operation(&local);
    let recent = git::recent_commits(&local, RECENT_COMMITS_LIMIT);
    Some((settled, in_progress, recent))
}

/// Phase B's comparison: the `sync` cell's ahead/behind counts against the
/// branch's upstream, for every entity whose HEAD carries a branch, every
/// Generation ([refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)).
/// `None` if `cancel` was already set, or if `branch_settled` is itself `None`
/// because the branch probe it depends on was cancelled first. A `Failed` branch
/// read fails `sync` the same way, rather than guessing at a HEAD shape the
/// branch probe itself could not read; every other shape (a live branch, a
/// detached or unborn HEAD) is handed to [`git::resolve_sync`], which is where
/// "no branch" and "no remote at all" settle to their own values. `repo` follows
/// the same cached-handle convention as [`probe_branch`].
fn probe_sync(
    path: &Path,
    repo: Option<&gix::ThreadSafeRepository>,
    branch_settled: Option<&Settled<Head>>,
    kind: Kind,
    cancel: &AtomicBool,
) -> Option<Settled<SyncState>> {
    if cancel.load(Ordering::Acquire) {
        return None;
    }
    let head = match branch_settled? {
        Settled::Known {
            value,
            at: _,
            stale: _,
        } => Some(value),
        Settled::Failed(error) => return Some(Settled::Failed(error.clone())),
        Settled::Unknown(_) | Settled::NotApplicable => None,
    };
    let opened;
    let repo = match repo {
        Some(repo) => repo,
        None => match git::open_thread_safe(path) {
            Ok(repo) => {
                opened = repo;
                &opened
            }
            Err(error) => return Some(submodule_open_failure(kind, error)),
        },
    };
    let local = repo.to_thread_local();
    let settled = match git::resolve_sync(&local, head) {
        Ok(value) => Settled::Known {
            value,
            at: Timestamp::now(),
            stale: false,
        },
        Err(error) => Settled::Failed(error),
    };
    Some(settled)
}

/// Phase B's second rev-walk: the `base` cell's count behind the resolved default
/// branch, for every entity [`crate::base::probe`] does not exempt
/// ([default-branch.md](https://github.com/paulchiu/repon/blob/main/docs/spec/default-branch.md)'s
/// "The two behind counts"). `None` if `cancel` was already set, or if either
/// `branch_settled` or `default_branch_settled` is itself `None` because the probe
/// it depends on was cancelled first; [`crate::base::probe`] itself always settles
/// once reached. A `Failed` or not-yet-`Known` `branch_settled` carries no commit to
/// compare, so it is treated the same "nothing to settle yet" way, except a genuine
/// `Failed` branch read, which propagates onto `base` too: a row whose HEAD could
/// not be read has nothing to compute behind anything. `repo` follows the same
/// cached-handle convention as [`probe_branch`].
fn probe_base(
    path: &Path,
    repo: Option<&gix::ThreadSafeRepository>,
    branch_settled: Option<&Settled<Head>>,
    default_branch_settled: Option<&Settled<DefaultBranch>>,
    cancel: &AtomicBool,
) -> Option<Settled<u32>> {
    if cancel.load(Ordering::Acquire) {
        return None;
    }
    let head = match branch_settled? {
        Settled::Known {
            value,
            at: _,
            stale: _,
        } => value,
        Settled::Failed(error) => return Some(Settled::Failed(error.clone())),
        Settled::Unknown(_) | Settled::NotApplicable => return None,
    };
    let default_branch_settled = default_branch_settled?;
    let opened;
    let repo = match repo {
        Some(repo) => repo,
        None => match git::open_thread_safe(path) {
            Ok(repo) => {
                opened = repo;
                &opened
            }
            Err(error) => return Some(Settled::Failed(error)),
        },
    };
    let local = repo.to_thread_local();
    Some(base::probe(&local, head, default_branch_settled))
}

/// Phase C's typed counts, dispatched over every entity in a Generation with no
/// scoping of its own: [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
/// "Scope and order" makes scope never a partial dial, only order, so this carries
/// no visibility filter and no cost heuristic; the caller's dispatch order is the
/// only dial, expressed entirely by the position `path` already holds in
/// `Core::refresh`'s `order`. `None` if `cancel` was already set before the read
/// started; unlike the cheaper phases above, `cancel` is also handed straight
/// into gix, which checks it while the read is under way rather than only before
/// it starts, since this is the one phase long enough for that to matter.
fn probe_status(
    path: &Path,
    repo: Option<&gix::ThreadSafeRepository>,
    kind: Kind,
    cancel: &Arc<AtomicBool>,
) -> Option<Settled<DirtyCounts>> {
    if cancel.load(Ordering::Acquire) {
        return None;
    }
    let opened;
    let repo = match repo {
        Some(repo) => repo,
        None => match git::open_thread_safe(path) {
            Ok(repo) => {
                opened = repo;
                &opened
            }
            Err(error) => return Some(submodule_open_failure(kind, error)),
        },
    };
    let local = repo.to_thread_local();
    classify_status_result(git::dirty_counts(&local, Arc::clone(cancel)), cancel)
}

/// Folds [`git::dirty_counts`]'s result into [`probe_status`]'s outcome. Split out as its own
/// function so the one case a live probe cannot reproduce deterministically, cancellation
/// observed genuinely mid-read, is directly testable: gix's own error carries no typed "this
/// was cancelled" case (its interrupt point reports through a bare `io::Error`, same as any
/// other I/O failure), so `cancel` itself, which this task alone owns for the duration of its
/// probe, is the answer. An error alongside a cancel flag now set is what an interruption
/// mid-read looks like, and [ADR 0013](https://github.com/paulchiu/repon/blob/main/docs/adr/0013-no-filesystem-watching-a-refresh-is-a-cancellable-generation.md)'s
/// precedent is that interrupted work is dropped rather than settled `Failed`, the same as
/// every cheaper phase's pre-check already does.
///
/// gix checks `should_interrupt` per index entry rather than before every read, so a walk
/// short enough to run out of entries to check between the flag flipping and the walk
/// finishing can still return `Ok`. `cancel` is re-checked on that arm too, and an `Ok` that
/// raced ahead of it is dropped the same way an `Err` alongside it already is, so a cancelled
/// generation never lands a value regardless of which side of that race gix landed on.
fn classify_status_result(
    result: Result<DirtyCounts, git::ProbeError>,
    cancel: &AtomicBool,
) -> Option<Settled<DirtyCounts>> {
    match result {
        Ok(_) if cancel.load(Ordering::Acquire) => None,
        Ok(value) => Some(Settled::Known {
            value,
            at: Timestamp::now(),
            stale: false,
        }),
        Err(_) if cancel.load(Ordering::Acquire) => None,
        Err(error) => Some(Settled::Failed(error)),
    }
}

/// Rung 1's config override and the network's session-held answer, bundled into
/// one argument the way [`ChainFactsMemo`] bundles its own two: both
/// [`probe_default_branch`] and [`probe_default_branch_memoised`] already sit at
/// clippy's argument limit, and the two hints always travel together, one per
/// dispatched entity.
struct DefaultBranchHints<'a> {
    /// Matched by common dir before this is called; `None` when no `[[repo]]`
    /// entry names this entity's own default branch.
    override_branch: Option<&'a str>,
    /// [`network_branch_for`]'s own answer for this entity's common dir; `None`
    /// until a fetch handshake or [`Core::rederive_default_branches`] has
    /// actually reached that remote this session.
    network_branch: Option<&'a str>,
}

/// [`Core::network_default_branch`]'s own lookup, by common dir: a small helper
/// so every probe site reads it the same way rather than repeating the lock and
/// clone.
fn network_branch_for(
    network_default_branch: &Mutex<HashMap<PathBuf, Arc<str>>>,
    common_dir: &Path,
) -> Option<Arc<str>> {
    network_default_branch
        .lock()
        .unwrap()
        .get(common_dir)
        .cloned()
}

/// Supersedes `resolution`'s own settled value with `network_branch`, if given,
/// per [default-branch.md](https://github.com/paulchiu/repon/blob/main/docs/spec/default-branch.md)'s
/// "The network": never the primary source, so `resolution` is always the local
/// chain's own complete answer, computed unconditionally by the caller before
/// this ever runs. This is the one place ADR 0012's stated ceiling is actually
/// closed: on a Repo where rung 2 and rung 3 agree and are both wrong (the
/// hidden-Submodule case the ADR measures), no local rung can ever correct
/// itself, and only a reachable remote's own answer, landed here, can.
fn supersede_with_network(
    mut resolution: default_branch::Resolution,
    network_branch: Option<&str>,
) -> default_branch::Resolution {
    if let Some(name) = network_branch {
        resolution.settled = Settled::Known {
            value: DefaultBranch::new(name.into()),
            at: Timestamp::now(),
            stale: false,
        };
    }
    resolution
}

/// Runs the four-rung default branch chain against `path`, or `None` if `cancel`
/// was already set before the read started, then [`supersede_with_network`]s the
/// result with `hints.network_branch`.
///
/// `repo` follows the same cached-handle convention as [`probe_branch`]: `None`
/// falls back to opening fresh, which is where an unreadable repository surfaces
/// as [`default_branch::Resolution::failed`] rather than a settled Unknown.
fn probe_default_branch(
    path: &Path,
    repo: Option<&gix::ThreadSafeRepository>,
    hints: DefaultBranchHints<'_>,
    kind: Kind,
    cancel: &AtomicBool,
) -> Option<default_branch::Resolution> {
    if cancel.load(Ordering::Acquire) {
        return None;
    }
    let opened;
    let repo = match repo {
        Some(repo) => repo,
        None => match git::open_thread_safe(path) {
            Ok(repo) => {
                opened = repo;
                &opened
            }
            Err(error) => {
                return Some(match kind {
                    Kind::Repo | Kind::Worktree => default_branch::Resolution::failed(error),
                    Kind::Submodule => default_branch::Resolution::submodule_uninitialized(),
                });
            }
        },
    };
    Some(supersede_with_network(
        default_branch::resolve(&repo.to_thread_local(), hints.override_branch),
        hints.network_branch,
    ))
}

/// Coordinates one common dir's Outstanding entities so every one of their own
/// merge bases against the default branch is known before the shared scan
/// runs, per [default-branch.md](https://github.com/paulchiu/repon/blob/main/docs/spec/default-branch.md)'s
/// requirement that the bound be *collected*, not computed lazily on whichever
/// entity happens to arrive first. `remaining` starts at the number of
/// dispatched entities in this common dir that will call [`GateReport::report`]
/// this Generation (every entity `landing::probe` runs for, whether it settles
/// immediately or reaches patch equivalence); `deepest` blocks until all of
/// them have, then folds their contributed merge bases pairwise via
/// [`git::checked_merge_base`] so the result is an ancestor of (at least as
/// deep as) every one of them, and memoises that answer for every later caller
/// sharing this dir.
struct BoundGate {
    state: Mutex<BoundGateState>,
    condvar: Condvar,
    bound: OnceLock<Option<gix::ObjectId>>,
}

struct BoundGateState {
    remaining: usize,
    candidates: Vec<gix::ObjectId>,
}

impl BoundGate {
    fn new(remaining: usize) -> Self {
        Self {
            state: Mutex::new(BoundGateState {
                remaining,
                candidates: Vec::new(),
            }),
            condvar: Condvar::new(),
            bound: OnceLock::new(),
        }
    }

    /// One entity's contribution: `Some(base)` when it reached patch
    /// equivalence and had a merge base to offer, `None` otherwise (it settled
    /// by ancestry, was cancelled, failed to read, or shared no history with
    /// the default branch at all). Wakes every task blocked in [`Self::deepest`]
    /// once every entity counted in `remaining` has reported.
    fn report(&self, candidate: Option<gix::ObjectId>) {
        let mut state = self.state.lock().unwrap();
        if let Some(candidate) = candidate {
            state.candidates.push(candidate);
        }
        state.remaining -= 1;
        if state.remaining == 0 {
            self.condvar.notify_all();
        }
    }

    /// Blocks until every entity sharing this common dir has reported, then
    /// returns the deepest merge base among their contributions (`None` if
    /// none contributed one, so the scan is left unbounded). The candidates are
    /// taken and folded into `bound` inside the same critical section, so
    /// whichever call is first to finish waiting is guaranteed to be the one
    /// that computes the memoised answer from them; computing outside the lock
    /// would let a later call, left holding an empty list by
    /// [`std::mem::take`], win the race into [`OnceLock::get_or_init`] and
    /// memoise `None` regardless of what the first call actually contributed.
    fn deepest(&self, repo: &gix::Repository) -> Option<gix::ObjectId> {
        let mut state = self.state.lock().unwrap();
        while state.remaining != 0 {
            state = self.condvar.wait(state).unwrap();
        }
        let candidates = std::mem::take(&mut state.candidates);
        *self
            .bound
            .get_or_init(|| deepest_merge_base(repo, &candidates))
    }
}

/// Folds `candidates` pairwise via [`git::checked_merge_base`] into the one
/// deepest among them: when two candidates are ancestor and descendant, their
/// own merge base is exactly the ancestor, so the fold converges on whichever
/// candidate is deepest; two on unrelated lines of history fold to their own
/// common ancestor instead, which is still a safe (if not the tightest
/// possible) lower bound for the scan.
fn deepest_merge_base(
    repo: &gix::Repository,
    candidates: &[gix::ObjectId],
) -> Option<gix::ObjectId> {
    let mut candidates = candidates.iter().copied();
    let mut deepest = candidates.next()?;
    for candidate in candidates {
        deepest = git::checked_merge_base(repo, deepest, candidate)
            .ok()
            .flatten()
            .unwrap_or(deepest);
    }
    Some(deepest)
}

/// Reports exactly once to a [`BoundGate`], on drop if [`Self::report_now`] was
/// never called explicitly: every exit path out of [`probe_worktree_state`]
/// and [`probe_patch_equivalence`] must release its common dir's gate, since a
/// path that forgot to would deadlock every sibling still waiting in
/// [`BoundGate::deepest`].
struct GateReport<'a> {
    gate: &'a BoundGate,
    reported: bool,
}

impl<'a> GateReport<'a> {
    fn new(gate: &'a BoundGate) -> Self {
        Self {
            gate,
            reported: false,
        }
    }

    /// Reports `candidate` immediately rather than waiting for drop: the one
    /// path that goes on to call [`BoundGate::deepest`] must report its own
    /// contribution first, or it would wait on a count that can never reach
    /// zero without its own report.
    fn report_now(&mut self, candidate: Option<gix::ObjectId>) {
        self.gate.report(candidate);
        self.reported = true;
    }
}

impl Drop for GateReport<'_> {
    fn drop(&mut self) {
        if !self.reported {
            self.gate.report(None);
        }
    }
}

/// The per-common-dir patch-equivalence memo plumbing, bundled into one
/// argument so [`probe_worktree_state`] and [`probe_patch_equivalence`] each
/// take it as a single parameter rather than three loose ones.
struct PatchEquivalenceMemo<'a> {
    cache: &'a PatchIdentityCache,
    reads: &'a AtomicUsize,
    /// Where [`probe_patch_equivalence`] records the bound it actually passed to
    /// [`patch_equivalence::scan_default_branch`], for `Core::patch_scan_bounds_for_test`.
    scan_bounds: &'a Mutex<Vec<Option<gix::ObjectId>>>,
}

/// Runs both of Phase D's passes for one Worktree entity: `landing::probe`'s
/// ancestry check, then, only when it answers `Outstanding`,
/// [`probe_patch_equivalence`]'s content check. `None` if `cancel` was already
/// set, or if `default_branch_settled` is itself `None` because the
/// default-branch probe it depends on was cancelled first. `repo` follows the
/// same cached-handle convention as [`probe_branch`]. `report` always reports
/// exactly once to this entity's common dir's `BoundGate`, on every path
/// through this function, via its own `Drop`.
fn probe_worktree_state(
    path: &Path,
    repo: Option<&gix::ThreadSafeRepository>,
    default_branch_settled: Option<&Settled<DefaultBranch>>,
    common_dir: &Arc<Path>,
    cancel: &AtomicBool,
    memo: &PatchEquivalenceMemo<'_>,
    report: &mut GateReport<'_>,
) -> Option<Settled<WorktreeState>> {
    if cancel.load(Ordering::Acquire) {
        return None;
    }
    let default_branch_settled = default_branch_settled?;
    let opened;
    let repo = match repo {
        Some(repo) => repo,
        None => match git::open_thread_safe(path) {
            Ok(repo) => {
                opened = repo;
                &opened
            }
            Err(error) => return Some(Settled::Failed(error)),
        },
    };
    let local = repo.to_thread_local();
    match landing::probe(&local, default_branch_settled) {
        landing::Outcome::Settle(settled) => Some(settled),
        landing::Outcome::Outstanding(outstanding) => {
            probe_patch_equivalence(&local, &outstanding, common_dir, cancel, memo, report)
        }
    }
}

/// Phase D's expensive half, reached only when `landing::probe` answered
/// `Outstanding`: this is the seam that keeps patch equivalence off every
/// entity ancestry already settled. Reports the merge base the first pass
/// already walked to `report` *before* asking for the shared scan, then checks
/// patch equivalence against `memo`'s per-common-dir cache, per
/// [default-branch.md](https://github.com/paulchiu/repon/blob/main/docs/spec/default-branch.md)'s
/// "Two passes on screen" and its bound on the scan's own depth.
fn probe_patch_equivalence(
    repo: &gix::Repository,
    outstanding: &landing::Outstanding,
    common_dir: &Arc<Path>,
    cancel: &AtomicBool,
    memo: &PatchEquivalenceMemo<'_>,
    report: &mut GateReport<'_>,
) -> Option<Settled<WorktreeState>> {
    if cancel.load(Ordering::Acquire) {
        return None;
    }
    let landing::Outstanding {
        entity_tip,
        default_tip,
        merge_base,
    } = *outstanding;
    let Some(merge_base) = merge_base else {
        // No shared history at all: a real negative the first pass already
        // established. This entity needs no bound and no shared scan, so it
        // reports and settles without waiting on either; the empty set is never
        // actually consulted, since `probe` returns `Active` for a `None` merge
        // base before it would look.
        report.report_now(None);
        return Some(patch_equivalence::probe(
            repo,
            entity_tip,
            None,
            &patch_equivalence::PatchIdentitySet::new(),
        ));
    };
    // Reported now, not left to `report`'s `Drop`: the wait just below blocks
    // on every entity sharing this common dir having reported, this entity
    // included, so reporting late here would deadlock on its own wait.
    report.report_now(Some(merge_base));
    let bound = report.gate.deepest(repo);
    let shared = match patch_identities_for(memo.cache, common_dir, memo.reads, || {
        // Recorded here, inside the closure that only ever runs for whichever
        // entity's task is first to reach `patch_identities_for` for this common
        // dir, so this is the bound the one real `scan_default_branch` call for
        // it actually used, not a value a test recomputes independently.
        memo.scan_bounds.lock().unwrap().push(bound);
        patch_equivalence::scan_default_branch(repo, default_tip, bound)
    }) {
        Ok(shared) => shared,
        Err(error) => return Some(Settled::Failed(error)),
    };
    Some(patch_equivalence::probe(
        repo,
        entity_tip,
        Some(merge_base),
        &shared,
    ))
}

/// One Generation's patch-equivalence memo: at most one
/// [`patch_equivalence::PatchIdentitySet`] per common dir, shared by every
/// dispatched entity `landing::probe` answered `Outstanding` for. Built fresh
/// in [`Core::refresh`] and dropped once every task from that dispatch has
/// finished, the same lifetime `ChainFactsCache` has. The computed `Result` is
/// itself cached, since a common dir a scan fails against fails identically
/// for every entity sharing it this Generation.
type PatchIdentityCache = Mutex<
    HashMap<Arc<Path>, Arc<OnceLock<Result<patch_equivalence::PatchIdentitySet, git::ProbeError>>>>,
>;

/// The per-common-dir half of [`probe_patch_equivalence`]: returns the
/// already-computed scan for `common_dir` if another entity in this
/// Generation's dispatch already ran it, blocking until that computation
/// finishes if it is still running; otherwise runs `compute` itself, caches the
/// result, and increments `reads` exactly once for the common dir this call is
/// the first to reach. Structurally identical to [`chain_facts_for`]; kept
/// separate rather than made generic over it, since the two caches are keyed by
/// different Generations' worth of dispatch and sharing one would blur which
/// pass a given read counted for.
fn patch_identities_for(
    cache: &PatchIdentityCache,
    common_dir: &Arc<Path>,
    reads: &AtomicUsize,
    compute: impl FnOnce() -> Result<patch_equivalence::PatchIdentitySet, git::ProbeError>,
) -> Result<patch_equivalence::PatchIdentitySet, git::ProbeError> {
    let cell = {
        let mut cache = cache.lock().unwrap();
        Arc::clone(
            cache
                .entry(Arc::clone(common_dir))
                .or_insert_with(|| Arc::new(OnceLock::new())),
        )
    };
    cell.get_or_init(|| {
        reads.fetch_add(1, Ordering::Relaxed);
        compute()
    })
    .clone()
}

/// One Generation's default-branch chain memo: at most one [`default_branch::ChainFacts`]
/// per common dir, shared by every dispatched entity that names it. Built fresh in
/// [`Core::refresh`] and dropped once every task from that dispatch has finished.
type ChainFactsCache = Mutex<HashMap<Arc<Path>, Arc<OnceLock<default_branch::ChainFacts>>>>;

/// The per-common-dir half of [`probe_default_branch_memoised`]: returns the
/// already-cached facts for `common_dir` if another entity in this Generation's
/// dispatch already computed them, blocking until that computation finishes if it
/// is still running; otherwise runs `compute` itself, caches the result, and
/// increments `reads` exactly once for the common dir this call is the first to
/// reach.
fn chain_facts_for(
    cache: &ChainFactsCache,
    common_dir: &Arc<Path>,
    reads: &AtomicUsize,
    compute: impl FnOnce() -> default_branch::ChainFacts,
) -> default_branch::ChainFacts {
    let cell = {
        let mut cache = cache.lock().unwrap();
        Arc::clone(
            cache
                .entry(Arc::clone(common_dir))
                .or_insert_with(|| Arc::new(OnceLock::new())),
        )
    };
    cell.get_or_init(|| {
        reads.fetch_add(1, Ordering::Relaxed);
        compute()
    })
    .clone()
}

/// Runs the four-rung default branch chain against `path`, memoising rungs 2 and
/// 3's own per-common-dir facts in `cache` so every entity sharing `common_dir`
/// within the same dispatch reads the loose file and its reference lookups once
/// rather than once per entity, per [default-branch.md](https://github.com/paulchiu/repon/blob/main/docs/spec/default-branch.md)'s
/// "Memoised per common dir within a single refresh generation". `None` if
/// `cancel` was already set before the read started; `override_branch` is rung 1's
/// own entity-specific value, never memoised because it is not a common-dir fact.
/// [`chain_facts_for`]'s own two collaborators, bundled so
/// [`probe_default_branch_memoised`] stays within clippy's argument limit: the two always
/// travel together, one dispatch's worth of both, per [`Core::refresh_handles`].
struct ChainFactsMemo<'a> {
    cache: &'a ChainFactsCache,
    reads: &'a AtomicUsize,
}

fn probe_default_branch_memoised(
    path: &Path,
    repo: Option<&gix::ThreadSafeRepository>,
    common_dir: &Arc<Path>,
    hints: DefaultBranchHints<'_>,
    kind: Kind,
    cancel: &AtomicBool,
    memo: &ChainFactsMemo<'_>,
) -> Option<default_branch::Resolution> {
    if cancel.load(Ordering::Acquire) {
        return None;
    }
    let opened;
    let repo = match repo {
        Some(repo) => repo,
        None => match git::open_thread_safe(path) {
            Ok(repo) => {
                opened = repo;
                &opened
            }
            Err(error) => {
                return Some(match kind {
                    Kind::Repo | Kind::Worktree => default_branch::Resolution::failed(error),
                    Kind::Submodule => default_branch::Resolution::submodule_uninitialized(),
                });
            }
        },
    };
    let local = repo.to_thread_local();
    let facts = chain_facts_for(memo.cache, common_dir, memo.reads, || {
        default_branch::ChainFacts::resolve(&local)
    });
    Some(supersede_with_network(
        default_branch::resolve_with_facts(&facts, hints.override_branch),
        hints.network_branch,
    ))
}

/// Phase A and B's per-cell outcomes, landed as soon as they are computed via
/// [`apply_cheap_probe_outcomes`], well before phase C or D answer. Named rather
/// than positional so a transposed pair of trailing `None`s cannot compile
/// silently into the wrong cell.
struct CheapProbeOutcomes {
    branch: Option<(
        Settled<Head>,
        Option<git::InProgressOperation>,
        Vec<git::RecentCommit>,
    )>,
    sync: Option<Settled<SyncState>>,
    base: Option<Settled<u32>>,
    default_branch: Option<default_branch::Resolution>,
}

/// Writes phase A and B's cells for `key` at `generation`, subject to the
/// per-cell supersession `Cell::settle` already enforces, and records the
/// default-branch diagnostics only on the write that actually won. Deliberately
/// does not touch `in_flight` or `settle_gate`: those belong to whichever apply
/// closes out the entity's dispatch, which per
/// [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
/// "The first frame" is this call's whole point, since a slow phase C or D must
/// never hold these cells off the table.
fn apply_cheap_probe_outcomes(
    table: &Arc<RwLock<Table>>,
    key: &EntityKey,
    generation: Generation,
    outcomes: CheapProbeOutcomes,
) {
    let CheapProbeOutcomes {
        branch: branch_outcome,
        sync: sync_outcome,
        base: base_outcome,
        default_branch: default_branch_outcome,
    } = outcomes;
    let mut table = table.write().unwrap();
    if let Some(&idx) = table.index.get(key) {
        if let Some((settled, in_progress, recent)) = branch_outcome {
            table.entities[idx].apply_branch_probe(generation, settled, in_progress, recent);
        }
        if let Some(settled) = sync_outcome {
            table.entities[idx].sync.settle(generation, settled);
        }
        if let Some(settled) = base_outcome {
            table.entities[idx].base.settle(generation, settled);
        }
        if let Some(resolution) = default_branch_outcome {
            table.entities[idx].apply_default_branch_resolution(generation, resolution);
        }
    }
}

/// Phase C and D's per-cell outcomes, landed once they answer, via
/// [`apply_probe_outcome`]: named rather than positional for the same reason as
/// [`CheapProbeOutcomes`].
struct ProbeOutcomes {
    state: Option<Settled<WorktreeState>>,
    dirty: Option<Settled<DirtyCounts>>,
}

/// Lands one probe's phase C/D outcome for `key` at `generation`: writes the
/// `state` and `dirty` cells subject to the per-cell supersession `Cell::settle`
/// already enforces, then clears `key`'s in-flight entry if `generation` still
/// owns it and signals `settle_gate` once for the whole entity. This is the one
/// write that closes out a dispatched entity, whether or not
/// [`apply_cheap_probe_outcomes`] already landed that same entity's cheap cells;
/// a test's simulated late result goes through the same path so it does not
/// duplicate this bookkeeping.
///
/// `outcomes.state` being `None` writes nothing at all: the `state` cell is left
/// exactly as unsettled as `begin_probe` alone leaves it, which is what an
/// attached branch with a live upstream ancestry could not clear, and that
/// `probe_patch_equivalence` was itself cancelled before answering, still shows.
fn apply_probe_outcome(
    table: &Arc<RwLock<Table>>,
    settle_gate: &Arc<SettleGate>,
    key: &EntityKey,
    generation: Generation,
    outcomes: ProbeOutcomes,
) {
    let ProbeOutcomes {
        state: state_outcome,
        dirty: dirty_outcome,
    } = outcomes;
    let mut table = table.write().unwrap();
    if let Some(&idx) = table.index.get(key) {
        if let Some(settled) = state_outcome {
            table.entities[idx].state.settle(generation, settled);
        }
        if let Some(settled) = dirty_outcome {
            table.entities[idx].dirty.settle(generation, settled);
        }
    }
    // By Generation as well as by key. Cancellation is cooperative, so a superseded
    // probe still runs to completion and arrives here after the Generation that
    // superseded it has already put its own entry under this key; clearing by key
    // alone would delete that live entry, leaving the entity with nothing for the
    // next Generation to interrupt and nothing for the deadline sweep to time out.
    // The settle gate is signalled either way, since the debt belongs to the probe
    // rather than to the entry.
    if table
        .in_flight
        .get(key)
        .is_some_and(|in_flight| in_flight.generation == generation.value())
    {
        table.in_flight.remove(key);
    }
    drop(table);
    complete_one(settle_gate);
}

/// Reconciles one discovery result into `table`: a found entity is inserted or
/// marked Present again, even if it was Vanished, and one no longer found is
/// marked Vanished via [`EntityState::mark_vanished`]. Returns how many
/// in-flight probes were cancelled by a newly Vanished entity, for the caller
/// to signal `settle_gate`.
fn merge_discovery(
    table: &mut Table,
    exclusions: &[ResolvedExclusion],
    discovered: Vec<discovery::DiscoveredEntity>,
    gitmodules_failures: Vec<(EntityKey, String)>,
) -> usize {
    let mut found: HashSet<EntityKey> = HashSet::with_capacity(discovered.len());

    for discovered in discovered {
        found.insert(discovered.key.clone());
        match table.index.get(&discovered.key).copied() {
            Some(idx) => {
                table.entities[idx].presence = Presence::Present;
                if let Some(repo) = discovered.repo {
                    table.repos.insert(discovered.key.clone(), repo);
                }
            }
            None => {
                let name = discovered
                    .display_name_override
                    .clone()
                    .unwrap_or_else(|| display_name(discovered.key.path()));
                let mut entity = EntityState::new(
                    discovered.key.clone(),
                    name,
                    Arc::clone(&discovered.common_dir),
                    discovered.kind,
                );
                entity.excluded =
                    excluded_by(exclusions, discovered.key.path(), &discovered.common_dir);
                if let Some(repo) = discovered.repo {
                    table.repos.insert(discovered.key.clone(), repo);
                }
                let idx = table.entities.len();
                table.index.insert(discovered.key, idx);
                table.entities.push(entity);
            }
        }
    }

    // A boundary's `.gitmodules` failure is re-derived from this pass alone,
    // never carried over from a previous one: a failure that was fixed since the
    // last Generation must clear, not stay stuck forever.
    let now_failing: HashMap<EntityKey, String> = gitmodules_failures.into_iter().collect();
    for key in &found {
        if let Some(&idx) = table.index.get(key) {
            table.entities[idx].diagnostics.gitmodules_failed = now_failing
                .get(key)
                .map(|message| Arc::from(message.as_str()));
        }
    }

    let missing: Vec<EntityKey> = table
        .index
        .keys()
        .filter(|key| !found.contains(*key))
        .cloned()
        .collect();
    let mut cancelled = 0usize;
    for key in missing {
        if let Some(&idx) = table.index.get(&key) {
            table.entities[idx].mark_vanished();
        }
        if let Some(in_flight) = table.in_flight.remove(&key) {
            in_flight.cancel.store(true, Ordering::Release);
            cancelled += 1;
        }
    }

    cancelled
}

/// A basename read from the entity's own resolved path. A real display name has
/// collision handling that belongs to [config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md);
/// this is a placeholder good enough to populate the table.
///
/// This is the one function that computes it: `start_internal`'s discovery loop
/// and `probe_now`'s fallback insert for an unknown key both call it rather than
/// formatting a name of their own, which is what keeps the name shown on screen
/// and the name a future state file would key by byte-identical.
fn display_name(path: &Path) -> Arc<str> {
    Arc::from(
        path.file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("?"),
    )
}

/// Sleeps for `warn_after`, then reports `progress`'s count and `roots` if the walk
/// still has not finished, per [discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md):
/// the one-second still-walking warning needs a timer watching an in-flight walk
/// from outside it, since discovery itself has no callback and no notion of "still
/// running". `None` once the walk has already finished.
fn watch_for_slow_discovery(
    progress: Arc<AtomicUsize>,
    finished: Arc<AtomicBool>,
    roots: Vec<PathBuf>,
    warn_after: Duration,
) -> Option<String> {
    thread::sleep(warn_after);
    if finished.load(Ordering::Acquire) {
        return None;
    }
    Some(still_walking_message(
        progress.load(Ordering::Acquire),
        &roots,
    ))
}

fn still_walking_message(directories_visited: usize, roots: &[PathBuf]) -> String {
    let roots = roots
        .iter()
        .map(|root| root.display().to_string())
        .collect::<Vec<_>>()
        .join(", ");
    format!("discovery: still walking, {directories_visited} directories reached under {roots}")
}

/// The persistent warning left once a walk abandons, per
/// [config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md#discovery-bounds):
/// unlike the still-walking warning, this one never clears itself, since the Set
/// stays out of the automatic refresh path for the life of this `Core`.
fn abandoned_discovery_message(directories_visited: usize) -> String {
    format!("discovery: stopped at {directories_visited} directories")
}

/// Runs `step` until it says it is done or `cancel` is observed set, checked before
/// every call. Returns how many times `step` actually ran, which is what lets a
/// test prove a cancelled loop stopped mid-flight rather than merely having a flag
/// set on it somewhere. Not yet called from a real probe: `git::head_shape` has no
/// loop to interrupt, so this is the shape a later, genuinely interruptible phase
/// (gix `status`, taking `should_interrupt` directly) will use.
#[allow(dead_code)] // exercised by its own test; no interruptible probe calls it yet
pub(crate) fn run_while_not_cancelled(
    cancel: &AtomicBool,
    mut step: impl FnMut() -> bool,
) -> usize {
    let mut ran = 0;
    while !cancel.load(Ordering::Acquire) {
        if !step() {
            break;
        }
        ran += 1;
    }
    ran
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::process::Command;

    use super::*;
    use crate::entity::{AheadBehind, DefaultBranchStopped, WorktreeState};
    use crate::liveness::{BACKSTOP, FIXTURE_LIFETIME, wait_for};
    use crate::snapshot::{RowSummary, summary};
    use crate::test_support::{git, head_sha, loose_object_count};

    fn init_repo_with_a_commit(path: &Path) {
        fs::create_dir_all(path).expect("create repo dir");
        gix::init(path).expect("init repo");
        let status = Command::new("git")
            .arg("-C")
            .arg(path)
            .args(["-c", "user.email=test@example.com", "-c", "user.name=Test"])
            .args(["commit", "--allow-empty", "-m", "first"])
            .status()
            .expect("run git commit");
        assert!(status.success());
    }

    /// A second (or later) commit against an already-initialised repo at `path`,
    /// with the same explicit identity `init_repo_with_a_commit` supplies: never
    /// relying on a global git identity, which a machine running CI has none of.
    /// Commits a real change, which is what the poll's own user story is about and what an
    /// empty commit is not: `git add` rewrites `.git/index` unconditionally, while whether a
    /// commit with nothing staged rewrites it is left to git's racy-entry heuristic and
    /// differs between platforms. `index` is the only one of the polled paths a commit on an
    /// attached HEAD moves, so a test that depends on an empty commit moving it is testing
    /// that heuristic rather than the poll.
    fn commit_a_change(path: &Path, message: &str) {
        let gitdir = gitdir_of(path);
        let before = poll::fingerprint(&gitdir);

        std::fs::write(path.join(format!("{message}.txt")), message.as_bytes())
            .expect("write a file to commit");
        let added = Command::new("git")
            .arg("-C")
            .arg(path)
            .args(["add", "-A"])
            .status()
            .expect("run git add");
        assert!(added.success());
        commit(path, message, &["-m", message]);

        // The fixture's own premise, asserted rather than assumed: a commit on an attached
        // HEAD moves none of the polled paths except `index` (`HEAD` is untouched, and
        // rewriting `refs/heads/<branch>` does not move `refs/` itself), so if git leaves
        // `index` alone here there is nothing for the poll to see and the failure belongs to
        // this fixture, not to the sweep it is setting up.
        assert!(
            poll::moved(&before, &poll::fingerprint(&gitdir)),
            "committing in {} moved none of the polled paths under {}, so this fixture cannot \
             show the poll anything",
            path.display(),
            gitdir.display()
        );
    }

    /// The absolute gitdir git itself reports, which for a linked Worktree is its own
    /// `.git/worktrees/<name>` rather than the `.git` file beside the checkout.
    fn gitdir_of(work_dir: &Path) -> PathBuf {
        let output = Command::new("git")
            .arg("-C")
            .arg(work_dir)
            .args(["rev-parse", "--absolute-git-dir"])
            .output()
            .expect("run git rev-parse");
        assert!(
            output.status.success(),
            "resolve the gitdir of {}",
            work_dir.display()
        );
        PathBuf::from(
            std::str::from_utf8(&output.stdout)
                .expect("a utf-8 gitdir path")
                .trim(),
        )
    }

    /// The shared tail of the commit helpers.
    fn commit(path: &Path, message: &str, args: &[&str]) {
        let status = Command::new("git")
            .arg("-C")
            .arg(path)
            .args(["-c", "user.email=test@example.com", "-c", "user.name=Test"])
            .arg("commit")
            .args(args)
            .status()
            .unwrap_or_else(|error| panic!("run git commit {message}: {error}"));
        assert!(status.success());
    }

    /// A `FetchSpec` that never fires on its own: `enabled: false`, so every
    /// existing test that does not care about the periodic fetch keeps behaving
    /// exactly as it did before this field existed.
    fn fetch_spec_for_test() -> FetchSpec {
        FetchSpec {
            enabled: false,
            interval: Duration::from_secs(3600),
            concurrency: 4,
        }
    }

    /// An `AutoUpdateSpec` that never fires on its own, the same reason
    /// [`fetch_spec_for_test`] never does: every existing test that does not care
    /// about the auto-update keeps behaving exactly as it did before this field
    /// existed.
    fn auto_update_spec_for_test() -> AutoUpdateSpec {
        AutoUpdateSpec { enabled: false }
    }

    fn spec(roots: Vec<PathBuf>) -> CoreSpec {
        CoreSpec {
            set: SetSpec {
                name: "test".to_string(),
                roots,
                include: Vec::new(),
                exclude: Vec::new(),
            },
            overrides: Vec::new(),
            poll_interval: Duration::from_secs(3600),
            status_stale_after: Duration::from_secs(3600),
            generation_deadline: Duration::from_secs(3600),
            show_submodules: false,
            fetch: fetch_spec_for_test(),
            auto_update: auto_update_spec_for_test(),
        }
    }

    /// Criterion 2's "no field" half: scope is never a partial dial, not even as a field
    /// on the plain-data struct crossing into the core. An exhaustive destructure names
    /// every field `CoreSpec` has; a scoping field added under any name fails to compile
    /// this test rather than landing unacknowledged. `show_submodules` is named here too,
    /// deliberately: it narrows probing and rendering, never what discovery bounds, so it
    /// is not the scoping field this test guards against
    /// ([discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)'s
    /// "narrows the view rather than bounding the work"). `fetch` and `auto_update` are
    /// excluded from that same guard for the same reason: they narrow what the periodic
    /// fetch and the fast-forward-only update touch, never what discovery bounds.
    #[test]
    fn core_spec_carries_no_scoping_field_scope_is_never_a_dial() {
        let CoreSpec {
            set: _,
            overrides: _,
            poll_interval: _,
            status_stale_after: _,
            generation_deadline: _,
            show_submodules: _,
            fetch: _,
            auto_update: _,
        } = spec(Vec::new());
    }

    fn root_of(dir: &tempfile::TempDir) -> PathBuf {
        dir.path().canonicalize().expect("canonicalize temp dir")
    }

    /// Blocks until `core`'s launch Generation has settled, and hands back what it settled
    /// to.
    ///
    /// `Core::start`'s own first walk is that `Core`'s Generation 1 and probes every row it
    /// finds, so a test that counts what a later Generation did, or that watches a cell
    /// only its own Generation may write, has to begin from a table launch has already
    /// finished with. [`BACKSTOP`] rather than a budget, and the gate is read afterwards so
    /// an expired wait fails here by name instead of downstream as a wrong value.
    fn settle_launch(core: &Core) -> Snapshot {
        let launched = core.settle();
        assert_eq!(
            core.settle_gate_count_for_test(),
            0,
            "launch's own Generation never settled, so nothing after this is starting from \
             the point it claims to"
        );
        launched
    }

    /// [`settle_launch`] over a `Core` built the ordinary way, for the many tests that want
    /// nothing else from the constructor.
    fn started_and_settled(spec: CoreSpec) -> (Core, Snapshot) {
        let core = Core::start_discovered(spec);
        let launched = settle_launch(&core);
        (core, launched)
    }

    /// Sets every polled gitdir entry's modification time ten seconds into the past, so any
    /// write that follows reads as newer than the baseline by more than a filesystem's
    /// timestamp granularity. Without it a commit made microseconds after the baseline sweep
    /// lands in the same coarse tick on Linux and reads as no movement at all, which is a race
    /// in the harness rather than in the poll: real sweeps are a configured interval apart.
    /// Reads the polled names from [`poll::POLLED_GITDIR_ENTRIES`] rather than restating them.
    fn backdate_polled_entries(work_dir: &Path) {
        let gitdir = gitdir_of(work_dir);

        let past = std::time::SystemTime::now() - Duration::from_secs(10);
        let mut touched = 0;
        for name in poll::POLLED_GITDIR_ENTRIES {
            let path = gitdir.join(name);
            if path.exists() {
                set_mtime_to(&path, past);
                touched += 1;
            }
        }
        assert!(
            touched > 0,
            "backdated nothing under {}; the gitdir holds none of the polled entries and the \
             baseline this sets up would not be older than what follows",
            gitdir.display()
        );
    }

    /// `utimensat`, since a plain file handle cannot set a directory's time and `refs` is one.
    fn set_mtime_to(path: &Path, at: std::time::SystemTime) {
        use std::os::unix::ffi::OsStrExt;

        let secs = at
            .duration_since(std::time::SystemTime::UNIX_EPOCH)
            .expect("a time after the epoch")
            .as_secs() as libc::time_t;
        let times = [
            libc::timespec {
                tv_sec: secs,
                tv_nsec: 0,
            },
            libc::timespec {
                tv_sec: secs,
                tv_nsec: 0,
            },
        ];
        let c_path =
            std::ffi::CString::new(path.as_os_str().as_bytes()).expect("a path with no NUL");
        let rc = unsafe { libc::utimensat(libc::AT_FDCWD, c_path.as_ptr(), times.as_ptr(), 0) };
        assert_eq!(
            rc,
            0,
            "set mtime on {}: {}",
            path.display(),
            std::io::Error::last_os_error()
        );
    }

    fn step(argv: &[&str]) -> Step {
        Step {
            argv: argv.iter().map(|s| s.to_string()).collect(),
            shell: false,
            interactive: false,
            env: Vec::new(),
        }
    }

    /// `shell = true`'s own convention: one argv element, the whole command string.
    fn shell_step(command: &str) -> Step {
        Step {
            argv: vec![command.to_string()],
            shell: true,
            interactive: false,
            env: Vec::new(),
        }
    }

    /// `shell = true` plus `interactive = true`: the same convention, run through
    /// `$SHELL -ic` instead of `$SHELL -c`.
    fn interactive_shell_step(command: &str) -> Step {
        Step {
            argv: vec![command.to_string()],
            shell: true,
            interactive: true,
            env: Vec::new(),
        }
    }

    fn action(label: &str, steps: Vec<Step>) -> ActionSpec {
        ActionSpec {
            label: Arc::from(label),
            name: Some(Arc::from(label)),
            steps,
            concurrency: 4,
            when: None,
        }
    }

    /// [`action`], narrowed by `when`, a Filter grammar predicate
    /// (`docs/spec/actions.md`'s "The Selection and the gate").
    fn action_with_when(label: &str, steps: Vec<Step>, when: &str) -> ActionSpec {
        ActionSpec {
            when: Some(Filter::parse(when)),
            ..action(label, steps)
        }
    }

    /// End-to-end: the test thread never spawns anything itself, only calls
    /// `Core`'s public methods, and real branch data still lands in the snapshot.
    /// That is the proof that the core owns the threads doing the work, not the
    /// consumer.
    #[test]
    fn refresh_and_settle_populate_real_cells_without_the_caller_spawning_a_thread() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let keys: Vec<EntityKey> = core
            .snapshot()
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();
        assert_eq!(keys.len(), 1);

        core.refresh(&keys);
        let settled = core.settle();

        let entity = &settled.entities[0];
        match entity.branch.settled() {
            Some(Settled::Known {
                value: Head::Branch { .. },
                at: _,
                stale: _,
            }) => {}
            other => panic!("expected an attached branch, got {other:?}"),
        }
    }

    // --- Single source of truth: read the first-frame budgets from the spec itself,
    // the same pattern `executor.rs` already uses for its PTY width and capture bounds
    // against `docs/spec/actions.md`. ---

    fn spec_refresh_md() -> String {
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        std::fs::read_to_string(manifest_dir.join("../../docs/spec/refresh.md"))
            .expect("read docs/spec/refresh.md")
    }

    fn spec_first_frame_budgets_ms(spec: &str) -> (u64, u64) {
        let anchor = "rows with names on screen within ";
        let after = spec
            .split(anchor)
            .nth(1)
            .expect("the first-frame budget sentence is present");
        let mut parts = after.splitn(2, "ms, every cheap column filled within ");
        let names: u64 = parts
            .next()
            .expect("a names-on-screen budget")
            .parse()
            .expect("the names-on-screen budget is an integer");
        let after_cheap = parts.next().expect("a cheap-column budget and beyond");
        let cheap_columns: u64 = after_cheap
            .split("ms,")
            .next()
            .expect("a cheap-column budget")
            .parse()
            .expect("the cheap-column budget is an integer");
        (names, cheap_columns)
    }

    /// Criterion 1: the two budgets `refresh.md`'s "The first frame" states are declared
    /// once as named constants and cross-checked against the spec sentence here, so the
    /// spec and the code cannot drift apart silently.
    #[test]
    fn first_frame_budget_constants_match_the_spec_of_record() {
        let spec = spec_refresh_md();
        let (names_ms, cheap_columns_ms) = spec_first_frame_budgets_ms(&spec);
        assert_eq!(names_ms, FIRST_FRAME_NAMES_BUDGET_MS);
        assert_eq!(cheap_columns_ms, FIRST_FRAME_CHEAP_COLUMNS_BUDGET_MS);
    }

    /// Criterion 2: every entity a Generation is dispatched over gets its phase C read,
    /// never a subset. `refresh.md`'s "Scope and order" makes scope never a partial dial,
    /// so this proves it against a population wide enough that a mistaken "first K" or
    /// "last K" scoping mistake would leave a visible gap: sixteen real repos, dispatched in
    /// one Generation, every one of them still `dirty: Known` once settled, position sixteen
    /// exactly as covered as position one. A mutation that scoped phase C to, say, the first
    /// ten dispatched entities fails this directly.
    #[test]
    fn every_dispatched_entity_gets_its_dirty_cell_settled_not_a_subset() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        const ENTITY_COUNT: usize = 16;
        for index in 0..ENTITY_COUNT {
            init_repo_with_a_commit(&root.join(format!("repo-{index}")));
        }

        let core = Core::start_discovered(spec(vec![root]));
        let keys: Vec<EntityKey> = core
            .snapshot()
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();
        assert_eq!(keys.len(), ENTITY_COUNT, "expected every repo discovered");

        core.refresh(&keys);
        let settled = core.settle();

        for entity in &settled.entities {
            assert!(
                matches!(
                    entity.dirty.settled(),
                    Some(Settled::Known {
                        value: _,
                        at: _,
                        stale: _
                    })
                ),
                "entity {:?} was left without a settled dirty cell, which is exactly what a \
                 visibility-scoped dispatch would leave behind on the entities it skipped: \
                 got {:?}",
                entity.name,
                entity.dirty.settled()
            );
        }
    }

    /// refresh.md's "The first frame" budget (cheap columns filled within 200ms) is
    /// unreachable if the cheap outcomes wait behind phase C, so this proves the two
    /// applies are independent with a blocking seam rather than a sleep or a wall-clock
    /// deadline: `Core::hold_phase_c_for_test` holds phase C (and D) open after the cheap
    /// outcomes have already landed, and the test observes `branch` carrying this
    /// Generation's answer while `dirty` still carries the previous one. Run this against
    /// a version that bundles every outcome into one apply placed after phase C computes
    /// (this ticket's regression) and it fails, since nothing writes `branch` until that
    /// single bundled apply lands alongside `dirty`.
    ///
    /// Launch's own Generation is drained first and both cells are then moved, so each is
    /// read on the value it holds rather than on being blank: a table that has already
    /// been probed once is the only starting point available now that `Core::start` runs
    /// a Generation of its own, and reading values is the stronger claim anyway.
    #[test]
    fn cheap_outcomes_land_before_a_held_phase_c_settles() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let (core, launched) = started_and_settled(spec(vec![root]));
        let key = launched.entities[0].key.clone();
        assert_eq!(
            dirty_total(&launched.entities[0]),
            0,
            "the fixture starts clean, which is the value the held phase C must still be \
             reading once the working tree below has moved"
        );

        // One move per phase, so neither cell can be read on absence: `branch` is phase A
        // and must carry the new name while phase C is held, `dirty` is phase C and must
        // still carry launch's own clean count until it is released.
        git(&repo, &["checkout", "-b", "held"]);
        fs::write(repo.join("untracked.txt"), b"uncommitted")
            .expect("write an untracked file into the fixture");

        core.hold_phase_c_for_test(&key);
        core.refresh(std::slice::from_ref(&key));
        core.wait_phase_c_landed_for_test(&key);

        let mid_flight = core.snapshot();
        let entity = mid_flight
            .entities
            .iter()
            .find(|entity| entity.key == key)
            .expect("entity present");
        assert!(
            matches!(
                entity.branch.settled(),
                Some(Settled::Known {
                    value: Head::Branch { name, .. },
                    at: _,
                    stale: _
                }) if &**name == "held"
            ),
            "the cheap branch cell must carry this Generation's own answer while phase C is \
             still held open, got {:?}",
            entity.branch.settled()
        );
        assert!(
            entity.dirty.is_in_flight() && dirty_total(entity) == 0,
            "phase C is deliberately held open here; a bundled apply would already have \
             written this cell's new count alongside branch, got {:?}",
            entity.dirty.settled()
        );

        core.release_phase_c_for_test(&key);
        core.wait_phase_c_finished_for_test(&key);

        let settled = core.snapshot();
        let entity = settled
            .entities
            .iter()
            .find(|entity| entity.key == key)
            .expect("entity present");
        assert_eq!(
            dirty_total(entity),
            1,
            "phase C must settle its own count once released, got {:?}",
            entity.dirty.settled()
        );
    }

    /// One entity's settled dirty count, or a panic naming what it read instead. Lets a
    /// test that has to distinguish two Generations by value say "still zero" and "now
    /// one" without repeating the match on every read.
    fn dirty_total(entity: &EntityState) -> u32 {
        match entity.dirty.settled() {
            Some(Settled::Known {
                value,
                at: _,
                stale: _,
            }) => value.total(),
            other => panic!("expected a settled dirty count, got {other:?}"),
        }
    }

    /// Splitting one dispatched entity's write into a cheap apply and a phase C/D apply
    /// must still signal `settle_gate` exactly once per entity, or `settle` hangs (never
    /// decremented enough) or returns early (decremented twice). Two entities held open
    /// together prove the exact count at each step: a mutation that also decrements the
    /// gate from the cheap apply leaves it at 0 instead of 2 after both entities' cheap
    /// outcomes land, and a mutation that drops the decrement from the phase C/D apply
    /// leaves it at 2, never 1, once only the first entity finishes.
    #[test]
    fn splitting_the_probe_write_signals_settle_gate_exactly_once_per_entity() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("a"));
        init_repo_with_a_commit(&root.join("b"));

        let (core, snapshot) = started_and_settled(spec(vec![root]));
        let key_a = snapshot
            .entities
            .iter()
            .find(|entity| &*entity.name == "a")
            .expect("entity a present")
            .key
            .clone();
        let key_b = snapshot
            .entities
            .iter()
            .find(|entity| &*entity.name == "b")
            .expect("entity b present")
            .key
            .clone();

        core.hold_phase_c_for_test(&key_a);
        core.hold_phase_c_for_test(&key_b);
        core.refresh(&[key_a.clone(), key_b.clone()]);
        // A Generation reserves its number on this thread and raises the gate on one of
        // its own, so this is the rendezvous that says the raise has happened. A join,
        // never a sleep.
        core.wait_dispatched_for_test();
        assert_eq!(
            core.settle_gate_count_for_test(),
            2,
            "dispatching two entities must add exactly two to the settle gate"
        );

        core.wait_phase_c_landed_for_test(&key_a);
        core.wait_phase_c_landed_for_test(&key_b);
        assert_eq!(
            core.settle_gate_count_for_test(),
            2,
            "the cheap apply must never touch the settle gate: both entities' cheap \
             outcomes have landed and neither has finished phase C yet"
        );

        core.release_phase_c_for_test(&key_a);
        core.wait_phase_c_finished_for_test(&key_a);
        assert_eq!(
            core.settle_gate_count_for_test(),
            1,
            "exactly one entity finished, so the gate must fall by exactly one, not two \
             (double-counted) and not zero (left short)"
        );

        core.release_phase_c_for_test(&key_b);
        core.wait_phase_c_finished_for_test(&key_b);
        assert_eq!(
            core.settle_gate_count_for_test(),
            0,
            "both entities finished, so the gate must be fully drained"
        );
    }

    /// The gate [`Core::hold_phase_c_for_test`] last registered for `key`, so a test can
    /// still name one a later registration for the same entity has replaced in the map.
    fn registered_gate(core: &Core, key: &EntityKey) -> PhaseCGateHandle {
        core.phase_c_gates
            .lock()
            .unwrap()
            .get(key)
            .cloned()
            .expect("hold_phase_c_for_test must be called before reading its gate")
    }

    /// Opens `gate` directly rather than through [`Core::release_phase_c_for_test`], which
    /// resolves by key and so cannot name a gate a later registration has replaced.
    fn release_gate(gate: &PhaseCGateHandle) {
        let (lock, cvar) = &**gate;
        lock.lock().unwrap().may_proceed = true;
        cvar.notify_all();
    }

    fn gate_is_finished(gate: &PhaseCGateHandle) -> bool {
        gate.0.lock().unwrap().finished
    }

    /// A probe signals the phase C gate its own Generation was dispatched against, never
    /// whatever gate the map holds by the time that probe finishes.
    ///
    /// Reading the map twice per probe, once before phase C and once after, made the gate
    /// a probe signalled a function of when it got there: a probe from an already-settled
    /// Generation, past its own first read but not yet past its second, would find a gate
    /// registered in between and mark it finished, so the wait a later Generation was
    /// making returned before that Generation had applied anything or touched the settle
    /// gate. Registering a second gate for the same entity while the first is still held
    /// open is that interleaving with the timing taken out of it: the parked probe took
    /// the first gate, and the map holds the second by the time it finishes.
    #[test]
    fn a_probe_signals_the_phase_c_gate_its_own_generation_was_dispatched_against() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("repo"));

        let (core, launched) = started_and_settled(spec(vec![root]));
        let key = launched.entities[0].key.clone();

        core.hold_phase_c_for_test(&key);
        let dispatched_against = registered_gate(&core, &key);
        core.refresh(std::slice::from_ref(&key));
        core.wait_phase_c_landed_for_test(&key);

        core.hold_phase_c_for_test(&key);
        let registered_later = registered_gate(&core, &key);
        release_gate(&dispatched_against);

        wait_for(
            "the held probe to signal the gate its own Generation was dispatched against",
            || gate_is_finished(&dispatched_against),
        );
        assert!(
            !gate_is_finished(&registered_later),
            "a gate registered after this Generation dispatched must never be marked \
             finished by it: a test waiting on that gate would return before this \
             Generation had applied its outcome or decremented the settle gate"
        );
    }

    /// A probe finishing clears its own Generation's in-flight entry, never whatever the
    /// table holds under that key by the time it gets there.
    ///
    /// Cancellation is cooperative (refresh.md's "Cancellation"), so a superseded probe
    /// runs to completion and reaches `apply_probe_outcome` after the Generation that
    /// superseded it has already put its own entry under the same key. Clearing by key
    /// alone deleted that live entry, and refresh.md's "Supersession" then had nothing to
    /// set: the Generation after it found no previous entry, so the entity's interrupt
    /// flag stayed false and its probe ran on uncancelled, which is the 1.79x ADR 0013
    /// measured. Parking a probe at its phase C gate and superseding it while it is held
    /// is that interleaving with the timing taken out of it.
    #[test]
    fn a_probe_finishing_clears_only_its_own_generations_in_flight_entry() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("repo"));

        let (core, launched) = started_and_settled(spec(vec![root]));
        let key = launched.entities[0].key.clone();

        core.hold_phase_c_for_test(&key);
        core.refresh(std::slice::from_ref(&key));
        core.wait_phase_c_landed_for_test(&key);

        // The Generation that supersedes the parked probe, holding the interrupt flag the
        // `refresh` below has to be able to find and set.
        let superseding = core.begin_shared_generation_for_test(std::slice::from_ref(&key));

        core.release_phase_c_for_test(&key);
        core.wait_phase_c_finished_for_test(&key);

        core.refresh(std::slice::from_ref(&key));
        core.wait_dispatched_for_test();

        assert!(
            superseding.cancels[&key].load(Ordering::Acquire),
            "a probe from a Generation that has already been superseded must leave the \
             live Generation's in-flight entry alone, or the Generation after it has \
             nothing to interrupt"
        );
    }

    /// Criterion 5, the honest half: a concurrent pool's *completion* order is not
    /// dispatch order and asserting it would make this test flaky in exact proportion to
    /// how well rayon's scheduler works, so this asserts *dispatch* order instead, which is
    /// deterministic because `refresh`'s own dispatch loop is a single sequential pass over
    /// `order` that spawns work without ever waiting on it. `dispatch_order` itself, the
    /// function that actually builds the cursor-then-visible-then-rest sequence
    /// `refresh.md`'s "Scope and order" names, lives in the `repon` crate and is tested
    /// there: `core-api.md`'s ownership table gives that computation to the consumer, never
    /// to this crate. What this test proves on the core side is the half core-api.md commits
    /// to: `refresh` dispatches in exactly the order it is handed, position for position,
    /// never reordered by any heuristic of its own (never, per `refresh.md`, by predicted
    /// cost). A hand-built three-tier order stands in for what `dispatch_order` would
    /// produce, six entities discovered, one named cursor, two named visible, three left
    /// over in discovery order.
    #[test]
    fn refresh_dispatches_phase_c_in_exactly_the_order_it_is_given() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        const ENTITY_COUNT: usize = 6;
        for index in 0..ENTITY_COUNT {
            init_repo_with_a_commit(&root.join(format!("repo-{index}")));
        }

        let (core, launched) = started_and_settled(spec(vec![root]));
        let discovery_order: Vec<EntityKey> = launched
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();
        assert_eq!(
            discovery_order.len(),
            ENTITY_COUNT,
            "expected every repo discovered"
        );

        // The cursor row, then the visible rows (never the cursor's own row twice), then
        // everything else in discovery order: refresh.md's own three tiers, hand-assembled
        // the way `dispatch_order` would.
        let cursor = discovery_order[3].clone();
        let visible = [discovery_order[1].clone(), discovery_order[4].clone()];
        let mut three_tier_order = vec![cursor.clone()];
        three_tier_order.extend(visible.iter().cloned());
        for key in &discovery_order {
            if *key != cursor && !visible.contains(key) {
                three_tier_order.push(key.clone());
            }
        }
        assert_eq!(
            three_tier_order.len(),
            ENTITY_COUNT,
            "sanity check: the hand-built order must cover every discovered entity exactly \
             once"
        );

        core.refresh(&three_tier_order);
        core.settle();

        assert_eq!(
            core.dispatch_log_for_test(),
            three_tier_order,
            "refresh must dispatch phase C in exactly the order it was given: the cursor \
             row, then the visible rows, then the rest in discovery order"
        );
    }

    /// The defining behaviour for the shared-handle probe path: discovery leaves
    /// one thread-safe handle per entity, and a `refresh` reuses that same `Arc`
    /// rather than opening the repository again, proven by pointer identity
    /// surviving a probe rather than by inference from timing.
    #[test]
    fn refresh_reuses_the_cached_repository_handle_rather_than_reopening_it() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let before = core
            .cached_repo_handle_for_test(&key)
            .expect("discovery should have cached a handle");

        core.refresh(std::slice::from_ref(&key));
        core.settle();

        let after = core
            .cached_repo_handle_for_test(&key)
            .expect("the cached handle should still be there after a refresh");
        assert!(
            Arc::ptr_eq(&before, &after),
            "a refresh must reuse the cached handle, not replace it with a new one"
        );
    }

    /// `refresh_running` reads true from the instant `refresh` returns, before its spawned
    /// dispatch has raised a single probe: `refresh` reserves the Generation and records the
    /// dispatch debt on the calling thread, so a caller reading this the same frame it
    /// dispatched must never see a false "nothing outstanding". It reads false again once
    /// the Generation has fully landed.
    #[test]
    fn refresh_running_reads_true_the_instant_refresh_returns_and_false_once_it_settles() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("repo"));

        let core = Core::start_discovered(spec(vec![root]));
        core.settle();
        assert!(
            !core.refresh_running(),
            "sanity: nothing outstanding once startup has settled"
        );

        let keys: Vec<EntityKey> = core
            .snapshot()
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();
        core.refresh(&keys);
        assert!(
            core.refresh_running(),
            "refresh reserves its Generation and records the dispatch debt before it \
             returns, so this must already read true"
        );

        core.settle();
        assert!(
            !core.refresh_running(),
            "settle blocks until nothing is outstanding, so this must read false once it \
             returns"
        );
    }

    /// A key with no cached handle, either because it was never discovered or
    /// because discovery could not open it, still gets a real answer: the probe
    /// falls back to opening the repository itself rather than failing outright.
    #[test]
    fn probing_a_key_with_no_cached_handle_still_opens_the_repository_itself() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        // A core discovering an unrelated, empty root, so `repo` is never cached.
        let empty_root = root_of(&tempfile::tempdir().expect("temp dir"));
        let core = Core::start_discovered(spec(vec![empty_root]));
        let key = EntityKey::new(Arc::from(repo.as_path()));
        assert!(core.cached_repo_handle_for_test(&key).is_none());

        let entity = core.probe_now(&key);

        assert!(matches!(
            entity.branch.settled(),
            Some(Settled::Known {
                value: Head::Branch { .. },
                at: _,
                stale: _
            })
        ));
    }

    /// An empty order names no key, so the Generation it starts must reach no entity at
    /// all. Read off the dispatch log and the in-flight flag rather than off an unprobed
    /// cell, since launch's own Generation has already filled every cell by here.
    #[test]
    fn an_empty_order_dispatches_nothing_and_settle_returns_immediately() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let (core, _launched) = started_and_settled(spec(vec![root]));
        assert!(
            !core.dispatch_log_for_test().is_empty(),
            "launch dispatched nothing, so an empty log below would say nothing about the \
             empty order"
        );

        core.refresh(&[]);
        core.wait_dispatched_for_test();

        assert_eq!(
            core.dispatch_log_for_test(),
            Vec::new(),
            "an empty order must dispatch no probe"
        );
        // The number is the claim here, not a backstop: an order naming nobody raises no
        // probe, so the gate is already at zero and this must come back settled at once
        // rather than eventually.
        let settled = core
            .try_settle(Duration::from_millis(50))
            .expect("an empty order raises no probe, so the settle gate is already at zero");
        assert!(!settled.entities[0].branch.is_in_flight());
    }

    /// One entity left owing a probe that nothing will ever complete: no tick is sent, so
    /// the deadline sweep that would otherwise time the cell out never runs, and the settle
    /// gate stays above zero for as long as anyone waits on it.
    ///
    /// Returns the live `Core` and the tick sender, which the caller must hold: dropping it
    /// stops the dedicated thread's own select arm, and a `Core` whose thread has gone is a
    /// different fixture from the one these waits mean to test.
    fn one_probe_owed_that_never_lands(
        dir: &tempfile::TempDir,
    ) -> (Core, crossbeam_channel::Sender<Instant>) {
        let root = root_of(dir);
        init_repo_with_a_commit(&root.join("repo"));
        let (tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();
        let core = Core::start_for_test(spec(vec![root]), Duration::from_secs(3600), tick_rx)
            .discovered()
            .core;
        let key = settle_launch(&core).entities[0].key.clone();
        core.begin_untracked_probe_for_test(&key);
        (core, tick_tx)
    }

    /// The defect this pair exists for: a settle that gives up used to be indistinguishable
    /// from one that succeeded, so the table it handed back was read as an answer and the
    /// run failed several steps downstream with nothing left naming the wait.
    ///
    /// [`Core::settle`]'s half is to report at the wait, the way `liveness::wait_for` does.
    /// Driven through `settle_within` rather than `settle` so the expiry path is exercised
    /// without waiting out a real backstop.
    #[test]
    #[should_panic(expected = "waiting for everything this Core has in flight to land")]
    fn a_settle_that_expires_reports_at_the_wait_rather_than_returning_the_table() {
        let dir = tempfile::tempdir().expect("temp dir");
        let (core, _tick_tx) = one_probe_owed_that_never_lands(&dir);

        core.settle_within(Duration::from_millis(20));
    }

    /// [`Core::try_settle`]'s half of the same claim, for the callers that mean to degrade
    /// rather than fail: the expiry comes back as `Err`, so the unsettled table can only be
    /// reached by a caller that has already acknowledged the wait gave up.
    #[test]
    fn try_settle_hands_an_expiry_back_as_an_error_carrying_the_table_it_gave_up_on() {
        let dir = tempfile::tempdir().expect("temp dir");
        let (core, _tick_tx) = one_probe_owed_that_never_lands(&dir);

        let unsettled = core
            .try_settle(Duration::from_millis(20))
            .expect_err("a probe nothing will ever complete cannot settle");

        assert!(
            unsettled.entities[0].branch.is_in_flight(),
            "the Err arm must still carry the table as it stood, so a caller that degrades \
             deliberately has something to degrade with"
        );
    }

    /// The other arm, so the two are told apart by what actually happened rather than by
    /// `Err` being the only reachable answer.
    #[test]
    fn try_settle_hands_a_generation_that_really_landed_back_as_ok() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("repo"));

        let (core, launched) = started_and_settled(spec(vec![root]));
        let key = launched.entities[0].key.clone();
        core.refresh(std::slice::from_ref(&key));

        let settled = core
            .try_settle(BACKSTOP)
            .expect("a dispatched Generation must land inside the backstop");

        assert!(!settled.entities[0].branch.is_in_flight());
    }

    /// A Launcher return re-probes one entity through `probe_now`, so every cell a
    /// Generation settles must settle here too. `sync` is the one most recently added and
    /// the one a merge is most likely to drop, since no other test reads it off this path.
    #[test]
    fn probe_now_settles_the_sync_cell_as_well_as_the_branch_it_depends_on() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        let entity = core.probe_now(&key);

        assert!(
            matches!(
                entity.sync.settled(),
                Some(Settled::Known {
                    value: SyncState::NoRemote,
                    at: _,
                    stale: _
                })
            ),
            "expected probe_now to settle sync, got {:?}",
            entity.sync.settled()
        );
    }

    /// The same guard as the `sync` one above, for `base`: `probe_now` must settle it
    /// too, not only the dispatch loop `refresh` drives.
    #[test]
    fn probe_now_settles_the_base_cell_as_well_as_the_branch_it_depends_on() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        let entity = core.probe_now(&key);

        assert!(
            matches!(entity.base.settled(), Some(Settled::NotApplicable)),
            "expected probe_now to settle base Not applicable for a Repo with no remote, \
             got {:?}",
            entity.base.settled()
        );
    }

    /// The end-to-end wiring `probe_now`'s own guard above cannot prove: a real
    /// `refresh` dispatch, through `CheapProbeOutcomes`, must land a genuine
    /// computed `base` count on the table, not just a Not-applicable fallback.
    #[test]
    fn refresh_settles_a_real_base_count_against_the_resolved_default_branch() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        git(
            &repo,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let root_sha = head_sha(&repo);
        // The default branch (`origin/main`, resolved through rung 3's name list
        // since no `origin/HEAD` exists) moves one commit ahead of this Repo's own
        // checked-out branch, which never gets its own upstream configured, so
        // `sync` reads `-` while `base` still has a resolved default branch to
        // count behind.
        git(&repo, &["commit", "--allow-empty", "-m", "second"]);
        let tip_sha = head_sha(&repo);
        git(&repo, &["reset", "--hard", &root_sha]);
        git(&repo, &["update-ref", "refs/remotes/origin/main", &tip_sha]);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        core.refresh(std::slice::from_ref(&key));
        let settled = core.settle();

        assert!(
            matches!(
                settled.entities[0].base.settled(),
                Some(Settled::Known {
                    value: 1,
                    at: _,
                    stale: _
                })
            ),
            "expected a real refresh to settle base's live count against the resolved \
             default branch, got {:?}",
            settled.entities[0].base.settled()
        );
    }

    /// The same guard as the `sync` one above, for `dirty`: it is the cell most recently
    /// added to this path, and dropping its settle here leaves every other test green.
    /// The repo carries one untracked file so a settled cell has to hold the counted
    /// value, not a zeroed placeholder that a default-constructed `DirtyCounts` would
    /// also satisfy.
    #[test]
    fn probe_now_settles_the_dirty_cell_with_the_counts_it_probed() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        fs::write(repo.join("untracked.txt"), "x").expect("write untracked file");

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        let entity = core.probe_now(&key);

        assert!(
            matches!(
                entity.dirty.settled(),
                Some(Settled::Known {
                    value: DirtyCounts {
                        modified: 0,
                        untracked: 1,
                        deleted: 0,
                    },
                    at: _,
                    stale: _
                })
            ),
            "expected probe_now to settle dirty with the one untracked path, got {:?}",
            entity.dirty.settled()
        );
    }

    #[test]
    fn probe_now_updates_the_entity_synchronously_with_no_refresh_call() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        let entity = core.probe_now(&key);

        assert!(matches!(
            entity.branch.settled(),
            Some(Settled::Known {
                value: Head::Branch { .. },
                at: _,
                stale: _
            })
        ));
    }

    /// The one-function guarantee: whether an entity's name is set by discovery at
    /// `Core::start` or by `probe_now`'s fallback insert for a key the table did
    /// not already know, both routes must produce the same string for the same
    /// path, since a future state file keys the Selection by this name and a
    /// second formatting of it would silently break restoring by name.
    #[test]
    fn the_display_name_agrees_between_discovery_and_probe_nows_fallback_insert() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("named-repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let discovered = core.snapshot().entities[0].clone();
        assert_eq!(&*discovered.name, "named-repo");

        core.dismiss(&discovered.key);
        assert!(core.snapshot().entities.is_empty());

        let reinserted = core.probe_now(&discovered.key);

        assert_eq!(
            reinserted.name, discovered.name,
            "the name discovery assigned and the name probe_now's fallback insert \
             assigns for the same path must be byte-identical"
        );
    }

    #[test]
    fn dismiss_removes_the_entity_from_the_snapshot() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        core.dismiss(&key);

        assert!(core.snapshot().entities.is_empty());
    }

    /// Foundation for every criterion below: one entity's own steps run in order and a
    /// failure marks every later step `NotRun` rather than silently skipping it or
    /// running it anyway, exactly the closed set of four outcomes
    /// [config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
    /// "Actions" and `docs/spec/actions.md`'s "Step outcomes" both fix.
    ///
    /// The third step would succeed if it ran (`true` always exits zero), so its being
    /// stopped is what this test observes, not an accident of a step that would have
    /// failed anyway. It also writes a marker file rather than only exiting zero: a
    /// receipt correctly labelled `NotRun` is not, by itself, proof the step never ran
    /// (an implementation could execute a step and then paper over its result), so the
    /// missing file is evidence the receipt cannot fake.
    #[test]
    fn an_entitys_steps_run_in_order_and_a_failure_marks_every_later_step_not_run() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let marker = repo.join("step-three-ran");

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let steps = vec![
            step(&["true"]),
            step(&["sh", "-c", "exit 7"]),
            step(&["touch", "step-three-ran"]),
        ];

        let started = core.run_action(action("reinstall", steps), std::slice::from_ref(&key));

        assert!(started);
        wait_for("the fan-out to finish and write a receipt", || {
            !core.action_running()
        });
        let receipt = core.snapshot().entities[0]
            .last_action
            .clone()
            .expect("receipt written");
        assert_eq!(receipt.steps.len(), 3);
        assert_eq!(receipt.steps[0].outcome, StepOutcome::Ok);
        assert_eq!(receipt.steps[1].outcome, StepOutcome::Failed(7));
        assert_eq!(
            receipt.steps[2].outcome,
            StepOutcome::NotRun,
            "a step after a failure must be recorded NotRun, not silently dropped or run anyway"
        );
        assert!(
            !marker.exists(),
            "the third step's own `touch` must never have run: its marker file exists, so \
             the step ran despite being recorded NotRun"
        );
    }

    /// Independent of stopping at a failure: three always-succeeding steps each append
    /// their own digit to the same file, so the file's final content pins the actual
    /// execution order rather than trusting that a linear scan of `action.steps` runs
    /// them in the sequence they were declared in.
    #[test]
    fn steps_run_in_the_order_theyre_declared_not_some_other_order() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let order_log = repo.join("order.log");

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let steps = vec![
            step(&["sh", "-c", "printf 1 >> order.log"]),
            step(&["sh", "-c", "printf 2 >> order.log"]),
            step(&["sh", "-c", "printf 3 >> order.log"]),
        ];

        let started = core.run_action(action("ordering", steps), std::slice::from_ref(&key));

        assert!(started);
        wait_for("the fan-out to finish and write a receipt", || {
            !core.action_running()
        });
        let receipt = core.snapshot().entities[0]
            .last_action
            .clone()
            .expect("receipt written");
        assert_eq!(receipt.steps.len(), 3);
        assert!(
            receipt
                .steps
                .iter()
                .all(|result| result.outcome == StepOutcome::Ok),
            "every step here always exits zero; this test isolates ordering from gating"
        );
        let content = fs::read_to_string(&order_log).expect("order.log written by the steps");
        assert_eq!(
            content, "123",
            "the file's content pins actual execution order; running the steps out of \
             declaration order would produce a different digit sequence here even though \
             every step still succeeds"
        );
    }

    /// `docs/spec/actions.md`'s "The run on screen": a reader must see a step's own
    /// finished output "as it arrives", not only once the whole entity's run has ended.
    /// The second step sleeps long enough to give a poll a real window to observe the
    /// receipt mid-run; a version of `run_action_for_entity` that only wrote once, at the
    /// end, would never let this test observe `running: Some(_)` at all; it would either
    /// see no receipt (before) or the whole finished one (after), never the state in
    /// between where the first step is done and the second is still going.
    #[test]
    fn a_still_running_actions_finished_step_and_its_currently_executing_one_are_both_visible_before_the_whole_run_ends()
     {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let steps = vec![step(&["true"]), step(&["sh", "-c", "sleep 0.5"])];

        let started = core.run_action(action("reinstall", steps), std::slice::from_ref(&key));
        assert!(started);

        // Waits specifically for the *second* step's own running receipt, not merely any
        // one: under a slow or busy machine the first step (`true`) can still be the one
        // reported running the first time this poll checks, which would assert the wrong
        // step's own shape below rather than a flaky pass.
        wait_for(
            "a receipt naming the second step running before the run finished",
            || {
                core.snapshot().entities[0]
                    .last_action
                    .as_ref()
                    .and_then(|receipt| receipt.running.as_ref())
                    .is_some_and(|running| running.label.contains("sleep"))
            },
        );
        let mid_run = core.snapshot().entities[0]
            .last_action
            .clone()
            .expect("receipt written");
        assert_eq!(
            mid_run.steps.len(),
            1,
            "the first, already-finished step must already be in `steps`"
        );
        assert_eq!(mid_run.steps[0].outcome, StepOutcome::Ok);
        let running = mid_run.running.expect("a step must be recorded running");
        assert!(
            running.label.contains("sleep"),
            "expected the running step's own label, got {:?}",
            running.label
        );

        wait_for("the fan-out to finish", || !core.action_running());
        let finished = core.snapshot().entities[0]
            .last_action
            .clone()
            .expect("receipt written");
        assert!(
            finished.running.is_none(),
            "a finished receipt must carry no running step"
        );
        assert_eq!(finished.steps.len(), 2);
    }

    /// `Step::shell` must actually reach the child, end to end through `run_action`,
    /// not merely be a field that parses. Prints `$0` inside the step's own
    /// command string: `sh -c <string>` with no third argument would leave `$0` reading
    /// whatever the shell defaults it to, never the literal `repon`
    /// [config.md](https://github.com/paulchiu/repon/blob/main/docs/spec/config.md)'s
    /// `shell = true` sentence requires. `executor.rs`'s own unit tests cover `run_step`
    /// directly; this proves `core.rs` actually sets `shell` on the `Step` it builds and
    /// passes it through.
    #[test]
    fn a_shell_true_step_runs_through_shell_c_with_repon_as_its_own_dollar_zero() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let steps = vec![shell_step("echo \"[$0]\"")];

        let started = core.run_action(action("shell-step", steps), std::slice::from_ref(&key));

        assert!(started);
        wait_for("the fan-out to finish and write a receipt", || {
            !core.action_running()
        });
        let receipt = core.snapshot().entities[0]
            .last_action
            .clone()
            .expect("receipt written");
        assert_eq!(receipt.steps.len(), 1);
        assert_eq!(receipt.steps[0].outcome, StepOutcome::Ok);
        assert_eq!(&*receipt.steps[0].output, b"[repon]\n");
        assert!(
            receipt.steps[0].shell,
            "the receipt's own StepResult::shell must carry the mode the step ran under"
        );
    }

    /// `Step::interactive` must actually reach `run_step` end to end through `run_action`,
    /// the same proof `a_shell_true_step_runs_through_shell_c_with_repon_as_its_own_dollar_zero`
    /// already gives `shell`: this asserts `core.rs` sets `interactive` on the `Step` it
    /// builds and that the receipt carries it back, not the shell's own rc-sourcing
    /// behaviour, which `executor.rs`'s own `shell_argv` unit test already covers on the
    /// constructed argv.
    #[test]
    fn an_interactive_shell_true_step_runs_through_run_action_with_interactive_on_its_receipt() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let steps = vec![interactive_shell_step("true")];

        let started = core.run_action(
            action("interactive-step", steps),
            std::slice::from_ref(&key),
        );

        assert!(started);
        wait_for("the fan-out to finish and write a receipt", || {
            !core.action_running()
        });
        let receipt = core.snapshot().entities[0]
            .last_action
            .clone()
            .expect("receipt written");
        assert_eq!(receipt.steps.len(), 1);
        assert_eq!(receipt.steps[0].outcome, StepOutcome::Ok);
        assert!(
            receipt.steps[0].shell,
            "an interactive step is still a shell step"
        );
        assert!(
            receipt.steps[0].interactive,
            "the receipt's own StepResult::interactive must carry the mode the step ran under"
        );
    }

    /// [`StepResult::shell`]'s own claim on the plain argv side, so the two modes are
    /// proven end to end through `run_action` rather than only `shell = true`: an ordinary
    /// step's receipt must read `false`, not merely default to it by construction.
    #[test]
    fn an_argv_step_runs_through_run_action_with_shell_false_on_its_receipt() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let steps = vec![Step {
            argv: vec!["true".to_string()],
            shell: false,
            interactive: false,
            env: Vec::new(),
        }];

        let started = core.run_action(action("argv-step", steps), std::slice::from_ref(&key));

        assert!(started);
        wait_for("the fan-out to finish and write a receipt", || {
            !core.action_running()
        });
        let receipt = core.snapshot().entities[0]
            .last_action
            .clone()
            .expect("receipt written");
        assert!(!receipt.steps[0].shell);
    }

    /// Criterion 3's first half. `begin_shared_generation_for_test` puts the entity
    /// in flight against a Generation of its own, exactly as a real `refresh` would;
    /// this proves `run_action` cancels that Generation's own flag rather than merely
    /// starting alongside it, which is the difference between the 0.85s and 3.14s
    /// measurements `docs/spec/actions.md`'s "Refreshing around a run" reports.
    #[test]
    fn starting_an_action_cancels_any_generation_already_in_flight() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let in_flight = core.begin_shared_generation_for_test(std::slice::from_ref(&key));
        let cancel = in_flight
            .cancels
            .get(&key)
            .expect("the in-flight entity has a cancel flag")
            .clone();
        assert!(!cancel.load(Ordering::Acquire));

        let started = core.run_action(
            action("reinstall", vec![step(&["true"])]),
            std::slice::from_ref(&key),
        );

        assert!(started);
        assert!(
            cancel.load(Ordering::Acquire),
            "starting an Action must cancel a Generation already in flight, not share \
             execution with it"
        );
        // Drain the fan-out and its completion refresh so this test's background
        // thread does not outlive it.
        wait_for("the fan-out and its completion refresh to drain", || {
            !core.action_running()
        });
    }

    /// Criterion 3's second half, and the double-refresh mutation this test is written
    /// to catch: a completed Action starting its own Generation *and* a second one
    /// left over from a naive implementation that also called `refresh` directly would
    /// both leave every entity settled, so counting settled entities alone cannot tell
    /// zero, one and two apart. Reading the table's own `generation` number after
    /// completion can: it must be the Generation immediately after the settled table
    /// this Action ran against, covering both entities although the Action only ever
    /// named one of them. Named by its order rather than by a number, so what launch
    /// itself mints cannot renumber the claim.
    #[test]
    fn a_finished_action_starts_exactly_one_generation_over_every_known_entity() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let acted_on = root.join("acted-on");
        let untouched = root.join("untouched");
        init_repo_with_a_commit(&acted_on);
        init_repo_with_a_commit(&untouched);

        let (core, before) = started_and_settled(spec(vec![root]));
        let acted_key = before
            .entities
            .iter()
            .find(|entity| entity.key.path() == acted_on)
            .expect("the acted-on entity is discovered")
            .key
            .clone();

        let started = core.run_action(
            action("reinstall", vec![step(&["true"])]),
            std::slice::from_ref(&acted_key),
        );

        assert!(started);
        wait_for(
            "the completion Generation to probe every known entity, including the one the \
             Action never touched",
            || {
                let snapshot = core.snapshot();
                snapshot.generation != before.generation
                    && snapshot.entities.iter().all(|entity| {
                        matches!(
                            entity.branch.settled(),
                            Some(Settled::Known {
                                value: _,
                                at: _,
                                stale: _
                            })
                        )
                    })
            },
        );
        assert_eq!(
            core.settle().generation,
            before.generation.successor(),
            "completion must start exactly one Generation: not zero (no refresh at all) and \
             not two (a double refresh)"
        );
    }

    /// Criterion 5. The excluded row gets the one legitimate `not_applicable` receipt
    /// with no steps; the acted-on row's own step is made to fail, which is the strong
    /// half of the claim: a receipt with steps that failed is still not the
    /// `not_applicable` shape, so nothing but an excluded row can ever produce it.
    #[test]
    fn an_excluded_row_swept_into_an_action_gets_a_not_applicable_receipt_and_no_other_path_does() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let excluded_repo = root.join("excluded");
        let normal_repo = root.join("normal");
        init_repo_with_a_commit(&excluded_repo);
        init_repo_with_a_commit(&normal_repo);

        let core = Core::start_discovered(spec_with_overrides(
            vec![root],
            vec![RepoOverride {
                path: excluded_repo.clone(),
                default_branch: None,
                excluded: true,
            }],
        ));
        let snapshot = core.snapshot();
        let find = |path: &Path| {
            snapshot
                .entities
                .iter()
                .find(|entity| entity.key.path() == path)
                .unwrap_or_else(|| panic!("entity at {path:?} present"))
                .key
                .clone()
        };
        let excluded_key = find(&excluded_repo);
        let normal_key = find(&normal_repo);
        assert!(
            snapshot
                .entities
                .iter()
                .find(|entity| entity.key == excluded_key)
                .unwrap()
                .excluded
        );

        let started = core.run_action(
            action("reinstall", vec![step(&["sh", "-c", "exit 3"])]),
            &[excluded_key.clone(), normal_key.clone()],
        );

        assert!(started);
        // `!core.action_running()`, not merely "both entities have some receipt": a
        // still-running entity now writes an intermediate receipt naming its currently
        // executing step before it finishes (`docs/spec/actions.md`'s "The run on screen"),
        // so `last_action.is_some()` alone can be true well before `normal_key`'s own step
        // has actually run.
        wait_for("the fan-out to finish", || !core.action_running());

        let after = core.snapshot();
        let receipt_of = |key: &EntityKey| {
            after
                .entities
                .iter()
                .find(|entity| entity.key == *key)
                .unwrap()
                .last_action
                .clone()
                .unwrap()
        };
        let excluded_receipt = receipt_of(&excluded_key);
        assert!(excluded_receipt.not_applicable());
        assert!(excluded_receipt.steps.is_empty());

        let normal_receipt = receipt_of(&normal_key);
        assert!(
            !normal_receipt.not_applicable(),
            "a row that actually ran a step, even a failing one, must never read as \
             not_applicable: an excluded row is the one legitimate producer of that outcome"
        );
        assert!(!normal_receipt.steps.is_empty());
        assert!(normal_receipt.failed());
    }

    /// Criterion 4: `operable_count` and `run_action`'s own partition must be one
    /// computation, not two that happen to agree today. Proven against independent
    /// evidence, the same way the test above does: run an Action over one excluded and
    /// one normal entity, then check `operable_count`'s answer against how many of the
    /// two actually got a real (not `not_applicable`) receipt, rather than against a
    /// second hand-written copy of the exclusion rule.
    #[test]
    fn operable_count_matches_how_many_entities_run_action_actually_runs_a_step_against() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let excluded_repo = root.join("excluded");
        let normal_repo = root.join("normal");
        init_repo_with_a_commit(&excluded_repo);
        init_repo_with_a_commit(&normal_repo);

        let core = Core::start_discovered(spec_with_overrides(
            vec![root],
            vec![RepoOverride {
                path: excluded_repo.clone(),
                default_branch: None,
                excluded: true,
            }],
        ));
        let snapshot = core.snapshot();
        let find = |path: &Path| {
            snapshot
                .entities
                .iter()
                .find(|entity| entity.key.path() == path)
                .unwrap_or_else(|| panic!("entity at {path:?} present"))
                .key
                .clone()
        };
        let order = [find(&excluded_repo), find(&normal_repo)];

        assert_eq!(
            core.operable_count(&order),
            1,
            "one of the two rows is excluded, so exactly one is operable"
        );

        let started = core.run_action(action("reinstall", vec![step(&["true"])]), &order);
        assert!(started);

        wait_for("every entity in the order to carry a receipt", || {
            let snapshot = core.snapshot();
            order.iter().all(|key| {
                snapshot
                    .entities
                    .iter()
                    .find(|entity| entity.key == *key)
                    .and_then(|entity| entity.last_action.as_ref())
                    .is_some()
            })
        });

        let after = core.snapshot();
        let actually_ran = after
            .entities
            .iter()
            .filter(|entity| order.contains(&entity.key))
            .filter(|entity| {
                entity
                    .last_action
                    .as_ref()
                    .is_some_and(|receipt| !receipt.not_applicable())
            })
            .count();

        assert_eq!(
            core.operable_count(&order),
            actually_ran,
            "operable_count must report exactly how many rows run_action actually ran a \
             step against, not merely how many keys resolved"
        );
    }

    /// [`Core::run_action_for_entity_blocking`]'s own reason to exist: it returns the
    /// finished receipt on the calling thread rather than handing the run off, so a caller
    /// needs no `wait_for` at all to see the step's own effect, unlike every `run_action`
    /// test above.
    #[test]
    fn run_action_for_entity_blocking_returns_the_finished_receipt_on_the_calling_thread() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let marker = repo.join("hook-ran");

        let core = Core::start_discovered(spec_with_overrides(vec![root], Vec::new()));
        let key = core
            .snapshot()
            .entities
            .iter()
            .find(|entity| entity.key.path() == repo)
            .expect("the repo is discovered")
            .key
            .clone();

        let receipt = core
            .run_action_for_entity_blocking(
                &action("hook", vec![step(&["touch", "hook-ran"])]),
                &key,
            )
            .expect("the entity is known");

        assert!(
            marker.exists(),
            "the step must have already run by the time this call returns"
        );
        assert_eq!(receipt.steps.len(), 1);
        assert_eq!(receipt.steps[0].outcome, StepOutcome::Ok);
    }

    /// `None` rather than a receipt for a key the table does not know: the same fallback
    /// every other key-addressed `Core` entry point gives one, and the caller's own signal
    /// for "no hook to consult" when a hook names a row `sync`'s own eligibility has already
    /// dropped.
    #[test]
    fn run_action_for_entity_blocking_answers_none_for_an_unknown_key() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let core = Core::start_discovered(spec_with_overrides(vec![root.clone()], Vec::new()));

        let unknown = EntityKey::new(Arc::from(root.join("never-discovered").as_path()));

        assert!(
            core.run_action_for_entity_blocking(&action("hook", vec![step(&["true"])]), &unknown)
                .is_none()
        );
    }

    /// The reversed decision itself: `when` now decides what runs, not only what a palette
    /// reports about it. A row the predicate proves runs a real step; a row it disproves
    /// gets a `Skip::Inapplicable` receipt with no steps and never spawns a child process at
    /// all, which the failing command below would have surfaced as a `Failed` step had it
    /// run (`docs/spec/actions.md`'s "The Selection and the gate", reversing what that
    /// section originally decided).
    #[test]
    fn run_action_skips_a_row_its_when_predicate_disproves_rather_than_running_it_anyway() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let proved_repo = root.join("alpha");
        let disproved_repo = root.join("beta");
        init_repo_with_a_commit(&proved_repo);
        init_repo_with_a_commit(&disproved_repo);

        let core = Core::start_discovered(spec(vec![root]));
        let snapshot = core.snapshot();
        let find = |path: &Path| {
            snapshot
                .entities
                .iter()
                .find(|entity| entity.key.path() == path)
                .unwrap_or_else(|| panic!("entity at {path:?} present"))
                .key
                .clone()
        };
        let proved_key = find(&proved_repo);
        let disproved_key = find(&disproved_repo);
        let order = [proved_key.clone(), disproved_key.clone()];

        // A command that would mark a real run `Failed` if it ever ran, so a disproved row
        // that wrongly ran a step is caught by its own outcome rather than only by `skip`.
        let started = core.run_action(
            action_with_when(
                "reinstall",
                vec![step(&["sh", "-c", "exit 3"])],
                "name:alpha",
            ),
            &order,
        );
        assert!(started);
        wait_for("the fan-out to finish", || !core.action_running());

        let after = core.snapshot();
        let receipt_of = |key: &EntityKey| {
            after
                .entities
                .iter()
                .find(|entity| entity.key == *key)
                .unwrap()
                .last_action
                .clone()
                .unwrap()
        };

        let proved_receipt = receipt_of(&proved_key);
        assert_eq!(
            proved_receipt.skip, None,
            "the row the predicate proved must actually run"
        );
        assert!(proved_receipt.failed(), "its own step still ran and failed");

        let disproved_receipt = receipt_of(&disproved_key);
        assert!(
            disproved_receipt.inapplicable(),
            "the row the predicate disproved must be skipped rather than run"
        );
        assert!(disproved_receipt.steps.is_empty());
        assert!(
            !disproved_receipt.failed(),
            "a skipped row never ran a step, so it cannot have failed one"
        );
    }

    /// An excluded row is subtracted before an Action's `when` ever sees it, so the
    /// predicate narrows what is left rather than replacing that subtraction
    /// (`docs/spec/actions.md`'s "The Selection and the gate").
    ///
    /// Proven against `operable_count` itself rather than against a hand-written expectation:
    /// a predicate every remaining row satisfies must leave a total identical to that count,
    /// which it cannot do if the excluded row reached the tally under any of the three
    /// headings.
    #[test]
    fn applicability_subtracts_an_excluded_row_before_the_predicate_reads_it() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let excluded_repo = root.join("excluded");
        let normal_repo = root.join("normal");
        init_repo_with_a_commit(&excluded_repo);
        init_repo_with_a_commit(&normal_repo);

        let core = Core::start_discovered(spec_with_overrides(
            vec![root],
            vec![RepoOverride {
                path: excluded_repo.clone(),
                default_branch: None,
                excluded: true,
            }],
        ));
        let order: Vec<EntityKey> = core
            .snapshot()
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();
        assert_eq!(order.len(), 2, "the fixture must discover both repos");

        let counts = core.applicability(&order, &Filter::parse("kind:repo"));

        assert_eq!(
            counts.total(),
            core.operable_count(&order),
            "the predicate must be counted over exactly the rows `operable_count` keeps"
        );
        assert_eq!(
            counts,
            Applicability {
                applicable: 1,
                inapplicable: 0,
                unresolved: 0,
            }
        );
    }

    /// An unknown key (already dismissed, or never discovered) is silently dropped from
    /// the count, the same fallback `run_action` gives one: this is the half of
    /// `partition_operable` no fixture above exercises, since every key there resolves.
    #[test]
    fn operable_count_silently_drops_a_key_that_no_longer_resolves() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let real_key = core.snapshot().entities[0].key.clone();
        let unknown_key = EntityKey::new(Arc::from(dir.path().join("never-discovered")));

        assert_eq!(core.operable_count(&[real_key, unknown_key]), 1);
    }

    /// Criterion 6. The second call is rejected synchronously (`action_running`'s
    /// `compare_exchange` fails before anything else runs), so this needs no waiting to
    /// observe; only the cleanup wait at the end needs [`wait_for`].
    #[test]
    fn only_one_action_fan_out_runs_at_a_time_a_second_call_is_rejected_while_one_is_live() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let slow = action("first", vec![step(&["sh", "-c", "sleep 0.3"])]);
        let fast = action("second", vec![step(&["true"])]);

        let first_started = core.run_action(slow, std::slice::from_ref(&key));
        let second_started = core.run_action(fast, std::slice::from_ref(&key));

        assert!(first_started);
        assert!(
            !second_started,
            "a second run_action call must be rejected while the first is still in flight"
        );
        wait_for("the accepted first fan-out to finish", || {
            !core.action_running()
        });
        let receipt = core.snapshot().entities[0].last_action.clone().unwrap();
        assert_eq!(
            &*receipt.label, "first",
            "the surviving receipt must be the accepted first run's, never the rejected second"
        );
    }

    // =====================================================================================
    // Criteria 3 and 4: `Core::hold_action`/`Core::continue_action` are their own verbs on
    // the core, kept apart from the generic `pause`/`resume` the probes use, and suspending
    // a fan-out is reversible: a held step's own progress genuinely pauses, and resumes
    // exactly where it left off, rather than the run merely finishing on its own regardless.
    // =====================================================================================

    /// A black-box proof through the public API alone, with no reach into the step's own
    /// pid: a one-second step, held for 1.5s (comfortably longer than the step would ever
    /// take unheld) and then continued. If `hold_action` were a no-op, the step would
    /// already have finished on its own well before this test ever calls
    /// `continue_action`, and `action_running` would already read `false` at the
    /// mid-hold checkpoint below; that is the exact mutation this test is written to catch.
    #[test]
    fn hold_action_genuinely_pauses_a_running_steps_progress_and_continue_action_resumes_it() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let two_seconds = action("brief", vec![step(&["sh", "-c", "sleep 2"])]);

        assert!(core.run_action(two_seconds, std::slice::from_ref(&key)));
        wait_for("the two-second step to actually start running", || {
            core.snapshot().entities[0]
                .last_action
                .as_ref()
                .is_some_and(|receipt| receipt.running.is_some())
        });

        // The receipt's own `running: Some(_)` is written just before `run_step` is even
        // called, so it can race that call's own spawn, which is when the step's process
        // group is actually registered. SIGSTOP is idempotent, so pulsing `hold_action`
        // over a short bounded window (well inside the step's own 2s) is what makes that
        // race resolve deterministically rather than flakily, without ever risking a hang:
        // a stuck `hold_action` here fails this loop's own fixed iteration count, not this
        // test's wall clock.
        for _ in 0..20 {
            core.hold_action();
            thread::sleep(Duration::from_millis(20));
        }

        thread::sleep(Duration::from_millis(1_800));
        assert!(
            core.action_running(),
            "a genuinely held step must not have finished on its own well past its own 2s \
             sleep; a no-op hold_action would already show this false here"
        );

        core.continue_action();
        wait_for("continue_action to let the held step finish", || {
            !core.action_running()
        });
        let receipt = core.snapshot().entities[0].last_action.clone().unwrap();
        assert_eq!(receipt.steps[0].outcome, StepOutcome::Ok);
    }

    /// `hold_action`, `continue_action` and `stop_action` must all be safe to call with no
    /// fan-out live: nothing to signal, so each is a plain no-op rather than a panic or a
    /// stray signal to nothing.
    #[test]
    fn hold_continue_and_stop_action_are_no_ops_with_no_fan_out_running() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));

        core.hold_action();
        core.continue_action();
        core.stop_action();

        assert!(!core.action_running());
    }

    // =====================================================================================
    // Criterion 1: Escape (`Core::stop_action`) cancels the fan-out with two signals, the
    // terminating one and then the uncatchable one after a grace, because the first is
    // trappable. Exercised through the real public seam, never by calling `RunControl`
    // directly, so this is `stop_action` end to end rather than only its own primitive.
    // =====================================================================================

    /// A child that traps and ignores SIGTERM is the only fixture that actually
    /// discriminates the two-signal design from a one-signal one: a child that dies on
    /// SIGTERM alone would pass this test even if `stop_action` were mutated to drop its
    /// own SIGKILL follow-up entirely, which is exactly the regression this criterion
    /// exists to catch.
    ///
    /// The step sleeps [`FIXTURE_LIFETIME`], ten times the backstop every wait below
    /// carries, so a `stop_action` that stops working reads back as a named wait giving up
    /// rather than as the step ending on its own inside the wait watching it. That margin is
    /// the whole discrimination here, because the outcome assertion cannot supply it:
    /// `run_action_for_entity` stamps `Cancelled` on whatever was running the moment the run
    /// was cancelled, however the step actually ended. A run that does fail here leaves the
    /// trapping child alive until its own sleep ends, which is the price of a fixture the
    /// wait cannot outlast.
    #[test]
    fn stop_action_escalates_from_sigterm_to_sigkill_against_a_trapping_step() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let sleep_past_the_backstop = format!("trap '' TERM; sleep {}", FIXTURE_LIFETIME.as_secs());
        let trapping = action(
            "trapping",
            vec![step(&["sh", "-c", &sleep_past_the_backstop])],
        );

        assert!(core.run_action(trapping, std::slice::from_ref(&key)));
        wait_for("the trapping step to actually start running", || {
            core.snapshot().entities[0]
                .last_action
                .as_ref()
                .is_some_and(|receipt| receipt.running.is_some())
        });
        // Gives the shell time to install its own trap before any signal can arrive; the
        // outcome asserted below is the actual proof, not this fixed delay.
        thread::sleep(Duration::from_millis(100));

        core.stop_action();

        wait_for(
            "a SIGTERM-trapping step to come down from the follow-up SIGKILL",
            || !core.action_running(),
        );
        let receipt = core.snapshot().entities[0].last_action.clone().unwrap();
        assert_eq!(receipt.steps.len(), 1);
        assert_eq!(
            receipt.steps[0].outcome,
            StepOutcome::Cancelled,
            "a step running when the run was cancelled must read Cancelled, never Failed"
        );
    }

    // =====================================================================================
    // Criterion 2: cancellation produces `Cancelled`, never `NotRun`, which stays reserved
    // for being blocked by an earlier failure. Both outcomes are shown live in the same
    // run, on different entities, so they can be told apart rather than merely observed
    // one at a time.
    // =====================================================================================

    /// One Action, two entities, dispatched together at `concurrency: 2`: `fail`'s own
    /// first step exits nonzero well before the run is ever cancelled, so its second step
    /// is a genuine `NotRun`; `slow`'s own first step is still sleeping when
    /// `stop_action` fires, so both of its steps read `Cancelled`. A test that only ever
    /// produced one of the two outcomes could not prove they are told apart; this fixture
    /// has both live in the same receipt set, so a mutation that collapsed one into the
    /// other would be caught by whichever entity it broke.
    #[test]
    fn cancelled_and_not_run_are_distinct_outcomes_shown_together_in_one_run() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("fail"));
        init_repo_with_a_commit(&root.join("slow"));

        let core = Core::start_discovered(spec(vec![root]));
        let snapshot = core.snapshot();
        let fail_key = snapshot
            .entities
            .iter()
            .find(|entity| &*entity.name == "fail")
            .expect("the fail entity is present")
            .key
            .clone();
        let slow_key = snapshot
            .entities
            .iter()
            .find(|entity| &*entity.name == "slow")
            .expect("the slow entity is present")
            .key
            .clone();

        // One step list run against both entities: behaviour branches on the entity's own
        // directory name, which is `$PWD`'s basename in each entity's own working
        // directory, so `fail` fails immediately and `slow` is still running when this
        // test cancels the whole run.
        // `slow`'s branch sleeps `FIXTURE_LIFETIME` rather than a number of its own: the
        // wait below is on cancellation bringing the fan-out down, which a step that ends by
        // itself inside the backstop would satisfy without cancellation working at all.
        let branch_on_the_entity_name = format!(
            "case \"$(basename \"$PWD\")\" in fail) exit 1 ;; *) sleep {} ;; esac",
            FIXTURE_LIFETIME.as_secs()
        );
        let steps = vec![
            step(&["sh", "-c", &branch_on_the_entity_name]),
            step(&["true"]),
        ];
        let mut action_spec = action("mixed", steps);
        action_spec.concurrency = 2;

        assert!(core.run_action(action_spec, &[fail_key.clone(), slow_key.clone()]));

        // `fail` must have already finished (both its steps recorded) while `slow` is
        // still running its own first step: the two entities' own outcomes are captured
        // at the same moment, which is what makes them "shown together".
        wait_for(
            "`fail` finished and `slow` still running before cancelling",
            || {
                let snapshot = core.snapshot();
                let fail_done = snapshot
                    .entities
                    .iter()
                    .find(|entity| entity.key == fail_key)
                    .and_then(|entity| entity.last_action.as_ref())
                    .is_some_and(|receipt| receipt.steps.len() == 2);
                let slow_running = snapshot
                    .entities
                    .iter()
                    .find(|entity| entity.key == slow_key)
                    .and_then(|entity| entity.last_action.as_ref())
                    .is_some_and(|receipt| receipt.running.is_some());
                fail_done && slow_running
            },
        );

        core.stop_action();
        wait_for("the fan-out to finish once cancelled", || {
            !core.action_running()
        });

        let snapshot = core.snapshot();
        let fail_receipt = snapshot
            .entities
            .iter()
            .find(|entity| entity.key == fail_key)
            .and_then(|entity| entity.last_action.clone())
            .expect("fail's own receipt");
        assert_eq!(fail_receipt.steps[0].outcome, StepOutcome::Failed(1));
        assert_eq!(
            fail_receipt.steps[1].outcome,
            StepOutcome::NotRun,
            "blocked by fail's own earlier failure, not by the later cancellation"
        );

        let slow_receipt = snapshot
            .entities
            .iter()
            .find(|entity| entity.key == slow_key)
            .and_then(|entity| entity.last_action.clone())
            .expect("slow's own receipt");
        assert_eq!(
            slow_receipt.steps[0].outcome,
            StepOutcome::Cancelled,
            "a step running when the run was cancelled must read Cancelled"
        );
        assert_eq!(
            slow_receipt.steps[1].outcome,
            StepOutcome::Cancelled,
            "a step that had not started when the run was cancelled must also read \
             Cancelled, never NotRun, which stays reserved for an earlier failure"
        );
    }

    /// A panic anywhere inside the fan-out, a poisoned `RwLock` from an unrelated
    /// earlier panic is enough, must not leave `action_running` stuck true for the
    /// life of this `Core`. Poisons the table lock directly rather than
    /// injecting a fault into `run_action_for_entity`, which runs a real child process
    /// and has no seam for one: the fan-out's own `table_handle.write().unwrap()` then
    /// panics on the poisoned lock exactly the way an unrelated earlier panic would in
    /// production.
    #[test]
    fn a_panicking_fan_out_still_resets_action_running_so_a_later_action_can_start() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        // Drained before the table lock is poisoned below: a probe still in flight would
        // take the poison too, and a panic in one of rayon's global workers aborts the
        // process rather than unwinding.
        let (core, launched) = started_and_settled(spec(vec![root]));
        let key = launched.entities[0].key.clone();

        // A step slow enough that the fan-out's own write of `last_action` cannot have
        // happened yet by the time the poisoning below completes: `run_action`'s own
        // synchronous prefix (the `compare_exchange`, `cancel_in_flight`, the read
        // that builds `included`) is already finished by the time this call returns,
        // so poisoning the lock afterwards can only reach the fan-out's own write,
        // inside its own spawned thread.
        let started = core.run_action(
            action("boom", vec![step(&["sh", "-c", "sleep 0.3"])]),
            std::slice::from_ref(&key),
        );
        assert!(started);

        let table = Arc::clone(&core.table);
        thread::spawn(move || {
            let _guard = table.write().unwrap();
            panic!("deliberately poison the table lock for this test");
        })
        .join()
        .expect_err("the poisoning thread must itself panic to poison the lock");

        // Without `catch_unwind` around the fan-out this never becomes false: its own write
        // panics on the now-poisoned lock, unwinds out of `pool.install` and skips the
        // `action_running.store(false, ...)` line entirely, leaving the flag stuck
        // true for the life of this `Core`.
        wait_for(
            "a panicking fan-out to reset action_running rather than leave it stuck true",
            || !core.action_running.load(Ordering::Acquire),
        );

        // Clears the poison this test itself introduced to force the panic, an
        // artifact of the test rather than anything production code ever does, so a
        // real, full `run_action` call below proves the reset flag actually lets
        // another Action run to completion, not merely that one private atomic flipped.
        core.table.clear_poison();

        let second_started = core.run_action(
            action("second", vec![step(&["true"])]),
            std::slice::from_ref(&key),
        );
        assert!(
            second_started,
            "a later Action must be able to start once the panicking one has finished"
        );
        wait_for("the second Action to run to completion", || {
            core.snapshot()
                .entities
                .iter()
                .find(|entity| entity.key == key)
                .and_then(|entity| entity.last_action.as_ref())
                .is_some_and(|receipt| &*receipt.label == "second")
        });
    }

    /// Asserts `entity` reads exactly as a Vanished row must: still in the table,
    /// its last known branch value untouched, and that same cell's staleness
    /// forced on. Shared by the Repo and the Submodule vanish tests so both
    /// exercise the identical assertion rather than a Repo-shaped one and a
    /// Submodule-shaped one that only look alike.
    fn assert_vanished_with_stale_branch(entity: &EntityState, expected_branch: &str) {
        assert_eq!(entity.presence, crate::entity::Presence::Vanished);
        match entity.branch.settled() {
            Some(Settled::Known {
                value: Head::Branch { name, .. },
                stale: true,
                at: _,
            }) => assert_eq!(
                &**name, expected_branch,
                "a Vanished entity must keep its last known branch value"
            ),
            other => panic!(
                "expected the branch cell to keep its Known value and go stale, got {other:?}"
            ),
        }
    }

    /// The central behaviour this ticket adds: an entity discovery no longer
    /// finds stays in the table with its last known values, every cell forced
    /// stale, rather than disappearing. Proven end to end through `refresh` and
    /// `settle`, which is what proves discovery itself re-ran rather than the
    /// entity merely being left alone.
    #[test]
    fn a_repo_removed_from_disk_stays_in_the_table_vanished_with_its_last_values() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        core.refresh(std::slice::from_ref(&key));
        let before = core.settle();
        let branch_name = match before.entities[0].branch.settled() {
            Some(Settled::Known {
                value: Head::Branch { name, .. },
                at: _,
                stale: _,
            }) => name.to_string(),
            other => panic!("expected the first refresh to settle a branch, got {other:?}"),
        };

        fs::remove_dir_all(&repo).expect("remove the repo from disk");

        core.refresh(&[]);
        let after = core.settle();

        assert_eq!(
            after.entities.len(),
            1,
            "a vanished entity must stay in the snapshot, not disappear from it"
        );
        assert_vanished_with_stale_branch(&after.entities[0], &branch_name);
    }

    /// Criterion 2's "untouched by the vanished-staleness path" made behavioural, through a
    /// real `Core::refresh` rather than calling `mark_vanished` directly: the same pass that
    /// forces every settled Cell stale on this entity must leave its receipt exactly as it was.
    #[test]
    fn a_vanished_entitys_action_receipt_survives_the_vanished_staleness_pass_untouched() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let receipt = crate::entity::ActionReceipt {
            label: Arc::from("reinstall"),
            steps: Arc::from(vec![crate::entity::StepResult {
                label: Arc::from("pnpm install"),
                outcome: crate::entity::StepOutcome::Ok,
                output: Arc::from(&b""[..]),
                elapsed: Duration::from_millis(1),
                elision: None,
                shell: false,
                interactive: false,
            }]),
            skip: None,
            finished_at: Timestamp::now(),
            running: None,
        };
        core.set_last_action_for_test(&key, receipt.clone());

        fs::remove_dir_all(&repo).expect("remove the repo from disk");
        core.refresh(&[]);
        let after = core.settle();

        let entity = &after.entities[0];
        assert_eq!(entity.presence, crate::entity::Presence::Vanished);
        assert_eq!(entity.last_action, Some(receipt));
    }

    /// Criterion 6's reason for `ActionReceipt` sharing rather than copying is "the snapshot
    /// is cloned every frame"; a bare `ActionReceipt::clone()` only proves `Arc::clone` shares,
    /// which holds by definition and says nothing about this design. Proven instead through
    /// `Core::snapshot` itself: put a receipt on a live `Core`'s table, take two snapshots, and
    /// assert the label and steps are the same allocation across them, not merely equal. This
    /// passes as written, since the sharing does hold end to end; it exists to fail if some
    /// intermediate step ever re-materialised the receipt's bytes.
    #[test]
    fn two_snapshots_of_an_entity_share_its_last_actions_label_and_steps_by_pointer() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        let receipt = crate::entity::ActionReceipt {
            label: Arc::from("reinstall"),
            steps: Arc::from(vec![crate::entity::StepResult {
                label: Arc::from("pnpm install"),
                outcome: crate::entity::StepOutcome::Failed(1),
                output: Arc::from(&b""[..]),
                elapsed: Duration::from_millis(1),
                elision: None,
                shell: false,
                interactive: false,
            }]),
            skip: None,
            finished_at: Timestamp::now(),
            running: None,
        };
        core.set_last_action_for_test(&key, receipt);

        let first = core.snapshot();
        let second = core.snapshot();
        let first_receipt = first.entities[0]
            .last_action
            .as_ref()
            .expect("receipt was set");
        let second_receipt = second.entities[0]
            .last_action
            .as_ref()
            .expect("receipt was set");

        assert!(
            Arc::ptr_eq(&first_receipt.label, &second_receipt.label),
            "two snapshots of the same receipt must share the label's allocation, not \
             re-copy it"
        );
        assert!(
            Arc::ptr_eq(&first_receipt.steps, &second_receipt.steps),
            "two snapshots of the same receipt must share the steps slice's allocation, not \
             re-copy it, which is also what shares every step's own captured output"
        );
    }

    /// A Submodule vanishes by exactly the same rule as a Repo: no code path here
    /// is specific to which half of discovery produced the entry. Driven through
    /// the Submodule half (removing its declaration from `.gitmodules`, never
    /// touched by the boundary walk) and asserted with the very same helper the
    /// Repo test above uses.
    #[test]
    fn a_submodule_removed_from_gitmodules_vanishes_by_the_same_rule_as_a_repo() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        fs::write(
            parent.join(".gitmodules"),
            "[submodule \"lib\"]\n\tpath = vendor/lib\n\turl = https://example.com/lib.git\n",
        )
        .expect("write .gitmodules");
        let submodule_path = parent.join("vendor").join("lib");
        init_repo_with_a_commit(&submodule_path);

        // Shown, so the explicit `refresh` just below actually dispatches a probe against
        // it: this test is about the Vanished rule, not about `show_submodules` gating.
        let mut core_spec = spec(vec![root]);
        core_spec.show_submodules = true;
        let core = Core::start_discovered(core_spec);
        let snapshot = core.snapshot();
        let submodule_key = snapshot
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Submodule))
            .expect("submodule discovered")
            .key
            .clone();
        core.refresh(std::slice::from_ref(&submodule_key));
        let before = core.settle();
        let submodule_before = before
            .entities
            .iter()
            .find(|entity| entity.key == submodule_key)
            .expect("submodule present");
        let branch_name = match submodule_before.branch.settled() {
            Some(Settled::Known {
                value: Head::Branch { name, .. },
                at: _,
                stale: _,
            }) => name.to_string(),
            other => {
                panic!("expected the submodule's first refresh to settle a branch, got {other:?}")
            }
        };

        // The submodule is no longer declared: discovery's second half will no
        // longer produce this entry, exactly as removing the parent's own `.git`
        // boundary would remove a Repo's entry.
        fs::write(parent.join(".gitmodules"), "").expect("clear .gitmodules");

        core.refresh(&[]);
        let after = core.settle();

        let submodule_after = after
            .entities
            .iter()
            .find(|entity| entity.key == submodule_key)
            .expect("the vanished submodule must stay in the snapshot");
        assert_vanished_with_stale_branch(submodule_after, &branch_name);
    }

    /// Dismissal writes nothing to disk, so a Repo dismissed from one `Core`
    /// reads as an ordinary, freshly discovered Present entity on a brand new
    /// `Core` over the same roots, never as a restored Vanished row: startup is
    /// always a Generation with an empty prior state.
    #[test]
    fn dismissal_persists_nothing_across_a_fresh_core() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let first_core = Core::start_discovered(spec(vec![root.clone()]));
        let key = first_core.snapshot().entities[0].key.clone();
        first_core.dismiss(&key);
        assert!(first_core.snapshot().entities.is_empty());
        drop(first_core);

        let second_core = Core::start_discovered(spec(vec![root]));
        let snapshot = second_core.snapshot();

        assert_eq!(
            snapshot.entities.len(),
            1,
            "a fresh Core must discover the repo again"
        );
        assert_eq!(
            snapshot.entities[0].presence,
            crate::entity::Presence::Present,
            "nothing from the dismissing Core's lifetime may be persisted, so the \
             repo must come back Present, never restored as Vanished"
        );
    }

    /// An entity that moves reads as vanished plus new: its old key stays in the
    /// table Vanished with its last values, and a brand new entity appears at the
    /// new path, rather than the move being recognised as a rename.
    #[test]
    fn a_repo_that_moves_reads_as_vanished_plus_new() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let original_path = root.join("original-name");
        init_repo_with_a_commit(&original_path);

        let core = Core::start_discovered(spec(vec![root.clone()]));
        let original_key = core.snapshot().entities[0].key.clone();
        core.refresh(std::slice::from_ref(&original_key));
        let before = core.settle();
        let branch_name = match before.entities[0].branch.settled() {
            Some(Settled::Known {
                value: Head::Branch { name, .. },
                at: _,
                stale: _,
            }) => name.to_string(),
            other => panic!("expected the first refresh to settle a branch, got {other:?}"),
        };

        let moved_path = root.join("new-name");
        fs::rename(&original_path, &moved_path).expect("move the repo on disk");

        core.refresh(&[]);
        let after = core.settle();

        assert_eq!(
            after.entities.len(),
            2,
            "a moved entity must read as the old key vanished plus a new one present, \
             never as one renamed entity"
        );
        let old_entity = after
            .entities
            .iter()
            .find(|entity| entity.key == original_key)
            .expect("the old key must stay in the table");
        assert_vanished_with_stale_branch(old_entity, &branch_name);
        let new_entity = after
            .entities
            .iter()
            .find(|entity| entity.key != original_key)
            .expect("a new entity at the moved path must be present");
        assert_eq!(new_entity.presence, crate::entity::Presence::Present);
        assert_eq!(new_entity.key.path(), moved_path);
    }

    /// Reappearance is vanishing's mirror: an entity discovery stops finding, and
    /// then finds again, must come back Present rather than staying stuck
    /// Vanished forever.
    #[test]
    fn a_vanished_repo_recreated_on_disk_reads_present_on_the_next_refresh() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        fs::remove_dir_all(&repo).expect("remove the repo from disk");
        core.refresh(&[]);
        let vanished = core.settle();
        assert_eq!(
            vanished.entities[0].presence,
            crate::entity::Presence::Vanished,
            "the repo must read Vanished once removed from disk"
        );

        init_repo_with_a_commit(&repo);
        core.refresh(&[]);
        let recreated = core.settle();

        let entity = recreated
            .entities
            .iter()
            .find(|entity| entity.key == key)
            .expect("the recreated repo must still resolve to the same entity key");
        assert_eq!(
            entity.presence,
            crate::entity::Presence::Present,
            "an entity discovery finds again after it vanished must read Present, \
             not stay stuck Vanished forever"
        );
    }

    /// Discovery riding the refresh is what lets a brand new entity appear
    /// without a fresh `Core::start`: a repo created after `start` is picked up
    /// by the very next `refresh`, even though the caller's `order` cannot yet
    /// name a key it never saw.
    #[test]
    fn a_new_repo_created_after_start_is_discovered_by_the_next_refresh() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("first"));

        let core = Core::start_discovered(spec(vec![root.clone()]));
        assert_eq!(core.snapshot().entities.len(), 1);

        init_repo_with_a_commit(&root.join("second"));
        core.refresh(&[]);
        let after = core.settle();

        assert_eq!(
            after.entities.len(),
            2,
            "a new repo created after start must be found by the next refresh's own discovery"
        );

        // The entity is usable, not merely counted: a refresh that names its key
        // actually probes it and settles a real cell.
        let new_key = after
            .entities
            .iter()
            .find(|entity| &*entity.name == "second")
            .expect("the newly discovered repo must be named by the walk")
            .key
            .clone();
        core.refresh(std::slice::from_ref(&new_key));
        let probed = core.settle();
        let new_entity = probed
            .entities
            .iter()
            .find(|entity| entity.key == new_key)
            .expect("the newly discovered repo must still be present");
        assert!(
            matches!(
                new_entity.branch.settled(),
                Some(Settled::Known {
                    value: _,
                    at: _,
                    stale: _
                })
            ),
            "a refresh naming the newly discovered repo's key must actually probe \
             it and settle its branch cell, got {:?}",
            new_entity.branch.settled()
        );
    }

    /// The abandon path takes the Set out of the automatic refresh path: once one
    /// discovery invocation abandons, a later `refresh` does not re-run discovery
    /// at all, proven by a repo created afterward never appearing, not merely by
    /// reading an internal flag.
    #[test]
    fn an_abandoned_discovery_stops_riding_later_refreshes() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        // A wide fan of plain directories, real enough for the walk to measurably
        // outrun a millisecond-scale deadline, so `start`'s own discovery
        // abandons rather than merely being told to (`Duration::ZERO` would trip
        // on the very first directory regardless of what is actually here, which
        // could never distinguish a guarded `refresh` from an unguarded one that
        // simply keeps re-abandoning against the same still-huge tree).
        let decoys = root.join("decoys");
        for i in 0..4_000 {
            fs::create_dir(decoys.join(format!("decoy-{i}")))
                .or_else(|_| fs::create_dir_all(decoys.join(format!("decoy-{i}"))))
                .expect("create decoy dir");
        }
        let (_tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();

        let started = Core::start_for_test_with_discovery_abandon(
            spec(vec![root.clone()]),
            Duration::from_secs(3600),
            Duration::from_micros(500),
            tick_rx,
        )
        .discovered();
        let core = started.core;
        assert!(
            core.discovery_manual_for_test(),
            "walking 4,000 decoy directories against a 500 microsecond deadline \
             must have abandoned and taken the Set manual"
        );

        // The tree shrinks back to nothing slow: if `refresh` were still (wrongly)
        // re-running discovery, this walk would finish comfortably inside the
        // same deadline and find the new repo below. Only the manual guard can
        // account for it staying undiscovered.
        fs::remove_dir_all(&decoys).expect("remove decoy directories");
        init_repo_with_a_commit(&root.join("second"));

        core.refresh(&[]);
        let after = core.settle();

        assert!(
            !after
                .entities
                .iter()
                .any(|entity| &*entity.name == "second"),
            "once discovery has abandoned, a later refresh must not re-run it, so a \
             repo created afterward, on a tree that would now resolve quickly, \
             must still never appear"
        );
    }

    /// `rerun_discovery`'s own abandon handling, exercised by a walk that only
    /// abandons on a later `refresh`, never on `start`'s: the first walk, over a
    /// tree small enough to finish comfortably inside the deadline, must leave
    /// the Set automatic, and only the second walk, once the same tree has grown
    /// a wide fan of decoys, may flip the manual flag and leave the abandoned
    /// warning. Both existing abandon tests force the abandon inside `start`'s
    /// own walk, which can never reach this block: `refresh` gates
    /// `rerun_discovery` behind the manual flag `start` already set.
    #[test]
    fn a_refresh_triggered_discovery_abandon_sets_manual_and_warns() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("first"));
        let (_tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();

        // The first walk runs under a deadline it cannot lose against, so this
        // precondition is not a race. Tightening the deadline afterwards is what
        // separates the walk that must survive from the walk that must abandon:
        // one deadline serving both is a knife edge, and scheduling latency on a
        // loaded machine erases any margin a wall-clock figure can buy.
        let started = Core::start_for_test_with_discovery_abandon(
            spec(vec![root.clone()]),
            Duration::from_secs(3600),
            Duration::from_secs(3600),
            tick_rx,
        )
        .discovered();
        let core = started.core;
        assert!(
            !core.discovery_manual_for_test(),
            "an hour-long deadline must leave the first walk automatic"
        );

        // Grown only after the first walk has finished (`discovered` above joined it),
        // so this fan of decoys is invisible to that walk and can only be reached by a
        // walk `refresh` triggers itself.
        let decoys = root.join("decoys");
        for i in 0..4_000 {
            fs::create_dir(decoys.join(format!("decoy-{i}")))
                .or_else(|_| fs::create_dir_all(decoys.join(format!("decoy-{i}"))))
                .expect("create decoy dir");
        }
        core.set_discovery_abandon_after_for_test(Duration::from_micros(500));

        core.refresh(&[]);
        // `refresh` returns the moment it has reserved its Generation; this is the
        // rendezvous that says its own walk has run.
        core.wait_dispatched_for_test();

        assert!(
            core.discovery_manual_for_test(),
            "refresh's own rerun_discovery must abandon against the newly-grown \
             tree and take the Set manual, the same as an abandon at start does"
        );
        let warning = core.discovery_warning();
        assert!(
            warning
                .as_deref()
                .is_some_and(|message| message.starts_with("discovery: stopped at")),
            "refresh's rerun_discovery must leave the abandoned-discovery warning \
             behind, not merely flip the manual flag: got {warning:?}"
        );
    }

    /// The other half: an abandoned Set going manual must not leak into a
    /// different `Core`. The only way this crate can express "the Set's roots or
    /// globs changed" today is a fresh `Core::start` (a live in-place reload has
    /// no entry point in `Core` yet), so this proves the manual flag lives on one
    /// `Core` instance rather than anywhere global.
    #[test]
    fn a_fresh_core_over_different_roots_is_unaffected_by_another_cores_abandoned_discovery() {
        let abandoned_dir = tempfile::tempdir().expect("temp dir");
        let abandoned_root = root_of(&abandoned_dir);
        init_repo_with_a_commit(&abandoned_root.join("first"));
        let (_tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();
        let started = Core::start_for_test_with_discovery_abandon(
            spec(vec![abandoned_root]),
            Duration::from_secs(3600),
            Duration::ZERO,
            tick_rx,
        )
        .discovered();
        started.core.refresh(&[]);
        started.core.settle();
        assert!(
            started.core.discovery_manual_for_test(),
            "the zero-length abandon deadline must have already taken this Core manual"
        );
        drop(started.core);

        let fresh_dir = tempfile::tempdir().expect("temp dir");
        let fresh_root = root_of(&fresh_dir);
        init_repo_with_a_commit(&fresh_root.join("first"));
        let fresh_core = Core::start_discovered(spec(vec![fresh_root.clone()]));
        assert_eq!(fresh_core.snapshot().entities.len(), 1);

        init_repo_with_a_commit(&fresh_root.join("second"));
        fresh_core.refresh(&[]);
        let after = fresh_core.settle();

        assert_eq!(
            after.entities.len(),
            2,
            "a fresh Core, standing in for the Set's roots changing, must discover \
             normally regardless of an earlier, unrelated Core having gone manual"
        );
    }

    /// Proves shutdown is clean: dropping the core blocks until the dedicated
    /// thread has actually returned, not merely until a message was sent to it.
    /// The tick sender is kept alive for the whole test, so the only way the
    /// thread can have stopped is the shutdown message `Drop` sends.
    #[test]
    fn dropping_the_core_joins_the_dedicated_thread_before_returning() {
        let (tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);

        let started =
            Core::start_for_test(spec(vec![root]), Duration::from_secs(3600), tick_rx).discovered();
        assert!(started.clock_alive.load(Ordering::Acquire));

        drop(started.core);

        assert!(
            !started.clock_alive.load(Ordering::Acquire),
            "the dedicated thread should have exited, and cleared this flag, before drop returned"
        );
        drop(tick_tx);
    }

    /// Cadence is driven entirely by the injected tick channel, never by a clock of
    /// the loop's own: with a zero deadline, the sweep is provably ready to fire
    /// the instant it runs, so whether it has run is exactly whether a tick has
    /// been sent, proven with no sleep on either side.
    #[test]
    fn the_deadline_sweep_runs_only_when_a_tick_arrives() {
        let (tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let mut spec = spec(vec![root]);
        spec.generation_deadline = Duration::ZERO;
        let started = Core::start_for_test(spec, Duration::from_secs(3600), tick_rx).discovered();
        let core = started.core;
        // Drained, so the only entry in flight below is this test's own and only the sweep
        // can settle it again.
        let key = settle_launch(&core).entities[0].key.clone();

        core.begin_untracked_probe_for_test(&key);

        // No tick has been sent: the sweep has not run even though the (zero)
        // deadline has already elapsed in real time.
        let before = core.snapshot();
        assert!(
            matches!(
                before.entities[0].branch.settled(),
                Some(Settled::Known {
                    value: _,
                    at: _,
                    stale: _
                })
            ),
            "the cell still holds launch's own answer here, so the Unknown below is the \
             sweep's write rather than a cell that was already empty"
        );
        assert!(before.entities[0].branch.is_in_flight());

        tick_tx.send(Instant::now()).expect("send one tick");
        let after = core.settle();

        assert!(matches!(
            after.entities[0].branch.settled(),
            Some(Settled::Unknown(Unknown::TimedOut))
        ));
    }

    /// Proves the real dedicated thread's tick arm actually reaches
    /// [`run_poll_sweep`], not merely that [`Core::poll_once_for_test`]'s direct
    /// call does the right thing: a mutation deleting the call inside
    /// `spawn_clock_thread` would leave every other poll test in this file green
    /// while failing only this one. [`wait_for`] backstops the wait rather than
    /// asserting any particular latency: the two ticks are sent from this thread
    /// and merely need to be picked up by the idle dedicated thread, not to land
    /// within a stated budget.
    #[test]
    fn a_real_tick_through_the_dedicated_thread_reaches_the_poll_sweep_and_reprobes_a_moved_entity()
    {
        let (tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let started =
            Core::start_for_test(spec(vec![root]), Duration::from_secs(3600), tick_rx).discovered();
        let core = started.core;
        let key = core.snapshot().entities[0].key.clone();

        backdate_polled_entries(&repo);

        // The first tick only records a baseline: nothing has moved yet against a
        // fingerprint that did not exist before this tick.
        tick_tx
            .send(Instant::now())
            .expect("send the baseline tick");
        wait_for(
            "a tick sent on the real channel to reach the poll sweep",
            || core.poll_sweep_count_for_test() >= 1,
        );
        assert!(core.poll_reprobed_for_test().is_empty());

        commit_a_change(&repo, "second");

        tick_tx
            .send(Instant::now())
            .expect("send the movement tick");
        wait_for(
            "the real tick channel to reach the poll sweep and reprobe the moved entity",
            || core.poll_reprobed_for_test() == vec![key.clone()],
        );
        drop(tick_tx);
    }

    /// Criterion 2's whole claim, over two entities so "for that entity only" has
    /// something to discriminate against: committing into one of two Repos and
    /// running one poll sweep re-probes branch/sync/base for the moved Repo alone
    /// (`poll_reprobed_for_test` names exactly it, never the other), force-stales
    /// its `dirty` and `state` without changing their value or timestamp (the
    /// absence claim that no status probe ran), and leaves the untouched Repo's
    /// cells byte-for-byte as the prior real `refresh` left them.
    #[test]
    fn poll_reprobe_touches_only_the_moved_entity_and_never_runs_a_status_probe() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo_a = root.join("repo-a");
        let repo_b = root.join("repo-b");
        init_repo_with_a_commit(&repo_a);
        init_repo_with_a_commit(&repo_b);

        let core = Core::start_discovered(spec(vec![root]));
        let snapshot = core.snapshot();
        let key_a = snapshot
            .entities
            .iter()
            .find(|entity| entity.key.path() == repo_a)
            .expect("repo-a discovered")
            .key
            .clone();
        let key_b = snapshot
            .entities
            .iter()
            .find(|entity| entity.key.path() == repo_b)
            .expect("repo-b discovered")
            .key
            .clone();

        core.refresh(&[key_a.clone(), key_b.clone()]);
        let landed = core.settle();
        let entity_of = |snapshot: &Snapshot, key: &EntityKey| {
            snapshot
                .entities
                .iter()
                .find(|entity| &entity.key == key)
                .expect("entity present")
                .clone()
        };
        let a_before = entity_of(&landed, &key_a);
        let b_before = entity_of(&landed, &key_b);
        let branch_at = |entity: &EntityState| match entity.branch.settled() {
            Some(Settled::Known {
                at,
                value: _,
                stale: _,
            }) => *at,
            other => panic!("expected a landed branch, got {other:?}"),
        };
        let dirty_state = |entity: &EntityState| match entity.dirty.settled() {
            Some(Settled::Known { value, at, stale }) => (*value, *at, *stale),
            other => panic!("expected a landed dirty count, got {other:?}"),
        };
        let (a_dirty_value_before, a_dirty_at_before, a_dirty_stale_before) =
            dirty_state(&a_before);
        assert!(
            !a_dirty_stale_before,
            "the fresh refresh must land dirty as not stale"
        );

        backdate_polled_entries(&repo_a);

        backdate_polled_entries(&repo_b);

        core.poll_once_for_test();
        assert!(
            core.poll_reprobed_for_test().is_empty(),
            "a first sweep has nothing to compare against, so it must report no movement"
        );

        commit_a_change(&repo_a, "second");
        core.poll_once_for_test();

        assert_eq!(
            core.poll_reprobed_for_test(),
            vec![key_a.clone()],
            "only the entity whose gitdir actually moved must be re-probed"
        );

        let after = core.snapshot();
        let a_after = entity_of(&after, &key_a);
        let b_after = entity_of(&after, &key_b);

        assert_ne!(
            branch_at(&a_after),
            branch_at(&a_before),
            "the moved entity's branch must carry a fresh timestamp from the re-probe"
        );
        let (a_dirty_value_after, a_dirty_at_after, a_dirty_stale_after) = dirty_state(&a_after);
        assert_eq!(
            a_dirty_value_after, a_dirty_value_before,
            "no status probe ran, so dirty's value must be exactly what the last real refresh \
             landed"
        );
        assert_eq!(
            a_dirty_at_after, a_dirty_at_before,
            "no status probe ran, so dirty's timestamp must be untouched, only its stale flag \
             set"
        );
        assert!(
            a_dirty_stale_after,
            "the moved entity's dirty cell must go stale on poll evidence"
        );

        assert_eq!(
            branch_at(&b_after),
            branch_at(&b_before),
            "the untouched entity's branch must be exactly as the prior refresh left it"
        );
        let (b_dirty_value_after, b_dirty_at_after, b_dirty_stale_after) = dirty_state(&b_after);
        let (b_dirty_value_before, b_dirty_at_before, b_dirty_stale_before) =
            dirty_state(&b_before);
        assert_eq!(b_dirty_value_after, b_dirty_value_before);
        assert_eq!(b_dirty_at_after, b_dirty_at_before);
        assert_eq!(
            b_dirty_stale_after, b_dirty_stale_before,
            "an entity the sweep found unmoved must never go stale"
        );
    }

    /// Criterion 3's attached half, and one of `refresh.md`'s two named traps: a
    /// commit on an attached HEAD never touches `.git/HEAD` at all, only
    /// `.git/logs/HEAD`. The poll must still see the commit, through `index`
    /// rather than through `HEAD`.
    #[test]
    fn poll_detects_an_attached_commit_through_index_while_head_itself_never_moves() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        backdate_polled_entries(&repo);
        core.poll_once_for_test();
        assert!(core.poll_reprobed_for_test().is_empty());

        let head_path = repo.join(".git").join("HEAD");
        let head_mtime_before = fs::metadata(&head_path)
            .expect("stat HEAD")
            .modified()
            .expect("HEAD mtime");

        commit_a_change(&repo, "second");

        let head_mtime_after = fs::metadata(&head_path)
            .expect("stat HEAD")
            .modified()
            .expect("HEAD mtime");
        assert_eq!(
            head_mtime_before, head_mtime_after,
            "a commit on an attached HEAD must never touch HEAD itself"
        );

        core.poll_once_for_test();
        assert_eq!(
            core.poll_reprobed_for_test(),
            vec![key],
            "the poll must still detect the attached commit, through index rather than HEAD"
        );
    }

    /// Criterion 3's detached half: [head.md](https://github.com/paulchiu/repon/blob/main/docs/spec/head.md)'s
    /// claim that a detached row's evidence is better than an attached row's,
    /// because a commit on a detached HEAD writes the new object id straight into
    /// the per-worktree `HEAD` file itself. Run against a real linked Worktree,
    /// never the main working tree, since that per-worktree file is exactly what
    /// distinguishes this case from the attached one above.
    #[test]
    fn poll_detects_a_detached_commit_through_the_per_worktree_head_file() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        let worktree_path = root.join("detached-worktree");
        let status = Command::new("git")
            .arg("-C")
            .arg(&parent)
            .args([
                "worktree",
                "add",
                "--detach",
                worktree_path.to_str().expect("utf8 path"),
            ])
            .status()
            .expect("run git worktree add");
        assert!(status.success());

        let core = Core::start_discovered(spec(vec![root]));
        let snapshot = core.snapshot();
        let worktree_key = snapshot
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Worktree))
            .expect("worktree discovered")
            .key
            .clone();

        backdate_polled_entries(&parent);
        backdate_polled_entries(&worktree_path);

        core.poll_once_for_test();
        assert!(core.poll_reprobed_for_test().is_empty());

        let worktree_head_path = parent
            .join(".git")
            .join("worktrees")
            .join("detached-worktree")
            .join("HEAD");
        let head_mtime_before = fs::metadata(&worktree_head_path)
            .expect("stat the per-worktree HEAD")
            .modified()
            .expect("HEAD mtime");

        commit_a_change(&worktree_path, "on the detached worktree");

        let head_mtime_after = fs::metadata(&worktree_head_path)
            .expect("stat the per-worktree HEAD")
            .modified()
            .expect("HEAD mtime");
        assert_ne!(
            head_mtime_before, head_mtime_after,
            "a commit on a detached HEAD must write the new object id straight into its own \
             HEAD file"
        );

        core.poll_once_for_test();
        assert_eq!(
            core.poll_reprobed_for_test(),
            vec![worktree_key],
            "the poll must detect the detached commit via the per-worktree HEAD file"
        );
    }

    /// Criterion 4's elapsed-age writer, wired through `Core::snapshot` end to end:
    /// `status_stale_after` from `CoreSpec` is what decides whether a freshly
    /// landed `dirty` cell already reads Stale. A `Duration::from_nanos(1)`
    /// threshold has necessarily already elapsed by the time `snapshot` runs
    /// afterwards, so this needs no sleep and depends on no stated latency budget,
    /// only on real wall-clock time having advanced at all between two calls.
    #[test]
    fn snapshot_ages_a_freshly_landed_dirty_cell_stale_once_status_stale_after_has_elapsed() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let mut short_lived = spec(vec![root]);
        short_lived.status_stale_after = Duration::from_nanos(1);
        let core = Core::start_discovered(short_lived);
        let key = core.snapshot().entities[0].key.clone();
        core.refresh(std::slice::from_ref(&key));
        core.settle();

        let aged = core.snapshot();
        match aged.entities[0].dirty.settled() {
            Some(Settled::Known {
                stale: true,
                value: _,
                at: _,
            }) => {}
            other => panic!(
                "expected a landed dirty cell to have already aged past a one-nanosecond \
                 threshold, got {other:?}"
            ),
        }
    }

    /// The same wiring's other side: a landed `dirty` cell stays fresh under a
    /// large `status_stale_after`, so the wiring is genuinely reading the
    /// threshold rather than always staling.
    #[test]
    fn snapshot_leaves_a_freshly_landed_dirty_cell_fresh_under_a_large_status_stale_after() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();
        core.refresh(std::slice::from_ref(&key));
        core.settle();

        let fresh = core.snapshot();
        match fresh.entities[0].dirty.settled() {
            Some(Settled::Known {
                stale: false,
                value: _,
                at: _,
            }) => {}
            other => panic!("expected a freshly landed dirty cell to stay fresh, got {other:?}"),
        }
    }

    /// Criterion 5's absence claim: a hidden Submodule (`show_submodules` off) is
    /// never in the poll's own candidate set, so a commit into it is never
    /// detected, while the identical commit against the same Submodule shown is.
    /// Run as one test over the same fixture with the flag flipped, rather than
    /// two, so the only variable between the two sweeps is the flag itself.
    #[test]
    fn hidden_submodules_are_never_polled_but_shown_ones_are() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        fs::write(
            parent.join(".gitmodules"),
            "[submodule \"lib\"]\n\tpath = vendor/lib\n\turl = https://example.com/lib.git\n",
        )
        .expect("write .gitmodules");
        let submodule_path = parent.join("vendor").join("lib");
        init_repo_with_a_commit(&submodule_path);

        let mut hidden_spec = spec(vec![root.clone()]);
        hidden_spec.show_submodules = false;
        let hidden_core = Core::start_discovered(hidden_spec);
        // Discovery's own pass always runs regardless of the flag
        // (discovery.md's "Showing Submodules": "the pass always runs, so
        // Submodules are always known"), so the row exists; only probing and the
        // poll are gated on it.
        let hidden_submodule_key = hidden_core
            .snapshot()
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Submodule))
            .expect("the submodule is discovered regardless of show_submodules")
            .key
            .clone();
        backdate_polled_entries(&submodule_path);
        hidden_core.poll_once_for_test();
        commit_a_change(&submodule_path, "into the hidden submodule");
        hidden_core.poll_once_for_test();
        assert!(
            !hidden_core
                .poll_reprobed_for_test()
                .contains(&hidden_submodule_key),
            "a hidden Submodule must never be re-probed by the poll, since it was never \
             polled at all"
        );
        drop(hidden_core);

        let mut shown_spec = spec(vec![root]);
        shown_spec.show_submodules = true;
        let shown_core = Core::start_discovered(shown_spec);
        let submodule_key = shown_core
            .snapshot()
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Submodule))
            .expect("the submodule is discovered regardless of show_submodules")
            .key
            .clone();
        backdate_polled_entries(&submodule_path);
        shown_core.poll_once_for_test();
        commit_a_change(&submodule_path, "into the shown submodule");
        shown_core.poll_once_for_test();
        assert_eq!(
            shown_core.poll_reprobed_for_test(),
            vec![submodule_key],
            "a shown Submodule must be polled and re-probed exactly like any other row"
        );
    }

    /// Pause cancels a real in-flight entry (not merely stores a flag nobody
    /// reads): the cancel flag `begin_untracked_probe_for_test` returns is
    /// observed `true` afterward, and `settle` unblocks because pause released it,
    /// which is only possible if pause's handler on the dedicated thread actually
    /// ran.
    #[test]
    fn pause_cancels_every_in_flight_entity_and_releases_a_pending_settle() {
        let (tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let started =
            Core::start_for_test(spec(vec![root]), Duration::from_secs(3600), tick_rx).discovered();
        let core = started.core;
        // Drained, so the only entry in flight below is the one this test puts there.
        let key = settle_launch(&core).entities[0].key.clone();
        let cancel = core.begin_untracked_probe_for_test(&key);
        assert!(!cancel.load(Ordering::Acquire));

        core.pause();
        let settled = core.settle();

        assert!(
            cancel.load(Ordering::Acquire),
            "pause should cancel the entity that was in flight"
        );
        assert!(settled.entities[0].branch.is_in_flight());
        drop(tick_tx);
    }

    /// A launch walks the tree once.
    ///
    /// Discovery rides on every Generation
    /// ([refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
    /// "Discovery is never on the calling thread"), so counting a launch's walks is
    /// counting its Generations: one walk means the very first Generation a fresh `Core`
    /// mints is the only one a settled launch has, and that it already covers every row
    /// the walk found. A second walk would be a second Generation and would read here.
    #[test]
    fn a_launch_is_one_generation_over_every_row_its_own_walk_found() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("first"));
        init_repo_with_a_commit(&root.join("second"));

        let (_core, launched) = started_and_settled(spec(vec![root]));

        assert_eq!(
            launched.generation,
            Generation::default().successor(),
            "a launch must settle on the first Generation a fresh `Core` mints; a second \
             walk of the same tree would be a second Generation"
        );
        let mut named: Vec<String> = launched
            .entities
            .iter()
            .filter(|entity| entity.branch.settled().is_some())
            .map(|entity| entity.name.to_string())
            .collect();
        named.sort();
        assert_eq!(
            named,
            vec!["first".to_string(), "second".to_string()],
            "that one Generation must cover every row its own walk found, or the walk it \
             saved would have to be paid by a second one"
        );
    }

    /// A `Core` going away cancels what it still has in flight, the same way `pause` does.
    ///
    /// [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
    /// "Cancellation": an abandoned Generation is cancelled rather than left to finish,
    /// because both would contend for the same cores. A Set switch is where that bites,
    /// rebuilding the `Core` while the outgoing one's fan-out is still running.
    #[test]
    fn dropping_a_core_cancels_every_entity_it_still_has_in_flight() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("repo"));

        let (core, launched) = started_and_settled(spec(vec![root]));
        let key = launched.entities[0].key.clone();
        let cancel = core.begin_untracked_probe_for_test(&key);
        assert!(!cancel.load(Ordering::Acquire));

        drop(core);

        assert!(
            cancel.load(Ordering::Acquire),
            "a dropped Core must cancel the Generation it still has in flight rather than \
             leave it running against a Set nothing will read again"
        );
    }

    /// Per-entity supersession, not global. An older Generation covers two entities,
    /// A and B, both simulated as still in flight. A Selection-scoped newer
    /// Generation covers only A: A's own older interrupt flag must be set, and B's
    /// must not, since the newer one never mentions B. Once the newer Generation has
    /// written A's cell, A's slow older result finally arrives and must be dropped
    /// there; B's own older result, arriving after everything else, must still be
    /// accepted, because the newer Generation never superseded it.
    ///
    /// The two are named by their order, never by their counter values, so a
    /// Generation minted earlier in the crate cannot renumber this test out from
    /// under itself.
    ///
    /// This is exactly the distinction a global-current-Generation comparison
    /// would get wrong: such a check compares every write against the table's one
    /// counter, which the Selection-scoped refresh has already advanced, so B's
    /// older result would be wrongly dropped even though nothing ever superseded B
    /// specifically. Before `Cell::settle`'s comparison was wired
    /// against the cell's own recorded Generation this test failed exactly there:
    /// B's late result was rejected, which is precisely the "cannot strand the
    /// rows it never spoke for" defect the ticket names.
    ///
    /// This test read A's interrupt flag intermittently false under load. The cause was
    /// `apply_probe_outcome` clearing the in-flight entry by key alone: launch's own
    /// Generation was left undrained here, so one of its probes could finish after the
    /// simulated older Generation had put its flags under the same keys and delete the
    /// entry holding them, leaving the Selection-scoped refresh nothing to supersede.
    /// Launch is drained first now, and the entry is cleared by Generation as well as by
    /// key, which `a_probe_finishing_clears_only_its_own_generations_in_flight_entry`
    /// pins directly.
    #[test]
    fn a_selection_scoped_refresh_supersedes_only_the_entity_it_covers() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("a"));
        init_repo_with_a_commit(&root.join("b"));

        let (core, snapshot) = started_and_settled(spec(vec![root]));
        let key_a = snapshot
            .entities
            .iter()
            .find(|entity| &*entity.name == "a")
            .expect("entity a discovered")
            .key
            .clone();
        let key_b = snapshot
            .entities
            .iter()
            .find(|entity| &*entity.name == "b")
            .expect("entity b discovered")
            .key
            .clone();

        // The older Generation, simulated: both A and B are mid-flight, with nothing
        // spawned to complete either one, so the test controls exactly when each
        // one's result lands.
        let older = core.begin_shared_generation_for_test(&[key_a.clone(), key_b.clone()]);

        // A Selection-scoped refresh over A alone, the very next Generation after the
        // one still in flight.
        let newer = core.refresh(std::slice::from_ref(&key_a));
        assert_eq!(
            newer,
            older.generation.successor(),
            "the Selection-scoped refresh must be the Generation immediately after the one \
             still in flight, with nothing minted in between"
        );

        // Supersession happens on the new Generation's own thread, behind its walk, so
        // this is the rendezvous that says it has happened. A join, never a deadline: no
        // production rule bounds how long that walk takes short of the thirty seconds at
        // which discovery is abandoned.
        core.wait_dispatched_for_test();
        assert!(
            older.cancels[&key_a].load(Ordering::Acquire),
            "the entity the new Generation covers must have its old interrupt flag set"
        );
        assert!(
            !older.cancels[&key_b].load(Ordering::Acquire),
            "an entity the new Generation does not cover must be left running, untouched"
        );

        // [`BACKSTOP`] rather than a budget: what follows reads the cell the new
        // Generation's own probe writes, which is a liveness property with no wall-clock
        // bound of its own.
        let after_refresh = core.settle();

        let a_after_gen2 = after_refresh
            .entities
            .iter()
            .find(|entity| entity.key == key_a)
            .expect("entity a present");
        assert!(
            matches!(
                a_after_gen2.branch.settled(),
                Some(Settled::Known {
                    value: Head::Branch { .. },
                    at: _,
                    stale: _
                })
            ),
            "the newer Generation's real probe should have written A's cell by now"
        );

        // A's slow older result finally arrives, after the newer Generation has
        // already written the cell: dropped, since it is lower than the Generation
        // already recorded there.
        core.apply_probe_result_for_test(
            &key_a,
            older.generation,
            Settled::Known {
                value: Head::Branch {
                    name: Arc::from("stale-from-generation-one"),
                    commit: gix::hash::Kind::Sha1.null(),
                },
                at: Timestamp::now(),
                stale: false,
            },
        );
        let after_stale_write = core.snapshot();
        let a_final = after_stale_write
            .entities
            .iter()
            .find(|entity| entity.key == key_a)
            .expect("entity a present");
        match a_final.branch.settled() {
            Some(Settled::Known {
                value: Head::Branch { name, .. },
                at: _,
                stale: _,
            }) => assert_ne!(
                &**name, "stale-from-generation-one",
                "a lower-Generation result must be dropped at the cell it would write"
            ),
            other => panic!("expected A to still hold the newer Generation's value, got {other:?}"),
        }

        // B's own older result, landing last of all, is still accepted: the newer
        // Generation never covered B, so nothing superseded it.
        core.apply_probe_result_for_test(
            &key_b,
            older.generation,
            Settled::Known {
                value: Head::Branch {
                    name: Arc::from("b-generation-one-result"),
                    commit: gix::hash::Kind::Sha1.null(),
                },
                at: Timestamp::now(),
                stale: false,
            },
        );
        let final_snapshot = core.snapshot();
        let b_final = final_snapshot
            .entities
            .iter()
            .find(|entity| entity.key == key_b)
            .expect("entity b present");
        match b_final.branch.settled() {
            Some(Settled::Known {
                value: Head::Branch { name, .. },
                at: _,
                stale: _,
            }) => assert_eq!(
                &**name, "b-generation-one-result",
                "an entity the new Generation never covered must still accept its own result"
            ),
            other => {
                panic!("expected B's un-superseded older result to be accepted, got {other:?}")
            }
        }
    }

    /// The deadline sweep abandons only what is still Loading when it fires. An
    /// entity already settled by the time the deadline sweep runs keeps its value
    /// untouched, blanking nothing, while a different entity still mid-flight in
    /// the same sweep becomes Unknown with the timed-out reason.
    #[test]
    fn the_deadline_sweep_keeps_already_settled_cells_and_only_times_out_what_is_still_loading() {
        let (tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("a"));
        init_repo_with_a_commit(&root.join("b"));

        let mut spec = spec(vec![root]);
        spec.generation_deadline = Duration::ZERO;
        let started = Core::start_for_test(spec, Duration::from_secs(3600), tick_rx).discovered();
        let core = started.core;
        // Drained, so the only cell still loading when the sweep fires is the one this
        // test puts in flight.
        let snapshot = settle_launch(&core);
        let key_a = snapshot
            .entities
            .iter()
            .find(|entity| &*entity.name == "a")
            .expect("entity a discovered")
            .key
            .clone();
        let key_b = snapshot
            .entities
            .iter()
            .find(|entity| &*entity.name == "b")
            .expect("entity b discovered")
            .key
            .clone();

        // A is already settled, synchronously, before the deadline ever has a
        // chance to fire.
        let a_settled = core.probe_now(&key_a);
        let a_value_before = match a_settled.branch.settled() {
            Some(Settled::Known {
                value: Head::Branch { name, .. },
                at: _,
                stale: _,
            }) => Arc::clone(name),
            other => panic!("expected A's synchronous probe to settle a branch, got {other:?}"),
        };

        // B is left mid-flight, in a Generation whose (zero) deadline has already
        // elapsed in real time, but the sweep has not run yet: no tick has been
        // sent.
        let cancel_b = core.begin_untracked_probe_for_test(&key_b);
        let before_tick = core.snapshot();
        let b_before = before_tick
            .entities
            .iter()
            .find(|entity| entity.key == key_b)
            .expect("entity b present");
        assert!(
            b_before.branch.is_in_flight(),
            "B must be mid-flight when the sweep fires; that is the only shape the sweep \
             may touch"
        );
        assert!(
            matches!(
                b_before.branch.settled(),
                Some(Settled::Known {
                    value: _,
                    at: _,
                    stale: _
                })
            ),
            "B still carries launch's own answer here, so the Unknown below is a write the \
             sweep made rather than a cell that was already empty, got {:?}",
            b_before.branch.settled()
        );

        tick_tx.send(Instant::now()).expect("send one tick");
        let after_sweep = core.settle();

        let a_after = after_sweep
            .entities
            .iter()
            .find(|entity| entity.key == key_a)
            .expect("entity a present");
        match a_after.branch.settled() {
            Some(Settled::Known {
                value: Head::Branch { name, .. },
                at: _,
                stale: _,
            }) => assert_eq!(
                name, &a_value_before,
                "an already-settled cell must keep its value when the deadline sweep runs, not be blanked"
            ),
            other => panic!("expected A's settled value to survive the sweep, got {other:?}"),
        }

        let b_after = after_sweep
            .entities
            .iter()
            .find(|entity| entity.key == key_b)
            .expect("entity b present");
        assert!(matches!(
            b_after.branch.settled(),
            Some(Settled::Unknown(Unknown::TimedOut))
        ));
        assert!(
            !cancel_b.load(Ordering::Acquire),
            "the deadline sweep marks a cell Unknown; it never sets the entity's own \
             cancel flag, since the underlying probe (nonexistent here) is left to keep running"
        );
    }

    /// The deadline sweep must reach a Worktree's outstanding `state` cell the
    /// same way it already reaches `branch` and `default_branch`: asking and
    /// getting nothing back is Unknown, not a cell stuck in-flight forever once
    /// the Generation that would have answered it is gone. A Repo's `state`,
    /// `NotApplicable` from construction and never in flight, must survive the
    /// same sweep untouched, proving the sweep only times out a cell actually
    /// marked in flight rather than blanket-settling every entity's `state` cell.
    #[test]
    fn the_deadline_sweep_times_out_a_worktrees_outstanding_state_but_leaves_a_repos_not_applicable_one_alone()
     {
        let (tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        let worktree_path = root.join("feature-worktree");
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature",
                worktree_path.to_str().expect("utf8 path"),
            ],
        );

        let mut spec = spec(vec![root]);
        spec.generation_deadline = Duration::ZERO;
        let started = Core::start_for_test(spec, Duration::from_secs(3600), tick_rx).discovered();
        let core = started.core;
        // Drained, so launch's own real refresh has already landed on every cell before
        // either `begin_untracked_probe_for_test` call below puts one artificially back in
        // flight: skipping this left a real probe for the same cell free to settle it
        // between that call and the sweep, which turns the sweep's own `is_in_flight`
        // guard (working exactly as designed, since a cell no longer loading is not the
        // sweep's to touch) into a race the assertion below loses however rarely.
        let snapshot = settle_launch(&core);
        let repo_key = snapshot
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Repo))
            .expect("repo entity present")
            .key
            .clone();
        let worktree_key = snapshot
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Worktree))
            .expect("worktree entity present")
            .key
            .clone();

        // Both left mid-flight in a Generation whose (zero) deadline has already
        // elapsed, with no tick sent yet, mirroring how `Core::refresh` begins a
        // Worktree's `state` probe alongside `branch`. The Repo is in flight too
        // (on `branch` only, per the same gate), so the sweep actually reaches
        // it and the guard has something real to prove.
        core.begin_untracked_probe_for_test(&repo_key);
        core.begin_untracked_probe_for_test(&worktree_key);

        tick_tx.send(Instant::now()).expect("send one tick");
        let after_sweep = core.settle();

        let worktree_after = after_sweep
            .entities
            .iter()
            .find(|entity| entity.key == worktree_key)
            .expect("worktree entity present");
        assert!(
            matches!(
                worktree_after.state.settled(),
                Some(Settled::Unknown(Unknown::TimedOut))
            ),
            "expected the outstanding state cell to time out, got {:?}",
            worktree_after.state.settled()
        );

        let repo_after = after_sweep
            .entities
            .iter()
            .find(|entity| entity.key == repo_key)
            .expect("repo entity present");
        assert!(
            matches!(repo_after.state.settled(), Some(Settled::NotApplicable)),
            "a Repo's Not applicable state must survive the sweep untouched, got {:?}",
            repo_after.state.settled()
        );
    }

    /// Criterion 2's "never goes stale on a poll" made behavioural: the dedicated thread's
    /// tick-driven sweep is what a poll is in this codebase today (`spawn_clock_thread` calls
    /// [`sweep_deadline`] on every tick), and it must leave a receipt exactly as it was even
    /// while it is busy timing out a genuinely outstanding Cell on the very same entity.
    #[test]
    fn the_deadline_sweeps_poll_never_touches_an_entitys_action_receipt() {
        let (tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let mut spec = spec(vec![root]);
        spec.generation_deadline = Duration::ZERO;
        let started = Core::start_for_test(spec, Duration::from_secs(3600), tick_rx).discovered();
        let core = started.core;
        // Drained, so the only entry the sweep below finds in flight is this test's own.
        let key = settle_launch(&core).entities[0].key.clone();

        let receipt = crate::entity::ActionReceipt {
            label: Arc::from("reinstall"),
            steps: Arc::from(vec![crate::entity::StepResult {
                label: Arc::from("pnpm install"),
                outcome: crate::entity::StepOutcome::Ok,
                output: Arc::from(&b""[..]),
                elapsed: Duration::from_millis(1),
                elision: None,
                shell: false,
                interactive: false,
            }]),
            skip: None,
            finished_at: Timestamp::now(),
            running: None,
        };
        core.set_last_action_for_test(&key, receipt.clone());

        // Left mid-flight in a Generation whose (zero) deadline has already elapsed, so the
        // sweep this tick triggers has a real Cell to time out on this very entity.
        core.begin_untracked_probe_for_test(&key);
        tick_tx.send(Instant::now()).expect("send one tick");
        let after = core.settle();

        let entity = after
            .entities
            .iter()
            .find(|entity| entity.key == key)
            .expect("entity present");
        assert!(
            matches!(
                entity.branch.settled(),
                Some(Settled::Unknown(Unknown::TimedOut))
            ),
            "sanity check: the sweep must have actually timed out the in-flight cell, got {:?}",
            entity.branch.settled()
        );
        assert_eq!(entity.last_action, Some(receipt));
    }

    /// Cancellation observed before a probe's very first read stops it from ever
    /// opening the repository at all, proven behaviourally rather than by
    /// re-reading the flag: a path that does not exist would settle as
    /// `Failed(Open(_))` if the open call actually ran, so getting `None` back
    /// instead is only possible if the read never started. This is the honest
    /// limit of what phase A can prove: `git::head_shape` is one syscall with no
    /// interruption point mid-read, so cancellation here stops work that has not
    /// started rather than work already running. [`classify_status_result_drops_an_error_once_cancel_reads_true`]
    /// covers the genuinely interruptible phase this crate now has.
    #[test]
    fn a_cancelled_probe_never_opens_the_repository_at_all() {
        let cancel = AtomicBool::new(true);

        let outcome = probe_branch(
            Path::new("/nonexistent/nowhere-at-all"),
            None,
            Kind::Repo,
            &cancel,
        );

        assert!(
            outcome.is_none(),
            "a probe observing cancellation before its first read must do no work \
             at all, not attempt the read and fail having tried it"
        );
    }

    /// Phase C's own cancellation shape, distinct from phase A and B's "before the read
    /// starts" check: gix can report a genuinely mid-read cancellation as an `Err`
    /// (`dirty_counts_threads_the_cancel_flag_into_gix` in `git.rs` proves the flag actually
    /// reaches gix, which is what makes that `Err` possible at all), and this test covers the
    /// half that lives here, that `classify_status_result` folds that error back to `None`
    /// rather than `Settled::Failed` once `cancel` reads `true`, per ADR 0013's "interrupted
    /// work becomes Unknown rather than Failed". A mutation that dropped the `cancel`-aware
    /// arm (always settling `Failed` on any error, the way the cheaper phases' own errors do)
    /// fails this directly.
    #[test]
    fn classify_status_result_drops_an_error_once_cancel_reads_true() {
        let cancel = AtomicBool::new(true);

        let outcome = classify_status_result(
            Err(crate::git::ProbeError::Status(Arc::from("boom"))),
            &cancel,
        );

        assert!(
            outcome.is_none(),
            "an error alongside a cancel flag already set must read as cancelled, not \
             Failed, got {outcome:?}"
        );
    }

    /// The other side of the same fold: an error with `cancel` still `false` is a genuine
    /// failure and must settle `Failed`, not be silently dropped the way a cancelled read is.
    #[test]
    fn classify_status_result_settles_failed_when_cancel_never_fired() {
        let cancel = AtomicBool::new(false);

        let outcome = classify_status_result(
            Err(crate::git::ProbeError::Status(Arc::from("boom"))),
            &cancel,
        );

        assert!(
            matches!(outcome, Some(Settled::Failed(git::ProbeError::Status(_)))),
            "a genuine error with no cancellation must settle Failed, got {outcome:?}"
        );
    }

    /// gix polls `should_interrupt` per index entry rather than before every read, so a walk
    /// short enough to finish between checks (or with nothing left to check against) can
    /// complete and return `Ok` even though `cancel` was set part way through it. Settling
    /// that `Ok` anyway would let a cancelled generation write a value, exactly the outcome
    /// [refresh.md's "Cancellation"](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)
    /// says cancellation prevents. `classify_status_result` must re-check the same flag it
    /// owns on the `Ok` arm too, not only on `Err`, and drop the value the same way a
    /// cancelled `Err` is already dropped.
    #[test]
    fn classify_status_result_drops_an_ok_once_cancel_reads_true() {
        let cancel = AtomicBool::new(true);

        let outcome = classify_status_result(Ok(DirtyCounts::default()), &cancel);

        assert!(
            outcome.is_none(),
            "an Ok value that raced ahead of a cancel flag now set must read as cancelled, \
             not be settled Known, got {outcome:?}"
        );
    }

    /// The other side of the same fold: an `Ok` with `cancel` still `false` is a genuine
    /// completed read and must settle `Known`, not be silently dropped.
    #[test]
    fn classify_status_result_settles_known_when_cancel_never_fired() {
        let cancel = AtomicBool::new(false);
        let counts = DirtyCounts {
            modified: 1,
            untracked: 2,
            deleted: 3,
        };

        let outcome = classify_status_result(Ok(counts), &cancel);

        assert!(
            matches!(
                outcome,
                Some(Settled::Known {
                    value,
                    at: _,
                    stale: _
                }) if value == counts
            ),
            "a genuine completed read with no cancellation must settle Known, got {outcome:?}"
        );
    }

    /// The defining behaviour: a linked Worktree shares its parent's object store
    /// and remotes, but `Core` must still surface it as its own row rather than
    /// folding it into the Repo it is attached to. A real `git worktree add` is run
    /// against a genuine parent so the proof covers git's actual on-disk shape, not
    /// a hand-built stand-in for it.
    #[test]
    fn a_linked_worktree_is_its_own_entity_and_never_doubles_as_a_repo() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        let worktree_path = root.join("feature-worktree");
        let status = Command::new("git")
            .arg("-C")
            .arg(&parent)
            .args([
                "worktree",
                "add",
                "-b",
                "feature",
                worktree_path.to_str().expect("utf8 path"),
            ])
            .status()
            .expect("run git worktree add");
        assert!(status.success());

        let core = Core::start_discovered(spec(vec![root]));
        let snapshot = core.snapshot();

        assert_eq!(
            snapshot.entities.len(),
            2,
            "expected the parent plus one Worktree, not two Repos"
        );
        let repo_count = snapshot
            .entities
            .iter()
            .filter(|entity| matches!(entity.kind, Kind::Repo))
            .count();
        let worktree_count = snapshot
            .entities
            .iter()
            .filter(|entity| matches!(entity.kind, Kind::Worktree))
            .count();
        assert_eq!(
            repo_count, 1,
            "the parent must be counted as exactly one Repo"
        );
        assert_eq!(
            worktree_count, 1,
            "the linked worktree must be counted as exactly one Worktree"
        );

        let worktree_entity = snapshot
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Worktree))
            .expect("worktree entity present");
        let repo_entity = snapshot
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Repo))
            .expect("repo entity present");
        assert_eq!(worktree_entity.common_dir, repo_entity.common_dir);

        // Each carries its own branch: the parent stayed on its default branch and
        // the worktree checked out `feature`.
        let repo_branch = core.probe_now(&repo_entity.key);
        let worktree_branch = core.probe_now(&worktree_entity.key);
        match (
            repo_branch.branch.settled(),
            worktree_branch.branch.settled(),
        ) {
            (
                Some(Settled::Known {
                    value:
                        Head::Branch {
                            name: repo_name, ..
                        },
                    at: _,
                    stale: _,
                }),
                Some(Settled::Known {
                    value:
                        Head::Branch {
                            name: worktree_name,
                            ..
                        },
                    at: _,
                    stale: _,
                }),
            ) => {
                assert_ne!(repo_name, worktree_name);
                assert_eq!(&**worktree_name, "feature");
            }
            other => panic!("expected both entities to read an attached branch, got {other:?}"),
        }
    }

    /// End-to-end proof that `state` is actually wired into a real Generation:
    /// a linked Worktree whose branch is an ancestor of the default branch reads
    /// `Merged` after a real `refresh`, not merely in `landing`'s own unit tests.
    #[test]
    fn a_worktrees_branch_that_is_an_ancestor_of_the_default_branch_reads_merged_after_a_refresh() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        git(
            &parent,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let sha = head_sha(&parent);
        git(&parent, &["update-ref", "refs/remotes/origin/main", &sha]);
        let worktree_path = root.join("feature-worktree");
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature",
                worktree_path.to_str().expect("utf8 path"),
            ],
        );

        let core = Core::start_discovered(spec(vec![root]));
        let keys: Vec<EntityKey> = core
            .snapshot()
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();

        core.refresh(&keys);
        let settled = core.settle();

        let worktree_entity = settled
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Worktree))
            .expect("worktree entity present");
        assert!(
            matches!(
                worktree_entity.state.settled(),
                Some(Settled::Known {
                    value: WorktreeState::Merged,
                    at: _,
                    stale: _
                })
            ),
            "expected the worktree, at the same commit as the default branch, to read Merged, got {:?}",
            worktree_entity.state.settled()
        );
    }

    /// The squash merge this whole ticket is named for, proven end to end
    /// through a real `refresh`: `feature`'s two commits are squashed into one
    /// commit on the default branch, so ancestry cannot see it (`feature`'s tip
    /// never becomes an ancestor), and only patch equivalence can. Its upstream
    /// tracking ref still resolves, matching the moment right after a squash
    /// merge and before the next prune removes it, which is what routes this
    /// entity through `Outstanding` into the second pass rather than settling
    /// `Gone` at the first.
    #[test]
    fn a_squash_merged_worktree_branch_reads_merged_after_a_refresh() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        git(
            &parent,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let worktree_path = root.join("feature-worktree");
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature",
                worktree_path.to_str().expect("utf8 path"),
            ],
        );
        fs::write(worktree_path.join("a.txt"), "one\n").expect("write a.txt");
        git(&worktree_path, &["add", "a.txt"]);
        git(&worktree_path, &["commit", "-m", "add a"]);
        fs::write(worktree_path.join("b.txt"), "two\n").expect("write b.txt");
        git(&worktree_path, &["add", "b.txt"]);
        git(&worktree_path, &["commit", "-m", "add b"]);
        let feature_sha = head_sha(&worktree_path);

        // Squashed into the parent's own checkout, which is what the default
        // branch resolves against.
        git(&parent, &["merge", "--squash", "feature"]);
        git(&parent, &["commit", "-m", "squashed feature"]);
        let main_sha = head_sha(&parent);
        git(
            &parent,
            &["update-ref", "refs/remotes/origin/main", &main_sha],
        );

        // `feature`'s own upstream, still resolving: the moment before a prune
        // removes it.
        git(&parent, &["config", "branch.feature.remote", "origin"]);
        git(
            &parent,
            &["config", "branch.feature.merge", "refs/heads/feature"],
        );
        git(
            &parent,
            &["update-ref", "refs/remotes/origin/feature", &feature_sha],
        );

        let core = Core::start_discovered(spec(vec![root]));
        let keys: Vec<EntityKey> = core
            .snapshot()
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();

        core.refresh(&keys);
        let settled = core.settle();

        let worktree_entity = settled
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Worktree))
            .expect("worktree entity present");
        assert!(
            matches!(
                worktree_entity.state.settled(),
                Some(Settled::Known {
                    value: WorktreeState::Merged,
                    at: _,
                    stale: _
                })
            ),
            "expected a squash-merged worktree branch to read Merged, got {:?}",
            worktree_entity.state.settled()
        );
    }

    /// Proves the negative the state cell alone cannot: patch equivalence's
    /// expensive scan must never even start for an entity ancestry already
    /// settled. A Worktree whose branch is an ancestor of the default branch
    /// settles `Merged` at the first pass, so the only common dir in this test
    /// must show zero scans; a `state`-only assertion would still pass an
    /// implementation that ran the second pass over every entity and discarded
    /// whichever answer ancestry had already provided.
    #[test]
    fn patch_equivalence_never_runs_for_an_entity_ancestry_already_settled() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        git(
            &parent,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let sha = head_sha(&parent);
        git(&parent, &["update-ref", "refs/remotes/origin/main", &sha]);
        let worktree_path = root.join("feature-worktree");
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature",
                worktree_path.to_str().expect("utf8 path"),
            ],
        );

        let (core, launched) = started_and_settled(spec(vec![root]));
        let keys: Vec<EntityKey> = launched
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();

        core.refresh(&keys);
        let settled = core.settle();

        let worktree_entity = settled
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Worktree))
            .expect("worktree entity present");
        assert!(
            matches!(
                worktree_entity.state.settled(),
                Some(Settled::Known {
                    value: WorktreeState::Merged,
                    at: _,
                    stale: _
                })
            ),
            "expected ancestry alone to settle Merged here, got {:?}",
            worktree_entity.state.settled()
        );
        assert_eq!(
            core.patch_identity_reads_for_test(),
            0,
            "ancestry already settled this entity, so patch equivalence's shared \
             scan must never run for its common dir at all"
        );
    }

    /// [`patch_equivalence`]'s own unit test proves the module itself writes no
    /// loose object; this proves the same through the real dispatch path a
    /// user's refresh actually runs, so a write introduced in `core.rs`'s glue
    /// rather than in the module would be caught too. Reuses the squash-merge
    /// fixture that routes a real `Core::refresh` into patch equivalence's
    /// second pass, and counts loose objects in the parent repository, since a
    /// linked Worktree shares its object database with its common dir.
    #[test]
    fn a_full_refresh_reaching_patch_equivalence_writes_no_loose_objects() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        git(
            &parent,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let worktree_path = root.join("feature-worktree");
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature",
                worktree_path.to_str().expect("utf8 path"),
            ],
        );
        fs::write(worktree_path.join("a.txt"), "one\n").expect("write a.txt");
        git(&worktree_path, &["add", "a.txt"]);
        git(&worktree_path, &["commit", "-m", "add a"]);
        fs::write(worktree_path.join("b.txt"), "two\n").expect("write b.txt");
        git(&worktree_path, &["add", "b.txt"]);
        git(&worktree_path, &["commit", "-m", "add b"]);
        let feature_sha = head_sha(&worktree_path);

        git(&parent, &["merge", "--squash", "feature"]);
        git(&parent, &["commit", "-m", "squashed feature"]);
        let main_sha = head_sha(&parent);
        git(
            &parent,
            &["update-ref", "refs/remotes/origin/main", &main_sha],
        );
        git(&parent, &["config", "branch.feature.remote", "origin"]);
        git(
            &parent,
            &["config", "branch.feature.merge", "refs/heads/feature"],
        );
        git(
            &parent,
            &["update-ref", "refs/remotes/origin/feature", &feature_sha],
        );

        let core = Core::start_discovered(spec(vec![root]));
        let keys: Vec<EntityKey> = core
            .snapshot()
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();

        let before = loose_object_count(&parent);
        core.refresh(&keys);
        let settled = core.settle();
        let after = loose_object_count(&parent);

        let worktree_entity = settled
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Worktree))
            .expect("worktree entity present");
        assert!(
            matches!(
                worktree_entity.state.settled(),
                Some(Settled::Known {
                    value: WorktreeState::Merged,
                    at: _,
                    stale: _
                })
            ),
            "expected this refresh to actually reach patch equivalence and settle \
             Merged, got {:?}",
            worktree_entity.state.settled()
        );
        assert_eq!(
            before, after,
            "a full refresh reaching patch equivalence must never write a loose \
             object to the repository"
        );
    }

    /// With patch equivalence now built, a diverged attached branch with a live
    /// upstream no longer stays outstanding forever: once ancestry says no,
    /// the second pass gets a real answer, and genuinely unmerged work (a real
    /// file change with no counterpart on the default branch, not merely an
    /// empty marker commit) settles `Active` rather than `Gone` or `Merged`,
    /// proven through the real dispatch path rather than either pass in
    /// isolation.
    #[test]
    fn a_diverged_worktree_with_a_live_upstream_and_genuinely_unmerged_work_settles_active_after_a_refresh()
     {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        let base_sha = head_sha(&parent);
        git(
            &parent,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        git(
            &parent,
            &["update-ref", "refs/remotes/origin/main", &base_sha],
        );
        let worktree_path = root.join("feature-worktree");
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature",
                worktree_path.to_str().expect("utf8 path"),
            ],
        );
        // Unmerged work: a real file change feature has that main (and
        // origin/main) do not, and that main never gains by any other means.
        fs::write(worktree_path.join("feature.txt"), "unmerged work\n").expect("write feature.txt");
        git(&worktree_path, &["add", "feature.txt"]);
        git(&worktree_path, &["commit", "-m", "unmerged"]);
        let feature_sha = head_sha(&worktree_path);
        // `feature`'s own upstream, live: the common dir's shared config and refs
        // make this visible from the worktree's own probe too.
        git(&parent, &["config", "branch.feature.remote", "origin"]);
        git(
            &parent,
            &["config", "branch.feature.merge", "refs/heads/feature"],
        );
        git(
            &parent,
            &["update-ref", "refs/remotes/origin/feature", &feature_sha],
        );

        let core = Core::start_discovered(spec(vec![root]));
        let keys: Vec<EntityKey> = core
            .snapshot()
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();

        core.refresh(&keys);
        let settled = core.settle();

        let worktree_entity = settled
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Worktree))
            .expect("worktree entity present");
        assert!(
            matches!(
                worktree_entity.state.settled(),
                Some(Settled::Known {
                    value: WorktreeState::Active,
                    at: _,
                    stale: _
                })
            ),
            "expected genuinely unmerged work with a live upstream to settle Active, got {:?}",
            worktree_entity.state.settled()
        );
    }

    /// `CoreSpec::show_submodules` gates probing and dispatch, never Snapshot membership:
    /// a discovered Submodule is always part of the snapshot `Core::start` builds, shown or
    /// not, because the module pass that finds it always runs
    /// ([discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)'s
    /// "the pass always runs, so Submodules are always known"). Built with the default,
    /// hidden reading precisely to prove that.
    #[test]
    fn a_submodule_is_in_the_snapshot_even_though_hidden_by_the_default_preference() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        fs::write(
            parent.join(".gitmodules"),
            "[submodule \"lib\"]\n\tpath = vendor/lib\n\turl = https://example.com/lib.git\n",
        )
        .expect("write .gitmodules");
        fs::create_dir_all(parent.join("vendor").join("lib")).expect("create submodule dir");

        let core = Core::start_discovered(spec(vec![root]));
        let snapshot = core.snapshot();

        assert!(
            snapshot
                .entities
                .iter()
                .any(|entity| matches!(entity.kind, Kind::Submodule)),
            "a discovered Submodule must be in the snapshot even while show_submodules is off"
        );
    }

    /// A Submodule's `state` and `base` cells must stay `Unknown` through a real
    /// refresh cycle, not only at construction:
    /// [`EntityState::probes_state`] and [`EntityState::probes_base`] are what
    /// stop `refresh`'s dispatch from ever calling `landing::probe` or
    /// `probe_base` for it again. The Submodule here is a real, valid repository
    /// with a real remote and a resolvable default branch ahead of its own tip
    /// (in fact an ancestor of it, so ancestry alone would prove `Merged`), so if
    /// either gate were missing this would settle a genuine live answer rather
    /// than merely fail to open.
    #[test]
    fn a_submodules_state_and_base_cells_stay_unknown_through_a_real_refresh() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        fs::write(
            parent.join(".gitmodules"),
            "[submodule \"lib\"]\n\tpath = vendor/lib\n\turl = https://example.com/lib.git\n",
        )
        .expect("write .gitmodules");
        let submodule = parent.join("vendor").join("lib");
        init_repo_with_a_commit(&submodule);
        git(
            &submodule,
            &["remote", "add", "origin", "https://example.invalid/lib.git"],
        );
        let root_sha = head_sha(&submodule);
        git(&submodule, &["commit", "--allow-empty", "-m", "second"]);
        let tip_sha = head_sha(&submodule);
        git(&submodule, &["reset", "--hard", &root_sha]);
        git(
            &submodule,
            &["update-ref", "refs/remotes/origin/main", &tip_sha],
        );

        // Shown, so the explicit `refresh` below actually dispatches a probe against it:
        // this test is about `probes_base`'s own gate, not about `show_submodules`'s.
        let mut core_spec = spec(vec![root]);
        core_spec.show_submodules = true;
        let core = Core::start_discovered(core_spec);
        let key = core
            .snapshot()
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Submodule))
            .expect("a discovered Submodule")
            .key
            .clone();

        core.refresh(std::slice::from_ref(&key));
        let settled = core.settle();
        let submodule_entity = settled
            .entities
            .iter()
            .find(|entity| entity.key == key)
            .expect("the Submodule entity");

        assert!(
            matches!(
                submodule_entity.base.settled(),
                Some(Settled::Unknown(Unknown::NoDefaultBranch))
            ),
            "expected a Submodule's base to stay Unknown through a real refresh, \
             got {:?}",
            submodule_entity.base.settled()
        );
        assert!(
            matches!(
                submodule_entity.state.settled(),
                Some(Settled::Unknown(Unknown::NoDefaultBranch))
            ),
            "expected a Submodule's state to stay Unknown through a real refresh, \
             rather than settling Merged off an untrusted default branch, got {:?}",
            submodule_entity.state.settled()
        );
    }

    /// [discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)'s
    /// "The Submodule row" fixes `name` as "the submodule path"; this proves the fact lands
    /// on the real `EntityState` `Core::start` builds, not only on the intermediate
    /// `DiscoveredEntity` `discovery::tests` already covers.
    #[test]
    fn a_submodules_entity_name_is_its_relative_path_not_its_basename() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        fs::write(
            parent.join(".gitmodules"),
            "[submodule \"lib\"]\n\tpath = vendor/lib\n\turl = https://example.com/lib.git\n",
        )
        .expect("write .gitmodules");
        fs::create_dir_all(parent.join("vendor").join("lib")).expect("create submodule dir");

        let core = Core::start_discovered(spec(vec![root]));
        let submodule = core
            .snapshot()
            .entities
            .into_iter()
            .find(|entity| matches!(entity.kind, Kind::Submodule))
            .expect("a discovered Submodule");

        assert_eq!(
            submodule.name.as_ref(),
            "vendor/lib",
            "expected the declared relative path, not the basename `lib`"
        );
    }

    /// AC3's negative case: an uninitialised Submodule (never `git submodule update
    /// --init`-ed, so its own path holds no `.git` at all) settles every cell a probe would
    /// otherwise open a repository for `Unknown(SubmoduleUninitialized)`, never `Failed`,
    /// because not being there yet is the normal, expected shape
    /// ([discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)'s
    /// "An uninitialised Submodule is a row with every cell blank and `?` in the gutter").
    /// The row still exists (the assertion below finds it), so the row itself is not the
    /// mutation this covers; `probe_branch`/`probe_sync`/`probe_status`'s classification is.
    #[test]
    fn an_uninitialised_submodules_probed_cells_settle_unknown_not_failed() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        fs::write(
            parent.join(".gitmodules"),
            "[submodule \"lib\"]\n\tpath = vendor/lib\n\turl = https://example.com/lib.git\n",
        )
        .expect("write .gitmodules");
        // Deliberately never initialised: no directory at all at the declared path, the
        // shape a plain `git clone` (no `--recurse-submodules`) leaves behind.

        let mut core_spec = spec(vec![root]);
        core_spec.show_submodules = true;
        let core = Core::start_discovered(core_spec);
        let key = core
            .snapshot()
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Submodule))
            .expect("a discovered Submodule")
            .key
            .clone();

        core.refresh(std::slice::from_ref(&key));
        let settled = core.settle();
        let submodule = settled
            .entities
            .iter()
            .find(|entity| entity.key == key)
            .expect("the Submodule entity");

        assert!(
            matches!(
                submodule.branch.settled(),
                Some(Settled::Unknown(Unknown::SubmoduleUninitialized))
            ),
            "expected branch to settle Unknown(SubmoduleUninitialized), got {:?}",
            submodule.branch.settled()
        );
        assert!(
            matches!(
                submodule.sync.settled(),
                Some(Settled::Unknown(Unknown::SubmoduleUninitialized))
            ),
            "expected sync to settle Unknown(SubmoduleUninitialized), got {:?}",
            submodule.sync.settled()
        );
        assert!(
            matches!(
                submodule.dirty.settled(),
                Some(Settled::Unknown(Unknown::SubmoduleUninitialized))
            ),
            "expected dirty to settle Unknown(SubmoduleUninitialized), got {:?}",
            submodule.dirty.settled()
        );
        assert_eq!(
            summary(submodule),
            RowSummary::Unknown,
            "expected the row's own gutter fold to read Unknown, not Failed"
        );
    }

    /// AC4's cost half: `show_submodules` off means a dispatched Generation never even
    /// opens a shown Submodule's own repository, while a shown one right beside it is
    /// probed normally in the very same Generation. Both submodules are real, valid
    /// repositories, so a probed-but-ignored implementation and a never-dispatched one are
    /// distinguishable only by whether the hidden one's cells ever leave "never settled".
    #[test]
    fn dispatch_skips_probing_a_hidden_submodule_while_probing_the_same_one_shown() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        fs::write(
            parent.join(".gitmodules"),
            "[submodule \"lib\"]\n\tpath = vendor/lib\n\turl = https://example.com/lib.git\n",
        )
        .expect("write .gitmodules");
        init_repo_with_a_commit(&parent.join("vendor").join("lib"));

        // `spec`'s own default: `show_submodules: false`.
        let core = Core::start_discovered(spec(vec![root]));
        let key = core
            .snapshot()
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Submodule))
            .expect("a discovered Submodule")
            .key
            .clone();

        // First Generation, dispatched while hidden: `dispatch` must skip it outright.
        core.refresh(std::slice::from_ref(&key));
        let while_hidden = core.settle();
        let hidden_entity = while_hidden
            .entities
            .iter()
            .find(|entity| entity.key == key)
            .expect("submodule entity");
        assert!(
            hidden_entity.branch.settled().is_none(),
            "a Submodule dispatched while hidden must never even reach probe_branch, \
             so its cell stays never-settled rather than holding any value at all, got {:?}",
            hidden_entity.branch.settled()
        );

        // Toggled live, no rebuild, then the very same key is handed to `refresh` again:
        // the second Generation is what proves the flag narrows the work rather than the
        // key, since nothing about the key or the `Core` itself changed in between.
        core.set_show_submodules(true);
        core.refresh(std::slice::from_ref(&key));
        let while_shown = core.settle();
        let shown_entity = while_shown
            .entities
            .iter()
            .find(|entity| entity.key == key)
            .expect("submodule entity");
        assert!(
            matches!(
                shown_entity.branch.settled(),
                Some(Settled::Known {
                    value: _,
                    at: _,
                    stale: _
                })
            ),
            "expected the same Submodule's branch to settle a real value once shown, got {:?}",
            shown_entity.branch.settled()
        );
    }

    /// AC4's other half: toggling the live preference is free. Proven the same way
    /// `reload_with_the_same_active_set_leaves_discovery_and_its_generation_untouched`
    /// proves a same-Set reload never rebuilds `Core`: a Generation counter a rediscovery
    /// or a dispatch would have to move, checked before and after the toggle with nothing
    /// else run in between.
    #[test]
    fn toggling_show_submodules_starts_no_new_generation_and_dispatches_nothing() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("repo-a"));

        // Drained, so the two readings below differ only by whatever the toggles did.
        let (core, launched) = started_and_settled(spec(vec![root]));
        let before = launched.generation;
        let dispatched_before = core.dispatch_log_for_test();
        assert!(
            !dispatched_before.is_empty(),
            "launch dispatched nothing, so the comparison below would hold however much a \
             toggle dispatched"
        );

        core.set_show_submodules(true);
        core.set_show_submodules(false);

        assert_eq!(
            core.snapshot().generation,
            before,
            "toggling show_submodules must start no Generation of its own"
        );
        assert_eq!(
            core.dispatch_log_for_test(),
            dispatched_before,
            "toggling show_submodules must dispatch no probe of its own, leaving the last \
             Generation's own log exactly as it found it"
        );
    }

    /// AC5: a `.gitmodules` parse failure marks the parent Repo's row Failed whether or not
    /// Submodules are shown, because the module pass that finds the failure runs either way
    /// ([discovery.md](https://github.com/paulchiu/repon/blob/main/docs/spec/discovery.md)'s
    /// "Failure": "The mark appears whether or not `show_submodules` is on, because the pass
    /// ran either way"). `spec`'s own default is already `show_submodules: false`, which is
    /// what makes this a real proof rather than a coincidence of some other default.
    #[test]
    fn a_malformed_gitmodules_file_still_fails_the_parent_while_submodules_are_hidden() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        fs::write(
            parent.join(".gitmodules"),
            "[submodule \"lib\"\n\tpath = lib\n",
        )
        .expect("write malformed .gitmodules");

        let core = Core::start_discovered(spec(vec![root]));
        let key = core
            .snapshot()
            .entities
            .iter()
            .find(|entity| entity.key.path() == parent)
            .expect("the parent entity")
            .key
            .clone();
        // The fold reads Failed only once the row holds some probed value at all: a
        // Generation's own dispatch is what proves the mark survives real probing, not
        // merely discovery's own construction-time diagnostics write.
        core.refresh(std::slice::from_ref(&key));
        let settled = core.settle();
        let parent_entity = settled
            .entities
            .iter()
            .find(|entity| entity.key == key)
            .expect("the parent entity");

        assert_eq!(
            summary(parent_entity),
            RowSummary::Failed,
            "expected the parent to fold Failed even with Submodules hidden"
        );
        assert!(
            parent_entity.diagnostics.gitmodules_failed.is_some(),
            "expected the failure recorded in Diagnostics for the detail pane"
        );
        assert!(
            !settled
                .entities
                .iter()
                .any(|entity| matches!(entity.kind, Kind::Submodule)),
            "an unparseable .gitmodules yields no Submodule rows for that parent"
        );
    }

    #[test]
    fn count_matches_a_plain_discoverys_entity_count() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("one"));
        init_repo_with_a_commit(&root.join("two"));

        let set = SetSpec {
            name: "test".to_string(),
            roots: vec![root],
            include: Vec::new(),
            exclude: Vec::new(),
        };

        assert_eq!(discovery::count(&set), 2);
    }

    #[test]
    fn the_slow_discovery_watcher_warns_with_the_count_reached_and_the_roots() {
        let progress = Arc::new(AtomicUsize::new(42));
        let finished = Arc::new(AtomicBool::new(false));
        let roots = vec![PathBuf::from("/repos/a"), PathBuf::from("/repos/b")];

        let warning = watch_for_slow_discovery(progress, finished, roots, Duration::from_millis(1));

        let message = warning.expect("a walk that has not finished should warn");
        assert!(message.contains("42"));
        assert!(message.contains("/repos/a"));
        assert!(message.contains("/repos/b"));
    }

    #[test]
    fn the_slow_discovery_watcher_is_silent_once_the_walk_has_already_finished() {
        let progress = Arc::new(AtomicUsize::new(7));
        let finished = Arc::new(AtomicBool::new(true));

        let warning =
            watch_for_slow_discovery(progress, finished, Vec::new(), Duration::from_millis(1));

        assert!(warning.is_none());
    }

    /// The same watcher `start_internal` wires in: on a fast, already-finished
    /// walk (the common case), joining its handle proves it ran and recorded no
    /// warning, exercised through `Core::start` itself rather than in isolation.
    /// `warn_after` is one second, the real production threshold, rather than a
    /// margin picked for speed: a one-repository walk finishes orders of
    /// magnitude faster than that even on a loaded machine, so this proves the
    /// fast path without racing a real walk the way a millisecond threshold did.
    #[test]
    fn a_fast_discovery_leaves_no_warning_once_the_watcher_has_run() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("repo"));
        let (_tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();

        let started =
            Core::start_for_test(spec(vec![root]), Duration::from_secs(1), tick_rx).discovered();
        started
            .discovery_watcher
            .join()
            .expect("watcher thread should not panic");

        assert!(started.core.discovery_warning().is_none());
    }

    /// A [`DiscoveryGate`] starting `open`, and the channel that opens it once the call
    /// under test has returned.
    ///
    /// The gate is what makes "before its walk has run" a rendezvous rather than a
    /// margin. The channel is what makes an implementation that walks inline fail its
    /// assertion instead of wedging the run: nothing else would ever open the gate for
    /// it, so the backstop below is its only release, and the assertion then reports.
    fn gate_opened_on_signal(open: bool) -> (DiscoveryGate, Sender<()>, JoinHandle<()>) {
        let gate: DiscoveryGate = Arc::new((Mutex::new(open), Condvar::new()));
        let (returned_tx, returned_rx) = crossbeam_channel::bounded::<()>(1);
        let opener = thread::spawn({
            let gate = Arc::clone(&gate);
            move || {
                let _ = returned_rx.recv_timeout(crate::liveness::BACKSTOP);
                set_discovery_gate(&gate, true);
            }
        });
        (gate, returned_tx, opener)
    }

    /// Criterion 1: `Core::start` returns before discovery has finished, and the rows
    /// land when discovery does.
    ///
    /// The walk is held closed before the `Core` is built, so the empty table below is
    /// the table `start` actually returned rather than one this test raced it to. Joining
    /// the harness's own `initial_discovery` handle afterwards is the rendezvous that says
    /// the walk landed: no sleep and no poll on either side.
    ///
    /// The row's phase C is held from before the walk is let go, so the cell read below
    /// is read at a point this test fixes rather than at whatever point launch's own
    /// Generation happened to have reached.
    #[test]
    fn start_returns_against_an_empty_table_and_the_rows_land_when_discovery_does() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let (_tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();
        let (gate, start_returned, opener) = gate_opened_on_signal(false);

        let started = Core::start_for_test_gated(
            spec(vec![root]),
            Duration::from_secs(3600),
            discovery::ABANDON_AFTER,
            tick_rx,
            Some(Arc::clone(&gate)),
        );
        let at_start = started.core.snapshot();
        let key = EntityKey::new(Arc::from(repo.as_path()));
        started.core.hold_phase_c_for_test(&key);
        start_returned.send(()).expect("the opener is listening");
        opener.join().expect("the opener thread should not panic");
        let started = started.discovered();

        assert!(
            at_start.entities.is_empty(),
            "`Core::start` must return before discovery has finished, against the empty \
             table a consumer draws its first frame from, got {:?}",
            at_start
                .entities
                .iter()
                .map(|entity| entity.name.to_string())
                .collect::<Vec<_>>()
        );

        let landed = started.core.snapshot();
        assert_eq!(
            landed
                .entities
                .iter()
                .map(|entity| entity.name.to_string())
                .collect::<Vec<_>>(),
            vec!["repo".to_string()],
            "the row must land on the table as soon as discovery does"
        );
        assert!(
            landed.entities[0].dirty.settled().is_none() && landed.entities[0].dirty.is_in_flight(),
            "discovery lands the row alone: launch's own Generation is already covering it \
             and its Cells stay unsettled until that Generation answers, which is what the \
             spinner sits behind"
        );

        started.core.release_phase_c_for_test(&key);
        started.core.wait_phase_c_finished_for_test(&key);
    }

    /// Criterion 2: a Generation that resolves its own order after its own discovery
    /// covers every row that walk found, including the ones the caller could not have
    /// named, and fills their Cells.
    ///
    /// `refresh_all` rather than `refresh`, because a caller that has just discarded the
    /// old Set's rows has no key to order by; the row below is discovered by this
    /// Generation's own walk and probed by the same Generation. Named by its order after
    /// launch's own Generation rather than by a number.
    #[test]
    fn refresh_all_covers_every_row_its_own_discovery_found() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("repo"));

        let (core, launched) = started_and_settled(spec(vec![root.clone()]));
        assert_eq!(
            launched
                .entities
                .iter()
                .map(|entity| entity.name.to_string())
                .collect::<Vec<_>>(),
            vec!["repo".to_string()],
            "launch's own walk must have landed and covered exactly the one row that \
             existed when it ran"
        );
        // Created after that walk finished, so this row exists in no snapshot the caller
        // could have read: only a Generation that resolves its own order after its own
        // discovery reaches it.
        init_repo_with_a_commit(&root.join("late"));

        assert_eq!(
            core.refresh_all(),
            launched.generation.successor(),
            "`refresh_all` must be the Generation immediately after the one already on the \
             table"
        );
        let settled = core.settle();

        let mut named: Vec<String> = settled
            .entities
            .iter()
            .filter(|entity| entity.branch.settled().is_some())
            .map(|entity| entity.name.to_string())
            .collect();
        named.sort();
        assert_eq!(
            named,
            vec!["late".to_string(), "repo".to_string()],
            "the Generation must cover every row its own discovery found, including one the \
             caller had no key for"
        );
    }

    /// Criterion 3: `r`, focus gained and resume all reach `Core::refresh`, and it
    /// returns before its own Generation's discovery has run, so none of them holds the
    /// event loop for the length of a walk.
    ///
    /// `late` is created after the first walk has already finished, so only this
    /// `refresh`'s own walk could ever find it: its absence from the table `refresh`
    /// returned against is what says that walk had not run. Opening the gate afterwards
    /// lets the same Generation finish, which is what proves the work was deferred rather
    /// than dropped.
    #[test]
    fn refresh_returns_before_its_own_generations_discovery_has_run() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("repo"));
        let (_tick_tx, tick_rx) = crossbeam_channel::unbounded::<Instant>();
        let (gate, walk_may_run, opener) = gate_opened_on_signal(true);

        let started = Core::start_for_test_gated(
            spec(vec![root.clone()]),
            Duration::from_secs(3600),
            discovery::ABANDON_AFTER,
            tick_rx,
            Some(Arc::clone(&gate)),
        )
        .discovered();
        let core = started.core;
        // Drained, so the settle-gate reading below is this `refresh`'s alone.
        let launched = settle_launch(&core);
        let keys: Vec<EntityKey> = launched
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();
        init_repo_with_a_commit(&root.join("late"));

        set_discovery_gate(&gate, false);
        let generation = core.refresh(&keys);
        let while_held = core.snapshot();
        let dispatched_while_held = core.settle_gate_count_for_test();
        walk_may_run.send(()).expect("the opener is listening");
        opener.join().expect("the opener thread should not panic");

        assert_eq!(
            generation,
            launched.generation.successor(),
            "`refresh` must return its own Generation's number, the one immediately after \
             the table's, before that Generation has done any of its work"
        );
        assert!(
            !while_held
                .entities
                .iter()
                .any(|entity| &*entity.name == "late"),
            "`refresh` must return before its own Generation's walk has run, so a Repo \
             created after the previous walk is not on the table it returned against"
        );
        assert_eq!(
            dispatched_while_held, 0,
            "`refresh` returned before its Generation reached the table at all, so nothing \
             is dispatched yet"
        );

        core.wait_dispatched_for_test();
        let settled = core.settle();

        assert!(
            settled
                .entities
                .iter()
                .any(|entity| &*entity.name == "late"),
            "the deferred Generation must still run its own walk once it is let through: \
             deferred, never dropped"
        );
    }

    /// The turnstile's whole claim: a Generation reserved second cannot reach the table
    /// before the one reserved first, whatever the two threads' own scheduling does.
    ///
    /// Without it a `refresh` whose walk finished quickly could insert its in-flight
    /// entries ahead of an older Generation's, leaving the older one to cancel the newer
    /// one and record itself as the live one, which is
    /// [refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
    /// "Supersession" read backwards. The later ticket is taken on this thread, so it can
    /// only ever record itself after the earlier body has recorded and released; an
    /// implementation that did not wait would record the later one first.
    #[test]
    fn a_dispatch_body_waits_for_every_earlier_reserved_generation() {
        let turnstile = Arc::new(DispatchTurnstile::default());
        let earlier = turnstile.reserve();
        let later = turnstile.reserve();
        let order = Arc::new(Mutex::new(Vec::new()));

        let earlier_body = thread::spawn({
            let turnstile = Arc::clone(&turnstile);
            let order = Arc::clone(&order);
            move || {
                let _turn = turnstile.take(earlier);
                order.lock().unwrap().push(earlier);
            }
        });

        {
            let _turn = turnstile.take(later);
            order.lock().unwrap().push(later);
        }
        earlier_body
            .join()
            .expect("the earlier body should not panic");

        assert_eq!(
            *order.lock().unwrap(),
            vec![earlier, later],
            "a dispatch body must run in the order its Generation was reserved"
        );
    }

    /// The generic cancellation primitive stops a loop the instant `cancel` is
    /// observed, proven with a channel rendezvous rather than a sleep: `cancel` is
    /// set only after the worker's third step has genuinely completed, so a fourth
    /// step running at all would mean the flag was set but never actually checked.
    #[test]
    fn run_while_not_cancelled_stops_at_the_next_check_rather_than_running_forever() {
        let cancel = Arc::new(AtomicBool::new(false));
        let worker_cancel = Arc::clone(&cancel);
        let (step_started_tx, step_started_rx) = crossbeam_channel::bounded::<()>(0);
        let (proceed_tx, proceed_rx) = crossbeam_channel::bounded::<()>(0);

        let worker = thread::spawn(move || {
            run_while_not_cancelled(&worker_cancel, || {
                step_started_tx.send(()).expect("test should be listening");
                proceed_rx.recv().is_ok()
            })
        });

        for _ in 0..2 {
            step_started_rx
                .recv()
                .expect("worker should announce each step");
            proceed_tx.send(()).expect("let the step finish");
        }
        step_started_rx
            .recv()
            .expect("worker should announce its third step");
        cancel.store(true, Ordering::Release);
        proceed_tx.send(()).expect("let the third step finish");

        let ran = worker.join().expect("worker thread should not panic");

        assert_eq!(
            ran, 3,
            "expected cancellation to stop the loop after its third step"
        );
    }

    /// Phase A's own per-entity timing distribution: opens (or reuses a cached
    /// handle for) every entity in `population` and reads `HEAD` from it, exactly
    /// the work `probe_branch` does, one rayon task per entity via `fanout::scatter`
    /// rather than `Core::refresh`, so the timing is not entangled with the
    /// settle-gate bookkeeping a full `Core` also pays for. Returns one
    /// [`Duration`] per entity actually probed, so a caller reports a real
    /// distribution rather than a total divided by a count.
    fn benchmark_identity_phase(
        population: Vec<crate::discovery::DiscoveredEntity>,
    ) -> (Duration, Vec<Duration>) {
        let (tx, rx) = crossbeam_channel::unbounded();
        let started = Instant::now();
        crate::fanout::scatter(population, tx, |entity| {
            let task_started = Instant::now();
            let repo = match &entity.repo {
                Some(repo) => repo.to_thread_local(),
                None => match git::open_thread_safe(entity.key.path()) {
                    Ok(repo) => repo.to_thread_local(),
                    Err(_) => return None,
                },
            };
            let _ = git::head_shape(&repo);
            Some(task_started.elapsed())
        });
        let wall = started.elapsed();
        let durations: Vec<Duration> = rx.into_iter().flatten().collect();
        (wall, durations)
    }

    /// Every root this machine actually has of the two the owner's real corpus
    /// lives under. Read from `$HOME` at run time rather than a literal in this
    /// file, so no personal path is ever recorded in committed source.
    fn real_corpus_roots() -> Vec<PathBuf> {
        let Some(home) = std::env::var_os("HOME") else {
            return Vec::new();
        };
        let home = PathBuf::from(home);
        ["dev", "dev-misc"]
            .into_iter()
            .map(|leaf| home.join(leaf))
            .filter(|root| root.is_dir())
            .collect()
    }

    /// A `.git`-committed disposable repository per index, standing in for the
    /// real corpus when it is absent or too small to be meaningful. Each one gets
    /// a distinct commit so opening it is not a single cached filesystem page for
    /// every entity.
    fn generated_fixture_corpus(size: usize) -> tempfile::TempDir {
        let root = tempfile::tempdir().expect("temp dir for generated fixture corpus");
        for i in 0..size {
            let repo = root.path().join(format!("fixture-repo-{i}"));
            fs::create_dir_all(&repo).expect("create fixture repo dir");
            gix::init(&repo).expect("init fixture repo");
            let status = Command::new("git")
                .arg("-C")
                .arg(&repo)
                .args(["-c", "user.email=test@example.com", "-c", "user.name=Test"])
                .args(["commit", "--allow-empty", "-m", &format!("commit {i}")])
                .status()
                .expect("run git commit");
            assert!(status.success());
        }
        root
    }

    /// Percentile `p` (0 to 100) of an already-sorted, non-empty slice.
    fn percentile(sorted: &[Duration], p: usize) -> Duration {
        let index = (sorted.len() - 1) * p / 100;
        sorted[index]
    }

    /// Path-component names to keep out of the benchmark's population entirely,
    /// read from an environment variable rather than a literal in this file: a
    /// standing project rule keeps certain names out of committed source, so a
    /// real run supplies them at invocation time
    /// (`REPON_BENCHMARK_EXCLUDE_NAMES=name-one,name-two`) instead of this file
    /// ever spelling one out. Empty, and therefore excluding nothing, when unset.
    fn extra_excluded_names() -> Vec<String> {
        parse_excluded_names(&std::env::var("REPON_BENCHMARK_EXCLUDE_NAMES").unwrap_or_default())
    }

    /// The comma-separated parsing `extra_excluded_names` applies to whatever the
    /// environment variable holds, split out so it can be proven against a literal
    /// string rather than by mutating process environment state a parallel test
    /// run could race on.
    fn parse_excluded_names(raw: &str) -> Vec<String> {
        raw.split(',')
            .map(str::trim)
            .filter(|name| !name.is_empty())
            .map(str::to_string)
            .collect()
    }

    /// Discovers, resolves and excluded-name-filters one root list into a
    /// population, without opening anything `excluded_names` names at any depth.
    /// Returns the wall time of discovery and resolution alongside the
    /// population, since resolution is where every entity's repository is
    /// actually opened the first time ([`git::resolve_boundary`]); the identity
    /// phase timed afterwards only re-reads `HEAD` from the handle that step
    /// already cached.
    fn discover_population(
        roots: Vec<PathBuf>,
        excluded_names: &[String],
    ) -> (Vec<crate::discovery::DiscoveredEntity>, Duration) {
        let set = SetSpec {
            name: "identity-probe-benchmark".to_string(),
            roots,
            include: Vec::new(),
            exclude: Vec::new(),
        };
        let started = Instant::now();
        let discovery = discovery::discover(&set);
        let (discovered, _) = discovery::resolve(&set, &discovery.entities);
        let elapsed = started.elapsed();
        let population = discovered
            .into_iter()
            .filter(|entity| {
                !entity.key.path().components().any(|component| {
                    excluded_names
                        .iter()
                        .any(|name| component.as_os_str() == name.as_str())
                })
            })
            .collect();
        (population, elapsed)
    }

    /// The exclusion mechanism proven against a fixture: a name present nowhere
    /// but this test's own excluded-names list still keeps a matching boundary
    /// out of the discovered population, and its two siblings still get through.
    #[test]
    fn a_boundary_whose_path_matches_an_excluded_name_is_left_out_of_the_population() {
        let fixture = generated_fixture_corpus(3);
        let excluded = vec!["fixture-repo-1".to_string()];

        let (population, _) = discover_population(vec![fixture.path().to_path_buf()], &excluded);

        assert_eq!(population.len(), 2);
        assert!(
            population
                .iter()
                .all(|entity| entity.key.path().file_name().unwrap() != "fixture-repo-1"),
            "the excluded name must never appear in the population discovery returns"
        );
    }

    #[test]
    fn excluded_names_parses_a_comma_separated_list_and_ignores_blanks() {
        assert_eq!(
            parse_excluded_names("foo, bar ,,baz"),
            vec!["foo".to_string(), "bar".to_string(), "baz".to_string()]
        );
        assert!(parse_excluded_names("").is_empty());
        assert!(parse_excluded_names("   ").is_empty());
    }

    /// Benchmarks the identity probe (phase A: open the repository, read `HEAD`)
    /// against the owner's real corpus under `$HOME/dev` and `$HOME/dev-misc`,
    /// falling back to a generated fixture when the real corpus is absent or too
    /// small to be meaningful (fewer than 20 entities). Never run by `just ci`:
    /// this is a hand-run measurement, per this project's convention of recording
    /// hand-run figures with the date, machine and toolchain rather than asserting
    /// a timing budget in a committed test. Run it with:
    /// `cargo test -p repon-core --release -- --ignored --nocapture identity_probe_benchmark`
    ///
    /// Read-only throughout: discovery only stats for a `.git` entry and phase A
    /// only reads `HEAD`. Any boundary whose path has a component named by
    /// `REPON_BENCHMARK_EXCLUDE_NAMES` is dropped before discovery's second half
    /// would ever open it, which is how a standing exclusion is honoured without
    /// this file naming what it excludes.
    #[test]
    #[ignore = "hand-run against the owner's real corpus; see docs/spec/refresh.md for the recorded figures"]
    fn identity_probe_benchmark() {
        let excluded_names = extra_excluded_names();

        // `_fixture` is held for the rest of the test whenever a fixture is used,
        // so its directories still exist when the identity phase opens them; it is
        // simply never populated on the real-corpus path.
        let mut _fixture: Option<tempfile::TempDir> = None;

        let (real_population, real_discovery_wall) =
            discover_population(real_corpus_roots(), &excluded_names);
        let (population, using_fixture, discovery_wall) = if real_population.len() >= 20 {
            (real_population, false, real_discovery_wall)
        } else {
            println!(
                "real corpus absent or too small to be meaningful ({} entities); \
                 using a generated fixture instead",
                real_population.len()
            );
            let fixture = generated_fixture_corpus(300);
            let (population, fixture_discovery_wall) =
                discover_population(vec![fixture.path().to_path_buf()], &excluded_names);
            _fixture = Some(fixture);
            (population, true, fixture_discovery_wall)
        };

        let population_size = population.len();
        assert!(
            population_size > 0,
            "neither a real corpus root nor the generated fixture produced any entities"
        );

        let (wall, mut durations) = benchmark_identity_phase(population);
        durations.sort();

        println!(
            "identity probe benchmark: corpus = {}, population = {population_size}",
            if using_fixture {
                "generated fixture"
            } else {
                "real corpus"
            }
        );
        println!(
            "discovery + first open (serial, every entity's own gix::open): {discovery_wall:?}"
        );
        println!("identity phase, warm, parallel (HEAD re-read from the cached handle): {wall:?}");
        println!(
            "identity phase per entity: p50 {:?}, p90 {:?}, max {:?}",
            percentile(&durations, 50),
            percentile(&durations, 90),
            durations.last().copied().unwrap_or_default(),
        );
    }

    fn spec_with_overrides(roots: Vec<PathBuf>, overrides: Vec<RepoOverride>) -> CoreSpec {
        let mut spec = spec(roots);
        spec.overrides = overrides;
        spec
    }

    /// The seam this proves: an explicit per-Repo override reaches all the way
    /// through `Core::refresh` and `settle` into the `default_branch` cell as
    /// rung 1, recorded in diagnostics, even though `origin/HEAD` and the name
    /// list would both answer differently if asked.
    #[test]
    fn a_per_repo_override_resolves_the_default_branch_at_rung_one_through_a_real_refresh() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        git(
            &repo,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let sha = head_sha(&repo);
        git(&repo, &["update-ref", "refs/remotes/origin/main", &sha]);
        let remote_refs_dir = repo
            .join(".git")
            .join("refs")
            .join("remotes")
            .join("origin");
        fs::create_dir_all(&remote_refs_dir).expect("create refs/remotes/origin dir");
        fs::write(
            remote_refs_dir.join("HEAD"),
            "ref: refs/remotes/origin/main\n",
        )
        .expect("write HEAD");

        let core = Core::start_discovered(spec_with_overrides(
            vec![root],
            vec![RepoOverride {
                path: repo.clone(),
                default_branch: Some("develop".to_string()),
                excluded: false,
            }],
        ));
        let key = core.snapshot().entities[0].key.clone();

        core.refresh(std::slice::from_ref(&key));
        let settled = core.settle();
        let entity = &settled.entities[0];

        match entity.default_branch.settled() {
            Some(Settled::Known {
                value,
                at: _,
                stale: _,
            }) => assert_eq!(
                value.name(),
                "origin/develop",
                "the override must win even though origin/HEAD names a different branch"
            ),
            other => panic!("expected the override's own answer, got {other:?}"),
        }
        assert_eq!(
            entity.diagnostics.default_branch_rung,
            Some(1),
            "an override must be recorded as rung 1"
        );
    }

    /// `probe_now`'s synchronous path carries the same override wiring as
    /// `refresh`, proven directly since a Launcher return uses it without ever
    /// calling `refresh` first.
    #[test]
    fn a_per_repo_override_also_resolves_through_probe_now() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec_with_overrides(
            vec![root],
            vec![RepoOverride {
                path: repo.clone(),
                default_branch: Some("release".to_string()),
                excluded: false,
            }],
        ));
        let key = core.snapshot().entities[0].key.clone();

        let entity = core.probe_now(&key);

        match entity.default_branch.settled() {
            // No remote at all: the override still answers, using the bare name.
            Some(Settled::Known {
                value,
                at: _,
                stale: _,
            }) => assert_eq!(value.name(), "release"),
            other => panic!("expected the override's own answer, got {other:?}"),
        }
        assert_eq!(entity.diagnostics.default_branch_rung, Some(1));
    }

    /// The three named ways rung 4 is reached are recorded distinctly, not merged
    /// into one opaque "gave up" fact: no remote at all, two or more remotes with
    /// none named `origin`, and a chosen remote whose tracking refs matched
    /// nothing in the name list.
    #[test]
    fn reaching_rung_four_with_no_remote_at_all_records_why() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        core.refresh(std::slice::from_ref(&key));
        let settled = core.settle();
        let entity = &settled.entities[0];

        assert_eq!(entity.diagnostics.default_branch_rung, Some(4));
        assert_eq!(
            entity.diagnostics.default_branch_stopped,
            Some(DefaultBranchStopped::NoRemote)
        );
    }

    #[test]
    fn reaching_rung_four_with_two_unnamed_remotes_records_why() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        git(
            &repo,
            &[
                "remote",
                "add",
                "fork-one",
                "https://example.invalid/one.git",
            ],
        );
        git(
            &repo,
            &[
                "remote",
                "add",
                "fork-two",
                "https://example.invalid/two.git",
            ],
        );

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        core.refresh(std::slice::from_ref(&key));
        let settled = core.settle();
        let entity = &settled.entities[0];

        assert_eq!(entity.diagnostics.default_branch_rung, Some(4));
        assert_eq!(
            entity.diagnostics.default_branch_stopped,
            Some(DefaultBranchStopped::AmbiguousRemote)
        );
    }

    #[test]
    fn reaching_rung_four_with_a_chosen_remote_and_no_matching_ref_records_why() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        git(
            &repo,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        // A remote-tracking ref exists, but under a name outside rung 3's list, and
        // there is no origin/HEAD at all.
        let sha = head_sha(&repo);
        git(&repo, &["update-ref", "refs/remotes/origin/feature", &sha]);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        core.refresh(std::slice::from_ref(&key));
        let settled = core.settle();
        let entity = &settled.entities[0];

        assert_eq!(entity.diagnostics.default_branch_rung, Some(4));
        assert_eq!(
            entity.diagnostics.default_branch_stopped,
            Some(DefaultBranchStopped::NameListExhausted)
        );
    }

    /// A Repo with no override and no resolvable remote reaches rung 4: Unknown,
    /// never Failed, which stays reserved for a git error.
    #[test]
    fn a_repo_with_nothing_to_resolve_settles_unknown_never_failed() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        core.refresh(std::slice::from_ref(&key));
        let settled = core.settle();
        let entity = &settled.entities[0];

        assert!(matches!(
            entity.default_branch.settled(),
            Some(Settled::Unknown(Unknown::NoDefaultBranch))
        ));
        assert_eq!(entity.diagnostics.default_branch_rung, Some(4));
    }

    /// The seam this proves: a stale symbolic `origin/HEAD` reaches all the way
    /// through `Core::refresh` and `settle` into `Diagnostics`, not just the
    /// fallen-through rung 3 answer, since the spec requires recording that the
    /// stale case is what happened rather than leaving the same trail a merely
    /// absent `origin/HEAD` would.
    #[test]
    fn a_stale_remote_head_is_recorded_in_diagnostics_through_a_real_refresh() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        git(
            &repo,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let sha = head_sha(&repo);
        git(&repo, &["update-ref", "refs/remotes/origin/trunk", &sha]);
        let remote_refs_dir = repo
            .join(".git")
            .join("refs")
            .join("remotes")
            .join("origin");
        fs::create_dir_all(&remote_refs_dir).expect("create refs/remotes/origin dir");
        // Points at a name never created as a ref: the stale case, not merely absent.
        fs::write(
            remote_refs_dir.join("HEAD"),
            "ref: refs/remotes/origin/main\n",
        )
        .expect("write HEAD");

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        core.refresh(std::slice::from_ref(&key));
        let settled = core.settle();
        let entity = &settled.entities[0];

        match entity.default_branch.settled() {
            Some(Settled::Known {
                value,
                at: _,
                stale: _,
            }) => {
                assert_eq!(value.name(), "origin/trunk")
            }
            other => panic!("expected the name list's answer, got {other:?}"),
        }
        assert!(
            entity.diagnostics.default_branch_rung_two_stale,
            "a stale origin/HEAD target must be recorded on the entity's diagnostics"
        );
    }

    /// A resolvable `origin/HEAD` must never be marked stale, so the flag actually
    /// distinguishes the two cases rather than always being set once rung 2 runs.
    #[test]
    fn a_resolvable_remote_head_is_not_recorded_as_stale() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        git(
            &repo,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let sha = head_sha(&repo);
        git(&repo, &["update-ref", "refs/remotes/origin/main", &sha]);
        let remote_refs_dir = repo
            .join(".git")
            .join("refs")
            .join("remotes")
            .join("origin");
        fs::create_dir_all(&remote_refs_dir).expect("create refs/remotes/origin dir");
        fs::write(
            remote_refs_dir.join("HEAD"),
            "ref: refs/remotes/origin/main\n",
        )
        .expect("write HEAD");

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.snapshot().entities[0].key.clone();

        core.refresh(std::slice::from_ref(&key));
        let settled = core.settle();
        let entity = &settled.entities[0];

        assert!(!entity.diagnostics.default_branch_rung_two_stale);
    }

    /// The defining behaviour for per-Repo matching: one `[[repo]]` entry naming
    /// only the parent Repo's own path still applies to a linked Worktree sharing
    /// its common dir, proven against a real `git worktree add` rather than a
    /// hand-built stand-in for the on-disk relationship.
    #[test]
    fn one_override_on_a_repos_path_covers_a_worktree_sharing_its_common_dir() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        let worktree = root.join("worktree");
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature",
                worktree.to_str().expect("utf8 path"),
            ],
        );

        let core = Core::start_discovered(spec_with_overrides(
            vec![root],
            vec![RepoOverride {
                path: parent.clone(),
                default_branch: None,
                excluded: true,
            }],
        ));
        let snapshot = core.snapshot();

        for entity in &snapshot.entities {
            assert!(
                entity.excluded,
                "both the Repo and its Worktree must inherit the entry declared on the Repo's own path, entity: {:?}",
                entity.key
            );
        }
        assert_eq!(
            snapshot.entities.len(),
            2,
            "expected the parent plus its worktree"
        );
    }

    /// The other direction: an entry naming a Worktree's own path beats the entry
    /// it would otherwise inherit from the Repo it shares a common dir with, while
    /// a second Worktree with no entry of its own still inherits the Repo's entry.
    #[test]
    fn an_entry_naming_a_worktrees_own_path_beats_the_inherited_one() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        let worktree_own = root.join("worktree-own");
        let worktree_inherits = root.join("worktree-inherits");
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature-own",
                worktree_own.to_str().expect("utf8 path"),
            ],
        );
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature-inherits",
                worktree_inherits.to_str().expect("utf8 path"),
            ],
        );

        let core = Core::start_discovered(spec_with_overrides(
            vec![root],
            vec![
                RepoOverride {
                    path: parent.clone(),
                    default_branch: None,
                    excluded: true,
                },
                RepoOverride {
                    path: worktree_own.clone(),
                    default_branch: None,
                    excluded: false,
                },
            ],
        ));
        let snapshot = core.snapshot();

        let find = |path: &Path| {
            snapshot
                .entities
                .iter()
                .find(|entity| entity.key.path() == path)
                .unwrap_or_else(|| panic!("entity at {path:?} present"))
        };

        assert!(
            find(&parent).excluded,
            "the parent Repo has no entry of its own and inherits the excluding one"
        );
        assert!(
            !find(&worktree_own).excluded,
            "the Worktree named directly by its own path must use its own entry, not the inherited one"
        );
        assert!(
            find(&worktree_inherits).excluded,
            "a sibling Worktree with no entry of its own still inherits the Repo's entry"
        );
    }

    /// A Submodule's own common dir differs from its parent's
    /// (`<parent common dir>/modules/<name>`), so an entry naming only the
    /// parent's path can never also exclude the parent's Submodule: the entry
    /// covers the parent and its Worktrees, never a Submodule reached through it.
    #[test]
    fn an_override_on_the_parents_path_never_excludes_its_submodule() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        fs::write(
            parent.join(".gitmodules"),
            "[submodule \"lib\"]\n\tpath = vendor/lib\n\turl = https://example.com/lib.git\n",
        )
        .expect("write .gitmodules");
        fs::create_dir_all(parent.join("vendor").join("lib")).expect("create submodule dir");

        let core = Core::start_discovered(spec_with_overrides(
            vec![root],
            vec![RepoOverride {
                path: parent.clone(),
                default_branch: None,
                excluded: true,
            }],
        ));
        let snapshot = core.snapshot();

        let submodule = snapshot
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Submodule))
            .expect("the submodule is still discovered and listed");
        assert!(
            !submodule.excluded,
            "an entry naming only the parent's path must never reach a Submodule, \
             whose own common dir differs from its parent's"
        );
    }

    /// The seam this proves: `Core::default_branch_chain_reads_for_test` counts
    /// how many times a `refresh` actually computed the default-branch chain's
    /// per-common-dir facts (`default_branch::ChainFacts::resolve`, the loose-file
    /// read plus the reference lookups), rather than reusing an already-computed
    /// answer for a common dir another entity in the same Generation already paid
    /// for. Reading the count off `Core` this way is the seam, not an internal:
    /// it is a named, stable test-only entry point in the same
    /// `#[cfg(test)] impl Core` family as `cached_repo_handle_for_test`, which
    /// already proves a different sharing question the same way. There is no
    /// black-box way to observe "how many times an internal read ran" through
    /// `Snapshot` alone, since two different common dirs can legitimately answer
    /// with the same branch name.
    ///
    /// Three Worktrees share one common dir with their Repo (four entities); a
    /// second, unrelated Repo has its own. Memoised, the count is 2, the number of
    /// distinct common dirs; unmemoised, it is 4, the number of entities.
    #[test]
    fn the_default_branch_chain_is_memoised_once_per_common_dir_per_generation() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        for name in ["wt-a", "wt-b", "wt-c"] {
            let worktree = root.join(name);
            git(
                &parent,
                &[
                    "worktree",
                    "add",
                    "-b",
                    name,
                    worktree.to_str().expect("utf8 path"),
                ],
            );
        }
        let other_repo = root.join("other");
        init_repo_with_a_commit(&other_repo);

        let (core, launched) = started_and_settled(spec(vec![root]));
        let keys: Vec<EntityKey> = launched
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();
        assert_eq!(
            keys.len(),
            5,
            "expected the parent, its three worktrees and the unrelated repo"
        );

        core.refresh(&keys);
        core.settle();

        assert_eq!(
            core.default_branch_chain_reads_for_test(),
            2,
            "four entities span exactly two common dirs; a memoised chain reads \
             each common dir once, not once per entity"
        );

        // A second Generation pays the same two reads again. A cache hoisted onto
        // `Core` would answer this refresh for free and read 0, which is the
        // persistence ADR 0006 refuses.
        core.refresh(&keys);
        core.settle();
        assert_eq!(
            core.default_branch_chain_reads_for_test(),
            2,
            "the memo lives inside one Generation's dispatch; the next Generation \
             recomputes rather than inheriting it"
        );
    }

    /// The same proof as `the_default_branch_chain_is_memoised_once_per_common_dir_per_generation`,
    /// for patch equivalence's own expensive half: two sibling Worktrees, each
    /// with a live upstream and unmerged work of its own, share one common dir
    /// and must scan its default-branch history once between them, not twice;
    /// an unrelated Repo's own Worktree, in its own common dir, pays for a
    /// second scan. Both entities settling (`Active`, since neither's work
    /// actually landed) is what proves the second pass ran for both rather than
    /// one being cancelled or skipped, which would otherwise let a
    /// once-per-entity implementation coincidentally also read 2.
    #[test]
    fn patch_equivalence_is_memoised_once_per_common_dir_per_generation() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        git(
            &parent,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let base_sha = head_sha(&parent);
        git(
            &parent,
            &["update-ref", "refs/remotes/origin/main", &base_sha],
        );
        for name in ["feature-x", "feature-y"] {
            let worktree = root.join(name);
            git(
                &parent,
                &[
                    "worktree",
                    "add",
                    "-b",
                    name,
                    worktree.to_str().expect("utf8 path"),
                ],
            );
            fs::write(worktree.join(format!("{name}.txt")), "unmerged\n")
                .expect("write worktree file");
            git(&worktree, &["add", "."]);
            git(&worktree, &["commit", "-m", "unmerged work"]);
            let tip_sha = head_sha(&worktree);
            git(
                &parent,
                &["config", &format!("branch.{name}.remote"), "origin"],
            );
            git(
                &parent,
                &[
                    "config",
                    &format!("branch.{name}.merge"),
                    &format!("refs/heads/{name}"),
                ],
            );
            git(
                &parent,
                &[
                    "update-ref",
                    &format!("refs/remotes/origin/{name}"),
                    &tip_sha,
                ],
            );
        }

        let other_parent = root.join("other");
        init_repo_with_a_commit(&other_parent);
        git(
            &other_parent,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/other.git",
            ],
        );
        let other_base_sha = head_sha(&other_parent);
        git(
            &other_parent,
            &["update-ref", "refs/remotes/origin/main", &other_base_sha],
        );
        let other_worktree = root.join("other-feature");
        git(
            &other_parent,
            &[
                "worktree",
                "add",
                "-b",
                "other-feature",
                other_worktree.to_str().expect("utf8 path"),
            ],
        );
        fs::write(other_worktree.join("other.txt"), "unmerged\n").expect("write worktree file");
        git(&other_worktree, &["add", "."]);
        git(&other_worktree, &["commit", "-m", "unmerged work"]);
        let other_tip_sha = head_sha(&other_worktree);
        git(
            &other_parent,
            &["config", "branch.other-feature.remote", "origin"],
        );
        git(
            &other_parent,
            &[
                "config",
                "branch.other-feature.merge",
                "refs/heads/other-feature",
            ],
        );
        git(
            &other_parent,
            &[
                "update-ref",
                "refs/remotes/origin/other-feature",
                &other_tip_sha,
            ],
        );

        let (core, launched) = started_and_settled(spec(vec![root]));
        let keys: Vec<EntityKey> = launched
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();
        assert_eq!(
            keys.len(),
            5,
            "expected two parents plus their three worktrees"
        );

        core.refresh(&keys);
        let settled = core.settle();

        let worktree_states: Vec<_> = settled
            .entities
            .iter()
            .filter(|entity| matches!(entity.kind, Kind::Worktree))
            .map(|entity| entity.state.settled())
            .collect();
        assert_eq!(worktree_states.len(), 3, "expected three worktree rows");
        for settled_state in &worktree_states {
            assert!(
                matches!(
                    settled_state,
                    Some(Settled::Known {
                        value: WorktreeState::Active,
                        at: _,
                        stale: _
                    })
                ),
                "expected every worktree's genuinely unmerged work to settle Active, got {settled_state:?}"
            );
        }

        assert_eq!(
            core.patch_identity_reads_for_test(),
            2,
            "two worktrees share one common dir and must scan its default-branch \
             history once between them, not once per entity; the unrelated repo's \
             own worktree pays for a second scan"
        );

        // A second Generation pays for the same two scans again: a cache hoisted
        // onto `Core` would answer this refresh for free and read 0.
        core.refresh(&keys);
        core.settle();
        assert_eq!(
            core.patch_identity_reads_for_test(),
            2,
            "the memo lives inside one Generation's dispatch; the next Generation \
             recomputes rather than inheriting it"
        );
    }

    /// Criterion 3's widen direction, end to end: `feature-deep` forks at the
    /// parent commit `deep_fork_sha` and is squashed into main immediately
    /// afterwards; `feature-shallow` forks at that squash commit (strictly more
    /// recent, so its own merge base is shallower) and is squashed in turn to
    /// produce `main`'s tip. The deepest merge base among the two siblings is
    /// `feature-deep`'s own, `deep_fork_sha`, not `feature-shallow`'s.
    ///
    /// A scan bounded by the *shallowest* sibling's merge base instead of the
    /// deepest would stop before reaching the commit that squashed
    /// `feature-deep` in, since that commit sits strictly between the two
    /// bounds: `feature-deep` would then settle `Active` instead of `Merged`.
    /// This is a smoke test for that outcome through the real dispatch
    /// pipeline, not a proof: rayon's work stealing gives dispatch `order` no
    /// ordering guarantee, so `feature-deep` landing last here is a nudge
    /// towards, never proof of, exercising a lazy first-arrival bound.
    /// `bound_gate_deepest_folds_every_candidate_regardless_of_report_order`
    /// below is what deterministically proves the bound is collected from
    /// every sibling rather than computed lazily from whichever arrives first.
    #[test]
    fn an_entity_whose_merge_base_is_deeper_than_its_siblings_widens_the_shared_scan() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        git(
            &parent,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let deep_fork_sha = head_sha(&parent);

        git(&parent, &["branch", "feature-deep"]);
        let deep_worktree = root.join("feature-deep");
        git(
            &parent,
            &[
                "worktree",
                "add",
                deep_worktree.to_str().expect("utf8 path"),
                "feature-deep",
            ],
        );
        fs::write(deep_worktree.join("deep.txt"), "deep work\n").expect("write deep.txt");
        git(&deep_worktree, &["add", "."]);
        git(&deep_worktree, &["commit", "-m", "deep work"]);
        let deep_tip_sha = head_sha(&deep_worktree);

        git(&parent, &["merge", "--squash", "feature-deep"]);
        git(&parent, &["commit", "-m", "squashed deep"]);
        let shallow_fork_sha = head_sha(&parent);

        git(&parent, &["branch", "feature-shallow"]);
        let shallow_worktree = root.join("feature-shallow");
        git(
            &parent,
            &[
                "worktree",
                "add",
                shallow_worktree.to_str().expect("utf8 path"),
                "feature-shallow",
            ],
        );
        fs::write(shallow_worktree.join("shallow.txt"), "shallow work\n")
            .expect("write shallow.txt");
        git(&shallow_worktree, &["add", "."]);
        git(&shallow_worktree, &["commit", "-m", "shallow work"]);
        let shallow_tip_sha = head_sha(&shallow_worktree);

        git(&parent, &["merge", "--squash", "feature-shallow"]);
        git(&parent, &["commit", "-m", "squashed shallow"]);
        let main_tip_sha = head_sha(&parent);
        assert_ne!(
            deep_fork_sha, shallow_fork_sha,
            "the two siblings must fork at genuinely different commits"
        );

        git(
            &parent,
            &["update-ref", "refs/remotes/origin/main", &main_tip_sha],
        );
        for (name, tip_sha) in [
            ("feature-deep", &deep_tip_sha),
            ("feature-shallow", &shallow_tip_sha),
        ] {
            git(
                &parent,
                &["config", &format!("branch.{name}.remote"), "origin"],
            );
            git(
                &parent,
                &[
                    "config",
                    &format!("branch.{name}.merge"),
                    &format!("refs/heads/{name}"),
                ],
            );
            git(
                &parent,
                &[
                    "update-ref",
                    &format!("refs/remotes/origin/{name}"),
                    tip_sha,
                ],
            );
        }

        let (core, snapshot) = started_and_settled(spec(vec![root]));
        let deep_key = snapshot
            .entities
            .iter()
            .find(|entity| entity.key.path() == deep_worktree)
            .expect("feature-deep worktree discovered")
            .key
            .clone();
        let shallow_key = snapshot
            .entities
            .iter()
            .find(|entity| entity.key.path() == shallow_worktree)
            .expect("feature-shallow worktree discovered")
            .key
            .clone();
        let parent_key = snapshot
            .entities
            .iter()
            .find(|entity| entity.key.path() == parent)
            .expect("parent repo discovered")
            .key
            .clone();
        // The deepest sibling dispatched last, so a lazy bound computed from
        // whichever entity arrives first would reach for the shallow sibling's
        // own narrower merge base instead.
        let order = vec![parent_key, shallow_key.clone(), deep_key.clone()];

        core.refresh(&order);
        let settled = core.settle();

        let state_of = |key: &EntityKey| {
            settled
                .entities
                .iter()
                .find(|entity| &entity.key == key)
                .and_then(|entity| entity.state.settled())
                .cloned()
        };
        assert!(
            matches!(
                state_of(&deep_key),
                Some(Settled::Known {
                    value: WorktreeState::Merged,
                    at: _,
                    stale: _
                })
            ),
            "expected the deepest sibling's own squash commit to be found once the scan is \
             bounded by the deepest merge base, got {:?}",
            state_of(&deep_key)
        );
        assert!(
            matches!(
                state_of(&shallow_key),
                Some(Settled::Known {
                    value: WorktreeState::Merged,
                    at: _,
                    stale: _
                })
            ),
            "expected the shallow sibling to settle Merged too, got {:?}",
            state_of(&shallow_key)
        );
        assert_eq!(
            core.patch_identity_reads_for_test(),
            1,
            "both worktrees share one common dir and must still scan its default-branch \
             history once between them, not once per entity"
        );
        assert_eq!(
            core.patch_scan_bounds_for_test(),
            vec![Some(id(&deep_fork_sha))],
            "the one shared scan that ran must have been bounded by the deepest sibling's own \
             merge base, not the shallower one's"
        );
    }

    fn id(sha: &str) -> gix::ObjectId {
        gix::ObjectId::from_hex(sha.as_bytes()).expect("parse sha")
    }

    /// Criterion 1, proved at the barrier itself rather than through rayon's
    /// unordered dispatch: `shallow` is reported before `deep` on purpose, so a
    /// lazy first-arrival implementation (answer with whichever candidate
    /// showed up first, rather than collecting every sibling's own merge base)
    /// would settle on `shallow` and fail this assertion. `deep` is an ancestor
    /// of `shallow`, so the correct fold finds it regardless of report order.
    #[test]
    fn bound_gate_deepest_folds_every_candidate_regardless_of_report_order() {
        let dir = tempfile::tempdir().expect("temp dir");
        let repo_path = root_of(&dir).join("repo");
        init_repo_with_a_commit(&repo_path);
        let deep_sha = id(&head_sha(&repo_path));
        fs::write(repo_path.join("child.txt"), "child\n").expect("write child.txt");
        git(&repo_path, &["add", "."]);
        git(&repo_path, &["commit", "-m", "child of deep"]);
        let shallow_sha = id(&head_sha(&repo_path));

        let repo = gix::open(&repo_path).expect("open repo");
        let gate = BoundGate::new(2);
        gate.report(Some(shallow_sha));
        gate.report(Some(deep_sha));

        assert_eq!(
            gate.deepest(&repo),
            Some(deep_sha),
            "the deepest candidate must win even though the shallower one reported first"
        );
    }

    /// Deterministic proof that [`probe_patch_equivalence`] itself consults
    /// [`BoundGate::deepest`] for the bound it hands to
    /// [`patch_equivalence::scan_default_branch`], rather than reaching for its
    /// own entity's merge base. Unlike
    /// `bound_gate_deepest_folds_every_candidate_regardless_of_report_order`,
    /// which proves `BoundGate` and `deepest_merge_base` correct in isolation,
    /// this drives `probe_patch_equivalence` itself and inspects what it
    /// actually recorded into `memo.scan_bounds`. `deep_sha`'s contribution is
    /// pre-reported by hand, standing in for a sibling entity that already ran
    /// this Generation; the one entity this test drives through the real
    /// function arrives at `shallow_sha`, so its own merge base against
    /// `default_tip` is `shallow_sha`, strictly shallower than `deep_sha`. A
    /// regression that bounds the scan by the arriving entity's own merge base
    /// instead of the gate's answer would record `shallow_sha` here, and would
    /// do so every single run: unlike the integration smoke test below, there
    /// is no rayon dispatch order here to sometimes get it right by accident.
    #[test]
    fn probe_patch_equivalence_bounds_the_scan_by_the_gates_deepest_not_its_own_merge_base() {
        let dir = tempfile::tempdir().expect("temp dir");
        let repo_path = root_of(&dir).join("repo");
        init_repo_with_a_commit(&repo_path);
        let deep_sha = id(&head_sha(&repo_path));
        fs::write(repo_path.join("child.txt"), "child\n").expect("write child.txt");
        git(&repo_path, &["add", "."]);
        git(&repo_path, &["commit", "-m", "child of deep"]);
        let shallow_sha_hex = head_sha(&repo_path);
        let shallow_sha = id(&shallow_sha_hex);
        fs::write(repo_path.join("tip.txt"), "tip\n").expect("write tip.txt");
        git(&repo_path, &["add", "."]);
        git(&repo_path, &["commit", "-m", "default tip"]);
        let default_tip_hex = head_sha(&repo_path);

        let repo = gix::open(&repo_path).expect("open repo");
        // What `landing::probe` hands over for a Worktree entity sitting at
        // `shallow`, whose own tip is not main's actual tip.
        let outstanding = landing::Outstanding {
            entity_tip: shallow_sha,
            default_tip: id(&default_tip_hex),
            merge_base: Some(shallow_sha),
        };
        let common_dir: Arc<Path> = Arc::from(repo_path.join(".git"));
        let cancel = AtomicBool::new(false);
        let patch_cache: PatchIdentityCache = Mutex::new(HashMap::new());
        let patch_reads = AtomicUsize::new(0);
        let patch_scan_bounds: Mutex<Vec<Option<gix::ObjectId>>> = Mutex::new(Vec::new());
        let memo = PatchEquivalenceMemo {
            cache: &patch_cache,
            reads: &patch_reads,
            scan_bounds: &patch_scan_bounds,
        };
        // Two entities share this common dir this Generation: `deep_sha` stands
        // in for a sibling that already reported its own, deeper merge base;
        // `shallow` is the one entity driven through the real function below.
        let gate = BoundGate::new(2);
        gate.report(Some(deep_sha));
        let mut report = GateReport::new(&gate);

        probe_patch_equivalence(
            &repo,
            &outstanding,
            &common_dir,
            &cancel,
            &memo,
            &mut report,
        );

        assert_eq!(
            patch_scan_bounds.lock().unwrap().as_slice(),
            [Some(deep_sha)],
            "the scan must be bounded by the deepest sibling's merge base, not shallow's own \
             ({shallow_sha:?})"
        );
    }

    /// The carry itself: [`probe_patch_equivalence`] diffs the entity's own
    /// range from the merge base `landing::probe` handed over, rather than
    /// walking the same commit pair a second time. `mid_sha` is a real commit
    /// on `feature` but not its fork point, so the two answers differ: from the
    /// fork point the range is the whole squashed change and settles `Merged`,
    /// from `mid_sha` it is only `b.txt` and settles `Active`. A regression that
    /// recomputed the base here would answer `Merged` and fail this test.
    #[test]
    fn probe_patch_equivalence_diffs_from_the_merge_base_it_was_handed() {
        let dir = tempfile::tempdir().expect("temp dir");
        let repo_path = root_of(&dir).join("repo");
        init_repo_with_a_commit(&repo_path);
        let fork_point_hex = head_sha(&repo_path);
        git(&repo_path, &["checkout", "-b", "feature"]);
        fs::write(repo_path.join("a.txt"), "one\n").expect("write a.txt");
        git(&repo_path, &["add", "a.txt"]);
        git(&repo_path, &["commit", "-m", "add a"]);
        let mid_sha = id(&head_sha(&repo_path));
        fs::write(repo_path.join("b.txt"), "two\n").expect("write b.txt");
        git(&repo_path, &["add", "b.txt"]);
        git(&repo_path, &["commit", "-m", "add b"]);
        let feature_sha = id(&head_sha(&repo_path));
        git(&repo_path, &["checkout", "-B", "main", &fork_point_hex]);
        git(&repo_path, &["merge", "--squash", "feature"]);
        git(&repo_path, &["commit", "-m", "squashed feature"]);
        let main_sha = id(&head_sha(&repo_path));

        let repo = gix::open(&repo_path).expect("open repo");
        // What `landing::probe` hands over, with a base halfway along the
        // branch standing in for one only this pass could know.
        let outstanding = landing::Outstanding {
            entity_tip: feature_sha,
            default_tip: main_sha,
            merge_base: Some(mid_sha),
        };
        let common_dir: Arc<Path> = Arc::from(repo_path.join(".git"));
        let cancel = AtomicBool::new(false);
        let patch_cache: PatchIdentityCache = Mutex::new(HashMap::new());
        let patch_reads = AtomicUsize::new(0);
        let patch_scan_bounds: Mutex<Vec<Option<gix::ObjectId>>> = Mutex::new(Vec::new());
        let memo = PatchEquivalenceMemo {
            cache: &patch_cache,
            reads: &patch_reads,
            scan_bounds: &patch_scan_bounds,
        };
        let gate = BoundGate::new(1);
        let mut report = GateReport::new(&gate);

        let settled = probe_patch_equivalence(
            &repo,
            &outstanding,
            &common_dir,
            &cancel,
            &memo,
            &mut report,
        );

        assert!(
            matches!(
                settled,
                Some(Settled::Known {
                    value: WorktreeState::Active,
                    at: _,
                    stale: _
                })
            ),
            "the range must be measured from the handed-in base ({mid_sha:?}), whose only \
             change the squash commit does not match, got {settled:?}"
        );
    }

    /// The edge [`deepest_merge_base`] exists for: no entity sharing a common
    /// dir ever had a merge base to offer (every one settled by ancestry, was
    /// cancelled, or shared no history with the default branch at all), so the
    /// scan is left unbounded. `deepest_merge_base` returns before its first
    /// candidate lookup here, which is what lets this fixture skip building any
    /// commit history at all.
    #[test]
    fn bound_gate_deepest_with_no_candidates_leaves_the_scan_unbounded() {
        let dir = tempfile::tempdir().expect("temp dir");
        let repo_path = root_of(&dir).join("repo");
        gix::init(&repo_path).expect("init repo");
        let repo = gix::open(&repo_path).expect("open repo");

        let gate = BoundGate::new(2);
        gate.report(None);
        gate.report(None);

        assert_eq!(
            gate.deepest(&repo),
            None,
            "no contributed candidate must leave the scan unbounded"
        );
    }

    /// `probe_patch_equivalence`'s `Ok(None)` arm bypasses the shared scan for
    /// an Outstanding entity with no shared history at all. `unrelated` is a
    /// real branch, with a live upstream so `landing::probe`
    /// leaves it `Outstanding`, whose own root commit shares no history with
    /// `main`'s, driven through `Core` end to end rather than by calling
    /// `probe_patch_equivalence` or `patch_equivalence::probe` directly, so a
    /// removed bypass (the shared scan run unconditionally instead) is
    /// exercised for real: `BoundGate::deepest` would then block forever on a
    /// scan this entity never asked for.
    #[test]
    fn an_outstanding_entity_with_no_shared_history_settles_active_without_the_shared_scan() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        git(&parent, &["branch", "-M", "main"]);
        git(
            &parent,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let main_sha = head_sha(&parent);
        git(
            &parent,
            &["update-ref", "refs/remotes/origin/main", &main_sha],
        );

        git(&parent, &["checkout", "--orphan", "unrelated"]);
        git(
            &parent,
            &["commit", "--allow-empty", "-m", "unrelated root"],
        );
        let unrelated_sha = head_sha(&parent);
        git(&parent, &["checkout", "main"]);

        let worktree = root.join("unrelated");
        git(
            &parent,
            &[
                "worktree",
                "add",
                worktree.to_str().expect("utf8 path"),
                "unrelated",
            ],
        );
        git(&parent, &["config", "branch.unrelated.remote", "origin"]);
        git(
            &parent,
            &["config", "branch.unrelated.merge", "refs/heads/unrelated"],
        );
        git(
            &parent,
            &[
                "update-ref",
                "refs/remotes/origin/unrelated",
                &unrelated_sha,
            ],
        );

        let (core, snapshot) = started_and_settled(spec(vec![root]));
        let worktree_key = snapshot
            .entities
            .iter()
            .find(|entity| entity.key.path() == worktree)
            .expect("unrelated worktree discovered")
            .key
            .clone();

        core.refresh(std::slice::from_ref(&worktree_key));
        let settled = core.settle();

        let state = settled
            .entities
            .iter()
            .find(|entity| entity.key == worktree_key)
            .and_then(|entity| entity.state.settled())
            .cloned();
        assert!(
            matches!(
                state,
                Some(Settled::Known {
                    value: WorktreeState::Active,
                    at: _,
                    stale: _
                })
            ),
            "expected an Outstanding entity with no shared history to settle Active via the \
             bypass, got {state:?}"
        );
        assert_eq!(
            core.patch_identity_reads_for_test(),
            0,
            "the bypass must settle without ever running the shared scan"
        );
    }

    // --- Phase B's comparison: the `sync` cell, end to end through a real `Core`:
    // the six named cases, plus the two ways "every entity, every Generation" is
    // most easily lost. ---

    fn add_origin_remote(path: &Path) {
        git(
            path,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
    }

    /// Wires `branch` up to track `refs/remotes/origin/<branch>` at `upstream_sha`,
    /// mirroring `patch_equivalence_is_memoised_once_per_common_dir_per_generation`'s
    /// own fixture shape against a real disposable repo.
    fn set_upstream(path: &Path, branch: &str, upstream_sha: &str) {
        git(
            path,
            &["config", &format!("branch.{branch}.remote"), "origin"],
        );
        git(
            path,
            &[
                "config",
                &format!("branch.{branch}.merge"),
                &format!("refs/heads/{branch}"),
            ],
        );
        git(
            path,
            &[
                "update-ref",
                &format!("refs/remotes/origin/{branch}"),
                upstream_sha,
            ],
        );
    }

    fn refresh_and_settle(core: &Core) -> crate::snapshot::Snapshot {
        let keys: Vec<EntityKey> = core
            .snapshot()
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();
        core.refresh(&keys);
        core.settle()
    }

    fn sync_of<'a>(
        snapshot: &'a crate::snapshot::Snapshot,
        path: &Path,
    ) -> Option<&'a Settled<SyncState>> {
        snapshot
            .entities
            .iter()
            .find(|entity| entity.key.path() == path)
            .unwrap_or_else(|| panic!("no entity for {}", path.display()))
            .sync
            .settled()
    }

    /// Named case 1 of 6: an attached branch ahead of its upstream.
    #[test]
    fn an_attached_branch_ahead_of_its_upstream_reads_the_ahead_count() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let fork_sha = head_sha(&repo);
        add_origin_remote(&repo);
        set_upstream(&repo, "main", &fork_sha);
        git(&repo, &["commit", "--allow-empty", "-m", "local work"]);

        let core = Core::start_discovered(spec(vec![root]));
        let settled = refresh_and_settle(&core);

        match sync_of(&settled, &repo) {
            Some(Settled::Known {
                value: SyncState::Tracking(AheadBehind { ahead, behind }),
                at: _,
                stale: _,
            }) => {
                assert_eq!(*ahead, 1);
                assert_eq!(*behind, 0);
            }
            other => panic!("expected 1 ahead, 0 behind, got {other:?}"),
        }
    }

    /// Named case 2 of 6: an attached branch behind its upstream.
    #[test]
    fn an_attached_branch_behind_its_upstream_reads_the_behind_count() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        git(&repo, &["checkout", "-b", "temp"]);
        git(&repo, &["commit", "--allow-empty", "-m", "upstream work"]);
        let upstream_sha = head_sha(&repo);
        git(&repo, &["checkout", "main"]);
        git(&repo, &["branch", "-D", "temp"]);
        add_origin_remote(&repo);
        set_upstream(&repo, "main", &upstream_sha);

        let core = Core::start_discovered(spec(vec![root]));
        let settled = refresh_and_settle(&core);

        match sync_of(&settled, &repo) {
            Some(Settled::Known {
                value: SyncState::Tracking(AheadBehind { ahead, behind }),
                at: _,
                stale: _,
            }) => {
                assert_eq!(*ahead, 0);
                assert_eq!(*behind, 1);
            }
            other => panic!("expected 0 ahead, 1 behind, got {other:?}"),
        }
    }

    /// Named case 3 of 6: an attached branch level with its upstream.
    #[test]
    fn an_attached_branch_level_with_its_upstream_reads_in_sync() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let sha = head_sha(&repo);
        add_origin_remote(&repo);
        set_upstream(&repo, "main", &sha);

        let core = Core::start_discovered(spec(vec![root]));
        let settled = refresh_and_settle(&core);

        match sync_of(&settled, &repo) {
            Some(Settled::Known {
                value:
                    SyncState::Tracking(AheadBehind {
                        ahead: 0,
                        behind: 0,
                    }),
                at: _,
                stale: _,
            }) => {}
            other => panic!("expected level with its upstream, got {other:?}"),
        }
    }

    /// Named case 4 of 6: an attached branch tracking nothing, on a Repo that does
    /// have a remote. Distinguishes this from case 6 below: the absence here is the
    /// branch's own tracking configuration, not the Repo's remote.
    #[test]
    fn an_attached_branch_tracking_nothing_reads_no_upstream() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        add_origin_remote(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let settled = refresh_and_settle(&core);

        match sync_of(&settled, &repo) {
            Some(Settled::Known {
                value: SyncState::NoUpstream,
                at: _,
                stale: _,
            }) => {}
            other => panic!("expected no upstream configured, got {other:?}"),
        }
    }

    /// Named case 5 of 6: a detached row, on a Repo that does have a remote.
    /// Distinguishes this from case 6 below the same way case 4 does.
    #[test]
    fn a_detached_row_reads_no_upstream() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let first_sha = head_sha(&repo);
        git(&repo, &["commit", "--allow-empty", "-m", "second"]);
        git(&repo, &["checkout", "--detach", &first_sha]);
        add_origin_remote(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let settled = refresh_and_settle(&core);

        match sync_of(&settled, &repo) {
            Some(Settled::Known {
                value: SyncState::NoUpstream,
                at: _,
                stale: _,
            }) => {}
            other => panic!("expected a detached row to read no upstream, got {other:?}"),
        }
    }

    /// Named case 6 of 6: a Repo with no remote at all. The propagation half of
    /// criterion 3 is the substance here, not the Repo row alone: a linked Worktree
    /// shares the parent's config and has no upstream of its own to speak of either,
    /// so it must read the exact same `NoRemote` value, not `NoUpstream`.
    #[test]
    fn a_repo_with_no_remote_reads_no_remote_on_itself_and_every_worktree() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        let worktree = root.join("feature");
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature",
                worktree.to_str().expect("utf8 path"),
            ],
        );

        let core = Core::start_discovered(spec(vec![root]));
        let settled = refresh_and_settle(&core);

        assert_eq!(
            settled.entities.len(),
            2,
            "expected the parent Repo and its one linked Worktree"
        );
        for path in [&parent, &worktree] {
            match sync_of(&settled, path) {
                Some(Settled::Known {
                    value: SyncState::NoRemote,
                    at: _,
                    stale: _,
                }) => {}
                other => panic!(
                    "expected {} to read no remote at all, got {other:?}",
                    path.display()
                ),
            }
        }
    }

    /// Criterion 1's "every entity" half: two sibling Worktrees under one Repo, each
    /// with a different sync outcome, computed together in one Generation. A test
    /// driving only one of them could not see an implementation that dispatches the
    /// comparison for a single hand-picked entity rather than every one whose HEAD
    /// carries a branch.
    #[test]
    fn sync_is_computed_for_every_entity_dispatched_this_generation_not_only_one() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let parent = root.join("parent");
        init_repo_with_a_commit(&parent);
        let fork_sha = head_sha(&parent);
        add_origin_remote(&parent);

        let ahead_worktree = root.join("feature-ahead");
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature-ahead",
                ahead_worktree.to_str().expect("utf8 path"),
            ],
        );
        set_upstream(&parent, "feature-ahead", &fork_sha);
        git(
            &ahead_worktree,
            &["commit", "--allow-empty", "-m", "unpushed"],
        );

        let behind_worktree = root.join("feature-behind");
        git(
            &parent,
            &[
                "worktree",
                "add",
                "-b",
                "feature-behind",
                behind_worktree.to_str().expect("utf8 path"),
            ],
        );
        git(
            &behind_worktree,
            &["commit", "--allow-empty", "-m", "on the remote only"],
        );
        let ahead_of_behind_sha = head_sha(&behind_worktree);
        git(&behind_worktree, &["reset", "--hard", "HEAD~1"]);
        set_upstream(&parent, "feature-behind", &ahead_of_behind_sha);

        let core = Core::start_discovered(spec(vec![root]));
        let settled = refresh_and_settle(&core);

        match sync_of(&settled, &ahead_worktree) {
            Some(Settled::Known {
                value:
                    SyncState::Tracking(AheadBehind {
                        ahead: 1,
                        behind: 0,
                    }),
                at: _,
                stale: _,
            }) => {}
            other => panic!("expected feature-ahead to read 1 ahead, got {other:?}"),
        }
        match sync_of(&settled, &behind_worktree) {
            Some(Settled::Known {
                value:
                    SyncState::Tracking(AheadBehind {
                        ahead: 0,
                        behind: 1,
                    }),
                at: _,
                stale: _,
            }) => {}
            other => panic!("expected feature-behind to read 1 behind, got {other:?}"),
        }
    }

    /// Criterion 1's "every Generation" half: a second, later refresh recomputes
    /// `sync` rather than a first Generation's answer sticking around unrefreshed.
    /// A test that only ever drives one Generation cannot see an implementation
    /// that dispatches the comparison once, at `Core::start`'s own discovery, and
    /// never again on an explicit `refresh`.
    #[test]
    fn sync_recomputes_on_a_second_generation_not_only_the_first() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let fork_sha = head_sha(&repo);
        add_origin_remote(&repo);
        set_upstream(&repo, "main", &fork_sha);

        let core = Core::start_discovered(spec(vec![root]));
        let first = refresh_and_settle(&core);
        match sync_of(&first, &repo) {
            Some(Settled::Known {
                value:
                    SyncState::Tracking(AheadBehind {
                        ahead: 0,
                        behind: 0,
                    }),
                at: _,
                stale: _,
            }) => {}
            other => panic!("expected the first Generation level with its upstream, got {other:?}"),
        }

        git(
            &repo,
            &[
                "commit",
                "--allow-empty",
                "-m",
                "second Generation's own work",
            ],
        );
        let second = refresh_and_settle(&core);
        match sync_of(&second, &repo) {
            Some(Settled::Known {
                value:
                    SyncState::Tracking(AheadBehind {
                        ahead: 1,
                        behind: 0,
                    }),
                at: _,
                stale: _,
            }) => {}
            other => panic!(
                "expected the second Generation to recompute and read 1 ahead, got {other:?}"
            ),
        }
    }

    /// The Worktree-reporting criterion: after a default branch moves, the Worktrees
    /// now behind it are reported by name. `base` (the same "behind the default branch"
    /// count [`base.rs`] computes and every row's own `name` already carries) is what
    /// "reported by name" means in practice: a snapshot reader finds each Worktree by
    /// the name on its row, not by position, so this test does the same, matching each
    /// assertion to its own fixture's name rather than to "the first" or "the last"
    /// entity.
    ///
    /// `wt-behind` is branched from the default branch's tip before it moves and is left
    /// untouched, the same shape a fetch leaves an existing linked Worktree in; `wt-
    /// caught-up` is branched from the tip *after* it moves, so it is unaffected. Two
    /// Worktrees are required, not one: a test with only `wt-behind` would still pass
    /// against an implementation that reports every Worktree as behind regardless of
    /// whether it actually is, and a test that asserted only "something is reported"
    /// would pass even if the names or the counts were swapped.
    #[test]
    fn worktrees_now_behind_a_moved_default_branch_are_reported_by_name() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let sha_a = head_sha(&repo);
        add_origin_remote(&repo);
        set_upstream(&repo, "main", &sha_a);

        let behind_path = root.join("wt-behind");
        git(
            &repo,
            &[
                "worktree",
                "add",
                "-b",
                "topic-behind",
                behind_path.to_str().expect("utf8 path"),
                "main",
            ],
        );

        // Moves only the default branch's own remote-tracking ref, the same shape a
        // fetch leaves behind: `repo`'s own checked-out `main` does not move, so this
        // is deliberately not exercising the auto-update itself, only what a moved
        // default branch does to every Worktree's own `base` count.
        git(&repo, &["checkout", "-b", "scratch"]);
        git(&repo, &["commit", "--allow-empty", "-m", "second"]);
        let sha_b = head_sha(&repo);
        git(&repo, &["checkout", "main"]);
        git(&repo, &["update-ref", "refs/remotes/origin/main", &sha_b]);
        git(&repo, &["branch", "-D", "scratch"]);

        // Branched from the plain commit sha, not `refs/remotes/origin/main` itself:
        // starting a new branch from a remote-tracking ref makes git auto-configure it
        // to track that same ref, which would make this row the default branch's own
        // row (`base.rs`'s `branch_is_default_branchs_own_row`) and settle `base` as
        // `NotApplicable` rather than the `0` this fixture means to prove.
        let caught_up_path = root.join("wt-caught-up");
        git(
            &repo,
            &[
                "worktree",
                "add",
                "-b",
                "topic-caught-up",
                caught_up_path.to_str().expect("utf8 path"),
                &sha_b,
            ],
        );

        let core = Core::start_discovered(spec(vec![root]));
        let snapshot = refresh_and_settle(&core);

        let base_of = |name: &str| -> u32 {
            let entity = snapshot
                .entities
                .iter()
                .find(|entity| &*entity.name == name)
                .unwrap_or_else(|| panic!("no entity named {name} in {snapshot:?}"));
            match entity.base.settled() {
                Some(Settled::Known {
                    value,
                    at: _,
                    stale: _,
                }) => *value,
                other => panic!("expected a known base count for {name}, got {other:?}"),
            }
        };

        assert!(
            base_of("wt-behind") > 0,
            "a Worktree branched before the default branch moved must be reported behind"
        );
        assert_eq!(
            base_of("wt-caught-up"),
            0,
            "a Worktree branched from the new tip must not be reported behind"
        );
    }

    /// The periodic fetch's own scheduler: criterion 3's five rules
    /// ([refresh.md](https://github.com/paulchiu/repon/blob/main/docs/spec/refresh.md)'s
    /// "The periodic fetch"). Every fixture here is a bare repo this test creates plus a
    /// real `git clone` of it, per the standing constraint that a fetch test never
    /// touches a real remote or the network.
    mod fetch_scheduler {
        use super::*;
        use crate::liveness::wait_for_or;

        fn fetch_spec(enabled: bool, root: PathBuf) -> CoreSpec {
            let mut spec = spec(vec![root]);
            spec.fetch = FetchSpec {
                enabled,
                interval: Duration::from_secs(3600),
                concurrency: 4,
            };
            spec
        }

        /// A bare "remote" this call creates and seeds with one commit, never a real
        /// remote and never touched over the network.
        fn seeded_remote() -> tempfile::TempDir {
            let remote = tempfile::tempdir().expect("temp dir");
            crate::test_support::init_bare(remote.path());
            crate::test_support::push_new_commit(remote.path(), "README.md", "seed\n");
            remote
        }

        fn clone_into(remote: &Path, dest: &Path) {
            let status = Command::new("git")
                .arg("clone")
                .arg(remote)
                .arg(dest)
                .status()
                .expect("run git clone");
            assert!(status.success());
            crate::test_support::set_identity(dest);
        }

        /// The scheduler's first rule: enabling the periodic fetch runs one cycle
        /// immediately rather than waiting for `fetch.interval` to elapse. `fetch_ticks`
        /// is `crossbeam_channel::never()`, so the only way `fetch_cycle_count_for_test`
        /// can ever move is the immediate cycle `start_internal` dispatches on its own
        /// plain thread; a scheduler that only reacted to a tick would leave this at
        /// zero forever.
        #[test]
        fn enabling_the_periodic_fetch_runs_one_cycle_before_any_tick_arrives() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            clone_into(remote.path(), &root_path.join("parent"));

            let fetch_ticks: Receiver<Instant> = crossbeam_channel::never();
            let started = Core::start_for_test_with_fetch(
                fetch_spec(true, root_path),
                Duration::from_secs(3600),
                crossbeam_channel::never(),
                fetch_ticks,
            )
            .discovered();
            let core = started.core;

            wait_for(
                "the periodic fetch to run its first cycle without waiting for a tick",
                || core.fetch_cycle_count_for_test() >= 1,
            );
        }

        /// A tick on the periodic fetch's own channel runs a second cycle, proving the
        /// recurring cadence is wired to the same dedicated thread the immediate cycle
        /// used, not merely a one-shot dispatched at start.
        #[test]
        fn a_tick_on_the_fetch_channel_runs_another_cycle() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            clone_into(remote.path(), &root_path.join("parent"));

            let (fetch_tick_tx, fetch_tick_rx) = crossbeam_channel::unbounded();
            let started = Core::start_for_test_with_fetch(
                fetch_spec(true, root_path),
                Duration::from_secs(3600),
                crossbeam_channel::never(),
                fetch_tick_rx,
            )
            .discovered();
            let core = started.core;

            wait_for("the immediate cycle to have run first", || {
                core.fetch_cycle_count_for_test() >= 1
            });

            fetch_tick_tx
                .send(Instant::now())
                .expect("send a fetch tick");

            wait_for("a tick on the fetch channel to run a second cycle", || {
                core.fetch_cycle_count_for_test() >= 2
            });
        }

        /// Points `repo`'s `origin` at a path nothing lives at, breaking `fetch_and_prune`
        /// alone: discovery has already found `repo` as a real Repo before this runs, so
        /// only the fetch itself fails, never the walk. A local path rather than a loopback
        /// address, so this never touches even the machine's own network stack, the same
        /// standing constraint every fixture in this module already holds to.
        fn break_remote(repo: &Path) {
            let status = Command::new("git")
                .arg("-C")
                .arg(repo)
                .args(["remote", "set-url", "origin", "/nonexistent-remote-282"])
                .status()
                .expect("run git remote set-url");
            assert!(status.success());
        }

        /// Criterion: a cycle where every fetch succeeds reports no failures.
        #[test]
        fn a_cycle_in_which_every_fetch_succeeds_reports_no_failures() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            clone_into(remote.path(), &root_path.join("parent"));

            let fetch_ticks: Receiver<Instant> = crossbeam_channel::never();
            let started = Core::start_for_test_with_fetch(
                fetch_spec(true, root_path),
                Duration::from_secs(3600),
                crossbeam_channel::never(),
                fetch_ticks,
            )
            .discovered();
            let core = started.core;

            wait_for("the periodic fetch to run its first cycle", || {
                core.fetch_cycle_count_for_test() >= 1
            });

            assert!(
                core.fetch_failures().failed.is_empty(),
                "a cycle where every fetch succeeds must report no failures, got: {:?}",
                core.fetch_failures().failed
            );
        }

        /// A cycle in which one repository cannot be fetched counts that one failure, and
        /// the per-repository independence at the fetch loop's own swallow is unchanged,
        /// proven here by the sibling repository still fetching.
        #[test]
        fn a_repository_that_cannot_be_fetched_is_counted_while_its_sibling_still_fetches() {
            let good_remote = seeded_remote();
            let bad_remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            let good = root_path.join("good");
            let bad = root_path.join("bad");
            clone_into(good_remote.path(), &good);
            clone_into(bad_remote.path(), &bad);
            break_remote(&bad);

            crate::test_support::push_new_commit(good_remote.path(), "second.txt", "second\n");
            let good_remote_tip = rev_parse(good_remote.path(), "refs/heads/main");

            let fetch_ticks: Receiver<Instant> = crossbeam_channel::never();
            let started = Core::start_for_test_with_fetch(
                fetch_spec(true, root_path),
                Duration::from_secs(3600),
                crossbeam_channel::never(),
                fetch_ticks,
            )
            .discovered();
            let core = started.core;

            wait_for(
                "the cycle to run and count the one repository it could not fetch",
                || core.fetch_failures().failed.len() == 1,
            );

            let failures = core.fetch_failures();
            assert_eq!(
                failures.failed.len(),
                1,
                "exactly one repository failed, so exactly one failure must be counted, \
                 got: {:?}",
                failures.failed
            );
            assert!(
                failures.failed[0].0.to_string_lossy().contains("bad"),
                "the counted failure must name the repository that actually failed, \
                 got: {:?}",
                failures.failed
            );

            wait_for(
                "the sibling repository to still fetch despite the other one failing",
                || rev_parse(&good, "refs/remotes/origin/main") == good_remote_tip,
            );
        }

        /// [`crate::test_support::push_new_commit`], but onto `branch` rather than
        /// always `main`: this scheduler test needs a second commit on `topic`
        /// specifically, so ancestry alone cannot call it merged into `main`.
        fn push_new_commit_on_branch(remote: &Path, branch: &str, name: &str, contents: &str) {
            let contributor = tempfile::tempdir().expect("temp dir");
            let status = Command::new("git")
                .arg("clone")
                .arg("--branch")
                .arg(branch)
                .arg(remote)
                .arg(contributor.path())
                .status()
                .expect("run git clone");
            assert!(status.success());
            std::fs::write(contributor.path().join(name), contents).expect("write fixture file");
            git(contributor.path(), &["add", name]);
            git(contributor.path(), &["commit", "-m", "extra work on topic"]);
            git(contributor.path(), &["push", "origin", branch]);
        }

        /// Criteria 3 and 4 together, end to end: the periodic fetch always prunes, so
        /// `Gone` can appear at all, and a finished fetch starts one normal Generation
        /// on its own, so the pruned state actually lands on the table without the test
        /// calling `refresh` itself. `topic` carries a commit `main` never gets, so
        /// ancestry alone cannot call it `Merged`; deleting it upstream before the
        /// scheduler's own fetch is what a plain, non-pruning fetch could never turn
        /// into `Gone`.
        #[test]
        fn a_finished_fetch_prunes_and_starts_its_own_generation_that_lands_gone() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            let parent = root_path.join("parent");
            clone_into(remote.path(), &parent);

            git(remote.path(), &["branch", "topic"]);
            push_new_commit_on_branch(remote.path(), "topic", "topic.txt", "extra work\n");

            // A deliberate, ordinary fetch by the test's own setup, distinct from the
            // Core's own periodic fetch under test: `parent` was cloned before `topic`
            // existed, so this is what teaches it about `origin/topic` at all, the same
            // way any real clone would only learn of a branch created after it cloned
            // on its own next fetch.
            git(&parent, &["fetch", "origin"]);

            let worktree_path = root_path.join("topic-worktree");
            git(
                &parent,
                &[
                    "worktree",
                    "add",
                    "-b",
                    "topic",
                    worktree_path.to_str().expect("utf8 path"),
                    "origin/topic",
                ],
            );

            // Deleted only now, after the worktree already tracks it: this is the
            // upstream disappearance a plain fetch can see but never prune away, and
            // exactly what the scheduler's own fetch (not this setup) must prune.
            git(remote.path(), &["branch", "-D", "topic"]);

            let fetch_ticks: Receiver<Instant> = crossbeam_channel::never();
            let started = Core::start_for_test_with_fetch(
                fetch_spec(true, root_path),
                Duration::from_secs(3600),
                crossbeam_channel::never(),
                fetch_ticks,
            )
            .discovered();
            let core = started.core;

            wait_for_or(
                "a finished fetch's own Generation to land the pruned Worktree as Gone \
                 without the test ever calling refresh",
                || {
                    core.snapshot()
                        .entities
                        .iter()
                        .filter(|entity| matches!(entity.kind, Kind::Worktree))
                        .any(|entity| {
                            matches!(
                                entity.state.settled(),
                                Some(Settled::Known {
                                    value: WorktreeState::Gone,
                                    at: _,
                                    stale: _,
                                })
                            )
                        })
                },
                || {
                    format!(
                        "snapshot: {:?}",
                        core.snapshot()
                            .entities
                            .iter()
                            .map(|entity| (entity.kind, entity.state.settled().cloned()))
                            .collect::<Vec<_>>()
                    )
                },
            );
        }

        fn spec_with_auto_update(
            fetch_enabled: bool,
            auto_update_enabled: bool,
            root: PathBuf,
        ) -> CoreSpec {
            let mut spec = fetch_spec(fetch_enabled, root);
            spec.auto_update = AutoUpdateSpec {
                enabled: auto_update_enabled,
            };
            spec
        }

        fn rev_parse(path: &Path, rev: &str) -> String {
            let output = Command::new("git")
                .arg("-C")
                .arg(path)
                .args(["rev-parse", rev])
                .output()
                .expect("run git rev-parse");
            assert!(output.status.success(), "git rev-parse {rev} failed");
            String::from_utf8(output.stdout)
                .expect("utf8 sha")
                .trim()
                .to_string()
        }

        /// Criterion 1's "off by default" half: `fetch.enabled` alone is not enough to
        /// move a branch. `fetch_ticks` never fires, so the only cycle that can possibly
        /// run is the immediate one `start_internal` dispatches on being enabled; that
        /// cycle fetches (`fetch_cycle_count_for_test` proves it ran) and must still
        /// leave the eligible local branch exactly where it was, since `auto_update`
        /// carries its own, separate `enabled` flag this spec never turns on.
        #[test]
        fn auto_update_is_off_by_default_even_with_fetch_enabled() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            let parent = root_path.join("parent");
            clone_into(remote.path(), &parent);
            let before = rev_parse(&parent, "refs/heads/main");

            crate::test_support::push_new_commit(remote.path(), "second.txt", "second\n");

            let fetch_ticks: Receiver<Instant> = crossbeam_channel::never();
            let started = Core::start_for_test_with_fetch(
                spec_with_auto_update(true, false, root_path),
                Duration::from_secs(3600),
                crossbeam_channel::never(),
                fetch_ticks,
            )
            .discovered();
            let core = started.core;

            wait_for(
                "the periodic fetch to still run its immediate cycle",
                || core.fetch_cycle_count_for_test() >= 1,
            );
            assert_eq!(
                rev_parse(&parent, "refs/heads/main"),
                before,
                "an eligible branch must not move while auto_update.enabled is false, \
                 even though fetch.enabled is true"
            );
        }

        /// Criterion 1's "rides the fetch cycle with no timer of its own" half: the
        /// remote is already ahead *before* `Core::start`, `fetch_ticks` is
        /// `crossbeam_channel::never()` so no recurring tick ever fires, and yet the
        /// eligible branch still moves, proving the auto-update ran on the same
        /// immediate first cycle the periodic fetch itself uses rather than waiting on
        /// any tick of its own.
        #[test]
        fn auto_update_enabled_rides_the_immediate_fetch_cycle_with_no_timer_of_its_own() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            let parent = root_path.join("parent");
            clone_into(remote.path(), &parent);

            crate::test_support::push_new_commit(remote.path(), "second.txt", "second\n");
            let remote_tip = rev_parse(remote.path(), "refs/heads/main");

            let fetch_ticks: Receiver<Instant> = crossbeam_channel::never();
            let started = Core::start_for_test_with_fetch(
                spec_with_auto_update(true, true, root_path),
                Duration::from_secs(3600),
                crossbeam_channel::never(),
                fetch_ticks,
            )
            .discovered();
            // Kept alive, unused otherwise: dropping `Core` joins its dedicated thread,
            // which would stop the immediate cycle this test is waiting on.
            let _core = started.core;

            wait_for(
                "the eligible branch to fast-forward on the immediate cycle alone, with no \
                 fetch tick and no auto-update tick of its own",
                || rev_parse(&parent, "refs/heads/main") == remote_tip,
            );
        }
    }

    /// [`Core::attempt_auto_update`] must answer exactly what
    /// [`crate::auto_update::attempt`] would for the same Repo, since it delegates to that
    /// function rather than reimplementing its own copy of the eligibility rules: the
    /// built-in `sync` action's own "reuses `auto_update`'s existing rules rather than a
    /// second implementation"
    /// ([repo-management.md](https://github.com/paulchiu/repon/blob/main/docs/spec/repo-management.md))
    /// is proven here, at the one seam a reimplementation could actually diverge from the
    /// rules it is supposed to reuse. Every fixture is a bare repo this test creates plus a
    /// real `git clone` of it, the same standing constraint `fetch_scheduler` above follows.
    mod attempt_auto_update {
        use super::*;

        fn seeded_remote() -> tempfile::TempDir {
            let remote = tempfile::tempdir().expect("temp dir");
            crate::test_support::init_bare(remote.path());
            crate::test_support::push_new_commit(remote.path(), "README.md", "seed\n");
            remote
        }

        fn clone_into(remote: &Path, dest: &Path) {
            let status = Command::new("git")
                .arg("clone")
                .arg(remote)
                .arg(dest)
                .status()
                .expect("run git clone");
            assert!(status.success());
            crate::test_support::set_identity(dest);
        }

        /// Discovers `root`'s one Repo and hands back the live `Core` alongside its key,
        /// the same `Core::start_discovered` plus `settle` shape [`delete_risk`]'s own tests
        /// already use: this method reads the repository fresh, not a Cell, so discovery's
        /// own read-only probes running first are never a race with it.
        fn discover_repo(root: &Path) -> (Core, EntityKey) {
            let core = Core::start_discovered(spec(vec![root.to_path_buf()]));
            let key = core
                .settle()
                .entities
                .into_iter()
                .find(|entity| entity.kind == Kind::Repo)
                .expect("the Repo row is discovered")
                .key;
            (core, key)
        }

        /// The eligible condition: clean, behind, not ahead, tracking an upstream. Proves
        /// the wrapper both classifies and actually moves the branch, not only the former.
        #[test]
        fn an_eligible_repo_fast_forwards_through_the_wrapper_too() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            let repo = root_path.join("repo");
            clone_into(remote.path(), &repo);
            crate::test_support::push_new_commit(remote.path(), "second.txt", "second\n");
            crate::test_support::git(&repo, &["fetch", "origin"]);

            let (core, key) = discover_repo(&root_path);

            assert_eq!(core.attempt_auto_update(&key), AutoUpdateAttempt::Updated);
            assert!(
                repo.join("second.txt").exists(),
                "the fast-forward must reach the working tree through the wrapper too"
            );
        }

        /// Condition 1: a dirty working tree.
        #[test]
        fn a_dirty_repo_is_reported_not_clean_through_the_wrapper_too() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            let repo = root_path.join("repo");
            clone_into(remote.path(), &repo);
            crate::test_support::push_new_commit(remote.path(), "second.txt", "second\n");
            crate::test_support::git(&repo, &["fetch", "origin"]);
            fs::write(repo.join("stray.txt"), "uncommitted\n").expect("write a stray file");

            let (core, key) = discover_repo(&root_path);

            assert_eq!(core.attempt_auto_update(&key), AutoUpdateAttempt::NotClean);
        }

        /// Condition 2: already level with the upstream.
        #[test]
        fn an_up_to_date_repo_is_reported_not_behind_through_the_wrapper_too() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            let repo = root_path.join("repo");
            clone_into(remote.path(), &repo);
            crate::test_support::git(&repo, &["fetch", "origin"]);

            let (core, key) = discover_repo(&root_path);

            assert_eq!(core.attempt_auto_update(&key), AutoUpdateAttempt::NotBehind);
        }

        /// Condition 3: a local commit the upstream does not have.
        #[test]
        fn an_unpublished_local_commit_is_reported_not_fast_forward_through_the_wrapper_too() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            let repo = root_path.join("repo");
            clone_into(remote.path(), &repo);
            crate::test_support::push_new_commit(remote.path(), "second.txt", "second\n");
            crate::test_support::git(&repo, &["fetch", "origin"]);
            crate::test_support::commit_file(&repo, "local-only.txt", "never pushed\n");

            let (core, key) = discover_repo(&root_path);

            assert_eq!(
                core.attempt_auto_update(&key),
                AutoUpdateAttempt::NotFastForward
            );
        }

        /// Condition 4: no upstream configured at all.
        #[test]
        fn a_branch_with_no_upstream_is_reported_through_the_wrapper_too() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            let repo = root_path.join("repo");
            clone_into(remote.path(), &repo);
            crate::test_support::git(&repo, &["checkout", "-b", "untracked-branch"]);

            let (core, key) = discover_repo(&root_path);

            assert_eq!(
                core.attempt_auto_update(&key),
                AutoUpdateAttempt::NoUpstream
            );
        }
    }

    /// [default-branch.md](https://github.com/paulchiu/repon/blob/main/docs/spec/default-branch.md)'s
    /// "The network": criterion 3 (the local chain answers first, and only a later network
    /// round trip supersedes it) and criterion 4 (`Core::rederive_default_branches` runs the
    /// same lookup on demand, over exactly the given keys, without fetching). Every fixture
    /// here is a bare repo this test creates plus a real `git clone` of it, the same standing
    /// constraint `fetch_scheduler` above already follows.
    mod network_default_branch {
        use super::*;

        fn seeded_remote() -> tempfile::TempDir {
            let remote = tempfile::tempdir().expect("temp dir");
            crate::test_support::init_bare(remote.path());
            crate::test_support::push_new_commit(remote.path(), "README.md", "seed\n");
            remote
        }

        fn clone_into(remote: &Path, dest: &Path) {
            let status = Command::new("git")
                .arg("clone")
                .arg(remote)
                .arg(dest)
                .status()
                .expect("run git clone");
            assert!(status.success());
            crate::test_support::set_identity(dest);
        }

        /// Sets `path`'s own `HEAD` (a bare repo, so this is the "remote"'s advertised
        /// answer) to point at `branch`, without checking anything out.
        fn set_remote_head(path: &Path, branch: &str) {
            git(
                path,
                &["symbolic-ref", "HEAD", &format!("refs/heads/{branch}")],
            );
        }

        fn rev_parse(path: &Path, rev: &str) -> String {
            let output = Command::new("git")
                .arg("-C")
                .arg(path)
                .args(["rev-parse", rev])
                .output()
                .expect("run git rev-parse");
            assert!(output.status.success());
            String::from_utf8(output.stdout)
                .expect("utf8 sha")
                .trim()
                .to_string()
        }

        fn default_branch_name(entity: &EntityState) -> Option<String> {
            match entity.default_branch.settled() {
                Some(Settled::Known {
                    value,
                    at: _,
                    stale: _,
                }) => Some(value.name().to_string()),
                _ => None,
            }
        }

        /// Criterion 3: with a reachable remote whose advertised HEAD differs from the
        /// clone's own cached `origin/HEAD`, a plain refresh still answers from the local
        /// chain alone (the network is never consulted just to render a Generation), and
        /// only [`Core::rederive_default_branches`] actually reaching the remote supersedes
        /// it, for the rest of this `Core`'s own session (default-branch.md's "The network":
        /// "supersedes the local one for that session"). The mutation this is chosen to
        /// catch: were `supersede_with_network` never applied (or applied unconditionally
        /// before the local chain even ran), either the first assertion would already read
        /// `origin/trunk`, or the second would still read `origin/main`.
        #[test]
        fn the_local_chain_answers_first_and_only_a_later_network_round_trip_supersedes_it() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            let repo_path = root_path.join("repo");
            clone_into(remote.path(), &repo_path);

            // The clone's own cached `origin/HEAD` still names `main`; the remote's own
            // current answer is changed to a different, real branch only after cloning.
            git(remote.path(), &["branch", "trunk"]);
            set_remote_head(remote.path(), "trunk");

            let core = Core::start_discovered(spec(vec![root_path]));
            let key = core.snapshot().entities[0].key.clone();

            core.refresh(std::slice::from_ref(&key));
            let settled = core.settle();
            assert_eq!(
                default_branch_name(&settled.entities[0]),
                Some("origin/main".to_string()),
                "a plain refresh must answer from the local chain alone, unaffected by the \
                 remote's own current (but not yet asked) truth"
            );

            core.rederive_default_branches(std::slice::from_ref(&key));
            let settled = core.settle();
            assert_eq!(
                default_branch_name(&settled.entities[0]),
                Some("origin/trunk".to_string()),
                "once the network round trip actually ran, its own differing answer must \
                 supersede the local chain's"
            );
        }

        /// Criterion 4: [`Core::rederive_default_branches`] runs the same lookup on demand,
        /// over exactly the given keys, without fetching. "Without fetching" is shown the
        /// way `fetch.rs`'s own `a_fetch_transfers_new_commits_so_a_behind_count_can_move`
        /// shows a real fetch moving one, the mirror image: the remote gains a new commit
        /// after the clone, and this call must leave the clone's own remote-tracking ref
        /// exactly where it was, because `probe_remote_head`'s handshake-only lookup
        /// transfers no pack. "Over the Selection" is exercised as "over exactly the given
        /// keys": a second, unrelated repo stands in for a row outside it, and its whole
        /// entity state (every cell, not only `default_branch`) is asserted unchanged.
        #[test]
        fn rederive_default_branches_never_fetches_and_leaves_a_row_outside_it_untouched() {
            let remote = seeded_remote();
            let root = tempfile::tempdir().expect("temp dir");
            let root_path = root_of(&root);
            let selected_path = root_path.join("selected");
            let outside_path = root_path.join("outside");
            clone_into(remote.path(), &selected_path);
            init_repo_with_a_commit(&outside_path);

            git(remote.path(), &["branch", "trunk"]);
            crate::test_support::push_new_commit(remote.path(), "second.txt", "second\n");
            set_remote_head(remote.path(), "trunk");
            let before_tracking = rev_parse(&selected_path, "refs/remotes/origin/main");

            let core = Core::start_discovered(spec(vec![root_path]));
            let snapshot = core.snapshot();
            let selected_key = snapshot
                .entities
                .iter()
                .find(|entity| entity.key.path() == selected_path)
                .expect("discovered the selected repo")
                .key
                .clone();
            let outside_key = snapshot
                .entities
                .iter()
                .find(|entity| entity.key.path() == outside_path)
                .expect("discovered the outside repo")
                .key
                .clone();

            core.refresh(&[selected_key.clone(), outside_key.clone()]);
            let settled = core.settle();
            let outside_before = format!(
                "{:?}",
                settled
                    .entities
                    .iter()
                    .find(|entity| entity.key == outside_key)
                    .expect("outside entity present")
            );

            core.rederive_default_branches(std::slice::from_ref(&selected_key));
            let settled = core.settle();

            let selected_after = settled
                .entities
                .iter()
                .find(|entity| entity.key == selected_key)
                .expect("selected entity present");
            assert_eq!(
                default_branch_name(selected_after),
                Some("origin/trunk".to_string()),
                "the rederive must have reached the remote's own current, differing answer"
            );

            let after_tracking = rev_parse(&selected_path, "refs/remotes/origin/main");
            assert_eq!(
                before_tracking, after_tracking,
                "a rederive must never fetch: the remote-tracking ref must not have moved \
                 even though the remote gained a new commit"
            );

            let outside_after = format!(
                "{:?}",
                settled
                    .entities
                    .iter()
                    .find(|entity| entity.key == outside_key)
                    .expect("outside entity present")
            );
            assert_eq!(
                outside_before, outside_after,
                "a row outside the rederive's own keys must be left exactly as it was, not \
                 only on its default_branch cell"
            );
        }
    }

    // =====================================================================================
    // `set_exclusions`: `[[repo]]`'s `exclude` re-applied live, with no rebuild and no
    // rediscovery, per repo-management.md's "Writing config".
    // =====================================================================================

    /// The live half: a row already in the table becomes excluded, and is subtracted from
    /// `operable_count`, without a rebuilt `Core` and without a Generation of any kind.
    #[test]
    fn set_exclusions_excludes_a_row_already_in_the_table_with_no_rebuild() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec(vec![root]));
        let snapshot = core.settle();
        let key = snapshot.entities[0].key.clone();
        let generation_before = snapshot.generation;
        assert!(
            !snapshot.entities[0].excluded,
            "nothing excludes it to start with"
        );
        assert_eq!(core.operable_count(std::slice::from_ref(&key)), 1);

        core.set_exclusions(&[RepoOverride {
            path: repo.clone(),
            default_branch: None,
            excluded: true,
        }]);

        let after = core.snapshot();
        assert!(
            after.entities[0].excluded,
            "the row the write named is excluded in the very next snapshot"
        );
        assert_eq!(
            core.operable_count(&[key]),
            0,
            "an excluded row is subtracted from what an operation may reach"
        );
        assert_eq!(
            after.generation, generation_before,
            "re-applying an operate-time filter must start no Generation of its own"
        );
    }

    /// The other direction: dropping the entry clears the flag, so a row ignored and shown
    /// again in one session ends where it started.
    #[test]
    fn set_exclusions_clears_the_flag_when_the_entry_is_gone() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);

        let core = Core::start_discovered(spec_with_overrides(
            vec![root],
            vec![RepoOverride {
                path: repo.clone(),
                default_branch: None,
                excluded: true,
            }],
        ));
        assert!(
            core.settle().entities[0].excluded,
            "the starting override excludes it"
        );

        core.set_exclusions(&[]);

        assert!(
            !core.snapshot().entities[0].excluded,
            "removing the entry unexcludes the row in the very next snapshot"
        );
    }

    /// The boundary the specification draws around the live half: `exclude` re-applies and
    /// `default_branch` does not, because one is an operate-time filter and the other is a
    /// probe input. A `set_exclusions` that swapped the whole `[[repo]]` reading in would
    /// move both, which is what this refuses.
    #[test]
    fn set_exclusions_moves_exclude_alone_and_never_the_default_branch_override() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        crate::test_support::git(&repo, &["branch", "trunk"]);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.settle().entities[0].key.clone();
        core.refresh(std::slice::from_ref(&key));
        let before = format!("{:?}", core.settle().entities[0].default_branch.settled());

        core.set_exclusions(&[RepoOverride {
            path: repo.clone(),
            default_branch: Some("trunk".to_string()),
            excluded: true,
        }]);
        core.refresh(&[key]);
        core.settle();

        let after = core.snapshot();
        assert!(after.entities[0].excluded, "exclude took effect");
        assert_eq!(
            format!("{:?}", after.entities[0].default_branch.settled()),
            before,
            "a default_branch override reaches a session only through a rebuilt Core"
        );
    }

    // =====================================================================================
    // `record_own_work`: the receipt a Management operation leaves, docs/spec/repo-management.md
    // =====================================================================================

    /// One receipt per named row, and the shape the caller never gets to choose: `running` is
    /// `None`, `skip` is `None` (a refusal is not an excluded row), and there is
    /// exactly one step, because such an operation is one act rather than an ordered list.
    #[test]
    fn record_own_work_leaves_one_receipt_per_row_it_names_and_none_elsewhere() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("repo-a"));
        init_repo_with_a_commit(&root.join("repo-b"));

        let core = Core::start_discovered(spec(vec![root]));
        let entities = core.settle().entities;
        let named = entities
            .iter()
            .find(|entity| &*entity.name == "repo-a")
            .expect("repo-a is discovered")
            .key
            .clone();

        core.record_own_work(
            "ignore",
            &[(
                named.clone(),
                OwnWork::Refused(Arc::from("refused, already ignored")),
                Duration::from_millis(7),
            )],
        );

        let after = core.snapshot().entities;
        let receipt = after
            .iter()
            .find(|entity| entity.key == named)
            .and_then(|entity| entity.last_action.clone())
            .expect("the row it named carries a receipt");
        assert_eq!(&*receipt.label, "ignore");
        assert!(
            !receipt.not_applicable(),
            "a refusal is not an excluded row"
        );
        assert!(receipt.running.is_none(), "the work is already done");
        assert_eq!(receipt.steps.len(), 1, "one act, not an ordered list");
        assert_eq!(&*receipt.steps[0].label, "ignore");
        assert_eq!(receipt.steps[0].elapsed, Duration::from_millis(7));
        assert!(receipt.steps[0].output.is_empty(), "nothing to quote");
        assert!(receipt.steps[0].elision.is_none());
        assert_eq!(
            receipt.steps[0].outcome,
            StepOutcome::OwnWork(OwnWork::Refused(Arc::from("refused, already ignored"))),
        );
        assert!(
            after
                .iter()
                .filter(|entity| entity.key != named)
                .all(|entity| entity.last_action.is_none()),
            "no row this did not name takes a receipt"
        );
    }

    /// A key the table no longer holds is skipped rather than panicking or landing on the
    /// wrong row, the same fallback every key-addressed entry point here gives one: a `delete`
    /// whose Repo is already gone is exactly this case.
    #[test]
    fn record_own_work_skips_a_key_the_table_no_longer_holds() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        init_repo_with_a_commit(&root.join("repo-a"));

        let core = Core::start_discovered(spec(vec![root]));
        let entities = core.settle().entities;
        let stranger = EntityKey::new(Arc::from(std::path::Path::new("/nowhere/at/all")));

        core.record_own_work(
            "delete",
            &[(stranger, OwnWork::Did(Arc::from("gone")), Duration::ZERO)],
        );

        assert!(
            core.snapshot()
                .entities
                .iter()
                .all(|entity| entity.last_action.is_none()),
            "an unknown key writes nothing anywhere"
        );
        assert_eq!(core.snapshot().entities.len(), entities.len());
    }

    // =====================================================================================
    // `delete_risk`: the three facts repo-management.md's confirm gate names per Repo, read
    // rather than stubbed. Every repository here is built in a temp directory this test owns,
    // and no path comes from config, an environment variable or the working directory.
    // =====================================================================================

    /// A Repo with all three: an uncommitted change, a commit no remote-tracking ref carries,
    /// and a linked Worktree pointing into it.
    #[test]
    fn delete_risk_reads_all_three_facts_the_confirm_gate_names() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        fs::write(repo.join("uncommitted.txt"), "not staged\n").expect("write a stray file");
        crate::test_support::git(
            &repo,
            &["worktree", "add", "-b", "sidecar", "../sidecar-worktree"],
        );

        let core = Core::start_discovered(spec(vec![root]));
        // Settled first, so the startup Generation's own phase C is no longer reading this
        // same repository while the line below reads it: two concurrent gix statuses over one
        // working tree is a race in the harness, not in `delete_risk`.
        let key = core
            .settle()
            .entities
            .into_iter()
            .find(|entity| entity.kind == Kind::Repo)
            .expect("the Repo row is discovered")
            .key;

        let risk = core.delete_risk(&key).expect("read the risk");

        assert!(risk.uncommitted, "the stray file makes the tree dirty");
        assert!(
            risk.unpushed_commits > 0 && risk.unpushed_branches > 0,
            "no remote-tracking ref carries any of this Repo's commits, got {risk:?}"
        );
        assert_eq!(
            risk.linked_worktrees, 1,
            "the one linked Worktree pointing into this Repo is counted, got {risk:?}"
        );
    }

    /// The `uncommitted` field's own range, one position at a time, because the composition
    /// behind it folds four separate reads: a modified tracked file, a deleted tracked file,
    /// an untracked file, and a staged change. Each gets a repository of its own with nothing
    /// else wrong with it, so narrowing the composition to any one of the four fails here
    /// rather than passing on whichever position a single fixture happened to sample.
    #[test]
    fn every_kind_of_work_that_is_not_in_a_commit_makes_the_gate_say_uncommitted() {
        for kind in ["modified", "deleted", "untracked", "staged"] {
            let dir = tempfile::tempdir().expect("temp dir");
            let root = root_of(&dir);
            let repo = root.join("repo");
            init_repo_with_a_commit(&repo);
            fs::write(repo.join("tracked.txt"), "first\n").expect("write a tracked file");
            crate::test_support::git(&repo, &["add", "tracked.txt"]);
            crate::test_support::git(&repo, &["commit", "-m", "add tracked"]);
            let sha = crate::test_support::head_sha(&repo);
            crate::test_support::git(&repo, &["update-ref", "refs/remotes/origin/main", &sha]);

            match kind {
                "modified" => fs::write(repo.join("tracked.txt"), "second\n").expect("modify it"),
                "deleted" => fs::remove_file(repo.join("tracked.txt")).expect("delete it"),
                "untracked" => fs::write(repo.join("stray.txt"), "new\n").expect("write a stray"),
                "staged" => {
                    fs::write(repo.join("staged.txt"), "new\n").expect("write a new file");
                    crate::test_support::git(&repo, &["add", "staged.txt"]);
                }
                other => unreachable!("unhandled kind {other}"),
            }

            let core = Core::start_discovered(spec(vec![root]));
            let key = core.settle().entities[0].key.clone();

            let risk = core.delete_risk(&key).expect("read the risk");

            assert!(
                risk.uncommitted,
                "a {kind} change is work that is not in a commit, got {risk:?}"
            );
        }
    }

    /// The staged case, stated on its own as well as in the range above, because it is the
    /// one the dirty column deliberately answers `clean` to: `dirty_counts` compares the index
    /// against the working tree and never against `HEAD`, so a `git add` with no commit is
    /// invisible to it. Both readings are asserted here together, so a fix that widened
    /// `dirty_counts` instead of giving the gate its own read would fail this rather than
    /// silently change what the dirty column means.
    #[test]
    fn staged_work_reads_clean_to_the_dirty_column_and_uncommitted_to_the_delete_gate() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let sha = crate::test_support::head_sha(&repo);
        crate::test_support::git(&repo, &["update-ref", "refs/remotes/origin/main", &sha]);
        fs::write(repo.join("staged.txt"), "staged\n").expect("write a new file");
        crate::test_support::git(&repo, &["add", "staged.txt"]);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.settle().entities[0].key.clone();

        let opened = git::open_thread_safe(repo.as_path())
            .expect("open the repo")
            .to_thread_local();
        let dirty = git::dirty_counts(&opened, Arc::new(AtomicBool::new(false)))
            .expect("read the dirty counts");
        assert_eq!(
            dirty.total(),
            0,
            "the dirty column stays an index-to-worktree comparison, got {dirty:?}"
        );

        let risk = core.delete_risk(&key).expect("read the risk");
        assert!(
            risk.uncommitted,
            "a Repo whose only work is staged must never be listed plainly, got {risk:?}"
        );
    }

    /// The two unpushed quantities are two quantities: a fixture whose commit count and
    /// branch count differ, so transposing the pair in the composition changes both numbers
    /// rather than satisfying an inequality either way round.
    #[test]
    fn unpushed_commits_and_unpushed_branches_are_counted_into_their_own_fields() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let sha = crate::test_support::head_sha(&repo);
        crate::test_support::git(&repo, &["update-ref", "refs/remotes/origin/main", &sha]);
        for nth in 0..3 {
            fs::write(repo.join(format!("file-{nth}.txt")), "x\n").expect("write a file");
            crate::test_support::git(&repo, &["add", "."]);
            crate::test_support::git(&repo, &["commit", "-m", "unpushed"]);
        }
        crate::test_support::git(&repo, &["checkout", "."]);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.settle().entities[0].key.clone();

        let risk = core.delete_risk(&key).expect("read the risk");

        assert_eq!(
            (risk.unpushed_commits, risk.unpushed_branches),
            (3, 1),
            "three commits on one branch, each in its own field, got {risk:?}"
        );
    }

    /// The linked-Worktree count is git's own register, not the table's: a Worktree living
    /// outside the active Set's roots is never discovered, and deleting the Repo it is linked
    /// from orphans it just the same.
    #[test]
    fn a_linked_worktree_outside_the_sets_roots_is_still_counted_by_the_gate() {
        let dir = tempfile::tempdir().expect("temp dir");
        let base = root_of(&dir);
        let inside = base.join("inside");
        let outside = base.join("outside");
        fs::create_dir_all(&outside).expect("create the outside dir");
        let repo = inside.join("repo");
        init_repo_with_a_commit(&repo);
        crate::test_support::git(
            &repo,
            &["worktree", "add", "-b", "sidecar", "../../outside/sidecar"],
        );
        assert!(
            outside.join("sidecar").exists(),
            "the harness really created a linked Worktree outside the Set's roots"
        );

        // Bounded by `inside` alone, so the Worktree is not a row in this Core's own table.
        let core = Core::start_discovered(spec(vec![inside]));
        let snapshot = core.settle();
        assert!(
            snapshot
                .entities
                .iter()
                .all(|entity| entity.kind != Kind::Worktree),
            "the Worktree is outside the roots and so is not discovered, got {:?}",
            snapshot.entities.iter().map(|e| e.kind).collect::<Vec<_>>()
        );
        let key = snapshot
            .entities
            .into_iter()
            .find(|entity| entity.kind == Kind::Repo)
            .expect("the Repo row is discovered")
            .key;

        let risk = core.delete_risk(&key).expect("read the risk");

        assert_eq!(
            risk.linked_worktrees, 1,
            "the gate must name the linked Worktree deleting this Repo would orphan, got {risk:?}"
        );
    }

    /// The "listed plainly" case: nothing uncommitted, every commit already on a
    /// remote-tracking ref, and no linked Worktree at all. Asserted as its own test rather
    /// than left implied, since a gate that reports risk on every Repo is as wrong as one
    /// that reports it on none.
    #[test]
    fn delete_risk_on_a_clean_fully_pushed_repo_with_no_worktrees_reports_nothing() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let sha = crate::test_support::head_sha(&repo);
        crate::test_support::git(&repo, &["update-ref", "refs/remotes/origin/main", &sha]);

        let core = Core::start_discovered(spec(vec![root]));
        let key = core.settle().entities[0].key.clone();

        let risk = core.delete_risk(&key).expect("read the risk");

        assert_eq!(
            risk,
            DeleteRisk {
                uncommitted: false,
                unpushed_commits: 0,
                unpushed_branches: 0,
                linked_worktrees: 0,
            }
        );
    }

    // =====================================================================================
    // `worktree_admin_dir` and `linked_worktree_paths`: what `delete` needs to remove a
    // linked Worktree the way `git worktree remove` does, and to take a Repo's own linked
    // Worktrees with it. Every repository here is built in a temp directory this test owns.
    // =====================================================================================

    /// The administrative directory named for a Worktree row is the one `git worktree list`
    /// stops naming once it is gone, proven by removing exactly that directory by hand.
    #[test]
    fn worktree_admin_dir_names_the_entry_git_worktree_list_forgets_once_it_is_removed() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let worktree = root.join("sidecar");
        crate::test_support::git(
            &repo,
            &[
                "worktree",
                "add",
                "-b",
                "sidecar",
                worktree.to_str().expect("utf8 path"),
            ],
        );

        let core = Core::start_discovered(spec(vec![root]));
        let key = core
            .settle()
            .entities
            .into_iter()
            .find(|entity| entity.kind == Kind::Worktree)
            .expect("the Worktree row is discovered")
            .key;

        let admin_dir = core.worktree_admin_dir(&key).expect("read the admin dir");
        fs::remove_dir_all(&admin_dir).expect("remove the admin dir by hand");

        let reopened = git::open_thread_safe(&repo)
            .expect("reopen the repo")
            .to_thread_local();
        assert_eq!(
            git::linked_worktrees(&reopened).expect("count"),
            0,
            "removing the admin dir alone must be what git's own register stops naming"
        );
    }

    /// A Worktree whose own path is not a git repository at all (the fixture for "the parent
    /// Repo is gone or unreadable"): the read errors rather than naming a directory that was
    /// never a Worktree's own administrative entry.
    #[test]
    fn worktree_admin_dir_errors_when_the_path_cannot_be_opened_as_a_repository() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let not_a_repo = root.join("plain-directory");
        fs::create_dir_all(&not_a_repo).expect("create it");

        let core = Core::start_discovered(spec(vec![root]));
        core.settle();
        let key = EntityKey::new(Arc::from(not_a_repo.as_path()));

        assert!(core.worktree_admin_dir(&key).is_err());
    }

    /// Every linked Worktree's own working directory, named by path rather than merely
    /// counted, for the Repo deletion cascade to remove.
    #[test]
    fn linked_worktree_paths_names_every_linked_worktrees_own_directory() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = root_of(&dir);
        let repo = root.join("repo");
        init_repo_with_a_commit(&repo);
        let first = root.join("first-worktree");
        let second = root.join("second-worktree");
        crate::test_support::git(
            &repo,
            &[
                "worktree",
                "add",
                "-b",
                "one",
                first.to_str().expect("utf8 path"),
            ],
        );
        crate::test_support::git(
            &repo,
            &[
                "worktree",
                "add",
                "-b",
                "two",
                second.to_str().expect("utf8 path"),
            ],
        );

        let core = Core::start_discovered(spec(vec![root]));
        let key = core
            .settle()
            .entities
            .into_iter()
            .find(|entity| entity.kind == Kind::Repo)
            .expect("the Repo row is discovered")
            .key;

        let mut paths = core
            .linked_worktree_paths(&key)
            .expect("read the linked worktree paths");
        paths.sort();
        let mut expected = vec![
            first.canonicalize().expect("canonicalize first"),
            second.canonicalize().expect("canonicalize second"),
        ];
        expected.sort();

        assert_eq!(paths, expected);
    }
}