magi-cli 0.269.3

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
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
//! The disk janitor: finished runs get their worktrees folded, worktrees whose
//! run record is already gone get reclaimed too, and the shared build cache is
//! pruned to its cap.
//!
//! A run's state being written by an older schema is not the same thing as it
//! being unreadable, and this module used to conflate the two: [`fold_due`]
//! treated any `run.json` its version check rejected exactly like one that
//! failed to parse at all, so a single schema bump silently stopped every
//! automatic fold in the fleet the moment it shipped, and did so with no
//! counter and no log line to say so. A record magi genuinely cannot parse —
//! missing fields, broken JSON, a schema newer than this build has ever heard
//! of — is still left alone here, still counted in
//! [`Housekeeping::unreadable`], and still only ever removed by an explicit
//! operator action (`magi fold`, or the equivalent phone route). One written
//! by a schema this build merely disagrees with the *meaning* of is not that:
//! as long as it still parses, folding proceeds regardless of the number in
//! its `schema` field.
//!
//! Everything policy-shaped — which statuses are foldable, how long a finished
//! run is left alone, whether the cache is over its limit — is a pure function
//! injected with numbers, so nothing here has to ask the operating system to
//! be testable. The only I/O is the removal itself.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use anyhow::{Context as _, Result, bail};
use jiff::{SignedDuration, Timestamp};
use serde::{Deserialize, Serialize};

use crate::ask::Questions;
use crate::config::Disk;
use crate::run::{RunState, RunStatus, SCHEMA, short_of};

use crate::disk::{Prune, dir_size};

/// What one janitor pass did, for the caller's log line.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Housekeeping {
    /// Runs folded (worktrees dropped).
    pub folded: usize,
    /// Runs [`fold_due`] left alone because their `run.json` genuinely could
    /// not be read - missing, broken JSON, a schema this build has never
    /// heard of - as opposed to one merely written by a different schema
    /// number, which is folded like any other (see the module docs). This was
    /// defined but never incremented for a long stretch of this module's
    /// history, which is exactly how 90 of 93 runs sat unfolded on one
    /// operator's machine with nothing anywhere saying why: every one of them
    /// was misclassified as unreadable by a schema check that has since been
    /// narrowed to only the runs that actually are.
    pub unreadable: usize,
    /// Worktrees under the worktree bay reclaimed because no run record in
    /// `runs/` claims them anymore (see [`fold_orphaned_worktrees`]).
    pub orphaned_worktrees: usize,
    /// Files dropped from the shared cache.
    pub cache_files: usize,
    /// Bytes freed from the shared cache.
    pub cache_freed: u64,
    /// Open questions abandoned because the run that asked them has already
    /// settled where nothing is coming back to read an answer.
    pub questions_abandoned: usize,
    /// Runs found blocked on a merge magi never recorded — a pull request the
    /// operator merged by hand while `land::land` never got as far as
    /// opening one itself — and corrected automatically. See
    /// [`reconcile_external_merges`].
    pub external_merges_recorded: usize,
    /// Run records that still called their pull request open after it was
    /// merged or closed, and were rewritten (see
    /// [`crate::land::repair_stale_pr_states`]).
    pub stale_pr_states_repaired: usize,
}

/// Run the janitor: fold due runs, reclaim orphaned worktrees, prune stale
/// worktree registrations, then prune the cache if it is over its cap.
///
/// Every part is best-effort; a jammed cache lock or a run whose worktree
/// another borrower holds must not stop the rest. Errors are reported through
/// `tracing::warn` - this is housekeeping, and the daemon keeps serving
/// either way.
pub async fn housekeep(
    cfg: &crate::config::Config,
    home: &Path,
    worktrees_root: &Path,
    repo: &Path,
    now: Timestamp,
) -> Housekeeping {
    let mut out = Housekeeping::default();
    crate::retention::sweep(home, &cfg.disk, now).await;
    if cfg.disk.auto_fold {
        let runs = home.join("runs");
        match fold_due(&runs, home, worktrees_root, &cfg.disk, now).await {
            Ok((folded, unreadable)) => {
                out.folded = folded;
                out.unreadable = unreadable;
            }
            Err(e) => {
                tracing::warn!("housekeep: fold due runs: {e:#}");
                // Stable wording: the reason varies per pass, and a changed
                // message would relight the bell on every retry.
                crate::notices::raise_in(
                    home,
                    crate::notices::Notice::warn(
                        "housekeep:fold",
                        "Automatic cleanup of finished runs failed; disk usage may keep growing.",
                    ),
                );
            }
        }
        out.orphaned_worktrees =
            fold_orphaned_worktrees(&runs, worktrees_root, home, cfg.disk.fold_grace_secs, now)
                .await;
        // Best-effort in the same sense as everything else here: a repository
        // this janitor pass has nothing to do with (or none at all, in a unit
        // test) must not turn a `warn` into a reason to skip the rest.
        if let Err(e) = crate::git::worktree_prune(repo).await {
            tracing::warn!("housekeep: prune worktree registrations: {e:#}");
        }
        out.external_merges_recorded = reconcile_external_merges(&runs, home, &cfg.disk, now).await;
        // Bounded: a handful of forge lookups a pass keeps this cheap, and the
        // pass is idempotent, so a backlog drains over several passes.
        out.stale_pr_states_repaired = crate::land::repair_stale_pr_states(home, 5).await.0;
    }
    match prune_cache_if_over_limit(cfg, home) {
        Ok(Some(pruned)) => {
            out.cache_files = pruned.files;
            out.cache_freed = pruned.freed;
        }
        Ok(None) => {}
        Err(e) => tracing::warn!("housekeep: prune cache: {e:#}"),
    }
    match crate::build_target::prune_registered(home, &cfg.disk) {
        Ok(pruned) => {
            out.cache_files = out.cache_files.saturating_add(pruned.files);
            out.cache_freed = out.cache_freed.saturating_add(pruned.freed);
        }
        Err(e) => tracing::warn!("housekeep: prune isolated builds: {e:#}"),
    }
    // Unconditional, unlike the two passes above: this is not a disk policy
    // with a cap or an opt-out, it is closing a gap `graph::Runner` itself
    // cannot - a run that reached `Merged`/`Ready`/`Failed` before this
    // cleanup existed, or whose process died between saving that status and
    // abandoning the question it leaves behind (see `Runner::settle_questions`).
    // Left alone, that question sits `open` forever: the owner's badge,
    // banner and title all keep counting a decision nobody is left to read.
    out.questions_abandoned =
        abandon_settled_questions(&Questions::at(home.join("questions")), &home.join("runs"));
    // Also unconditional: leftovers of run deletions that were killed between
    // moving the directory away and removing it (see `sweep_graveyard`).
    sweep_graveyard(home);
    out
}

/// Abandon every open question whose run has already settled into a status
/// nothing comes back from, worded with what the run became - the same
/// cleanup `graph::Runner::settle_questions` runs the moment `status` lands
/// there, for questions that missed it.
///
/// Scans questions rather than runs: the open list is normally short, and a
/// run that never asked anything costs nothing here. A run this cannot read,
/// deleted or written by a schema this build does not speak, is left alone
/// the same as everywhere else in this module; the question stays open
/// rather than guessed at.
pub fn abandon_settled_questions(store: &Questions, runs: &Path) -> usize {
    let waiting_on: BTreeSet<String> = store
        .list()
        .into_iter()
        .filter(|q| q.status.open())
        .map(|q| q.run)
        .collect();
    let mut abandoned = 0;
    for run in waiting_on {
        let Ok(meta) = read_meta(runs, &run) else {
            continue;
        };
        match store.settle_run(&run, meta.status) {
            Ok(n) => abandoned += n,
            Err(e) => tracing::warn!("housekeep: abandon questions for {run}: {e:#}"),
        }
    }
    abandoned
}

/// Fold every run that is finished, older than the grace period, and not being
/// worked on; return `(folded, unreadable)`.
///
/// A run whose `run.json` genuinely cannot be parsed — missing fields, broken
/// JSON, a schema newer than this build has ever heard of — is left exactly
/// as it is. Automatic housekeeping cannot tell a mid-write file from one that
/// will never parse again, and `<home>/runs/<id>/` is the evidence `magi
/// stats` and the deck read; when unsure whether it is safe to touch, the
/// janitor keeps rather than deletes (see the module docs). Discarding a
/// record this unreadable is an explicit operator action (`magi fold`, or the
/// equivalent phone route), never something that happens unattended. Every
/// such skip is counted in the returned `unreadable` and logged through
/// `tracing::warn` with the parse failure that caused it - silence here is
/// exactly the failure mode that let 90 of 93 runs sit unfolded with nothing
/// to show for it.
///
/// A run merely written by a *different* schema number is not unreadable: as
/// long as `run.json` still parses, it folds like any other terminal run (see
/// the module docs for why the two are different questions).
///
/// Runnable statuses and runs newer than the grace period are also left
/// alone; folding them would throw away work that is still the answer to
/// somebody's question. `Merged` runs forget their winner's worktree (the
/// merge already landed it); `Ready` and `Failed` runs keep it.
pub async fn fold_due(
    runs: &Path,
    home: &Path,
    _worktrees_root: &Path,
    disk: &Disk,
    now: Timestamp,
) -> Result<(usize, usize)> {
    let mut folded = 0usize;
    let mut unreadable = 0usize;
    for id in fold_ids(runs) {
        match fold_one(runs, home, disk, now, &id, false, &mut || {})
            .await
            .outcome
        {
            FoldOutcome::Folded | FoldOutcome::NothingLeft => folded += 1,
            FoldOutcome::Unreadable => unreadable += 1,
            _ => {}
        }
    }
    Ok((folded, unreadable))
}

/// Every run directory [`fold_due`] considers, oldest id first.
fn fold_ids(runs: &Path) -> Vec<String> {
    let mut ids: Vec<String> = std::fs::read_dir(runs)
        .into_iter()
        .flatten()
        .flatten()
        .filter(|e| e.path().join("run.json").is_file())
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .collect();
    ids.sort_unstable();
    ids
}

/// The run directories [`fold_turn`] walks: [`fold_ids`] restricted to names
/// that are run ids. The turn saves an id as its cursor and high-water mark and
/// refuses to continue from one that is not a run id, so a stray directory with
/// a `run.json` (`runs/backup/`) must not be able to become either: it would
/// restart the cycle on every pass and starve the runs after the inspection
/// bound. The idle pass keeps its wider inventory.
fn fold_turn_ids(runs: &Path) -> Vec<String> {
    let mut ids = fold_ids(runs);
    ids.retain(|id| crate::run::is_run_id(id));
    ids
}

/// What one run's turn through [`fold_one`] came to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FoldOutcome {
    /// `graph::fold_run_when` ran and removed something.
    Folded,
    /// `graph::fold_run_when` ran and found nothing left to remove.
    NothingLeft,
    /// The run is `settled`: a fold recorded that it found nothing left and
    /// the bay is confirmed absent, so no fold was started (only the busy-time
    /// turn asks for this).
    AlreadyFolded,
    /// A live claim, or a held execution/ownership/output lease, protects the run.
    Live,
    /// A resumable status: someone may still continue this run.
    Resumable,
    /// Finished less than `fold_grace_secs` ago.
    WithinGrace,
    /// Explicitly retained recovery source (`pr_recovery::source_retention_reason`).
    Retained,
    /// The proof that nothing is lost is incomplete: startup or candidate
    /// preservation unfinished, or the confirmed-merge source proof.
    ProofIncomplete,
    /// `run.json` could not be parsed, or became unreadable once the fold
    /// held the run's locks.
    Unreadable,
    /// The record was deleted while the fold waited for its locks.
    RecordGone,
    /// `graph::fold_run_when` failed (git, filesystem).
    Failed,
}

/// One run's [`FoldOutcome`], with the text of what stopped it where there is
/// any worth keeping (`ProofIncomplete`, `Failed`).
struct Judged {
    outcome: FoldOutcome,
    note: Option<String>,
}

impl From<FoldOutcome> for Judged {
    fn from(outcome: FoldOutcome) -> Self {
        Self {
            outcome,
            note: None,
        }
    }
}

fn refused(refusal: &crate::graph::FoldRefusal) -> Judged {
    use crate::graph::FoldRefusal;
    match refusal {
        FoldRefusal::Live(_) => FoldOutcome::Live.into(),
        FoldRefusal::Resumable => FoldOutcome::Resumable.into(),
        FoldRefusal::WithinGrace => FoldOutcome::WithinGrace.into(),
        FoldRefusal::Retained(_) => FoldOutcome::Retained.into(),
        FoldRefusal::ProofIncomplete(detail) => Judged {
            outcome: FoldOutcome::ProofIncomplete,
            note: Some(detail.clone()),
        },
        FoldRefusal::RecordGone => FoldOutcome::RecordGone.into(),
        FoldRefusal::Unreadable(_) => FoldOutcome::Unreadable.into(),
    }
}

/// May this record be folded now, and does its winner go too? The one
/// decision, shared by the idle janitor and the busy-time turn, and asked
/// twice: on the record read before any lock, and again by
/// `graph::fold_run_when` on the record it reloads under the run's owner lock
/// and execution lease. See [`fold_due`] for why every refusal is a skip and
/// not an error.
fn eligibility(
    state: &RunState,
    home: &Path,
    disk: &Disk,
    now: Timestamp,
) -> Result<bool, crate::graph::FoldRefusal> {
    use crate::graph::FoldRefusal;
    if crate::daemon::is_working_on(home, &state.id, now) {
        return Err(FoldRefusal::Live(
            "claimed by a live driver or worker".into(),
        ));
    }
    if state.status.resumable() {
        return Err(FoldRefusal::Resumable);
    }
    if !due(now, state.updated_at, disk.fold_grace_secs) {
        return Err(FoldRefusal::WithinGrace);
    }
    if state.startup.as_ref().is_some_and(|s| !s.complete) {
        return Err(FoldRefusal::ProofIncomplete("startup incomplete".into()));
    }
    handover_settled(state, home, now)?;
    if let Some(reason) = crate::pr_recovery::source_retention_reason(home, state) {
        tracing::info!(id = %state.id, %reason, "housekeep: source retained; fold refused");
        return Err(FoldRefusal::Retained(reason));
    }
    // The same predicate `graph::fold_run_when` refuses on before it takes any lock.
    if !state.candidate_preservation.is_empty() || !state.interrupted_implementations.is_empty() {
        return Err(FoldRefusal::ProofIncomplete(
            "candidate preservation incomplete; refusing cleanup".into(),
        ));
    }
    // `Merged`'s winner branch is safe to drop because it already landed
    // in the real target branch; `Superseded`'s winner branch is safe to
    // drop for a different reason - a later attempt at the same task is
    // what actually landed (or didn't), so *this* run's own winner is
    // never going to be merged by anyone. Every other terminal status
    // keeps the winner: `Ready`/`Blocked`/`Stalled`/`Failed`/`VerifiedNoop`
    // may still have a human's decision pending on that exact branch.
    // `AlreadyInBase` is the same: the change is on the base under other
    // commit ids, so the branch holds nothing anyone still needs.
    Ok(matches!(
        state.status,
        RunStatus::Merged | RunStatus::Superseded | RunStatus::AlreadyInBase
    ))
}

/// A handover in flight is not folded: a record naming a successor
/// (`released_to`) whose startup has not settled, or whose driver is live, is
/// `live` and nothing is touched.
///
/// `handover::release` records `released_to` under the predecessor's owner
/// lock and keeps going; when the successor's startup then fails,
/// `handover::Released::restore` takes the same owner lock to put the old
/// worktree back. An automatic fold that holds that lock at that moment would
/// make the rollback abandon, leaving the predecessor marked as released to a
/// run that never started. The successor's own record says whether it is still
/// starting (`startup` present, not complete, no failure recorded - a failed
/// startup has settled: its rollback is what follows) or driving (a live
/// driver). A successor record that is not there protects nothing; one that
/// cannot be read is unknown, which refuses. A startup killed mid-way leaves the
/// same marker as one in progress, so it keeps its predecessor out of automatic
/// folding until an operator settles that run - the safe direction. Asked on
/// the first read and again on the record the fold reloads under its locks.
fn handover_settled(
    state: &RunState,
    home: &Path,
    now: Timestamp,
) -> Result<(), crate::graph::FoldRefusal> {
    use crate::graph::FoldRefusal;
    let Some(next) = state.released_to.as_deref() else {
        return Ok(());
    };
    let successor = match RunState::load_tolerant_under(next, home) {
        Ok(successor) => successor,
        Err(e)
            if e.chain().any(|cause| {
                cause
                    .downcast_ref::<std::io::Error>()
                    .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
            }) =>
        {
            return Ok(());
        }
        Err(e) => {
            return Err(FoldRefusal::Live(format!(
                "the successor {next} of a handover cannot be read: {e:#}"
            )));
        }
    };
    if successor
        .startup
        .as_ref()
        .is_some_and(|startup| !startup.complete && startup.failure.is_none())
    {
        return Err(FoldRefusal::Live(format!(
            "handover in flight: run {next} is still starting"
        )));
    }
    let claimed = crate::daemon::is_working_on(home, next, now);
    if successor.liveness_under(home, claimed) == crate::run::Liveness::Live {
        return Err(FoldRefusal::Live(format!(
            "handover in flight: run {next} is being driven"
        )));
    }
    Ok(())
}

/// Fold the run whose merge was just recorded from the forge
/// (`reconcile_external_merges`). An automatic caller like the janitor's own
/// fold: the record is read again under the run's locks, tolerant of older
/// schemas, and the conditions that made this a confirmed merge are re-checked
/// on it - it must still be a confirmed merge, its winner goes too, and a
/// handover in flight still protects it. There is no grace - the merge is the
/// news - and every other refusal stays with `graph::fold_run_when`.
async fn fold_recorded_merge(
    state: &mut RunState,
    home: &Path,
    now: Timestamp,
) -> Result<Vec<String>> {
    crate::graph::fold_run_when(state, home, &|fresh| {
        use crate::graph::FoldRefusal;
        if fresh.status != RunStatus::Merged || !fresh.merge.as_ref().is_some_and(|merge| merge.ok)
        {
            return Err(FoldRefusal::ProofIncomplete(
                "the run is not a confirmed merge".into(),
            ));
        }
        handover_settled(fresh, home, now)?;
        Ok(true)
    })
    .await
}

/// May the busy-time turn answer a run without starting a fold?
///
/// Only on a fact a fold itself recorded: `graph::fold_run_when` completed under
/// the run's locks, found nothing left to remove and saw the worktree bay gone
/// (`RunState::fold_settled_at`), *and* the bay is confirmed absent now -
/// `bay` is the answer of `Path::try_exists`, so a failing check and a bay that
/// exists (even an empty one, which a fold removes) both mean "judge normally and
/// invoke the fold". Nothing is inferred from candidate flags, directory listings
/// or Git: a stale registration or a leftover branch without a bay is not disk
/// and is left to the ordinary paths. A pending worktree-config release is work,
/// so it is not skipped either. This spares a run that was folded long ago the
/// fold budget every cycle; the idle pass never skips.
fn settled(state: &RunState, drop_winner: bool, bay: std::io::Result<bool>) -> bool {
    state.fold_settled_at.is_some()
        && !(state.enabled_worktree_config && drop_winner)
        && matches!(bay, Ok(false))
}

/// Judge one run and, when [`eligibility`] allows it, fold it.
///
/// Shared by the idle janitor ([`fold_due`]) and the bounded busy-time turn
/// ([`fold_turn`]); neither may decide differently, so the checks live here
/// and nowhere else. `skip_finished` (the turn only) answers a run that is
/// [`settled`] without starting a fold. `begin_fold` is called right
/// before `graph::fold_run_when` is entered, whatever it then returns, so the
/// caller's budget is charged for every invocation, not only for the ones that
/// removed something.
async fn fold_one(
    runs: &Path,
    home: &Path,
    disk: &Disk,
    now: Timestamp,
    id: &str,
    skip_finished: bool,
    begin_fold: &mut (dyn FnMut() + Send),
) -> Judged {
    if crate::daemon::is_working_on(home, id, now) {
        return FoldOutcome::Live.into();
    }
    let meta = match read_meta(runs, id) {
        Ok(meta) => meta,
        Err(e) => {
            tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
            return FoldOutcome::Unreadable.into();
        }
    };
    if meta.status.resumable() {
        return FoldOutcome::Resumable.into();
    }
    if !due(now, meta.updated_at, disk.fold_grace_secs) {
        return FoldOutcome::WithinGrace.into();
    }
    // `read_meta` already proved the file parses; `read_state` asks for
    // the rest of the fields `graph::fold_run` needs (worktree paths,
    // candidates, tally). A schema mismatch alone does not fail this -
    // see the module docs - so reaching `Err` here means the JSON itself
    // is broken in a way `read_meta` did not exercise, which is rare but
    // not impossible (a body truncated between the two fields it reads
    // and the rest). That must not cost every other run its turn through
    // the caller's loop, so it is a skip, not a `?`.
    let mut state = match read_state(runs, id) {
        Ok(state) => state,
        Err(e) => {
            tracing::warn!("housekeep: run {id} unreadable, left alone: {e:#}");
            return FoldOutcome::Unreadable.into();
        }
    };
    let decide = |state: &RunState| eligibility(state, home, disk, now);
    let drop_winner = match decide(&state) {
        Ok(drop_winner) => drop_winner,
        Err(refusal) => return refused(&refusal),
    };
    if state.schema != SCHEMA {
        tracing::info!(
            "housekeep: run {id} was written by schema {} (this build speaks {SCHEMA}); \
             folding it anyway",
            state.schema
        );
    }
    if skip_finished && settled(&state, drop_winner, state.worktree_root().try_exists()) {
        return FoldOutcome::AlreadyFolded.into();
    }
    // The window a handover can fall into: after the read above, before the
    // fold takes the run's locks. Tests run their handover here, deterministically.
    #[cfg(test)]
    if let Some(hook) = tests::AFTER_FIRST_READ.with(|hook| hook.borrow_mut().take()) {
        hook(home, id);
    }
    // One run's fold must not cost every later run its turn. A worktree
    // another borrower holds, a branch git refuses to delete, a repository
    // that has since moved: each is a reason this run cannot be folded
    // now, and none is a reason to stop the pass. Left unfolded, it is
    // simply due again next time; a `?` here stopped automatic folding
    // permanently at the first such run (finding R3-1-1 of run 51a3).
    begin_fold();
    match crate::graph::fold_run_when(&mut state, home, &decide).await {
        Ok(removed) if removed.is_empty() => FoldOutcome::NothingLeft.into(),
        Ok(_) => FoldOutcome::Folded.into(),
        Err(e) => match e.downcast_ref::<crate::graph::FoldRefusal>() {
            Some(refusal) => {
                tracing::info!("housekeep: fold {id}: {refusal}");
                refused(refusal)
            }
            None => {
                tracing::warn!("housekeep: fold {id}: {e:#}");
                Judged {
                    outcome: FoldOutcome::Failed,
                    note: Some(format!("{e:#}")),
                }
            }
        },
    }
}

/// How much one [`fold_turn`] may do. Whichever bound is reached first ends the
/// pass; the cycle state says where the next one continues.
#[derive(Debug, Clone, Copy)]
pub struct FoldBounds {
    /// Run records read and judged (cheap: one JSON each).
    pub inspect: usize,
    /// `graph::fold_run_when` invocations (expensive: git, locks, deleting
    /// build output), charged when the invocation begins, whatever it returns.
    pub fold: usize,
    /// Wall clock, inventory included, checked between runs only; a started
    /// fold always finishes.
    pub budget: std::time::Duration,
}

/// What the scheduler's busy-time turn may do per pass: judging at most 64
/// records (a 218-run history is four passes), starting at most four folds and
/// starting none after five minutes, whichever bound comes first.
///
/// The costs are not alike, and none is "milliseconds" in general. Judging a
/// record reads its `run.json` and asks for a live claim (`daemon.json`, the
/// worker store); one that is eligible is read in full and its decision
/// evaluated, which reads the queue for recovery-source retention. Those are
/// local file reads and are bounded by `inspect`, but their wall time depends
/// on the disk and on how loaded the machine is, which is why the time budget
/// also applies to them. A fold can take a minute (Git plus deleting
/// gigabytes of build output), so the fold bound, not the inspect bound, is
/// what limits how long a pass holds run ownership locks. It never waits for
/// repository coordination while it holds them (see `graph::fold_run_when`).
///
/// The inventory (listing `runs/`, sorting the ids) is not bounded by
/// `inspect`: it costs one directory listing plus one `is_file` per record on
/// every pass, i.e. O(history) syscalls. It is counted in the pass's elapsed
/// time and reported (`FoldTurn::records`, `FoldTurn::elapsed_ms`).
///
/// **The bound on revisiting.** A cycle covers the run ids that are not newer
/// than the persisted high-water mark, the newest id present when it began,
/// in id order, and then ends; the next pass begins a new cycle. With N records
/// at the start of a cycle, every one of them is judged within
/// `ceil(N / inspect)` passes plus the passes its fold invocations consume
/// (`ceil(F / fold)` for F invocations), plus one more for every pass the time
/// budget cuts short - a pass can spend the whole budget judging records
/// without starting a fold, so each such pass is charged by itself. Ids start with the
/// local wall-clock time of creation, so runs created later sort after the mark
/// and wait for the next cycle: a growing history cannot postpone the
/// wraparound. Two things can still put a later run inside the range - one
/// created in the same second as the mark's, or after the clock stepped
/// backwards - and each such run adds at most its own judgement to the cycle;
/// there is no cohort list, so that is the whole bound on them. A run that
/// left its grace period after being judged is folded within the next cycle:
/// at most one cycle plus one cycle later.
pub const BUSY_FOLD_BOUNDS: FoldBounds = FoldBounds {
    inspect: 64,
    fold: 4,
    budget: std::time::Duration::from_secs(300),
};

