ghost-link 2.3.0

CLI and API runtime for Ghostlink, a distributed inference fabric for routing and scheduling custom LLM workloads across heterogeneous hardware.
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
use anyhow::{anyhow, Context, Result};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::{broadcast, Mutex};
use uuid::Uuid;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ProjectKind {
    Code,
    Work,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Project {
    pub id: String,
    pub name: String,
    pub kind: ProjectKind,
    pub root_path: String,
    pub allowed_tools: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_model: Option<String>,
    pub created_at: String,
}

impl Project {
    pub fn effective_allowed_tools(&self) -> Vec<String> {
        if self.allowed_tools.is_empty() && self.kind == ProjectKind::Code {
            vec![
                "write_file".to_string(),
                "read_file".to_string(),
                "run_command".to_string(),
            ]
        } else {
            self.allowed_tools.clone()
        }
    }
}

/// How a project proves a change is good.
///
/// Without this, `ReviewPacket.checks` only ever contained commands the *model
/// chose* to run — so "it passed checks" meant "the model ran something", not
/// "the project's tests pass". A packet with zero checks was equally
/// acceptable, which is how unverified work reached `main`.
///
/// A plan is a list of commands the project itself declares as its definition
/// of done. They run through the same `Judge` policy as agent-issued commands,
/// so a plan cannot be used to smuggle in a denied command.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct VerificationPlan {
    /// Each entry is an argv vector, e.g. `["cargo", "test", "--workspace"]`.
    #[serde(default)]
    pub commands: Vec<Vec<String>>,
    /// When true, a failing (or absent) verification blocks acceptance.
    #[serde(default)]
    pub required: bool,
}

impl VerificationPlan {
    /// Detect a plan from the project's own build files.
    ///
    /// The point is that this works with no configuration: point Ghostlink at
    /// any repository and it already knows how to check itself. Detection is
    /// deliberately conservative — it only emits commands the `Judge` allows.
    pub fn detect(root_path: &str) -> Option<VerificationPlan> {
        let root = std::path::Path::new(root_path);
        let mut commands: Vec<Vec<String>> = Vec::new();

        if root.join("Cargo.toml").exists() {
            commands.push(vec!["cargo".into(), "test".into(), "--workspace".into()]);
        }
        if root.join("package.json").exists() {
            // `npm test` is the conventional entry point; only include it when
            // the manifest actually defines a test script.
            let has_test_script = fs::read_to_string(root.join("package.json"))
                .ok()
                .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
                .and_then(|v| v.get("scripts").and_then(|s| s.get("test")).cloned())
                .is_some();
            if has_test_script {
                commands.push(vec!["npx".into(), "vitest".into(), "run".into()]);
            }
        }
        if root.join("pyproject.toml").exists() || root.join("pytest.ini").exists() {
            commands.push(vec!["python3".into(), "-m".into(), "pytest".into()]);
        }

        if commands.is_empty() {
            None
        } else {
            Some(VerificationPlan {
                commands,
                required: true,
            })
        }
    }

    /// Commands in this plan that the `Judge` would refuse to run. A plan
    /// containing one is misconfigured, and we say so rather than silently
    /// executing it (the Judge is the single authority on what may run).
    pub fn disallowed_commands(&self) -> Vec<Vec<String>> {
        self.commands
            .iter()
            .filter(|argv| Judge::evaluate(argv) != JudgeResult::Allow)
            .cloned()
            .collect()
    }
}

/// Outcome of running one verification command.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerificationResult {
    pub argv: Vec<String>,
    pub exit: i32,
    pub passed: bool,
    /// Captured output, truncated — enough to see *why* it failed.
    pub excerpt: String,
    #[serde(default)]
    pub timed_out: bool,
}

impl VerificationResult {
    /// One-line summary suitable for a reviewer.
    pub fn summary(&self) -> String {
        let cmd = self.argv.join(" ");
        if self.timed_out {
            format!("TIMED OUT: {cmd}")
        } else if self.passed {
            format!("PASS: {cmd}")
        } else {
            format!("FAIL (exit {}): {cmd}", self.exit)
        }
    }
}

/// Run a verification plan against a project root.
///
/// Every command goes through `Judge` first — a plan cannot bypass the policy
/// that governs agent-issued commands. Each command gets its own timeout so a
/// hanging test suite cannot stall a task forever.
pub async fn run_verification_plan(
    plan: &VerificationPlan,
    root_path: &str,
    per_command_timeout: std::time::Duration,
) -> Vec<VerificationResult> {
    let mut results = Vec::new();

    for argv in &plan.commands {
        if argv.is_empty() {
            continue;
        }

        // The Judge is the single authority on what may run.
        if Judge::evaluate(argv) != JudgeResult::Allow {
            results.push(VerificationResult {
                argv: argv.clone(),
                exit: -1,
                passed: false,
                excerpt: "Refused: command is not permitted by the Judge policy".into(),
                timed_out: false,
            });
            continue;
        }

        let mut cmd = tokio::process::Command::new(&argv[0]);
        cmd.args(&argv[1..])
            .current_dir(root_path)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped());

        let outcome = tokio::time::timeout(per_command_timeout, cmd.output()).await;

        match outcome {
            Err(_elapsed) => results.push(VerificationResult {
                argv: argv.clone(),
                exit: -1,
                passed: false,
                excerpt: format!("Timed out after {}s", per_command_timeout.as_secs()),
                timed_out: true,
            }),
            Ok(Err(e)) => results.push(VerificationResult {
                argv: argv.clone(),
                exit: -1,
                passed: false,
                excerpt: format!("Failed to spawn: {e}"),
                timed_out: false,
            }),
            Ok(Ok(output)) => {
                let exit = output.status.code().unwrap_or(-1);
                let mut excerpt = format!(
                    "STDOUT:\n{}\nSTDERR:\n{}",
                    String::from_utf8_lossy(&output.stdout),
                    String::from_utf8_lossy(&output.stderr)
                );
                // Keep the tail as well as the head: test failures print their
                // summary at the end, which is the part a reader needs.
                if excerpt.len() > 4000 {
                    let head = &excerpt[..2000];
                    let tail = &excerpt[excerpt.len() - 2000..];
                    excerpt = format!("{head}\n...\n(tail)\n{tail}");
                }
                results.push(VerificationResult {
                    argv: argv.clone(),
                    exit,
                    passed: exit == 0,
                    excerpt,
                    timed_out: false,
                });
            }
        }
    }

    results
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskBudget {
    pub max_steps: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    pub max_minutes: u32,
}

