blyte 0.73.2

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
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
//! `blyte dispatch` and `blyte review` commands.

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::cli::{DispatchArgs, ReviewArgs};

pub const DEFAULT_MAX_COST_USD: f64 = 25.0;

pub(crate) fn resolve_max_cost(flag: Option<f64>, config: Option<f64>) -> f64 {
    match flag.or(config) {
        Some(v) => v,
        None => DEFAULT_MAX_COST_USD,
    }
}

pub const DISPATCH_RULES: &str = r#"Rules:
- Stay within the task. If it cannot pass without a small change elsewhere, make the smallest one and say so.
- Write no comments in code: not to explain it, not to mark a section, not to note an assumption or a TODO. The check fails on any comment you add. If something needs saying, say it in your final report. Documentation comments a tool reads (///, //!, /** */) and tool directives (noqa, eslint-disable, SAFETY:) are the only exceptions; do not use them to get around this rule.
- Never delete, clean or modify anything outside the worktree, and never change the machine to make a check pass. If a check fails because of the environment (disk, network, a missing service), stop and say so.
- Never copy, link or use a dependency environment from outside the worktree (a .venv, node_modules, site-packages or a package-cache entry from the main checkout, another worktree, another repository or your home directory). If the environment cannot be built here, stop and say so.
- Find files with the glob tool and search file contents with the grep tool. Do not run `find`, `grep -r` or `rg` in the shell over `/`, your home directory, or any directory outside the worktree: they walk huge trees and are killed at the time limit.
- Do not push, open pull requests, or read secrets.
- Commit locally before you stop, with the exact commit message the task gives (or a conventional one if it gives none).
- When you believe the task is done and committed, stop calling tools: the harness then runs the check. Before that, run the check's quick steps (formatting, lint, the tests for your change) yourself; the full run happens at the gate.
- Do not run the full test suite or the whole check yourself, not before you start and not while you work: the gate runs it when you stop, and each extra run costs minutes. Run the tests for the code you change.
- Read the code before you change it. If the task is already satisfied, or is smaller or larger than it says, do what is actually needed and say so at the top of your final report: what you found and what you did instead. Nobody has read the code for you first.
- Finish with a short report: what you changed, what you ran, and anything that deviated from the task."#;

/// Writes a start record as pretty JSON plus a newline, through a temporary file renamed
/// into place, so a concurrent reader never sees a partly written file.
pub fn write_start_record(
    path: &std::path::Path,
    value: &serde_json::Value,
) -> std::io::Result<()> {
    let mut json = serde_json::to_string_pretty(value).map_err(std::io::Error::other)?;
    json.push('\n');
    let mut tmp_name = path.as_os_str().to_os_string();
    tmp_name.push(".tmp");
    let tmp_path = std::path::PathBuf::from(tmp_name);
    std::fs::write(&tmp_path, json)?;
    std::fs::rename(&tmp_path, path)
}

struct StartRecordGuard {
    path: PathBuf,
    armed: bool,
}

impl Drop for StartRecordGuard {
    fn drop(&mut self) {
        if self.armed {
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

pub fn wrap_task(task: &str) -> String {
    format!(
        "You are implementing exactly one task. Your working directory is a git worktree on its own branch; work only there.\n\n{}\n\n{}",
        task.trim(),
        DISPATCH_RULES
    )
}

pub const RESEARCH_RULES: &str = r#"Rules:
- Do not create, modify, move or delete any file anywhere except `report.md` in your working directory.
- Do not run git commands that change state (no checkout, pull, commit, stash, worktree), and do not build, install, push, open pull requests, or write to any service.
- Read the code with the read, grep and glob tools, using absolute paths under the repository (glob and grep with `path` set to the repository's absolute path); use the shell only when they cannot do what you need. Do not run `find`, `grep -r` or `rg` in the shell over `/`, your home directory, or any directory outside the repository: they walk huge trees and are killed at the time limit.
- Answer the question with evidence: file paths with line numbers, and quote only what is needed.
- To quote code, do not retype it: put a line `<<quote /absolute/path:N-M>>` on its own in report.md (at most 200 lines) and the harness replaces it with those lines of the file. You need the line numbers, not a fresh read of the file.
- Write your findings to `report.md` in your working directory, then stop calling tools and reply with one line summarising them.
- The harness checks report.md: every cited `path:line` must exist, and a code block must be copied from the file and lines cited on the line before it (`path:N-M`). A code block you type yourself is checked the same way, so prefer the quote line. A code block with no citation fails unless it is a command or output (```bash, ```text) or is tagged ```proposed (code you propose or sketch, not in the repository). If the check fails you get the list of problems to fix.
- Start report.md early, after your first findings, and keep it updated as you go, so it always holds your best answer."#;

pub fn wrap_research(question: &str, root: &Path) -> String {
    format!(
        "READ-ONLY RESEARCH TASK. The code to research is under {}: read it there by absolute path.\n\n{}\n\n{}",
        root.display(),
        question.trim(),
        RESEARCH_RULES
    )
}

pub fn comment_step(exe: &std::path::Path, base_sha: &str) -> String {
    let escaped = exe.display().to_string().replace('\'', r"'\''");
    format!("'{escaped}' comments --base {base_sha}")
}

pub fn gate_with_comment_step(gate: &str, step: &str) -> String {
    if gate.lines().all(|l| l.trim().is_empty()) {
        gate.to_string()
    } else {
        format!("{step}\n{gate}")
    }
}

pub fn quick_steps(gate: &str) -> Option<String> {
    let lines: Vec<&str> = gate
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .collect();
    if lines.len() < 2 {
        return None;
    }
    let steps = lines[..lines.len() - 1]
        .iter()
        .map(|s| format!("`{s}`"))
        .collect::<Vec<_>>()
        .join(", ");
    Some(format!(
        "The check's quick steps, to run yourself before you stop: {steps}. The last step, the full run, happens at the gate."
    ))
}

pub fn dispatch_outcome(report_outcome: &str, commits: usize) -> &'static str {
    match report_outcome {
        "verified" => {
            if commits == 0 {
                "no_changes"
            } else {
                "verified"
            }
        }
        "gate_failed" => "gate_failed",
        "budget_exhausted" => "budget_exhausted",
        "blocked" => "blocked",
        "error" => "error",
        _ => "error",
    }
}

pub fn exit_code(outcome: &str) -> i32 {
    match outcome {
        "verified" | "finished" => 0,
        "no_changes" => 4,
        "blocked" => 5,
        _ => 1,
    }
}

pub fn summary_error(outcome: &str, error: Option<&str>) -> Option<String> {
    let err = error?;
    if outcome == "blocked" {
        err.lines().next().map(String::from)
    } else {
        Some(err.to_string())
    }
}

/// Bounds a gate failure entry for `.wt/<id>.json`, keeping its first line and tail.
pub fn cut_summary_gate_failure(s: &str) -> String {
    const MAX_CHARS: usize = 1_000;
    const FIRST_LINE_MAX: usize = 200;

    let total_chars = s.chars().count();
    if total_chars <= MAX_CHARS {
        return s.to_string();
    }

    let first_line = s.lines().next().unwrap_or("");
    let head_end = first_line
        .char_indices()
        .nth(FIRST_LINE_MAX)
        .map(|(i, _)| i)
        .unwrap_or(first_line.len());
    let head = &first_line[..head_end];
    let head_chars = head.chars().count();

    let tail_budget = MAX_CHARS.saturating_sub(head_chars);
    let tail_start_byte = s
        .char_indices()
        .nth(total_chars.saturating_sub(tail_budget))
        .map(|(i, _)| i)
        .unwrap_or(s.len());
    let tail_cand = &s[tail_start_byte..];
    let tail = if tail_start_byte > 0 && s.as_bytes()[tail_start_byte - 1] == b'\n' {
        tail_cand
    } else if let Some(idx) = tail_cand.find('\n') {
        let after = &tail_cand[idx + 1..];
        if after.trim_matches(['\r', '\n']).is_empty() {
            tail_cand
        } else {
            after
        }
    } else {
        tail_cand
    };
    let tail_chars = tail.chars().count();
    let omitted = total_chars.saturating_sub(head_chars + tail_chars);
    format!("{head}\n[... {omitted} characters left out ...]\n{tail}")
}

#[derive(Debug, Serialize)]
pub struct CommitRecord {
    pub sha: String,
    pub subject: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BaseCheckDecision {
    Run,
    Disabled,
    AlreadyPassed,
}

impl BaseCheckDecision {
    pub fn as_json(self) -> serde_json::Value {
        match self {
            Self::Run => serde_json::json!(true),
            Self::Disabled => serde_json::json!(false),
            Self::AlreadyPassed => serde_json::json!("already_passed"),
        }
    }
}

#[allow(clippy::too_many_arguments)]
pub fn decide_base_check(
    root: &Path,
    worktree_dir: &Path,
    base_sha: &str,
    configured_gate: &str,
    env: &std::collections::BTreeMap<String, String>,
    research: bool,
    no_base_check: bool,
    config_base_check: Option<bool>,
    now: u64,
) -> Result<(BaseCheckDecision, Option<String>), String> {
    if research || no_base_check || config_base_check == Some(false) {
        return Ok((BaseCheckDecision::Disabled, None));
    }
    let tree = crate::passed_trees::tree_of(worktree_dir, base_sha)?;
    let key = crate::passed_trees::check_key(configured_gate, env);
    if crate::passed_trees::has_passed(root, &tree, &key, now)? {
        Ok((BaseCheckDecision::AlreadyPassed, Some(tree)))
    } else {
        Ok((BaseCheckDecision::Run, Some(tree)))
    }
}

#[allow(clippy::too_many_arguments)]
pub fn record_passed_after_run(
    root: &Path,
    worktree_dir: &Path,
    research: bool,
    base_check_decision: BaseCheckDecision,
    base_tree: Option<&str>,
    key: Option<&str>,
    outcome: &str,
    base_check_passed: Option<bool>,
) -> Vec<String> {
    let mut warnings = Vec::new();
    if research {
        return warnings;
    }
    let Some(key) = key else {
        return warnings;
    };
    if base_check_decision == BaseCheckDecision::Run && base_check_passed == Some(true) {
        if let Some(tree) = base_tree {
            if let Err(err) = crate::passed_trees::record_passed(root, tree, key) {
                warnings.push(format!("could not record passed base tree: {err}"));
            }
        }
    }
    if outcome == "verified" {
        match crate::passed_trees::worktree_is_clean(worktree_dir) {
            Ok(true) => match crate::passed_trees::tree_of(worktree_dir, "HEAD") {
                Ok(head_tree) => {
                    if let Err(err) = crate::passed_trees::record_passed(root, &head_tree, key) {
                        warnings.push(format!("could not record passed tree: {err}"));
                    }
                }
                Err(err) => {
                    warnings.push(format!("could not resolve HEAD tree to record pass: {err}"));
                }
            },
            Ok(false) => {}
            Err(err) => {
                warnings.push(format!("could not check worktree cleanliness: {err}"));
            }
        }
    }
    warnings
}

#[derive(Debug, Serialize)]
pub struct DispatchSummary {
    pub id: String,
    pub worktree: String,
    pub branch: String,
    pub outcome: &'static str,
    pub exit: i32,
    pub error: Option<String>,
    pub commits: Vec<CommitRecord>,
    pub changed_files: Vec<String>,
    pub final_message: Option<String>,
    pub turns: u32,
    pub gate_attempts: u32,
    pub gate_failures: Vec<String>,
    pub cost_usd: Option<f64>,
    pub model: Option<String>,
    pub seconds: u64,
    pub sandbox: String,
    pub log: String,
    pub report: String,
    pub gate_source: &'static str,
    pub research_report: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_check_seconds: Option<f64>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fix_round: Option<crate::fix_round::FixRoundSummary>,
}

pub(crate) struct ImplementerConfig<'a> {
    pub(crate) current_exe: &'a Path,
    pub(crate) worktree_dir: &'a Path,
    pub(crate) root: &'a Path,
    pub(crate) id: &'a str,
    pub(crate) gate: &'a str,
    pub(crate) env: &'a std::collections::BTreeMap<String, String>,
    pub(crate) model: Option<&'a str>,
    pub(crate) max_seconds: u64,
    pub(crate) max_turns: u32,
    pub(crate) max_cost: f64,
    pub(crate) fold_budget: Option<usize>,
    pub(crate) sandbox: &'a str,
    pub(crate) network: &'a str,
    pub(crate) config_allow_read: &'a [PathBuf],
    pub(crate) cli_allow_read: &'a [PathBuf],
    pub(crate) pass_env: &'a [String],
    pub(crate) research: bool,
    pub(crate) no_claim_check: bool,
    pub(crate) left_out: &'a [(String, String)],
    pub(crate) snapshot_dir: Option<&'a Path>,
    pub(crate) snapshot_manifest: Option<&'a Path>,
}

pub(crate) struct PassReport {
    pub(crate) report_outcome: String,
    pub(crate) error: Option<String>,
    pub(crate) final_message: Option<String>,
    pub(crate) turns: u32,
    pub(crate) report_turns: Option<u64>,
    pub(crate) gate_attempts: u32,
    pub(crate) gate_failures: Vec<String>,
    pub(crate) cost_usd: Option<f64>,
    pub(crate) model: Option<String>,
    pub(crate) seconds: u64,
    pub(crate) sandbox: String,
    pub(crate) base_check_passed: Option<bool>,
    pub(crate) base_check_seconds: Option<f64>,
}

fn open_pass_log(log_path: &Path, append_header: Option<&str>) -> Result<std::fs::File, String> {
    match append_header {
        None => std::fs::File::create(log_path)
            .map_err(|e| format!("error creating log file {}: {e}", log_path.display())),
        Some(header) => {
            use std::io::Write;
            let needs_leading_nl = match std::fs::read(log_path) {
                Ok(bytes) => !bytes.is_empty() && !bytes.ends_with(b"\n"),
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
                Err(e) => {
                    return Err(format!(
                        "error reading log file {}: {e}",
                        log_path.display()
                    ));
                }
            };
            let mut f = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(log_path)
                .map_err(|e| format!("error opening log file {}: {e}", log_path.display()))?;
            if needs_leading_nl {
                writeln!(f)
                    .map_err(|e| format!("error writing log file {}: {e}", log_path.display()))?;
            }
            writeln!(f, "{header}")
                .map_err(|e| format!("error writing log file {}: {e}", log_path.display()))?;
            Ok(f)
        }
    }
}

pub(crate) fn run_implementer_pass<F>(
    cfg: &ImplementerConfig<'_>,
    log_path: &Path,
    append_log_header: Option<&str>,
    report_path: &Path,
    task_prompt: &str,
    base_check_dir: Option<&Path>,
    on_spawn: F,
) -> Result<(), String>
where
    F: FnOnce(u32),
{
    if report_path.exists() {
        std::fs::remove_file(report_path)
            .map_err(|e| format!("error removing {}: {e}", report_path.display()))?;
    }
    let log_file = open_pass_log(log_path, append_log_header)?;
    let log_file_err = log_file
        .try_clone()
        .map_err(|e| format!("error cloning log file handle: {e}"))?;

    let mut cmd = Command::new(cfg.current_exe);
    cmd.current_dir(cfg.worktree_dir);
    cmd.stdout(log_file);
    cmd.stderr(log_file_err);

    for (k, v) in cfg.env {
        cmd.env(k, v);
    }
    cmd.env("BLYTE_DISPATCH_ID", cfg.id);
    cmd.env_remove(blyte_agent::shell::MODEL_SHELL_ENV);

    cmd.arg("--gate").arg(cfg.gate);
    cmd.arg("--rollback=false");
    cmd.arg("--max-seconds").arg(cfg.max_seconds.to_string());
    cmd.arg("--max-turns").arg(cfg.max_turns.to_string());
    cmd.arg("--report").arg(report_path);

    if let Some(m) = cfg.model {
        cmd.arg("--model").arg(m);
    }
    cmd.arg("--max-cost").arg(cfg.max_cost.to_string());
    if let Some(fb) = cfg.fold_budget {
        cmd.arg("--fold-budget").arg(fb.to_string());
    }
    cmd.arg("--sandbox").arg(cfg.sandbox);
    cmd.arg("--network").arg(cfg.network);
    for r in cfg.config_allow_read {
        cmd.arg("--allow-read").arg(r);
    }
    for r in cfg.cli_allow_read {
        cmd.arg("--allow-read").arg(r);
    }
    for p in cfg.pass_env {
        cmd.arg("--pass-env").arg(p);
    }
    for r in cfg.config_allow_read.iter().chain(cfg.cli_allow_read) {
        cmd.arg("--read-root").arg(r);
    }
    if cfg.research {
        cmd.arg("--read-root").arg(cfg.root);
        cmd.arg("--no-gate-slot");
        cmd.arg("--research");
        if !cfg.no_claim_check {
            cmd.arg("--claim-check");
        }
    } else if let Some(base_wt_dir) = base_check_dir {
        cmd.arg("--base-check");
        cmd.arg("--base-check-dir").arg(base_wt_dir);
    }

    if let (Some(before_dir), Some(manifest)) = (cfg.snapshot_dir, cfg.snapshot_manifest) {
        cmd.arg("--snapshot-dir").arg(before_dir);
        cmd.arg("--snapshot-manifest").arg(manifest);
    }

    cmd.arg("--");
    cmd.arg(task_prompt);

    let mut child = cmd
        .spawn()
        .map_err(|e| format!("error spawning child process: {e}"))?;
    let pid = child.id();
    on_spawn(pid);
    if let Err(msg) = crate::keep_awake::hold(pid) {
        eprintln!("blyte: warning: {msg}; the machine may sleep during this run");
    }

    child
        .wait()
        .map_err(|e| format!("error waiting for child process (pid {pid}): {e}"))?;

    patch_report_gate_left_out(report_path, cfg.left_out)?;

    Ok(())
}

pub fn patch_report_gate_left_out(
    report_path: &Path,
    left_out: &[(String, String)],
) -> Result<(), String> {
    if left_out.is_empty() {
        return Ok(());
    }
    let report_str = match std::fs::read_to_string(report_path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(format!("cannot read {}: {e}", report_path.display())),
    };
    let mut report_val: serde_json::Value = serde_json::from_str(&report_str)
        .map_err(|e| format!("cannot parse {}: {e}", report_path.display()))?;
    let obj = report_val
        .as_object_mut()
        .ok_or_else(|| format!("expected JSON object in {}", report_path.display()))?;
    let formatted: Vec<String> = left_out
        .iter()
        .map(|(cmd_name, reason)| format!("{cmd_name} ({reason})"))
        .collect();
    obj.insert("gate_left_out".to_string(), serde_json::json!(formatted));
    let updated = serde_json::to_string_pretty(&report_val)
        .map_err(|e| format!("cannot serialize {}: {e}", report_path.display()))?;
    std::fs::write(report_path, updated + "\n")
        .map_err(|e| format!("cannot write {}: {e}", report_path.display()))?;
    Ok(())
}

#[derive(Debug, PartialEq, Eq)]
pub struct GateDriftCheck {
    pub left_out: Vec<(String, String)>,
    pub warning: Option<String>,
}

pub fn load_gate_drift(
    root: &Path,
    toml_path: &Path,
    gate: &str,
) -> Result<GateDriftCheck, String> {
    let toml_content = std::fs::read_to_string(toml_path)
        .map_err(|e| format!("cannot read {}: {e}", toml_path.display()))?;
    let left_out = crate::gate_drift::left_out_steps(&toml_content);
    if gate.trim().is_empty() {
        let mut msg = "the gate in blyte.toml is empty; every step was left out. Fix the steps blyte init named, or pass --gate.".to_string();
        for (cmd, reason) in &left_out {
            msg.push_str(&format!("\n  {cmd}: {reason}"));
        }
        return Err(msg);
    }
    let missing = crate::gate_drift::missing_ci_steps(root, gate, &toml_content);
    let warning = crate::gate_drift::format_gate_drift_warning(&missing);
    Ok(GateDriftCheck { left_out, warning })
}

pub(crate) fn parse_pass_report(
    report_path: &Path,
    default_sandbox: &str,
) -> Result<PassReport, String> {
    let raw = std::fs::read_to_string(report_path)
        .map_err(|e| format!("missing report {}: {e}", report_path.display()))?;
    let rec: serde_json::Value = serde_json::from_str(&raw)
        .map_err(|e| format!("unreadable report JSON {}: {e}", report_path.display()))?;

    let gate_failures = match rec.get("gate_failures").and_then(|v| v.as_array()) {
        Some(arr) => arr
            .iter()
            .filter_map(|v| v.as_str())
            .map(cut_summary_gate_failure)
            .collect(),
        None => Vec::new(),
    };
    let raw_turns = rec.get("turns").and_then(|v| v.as_u64());
    let rec_outcome = rec
        .get("outcome")
        .and_then(|v| v.as_str())
        .ok_or_else(|| format!("missing \"outcome\" in {}", report_path.display()))?;
    let turns = match raw_turns {
        Some(t) => t as u32,
        None => 0,
    };
    let gate_attempts = match rec.get("gate_attempts").and_then(|v| v.as_u64()) {
        Some(n) => n as u32,
        None => 0,
    };
    let seconds = match rec.get("duration_seconds").and_then(|v| v.as_f64()) {
        Some(d) => d.round() as u64,
        None => 0,
    };
    let sandbox = match rec.get("sandbox").and_then(|v| v.as_str()) {
        Some(s) => s.to_string(),
        None => default_sandbox.to_string(),
    };

    Ok(PassReport {
        report_outcome: rec_outcome.to_string(),
        error: summary_error(rec_outcome, rec.get("error").and_then(|v| v.as_str())),
        final_message: rec
            .get("final_message")
            .and_then(|v| v.as_str())
            .map(String::from),
        turns,
        report_turns: raw_turns,
        gate_attempts,
        gate_failures,
        cost_usd: rec.get("cost_usd").and_then(|v| v.as_f64()),
        model: rec
            .get("model_id")
            .and_then(|v| v.as_str())
            .map(String::from),
        seconds,
        sandbox,
        base_check_passed: rec.get("base_check_passed").and_then(|v| v.as_bool()),
        base_check_seconds: rec.get("base_check_seconds").and_then(|v| v.as_f64()),
    })
}

pub(crate) fn pass_report_from_error(err_msg: String, default_sandbox: &str) -> PassReport {
    PassReport {
        report_outcome: "error".to_string(),
        error: Some(err_msg),
        final_message: None,
        turns: 0,
        report_turns: None,
        gate_attempts: 0,
        gate_failures: Vec::new(),
        cost_usd: None,
        model: None,
        seconds: 0,
        sandbox: default_sandbox.to_string(),
        base_check_passed: None,
        base_check_seconds: None,
    }
}

fn git_head_sha(worktree_dir: &Path) -> Result<String, String> {
    let wt = worktree_dir
        .to_str()
        .ok_or_else(|| format!("non-UTF-8 worktree path {}", worktree_dir.display()))?;
    let out = Command::new("git")
        .args(["-C", wt, "rev-parse", "HEAD"])
        .output()
        .map_err(|e| format!("failed to execute git rev-parse HEAD in {wt}: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "git rev-parse HEAD failed in {wt}: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

fn git_reset_hard(worktree_dir: &Path, sha: &str) -> Result<(), String> {
    let wt = worktree_dir
        .to_str()
        .ok_or_else(|| format!("non-UTF-8 worktree path {}", worktree_dir.display()))?;
    let out = Command::new("git")
        .args(["-C", wt, "reset", "--hard", sha])
        .output()
        .map_err(|e| format!("failed to run git reset --hard {sha} in {wt}: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "git reset --hard {sha} failed in {wt}: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    Ok(())
}

fn git_commits_since(worktree_dir: &Path, base_sha: &str) -> Vec<CommitRecord> {
    let log_out = Command::new("git")
        .args([
            "-C",
            worktree_dir.to_str().unwrap(),
            "log",
            "--reverse",
            "--format=%h%x09%s",
            &format!("{base_sha}..HEAD"),
        ])
        .output();

    let mut commits = Vec::new();
    if let Ok(o) = log_out {
        let text = String::from_utf8_lossy(&o.stdout);
        for line in text.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }
            if let Some((sha, subject)) = line.split_once('\t') {
                commits.push(CommitRecord {
                    sha: sha.to_string(),
                    subject: subject.to_string(),
                });
            }
        }
    }
    commits
}

fn git_changed_files_since(worktree_dir: &Path, base_sha: &str) -> Vec<String> {
    let diff_out = Command::new("git")
        .args([
            "-C",
            worktree_dir.to_str().unwrap(),
            "diff",
            "--name-only",
            &format!("{base_sha}..HEAD"),
        ])
        .output();

    let mut changed_files = Vec::new();
    if let Ok(o) = diff_out {
        let text = String::from_utf8_lossy(&o.stdout);
        for line in text.lines() {
            let line = line.trim();
            if !line.is_empty() {
                changed_files.push(line.to_string());
            }
        }
    }
    changed_files
}

fn update_start_record_pid(start_path: &Path, pid: u32) {
    let raw = match std::fs::read_to_string(start_path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("warning: cannot read {}: {e}", start_path.display());
            return;
        }
    };
    let mut val = match serde_json::from_str::<serde_json::Value>(&raw) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("warning: cannot parse {}: {e}", start_path.display());
            return;
        }
    };
    val["pid"] = serde_json::json!(pid);
    if let Err(e) = write_start_record(start_path, &val) {
        eprintln!("warning: cannot update {}: {e}", start_path.display());
    }
}

fn read_start_base_sha(start_path: &Path) -> Result<String, String> {
    let raw = std::fs::read_to_string(start_path)
        .map_err(|e| format!("cannot read {}: {e}", start_path.display()))?;
    let val: serde_json::Value = serde_json::from_str(&raw)
        .map_err(|e| format!("cannot parse {}: {e}", start_path.display()))?;
    val.get("base_sha")
        .and_then(|v| v.as_str())
        .map(str::to_string)
        .ok_or_else(|| format!("missing \"base_sha\" in {}", start_path.display()))
}

fn read_start_task_content(root: &Path, start_path: &Path) -> Result<String, String> {
    let raw = std::fs::read_to_string(start_path)
        .map_err(|e| format!("cannot read {}: {e}", start_path.display()))?;
    let val: serde_json::Value = serde_json::from_str(&raw)
        .map_err(|e| format!("cannot parse {}: {e}", start_path.display()))?;
    let task_file_str = val
        .get("task_file")
        .and_then(|v| v.as_str())
        .ok_or_else(|| format!("missing \"task_file\" in {}", start_path.display()))?;
    let task_path = Path::new(task_file_str);
    let resolved = if task_path.is_absolute() {
        task_path.to_path_buf()
    } else {
        root.join(task_path)
    };
    std::fs::read_to_string(&resolved)
        .map_err(|e| format!("cannot read task file {}: {e}", resolved.display()))
}

#[allow(clippy::too_many_arguments)]
fn build_error_summary(
    id: &str,
    worktree_dir: &Path,
    branch: String,
    err_msg: String,
    sandbox: String,
    log_path: &Path,
    report_path: &Path,
    gate_source: &'static str,
    warnings: Vec<String>,
) -> DispatchSummary {
    let outcome = "error";
    DispatchSummary {
        id: id.to_string(),
        worktree: worktree_dir.display().to_string(),
        branch,
        outcome,
        exit: exit_code(outcome),
        error: Some(err_msg),
        commits: Vec::new(),
        changed_files: Vec::new(),
        final_message: None,
        turns: 0,
        gate_attempts: 0,
        gate_failures: Vec::new(),
        cost_usd: None,
        model: None,
        seconds: 0,
        sandbox,
        log: log_path.display().to_string(),
        report: report_path.display().to_string(),
        gate_source,
        research_report: None,
        base_check_seconds: None,
        warnings,
        fix_round: None,
    }
}

#[allow(clippy::too_many_arguments)]
fn execute_fix_round(
    root: &Path,
    start_path: &Path,
    impl_cfg: &ImplementerConfig<'_>,
    log_path: &Path,
    fix_report_path: &Path,
    fixround_path: &Path,
    passed_key: Option<&str>,
    original_task: &str,
    pre_round_sha: String,
    fallbacks_sent: Vec<crate::fix_round::ConfirmedFallback>,
    concerns_sent: Vec<crate::model_review::Concern>,
    round_started_at: u64,
    warnings: &mut Vec<String>,
) -> Result<(crate::fix_round::FixRoundSummary, PassReport), String> {
    let round_task = crate::fix_round::task_text(original_task, &fallbacks_sent, &concerns_sent);
    let mut round_prompt = wrap_task(&round_task);
    if let Some(qs) = quick_steps(impl_cfg.gate) {
        round_prompt.push_str("\n\n");
        round_prompt.push_str(&qs);
    }

    if fix_report_path.exists() {
        std::fs::remove_file(fix_report_path).map_err(|e| {
            format!(
                "cannot remove stale fix round report {}: {e}",
                fix_report_path.display()
            )
        })?;
    }

    run_implementer_pass(
        impl_cfg,
        log_path,
        Some("== fix round"),
        fix_report_path,
        &round_prompt,
        None,
        |pid| update_start_record_pid(start_path, pid),
    )?;

    let round_report = match parse_pass_report(fix_report_path, impl_cfg.sandbox) {
        Ok(r) => r,
        Err(err_msg) => pass_report_from_error(err_msg, impl_cfg.sandbox),
    };
    let round_commits = git_commits_since(impl_cfg.worktree_dir, &pre_round_sha);

    let (kept, round_outcome, done_commits, fallbacks_left, concerns_left) =
        if round_report.report_outcome == "verified" && !round_commits.is_empty() {
            let second_review = match crate::queue_actions::evaluate_verified_run(root, impl_cfg.id)
            {
                Ok(mr) => mr,
                Err(err) => {
                    eprintln!(
                        "warning: post-dispatch review check failed for {}: {err}",
                        impl_cfg.id
                    );
                    None
                }
            };
            let round_warnings = record_passed_after_run(
                root,
                impl_cfg.worktree_dir,
                false,
                BaseCheckDecision::Disabled,
                None,
                passed_key,
                "verified",
                None,
            );
            for w in &round_warnings {
                eprintln!("warning: {w}");
            }
            warnings.extend(round_warnings);
            let left = crate::fix_round::fallbacks_left(second_review.as_ref());
            let c_left = crate::fix_round::concerns_left(second_review.as_ref());
            let commit_shas = round_commits.into_iter().map(|c| c.sha).collect();
            (true, "verified".to_string(), commit_shas, left, c_left)
        } else {
            let round_outcome = if round_report.report_outcome == "verified" {
                "no_change".to_string()
            } else {
                match round_report.report_outcome.as_str() {
                    "gate_failed" => "gate_failed".to_string(),
                    "budget_exhausted" => "budget_exhausted".to_string(),
                    "blocked" => "blocked".to_string(),
                    _ => "error".to_string(),
                }
            };
            git_reset_hard(impl_cfg.worktree_dir, &pre_round_sha)?;
            let flag = crate::fix_round::failure_flag(&round_outcome);
            crate::fix_round::append_check_flag(root, impl_cfg.id, &flag)?;
            (
                false,
                round_outcome,
                Vec::new(),
                Some(fallbacks_sent.len()),
                Some(concerns_sent.len()),
            )
        };

    let fix_summary = crate::fix_round::FixRoundSummary {
        outcome: round_outcome,
        turns: round_report.turns,
        cost_usd: round_report.cost_usd,
        seconds: round_report.seconds,
        commits: done_commits,
        fallbacks_left,
        concerns_left,
        kept,
    };
    let done_record = crate::fix_round::FixRoundRecord::Done {
        pre_round_sha: Some(pre_round_sha),
        fallbacks_sent,
        concerns_sent,
        started_at: Some(round_started_at),
        summary: fix_summary.clone(),
    };
    crate::fix_round::write_record(fixround_path, &done_record)?;
    Ok((fix_summary, round_report))
}

struct BaseWorktreeGuard {
    root: PathBuf,
    dir: PathBuf,
}

impl BaseWorktreeGuard {
    fn create(root: &Path, dir: PathBuf, base_sha: &str) -> Result<Self, String> {
        if dir.exists() {
            let _ = Command::new("git")
                .args([
                    "-C",
                    root.to_str().unwrap_or("."),
                    "worktree",
                    "remove",
                    "--force",
                ])
                .arg(&dir)
                .output();
            if dir.exists() {
                let _ = std::fs::remove_dir_all(&dir);
            }
            let _ = Command::new("git")
                .args(["-C", root.to_str().unwrap_or("."), "worktree", "prune"])
                .output();
        }
        let out = Command::new("git")
            .args([
                "-C",
                root.to_str().unwrap_or("."),
                "worktree",
                "add",
                "--detach",
            ])
            .arg(&dir)
            .arg(base_sha)
            .output()
            .map_err(|e| format!("failed to run git worktree add --detach: {e}"))?;
        if !out.status.success() {
            return Err(format!(
                "git worktree add --detach failed: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            ));
        }
        Ok(Self {
            root: root.to_path_buf(),
            dir,
        })
    }
}

impl Drop for BaseWorktreeGuard {
    fn drop(&mut self) {
        let _ = Command::new("git")
            .args([
                "-C",
                self.root.to_str().unwrap_or("."),
                "worktree",
                "remove",
                "--force",
            ])
            .arg(&self.dir)
            .output();
    }
}

pub(crate) fn copy_report_file(
    scratch_report: &Path,
    dest: &Path,
    research_sources: Option<&str>,
) -> Result<(), String> {
    if let Some(parent) = dest.parent() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent).map_err(|e| {
                format!(
                    "could not create directory {} for {}: {e}",
                    parent.display(),
                    dest.display()
                )
            })?;
        }
    }
    std::fs::copy(scratch_report, dest)
        .map_err(|e| format!("could not copy research report to {}: {e}", dest.display()))?;
    if let Some(block) = research_sources {
        append_source_state(dest, block);
    }
    Ok(())
}

pub(crate) fn research_gate() -> (String, &'static str) {
    ("test -s report.md".to_string(), "research")
}

pub(crate) fn research_budgets(args: &DispatchArgs) -> (u64, u32) {
    (
        args.max_seconds.unwrap_or(1800),
        args.max_turns.unwrap_or(300),
    )
}

pub(crate) fn research_outcome(report_outcome: &str) -> &'static str {
    match report_outcome {
        "verified" => "verified",
        "gate_failed" => "gate_failed",
        "budget_exhausted" => "budget_exhausted",
        "blocked" => "blocked",
        _ => "error",
    }
}

pub(crate) fn create_research_scratch_dir(worktree_dir: &Path) -> Result<(), String> {
    std::fs::create_dir_all(worktree_dir).map_err(|e| {
        format!(
            "error creating scratch directory {}: {e}",
            worktree_dir.display()
        )
    })?;
    let init_out = Command::new("git")
        .args(["init", "-q"])
        .current_dir(worktree_dir)
        .output()
        .map_err(|e| format!("error: failed to execute git init: {e}"))?;
    if !init_out.status.success() {
        return Err(format!(
            "error: git init failed: {}",
            String::from_utf8_lossy(&init_out.stderr)
        ));
    }
    let commit_out = Command::new("git")
        .args([
            "-c",
            "user.name=blyte",
            "-c",
            "user.email=blyte@local",
            "commit",
            "-q",
            "--allow-empty",
            "-m",
            "research",
        ])
        .current_dir(worktree_dir)
        .output()
        .map_err(|e| format!("error: failed to execute git commit: {e}"))?;
    if !commit_out.status.success() {
        return Err(format!(
            "error: git commit failed: {}",
            String::from_utf8_lossy(&commit_out.stderr)
        ));
    }
    Ok(())
}

fn copy_research_reports(
    scratch_report: &Path,
    research_report_path: &Path,
    report_to: Option<&Path>,
    research_sources: Option<&str>,
) -> Result<(), String> {
    copy_report_file(scratch_report, research_report_path, research_sources)?;
    if let Some(dest) = report_to {
        copy_report_file(scratch_report, dest, research_sources)?;
    }
    Ok(())
}

pub(crate) fn write_summary_to_dir(
    summary: &DispatchSummary,
    dir: &Path,
    stdout: &mut dyn std::io::Write,
    stderr: &mut dyn std::io::Write,
) -> (bool, i32) {
    let json_str = serde_json::to_string_pretty(summary).unwrap();
    let summary_path = dir.join(format!("{}.json", summary.id));
    let write_failed = match std::fs::create_dir_all(dir)
        .and_then(|()| std::fs::write(&summary_path, format!("{json_str}\n")))
    {
        Ok(()) => false,
        Err(e) => {
            let _ = writeln!(
                stderr,
                "blyte: could not write {}: {e}",
                summary_path.display()
            );
            true
        }
    };
    let _ = writeln!(stdout, "{json_str}");
    let exit = if write_failed && summary.exit == 0 {
        1
    } else {
        summary.exit
    };
    (write_failed, exit)
}

pub(crate) fn load_task_text(
    task_file: Option<&Path>,
    plan: Option<&str>,
    plan_task: Option<&str>,
) -> Result<Option<(String, Option<String>)>, String> {
    if let Some(tf) = task_file {
        let content = std::fs::read_to_string(tf)
            .map_err(|e| format!("error reading task file {}: {e}", tf.display()))?;
        return Ok(Some((content, Some(tf.display().to_string()))));
    }
    if let (Some(plan_path), Some(plan_task)) = (plan, plan_task) {
        let plan_str = std::fs::read_to_string(plan_path)
            .map_err(|e| format!("error reading plan {plan_path}: {e}"))?;
        let Some(section) = crate::plan_section::extract(&plan_str, plan_task) else {
            let mut msg = format!("error: no heading \"{plan_task}\" in {plan_path}");
            if let Some(hint) = crate::plan_section::explain_missing(&plan_str, plan_task) {
                msg.push_str(&format!("\n  {hint}"));
            }
            return Err(msg);
        };
        let content = format!("From the plan {plan_path}:\n\n{section}");
        return Ok(Some((content, None)));
    }
    Ok(None)
}

fn finish_summary(summary: &DispatchSummary, root: &Path) -> i32 {
    finish_summary_with_writers(
        summary,
        root,
        &mut std::io::stdout(),
        &mut std::io::stderr(),
    )
}

fn finish_summary_with_writers(
    summary: &DispatchSummary,
    root: &Path,
    stdout: &mut dyn std::io::Write,
    stderr: &mut dyn std::io::Write,
) -> i32 {
    let wt_parent = root.join(".wt");
    let (write_failed, exit) = write_summary_to_dir(summary, &wt_parent, stdout, stderr);
    if !write_failed {
        let notify_outcome = crate::surface_notify::notify_runs_changed(root, &summary.id);
        crate::surface_notify::report(&notify_outcome, stderr);
    }
    exit
}

const RUN_RECORD_EXTENSIONS: &[&str] = &[
    "json",
    "report.json",
    "reported.json",
    "report.md",
    "start.json",
    "verdict.json",
    "checks.json",
    "model-review.json",
    "fixround.json",
    "fix.report.json",
    "hold.json",
    "removed.json",
    "log",
    "setup.log",
];

fn archive_run_records_at(root: &Path, id: &str, unix_secs: u64) -> Result<Option<String>, String> {
    let wt_parent = root.join(".wt");
    let mut existing: Vec<(String, PathBuf)> = Vec::new();
    for ext in RUN_RECORD_EXTENSIONS {
        let file_name = format!("{id}.{ext}");
        let src = wt_parent.join(&file_name);
        match std::fs::symlink_metadata(&src) {
            Ok(_) => existing.push((file_name, src)),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => {
                return Err(format!("{}: {e}", src.display()));
            }
        }
    }
    if existing.is_empty() {
        return Ok(None);
    }

    let archive_root = wt_parent.join("archive");
    if let Err(e) = std::fs::create_dir_all(&archive_root) {
        return Err(format!("{}: {e}", archive_root.display()));
    }
    let mut suffix: u64 = 1;
    let (archive_rel, archive_dir) = loop {
        let dir_name = if suffix == 1 {
            format!("{id}-{unix_secs}")
        } else {
            format!("{id}-{unix_secs}-{suffix}")
        };
        let rel = format!(".wt/archive/{dir_name}");
        let dir = archive_root.join(&dir_name);
        match std::fs::create_dir(&dir) {
            Ok(()) => break (rel, dir),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                suffix += 1;
            }
            Err(e) => {
                return Err(format!("{}: {e}", dir.display()));
            }
        }
    };

    for (file_name, src) in existing {
        let dst = archive_dir.join(&file_name);
        if let Err(e) = std::fs::rename(&src, &dst) {
            return Err(format!(
                "rename {} -> {}: {e}",
                src.display(),
                dst.display()
            ));
        }
    }
    Ok(Some(archive_rel))
}

fn archive_run_records(root: &Path, id: &str) -> Result<Option<String>, String> {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| format!("system clock before unix epoch: {e}"))?
        .as_secs();
    archive_run_records_at(root, id, secs)
}

pub fn branch_exists_message(root: &Path, branch: &str, id: &str) -> String {
    if crate::clean::is_branch_merged(root, branch) {
        format!(
            "error: branch {branch} already exists from an earlier run, and its work is already merged. Run `blyte clean` to remove it, or dispatch with a new ID."
        )
    } else {
        format!(
            "error: branch {branch} already exists from an earlier run and is not merged. Review it with `blyte review {id}`, delete it (`git branch -D {branch}`) if it is not needed, or dispatch with a new ID."
        )
    }
}

/// Source-state block for the research root and each read root, skipping duplicates.
pub(crate) fn research_source_block(
    root: &Path,
    config_allow_read: &[PathBuf],
    allow_read: &[PathBuf],
) -> String {
    let mut roots: Vec<PathBuf> = vec![root.to_path_buf()];
    for r in config_allow_read.iter().chain(allow_read) {
        if !roots.contains(r) {
            roots.push(r.clone());
        }
    }
    let sources: Vec<(PathBuf, crate::provenance::SourceState)> = roots
        .into_iter()
        .map(|p| {
            let state = crate::provenance::source_state(&p);
            (p, state)
        })
        .collect();
    crate::provenance::render(&sources)
}

/// Appends the source-state block to a copied report. Failure is reported, not fatal.
fn append_source_state(path: &Path, block: &str) {
    use std::io::Write;
    let result = std::fs::OpenOptions::new()
        .append(true)
        .open(path)
        .and_then(|mut f| f.write_all(format!("\n\n{block}").as_bytes()));
    if let Err(e) = result {
        eprintln!(
            "error: could not add the source state to {}: {e}",
            path.display()
        );
    }
}

pub fn validate_run_id(id: &str) -> Result<(), String> {
    if id.is_empty() {
        return Err("invalid run id: must not be empty".to_string());
    }
    if id.len() > 128 {
        return Err(format!(
            "invalid run id {:?}: must be at most 128 characters",
            id
        ));
    }
    if id.starts_with('.')
        || id.starts_with('-')
        || id.ends_with('.')
        || id.contains("..")
        || id.ends_with(".lock")
        || !id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
    {
        return Err(format!(
            "invalid run id {:?}: only ASCII letters, digits, '.', '-' and '_' are allowed (no leading '.' or '-', no '..')",
            id
        ));
    }
    Ok(())
}

pub fn resolve_base_commit(start_dir: &Path, base: &str) -> Result<String, String> {
    let out = Command::new("git")
        .args(["rev-parse", "--verify", &format!("{base}^{{commit}}")])
        .current_dir(start_dir)
        .output();
    match out {
        Ok(o) if o.status.success() => Ok(String::from_utf8_lossy(&o.stdout).trim().to_string()),
        _ => Err(format!("base {base} is not a commit")),
    }
}

pub fn validate_request_id(id: &str) -> Result<(), String> {
    if id.is_empty() {
        return Err("invalid --request value: must not be empty".to_string());
    }
    if id.len() > 64 {
        return Err(format!(
            "invalid --request value {:?}: must be at most 64 characters",
            id
        ));
    }
    if !id
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        return Err(format!(
            "invalid --request value {:?}: only ASCII letters, digits, '-' and '_' are allowed",
            id
        ));
    }
    Ok(())
}

pub fn run_dispatch(args: &DispatchArgs) -> i32 {
    if let Err(e) = validate_run_id(&args.id) {
        eprintln!("error: {e}");
        return 2;
    }
    if let Some(ref req) = args.request {
        if let Err(e) = validate_request_id(req) {
            eprintln!("error: {e}");
            return 2;
        }
    }
    if let Some(ref surface) = args.surface {
        if let Err(e) = blyte_agent::sandbox::validate_surface_id(surface) {
            eprintln!("blyte: {e}");
            return 2;
        }
    }
    if let Some(ref started_by) = args.started_by {
        if let Err(e) = crate::surface_dir::validate_surface_name(started_by) {
            eprintln!("blyte: {e}");
            return 2;
        }
    }
    if let Ok(home) = crate::skill::home_dir() {
        if let Ok(Some(path)) = crate::skill::ensure_context_block(&home) {
            eprintln!(
                "blyte: added context rules to {} (they apply from the next Claude session)",
                path.display()
            );
        }
    }

    // 1. Root repository discovery and worktree preparation
    let out = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .output();
    let Ok(out) = out else {
        eprintln!("error: git not found");
        return 2;
    };
    if !out.status.success() {
        return crate::dispatch_in_place::run(args);
    }
    let start_dir = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
    let root = match crate::clean::find_repo_root() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };
    crate::registry::register(&root);

    let (repo_config, from_main) = match crate::config::load_with_fallback(&start_dir) {
        Ok(Some((cfg, from_main))) => (Some(cfg), from_main),
        Ok(None) => (None, false),
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };
    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
    let comments = match crate::config::comment_mode(dispatch_cfg.comments.as_deref()) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };

    let mut left_out: Vec<(String, String)> = Vec::new();
    let (gate, gate_source) = if args.research {
        research_gate()
    } else if let Some(ref g) = args.gate {
        (g.clone(), "flag")
    } else if let Some(ref g) = dispatch_cfg.gate {
        let toml_path = if from_main {
            root.join("blyte.toml")
        } else {
            start_dir.join("blyte.toml")
        };
        let drift = match load_gate_drift(&root, &toml_path, g) {
            Ok(v) => v,
            Err(e) => {
                eprintln!("error: {e}");
                return 2;
            }
        };
        left_out = drift.left_out;
        if let Some(warning) = drift.warning {
            eprintln!("{warning}");
        }
        if !left_out.is_empty() {
            let formatted: Vec<String> = left_out
                .iter()
                .map(|(cmd, reason)| format!("{cmd} ({reason})"))
                .collect();
            eprintln!(
                "blyte: the gate is partial; left out: {}",
                formatted.join("; ")
            );
        }
        let source = if from_main {
            "blyte.toml (main checkout)"
        } else {
            "blyte.toml"
        };
        (g.clone(), source)
    } else {
        eprintln!("no gate: pass --gate, or run blyte init to write blyte.toml");
        return 2;
    };

    let model = args.model.as_ref().or(dispatch_cfg.model.as_ref());
    let (max_seconds, max_turns) = if args.research {
        research_budgets(args)
    } else {
        (
            args.max_seconds
                .or(dispatch_cfg.max_seconds)
                .unwrap_or(3600),
            args.max_turns.or(dispatch_cfg.max_turns).unwrap_or(300),
        )
    };
    let max_cost = resolve_max_cost(args.max_cost_usd, dispatch_cfg.max_cost);
    let fold_budget = args.fold_budget.or(dispatch_cfg.fold_budget);
    let network = args
        .network
        .as_deref()
        .or(dispatch_cfg.network.as_deref())
        .unwrap_or("on");

    let wt_parent = root.join(".wt");
    let worktree_dir = wt_parent.join(&args.id);
    let branch = format!("wip/{}", args.id);
    let task_md_path = wt_parent.join(format!("{}.task.md", args.id));
    let summary_path = wt_parent.join(format!("{}.json", args.id));
    let fixround_path = crate::fix_round::record_path(&wt_parent, &args.id);

    let existing_fixround = if args.research {
        None
    } else {
        match crate::fix_round::load_record(&fixround_path) {
            Ok(rec) => rec,
            Err(e) => {
                eprintln!("error: {e}");
                return 2;
            }
        }
    };

    let resuming_fix_round = !args.research
        && !summary_path.exists()
        && matches!(
            existing_fixround,
            Some(crate::fix_round::FixRoundRecord::Started { .. })
        );

    let (task_content, recorded_task_file) = match load_task_text(
        args.task_file.as_deref(),
        args.plan.as_deref(),
        args.plan_task.as_deref(),
    ) {
        Ok(Some(pair)) => pair,
        Ok(None) if resuming_fix_round => {
            let start_path = wt_parent.join(format!("{}.start.json", args.id));
            match read_start_task_content(&root, &start_path) {
                Ok(content) => (content, None),
                Err(e) => {
                    eprintln!("error: {e}");
                    return 2;
                }
            }
        }
        Ok(None) => {
            eprintln!("error: give a task file, or --plan with --plan-task");
            if args.research {
                eprintln!(
                    "A research question needs these sections:\n\n{}",
                    crate::research_brief::TEMPLATE
                );
            }
            return 2;
        }
        Err(msg) => {
            eprintln!("{msg}");
            return 2;
        }
    };

    let brief_missing = args
        .research
        .then(|| crate::research_brief::missing_sections(&task_content));
    if let Some(ref missing) = brief_missing {
        if !args.no_brief_check {
            if !missing.is_empty() {
                eprintln!(
                    "blyte: warning: the research question has no section for: {}. Questions with all four run faster and fail less (the template: blyte dispatch {} --research); --no-brief-check hides this.",
                    missing.join(", "),
                    args.id
                );
            }
            let unverified = crate::research_brief::unverified_inputs(&task_content, &root);
            if !unverified.is_empty() {
                let paths: Vec<String> =
                    unverified.iter().map(|p| p.display().to_string()).collect();
                eprintln!(
                    "blyte: the question names a report that did not pass blyte's checks: {}. Use a verified report, or --no-brief-check to start anyway.",
                    paths.join(", ")
                );
                return 2;
            }
        }
    }

    let home = std::env::var_os("HOME").map(PathBuf::from);
    let main_checkout = root.clone();
    let config_allow_read = match crate::config::expand_allow_read(
        &dispatch_cfg.allow_read,
        home.as_deref(),
        &main_checkout,
    ) {
        Ok(paths) => paths,
        Err(e) => {
            eprintln!("{e}");
            return 2;
        }
    };

    if !args.no_path_check {
        let mut readable = vec![start_dir.clone(), root.clone()];
        readable.extend(config_allow_read.iter().cloned());
        readable.extend(args.allow_read.iter().cloned());
        let bad = unreadable_paths(&task_content, &readable);
        if !bad.is_empty() {
            let shown: Vec<String> = bad
                .iter()
                .take(5)
                .map(|p| p.display().to_string())
                .collect();
            eprintln!(
                "blyte: the task names paths this run cannot read: {}. Add --allow-read <dir> for each (or --no-path-check to start anyway).",
                shown.join(", ")
            );
            if args.research {
                return 2;
            }
        }
    }

    let task_file_recorded =
        recorded_task_file.unwrap_or_else(|| task_md_path.display().to_string());

    let start_path = wt_parent.join(format!("{}.start.json", args.id));
    if start_path.exists() {
        let start_str = match std::fs::read_to_string(&start_path) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("error reading {}: {e}", start_path.display());
                return 2;
            }
        };
        let start_val: serde_json::Value = match serde_json::from_str(&start_str) {
            Ok(v) => v,
            Err(e) => {
                eprintln!("error parsing {}: {e}", start_path.display());
                return 2;
            }
        };
        let Some(pid) = start_val.get("pid").and_then(|v| v.as_i64()) else {
            eprintln!("error: missing pid in {}", start_path.display());
            return 2;
        };
        let Some(started_at) = start_val.get("started_at").and_then(|v| v.as_u64()) else {
            eprintln!("error: missing started_at in {}", start_path.display());
            return 2;
        };
        if crate::clean::is_pid_alive(pid) {
            let finished_since_start = if summary_path.exists() {
                let meta = match std::fs::metadata(&summary_path) {
                    Ok(m) => m,
                    Err(e) => {
                        eprintln!("error reading metadata of {}: {e}", summary_path.display());
                        return 2;
                    }
                };
                let mtime = match meta.modified() {
                    Ok(t) => t,
                    Err(e) => {
                        eprintln!("error reading mtime of {}: {e}", summary_path.display());
                        return 2;
                    }
                };
                let mtime_secs = match mtime.duration_since(std::time::UNIX_EPOCH) {
                    Ok(d) => d.as_secs(),
                    Err(e) => {
                        eprintln!("error reading timestamp of {}: {e}", summary_path.display());
                        return 2;
                    }
                };
                mtime_secs >= started_at
            } else {
                false
            };
            if !finished_since_start {
                eprintln!(
                    "error: run {} is still running (pid {pid}). Wait for it to finish, or dispatch with a new ID.",
                    args.id
                );
                return 2;
            }
        }
    }

    let mut replaced_reason: Option<String> = None;
    let mut need_worktree_add = false;
    let base_commit: Option<String> = if !args.research {
        if let Some(crate::fix_round::FixRoundRecord::Started {
            pre_round_sha,
            fallbacks_sent,
            concerns_sent,
            started_at: round_started_at,
        }) = existing_fixround.clone()
        {
            if !summary_path.exists() {
                if !worktree_dir.exists() {
                    eprintln!("error: missing worktree {}", worktree_dir.display());
                    return 2;
                }
                let base_sha = match read_start_base_sha(&start_path) {
                    Ok(sha) => sha,
                    Err(e) => {
                        eprintln!("error: {e}");
                        return 2;
                    }
                };
                let report_path = wt_parent.join(format!("{}.report.json", args.id));
                let log_path = wt_parent.join(format!("{}.log", args.id));
                let fix_report_path = wt_parent.join(format!("{}.fix.report.json", args.id));
                let pass1 = match parse_pass_report(&report_path, &args.sandbox) {
                    Ok(r) => r,
                    Err(e) => {
                        eprintln!("error: {e}");
                        return 2;
                    }
                };
                let current_exe = match std::env::current_exe() {
                    Ok(p) => p,
                    Err(e) => {
                        eprintln!("error getting current executable: {e}");
                        return 2;
                    }
                };
                let configured_gate = gate;
                let passed_key = Some(crate::passed_trees::check_key(
                    &configured_gate,
                    &dispatch_cfg.env,
                ));
                let effective_gate = if comments == crate::config::CommentMode::Gate {
                    gate_with_comment_step(&configured_gate, &comment_step(&current_exe, &base_sha))
                } else {
                    configured_gate
                };
                let mut warnings = Vec::new();
                if let Err(err_msg) = git_reset_hard(&worktree_dir, &pre_round_sha) {
                    let summary = build_error_summary(
                        &args.id,
                        &worktree_dir,
                        branch,
                        err_msg,
                        pass1.sandbox,
                        &log_path,
                        &report_path,
                        gate_source,
                        warnings,
                    );
                    return finish_summary(&summary, &root);
                }
                let impl_cfg = ImplementerConfig {
                    current_exe: &current_exe,
                    worktree_dir: &worktree_dir,
                    root: &root,
                    id: &args.id,
                    gate: &effective_gate,
                    env: &dispatch_cfg.env,
                    model: model.map(String::as_str),
                    max_seconds,
                    max_turns,
                    max_cost,
                    fold_budget,
                    sandbox: &args.sandbox,
                    network,
                    config_allow_read: &config_allow_read,
                    cli_allow_read: &args.allow_read,
                    pass_env: &args.pass_env,
                    research: false,
                    no_claim_check: args.no_claim_check,
                    left_out: &left_out,
                    snapshot_dir: None,
                    snapshot_manifest: None,
                };
                let (fix_summary, round_report) = match execute_fix_round(
                    &root,
                    &start_path,
                    &impl_cfg,
                    &log_path,
                    &fix_report_path,
                    &fixround_path,
                    passed_key.as_deref(),
                    &task_content,
                    pre_round_sha,
                    fallbacks_sent,
                    concerns_sent,
                    round_started_at,
                    &mut warnings,
                ) {
                    Ok(res) => res,
                    Err(err_msg) => {
                        let summary = build_error_summary(
                            &args.id,
                            &worktree_dir,
                            branch,
                            err_msg,
                            pass1.sandbox,
                            &log_path,
                            &report_path,
                            gate_source,
                            warnings,
                        );
                        return finish_summary(&summary, &root);
                    }
                };
                let commits = git_commits_since(&worktree_dir, &base_sha);
                let changed_files = git_changed_files_since(&worktree_dir, &base_sha);
                let kept = fix_summary.kept;
                let summary = DispatchSummary {
                    id: args.id.clone(),
                    worktree: worktree_dir.display().to_string(),
                    branch,
                    outcome: "verified",
                    exit: exit_code("verified"),
                    error: pass1.error,
                    commits,
                    changed_files,
                    final_message: crate::fix_round::combined_final_message(
                        pass1.final_message,
                        round_report.final_message,
                        kept,
                    ),
                    turns: pass1.turns.saturating_add(round_report.turns),
                    gate_attempts: pass1.gate_attempts,
                    gate_failures: pass1.gate_failures,
                    cost_usd: crate::fix_round::sum_costs(pass1.cost_usd, round_report.cost_usd),
                    model: pass1.model.or(round_report.model),
                    seconds: pass1.seconds.saturating_add(round_report.seconds),
                    sandbox: pass1.sandbox,
                    log: log_path.display().to_string(),
                    report: report_path.display().to_string(),
                    gate_source,
                    research_report: None,
                    base_check_seconds: pass1.base_check_seconds,
                    warnings,
                    fix_round: Some(fix_summary),
                };
                return finish_summary(&summary, &root);
            }
        }

        let resolved_base = match resolve_base_commit(&start_dir, &args.base) {
            Ok(sha) => sha,
            Err(e) => {
                eprintln!("error: {e}");
                return 2;
            }
        };

        let branch_ref = format!("refs/heads/{branch}");
        let branch_out = Command::new("git")
            .args(["show-ref", "--verify", "--quiet", &branch_ref])
            .current_dir(&root)
            .output();
        let mut branch_exists = match branch_out {
            Ok(o) if o.status.success() => true,
            Ok(o) if o.status.code() == Some(1) => false,
            Ok(o) => {
                eprintln!(
                    "error: git show-ref --verify --quiet {branch_ref}: {}",
                    String::from_utf8_lossy(&o.stderr).trim()
                );
                return 2;
            }
            Err(e) => {
                eprintln!("error: git show-ref --verify --quiet {branch_ref}: {e}");
                return 2;
            }
        };

        if worktree_dir.exists() || branch_exists {
            match crate::clean::remove_finished_run(&root, &args.id) {
                Ok(Some(reason)) => {
                    replaced_reason = Some(reason);
                    branch_exists = false;
                }
                Ok(None) => {}
                Err(e) => {
                    eprintln!("error: could not remove the earlier run {}: {e}", args.id);
                    return 2;
                }
            }
        }

        if !worktree_dir.exists() {
            if branch_exists {
                eprintln!("{}", branch_exists_message(&root, &branch, &args.id));
                return 2;
            }
            need_worktree_add = true;
        } else {
            let wt_head = match Command::new("git")
                .args([
                    "-C",
                    worktree_dir.to_str().unwrap(),
                    "rev-parse",
                    "--verify",
                    "HEAD^{commit}",
                ])
                .output()
            {
                Ok(o) if o.status.success() => {
                    String::from_utf8_lossy(&o.stdout).trim().to_string()
                }
                Ok(o) => {
                    eprintln!(
                        "error: git -C {} rev-parse HEAD failed: {}",
                        worktree_dir.display(),
                        String::from_utf8_lossy(&o.stderr).trim()
                    );
                    return 2;
                }
                Err(e) => {
                    eprintln!("error: failed to execute git rev-parse: {e}");
                    return 2;
                }
            };
            let ancestor_out = Command::new("git")
                .args(["merge-base", "--is-ancestor", &resolved_base, &wt_head])
                .current_dir(&root)
                .output();
            match ancestor_out {
                Ok(o) if o.status.success() => {}
                Ok(o) if o.status.code() == Some(1) => {
                    let short_wt_head = &wt_head[..wt_head.len().min(7)];
                    let short_base = &resolved_base[..resolved_base.len().min(7)];
                    eprintln!(
                        "error: .wt/{id} is from an earlier run based on {short_wt_head}, which does not contain {short_base} ({base_name}). Run `blyte clean`, remove it with `git worktree remove .wt/{id}` and `git branch -D wip/{id}` if it is not needed, or dispatch with a new ID.",
                        id = args.id,
                        base_name = args.base,
                    );
                    return 2;
                }
                Ok(o) => {
                    eprintln!(
                        "error: git merge-base --is-ancestor failed: {}",
                        String::from_utf8_lossy(&o.stderr).trim()
                    );
                    return 2;
                }
                Err(e) => {
                    eprintln!("error: failed to execute git merge-base --is-ancestor: {e}");
                    return 2;
                }
            }
        }
        Some(resolved_base)
    } else if worktree_dir.exists() {
        eprintln!("error: {} already exists", worktree_dir.display());
        return 2;
    } else {
        None
    };

    let replaced_earlier_run = replaced_reason.is_some();
    let fix_round_already_done = !replaced_earlier_run
        && matches!(
            existing_fixround,
            Some(crate::fix_round::FixRoundRecord::Done { .. })
        );

    let archive_rel = match archive_run_records(&root, &args.id) {
        Ok(rel) => rel,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };
    if let Some(reason) = replaced_reason {
        if let Some(ref rel) = archive_rel {
            eprintln!(
                "dispatch: replaced the earlier run {} ({reason}); its records are in {rel}/",
                args.id
            );
        } else {
            eprintln!("dispatch: replaced the earlier run {} ({reason})", args.id);
        }
    }

    let started_at = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let mut tags = args.tags.clone();
    if args.research {
        tags.push("research".to_string());
    }
    let session = crate::usage_log::session_from(
        std::env::var("BLYTE_SESSION").ok(),
        std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
    );
    let mut initial_start = serde_json::json!({
        "id": args.id,
        "pid": std::process::id(),
        "started_at": started_at,
        "starting": true,
        "tags": tags,
        "plan": args.plan,
        "plan_task": args.plan_task,
        "request": args.request,
        "surface": args.surface,
        "base": args.base,
    });
    if let Some(ref started_by) = args.started_by {
        initial_start["started_by"] = serde_json::json!(started_by);
    }
    if let Some(ref s) = session {
        initial_start["session"] = serde_json::json!(s);
    }
    if let Some(ref missing) = brief_missing {
        initial_start["research"] = serde_json::json!(true);
        initial_start["brief_missing"] = serde_json::json!(missing);
    }
    if let Err(err) = std::fs::create_dir_all(&wt_parent)
        .and_then(|()| write_start_record(&start_path, &initial_start))
    {
        eprintln!(
            "error: could not write the start record {}: {err}",
            start_path.display()
        );
        return 2;
    }
    let mut start_guard = StartRecordGuard {
        path: start_path.clone(),
        armed: true,
    };

    if !args.research {
        crate::clean::spawn_background_clean(&root, Some(&args.id));
    }

    if args.research {
        if let Err(e) = create_research_scratch_dir(&worktree_dir) {
            eprintln!("{e}");
            return 2;
        }
    } else if need_worktree_add {
        let base_ref = base_commit.as_deref().unwrap();
        let add_out = Command::new("git")
            .args([
                "worktree",
                "add",
                "-b",
                &branch,
                worktree_dir.to_str().unwrap(),
                base_ref,
            ])
            .current_dir(&root)
            .output();
        match add_out {
            Ok(o) if o.status.success() => {}
            Ok(o) => {
                eprintln!(
                    "error: git worktree add failed: {}",
                    String::from_utf8_lossy(&o.stderr)
                );
                return 2;
            }
            Err(e) => {
                eprintln!("error: failed to execute git worktree add: {e}");
                return 2;
            }
        }
    }

    // 2. Ensure .wt/ is in info/exclude
    let common_dir_raw = Command::new("git")
        .args(["rev-parse", "--git-common-dir"])
        .current_dir(&root)
        .output();
    let common_dir = if let Ok(out) = common_dir_raw {
        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
        if p.is_absolute() {
            p
        } else {
            root.join(p)
        }
    } else {
        root.join(".git")
    };

    let exclude_path = common_dir.join("info").join("exclude");
    if let Some(parent) = exclude_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
    if !content.lines().any(|l| l.trim() == ".wt/") {
        let mut new_content = content;
        if !new_content.is_empty() && !new_content.ends_with('\n') {
            new_content.push('\n');
        }
        new_content.push_str(".wt/\n");
        let _ = std::fs::write(&exclude_path, new_content);
    }

    // 3. Record base_sha
    let base_out = Command::new("git")
        .args(["-C", worktree_dir.to_str().unwrap(), "rev-parse", "HEAD"])
        .output();
    let base_sha = match base_out {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
        _ => {
            eprintln!("error: could not resolve HEAD in worktree");
            return 2;
        }
    };

    if !args.research {
        if let Some(ref setup_cmd) = dispatch_cfg.setup {
            let first_line = setup_cmd.lines().next().unwrap_or("");
            eprintln!("setup: {first_line}");
            let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
            let setup_log_path = wt_parent.join(format!("{}.setup.log", args.id));
            if let Err(msg) = crate::setup::run_setup(
                setup_cmd,
                &worktree_dir,
                &main_checkout,
                &dispatch_cfg.env,
                &setup_log_path,
                crate::setup::SETUP_TIMEOUT,
            ) {
                let outcome = "blocked";
                let exit = exit_code(outcome);
                let first_line_err = msg.lines().next().unwrap_or("").to_string();
                let summary = DispatchSummary {
                    id: args.id.clone(),
                    worktree: worktree_dir.display().to_string(),
                    branch: branch.clone(),
                    outcome,
                    exit,
                    error: Some(first_line_err),
                    commits: Vec::new(),
                    changed_files: Vec::new(),
                    final_message: Some(msg),
                    turns: 0,
                    gate_attempts: 0,
                    gate_failures: Vec::new(),
                    cost_usd: None,
                    model: None,
                    seconds: 0,
                    sandbox: args.sandbox.clone(),
                    log: if setup_log_path.is_file() {
                        setup_log_path.display().to_string()
                    } else {
                        String::new()
                    },
                    report: "".to_string(),
                    gate_source,
                    research_report: None,
                    base_check_seconds: None,
                    warnings: Vec::new(),
                    fix_round: None,
                };
                return finish_summary(&summary, &root);
            }
        }
    }

    // 4. Write task file and spawn child process
    let _ = std::fs::create_dir_all(&wt_parent);
    if let Err(e) = std::fs::write(&task_md_path, &task_content) {
        eprintln!("error writing task file {}: {e}", task_md_path.display());
        return 2;
    }

    let log_path = wt_parent.join(format!("{}.log", args.id));
    let report_path = wt_parent.join(format!("{}.report.json", args.id));
    let research_report_path = wt_parent.join(format!("{}.report.md", args.id));

    let configured_gate = gate;
    let passed_key = (!args.research)
        .then(|| crate::passed_trees::check_key(&configured_gate, &dispatch_cfg.env));
    let (base_check_decision, base_tree) = match decide_base_check(
        &root,
        &worktree_dir,
        &base_sha,
        &configured_gate,
        &dispatch_cfg.env,
        args.research,
        args.no_base_check,
        dispatch_cfg.base_check,
        crate::passed_trees::now_secs(),
    ) {
        Ok(res) => res,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };
    if base_check_decision == BaseCheckDecision::AlreadyPassed {
        eprintln!("base check: this commit's content already passed");
    }

    let current_exe = match std::env::current_exe() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("error getting current executable: {e}");
            return 2;
        }
    };

    let gate = if !args.research && comments == crate::config::CommentMode::Gate {
        gate_with_comment_step(&configured_gate, &comment_step(&current_exe, &base_sha))
    } else {
        configured_gate
    };

    let mut base_wt_guard: Option<BaseWorktreeGuard> = None;
    let base_check_dir = if !args.research && base_check_decision == BaseCheckDecision::Run {
        let base_wt_dir = wt_parent.join(format!("{}.base", args.id));
        match BaseWorktreeGuard::create(&root, base_wt_dir.clone(), &base_sha) {
            Ok(guard) => {
                base_wt_guard = Some(guard);
                Some(base_wt_dir)
            }
            Err(e) => {
                eprintln!("error creating base check worktree: {e}");
                return 2;
            }
        }
    } else {
        None
    };

    let research_sources = args
        .research
        .then(|| research_source_block(&root, &config_allow_read, &args.allow_read));
    let task_prompt = if let Some(block) = &research_sources {
        wrap_research(&format!("{block}\n\n{task_content}"), &root)
    } else {
        let mut prompt = wrap_task(&task_content);
        if let Some(qs) = quick_steps(&gate) {
            prompt.push_str("\n\n");
            prompt.push_str(&qs);
        }
        prompt
    };

    let impl_cfg = ImplementerConfig {
        current_exe: &current_exe,
        worktree_dir: &worktree_dir,
        root: &root,
        id: &args.id,
        gate: &gate,
        env: &dispatch_cfg.env,
        model: model.map(String::as_str),
        max_seconds,
        max_turns,
        max_cost,
        fold_budget,
        sandbox: &args.sandbox,
        network,
        config_allow_read: &config_allow_read,
        cli_allow_read: &args.allow_read,
        pass_env: &args.pass_env,
        research: args.research,
        no_claim_check: args.no_claim_check,
        left_out: &left_out,
        snapshot_dir: None,
        snapshot_manifest: None,
    };

    let comments_str = if args.research {
        "off"
    } else {
        match comments {
            crate::config::CommentMode::Gate => "gate",
            crate::config::CommentMode::Review => "review",
            crate::config::CommentMode::Off => "off",
        }
    };
    let env_names: Vec<&str> = dispatch_cfg.env.keys().map(String::as_str).collect();
    if let Err(e) = run_implementer_pass(
        &impl_cfg,
        &log_path,
        None,
        &report_path,
        &task_prompt,
        base_check_dir.as_deref(),
        |pid| {
            start_guard.armed = false;
            let mut start_json = serde_json::json!({
                "id": args.id,
                "pid": pid,
                "started_at": started_at,
                "task_file": task_file_recorded,
                "gate": gate,
                "tags": tags,
                "env": env_names,
                "max_turns": max_turns,
                "max_seconds": max_seconds,
                "plan": args.plan,
                "plan_task": args.plan_task,
                "request": args.request,
                "surface": args.surface,
                "base": args.base,
                "base_sha": base_commit,
                "base_check": base_check_decision.as_json(),
                "comments": comments_str,
            });
            if let Some(ref started_by) = args.started_by {
                start_json["started_by"] = serde_json::json!(started_by);
            }
            if let Some(ref session) = session {
                start_json["session"] = serde_json::json!(session);
            }
            if let Some(ref missing) = brief_missing {
                start_json["research"] = serde_json::json!(true);
                start_json["brief_missing"] = serde_json::json!(missing);
            }
            if !left_out.is_empty() {
                start_json["gate_left_out"] = serde_json::json!(left_out
                    .iter()
                    .map(|(command, reason)| serde_json::json!({
                        "command": command,
                        "reason": reason,
                    }))
                    .collect::<Vec<_>>());
            }
            if let Err(err) = write_start_record(&start_path, &start_json) {
                eprintln!(
                    "error: could not write the start record {}: {err}",
                    start_path.display()
                );
            }
        },
    ) {
        eprintln!("{e}");
        return 2;
    }
    drop(base_wt_guard);

    let scratch_report = worktree_dir.join("report.md");
    if args.research {
        let is_non_empty = std::fs::metadata(&scratch_report)
            .map(|m| m.len() > 0)
            .unwrap_or(false);
        if is_non_empty {
            if let Err(err_msg) = copy_research_reports(
                &scratch_report,
                &research_report_path,
                args.report_to.as_deref(),
                research_sources.as_deref(),
            ) {
                if research_report_path.exists() {
                    if let Err(err) =
                        crate::provenance::mark_if_unverified(&research_report_path, "error", None)
                    {
                        eprintln!(
                            "error: could not mark {} as not verified: {err}",
                            research_report_path.display()
                        );
                    }
                }
                let summary = build_error_summary(
                    &args.id,
                    &worktree_dir,
                    branch,
                    err_msg,
                    args.sandbox.clone(),
                    &log_path,
                    &report_path,
                    gate_source,
                    Vec::new(),
                );
                return finish_summary(&summary, &root);
            }
        }
    }

    // 5. Read report, commits and changed files
    let mut commits = git_commits_since(&worktree_dir, &base_sha);
    let mut changed_files = git_changed_files_since(&worktree_dir, &base_sha);

    let pass1 = match parse_pass_report(&report_path, &args.sandbox) {
        Ok(r) => r,
        Err(err_msg) => pass_report_from_error(err_msg, &args.sandbox),
    };

    let outcome = if args.research {
        research_outcome(&pass1.report_outcome)
    } else {
        dispatch_outcome(&pass1.report_outcome, commits.len())
    };
    let exit = exit_code(outcome);

    if args.research {
        if research_report_path.exists() {
            if let Err(err) = crate::provenance::mark_if_unverified(
                &research_report_path,
                outcome,
                pass1.report_turns,
            ) {
                eprintln!(
                    "error: could not mark {} as not verified: {err}",
                    research_report_path.display()
                );
            }
        }
        if let Some(ref report_to) = args.report_to {
            if report_to.exists() {
                if let Err(err) =
                    crate::provenance::mark_if_unverified(report_to, outcome, pass1.report_turns)
                {
                    eprintln!(
                        "error: could not mark {} as not verified: {err}",
                        report_to.display()
                    );
                }
            }
        }
    }

    let research_report = if args.research && research_report_path.exists() {
        Some(research_report_path.display().to_string())
    } else {
        None
    };

    let mut warnings = record_passed_after_run(
        &root,
        &worktree_dir,
        args.research,
        base_check_decision,
        base_tree.as_deref(),
        passed_key.as_deref(),
        outcome,
        pass1.base_check_passed,
    );
    for warning in &warnings {
        eprintln!("warning: {warning}");
    }

    let mut final_message = pass1.final_message;
    let mut turns = pass1.turns;
    let mut cost_usd = pass1.cost_usd;
    let mut seconds = pass1.seconds;
    let mut summary_model = pass1.model;
    let mut fix_round_summary: Option<crate::fix_round::FixRoundSummary> = None;

    if outcome == "verified" && !args.research {
        let first_review = match crate::queue_actions::evaluate_verified_run(&root, &args.id) {
            Ok(mr) => mr,
            Err(err) => {
                eprintln!(
                    "warning: post-dispatch review check failed for {}: {err}",
                    args.id
                );
                None
            }
        };

        if !fix_round_already_done
            && crate::fix_round::should_run(
                args.research,
                outcome,
                dispatch_cfg.fix_round,
                first_review.as_ref(),
            )
        {
            let review_ref = first_review.as_ref().unwrap();
            let pre_round_sha = match git_head_sha(&worktree_dir) {
                Ok(sha) => sha,
                Err(err_msg) => {
                    let summary = build_error_summary(
                        &args.id,
                        &worktree_dir,
                        branch,
                        err_msg,
                        pass1.sandbox,
                        &log_path,
                        &report_path,
                        gate_source,
                        warnings,
                    );
                    return finish_summary(&summary, &root);
                }
            };
            let fallbacks_sent = if crate::fix_round::confirmed_count(review_ref) > 0 {
                match crate::fix_round::collect_confirmed_fallbacks(
                    &root,
                    &args.id,
                    &worktree_dir,
                    review_ref,
                ) {
                    Ok(fbs) => fbs,
                    Err(err_msg) => {
                        let summary = build_error_summary(
                            &args.id,
                            &worktree_dir,
                            branch,
                            err_msg,
                            pass1.sandbox,
                            &log_path,
                            &report_path,
                            gate_source,
                            warnings,
                        );
                        return finish_summary(&summary, &root);
                    }
                }
            } else {
                Vec::new()
            };
            let concerns_sent = review_ref.concerns.clone();
            let round_started_at =
                match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
                    Ok(d) => d.as_secs(),
                    Err(e) => {
                        let summary = build_error_summary(
                            &args.id,
                            &worktree_dir,
                            branch,
                            format!("system clock before UNIX_EPOCH: {e}"),
                            pass1.sandbox,
                            &log_path,
                            &report_path,
                            gate_source,
                            warnings,
                        );
                        return finish_summary(&summary, &root);
                    }
                };
            let started_record = crate::fix_round::FixRoundRecord::Started {
                pre_round_sha: pre_round_sha.clone(),
                fallbacks_sent: fallbacks_sent.clone(),
                concerns_sent: concerns_sent.clone(),
                started_at: round_started_at,
            };
            if let Err(err_msg) = crate::fix_round::write_record(&fixround_path, &started_record) {
                let summary = build_error_summary(
                    &args.id,
                    &worktree_dir,
                    branch,
                    err_msg,
                    pass1.sandbox,
                    &log_path,
                    &report_path,
                    gate_source,
                    warnings,
                );
                return finish_summary(&summary, &root);
            }

            let fix_report_path = wt_parent.join(format!("{}.fix.report.json", args.id));
            match execute_fix_round(
                &root,
                &start_path,
                &impl_cfg,
                &log_path,
                &fix_report_path,
                &fixround_path,
                passed_key.as_deref(),
                &task_content,
                pre_round_sha,
                fallbacks_sent,
                concerns_sent,
                round_started_at,
                &mut warnings,
            ) {
                Ok((fix_sum, round_report)) => {
                    commits = git_commits_since(&worktree_dir, &base_sha);
                    changed_files = git_changed_files_since(&worktree_dir, &base_sha);
                    turns = turns.saturating_add(round_report.turns);
                    cost_usd = crate::fix_round::sum_costs(cost_usd, round_report.cost_usd);
                    seconds = seconds.saturating_add(round_report.seconds);
                    summary_model = summary_model.or(round_report.model);
                    final_message = crate::fix_round::combined_final_message(
                        final_message,
                        round_report.final_message,
                        fix_sum.kept,
                    );
                    fix_round_summary = Some(fix_sum);
                }
                Err(err_msg) => {
                    let summary = build_error_summary(
                        &args.id,
                        &worktree_dir,
                        branch,
                        err_msg,
                        pass1.sandbox,
                        &log_path,
                        &report_path,
                        gate_source,
                        warnings,
                    );
                    return finish_summary(&summary, &root);
                }
            }
        }
    }

    // 6. Print JSON summary
    let summary = DispatchSummary {
        id: args.id.clone(),
        worktree: worktree_dir.display().to_string(),
        branch,
        outcome,
        exit,
        error: pass1.error,
        commits,
        changed_files,
        final_message,
        turns,
        gate_attempts: pass1.gate_attempts,
        gate_failures: pass1.gate_failures,
        cost_usd,
        model: summary_model,
        seconds,
        sandbox: pass1.sandbox,
        log: log_path.display().to_string(),
        report: report_path.display().to_string(),
        gate_source,
        research_report,
        base_check_seconds: pass1.base_check_seconds,
        warnings,
        fix_round: fix_round_summary,
    };

    finish_summary(&summary, &root)
}

pub fn run_review(args: &ReviewArgs) -> i32 {
    if let Ok(cwd) = std::env::current_dir() {
        if let Ok(out) = Command::new("git")
            .current_dir(&cwd)
            .args(["rev-parse", "--show-toplevel"])
            .output()
        {
            if !out.status.success() {
                return crate::in_place_review::review(args);
            }
        }
    }

    let root = match crate::clean::find_repo_root() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };

    if args.notes.is_some() && args.verdict.is_none() {
        eprintln!("error: --notes requires --verdict");
        return 2;
    }

    if let Some(v) = args.verdict {
        let ts = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        if let Err(e) = crate::queue_actions::record_verdict(
            &root,
            &args.id,
            v,
            args.notes.as_deref().unwrap_or(""),
            ts,
        ) {
            eprintln!("{e}");
            return 2;
        }
        let notify_outcome = crate::surface_notify::notify_runs_changed(&root, &args.id);
        crate::surface_notify::report(&notify_outcome, &mut std::io::stderr());
        println!("recorded verdict {} for {}", v.as_str(), args.id);
        return 0;
    }

    let mut data = match crate::queue_actions::compute_review(&root, &args.id, args.diff) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };

    let stored_model_review = if args.model_review {
        None
    } else {
        match crate::queue_actions::read_stored_model_review(&root, &args.id) {
            Ok(mr) => mr,
            Err(e) => {
                eprintln!("error: {e}");
                return 2;
            }
        }
    };
    if !args.model_review {
        data.checks
            .flags
            .extend(crate::fallback_check::flags_for_review(
                &data.fallbacks,
                stored_model_review.as_ref(),
            ));
        if let Some(ref mr) = stored_model_review {
            if let Some(flag) = mr.flag() {
                if !data
                    .checks
                    .flags
                    .iter()
                    .any(|f| f.starts_with("model review"))
                {
                    data.checks.flags.push(flag);
                }
            }
        }
    }

    if !args.model_review {
        if let Err(e) = crate::queue_actions::write_checks_file(
            &root,
            &args.id,
            &data.checks.flags,
            &data.fallbacks,
            stored_model_review.as_ref(),
        ) {
            eprintln!("{e}");
            return 2;
        }
    }

    let crate::queue_actions::ReviewComputation {
        wt,
        wt_exists,
        is_research: _,
        base,
        task_text: _,
        changed_files: _,
        commits_out,
        files_out,
        tree_out,
        diff_out,
        hcmds,
        reads,
        report_val,
        quote_problems,
        claim_check,
        claim_check_skipped,
        mut checks,
        fallbacks,
    } = data;

    println!("== checks");
    if checks.flags.is_empty() {
        println!("nothing flagged");
    } else {
        for flag in &checks.flags {
            println!("! {flag}");
        }
    }

    println!("== commits");
    if !wt_exists {
        println!("(worktree removed)");
    } else if !commits_out.is_empty() {
        println!("{commits_out}");
    }
    println!("== files");
    if !wt_exists {
        println!("(worktree removed)");
    } else if !files_out.is_empty() {
        println!("{files_out}");
    }
    println!("== tree");
    if !wt_exists {
        println!("(worktree removed)");
    } else if tree_out.is_empty() {
        println!("(clean)");
    } else {
        println!("{tree_out}");
    }
    println!("== report");
    if let Some(ref v) = report_val {
        if let Some(outcome) = v.get("outcome").and_then(|x| x.as_str()) {
            println!("outcome: {outcome}");
        }
        let final_message = v.get("final_message").and_then(|x| x.as_str());
        if let Some(err) = v
            .get("error")
            .and_then(|x| x.as_str())
            .filter(|s| !s.trim().is_empty())
        {
            if !final_message.is_some_and(|m| m.contains(err)) {
                println!("error: {err}");
            }
        }
        if let Some(turns) = v.get("turns").and_then(|x| x.as_u64()) {
            println!("turns: {turns}");
        }
        if let Some(cost) = v.get("cost_usd").and_then(|x| x.as_f64()) {
            println!("cost_usd: {cost}");
        }
        if let Some(msg) = final_message {
            println!("final_message: {msg}");
        }
        if let Some(ref problems) = quote_problems {
            if problems.is_empty() {
                println!("quote check: passed");
            } else {
                println!(
                    "quote check: FAILED, {} problems (the report's quotes do not match the code)",
                    problems.len()
                );
                for p in problems.iter().take(5) {
                    let cut: String = p.chars().take(200).collect();
                    println!("  {cut}");
                }
            }
        }
        if let Some(ref cc) = claim_check {
            println!(
                "claim check: {} checked, {} contradicted, {} not enough evidence, {} parse errors, {} unchecked",
                cc.checked,
                cc.contradicted.len(),
                cc.not_enough_evidence,
                cc.parse_errors,
                cc.unchecked
            );
            for f in cc.contradicted.iter().take(5) {
                let cut: String = f.text.chars().take(200).collect();
                println!("  report.md:{}: {cut}", f.line);
                println!("    {}", f.reason);
            }
        }
        if let Some(ref skipped) = claim_check_skipped {
            println!("claim check skipped: {skipped}");
        }
    }

    if let Some(ref v) = report_val {
        if let Some(failures) = v.get("gate_failures").and_then(|x| x.as_array()) {
            let entries: Vec<&str> = failures.iter().filter_map(|x| x.as_str()).collect();
            if let Some(last) = entries.last() {
                println!("== check failures");
                if entries.len() > 1 {
                    println!("({} failed attempts; the last one)", entries.len());
                }
                println!("{last}");
            }
        }
    }

    let research_report_file = root.join(".wt").join(format!("{}.report.md", args.id));
    if research_report_file.exists() {
        println!("== research report");
        println!("{}", research_report_file.display());
        if let Ok(content) = std::fs::read_to_string(&research_report_file) {
            for line in content.lines().take(40) {
                println!("{line}");
            }
        }
    }

    if !hcmds.is_empty() {
        println!("== host commands (may have changed things outside the worktree)");
        for cmd in hcmds {
            println!("{cmd}");
        }
    }
    if !reads.is_empty() {
        println!("== reads outside the repository");
        for cmd in reads {
            println!("{cmd}");
        }
    }

    if args.diff {
        println!("== diff");
        if !wt_exists {
            println!("(worktree removed)");
        } else if !diff_out.is_empty() {
            println!("{diff_out}");
        }
    }

    if args.model_review && wt_exists {
        let mr = crate::model_review::run(&root, &args.id, &base, &wt);
        crate::model_review::print_result(&mr);
        checks.flags.extend(crate::fallback_check::flags_for_review(
            &fallbacks,
            Some(&mr),
        ));
        if let Some(flag) = mr.flag() {
            checks.flags.push(flag);
        }
        if let Err(e) = crate::queue_actions::write_checks_file(
            &root,
            &args.id,
            &checks.flags,
            &fallbacks,
            Some(&mr),
        ) {
            eprintln!("{e}");
            return 2;
        }
    } else if args.model_review {
        checks
            .flags
            .extend(crate::fallback_check::flags_for_review(&fallbacks, None));
        if let Err(e) = crate::queue_actions::write_checks_file(
            &root,
            &args.id,
            &checks.flags,
            &fallbacks,
            None,
        ) {
            eprintln!("{e}");
            return 2;
        }
    } else if let Some(ref mr) = stored_model_review {
        crate::model_review::print_result(mr);
    }

    0
}

const OUTSIDE_PATHS: &[&str] = &[
    "~/",
    "$HOME",
    "/Users/",
    "/home/",
    "/private/",
    "/var/",
    "/etc/",
    "/opt/",
    "/usr/",
];

const CHANGE_WORDS: &[&str] = &[
    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", "tee", "ln",
];

fn contains_word(cmd: &str, word: &str) -> bool {
    let mut start = 0;
    while let Some(pos) = cmd[start..].find(word) {
        let abs_pos = start + pos;
        let before_ok = if abs_pos == 0 {
            true
        } else {
            let prev = cmd[..abs_pos].chars().next_back().unwrap();
            !prev.is_alphanumeric() && prev != '_' && prev != '-'
        };
        let after_pos = abs_pos + word.len();
        let after_ok = if after_pos >= cmd.len() {
            true
        } else {
            let next = cmd[after_pos..].chars().next().unwrap();
            !next.is_alphanumeric() && next != '_' && next != '-'
        };
        if before_ok && after_ok {
            return true;
        }
        start = abs_pos + word.len();
    }
    false
}

fn has_non_dev_null_redirect(cmd: &str) -> bool {
    let chars: Vec<char> = cmd.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '>' {
            while i < chars.len() && chars[i] == '>' {
                i += 1;
            }
            if i < chars.len() && chars[i] == '|' {
                i += 1;
            }
            while i < chars.len() && chars[i].is_whitespace() {
                i += 1;
            }
            if i >= chars.len() {
                break;
            }
            if chars[i] == '&'
                && i + 1 < chars.len()
                && (chars[i + 1].is_ascii_digit() || chars[i + 1] == '-')
            {
                i += 1;
                continue;
            }
            let target_start = i;
            while i < chars.len()
                && !chars[i].is_whitespace()
                && chars[i] != ';'
                && chars[i] != '|'
                && chars[i] != '&'
                && chars[i] != ')'
            {
                i += 1;
            }
            let target: String = chars[target_start..i].iter().collect();
            let target = target.trim_matches(|c| c == '\'' || c == '"');
            if !target.is_empty() && target != "/dev/null" {
                return true;
            }
        } else {
            i += 1;
        }
    }
    false
}

fn changes_something(cmd: &str) -> bool {
    for &word in CHANGE_WORDS {
        if contains_word(cmd, word) {
            return true;
        }
    }
    has_non_dev_null_redirect(cmd)
}

fn is_host_command(cmd: &str) -> bool {
    if cmd.contains("git push")
        || cmd.contains("sudo ")
        || cmd.contains("cache clean")
        || cmd.contains("cache prune")
        || cmd.contains("brew ")
    {
        return true;
    }

    let names_outside = OUTSIDE_PATHS.iter().any(|path| cmd.contains(path));
    names_outside && changes_something(cmd)
}

pub(crate) fn bash_commands(log: &str) -> Vec<String> {
    let cleaned = strip_ansi(log);
    let mut result = Vec::new();
    for line in cleaned.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("● bash ") {
            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
                let cmd = cmd.trim();
                if !cmd.is_empty() {
                    result.push(cmd.to_string());
                }
            }
        }
    }
    result
}

pub fn host_commands(log: &str) -> Vec<String> {
    let mut result = Vec::new();
    for cmd in bash_commands(log) {
        if is_host_command(&cmd) && !result.iter().any(|c| c == &cmd) {
            result.push(cmd);
            if result.len() == 20 {
                break;
            }
        }
    }
    result
}

const TERMINAL_READS: &[&str] = &[
    "herdr pane read",
    "tmux capture-pane",
    "screen -X hardcopy",
    "zellij action dump-screen",
    "wezterm cli get-text",
];

const TOOL_CACHES: &[&str] = &[
    ".cargo",
    ".rustup",
    ".cache",
    ".npm",
    ".local",
    "Library/Caches",
    ".gradle",
    ".m2",
    "go",
];

fn normalize_path(path: &Path) -> PathBuf {
    use std::path::Component;
    let mut out = PathBuf::new();
    for comp in path.components() {
        match comp {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            _ => out.push(comp),
        }
    }
    out
}

fn is_outside_read(cmd: &str, allowed: &[PathBuf], home: &Path, tool_caches: &[PathBuf]) -> bool {
    if TERMINAL_READS.iter().any(|pattern| cmd.contains(pattern)) {
        return true;
    }

    for raw_word in cmd.split_whitespace() {
        let word = raw_word.trim_end_matches(&[':', ',', ')', '\'', '"'][..]);
        let raw_path = if let Some(suffix) = word.strip_prefix("~/") {
            Some(home.join(suffix))
        } else if let Some(suffix) = word.strip_prefix("$HOME/") {
            Some(home.join(suffix))
        } else if word.starts_with('/') {
            Some(PathBuf::from(word))
        } else {
            None
        };

        if let Some(path) = raw_path {
            let norm_path = normalize_path(&path);
            if !norm_path.starts_with(home) {
                continue;
            }
            let under_allowed = allowed.iter().any(|a| norm_path.starts_with(a));
            if under_allowed {
                continue;
            }
            let under_cache = tool_caches.iter().any(|c| norm_path.starts_with(c));
            if under_cache {
                continue;
            }
            return true;
        }
    }

    false
}

pub fn outside_reads(log: &str, allowed: &[PathBuf], home: &Path) -> Vec<String> {
    let host_cmds = host_commands(log);
    let norm_home = normalize_path(home);
    let norm_allowed: Vec<PathBuf> = allowed.iter().map(|p| normalize_path(p)).collect();
    let cache_dirs: Vec<PathBuf> = TOOL_CACHES
        .iter()
        .map(|c| normalize_path(&norm_home.join(c)))
        .collect();

    let cleaned = strip_ansi(log);
    let mut result = Vec::new();
    for line in cleaned.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("● bash ") {
            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
                let cmd = cmd.trim();
                if host_cmds.iter().any(|c| c == cmd) {
                    continue;
                }
                if is_outside_read(cmd, &norm_allowed, &norm_home, &cache_dirs)
                    && !result.iter().any(|c| c == cmd)
                {
                    result.push(cmd.to_string());
                    if result.len() == 20 {
                        break;
                    }
                }
            }
        }
    }
    result
}

fn strip_ansi(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' && chars.peek() == Some(&'[') {
            chars.next();
            while let Some(&next_c) = chars.peek() {
                chars.next();
                if ('\x40'..='\x7e').contains(&next_c) {
                    break;
                }
                if next_c == '\n' || next_c == '\x1b' {
                    out.push(next_c);
                    break;
                }
            }
            continue;
        }
        out.push(c);
    }
    out
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LogProgress {
    pub turn: u32,
    pub last_tool: Option<String>,
    pub gate_attempts: u32,
    pub gate_passed: bool,
}

pub fn parse_log(log: &str) -> LogProgress {
    let cleaned = strip_ansi(log);
    let mut turn: u32 = 0;
    let mut last_tool: Option<String> = None;
    let mut gate_attempts: u32 = 0;
    let mut gate_passed: bool = false;

    for line in cleaned.lines() {
        if let Some(rest) = line.strip_prefix("[Turn ") {
            if let Some((n_str, _)) = rest.split_once(']') {
                if let Ok(n) = n_str.trim().parse::<u32>() {
                    turn = turn.max(n);
                }
            }
        }

        if let Some(tool) = line.strip_prefix("● ") {
            let truncated = if tool.chars().count() > 200 {
                tool.chars().take(200).collect()
            } else {
                tool.to_string()
            };
            last_tool = Some(truncated);
        }

        if line.starts_with("✓ Gate passed") {
            gate_attempts += 1;
            gate_passed = true;
        } else if line.starts_with("✗ Gate failed") {
            gate_attempts += 1;
            gate_passed = false;
        }
    }

    LogProgress {
        turn,
        last_tool,
        gate_attempts,
        gate_passed,
    }
}

#[derive(Debug, Serialize)]
pub struct StatusOutput {
    pub id: String,
    pub state: String,
    pub elapsed_s: u64,
    pub turn: u32,
    pub last_tool: Option<String>,
    pub gate_attempts: u32,
    pub gate_passed: bool,
    pub outcome: Option<String>,
    pub cost_usd: Option<f64>,
    pub final_message: Option<String>,
}

pub fn run_status(id: &str, json: bool) -> i32 {
    let cwd = match std::env::current_dir() {
        Ok(d) => d,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };
    let records_dir = match crate::dispatch_in_place::records_dir_for(&cwd) {
        Ok(d) => d,
        Err(e) => {
            eprintln!("error: {e}");
            return 2;
        }
    };

    let start_path = records_dir.join(format!("{id}.start.json"));
    let start_raw = match std::fs::read_to_string(&start_path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            eprintln!("no dispatch {id} here");
            return 2;
        }
        Err(e) => {
            eprintln!("error reading {}: {e}", start_path.display());
            return 2;
        }
    };
    let start_record: serde_json::Value = match serde_json::from_str(&start_raw) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("error parsing {}: {e}", start_path.display());
            return 2;
        }
    };

    let pid = start_record
        .get("pid")
        .and_then(|v| v.as_i64())
        .map(|v| v as libc::pid_t);
    let Some(started_at) = start_record.get("started_at").and_then(|v| v.as_u64()) else {
        eprintln!(
            "error: missing or invalid \"started_at\" in {}",
            start_path.display()
        );
        return 2;
    };

    let is_alive = if let Some(pid) = pid {
        if pid > 0 {
            let ret = unsafe { libc::kill(pid, 0) };
            if ret == 0 {
                true
            } else {
                std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
            }
        } else {
            false
        }
    } else {
        false
    };

    let report_path = records_dir.join(format!("{id}.report.json"));
    let report_json: Option<serde_json::Value> = match std::fs::read_to_string(&report_path) {
        Ok(content) => match serde_json::from_str::<serde_json::Value>(&content) {
            Ok(v) if v.is_object() => Some(v),
            Ok(_) => {
                eprintln!(
                    "error parsing {}: expected a JSON object",
                    report_path.display()
                );
                return 2;
            }
            Err(e) => {
                eprintln!("error parsing {}: {e}", report_path.display());
                return 2;
            }
        },
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => {
            eprintln!("error reading {}: {e}", report_path.display());
            return 2;
        }
    };

    let state = if report_json.is_some() {
        "finished"
    } else if is_alive {
        "running"
    } else {
        "dead"
    };

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    let (outcome, cost_usd, final_message, report_duration) = if let Some(ref v) = report_json {
        let outcome = v.get("outcome").and_then(|x| x.as_str()).map(String::from);
        let cost_usd = v.get("cost_usd").and_then(|x| x.as_f64());
        let final_message = v.get("final_message").and_then(|x| x.as_str()).map(|s| {
            if s.chars().count() > 500 {
                s.chars().take(500).collect()
            } else {
                s.to_string()
            }
        });
        let duration = v.get("duration_seconds").and_then(|x| x.as_f64());
        (outcome, cost_usd, final_message, duration)
    } else {
        (None, None, None, None)
    };

    let elapsed_s = if state == "finished" {
        report_duration
            .map(|d| d.round() as u64)
            .unwrap_or_else(|| now.saturating_sub(started_at))
    } else {
        now.saturating_sub(started_at)
    };

    let log_path = records_dir.join(format!("{id}.log"));
    let log_content = match std::fs::read_to_string(&log_path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => {
            eprintln!("error reading {}: {e}", log_path.display());
            return 2;
        }
    };
    let progress = parse_log(&log_content);

    if json {
        let status_obj = StatusOutput {
            id: id.to_string(),
            state: state.to_string(),
            elapsed_s,
            turn: progress.turn,
            last_tool: progress.last_tool,
            gate_attempts: progress.gate_attempts,
            gate_passed: progress.gate_passed,
            outcome,
            cost_usd,
            final_message,
        };
        let json_str = serde_json::to_string_pretty(&status_obj).unwrap();
        println!("{json_str}");
    } else {
        println!("id: {id}");
        println!("state: {state}");
        println!("elapsed_s: {elapsed_s}");
        println!("turn: {}", progress.turn);
        println!(
            "last_tool: {}",
            progress.last_tool.as_deref().unwrap_or("none")
        );
        println!("gate_attempts: {}", progress.gate_attempts);
        println!("gate_passed: {}", progress.gate_passed);
        if state == "finished" {
            if let Some(ref o) = outcome {
                println!("outcome: {o}");
            }
            if let Some(c) = cost_usd {
                println!("cost_usd: {c}");
            }
            if let Some(ref msg) = final_message {
                println!("final_message: {msg}");
            }
        }
    }

    match state {
        "running" | "finished" => 0,
        _ => 1,
    }
}

pub fn unreadable_paths(text: &str, readable: &[PathBuf]) -> Vec<PathBuf> {
    let readable_canon: Vec<PathBuf> = readable
        .iter()
        .filter_map(|r| std::fs::canonicalize(r).ok())
        .collect();
    let mut out = Vec::new();
    for raw in text.split(|c: char| {
        c.is_whitespace()
            || matches!(
                c,
                '`' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>'
            )
    }) {
        let trimmed = raw.trim_end_matches(['.', ',', ';', ':', '!', '?']);
        if !trimmed.starts_with('/')
            || trimmed.starts_with("//")
            || trimmed.len() <= 1
            || trimmed == "/dev/null"
        {
            continue;
        }
        let p = Path::new(trimmed);
        let Ok(canon) = std::fs::canonicalize(p) else {
            continue;
        };
        if readable_canon.iter().any(|r| canon.starts_with(r))
            || is_system_path(p)
            || is_system_path(&canon)
        {
            continue;
        }
        let pb = PathBuf::from(trimmed);
        if !out.contains(&pb) {
            out.push(pb);
        }
    }
    out
}

/// A path no research task means as code to read: the filesystem root, a top-level directory,
/// or anything under the system directories (`/usr/bin/env`, `/tmp`, `/dev/null`).
fn is_system_path(p: &Path) -> bool {
    const SYSTEM: &[&str] = &[
        "/usr",
        "/bin",
        "/sbin",
        "/etc",
        "/dev",
        "/opt",
        "/System",
        "/Library",
        "/Applications",
        "/nix",
        "/proc",
        "/sys",
    ];
    p.components().count() <= 2 || SYSTEM.iter().any(|s| p.starts_with(s))
}

pub fn refused_reads(log_content: &str) -> (usize, Vec<String>) {
    let mut count = 0;
    let mut paths = Vec::new();
    for line in log_content.lines() {
        if !line.contains("path escapes the workspace") {
            continue;
        }
        count += 1;
        if let Some((_, after)) = line.split_once("path escapes the workspace:") {
            let after = after.trim_start();
            let after = after.split("\x1b[").next().unwrap_or(after);
            let path = after
                .split(". This run can read")
                .next()
                .unwrap_or(after)
                .trim();
            if !path.is_empty() && !paths.iter().any(|p| p == path) {
                paths.push(path.to_string());
            }
        }
    }
    (count, paths)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn outside_reads_excludes_commands_in_host_commands() {
        let home = Path::new("/Users/u");
        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
        // rm -rf ~/repos/other is a host command (names outside and changes something)
        // cat ~/repos/other is not a host command (only reads)
        let log = "\
● bash rm -rf ~/repos/other/file.py -> exit 0
● bash cat ~/repos/other/file.py -> exit 0
";
        assert_eq!(
            host_commands(log),
            vec!["rm -rf ~/repos/other/file.py".to_string()]
        );
        assert_eq!(
            outside_reads(log, &allowed, home),
            vec!["cat ~/repos/other/file.py".to_string()]
        );
    }

    #[test]
    fn outside_reads_all_terminal_patterns() {
        let home = Path::new("/Users/u");
        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
        let log = "\
● bash herdr pane read p1 -> exit 0
● bash tmux capture-pane -t 1 -> exit 0
● bash screen -X hardcopy /tmp/screen.log -> exit 0
● bash zellij action dump-screen /tmp/dump -> exit 0
● bash wezterm cli get-text --pane-id 1 -> exit 0
";
        let reads = outside_reads(log, &allowed, home);
        assert_eq!(
            reads,
            vec![
                "herdr pane read p1",
                "tmux capture-pane -t 1",
                "screen -X hardcopy /tmp/screen.log",
                "zellij action dump-screen /tmp/dump",
                "wezterm cli get-text --pane-id 1",
            ]
        );
    }

    #[test]
    fn outside_reads_all_tool_caches_ignored() {
        let home = Path::new("/Users/u");
        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
        let log = "\
● bash ls ~/.cargo/bin -> exit 0
● bash ls ~/.rustup/toolchains -> exit 0
● bash ls ~/.cache/pip -> exit 0
● bash ls ~/.npm/_cacache -> exit 0
● bash ls ~/.local/share -> exit 0
● bash ls ~/Library/Caches/com.apple -> exit 0
● bash ls ~/.gradle/caches -> exit 0
● bash ls ~/.m2/repository -> exit 0
● bash ls ~/go/pkg -> exit 0
";
        assert!(outside_reads(log, &allowed, home).is_empty());
    }

    #[test]
    fn outside_reads_trailing_punctuations_stripped() {
        let home = Path::new("/Users/u");
        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
        let log = "\
● bash ls ~/secret: -> exit 0
● bash ls ~/secret, -> exit 0
● bash (ls ~/secret) -> exit 0
● bash bash -c 'ls ~/secret' -> exit 0
● bash bash -c \"ls ~/secret\" -> exit 0
";
        let reads = outside_reads(log, &allowed, home);
        // Deduplicated, so only one instance of the command or distinct commands:
        assert_eq!(reads.len(), 5);
    }

    #[test]
    fn outside_reads_caps_at_20_and_deduplicates() {
        let home = Path::new("/Users/u");
        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
        let mut log = String::new();
        for i in 0..30 {
            log.push_str(&format!("● bash cat ~/secret/{i}.txt -> exit 0\n"));
        }
        // Duplicate the first one
        log.push_str("● bash cat ~/secret/0.txt -> exit 0\n");
        let reads = outside_reads(&log, &allowed, home);
        assert_eq!(reads.len(), 20);
        assert_eq!(reads[0], "cat ~/secret/0.txt");
        assert_eq!(reads[19], "cat ~/secret/19.txt");
    }

    fn sample_summary(id: &str, exit: i32) -> DispatchSummary {
        DispatchSummary {
            id: id.to_string(),
            worktree: "/tmp/wt".to_string(),
            branch: format!("wip/{id}"),
            outcome: if exit == 0 { "verified" } else { "gate_failed" },
            exit,
            error: None,
            commits: Vec::new(),
            changed_files: Vec::new(),
            final_message: Some("ok".to_string()),
            turns: 1,
            gate_attempts: 1,
            gate_failures: Vec::new(),
            cost_usd: Some(0.01),
            model: None,
            seconds: 1,
            sandbox: "off".to_string(),
            log: "/tmp/wt.log".to_string(),
            report: "/tmp/wt.report.json".to_string(),
            gate_source: "flag",
            research_report: None,
            base_check_seconds: None,
            warnings: Vec::new(),
            fix_round: None,
        }
    }

    #[test]
    fn finish_summary_reports_error_when_wt_is_a_regular_file() {
        let d = tempfile::tempdir().unwrap();
        let wt_file = d.path().join(".wt");
        std::fs::write(&wt_file, "not a dir").unwrap();

        let summary_ok = sample_summary("FC1", 0);
        let mut out_ok = Vec::new();
        let mut err_ok = Vec::new();
        let code_ok = finish_summary_with_writers(&summary_ok, d.path(), &mut out_ok, &mut err_ok);
        assert_eq!(code_ok, 1);
        let stderr_ok = String::from_utf8(err_ok).unwrap();
        let expected_path = wt_file.join("FC1.json");
        assert!(
            stderr_ok.contains("blyte: could not write"),
            "stderr: {stderr_ok}"
        );
        assert!(
            stderr_ok.contains(&expected_path.display().to_string()),
            "stderr: {stderr_ok}"
        );
        let parsed_ok: serde_json::Value = serde_json::from_slice(&out_ok).unwrap();
        assert_eq!(parsed_ok["id"], "FC1");
        assert_eq!(parsed_ok["exit"], 0);

        let summary_fail = sample_summary("FC3", 3);
        let mut out_fail = Vec::new();
        let mut err_fail = Vec::new();
        let code_fail =
            finish_summary_with_writers(&summary_fail, d.path(), &mut out_fail, &mut err_fail);
        assert_eq!(code_fail, 3);
        let stderr_fail = String::from_utf8(err_fail).unwrap();
        assert!(
            stderr_fail.contains(&wt_file.join("FC3.json").display().to_string()),
            "stderr: {stderr_fail}"
        );
        let parsed_fail: serde_json::Value = serde_json::from_slice(&out_fail).unwrap();
        assert_eq!(parsed_fail["id"], "FC3");
        assert_eq!(parsed_fail["exit"], 3);
    }

    #[test]
    fn resolve_max_cost_precedence() {
        assert_eq!(resolve_max_cost(None, None), 25.0);
        assert_eq!(resolve_max_cost(None, None), DEFAULT_MAX_COST_USD);
        assert_eq!(resolve_max_cost(None, Some(8.0)), 8.0);
        assert_eq!(resolve_max_cost(Some(3.0), Some(8.0)), 3.0);
        assert_eq!(resolve_max_cost(Some(3.0), None), 3.0);
    }

    #[test]
    fn archive_run_records_skips_archive_dir_when_empty() {
        let d = tempfile::tempdir().unwrap();
        let wt = d.path().join(".wt");
        std::fs::create_dir_all(&wt).unwrap();
        std::fs::write(wt.join("A1.task.md"), "task").unwrap();
        std::fs::write(wt.join("A1.out"), "out").unwrap();

        let res = archive_run_records_at(d.path(), "A1", 1700000000).unwrap();
        assert_eq!(res, None);
        assert!(!wt.join("archive").exists());
        assert!(wt.join("A1.task.md").is_file());
        assert!(wt.join("A1.out").is_file());
    }

    #[test]
    fn archive_run_records_moves_all_extensions_and_uses_non_colliding_suffix() {
        let d = tempfile::tempdir().unwrap();
        let wt = d.path().join(".wt");
        std::fs::create_dir_all(&wt).unwrap();
        for ext in RUN_RECORD_EXTENSIONS {
            std::fs::write(wt.join(format!("A1.{ext}")), format!("first-{ext}")).unwrap();
        }
        std::fs::write(wt.join("A1.task.md"), "keep task").unwrap();
        std::fs::write(wt.join("A1.out"), "keep out").unwrap();

        let rel1 = archive_run_records_at(d.path(), "A1", 1700000000)
            .unwrap()
            .unwrap();
        assert_eq!(rel1, ".wt/archive/A1-1700000000");
        for ext in RUN_RECORD_EXTENSIONS {
            assert!(!wt.join(format!("A1.{ext}")).exists());
            assert_eq!(
                std::fs::read_to_string(d.path().join(&rel1).join(format!("A1.{ext}"))).unwrap(),
                format!("first-{ext}")
            );
        }
        assert_eq!(
            std::fs::read_to_string(wt.join("A1.task.md")).unwrap(),
            "keep task"
        );
        assert_eq!(
            std::fs::read_to_string(wt.join("A1.out")).unwrap(),
            "keep out"
        );

        std::fs::write(wt.join("A1.verdict.json"), "second").unwrap();
        let rel2 = archive_run_records_at(d.path(), "A1", 1700000000)
            .unwrap()
            .unwrap();
        assert_eq!(rel2, ".wt/archive/A1-1700000000-2");
        assert_eq!(
            std::fs::read_to_string(d.path().join(&rel2).join("A1.verdict.json")).unwrap(),
            "second"
        );
        assert_eq!(
            std::fs::read_to_string(d.path().join(&rel1).join("A1.verdict.json")).unwrap(),
            "first-verdict.json"
        );

        std::fs::write(wt.join("A1.verdict.json"), "third").unwrap();
        let rel3 = archive_run_records_at(d.path(), "A1", 1700000000)
            .unwrap()
            .unwrap();
        assert_eq!(rel3, ".wt/archive/A1-1700000000-3");
        assert_eq!(
            std::fs::read_to_string(d.path().join(&rel3).join("A1.verdict.json")).unwrap(),
            "third"
        );
    }

    #[test]
    fn archive_run_records_errors_naming_path_when_archive_root_is_file() {
        let d = tempfile::tempdir().unwrap();
        let wt = d.path().join(".wt");
        std::fs::create_dir_all(&wt).unwrap();
        let blocker = wt.join("archive");
        std::fs::write(&blocker, "not a dir").unwrap();
        std::fs::write(wt.join("A1.verdict.json"), r#"{"verdict":"accepted"}"#).unwrap();

        let err = archive_run_records_at(d.path(), "A1", 1700000000).unwrap_err();
        assert!(
            err.contains(&blocker.display().to_string()),
            "error should name archive root path: {err}"
        );
    }
}