/// Why a [`fold_turn`] ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FoldStop {
    /// Every run of the cycle's range was judged; the next pass starts a new cycle.
    EndOfCycle,
    /// The bound on run records judged was reached.
    InspectLimit,
    /// The bound on folds started was reached.
    FoldLimit,
    /// The wall-clock budget was spent (checked between runs).
    TimeBudget,
}

/// What stopped one run, for the receipt: the run, the outcome, and the text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FoldNote {
    /// The run id.
    pub run: String,
    /// `proof_incomplete` or `failed`.
    pub outcome: &'static str,
    /// Scrubbed and clipped to [`NOTE_CHARS`].
    pub text: String,
}

/// Notes kept per pass, and characters kept per note.
const MAX_NOTES: usize = 8;
const NOTE_CHARS: usize = 300;

/// What one [`fold_turn`] did, per outcome, for the service receipt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FoldTurn {
    /// Run records in the history when the pass began (the inventory's size).
    pub records: usize,
    /// Run records judged this pass.
    pub inspected: usize,
    /// `graph::fold_run_when` invocations this pass (what `bounds.fold` bounds).
    pub invoked: usize,
    /// Folds that ran and removed something.
    pub folded: usize,
    /// Folds that ran and found nothing left to remove.
    pub nothing_left: usize,
    /// Runs the record shows to be folded already; no fold was started.
    pub already_folded: usize,
    /// Claimed by a live driver or worker, or a lease/lock of it is held.
    pub live: usize,
    /// A resumable status: someone may still continue the run.
    pub resumable: usize,
    /// Finished less than `fold_grace_secs` ago.
    pub within_grace: usize,
    /// Explicitly retained recovery sources.
    pub recovery_retained: usize,
    /// Startup, candidate preservation or the confirmed-merge source proof incomplete.
    pub proof_incomplete: usize,
    /// `run.json` could not be parsed, or became unreadable once the run's
    /// locks were held.
    pub unreadable: usize,
    /// The record was deleted while the fold waited for its locks.
    pub record_gone: usize,
    /// `graph::fold_run_when` failed (git, filesystem).
    pub failed: usize,
    /// Run id the next pass continues after; `None`: it starts a new cycle.
    pub cursor: Option<String>,
    /// Last run id of the cycle's range, fixed when the cycle began.
    pub high_water: Option<String>,
    /// Why this pass ended.
    pub stopped: FoldStop,
    /// Why a new cycle was started although one was saved, when it was
    /// (unreadable cursor file, high-water mark below the cursor, a cursor
    /// naming a run that no longer exists).
    pub cycle_restart: Option<String>,
    /// The cycle file could not be saved: the next pass repeats this slice.
    pub cursor_error: Option<String>,
    /// Wall clock of the pass, inventory included.
    pub elapsed_ms: u64,
    /// What stopped the first few `proof_incomplete` and `failed` runs.
    pub notes: Vec<FoldNote>,
}

impl FoldTurn {
    fn begin(records: usize) -> Self {
        Self {
            records,
            inspected: 0,
            invoked: 0,
            folded: 0,
            nothing_left: 0,
            already_folded: 0,
            live: 0,
            resumable: 0,
            within_grace: 0,
            recovery_retained: 0,
            proof_incomplete: 0,
            unreadable: 0,
            record_gone: 0,
            failed: 0,
            cursor: None,
            high_water: None,
            stopped: FoldStop::EndOfCycle,
            cycle_restart: None,
            cursor_error: None,
            elapsed_ms: 0,
            notes: Vec::new(),
        }
    }

    fn record(&mut self, id: &str, judged: Judged) {
        match judged.outcome {
            FoldOutcome::Folded => self.folded += 1,
            FoldOutcome::NothingLeft => self.nothing_left += 1,
            FoldOutcome::AlreadyFolded => self.already_folded += 1,
            FoldOutcome::Live => self.live += 1,
            FoldOutcome::Resumable => self.resumable += 1,
            FoldOutcome::WithinGrace => self.within_grace += 1,
            FoldOutcome::Retained => self.recovery_retained += 1,
            FoldOutcome::ProofIncomplete => self.proof_incomplete += 1,
            FoldOutcome::Unreadable => self.unreadable += 1,
            FoldOutcome::RecordGone => self.record_gone += 1,
            FoldOutcome::Failed => self.failed += 1,
        }
        let outcome = match judged.outcome {
            FoldOutcome::ProofIncomplete => "proof_incomplete",
            FoldOutcome::Failed => "failed",
            _ => return,
        };
        if let (Some(text), true) = (judged.note, self.notes.len() < MAX_NOTES) {
            let text = crate::scrub::scrub(&text, &crate::scrub::Identity::current());
            self.notes.push(FoldNote {
                run: id.to_owned(),
                outcome,
                text: text.chars().take(NOTE_CHARS).collect(),
            });
        }
    }
}

/// Where one cycle through the history stands, saved between passes.
///
/// `high_water` is the last run id that existed when the cycle began; the
/// cycle covers `(cursor, high_water]` and nothing created later.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Cycle {
    cursor: Option<String>,
    high_water: String,
}

/// What the cycle file held.
enum Saved {
    /// No cycle in progress: the next pass begins one.
    Absent,
    Cycle(Cycle),
    /// The file exists and cannot be used (read failure, bad JSON).
    Unreadable(String),
}

/// One bounded, resumable step through finished-run folding.
///
/// Continues the saved cycle (or begins one), judges each run with
/// [`fold_one`] - the same decision, grace, liveness and source-retention
/// checks as [`fold_due`] - and stops at the first bound in `bounds`. At least
/// one run is always judged, so a zero budget still makes progress. Returns
/// the cycle to save: `None` when the cycle's range is exhausted.
///
/// A saved cycle that cannot be trusted starts a fresh one, and the receipt
/// says why (`cycle_restart`): an unreadable file, a high-water mark below the
/// cursor, a cursor naming a run that no longer exists, or a range with
/// nothing left in it. Starting over only costs judging runs again.
async fn fold_turn_from(
    runs: &Path,
    home: &Path,
    disk: &Disk,
    now: Timestamp,
    saved: Saved,
    bounds: FoldBounds,
) -> (FoldTurn, Option<Cycle>) {
    let began = std::time::Instant::now();
    let ids = fold_turn_ids(runs);
    let mut turn = FoldTurn::begin(ids.len());
    let mut cycle = match saved {
        Saved::Absent => None,
        Saved::Unreadable(why) => {
            turn.cycle_restart = Some(format!("cursor file unreadable: {why}"));
            None
        }
        Saved::Cycle(cycle) => {
            let restart = if !crate::run::is_run_id(&cycle.high_water)
                || cycle
                    .cursor
                    .as_deref()
                    .is_some_and(|cursor| !crate::run::is_run_id(cursor))
            {
                Some("cycle file names an id that is not a run id")
            } else if ids.last().is_none_or(|newest| cycle.high_water > *newest) {
                Some("high-water mark is newer than every run")
            } else {
                match &cycle.cursor {
                    Some(cursor) if *cursor > cycle.high_water => {
                        Some("high-water mark is below the cursor")
                    }
                    Some(cursor) if ids.binary_search(cursor).is_err() => {
                        Some("cursor names a run that no longer exists")
                    }
                    _ => None,
                }
            };
            match restart {
                Some(why) => {
                    turn.cycle_restart = Some(why.into());
                    None
                }
                None => Some(cycle),
            }
        }
    };
    let range = |cycle: &Cycle| {
        let start = cycle
            .cursor
            .as_deref()
            .map_or(0, |c| ids.partition_point(|id| id.as_str() <= c));
        let end = ids.partition_point(|id| id.as_str() <= cycle.high_water.as_str());
        (start, end)
    };
    if cycle.as_ref().is_some_and(|c| {
        let (start, end) = range(c);
        start >= end
    }) {
        turn.cycle_restart = Some("the saved cycle had nothing left in its range".into());
        cycle = None;
    }
    let Some(cycle) = cycle.or_else(|| {
        ids.last().map(|last| Cycle {
            cursor: None,
            high_water: last.clone(),
        })
    }) else {
        turn.elapsed_ms = began.elapsed().as_millis() as u64;
        return (turn, None);
    };
    turn.high_water = Some(cycle.high_water.clone());
    let (start, end) = range(&cycle);
    let mut begun = 0usize;
    let mut last: Option<&String> = None;
    let mut next = None;
    for id in &ids[start..end] {
        let stop = if turn.inspected == 0 {
            None
        } else if turn.inspected >= bounds.inspect {
            Some(FoldStop::InspectLimit)
        } else if begun >= bounds.fold {
            Some(FoldStop::FoldLimit)
        } else if began.elapsed() >= bounds.budget {
            Some(FoldStop::TimeBudget)
        } else {
            None
        };
        if let Some(stop) = stop {
            turn.stopped = stop;
            turn.cursor = last.cloned();
            next = Some(Cycle {
                cursor: last.cloned(),
                high_water: cycle.high_water.clone(),
            });
            break;
        }
        turn.inspected += 1;
        last = Some(id);
        let judged = fold_one(runs, home, disk, now, id, true, &mut || begun += 1).await;
        turn.record(id, judged);
    }
    turn.invoked = begun;
    turn.elapsed_ms = began.elapsed().as_millis() as u64;
    (turn, next)
}

/// Where [`fold_turn`] remembers its cycle: JSON `{cursor, high_water}`. Absent
/// means "no cycle in progress", an unusable file starts a new one and is
/// reported; either only costs judging runs again.
const FOLD_TURN_CURSOR_FILE: &str = "fold-turn-cursor";

fn read_cycle(home: &Path) -> Saved {
    match std::fs::read(home.join(FOLD_TURN_CURSOR_FILE)) {
        Ok(body) => match serde_json::from_slice(&body) {
            Ok(cycle) => Saved::Cycle(cycle),
            Err(e) => Saved::Unreadable(e.to_string()),
        },
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Saved::Absent,
        Err(e) => Saved::Unreadable(e.to_string()),
    }
}

fn write_cycle(home: &Path, cycle: Option<&Cycle>) -> Result<()> {
    let path = home.join(FOLD_TURN_CURSOR_FILE);
    match cycle {
        Some(cycle) => crate::fold_evidence::atomic_write(&path, &serde_json::to_vec(cycle)?),
        None => match std::fs::remove_file(&path) {
            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()),
            _ => Ok(()),
        },
    }
}

/// [`fold_turn_from`] continuing from, and saving, the persisted cycle.
///
/// The cycle is saved after every pass, before the caller reports it, so a
/// restart resumes where this pass ended. A save failure is reported in
/// [`FoldTurn::cursor_error`] rather than hidden: the next pass would then
/// repeat the same slice, and the receipt must say so. Passes never overlap:
/// the scheduler admits one `fold` service worker at a time.
pub async fn fold_turn(
    runs: &Path,
    home: &Path,
    disk: &Disk,
    now: Timestamp,
    bounds: FoldBounds,
) -> FoldTurn {
    let (mut turn, next) = fold_turn_from(runs, home, disk, now, read_cycle(home), bounds).await;
    if let Err(e) = write_cycle(home, next.as_ref()) {
        tracing::warn!("housekeep: persist the fold turn's cycle: {e:#}");
        turn.cursor_error = Some(format!("{e:#}"));
    }
    turn
}

/// What one [`fetch_origins`] pass did.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FetchReport {
    /// Repos whose fetch succeeded.
    pub fetched: usize,
    /// Repos with no `origin` remote, skipped.
    pub no_origin: usize,
    /// Repos whose fetch failed or timed out.
    pub failed: usize,
}

/// Run `git fetch origin` in every checkout under `roots` (the set `magi
/// repos` lists), so `origin/main` stays current.
///
/// Fetch only: never a checkout, merge or fast-forward, so no HEAD, branch or
/// working tree moves. Best-effort like [`fold_due`]: a repo with no `origin`
/// is skipped silently, a failure or timeout is a warning, and the pass never
/// errors. `stop` is checked between repos.
pub async fn fetch_origins(
    roots: &[PathBuf],
    per_repo: std::time::Duration,
    stop: impl Fn() -> bool,
) -> FetchReport {
    let mut report = FetchReport::default();
    for repo in crate::repos::scan(roots) {
        if stop() {
            break;
        }
        match crate::git::git_raw(&repo.path, &["remote", "get-url", "origin"]).await {
            Ok(out) if out.ok() => {}
            _ => {
                report.no_origin += 1;
                continue;
            }
        }
        match crate::git::fetch_origin(&repo.path, per_repo).await {
            Ok(()) => report.fetched += 1,
            Err(e) => {
                tracing::warn!("fetch origin in {}: {e:#}", repo.name);
                report.failed += 1;
            }
        }
    }
    report
}

/// Is `updated` old enough, measured against `now`, that the run may fold?
///
/// Pure; the janitor compares against wallclock, tests inject both sides. The
/// comparison is strict, so a run exactly at the edge of its grace period is
/// left alone one more pass — the same convention as [`crate::disk::over_limit`].
pub fn due(now: Timestamp, updated: Timestamp, grace_secs: u64) -> bool {
    now.duration_since(updated) > SignedDuration::new(grace_secs as i64, 0)
}

/// The two fields the janitor decides on, read with a serde that tolerates
/// everything else about the run being unreadable.
#[derive(Deserialize)]
struct Meta {
    /// Absent from records too broken to say; present, it must name the
    /// directory the record was read from.
    #[serde(default)]
    id: Option<String>,
    status: RunStatus,
    updated_at: Timestamp,
}

/// Read `status` and `updated_at` straight off the state file, asking for
/// nothing else. `Err` when the file is missing, not parseable, a status in
/// a version this build does not speak, or the record of another run than the
/// directory's - all of which mean "unreadable".
fn read_meta(runs: &Path, id: &str) -> Result<Meta> {
    let path = runs.join(id).join("run.json");
    let body =
        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
    let meta: Meta =
        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
    if let Some(recorded) = &meta.id {
        anyhow::ensure!(
            recorded == id,
            "runs/{id}/run.json records run {recorded}, not run {id}"
        );
    }
    Ok(meta)
}

/// Runs checked against GitHub in one janitor pass, at most.
///
/// A fleet with many stuck runs must not turn every idle tick into a burst of
/// `gh pr list` calls; a run left unchecked this pass is checked again next
/// pass, same as an unfolded due run is.
const MAX_EXTERNAL_MERGE_CHECKS_PER_PASS: usize = 5;

/// The fields [`reconcile_external_merges`] filters on before paying for a
/// full [`RunState`] parse or a `gh` round trip.
#[derive(Deserialize)]
struct ExternalMergeMeta {
    status: RunStatus,
    updated_at: Timestamp,
    #[serde(default)]
    merge: Option<crate::run::MergeOutcome>,
}

fn read_external_merge_meta(runs: &Path, id: &str) -> Result<ExternalMergeMeta> {
    let path = runs.join(id).join("run.json");
    let body =
        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
    let meta: ExternalMergeMeta =
        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
    Ok(meta)
}

/// Is a run worth asking GitHub about?
///
/// Pure, so the filter itself is assertable without a fixture that writes
/// `run.json` files or spawns `gh`. Narrower than "blocked": `merge_recorded`
/// excludes a run `land::land` already finished landing (successfully or
/// not) - that path already carries its own record of what happened - and
/// `due` gives an operator who is about to fix a run by hand a grace window
/// before the janitor starts asking the same question about it.
pub fn eligible_for_external_merge_check(
    status: RunStatus,
    merge_recorded: bool,
    updated_at: Timestamp,
    now: Timestamp,
    grace_secs: u64,
) -> bool {
    status == RunStatus::Blocked && !merge_recorded && due(now, updated_at, grace_secs)
}

/// Rotate `ids` so a fixed per-pass cap does not always land on the same
/// prefix of the list, starting at `start` (already reduced modulo nothing -
/// callers pass whatever a persisted cursor last recorded, and this takes it
/// modulo `ids.len()` itself).
///
/// Pure: the offset is the caller's problem, not wall-clock time. An earlier
/// version derived `start` from `now.as_second() % ids.len()`, which looked
/// independent of any state to persist but is not actually independent of
/// how often the janitor runs - a poll interval and a pass's own duration
/// that alias onto the same handful of `now.as_second()` values (say, a
/// ten-second poll and a pass that finishes in under a second) revisit only
/// those same few residues forever and never advance into the rest of the
/// list at all. [`reconcile_external_merges`] instead persists a cursor
/// across passes ([`read_external_merge_cursor`] /
/// [`write_external_merge_cursor`]) and advances it by exactly how many ids
/// this pass actually looked at, which is the only quantity that is
/// guaranteed to move forward pass over pass regardless of timing.
fn rotate_from(ids: &[String], start: usize) -> Vec<String> {
    if ids.is_empty() {
        return Vec::new();
    }
    let start = start % ids.len();
    ids[start..]
        .iter()
        .chain(ids[..start].iter())
        .cloned()
        .collect()
}

/// Where [`reconcile_external_merges`] remembers how far it got, so a fixed
/// per-pass cap advances through a fleet's eligible runs pass over pass
/// instead of camping on whichever ones happen to sort first.
const EXTERNAL_MERGE_CURSOR_FILE: &str = "external-merge-cursor";

/// `0` for anything this cannot read as a plain number - a first run, a
/// corrupt or missing file, a build that has never written one - which is
/// exactly as good a starting point as any: the cursor's whole job is to
/// keep moving, not to encode any particular position as meaningful.
fn read_external_merge_cursor(home: &Path) -> usize {
    std::fs::read_to_string(home.join(EXTERNAL_MERGE_CURSOR_FILE))
        .ok()
        .and_then(|s| s.trim().parse().ok())
        .unwrap_or(0)
}

/// Best-effort, like every other write in this module's sweep: a failure to
/// persist the cursor costs the fleet one pass's worth of forward progress
/// on this sweep, never the run whose housekeeping it is racing to keep up
/// with.
fn write_external_merge_cursor(home: &Path, cursor: usize) {
    if let Err(e) = std::fs::write(home.join(EXTERNAL_MERGE_CURSOR_FILE), cursor.to_string()) {
        tracing::warn!("housekeep: persist the external-merge sweep's cursor: {e:#}");
    }
}

/// Close the gap `magi fold --merged` exists for, without waiting for an
/// operator to notice and go find the pull request URL: a run that stopped
/// `Blocked` with no `merge` recorded may have been merged anyway, by hand,
/// on a pull request `land::land` never opened or never got to observe as
/// merged. `land::find_external_merge` asks GitHub about the run's own
/// winning branch, and only a pull request it can uniquely tie back to this
/// run is ever acted on - see that function's own doc for what "uniquely"
/// excludes.
///
/// A run this finds and fixes goes through
/// [`crate::land::correct_confirmed_external_merge`] - the same correction
/// `magi fold --merged` performs, minus the same-repo guard that command
/// needs and this loop doesn't (see that function's own doc: the URL here
/// was never operator-supplied, it came from asking `state.repo`'s own
/// remote) - then through [`crate::graph::fold_run`] so it stops holding
/// worktrees the moment it stops needing them. A run this cannot decide
/// about - `gh` unreachable, more than one candidate pull
/// request, nothing found at all - is left exactly as it is; only an error
/// asking GitHub raises a notice, since "nothing found" is the ordinary,
/// expected shape of a run that really is just blocked.
async fn reconcile_external_merges(runs: &Path, home: &Path, disk: &Disk, now: Timestamp) -> usize {
    reconcile_external_merges_with(runs, home, disk, now, |state| async move {
        crate::land::find_external_merge(&state).await
    })
    .await
}

async fn reconcile_external_merges_with<F, Fut>(
    runs: &Path,
    home: &Path,
    disk: &Disk,
    now: Timestamp,
    check: F,
) -> usize
where
    F: Fn(RunState) -> Fut,
    Fut: std::future::Future<Output = Result<Option<crate::land::ExternalMerge>>>,
{
    let mut ids: Vec<String> = std::fs::read_dir(runs)
        .into_iter()
        .flatten()
        .flatten()
        .filter(|e| e.path().join("run.json").is_file())
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .collect();
    ids.sort_unstable();

    // Every eligible id first, cheaply (a `Meta` read, no `gh`), then rotated
    // before the cap is applied. Capping the sorted order directly would
    // always land on the same lexicographic prefix - a fleet's oldest run ids
    // - so a handful of long-blocked runs that never turn out to be merged
    // would starve every id after them of a `gh` check, forever.
    let mut eligible: Vec<String> = Vec::new();
    for id in ids {
        if crate::daemon::is_working_on(home, &id, now) {
            continue;
        }
        let meta = match read_external_merge_meta(runs, &id) {
            Ok(meta) => meta,
            // Already counted as unreadable by `fold_due`'s own pass; not
            // worth a second warning for the same file.
            Err(_) => continue,
        };
        if eligible_for_external_merge_check(
            meta.status,
            meta.merge.is_some(),
            meta.updated_at,
            now,
            disk.fold_grace_secs,
        ) {
            eligible.push(id);
        }
    }

    if eligible.is_empty() {
        return 0;
    }
    let cursor = read_external_merge_cursor(home);
    let window: Vec<String> = rotate_from(&eligible, cursor)
        .into_iter()
        .take(MAX_EXTERNAL_MERGE_CHECKS_PER_PASS)
        .collect();
    // Advances by exactly how many ids this pass looked at, regardless of
    // what came of looking - a run that turned out not to be merged after
    // all must not be revisited before every other eligible run has had its
    // own turn.
    write_external_merge_cursor(home, (cursor + window.len()) % eligible.len());

    let mut reconciled = 0usize;
    for id in window {
        let mut state = match read_state(runs, &id) {
            Ok(state) => state,
            Err(_) => continue,
        };
        if let Ok(record) = serde_json::to_value(&state)
            && let Some(reason) =
                crate::external_merge_attention::historical_reason(home, &id, &record)
        {
            tracing::info!("housekeep: external merge for {id}: {reason}");
            continue;
        }
        match check(state.clone()).await {
            Ok(Some(found)) => {
                match crate::land::correct_confirmed_external_merge(&mut state, &found.url).await {
                    Ok(_) => {
                        if let Err(e) = fold_recorded_merge(&mut state, home, now).await {
                            tracing::warn!(
                                "housekeep: fold {id} after recording its external merge: {e:#}"
                            );
                        }
                        reconciled += 1;
                    }
                    Err(e) => tracing::warn!(
                        "housekeep: record external merge {} for {id}: {e:#}",
                        found.url
                    ),
                }
            }
            Ok(None) => {}
            Err(e) => {
                tracing::warn!("housekeep: check external merge for {id}: {e:#}");
                crate::notices::raise_in(
                    home,
                    crate::notices::Notice::warn(
                        &format!("merged-unrecorded:{id}"),
                        format!(
                            "Run {id} is blocked with no recorded merge, and checking GitHub \
                             for a merge failed; check by hand."
                        ),
                    )
                    .link(crate::notices::Link::Run { id: id.clone() }),
                );
            }
        }
    }
    reconciled
}

/// Read a whole run state from a runs directory, for folding only.
///
/// Deliberately more permissive than [`RunState::load`], which this does not
/// call: `load` backs `--resume` and every hand-driven command, where a
/// schema this build disagrees with the *meaning* of must refuse outright
/// rather than resume a review round or a tally against stale semantics
/// (`RunState::SCHEMA`'s own docs list what has changed meaning at each
/// bump). Folding recomputes nothing - it only reads worktree paths, branch
/// names and a tally winner off the struct to remove them - so an old
/// schema's values are exactly as good here as a current one's; every schema
/// bump so far has only ever added a field or a variant, never repurposed an
/// existing one, and serde already fills an added field's default when an
/// older record has nothing to say about it. What this cannot tolerate, and
/// what still surfaces as an `Err`, is `run.json` failing to parse at all.
fn read_state(runs: &Path, id: &str) -> Result<RunState> {
    let state = RunState::read_unmigrated(&runs.join(id).join("run.json"))?;
    state.ensure_directory(id)?;
    Ok(state)
}