impl Default for TaskBudget {
    fn default() -> Self {
        Self {
            max_steps: 30,
            max_tokens: Some(100_000),
            max_minutes: 15,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TaskStatus {
    Queued,
    Running,
    NeedsReview,
    Accepted,
    Rejected,
    Blocked,
    Cancelled,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
    pub id: String,
    pub project_id: String,
    pub goal: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acceptance_criteria: Option<String>,
    pub status: TaskStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<String>,
    pub budget: TaskBudget,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentRun {
    pub id: String,
    pub task_id: String,
    pub role: String,
    pub model: String,
    pub status: String,
    pub step_count: u32,
    pub token_count: u32,
    pub started_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finished_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReviewDiff {
    pub path: String,
    pub unified_diff: String,
    pub original: String,
    pub proposed: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum JudgeDecision {
    Allow,
    Deny,
    Pause,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReviewCommand {
    pub argv: Vec<String>,
    pub judge: JudgeDecision,
    pub exit: i32,
    pub excerpt: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReviewPacket {
    pub id: String,
    pub task_id: String,
    pub run_id: String,
    pub summary: String,
    pub diffs: Vec<ReviewDiff>,
    pub commands: Vec<ReviewCommand>,
    pub checks: Vec<String>,
    pub risks: Vec<String>,
    /// Results of running the project's own verification plan against the
    /// change. Empty means no plan was detected/configured — which is itself
    /// reported in `risks`, not silently treated as success.
    #[serde(default)]
    pub verification: Vec<VerificationResult>,
    pub created_at: String,
}

impl ReviewPacket {
    /// True when every verification command passed.
    ///
    /// `None` (rather than `false`) when nothing was run, so "unverified" and
    /// "verified and failed" stay distinguishable — collapsing them is how a
    /// task with no checks ends up looking as good as one that passed a suite.
    pub fn verification_passed(&self) -> Option<bool> {
        if self.verification.is_empty() {
            None
        } else {
            Some(self.verification.iter().all(|r| r.passed))
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskEvent {
    pub task_id: String,
    pub ts: u64,
    pub kind: String,
    pub payload: serde_json::Value,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JudgeResult {
    Allow,
    Deny,
    Pause,
}

pub struct Judge;

impl Judge {
    pub fn evaluate(argv: &[String]) -> JudgeResult {
        if argv.is_empty() {
            return JudgeResult::Deny;
        }

        let cmd_str = argv.join(" ");

        // Check explicit DENY rules first
        if cmd_str.contains("rm -rf")
            || cmd_str.contains("mkfs")
            || cmd_str.contains("dd ")
            || cmd_str.contains("format ")
            || cmd_str.contains("git reset --hard")
            || cmd_str.contains("git push --force")
            || cmd_str.contains("git push -f")
            || cmd_str.contains(".git/objects")
            || cmd_str.contains(".env")
            || cmd_str.contains("id_rsa")
        {
            return JudgeResult::Deny;
        }

        let first = argv[0].as_str();
        if first == "curl"
            || first == "wget"
            || first == "scp"
            || first == "ssh"
            || first == "sudo"
            || first == "su"
            || first == "docker"
            || first == "kubectl"
        {
            return JudgeResult::Deny;
        }

        // ALLOW table check
        if Self::is_allowed(argv) {
            return JudgeResult::Allow;
        }

        // Default to PAUSE for unrecognized commands
        JudgeResult::Pause
    }

    fn is_allowed(argv: &[String]) -> bool {
        if argv.is_empty() {
            return false;
        }

        let prog = argv[0].as_str();
        match prog {
            "ls" | "rg" | "grep" => true,
            "git" => {
                if argv.len() >= 2 {
                    matches!(argv[1].as_str(), "status" | "diff" | "log")
                } else {
                    false
                }
            }
            "cargo" => {
                if argv.len() >= 2 {
                    matches!(argv[1].as_str(), "test" | "check" | "clippy")
                } else {
                    false
                }
            }
            "npx" => {
                argv.len() >= 3
                    && ((argv[1] == "vitest" && argv[2] == "run")
                        || (argv[1] == "tsc" && argv[2] == "--noEmit"))
            }
            "python" | "python3" => argv.len() >= 3 && argv[1] == "-m" && argv[2] == "pytest",
            _ => false,
        }
    }
}

#[derive(Debug)]
pub struct TaskRuntimeStore {
    data_dir: PathBuf,
    event_bus: broadcast::Sender<TaskEvent>,
    active_runs: Mutex<HashMap<String, tokio_util::sync::CancellationToken>>,
}

impl TaskRuntimeStore {
    pub fn new<P: AsRef<Path>>(data_dir: P) -> Result<Self> {
        let path = data_dir.as_ref().to_path_buf();
        fs::create_dir_all(&path)?;
        fs::create_dir_all(path.join("projects"))?;
        fs::create_dir_all(path.join("tasks"))?;
        fs::create_dir_all(path.join("runs"))?;
        fs::create_dir_all(path.join("reviews"))?;

        fs::create_dir_all(path.join("events"))?;
        let (event_bus, _) = broadcast::channel(64);

        Ok(Self {
            data_dir: path,
            event_bus,
            active_runs: Mutex::new(HashMap::new()),
        })
    }

    pub fn subscribe_events(&self) -> broadcast::Receiver<TaskEvent> {
        self.event_bus.subscribe()
    }

    pub fn emit_event(&self, event: TaskEvent) {
        let events_dir = self.data_dir.join("events");
        let file_path = events_dir.join(format!("{}.jsonl", event.task_id));
        if let Ok(json) = serde_json::to_string(&event) {
            use std::io::Write;
            if let Ok(mut file) = fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(file_path)
            {
                let _ = writeln!(file, "{}", json);
            }
        }
        let _ = self.event_bus.send(event);
    }

    pub fn get_task_events(&self, task_id: &str) -> Vec<TaskEvent> {
        let file_path = self
            .data_dir
            .join("events")
            .join(format!("{}.jsonl", task_id));
        let mut events = Vec::new();
        if file_path.exists() {
            if let Ok(content) = fs::read_to_string(file_path) {
                for line in content.lines() {
                    let trimmed = line.trim();
                    if !trimmed.is_empty() {
                        if let Ok(ev) = serde_json::from_str::<TaskEvent>(trimmed) {
                            events.push(ev);
                        }
                    }
                }
            }
        }
        events
    }

    pub fn register_cancel_token(
        &self,
        task_id: String,
        token: tokio_util::sync::CancellationToken,
    ) {
        if let Ok(mut guard) = self.active_runs.try_lock() {
            guard.insert(task_id, token);
        }
    }

    pub fn cancel_task_run(&self, task_id: &str) -> bool {
        let mut cancelled = false;
        if let Ok(mut guard) = self.active_runs.try_lock() {
            if let Some(token) = guard.remove(task_id) {
                token.cancel();
                cancelled = true;
            }
        }

        // Cascade cancel to children if task_id has children
        if let Ok(task) = self.get_task(task_id) {
            if let Ok(tasks) = self.list_project_tasks(&task.project_id) {
                for child in tasks
                    .iter()
                    .filter(|t| t.parent_id.as_deref() == Some(task_id))
                {
                    let _ = self.cancel_task_run(&child.id);
                    let _ = self.update_task_status(&child.id, TaskStatus::Cancelled);
                }
            }
        }

        cancelled
    }

    fn atomic_write_json<T: Serialize>(path: &Path, val: &T) -> Result<()> {
        let temp_path = path.with_extension(format!("tmp.{}", Uuid::new_v4()));
        let json = serde_json::to_string_pretty(val)?;
        fs::write(&temp_path, json)?;
        fs::rename(&temp_path, path)?;
        Ok(())
    }

    // Projects
    pub fn create_project(
        &self,
        name: String,
        kind: ProjectKind,
        root_path: String,
        allowed_tools: Option<Vec<String>>,
        default_model: Option<String>,
    ) -> Result<Project> {
        let canonical_root = fs::canonicalize(&root_path).with_context(|| {
            format!(
                "Project root_path '{}' does not exist or is invalid",
                root_path
            )
        })?;
        if !canonical_root.is_dir() {
            return Err(anyhow!(
                "Project root_path '{}' is not a directory",
                root_path
            ));
        }

        let proj = Project {
            id: format!("proj_{}", Uuid::new_v4().simple()),
            name,
            kind,
            root_path: canonical_root.to_string_lossy().to_string(),
            allowed_tools: allowed_tools.unwrap_or_else(|| {
                vec![
                    "read_file".into(),
                    "write_file".into(),
                    "run_command".into(),
                ]
            }),
            default_model,
            created_at: Utc::now().to_rfc3339(),
        };

        let file_path = self
            .data_dir
            .join("projects")
            .join(format!("{}.json", proj.id));
        Self::atomic_write_json(&file_path, &proj)?;
        Ok(proj)
    }

    pub fn list_projects(&self) -> Result<Vec<Project>> {
        let dir = self.data_dir.join("projects");
        let mut projects = Vec::new();
        if dir.is_dir() {
            for entry in fs::read_dir(dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.extension().and_then(|s| s.to_str()) == Some("json") {
                    let content = fs::read_to_string(&path)?;
                    if let Ok(proj) = serde_json::from_str::<Project>(&content) {
                        projects.push(proj);
                    }
                }
            }
        }
        projects.sort_by(|a, b| b.created_at.cmp(&a.created_at));
        Ok(projects)
    }

    pub fn get_project(&self, id: &str) -> Result<Project> {
        let file_path = self.data_dir.join("projects").join(format!("{}.json", id));
        if !file_path.exists() {
            return Err(anyhow!("Project '{}' not found", id));
        }
        let content = fs::read_to_string(file_path)?;
        Ok(serde_json::from_str(&content)?)
    }

    pub fn update_project(
        &self,
        id: &str,
        name: Option<String>,
        default_model: Option<String>,
        allowed_tools: Option<Vec<String>>,
    ) -> Result<Project> {
        let mut proj = self.get_project(id)?;
        if let Some(n) = name {
            proj.name = n;
        }
        if let Some(m) = default_model {
            proj.default_model = Some(m);
        }
        if let Some(t) = allowed_tools {
            proj.allowed_tools = t;
        }
        let file_path = self.data_dir.join("projects").join(format!("{}.json", id));
        Self::atomic_write_json(&file_path, &proj)?;
        Ok(proj)
    }

    // Tasks
    pub fn create_task(
        &self,
        project_id: &str,
        goal: String,
        acceptance_criteria: Option<String>,
        budget: Option<TaskBudget>,
        parent_id: Option<String>,
    ) -> Result<Task> {
        let _proj = self.get_project(project_id)?;

        // Phase B Fan-Out caps: max_depth = 1, max_children = 4
        if let Some(ref p_id) = parent_id {
            let parent_task = self.get_task(p_id)?;
            if parent_task.parent_id.is_some() {
                return Err(anyhow!("Child task depth limit exceeded (max_depth=1)"));
            }

            let existing_tasks = self.list_project_tasks(project_id)?;
            let child_count = existing_tasks
                .iter()
                .filter(|t| t.parent_id.as_deref() == Some(p_id.as_str()))
                .count();
            if child_count >= 4 {
                return Err(anyhow!(
                    "Child task count limit exceeded for parent (max_children=4)"
                ));
            }
        }

        let now = Utc::now().to_rfc3339();
        let task = Task {
            id: format!("task_{}", Uuid::new_v4().simple()),
            project_id: project_id.to_string(),
            goal,
            acceptance_criteria,
            status: TaskStatus::Queued,
            parent_id,
            budget: budget.unwrap_or_default(),
            created_at: now.clone(),
            updated_at: now,
        };

        let file_path = self
            .data_dir
            .join("tasks")
            .join(format!("{}.json", task.id));
        Self::atomic_write_json(&file_path, &task)?;
        Ok(task)
    }

    pub fn list_project_tasks(&self, project_id: &str) -> Result<Vec<Task>> {
        let dir = self.data_dir.join("tasks");
        let mut tasks = Vec::new();
        if dir.is_dir() {
            for entry in fs::read_dir(dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.extension().and_then(|s| s.to_str()) == Some("json") {
                    let content = fs::read_to_string(&path)?;
                    if let Ok(task) = serde_json::from_str::<Task>(&content) {
                        if task.project_id == project_id {
                            tasks.push(task);
                        }
                    }
                }
            }
        }
        tasks.sort_by(|a, b| b.created_at.cmp(&a.created_at));
        Ok(tasks)
    }

    pub fn list_child_tasks(&self, parent_id: &str) -> Result<Vec<Task>> {
        let parent = self.get_task(parent_id)?;
        let all_tasks = self.list_project_tasks(&parent.project_id)?;
        Ok(all_tasks
            .into_iter()
            .filter(|t| t.parent_id.as_deref() == Some(parent_id))
            .collect())
    }

    pub fn get_task(&self, id: &str) -> Result<Task> {
        let file_path = self.data_dir.join("tasks").join(format!("{}.json", id));
        if !file_path.exists() {
            return Err(anyhow!("Task '{}' not found", id));
        }
        let content = fs::read_to_string(file_path)?;
        Ok(serde_json::from_str(&content)?)
    }

    pub fn update_task_status(&self, id: &str, status: TaskStatus) -> Result<Task> {
        let mut task = self.get_task(id)?;
        task.status = status;
        task.updated_at = Utc::now().to_rfc3339();
        let file_path = self.data_dir.join("tasks").join(format!("{}.json", id));
        Self::atomic_write_json(&file_path, &task)?;
        Ok(task)
    }

    pub fn requeue_task(&self, id: &str) -> Result<Task> {
        let mut task = self.get_task(id)?;
        task.status = TaskStatus::Queued;
        task.updated_at = Utc::now().to_rfc3339();
        let file_path = self.data_dir.join("tasks").join(format!("{}.json", id));
        Self::atomic_write_json(&file_path, &task)?;
        Ok(task)
    }

    // Runs
    pub fn save_run(&self, run: &AgentRun) -> Result<()> {
        let file_path = self.data_dir.join("runs").join(format!("{}.json", run.id));
        Self::atomic_write_json(&file_path, run)
    }

    #[allow(dead_code)]
    pub fn get_run(&self, id: &str) -> Result<AgentRun> {
        let file_path = self.data_dir.join("runs").join(format!("{}.json", id));
        if !file_path.exists() {
            return Err(anyhow!("Run '{}' not found", id));
        }
        let content = fs::read_to_string(file_path)?;
        Ok(serde_json::from_str(&content)?)
    }

    // Reviews
    pub fn save_review(&self, review: &ReviewPacket) -> Result<()> {
        let file_path = self
            .data_dir
            .join("reviews")
            .join(format!("{}.json", review.id));
        Self::atomic_write_json(&file_path, review)?;
        // Also save by task_id for quick lookup
        let task_review_path = self
            .data_dir
            .join("reviews")
            .join(format!("task_{}.json", review.task_id));
        Self::atomic_write_json(&task_review_path, review)
    }

    pub fn get_task_review(&self, task_id: &str) -> Result<ReviewPacket> {
        let task_review_path = self
            .data_dir
            .join("reviews")
            .join(format!("task_{}.json", task_id));
        if !task_review_path.exists() {
            return Err(anyhow!("No review packet found for task '{}'", task_id));
        }
        let content = fs::read_to_string(task_review_path)?;
        Ok(serde_json::from_str(&content)?)
    }

    pub fn get_review(&self, id: &str) -> Result<ReviewPacket> {
        let file_path = self.data_dir.join("reviews").join(format!("{}.json", id));
        if !file_path.exists() {
            // Check if id is actually a task_id
            return self.get_task_review(id);
        }
        let content = fs::read_to_string(file_path)?;
        Ok(serde_json::from_str(&content)?)
    }

    // Path Isolation & Staging Helpers
    pub fn validate_and_resolve_path(root_path: &str, relative_path: &str) -> Result<PathBuf> {
        let root = PathBuf::from(root_path);
        let target = root.join(relative_path);

        // Normalize path without requiring target file to exist yet
        let mut normalized = PathBuf::new();
        for component in target.components() {
            match component {
                std::path::Component::ParentDir => {
                    if !normalized.pop() {
                        return Err(anyhow!("Path traversal detected in '{}'", relative_path));
                    }
                }
                std::path::Component::CurDir => {}
                c => normalized.push(c),
            }
        }

        let canonical_root =
            fs::canonicalize(&root).with_context(|| "Failed to canonicalize root_path")?;

        // Ensure normalized target stays under root
        if !normalized.starts_with(&canonical_root) && !normalized.starts_with(&root) {
            return Err(anyhow!("Path '{}' escapes project root", relative_path));
        }

        Ok(normalized)
    }

    pub fn get_task_proposed_dir(&self, project_root: &str, task_id: &str) -> PathBuf {
        PathBuf::from(project_root)
            .join(".ghostlink")
            .join("tasks")
            .join(task_id)
            .join("proposed")
    }

    /// Directory holding the pre-apply snapshot of every live file an accept
    /// is about to overwrite, so `rollback_applied_changes` can restore them.
    pub fn get_task_backup_dir(&self, project_root: &str, task_id: &str) -> PathBuf {
        PathBuf::from(project_root)
            .join(".ghostlink")
            .join("tasks")
            .join(task_id)
            .join("backup")
    }

    pub fn write_proposed_file(
        &self,
        project_root: &str,
        task_id: &str,
        relative_path: &str,
        content: &str,
    ) -> Result<PathBuf> {
        // Prevent path traversal
        let target_live_path = Self::validate_and_resolve_path(project_root, relative_path)?;
        let root = PathBuf::from(project_root);
        let rel = target_live_path
            .strip_prefix(&root)
            .map_err(|_| anyhow!("Target path outside root"))?;

        let proposed_dir = self.get_task_proposed_dir(project_root, task_id);
        let proposed_file_path = proposed_dir.join(rel);

        if let Some(parent) = proposed_file_path.parent() {
            fs::create_dir_all(parent)?;
        }

        fs::write(&proposed_file_path, content)?;
        Ok(proposed_file_path)
    }

    pub fn check_parent_accept_allowed(
        &self,
        project_id: &str,
        parent_task_id: &str,
    ) -> Result<()> {
        let tasks = self.list_project_tasks(project_id)?;
        let unaccepted_children: Vec<_> = tasks
            .into_iter()
            .filter(|t| t.parent_id.as_deref() == Some(parent_task_id))
            .filter(|t| !matches!(t.status, TaskStatus::Accepted | TaskStatus::Cancelled))
            .map(|t| t.id)
            .collect();

        if !unaccepted_children.is_empty() {
            return Err(anyhow!("Parent task accept is blocked until all child tasks are accepted or cancelled (open children: {})", unaccepted_children.join(", ")));
        }
        Ok(())
    }

    /// Apply a task's staged files onto the live project root.
    ///
    /// Every live file that is about to be overwritten is copied into the
    /// task's `backup/` directory first, and a manifest of which paths
    /// existed before is written alongside it. Without this, an accept was
    /// an unrecoverable blind `fs::copy` over the user's working tree — a
    /// dirty tree had no way back. `rollback_applied_changes` reverses it.
    pub fn apply_proposed_changes(&self, project_root: &str, task_id: &str) -> Result<Vec<String>> {
        let proposed_dir = self.get_task_proposed_dir(project_root, task_id);
        let mut applied_files = Vec::new();

        if !proposed_dir.exists() {
            return Ok(applied_files);
        }

        let backup_dir = self.get_task_backup_dir(project_root, task_id);
        let _ = fs::remove_dir_all(&backup_dir);
        fs::create_dir_all(&backup_dir)
            .with_context(|| format!("Failed to create backup dir {}", backup_dir.display()))?;

        let root = PathBuf::from(project_root);
        // Relative paths that did not exist before this apply, so a rollback
        // deletes them rather than restoring an empty file.
        let mut created_paths: Vec<String> = Vec::new();

        fn visit_dirs(
            dir: &Path,
            proposed_root: &Path,
            live_root: &Path,
            backup_root: &Path,
            applied: &mut Vec<String>,
            created: &mut Vec<String>,
        ) -> Result<()> {
            if dir.is_dir() {
                for entry in fs::read_dir(dir)? {
                    let entry = entry?;
                    let path = entry.path();
                    if path.is_dir() {
                        visit_dirs(
                            &path,
                            proposed_root,
                            live_root,
                            backup_root,
                            applied,
                            created,
                        )?;
                    } else {
                        let rel = path.strip_prefix(proposed_root)?;
                        let live_target = live_root.join(rel);
                        let rel_str = rel.to_string_lossy().to_string();

                        if live_target.exists() {
                            // Snapshot the current contents before clobbering.
                            let backup_target = backup_root.join(rel);
                            if let Some(parent) = backup_target.parent() {
                                fs::create_dir_all(parent)?;
                            }
                            fs::copy(&live_target, &backup_target).with_context(|| {
                                format!("Failed to back up {}", live_target.display())
                            })?;
                        } else {
                            created.push(rel_str.clone());
                        }

                        if let Some(parent) = live_target.parent() {
                            fs::create_dir_all(parent)?;
                        }
                        fs::copy(&path, &live_target)?;
                        applied.push(rel_str);
                    }
                }
            }
            Ok(())
        }

        visit_dirs(
            &proposed_dir,
            &proposed_dir,
            &root,
            &backup_dir,
            &mut applied_files,
            &mut created_paths,
        )?;

        // Record which applied paths were newly created, so rollback knows to
        // delete them instead of restoring from an (absent) snapshot.
        let manifest = serde_json::json!({
            "task_id": task_id,
            "applied": applied_files,
            "created": created_paths,
            "created_at": Utc::now().to_rfc3339(),
        });
        let manifest_path = backup_dir.join("manifest.json");
        let _ = Self::atomic_write_json(&manifest_path, &manifest);

        // Clean up proposed directory after successful apply
        let _ = fs::remove_dir_all(&proposed_dir);

        Ok(applied_files)
    }

    /// Undo a previous `apply_proposed_changes` for this task.
    ///
    /// Restores every file captured in the task's `backup/` snapshot and
    /// deletes the paths the apply created. Returns the list of paths that
    /// were restored or removed. Errors if there is no snapshot to roll back
    /// to, rather than silently reporting success.
    pub fn rollback_applied_changes(
        &self,
        project_root: &str,
        task_id: &str,
    ) -> Result<Vec<String>> {
        let backup_dir = self.get_task_backup_dir(project_root, task_id);
        let manifest_path = backup_dir.join("manifest.json");

        if !manifest_path.exists() {
            return Err(anyhow!(
                "No apply snapshot for task '{}' — nothing to roll back",
                task_id
            ));
        }

        let raw = fs::read_to_string(&manifest_path)?;
        let manifest: serde_json::Value = serde_json::from_str(&raw)?;

        let root = PathBuf::from(project_root);
        let mut touched = Vec::new();

        // Delete paths that this apply created.
        if let Some(created) = manifest.get("created").and_then(|c| c.as_array()) {
            for rel in created.iter().filter_map(|v| v.as_str()) {
                if let Ok(target) = Self::validate_and_resolve_path(project_root, rel) {
                    if target.exists() {
                        let _ = fs::remove_file(&target);
                    }
                    touched.push(rel.to_string());
                }
            }
        }

        // Restore paths that existed before the apply.
        fn restore_dirs(
            dir: &Path,
            backup_root: &Path,
            live_root: &Path,
            touched: &mut Vec<String>,
        ) -> Result<()> {
            if !dir.is_dir() {
                return Ok(());
            }
            for entry in fs::read_dir(dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.is_dir() {
                    restore_dirs(&path, backup_root, live_root, touched)?;
                } else if path
                    .file_name()
                    .map(|n| n == "manifest.json")
                    .unwrap_or(false)
                {
                    continue;
                } else {
                    let rel = path.strip_prefix(backup_root)?;
                    let live_target = live_root.join(rel);
                    if let Some(parent) = live_target.parent() {
                        fs::create_dir_all(parent)?;
                    }
                    fs::copy(&path, &live_target)?;
                    touched.push(rel.to_string_lossy().to_string());
                }
            }
            Ok(())
        }

        restore_dirs(&backup_dir, &backup_dir, &root, &mut touched)?;

        // Snapshot consumed — remove it so a second rollback errors instead of
        // silently re-restoring stale content.
        let _ = fs::remove_dir_all(&backup_dir);

        Ok(touched)
    }

    pub fn discard_proposed_changes(&self, project_root: &str, task_id: &str) -> Result<()> {
        let proposed_dir = self.get_task_proposed_dir(project_root, task_id);
        if proposed_dir.exists() {
            fs::remove_dir_all(&proposed_dir)?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
    pub id: String,
    pub name: String,
    pub args: serde_json::Value,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentResponse {
    pub content: Option<String>,
    pub tool_calls: Vec<ToolCall>,
    /// Real token usage for this turn when the backend reports it
    /// (prompt + completion). `None` means "unknown" — the runtime then falls
    /// back to a character-based estimate rather than pretending it knows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usage_tokens: Option<u32>,
}

#[allow(clippy::double_must_use)]
#[async_trait::async_trait]
pub trait AgentBackend: Send + Sync {
    async fn chat(
        &self,
        messages: &[serde_json::Value],
        allowed_tools: &[String],
    ) -> Result<AgentResponse>;
}

/// Produce a real unified diff between `original` and `proposed`.
///
/// `ReviewPacket.diffs[].unified_diff` previously carried a hand-built string
/// with a hardcoded `@@ -0,0 +1,3 @@` hunk header regardless of the actual
/// content, so a reviewer saw fabricated line numbers. This computes an
/// LCS-based diff with correct hunk headers instead of pulling in a new
/// dependency for one function.
///
/// Returns an empty string when the two sides are identical.
pub fn unified_diff(rel_path: &str, original: &str, proposed: &str) -> String {
    if original == proposed {
        return String::new();
    }

    let a: Vec<&str> = original.lines().collect();
    let b: Vec<&str> = proposed.lines().collect();

    // LCS table over lines.
    let (n, m) = (a.len(), b.len());
    let mut lcs = vec![vec![0usize; m + 1]; n + 1];
    for i in (0..n).rev() {
        for j in (0..m).rev() {
            lcs[i][j] = if a[i] == b[j] {
                lcs[i + 1][j + 1] + 1
            } else {
                lcs[i + 1][j].max(lcs[i][j + 1])
            };
        }
    }

    // Walk the table emitting context / deletions / additions.
    #[derive(PartialEq)]
    enum Op {
        Ctx,
        Del,
        Add,
    }
    let mut ops: Vec<(Op, &str)> = Vec::new();
    let (mut i, mut j) = (0usize, 0usize);
    while i < n && j < m {
        if a[i] == b[j] {
            ops.push((Op::Ctx, a[i]));
            i += 1;
            j += 1;
        } else if lcs[i + 1][j] >= lcs[i][j + 1] {
            ops.push((Op::Del, a[i]));
            i += 1;
        } else {
            ops.push((Op::Add, b[j]));
            j += 1;
        }
    }
    while i < n {
        ops.push((Op::Del, a[i]));
        i += 1;
    }
    while j < m {
        ops.push((Op::Add, b[j]));
        j += 1;
    }

    // Group into hunks with 3 lines of context, tracking real line numbers.
    const CTX: usize = 3;
    let mut out = String::new();
    out.push_str(&format!("--- a/{rel_path}\n+++ b/{rel_path}\n"));

    let changed: Vec<usize> = ops
        .iter()
        .enumerate()
        .filter(|(_, (op, _))| *op != Op::Ctx)
        .map(|(idx, _)| idx)
        .collect();

    if changed.is_empty() {
        return out;
    }

    // Build hunk ranges [start, end) over `ops`.
    let mut hunks: Vec<(usize, usize)> = Vec::new();
    let mut start = changed[0].saturating_sub(CTX);
    let mut end = (changed[0] + CTX + 1).min(ops.len());
    for &idx in &changed[1..] {
        if idx <= end + CTX {
            end = (idx + CTX + 1).min(ops.len());
        } else {
            hunks.push((start, end));
            start = idx.saturating_sub(CTX);
            end = (idx + CTX + 1).min(ops.len());
        }
    }
    hunks.push((start, end));

    for (hs, he) in hunks {
        // Line numbers at the start of this hunk (1-based, as of the first
        // op in the range).
        let old_start = 1 + ops[..hs].iter().filter(|(o, _)| *o != Op::Add).count();
        let new_start = 1 + ops[..hs].iter().filter(|(o, _)| *o != Op::Del).count();
        let old_len = ops[hs..he].iter().filter(|(o, _)| *o != Op::Add).count();
        let new_len = ops[hs..he].iter().filter(|(o, _)| *o != Op::Del).count();

        out.push_str(&format!(
            "@@ -{},{} +{},{} @@\n",
            old_start, old_len, new_start, new_len
        ));
        for (op, line) in &ops[hs..he] {
            let prefix = match op {
                Op::Ctx => ' ',
                Op::Del => '-',
                Op::Add => '+',
            };
            out.push(prefix);
            out.push_str(line);
            out.push('\n');
        }
    }

    out
}

/// Context-window policy for the agent loop.
///
/// The loop's `messages` vector grows by one assistant turn plus one tool-result
/// turn per tool call, with no upper bound — only individual tool *outputs* were
/// truncated. On a local model with a small `n_ctx` a long task therefore hit a
/// context overflow instead of compacting, and the backend call failed.
///
/// This is a real budget: the system prompt and the original task prompt are
/// pinned (dropping them loses the task), and the most recent turns are kept up
/// to whatever budget remains. Older turns are dropped oldest-first.
#[derive(Debug, Clone)]
pub struct ContextGovernor {
    /// Total token budget for the assembled message list.
    pub token_budget: usize,
    /// Tokens reserved for the model's own completion, subtracted from the
    /// budget before history is packed.
    pub reserve_completion_tokens: usize,
    /// Always-kept recent turns, even if they exceed the remaining budget.
    pub keep_last_turns: usize,
}

impl Default for ContextGovernor {
    fn default() -> Self {
        Self {
            token_budget: 4096,
            reserve_completion_tokens: 512,
            keep_last_turns: 6,
        }
    }
}

impl ContextGovernor {
    /// Approximate token count for a message. Uses the same
    /// chars/4 heuristic as the rest of the runtime; `usage_tokens` from the
    /// backend is preferred for *accounting*, but a cheap estimate is what's
    /// needed for a pre-flight packing decision.
    fn message_tokens(msg: &serde_json::Value) -> usize {
        let content = msg.get("content").and_then(|c| c.as_str()).unwrap_or("");
        let tool_calls = msg
            .get("tool_calls")
            .map(|t| t.to_string().len())
            .unwrap_or(0);
        ((content.len() + tool_calls) / 4).max(1)
    }

    /// Total estimated tokens across a message list.
    pub fn estimate_tokens(messages: &[serde_json::Value]) -> usize {
        messages.iter().map(Self::message_tokens).sum()
    }

    /// Pack `messages` into the budget, returning the kept list and how many
    /// messages were dropped.
    ///
    /// The first message (system prompt) and the second (the original task
    /// prompt) are pinned — they carry the goal and are never dropped, even if
    /// they alone exceed the budget. The most recent `keep_last_turns` turns
    /// are also always kept. Everything in between is dropped oldest-first
    /// until the remainder fits.
    pub fn fit(&self, messages: &[serde_json::Value]) -> (Vec<serde_json::Value>, usize) {
        // System + original task prompt are the pinned prefix.
        let pinned_prefix = messages.len().min(2);
        let pinned: Vec<serde_json::Value> = messages[..pinned_prefix].to_vec();
        let rest = &messages[pinned_prefix..];

        if rest.is_empty() {
            return (pinned, 0);
        }

        let budget = self
            .token_budget
            .saturating_sub(self.reserve_completion_tokens);
        let pinned_cost = Self::estimate_tokens(&pinned);
        let mut remaining = budget.saturating_sub(pinned_cost);

        // Walk backwards, always keeping the last `keep_last_turns` messages,
        // then as many older ones as fit.
        let keep_always = self.keep_last_turns.min(rest.len());
        let mut kept_from_rest: Vec<serde_json::Value> = Vec::new();

        for (idx, msg) in rest.iter().enumerate().rev() {
            let cost = Self::message_tokens(msg);
            let is_recent = idx >= rest.len() - keep_always;
            if is_recent {
                remaining = remaining.saturating_sub(cost);
                kept_from_rest.push(msg.clone());
            } else if cost <= remaining {
                remaining -= cost;
                kept_from_rest.push(msg.clone());
            } else {
                // Older message doesn't fit — stop scanning; everything before
                // it is older still.
                break;
            }
        }
        kept_from_rest.reverse();

        let dropped = rest.len() - kept_from_rest.len();
        let mut out = pinned;
        out.extend(kept_from_rest);
        (out, dropped)
    }
}

// Helper to recursively list relative paths in a directory
fn list_dir_relative(
    base_dir: &Path,
    current_dir: &Path,
    rel_paths: &mut Vec<String>,
) -> Result<()> {
    if !current_dir.exists() {
        return Ok(());
    }
    for entry in fs::read_dir(current_dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            list_dir_relative(base_dir, &path, rel_paths)?;
        } else if path.is_file() {
            if let Ok(rel) = path.strip_prefix(base_dir) {
                rel_paths.push(rel.to_string_lossy().to_string());
            }
        }
    }
    Ok(())
}

// Implementer Loop Runner
pub struct TaskRunner;

impl TaskRunner {
    #[allow(dead_code)]
    pub async fn spawn_implementer_joined(
        store: Arc<TaskRuntimeStore>,
        backend: Arc<dyn AgentBackend>,
        task: Task,
        role: String,
        model: String,
        brief: Option<String>,
        cancel_token: tokio_util::sync::CancellationToken,
    ) -> Result<AgentRun> {
        let now = Utc::now().to_rfc3339();
        let run = AgentRun {
            id: format!("run_{}", Uuid::new_v4().simple()),
            task_id: task.id.clone(),
            role,
            model,
            status: "running".into(),
            step_count: 0,
            token_count: 0,
            started_at: now,
            finished_at: None,
            error: None,
        };

        store.save_run(&run)?;
        store.update_task_status(&task.id, TaskStatus::Running)?;
        store.register_cancel_token(task.id.clone(), cancel_token.clone());

        let mut run_clone = run.clone();
        let res = Self::run_loop(
            store.clone(),
            backend,
            task.clone(),
            &mut run_clone,
            brief,
            cancel_token,
        )
        .await;

        let finished_at = Utc::now().to_rfc3339();
        run_clone.finished_at = Some(finished_at.clone());

        match res {
            Ok((review, final_status)) => {
                run_clone.status = "finished".into();
                let _ = store.save_run(&run_clone);
                let _ = store.save_review(&review);
                let _ = store.update_task_status(&task.id, final_status);

                store.emit_event(TaskEvent {
                    task_id: task.id.clone(),
                    ts: Utc::now().timestamp_millis() as u64,
                    kind: "review_ready".into(),
                    payload: serde_json::to_value(&review).unwrap_or_default(),
                });
                Ok(run_clone)
            }
            Err(err) => {
                let err_msg = err.to_string();
                let is_cancelled = err_msg.contains("cancelled");
                run_clone.status = if is_cancelled {
                    "cancelled".into()
                } else {
                    "failed".into()
                };
                run_clone.error = Some(err_msg.clone());
                let _ = store.save_run(&run_clone);

                let status = if is_cancelled {
                    TaskStatus::Cancelled
                } else {
                    TaskStatus::Blocked
                };
                let _ = store.update_task_status(&task.id, status);

                store.emit_event(TaskEvent {
                    task_id: task.id.clone(),
                    ts: Utc::now().timestamp_millis() as u64,
                    kind: if is_cancelled {
                        "cancelled".into()
                    } else {
                        "error".into()
                    },
                    payload: serde_json::json!({ "error": err_msg }),
                });

                Err(anyhow!(err_msg))
            }
        }
    }
    pub async fn spawn_implementer(
        store: Arc<TaskRuntimeStore>,
        backend: Arc<dyn AgentBackend>,
        task: Task,
        role: String,
        model: String,
        brief: Option<String>,
        cancel_token: tokio_util::sync::CancellationToken,
    ) -> Result<AgentRun> {
        let now = Utc::now().to_rfc3339();
        let run = AgentRun {
            id: format!("run_{}", Uuid::new_v4().simple()),
            task_id: task.id.clone(),
            role,
            model,
            status: "running".into(),
            step_count: 0,
            token_count: 0,
            started_at: now,
            finished_at: None,
            error: None,
        };

        store.save_run(&run)?;
        store.update_task_status(&task.id, TaskStatus::Running)?;
        store.register_cancel_token(task.id.clone(), cancel_token.clone());

        let store_clone = Arc::clone(&store);
        let task_clone = task.clone();
        let mut run_clone = run.clone();

        tokio::spawn(async move {
            let res = Self::run_loop(
                store_clone.clone(),
                backend,
                task_clone.clone(),
                &mut run_clone,
                brief,
                cancel_token,
            )
            .await;

            let finished_at = Utc::now().to_rfc3339();
            run_clone.finished_at = Some(finished_at.clone());

            match res {
                Ok((review, final_status)) => {
                    run_clone.status = "finished".into();
                    let _ = store_clone.save_run(&run_clone);
                    let _ = store_clone.save_review(&review);
                    let _ = store_clone.update_task_status(&task_clone.id, final_status);

                    store_clone.emit_event(TaskEvent {
                        task_id: task_clone.id.clone(),
                        ts: Utc::now().timestamp_millis() as u64,
                        kind: "review_ready".into(),
                        payload: serde_json::to_value(&review).unwrap_or_default(),
                    });
                }
                Err(err) => {
                    let err_msg = err.to_string();
                    let is_cancelled = err_msg.contains("cancelled");
                    run_clone.status = if is_cancelled {
                        "cancelled".into()
                    } else {
                        "failed".into()
                    };
                    run_clone.error = Some(err_msg.clone());
                    let _ = store_clone.save_run(&run_clone);

                    let status = if is_cancelled {
                        TaskStatus::Cancelled
                    } else {
                        TaskStatus::Blocked
                    };
                    let _ = store_clone.update_task_status(&task_clone.id, status);

                    store_clone.emit_event(TaskEvent {
                        task_id: task_clone.id.clone(),
                        ts: Utc::now().timestamp_millis() as u64,
                        kind: if is_cancelled {
                            "cancelled".into()
                        } else {
                            "error".into()
                        },
                        payload: serde_json::json!({ "error": err_msg }),
                    });
                }
            }
        });

        Ok(run)
    }

    #[allow(clippy::type_complexity)]
    fn run_loop<'a>(
        store: Arc<TaskRuntimeStore>,
        backend: Arc<dyn AgentBackend>,
        task: Task,
        run: &'a mut AgentRun,
        brief: Option<String>,
        cancel_token: tokio_util::sync::CancellationToken,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<(ReviewPacket, TaskStatus)>> + Send + 'a>,
    > {
        Box::pin(async move {
            let project = store.get_project(&task.project_id)?;

            store.emit_event(TaskEvent {
                task_id: task.id.clone(),
                ts: Utc::now().timestamp_millis() as u64,
                kind: "run_started".into(),
                payload: serde_json::json!({ "run_id": run.id, "brief": brief }),
            });

            let mut commands_executed = Vec::new();
            let mut checks = Vec::new();
            let mut risks = Vec::new();
            let mut final_status = TaskStatus::NeedsReview;

            let start_time = std::time::Instant::now();

            // Build initial messages
            let system_prompt = format!(
            "You are an AI task agent implementing project '{}' at root path '{}'. Use available tools to write proposed files and execute checks.",
            project.name, project.root_path
        );

            let mut user_prompt = format!("Task Goal: {}\n", task.goal);
            if let Some(b) = &brief {
                user_prompt.push_str(&format!("Execution Brief: {}\n", b));
            }
            if let Some(ac) = &task.acceptance_criteria {
                user_prompt.push_str(&format!("Acceptance Criteria: {}\n", ac));
            }

            let mut messages = vec![
                serde_json::json!({ "role": "system", "content": system_prompt }),
                serde_json::json!({ "role": "user", "content": user_prompt }),
            ];

            let max_steps = task.budget.max_steps;
            let max_minutes = task.budget.max_minutes as u64;

            // Real context budget for this run. Previously `messages` grew
            // unbounded and the backend call eventually failed on a context
            // overflow; now the list is packed to fit before every call.
            let governor = ContextGovernor::default();
            let mut context_dropped_total = 0usize;

            for _step in 1..=max_steps {
                if cancel_token.is_cancelled() {
                    return Err(anyhow!("Task execution cancelled by user"));
                }

                if start_time.elapsed().as_secs() > max_minutes * 60 {
                    risks.push("Exceeded time budget (max_minutes)".into());
                    break;
                }

                if let Some(max_tok) = task.budget.max_tokens {
                    if run.token_count >= max_tok {
                        risks.push("Exceeded token budget (max_tokens)".into());
                        break;
                    }
                }

                run.step_count += 1;
                store.emit_event(TaskEvent {
                task_id: task.id.clone(),
                ts: Utc::now().timestamp_millis() as u64,
                kind: "step".into(),
                payload: serde_json::json!({ "step": run.step_count, "description": format!("Agent step {}", run.step_count) }),
            });

                // Call model via AgentBackend.
                //
                // Retried with exponential backoff: a local inference backend
                // (llama-server mid model-swap, a transient RPC hiccup) used to
                // fail the whole task on a single error, pushing it to
                // `Blocked` — the same transient-failure class the RPC fabric
                // already handles with its own backoff policy. Cancellation is
                // honoured between attempts.
                const MAX_CHAT_ATTEMPTS: u32 = 3;
                let mut last_err: Option<String> = None;
                let mut attempt_resp = None;

                // Pack the transcript to fit the context budget before the
                // call. The system prompt and original task prompt are pinned.
                let (fitted, dropped) = governor.fit(&messages);
                if dropped > 0 {
                    context_dropped_total += dropped;
                    store.emit_event(TaskEvent {
                        task_id: task.id.clone(),
                        ts: Utc::now().timestamp_millis() as u64,
                        kind: "context_compacted".into(),
                        payload: serde_json::json!({
                            "dropped_messages": dropped,
                            "kept_messages": fitted.len(),
                            "estimated_tokens": ContextGovernor::estimate_tokens(&fitted),
                            "token_budget": governor.token_budget,
                        }),
                    });
                }

                for attempt in 0..MAX_CHAT_ATTEMPTS {
                    if cancel_token.is_cancelled() {
                        return Err(anyhow!("Task execution cancelled by user"));
                    }
                    match backend
                        .chat(&fitted, &project.effective_allowed_tools())
                        .await
                    {
                        Ok(resp) => {
                            attempt_resp = Some(resp);
                            break;
                        }
                        Err(err) => {
                            let msg = err.to_string();
                            last_err = Some(msg.clone());
                            if attempt + 1 < MAX_CHAT_ATTEMPTS {
                                // 1s, 2s — bounded, and short enough not to
                                // eat a meaningful slice of max_minutes.
                                let backoff = std::time::Duration::from_secs(1 << attempt);
                                store.emit_event(TaskEvent {
                                    task_id: task.id.clone(),
                                    ts: Utc::now().timestamp_millis() as u64,
                                    kind: "retry".into(),
                                    payload: serde_json::json!({
                                        "attempt": attempt + 1,
                                        "max_attempts": MAX_CHAT_ATTEMPTS,
                                        "backoff_ms": backoff.as_millis() as u64,
                                        "error": msg,
                                    }),
                                });
                                tokio::time::sleep(backoff).await;
                            }
                        }
                    }
                }

                let agent_resp = match attempt_resp {
                    Some(resp) => resp,
                    None => {
                        let err = last_err.unwrap_or_else(|| "unknown backend error".into());
                        risks.push(format!(
                            "Backend inference error after {} attempts: {}",
                            MAX_CHAT_ATTEMPTS, err
                        ));
                        break;
                    }
                };

                // Count tokens. Prefer the backend's reported usage; fall back
                // to a character estimate only when the backend doesn't report
                // it. The old code *always* estimated from assistant text
                // alone, ignoring prompt and tool-call tokens, so a
                // tool-call-only turn charged a flat 10 tokens and
                // `max_tokens` was effectively unreachable.
                let content_str = agent_resp.content.clone().unwrap_or_default();
                run.token_count += match agent_resp.usage_tokens {
                    Some(usage) => usage,
                    None => (content_str.len() / 4).max(10) as u32,
                };

                if !content_str.is_empty() {
                    messages
                        .push(serde_json::json!({ "role": "assistant", "content": content_str }));
                }

                if agent_resp.tool_calls.is_empty() {
                    break;
                }

                let mut should_stop = false;

                for tool_call in agent_resp.tool_calls {
                    store.emit_event(TaskEvent {
                    task_id: task.id.clone(),
                    ts: Utc::now().timestamp_millis() as u64,
                    kind: "tool".into(),
                    payload: serde_json::json!({ "name": tool_call.name, "args": tool_call.args }),
                });

                    match tool_call.name.as_str() {
                        "spawn_subagent" | "create_child_task" => {
                            if run.role != "planner" {
                                risks.push(
                                    "Implementer agent tried to spawn subagent (denied)".into(),
                                );
                                messages.push(serde_json::json!({ "role": "user", "content": "Error: implementer agents cannot spawn subagents" }));
                                continue;
                            }

                            let child_goal = tool_call
                                .args
                                .get("goal")
                                .and_then(|g| g.as_str())
                                .unwrap_or("");
                            let child_criteria = tool_call
                                .args
                                .get("acceptance_criteria")
                                .and_then(|c| c.as_str());

                            if child_goal.is_empty() {
                                messages.push(serde_json::json!({ "role": "user", "content": "Error: goal cannot be empty for child task" }));
                                continue;
                            }

                            let elapsed_mins = (start_time.elapsed().as_secs() / 60) as u32;
                            let rem_mins =
                                task.budget.max_minutes.saturating_sub(elapsed_mins).max(1);
                            let rem_steps =
                                task.budget.max_steps.saturating_sub(run.step_count).max(1);
                            let rem_tokens = task
                                .budget
                                .max_tokens
                                .map(|mt| mt.saturating_sub(run.token_count));

                            let child_budget = TaskBudget {
                                max_steps: rem_steps,
                                max_tokens: rem_tokens,
                                max_minutes: rem_mins,
                            };

                            match store.create_task(
                                &project.id,
                                child_goal.to_string(),
                                child_criteria.map(|s| s.to_string()),
                                Some(child_budget),
                                Some(task.id.clone()),
                            ) {
                                Ok(child) => {
                                    store.emit_event(TaskEvent {
                                    task_id: task.id.clone(),
                                    ts: Utc::now().timestamp_millis() as u64,
                                    kind: "child_created".into(),
                                    payload: serde_json::json!({ "child_id": child.id, "goal": child.goal }),
                                });

                                    // Auto-spawn child task as implementer run with inherited cancel token
                                    let child_store = Arc::clone(&store);
                                    let child_backend = Arc::clone(&backend);
                                    let child_task = child.clone();
                                    let child_model = run.model.clone();
                                    let child_token = cancel_token.child_token();

                                    tokio::spawn(Box::pin(async move {
                                        let _ = Self::spawn_implementer(
                                            child_store,
                                            child_backend,
                                            child_task,
                                            "implementer".into(),
                                            child_model,
                                            None,
                                            child_token,
                                        )
                                        .await;
                                    }));

                                    messages.push(serde_json::json!({ "role": "user", "content": format!("Successfully created child task #{} ({})", child.id, child.goal) }));
                                }
                                Err(e) => {
                                    risks.push(format!("Failed to create child task: {}", e));
                                    messages.push(serde_json::json!({ "role": "user", "content": format!("Failed to create child task: {}", e) }));
                                }
                            }
                        }
                        "write_file" => {
                            let rel_path = tool_call
                                .args
                                .get("path")
                                .and_then(|p| p.as_str())
                                .unwrap_or("");
                            let file_content = tool_call
                                .args
                                .get("content")
                                .and_then(|c| c.as_str())
                                .unwrap_or("");

                            if rel_path.is_empty() {
                                risks.push("write_file tool called with empty path".into());
                                messages.push(serde_json::json!({ "role": "user", "content": "Error: write_file path is empty" }));
                                continue;
                            }

                            if !project.allowed_tools.contains(&"write_file".to_string()) {
                                risks.push("write_file tool not allowed by project policy".into());
                                messages.push(serde_json::json!({ "role": "user", "content": "Error: write_file tool is disabled for this project" }));
                                continue;
                            }

                            match store.write_proposed_file(
                                &project.root_path,
                                &task.id,
                                rel_path,
                                file_content,
                            ) {
                                Ok(_) => {
                                    store.emit_event(TaskEvent {
                                    task_id: task.id.clone(),
                                    ts: Utc::now().timestamp_millis() as u64,
                                    kind: "file".into(),
                                    payload: serde_json::json!({ "path": rel_path, "action": "write_proposed" }),
                                });
                                    messages.push(serde_json::json!({ "role": "user", "content": format!("Successfully wrote proposed file {}", rel_path) }));
                                }
                                Err(e) => {
                                    risks.push(format!(
                                        "Failed writing proposed file {}: {}",
                                        rel_path, e
                                    ));
                                    messages.push(serde_json::json!({ "role": "user", "content": format!("Error writing proposed file {}: {}", rel_path, e) }));
                                }
                            }
                        }
                        "read_file" => {
                            let rel_path = tool_call
                                .args
                                .get("path")
                                .and_then(|p| p.as_str())
                                .unwrap_or("");
                            let proposed_file = store
                                .get_task_proposed_dir(&project.root_path, &task.id)
                                .join(rel_path);
                            let file_text = if proposed_file.exists() {
                                fs::read_to_string(&proposed_file).unwrap_or_default()
                            } else if let Ok(live_p) = TaskRuntimeStore::validate_and_resolve_path(
                                &project.root_path,
                                rel_path,
                            ) {
                                fs::read_to_string(&live_p).unwrap_or_default()
                            } else {
                                "File not found".to_string()
                            };
                            messages.push(serde_json::json!({ "role": "user", "content": format!("File content of {}:\n{}", rel_path, file_text) }));
                        }
                        "run_command" | "exec" | "execute" | "shell" => {
                            let argv: Vec<String> = if let Some(arr) =
                                tool_call.args.get("argv").and_then(|a| a.as_array())
                            {
                                arr.iter()
                                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
                                    .collect()
                            } else if let Some(cmd_str) =
                                tool_call.args.get("command").and_then(|c| c.as_str())
                            {
                                cmd_str.split_whitespace().map(|s| s.to_string()).collect()
                            } else {
                                vec![]
                            };

                            if argv.is_empty() {
                                messages.push(serde_json::json!({ "role": "user", "content": "Error: empty command" }));
                                continue;
                            }

                            let judge_eval = Judge::evaluate(&argv);
                            store.emit_event(TaskEvent {
                            task_id: task.id.clone(),
                            ts: Utc::now().timestamp_millis() as u64,
                            kind: "judge".into(),
                            payload: serde_json::json!({ "argv": argv, "decision": format!("{:?}", judge_eval) }),
                        });

                            match judge_eval {
                                JudgeResult::Allow => {
                                    if !project.allowed_tools.contains(&"run_command".to_string())
                                        && !project.allowed_tools.contains(&"execute".to_string())
                                    {
                                        risks.push(
                                            "Command execution tool not allowed by project policy"
                                                .into(),
                                        );
                                        messages.push(serde_json::json!({ "role": "user", "content": "Error: command execution is disabled for this project" }));
                                        continue;
                                    }

                                    let output_res = tokio::process::Command::new(&argv[0])
                                        .args(&argv[1..])
                                        .current_dir(&project.root_path)
                                        .output()
                                        .await;

                                    match output_res {
                                        Ok(output) => {
                                            let exit_code = output.status.code().unwrap_or(-1);
                                            let stdout = String::from_utf8_lossy(&output.stdout);
                                            let stderr = String::from_utf8_lossy(&output.stderr);
                                            let excerpt =
                                                format!("STDOUT:\n{}\nSTDERR:\n{}", stdout, stderr);
                                            let trimmed_excerpt = if excerpt.len() > 1000 {
                                                format!("{}...\n(truncated)", &excerpt[..1000])
                                            } else {
                                                excerpt
                                            };

                                            commands_executed.push(ReviewCommand {
                                                argv: argv.clone(),
                                                judge: JudgeDecision::Allow,
                                                exit: exit_code,
                                                excerpt: trimmed_excerpt.clone(),
                                            });

                                            if exit_code == 0 {
                                                checks.push(format!("Passed: {}", argv.join(" ")));
                                            } else {
                                                risks.push(format!(
                                                    "Command failed (exit {}): {}",
                                                    exit_code,
                                                    argv.join(" ")
                                                ));
                                            }

                                            messages.push(serde_json::json!({
                                            "role": "user",
                                            "content": format!("Command '{}' exited with {}:\n{}", argv.join(" "), exit_code, trimmed_excerpt)
                                        }));
                                        }
                                        Err(e) => {
                                            commands_executed.push(ReviewCommand {
                                                argv: argv.clone(),
                                                judge: JudgeDecision::Allow,
                                                exit: -1,
                                                excerpt: format!("Failed to spawn command: {}", e),
                                            });
                                            risks.push(format!(
                                                "Failed to execute command {}: {}",
                                                argv.join(" "),
                                                e
                                            ));
                                            messages.push(serde_json::json!({ "role": "user", "content": format!("Failed to execute command: {}", e) }));
                                        }
                                    }
                                }
                                JudgeResult::Deny => {
                                    commands_executed.push(ReviewCommand {
                                        argv: argv.clone(),
                                        judge: JudgeDecision::Deny,
                                        exit: -1,
                                        excerpt: "Command denied by Judge security policy".into(),
                                    });
                                    risks.push(format!(
                                        "Denied unsafe command execution: {}",
                                        argv.join(" ")
                                    ));
                                    messages.push(serde_json::json!({ "role": "user", "content": "Command denied by Judge security policy" }));
                                }
                                JudgeResult::Pause => {
                                    final_status = TaskStatus::Blocked;
                                    commands_executed.push(ReviewCommand {
                                        argv: argv.clone(),
                                        judge: JudgeDecision::Pause,
                                        exit: -1,
                                        excerpt: "Command execution paused pending approval".into(),
                                    });
                                    risks.push("Command requires human approval".into());
                                    messages.push(serde_json::json!({ "role": "user", "content": "Command paused pending human approval" }));
                                    should_stop = true;
                                }
                            }
                        }
                        _ => {
                            messages.push(serde_json::json!({ "role": "user", "content": format!("Unknown or unhandled tool: {}", tool_call.name) }));
                        }
                    }

                    if should_stop {
                        break;
                    }
                }

                if should_stop {
                    break;
                }
            }

            if run.step_count >= max_steps && final_status != TaskStatus::Blocked {
                risks.push("Step budget exhausted (max_steps)".into());
            }

            if context_dropped_total > 0 {
                // Surface it rather than letting compaction happen silently:
                // a reviewer should know the agent was working from a
                // truncated transcript, not the whole history.
                risks.push(format!(
                    "Context compacted: {} older message(s) dropped to fit the \
                     {}-token budget (system prompt and task goal pinned)",
                    context_dropped_total, governor.token_budget
                ));
            }

            if cancel_token.is_cancelled() {
                return Err(anyhow!("Task execution cancelled by user"));
            }

            // Generate ReviewPacket from proposed/ tree vs live root
            let proposed_dir = store.get_task_proposed_dir(&project.root_path, &task.id);
            let mut rel_proposed_files = Vec::new();
            let _ = list_dir_relative(&proposed_dir, &proposed_dir, &mut rel_proposed_files);

            let mut diffs = Vec::new();
            for rel_path in rel_proposed_files {
                let proposed_file_path = proposed_dir.join(&rel_path);
                let proposed_content = fs::read_to_string(&proposed_file_path).unwrap_or_default();

                let original_content = if let Ok(live_path) =
                    TaskRuntimeStore::validate_and_resolve_path(&project.root_path, &rel_path)
                {
                    fs::read_to_string(live_path).unwrap_or_default()
                } else {
                    "".to_string()
                };

                let unified_diff = unified_diff(&rel_path, &original_content, &proposed_content);

                diffs.push(ReviewDiff {
                    path: rel_path,
                    unified_diff,
                    original: original_content,
                    proposed: proposed_content,
                });
            }

            // ---- Verification ------------------------------------------------
            //
            // Run the project's own definition of done against the *merged*
            // result, not the staged tree in isolation: a change is only good
            // if it works alongside the code it is being merged into. The
            // proposed files are applied to a scratch copy of the project so
            // the live tree is never touched.
            let plan = VerificationPlan::detect(&project.root_path);
            let mut verification: Vec<VerificationResult> = Vec::new();

            match &plan {
                None => {
                    risks.push(
                        "No verification plan detected (no Cargo.toml / package.json \
                         test script / pytest config) — this change is UNVERIFIED"
                            .into(),
                    );
                }
                Some(plan) => {
                    let disallowed = plan.disallowed_commands();
                    if !disallowed.is_empty() {
                        // A plan that asks for something the Judge refuses is a
                        // configuration error, not a reason to run it anyway.
                        for argv in disallowed {
                            risks.push(format!(
                                "Verification plan command refused by Judge policy: {}",
                                argv.join(" ")
                            ));
                        }
                    } else if !diffs.is_empty() {
                        store.emit_event(TaskEvent {
                            task_id: task.id.clone(),
                            ts: Utc::now().timestamp_millis() as u64,
                            kind: "verification_started".into(),
                            payload: serde_json::json!({
                                "commands": plan.commands,
                            }),
                        });

                        match Self::verify_on_scratch_copy(
                            &store,
                            &project.root_path,
                            &task.id,
                            plan,
                        )
                        .await
                        {
                            Ok(results) => {
                                for r in &results {
                                    if r.passed {
                                        checks.push(r.summary());
                                    } else {
                                        risks.push(r.summary());
                                    }
                                }
                                verification = results;
                            }
                            Err(e) => risks.push(format!(
                                "Verification could not run: {e} — change is UNVERIFIED"
                            )),
                        }
                    }

                    // Be explicit about the unverified case rather than letting
                    // an empty `checks` read as success.
                    if verification.is_empty() && !plan.commands.is_empty() {
                        risks
                            .push("Verification produced no results — change is UNVERIFIED".into());
                    }
                }
            }

            let review = ReviewPacket {
                id: format!("rev_{}", Uuid::new_v4().simple()),
                task_id: task.id.clone(),
                run_id: run.id.clone(),
                summary: format!("Proposed changes for task: {}", task.goal),
                diffs,
                commands: commands_executed,
                checks,
                risks,
                verification,
                created_at: Utc::now().to_rfc3339(),
            };

            Ok((review, final_status))
        })
    }

    /// Apply the task's staged files to a scratch copy of the project, run the
    /// verification plan there, and clean up. The live tree is never modified.
    async fn verify_on_scratch_copy(
        store: &Arc<TaskRuntimeStore>,
        project_root: &str,
        task_id: &str,
        plan: &VerificationPlan,
    ) -> Result<Vec<VerificationResult>> {
        let scratch = std::env::temp_dir().join(format!(
            "ghostlink_verify_{}_{}",
            task_id,
            Uuid::new_v4().simple()
        ));
        let _ = fs::remove_dir_all(&scratch);

        copy_dir_recursive(Path::new(project_root), &scratch)
            .with_context(|| "failed to copy project to scratch dir for verification")?;

        // Overlay the staged files onto the copy.
        let proposed_dir = store.get_task_proposed_dir(project_root, task_id);
        if proposed_dir.exists() {
            copy_dir_recursive(&proposed_dir, &scratch)
                .with_context(|| "failed to apply staged files to scratch copy")?;
        }

        let results = run_verification_plan(
            plan,
            &scratch.to_string_lossy(),
            std::time::Duration::from_secs(600),
        )
        .await;

        let _ = fs::remove_dir_all(&scratch);
        Ok(results)
    }
}

/// Recursively copy `src` into `dst`, skipping the task staging tree and VCS
/// metadata (copying `.git` would be both slow and wrong for a scratch build).
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
    fs::create_dir_all(dst)?;
    if !src.is_dir() {
        return Ok(());
    }
    for entry in fs::read_dir(src)? {
        let entry = entry?;
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        if name_str == ".git" || name_str == "target" || name_str == "node_modules" {
            continue;
        }
        // Don't copy the staging tree into its own verification copy.
        if name_str == ".ghostlink" {
            continue;
        }
        let from = entry.path();
        let to = dst.join(&name);
        if from.is_dir() {
            copy_dir_recursive(&from, &to)?;
        } else {
            fs::copy(&from, &to)?;
        }
    }
    Ok(())
}

#[cfg(test)]
pub struct FakeBackend {
    pub responses: Arc<Mutex<Vec<AgentResponse>>>,
}

#[cfg(test)]
#[async_trait::async_trait]
impl AgentBackend for FakeBackend {
    async fn chat(
        &self,
        _messages: &[serde_json::Value],
        _allowed_tools: &[String],
    ) -> Result<AgentResponse> {
        let mut guard = self.responses.lock().await;
        if guard.is_empty() {
            Ok(AgentResponse {
                content: Some("Finished".into()),
                tool_calls: vec![],
                usage_tokens: None,
            })
        } else {
            Ok(guard.remove(0))
        }
    }
}

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

    #[tokio::test]
    async fn test_fake_backend_write_file_and_acceptance() {
        let temp_dir = std::env::temp_dir().join(format!("ghostlink_slice1_{}", Uuid::new_v4()));
        let store = Arc::new(TaskRuntimeStore::new(&temp_dir).unwrap());

        let proj_dir =
            std::env::temp_dir().join(format!("ghostlink_slice1_proj_{}", Uuid::new_v4()));
        fs::create_dir_all(&proj_dir).unwrap();
        let root_str = proj_dir.to_string_lossy().to_string();

        let proj = store
            .create_project(
                "Slice1 Proj".into(),
                ProjectKind::Code,
                root_str.clone(),
                None,
                None,
            )
            .unwrap();
        let task = store
            .create_task(&proj.id, "Create output file".into(), None, None, None)
            .unwrap();

        let fake_backend = Arc::new(FakeBackend {
            responses: Arc::new(Mutex::new(vec![
                AgentResponse {
                    content: Some("Writing file".into()),
                    tool_calls: vec![ToolCall {
                        id: "tc_1".into(),
                        name: "write_file".into(),
                        args: serde_json::json!({
                            "path": "test_output.txt",
                            "content": "Hello Slice 1"
                        }),
                    }],
                    usage_tokens: None,
                },
                AgentResponse {
                    content: Some("All done".into()),
                    tool_calls: vec![],
                    usage_tokens: None,
                },
            ])),
        });

        let cancel_token = tokio_util::sync::CancellationToken::new();
        let mut run = AgentRun {
            id: format!("run_{}", Uuid::new_v4().simple()),
            task_id: task.id.clone(),
            role: "implementer".into(),
            model: "mock-model".into(),
            status: "running".into(),
            step_count: 0,
            token_count: 0,
            started_at: Utc::now().to_rfc3339(),
            finished_at: None,
            error: None,
        };

        let (review, final_status) = TaskRunner::run_loop(
            store.clone(),
            fake_backend,
            task.clone(),
            &mut run,
            None,
            cancel_token,
        )
        .await
        .unwrap();

        assert_eq!(final_status, TaskStatus::NeedsReview);
        assert_eq!(review.diffs.len(), 1);
        assert_eq!(review.diffs[0].path, "test_output.txt");

        let proposed_file = store
            .get_task_proposed_dir(&root_str, &task.id)
            .join("test_output.txt");
        let live_file = proj_dir.join("test_output.txt");

        assert!(proposed_file.exists());
        assert!(!live_file.exists());

        store.apply_proposed_changes(&root_str, &task.id).unwrap();
        assert!(live_file.exists());
        assert_eq!(fs::read_to_string(live_file).unwrap(), "Hello Slice 1");

        let _ = fs::remove_dir_all(&temp_dir);
        let _ = fs::remove_dir_all(&proj_dir);
    }

    #[tokio::test]
    async fn test_judge_deny_tool_is_not_executed() {
        let temp_dir = std::env::temp_dir().join(format!("ghostlink_deny_{}", Uuid::new_v4()));
        let store = Arc::new(TaskRuntimeStore::new(&temp_dir).unwrap());

        let proj_dir = std::env::temp_dir().join(format!("ghostlink_deny_proj_{}", Uuid::new_v4()));
        fs::create_dir_all(&proj_dir).unwrap();

        let proj = store
            .create_project(
                "Deny Proj".into(),
                ProjectKind::Code,
                proj_dir.to_string_lossy().to_string(),
                None,
                None,
            )
            .unwrap();
        let task = store
            .create_task(&proj.id, "Try dangerous command".into(), None, None, None)
            .unwrap();

        let fake_backend = Arc::new(FakeBackend {
            responses: Arc::new(Mutex::new(vec![AgentResponse {
                content: Some("Exec rm".into()),
                tool_calls: vec![ToolCall {
                    id: "tc_deny".into(),
                    name: "run_command".into(),
                    args: serde_json::json!({
                        "argv": ["rm", "-rf", "/"]
                    }),
                }],
                usage_tokens: None,
            }])),
        });

        let cancel_token = tokio_util::sync::CancellationToken::new();
        let mut run = AgentRun {
            id: format!("run_{}", Uuid::new_v4().simple()),
            task_id: task.id.clone(),
            role: "implementer".into(),
            model: "mock-model".into(),
            status: "running".into(),
            step_count: 0,
            token_count: 0,
            started_at: Utc::now().to_rfc3339(),
            finished_at: None,
            error: None,
        };

        let (review, _status) = TaskRunner::run_loop(
            store.clone(),
            fake_backend,
            task.clone(),
            &mut run,
            None,
            cancel_token,
        )
        .await
        .unwrap();

        assert_eq!(review.commands.len(), 1);
        assert_eq!(review.commands[0].judge, JudgeDecision::Deny);
        assert!(review
            .risks
            .iter()
            .any(|r| r.contains("Denied unsafe command")));

        let _ = fs::remove_dir_all(&temp_dir);
        let _ = fs::remove_dir_all(&proj_dir);
    }

    #[tokio::test]
    async fn test_judge_pause_sets_blocked() {
        let temp_dir = std::env::temp_dir().join(format!("ghostlink_pause_{}", Uuid::new_v4()));
        let store = Arc::new(TaskRuntimeStore::new(&temp_dir).unwrap());

        let proj_dir =
            std::env::temp_dir().join(format!("ghostlink_pause_proj_{}", Uuid::new_v4()));
        fs::create_dir_all(&proj_dir).unwrap();

        let proj = store
            .create_project(
                "Pause Proj".into(),
                ProjectKind::Code,
                proj_dir.to_string_lossy().to_string(),
                None,
                None,
            )
            .unwrap();
        let task = store
            .create_task(&proj.id, "Try unknown command".into(), None, None, None)
            .unwrap();

        let fake_backend = Arc::new(FakeBackend {
            responses: Arc::new(Mutex::new(vec![AgentResponse {
                content: Some("Exec custom".into()),
                tool_calls: vec![ToolCall {
                    id: "tc_pause".into(),
                    name: "run_command".into(),
                    args: serde_json::json!({
                        "argv": ["custom_unknown_binary", "--arg"]
                    }),
                }],
                usage_tokens: None,
            }])),
        });

        let cancel_token = tokio_util::sync::CancellationToken::new();
        let mut run = AgentRun {
            id: format!("run_{}", Uuid::new_v4().simple()),
            task_id: task.id.clone(),
            role: "implementer".into(),
            model: "mock-model".into(),
            status: "running".into(),
            step_count: 0,
            token_count: 0,
            started_at: Utc::now().to_rfc3339(),
            finished_at: None,
            error: None,
        };

        let (review, final_status) = TaskRunner::run_loop(
            store.clone(),
            fake_backend,
            task.clone(),
            &mut run,
            None,
            cancel_token,
        )
        .await
        .unwrap();

        assert_eq!(final_status, TaskStatus::Blocked);
        assert_eq!(review.commands.len(), 1);
        assert_eq!(review.commands[0].judge, JudgeDecision::Pause);

        let _ = fs::remove_dir_all(&temp_dir);
        let _ = fs::remove_dir_all(&proj_dir);
    }

    #[tokio::test]
    async fn test_cancel_mid_loop_sets_cancelled() {
        let temp_dir = std::env::temp_dir().join(format!("ghostlink_cancel_{}", Uuid::new_v4()));
        let store = Arc::new(TaskRuntimeStore::new(&temp_dir).unwrap());

        let proj_dir =
            std::env::temp_dir().join(format!("ghostlink_cancel_proj_{}", Uuid::new_v4()));
        fs::create_dir_all(&proj_dir).unwrap();

        let proj = store
            .create_project(
                "Cancel Proj".into(),
                ProjectKind::Code,
                proj_dir.to_string_lossy().to_string(),
                None,
                None,
            )
            .unwrap();
        let task = store
            .create_task(&proj.id, "Cancel task".into(), None, None, None)
            .unwrap();

        let fake_backend = Arc::new(FakeBackend {
            responses: Arc::new(Mutex::new(vec![AgentResponse {
                content: Some("Step 1".into()),
                tool_calls: vec![],
                usage_tokens: None,
            }])),
        });

        let cancel_token = tokio_util::sync::CancellationToken::new();
        cancel_token.cancel();

        let mut run = AgentRun {
            id: format!("run_{}", Uuid::new_v4().simple()),
            task_id: task.id.clone(),
            role: "implementer".into(),
            model: "mock-model".into(),
            status: "running".into(),
            step_count: 0,
            token_count: 0,
            started_at: Utc::now().to_rfc3339(),
            finished_at: None,
            error: None,
        };

        let res = TaskRunner::run_loop(
            store.clone(),
            fake_backend,
            task.clone(),
            &mut run,
            None,
            cancel_token,
        )
        .await;

        assert!(res.is_err());
        assert!(res.unwrap_err().to_string().contains("cancelled"));

        let _ = fs::remove_dir_all(&temp_dir);
        let _ = fs::remove_dir_all(&proj_dir);
    }

    #[tokio::test]
    async fn test_budget_max_steps_stops_and_emits_review() {
        let temp_dir = std::env::temp_dir().join(format!("ghostlink_budget_{}", Uuid::new_v4()));
        let store = Arc::new(TaskRuntimeStore::new(&temp_dir).unwrap());

        let proj_dir =
            std::env::temp_dir().join(format!("ghostlink_budget_proj_{}", Uuid::new_v4()));
        fs::create_dir_all(&proj_dir).unwrap();

        let proj = store
            .create_project(
                "Budget Proj".into(),
                ProjectKind::Code,
                proj_dir.to_string_lossy().to_string(),
                None,
                None,
            )
            .unwrap();
        let budget = TaskBudget {
            max_steps: 1,
            ..Default::default()
        };

        let task = store
            .create_task(&proj.id, "Budget task".into(), None, Some(budget), None)
            .unwrap();

        let fake_backend = Arc::new(FakeBackend {
            responses: Arc::new(Mutex::new(vec![
                AgentResponse {
                    content: Some("Step 1".into()),
                    tool_calls: vec![ToolCall {
                        id: "tc_1".into(),
                        name: "read_file".into(),
                        args: serde_json::json!({ "path": "nonexistent.txt" }),
                    }],
                    usage_tokens: None,
                },
                AgentResponse {
                    content: Some("Step 2 - should not run".into()),
                    tool_calls: vec![],
                    usage_tokens: None,
                },
            ])),
        });

        let cancel_token = tokio_util::sync::CancellationToken::new();
        let mut run = AgentRun {
            id: format!("run_{}", Uuid::new_v4().simple()),
            task_id: task.id.clone(),
            role: "implementer".into(),
            model: "mock-model".into(),
            status: "running".into(),
            step_count: 0,
            token_count: 0,
            started_at: Utc::now().to_rfc3339(),
            finished_at: None,
            error: None,
        };

        let (review, _status) = TaskRunner::run_loop(
            store.clone(),
            fake_backend,
            task.clone(),
            &mut run,
            None,
            cancel_token,
        )
        .await
        .unwrap();

        assert_eq!(run.step_count, 1);
        assert!(review
            .risks
            .iter()
            .any(|r| r.contains("Step budget exhausted")));

        let _ = fs::remove_dir_all(&temp_dir);
        let _ = fs::remove_dir_all(&proj_dir);
    }
}

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

    #[test]
    fn test_store_roundtrip_and_atomic_write() {
        let temp_dir =
            std::env::temp_dir().join(format!("ghostlink_test_{}", uuid::Uuid::new_v4()));
        let store = TaskRuntimeStore::new(&temp_dir).unwrap();

        let proj_dir =
            std::env::temp_dir().join(format!("ghostlink_proj_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&proj_dir).unwrap();

        let proj = store
            .create_project(
                "Test Proj".into(),
                ProjectKind::Code,
                proj_dir.to_string_lossy().to_string(),
                None,
                None,
            )
            .unwrap();

        assert_eq!(proj.name, "Test Proj");
        let fetched_proj = store.get_project(&proj.id).unwrap();
        assert_eq!(fetched_proj.id, proj.id);

        let task = store
            .create_task(&proj.id, "Build feature X".into(), None, None, None)
            .unwrap();
        assert_eq!(task.goal, "Build feature X");
        assert_eq!(task.status, TaskStatus::Queued);

        let fetched_task = store.get_task(&task.id).unwrap();
        assert_eq!(fetched_task.id, task.id);

        let _ = std::fs::remove_dir_all(&temp_dir);
        let _ = std::fs::remove_dir_all(&proj_dir);
    }

    #[test]
    fn test_path_traversal_rejection() {
        let root_dir =
            std::env::temp_dir().join(format!("ghostlink_root_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&root_dir).unwrap();
        let root = root_dir.to_string_lossy().to_string();

        let valid = TaskRuntimeStore::validate_and_resolve_path(&root, "src/main.rs");
        assert!(valid.is_ok());

        let invalid = TaskRuntimeStore::validate_and_resolve_path(&root, "../../../etc/passwd");
        assert!(invalid.is_err());

        let _ = std::fs::remove_dir_all(&root_dir);
    }

    #[test]
    fn test_judge_policy() {
        assert_eq!(
            Judge::evaluate(&["ls".into(), "-la".into()]),
            JudgeResult::Allow
        );
        assert_eq!(
            Judge::evaluate(&["cargo".into(), "test".into()]),
            JudgeResult::Allow
        );
        assert_eq!(
            Judge::evaluate(&["git".into(), "status".into()]),
            JudgeResult::Allow
        );

        assert_eq!(
            Judge::evaluate(&["rm".into(), "-rf".into(), "/".into()]),
            JudgeResult::Deny
        );
        assert_eq!(
            Judge::evaluate(&["curl".into(), "http://example.com".into()]),
            JudgeResult::Deny
        );
        assert_eq!(
            Judge::evaluate(&["sudo".into(), "reboot".into()]),
            JudgeResult::Deny
        );

        assert_eq!(
            Judge::evaluate(&["custom_tool".into(), "arg".into()]),
            JudgeResult::Pause
        );
    }

    #[test]
    fn test_accept_reject_and_request_changes() {
        let temp_dir =
            std::env::temp_dir().join(format!("ghostlink_test_{}", uuid::Uuid::new_v4()));
        let store = TaskRuntimeStore::new(&temp_dir).unwrap();

        let proj_dir =
            std::env::temp_dir().join(format!("ghostlink_proj_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&proj_dir).unwrap();
        let root_str = proj_dir.to_string_lossy().to_string();

        let proj = store
            .create_project(
                "Sample".into(),
                ProjectKind::Code,
                root_str.clone(),
                None,
                None,
            )
            .unwrap();
        let task = store
            .create_task(&proj.id, "Add file".into(), None, None, None)
            .unwrap();

        // Write proposed file
        store
            .write_proposed_file(&root_str, &task.id, "hello.txt", "Hello World")
            .unwrap();

        let live_file = proj_dir.join("hello.txt");
        assert!(!live_file.exists());

        // Reject test
        store.discard_proposed_changes(&root_str, &task.id).unwrap();
        let proposed_dir = store.get_task_proposed_dir(&root_str, &task.id);
        assert!(!proposed_dir.exists());

        // Re-write proposed file & Accept test
        store
            .write_proposed_file(&root_str, &task.id, "hello.txt", "Hello World")
            .unwrap();
        let applied = store.apply_proposed_changes(&root_str, &task.id).unwrap();
        assert_eq!(applied, vec!["hello.txt"]);
        assert!(live_file.exists());
        assert_eq!(std::fs::read_to_string(&live_file).unwrap(), "Hello World");

        // Request changes test
        let requeued = store.requeue_task(&task.id).unwrap();
        assert_eq!(requeued.status, TaskStatus::Queued);

        let _ = std::fs::remove_dir_all(&temp_dir);
        let _ = std::fs::remove_dir_all(&proj_dir);
    }
}

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

    #[test]
    fn test_fanout_depth_and_child_caps() {
        let temp_dir = std::env::temp_dir().join(format!("ghostlink_fanout_{}", Uuid::new_v4()));
        let store = TaskRuntimeStore::new(&temp_dir).unwrap();

        let proj_dir =
            std::env::temp_dir().join(format!("ghostlink_fanout_proj_{}", Uuid::new_v4()));
        fs::create_dir_all(&proj_dir).unwrap();

        let proj = store
            .create_project(
                "Fanout Proj".into(),
                ProjectKind::Code,
                proj_dir.to_string_lossy().to_string(),
                None,
                None,
            )
            .unwrap();

        let parent = store
            .create_task(&proj.id, "Parent Goal".into(), None, None, None)
            .unwrap();

        // Create 4 children (max_children=4)
        for i in 0..4 {
            let child = store
                .create_task(
                    &proj.id,
                    format!("Child {}", i),
                    None,
                    None,
                    Some(parent.id.clone()),
                )
                .unwrap();
            assert_eq!(child.parent_id.as_deref(), Some(parent.id.as_str()));
        }

        // 5th child fails
        let child5_err = store.create_task(
            &proj.id,
            "Child 5".into(),
            None,
            None,
            Some(parent.id.clone()),
        );
        assert!(child5_err.is_err());
        assert!(child5_err
            .unwrap_err()
            .to_string()
            .contains("max_children=4"));

        // Sub-child fails (max_depth=1)
        let child1 = store
            .list_project_tasks(&proj.id)
            .unwrap()
            .into_iter()
            .find(|t| t.parent_id == Some(parent.id.clone()))
            .unwrap();
        let subchild_err = store.create_task(
            &proj.id,
            "Sub-child".into(),
            None,
            None,
            Some(child1.id.clone()),
        );
        assert!(subchild_err.is_err());
        assert!(subchild_err
            .unwrap_err()
            .to_string()
            .contains("max_depth=1"));

        // Parent accept blocked
        let check_accept = store.check_parent_accept_allowed(&proj.id, &parent.id);
        assert!(check_accept.is_err());

        // Cancel cascade
        let _ = store.cancel_task_run(&parent.id);
        let check_accept_after_cancel = store.check_parent_accept_allowed(&proj.id, &parent.id);
        assert!(check_accept_after_cancel.is_ok());

        let _ = fs::remove_dir_all(&temp_dir);
        let _ = fs::remove_dir_all(&proj_dir);
    }
}

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

    #[tokio::test]
    async fn test_parallel_isolated_tools_execution() {
        let temp_dir = std::env::temp_dir().join(format!("ghostlink_par_{}", Uuid::new_v4()));
        let store = Arc::new(TaskRuntimeStore::new(&temp_dir).unwrap());

        let proj_dir = std::env::temp_dir().join(format!("ghostlink_par_proj_{}", Uuid::new_v4()));
        fs::create_dir_all(&proj_dir).unwrap();
        fs::write(proj_dir.join("file1.txt"), "content 1").unwrap();
        fs::write(proj_dir.join("file2.txt"), "content 2").unwrap();

        let proj = store
            .create_project(
                "Parallel Proj".into(),
                ProjectKind::Code,
                proj_dir.to_string_lossy().to_string(),
                None,
                None,
            )
            .unwrap();

        let task = store
            .create_task(
                &proj.id,
                "Read two files in parallel".into(),
                None,
                None,
                None,
            )
            .unwrap();

        let responses = Arc::new(Mutex::new(vec![
            AgentResponse {
                content: Some("Reading files...".into()),
                tool_calls: vec![
                    ToolCall {
                        id: "call_1".into(),
                        name: "read_file".into(),
                        args: serde_json::json!({ "path": "file1.txt" }),
                    },
                    ToolCall {
                        id: "call_2".into(),
                        name: "read_file".into(),
                        args: serde_json::json!({ "path": "file2.txt" }),
                    },
                ],
                usage_tokens: None,
            },
            AgentResponse {
                content: Some("Done reading".into()),
                tool_calls: vec![],
                usage_tokens: None,
            },
        ]));

        let backend = Arc::new(FakeBackend { responses });
        let cancel_token = tokio_util::sync::CancellationToken::new();

        let run = TaskRunner::spawn_implementer_joined(
            store.clone(),
            backend,
            task.clone(),
            "implementer".into(),
            "test-model".into(),
            None,
            cancel_token,
        )
        .await
        .unwrap();

        assert_eq!(run.status, "finished");
        let review = store.get_task_review(&task.id).unwrap();
        assert_eq!(review.task_id, task.id);
    }

    #[tokio::test]
    async fn test_parent_review_waits_for_child_completion() {
        let temp_dir = std::env::temp_dir().join(format!("ghostlink_wait_{}", Uuid::new_v4()));
        let store = Arc::new(TaskRuntimeStore::new(&temp_dir).unwrap());

        let proj_dir = std::env::temp_dir().join(format!("ghostlink_wait_proj_{}", Uuid::new_v4()));
        fs::create_dir_all(&proj_dir).unwrap();

        let proj = store
            .create_project(
                "Wait Proj".into(),
                ProjectKind::Code,
                proj_dir.to_string_lossy().to_string(),
                None,
                None,
            )
            .unwrap();

        let parent_task = store
            .create_task(&proj.id, "Parent task goal".into(), None, None, None)
            .unwrap();

        let responses = Arc::new(Mutex::new(vec![
            AgentResponse {
                content: Some("Spawning child...".into()),
                tool_calls: vec![ToolCall {
                    id: "call_spawn".into(),
                    name: "spawn_subagent".into(),
                    args: serde_json::json!({ "goal": "Child goal" }),
                }],
                usage_tokens: None,
            },
            AgentResponse {
                content: Some("Parent finished".into()),
                tool_calls: vec![],
                usage_tokens: None,
            },
            AgentResponse {
                content: Some("Child finished".into()),
                tool_calls: vec![],
                usage_tokens: None,
            },
        ]));

        let backend = Arc::new(FakeBackend { responses });
        let cancel_token = tokio_util::sync::CancellationToken::new();

        let run = TaskRunner::spawn_implementer_joined(
            store.clone(),
            backend,
            parent_task.clone(),
            "planner".into(),
            "test-model".into(),
            None,
            cancel_token,
        )
        .await
        .unwrap();

        assert_eq!(run.status, "finished");
        let children = store.list_child_tasks(&parent_task.id).unwrap();
        assert_eq!(children.len(), 1);
    }

    #[tokio::test]
    async fn test_compact_review_diff_generation() {
        let temp_dir = std::env::temp_dir().join(format!("ghostlink_diff_{}", Uuid::new_v4()));
        let store = Arc::new(TaskRuntimeStore::new(&temp_dir).unwrap());

        let proj_dir = std::env::temp_dir().join(format!("ghostlink_diff_proj_{}", Uuid::new_v4()));
        fs::create_dir_all(&proj_dir).unwrap();
        fs::write(proj_dir.join("code.rs"), "fn hello() {}\n").unwrap();

        let proj = store
            .create_project(
                "Diff Proj".into(),
                ProjectKind::Code,
                proj_dir.to_string_lossy().to_string(),
                None,
                None,
            )
            .unwrap();

        let task = store
            .create_task(&proj.id, "Update code".into(), None, None, None)
            .unwrap();

        store
            .write_proposed_file(
                &proj.root_path,
                &task.id,
                "code.rs",
                "fn hello() {\n    println!(\"world\");\n}\n",
            )
            .unwrap();

        let responses = Arc::new(Mutex::new(vec![AgentResponse {
            content: Some("Done".into()),
            tool_calls: vec![],
            usage_tokens: None,
        }]));

        let backend = Arc::new(FakeBackend { responses });
        let cancel_token = tokio_util::sync::CancellationToken::new();

        let _run = TaskRunner::spawn_implementer_joined(
            store.clone(),
            backend,
            task.clone(),
            "implementer".into(),
            "test-model".into(),
            None,
            cancel_token,
        )
        .await
        .unwrap();

        let review = store.get_task_review(&task.id).unwrap();
        assert_eq!(review.diffs.len(), 1);
        assert!(review.diffs[0].unified_diff.contains("--- a/code.rs"));
        assert!(review.diffs[0].unified_diff.contains("+++ b/code.rs"));
        // The old implementation emitted a hardcoded `@@ -0,0 +1,3 @@`
        // regardless of content; assert real line numbers now.
        assert!(
            review.diffs[0].unified_diff.contains("@@ -1,1 +1,3 @@"),
            "expected a real hunk header, got:\n{}",
            review.diffs[0].unified_diff
        );
    }

    #[test]
    fn unified_diff_reports_real_hunk_headers() {
        let d = unified_diff(
            "a.rs",
            "fn hello() {}\n",
            "fn hello() {\n    println!(\"world\");\n}\n",
        );
        assert!(d.contains("@@ -1,1 +1,3 @@"), "{d}");
        assert!(d.contains("-fn hello() {}"), "{d}");
        assert!(d.contains("+    println!(\"world\");"), "{d}");
    }

    #[test]
    fn unified_diff_is_empty_when_unchanged() {
        assert_eq!(unified_diff("a.rs", "same\n", "same\n"), "");
    }

    #[test]
    fn unified_diff_handles_pure_insert_and_delete() {
        let added = unified_diff("a.rs", "", "new\n");
        assert!(added.contains("+new"), "{added}");

        let removed = unified_diff("a.rs", "gone\n", "");
        assert!(removed.contains("-gone"), "{removed}");
    }

    #[test]
    fn unified_diff_line_numbers_are_correct_mid_file() {
        let original: String = (1..=10).map(|i| format!("line{i}\n")).collect();
        let mut proposed: String = (1..=10).map(|i| format!("line{i}\n")).collect();
        proposed = proposed.replace("line7\n", "line7-changed\n");
        let d = unified_diff("f.rs", &original, &proposed);
        // Change is on line 7, so the hunk starts 3 lines earlier at line 4.
        assert!(d.contains("@@ -4,7 +4,7 @@"), "{d}");
    }

    #[tokio::test]
    async fn rollback_restores_overwritten_file_and_deletes_created_one() {
        let temp_dir = std::env::temp_dir().join(format!("ghostlink_rb_{}", Uuid::new_v4()));
        let store = Arc::new(TaskRuntimeStore::new(&temp_dir).unwrap());

        let proj_dir = std::env::temp_dir().join(format!("ghostlink_rb_proj_{}", Uuid::new_v4()));
        fs::create_dir_all(&proj_dir).unwrap();
        fs::write(proj_dir.join("existing.rs"), "ORIGINAL\n").unwrap();

        let proj = store
            .create_project(
                "RB Proj".into(),
                ProjectKind::Code,
                proj_dir.to_string_lossy().to_string(),
                None,
                None,
            )
            .unwrap();
        let task = store
            .create_task(&proj.id, "Mutate".into(), None, None, None)
            .unwrap();

        // Overwrite one existing file and create one brand-new file.
        store
            .write_proposed_file(&proj.root_path, &task.id, "existing.rs", "CLOBBERED\n")
            .unwrap();
        store
            .write_proposed_file(&proj.root_path, &task.id, "brand_new.rs", "NEW\n")
            .unwrap();

        let applied = store
            .apply_proposed_changes(&proj.root_path, &task.id)
            .unwrap();
        assert_eq!(applied.len(), 2);
        assert_eq!(
            fs::read_to_string(proj_dir.join("existing.rs")).unwrap(),
            "CLOBBERED\n"
        );
        assert!(proj_dir.join("brand_new.rs").exists());

        let touched = store
            .rollback_applied_changes(&proj.root_path, &task.id)
            .unwrap();
        assert_eq!(touched.len(), 2);
        // Overwritten file is restored...
        assert_eq!(
            fs::read_to_string(proj_dir.join("existing.rs")).unwrap(),
            "ORIGINAL\n"
        );
        // ...and the created file is removed.
        assert!(!proj_dir.join("brand_new.rs").exists());

        // A second rollback must fail rather than silently succeed.
        assert!(store
            .rollback_applied_changes(&proj.root_path, &task.id)
            .is_err());
    }

    #[test]
    fn rollback_without_snapshot_errors() {
        let temp_dir = std::env::temp_dir().join(format!("ghostlink_rb2_{}", Uuid::new_v4()));
        let store = Arc::new(TaskRuntimeStore::new(&temp_dir).unwrap());
        let proj_dir = std::env::temp_dir().join(format!("ghostlink_rb2_proj_{}", Uuid::new_v4()));
        fs::create_dir_all(&proj_dir).unwrap();
        let proj = store
            .create_project(
                "P".into(),
                ProjectKind::Code,
                proj_dir.to_string_lossy().to_string(),
                None,
                None,
            )
            .unwrap();
        let task = store
            .create_task(&proj.id, "g".into(), None, None, None)
            .unwrap();
        assert!(store
            .rollback_applied_changes(&proj.root_path, &task.id)
            .is_err());
    }

    fn msg(role: &str, content: &str) -> serde_json::Value {
        serde_json::json!({ "role": role, "content": content })
    }

    #[test]
    fn governor_keeps_short_transcripts_intact() {
        let g = ContextGovernor {
            token_budget: 100_000,
            reserve_completion_tokens: 0,
            keep_last_turns: 6,
        };
        let msgs = vec![
            msg("system", "sys"),
            msg("user", "goal"),
            msg("assistant", "a1"),
            msg("user", "t1"),
        ];
        let (fitted, dropped) = g.fit(&msgs);
        assert_eq!(dropped, 0);
        assert_eq!(fitted.len(), msgs.len());
    }

    #[test]
    fn governor_pins_system_and_goal_and_keeps_recent_turns() {
        // Tiny budget so older turns cannot fit.
        let g = ContextGovernor {
            token_budget: 40,
            reserve_completion_tokens: 0,
            keep_last_turns: 2,
        };
        let mut msgs = vec![msg("system", "SYSTEM-PROMPT"), msg("user", "TASK-GOAL")];
        for i in 0..20 {
            msgs.push(msg(
                "assistant",
                &format!("assistant turn number {i} padding padding"),
            ));
        }
        let (fitted, dropped) = g.fit(&msgs);
        assert!(dropped > 0, "expected compaction, got none");

        let text: String = fitted
            .iter()
            .filter_map(|m| m.get("content").and_then(|c| c.as_str()))
            .collect::<Vec<_>>()
            .join("|");
        // Pinned prefix survives...
        assert!(text.contains("SYSTEM-PROMPT"), "{text}");
        assert!(text.contains("TASK-GOAL"), "{text}");
        // ...and the most recent turn survives, while an early one is gone.
        assert!(text.contains("assistant turn number 19"), "{text}");
        assert!(!text.contains("assistant turn number 0 "), "{text}");
    }

    #[test]
    fn governor_never_drops_below_pinned_prefix() {
        // Budget smaller than the pinned prompt itself.
        let g = ContextGovernor {
            token_budget: 4,
            reserve_completion_tokens: 0,
            keep_last_turns: 0,
        };
        let msgs = vec![
            msg(
                "system",
                "a-very-long-system-prompt-that-exceeds-the-budget",
            ),
            msg("user", "the-goal"),
            msg("assistant", "x"),
        ];
        let (fitted, _dropped) = g.fit(&msgs);
        assert!(fitted.len() >= 2, "pinned prefix must survive: {fitted:?}");
        let text: String = fitted
            .iter()
            .filter_map(|m| m.get("content").and_then(|c| c.as_str()))
            .collect::<Vec<_>>()
            .join("|");
        assert!(text.contains("a-very-long-system-prompt"), "{text}");
        assert!(text.contains("the-goal"), "{text}");
    }

    #[test]
    fn governor_reserves_completion_budget() {
        let msgs: Vec<serde_json::Value> = (0..50)
            .map(|_| msg("assistant", &"x".repeat(400)))
            .collect();
        // ~100 tokens/msg. With a 1000 budget and 900 reserved, little fits
        // beyond the pinned prefix.
        let g = ContextGovernor {
            token_budget: 1000,
            reserve_completion_tokens: 900,
            keep_last_turns: 1,
        };
        let (fitted, _d) = g.fit(&msgs);
        assert!(fitted.len() < msgs.len());
        // keep_last_turns still guarantees the most recent message.
        assert!(fitted.len() >= 3, "{fitted:?}");
    }

    // ---- Verification -----------------------------------------------------

    #[test]
    fn verification_plan_detects_cargo_project() {
        let dir = std::env::temp_dir().join(format!("gl_vp_cargo_{}", Uuid::new_v4()));
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("Cargo.toml"), "[workspace]\n").unwrap();

        let plan = VerificationPlan::detect(&dir.to_string_lossy()).expect("should detect");
        assert!(plan.required);
        assert_eq!(plan.commands, vec![vec!["cargo", "test", "--workspace"]]);
        // A detected plan must never contain something the Judge would refuse.
        assert!(plan.disallowed_commands().is_empty());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn verification_plan_requires_a_package_test_script() {
        let dir = std::env::temp_dir().join(format!("gl_vp_npm_{}", Uuid::new_v4()));
        fs::create_dir_all(&dir).unwrap();

        // No test script -> not a verification target.
        fs::write(
            dir.join("package.json"),
            r#"{"scripts":{"build":"vite build"}}"#,
        )
        .unwrap();
        assert!(VerificationPlan::detect(&dir.to_string_lossy()).is_none());

        // With one -> detected.
        fs::write(
            dir.join("package.json"),
            r#"{"scripts":{"test":"vitest run"}}"#,
        )
        .unwrap();
        let plan = VerificationPlan::detect(&dir.to_string_lossy()).expect("should detect");
        assert_eq!(plan.commands, vec![vec!["npx", "vitest", "run"]]);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn verification_plan_none_for_unknown_project() {
        let dir = std::env::temp_dir().join(format!("gl_vp_none_{}", Uuid::new_v4()));
        fs::create_dir_all(&dir).unwrap();
        assert!(VerificationPlan::detect(&dir.to_string_lossy()).is_none());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn verification_plan_flags_disallowed_commands() {
        // A plan asking for something the Judge denies must be reportable,
        // not silently executed.
        let plan = VerificationPlan {
            commands: vec![
                vec!["cargo".into(), "test".into()],
                vec!["rm".into(), "-rf".into(), "/".into()],
            ],
            required: true,
        };
        let bad = plan.disallowed_commands();
        assert_eq!(bad.len(), 1);
        assert_eq!(bad[0][0], "rm");
    }

    #[tokio::test]
    async fn verification_runs_commands_and_reports_failures() {
        let dir = std::env::temp_dir().join(format!("gl_vr_{}", Uuid::new_v4()));
        fs::create_dir_all(&dir).unwrap();

        // `cargo test` with no Cargo.toml fails; `cargo check` likewise. Use
        // two allowed commands so we exercise both pass and fail paths without
        // depending on a toolchain being present for a real test run.
        let plan = VerificationPlan {
            commands: vec![
                // `cargo check` in an empty dir exits non-zero -> failure path
                vec!["cargo".into(), "check".into()],
            ],
            required: true,
        };
        let results = run_verification_plan(
            &plan,
            &dir.to_string_lossy(),
            std::time::Duration::from_secs(120),
        )
        .await;

        assert_eq!(results.len(), 1);
        // Either it ran and failed (no manifest), or the toolchain is absent and
        // it failed to spawn — both are `passed == false`, which is the point.
        assert!(!results[0].passed, "expected failure: {:?}", results[0]);
        assert!(results[0].summary().contains("FAIL") || results[0].summary().contains("TIMED"));

        let _ = fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn verification_refuses_disallowed_command() {
        let dir = std::env::temp_dir().join(format!("gl_vr2_{}", Uuid::new_v4()));
        fs::create_dir_all(&dir).unwrap();

        let plan = VerificationPlan {
            commands: vec![vec!["sudo".into(), "rm".into(), "-rf".into(), "/".into()]],
            required: true,
        };
        let results = run_verification_plan(
            &plan,
            &dir.to_string_lossy(),
            std::time::Duration::from_secs(5),
        )
        .await;
        assert_eq!(results.len(), 1);
        assert!(!results[0].passed);
        assert!(results[0].excerpt.contains("Refused"), "{:?}", results[0]);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn verification_passed_distinguishes_unverified_from_failed() {
        // The distinction that matters: no results is NOT the same as passing.
        let empty = ReviewPacket {
            id: "r".into(),
            task_id: "t".into(),
            run_id: "run".into(),
            summary: String::new(),
            diffs: vec![],
            commands: vec![],
            checks: vec![],
            risks: vec![],
            verification: vec![],
            created_at: String::new(),
        };
        assert_eq!(
            empty.verification_passed(),
            None,
            "unverified is not 'passed'"
        );

        let failed = ReviewPacket {
            verification: vec![VerificationResult {
                argv: vec!["cargo".into(), "test".into()],
                exit: 101,
                passed: false,
                excerpt: String::new(),
                timed_out: false,
            }],
            ..empty.clone()
        };
        assert_eq!(failed.verification_passed(), Some(false));

        let ok = ReviewPacket {
            verification: vec![VerificationResult {
                argv: vec!["cargo".into(), "test".into()],
                exit: 0,
                passed: true,
                excerpt: String::new(),
                timed_out: false,
            }],
            ..empty.clone()
        };
        assert_eq!(ok.verification_passed(), Some(true));
    }
}