/// Remove only verified clean Git worktrees and empty directory scaffolding.
/// Unknown files or unreadable Git state require recovery, never recursive deletion.
async fn remove_clean_bay(root: &Path) -> Result<()> {
    let mut pending = vec![root.to_path_buf()];
    let mut directories = Vec::new();
    let mut worktrees = Vec::new();
    while let Some(path) = pending.pop() {
        if path.join(".git").exists() {
            if !crate::git::is_clean(&path).await? {
                anyhow::bail!("uncommitted work in {}; recovery required", path.display());
            }
            worktrees.push(path);
        } else {
            for entry in std::fs::read_dir(&path)? {
                let entry = entry?;
                if !entry.file_type()?.is_dir() {
                    anyhow::bail!(
                        "unknown worktree content in {}; recovery required",
                        path.display()
                    );
                }
                pending.push(entry.path());
            }
            directories.push(path);
        }
    }
    for path in worktrees {
        if !crate::git::worktree_remove_clean(&path, &path).await? {
            anyhow::bail!("clean worktree removal refused: {}", path.display());
        }
    }
    for path in directories.into_iter().rev() {
        std::fs::remove_dir(path)?;
    }
    Ok(())
}

/// A run's lock is held by somebody: a [`DeleteRefused`] that says so. Any other
/// failure of the lock call stays what it was.
fn busy_run(id: &str) -> impl Fn(anyhow::Error) -> anyhow::Error + '_ {
    move |e| {
        if crate::graph::held_by_live_owner(&e) {
            DeleteRefused(format!(
                "run {id} is being worked on or folded right now ({e:#}); try again later"
            ))
            .into()
        } else {
            e
        }
    }
}

/// Remove a run that cannot be read: its state directory under `runs` and its
/// worktree directory under `worktrees_root`.
///
/// Inspect worktrees before deleting any state or artifacts. Only clean registered
/// worktrees and empty directory scaffolding can be reclaimed; unknown or dirty
/// content remains available for recovery. Nonstandard worktree roots remain the
/// operator's responsibility when the state file cannot identify them.
pub async fn fold_unreadable(runs: &Path, worktrees_root: &Path, id: &str) -> Result<Vec<String>> {
    let resolved = resolve_id_path(runs, id)?;
    ensure_record_identity(runs, &resolved)?;
    let mut removed = Vec::new();
    let run_dir = runs.join(&resolved);
    // The two locks every writer of the record takes, held until the directory
    // is gone: a fold in progress makes this a refusal, not a race.
    let locks = if run_dir.is_dir()
        && let Some(home) = runs.parent()
    {
        let busy = busy_run(&resolved);
        Some((
            crate::pr_head::owner_lock(home, &resolved).map_err(&busy)?,
            crate::driver::maintenance(home, &resolved).map_err(&busy)?,
        ))
    } else {
        None
    };
    let wt = worktrees_root.join(short_of(&resolved));
    if wt.exists() {
        remove_clean_bay(&wt).await?;
        removed.push(wt.to_string_lossy().into_owned());
    }
    // Keep the recovery artifacts if any worktree could not be removed safely.
    if run_dir.exists() {
        // With both guards held the directory leaves through the tombstone, like
        // a deleted run's, so its lock files and `run.json` disappear together.
        match (&locks, runs.parent()) {
            (Some(_), Some(home)) => remove_run_dir(home, &resolved, &run_dir)?,
            _ => std::fs::remove_dir_all(&run_dir)
                .with_context(|| format!("remove {}", run_dir.display()))?,
        }
        removed.push(format!("runs/{resolved}"));
    }
    Ok(removed)
}

/// Reclaim worktrees under `worktrees_root` that no run record in `runs`
/// claims anymore, and return how many were removed.
///
/// [`fold_due`] only ever sees a worktree by walking `runs/` first, so a
/// worktree whose run record is already gone — `magi run rm`, or a record
/// deleted before its worktree — never enters that loop at all: nothing there
/// is looking for it. This walks the worktree bay directly instead, and
/// removes any `<short>` directory that no run id maps to.
///
/// Two things must never happen, and this checks both before ever touching a
/// directory:
///
/// - **A worktree bay is never the only kind of thing under `worktrees_root`,
///   and this must not assume it is.** A hand-placed scratch directory, or
///   anything else an operator or another tool left in the same bay, has the
///   same "no run claims it" shape as a genuine orphan but is not one -
///   [`looks_like_a_worktree_bay`] is the same tag shape [`crate::run::is_run_id`]
///   already requires of a real run's short id, and anything else is left
///   alone regardless of what else is true about it.
/// - **A worktree that was only just created might not have a `run.json` yet
///   for a reason that has nothing to do with being orphaned.** `Runner::start`
///   and `Runner::review` both create the worktree before the first
///   `RunState::save` lands, and that gap - several `git` subprocesses wide -
///   is invisible to [`crate::daemon::is_working_on_short`] whenever the run
///   is not being driven through this daemon's own `poll` loop at all (a
///   `magi review` invocation, for one). A directory whose own modification
///   time is within `grace_secs` of `now` is left alone on that basis alone,
///   the same margin [`fold_due`] gives a run before treating it as truly
///   finished - long enough that no realistic gap between a `worktree add`
///   and its `run.json` could ever be mistaken for one.
///
/// The one failure this must never cause is deleting the worktree of a run
/// that is genuinely in flight. [`crate::daemon::is_working_on_short`] is the
/// same liveness check [`fold_due`] trusts everywhere else in this module,
/// checked by short id because there is no full id to compare here; when it
/// cannot tell, this leaves the directory alone. Best-effort like the rest of
/// housekeeping: one directory git or the filesystem refuses to give up is a
/// `tracing::warn`, not a reason to abandon the rest of the pass.
pub async fn fold_orphaned_worktrees(
    runs: &Path,
    worktrees_root: &Path,
    home: &Path,
    grace_secs: u64,
    now: Timestamp,
) -> usize {
    let known: std::collections::HashSet<String> = std::fs::read_dir(runs)
        .into_iter()
        .flatten()
        .flatten()
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .filter(|name| crate::run::is_run_id(name))
        .map(|id| short_of(&id).to_owned())
        .collect();

    let mut folded = 0usize;
    for entry in std::fs::read_dir(worktrees_root)
        .into_iter()
        .flatten()
        .flatten()
    {
        if !entry.path().is_dir() {
            continue;
        }
        let short = entry.file_name().to_string_lossy().into_owned();
        if !looks_like_a_worktree_bay(&short) {
            continue;
        }
        if known.contains(&short) || crate::daemon::is_working_on_short(home, &short, now) {
            continue;
        }
        let wt = entry.path();
        if !stale_enough(&wt, grace_secs, now) {
            continue;
        }
        match remove_clean_bay(&wt).await {
            Ok(()) => folded += 1,
            Err(e) => tracing::warn!(
                "housekeep: remove orphaned worktree {}: {e:#}",
                wt.display()
            ),
        }
    }
    folded
}

/// Does `name` have the shape a run's own worktree bay is named with: the
/// same 4-character alphanumeric tag [`crate::run::is_run_id`] requires of a
/// full id's trailing block (see [`short_of`])?
///
/// Anything else under `worktrees_root` is not a bay this function reclaims
/// at all, claimed or not - answering "does a run claim this?" about a
/// directory that was never a run's worktree in the first place is exactly
/// the wrong question to ask before deleting it.
fn looks_like_a_worktree_bay(name: &str) -> bool {
    name.len() == 4 && name.bytes().all(|b| b.is_ascii_alphanumeric())
}

/// Is `dir`'s own modification time old enough, against `grace_secs` and
/// `now`, that its emptiness of a run record can be trusted rather than
/// caught mid-creation?
///
/// A directory this pass cannot stat at all - a race with its own removal, a
/// permission error - is treated as not yet stale: unreadable metadata is not
/// evidence of anything, and the janitor already keeps rather than deletes
/// whenever it cannot tell (see the module docs).
///
/// `grace_secs` is floored at [`MIN_ORPHAN_AGE_SECS`] regardless of what the
/// caller passes: `0` is a documented, legitimate value for
/// [`crate::config::Disk::fold_grace_secs`] (`due`'s own "always due" case),
/// because that grace answers a policy question the operator owns - how long
/// a *known, finished* run's worktree lingers before cleanup. Whether an
/// orphan worktree is actually a race with `Runner::review`'s `git worktree
/// add` landing before its `run.json` is not a policy question, and must not
/// collapse to zero just because the operator turned the other grace off -
/// that would defeat the very check meant to catch it.
fn stale_enough(dir: &Path, grace_secs: u64, now: Timestamp) -> bool {
    let Ok(modified) = std::fs::metadata(dir).and_then(|m| m.modified()) else {
        return false;
    };
    let Ok(ts) = Timestamp::try_from(modified) else {
        return false;
    };
    due(now, ts, grace_secs.max(MIN_ORPHAN_AGE_SECS))
}

/// The floor under [`stale_enough`]'s grace, independent of
/// [`crate::config::Disk::fold_grace_secs`].
///
/// Ample next to the race it guards: the gap between `Runner::start` or
/// `Runner::review` creating a worktree and the first `RunState::save`
/// landing is a handful of `git` subprocess calls, not minutes - but the
/// janitor cannot tell "still mid-setup" from "orphaned" by any other signal
/// for a run that never registers with `daemon::Status` at all (a `magi
/// review` invocation, for one), so this is generous on purpose rather than
/// tuned to the observed case.
const MIN_ORPHAN_AGE_SECS: u64 = 5 * 60;

/// Resolve an id or prefix against an explicit runs directory, exactly the way
/// [`crate::run::resolve_id`] does against the global home.
fn resolve_id_path(runs: &Path, prefix: &str) -> Result<String> {
    // Keyed on the directory, not on a readable state file: the record this
    // route exists to remove may be a lone `run.json.tmp` from a save that
    // ran out of disk, and that is precisely the one a human needs a way to
    // clear (see `crate::run::list_ids`).
    if runs.join(prefix).is_dir() && crate::run::is_run_id(prefix) {
        return Ok(prefix.to_owned());
    }
    let mut hits: Vec<String> = Vec::new();
    for e in std::fs::read_dir(runs).into_iter().flatten().flatten() {
        if !e.path().is_dir() {
            continue;
        }
        let id = e.file_name().to_string_lossy().into_owned();
        if crate::run::is_run_id(&id) && (id.starts_with(prefix) || id.ends_with(prefix)) {
            hits.push(id);
        }
    }
    match hits.len() {
        1 => Ok(hits.into_iter().next().expect("exactly one hit")),
        0 => bail!("no run matches `{prefix}`"),
        _ => bail!(
            "`{prefix}` matches {} runs: {}",
            hits.len(),
            hits.join(", ")
        ),
    }
}

/// `magi fold`'s recovery path for a run whose worktrees are already gone —
/// so [`crate::graph::fold_run`] removed nothing — but whose `run.json` still
/// lists active seats nobody is left to answer for: no live daemon claims the
/// run, and every one of those seats has overrun its own timeout (see
/// [`RunState::active_all_overrun`]). Clearing them and failing the run is
/// what lets it be deleted afterward — [`RunState::ensure_can_delete`] only
/// ever checks whether a live daemon is working on the run and whether its
/// candidates are folded, not `status`, but a run stuck `implementing`
/// forever with an empty worktree still reads as unresolved everywhere else
/// (`magi show`, the deck, the phone) until this runs.
///
/// Returns `false` without changing anything when a live daemon still claims
/// the run, or when some active seat has not actually overrun its budget yet
/// — a run that is merely between waves must never be guessed at.
///
/// `state` is only the caller's first look. The record is written under the
/// run's owner lock and execution lease (the locks `graph::fold_run` and a
/// handover take), read again once they are held, and the conditions above are
/// judged on that record; `state` is replaced by it. Saving the caller's copy
/// would erase a handover (`released_to` / `released_branches`) that landed
/// after the fold released its own locks. A lock held by somebody else, or a
/// record that is gone, changes nothing and answers `false`.
pub fn clear_abandoned_active(state: &mut RunState, home: &Path, now: Timestamp) -> Result<bool> {
    let id = state.id.clone();
    if !home.join("runs").join(&id).join("run.json").try_exists()? {
        return Ok(false);
    }
    let Some(_owner) = uncontended(crate::pr_head::owner_lock(home, &id))? else {
        return Ok(false);
    };
    let Some(_driver) = uncontended(crate::driver::maintenance(home, &id))? else {
        return Ok(false);
    };
    match RunState::load_under(&id, home) {
        Ok(fresh) if fresh.id == id => *state = fresh,
        Err(e)
            if e.chain().any(|cause| {
                cause
                    .downcast_ref::<std::io::Error>()
                    .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
            }) =>
        {
            return Ok(false);
        }
        Ok(_) => return Ok(false),
        Err(e) => return Err(e),
    }
    if crate::daemon::is_working_on(home, &id, now) || !state.active_all_overrun(now) {
        return Ok(false);
    }
    state.abandon("fold");
    state.save_under(home)?;
    // The seat that asked is gone for good now - the same door
    // `graph::Runner::settle_questions` closes the moment `status` lands
    // somewhere non-resumable, see that method's own doc. Without this, an
    // open question the abandoned seat left behind would keep badging the
    // operator until the next daemon startup's `abandon_settled_questions`
    // pass happened to notice it, or forever if nothing is running `magi
    // serve` at all.
    if let Err(e) = Questions::at(home.join("questions")).settle_run(&state.id, state.status) {
        tracing::warn!("abandon questions for {}: {e:#}", state.id);
    }
    Ok(true)
}

/// `Some(lock)`, or `None` when somebody else holds it; any other failure of
/// the lock call stays an error.
fn uncontended<T>(locked: Result<T>) -> Result<Option<T>> {
    match locked {
        Err(e) if crate::graph::held_by_live_owner(&e) => Ok(None),
        other => other.map(Some),
    }
}

/// Why [`delete_run`] left a run record alone: somebody holds the run, it is
/// not finished with its worktrees, or it is gone. Callers answer a refusal
/// with a conflict and anything else with a failure.
#[derive(Debug)]
pub struct DeleteRefused(pub String);

impl std::fmt::Display for DeleteRefused {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for DeleteRefused {}

/// Delete a run's directory (`magi run rm`, the phone's delete button) under
/// the protocol every writer of the run record follows.
///
/// A fold (`graph::fold_run*`) holds the run's owner lock and execution lease
/// from the moment it locks the record until it has saved it, and acts on what
/// it reads once they are held. A deletion that took no part in that let the
/// record vanish under a fold - which then recreated it from a stale copy - and
/// let the run's four-character worktree suffix be reserved by a new run while
/// the fold was still deleting that suffix's directories. So the deletion takes
/// both locks without waiting (a held lock means the run is busy, and the
/// answer is a refusal, not a wait), reads the record under them, and judges
/// [`RunState::ensure_can_delete`] on that read, not on the caller's.
pub fn delete_run(home: &Path, id: &str, now: Timestamp) -> Result<()> {
    let dir = home.join("runs").join(id);
    if !dir.join("run.json").try_exists()? {
        return Err(DeleteRefused(format!("run {id}: record gone")).into());
    }
    let busy = busy_run(id);
    let _owner = crate::pr_head::owner_lock(home, id).map_err(&busy)?;
    let _driver = crate::driver::maintenance(home, id).map_err(&busy)?;
    let state = RunState::load_under(id, home)?;
    state
        .ensure_can_delete(crate::daemon::is_working_on(home, id, now))
        .map_err(|e| DeleteRefused(format!("{e:#}")))?;
    remove_run_dir(home, id, &dir)
}

/// Where a removed run's directory waits, for the moment between its rename
/// and its removal. Nothing scans it: `runs/` is what every reader lists.
fn graveyard(home: &Path) -> PathBuf {
    home.join("deleted-runs")
}

/// Remove what earlier deletions left in the graveyard: a process killed
/// between the rename and the removal leaves a complete run directory there,
/// invisible to every inventory and report. The run was already authorised for
/// deletion when it was moved and nothing else reads the directory, so any
/// entry is a leftover. Best effort: an entry that cannot be removed now (a
/// deletion in another process is removing it this very moment, a file in use)
/// is tried again by the next deletion or housekeeping pass. Returns how many
/// entries are gone.
pub fn sweep_graveyard(home: &Path) -> usize {
    let mut removed = 0;
    for entry in std::fs::read_dir(graveyard(home))
        .into_iter()
        .flatten()
        .flatten()
    {
        let path = entry.path();
        let gone = match std::fs::remove_dir_all(&path) {
            Ok(()) => true,
            Err(e) => {
                // Taken by a concurrent sweep or deletion: nothing left to do.
                if !matches!(path.try_exists(), Ok(false)) {
                    tracing::warn!("housekeep: remove leftover {}: {e}", path.display());
                }
                false
            }
        };
        removed += usize::from(gone);
    }
    removed
}

/// Remove a run's directory while the caller still holds both of its guards, so
/// that the lock files and `run.json` disappear together.
///
/// Holding a file lock does not stop the file being unlinked (on Unix), and
/// unlinking the lock files one by one while `run.json` was still there let a
/// concurrent fold open replacement lock files and read the record of a run
/// being deleted. The directory is first renamed - one atomic step - to a
/// tombstone outside `runs/`, which nothing scans, and removed there. Where a
/// directory with open files in it cannot be renamed (Windows), `run.json` goes
/// first instead, so a reader that finds the lock files finds no record.
///
/// A crash between the rename and the removal leaves the tombstone behind;
/// [`sweep_graveyard`] removes such leftovers, here before this deletion
/// starts (so it never meets its own tombstone) and in idle housekeeping.
fn remove_run_dir(home: &Path, id: &str, dir: &Path) -> Result<()> {
    sweep_graveyard(home);
    let graveyard = graveyard(home);
    let tombstone = graveyard.join(format!("{id}-{}", Timestamp::now().as_nanosecond()));
    let renamed = std::fs::create_dir_all(&graveyard)
        .and_then(|()| std::fs::rename(dir, &tombstone))
        .is_ok();
    if renamed {
        return remove_tombstone(id, &tombstone);
    }
    match std::fs::remove_file(dir.join("run.json")) {
        Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
            return Err(e).with_context(|| format!("remove run record of {id}"));
        }
        _ => {}
    }
    std::fs::remove_dir_all(dir).with_context(|| format!("remove run directory {}", dir.display()))
}

/// Remove a tombstone that a deletion has just made. A tombstone that is
/// already gone, or that a concurrent [`sweep_graveyard`] removes while this
/// removal is under way, is a finished deletion: after a removal error only a
/// tombstone that still exists is a failure.
fn remove_tombstone(id: &str, tombstone: &Path) -> Result<()> {
    match std::fs::remove_dir_all(tombstone) {
        Err(e) if !matches!(tombstone.try_exists(), Ok(false)) => Err(e).with_context(|| {
            format!(
                "run {id} was deleted, but its leftovers remain in {}",
                tombstone.display()
            )
        }),
        _ => Ok(()),
    }
}

/// The run record in `runs/<id>/run.json`, when it parses at all, names this
/// run. Read before any schema migration, so that a record another run's, in a
/// schema this build refuses, is an identity error rather than an "unreadable"
/// run that is removed wholesale. A missing or unparseable record, or one with
/// no id, says nothing about identity and passes.
pub fn ensure_record_identity(runs: &Path, id: &str) -> Result<()> {
    #[derive(Deserialize)]
    struct Recorded {
        #[serde(default)]
        id: Option<String>,
    }
    let Ok(body) = std::fs::read_to_string(runs.join(id).join("run.json")) else {
        return Ok(());
    };
    if let Ok(Recorded { id: Some(recorded) }) = serde_json::from_str(&body) {
        anyhow::ensure!(
            recorded == id,
            "runs/{id}/run.json records run {recorded}, not run {id}"
        );
    }
    Ok(())
}

/// Delete files from the shared build cache until it fits its cap — but only
/// while nobody live is registered as using it. [`crate::cache::maintenance_prune`]
/// takes out the same lease a build would, so a prune can never race a
/// compile in flight (this run's own, another run's, or a human's `magi
/// review`) into deleting a file that build still needs. `Ok(None)` when the
/// cache is in use right now; the next pass catches it once the borrower
/// releases it, the same way a cap of `0` or a missing `CARGO_TARGET_DIR`
/// already meant "nothing to do this time" here.
pub fn prune_cache(home: &Path, cache: &Path, limit_bytes: u64) -> Result<Option<Prune>> {
    crate::cache::maintenance_prune(home, cache, limit_bytes)
}

/// [`prune_cache`], but resolving the operator's opt-out and missing
/// `CARGO_TARGET_DIR` first — the same two checks [`housekeep`]'s idle pass
/// makes before ever measuring the cache, factored out so
/// [`crate::daemon`]'s between-runs check (see the module's own doc for why
/// congestion can make "idle" arrive too rarely to matter) makes them
/// identically rather than growing its own copy that could drift. `Ok(None)`
/// covers a cap of `0` (see the module docs on `cache_limit_bytes`), a config
/// that renders no `CARGO_TARGET_DIR` to aggregate at all, and a cache
/// currently in use (see [`prune_cache`]).
pub fn prune_cache_if_over_limit(
    cfg: &crate::config::Config,
    home: &Path,
) -> Result<Option<Prune>> {
    prune_cache_under_pressure(cfg, home, crate::disk::free_bytes)
}

/// [`prune_cache_if_over_limit`] with the free-space measurement supplied by
/// the caller.
///
/// Free space on the cache's volume below
/// [`Disk::reclaim_threshold`](crate::config::Disk::reclaim_threshold) - the
/// collection threshold, not the admission floor - shrinks the limit by the
/// deficit ([`crate::disk::pressure_limit`]). While free space is at or above
/// the admission floor and below the collection threshold the cache also keeps
/// a reserve of half its cap
/// ([`crate::disk::pressure_reserve`]), and that is enforced where files are
/// removed: the pruning routine skips a file whose removal would leave less
/// ([`crate::disk::prune_dir_keeping`]), so one artifact larger than
/// `size - reserve` is kept rather than taking the cache to nothing.
///
/// This is estimated-deficit collection: free space is measured once, the
/// deficit computed from that one number, and that many *logical* bytes are
/// removed oldest-first. There is no re-measuring loop: hard links and other
/// writers mean the space freed can differ, and the next pass (the service's
/// ordinary period away) measures again and continues. A pass that removes
/// nothing is not an error. An unreadable measurement prunes to the plain cap.
/// The cache is measured (`dir_size`, for the limit) only below the threshold.
///
/// Log contract: a pass that *runs to completion* - it measured free space,
/// took the maintenance lease and walked the cache - emits one `info` line
/// with the admission floor, the collection threshold, the free bytes
/// measured, the size the pruning routine's own inventory reported, the
/// logical bytes removed and an outcome ([`crate::disk::PressureOutcome`]:
/// `within limit`, `at reserve`, `collected`, `nothing eligible`). A pass that
/// is refused or fails (lease or Cargo lock held, an I/O error, an unreadable
/// free-space measurement) reports exactly as it did before the threshold
/// existed - its return value or error - and emits no additional line.
pub(crate) fn prune_cache_under_pressure(
    cfg: &crate::config::Config,
    home: &Path,
    free_bytes: impl Fn(&Path) -> Result<u64>,
) -> Result<Option<Prune>> {
    let cap = cfg.disk.cache_limit_bytes;
    if cap == 0 {
        return Ok(None);
    }
    let Some(cache) = cfg.cache_dir() else {
        return Ok(None);
    };
    let floor = cfg.disk.min_free_bytes;
    let threshold = cfg.disk.reclaim_threshold();
    let free = free_bytes(&cache).ok();
    let (limit, keep) = free
        .filter(|free| *free < threshold)
        .map_or((cap, 0), |free| {
            (
                crate::disk::pressure_limit(dir_size(&cache), cap, floor, threshold, free),
                crate::disk::pressure_reserve(cap, floor, threshold, free),
            )
        });
    let prune = crate::cache::maintenance_prune_keeping(home, &cache, limit, keep)?;
    if let (Some(free), Some(pruned)) = (free, prune) {
        let size = pruned.remaining.saturating_add(pruned.freed);
        let outcome = crate::disk::pressure_outcome(pruned.freed, size, limit, keep);
        tracing::info!(
            cache = %cache.display(),
            admission_floor = floor,
            collection_threshold = threshold,
            free,
            size,
            removed = pruned.freed,
            outcome = outcome.as_str(),
            "shared build cache pressure pass"
        );
    }
    Ok(prune)
}

/// The cache's path, size and cap, for `magi cache show` and the health view.
/// `None` when the config declares no `CARGO_TARGET_DIR` to aggregate.
///
/// A cap of `0` means the operator opted out of pruning; the size is then
/// reported but never acted on.
pub fn cache_report(cfg: &crate::config::Config) -> Option<(PathBuf, u64, u64)> {
    let cache = cfg.cache_dir()?;
    Some((
        cache.clone(),
        cache_size(&cache),
        cfg.disk.cache_limit_bytes,
    ))
}

/// Size in bytes of the shared build cache.
pub fn cache_size(cache: &Path) -> u64 {
    dir_size(cache)
}

#[cfg(test)]
pub(crate) mod tests {

    async fn sh(cwd: &Path, args: &[&str]) {
        let out = crate::git::git_raw(cwd, args).await.expect("spawn git");
        assert!(out.ok(), "git {args:?}: {}", out.stderr);
    }

    async fn commit(cwd: &Path, file: &str, body: &str) {
        std::fs::write(cwd.join(file), body).unwrap();
        sh(cwd, &["add", file]).await;
        sh(
            cwd,
            &[
                "-c",
                "user.name=t",
                "-c",
                "user.email=t@example.com",
                "commit",
                "-q",
                "-m",
                body,
            ],
        )
        .await;
    }

    const LONG: std::time::Duration = std::time::Duration::from_secs(30);

    #[tokio::test]
    async fn fetch_advances_origin_main_and_leaves_the_checkout_alone() {
        let tmp = tempfile::tempdir().unwrap();
        let t = tmp.path();
        let bare = t.join("remote.git");
        sh(
            t,
            &["init", "-q", "--bare", "-b", "main", bare.to_str().unwrap()],
        )
        .await;
        let dir = t.join("root/h/o/r");
        std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
        sh(
            t,
            &["clone", "-q", bare.to_str().unwrap(), dir.to_str().unwrap()],
        )
        .await;
        sh(&dir, &["checkout", "-q", "-b", "main"]).await;
        commit(&dir, "a.txt", "one").await;
        sh(&dir, &["push", "-q", "origin", "main"]).await;
        sh(&dir, &["checkout", "-q", "--detach"]).await;
        std::fs::write(dir.join("a.txt"), "dirty").unwrap();

        let other = t.join("other");
        sh(
            t,
            &[
                "clone",
                "-q",
                bare.to_str().unwrap(),
                other.to_str().unwrap(),
            ],
        )
        .await;
        commit(&other, "b.txt", "two").await;
        sh(&other, &["push", "-q", "origin", "HEAD:main"]).await;

        let rev = |d: PathBuf, r: &'static str| async move {
            crate::git::git(&d, &["rev-parse", r]).await.unwrap()
        };
        let head = rev(dir.clone(), "HEAD").await;
        let before = rev(dir.clone(), "origin/main").await;
        let status = crate::git::git(&dir, &["status", "--porcelain"])
            .await
            .unwrap();

        let r = fetch_origins(&[t.join("root")], LONG, || false).await;
        assert_eq!(
            r,
            FetchReport {
                fetched: 1,
                no_origin: 0,
                failed: 0
            }
        );

        assert_ne!(rev(dir.clone(), "origin/main").await, before);
        assert_eq!(rev(dir.clone(), "HEAD").await, head);
        assert_eq!(
            crate::git::git(&dir, &["status", "--porcelain"])
                .await
                .unwrap(),
            status
        );
        assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "dirty");
    }

    #[tokio::test]
    async fn fetch_never_writes_a_local_branch_whatever_the_configured_refspec() {
        let tmp = tempfile::tempdir().unwrap();
        let t = tmp.path();
        let bare = t.join("remote.git");
        sh(
            t,
            &["init", "-q", "--bare", "-b", "main", bare.to_str().unwrap()],
        )
        .await;
        let dir = t.join("root/h/o/r");
        std::fs::create_dir_all(dir.parent().unwrap()).unwrap();
        sh(
            t,
            &["clone", "-q", bare.to_str().unwrap(), dir.to_str().unwrap()],
        )
        .await;
        sh(&dir, &["checkout", "-q", "-b", "main"]).await;
        commit(&dir, "a.txt", "one").await;
        sh(&dir, &["push", "-q", "origin", "main"]).await;
        sh(&dir, &["checkout", "-q", "--detach"]).await;
        // A hostile mapping onto the local branch, and no origin/* at all.
        sh(
            &dir,
            &[
                "config",
                "remote.origin.fetch",
                "+refs/heads/main:refs/heads/main",
            ],
        )
        .await;
        let _ = crate::git::git_raw(&dir, &["update-ref", "-d", "refs/remotes/origin/main"]).await;

        let other = t.join("other");
        sh(
            t,
            &[
                "clone",
                "-q",
                bare.to_str().unwrap(),
                other.to_str().unwrap(),
            ],
        )
        .await;
        commit(&other, "b.txt", "two").await;
        sh(&other, &["push", "-q", "origin", "HEAD:main"]).await;
        let remote_tip = crate::git::git(&other, &["rev-parse", "HEAD"])
            .await
            .unwrap();
        let local_main = crate::git::git(&dir, &["rev-parse", "refs/heads/main"])
            .await
            .unwrap();

        let r = fetch_origins(&[t.join("root")], LONG, || false).await;
        assert_eq!(r.fetched, 1);
        assert_eq!(
            crate::git::git(&dir, &["rev-parse", "refs/remotes/origin/main"])
                .await
                .unwrap(),
            remote_tip
        );
        assert_eq!(
            crate::git::git(&dir, &["rev-parse", "refs/heads/main"])
                .await
                .unwrap(),
            local_main
        );
    }

    #[tokio::test]
    async fn fetch_skips_no_origin_and_survives_an_unreachable_origin() {
        let tmp = tempfile::tempdir().unwrap();
        let t = tmp.path();
        let root = t.join("root");
        let bare = t.join("remote.git");
        sh(t, &["init", "-q", "--bare", bare.to_str().unwrap()]).await;

        let none = root.join("h/o/none");
        let dead = root.join("h/o/dead");
        let good = root.join("h/o/good");
        for d in [&none, &dead, &good] {
            std::fs::create_dir_all(d).unwrap();
            sh(d, &["init", "-q"]).await;
        }
        sh(
            &dead,
            &[
                "remote",
                "add",
                "origin",
                t.join("missing").to_str().unwrap(),
            ],
        )
        .await;
        sh(&good, &["remote", "add", "origin", bare.to_str().unwrap()]).await;

        let r = fetch_origins(&[root], LONG, || false).await;
        assert_eq!(
            r,
            FetchReport {
                fetched: 1,
                no_origin: 1,
                failed: 1
            }
        );
    }
    use super::*;
    use crate::config::Disk;
    use std::fs;

    fn ts(s: &str) -> Timestamp {
        s.parse().expect("rfc3339")
    }

    fn block_on<F: std::future::Future>(f: F) -> F::Output {
        tokio::runtime::Runtime::new().expect("runtime").block_on(f)
    }

    #[test]
    fn a_run_is_due_after_its_grace_and_not_before() {
        let now = ts("2026-09-05T00:00:00Z");
        let grace = 600;
        let old = now - SignedDuration::new(601, 0);
        let fresh = now - SignedDuration::new(599, 0);
        assert!(due(now, old, grace));
        assert!(!due(now, fresh, grace));
        // Exactly at the edge: not yet due.
        let edge = now - SignedDuration::new(600, 0);
        assert!(!due(now, edge, grace));
        // A zero grace folds everything, ever.
        assert!(due(now, old, 0));
    }

    #[test]
    fn rotate_from_moves_the_starting_point_as_the_cursor_advances() {
        let ids: Vec<String> = ["a", "b", "c", "d", "e"]
            .iter()
            .map(|s| s.to_string())
            .collect();

        // A cursor of 0 starts at the front, same as an unrotated list.
        assert_eq!(rotate_from(&ids, 0), ids);

        // A cursor of 2 starts two ids further along, with the skipped
        // front wrapping to the tail rather than being dropped.
        let at_2 = rotate_from(&ids, 2);
        assert_eq!(at_2, vec!["c", "d", "e", "a", "b"]);
        for id in &ids {
            assert!(at_2.contains(id));
        }

        // A cursor past the list's own length wraps rather than panicking -
        // the caller never has to reduce it modulo anything itself.
        assert_eq!(rotate_from(&ids, 7), rotate_from(&ids, 2));

        // An empty list has no start point to compute and must not panic.
        assert_eq!(rotate_from(&[], 0), Vec::<String>::new());
    }

    /// A fleet with more eligible runs than one pass can check must not park
    /// the same handful at the front of the window forever: advancing the
    /// cursor by exactly how many ids one pass actually looked at - the
    /// arithmetic [`reconcile_external_merges`] itself does - walks every id
    /// to the front within one full rotation, with no reliance on how often
    /// or how regularly passes happen to run.
    #[test]
    fn advancing_the_cursor_by_the_window_size_gives_every_id_a_turn() {
        let ids: Vec<String> = (0..12).map(|n| format!("run-{n}")).collect();
        let cap = 5usize;
        let mut cursor = 0usize;
        let mut ever_seen: std::collections::HashSet<String> = std::collections::HashSet::new();
        for _ in 0..ids.len() {
            let window: Vec<String> = rotate_from(&ids, cursor).into_iter().take(cap).collect();
            ever_seen.extend(window.iter().cloned());
            cursor = (cursor + window.len()) % ids.len();
        }
        assert_eq!(
            ever_seen.len(),
            ids.len(),
            "every id must be checked at least once across a full rotation, whatever \
             the cadence between passes"
        );
    }

    #[test]
    fn the_external_merge_cursor_round_trips_through_a_files_absence() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();

        // Nothing written yet: starts at 0, not an error.
        assert_eq!(read_external_merge_cursor(home), 0);

        write_external_merge_cursor(home, 7);
        assert_eq!(read_external_merge_cursor(home), 7);

        // Anything unreadable as a plain number falls back to 0 rather than
        // wedging the sweep on a corrupt file.
        std::fs::write(home.join(EXTERNAL_MERGE_CURSOR_FILE), "not a number").unwrap();
        assert_eq!(read_external_merge_cursor(home), 0);
    }

    #[test]
    fn a_run_qualifies_for_an_external_merge_check_only_when_blocked_unmerged_and_due() {
        let now = ts("2026-09-05T00:00:00Z");
        let grace = 600;
        let old = now - SignedDuration::new(601, 0);
        let fresh = now - SignedDuration::new(599, 0);

        assert!(
            eligible_for_external_merge_check(RunStatus::Blocked, false, old, now, grace),
            "blocked, unmerged, and past its grace period is exactly the run this exists for"
        );
        assert!(
            !eligible_for_external_merge_check(RunStatus::Blocked, false, fresh, now, grace),
            "an operator mid-fix deserves the same grace window `fold_due` gives before \
             the janitor starts asking GitHub about it"
        );
        assert!(
            !eligible_for_external_merge_check(RunStatus::Blocked, true, old, now, grace),
            "a run `land::land` already recorded a merge outcome for has its own answer \
             already; this check is only for a run with nothing recorded at all"
        );
        assert!(
            !eligible_for_external_merge_check(RunStatus::Stalled, false, old, now, grace),
            "stalled is not blocked - it means the tally never reached quorum, which a \
             pull request cannot fix"
        );
        assert!(
            !eligible_for_external_merge_check(RunStatus::Ready, false, old, now, grace),
            "ready has nothing to correct - it was never landed by design"
        );
        assert!(
            !eligible_for_external_merge_check(RunStatus::Superseded, false, old, now, grace),
            "a superseded run's task already has its answer from a later attempt; \
             there is nothing left for GitHub to confirm here"
        );
    }

    /// A blocked run with a winner in an isolated repository directory.
    /// Consumer tests inject forge results without invoking a real CLI.
    fn write_blocked_run(runs: &Path, id: &str, updated_at: Timestamp) {
        use crate::run::{Candidate, Tally};
        use std::collections::BTreeMap;

        let mut state = RunState::new(
            runs.parent().unwrap().to_path_buf(),
            "main".to_owned(),
            "0000000000000000000000000000000000000000".to_owned(),
            String::new(),
            crate::config::Config::default(),
        );
        state.id = id.to_owned();
        state.status = RunStatus::Blocked;
        state.updated_at = updated_at;
        state.candidates.push(Candidate {
            index: 0,
            label: 'A',
            agent: "agent".to_owned(),
            branch: format!("magi/{id}/A"),
            worktree: runs.parent().unwrap().join("candidate"),
            summary: String::new(),
            stat: String::new(),
            files: 0,
            commits: 0,
            empty: false,
            failed: None,
            verified_noop: None,
            duration_ms: 0,
            folded: false,
        });
        state.tally = Some(Tally {
            first_choice: BTreeMap::from([('A', 1)]),
            borda: BTreeMap::new(),
            winner: 'A',
            rankings: 1,
            unanimous_initial: true,
            deliberated: false,
            changed_votes: 0,
            unanimous_final: true,
            tie_break: None,
            judges: 1,
            present: 1,
            quorum: 1,
            met_quorum: true,
            uncontested: None,
        });
        std::fs::create_dir_all(runs.join(id)).unwrap();
        std::fs::write(
            runs.join(id).join("run.json"),
            serde_json::to_string_pretty(&state).unwrap(),
        )
        .unwrap();
    }

    /// No run here can be confirmed merged - one has a forge error,
    /// one has not sat blocked long enough, and one is
    /// claimed by a live daemon - so the sweep must leave every one of them
    /// exactly as it found them and never panic on the failures in between.
    #[tokio::test]
    async fn reconcile_external_merges_leaves_ineligible_and_unconfirmable_runs_alone() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let home = dir.path().to_path_buf();
        std::fs::create_dir_all(&runs).unwrap();

        let now = ts("2026-09-05T00:00:00Z");
        let disk = Disk {
            fold_grace_secs: 600,
            ..Disk::default()
        };

        let due_id = "20260905-000000-blkd";
        write_blocked_run(&runs, due_id, ts("2026-08-01T00:00:00Z"));

        let fresh_id = "20260905-000000-fres";
        write_blocked_run(&runs, fresh_id, now);

        let live_id = "20260905-000000-live";
        write_blocked_run(&runs, live_id, ts("2026-08-01T00:00:00Z"));
        let mut status = crate::daemon::Status::new();
        status.current = vec![crate::daemon::Current {
            worker: None,
            task: "20260905-000000-task".to_owned(),
            run: live_id.to_owned(),
        }];
        status.updated_at = now;
        crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();

        let reconciled = reconcile_external_merges_with(&runs, &home, &disk, now, |_| async {
            anyhow::bail!("injected forge authentication failure")
        })
        .await;
        assert_eq!(reconciled, 0, "a forge failure can never confirm a merge");
        for id in [due_id, fresh_id, live_id] {
            assert_eq!(
                read_meta(&runs, id).unwrap().status,
                RunStatus::Blocked,
                "{id} must be left exactly as it was found"
            );
        }
        let notices = crate::notices::Notices::at(home.join("notifications")).list();
        let due_notice = notices
            .iter()
            .find(|n| n.key == format!("merged-unrecorded:{due_id}"))
            .expect("notice for due_id must be raised");
        assert_eq!(
            due_notice.link,
            Some(crate::notices::Link::Run {
                id: due_id.to_owned(),
            })
        );
    }

    #[tokio::test]
    async fn historical_external_merge_check_preserves_unknown_history() {
        let home = tempfile::tempdir().unwrap();
        let runs = home.path().join("runs");
        let id = "legacy";
        write_blocked_run(&runs, id, ts("2026-08-01T00:00:00Z"));
        let path = runs.join(id).join("run.json");
        let mut state = read_state(&runs, id).unwrap();
        state.repo = home.path().join("removed");
        state.candidates[0].folded = true;
        let original = serde_json::to_vec(&state).unwrap();
        std::fs::write(&path, &original).unwrap();
        let count = reconcile_external_merges_with(
            &runs,
            home.path(),
            &Disk::default(),
            ts("2026-11-14T00:00:00Z"),
            |_| async { panic!("historical unavailable checkout must not invoke the forge") },
        )
        .await;
        assert_eq!(count, 0);
        assert_eq!(std::fs::read(&path).unwrap(), original);
        assert!(
            crate::notices::Notices::at(home.path().join("notifications"))
                .all()
                .is_empty()
        );

        // The same folded run is actionable when a current task owns it.
        let queue = crate::queue::Queue::at(home.path().join("queue"));
        let mut task = crate::queue::Task::new(
            "current".into(),
            "current".into(),
            state.repo.clone(),
            crate::queue::Source::Human,
        );
        task.runs.push(id.into());
        queue.put(&mut task).unwrap();
        reconcile_external_merges_with(
            &runs,
            home.path(),
            &Disk::default(),
            ts("2026-11-14T00:00:00Z"),
            |_| async { anyhow::bail!("current checkout unavailable") },
        )
        .await;
        assert_eq!(
            crate::notices::Notices::at(home.path().join("notifications"))
                .list()
                .len(),
            1
        );
        assert_eq!(std::fs::read(&path).unwrap(), original);
    }

    /// The bug this exists to pin: a first version rotated on
    /// `now.as_second() % len`, which is fully determined by wall-clock time
    /// and nothing else. Two passes seconds apart - as they would be when a
    /// short poll interval and a fast pass alias onto the same handful of
    /// `now.as_second()` residues - landed on the *same* starting point and
    /// never covered a fleet bigger than the per-pass cap, however many
    /// times housekeeping ran. Persisting a cursor makes forward progress a
    /// function of how many ids got looked at, not of when the clock reads
    /// this pass happened to run.
    #[tokio::test]
    async fn reconcile_external_merges_covers_a_larger_fleet_across_repeated_passes_at_one_instant()
    {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let home = dir.path().to_path_buf();
        std::fs::create_dir_all(&runs).unwrap();

        let now = ts("2026-09-05T00:00:00Z");
        let disk = Disk {
            fold_grace_secs: 600,
            ..Disk::default()
        };
        let old = ts("2026-08-01T00:00:00Z");

        let ids: Vec<String> = (0..8).map(|n| format!("20260905-000000-r{n:03}")).collect();
        for id in &ids {
            write_blocked_run(&runs, id, old);
        }

        let notices = crate::notices::Notices::at(home.join("notifications"));

        // Two passes at the exact same `now`, exactly what a fast pass on a
        // short poll interval looks like. Each of the 8 injected forge-failure
        // runs raises its own notice the first time it is looked at, so the
        // count of distinct notices is a direct readout of how many distinct
        // ids have been checked so far.
        reconcile_external_merges_with(&runs, &home, &disk, now, |_| async {
            anyhow::bail!("injected forge authentication failure")
        })
        .await;
        let after_first = notices.list().len();
        assert_eq!(
            after_first, MAX_EXTERNAL_MERGE_CHECKS_PER_PASS,
            "the first pass checks exactly one cap's worth"
        );

        reconcile_external_merges_with(&runs, &home, &disk, now, |_| async {
            anyhow::bail!("injected forge authentication failure")
        })
        .await;
        let after_second = notices.list().len();
        assert_eq!(
            after_second,
            ids.len(),
            "a second pass at the same instant must still reach every id the \
             first pass had no room for, not repeat the same cap's worth"
        );
    }

    #[test]
    fn the_meta_reader_is_tolerant_of_everything_except_the_deciders() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let id = "20260905-000000-abcd";
        std::fs::create_dir_all(runs.join(id)).unwrap();
        std::fs::write(
            runs.join(id).join("run.json"),
            r#"{"schema": 99, "id": "20260905-000000-abcd", "updated_at": "2026-09-05T00:00:00Z", "status": "ready", "junk_from_another_build": [1, 2, 3]}"#,
        )
        .unwrap();
        let meta = read_meta(&runs, id).expect("readable");
        assert_eq!(meta.status, RunStatus::Ready);
        assert_eq!(meta.updated_at, ts("2026-09-05T00:00:00Z"));
        assert!(read_meta(&runs, "nope").is_err(), "missing file unreadable");
        std::fs::write(runs.join(id).join("run.json"), "not json at all").unwrap();
        assert!(read_meta(&runs, id).is_err(), "garbage unreadable");
    }

    #[test]
    fn fold_unreadable_preserves_unknown_content_and_recovery_artifacts() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let wt = dir.path().join("wt");
        let id = "20260905-000000-abcd";
        std::fs::create_dir_all(runs.join(id).join("artifacts")).unwrap();
        std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
        std::fs::create_dir_all(wt.join("abcd")).unwrap();
        std::fs::write(wt.join("abcd/leftover"), "owned edits").unwrap();
        assert!(block_on(fold_unreadable(&runs, &wt, id)).is_err());
        assert!(runs.join(id).join("artifacts").exists());
        assert_eq!(
            std::fs::read_to_string(wt.join("abcd/leftover")).unwrap(),
            "owned edits"
        );
    }

    #[test]
    fn fold_unreadable_releases_run_dir_and_worktrees() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let wt = dir.path().join("wt");
        let id = "20260905-000000-abcd";
        std::fs::create_dir_all(runs.join(id)).unwrap();
        std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
        std::fs::create_dir_all(wt.join("abcd")).unwrap();

        let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold");
        assert_eq!(removed.len(), 2);
        assert!(!runs.join(id).exists(), "run dir gone");
        assert!(!wt.join("abcd").exists(), "worktrees gone");

        // A prefix resolves like `run::resolve_id` does.
        std::fs::create_dir_all(runs.join(id)).unwrap();
        std::fs::write(runs.join(id).join("run.json"), "garbage").unwrap();
        std::fs::create_dir_all(wt.join("abcd")).unwrap();
        let removed = block_on(fold_unreadable(&runs, &wt, "20260905")).expect("by prefix");
        assert_eq!(removed.len(), 2);
        // Once gone, `id` cannot be resolved at all - same as `run::resolve_id`
        // on an id nothing on disk matches - so a repeat pass errors rather
        // than silently reporting nothing removed.
        assert!(
            block_on(fold_unreadable(&runs, &wt, id)).is_err(),
            "a run already gone cannot be resolved again"
        );
    }

    #[test]
    fn prune_cache_sheds_the_oldest_generation_until_it_fits() {
        let home = tempfile::tempdir().unwrap();
        let dir = tempfile::tempdir().unwrap();
        // Same size, different age: only the age decides, and the newest
        // generation - the one the next build reuses - is what survives.
        fs::write(dir.path().join("old"), b"xx").unwrap();
        fs::write(dir.path().join("new"), b"yy").unwrap();
        touch(&dir.path().join("old"), 1_000_000);
        touch(&dir.path().join("new"), 2_000_000);

        let out = prune_cache(home.path(), dir.path(), 2)
            .expect("prune")
            .expect("the cache is free");
        assert_eq!(out.files, 1, "one deletion is enough to reach the cap");
        assert_eq!(out.remaining, 2);
        assert!(!dir.path().join("old").exists(), "the older file went");
        assert!(dir.path().join("new").exists(), "the newer one stayed");

        // A whole generation shares one timestamp tick, so the tie has to be
        // decided too: largest first, which reaches the cap in the fewest
        // deletions. Left to `read_dir` and an unstable sort this deleted
        // both files on Linux and one on Windows.
        let tied = tempfile::tempdir().unwrap();
        fs::write(tied.path().join("big"), b"xxxx").unwrap();
        fs::write(tied.path().join("small"), b"yy").unwrap();
        touch(&tied.path().join("big"), 1_000_000);
        touch(&tied.path().join("small"), 1_000_000);
        let out = prune_cache(home.path(), tied.path(), 2)
            .expect("prune")
            .expect("the cache is free");
        assert_eq!(out.files, 1, "the big one alone gets under the cap");
        assert_eq!(out.remaining, 2);
        assert!(tied.path().join("small").exists());
    }

    #[test]
    fn prune_cache_if_over_limit_resolves_the_opt_outs_before_ever_measuring() {
        let home = tempfile::tempdir().unwrap();
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("big"), vec![0u8; 10]).unwrap();

        let mut cfg = crate::config::Config::default();
        cfg.verify.gate = vec![format!(
            "CARGO_TARGET_DIR={} cargo make check",
            dir.path().display()
        )];

        // A cap of `0` is the operator's opt-out: never measured, never
        // pruned, regardless of what is actually on disk.
        cfg.disk.cache_limit_bytes = 0;
        assert_eq!(
            prune_cache_if_over_limit(&cfg, home.path()).unwrap(),
            None,
            "a zero cap must not even look at the directory"
        );
        assert!(dir.path().join("big").exists());

        // No `CARGO_TARGET_DIR` in either verify command: nothing to
        // aggregate, so there is nothing to prune either.
        let mut no_cache = crate::config::Config::default();
        no_cache.disk.cache_limit_bytes = 1;
        assert_eq!(
            prune_cache_if_over_limit(&no_cache, home.path()).unwrap(),
            None
        );

        // Over the cap and configured: pruned exactly like `prune_cache`
        // itself would.
        cfg.disk.cache_limit_bytes = 1;
        let pruned = prune_cache_if_over_limit(&cfg, home.path())
            .unwrap()
            .expect("a real cache dir over its cap prunes");
        assert_eq!(pruned.files, 1);
        assert!(!dir.path().join("big").exists());
    }

    /// A shared cache of four 100-byte files, `f1` the oldest, capped at 500
    /// (so its reserve is 250), and a config that names it with the given
    /// admission floor and collection setting. The cache dir is quoted in the
    /// command, as a path with spaces needs.
    fn pressure_fixture(
        min_free_bytes: u64,
        reclaim_free_bytes: Option<u64>,
    ) -> (tempfile::TempDir, tempfile::TempDir, crate::config::Config) {
        let home = tempfile::tempdir().unwrap();
        let dir = tempfile::tempdir().unwrap();
        for (i, name) in ["f1", "f2", "f3", "f4"].into_iter().enumerate() {
            fs::write(dir.path().join(name), vec![0u8; 100]).unwrap();
            touch(&dir.path().join(name), 1_000_000 + i as u64);
        }
        let mut cfg = crate::config::Config::default();
        cfg.verify.gate = vec![format!(
            "CARGO_TARGET_DIR=\"{}\" cargo make check",
            dir.path().display()
        )];
        cfg.disk.cache_limit_bytes = 500;
        cfg.disk.min_free_bytes = min_free_bytes;
        cfg.disk.reclaim_free_bytes = reclaim_free_bytes;
        (home, dir, cfg)
    }

    /// One pass with `free` as the volume's free space, and the files left.
    fn pass(
        cfg: &crate::config::Config,
        home: &Path,
        dir: &Path,
        free: u64,
    ) -> (Option<Prune>, Vec<&'static str>) {
        let pruned = prune_cache_under_pressure(cfg, home, |_| Ok(free)).unwrap();
        let left = ["f1", "f2", "f3", "f4"]
            .into_iter()
            .filter(|name| dir.join(name).exists())
            .collect();
        (pruned, left)
    }

    #[test]
    fn a_pass_removes_the_estimated_deficit_between_the_floor_and_the_threshold() {
        // Floor 10, threshold 30, free 11 (one byte above the floor): a 19-byte
        // deficit on a 400-byte cache above its reserve (250), so the limit is
        // 381 and the oldest file (100 logical bytes) covers it. The pass
        // measures free space once: the injected 11 never changes.
        // On origin/main (threshold = floor) the same input has no deficit and
        // removes nothing, so these assertions fail there.
        let (home, dir, cfg) = pressure_fixture(10, Some(30));
        let (pruned, left) = pass(&cfg, home.path(), dir.path(), 11);
        let pruned = pruned.expect("cache is free");
        assert_eq!(
            (pruned.files, pruned.freed, pruned.remaining),
            (1, 100, 300)
        );
        assert_eq!(left, ["f2", "f3", "f4"]);

        // The default threshold (twice the floor = 20) collects at free 11 too.
        let (home, dir, cfg) = pressure_fixture(10, None);
        let (pruned, left) = pass(&cfg, home.path(), dir.path(), 11);
        assert_eq!(pruned.unwrap().files, 1);
        assert_eq!(left, ["f2", "f3", "f4"]);
    }

    #[test]
    fn the_shared_cache_is_left_alone_at_or_above_the_threshold() {
        let (home, dir, cfg) = pressure_fixture(10, Some(30));
        for free in [30, 31, u64::MAX] {
            let (pruned, left) = pass(&cfg, home.path(), dir.path(), free);
            assert_eq!(pruned.unwrap().files, 0, "free {free}");
            assert_eq!(left.len(), 4);
        }
        // A threshold equal to the floor is the old behaviour: nothing at 11.
        let (home2, dir2, floor_only) = pressure_fixture(10, Some(10));
        let (pruned, left) = pass(&floor_only, home2.path(), dir2.path(), 11);
        assert_eq!(pruned.unwrap().files, 0);
        assert_eq!(left.len(), 4);

        // A zero cap is still "pruning off", whatever the pressure.
        let (home3, dir3, mut off) = pressure_fixture(10, Some(1000));
        off.disk.cache_limit_bytes = 0;
        assert!(
            prune_cache_under_pressure(&off, home3.path(), |_| Ok(0))
                .unwrap()
                .is_none()
        );
        assert!(dir3.path().join("f1").exists());
    }

    #[test]
    fn above_the_floor_the_reserve_is_enforced_where_files_go_and_passes_converge() {
        // The threshold is out of reach and free space is pinned at 11 by
        // another program. Reserve = half the 500 cap = 250. The limit (250)
        // would take the cache from 400 to 250; the oldest file goes (300),
        // and the next removal would leave 200, below the reserve, so it is
        // skipped, as is every later one.
        let (home, dir, cfg) = pressure_fixture(10, Some(1_000_000));
        let (first, left) = pass(&cfg, home.path(), dir.path(), 11);
        let first = first.unwrap();
        assert_eq!((first.files, first.remaining), (1, 300), "{first:?}");
        assert_eq!(left, ["f2", "f3", "f4"]);

        // However long the pressure lasts, nothing more goes.
        let (second, left) = pass(&cfg, home.path(), dir.path(), 11);
        assert_eq!(second.unwrap().files, 0);
        assert_eq!(left, ["f2", "f3", "f4"]);
    }

    #[test]
    fn an_artifact_larger_than_size_minus_reserve_survives_every_pass() {
        // One 300-byte artifact, cap 500 (reserve 250), free pinned at 11
        // between the floor (10) and the threshold. The limit is 250, which
        // alone would delete the artifact; the next build recreates it and the
        // next pass would delete it again. The reserve keeps it.
        let (home, dir, cfg) = pressure_fixture(10, Some(1_000_000));
        for name in ["f1", "f2", "f3", "f4"] {
            fs::remove_file(dir.path().join(name)).unwrap();
        }
        let artifact = dir.path().join("artifact");
        for _ in 0..3 {
            fs::write(&artifact, vec![0u8; 300]).unwrap();
            let pruned = prune_cache_under_pressure(&cfg, home.path(), |_| Ok(11))
                .unwrap()
                .expect("the cache is free");
            assert_eq!((pruned.files, pruned.remaining), (0, 300), "{pruned:?}");
            assert!(artifact.exists());
        }
        // Below the admission floor the reserve is gone: space outranks it.
        let pruned = prune_cache_under_pressure(&cfg, home.path(), |_| Ok(0))
            .unwrap()
            .expect("the cache is free");
        assert_eq!(pruned.files, 1);
        assert!(!artifact.exists());
    }

    #[test]
    fn an_oversized_oldest_artifact_is_skipped_and_smaller_files_are_still_collected() {
        // Cap 500 (reserve 250), free pinned at 11 between the floor (10) and
        // the threshold. The oldest artifact is 300 bytes of a 400-byte cache:
        // removing it would leave 100, below the reserve, so it stays - and the
        // pass goes on to the four newer 25-byte files (400 -> 300), each of
        // which leaves at least the reserve. A caller that stopped at the
        // oversized artifact would remove nothing.
        let (home, dir, cfg) = pressure_fixture(10, Some(1_000_000));
        for name in ["f1", "f2", "f3", "f4"] {
            fs::remove_file(dir.path().join(name)).unwrap();
        }
        let big = dir.path().join("big");
        fs::write(&big, vec![0u8; 300]).unwrap();
        touch(&big, 1_000_000);
        let small = ["s1", "s2", "s3", "s4"];
        for (i, name) in small.into_iter().enumerate() {
            let path = dir.path().join(name);
            fs::write(&path, vec![0u8; 25]).unwrap();
            touch(&path, 1_000_001 + i as u64);
        }
        let pruned = prune_cache_under_pressure(&cfg, home.path(), |_| Ok(11))
            .unwrap()
            .expect("the cache is free");
        assert_eq!(
            (pruned.files, pruned.freed, pruned.remaining),
            (4, 100, 300),
            "{pruned:?}"
        );
        assert!(big.exists());
        for name in small {
            assert!(!dir.path().join(name).exists(), "{name} should be gone");
        }

        // The reserve holds on the next pass: nothing more goes.
        let again = prune_cache_under_pressure(&cfg, home.path(), |_| Ok(11))
            .unwrap()
            .expect("the cache is free");
        assert_eq!((again.files, again.remaining), (0, 300), "{again:?}");
        assert!(big.exists());
    }

    #[test]
    fn below_the_admission_floor_there_is_no_reserve() {
        // Floor 150, threshold 300. At free 160 (above the floor) the reserve
        // keeps 250 of the 400 bytes: one file goes (to 300), the next would
        // leave 200. At free 0 (below the floor) the old rule applies - the
        // limit is 400 - 150 = 250 - and two go, below the reserve.
        let (home, dir, cfg) = pressure_fixture(150, Some(300));
        let (pruned, left) = pass(&cfg, home.path(), dir.path(), 160);
        assert_eq!(pruned.unwrap().files, 1);
        assert_eq!(left, ["f2", "f3", "f4"]);

        let (home, dir, cfg) = pressure_fixture(150, Some(300));
        let (pruned, left) = pass(&cfg, home.path(), dir.path(), 0);
        let pruned = pruned.unwrap();
        assert_eq!((pruned.files, pruned.remaining), (2, 200));
        assert_eq!(left, ["f3", "f4"]);
    }

    #[test]
    fn a_cache_in_use_is_left_alone() {
        let (home, dir, cfg) = pressure_fixture(10, Some(1_000_000));
        let owner = crate::cache::Owner::here("run", "node", "seat", dir.path(), "head");
        let _held = match crate::cache::try_acquire(home.path(), dir.path(), &owner).unwrap() {
            crate::cache::AcquireOutcome::Acquired(guard) => guard,
            crate::cache::AcquireOutcome::Busy(_) => panic!("fresh cache is busy"),
        };
        let (pruned, left) = pass(&cfg, home.path(), dir.path(), 11);
        assert!(pruned.is_none());
        assert_eq!(left.len(), 4);
    }

    #[test]
    fn an_unmeasurable_volume_prunes_to_the_plain_cap() {
        let (home, dir, mut cfg) = pressure_fixture(10, Some(1_000_000));
        cfg.disk.cache_limit_bytes = 350;
        let pruned = prune_cache_under_pressure(&cfg, home.path(), |_| anyhow::bail!("no volume"))
            .unwrap()
            .unwrap();
        assert_eq!(pruned.files, 1, "only the cap applies");
        assert!(!dir.path().join("f1").exists() && dir.path().join("f2").exists());
    }

    /// Pin a file's mtime, so a test asserts the policy and not the runner's
    /// timestamp granularity.
    fn touch(path: &Path, secs: u64) {
        let f = fs::File::options().write(true).open(path).unwrap();
        f.set_times(fs::FileTimes::new().set_modified(
            std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs),
        ))
        .unwrap();
    }

    /// The disk-full casualty: a run whose first save left `run.json.tmp` and
    /// nothing else. It has to be clearable, or the record is permanent.
    #[test]
    fn fold_unreadable_clears_a_run_whose_state_never_landed() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let wt = dir.path().join("wt");
        let id = "20260904-014540-88c0";
        std::fs::create_dir_all(runs.join(id)).unwrap();
        std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();

        let removed = block_on(fold_unreadable(&runs, &wt, id)).expect("fold by id");
        assert_eq!(removed, vec![format!("runs/{id}")]);
        assert!(!runs.join(id).exists(), "record gone");

        // And by prefix, the way the deck and the phone address a run.
        std::fs::create_dir_all(runs.join(id)).unwrap();
        std::fs::write(runs.join(id).join("run.json.tmp"), b"").unwrap();
        assert!(
            block_on(fold_unreadable(&runs, &wt, "88c0")).is_ok(),
            "by prefix"
        );

        // A directory under `runs` that is not a run is never a fold target.
        std::fs::create_dir_all(runs.join("scratch")).unwrap();
        assert!(
            block_on(fold_unreadable(&runs, &wt, "scratch")).is_err(),
            "a stray directory is not a run"
        );
    }

    #[test]
    fn fold_due_folds_terminal_runs_of_any_schema_but_leaves_genuinely_unreadable_ones() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let wt = dir.path().join("wt");
        let home = dir.path().to_path_buf();
        let disk = Disk::default();
        let now = ts("2026-09-05T00:00:00Z");

        // 1. Runnable (judging): never folded, however old.
        let judging = "20260801-000000-0001";
        write_meta(&runs, judging, "judging", "2026-08-01T00:00:00Z");

        // 2. Finished but fresh: grace not elapsed. Within the default 6h
        //    grace of `now`, so `fold_due` must stop at the freshness check
        //    and never even reach `read_state` - `write_meta`'s minimal JSON
        //    would fail that full parse anyway, and this case exists to
        //    prove freshness is why the run survives, not an accident of the
        //    fixture being unparseable as a whole `RunState`.
        let ready_fresh = "20260904-220000-0002";
        write_meta(&runs, ready_fresh, "ready", "2026-09-04T22:00:00Z");

        // 3. Genuinely unreadable: broken JSON, not merely an unfamiliar
        //    schema number. Left alone and counted - this is the one case
        //    automatic housekeeping must never touch (see `fold_due`'s docs);
        //    discarding it is an explicit operator action, not something a
        //    background pass does.
        let garbage = "20260901-000000-0004";
        std::fs::create_dir_all(runs.join(garbage)).unwrap();
        std::fs::write(runs.join(garbage).join("run.json"), "not json").unwrap();
        std::fs::create_dir_all(wt.join("0004")).unwrap();

        // 4. Finished, well past grace, current schema: the ordinary case
        //    `fold_due` has always acted on.
        let due_ready = due_run(&runs, &wt, "20260801-000000-ffff", SCHEMA);

        // 5. Finished, well past grace, but written by a schema number this
        //    build no longer matches - the defect this task exists to fix.
        //    It still parses cleanly, so only the version number differs, and
        //    that alone must not block folding.
        let due_old_schema = due_run(&runs, &wt, "20260801-000000-eeee", SCHEMA - 1);

        let (folded, unreadable) =
            block_on(fold_due(&runs, &home, &wt, &disk, now)).expect("fold_due");
        assert_eq!(
            folded, 2,
            "both due, parseable runs fold regardless of their schema number"
        );
        assert_eq!(
            unreadable, 1,
            "only the run with broken JSON counts as unreadable"
        );
        assert!(runs.join(judging).exists(), "runnable never folded");
        assert!(runs.join(ready_fresh).exists(), "fresh never folded");
        assert!(runs.join(garbage).exists(), "unreadable record kept");
        assert!(wt.join("0004").exists(), "unreadable worktree kept");
        assert!(
            runs.join(&due_ready).exists(),
            "folding drops worktrees, not the record"
        );
        assert!(
            runs.join(&due_old_schema).exists(),
            "an old-schema record survives its fold exactly like a current one"
        );
        // `graph::fold_run` saves the state it just folded back to disk. That
        // write must land under this test's own `runs` - the argument it
        // passed to `fold_due`, not the process-global `run::home` - or a
        // fold that landed somewhere else entirely would still be counted
        // above as one of the two `folded` runs.
        for id in [&due_ready, &due_old_schema] {
            let saved = read_meta(&runs, id).expect("folded run still parses");
            assert_ne!(
                saved.updated_at,
                ts("2026-08-01T00:00:00Z"),
                "fold_run must have saved the updated state back through the \
                 `runs` directory this test passed to fold_due"
            );
        }
    }

    /// `[disk] auto_fold = false` must leave the janitor's fold-and-reclaim
    /// passes completely inert - a due run's worktree and record both
    /// survive exactly as if `housekeep` had never run at all. Cache pruning
    /// is a separate opt-out (`cache_limit_bytes`) and stays disabled here
    /// too, so this test is only ever about `auto_fold`.
    #[tokio::test]
    async fn housekeep_leaves_everything_alone_when_auto_fold_is_disabled() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let wt = dir.path().join("wt");
        let home = dir.path().to_path_buf();
        crate::run::set_home(dir.path().to_path_buf());

        let due_id = due_run(&runs, &wt, "20260801-000000-abcd", SCHEMA);
        std::fs::create_dir_all(wt.join("orphan").join("cand-A")).unwrap();

        let mut cfg = crate::config::Config::default();
        cfg.disk.auto_fold = false;
        cfg.disk.cache_limit_bytes = 0;

        let out = housekeep(&cfg, &home, &wt, &dir.path().join("repo"), Timestamp::now()).await;

        assert_eq!(out.folded, 0);
        assert_eq!(out.unreadable, 0);
        assert_eq!(out.orphaned_worktrees, 0);
        assert!(
            runs.join(&due_id).exists(),
            "a due run's record survives untouched"
        );
        assert!(
            wt.join("orphan").exists(),
            "an orphaned worktree survives untouched: the reclaim pass never ran"
        );
    }

    #[test]
    fn fold_orphaned_worktrees_removes_only_worktrees_no_run_claims_and_none_in_flight() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let wt = dir.path().join("wt");
        let home = dir.path().to_path_buf();

        // A run record exists for this one: its worktree is claimed, not
        // orphaned, however old the record.
        write_meta(
            &runs,
            "20260801-000000-aaaa",
            "ready",
            "2026-08-01T00:00:00Z",
        );
        std::fs::create_dir_all(wt.join("aaaa").join("cand-A")).unwrap();

        // No run record at all, and nobody is working on it: this is the
        // leftover `fold_due` can never see, because it only ever walks
        // `runs/`.
        std::fs::create_dir_all(wt.join("bbbb").join("cand-A")).unwrap();

        // No run record either, but a live daemon status names a run with
        // this short id - the save-timing gap between the daemon claiming a
        // task and `RunState::new` writing its first `run.json`. Must survive
        // untouched.
        std::fs::create_dir_all(wt.join("cccc")).unwrap();

        // Not shaped like a run's short id at all - a scratch directory an
        // operator or another tool left in the same bay - so it is never a
        // reclaim target regardless of what runs claim it or not.
        std::fs::create_dir_all(wt.join("scratch")).unwrap();

        // `now` pushed comfortably past `MIN_ORPHAN_AGE_SECS`, so a zero
        // grace - the same "always due" escape hatch `due` itself documents
        // - still reclaims once a worktree is genuinely old, without faking
        // an mtime: real directory creation just above is already in the
        // past relative to this `now`, by design rather than by timing.
        let now = Timestamp::now() + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
        let mut status = crate::daemon::Status::new();
        status.current = vec![crate::daemon::Current {
            worker: None,
            task: "20260905-000000-t111".to_owned(),
            run: "20260905-000000-cccc".to_owned(),
        }];
        status.updated_at = now;
        crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();

        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
        assert_eq!(
            folded, 1,
            "only the truly orphaned, idle, bay-shaped worktree is removed"
        );
        assert!(wt.join("aaaa").exists(), "claimed by a run record");
        assert!(!wt.join("bbbb").exists(), "orphaned and idle: reclaimed");
        assert!(wt.join("cccc").exists(), "a run in flight is never touched");
        assert!(
            wt.join("scratch").exists(),
            "not shaped like a worktree bay, so never a reclaim target"
        );
    }

    /// The gap this closes: `Runner::review` (`magi review`) creates the
    /// worktree with `git worktree add` before `RunState::save` ever writes a
    /// `run.json`, and that path never runs through the daemon's own `poll`
    /// loop at all, so `daemon::Status` never names it either. Without a
    /// grace window, a janitor pass landing in that gap would read the
    /// worktree as an orphan nothing is waiting on and delete a review still
    /// being set up.
    #[test]
    fn fold_orphaned_worktrees_leaves_a_freshly_created_bay_alone() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let wt = dir.path().join("wt");
        let home = dir.path().to_path_buf();

        std::fs::create_dir_all(wt.join("dddd").join("under-review")).unwrap();

        let now = Timestamp::now();
        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 6 * 60 * 60, now));
        assert_eq!(
            folded, 0,
            "too fresh to tell apart from a run still being set up"
        );
        assert!(wt.join("dddd").exists());
    }

    /// A fresh open question on `run`, stored and handed back for assertions.
    fn open_question(store: &Questions, run: &str) -> crate::ask::Question {
        let mut q = crate::ask::Question::new(
            run.to_owned(),
            "implement".to_owned(),
            "impl-A".to_owned(),
            "Which storage backend should the cache use?".to_owned(),
            String::new(),
            vec!["SQLite".to_owned(), "Redis".to_owned()],
        );
        store.put(&mut q).unwrap();
        q
    }

    /// The exact ghost the phone showed: a run that already finished, with a
    /// question its dead seat asked still sitting `open` because it reached
    /// that status before `graph::Runner::settle_questions` existed (or
    /// missed it in the crash window `daemon::reclaim_orphaned_running`
    /// covers). This sweep is the second door to the same fact.
    #[test]
    fn a_finished_runs_open_question_is_swept_up() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let store = Questions::at(dir.path().join("questions"));

        let failed = "20260908-205802-c9eb";
        write_meta(&runs, failed, "failed", "2026-09-08T20:58:02Z");
        let failed_q = open_question(&store, failed);

        let merged = "20260908-205501-ca67";
        write_meta(&runs, merged, "merged", "2026-09-08T20:55:01Z");
        let merged_q = open_question(&store, merged);

        let n = abandon_settled_questions(&store, &runs);
        assert_eq!(n, 2, "both dead runs' questions are swept in one pass");

        for (id, run) in [(&failed_q.id, failed), (&merged_q.id, merged)] {
            let back = store.get(id).unwrap();
            assert!(!back.status.open(), "{run} is done; nobody reads an answer");
            assert!(back.detail.contains(run), "{}", back.detail);
        }
    }

    #[test]
    fn a_still_alive_runs_open_question_survives_the_sweep() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let store = Questions::at(dir.path().join("questions"));

        // `Blocked` and `Stalled` are `RunStatus::resumable`: the run can
        // still be picked back up, so its question may yet get a real
        // answer. A run still mid-competition is even more obviously alive.
        for (id, status) in [
            ("20260908-000000-b10c", "blocked"),
            ("20260908-000000-5ta1", "stalled"),
            ("20260908-000000-jud6", "judging"),
        ] {
            write_meta(&runs, id, status, "2026-09-08T00:00:00Z");
            let q = open_question(&store, id);

            let n = abandon_settled_questions(&store, &runs);
            assert_eq!(n, 0, "{status} run is not done; nothing to sweep");
            assert!(
                store.get(&q.id).unwrap().status.open(),
                "{status} run's question must still be waiting"
            );
        }
    }

    #[test]
    fn the_sweep_leaves_an_answered_question_and_an_unreadable_run_alone() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let store = Questions::at(dir.path().join("questions"));

        // Already decided: a sweep must never revisit it, whatever the run
        // that asked went on to become.
        let done = "20260908-000000-answ";
        write_meta(&runs, done, "failed", "2026-09-08T00:00:00Z");
        let mut answered = open_question(&store, done);
        answered
            .answer(crate::ask::Answer::Choice("SQLite".to_owned()))
            .unwrap();
        store.put(&mut answered).unwrap();

        // No `run.json` at all for this one - deleted, or never landed.
        let gone = "20260908-000000-gone";
        let orphan = open_question(&store, gone);

        assert_eq!(abandon_settled_questions(&store, &runs), 0);
        assert_eq!(
            store.get(&answered.id).unwrap().status,
            crate::ask::QuestionStatus::Answered,
            "a real answer is never overwritten by a sweep"
        );
        assert!(
            store.get(&orphan.id).unwrap().status.open(),
            "a run this sweep cannot read is left exactly as it was, not guessed at"
        );
    }

    /// A grace of `0` is a legitimate, documented value for the operator's
    /// own `Disk::fold_grace_secs` - `due`'s "always due" case - but the
    /// freshness check this guards is not that policy, and must not collapse
    /// to it: a `0` handed straight through would reclaim a worktree the
    /// instant it exists, exactly the race `fold_orphaned_worktrees_leaves_a_
    /// freshly_created_bay_alone` exists to rule out, just with the operator
    /// having turned the other grace off instead of leaving it at its
    /// default.
    #[test]
    fn fold_orphaned_worktrees_floors_a_zero_grace_at_the_race_safe_minimum() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let wt = dir.path().join("wt");
        let home = dir.path().to_path_buf();

        std::fs::create_dir_all(wt.join("eeee").join("under-review")).unwrap();

        // Too fresh, even with the grace argument at zero.
        let now = Timestamp::now();
        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, now));
        assert_eq!(
            folded, 0,
            "a zero grace must not defeat the race-safety floor"
        );
        assert!(wt.join("eeee").exists());

        // Once genuinely past the floor, a zero grace reclaims it - the
        // floor is a minimum, not a replacement policy that never fires.
        let later = now + SignedDuration::new((MIN_ORPHAN_AGE_SECS + 1) as i64, 0);
        let folded = block_on(fold_orphaned_worktrees(&runs, &wt, &home, 0, later));
        assert_eq!(folded, 1, "old enough now, regardless of the zero grace");
        assert!(!wt.join("eeee").exists());
    }

    #[test]
    fn clear_abandoned_active_only_acts_once_dead_and_overrun() {
        let dir = tempfile::tempdir().unwrap();
        // Harmless if another test in this binary already pinned the global
        // home first (see `run::set_home`'s own doc): this test only checks
        // the in-memory mutation `clear_abandoned_active` makes, never a
        // write that landed under this exact directory.
        crate::run::set_home(dir.path().to_path_buf());
        let home = dir.path().to_path_buf();
        let now = ts("2026-09-14T12:00:00Z");
        let overrun_seat = || crate::run::ActiveSeat {
            node: "implement".to_owned(),
            started_at: now - SignedDuration::new(21_000, 0),
            timeout_secs: 3_600,
            attempt: 0,
            task: None,
            command: None,
            index: None,
            total: None,
        };

        let mut state = RunState::new(
            PathBuf::from("/repo"),
            "main".to_owned(),
            "abc1234".to_owned(),
            "fixture".to_owned(),
            crate::config::Config::default(),
        );
        state.status = RunStatus::Implementing;
        state.active.insert("impl-A".to_owned(), overrun_seat());

        // A seat still within its own budget: not provably dead yet, so this
        // must change nothing.
        let mut fresh = state.clone();
        fresh.active.insert(
            "impl-B".to_owned(),
            crate::run::ActiveSeat {
                node: "implement".to_owned(),
                started_at: now,
                timeout_secs: 3_600,
                attempt: 0,
                task: None,
                command: None,
                index: None,
                total: None,
            },
        );
        // The record is judged as saved, under the run's locks, not as the
        // caller holds it: so the records are saved first.
        fresh.save_under(&home).unwrap();
        assert!(!clear_abandoned_active(&mut fresh, &home, now).unwrap());
        assert!(!fresh.active.is_empty());
        assert_eq!(fresh.status, RunStatus::Implementing);

        state.save_under(&home).unwrap();
        let store = Questions::at(home.join("questions"));
        let q = open_question(&store, &state.id);

        assert!(clear_abandoned_active(&mut state, &home, now).unwrap());
        assert!(state.active.is_empty());
        assert_eq!(state.status, RunStatus::Failed);
        assert!(
            !store.get(&q.id).unwrap().status.open(),
            "the abandoned seat's own open question must not keep badging the \
             operator until some later daemon startup notices it"
        );
    }

    fn overrun_run(now: Timestamp) -> RunState {
        let mut state = RunState::new(
            PathBuf::from("/repo"),
            "main".to_owned(),
            "abc1234".to_owned(),
            "fixture".to_owned(),
            crate::config::Config::default(),
        );
        state.status = RunStatus::Implementing;
        state.active.insert(
            "impl-A".to_owned(),
            crate::run::ActiveSeat {
                node: "implement".to_owned(),
                started_at: now - SignedDuration::new(21_000, 0),
                timeout_secs: 3_600,
                attempt: 0,
                task: None,
                command: None,
                index: None,
                total: None,
            },
        );
        state
    }

    /// The cleanup writes the record under the run's locks, from a fresh read:
    /// a handover that landed after the fold released its own locks is neither
    /// erased by the caller's copy nor allowed to go unnoticed.
    #[test]
    fn clearing_abandoned_seats_keeps_a_handover_that_landed_after_the_fold() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path().to_path_buf();
        let now = ts("2026-09-14T12:00:00Z");
        let mut stale = overrun_run(now);
        stale.save_under(&home).unwrap();
        let mut handed = RunState::load_under(&stale.id, &home).unwrap();
        handed.released_to = Some("20260901-000000-succ".to_owned());
        handed.released_branches.push("magi/branch/A".to_owned());
        handed.save_under(&home).unwrap();

        assert!(clear_abandoned_active(&mut stale, &home, now).unwrap());
        let saved = RunState::load_under(&stale.id, &home).unwrap();
        assert_eq!(saved.released_to.as_deref(), Some("20260901-000000-succ"));
        assert_eq!(saved.released_branches, ["magi/branch/A"]);
        assert_eq!(saved.status, RunStatus::Failed);
        assert!(saved.active.is_empty());
    }

    /// Held locks and vanished records are "nothing done", never a write.
    #[test]
    fn clearing_abandoned_seats_writes_nothing_while_the_run_is_held_or_gone() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path().to_path_buf();
        let now = ts("2026-09-14T12:00:00Z");
        let mut state = overrun_run(now);
        state.save_under(&home).unwrap();
        let record = home.join("runs").join(&state.id).join("run.json");
        let before = std::fs::read(&record).unwrap();
        {
            let _owner = crate::pr_head::owner_lock(&home, &state.id).unwrap();
            assert!(!clear_abandoned_active(&mut state, &home, now).unwrap());
        }
        {
            let _lease = crate::driver::maintenance(&home, &state.id).unwrap();
            assert!(!clear_abandoned_active(&mut state, &home, now).unwrap());
        }
        assert_eq!(std::fs::read(&record).unwrap(), before);

        std::fs::remove_dir_all(home.join("runs").join(&state.id)).unwrap();
        assert!(!clear_abandoned_active(&mut state, &home, now).unwrap());
        assert!(
            !home.join("runs").join(&state.id).exists(),
            "a deleted run is not brought back by its cleanup"
        );
    }

    /// Write a whole `run.json` that magi can read, over the given state.
    fn write_meta(runs: &Path, id: &str, status: &str, updated_at: &str) {
        let day = &updated_at[..10];
        std::fs::create_dir_all(runs.join(id)).unwrap();
        let body = format!(
            r#"{{"schema": {SCHEMA}, "id": "{id}", "repo": "/nonexistent/repo", "base_branch": "main", "base_commit": "0000000000000000000000000000000000000000", "instruction": "", "created_at": "{day}T00:00:00Z", "updated_at": "{updated_at}", "status": "{status}", "seed": 1}}"#
        );
        std::fs::write(runs.join(id).join("run.json"), body).unwrap();
    }

    /// Write a fully-formed, `Ready`, well-past-grace `run.json` tagged with
    /// an arbitrary schema number - so a test can write one this build's own
    /// `RunState::new` could never produce on its own. Returns the id.
    ///
    /// `wt` becomes this run's `graph.worktree_root`: left at the config
    /// default, `RunState::worktree_root` falls through to
    /// `run::default_worktree_root` - the operator's real `~/wt/magi` - and
    /// `graph::fold_run`'s second sweep would then `read_dir` and remove
    /// worktrees there instead of anything this test owns.
    fn due_run(runs: &Path, wt: &Path, id: &str, schema: u32) -> String {
        due_run_with_status(runs, wt, id, schema, RunStatus::Ready)
    }

    /// [`due_run`], with the terminal status a caller wants instead of the
    /// `Ready` every other caller here happens to want.
    fn due_run_with_status(
        runs: &Path,
        wt: &Path,
        id: &str,
        schema: u32,
        status: RunStatus,
    ) -> String {
        let mut config = crate::config::Config::default();
        config.graph.worktree_root = Some(wt.to_path_buf());
        let mut state = RunState::new(
            PathBuf::from("/nonexistent/repo"),
            "main".to_owned(),
            "0000000000000000000000000000000000000000".to_owned(),
            String::new(),
            config,
        );
        state.id = id.to_owned();
        state.status = status;
        state.updated_at = ts("2026-08-01T00:00:00Z");
        let mut value = serde_json::to_value(&state).unwrap();
        value["schema"] = serde_json::json!(schema);
        std::fs::create_dir_all(runs.join(id)).unwrap();
        std::fs::write(
            runs.join(id).join("run.json"),
            serde_json::to_string_pretty(&value).unwrap(),
        )
        .unwrap();
        id.to_owned()
    }

    #[test]
    fn fold_due_folds_a_superseded_run_same_as_any_other_terminal_one() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let wt = dir.path().join("wt");
        let home = dir.path().to_path_buf();
        let disk = Disk::default();
        let now = ts("2026-09-05T00:00:00Z");

        let superseded = due_run_with_status(
            &runs,
            &wt,
            "20260801-000000-cccc",
            SCHEMA,
            RunStatus::Superseded,
        );

        let (folded, unreadable) =
            block_on(fold_due(&runs, &home, &wt, &disk, now)).expect("fold_due");
        assert_eq!(
            folded, 1,
            "a superseded run has nothing left for a human to check, so it folds \
             exactly like a merged one"
        );
        assert_eq!(unreadable, 0);
        assert!(
            read_meta(&runs, &superseded).is_ok(),
            "folding drops the worktree, not the record"
        );
    }

    /// A throwaway repo with one commit on `main`, for a test that needs a
    /// real winner worktree `fold_run` can actually remove.
    pub(crate) fn init_repo(dir: &Path) {
        use crate::proc::Quiet as _;
        let run = |args: &[&str]| {
            let out = std::process::Command::new("git")
                .args(args)
                .current_dir(dir)
                .quiet()
                .output()
                .expect("spawn git");
            assert!(
                out.status.success(),
                "git {args:?} failed: {}",
                String::from_utf8_lossy(&out.stderr)
            );
        };
        run(&["init", "-b", "main"]);
        run(&["config", "user.name", "magi test"]);
        run(&["config", "user.email", "magi@example.com"]);
        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
        run(&["add", "-A"]);
        run(&["commit", "-m", "init"]);
    }

    /// A due, terminal run with a decided winner that still has a real
    /// worktree and branch on disk - so a test can tell whether folding it
    /// actually removed the winner or only left it registered as folded.
    pub(crate) async fn due_run_with_winner_worktree(
        runs: &Path,
        wt: &Path,
        repo: &Path,
        id: &str,
        status: RunStatus,
    ) -> (String, PathBuf) {
        use crate::run::{Candidate, Tally};
        use std::collections::BTreeMap;

        let mut config = crate::config::Config::default();
        config.graph.worktree_root = Some(wt.to_path_buf());
        let mut state = RunState::new(
            repo.to_path_buf(),
            "main".to_owned(),
            "0000000000000000000000000000000000000000".to_owned(),
            String::new(),
            config,
        );
        state.id = id.to_owned();
        state.status = status;
        state.updated_at = ts("2026-08-01T00:00:00Z");

        let winner_wt = state.worktree_root().join("cand-A");
        crate::git::worktree_add_branch(repo, &winner_wt, &format!("magi/{id}/A"), "main")
            .await
            .expect("winner worktree");

        state.candidates.push(Candidate {
            index: 0,
            label: 'A',
            agent: "agent".to_owned(),
            branch: format!("magi/{id}/A"),
            worktree: winner_wt.clone(),
            summary: String::new(),
            stat: String::new(),
            files: 0,
            commits: 0,
            empty: false,
            failed: None,
            verified_noop: None,
            duration_ms: 0,
            folded: false,
        });
        state.tally = Some(Tally {
            first_choice: BTreeMap::from([('A', 1)]),
            borda: BTreeMap::new(),
            winner: 'A',
            rankings: 1,
            unanimous_initial: true,
            deliberated: false,
            changed_votes: 0,
            unanimous_final: true,
            tie_break: None,
            judges: 1,
            present: 1,
            quorum: 1,
            met_quorum: true,
            uncontested: None,
        });
        std::fs::create_dir_all(runs.join(id)).unwrap();
        std::fs::write(
            runs.join(id).join("run.json"),
            serde_json::to_string_pretty(&state).unwrap(),
        )
        .unwrap();
        (id.to_owned(), winner_wt)
    }

    /// [`due_run_with_winner_worktree`] for a *confirmed merged* run: the
    /// fetched base (`refs/remotes/origin/main`) already holds the winner's
    /// tip, so the confirmed-merge source proof passes and the fold keeps an
    /// evidence manifest instead of any patch. The record keeps its old
    /// `updated_at`, so the run stays past any grace.
    pub(crate) async fn merged_run_with_worktree(
        home: &Path,
        repo: &Path,
        wt: &Path,
        id: &str,
    ) -> (String, PathBuf) {
        let (id, worktree) =
            due_run_with_winner_worktree(&home.join("runs"), wt, repo, id, RunStatus::Merged).await;
        crate::git::git(repo, &["update-ref", "refs/remotes/origin/main", "main"])
            .await
            .unwrap();
        let mut state = RunState::load_under(&id, home).unwrap();
        state.merge = Some(crate::run::MergeOutcome {
            mode: crate::config::MergeMode::Pr,
            ok: true,
            detail: "confirmed merged".into(),
            empty: false,
        });
        state.driver_exited = true;
        let aged = state.updated_at;
        state.save_under_at(home, aged).unwrap();
        (id, worktree)
    }

    #[tokio::test]
    async fn completed_task_retains_independent_historical_sources_without_a_merge_proof() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let queue = crate::queue::Queue::at(home.join("queue"));
        let mut task = crate::queue::Task::new(
            "completed".into(),
            "retain independent historical changes".into(),
            repo.clone(),
            crate::queue::Source::Human,
        );
        let mut sources = Vec::new();
        for (id, status) in [
            ("20260801-000000-old1", RunStatus::Superseded),
            ("20260801-000000-old2", RunStatus::Failed),
        ] {
            let (id, worktree) = due_run_with_winner_worktree(&runs, &wt, &repo, id, status).await;
            std::fs::write(worktree.join("independent.txt"), &id).unwrap();
            crate::git::git(&worktree, &["add", "independent.txt"])
                .await
                .unwrap();
            crate::git::git(
                &worktree,
                &["commit", "-m", "Independent historical change"],
            )
            .await
            .unwrap();
            let head = crate::git::rev_parse(&worktree, "HEAD").await.unwrap();
            let mut state = RunState::load_under(&id, home).unwrap();
            state.driver_exited = true;
            if status == RunStatus::Failed {
                state.tally = None;
            }
            state.save_under(home).unwrap();
            task.link_run(&id);
            sources.push((id, worktree, head));
        }
        // A newer empty attempt and task completion are no proof that either
        // independent historical implementation was incorporated.
        let mut latest = RunState::new(
            repo.clone(),
            "main".into(),
            crate::git::rev_parse(&repo, "main").await.unwrap(),
            task.instruction.clone(),
            crate::config::Config::default(),
        );
        latest.status = RunStatus::Ready;
        latest.driver_exited = true;
        latest.save_under(home).unwrap();
        task.start(latest.id.clone());
        task.succeed(crate::queue::CompletionContext::new(
            crate::queue::CompletionActor::DaemonSettle,
            None,
            home,
            &task,
        ));
        queue.put(&mut task).unwrap();

        let (folded, unreadable) = fold_due(
            &runs,
            home,
            &wt,
            &Disk::default(),
            ts("2026-09-05T00:00:00Z"),
        )
        .await
        .unwrap();
        assert_eq!((folded, unreadable), (0, 0));
        for (id, worktree, head) in sources {
            assert!(worktree.exists());
            assert_eq!(
                crate::git::rev_parse(&worktree, "HEAD").await.unwrap(),
                head
            );
            let mut state = RunState::load_under(&id, home).unwrap();
            assert!(!state.candidates[0].folded);
            let error = crate::graph::fold_run(&mut state, true, home)
                .await
                .unwrap_err();
            assert!(
                error
                    .to_string()
                    .contains(&format!("source of task {}", task.id))
            );
            assert_eq!(
                crate::git::rev_parse(&repo, &state.candidates[0].branch)
                    .await
                    .unwrap(),
                head
            );
            assert!(worktree.exists());
            assert!(runs.join(&id).join("run.json").exists());
        }
    }

    #[tokio::test]
    async fn recovery_retains_historical_sources_after_success_and_automatic_cleanup() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let mut task = crate::queue::Task::new(
            "recover".into(),
            "keep measured behavior".into(),
            repo.clone(),
            crate::queue::Source::Human,
        );
        let mut sources = Vec::new();
        for (id, status) in [
            ("20260801-000000-old1", RunStatus::Blocked),
            ("20260801-000000-old2", RunStatus::Stalled),
        ] {
            let (id, worktree) = due_run_with_winner_worktree(&runs, &wt, &repo, id, status).await;
            let mut state = RunState::load_under(&id, home).unwrap();
            state.driver_exited = true;
            state.save_under(home).unwrap();
            task.link_run(&id);
            sources.push((id, worktree));
        }
        crate::pr_recovery::retain_sources(&task, home).unwrap();
        let mut recovered = RunState::new(
            repo.clone(),
            "main".into(),
            "base".into(),
            task.instruction.clone(),
            crate::config::Config::default(),
        );
        recovered.config.graph.worktree_root = Some(wt.clone());
        recovered.status = RunStatus::Ready;
        recovered.driver_exited = true;
        recovered.save_under(home).unwrap();
        task.start(recovered.id.clone());
        task.succeed(crate::queue::CompletionContext::new(
            crate::queue::CompletionActor::DaemonSettle,
            None,
            home,
            &task,
        ));
        crate::daemon::supersede_prior_runs(&task, home);
        for (id, _) in &sources {
            assert_eq!(
                RunState::load_under(id, home).unwrap().status,
                RunStatus::Superseded
            );
        }
        let disk = Disk::default();
        let now = Timestamp::now()
            .checked_add(SignedDuration::from_secs(
                i64::try_from(disk.fold_grace_secs + 1).unwrap(),
            ))
            .unwrap();
        let (_, unreadable) = fold_due(&runs, home, &wt, &disk, now).await.unwrap();
        assert_eq!(unreadable, 0);
        for (id, worktree) in sources {
            assert!(worktree.exists());
            assert!(
                crate::git::branch_exists(&repo, &format!("magi/{id}/A"))
                    .await
                    .unwrap()
            );
            let mut historical = RunState::load_under(&id, home).unwrap();
            assert!(!historical.candidates[0].folded);
            let error = crate::graph::fold_run(&mut historical, true, home)
                .await
                .unwrap_err();
            assert!(
                error
                    .to_string()
                    .contains("explicitly retained recovery source")
            );
            assert!(!historical.candidates[0].folded);
            assert!(
                worktree.exists(),
                "every automatic fold entry preserves retained sources"
            );
        }
    }

    #[tokio::test]
    async fn fold_due_drops_a_superseded_runs_own_winner_worktree_but_keeps_a_readys() {
        let dir = tempfile::tempdir().unwrap();
        let runs = dir.path().join("runs");
        let wt = dir.path().join("wt");
        let repo = dir.path().join("repo");
        let home = dir.path().to_path_buf();
        let disk = Disk::default();
        let now = ts("2026-09-05T00:00:00Z");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);

        let (superseded_id, superseded_wt) = due_run_with_winner_worktree(
            &runs,
            &wt,
            &repo,
            "20260801-000000-supw",
            RunStatus::Superseded,
        )
        .await;
        // `Ready` is auto-folded exactly like `Superseded` (both terminal and
        // non-resumable), but never landed anywhere - its own winner is
        // deliberately kept, which is what makes it the right contrast here.
        // `Blocked`/`Stalled` are `resumable()` and so never even reach
        // `fold_run` in the first place; they would not exercise the
        // `drop_winner` choice this test is about.
        let (ready_id, ready_wt) = due_run_with_winner_worktree(
            &runs,
            &wt,
            &repo,
            "20260801-000000-rdyw",
            RunStatus::Ready,
        )
        .await;

        let (folded, unreadable) = fold_due(&runs, &home, &wt, &disk, now)
            .await
            .expect("fold_due");
        assert_eq!(folded, 2);
        assert_eq!(unreadable, 0);

        assert!(
            !superseded_wt.exists(),
            "a superseded run's own winner never lands anywhere else, so its worktree \
             must be dropped exactly like a merged run's"
        );
        assert!(
            ready_wt.exists(),
            "a still-ready run's winner may yet be merged by hand - folding must not \
             touch it"
        );

        // Both records survive the fold; only the worktrees differ.
        assert!(read_meta(&runs, &superseded_id).is_ok());
        assert!(read_meta(&runs, &ready_id).is_ok());
    }

    /// What a test does between `fold_one`'s first read and its locks.
    type Interleaving = Box<dyn FnOnce(&Path, &str)>;

    thread_local! {
        /// Run once by `fold_one` after its first read of a run and before the
        /// fold takes the run's locks: the window a handover falls into.
        pub(crate) static AFTER_FIRST_READ: std::cell::RefCell<Option<Interleaving>> =
            const { std::cell::RefCell::new(None) };
    }

    /// Rewrite one field of a saved `run.json` without going through `RunState`.
    fn edit_run(runs: &Path, id: &str, edit: impl FnOnce(&mut serde_json::Value)) {
        let path = runs.join(id).join("run.json");
        let mut value: serde_json::Value =
            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        edit(&mut value);
        std::fs::write(path, serde_json::to_vec_pretty(&value).unwrap()).unwrap();
    }

    const NO_BOUNDS: FoldBounds = FoldBounds {
        inspect: usize::MAX,
        fold: usize::MAX,
        budget: std::time::Duration::from_secs(3600),
    };

    /// A pass that is far enough in the future for every fixture run to be past
    /// its grace period even after `fold_run` re-saved it (which stamps real time).
    fn well_after_every_fold() -> Timestamp {
        Timestamp::now()
            .checked_add(SignedDuration::from_hours(48))
            .unwrap()
    }

    /// One pass from an explicit saved state, without touching the home's cycle file.
    async fn pass_from(
        runs: &Path,
        home: &Path,
        disk: &Disk,
        now: Timestamp,
        saved: Saved,
        bounds: FoldBounds,
    ) -> FoldTurn {
        fold_turn_from(runs, home, disk, now, saved, bounds).await.0
    }

    fn run_json(home: &Path, id: &str) -> RunState {
        RunState::load_under(id, home).unwrap()
    }

    #[tokio::test]
    async fn a_mixed_pass_counts_each_outcome_and_touches_only_what_fold_due_would() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let now = ts("2026-09-05T00:00:00Z");
        let disk = Disk {
            fold_grace_secs: 600,
            ..Disk::default()
        };
        let run = |n: u32| format!("20260801-000000-a{n:03}");
        let mut worktrees = Vec::new();
        for (n, status) in [
            (1, RunStatus::Superseded),  // folds
            (2, RunStatus::Ready),       // nothing to remove: its winner is kept
            (3, RunStatus::Blocked),     // resumable
            (4, RunStatus::Superseded),  // within grace
            (5, RunStatus::Superseded),  // live (daemon claim)
            (6, RunStatus::Superseded),  // unreadable
            (7, RunStatus::Superseded),  // startup incomplete
            (8, RunStatus::Superseded),  // candidate preservation pending
            (9, RunStatus::Superseded),  // explicitly retained
            (10, RunStatus::Superseded), // fold fails: its repository is gone
            (11, RunStatus::Merged),     // confirmed merge, no fetched base to prove it
            (12, RunStatus::Superseded), // live (a borrower holds its output lease)
        ] {
            let (_, worktree) =
                due_run_with_winner_worktree(&runs, &wt, &repo, &run(n), status).await;
            worktrees.push(worktree);
        }
        let mut merged = RunState::load_under(&run(11), home).unwrap();
        merged.merge = Some(crate::run::MergeOutcome {
            mode: crate::config::MergeMode::Pr,
            ok: true,
            detail: "confirmed merged".into(),
            empty: false,
        });
        let aged = merged.updated_at;
        merged.save_under_at(home, aged).unwrap();
        edit_run(&runs, &run(4), |v| {
            v["updated_at"] = "2026-09-04T23:59:00Z".into()
        });
        let mut status = crate::daemon::Status::new();
        status.current = vec![crate::daemon::Current {
            worker: None,
            task: "20260905-000000-task".to_owned(),
            run: run(5),
        }];
        status.updated_at = now;
        crate::daemon::write_status_to(&home.join("daemon.json"), &status).unwrap();
        std::fs::write(runs.join(run(6)).join("run.json"), "{ not json").unwrap();
        edit_run(&runs, &run(7), |v| {
            v["startup"] = serde_json::json!({
                "kind": "implementation", "branch": null, "stage": "prepare",
                "complete": false, "failure": null
            })
        });
        edit_run(&runs, &run(8), |v| {
            v["candidate_preservation"] = serde_json::json!({"A": "rescue pending"})
        });
        let mut task = crate::queue::Task::new(
            "keep".into(),
            "keep".into(),
            repo.clone(),
            crate::queue::Source::Human,
        );
        task.link_run(&run(9));
        crate::pr_recovery::retain_sources(&task, home).unwrap();
        edit_run(&runs, &run(10), |v| {
            v["repo"] = home.join("gone").to_string_lossy().into_owned().into()
        });
        let _borrower = crate::retention::OutputLease::take(&worktrees[11], false).unwrap();

        let turn = pass_from(&runs, home, &disk, now, Saved::Absent, NO_BOUNDS).await;
        assert_eq!(
            (
                turn.inspected,
                turn.invoked,
                turn.folded,
                turn.nothing_left,
                turn.already_folded,
                turn.resumable,
                turn.within_grace,
                turn.live,
                turn.unreadable,
                turn.proof_incomplete,
                turn.recovery_retained,
                turn.failed,
            ),
            // Run 2 (`Ready`, winner kept) has a bay on disk, so it is not
            // settled: a fold is invoked and finds nothing to remove.
            (12, 5, 1, 1, 0, 1, 1, 2, 1, 3, 1, 1),
            "{turn:?}"
        );
        assert_eq!(
            (turn.cursor.as_deref(), turn.stopped),
            (None, FoldStop::EndOfCycle)
        );
        assert!(!worktrees[0].exists(), "the due superseded run folded");
        for (n, worktree) in worktrees.iter().enumerate().skip(1) {
            assert!(
                worktree.exists(),
                "run {} must be left exactly as it was found",
                n + 1
            );
        }
        let note = |id: String| turn.notes.iter().find(|note| note.run == id).unwrap();
        assert_eq!(note(run(7)).outcome, "proof_incomplete");
        let unproven = note(run(11));
        assert_eq!(unproven.outcome, "proof_incomplete");
        assert!(unproven.text.contains("fetched base"), "{unproven:?}");
        assert_eq!(note(run(10)).outcome, "failed");
        assert!(
            turn.notes
                .iter()
                .all(|note| note.text.chars().count() <= NOTE_CHARS)
        );
    }

    /// Bound, cursor and restart: more eligible runs than one pass may fold.
    #[tokio::test]
    async fn bounded_passes_resume_from_the_saved_cursor_and_fold_each_run_once() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let now = well_after_every_fold();
        let disk = Disk {
            fold_grace_secs: 600,
            ..Disk::default()
        };
        let bounds = FoldBounds {
            fold: 2,
            ..NO_BOUNDS
        };
        let ids: Vec<String> = (1..=5)
            .map(|n| format!("20260801-000000-b{n:03}"))
            .collect();
        let mut worktrees = Vec::new();
        for id in &ids {
            let (_, worktree) =
                due_run_with_winner_worktree(&runs, &wt, &repo, id, RunStatus::Superseded).await;
            worktrees.push(worktree);
        }
        let gone = |worktrees: &[PathBuf]| worktrees.iter().filter(|w| !w.exists()).count();

        let first = fold_turn(&runs, home, &disk, now, bounds).await;
        assert_eq!(
            (first.folded, first.inspected, first.invoked),
            (2, 2, 2),
            "{first:?}"
        );
        assert_eq!(first.stopped, FoldStop::FoldLimit);
        assert_eq!(first.cursor.as_deref(), Some(ids[1].as_str()));
        assert_eq!(first.high_water.as_deref(), Some(ids[4].as_str()));
        assert_eq!(gone(&worktrees), 2);
        let saved: serde_json::Value =
            serde_json::from_slice(&std::fs::read(home.join(FOLD_TURN_CURSOR_FILE)).unwrap())
                .unwrap();
        assert_eq!(
            (saved["cursor"].as_str(), saved["high_water"].as_str()),
            (Some(ids[1].as_str()), Some(ids[4].as_str())),
            "the cycle is saved before anyone could restart"
        );

        // Nothing is held in memory between passes: this is the restart.
        let second = fold_turn(&runs, home, &disk, now, bounds).await;
        assert_eq!(
            (second.folded, second.nothing_left, second.already_folded),
            (2, 0, 0),
            "the first two are not revisited: {second:?}"
        );
        assert_eq!(second.cursor.as_deref(), Some(ids[3].as_str()));
        assert_eq!(gone(&worktrees), 4);

        let third = fold_turn(&runs, home, &disk, now, bounds).await;
        assert_eq!((third.folded, third.inspected), (1, 1), "{third:?}");
        assert_eq!(
            (third.cursor.as_deref(), third.stopped),
            (None, FoldStop::EndOfCycle)
        );
        assert_eq!(gone(&worktrees), 5);
        assert!(
            !home.join(FOLD_TURN_CURSOR_FILE).exists(),
            "a finished cycle leaves nothing saved; the next pass begins another"
        );
        assert_eq!(first.folded + second.folded + third.folded, ids.len());

        // A fold that removed something has not seen the bay empty yet: the next
        // cycle's fold finds nothing left and records it (`fold_settled_at`),
        // so each of these runs spends one more invocation, once.
        let fourth = fold_turn(&runs, home, &disk, now, NO_BOUNDS).await;
        assert_eq!(
            (fourth.nothing_left, fourth.already_folded, fourth.invoked),
            (5, 0, 5),
            "{fourth:?}"
        );
        // Then the whole history is judged in one pass and no fold is started:
        // the fact a fold recorded and a bay confirmed absent are the whole proof.
        let fifth = fold_turn(&runs, home, &disk, now, bounds).await;
        assert_eq!(
            (fifth.already_folded, fifth.inspected, fifth.invoked),
            (5, 5, 0),
            "{fifth:?}"
        );
        assert_eq!(fifth.stopped, FoldStop::EndOfCycle);
    }

    #[tokio::test]
    async fn a_zero_time_budget_still_judges_one_run_per_pass_and_reaches_the_tail() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let disk = Disk::default();
        let now = well_after_every_fold();
        let mut worktrees = Vec::new();
        for n in 1..=3 {
            let id = format!("20260801-000000-c{n:03}");
            let (_, worktree) =
                due_run_with_winner_worktree(&runs, &wt, &repo, &id, RunStatus::Superseded).await;
            worktrees.push(worktree);
        }
        let bounds = FoldBounds {
            budget: std::time::Duration::ZERO,
            ..NO_BOUNDS
        };
        for (pass, worktree) in worktrees.iter().enumerate() {
            let turn = fold_turn(&runs, home, &disk, now, bounds).await;
            assert_eq!(
                (turn.inspected, turn.folded),
                (1, 1),
                "pass {pass}: {turn:?}"
            );
            assert!(!worktree.exists());
            let expected = if pass == 2 {
                FoldStop::EndOfCycle
            } else {
                FoldStop::TimeBudget
            };
            assert_eq!(turn.stopped, expected);
        }
    }

    #[tokio::test]
    async fn judging_is_bounded_too() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let disk = Disk::default();
        let now = ts("2026-09-05T00:00:00Z");
        let ids: Vec<String> = (1..=5)
            .map(|n| format!("20260801-000000-d{n:03}"))
            .collect();
        for id in &ids {
            write_meta(&runs, id, "blocked", "2026-08-01T00:00:00Z");
        }
        let bounds = FoldBounds {
            inspect: 2,
            ..NO_BOUNDS
        };
        let mut seen = Vec::new();
        for _ in 0..3 {
            let turn = fold_turn(&runs, home, &disk, now, bounds).await;
            assert_eq!(turn.resumable, turn.inspected);
            seen.push((turn.inspected, turn.cursor, turn.stopped));
        }
        assert_eq!(
            seen,
            vec![
                (2, Some(ids[1].clone()), FoldStop::InspectLimit),
                (2, Some(ids[3].clone()), FoldStop::InspectLimit),
                (1, None, FoldStop::EndOfCycle),
            ]
        );
    }

    /// A saved cycle that cannot be trusted starts a clean one, and says so.
    #[tokio::test]
    async fn a_saved_cycle_that_cannot_be_trusted_starts_over_and_says_why() {
        let ids: Vec<String> = (1..=5)
            .map(|n| format!("20260801-000000-r{n:03}"))
            .collect();
        let saved = |cursor: &str, high_water: &str| {
            serde_json::json!({"cursor": cursor, "high_water": high_water}).to_string()
        };
        let cases = [
            ("unreadable", Some("{ not json".to_owned())),
            (
                "unreadable",
                Some(ids[2].clone()), // the plain-id format of an earlier build
            ),
            (
                "no longer exists",
                Some(saved("20260801-000000-q999", &ids[4])),
            ),
            ("below the cursor", Some(saved(&ids[3], &ids[1]))),
            ("nothing left", Some(saved(&ids[4], &ids[4]))),
            // Ids that cannot be run ids, and a mark newer than every run:
            // with the latter, arrivals would never end the cycle.
            ("not a run id", Some(saved("nonsense", &ids[4]))),
            ("not a run id", Some(saved(&ids[1], "zzzz"))),
            (
                "newer than every run",
                Some(saved(&ids[1], "20260801-000000-zzzz")),
            ),
            ("unreadable", None), // a directory where the file belongs
        ];
        for (reason, body) in cases {
            let dir = tempfile::tempdir().unwrap();
            let home = dir.path();
            let runs = home.join("runs");
            for id in &ids {
                write_meta(&runs, id, "blocked", "2026-08-01T00:00:00Z");
            }
            match body {
                Some(body) => std::fs::write(home.join(FOLD_TURN_CURSOR_FILE), body).unwrap(),
                None => std::fs::create_dir(home.join(FOLD_TURN_CURSOR_FILE)).unwrap(),
            }
            let bounds = FoldBounds {
                inspect: 2,
                ..NO_BOUNDS
            };
            let turn = fold_turn(
                &runs,
                home,
                &Disk::default(),
                ts("2026-09-05T00:00:00Z"),
                bounds,
            )
            .await;
            assert!(
                turn.cycle_restart
                    .as_deref()
                    .is_some_and(|why| why.contains(reason)),
                "{reason}: {turn:?}"
            );
            assert_eq!(turn.inspected, 2, "{reason}: restarted from the oldest");
            assert_eq!(turn.cursor.as_deref(), Some(ids[1].as_str()), "{reason}");
            assert_eq!(
                turn.high_water.as_deref(),
                Some(ids[4].as_str()),
                "{reason}: a fresh high-water mark"
            );
        }
    }

    #[tokio::test]
    async fn an_unsaved_cursor_is_reported_not_hidden() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        for n in 1..=2 {
            write_meta(
                &runs,
                &format!("20260801-000000-e{n:03}"),
                "blocked",
                "2026-08-01T00:00:00Z",
            );
        }
        // A directory where the cursor file belongs cannot be replaced.
        std::fs::create_dir(home.join(FOLD_TURN_CURSOR_FILE)).unwrap();
        let bounds = FoldBounds {
            inspect: 1,
            ..NO_BOUNDS
        };
        let turn = fold_turn(
            &runs,
            home,
            &Disk::default(),
            ts("2026-09-05T00:00:00Z"),
            bounds,
        )
        .await;
        assert!(turn.cursor_error.is_some(), "{turn:?}");
    }

    /// Runs created while a cycle is under way wait for the next one, so a
    /// history that keeps growing cannot keep an earlier run from being
    /// revisited after it leaves its grace period. With a cursor that only
    /// wrapped at the current end of the history, two arrivals per pass against
    /// two judgements per pass never reached the end and the run was never folded.
    #[tokio::test]
    async fn continuous_arrivals_cannot_postpone_a_run_that_leaves_its_grace() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let disk = Disk {
            fold_grace_secs: 600,
            ..Disk::default()
        };
        let bounds = FoldBounds {
            inspect: 2,
            ..NO_BOUNDS
        };
        // The run's record says 2026-08-01T00:00:00Z: inside its grace at the
        // first pass, long past it afterwards.
        let (_, worktree) = due_run_with_winner_worktree(
            &runs,
            &wt,
            &repo,
            "20260801-000000-g001",
            RunStatus::Superseded,
        )
        .await;
        for n in 2..=4 {
            write_meta(
                &runs,
                &format!("20260801-000000-g{n:03}"),
                "blocked",
                "2026-08-01T00:00:00Z",
            );
        }
        // Run ids have a four-character tag, which the turn's inventory requires.
        let arrive = |pass: u32| {
            for k in 0..2 {
                write_meta(
                    &runs,
                    &format!("20260802-000000-n{pass:02}{k}"),
                    "blocked",
                    "2026-08-02T00:00:00Z",
                );
            }
        };
        let early = ts("2026-08-01T00:05:00Z");
        let late = ts("2026-09-05T00:00:00Z");

        // N = 4 records at the start: ceil(4 / 2) = 2 passes for the cycle,
        // and the run is folded by the first pass of the next one.
        let first = fold_turn(&runs, home, &disk, early, bounds).await;
        assert_eq!(first.within_grace, 1, "{first:?}");
        assert_eq!(first.stopped, FoldStop::InspectLimit);
        arrive(1);
        let second = fold_turn(&runs, home, &disk, late, bounds).await;
        assert_eq!(second.high_water, first.high_water, "same cycle");
        assert_eq!(second.stopped, FoldStop::EndOfCycle, "{second:?}");
        assert!(worktree.exists(), "judged inside its grace in this cycle");
        arrive(2);
        let third = fold_turn(&runs, home, &disk, late, bounds).await;
        assert_ne!(third.high_water, first.high_water, "a new cycle");
        assert_eq!(third.folded, 1, "{third:?}");
        assert!(!worktree.exists());
    }

    /// A contended fold is still a fold invocation: it takes the run's locks and
    /// reads its record, so the bound counts it. Charging only the folds that
    /// removed something let 64 contended runs start 64 folds.
    #[tokio::test]
    async fn contended_folds_are_charged_to_the_fold_budget() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let now = well_after_every_fold();
        let mut borrowers = Vec::new();
        let mut worktrees = Vec::new();
        for n in 1..=6 {
            let id = format!("20260801-000000-h{n:03}");
            let (_, worktree) =
                due_run_with_winner_worktree(&runs, &wt, &repo, &id, RunStatus::Superseded).await;
            borrowers.push(crate::retention::OutputLease::take(&worktree, false).unwrap());
            worktrees.push(worktree);
        }
        let bounds = FoldBounds {
            fold: 2,
            ..NO_BOUNDS
        };
        let turn = pass_from(&runs, home, &Disk::default(), now, Saved::Absent, bounds).await;
        assert_eq!(
            (turn.invoked, turn.live, turn.inspected, turn.stopped),
            (2, 2, 2, FoldStop::FoldLimit),
            "{turn:?}"
        );
        assert!(worktrees.iter().all(|w| w.exists()));
        drop(borrowers);
    }

    /// The fold acts on the record as it is once the run's locks are held. A
    /// handover (`handover::release`) that lands between the first read and the
    /// locks records `released_to` / `released_branches` and removes the old
    /// worktree, keeping the branch; acting on the earlier read deleted that
    /// branch and saved the earlier record over the handover.
    #[tokio::test]
    async fn a_handover_between_the_read_and_the_locks_is_neither_undone_nor_overwritten() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let id = "20260801-000000-k001";
        let (_, worktree) =
            due_run_with_winner_worktree(&runs, &wt, &repo, id, RunStatus::Superseded).await;
        let branch = format!("magi/{id}/A");
        AFTER_FIRST_READ.with(|hook| {
            let (repo, worktree, branch) = (repo.clone(), worktree.clone(), branch.clone());
            *hook.borrow_mut() = Some(Box::new(move |home: &Path, id: &str| {
                use crate::proc::Quiet as _;
                let mut fresh = RunState::load_under(id, home).unwrap();
                fresh.candidates[0].folded = true;
                fresh.released_to = Some("20260901-000000-succ".to_owned());
                fresh.released_branches.push(branch);
                let aged = fresh.updated_at;
                fresh.save_under_at(home, aged).unwrap();
                let removed = std::process::Command::new("git")
                    .args(["worktree", "remove"])
                    .arg(&worktree)
                    .current_dir(&repo)
                    .quiet()
                    .output()
                    .unwrap();
                assert!(removed.status.success());
            }));
        });

        let turn = pass_from(
            &runs,
            home,
            &Disk::default(),
            well_after_every_fold(),
            Saved::Absent,
            NO_BOUNDS,
        )
        .await;
        assert_eq!(
            (turn.invoked, turn.folded, turn.nothing_left),
            (1, 0, 1),
            "the run was handed over, not folded: {turn:?}"
        );
        assert!(
            crate::git::branch_exists(&repo, &branch).await.unwrap(),
            "the handed-over branch survives"
        );
        let saved = run_json(home, id);
        assert_eq!(saved.released_to.as_deref(), Some("20260901-000000-succ"));
        assert_eq!(saved.released_branches, [branch]);
        assert!(saved.candidates[0].folded);
    }

    /// Eligibility is judged again on the fresh record: a run that became
    /// resumable between the read and the locks is left exactly as it is.
    #[tokio::test]
    async fn a_run_that_became_resumable_after_the_read_is_left_alone() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let id = "20260801-000000-k002";
        let (_, worktree) =
            due_run_with_winner_worktree(&runs, &wt, &repo, id, RunStatus::Superseded).await;
        AFTER_FIRST_READ.with(|hook| {
            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
                let mut fresh = RunState::load_under(id, home).unwrap();
                fresh.status = RunStatus::Blocked;
                let aged = fresh.updated_at;
                fresh.save_under_at(home, aged).unwrap();
            }));
        });

        let turn = pass_from(
            &runs,
            home,
            &Disk::default(),
            well_after_every_fold(),
            Saved::Absent,
            NO_BOUNDS,
        )
        .await;
        assert_eq!(
            (turn.invoked, turn.resumable, turn.folded),
            (1, 1, 0),
            "{turn:?}"
        );
        assert!(worktree.exists());
        assert_eq!(run_json(home, id).status, RunStatus::Blocked);
    }

    /// A confirmed merge is folded on the turn, and its evidence stays.
    #[tokio::test]
    async fn a_confirmed_merged_run_is_folded_and_keeps_its_evidence() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let (id, worktree) =
            merged_run_with_worktree(home, &repo, &wt, "20260801-000000-m001").await;
        let turn = pass_from(
            &home.join("runs"),
            home,
            &Disk::default(),
            well_after_every_fold(),
            Saved::Absent,
            NO_BOUNDS,
        )
        .await;
        assert_eq!(
            (turn.folded, turn.proof_incomplete, turn.failed),
            (1, 0, 0),
            "{turn:?}"
        );
        assert!(!worktree.exists());
        assert!(
            !crate::git::branch_exists(&repo, &format!("magi/{id}/A"))
                .await
                .unwrap()
        );
        let evidence = home.join("runs").join(&id).join("artifacts/fold-evidence");
        assert!(evidence.join("manifest.json").is_file());
        assert!(home.join("runs").join(&id).join("run.json").is_file());
    }

    /// A directory in `runs/` that is not a run but holds a `run.json` must not
    /// become the cycle's high-water mark: the turn refuses to continue from an
    /// id that is not a run id, restarts from the oldest run on every pass and
    /// never reaches the tail past the inspection bound.
    #[tokio::test]
    async fn a_stray_directory_with_a_record_does_not_starve_the_runs_after_the_bound() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let mut worktrees = Vec::new();
        for n in 1..=5 {
            let id = format!("20260801-000000-s{n:03}");
            let (_, worktree) =
                due_run_with_winner_worktree(&runs, &wt, &repo, &id, RunStatus::Superseded).await;
            worktrees.push(worktree);
        }
        // Sorts after every run id.
        std::fs::create_dir_all(runs.join("backup")).unwrap();
        std::fs::copy(
            runs.join("20260801-000000-s001").join("run.json"),
            runs.join("backup").join("run.json"),
        )
        .unwrap();
        let bounds = FoldBounds {
            inspect: 2,
            ..NO_BOUNDS
        };
        let now = well_after_every_fold();
        let mut inspected = Vec::new();
        for _ in 0..3 {
            let turn = fold_turn(&runs, home, &Disk::default(), now, bounds).await;
            assert_eq!(turn.cycle_restart, None, "{turn:?}");
            assert_eq!(
                turn.records, 5,
                "the stray directory is not a record: {turn:?}"
            );
            inspected.push(turn.inspected);
        }
        assert_eq!(inspected, [2, 2, 1]);
        assert!(
            worktrees.iter().all(|w| !w.exists()),
            "the tail was reached"
        );
        assert!(runs.join("backup").join("run.json").is_file());
    }

    fn start_of(home: &Path, id: &str, complete: bool, failure: Option<&str>) {
        let mut successor = RunState::load_under(id, home).unwrap();
        successor.startup = Some(crate::run::Startup {
            kind: "review".to_owned(),
            branch: None,
            stage: "open-review".to_owned(),
            complete,
            failure: failure.map(str::to_owned),
        });
        let aged = successor.updated_at;
        successor.save_under_at(home, aged).unwrap();
    }

    fn hand_over_to(home: &Path, id: &str, successor: &str) {
        let mut predecessor = RunState::load_under(id, home).unwrap();
        predecessor.released_to = Some(successor.to_owned());
        let aged = predecessor.updated_at;
        predecessor.save_under_at(home, aged).unwrap();
    }

    /// `handover::Released::restore` needs the predecessor's owner lock, and an
    /// automatic fold that holds it for a moment makes the rollback abandon. A
    /// predecessor whose successor is still starting (or cannot be read) is
    /// left alone; one whose successor has settled - startup failed, or
    /// completed and nothing drives it - is folded as before.
    #[tokio::test]
    async fn a_handover_in_flight_protects_its_predecessor_until_the_successor_settles() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let mut folded = Vec::new();
        for (n, case) in ["starting", "failed", "complete", "unreadable", "gone"]
            .into_iter()
            .enumerate()
        {
            let id = format!("20260801-000000-p{n:03}");
            let next = format!("20260901-000000-n{n:03}");
            let (_, worktree) =
                due_run_with_winner_worktree(&runs, &wt, &repo, &id, RunStatus::Superseded).await;
            if case != "gone" {
                due_run(&runs, &wt, &next, SCHEMA);
            }
            match case {
                "starting" => start_of(home, &next, false, None),
                "failed" => start_of(home, &next, false, Some("setup failed")),
                "complete" => start_of(home, &next, true, None),
                "unreadable" => {
                    std::fs::write(runs.join(&next).join("run.json"), "not json").unwrap()
                }
                _ => {}
            }
            hand_over_to(home, &id, &next);
            folded.push((case, id, worktree));
        }
        let turn = pass_from(
            &runs,
            home,
            &Disk::default(),
            well_after_every_fold(),
            Saved::Absent,
            NO_BOUNDS,
        )
        .await;
        for (case, id, worktree) in &folded {
            let protected = matches!(*case, "starting" | "unreadable");
            assert_eq!(
                worktree.exists(),
                protected,
                "{case}: protected={protected} {turn:?}"
            );
            assert_eq!(
                run_json(home, id)
                    .released_to
                    .as_deref()
                    .map(|s| s.starts_with("20260901")),
                Some(true),
                "{case}: the record still says where the run went"
            );
        }
        assert!(turn.live >= 2, "{turn:?}");
    }

    /// The janitor's own fold after it recorded an external merge is an
    /// automatic caller: it reads the record under the run's locks tolerantly
    /// (the explicit loader refuses a schema it cannot migrate, which left the
    /// run unfolded until a later pass and another grace period), and the
    /// conditions that made it a confirmed merge are re-checked on that record.
    #[tokio::test]
    async fn a_recorded_external_merge_is_folded_on_the_locked_record_whatever_its_schema() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let (id, worktree) =
            merged_run_with_worktree(home, &repo, &wt, "20260801-000000-x001").await;
        let record = home.join("runs").join(&id).join("run.json");
        let mut value: serde_json::Value =
            serde_json::from_slice(&std::fs::read(&record).unwrap()).unwrap();
        value["schema"] = serde_json::json!(3);
        std::fs::write(&record, serde_json::to_vec_pretty(&value).unwrap()).unwrap();
        assert!(
            RunState::load_under(&id, home).is_err(),
            "the migrating loader refuses this record"
        );
        let mut state = read_state(&home.join("runs"), &id).unwrap();
        let removed = fold_recorded_merge(&mut state, home, Timestamp::now())
            .await
            .unwrap();
        assert!(!removed.is_empty() && !worktree.exists(), "{removed:?}");

        // Not a confirmed merge any more: refused, nothing removed.
        let (other, kept) = due_run_with_winner_worktree(
            &home.join("runs"),
            &wt,
            &repo,
            "20260801-000000-x002",
            RunStatus::Superseded,
        )
        .await;
        let mut state = read_state(&home.join("runs"), &other).unwrap();
        let error = fold_recorded_merge(&mut state, home, Timestamp::now())
            .await
            .unwrap_err();
        assert!(
            matches!(
                error.downcast_ref::<crate::graph::FoldRefusal>(),
                Some(crate::graph::FoldRefusal::ProofIncomplete(_))
            ),
            "{error:#}"
        );
        assert!(kept.exists());
    }

    /// The scenario of issue 1275: a queue that always has something runnable
    /// and a busy worker. Housekeeping is never admitted there, so before this
    /// turn nothing called `fold_due`: the assertion that the old run's
    /// worktree is gone after one fold service pass is what failed on
    /// `origin/main`.
    #[tokio::test]
    async fn the_fold_service_folds_an_old_run_beside_runnable_and_running_work() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let queue = crate::queue::Queue::at(home.join("queue"));
        let mut running = crate::queue::Task::new(
            "busy".into(),
            "busy".into(),
            repo.clone(),
            crate::queue::Source::Human,
        );
        running.status = crate::queue::TaskStatus::Running;
        queue.put(&mut running).unwrap();
        let mut waiting = crate::queue::Task::new(
            "next".into(),
            "next".into(),
            repo.clone(),
            crate::queue::Source::Human,
        );
        queue.put(&mut waiting).unwrap();
        let (id, worktree) = due_run_with_winner_worktree(
            &runs,
            &wt,
            &repo,
            "20260801-000000-f001",
            RunStatus::Superseded,
        )
        .await;
        let config = home.join("magi.toml");
        let write_config = |auto_fold: bool| {
            std::fs::write(
                &config,
                format!(
                    "[disk]\nmin_free_bytes = 0\ncache_limit_bytes = 0\nauto_fold = {auto_fold}\n"
                ),
            )
            .unwrap();
        };
        let payload = serde_json::json!({
            "opts": crate::daemon::Opts {
                repo: home.join("not-a-checkout"),
                config: Some(config.clone()),
                ..crate::daemon::Opts::default()
            },
            "queue": queue.root(),
            "worktrees_root": wt,
            "operation": "fold",
        });
        let receipt = || -> serde_json::Value {
            serde_json::from_slice(
                &std::fs::read(home.join("source-eviction-fold-worker.json")).unwrap(),
            )
            .unwrap()
        };

        write_config(false);
        crate::daemon::run_service_worker(home, payload.clone())
            .await
            .unwrap();
        assert!(worktree.exists(), "auto_fold = false folds nothing");
        assert_eq!(receipt()["outcome"], "skipped");
        assert_eq!(receipt()["detail"], "auto_fold disabled");

        write_config(true);
        crate::daemon::run_service_worker(home, payload)
            .await
            .unwrap();
        assert!(!worktree.exists(), "one pass folded the old finished run");
        assert!(runs.join(&id).join("run.json").exists());
        let receipt = receipt();
        assert_eq!(receipt["outcome"], "completed");
        assert_eq!(receipt["operation"], "fold");
        let fold = &receipt["fold"];
        assert_eq!(fold["records"], 1);
        assert_eq!(fold["inspected"], 1);
        assert_eq!(fold["invoked"], 1);
        assert_eq!(fold["folded"], 1);
        for zero in [
            "nothing_left",
            "already_folded",
            "live",
            "resumable",
            "within_grace",
            "recovery_retained",
            "proof_incomplete",
            "unreadable",
            "record_gone",
            "failed",
        ] {
            assert_eq!(fold[zero], 0, "{zero}");
        }
        assert_eq!(fold["stopped"], "end_of_cycle");
        assert_eq!(fold["high_water"], id);
        assert!(fold["cursor"].is_null());
        assert!(fold["cursor_error"].is_null());
        assert!(fold["cycle_restart"].is_null());
        assert!(fold["elapsed_ms"].is_u64());
        assert_eq!(fold["notes"], serde_json::json!([]));
    }

    /// One pass, no bounds, from the home's own cycle file's absence.
    async fn one_pass(home: &Path, now: Timestamp) -> FoldTurn {
        pass_from(
            &home.join("runs"),
            home,
            &Disk::default(),
            now,
            Saved::Absent,
            NO_BOUNDS,
        )
        .await
    }

    /// A due `Superseded` run with a winner worktree under `home`, plus its repo.
    async fn due_superseded(home: &Path, id: &str) -> (PathBuf, PathBuf) {
        let repo = home.join("repo");
        if !repo.exists() {
            std::fs::create_dir_all(&repo).unwrap();
            init_repo(&repo);
        }
        let (_, worktree) = due_run_with_winner_worktree(
            &home.join("runs"),
            &home.join("wt"),
            &repo,
            id,
            RunStatus::Superseded,
        )
        .await;
        (repo, worktree)
    }

    /// What a fold itself found is what lets the turn skip a run: nothing left
    /// and no bay, recorded under its locks, and the bay confirmed absent now.
    #[tokio::test]
    async fn a_fold_that_finds_nothing_marks_the_run_and_the_turn_then_skips_it() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let id = "20260801-000000-z001";
        let (_, worktree) = due_superseded(home, id).await;
        let now = well_after_every_fold();

        let first = one_pass(home, now).await;
        assert_eq!((first.folded, first.invoked), (1, 1), "{first:?}");
        assert!(!worktree.exists());
        assert!(
            run_json(home, id).fold_settled_at.is_none(),
            "a fold that removed something has not yet seen the bay empty"
        );

        let second = one_pass(home, now).await;
        assert_eq!((second.nothing_left, second.invoked), (1, 1), "{second:?}");
        assert!(run_json(home, id).fold_settled_at.is_some());

        let record = home.join("runs").join(id).join("run.json");
        let before = std::fs::read(&record).unwrap();
        let third = one_pass(home, now).await;
        assert_eq!(
            (third.already_folded, third.invoked, third.nothing_left),
            (1, 0, 0),
            "{third:?}"
        );
        assert_eq!(std::fs::read(&record).unwrap(), before, "no fold, no save");
    }

    /// An existing bay - even an empty one - is not "gone": the fold is invoked,
    /// removes it and records what it saw.
    #[tokio::test]
    async fn an_empty_bay_is_work_and_a_marked_run_with_work_is_folded() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let id = "20260801-000000-z002";
        let (_, worktree) = due_superseded(home, id).await;
        let now = well_after_every_fold();
        one_pass(home, now).await;
        one_pass(home, now).await;
        let bay = run_json(home, id).worktree_root();
        assert!(run_json(home, id).fold_settled_at.is_some());
        assert!(!bay.exists());

        std::fs::create_dir_all(&bay).unwrap();
        let pass = one_pass(home, now).await;
        assert_eq!((pass.invoked, pass.already_folded), (1, 0), "{pass:?}");
        assert!(!bay.exists(), "the fold removed the empty bay");
        assert!(run_json(home, id).fold_settled_at.is_some());

        // Work behind a mark: a bay that holds a worktree again. The fold that
        // removes it clears the mark in the same save.
        std::fs::create_dir_all(worktree.parent().unwrap()).unwrap();
        crate::git::worktree_add_branch(&home.join("repo"), &worktree, "magi/z002-again", "main")
            .await
            .unwrap();
        let pass = one_pass(home, now).await;
        assert_eq!((pass.invoked, pass.already_folded), (1, 0), "{pass:?}");
        assert!(!worktree.exists());
        assert!(
            run_json(home, id).fold_settled_at.is_none(),
            "a fold that found work clears the mark"
        );
    }

    #[test]
    fn settled_needs_the_mark_and_a_bay_confirmed_absent() {
        let mut state = RunState::new(
            PathBuf::from("/repo"),
            "main".to_owned(),
            "abc".to_owned(),
            "fixture".to_owned(),
            crate::config::Config::default(),
        );
        assert!(!settled(&state, true, Ok(false)), "no mark: unknown");
        state.fold_settled_at = Some(Timestamp::now());
        assert!(settled(&state, true, Ok(false)));
        assert!(!settled(&state, true, Ok(true)), "a bay on disk is work");
        let failed = Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied));
        assert!(!settled(&state, true, failed), "an unanswered check is not");
        state.enabled_worktree_config = true;
        assert!(
            !settled(&state, true, Ok(false)),
            "a pending worktree-config release is work"
        );
        assert!(settled(&state, false, Ok(false)));
    }

    /// A run deleted between the first read and the fold's locks is refused and
    /// nothing of it is brought back: no record, no directory, no lock files.
    #[tokio::test]
    async fn a_run_deleted_after_the_first_read_is_refused_and_not_recreated() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let id = "20260801-000000-z003";
        let (repo, worktree) = due_superseded(home, id).await;
        AFTER_FIRST_READ.with(|hook| {
            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
                std::fs::remove_dir_all(home.join("runs").join(id)).unwrap();
            }));
        });

        let turn = one_pass(home, well_after_every_fold()).await;
        assert_eq!(
            (turn.invoked, turn.record_gone, turn.folded, turn.failed),
            (1, 1, 0, 0),
            "{turn:?}"
        );
        assert!(
            !home.join("runs").join(id).exists(),
            "the fold recreated what was deleted"
        );
        assert!(worktree.exists(), "nothing of a deleted run is folded");
        assert!(
            crate::git::branch_exists(&repo, &format!("magi/{id}/A"))
                .await
                .unwrap()
        );
    }

    /// A record readable at the first look and not under the locks is
    /// `unreadable` - the idle pass counts it like any unreadable record - and
    /// is left exactly as found.
    #[tokio::test]
    async fn a_record_that_became_unreadable_under_the_locks_is_unreadable() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let id = "20260801-000000-z004";
        let (_, worktree) = due_superseded(home, id).await;
        AFTER_FIRST_READ.with(|hook| {
            *hook.borrow_mut() = Some(Box::new(|home: &Path, id: &str| {
                std::fs::write(home.join("runs").join(id).join("run.json"), "{ not json").unwrap();
            }));
        });
        let (folded, unreadable) = fold_due(
            &home.join("runs"),
            home,
            &home.join("wt"),
            &Disk::default(),
            well_after_every_fold(),
        )
        .await
        .unwrap();
        assert_eq!((folded, unreadable), (0, 1));
        assert!(worktree.exists());
        assert_eq!(
            std::fs::read(home.join("runs").join(id).join("run.json")).unwrap(),
            b"{ not json"
        );
    }

    /// Explicit callers keep the migrating loader: a schema-14 record whose
    /// unfolded candidate is empty and unverified gets its legacy preservation
    /// marker from the migration, and the explicit fold refuses on that fresh
    /// record. The tolerant read housekeeping uses never derives the marker.
    #[tokio::test]
    async fn an_explicit_fold_applies_the_migration_its_preservation_check_rests_on() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let id = "20260801-000000-z005";
        let (_, worktree) = due_superseded(home, id).await;
        edit_run(&home.join("runs"), id, |v| {
            v["schema"] = 14.into();
            v["candidates"][0]["empty"] = true.into();
        });
        let record = home.join("runs").join(id).join("run.json");
        let before = std::fs::read(&record).unwrap();

        let mut first_look = read_state(&home.join("runs"), id).unwrap();
        assert!(first_look.candidate_preservation.is_empty());
        let error = crate::graph::fold_run(&mut first_look, true, home)
            .await
            .unwrap_err();
        assert!(
            matches!(
                error.downcast_ref::<crate::graph::FoldRefusal>(),
                Some(crate::graph::FoldRefusal::ProofIncomplete(_))
            ),
            "{error:#}"
        );
        assert!(worktree.exists());
        assert_eq!(std::fs::read(&record).unwrap(), before, "nothing was saved");

        let turn = one_pass(home, well_after_every_fold()).await;
        assert_eq!(
            turn.folded, 1,
            "housekeeping reads the record as saved: {turn:?}"
        );
        assert!(!worktree.exists());
    }

    /// Only contention is "somebody holds it"; any other failure of a lock call
    /// is a real failure.
    #[test]
    fn only_lock_contention_means_a_live_owner() {
        use crate::graph::held_by_live_owner;
        let io = |kind| anyhow::Error::from(std::io::Error::from(kind));
        assert!(held_by_live_owner(&io(std::io::ErrorKind::WouldBlock)));
        assert!(held_by_live_owner(
            &io(std::io::ErrorKind::WouldBlock).context("run execution lease unavailable")
        ));
        assert!(!held_by_live_owner(&io(std::io::ErrorKind::Interrupted)));
        assert!(!held_by_live_owner(
            &anyhow::Error::msg("ENOLCK").context("output lease: lock")
        ));
        assert!(!held_by_live_owner(&io(
            std::io::ErrorKind::PermissionDenied
        )));
        let held = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(held.path().join("wt")).unwrap();
        let lock = held.path().join("magi-output.lock");
        let _first = crate::retention::OutputLease::lock(&lock, true).unwrap();
        let error = crate::retention::OutputLease::lock(&lock, true)
            .err()
            .unwrap();
        assert!(held_by_live_owner(&error), "{error:#}");
    }

    /// Deleting a run record takes the fold's locks: a held lock is a refusal,
    /// never a record vanishing under a fold.
    #[tokio::test]
    async fn deleting_a_run_is_refused_while_a_fold_holds_it_and_leaves_no_trace_when_gone() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let now = Timestamp::now();
        let refused = |result: Result<()>| -> String {
            let error = result.unwrap_err();
            error
                .downcast_ref::<DeleteRefused>()
                .unwrap_or_else(|| panic!("not a refusal: {error:#}"))
                .0
                .clone()
        };
        let id = "20260801-000000-z006";
        let mut state = RunState::new(
            PathBuf::from("/repo"),
            "main".to_owned(),
            "abc".to_owned(),
            "fixture".to_owned(),
            crate::config::Config::default(),
        );
        state.id = id.to_owned();
        state.status = RunStatus::Failed;
        state.save_under(home).unwrap();
        let run_dir = home.join("runs").join(id);

        {
            let _owner = crate::pr_head::owner_lock(home, id).unwrap();
            assert!(refused(delete_run(home, id, now)).contains("try again later"));
        }
        {
            let _lease = crate::driver::maintenance(home, id).unwrap();
            assert!(refused(delete_run(home, id, now)).contains("try again later"));
        }
        assert!(run_dir.join("run.json").is_file());

        delete_run(home, id, now).unwrap();
        assert!(!run_dir.exists());
        assert_eq!(
            std::fs::read_dir(home.join("deleted-runs"))
                .map(|entries| entries.count())
                .unwrap_or(0),
            0,
            "the run's lock files and record go together, tombstone included"
        );
        assert!(refused(delete_run(home, id, now)).contains("record gone"));
        assert!(
            !run_dir.exists(),
            "refusing must not recreate the directory"
        );

        // The guard on unfolded candidates is judged on the record read under the locks.
        let unfolded = "20260801-000000-z007";
        let (_, worktree) = due_superseded(home, unfolded).await;
        assert!(refused(delete_run(home, unfolded, now)).contains("magi fold"));
        assert!(worktree.exists());
        assert!(home.join("runs").join(unfolded).join("run.json").is_file());
    }

    /// The wholesale removal of an unreadable run takes the same two locks.
    #[tokio::test]
    async fn an_unreadable_run_is_not_removed_while_a_fold_holds_it() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let id = "20260801-000000-z008";
        write_meta(&runs, id, "failed", "2026-08-01T00:00:00Z");
        {
            let _lease = crate::driver::maintenance(home, id).unwrap();
            let error = fold_unreadable(&runs, &wt, id).await.unwrap_err();
            assert!(error.is::<DeleteRefused>(), "{error:#}");
            assert!(runs.join(id).join("run.json").is_file());
        }
        let removed = fold_unreadable(&runs, &wt, id).await.unwrap();
        assert_eq!(removed, [format!("runs/{id}")]);
        assert!(!runs.join(id).exists());
    }

    /// What a deletion killed between the rename and the removal leaves behind.
    fn leftover_tombstone(home: &Path, name: &str) -> PathBuf {
        let leftover = home.join("deleted-runs").join(name);
        std::fs::create_dir_all(leftover.join("artifacts")).unwrap();
        std::fs::write(leftover.join("run.json"), "{}").unwrap();
        std::fs::write(leftover.join("artifacts/review.json"), "findings").unwrap();
        leftover
    }

    /// A tombstone is removed by the next run deletion, by the wholesale removal
    /// of an unreadable run (which now leaves through the tombstone too) and by
    /// idle housekeeping: it was authorised for deletion when it was moved and
    /// nothing else reads the directory.
    #[tokio::test]
    async fn a_leftover_tombstone_is_removed_by_the_next_deletion_and_by_housekeeping() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let now = Timestamp::now();

        let first = leftover_tombstone(home, "20260701-000000-dead-1");
        let id = "20260801-000000-z009";
        let mut state = RunState::new(
            PathBuf::from("/repo"),
            "main".to_owned(),
            "abc".to_owned(),
            "fixture".to_owned(),
            crate::config::Config::default(),
        );
        state.id = id.to_owned();
        state.status = RunStatus::Failed;
        state.save_under(home).unwrap();
        delete_run(home, id, now).unwrap();
        assert!(!home.join("runs").join(id).exists());
        assert!(!first.exists(), "the next deletion removed the leftover");

        let second = leftover_tombstone(home, "20260701-000000-dead-2");
        let mut cfg = crate::config::Config::default();
        cfg.disk.auto_fold = false;
        cfg.disk.cache_limit_bytes = 0;
        housekeep(&cfg, home, &home.join("wt"), &home.join("repo"), now).await;
        assert!(!second.exists(), "idle housekeeping removed the leftover");
        assert_eq!(sweep_graveyard(home), 0, "nothing is left to remove");
    }

    /// A record that parses, names another run and has a schema the migrating
    /// loader refuses is an identity error, never an "unreadable" run removed
    /// wholesale.
    #[tokio::test]
    async fn a_foreign_record_in_a_refused_schema_is_not_removed_as_unreadable() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let id = "20260801-000000-z011";
        std::fs::create_dir_all(runs.join(id)).unwrap();
        let record = br#"{"schema": 99999, "id": "20260801-000000-z012"}"#.to_vec();
        std::fs::write(runs.join(id).join("run.json"), &record).unwrap();

        let error = ensure_record_identity(&runs, id).unwrap_err();
        assert!(
            format!("{error:#}").contains("records run 20260801-000000-z012"),
            "{error:#}"
        );
        let error = fold_unreadable(&runs, &home.join("wt"), id)
            .await
            .unwrap_err();
        assert!(
            format!("{error:#}").contains("records run 20260801-000000-z012"),
            "{error:#}"
        );
        assert_eq!(
            std::fs::read(runs.join(id).join("run.json")).unwrap(),
            record
        );
        // A record that names this run, or none that parses, passes.
        std::fs::write(
            runs.join(id).join("run.json"),
            format!(r#"{{"schema": 99999, "id": "{id}"}}"#),
        )
        .unwrap();
        ensure_record_identity(&runs, id).unwrap();
        std::fs::write(runs.join(id).join("run.json"), "not json").unwrap();
        ensure_record_identity(&runs, id).unwrap();
    }

    /// A sweep that takes the tombstone between a deletion's rename and its
    /// removal has finished that deletion; so has one that finds it gone.
    #[test]
    fn a_tombstone_taken_by_a_sweep_is_a_finished_deletion() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let tombstone = leftover_tombstone(home, "20260801-000000-z013-1");
        assert_eq!(sweep_graveyard(home), 1);
        assert!(!tombstone.exists());
        remove_tombstone("20260801-000000-z013", &tombstone).unwrap();
        let present = leftover_tombstone(home, "20260801-000000-z013-2");
        remove_tombstone("20260801-000000-z013", &present).unwrap();
        assert!(!present.exists());
    }

    /// An unreadable run's directory leaves through the same tombstone as a
    /// deleted run's, whose sweep is what removes the earlier leftover here.
    #[tokio::test]
    async fn an_unreadable_run_leaves_through_the_tombstone_helper() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let id = "20260801-000000-z010";
        write_meta(&runs, id, "failed", "2026-08-01T00:00:00Z");
        let leftover = leftover_tombstone(home, "20260701-000000-dead-3");
        let removed = fold_unreadable(&runs, &home.join("wt"), id).await.unwrap();
        assert_eq!(removed, [format!("runs/{id}")]);
        assert!(!runs.join(id).exists());
        assert!(!leftover.exists(), "it went through `remove_run_dir`");
        assert_eq!(
            std::fs::read_dir(home.join("deleted-runs"))
                .map(|entries| entries.count())
                .unwrap_or(0),
            0
        );
    }

    /// `runs/<A>/run.json` holding run B's record is not run A: the automatic
    /// callers judge it unreadable at the first read and touch nothing, and the
    /// explicit entry points refuse it.
    #[tokio::test]
    async fn a_record_naming_another_run_is_unreadable_at_the_first_read() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let (a, b) = ("20260801-000000-m001", "20260801-000000-m002");
        let (_, wt_a) = due_superseded(home, a).await;
        let (_, wt_b) = due_superseded(home, b).await;
        std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
        let record_a = std::fs::read(runs.join(a).join("run.json")).unwrap();
        let now = well_after_every_fold();

        let judged = fold_one(&runs, home, &Disk::default(), now, a, false, &mut || {}).await;
        assert_eq!(judged.outcome, FoldOutcome::Unreadable);
        assert!(read_state(&runs, a).is_err());
        assert!(
            RunState::read_unmigrated(&runs.join(a).join("run.json"))
                .unwrap()
                .ensure_directory(a)
                .is_err()
        );

        let turn = one_pass(home, now).await;
        assert_eq!((turn.unreadable, turn.folded), (1, 1), "{turn:?}");
        assert!(wt_a.exists() && !wt_b.exists(), "only run B was folded");
        assert_eq!(
            std::fs::read(runs.join(a).join("run.json")).unwrap(),
            record_a,
            "nothing was saved over the directory's record"
        );
    }

    /// The real operations in the window that matters: a `Ready` predecessor
    /// is handed over by `handover::release`, then an automatic fold with no
    /// grace judges it - `live`, nothing read back differently - and the
    /// rollback after the successor's startup failed still finds the worktree,
    /// the branch tip and the ownership record where it left them.
    #[tokio::test]
    async fn an_automatic_fold_between_a_real_release_and_its_rollback_finds_the_run_live() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let (id, next) = ("20260801-000000-h001", "20260901-000000-h002");
        let (_, worktree) =
            due_run_with_winner_worktree(&runs, &wt, &repo, id, RunStatus::Ready).await;
        let branch = format!("magi/{id}/A");
        let tip = crate::git::rev_parse(&repo, &branch).await.unwrap();
        let mut stopped = RunState::load_under(id, home).unwrap();
        stopped.driver_exited = true;
        let aged = stopped.updated_at;
        stopped.save_under_at(home, aged).unwrap();
        due_run(&runs, &wt, next, SCHEMA);
        start_of(home, next, false, None);

        let takeover = crate::handover::Takeover {
            earlier: vec![id.to_owned()],
            home: home.to_owned(),
            choice: None,
            task_instruction: None,
        };
        let released = crate::handover::release(&repo, &branch, next, &takeover)
            .await
            .unwrap()
            .expect("the stopped worktree is released");
        assert!(!worktree.exists());
        let record = std::fs::read(runs.join(id).join("run.json")).unwrap();

        let disk = Disk {
            fold_grace_secs: 0,
            ..Disk::default()
        };
        let now = well_after_every_fold();
        let judged = fold_one(&runs, home, &disk, now, id, false, &mut || {}).await;
        assert_eq!(judged.outcome, FoldOutcome::Live, "{:?}", judged.note);
        assert_eq!(
            std::fs::read(runs.join(id).join("run.json")).unwrap(),
            record,
            "the fold saved nothing over the handover"
        );

        start_of(home, next, false, Some("setup failed"));
        released.restore(&repo, &branch).await;
        let restored = run_json(home, id);
        assert!(restored.released_to.is_none() && !restored.candidates[0].folded);
        assert!(restored.driver_exited);
        assert_eq!(restored.status, RunStatus::Ready);
        assert!(worktree.exists(), "the worktree is back");
        assert_eq!(crate::git::rev_parse(&worktree, "HEAD").await.unwrap(), tip);
        assert_eq!(crate::git::rev_parse(&repo, &branch).await.unwrap(), tip);
    }

    /// A successor whose startup completed and whose execution lease is held is
    /// being driven: the handover is still in flight, whatever its record says
    /// about the predecessor. Once the lease is gone nothing protects it.
    #[tokio::test]
    async fn a_successor_holding_its_execution_lease_protects_its_predecessor() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        let runs = home.join("runs");
        let wt = home.join("wt");
        let repo = home.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_repo(&repo);
        let (id, next) = ("20260801-000000-l001", "20260901-000000-l002");
        let (_, worktree) =
            due_run_with_winner_worktree(&runs, &wt, &repo, id, RunStatus::Superseded).await;
        due_run(&runs, &wt, next, SCHEMA);
        hand_over_to(home, id, next);
        // Complete startup, no process identity: the held lease is the only
        // evidence the successor is running.
        let mut successor = RunState::load_under(next, home).unwrap();
        successor.startup = Some(crate::run::Startup {
            kind: "review".to_owned(),
            branch: None,
            stage: "open-review".to_owned(),
            complete: true,
            failure: None,
        });
        successor.status = RunStatus::Reviewing;
        successor.driver_exited = false;
        successor.driver_pid = None;
        successor.driver_started_at = None;
        successor.begin_pass();
        let aged = successor.updated_at;
        successor.save_under_at(home, aged).unwrap();
        let mut driving = crate::driver::DriverGuard::acquire(home, &successor).unwrap();
        driving.record(&successor).unwrap();

        let disk = Disk {
            fold_grace_secs: 0,
            ..Disk::default()
        };
        let now = well_after_every_fold();
        let judged = fold_one(&runs, home, &disk, now, id, false, &mut || {}).await;
        assert_eq!(judged.outcome, FoldOutcome::Live, "{:?}", judged.note);
        assert!(worktree.exists());

        drop(driving);
        let judged = fold_one(&runs, home, &disk, now, id, false, &mut || {}).await;
        assert_eq!(judged.outcome, FoldOutcome::Folded, "{:?}", judged.note);
        assert!(!worktree.exists());
    }
}