car-server-core 0.52.1

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

use car_engine::{builtin_tool_labels, format_tool_result, tool_output_is_external, Runtime};
use car_inference::tasks::generate::{ContentBlock, Message, Provenance, ToolCall};
use car_inference::{GenerateParams, GenerateRequest};
use car_ir::{ActionProposal, ActionStatus};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use super::memory::MemoryTools;
use crate::coder::native_loop::TurnGenerator;

/// Upper bound (bytes) on a single tool observation fed back into context, so a
/// large read/output can't blow the request size. Truncates on a char boundary.
///
/// Public because it is the threshold the whole `value_store_previews` A/B
/// turns on: below it both arms render identically, so a benchmark suite whose
/// observations all fit measures nothing. `car-bench`'s harness suite has a
/// guard test asserting its held-out split still contains a task that clears
/// this number, and that test has to read the real constant — a copy of `16 *
/// 1024` in the bench would go stale the day this one moved, and the A/B would
/// go quietly inert again.
pub const OBSERVATION_CAP: usize = 16 * 1024;

/// The shipped default for [`AssistantConfig::value_store_previews`] — the one
/// place any production call site reads it from, so "what does CAR do out of the
/// box" is a single greppable fact rather than a literal repeated at the four
/// production construction sites (`car do` twice, the MCP assistant, and coder
/// discussions), which can drift apart. The remaining hard-coded `false`s in the
/// workspace are deliberate and stay: eight test fixtures in `chat.rs`, this
/// module's own off-arm fixture, and `HarnessBenchConfig`, whose `false` names
/// the *truncating arm* of the A/B rather than a product setting.
///
/// `no_production_call_site_hard_codes_the_preview_default` (here, and its twin
/// in `car-cli`) is what keeps that true — pinning the constant's value alone
/// would let a re-hardcoded literal reinstate the old default with every test
/// still green.
///
/// **`false`, confirmed by the measured A/B on 2026-08-27**, which is what
/// Parslee-ai/car#813 asked for before this shape changed. Three paired
/// replicates of `car-bench-harness --split all` (29 tasks, model
/// `anthropic/claude-sonnet-5`, seed 0), off arm versus `--value-store-previews`:
///
/// | mean over 3 reps | off (truncating) | on (retained previews) |
/// |---|---|---|
/// | pass rate | 0.967 | **1.000** |
/// | model calls / task | 2.235 | 2.407 (**+7.7%**) |
/// | tokens / task | 14,467.7 | **10,073.1 (−30.4%)** |
///
/// **#813's stated trigger did not fire:** it asked for fewer model calls at
/// equal-or-better pass rate without a token blow-up, and calls rose 7.7% while
/// tokens fell 30.4%. The run also did not count actual `$rN` resolutions, so it
/// cannot attribute the extra calls to handle use rather than repeated tools.
/// With one model, three replicates, fixed arm order, and substantial variance
/// on byte-identical below-cap tasks, the pass-rate and token results do not
/// justify overriding the calls criterion. The conservative measured decision
/// is therefore to keep the product default off and improve/re-measure the
/// preview format before any wider rollout.
///
/// The measurement, caveats, and how to re-run it:
/// `docs/solutions/value-store-previews-ab-2026-08-27.md`.
pub const VALUE_STORE_PREVIEWS_DEFAULT: bool = false;

/// Streamed events from one loop run. `emit` is called synchronously as the loop
/// progresses; a chat caller forwards these to `agent.chat.event`, a CLI caller
/// prints them.
pub enum AssistantEvent {
    /// The model's free-text for a turn (may be empty when it only calls tools).
    Text(String),
    /// A tool is about to run.
    ToolCall { name: String, params: Value },
    /// A tool finished. `ok` is false for a failed/denied call.
    ToolResult {
        name: String,
        ok: bool,
        content: String,
    },
    /// Terminal: the model answered with no further tool calls.
    Done { text: String },
    /// Terminal: the run failed (inference/transport error).
    Error(String),
    /// Goal-loop verifier result after one iteration. This surfaces CAR's
    /// grounded completion evidence to CLI/chat hosts instead of hiding it in
    /// tracing logs.
    GoalEvaluated {
        iteration: u32,
        met: bool,
        grounded: bool,
        reason: String,
    },
}

/// Static configuration for a loop run.
#[derive(Clone)]
pub struct AssistantConfig {
    /// Model id, or `None` to let the router choose (pin a tool-capable model
    /// for real tool use — the local completion path ignores tools).
    pub model: Option<String>,
    /// Fail on the selected model rather than silently substituting another.
    /// Native chat enables this only for an explicit per-turn selection.
    pub strict_model: bool,
    /// Hard cap on loop turns.
    pub max_turns: u32,
    /// The model-visible tool list (from `GeneralExecutor::all_tool_defs()`).
    pub tools: Vec<Value>,
    /// Tool names that require human approval before running (the standing tier
    /// doesn't auto-allow them, e.g. writes/shell on the local host without
    /// `--full-access`). Empty when the tier auto-allows everything.
    pub gated_tools: Vec<String>,
    /// Optional per-agent approval policy. Given a tool name + params, returns
    /// whether to allow, require approval, or deny — the runtime enforcement of
    /// the `agent_permissions.*` posture for the running agent. When set it
    /// takes precedence over `gated_tools`; when `None`, `gated_tools` (the
    /// standing-tier list) applies, so existing callers are unchanged.
    pub approval_policy: Option<ApprovalPolicyFn>,
    /// Host-side proactive memory bank for the assistant loop. When present, CAR
    /// runs a deterministic memory-maintenance + selective-intervention pass
    /// before each model turn, so long-running agents do not depend on the model
    /// remembering to call `recall` at the right time.
    pub proactive_memory: Option<Arc<MemoryTools>>,
    /// Information-flow tool labels used to classify whether a tool result came
    /// from outside the trust boundary (car#723).
    ///
    /// `None` falls back to [`car_engine::builtin_tool_labels`], so the
    /// network-reaching commodity tools are always classified even when a caller
    /// supplies nothing. Deliberately `Option<_>` rather than a plain map with a
    /// `Default`: an empty map would silently classify everything as internal,
    /// and a security marking that a forgotten field can switch off is not one.
    /// Callers that load `.car/tool-labels.json` should pass the merged map so a
    /// project's own `trust: untrusted` declarations are honoured here too.
    pub tool_labels: Option<HashMap<String, car_verify::infoflow::ToolLabels>>,
    /// The run's task list, rendered into a per-turn state block at the tail of
    /// the request (Parslee-ai/car#814 items 2-3). `None` renders no block.
    pub todos: Option<Arc<tokio::sync::Mutex<super::todo::TodoList>>>,
    /// Retain tool results for the run and put a typed bounded preview in the
    /// transcript, instead of destructively truncating (Parslee-ai/car#813).
    ///
    /// Production call sites pass [`VALUE_STORE_PREVIEWS_DEFAULT`], which is
    /// `false` because the measured A/B did not meet #813's fewer-model-calls
    /// criterion. See that constant for the results and caveats.
    ///
    /// Still a field rather than a constant read inside the loop, because the
    /// bench needs both arms in one binary and a caller may want the old shape.
    /// With this `false` the observation path is byte-for-byte what it was:
    /// `cap()`, same cap, same notice.
    ///
    /// Below [`OBSERVATION_CAP`] the two arms *render* identically — the flag
    /// can only change an observation that crosses the cap. Note the flag also
    /// gates `SessionValues::resolve_refs` on every tool call, so once a handle
    /// exists a later below-cap call whose argument is a `$rN` reference is
    /// rewritten on the on arm only. That is a no-op until something over the
    /// cap has been retained; it is not the same statement as "nothing below
    /// the cap can ever differ".
    pub value_store_previews: bool,
    /// Constrain the run's FINAL answer to JSON. Applies to the answer, not
    /// to the work: it is NOT sent on any turn that offers tools, because a
    /// JSON-constrained request suppresses tool use on real providers (GLM
    /// 5.3 Flash answered in one turn without a single tool call under
    /// `json_object`; the same goal unconstrained ran two delegations and two
    /// reads and got it right). The loop instead checks the final
    /// no-tool-call answer itself and, only if it is not the requested shape,
    /// re-asks ONCE with no tools and `response_format` set — see
    /// [`final_text_matches_format`] and the repair branch. A run that offers
    /// no tools at all has nothing to suppress and carries the format on
    /// every turn. A final answer that already parses costs no extra call.
    ///
    /// `None` is the correct default for every caller that does not consume
    /// the answer as data. A knob that tightens the output contract, never a
    /// toggle between implementations (CLAUDE.md rule 1a). Provider-dependent:
    /// the Anthropic protocol rejects it up front (`UnsupportedMode`).
    pub response_format: Option<car_inference::ResponseFormat>,
    /// Override the context window (tokens) that bounds the running history
    /// each turn. `None` uses the registry's window for `model` (`0` when
    /// unknown, which disables compaction). Resolved through
    /// [`resolve_context_window`], which clamps a value ABOVE a known registry
    /// window back down to it: compaction exists to stop provider-side
    /// truncation of the original task (see `compact_history_to_window`), and
    /// a window larger than the real one would recreate exactly that. A value
    /// below the registry window is honored as-is — it only tightens.
    pub context_window_override: Option<usize>,
    /// Refuse any tool call whose name is not among `tools` with an error
    /// result, before approval or dispatch. Set on a `delegate` child so the
    /// tool subset it was granted holds at EXECUTION, not just advertisement:
    /// every tool is registered with the runtime, so a hallucinated call to an
    /// ungranted one would otherwise run (the same reason `run_task`'s GUI
    /// sub-agent enforces its restriction on the call, not the def).
    ///
    /// `false` everywhere else, so existing callers whose advertised list is
    /// deliberately narrower than the registry keep today's behavior.
    pub refuse_unadvertised_tools: bool,
    /// Validates a parsed final answer against the caller's JSON Schema.
    /// Carried as a closure so `car-server-core` needs no schema-validation
    /// dependency: `car-cli` compiles the `--json-schema` file with the
    /// `jsonschema` crate it already has and passes `Validator::is_valid`
    /// here. Without it a `JsonSchema` format is parse-only in the loop — and
    /// since tool turns never carry the format on the wire, NOBODY would
    /// enforce the schema on a tool-bearing run. Ignored for `JsonObject`.
    pub response_format_validator: Option<ResponseFormatValidator>,
    /// Run-level ceiling on `delegate` use. `None` applies
    /// [`DelegateBudget::default`] (20 delegations, 300 child turns); a call
    /// past either limit is an error result, never a spawn. Per parent run —
    /// children cannot delegate, so nothing nests under it.
    pub delegate_budget: Option<DelegateBudget>,
}

/// A compiled JSON-Schema check for the final answer — `true` when the parsed
/// answer conforms. See [`AssistantConfig::response_format_validator`].
pub type ResponseFormatValidator = Arc<dyn Fn(&Value) -> bool + Send + Sync>;

/// How much delegating one run may do, whatever each child's own cap says.
/// Bounds the model-call amplification a delegating parent can cause: without
/// it a parent at `max_turns` 50 could issue 50 children of 60 turns each.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DelegateBudget {
    /// Delegations that may be spawned in one run.
    pub max_delegations: u32,
    /// Child turns, summed over every delegation in the run.
    pub max_child_turns: u32,
}

impl Default for DelegateBudget {
    fn default() -> Self {
        Self {
            max_delegations: 20,
            max_child_turns: 300,
        }
    }
}

/// The effective context window for a run: the caller's override, clamped to
/// the registry window when that is known and smaller. Returns the window plus
/// an advisory when the clamp fired, so the caller can surface it.
///
/// `registry_window == 0` means "unknown" (local/test generators): an override
/// is then taken at face value, because there is nothing to clamp against and
/// the alternative — ignoring it — would silently disable the compaction the
/// caller asked for.
pub fn resolve_context_window(
    override_tokens: Option<usize>,
    registry_window: usize,
) -> (usize, Option<String>) {
    match override_tokens {
        None => (registry_window, None),
        Some(requested) if registry_window > 0 && requested > registry_window => (
            registry_window,
            Some(format!(
                "context window override {requested} exceeds the model's known window \
                 {registry_window}; using {registry_window} (a larger value would let the \
                 history overflow the real window and truncate the task provider-side, \
                 which is what compaction exists to prevent)"
            )),
        ),
        Some(requested) => (requested, None),
    }
}

/// Does a final answer satisfy the requested [`car_inference::ResponseFormat`]?
///
/// `JsonObject` requires a JSON *object*; `JsonSchema` requires parseable JSON
/// that also satisfies `validator` when the caller supplied one (the CLI
/// compiles the schema file and passes its check in) — parse-only without one,
/// deliberately not a partial schema re-implementation in this crate.
/// Tolerates a ```json fence around the payload, which models emit even under
/// JSON mode; the caller strips it via [`extract_json_payload`].
pub fn final_text_matches_format(
    text: &str,
    format: &car_inference::ResponseFormat,
    validator: Option<&ResponseFormatValidator>,
) -> bool {
    let payload = extract_json_payload(text);
    match format {
        car_inference::ResponseFormat::JsonObject => {
            serde_json::from_str::<Value>(payload).is_ok_and(|v| v.is_object())
        }
        car_inference::ResponseFormat::JsonSchema { .. } => {
            match serde_json::from_str::<Value>(payload) {
                // The schema itself, when the caller compiled one. Parse-only
                // otherwise (this crate carries no validator of its own).
                Ok(v) => validator.is_none_or(|is_valid| is_valid(&v)),
                Err(_) => false,
            }
        }
    }
}

/// Strip a single surrounding ``` / ```json fence, if present. Returns the
/// trimmed input otherwise.
pub fn extract_json_payload(text: &str) -> &str {
    let t = text.trim();
    let Some(rest) = t.strip_prefix("```") else {
        return t;
    };
    let Some(rest) = rest.strip_suffix("```") else {
        return t;
    };
    // Drop an optional language tag on the opening fence line.
    let rest = match rest.split_once('\n') {
        Some((tag, body)) if tag.trim().chars().all(|c| c.is_ascii_alphanumeric()) => body,
        _ => rest,
    };
    rest.trim()
}

/// The one-shot nudge sent when the final answer did not match the requested
/// format. Delivered as a user-role message: `Message::System` appears once at
/// the head of a conversation, and a mid-transcript system message is not a
/// shape every provider accepts.
const FORMAT_REPAIR_NUDGE: &str =
    "Your previous answer was not the requested JSON. Return only the JSON object — \
     no prose, no code fence, no tool calls.";
/// Schema variant of the nudge — a schema's root need not be an object, so it
/// must not say "object".
const FORMAT_REPAIR_NUDGE_SCHEMA: &str =
    "Your previous answer did not match the required JSON Schema. Return only JSON that \
     conforms to the schema — no prose, no code fence, no tool calls.";

/// The nudge for one format.
fn format_repair_nudge(format: &car_inference::ResponseFormat) -> &'static str {
    match format {
        car_inference::ResponseFormat::JsonObject => FORMAT_REPAIR_NUDGE,
        car_inference::ResponseFormat::JsonSchema { .. } => FORMAT_REPAIR_NUDGE_SCHEMA,
    }
}

/// Emitted (as [`AssistantEvent::Text`]) when the repair fires, so the run's
/// event stream records that the final answer was re-asked rather than taken
/// as returned.
pub const FORMAT_REPAIR_NOTICE: &str =
    "[format repair: final answer was not the requested JSON; re-asked the model once with no tools]";
/// Emitted when the single repair also missed. The repaired text is still the
/// answer — the contract is "one repair", not "retry until valid".
pub const FORMAT_REPAIR_STILL_INVALID: &str =
    "[format repair: the repaired answer still does not match the requested format; returning it as-is]";
/// Prefix of the notice emitted when the repair call itself failed (for
/// example an Anthropic-protocol model rejecting `response_format`). The DRAFT
/// answer is returned — a provider that cannot enforce the format is not a
/// reason to throw away the answer the model already gave.
pub const FORMAT_REPAIR_FAILED_PREFIX: &str = "[format repair failed:";

/// The loop-intercepted sub-agent tool. Advertised like any other tool (so a
/// caller can allowlist or omit it) but never dispatched to the executor: the
/// loop recognizes the name and runs a child loop in-process — the same shape
/// as `run_task`'s GUI sub-agent, chosen over a `ToolExecutor` because an
/// executor is built before the `Runtime` and `AssistantConfig` a child needs.
pub const DELEGATE_TOOL: &str = "delegate";
/// Child turn budget when the call names none.
pub const DELEGATE_DEFAULT_MAX_TURNS: u32 = 25;
/// Hard ceiling on a child's turn budget, whatever the call asks for.
pub const DELEGATE_MAX_TURNS_CAP: u32 = 60;

/// The names advertised in `tools`, minus [`DELEGATE_TOOL`] — what a child may
/// be granted. The delegate itself is excluded on purpose: no nesting in v1.
fn delegable_tool_names(tools: &[Value]) -> Vec<String> {
    tools
        .iter()
        .filter_map(|d| d.get("name").and_then(Value::as_str))
        .filter(|n| *n != DELEGATE_TOOL)
        .map(str::to_string)
        .collect()
}

/// Build the `delegate` tool def over the parent's advertised tools. The
/// `tools` parameter is a JSON-Schema `enum` of the parent's own tool names —
/// the verifiable subset precondition `car-multi`'s `spawn_subtask` uses — so
/// the validator rejects an escalation before the loop's own check does.
///
/// `tier: read_only`: the delegation itself changes nothing; the CHILD's calls
/// are what the gates see, and it inherits every gate the parent has.
/// `mutating: true` so a delegation that FINISHES counts as progress for the
/// no-progress guard (it is a real action, not a re-read); one that stalls,
/// errors, or hits its cap returns `ok: false` and does not.
pub fn delegate_tool_def(parent_tools: &[Value]) -> Value {
    let names = delegable_tool_names(parent_tools);
    json!({
        "name": DELEGATE_TOOL,
        "tier": "read_only",
        "mutating": true,
        "description": "Hand one self-contained sub-task to a fresh sub-agent that shares \
            your model, permissions, and working directory but starts with an EMPTY \
            transcript: it sees only the goal you write, not this conversation. Use it \
            to keep a long exploration or a noisy batch of tool output out of your own \
            context. It runs to completion before this call returns and you receive \
            ONLY its final written answer, so put everything it needs in `goal` and \
            ask it to report exactly what you need back. It cannot delegate further.",
        "parameters": {
            "type": "object",
            "properties": {
                "goal": {
                    "type": "string",
                    "description": "The single, self-contained task, with all the context the sub-agent needs and what to report back."
                },
                "tools": {
                    "type": "array",
                    "items": { "type": "string", "enum": names },
                    "description": "Tools to grant the sub-agent. Must be a subset of your own; omit for all of them."
                },
                "max_turns": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": DELEGATE_MAX_TURNS_CAP,
                    "description": "Turn budget for the sub-agent (default 25). It reports an error if it runs out."
                }
            },
            "required": ["goal"]
        }
    })
}

/// A parsed `delegate` call.
#[derive(Debug, Clone, PartialEq)]
pub struct DelegateRequest {
    pub goal: String,
    /// `None` = the parent's whole (delegable) set.
    pub tools: Option<Vec<String>>,
    pub max_turns: u32,
}

/// Parse the call's arguments. Shape errors are the model's to fix, so they
/// come back as an error result rather than sinking the run.
pub fn parse_delegate_params(params: &Value) -> Result<DelegateRequest, String> {
    let goal = params
        .get("goal")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|g| !g.is_empty())
        .ok_or("delegate needs a non-empty `goal` string")?
        .to_string();
    let tools = match params.get("tools") {
        None | Some(Value::Null) => None,
        Some(Value::Array(items)) => Some(
            items
                .iter()
                .map(|v| {
                    v.as_str().map(str::to_string).ok_or_else(|| {
                        "delegate `tools` must be an array of tool names".to_string()
                    })
                })
                .collect::<Result<Vec<_>, _>>()?,
        ),
        Some(_) => return Err("delegate `tools` must be an array of tool names".into()),
    };
    let max_turns = match params.get("max_turns") {
        None | Some(Value::Null) => DELEGATE_DEFAULT_MAX_TURNS,
        Some(v) => {
            let n = v
                .as_u64()
                .filter(|n| *n >= 1)
                .ok_or("delegate `max_turns` must be a positive integer")?;
            (n.min(DELEGATE_MAX_TURNS_CAP as u64)) as u32
        }
    };
    Ok(DelegateRequest {
        goal,
        tools,
        max_turns,
    })
}

/// Derive the child's config from the parent's. Everything is the parent's
/// (`clone()`) except:
/// * `tools` — the requested subset of the parent's delegable tools (default:
///   all of them), never including `delegate` itself. A name outside the
///   parent's set is an escalation and is refused here, mirroring
///   `spawn_subtask`'s defense-in-depth check behind its schema enum.
/// * `refuse_unadvertised_tools` — on, so the subset holds at execution.
/// * `max_turns` — the call's (capped) budget.
/// * `todos` — none; the parent's task list is not the child's.
/// * `response_format` — none; children answer in prose that the parent reads.
/// `gated_tools`, `approval_policy`, `model`, `strict_model`,
/// `context_window_override`, `proactive_memory`, `tool_labels` and
/// `value_store_previews` are inherited unchanged: a child can do nothing its
/// parent could not.
pub fn delegate_child_config(
    parent: &AssistantConfig,
    req: &DelegateRequest,
) -> Result<AssistantConfig, String> {
    let delegable = delegable_tool_names(&parent.tools);
    let requested: Vec<String> = match &req.tools {
        Some(list) => list.clone(),
        None => delegable.clone(),
    };
    let escalations: Vec<&String> = requested
        .iter()
        .filter(|t| !delegable.iter().any(|d| d == *t))
        .collect();
    if !escalations.is_empty() {
        let nested = escalations.iter().any(|t| *t == DELEGATE_TOOL);
        return Err(format!(
            "privilege escalation rejected: sub-agent tools {escalations:?} are not a subset of \
             your own tools{}",
            if nested {
                " (a sub-agent cannot delegate further)"
            } else {
                ""
            }
        ));
    }
    let tools: Vec<Value> = parent
        .tools
        .iter()
        .filter(|d| {
            d.get("name")
                .and_then(Value::as_str)
                .is_some_and(|n| requested.iter().any(|r| r == n))
        })
        .cloned()
        .collect();
    Ok(AssistantConfig {
        tools,
        refuse_unadvertised_tools: true,
        response_format_validator: None,
        delegate_budget: None,
        max_turns: req.max_turns,
        todos: None,
        response_format: None,
        ..parent.clone()
    })
}

/// The child's starting transcript: the parent's leading system prompt(s) and
/// the goal — nothing else from the parent. A fresh context is the point.
fn delegate_child_history(parent_messages: &[Message], goal: &str) -> Vec<Message> {
    let mut history: Vec<Message> = parent_messages
        .iter()
        .take_while(|m| matches!(m, Message::System { .. }))
        .cloned()
        .collect();
    history.push(Message::User {
        content: goal.to_string(),
    });
    history
}

/// What a finished delegation hands back to the parent's transcript.
struct DelegateOutcome {
    ok: bool,
    /// The tool-result content: the child's final text (capped) on success, a
    /// JSON error carrying the reason otherwise.
    content: String,
    turns: u32,
    /// Whether any of the child's tool results crossed the trust boundary,
    /// so the parent's `ToolResult` is marked accordingly.
    external: bool,
    /// The child's own receipts, for the parent to merge (tagged `via`).
    receipts: Vec<AssistantToolReceipt>,
    /// Whether a child loop actually ran (a parse or escalation refusal does
    /// not count against the run's delegation budget).
    spawned: bool,
}

/// Run one `delegate` call to completion. Sequential and in-process: the
/// parent's turn does not continue until the child returns.
///
/// Returns an explicitly boxed `dyn Future + Send` rather than being an
/// `async fn`: the loop awaits this, and this awaits the loop, so an inferred
/// future type would leave `Send` as an unsolvable cycle ("cannot satisfy …:
/// Send"). Naming the type here is what lets callers `tokio::spawn` the loop.
#[allow(clippy::too_many_arguments)]
fn run_delegate<'a>(
    generator: &'a dyn TurnGenerator,
    runtime: &'a Runtime,
    parent: &'a AssistantConfig,
    parent_messages: &'a [Message],
    params: &'a Value,
    cancel: &'a std::sync::atomic::AtomicBool,
    approval: Option<&'a dyn ApprovalGate>,
    runtime_session_id: Option<&'a str>,
    redrive_ungrounded_summary: bool,
    tool_labels: &'a HashMap<String, car_verify::infoflow::ToolLabels>,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = DelegateOutcome> + Send + 'a>> {
    Box::pin(async move {
        let req = match parse_delegate_params(params) {
            Ok(r) => r,
            Err(e) => {
                return DelegateOutcome {
                    ok: false,
                    content: cap(json!({ "error": e }).to_string()),
                    turns: 0,
                    external: false,
                    receipts: Vec::new(),
                    spawned: false,
                }
            }
        };
        let child_cfg = match delegate_child_config(parent, &req) {
            Ok(c) => c,
            Err(e) => {
                return DelegateOutcome {
                    ok: false,
                    content: cap(json!({ "error": e }).to_string()),
                    turns: 0,
                    external: false,
                    receipts: Vec::new(),
                    spawned: false,
                }
            }
        };
        let mut child_messages = delegate_child_history(parent_messages, &req.goal);
        // The child's events stay inside the child: the parent's stream records
        // the delegation as ONE tool call + result (+ a one-line summary), which is
        // what a `--json` consumer can attribute. `&mut dyn FnMut` on purpose —
        // a fresh closure type here would re-instantiate the generic loop for
        // every nesting depth, and `Box::pin` is what lets an async fn recurse.
        let mut child_emit: &mut (dyn FnMut(AssistantEvent) + Send) = &mut |_| {};
        let child = run_assistant_loop_cancellable_in_session_durable(
            generator,
            runtime,
            &child_cfg,
            &mut child_messages,
            cancel,
            approval,
            None,
            runtime_session_id,
            None,
            None,
            redrive_ungrounded_summary,
            &mut child_emit,
        )
        .await;
        let external = child
            .tool_receipts
            .iter()
            .any(|r| tool_output_is_external(&r.tool, tool_labels));
        if child.status == "success" {
            DelegateOutcome {
                ok: true,
                content: cap(child.summary),
                turns: child.turns,
                external,
                receipts: child.tool_receipts,
                spawned: true,
            }
        } else {
            // An unfinished delegation must not read as an answer (the GUI
            // sub-agent's `is_error` rule): the cap, a stall, a cancel or a
            // transport error all come back as an error result with the reason.
            DelegateOutcome {
                ok: false,
                content: cap(json!({
                    "error": format!(
                        "delegate did not finish (status: {}) after {} turns: {}",
                        child.status, child.turns, child.summary
                    )
                })
                .to_string()),
                turns: child.turns,
                external,
                receipts: child.tool_receipts,
                spawned: true,
            }
        }
    })
}

/// Resolves a per-agent approval decision for a tool call. Built by the caller
/// (chat.rs) from the loaded `AgentPermissionPolicy` + the session's agent id +
/// a risk classifier, so the loop stays decoupled from the policy store.
pub type ApprovalPolicyFn =
    std::sync::Arc<dyn Fn(&str, &Value) -> ToolApprovalDecision + Send + Sync>;

/// What the per-agent policy says to do with a tool call before it runs.
pub enum ToolApprovalDecision {
    /// Auto-allow: run without asking.
    Allow,
    /// Require human approval (routes through the `ApprovalGate`).
    RequireApproval,
    /// Refuse outright with a reason.
    Deny(String),
}

/// The outcome of an approval request.
pub enum ApprovalDecision {
    Approved,
    Denied(String),
}

/// The human-in-the-loop seam. Consulted by the loop before running a
/// `gated_tools` action. Implementations: a terminal stdin prompt (REPL /
/// one-shot) or the chat `approval_pending` → park → resolve flow. When no gate
/// is wired, a gated action is denied with an actionable message.
#[async_trait::async_trait]
pub trait ApprovalGate: Send + Sync {
    async fn request(&self, tool: &str, params: &Value) -> ApprovalDecision;

    async fn request_action(&self, _call_id: &str, tool: &str, params: &Value) -> ApprovalDecision {
        self.request(tool, params).await
    }

    /// Durable write-ahead dispatch marker for an approved consequential
    /// action. A failure is fail-closed: the runtime must not execute.
    async fn before_dispatch(
        &self,
        _call_id: &str,
        _tool: &str,
        _params: &Value,
    ) -> Result<(), String> {
        Ok(())
    }

    /// Durable terminal action receipt. If this append fails, the prior
    /// dispatched record remains and resume classifies it indeterminate.
    async fn after_dispatch(
        &self,
        _call_id: &str,
        _tool: &str,
        _params: &Value,
        _ok: bool,
        _receipt: &Value,
    ) -> Result<(), String> {
        Ok(())
    }
}

/// The terminal result of a loop run.
pub struct AssistantOutcome {
    /// `"success"` (model finished), `"max_turns"`, or `"error"`.
    pub status: &'static str,
    /// The final assistant text (or the error message).
    pub summary: String,
    /// Turns consumed.
    pub turns: u32,
    /// Names of tools that executed successfully.
    pub tools_called: Vec<String>,
    /// Tool executions attempted during this loop run, used to ground final
    /// prose claims such as "I ran the tests" against actual receipts.
    pub tool_receipts: Vec<AssistantToolReceipt>,
    /// The model id that produced the final turn (authoritative attribution;
    /// empty if no generate completed). Threaded out so the goal loop can stamp
    /// `model_id`/`model_tier` onto `GoalEvaluated`, mirroring the provenance
    /// `record_turn_completed` already stamps on the default path.
    pub model_used: String,
}

#[derive(Clone, Debug)]
pub struct AssistantToolReceipt {
    pub tool: String,
    pub call_id: Option<String>,
    pub ok: bool,
    pub params: Value,
    /// `Some("delegate:<call id>")` for a receipt a `delegate` child produced
    /// and the parent merged into its own list, so grounding and
    /// `receipts.by_tool` see the child's real calls while a reader can still
    /// tell them from the parent's own. `None` for the parent's own calls.
    pub via: Option<String>,
}

fn transcript_tool_receipts(messages: &[Message]) -> Vec<AssistantToolReceipt> {
    let mut calls: std::collections::HashMap<String, (String, Value)> =
        std::collections::HashMap::new();
    let mut receipts = Vec::new();
    for message in messages {
        match message {
            Message::Assistant { tool_calls, .. } => {
                for call in tool_calls {
                    if let Some(id) = call.id.as_deref() {
                        calls.insert(
                            id.to_string(),
                            (
                                call.name.clone(),
                                serde_json::to_value(&call.arguments)
                                    .unwrap_or_else(|_| Value::Object(Default::default())),
                            ),
                        );
                    }
                }
            }
            Message::ToolResult {
                tool_use_id,
                content,
                ..
            } => {
                let Some((tool, params)) = calls.get(tool_use_id).cloned() else {
                    continue;
                };
                let parsed = serde_json::from_str::<Value>(content).ok();
                let ok = parsed
                    .as_ref()
                    .map(|value| {
                        value.get("error").is_none()
                            && value.get("ok").and_then(Value::as_bool) != Some(false)
                            && value.get("status").and_then(Value::as_str) != Some("Failed")
                    })
                    .unwrap_or_else(|| {
                        let lower = content.to_ascii_lowercase();
                        !lower.contains("declined by user")
                            && !lower.contains("tool call denied")
                            && !lower.starts_with("error:")
                    });
                receipts.push(AssistantToolReceipt {
                    tool,
                    call_id: Some(tool_use_id.clone()),
                    ok,
                    params,
                    via: None,
                });
            }
            _ => {}
        }
    }
    receipts
}

/// Bound an observation to [`OBSERVATION_CAP`], stating what was lost (#813).
///
/// This is still destructive truncation — the elided bytes are NOT retained,
/// and recovering them means re-running the tool with a narrower query. The
/// full fix is a session value store plus typed previews with handles, which
/// #813 rightly says needs its own design pass and a `car-bench` A/B before it
/// changes the model-facing transcript shape.
///
/// What is fixable without that: the marker used to be a bare `…[truncated]…`,
/// so a model could not tell whether it had lost 10 bytes or 10 MB, and had no
/// signal that re-running was the only recovery. A model reasoning over a
/// clipped table would silently treat it as complete. Reporting the true size
/// and the elided amount costs nothing and makes the loss legible.
fn cap(mut s: String) -> String {
    let total = s.len();
    if total <= OBSERVATION_CAP {
        return s;
    }
    let mut end = OBSERVATION_CAP;
    while !s.is_char_boundary(end) {
        end -= 1;
    }
    let elided = total - end;
    s.truncate(end);
    // Leading newline so the notice can't be mistaken for part of the payload
    // (a clipped CSV row, a half-written JSON object).
    s.push_str(&format!(
        "\n…[truncated: showing first {end} of {total} bytes; {elided} bytes elided \
         and NOT retained. To see the rest, re-run this tool with a narrower \
         query — the elided bytes cannot be recovered by asking for them.]…"
    ));
    s
}

/// Fences for the per-turn runtime state block (#814 items 2-3). Explicit
/// delimiters because the block is appended to a message that is usually a tool
/// result, and unfenced runtime text there would read as part of the tool's
/// output.
const STATE_BLOCK_OPEN: &str = "\n\n<runtime-state>\n";
const STATE_BLOCK_CLOSE: &str = "\n</runtime-state>";

/// Append the per-turn state block to the LAST message's content.
///
/// Appended to an existing message rather than added as a new one, which is the
/// only placement that actually satisfies #814 item 3 on every provider. Item 3
/// asks for the tail so the cached prefix stays byte-stable — but the Anthropic
/// and Gemini handlers FOLD every `Message::System` into the top-level system
/// field (`protocol.rs`), so a trailing System block would land in the prefix
/// and be rewritten every turn, causing precisely the cache invalidation the
/// item exists to prevent. A trailing `Message::User` would keep its position,
/// but after a tool result it produces consecutive user-role turns, which is a
/// provider-shape risk not worth taking for a status line.
///
/// Operates on the request copy, never the durable history: the block is
/// regenerated every turn, so persisting it would stack stale copies.
fn append_state_block(messages: &mut [Message], block: &str) {
    let Some(last) = messages.last_mut() else {
        return;
    };
    let fenced = format!("{STATE_BLOCK_OPEN}{block}{STATE_BLOCK_CLOSE}");
    match last {
        Message::System { content }
        | Message::User { content }
        | Message::Assistant { content, .. }
        | Message::ToolResult { content, .. } => content.push_str(&fenced),
        // No text slot to append to; skipping is better than restructuring the
        // turn, and the next turn's message will carry the block.
        _ => {}
    }
}

/// How many remembered subjects reach the state block. Bounded deliberately:
/// this is a pointer to durable state, not a copy of it.
const STATE_BLOCK_MAX_FACTS: usize = 5;

/// Subjects of the facts this run wrote via `remember`, oldest first.
///
/// Derived from the run's tool receipts rather than from a second tracker: the
/// loop already records every call with its params, so there is nothing to keep
/// in sync and no way for the two views to disagree. Only *successful* calls
/// count — a rejected `remember` wrote nothing, and listing it would tell the
/// model it knows something it does not.
fn recent_fact_subjects(receipts: &[AssistantToolReceipt]) -> Vec<String> {
    let mut subjects: Vec<String> = Vec::new();
    for receipt in receipts.iter().filter(|r| r.ok && r.tool == "remember") {
        let Some(subject) = receipt.params.get("subject").and_then(Value::as_str) else {
            continue;
        };
        let subject = subject.trim();
        if subject.is_empty() {
            continue;
        }
        // A re-remember supersedes the earlier write rather than adding a second
        // fact (`memory.rs`), so the subject moves to the most-recent position
        // instead of appearing twice and inflating the count.
        subjects.retain(|s| s != subject);
        subjects.push(subject.to_string());
    }
    subjects
}

/// Compose the per-turn state block from live run state, or `None` when there
/// is nothing worth spending tokens on.
///
/// Subjects only, never bodies. The block exists so the model knows a fact
/// *exists* without having to remember writing it — turning a speculative
/// `recall` into an informed one. Inlining the bodies would duplicate memgine's
/// job without its relevance ranking, and would let the block grow into the
/// largest thing in the context, which is the failure mode the whole per-turn
/// design is bounded against.
fn render_state_block(todo: Option<String>, facts: &[String]) -> Option<String> {
    let mut sections: Vec<String> = Vec::new();
    if let Some(todo) = todo {
        sections.push(todo);
    }
    if !facts.is_empty() {
        // Keep the most RECENT subjects when over the cap — the oldest are the
        // ones the model is least likely to still be acting on.
        let hidden = facts.len().saturating_sub(STATE_BLOCK_MAX_FACTS);
        let listed = facts
            .iter()
            .skip(hidden)
            .map(String::as_str)
            .collect::<Vec<_>>()
            .join(", ");
        let mut line = format!("remembered this run: {listed}");
        if hidden > 0 {
            line.push_str(&format!(" (+{hidden} earlier)"));
        }
        line.push_str("\n  subjects only — call `recall` for the content");
        sections.push(line);
    }
    (!sections.is_empty()).then(|| sections.join("\n"))
}

/// Keep at least this many of the most-recent messages when compacting, so a
/// window-bounded run never loses the immediate working context.
const HISTORY_MIN_TAIL: usize = 6;

/// Opening of the system message left in place of compacted turns (#815).
///
/// Doubles as the marker's own identity: [`parse_compaction_notice`] recognizes
/// it so a later compaction updates the running totals in place instead of
/// stacking notices or dropping the earlier one.
const COMPACTION_NOTICE_PREFIX: &str = "[history compacted:";

/// Render the marker. Names `events_query` explicitly because a notice that
/// something is missing, without saying how to look, only converts a silent
/// failure into a visible dead end.
fn format_compaction_notice(turns: usize, tokens: usize) -> String {
    format!(
        "{COMPACTION_NOTICE_PREFIX} {turns} earlier turns removed to fit the context \
         window, ~{tokens} tokens. They are gone from this transcript but the run's \
         event log still has them — call `events_query` (e.g. {{\"kinds\": \
         [\"action_failed\"], \"limit\": 5}}) to see what was already tried, rather \
         than assuming you never tried it.]"
    )
}

/// Recover the running totals from an existing marker, or `None` if `message`
/// is not one.
///
/// Parses the numbers back out of the text rather than threading a counter
/// through every caller: the marker lives in `messages`, which is the only
/// state both callers of `compact_history_to_window` (the assistant loop and
/// the coder loop) already share.
fn parse_compaction_notice(message: &Message) -> Option<(usize, usize)> {
    let Message::System { content } = message else {
        return None;
    };
    let rest = content.strip_prefix(COMPACTION_NOTICE_PREFIX)?;
    let turns: usize = rest.split_whitespace().next()?.parse().ok()?;
    let tokens: usize = rest
        .split('~')
        .nth(1)?
        .split_whitespace()
        .next()?
        .parse()
        .ok()?;
    Some((turns, tokens))
}

/// A message's estimated token cost, using the *same* metric the inference
/// layer's window-fit check uses (`media_tokens::messages_history_tokens`: a
/// message's serialized-JSON length / 4, with calibrated media accounting).
/// Sharing one estimator is load-bearing — if compaction under-counts relative
/// to the truncation check, it leaves a history the check still flags.
fn approx_message_tokens(m: &Message) -> usize {
    car_inference::media_tokens::messages_history_tokens(std::slice::from_ref(m))
}

/// Bound the running conversation to the model's context window so a long,
/// tool-heavy run never overfills it. An overflowed history pushes the model to
/// its context limit and can truncate the *original task* provider-side — the
/// exact failure the gpt-5.5 benchmark run hit (17× `available_tokens=0`).
///
/// Deterministic sliding window: keep the system prompt(s) + the original task
/// (first user turn) + the most-recent exchanges, dropping the oldest middle
/// messages until the estimate fits `context_window * 3/4` (headroom for the
/// model's output + the next tool results). Drops land on a turn boundary so a
/// `ToolResult` is never orphaned from the `Assistant` call that produced it —
/// a dangling tool result is provider-invalid. No-op when the window is unknown
/// (`0`, e.g. local/test generators) or the history already fits.
pub(crate) fn compact_history_to_window(messages: &mut Vec<Message>, context_window: usize) {
    compact_history_measured(messages, context_window, PromptMeasure::default())
}

/// What a caller knows about the size of its next request beyond the
/// per-message chars/4 estimate. `Default` is "nothing": the estimate alone.
///
/// The estimate under-counts a real request in two ways this closes. It sees
/// only `messages` — not the tool definitions advertised on every turn
/// (`fixed_overhead`) — and it counts bytes/4 where code tokenizes denser, so
/// a 150k-window run measured ~100k while the provider billed 144k and
/// compaction never fired. The provider's own `prompt_tokens` from the
/// previous call is ground truth for the messages that call carried
/// (`reported`); what was appended since is estimated, scaled by the
/// observed reported/estimated ratio when the estimate was off by more than
/// 25%, so one compaction lands under budget instead of chasing it.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct PromptMeasure {
    /// Per-request tokens the per-message estimate cannot see: the tool
    /// definitions (and anything else fixed per call).
    pub fixed_overhead: usize,
    /// `(prompt_tokens, messages_covered)` from the most recent completed
    /// call: the provider-reported input size (all cache buckets summed) and
    /// how many leading messages of the current history that request
    /// carried. Everything past `messages_covered` was appended since.
    pub reported: Option<(usize, usize)>,
}

/// Same as [`compact_history_to_window`] with a [`PromptMeasure`]. WHETHER to
/// compact is decided on the best available measure — the provider-reported
/// count when there is one — while HOW MUCH to drop still walks the
/// per-message estimates (the only per-message measure), scaled to the
/// reported total when the two disagree by more than 25%.
pub(crate) fn compact_history_measured(
    messages: &mut Vec<Message>,
    context_window: usize,
    measure: PromptMeasure,
) {
    if context_window == 0 {
        return;
    }
    let budget = context_window / 4 * 3;
    let estimates: Vec<usize> = messages.iter().map(approx_message_tokens).collect();
    // The fallback total is the shared request-level estimate over the
    // history (`media_tokens::request_prompt_tokens`, the same function the
    // remote guard's warning uses) plus the per-run overhead the caller
    // measured once (tool definitions). The per-message vector above is the
    // same estimator applied one message at a time, for the drop loop.
    let estimated: usize =
        car_inference::media_tokens::request_prompt_tokens("", None, None, None, Some(messages))
            + measure.fixed_overhead;
    // `scale` maps a per-message estimate onto the provider's accounting.
    let (total, scale, reported) = match measure.reported {
        Some((reported, covered)) => {
            let covered = covered.min(messages.len());
            let covered_est = estimates[..covered].iter().sum::<usize>() + measure.fixed_overhead;
            let appended: usize = estimates[covered..].iter().sum();
            let scale = if covered_est > 0 && reported * 4 > covered_est * 5 {
                reported as f64 / covered_est as f64
            } else {
                1.0
            };
            let appended_scaled = (appended as f64 * scale).round() as usize;
            (reported + appended_scaled, scale, Some(reported))
        }
        None => (estimated, 1.0, None),
    };
    let scaled = |tokens: usize| (tokens as f64 * scale).round() as usize;
    if total <= budget {
        return;
    }
    tracing::info!(
        reported_prompt_tokens = reported,
        estimated_prompt_tokens = estimated,
        measured_prompt_tokens = total,
        scale,
        budget,
        context_window,
        "history exceeds the compaction budget"
    );

    // Pinned head: leading system prompt(s) + the first user turn (the task).
    let mut head_end = 0;
    while head_end < messages.len() && matches!(messages[head_end], Message::System { .. }) {
        head_end += 1;
    }
    if head_end < messages.len()
        && matches!(
            messages[head_end],
            Message::User { .. } | Message::UserMultimodal { .. }
        )
    {
        head_end += 1;
    }
    // A notice from an earlier compaction is part of the pinned head (#815).
    // Otherwise it sits first in the drop range and the next compaction erases
    // the record that the previous one happened — restoring exactly the silent
    // deletion the marker exists to prevent.
    let existing_notice = messages
        .get(head_end)
        .and_then(parse_compaction_notice)
        .map(|totals| {
            let at = head_end;
            head_end += 1;
            (at, totals)
        });

    // Never drop into the most-recent tail.
    if messages.len().saturating_sub(head_end) <= HISTORY_MIN_TAIL {
        return;
    }
    let max_drop = messages.len() - HISTORY_MIN_TAIL;

    // Drop oldest middle messages until we fit (or run into the tail).
    let mut drop_end = head_end;
    let mut running = total;
    while running > budget && drop_end < max_drop {
        running = running.saturating_sub(scaled(estimates[drop_end]));
        drop_end += 1;
    }
    // Land the kept suffix on a valid turn boundary. A Responses continuity
    // item precedes its Assistant message, so it is a valid boundary only as
    // that pair. If the item itself was just dropped, drop its now-orphaned
    // Assistant too; then skip any dangling tool results.
    if drop_end > head_end
        && drop_end < messages.len()
        && matches!(messages[drop_end - 1], Message::ProviderOutputItems { .. })
        && matches!(messages[drop_end], Message::Assistant { .. })
    {
        drop_end += 1;
    }
    while drop_end < messages.len() && matches!(messages[drop_end], Message::ToolResult { .. }) {
        drop_end += 1;
    }
    if drop_end <= head_end {
        return;
    }
    let dropped = drop_end - head_end;
    // Accounted in the same (scaled) measure the decision used, so the
    // notice's `~N tokens` is the provider-side size of what was removed.
    let dropped_tokens: usize = estimates[head_end..drop_end]
        .iter()
        .map(|t| scaled(*t))
        .sum();
    messages.drain(head_end..drop_end);
    // Leave a marker where the turns were (#815).
    //
    // Without one, turns simply cease to exist between one request and the
    // next and the transcript reads as continuous from the model's side — so a
    // run that degrades after compaction is indistinguishable, in the trace,
    // from a model that just got worse. "The model forgot" and "the harness
    // deleted it" are different bugs with different fixes, and only one of them
    // is the model's.
    //
    // Pinned into the head below so the next compaction cannot silently drop
    // the notice that the previous one happened, and totals accumulate across
    // compactions rather than only reporting the latest.
    match existing_notice {
        Some((at, (prior_turns, prior_tokens))) => {
            messages[at] = Message::System {
                content: format_compaction_notice(
                    prior_turns + dropped,
                    prior_tokens + dropped_tokens,
                ),
            };
        }
        None => messages.insert(
            head_end,
            Message::System {
                content: format_compaction_notice(dropped, dropped_tokens),
            },
        ),
    }
    tracing::debug!(
        dropped_messages = dropped,
        kept = messages.len(),
        context_window,
        budget,
        "compacted assistant history to fit the model context window"
    );
}

fn message_memory_text(message: &Message) -> Option<String> {
    match message {
        Message::System { content }
        | Message::User { content }
        | Message::Assistant { content, .. }
        | Message::ToolResult { content, .. } => {
            let trimmed = content.trim();
            (!trimmed.is_empty()).then(|| trimmed.to_string())
        }
        Message::UserMultimodal { content } => {
            let text = content
                .iter()
                .filter_map(|block| match block {
                    ContentBlock::Text { text } => Some(text.trim()),
                    _ => None,
                })
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>()
                .join("\n");
            (!text.is_empty()).then_some(text)
        }
        _ => None,
    }
}

fn proactive_query_from_messages(messages: &[Message]) -> String {
    messages
        .iter()
        .rev()
        .find_map(|m| match m {
            Message::User { content } => {
                let trimmed = content.trim();
                (!trimmed.is_empty()).then(|| trimmed.to_string())
            }
            Message::UserMultimodal { .. } => message_memory_text(m),
            _ => None,
        })
        .unwrap_or_default()
}

fn append_context_block(req: &mut GenerateRequest, title: &str, body: &str) {
    let block = format!("## {title}\n{body}");
    req.context = Some(match req.context.take() {
        Some(existing) if !existing.trim().is_empty() => format!("{existing}\n\n{block}"),
        _ => block,
    });
}

fn proactive_maintenance_event_data(
    report: &car_memgine::ProactiveMaintenanceReport,
) -> std::collections::HashMap<String, Value> {
    let mut data = proactive_trigger_event_data(&report.trigger);
    data.insert(
        "saved_count".to_string(),
        Value::from(report.saved.len() as u64),
    );
    data.insert(
        "skipped_existing".to_string(),
        Value::from(report.skipped_existing as u64),
    );
    data.insert(
        "status_updated".to_string(),
        Value::from(report.status.is_some()),
    );
    data
}

fn proactive_intervention_event_data(
    decision: &car_memgine::ProactiveMemoryDecision,
) -> std::collections::HashMap<String, Value> {
    let mut data = std::collections::HashMap::new();
    match decision {
        car_memgine::ProactiveMemoryDecision::Inject {
            selected,
            candidates,
            bank,
            ..
        } => {
            data.insert("decision".to_string(), Value::from("inject"));
            data.insert("selected_id".to_string(), Value::from(selected.id.clone()));
            data.insert(
                "selected_kind".to_string(),
                Value::from(format!("{:?}", selected.kind).to_ascii_lowercase()),
            );
            data.insert(
                "candidate_count".to_string(),
                Value::from(candidates.len() as u64),
            );
            data.insert(
                "bank_knowledge".to_string(),
                Value::from(bank.knowledge as u64),
            );
            data.insert(
                "bank_procedural".to_string(),
                Value::from(bank.procedural as u64),
            );
            data.insert(
                "bank_open_subgoals".to_string(),
                Value::from(bank.open_subgoals as u64),
            );
        }
        car_memgine::ProactiveMemoryDecision::Silent {
            reason,
            candidates,
            bank,
        } => {
            data.insert("decision".to_string(), Value::from("silent"));
            data.insert("reason".to_string(), Value::from(reason.clone()));
            data.insert(
                "candidate_count".to_string(),
                Value::from(candidates.len() as u64),
            );
            data.insert(
                "bank_knowledge".to_string(),
                Value::from(bank.knowledge as u64),
            );
            data.insert(
                "bank_procedural".to_string(),
                Value::from(bank.procedural as u64),
            );
            data.insert(
                "bank_open_subgoals".to_string(),
                Value::from(bank.open_subgoals as u64),
            );
        }
    }
    data
}

fn proactive_trigger_event_data(
    trigger: &car_memgine::ProactiveMemoryTrigger,
) -> std::collections::HashMap<String, Value> {
    std::collections::HashMap::from([
        (
            "repeated_failures".to_string(),
            Value::from(trigger.repeated_failures as u64),
        ),
        ("tool_error".to_string(), Value::from(trigger.tool_error)),
        (
            "explicit_uncertainty".to_string(),
            Value::from(trigger.explicit_uncertainty),
        ),
        (
            "high_risk_action".to_string(),
            Value::from(trigger.high_risk_action),
        ),
        (
            "context_shift".to_string(),
            Value::from(trigger.context_shift),
        ),
    ])
}

/// Record one completed model call into the run's event log as
/// [`car_eventlog::EventKind::InferenceMetered`].
///
/// Until this existed the assistant loop wrote **no** inference telemetry, so
/// `harness_metrics::compute_harness_metrics` over an assistant journal reported
/// zero tokens and zero model calls — which made the whole
/// `trajectory_efficiency` token branch of the Evolution Agent's regression gate
/// (`car_memgine::harness_evolution`) structurally inert. The data was never
/// missing: [`car_inference::InferenceResult`] has carried `usage` and
/// `latency_ms` all along and the loop simply dropped them.
///
/// Uses the log handle the loop already holds (`runtime.log`) — the same
/// mechanism `maybe_apply_assistant_proactive_memory` uses for its
/// `ProactiveMemoryMaintained` record, and the same `append_metered` contract
/// the streaming path in `handler.rs` uses. No new plumbing, no new field on any
/// signature.
///
/// **`usage: None` is recorded as a call with no token metrics, not as zeros.**
/// `car-inference` makes `usage` optional precisely so "nobody could count" is
/// distinguishable from "this really used no tokens" (Parslee-ai/car#795), and
/// `Metrics::latency` leaves the token keys absent from the event data rather
/// than writing `0`. The event is still emitted, because a call that happened
/// with an uncountable cost is still a call: skipping it would silently
/// undercount `model_calls`, the exact number the #813 A/B turns on.
///
/// `cost_usd` is left `None`: the loop has no price table, and a fabricated 0.0
/// would be indistinguishable from a free call. The gate does not read cost.
async fn record_inference_metered(runtime: &Runtime, result: &car_inference::InferenceResult) {
    let mut data: HashMap<String, Value> = HashMap::new();
    data.insert(
        "model_id".to_string(),
        Value::from(result.model_used.clone()),
    );
    // Explicit provenance for the absent-vs-zero distinction above, so a
    // consumer reading the journal need not infer it from missing keys.
    data.insert(
        "usage_measured".to_string(),
        Value::from(result.usage.is_some()),
    );

    let metrics = match &result.usage {
        Some(u) => car_eventlog::Metrics::inference(u.prompt_tokens, u.completion_tokens, None)
            .with_duration(result.latency_ms as f64),
        None => car_eventlog::Metrics::latency(result.latency_ms as f64),
    };

    runtime.log.lock().await.append_metered(
        car_eventlog::EventKind::InferenceMetered,
        None,
        None,
        data,
        metrics,
    );
}

async fn maybe_apply_assistant_proactive_memory(
    cfg: &AssistantConfig,
    runtime: &Runtime,
    req: &mut GenerateRequest,
    messages: &[Message],
) {
    let Some(memory) = &cfg.proactive_memory else {
        return;
    };
    let query = proactive_query_from_messages(messages);
    if query.trim().is_empty() {
        return;
    }
    let mut recent = messages
        .iter()
        .rev()
        .filter_map(message_memory_text)
        .take(6)
        .collect::<Vec<_>>();
    recent.reverse();
    let events = {
        let log = runtime.log.lock().await;
        log.events().to_vec()
    };
    let (maintenance, decision) = match memory.proactive_intervention(&query, recent, &events).await
    {
        Ok(out) => out,
        Err(e) => {
            tracing::debug!(error = %e, "assistant proactive memory pass failed");
            return;
        }
    };
    {
        let mut log = runtime.log.lock().await;
        log.append(
            car_eventlog::EventKind::ProactiveMemoryMaintained,
            None,
            None,
            proactive_maintenance_event_data(&maintenance),
        );
        log.append(
            car_eventlog::EventKind::ProactiveMemoryIntervention,
            None,
            None,
            proactive_intervention_event_data(&decision),
        );
    }
    if let car_memgine::ProactiveMemoryDecision::Inject { reminder, .. } = decision {
        append_context_block(req, "Proactive Memory", &reminder);
    }
}

/// Consecutive no-progress repeats before we nudge the model, then give up. A
/// repeat is the model re-requesting work it already tried since its last state
/// mutation — the degenerate read/recall loop a model can fall into, burning the
/// whole turn budget while producing nothing.
const STALL_NUDGE: u32 = 3;
const STALL_BREAK: u32 = 6;

/// Turns of pure information-gathering (no state mutation) before a single soft
/// nudge to transition from exploring to acting. Nudge-only: a genuinely
/// read-only task never mutates, so this must not terminate — only the
/// unambiguous repeat loop (`STALL_BREAK`) hard-stops. This is the "read/write
/// ratio" / "time since last mutation" signal from the agent-control literature.
const EXPLORE_NUDGE: u32 = 8;

/// The set of tools that change state — a successful one is real progress and
/// resets the no-progress guard. Derived from the model-facing tool defs: any
/// def that self-declares `"mutating": true` (e.g. `generate_image`), plus the
/// builtin file writers whose defs come from `agent_basics` without the
/// flag. Everything else (reads, searches, AND read-only shells like
/// `wc`/`node --check`) is non-progress, so probing between reads can't silently
/// reset the guard. `shell` is deliberately excluded: a shell that never
/// accompanies a file edit isn't moving the task forward, and one that does
/// mutate is paired with a write/edit that resets the guard anyway.
fn mutating_tool_names(tool_defs: &[Value]) -> std::collections::HashSet<String> {
    let mut set: std::collections::HashSet<String> = ["write_file", "edit_file"]
        .iter()
        .map(|s| s.to_string())
        .collect();
    for def in tool_defs {
        if def
            .get("mutating")
            .and_then(Value::as_bool)
            .unwrap_or(false)
        {
            if let Some(name) = def.get("name").and_then(Value::as_str) {
                set.insert(name.to_string());
            }
        }
    }
    set
}

/// A stable signature of a turn's tool calls (names + arguments; id-independent
/// and order-independent) so two turns that request the identical work compare
/// equal — the basis for detecting a no-progress repeat.
fn tool_calls_signature(calls: &[ToolCall]) -> String {
    let mut parts: Vec<String> = calls
        .iter()
        .map(|c| {
            format!(
                "{}({})",
                c.name,
                serde_json::to_string(&c.arguments).unwrap_or_default()
            )
        })
        .collect();
    parts.sort();
    parts.join("|")
}

/// What the loop should do after one turn's tool calls, per the no-progress
/// guard.
#[derive(Debug, PartialEq, Eq)]
enum GuardStep {
    /// A genuinely new state mutation — real progress; carry on fresh.
    Progress,
    /// Nothing notable; keep going.
    Continue,
    /// Spinning without progress — inject a nudge to act or finish this turn.
    Nudge,
    /// Repeated the same action too many times — stop the run as stalled.
    Break,
}

/// Tracks whether the agent loop is advancing or spinning in place.
///
/// A turn counts as progress ONLY when a mutating tool succeeds with a
/// signature not seen since the last progress. A repeated *identical* call is
/// idempotent — re-`remember`ing the same fact, re-writing identical bytes
/// changes nothing — so it is NOT progress even for a nominally `"mutating"`
/// tool. Counting such repeats as progress was the bug behind the observed
/// `remember()` loop that reset the guard every turn and ran to `max_turns`
/// instead of tripping `STALL_BREAK`. Non-mutating repeats are unchanged.
#[derive(Default)]
struct NoProgressGuard {
    seen_sigs: std::collections::HashSet<String>,
    stall_repeats: u32,
    turns_since_mutation: u32,
    nudged: bool,
}

impl NoProgressGuard {
    /// Feed one turn: `sig` is this turn's tool-call signature, `mutated_ok`
    /// whether a mutating tool succeeded this turn.
    fn observe(&mut self, sig: &str, mutated_ok: bool) -> GuardStep {
        let sig_is_new = self.seen_sigs.insert(sig.to_string());
        if mutated_ok && sig_is_new {
            // Real, new mutation: reset — but keep THIS signature so an immediate
            // identical repeat next turn still collides (and counts as a stall).
            self.seen_sigs.clear();
            self.seen_sigs.insert(sig.to_string());
            self.stall_repeats = 0;
            self.turns_since_mutation = 0;
            self.nudged = false;
            return GuardStep::Progress;
        }
        // Non-mutating, OR a repeated identical mutation → no real progress.
        self.turns_since_mutation += 1;
        if !sig_is_new {
            self.stall_repeats += 1;
            if self.stall_repeats >= STALL_BREAK {
                return GuardStep::Break;
            }
            if self.stall_repeats >= STALL_NUDGE && !self.nudged {
                self.nudged = true;
                return GuardStep::Nudge;
            }
        }
        if self.turns_since_mutation >= EXPLORE_NUDGE && !self.nudged {
            self.nudged = true;
            return GuardStep::Nudge;
        }
        GuardStep::Continue
    }
}

/// Build a single-action `tool_call` proposal, binding the action id to the
/// call id so the result correlates back.
/// Build the executable proposal for a tool call.
///
/// `parameters` is passed separately rather than read off `call.arguments`
/// because the loop may have substituted retained-value handles into it (#813).
/// Reading the raw arguments here would resolve `$r3` for the approval gate and
/// then execute the unresolved literal — the two must not disagree about what
/// is being run.
fn build_proposal(
    source: &str,
    call: &ToolCall,
    parameters: &Value,
) -> Result<ActionProposal, String> {
    serde_json::from_value(json!({
        "source": source,
        "actions": [{
            "id": call.id,
            "type": "tool_call",
            "tool": call.name,
            "parameters": parameters,
        }],
    }))
    .map_err(|e| format!("malformed proposal: {e}"))
}

/// Run the assistant loop to a terminal outcome, mutating `messages` (which must
/// already carry the system + first user turn) and streaming progress via
/// `emit`. Reusable across one-shot, REPL, and per-chat-turn.
pub async fn run_assistant_loop(
    generator: &dyn TurnGenerator,
    runtime: &Runtime,
    cfg: &AssistantConfig,
    messages: &mut Vec<Message>,
    emit: impl FnMut(AssistantEvent),
) -> AssistantOutcome {
    let never = std::sync::atomic::AtomicBool::new(false);
    run_assistant_loop_cancellable(generator, runtime, cfg, messages, &never, None, None, emit)
        .await
}

/// Same as [`run_assistant_loop`], but checks `cancel` before each turn so the
/// `agent.chat.cancel` path can interrupt a running turn between model calls,
/// and consults `approval` (if any) before running a `gated_tools` action.
pub async fn run_assistant_loop_cancellable(
    generator: &dyn TurnGenerator,
    runtime: &Runtime,
    cfg: &AssistantConfig,
    messages: &mut Vec<Message>,
    cancel: &std::sync::atomic::AtomicBool,
    approval: Option<&dyn ApprovalGate>,
    images: Option<&[ContentBlock]>,
    emit: impl FnMut(AssistantEvent),
) -> AssistantOutcome {
    run_assistant_loop_cancellable_in_session(
        generator, runtime, cfg, messages, cancel, approval, images, None, emit,
    )
    .await
}

/// Session-aware variant of [`run_assistant_loop_cancellable`]. A caller that
/// multiplexes conversations passes the Runtime session id so stateful tool
/// guards (notably read-before-edit) stay isolated between conversations.
pub async fn run_assistant_loop_cancellable_in_session(
    generator: &dyn TurnGenerator,
    runtime: &Runtime,
    cfg: &AssistantConfig,
    messages: &mut Vec<Message>,
    cancel: &std::sync::atomic::AtomicBool,
    approval: Option<&dyn ApprovalGate>,
    images: Option<&[ContentBlock]>,
    runtime_session_id: Option<&str>,
    emit: impl FnMut(AssistantEvent),
) -> AssistantOutcome {
    run_assistant_loop_cancellable_in_session_durable(
        generator,
        runtime,
        cfg,
        messages,
        cancel,
        approval,
        images,
        runtime_session_id,
        None,
        None,
        true,
        emit,
    )
    .await
}

/// Durable supervised-session variant. The checkpoint sink is invoked after
/// every mutation of the exact model-facing transcript, including compaction,
/// assistant tool calls, refusals, and tool results.
pub async fn run_assistant_loop_cancellable_in_session_durable(
    generator: &dyn TurnGenerator,
    runtime: &Runtime,
    cfg: &AssistantConfig,
    messages: &mut Vec<Message>,
    cancel: &std::sync::atomic::AtomicBool,
    approval: Option<&dyn ApprovalGate>,
    images: Option<&[ContentBlock]>,
    runtime_session_id: Option<&str>,
    durable_session_id: Option<&str>,
    durability: Option<&dyn super::governance::AssistantDurability>,
    redrive_ungrounded_summary: bool,
    mut emit: impl FnMut(AssistantEvent),
) -> AssistantOutcome {
    use std::sync::atomic::Ordering;
    let tools = if cfg.tools.is_empty() {
        None
    } else {
        Some(cfg.tools.clone())
    };
    let mut tools_called: Vec<String> = Vec::new();
    // Restored transcripts carry the authoritative tool-call/result pairs from
    // earlier process lifetimes. Seed grounding from them so a continuity turn
    // can cite prior evidence without rerunning completed actions.
    let mut tool_receipts: Vec<AssistantToolReceipt> = transcript_tool_receipts(messages);
    // Retained tool results for this run (#813). Constructed unconditionally
    // and left empty when the feature is off, so the off path allocates one
    // empty map and takes no other behavioral difference.
    let mut values = super::value_store::SessionValues::new();
    let mut last_text = String::new();
    let mut last_model = String::new();
    let mut turns = 0u32;
    let mut claim_corrections = 0u8;
    // The model's window, resolved once (the model is fixed for the run). Used
    // to bound the growing message history each turn; 0 (unknown) disables it.
    // A caller's override tightens it; one above the known window is clamped
    // (see `resolve_context_window`).
    let registry_window = cfg
        .model
        .as_deref()
        .map(|m| generator.context_window(m))
        .unwrap_or(0);
    let (context_window, window_advisory) =
        resolve_context_window(cfg.context_window_override, registry_window);
    if let Some(advisory) = window_advisory {
        tracing::warn!(
            requested = cfg.context_window_override,
            registry_window,
            "{advisory}"
        );
        emit(AssistantEvent::Text(format!(
            "[context window: {advisory}]"
        )));
    }
    // What the per-message estimate cannot see, plus the provider's own count
    // of the last request once there is one (see `PromptMeasure`). The tool
    // definitions ride on every turn; their estimate is the same shared
    // chars/4 the inference layer's guard uses.
    let mut prompt_measure = PromptMeasure {
        fixed_overhead: car_inference::media_tokens::tool_defs_tokens(&cfg.tools),
        reported: None,
    };
    // Tools whose success counts as progress (resets the no-progress guard),
    // derived from the advertised defs — so a capability tool that self-declares
    // `"mutating": true` (e.g. generate_image) is recognized without editing the
    // loop.
    let mutating_tools = mutating_tool_names(&cfg.tools);
    // The advertised names, for the delegate child's execution-time subset
    // check, and whether this run offers `delegate` at all.
    let advertised_names: std::collections::HashSet<String> = cfg
        .tools
        .iter()
        .filter_map(|d| d.get("name").and_then(Value::as_str))
        .map(str::to_string)
        .collect();
    let delegate_advertised = advertised_names.contains(DELEGATE_TOOL);
    // Run-level delegation budget (see `DelegateBudget`).
    let delegate_budget = cfg.delegate_budget.unwrap_or_default();
    let mut delegations_spawned: u32 = 0;
    let mut child_turns_used: u32 = 0;
    // Tool-result provenance labels, resolved once for the run. The fallback is
    // the built-in table, not an empty one: an empty map classifies every result
    // as internal, which would leave the marking switched off by omission
    // (car#723).
    let builtin_labels;
    let tool_labels = match &cfg.tool_labels {
        Some(m) => m,
        None => {
            builtin_labels = builtin_tool_labels();
            &builtin_labels
        }
    };
    // No-progress guard: tracks signatures of work tried since the last real
    // state mutation (a signature reappearing is a stall) plus turns spent
    // without changing anything. A repeated identical call is never progress,
    // even to a mutating tool — see NoProgressGuard.
    let mut guard = NoProgressGuard::default();

    while turns < cfg.max_turns {
        if cancel.load(Ordering::Relaxed) {
            return AssistantOutcome {
                status: "cancelled",
                summary: "cancelled".to_string(),
                turns,
                tools_called,
                tool_receipts,
                model_used: last_model.clone(),
            };
        }
        turns += 1;

        // Keep the running conversation within the model's context window so a
        // long tool-heavy run never overflows it (which degrades the model and
        // can truncate the original task provider-side).
        let before_compaction = messages.clone();
        compact_history_measured(messages, context_window, prompt_measure);
        if before_compaction != *messages {
            // The reported count covered the pre-compaction history; the next
            // call reports afresh.
            prompt_measure.reported = None;
            if let (Some(store), Some(session_id)) = (durability, durable_session_id) {
                if let Err(e) = store
                    .checkpoint(session_id, messages, "history_compacted", None)
                    .await
                {
                    let msg = format!("durable checkpoint failed after compaction: {e}");
                    emit(AssistantEvent::Error(msg.clone()));
                    return AssistantOutcome {
                        status: "error",
                        summary: msg,
                        turns,
                        tools_called,
                        tool_receipts,
                        model_used: last_model,
                    };
                }
            }
        }

        let mut req = GenerateRequest {
            prompt: String::new(),
            model: cfg.model.clone(),
            params: GenerateParams {
                temperature: 0.0,
                strict_model: cfg.strict_model,
                ..Default::default()
            },
            context: None,
            context_stable_prefix: None,
            tools: tools.clone(),
            // Attach any images to the first request (they belong to the user's
            // latest message); later turns are tool-result follow-ups.
            images: if turns == 1 {
                images.map(|imgs| imgs.to_vec())
            } else {
                None
            },
            messages: Some(messages.clone()),
            cache_control: false,
            // Only on tool-less turns: a JSON-constrained request suppresses
            // tool use on real providers, so a turn that offers tools stays
            // unconstrained and the final answer is checked (and repaired
            // once, without tools) below.
            response_format: if tools.is_none() {
                cfg.response_format.clone()
            } else {
                None
            },
            intent: None,
            client_ref: None,
            expected_row_digest: None,
            expected_catalog_revision: None,
            caller: None,
        };
        maybe_apply_assistant_proactive_memory(cfg, runtime, &mut req, messages).await;

        // Per-turn state block (#814 items 2-3). Rendered fresh every turn from
        // live state and appended to the request copy, so durable state reaches
        // the model whether or not it thinks to ask — the recall-discipline
        // dependency the issue is about. Skipped entirely when there is nothing
        // to say, so a run with no plan and no writes costs no tokens and no
        // cache churn.
        //
        // Carries the task list and the facts written this run. It deliberately
        // does NOT carry the working directory or the approval tier, which #814
        // also lists, because neither is live state: `root` is fixed at executor
        // construction and the standing tier at bind time, and both already reach
        // the model in the system prompt's `Environment:` sentence — which
        // compaction pins, so it can never be evicted. Repeating a constant in
        // the tail would re-send it every turn for no new information and create
        // a second copy free to drift from the substrate's own description.
        let todo_render = match &cfg.todos {
            Some(todos) => todos.lock().await.render(),
            None => None,
        };
        if let Some(block) = render_state_block(todo_render, &recent_fact_subjects(&tool_receipts))
        {
            if let Some(msgs) = req.messages.as_mut() {
                append_state_block(msgs, &block);
            }
        }
        // How many leading messages of the LIVE history this request carries
        // — the index the provider's reported prompt size will be attributed
        // to. Captured after the state block and memory context are attached:
        // both land on the request's own copy (`req.messages`), never on
        // `messages`, so their tokens are part of the reported count without
        // being messages the next turn can index. The ratio in
        // `compact_history_measured` absorbs them.
        let request_covers = messages.len();

        let mut result = match generator.generate(req).await {
            Ok(r) => r,
            Err(e) => {
                let msg = format!("inference failed: {e}");
                emit(AssistantEvent::Error(msg.clone()));
                return AssistantOutcome {
                    status: "error",
                    summary: msg,
                    turns,
                    tools_called,
                    tool_receipts,
                    model_used: last_model.clone(),
                };
            }
        };
        // Meter the call that just returned. Placed immediately after a
        // successful `generate` and before every early return below, so each
        // COMPLETED model call is counted exactly once no matter which of those
        // paths the turn takes.
        //
        // A call that *failed* is NOT counted: the `Err` arm above returns from
        // the loop before reaching this line. So `model_calls` is a count of
        // completed calls, never of attempts — a harness that retries a failing
        // provider ten times and gives up records zero. Read it alongside the
        // run's terminal status; do not read it as "requests issued".
        record_inference_metered(runtime, &result).await;
        // Ground truth for the next turn's compaction decision. All three
        // input buckets: Anthropic reports the cached prefix separately from
        // `prompt_tokens`, and the window holds the sum.
        if let Some(u) = &result.usage {
            let input = u.prompt_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens;
            if input > 0 {
                prompt_measure.reported = Some((input as usize, request_covers));
            }
        }
        // Strip any leaked model reasoning-channel prefix (e.g. gemma-4's
        // `thought`) from the answer at this choke point — the streamed
        // per-turn generate can bypass the inference-layer tool-call parsers, so
        // clean it here so no chat bubble ever shows the model's reasoning label
        // as the answer (table stakes, matching Claude Code / ChatGPT).
        result.text = car_inference::tasks::generate::strip_leaked_reasoning(&result.text);
        last_model = result.model_used.clone();

        // No tool calls → the model's text is the final answer.
        if result.tool_calls.is_empty() {
            last_text = result.text.clone();
            let ungrounded = ungrounded_summary_claims(&last_text, &tool_receipts);
            if redrive_ungrounded_summary && !ungrounded.is_empty() {
                result.append_assistant_history(messages, vec![]);
                if claim_corrections < 2 && turns < cfg.max_turns {
                    claim_corrections += 1;
                    messages.push(Message::User {
                        content: format!(
                            "Evidence check rejected the draft's unsupported operational claim(s): {}. \
                             Rewrite the answer using only claims supported by successful transcript \
                             tool receipts. Preserve useful source findings, explicitly mark missing \
                             live evidence, and do not rerun completed actions merely to support prose.",
                            ungrounded.join(", ")
                        ),
                    });
                    if let (Some(store), Some(session_id)) = (durability, durable_session_id) {
                        if let Err(e) = store
                            .checkpoint(session_id, messages, "ungrounded_summary_redrive", None)
                            .await
                        {
                            let msg =
                                format!("durable checkpoint failed before claim correction: {e}");
                            emit(AssistantEvent::Error(msg.clone()));
                            return AssistantOutcome {
                                status: "error",
                                summary: msg,
                                turns,
                                tools_called,
                                tool_receipts,
                                model_used: last_model,
                            };
                        }
                    }
                    continue;
                }
                let summary = annotate_summary_with_claim_note(&last_text, &ungrounded);
                emit(AssistantEvent::Error(summary.clone()));
                return AssistantOutcome {
                    status: "error",
                    summary,
                    turns,
                    tools_called,
                    tool_receipts,
                    model_used: last_model,
                };
            }
            // One-shot format repair. Tool turns are never JSON-constrained
            // (a constrained request suppresses tool use), so on a run with
            // tools this check is what makes the CONTRACT hold. If the final
            // text is not the requested shape, re-ask once with the draft in
            // the transcript, no tools, and the format set — a turn that
            // cannot be anything but the answer. A final text that already
            // parses costs no extra call. The repair is announced
            // as a Text event so a `--json` consumer sees it happened; it is
            // still one repair, never a loop (a second miss is reported, not
            // retried).
            // Whether the final assistant message is already in `messages`
            // (the repair path appends the draft before re-asking).
            let mut final_appended = false;
            if let Some(format) = cfg.response_format.as_ref().filter(|f| {
                !final_text_matches_format(&last_text, f, cfg.response_format_validator.as_ref())
            }) {
                emit(AssistantEvent::Text(FORMAT_REPAIR_NOTICE.to_string()));
                result.append_assistant_history(messages, vec![]);
                messages.push(Message::User {
                    content: format_repair_nudge(format).to_string(),
                });
                let repair = GenerateRequest {
                    prompt: String::new(),
                    model: cfg.model.clone(),
                    params: GenerateParams {
                        temperature: 0.0,
                        strict_model: cfg.strict_model,
                        ..Default::default()
                    },
                    context: None,
                    context_stable_prefix: None,
                    tools: None,
                    images: None,
                    messages: Some(messages.clone()),
                    cache_control: false,
                    response_format: Some(format.clone()),
                    intent: None,
                    client_ref: None,
                    expected_row_digest: None,
                    expected_catalog_revision: None,
                    caller: None,
                };
                match generator.generate(repair).await {
                    Ok(mut repaired) => {
                        record_inference_metered(runtime, &repaired).await;
                        repaired.text =
                            car_inference::tasks::generate::strip_leaked_reasoning(&repaired.text);
                        if !final_text_matches_format(
                            &repaired.text,
                            format,
                            cfg.response_format_validator.as_ref(),
                        ) {
                            emit(AssistantEvent::Text(
                                FORMAT_REPAIR_STILL_INVALID.to_string(),
                            ));
                        }
                        last_model = repaired.model_used.clone();
                        last_text = repaired.text.clone();
                        result = repaired;
                    }
                    Err(e) => {
                        // Keep the draft: it is the model's answer, and the
                        // provider's refusal to enforce a format does not
                        // unmake it. Drop the nudge so the durable transcript
                        // ends on the answer, not on a question nobody
                        // answered.
                        if matches!(messages.last(), Some(Message::User { content }) if content == format_repair_nudge(format))
                        {
                            messages.pop();
                        }
                        emit(AssistantEvent::Text(format!(
                            "{FORMAT_REPAIR_FAILED_PREFIX} {e}; returning the draft answer as-is]"
                        )));
                        final_appended = true;
                    }
                }
            }
            if !final_appended {
                result.append_assistant_history(messages, vec![]);
            }
            if let (Some(store), Some(session_id)) = (durability, durable_session_id) {
                if let Err(e) = store
                    .checkpoint(session_id, messages, "assistant_final", None)
                    .await
                {
                    let msg = format!("durable checkpoint failed after assistant response: {e}");
                    emit(AssistantEvent::Error(msg.clone()));
                    return AssistantOutcome {
                        status: "error",
                        summary: msg,
                        turns,
                        tools_called,
                        tool_receipts,
                        model_used: last_model,
                    };
                }
            }
            // Record why the loop stopped. On this ungrounded default path an
            // empty-tool-calls turn is treated as success even when the model was
            // truncated mid-answer — capture the truncation signal so a false
            // completion is diagnosable (docs/audits/car-tracing-design-2026-07-07).
            runtime
                .record_turn_completed(
                    "empty_tool_calls",
                    result.stop_reason.as_deref(),
                    result.was_truncated(),
                    turns,
                    &last_model,
                )
                .await;
            emit(AssistantEvent::Done {
                text: last_text.clone(),
            });
            return AssistantOutcome {
                status: "success",
                summary: last_text,
                turns,
                tools_called,
                tool_receipts,
                model_used: last_model.clone(),
            };
        }

        if !result.text.trim().is_empty() {
            last_text = result.text.clone();
            emit(AssistantEvent::Text(result.text.clone()));
        }

        // Assign ids to any call missing one so results correlate back.
        let mut calls = result.tool_calls.clone();
        for (i, call) in calls.iter_mut().enumerate() {
            if call.id.is_none() {
                call.id = Some(format!("call_{turns}_{i}"));
            }
        }

        result.append_assistant_history(messages, calls.clone());
        if let (Some(store), Some(session_id)) = (durability, durable_session_id) {
            if let Err(e) = store
                .checkpoint(session_id, messages, "assistant_tool_calls", None)
                .await
            {
                let msg = format!("durable checkpoint failed before tool dispatch: {e}");
                emit(AssistantEvent::Error(msg.clone()));
                return AssistantOutcome {
                    status: "error",
                    summary: msg,
                    turns,
                    tools_called,
                    tool_receipts,
                    model_used: last_model,
                };
            }
        }

        // The no-progress guard runs AFTER execution (below), so it can key on
        // whether a mutation actually SUCCEEDED — a repeatedly-*failing* write
        // (bad path, denied) is not progress, and resetting on the mere request
        // would let "40 failed writes" evade the guard.
        let mut mutated_ok = false;

        // Execute each call in emitted order (avoid the DAG racing same-turn
        // filesystem effects like mkdir-then-write).
        for call in &calls {
            let id = call.id.clone().expect("ids assigned above");
            emit(AssistantEvent::ToolCall {
                name: call.name.clone(),
                params: serde_json::to_value(&call.arguments).unwrap_or_default(),
            });

            // Per-agent approval gate. The policy (when set) decides allow /
            // require-approval / deny per the running agent's posture; otherwise
            // the standing-tier `gated_tools` list applies (unchanged behavior).
            let mut params_val = serde_json::to_value(&call.arguments).unwrap_or_default();
            // Resolve `$rN` handles BEFORE anything inspects the parameters
            // (#813). Ordering is load bearing three times over: the approval
            // policy and the human gate must see the REAL arguments, or a
            // reference becomes a way to get an unreviewed value past review;
            // and `car-validator` checks against the tool's JSON Schema, where
            // `"$r3"` is a string in a slot that may demand an array — resolving
            // first keeps every schema unweakened instead of teaching all of
            // them to admit a reference form.
            if cfg.value_store_previews {
                let resolved = values.resolve_refs(&mut params_val);
                if !resolved.is_empty() {
                    tracing::debug!(
                        tool = %call.name,
                        handles = ?resolved,
                        "resolved retained-value references in tool arguments"
                    );
                }
            }
            let params_val = params_val;
            let posture = match &cfg.approval_policy {
                Some(policy) => policy(&call.name, &params_val),
                None => {
                    if cfg.gated_tools.iter().any(|t| t == &call.name) {
                        ToolApprovalDecision::RequireApproval
                    } else {
                        ToolApprovalDecision::Allow
                    }
                }
            };
            // A delegate child may only call what it was granted (see
            // `AssistantConfig::refuse_unadvertised_tools`). Checked before
            // the gate so an ungranted tool never reaches an approver either.
            let posture = if cfg.refuse_unadvertised_tools && !advertised_names.contains(&call.name)
            {
                ToolApprovalDecision::Deny(format!(
                    "tool '{}' is not granted to this delegate; use only: {}",
                    call.name,
                    advertised_names
                        .iter()
                        .cloned()
                        .collect::<Vec<_>>()
                        .join(", ")
                ))
            } else {
                posture
            };
            let needs_approval = matches!(&posture, ToolApprovalDecision::RequireApproval);

            let refusal: Option<String> = match posture {
                ToolApprovalDecision::Allow => None,
                ToolApprovalDecision::Deny(reason) => Some(reason),
                ToolApprovalDecision::RequireApproval => {
                    let decision = match approval {
                        Some(gate) => gate.request_action(&id, &call.name, &params_val).await,
                        None => ApprovalDecision::Denied(format!(
                            "'{}' needs approval: re-run with --full-access to allow it on this host, \
                             or use the default sandbox where edits are isolated",
                            call.name
                        )),
                    };
                    match decision {
                        ApprovalDecision::Approved => None,
                        ApprovalDecision::Denied(reason) => Some(reason),
                    }
                }
            };
            if let Some(reason) = refusal {
                let content = cap(json!({ "error": reason }).to_string());
                emit(AssistantEvent::ToolResult {
                    name: call.name.clone(),
                    ok: false,
                    content: content.clone(),
                });
                messages.push(Message::ToolResult {
                    tool_use_id: id,
                    content,
                    // A refusal the runtime itself wrote — never fetched.
                    provenance: Provenance::Internal,
                });
                if let (Some(store), Some(session_id)) = (durability, durable_session_id) {
                    if let Err(e) = store
                        .checkpoint(session_id, messages, "tool_refused", None)
                        .await
                    {
                        let msg = format!("durable checkpoint failed after refusal: {e}");
                        emit(AssistantEvent::Error(msg.clone()));
                        return AssistantOutcome {
                            status: "error",
                            summary: msg,
                            turns,
                            tools_called,
                            tool_receipts,
                            model_used: last_model,
                        };
                    }
                }
                continue;
            }

            // Loop-intercepted sub-agent. Only when the parent advertised it
            // — a hallucinated `delegate` call on a run that never offered
            // one is an unknown tool like any other, not a free sub-agent.
            if delegate_advertised && call.name == DELEGATE_TOOL {
                let goal_brief = params_val
                    .get("goal")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .replace('\n', " ");
                let goal_brief: String = goal_brief.chars().take(80).collect();
                let over_budget = delegations_spawned >= delegate_budget.max_delegations
                    || child_turns_used >= delegate_budget.max_child_turns;
                let done = if over_budget {
                    DelegateOutcome {
                        ok: false,
                        content: cap(json!({
                            "error": format!(
                                "delegation budget exhausted ({delegations_spawned} delegations / \
                                 {child_turns_used} child turns used; limits {} / {}) — finish with \
                                 what you have",
                                delegate_budget.max_delegations, delegate_budget.max_child_turns
                            )
                        })
                        .to_string()),
                        turns: 0,
                        external: false,
                        receipts: Vec::new(),
                        spawned: false,
                    }
                } else {
                    run_delegate(
                        generator,
                        runtime,
                        cfg,
                        messages,
                        &params_val,
                        cancel,
                        approval,
                        runtime_session_id,
                        redrive_ungrounded_summary,
                        tool_labels,
                    )
                    .await
                };
                if done.spawned {
                    delegations_spawned += 1;
                    child_turns_used = child_turns_used.saturating_add(done.turns);
                }
                emit(AssistantEvent::Text(format!(
                    "[delegate: {goal_brief}{} turns, {}]",
                    done.turns,
                    if done.ok { "ok" } else { "error" }
                )));
                if done.ok {
                    tools_called.push(call.name.clone());
                    if mutating_tools.contains(&call.name) {
                        mutated_ok = true;
                    }
                }
                tool_receipts.push(AssistantToolReceipt {
                    tool: call.name.clone(),
                    call_id: Some(id.clone()),
                    ok: done.ok,
                    params: params_val.clone(),
                    via: None,
                });
                // The child's own receipts, merged and tagged: the parent's
                // grounding check ("tests passed" needs a successful `shell`
                // receipt) and `receipts.by_tool` must see what the child
                // actually ran, or a parent that delegated the test run is
                // flagged ungrounded for reporting a result it has evidence for.
                let via = format!("{DELEGATE_TOOL}:{id}");
                tool_receipts.extend(done.receipts.into_iter().map(|mut r| {
                    r.via = Some(via.clone());
                    r
                }));
                emit(AssistantEvent::ToolResult {
                    name: call.name.clone(),
                    ok: done.ok,
                    content: done.content.clone(),
                });
                messages.push(Message::ToolResult {
                    tool_use_id: id,
                    content: done.content,
                    // The child's prose is internal unless one of ITS tool
                    // results crossed the boundary — then the parent inherits
                    // the marking rather than laundering it through a summary.
                    provenance: if done.external {
                        Provenance::External
                    } else {
                        Provenance::Internal
                    },
                });
                if let (Some(store), Some(session_id)) = (durability, durable_session_id) {
                    if let Err(e) = store
                        .checkpoint(session_id, messages, "tool_result", None)
                        .await
                    {
                        let msg = format!("durable checkpoint failed after delegate result: {e}");
                        emit(AssistantEvent::Error(msg.clone()));
                        return AssistantOutcome {
                            status: "error",
                            summary: msg,
                            turns,
                            tools_called,
                            tool_receipts,
                            model_used: last_model,
                        };
                    }
                }
                continue;
            }

            let proposal = match build_proposal(&result.model_used, call, &params_val) {
                Ok(p) => p,
                Err(e) => {
                    // A malformed call shape shouldn't sink the run; feed the
                    // error back so the model can retry with a valid shape.
                    let content = cap(json!({ "error": e }).to_string());
                    emit(AssistantEvent::ToolResult {
                        name: call.name.clone(),
                        ok: false,
                        content: content.clone(),
                    });
                    messages.push(Message::ToolResult {
                        tool_use_id: id,
                        content,
                        // A shape error the runtime itself wrote.
                        provenance: Provenance::Internal,
                    });
                    if let (Some(store), Some(session_id)) = (durability, durable_session_id) {
                        if let Err(e) = store
                            .checkpoint(session_id, messages, "malformed_tool_call", None)
                            .await
                        {
                            let msg = format!("durable checkpoint failed after tool error: {e}");
                            emit(AssistantEvent::Error(msg.clone()));
                            return AssistantOutcome {
                                status: "error",
                                summary: msg,
                                turns,
                                tools_called,
                                tool_receipts,
                                model_used: last_model,
                            };
                        }
                    }
                    continue;
                }
            };

            if needs_approval {
                let dispatch = match approval {
                    Some(gate) => gate.before_dispatch(&id, &call.name, &params_val).await,
                    None => Err("approval gate disappeared before dispatch".into()),
                };
                if let Err(e) = dispatch {
                    let content =
                        cap(json!({ "error": format!("dispatch refused: {e}") }).to_string());
                    emit(AssistantEvent::ToolResult {
                        name: call.name.clone(),
                        ok: false,
                        content: content.clone(),
                    });
                    messages.push(Message::ToolResult {
                        tool_use_id: id,
                        content,
                        provenance: Provenance::Internal,
                    });
                    if let (Some(store), Some(session_id)) = (durability, durable_session_id) {
                        let _ = store
                            .checkpoint(session_id, messages, "dispatch_refused", None)
                            .await;
                    }
                    continue;
                }
            }

            let exec = match runtime_session_id {
                Some(session_id) => runtime.execute_with_session(&proposal, session_id).await,
                None => runtime.execute(&proposal).await,
            };
            let action = exec.results.first();
            let runtime_succeeded = action
                .map(|r| matches!(r.status, ActionStatus::Succeeded))
                .unwrap_or(false);
            // Shell non-zero is intentionally returned as an observation so
            // the model can repair it, but it is not a successful receipt.
            // Treating Runtime::Succeeded as "tests passed" was a false-proof
            // bug because the executor successfully *ran* a command that
            // exited 1.
            let ok = runtime_succeeded
                && (call.name != "shell"
                    || action
                        .and_then(|result| result.output.as_ref())
                        .and_then(|output| output.get("exit_code"))
                        .and_then(Value::as_i64)
                        == Some(0));
            if needs_approval {
                let receipt = json!({
                    "ok": ok,
                    "action_id": action.map(|result| result.action_id.clone()),
                    "status": action.map(|result| format!("{:?}", result.status)),
                });
                if let Some(gate) = approval {
                    if let Err(e) = gate
                        .after_dispatch(&id, &call.name, &params_val, ok, &receipt)
                        .await
                    {
                        let msg = format!(
                            "action executed but its durable terminal receipt failed: {e}; action is indeterminate"
                        );
                        emit(AssistantEvent::Error(msg.clone()));
                        return AssistantOutcome {
                            status: "error",
                            summary: msg,
                            turns,
                            tools_called,
                            tool_receipts,
                            model_used: last_model,
                        };
                    }
                }
            }
            // Observation shaping (#813). Only a result that WOULD have been
            // destructively truncated is replaced by a preview: one that
            // already fits is strictly more useful shown whole, and paying a
            // handle + indirection for it would trade information the model
            // had for free against nothing.
            //
            // Note this is the narrower of the two possible readings of #813.
            // Previewing EVERY result — the shape NVIDIA's numbers come from —
            // would also cut the per-turn re-serialization cost, but it removes
            // detail from results that fit today. That is exactly the kind of
            // trade the `car-bench` A/B exists to settle, so it is deliberately
            // not assumed here.
            let content = match action {
                Some(r)
                    if cfg.value_store_previews && matches!(r.status, ActionStatus::Succeeded) =>
                {
                    let rendered = format_tool_result(r);
                    match (&r.output, rendered.len() > OBSERVATION_CAP) {
                        (Some(v), true) => {
                            let handle = values.put(v.clone());
                            format!(
                                "{}{}",
                                super::value_store::render_preview(&handle, v),
                                super::value_store::reference_hint(&handle)
                            )
                        }
                        // Fits, or carries no structured output to retain —
                        // a handle to nothing helps nobody.
                        _ => cap(rendered),
                    }
                }
                Some(r) => cap(format_tool_result(r)),
                None => cap(format!("tool '{}' produced no result", call.name)),
            };
            if ok {
                tools_called.push(call.name.clone());
                if mutating_tools.contains(&call.name) {
                    mutated_ok = true;
                }
            }
            tool_receipts.push(AssistantToolReceipt {
                tool: call.name.clone(),
                call_id: action.map(|r| r.action_id.clone()),
                ok,
                params: params_val.clone(),
                via: None,
            });
            emit(AssistantEvent::ToolResult {
                name: call.name.clone(),
                ok,
                content: content.clone(),
            });
            messages.push(Message::ToolResult {
                tool_use_id: id,
                content,
                // The only site that can carry bytes from outside the trust
                // boundary. Classified from the tool's information-flow labels
                // rather than a name list local to this file — see
                // `tool_output_is_external`.
                provenance: if tool_output_is_external(&call.name, tool_labels) {
                    Provenance::External
                } else {
                    Provenance::Internal
                },
            });
            if let (Some(store), Some(session_id)) = (durability, durable_session_id) {
                if let Err(e) = store
                    .checkpoint(session_id, messages, "tool_result", None)
                    .await
                {
                    let msg = format!("durable checkpoint failed after tool result: {e}");
                    emit(AssistantEvent::Error(msg.clone()));
                    return AssistantOutcome {
                        status: "error",
                        summary: msg,
                        turns,
                        tools_called,
                        tool_receipts,
                        model_used: last_model,
                    };
                }
            }
        }

        // No-progress guard, now that we know what actually SUCCEEDED. A real,
        // NEW state mutation resets everything (progress). A repeated signature —
        // even to a mutating tool — is a tight loop (nudge at STALL_NUDGE, stop at
        // STALL_BREAK); too many turns gathering info / failing to change anything
        // earns one soft nudge to act (EXPLORE_NUDGE) — no hard stop, since a
        // genuinely read-only task legitimately never mutates.
        let mut inject_nudge = false;
        match guard.observe(&tool_calls_signature(&calls), mutated_ok) {
            GuardStep::Break => {
                let summary = format!(
                    "Stopped: repeated the same action {} times without changing \
                     anything — no progress was being made.",
                    guard.stall_repeats
                );
                runtime
                    .record_turn_completed("stalled", None, false, turns, &last_model)
                    .await;
                emit(AssistantEvent::Done {
                    text: summary.clone(),
                });
                return AssistantOutcome {
                    status: "stalled",
                    summary,
                    turns,
                    tools_called,
                    tool_receipts,
                    model_used: last_model.clone(),
                };
            }
            GuardStep::Nudge => inject_nudge = true,
            GuardStep::Progress | GuardStep::Continue => {}
        }

        // The model has been repeating itself: prod it to act or finish. Injected
        // after the tool results so it reads as guidance on the just-seen output.
        if inject_nudge {
            messages.push(Message::User {
                content: "You have repeated the same action several times without \
                          changing anything or making progress. Stop re-reading and \
                          either take a concrete action (write or edit a file, run a \
                          command) or, if the task is genuinely complete, finish now \
                          with your summary."
                    .into(),
            });
            if let (Some(store), Some(session_id)) = (durability, durable_session_id) {
                if let Err(e) = store
                    .checkpoint(session_id, messages, "progress_nudge", None)
                    .await
                {
                    let msg = format!("durable checkpoint failed after progress nudge: {e}");
                    emit(AssistantEvent::Error(msg.clone()));
                    return AssistantOutcome {
                        status: "error",
                        summary: msg,
                        turns,
                        tools_called,
                        tool_receipts,
                        model_used: last_model,
                    };
                }
            }
        }
    }

    runtime
        .record_turn_completed("max_turns", None, false, turns, &last_model)
        .await;
    AssistantOutcome {
        status: "max_turns",
        summary: if last_text.is_empty() {
            format!("stopped after {} turns without finishing", cfg.max_turns)
        } else {
            last_text
        },
        turns,
        tools_called,
        tool_receipts,
        model_used: last_model.clone(),
    }
}

#[derive(Debug, Clone)]
struct SummaryClaimRequirement {
    label: &'static str,
    tools: &'static [&'static str],
    require_ok: bool,
    shell_terms: &'static [&'static str],
    paths: Vec<String>,
}

const TEST_TERMS: &[&str] = &[
    "test",
    "pytest",
    "cargo test",
    "cargo nextest",
    "npm test",
    "npm run test",
    "pnpm test",
    "pnpm run test",
    "yarn test",
    "bun test",
    "go test",
    "swift test",
    "dotnet test",
    "ctest",
    "cmake --build",
    "make test",
];
const BUILD_TERMS: &[&str] = &[
    "build",
    "cargo check",
    "cargo build",
    "npm run build",
    "pnpm build",
    "yarn build",
    "bun run build",
    "cmake --build",
    "go build",
    "swift build",
    "dotnet build",
    "mvn package",
    "gradle build",
    "./gradlew build",
];
const CHECK_TERMS: &[&str] = &[
    "cargo check",
    "git diff --check",
    "npm run lint",
    "npm run check",
    "pnpm check",
    "pnpm lint",
    "yarn check",
    "yarn lint",
    "bun run check",
    "eslint",
    "clippy",
    "swiftlint",
    "ruff",
    "mypy",
    "biome check",
];
// Shell-command substrings that evidence a read / write, used to decide whether a
// final-summary claim ("I read the files", "I created the file") is backed by a
// real tool receipt. The assistant's shell is `cmd /C` on Windows, so these must
// carry the cmd spellings too — otherwise a Windows run that genuinely wrote a
// file produces no recognized receipt and the claim check false-negatives against
// the model (annotating a truthful summary as unverified, or failing a
// judge-dependent verdict closed).
// Matching is a plain `cmd.contains(term)` (see `receipt_supports_claim`), so a
// term must not be a substring of an unrelated command: `"dir "` is deliberately
// absent because it also matches `mkdir `, which would let a *write* stand in as
// a *read* receipt on every platform.
const READ_TERMS: &[&str] = &[
    "cat ", "sed ", "rg ", "grep ", "ls ", "find ", // POSIX
    "type ", "findstr ", // cmd
];
const WRITE_TERMS: &[&str] = &[
    "touch ",
    "cat >",
    "tee ",
    "python ",
    "node ",
    "perl ", // POSIX
    "type nul >",
    "echo >", // cmd
];
const GIT_STATUS_TERMS: &[&str] = &["git status"];
const GIT_REVISION_TERMS: &[&str] = &["git rev-parse", "git log", "git show"];
const APP_INSIGHTS_TERMS: &[&str] = &["az monitor app-insights query"];
const DEPLOYMENT_EVIDENCE_TERMS: &[&str] = &[
    "az pipelines show",
    "az pipelines runs show",
    "az devops invoke",
];
const SUMMARY_PATH_EXTENSIONS: &[&str] = &[
    ".rs", ".py", ".js", ".ts", ".tsx", ".jsx", ".go", ".swift", ".java", ".kt", ".kts", ".c",
    ".h", ".cc", ".hh", ".cpp", ".hpp", ".cxx", ".hxx", ".cs", ".fs", ".vb", ".php", ".rb", ".ex",
    ".exs", ".md", ".txt", ".json", ".yaml", ".yml", ".toml", ".html", ".css", ".xml", ".sh",
    ".sql",
];

fn normalize_summary_path_token(raw: &str) -> Option<String> {
    let token = raw.trim_matches(|c: char| {
        matches!(
            c,
            '"' | '\'' | '`' | ',' | ';' | ':' | ')' | '(' | '[' | ']' | '{' | '}' | '.'
        )
    });
    if token.is_empty() || token.starts_with('-') || token.contains("://") || token.contains("..") {
        return None;
    }
    let looks_like_path = token.contains('/')
        || SUMMARY_PATH_EXTENSIONS
            .iter()
            .any(|ext| token.to_ascii_lowercase().ends_with(ext));
    if !looks_like_path {
        return None;
    }
    Some(
        token
            .trim_start_matches("./")
            .replace('\\', "/")
            .to_ascii_lowercase(),
    )
}

fn summary_path_hints(summary: &str) -> Vec<String> {
    let mut paths = Vec::new();
    for raw in summary.split_whitespace() {
        if let Some(path) = normalize_summary_path_token(raw) {
            if !paths.contains(&path) {
                paths.push(path);
            }
        }
    }
    paths
}

fn summary_claim_requirements(summary: &str) -> Vec<SummaryClaimRequirement> {
    let s = summary.to_ascii_lowercase();
    let units: Vec<&str> = s
        .split(['\n', '.'])
        .map(str::trim)
        .filter(|unit| !unit.is_empty())
        .collect();
    let path_hints = summary_path_hints(summary);
    let mut claims = Vec::new();
    if units.iter().any(|unit| {
        unit.contains("ran the test")
            || unit.contains("ran tests")
            || (unit.contains("verified with") && unit.contains("test"))
            || (unit.contains("test")
                && (unit.contains("passed")
                    || unit.contains("green")
                    || unit.contains("succeeded")
                    || unit.contains("successful")))
    }) {
        claims.push(SummaryClaimRequirement {
            label: "tests were run/passed",
            tools: &["shell"],
            require_ok: true,
            shell_terms: TEST_TERMS,
            paths: Vec::new(),
        });
    }
    if units.iter().any(|unit| {
        (unit.contains("build") || unit.contains("cargo check"))
            && (unit.contains("passed")
                || unit.contains("succeeded")
                || unit.contains("successful")
                || unit.contains("built")
                || unit.contains("green")
                || unit.contains("ran the build")
                || unit.contains("ran cargo check"))
    }) {
        claims.push(SummaryClaimRequirement {
            label: "build succeeded",
            tools: &["shell"],
            require_ok: true,
            shell_terms: BUILD_TERMS,
            paths: Vec::new(),
        });
    }
    if units.iter().any(|unit| {
        (unit.contains("check") || unit.contains("lint"))
            && (unit.contains("passed")
                || unit.contains("green")
                || unit.contains("succeeded")
                || unit.contains("successful"))
    }) {
        claims.push(SummaryClaimRequirement {
            label: "checks were run/passed",
            tools: &["shell"],
            require_ok: true,
            shell_terms: CHECK_TERMS,
            paths: Vec::new(),
        });
    }
    if units.iter().any(|unit| {
        (unit.contains("read ") || unit.contains("inspected ") || unit.contains("looked at "))
            && (unit.contains("file") || unit.contains("source"))
    }) {
        claims.push(SummaryClaimRequirement {
            label: "files were read/inspected",
            tools: &["read_file", "list_dir", "find_files", "grep_files", "shell"],
            require_ok: true,
            shell_terms: READ_TERMS,
            paths: path_hints.clone(),
        });
    }
    if units.iter().any(|unit| {
        (unit.contains("created")
            || unit.contains("wrote")
            || unit.contains("updated")
            || unit.contains("edited"))
            && unit.contains("file")
    }) {
        claims.push(SummaryClaimRequirement {
            label: "files were created/updated",
            tools: &["write_file", "edit_file", "shell"],
            require_ok: true,
            shell_terms: WRITE_TERMS,
            paths: path_hints.clone(),
        });
    }
    if units.iter().any(|unit| {
        unit.contains("repository is clean")
            || unit.contains("repo is clean")
            || unit.contains("working tree is clean")
            || unit.contains("status: clean")
    }) {
        claims.push(SummaryClaimRequirement {
            label: "repository cleanliness was verified",
            tools: &["shell"],
            require_ok: true,
            shell_terms: GIT_STATUS_TERMS,
            paths: Vec::new(),
        });
    }
    if units.iter().any(|unit| {
        unit.contains("head matches origin")
            || unit.contains("head is aligned with origin")
            || unit.contains("head and origin are identical")
    }) {
        claims.push(SummaryClaimRequirement {
            label: "repository revision/remote relationship was verified",
            tools: &["shell"],
            require_ok: true,
            shell_terms: GIT_REVISION_TERMS,
            paths: Vec::new(),
        });
    }
    if units.iter().any(|unit| {
        (unit.contains("app insights")
            || unit.contains("application insights")
            || unit.contains("telemetry"))
            && (unit.contains("query showed")
                || unit.contains("query confirmed")
                || unit.contains("we observed")
                || unit.contains("live telemetry showed")
                || unit.contains("no recurrence")
                || unit.contains("recurred after"))
            && !unit.contains("not obtained")
            && !unit.contains("unable")
    }) {
        claims.push(SummaryClaimRequirement {
            label: "live Application Insights evidence was observed",
            tools: &["shell", "browse_observe"],
            require_ok: true,
            shell_terms: APP_INSIGHTS_TERMS,
            paths: Vec::new(),
        });
    }
    if units.iter().any(|unit| {
        (unit.contains("production") || unit.contains("live"))
            && (unit.contains("browser") || unit.contains("portal") || unit.contains("page"))
            && (unit.contains("inspected")
                || unit.contains("observed")
                || unit.contains("verified"))
            && !unit.contains("not obtained")
            && !unit.contains("unable")
    }) {
        claims.push(SummaryClaimRequirement {
            label: "production browser state was observed",
            tools: &["browse_observe"],
            require_ok: true,
            shell_terms: &[],
            paths: Vec::new(),
        });
    }
    if units.iter().any(|unit| {
        unit.contains("deployment")
            && (unit.contains("successfully fixed")
                || unit.contains("was deployed")
                || unit.contains("after fix")
                || unit.contains("post-deployment"))
            && !unit.contains("cannot")
            && !unit.contains("not obtained")
    }) {
        claims.push(SummaryClaimRequirement {
            label: "deployment state/change was verified",
            tools: &["shell"],
            require_ok: true,
            shell_terms: DEPLOYMENT_EVIDENCE_TERMS,
            paths: Vec::new(),
        });
    }
    if units.iter().any(|unit| {
        unit.contains("subscription")
            && (unit.contains("outside") || unit.contains("not in"))
            && unit
                .as_bytes()
                .windows(2)
                .any(|window| window[0] == b'n' && window[1].is_ascii_digit())
            && !unit.contains("cannot")
            && !unit.contains("not verified")
            && !unit.contains("not obtained")
            && !unit.contains("insufficient evidence")
    }) {
        claims.push(SummaryClaimRequirement {
            label: "named aircraft subscription status was observed live",
            tools: &["shell"],
            require_ok: true,
            shell_terms: APP_INSIGHTS_TERMS,
            paths: Vec::new(),
        });
    }
    claims
}

fn shell_command(params: &Value) -> Option<String> {
    params
        .get("command")
        .and_then(Value::as_str)
        .map(|s| s.to_ascii_lowercase())
}

fn normalized_receipt_path(params: &Value) -> Option<String> {
    params.get("path").and_then(Value::as_str).map(|path| {
        path.trim_start_matches("./")
            .replace('\\', "/")
            .to_ascii_lowercase()
    })
}

fn text_mentions_summary_path(text: &str, path: &str) -> bool {
    let text = text.replace('\\', "/").to_ascii_lowercase();
    text.contains(path) || text.contains(&format!("./{path}"))
}

fn receipt_mentions_summary_path(receipt: &AssistantToolReceipt, path: &str) -> bool {
    if receipt.tool == "shell" {
        return shell_command(&receipt.params)
            .map(|cmd| text_mentions_summary_path(&cmd, path))
            .unwrap_or(false);
    }
    normalized_receipt_path(&receipt.params)
        .map(|receipt_path| text_mentions_summary_path(&receipt_path, path))
        .unwrap_or(false)
}

fn receipt_satisfies_claim(
    receipt: &AssistantToolReceipt,
    claim: &SummaryClaimRequirement,
) -> bool {
    if claim.require_ok && !receipt.ok {
        return false;
    }
    if !claim.tools.iter().any(|t| *t == receipt.tool) {
        return false;
    }
    if !claim.paths.is_empty()
        && !claim
            .paths
            .iter()
            .any(|path| receipt_mentions_summary_path(receipt, path))
    {
        return false;
    }
    if receipt.tool != "shell" || claim.shell_terms.is_empty() {
        return true;
    }
    let Some(cmd) = shell_command(&receipt.params) else {
        return false;
    };
    claim.shell_terms.iter().any(|term| cmd.contains(term))
}

/// Operational claims the final prose makes that no same-run tool receipt
/// supports — "I ran the tests" with no matching shell call, "I created X"
/// with no matching write.
///
/// Public because a machine-readable caller (`car do --json`, and any host
/// embedding the assistant) needs this as a **field**, not as prose appended
/// to the summary. Folded into the text it is a note a relaying model can
/// silently drop; as data it is a caution the caller must decide what to do
/// with. This is the mechanical half of "receipts decide completion".
///
/// Detection is lexical and deliberately conservative: it flags claims whose
/// wording names an operation, and stays silent otherwise. An empty result
/// means "nothing detected", NOT "the summary is verified".
pub fn ungrounded_summary_claims(
    summary: &str,
    receipts: &[AssistantToolReceipt],
) -> Vec<&'static str> {
    summary_claim_requirements(summary)
        .into_iter()
        .filter(|claim| {
            !receipts
                .iter()
                .any(|receipt| receipt_satisfies_claim(receipt, claim))
        })
        .map(|claim| claim.label)
        .collect()
}

fn apply_summary_claim_grounding(
    mut verdict: car_verify::goal::GoalVerdict,
    outcome: &AssistantOutcome,
) -> car_verify::goal::GoalVerdict {
    if !verdict.met {
        return verdict;
    }
    let ungrounded = ungrounded_summary_claims(&outcome.summary, &outcome.tool_receipts);
    if ungrounded.is_empty() {
        return verdict;
    }
    verdict.grounded = false;
    verdict.reason = format!(
        "{}; ungrounded assistant summary claim(s): {}",
        verdict.reason,
        ungrounded.join(", ")
    );
    verdict
}

/// Append a **non-authoritative** claim-check note to a goal-loop reply.
///
/// Used only on the deterministic-pass path (F9): when the goal check already
/// passed against ground truth but the final prose named an operational claim
/// ("tests passed", "created file X") with no matching same-run tool receipt,
/// the completion still stands — this only flags the unverified wording to the
/// reader. Written ONLY to the returned `GoalLoopResult.outcome.summary`; the
/// caller must never fold it into the `messages` Vec, which chat.rs persists
/// into the session thread (the note would then leak into later turns' context).
pub fn annotate_summary_with_claim_note(summary: &str, ungrounded: &[&'static str]) -> String {
    if ungrounded.is_empty() {
        return summary.to_string();
    }
    format!(
        "{summary}\n\n[claim check] unverified summary claim(s) this run \
         (no matching tool receipt): {}",
        ungrounded.join(", ")
    )
}

/// The result of a goal-driven assistant run: the last iteration's
/// [`AssistantOutcome`] plus the [`GoalRun`] audit (per-iteration verdicts,
/// grounded flag, halt reason).
pub struct GoalLoopResult {
    pub outcome: AssistantOutcome,
    pub run: car_verify::goal::GoalRun,
}

/// Upper bound on one `gather` pass — the "is this iteration's condition met?"
/// evaluation run after every iteration (car#1112). `gather` is caller-supplied
/// and may itself await a human approval, a subprocess, or (for a future
/// [`car_verify::goal::GoalCondition::ModelJudge`]) an inference call; none of
/// those callees is guaranteed to resolve on their own. Reuses the crate's
/// existing single-check ceiling (`car do`'s shell tool) rather than inventing
/// a second magic number for what is, structurally, the same kind of wait.
const GOAL_EVALUATION_TIMEOUT: Duration =
    Duration::from_secs(crate::coder::shell_tool::DEFAULT_SHELL_TIMEOUT_SECS);

/// Drive the assistant as a **goal loop**: keep running iterations (each a full
/// [`run_assistant_loop_cancellable`] pass — the model works until it stops
/// emitting tool calls) until a **deterministic** [`car_verify::goal::GoalCondition`]
/// holds or a [`car_verify::goal::GoalGovernor`] bound is hit. This is CAR's
/// answer to `/goal`: the "am I done?" decision is made by
/// [`car_verify::goal::evaluate_goal`] over ground truth gathered from the
/// runtime (`gather`), never by a model reading its own transcript.
///
/// `messages` should carry only the system turn; the loop drives every user turn
/// from the pinned goal (the drift anchor, re-derived each iteration via
/// [`car_verify::goal::anchor_directive`], so no turn can repoint the objective).
/// `gather(&outcome)` projects a [`GoalGather`] after each iteration — the caller
/// owns which command/model checks to run; the runtime folds in receipts/state.
pub async fn run_assistant_goal_loop<G, GF>(
    generator: &dyn TurnGenerator,
    runtime: &Runtime,
    cfg: &AssistantConfig,
    messages: &mut Vec<Message>,
    cancel: &std::sync::atomic::AtomicBool,
    approval: Option<&dyn ApprovalGate>,
    spec: &car_verify::goal::GoalSpec,
    gather: G,
    emit: impl FnMut(AssistantEvent),
) -> GoalLoopResult
where
    G: FnMut(&AssistantOutcome) -> GF,
    GF: std::future::Future<Output = car_engine::GoalGather>,
{
    run_assistant_goal_loop_in_session(
        generator, runtime, cfg, messages, cancel, approval, spec, None, gather, emit,
    )
    .await
}

/// Session-aware variant of [`run_assistant_goal_loop`].
pub async fn run_assistant_goal_loop_in_session<G, GF>(
    generator: &dyn TurnGenerator,
    runtime: &Runtime,
    cfg: &AssistantConfig,
    messages: &mut Vec<Message>,
    cancel: &std::sync::atomic::AtomicBool,
    approval: Option<&dyn ApprovalGate>,
    spec: &car_verify::goal::GoalSpec,
    runtime_session_id: Option<&str>,
    gather: G,
    emit: impl FnMut(AssistantEvent),
) -> GoalLoopResult
where
    G: FnMut(&AssistantOutcome) -> GF,
    GF: std::future::Future<Output = car_engine::GoalGather>,
{
    run_assistant_goal_loop_in_session_durable(
        generator,
        runtime,
        cfg,
        messages,
        cancel,
        approval,
        spec,
        runtime_session_id,
        None,
        None,
        gather,
        emit,
    )
    .await
}

pub async fn run_assistant_goal_loop_in_session_durable<G, GF>(
    generator: &dyn TurnGenerator,
    runtime: &Runtime,
    cfg: &AssistantConfig,
    messages: &mut Vec<Message>,
    cancel: &std::sync::atomic::AtomicBool,
    approval: Option<&dyn ApprovalGate>,
    spec: &car_verify::goal::GoalSpec,
    runtime_session_id: Option<&str>,
    durable_session_id: Option<&str>,
    durability: Option<&dyn super::governance::AssistantDurability>,
    mut gather: G,
    mut emit: impl FnMut(AssistantEvent),
) -> GoalLoopResult
where
    G: FnMut(&AssistantOutcome) -> GF,
    GF: std::future::Future<Output = car_engine::GoalGather>,
{
    use car_verify::goal::{
        anchor_directive, evaluate_goal, governor_check, GoalHalt, GoalRun, GoalRunState,
        GoalStatus, GoalVerdict,
    };
    use std::sync::atomic::Ordering;

    let start = std::time::Instant::now();
    let mut run_state = GoalRunState::default();
    let mut evidence: Vec<GoalVerdict> = Vec::new();
    let mut last_reason = String::new();
    let mut last_outcome = AssistantOutcome {
        status: "goal_pending",
        summary: String::new(),
        turns: 0,
        tools_called: Vec::new(),
        tool_receipts: Vec::new(),
        model_used: String::new(),
    };

    let finish = |status: GoalStatus,
                  grounded: bool,
                  reason: String,
                  iterations: u32,
                  evidence: Vec<GoalVerdict>,
                  outcome: AssistantOutcome|
     -> GoalLoopResult {
        GoalLoopResult {
            run: GoalRun {
                status,
                iterations,
                grounded,
                cost_usd: 0.0,
                last_reason: reason,
                evidence,
            },
            outcome,
        }
    };

    loop {
        run_state.elapsed_secs = start.elapsed().as_secs();
        if cancel.load(Ordering::Relaxed) {
            return finish(
                GoalStatus::Halted {
                    halt: GoalHalt::Cancelled,
                },
                evidence.last().map(|v| v.grounded).unwrap_or(true),
                "cancelled".into(),
                run_state.turns,
                evidence,
                last_outcome,
            );
        }
        if let Some(halt) = governor_check(&spec.governor, &run_state) {
            return finish(
                GoalStatus::Halted { halt },
                evidence.last().map(|v| v.grounded).unwrap_or(true),
                if last_reason.is_empty() {
                    halt.as_str().to_string()
                } else {
                    format!("{} ({})", halt.as_str(), last_reason)
                },
                run_state.turns,
                evidence,
                last_outcome,
            );
        }

        // Anchor the directive from the pinned goal and push it as the next
        // user turn (the loop owns all user turns).
        let directive = anchor_directive(&spec.goal, &last_reason);
        messages.push(Message::User { content: directive });
        if let (Some(store), Some(session_id)) = (durability, durable_session_id) {
            if let Err(e) = store
                .checkpoint(
                    session_id,
                    messages,
                    "goal_directive",
                    serde_json::to_value(spec).ok(),
                )
                .await
            {
                last_outcome.status = "error";
                last_outcome.summary = format!("durable goal checkpoint failed: {e}");
                return finish(
                    GoalStatus::Halted {
                        halt: GoalHalt::Cancelled,
                    },
                    false,
                    last_outcome.summary.clone(),
                    run_state.turns,
                    evidence,
                    last_outcome,
                );
            }
        }

        let mut outcome = run_assistant_loop_cancellable_in_session_durable(
            generator,
            runtime,
            cfg,
            messages,
            cancel,
            approval,
            None,
            runtime_session_id,
            durable_session_id,
            durability,
            false,
            &mut emit,
        )
        .await;
        run_state.turns += 1;
        // Progress = the iteration actually executed a tool. A prose-only turn
        // that didn't move the world is thrash (drives the no-progress guard).
        if outcome.tools_called.is_empty() {
            run_state.turns_since_progress += 1;
        } else {
            run_state.turns_since_progress = 0;
        }

        if outcome.status == "cancelled" {
            return finish(
                GoalStatus::Halted {
                    halt: GoalHalt::Cancelled,
                },
                evidence.last().map(|v| v.grounded).unwrap_or(true),
                "cancelled".into(),
                run_state.turns,
                evidence,
                outcome,
            );
        }

        // Gather ground truth and evaluate the deterministic condition. Bounded
        // (car#1112): this iteration already produced a real reply in `outcome`
        // — that reply is owed to the caller regardless of whether the
        // condition can be graded, so a `gather` that never resolves must halt
        // immediately (fail open) rather than hang the turn or burn the rest
        // of the iteration budget re-running the model against a condition
        // that structurally can never be evaluated.
        let g = match tokio::time::timeout(GOAL_EVALUATION_TIMEOUT, gather(&outcome)).await {
            Ok(g) => g,
            Err(_) => {
                let reason = format!(
                    "goal check did not complete within {}s — treating this turn's reply as \
                     unevaluated rather than blocking on it",
                    GOAL_EVALUATION_TIMEOUT.as_secs()
                );
                // `grounded: false` (car#1113 review), not `true`: `grounded`
                // means the verdict rests on deterministic ground truth, but
                // there IS no verdict here — the check never ran. `grounded:
                // true` next to `met: false` reads on the wire as
                // "deterministically evaluated, definitively not met", which
                // is the opposite of what this halt means. Confirmed harmless
                // to flip: `met: false` alone already keeps
                // `ChatGoalState.status` at `"running"` in
                // `handler::update_chat_goal_from_event`'s `goal_evaluated`
                // arm (it only reads `grounded` when `met == true`), and this
                // arm returns immediately after, so no loop logic downstream
                // consumes the flipped value either.
                let verdict = GoalVerdict {
                    met: false,
                    grounded: false,
                    reason: reason.clone(),
                };
                evidence.push(verdict.clone());
                runtime
                    .record_goal_evaluated(
                        &spec.goal,
                        &spec.condition,
                        run_state.turns,
                        verdict.met,
                        verdict.grounded,
                        &verdict.reason,
                        &outcome.model_used,
                    )
                    .await;
                tracing::warn!(
                    target: "car::goal",
                    iteration = run_state.turns,
                    timeout_secs = GOAL_EVALUATION_TIMEOUT.as_secs(),
                    "goal evaluation timed out — halting with the primary reply intact"
                );
                emit(AssistantEvent::GoalEvaluated {
                    iteration: run_state.turns,
                    met: false,
                    grounded: false,
                    reason: reason.clone(),
                });
                return finish(
                    GoalStatus::Halted {
                        halt: GoalHalt::EvaluationTimeout,
                    },
                    false,
                    reason,
                    run_state.turns,
                    evidence,
                    outcome,
                );
            }
        };
        let inputs = runtime.gather_goal_inputs(&g).await;

        // Pre-grounding verdict. `base.met && base.grounded` is exactly "the
        // deterministic check passed": a met verdict is grounded iff it rested
        // only on deterministic leaves (Command / StatePredicate / receipts / …);
        // a met verdict that leaned on a `ModelJudge` is grounded=false.
        let base = evaluate_goal(&spec.condition, &inputs);
        let verdict = if base.met && base.grounded {
            // Deterministic pass: ground truth already verified completion, so
            // final-summary claim grounding is DEMOTED from an authority (it used
            // to flip grounded=false and re-drive the loop on word choice — F9) to
            // a reply annotation. Keep grounded=true; if the prose named an
            // operational claim with no matching same-run receipt, log it and note
            // it on the returned reply text ONLY — never touch `messages`
            // (persisted into the session thread) or the verdict's grounded flag /
            // durable event. A deterministically-verified completion is not the
            // false-completion pattern the Phase-0 miners look for, so the prose
            // mismatch is logged at info, not recorded as a failure signal.
            let ungrounded = ungrounded_summary_claims(&outcome.summary, &outcome.tool_receipts);
            if !ungrounded.is_empty() {
                tracing::info!(
                    target: "car::goal",
                    iteration = run_state.turns,
                    claims = %ungrounded.join(", "),
                    "deterministic goal check passed; final-summary claim(s) unmatched \
                     to a tool receipt — annotating reply, keeping grounded=true"
                );
                outcome.summary = annotate_summary_with_claim_note(&outcome.summary, &ungrounded);
            }
            base
        } else {
            // Not a deterministic pass (unmet, or met only via a `ModelJudge`):
            // UNCHANGED behavior — claim grounding retains its authority to flip
            // grounded=false and concat the reason, the loop keeps iterating, and
            // the Phase-0 miners keep receiving the ungrounded `GoalEvaluated`
            // signal (harness_adapt ungrounded-completion, evolution failure fold).
            apply_summary_claim_grounding(base, &outcome)
        };
        evidence.push(verdict.clone());
        runtime
            .record_goal_evaluated(
                &spec.goal,
                &spec.condition,
                run_state.turns,
                verdict.met,
                verdict.grounded,
                &verdict.reason,
                &outcome.model_used,
            )
            .await;
        // Audit and stream the "why continue?" decision. The typed event-log
        // entry above is durable; this tracing/UI event is for live operators.
        tracing::info!(
            target: "car::goal",
            iteration = run_state.turns,
            met = verdict.met,
            grounded = verdict.grounded,
            reason = %verdict.reason,
            "goal evaluated"
        );
        emit(AssistantEvent::GoalEvaluated {
            iteration: run_state.turns,
            met: verdict.met,
            grounded: verdict.grounded,
            reason: verdict.reason.clone(),
        });

        if verdict.met && verdict.grounded {
            return finish(
                GoalStatus::Achieved,
                verdict.grounded,
                verdict.reason,
                run_state.turns,
                evidence,
                outcome,
            );
        }
        last_reason = verdict.reason;
        last_outcome = outcome;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::assistant::executor::GeneralExecutor;
    use async_trait::async_trait;
    use car_engine::{LocalSubstrate, Runtime, Substrate, ToolExecutor};
    use car_inference::{InferenceEngine, InferenceResult};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex as StdMutex};

    // ---- observation truncation (#813) ----

    /// Truncation must state its magnitude. The old marker was a bare
    /// `…[truncated]…`, so a model could not tell whether it had lost 10 bytes
    /// or 10 MB, and a clipped table read as a complete one.
    ///
    /// This does NOT make truncation non-destructive — the elided bytes are
    /// still gone. That is the session-value-store work in #813, which needs
    /// its own design pass. This only makes the loss legible.
    #[test]
    fn truncation_reports_true_size_and_elided_amount() {
        let total = OBSERVATION_CAP + 5_000;
        let out = cap("x".repeat(total));

        assert!(
            out.contains(&format!("of {total} bytes")),
            "the TRUE size must be reported, not just the fact of truncation: {}",
            &out[out.len().saturating_sub(200)..]
        );
        assert!(
            out.contains("5000 bytes elided"),
            "the elided amount must be reported so the model can judge the loss: {}",
            &out[out.len().saturating_sub(200)..]
        );
        assert!(
            out.contains("NOT retained"),
            "the model must be told re-running is the only recovery"
        );
        // The payload itself is still bounded — the notice is additive.
        assert!(out.starts_with(&"x".repeat(1_000)));
    }

    /// An observation at or under the cap must pass through untouched — no
    /// notice, no allocation of a truncation message.
    #[test]
    fn observations_within_the_cap_are_unmodified() {
        let small = "y".repeat(OBSERVATION_CAP);
        assert_eq!(cap(small.clone()), small);
        let tiny = "hello".to_string();
        assert_eq!(cap(tiny.clone()), tiny);
    }

    /// Truncation must land on a char boundary — a multi-byte payload clipped
    /// mid-codepoint would panic on `truncate`.
    #[test]
    fn truncation_respects_char_boundaries() {
        // 3-byte chars, so OBSERVATION_CAP (16384) is not a boundary multiple.
        let s = "".repeat(OBSERVATION_CAP);
        let out = cap(s);
        assert!(out.contains("bytes elided"));
        assert!(out.is_char_boundary(0));
    }

    // ---- no-progress guard ----

    #[test]
    fn guard_breaks_on_repeated_mutation_not_just_reads() {
        // The bug: a "mutating" tool (e.g. remember) called with identical args
        // every turn reset the guard forever and ran to max_turns. A repeated
        // identical call is idempotent — no new progress — so it must trip
        // STALL_BREAK like any other stall.
        let mut g = NoProgressGuard::default();
        // First remember of this fact IS progress (new signature).
        assert_eq!(
            g.observe("remember({\"body\":\"x\"})", true),
            GuardStep::Progress
        );
        // Re-remembering the same fact makes no progress; it accumulates to a
        // hard stop rather than resetting.
        let sig = "remember({\"body\":\"x\"})";
        let mut steps = vec![];
        for _ in 0..STALL_BREAK {
            steps.push(g.observe(sig, true));
        }
        assert!(
            steps.contains(&GuardStep::Break),
            "repeated identical mutation must eventually Break, got {steps:?}"
        );
        assert!(
            steps.contains(&GuardStep::Nudge),
            "should nudge before breaking"
        );
    }

    #[test]
    fn guard_treats_distinct_mutations_as_progress() {
        // Remembering several DIFFERENT facts is real work — never a stall.
        let mut g = NoProgressGuard::default();
        for i in 0..20 {
            let sig = format!("remember({{\"body\":\"fact-{i}\"}})");
            assert_eq!(g.observe(&sig, true), GuardStep::Progress);
        }
    }

    #[test]
    fn guard_read_only_repeat_still_breaks() {
        // Non-mutating behavior is unchanged: a repeated read loop stalls out.
        let mut g = NoProgressGuard::default();
        let mut steps = vec![];
        for _ in 0..(STALL_BREAK + 1) {
            steps.push(g.observe("recall({\"q\":\"x\"})", false));
        }
        assert!(steps.contains(&GuardStep::Break));
    }

    #[test]
    fn guard_read_only_task_never_hard_stops_without_repeat() {
        // Distinct reads never repeat a signature, so they only ever earn the
        // soft EXPLORE_NUDGE — never a Break (a genuinely read-only task is legit).
        let mut g = NoProgressGuard::default();
        let mut steps = vec![];
        for i in 0..(EXPLORE_NUDGE + 5) {
            steps.push(g.observe(&format!("read_file({{\"p\":\"f{i}\"}})"), false));
        }
        assert!(
            !steps.contains(&GuardStep::Break),
            "distinct reads must not Break"
        );
        assert!(
            steps.contains(&GuardStep::Nudge),
            "should soft-nudge after EXPLORE_NUDGE"
        );
    }

    // ---- history compaction (context-window bound) ----

    fn sys(t: &str) -> Message {
        Message::System { content: t.into() }
    }
    fn usr(t: &str) -> Message {
        Message::User { content: t.into() }
    }
    fn asst_call(id: &str) -> Message {
        Message::Assistant {
            content: String::new(),
            tool_calls: vec![serde_json::from_value(json!({
                "name": "write_file",
                "arguments": {"path": "a.js"},
                "id": id
            }))
            .unwrap()],
            thinking: vec![],
        }
    }
    fn tool_res(id: &str, body: &str) -> Message {
        Message::ToolResult {
            tool_use_id: id.into(),
            content: body.into(),
            provenance: Default::default(),
        }
    }
    fn provider_item(id: &str, body: &str) -> Message {
        Message::ProviderOutputItems {
            protocol: car_inference::protocol::OPENAI_RESPONSES_PROTOCOL.into(),
            items: vec![json!({
                "type": "reasoning",
                "id": id,
                "status": "completed",
                "encrypted_content": body,
            })],
        }
    }

    /// A kept history must never begin a segment with an orphaned ToolResult
    /// (one whose Assistant call was dropped) — that is provider-invalid.
    fn no_orphan_tool_results(msgs: &[Message]) -> bool {
        let mut seen_call_ids: std::collections::HashSet<String> = Default::default();
        for m in msgs {
            match m {
                Message::Assistant { tool_calls, .. } => {
                    for c in tool_calls {
                        if let Some(id) = &c.id {
                            seen_call_ids.insert(id.clone());
                        }
                    }
                }
                Message::ToolResult { tool_use_id, .. } if !seen_call_ids.contains(tool_use_id) => {
                    return false;
                }
                _ => {}
            }
        }
        true
    }

    #[test]
    fn mutating_tools_are_derived_from_metadata_plus_builtin_file_writers() {
        let tools = vec![
            json!({"name": "remember", "mutating": true}),
            json!({"name": "recall"}),
            json!({"name": "generate_image", "mutating": true}),
        ];
        let names = mutating_tool_names(&tools);

        assert!(names.contains("write_file"));
        assert!(names.contains("edit_file"));
        assert!(names.contains("remember"));
        assert!(names.contains("generate_image"));
        assert!(!names.contains("recall"));
    }

    #[test]
    fn compaction_is_noop_under_budget_and_when_window_unknown() {
        let mut m = vec![
            sys("s"),
            usr("task"),
            asst_call("c1"),
            tool_res("c1", "small"),
        ];
        let before = m.clone();
        compact_history_to_window(&mut m, 128_000); // tiny history, huge window
        assert_eq!(m, before, "under-budget history must be untouched");
        compact_history_to_window(&mut m, 0); // unknown window
        assert_eq!(m, before, "unknown window must be a no-op");
    }

    #[test]
    fn compaction_pins_system_and_task_keeps_tail_no_orphans() {
        let big = "x".repeat(20_000); // ~5k tokens each
        let mut m = vec![sys("system"), usr("THE ORIGINAL TASK")];
        for i in 0..12 {
            m.push(asst_call(&format!("c{i}")));
            m.push(tool_res(&format!("c{i}"), &big));
        }
        let window = 20_000; // budget = 15k tokens — forces heavy trimming
        compact_history_to_window(&mut m, window);

        // Pinned head survives.
        assert!(matches!(&m[0], Message::System { .. }), "system pinned");
        assert!(
            matches!(&m[1], Message::User { content } if content == "THE ORIGINAL TASK"),
            "original task pinned"
        );
        // Recent tail survives (last exchange present).
        assert!(
            matches!(m.last(), Some(Message::ToolResult { tool_use_id, .. }) if tool_use_id == "c11"),
            "most-recent tool result kept"
        );
        // Structurally valid: no dangling tool results.
        assert!(
            no_orphan_tool_results(&m),
            "no orphaned tool results after trim"
        );
        // It actually shrank.
        assert!(m.len() < 26, "history was compacted (was 26 msgs)");
    }

    /// #814 items 2-3 — durable state must reach the model without it having to
    /// ask, and must land at the TAIL so the cached prefix stays byte-stable.
    ///
    /// Appending to the last message rather than adding a trailing
    /// `Message::System` is what makes the tail placement real: the Anthropic
    /// and Gemini handlers fold every System message into the top-level system
    /// field, so a trailing System block would land in the cached PREFIX on two
    /// of three providers — the exact invalidation item 3 exists to prevent.
    #[test]
    fn state_block_lands_at_the_tail_inside_the_last_message() {
        let mut messages = vec![
            sys("system prompt"),
            usr("do the thing"),
            tool_res("c1", "tool output here"),
        ];
        let before_prefix = format!("{:?}{:?}", messages[0], messages[1]);

        append_state_block(&mut messages, "todo: 1/3 done\n  [ ] 2 wire the CLI");

        // The block is inside the LAST message…
        let Message::ToolResult { content, .. } = &messages[2] else {
            panic!("last message should still be the tool result");
        };
        assert!(content.starts_with("tool output here"), "{content}");
        assert!(
            content.contains("wire the CLI"),
            "state must be present: {content}"
        );
        // …fenced, so it cannot read as part of the tool's own output.
        assert!(content.contains("<runtime-state>"), "{content}");
        assert!(content.contains("</runtime-state>"), "{content}");
        // …and no message was added or reordered.
        assert_eq!(messages.len(), 3);
        // The prefix is untouched — this is the property item 3 is about.
        assert_eq!(
            before_prefix,
            format!("{:?}{:?}", messages[0], messages[1]),
            "appending state must not perturb the cached prefix"
        );
    }

    /// The block is regenerated every turn, so it must never be persisted —
    /// otherwise stale copies stack up in the history, one per turn.
    #[tokio::test]
    async fn state_block_never_enters_the_durable_history() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let todos = Arc::new(tokio::sync::Mutex::new(super::super::todo::TodoList::new()));
        todos
            .lock()
            .await
            .write(&[json!({"text": "wire the CLI"})])
            .unwrap();

        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![turn("done", json!([]))],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("do it")];
        let mut cfg = cfg();
        cfg.todos = Some(Arc::clone(&todos));
        run_assistant_loop(&script, &rt, &cfg, &mut messages, |_| {}).await;

        // The model saw it…
        let sent = seen.lock().unwrap();
        let sent_msgs = sent[0].messages.as_ref().expect("messages sent");
        let tail = format!("{:?}", sent_msgs.last().unwrap());
        assert!(
            tail.contains("wire the CLI"),
            "the model must see live state: {tail}"
        );

        // …and the stored history did not keep it.
        assert!(
            !messages
                .iter()
                .any(|m| format!("{m:?}").contains("<runtime-state>")),
            "the block must not persist into history, or it stacks one copy per turn"
        );
    }

    /// An empty plan renders nothing at all — no fence, no tokens, no cache
    /// churn for a block with no content.
    #[tokio::test]
    async fn no_state_block_when_there_is_nothing_to_say() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![turn("done", json!([]))],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("do it")];
        let mut cfg = cfg();
        cfg.todos = Some(Arc::new(tokio::sync::Mutex::new(
            super::super::todo::TodoList::new(),
        )));
        run_assistant_loop(&script, &rt, &cfg, &mut messages, |_| {}).await;

        let sent = seen.lock().unwrap();
        let all = format!("{:?}", sent[0].messages);
        assert!(
            !all.contains("<runtime-state>"),
            "empty plan must render nothing: {all}"
        );
    }

    fn remember_receipt(subject: &str, ok: bool) -> AssistantToolReceipt {
        AssistantToolReceipt {
            tool: "remember".to_string(),
            call_id: None,
            ok,
            params: json!({"subject": subject, "body": ""}),
            via: None,
        }
    }

    /// #814 — the recall-discipline gap the issue is actually about.
    ///
    /// A fact written at turn 3 was invisible at turn 7 unless the model
    /// independently decided to `recall`. Surfacing the subject does not hand it
    /// the content, but it does mean the model no longer has to *remember that
    /// it remembered* — the recall becomes informed rather than speculative.
    #[test]
    fn written_facts_reach_the_state_block_without_being_asked_for() {
        let receipts = [
            remember_receipt("deploy target", true),
            AssistantToolReceipt {
                tool: "read_file".to_string(),
                call_id: None,
                ok: true,
                params: json!({"path": "x"}),
                via: None,
            },
            remember_receipt("user timezone", true),
        ];

        let subjects = recent_fact_subjects(&receipts);
        assert_eq!(subjects, vec!["deploy target", "user timezone"]);

        let block = render_state_block(None, &subjects).expect("facts alone must render a block");
        assert!(block.contains("deploy target"), "{block}");
        assert!(block.contains("user timezone"), "{block}");
        // Subjects only: the bodies stay in memgine, which ranks them.
        assert!(
            block.contains("recall"),
            "must point at the content: {block}"
        );
        assert!(!block.contains(''), "bodies must not be inlined: {block}");
    }

    /// A `remember` the runtime REJECTED wrote nothing. Listing it would tell
    /// the model it knows something it does not — worse than saying nothing,
    /// because it suppresses the retry.
    #[test]
    fn a_failed_remember_is_not_reported_as_known() {
        let receipts = [
            remember_receipt("landed fact", true),
            remember_receipt("rejected fact", false),
        ];
        assert_eq!(recent_fact_subjects(&receipts), vec!["landed fact"]);
    }

    /// A re-remember supersedes the earlier write rather than adding a second
    /// fact, so the subject must move — not duplicate, which would both inflate
    /// the count and spend the cap on one subject.
    #[test]
    fn re_remembering_a_subject_moves_it_instead_of_duplicating() {
        let receipts = [
            remember_receipt("api base url", true),
            remember_receipt("deploy target", true),
            remember_receipt("api base url", true),
        ];
        assert_eq!(
            recent_fact_subjects(&receipts),
            vec!["deploy target", "api base url"]
        );
    }

    /// The block is bounded: a run that remembers 40 things must not turn the
    /// tail into the largest part of the request. The most RECENT survive.
    #[test]
    fn the_fact_list_is_bounded_and_says_what_it_dropped() {
        let subjects: Vec<String> = (0..12).map(|i| format!("fact {i}")).collect();
        let block = render_state_block(None, &subjects).expect("must render");

        assert!(block.contains("fact 11"), "newest must survive: {block}");
        assert!(!block.contains("fact 6"), "oldest must be cut: {block}");
        assert!(
            block.contains("+7 earlier"),
            "a silent cut reads as 'that's all there is': {block}"
        );
    }

    /// Both sections are independent: either one alone renders, and neither
    /// renders an empty fence.
    #[test]
    fn sections_render_independently_and_nothing_renders_nothing() {
        assert!(render_state_block(None, &[]).is_none());
        assert!(render_state_block(Some("todo: 0/1 done".into()), &[]).is_some());
        assert!(render_state_block(None, &["a fact".to_string()]).is_some());

        let both = render_state_block(Some("todo: 0/1 done".into()), &["a fact".to_string()])
            .expect("must render");
        assert!(both.contains("todo:"), "{both}");
        assert!(both.contains("a fact"), "{both}");
    }

    /// Parslee-ai/car#815 — compaction must not be invisible.
    ///
    /// Turns used to simply cease to exist between one request and the next,
    /// so a run that degraded afterwards looked, in the trace, exactly like a
    /// model that got worse. "The model forgot" and "the harness deleted it"
    /// are different bugs with different fixes.
    #[test]
    fn compaction_leaves_a_marker_the_model_can_see() {
        let big = "x".repeat(20_000);
        let mut m = vec![sys("system"), usr("THE ORIGINAL TASK")];
        for i in 0..12 {
            m.push(asst_call(&format!("c{i}")));
            m.push(tool_res(&format!("c{i}"), &big));
        }
        compact_history_to_window(&mut m, 20_000);

        let notice = m
            .iter()
            .find_map(|msg| match msg {
                Message::System { content } if content.starts_with(COMPACTION_NOTICE_PREFIX) => {
                    Some(content.clone())
                }
                _ => None,
            })
            .expect("a compaction notice must be left in place of the removed turns");

        assert!(
            notice.contains("earlier turns removed"),
            "the notice must say turns were removed: {notice}"
        );
        assert!(
            notice.contains("events_query"),
            "a notice that says something is missing without saying how to look \
             only turns a silent failure into a visible dead end: {notice}"
        );
        // It sits at the head, where the removal happened — not appended at the
        // end, where it would read as a fact about the latest turn.
        assert!(
            matches!(&m[2], Message::System { content } if content.starts_with(COMPACTION_NOTICE_PREFIX)),
            "notice belongs where the turns were, after system + task"
        );
    }

    /// A second compaction must UPDATE the notice, not erase it or stack a
    /// second one. Erasing it would restore the exact silent-deletion property
    /// the marker exists to prevent — and the erasure would happen precisely in
    /// the long runs that need the signal most.
    #[test]
    fn repeated_compaction_accumulates_into_one_notice() {
        let big = "x".repeat(20_000);
        let mut m = vec![sys("system"), usr("THE ORIGINAL TASK")];
        for i in 0..12 {
            m.push(asst_call(&format!("c{i}")));
            m.push(tool_res(&format!("c{i}"), &big));
        }
        compact_history_to_window(&mut m, 20_000);
        let (first_turns, first_tokens) =
            parse_compaction_notice(&m[2]).expect("first notice parses");

        // Grow the history again and re-compact.
        for i in 12..24 {
            m.push(asst_call(&format!("c{i}")));
            m.push(tool_res(&format!("c{i}"), &big));
        }
        compact_history_to_window(&mut m, 20_000);

        let notices: Vec<&String> = m
            .iter()
            .filter_map(|msg| match msg {
                Message::System { content } if content.starts_with(COMPACTION_NOTICE_PREFIX) => {
                    Some(content)
                }
                _ => None,
            })
            .collect();
        assert_eq!(
            notices.len(),
            1,
            "exactly one notice, not a stack: {notices:?}"
        );

        let (turns, tokens) = parse_compaction_notice(&m[2]).expect("notice still parses");
        assert!(
            turns > first_turns && tokens > first_tokens,
            "totals must accumulate across compactions ({first_turns}/{first_tokens} \
             -> {turns}/{tokens})"
        );
    }

    /// The marker round-trips through its own text. If this drifts, repeated
    /// compaction silently resets the running totals to the latest pass.
    #[test]
    fn compaction_notice_round_trips() {
        let rendered = format_compaction_notice(12, 34_000);
        let parsed = parse_compaction_notice(&Message::System { content: rendered });
        assert_eq!(parsed, Some((12, 34_000)));
        // Anything else is not a notice.
        assert_eq!(
            parse_compaction_notice(&sys("ordinary system prompt")),
            None
        );
        assert_eq!(parse_compaction_notice(&usr("a user turn")), None);
    }

    #[test]
    fn compaction_keeps_responses_item_with_its_assistant_turn() {
        let big = "x".repeat(20_000);
        let mut messages = vec![sys("system"), usr("THE ORIGINAL TASK")];
        for i in 0..12 {
            messages.push(provider_item(&format!("rs_{i}"), &big));
            messages.push(asst_call(&format!("c{i}")));
            messages.push(tool_res(&format!("c{i}"), "ok"));
        }

        compact_history_to_window(&mut messages, 20_000);

        for (index, message) in messages.iter().enumerate() {
            if matches!(message, Message::ProviderOutputItems { .. }) {
                assert!(
                    matches!(messages.get(index + 1), Some(Message::Assistant { .. })),
                    "provider continuity item was orphaned from its assistant"
                );
            }
        }
        assert!(
            no_orphan_tool_results(&messages),
            "compacted history contains an orphan tool result"
        );
    }

    /// End-to-end wiring: the real assistant loop, driven by a generator with a
    /// small window that emits a large assistant message each turn, must bound
    /// the running history — proving the loop calls the compactor with the
    /// model's window every turn (the fix that eliminates the `available_tokens=0`
    /// overflow). Deterministic — no live model.
    #[tokio::test]
    async fn loop_compacts_history_to_window() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;

        // Window 4000 → compaction budget 3000 tokens. Each turn emits ~2000
        // tokens of assistant text + a tiny tool call, so the raw history would
        // blow past the window within a few turns.
        struct WindowedBig {
            cursor: AtomicUsize,
        }
        #[async_trait]
        impl TurnGenerator for WindowedBig {
            async fn generate(&self, _req: GenerateRequest) -> Result<InferenceResult, String> {
                let i = self.cursor.fetch_add(1, Ordering::SeqCst);
                if i < 6 {
                    // Distinct args each turn so this exercises compaction only,
                    // not the (separate) no-progress repeat guard.
                    Ok(turn(
                        &"x".repeat(8000),
                        json!([{ "id": format!("c{i}"), "name": "calculate",
                                 "arguments": { "expression": format!("1+{i}") } }]),
                    ))
                } else {
                    Ok(turn("done", json!([])))
                }
            }
            fn context_window(&self, _model: &str) -> usize {
                4000
            }
        }

        let generator = WindowedBig {
            cursor: AtomicUsize::new(0),
        };
        let mut messages = vec![
            Message::System {
                content: "system".into(),
            },
            Message::User {
                content: "THE TASK".into(),
            },
        ];
        let mut c = cfg();
        c.max_turns = 8;

        let out = run_assistant_loop(&generator, &rt, &c, &mut messages, |_e| {}).await;

        assert_eq!(out.status, "success");
        // Uncompacted this run would leave ~14 messages; compaction keeps the
        // pinned head + a recent tail, so it is materially bounded.
        assert!(
            messages.len() <= 11,
            "history bounded by compaction, got {} messages",
            messages.len()
        );
        assert!(
            matches!(&messages[0], Message::System { .. }),
            "system stays pinned"
        );
        assert!(
            matches!(&messages[1], Message::User { content } if content == "THE TASK"),
            "original task stays pinned"
        );
        assert!(
            no_orphan_tool_results(&messages),
            "no orphaned tool results in the live loop"
        );
    }

    /// The no-progress guard: a model stuck re-reading the same file (the
    /// observed gpt-5.x pathology — 49 reads, 0 writes) must be halted as
    /// `stalled`, well before the turn cap, instead of burning the whole budget.
    #[tokio::test]
    async fn loop_halts_a_no_progress_repeat_loop() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;

        struct Stuck;
        #[async_trait]
        impl TurnGenerator for Stuck {
            async fn generate(&self, _req: GenerateRequest) -> Result<InferenceResult, String> {
                // The identical read-only action, forever.
                Ok(turn(
                    "re-reading",
                    json!([{ "name": "read_file", "arguments": { "path": "app.js" } }]),
                ))
            }
        }

        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "task".into(),
            },
        ];
        let mut c = cfg();
        c.max_turns = 40; // high on purpose: the guard, not the cap, must stop it

        let out = run_assistant_loop(&Stuck, &rt, &c, &mut messages, |_e| {}).await;

        assert_eq!(
            out.status, "stalled",
            "a no-progress loop must halt as `stalled`, not run to max_turns"
        );
        assert!(
            out.turns < 40,
            "must stop well before the turn cap, got {} turns",
            out.turns
        );
    }

    /// A read + read-only-shell cycle (re-read a file, `wc` it, re-read, `wc`…)
    /// makes no state change. Because `shell` is not a state-mutating tool, it no
    /// longer resets the guard, so this cycle is caught — the exact hole that let
    /// the observed run interleave `shell(wc)` between reads and loop forever.
    #[tokio::test]
    async fn loop_halts_a_read_plus_readonly_shell_cycle() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;

        struct Cycle {
            cursor: AtomicUsize,
        }
        #[async_trait]
        impl TurnGenerator for Cycle {
            async fn generate(&self, _req: GenerateRequest) -> Result<InferenceResult, String> {
                let i = self.cursor.fetch_add(1, Ordering::SeqCst);
                if i.is_multiple_of(2) {
                    Ok(turn(
                        "read",
                        json!([{ "name": "read_file", "arguments": { "path": "app.js" } }]),
                    ))
                } else {
                    Ok(turn(
                        "probe",
                        json!([{ "name": "shell", "arguments": { "command": "wc -l app.js" } }]),
                    ))
                }
            }
        }

        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "task".into(),
            },
        ];
        let mut c = cfg();
        c.max_turns = 40;

        let out = run_assistant_loop(
            &Cycle {
                cursor: AtomicUsize::new(0),
            },
            &rt,
            &c,
            &mut messages,
            |_e| {},
        )
        .await;

        assert_eq!(
            out.status, "stalled",
            "a read/read-only-shell cycle with no file change must halt"
        );
        assert!(out.turns < 40, "stopped before the cap, got {}", out.turns);
    }

    /// A repeatedly-*failing* mutation is not progress. The model asks for the
    /// identical `write_file` every turn but it's rejected (escapes the root),
    /// so nothing ever changes. The guard must key on mutation SUCCESS, not the
    /// mere request, and halt — the "40 failed writes" twin of the read loop.
    #[tokio::test]
    async fn loop_halts_a_repeatedly_failing_mutation() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;

        struct FailWrite;
        #[async_trait]
        impl TurnGenerator for FailWrite {
            async fn generate(&self, _req: GenerateRequest) -> Result<InferenceResult, String> {
                // Escapes the clamped root every time → the executor rejects it,
                // so it is a mutating *request* that never *succeeds*.
                Ok(turn(
                    "writing",
                    json!([{ "name": "write_file",
                             "arguments": { "path": "../../etc/evil", "content": "x" } }]),
                ))
            }
        }

        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "task".into(),
            },
        ];
        let mut c = cfg();
        c.max_turns = 40;

        let out = run_assistant_loop(&FailWrite, &rt, &c, &mut messages, |_e| {}).await;

        assert_eq!(
            out.status, "stalled",
            "a repeatedly-failing mutation makes no progress and must halt (not reset the guard)"
        );
        assert!(out.turns < 40, "stopped before the cap, got {}", out.turns);
    }

    /// A scripted turn that reports token usage, the way every real provider
    /// does. `turn()` deliberately reports none, so the two together cover the
    /// measured and unmeasured halves of the `usage: Option` contract.
    fn turn_with_usage(
        text: &str,
        tool_calls: Value,
        prompt_tokens: u64,
        completion_tokens: u64,
    ) -> InferenceResult {
        serde_json::from_value(json!({
            "text": text,
            "tool_calls": tool_calls,
            "trace_id": "t",
            "model_used": "scripted",
            "latency_ms": 25,
            "usage": {
                "prompt_tokens": prompt_tokens,
                "completion_tokens": completion_tokens,
                "total_tokens": prompt_tokens + completion_tokens,
                "context_window": 8192,
            },
        }))
        .expect("scripted InferenceResult shape with usage")
    }

    /// GAP 1, the load-bearing assertion: a completed assistant-loop run must
    /// write `InferenceMetered` events carrying real token counts, and
    /// `compute_harness_metrics` over that trajectory must report
    /// `model_calls > 0` and `total_tokens > 0`.
    ///
    /// Before this, the loop dropped `InferenceResult::usage` entirely, so a
    /// `HarnessMetrics` computed from an assistant journal was structurally
    /// blank — zero tokens, zero calls — and the Evolution Agent's regression
    /// gate could never fire its token-improvement branch. Offline: the
    /// generator is scripted, so this runs in CI with no API key.
    #[tokio::test]
    async fn assistant_loop_meters_every_model_call_with_real_tokens() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        // Turn 1: a real tool call. Turn 2: finish with prose.
        let script = Script {
            turns: vec![
                turn_with_usage(
                    "computing",
                    json!([{ "id": "c1", "name": "calculate", "arguments": { "expression": "6*7" } }]),
                    120,
                    30,
                ),
                turn_with_usage("The answer is 42.", json!([]), 200, 15),
            ],
            cursor: AtomicUsize::new(0),
        };
        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "what is 6*7?".into(),
            },
        ];
        let outcome = run_assistant_loop(&script, &rt, &cfg(), &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");

        let events = rt.log.lock().await.events().to_vec();
        let metered: Vec<_> = events
            .iter()
            .filter(|e| e.kind == car_eventlog::EventKind::InferenceMetered)
            .collect();
        assert_eq!(
            metered.len(),
            2,
            "one InferenceMetered per model call; the loop made 2 generate() calls"
        );
        for ev in &metered {
            assert_eq!(
                ev.data.get("model_id").and_then(|v| v.as_str()),
                Some("scripted"),
                "each metered call must name the model that produced it"
            );
            assert_eq!(
                ev.data.get("usage_measured").and_then(|v| v.as_bool()),
                Some(true)
            );
        }

        let m = car_eventlog::harness_metrics::compute_harness_metrics(&events);
        assert_eq!(
            m.trajectory_efficiency.model_calls, 2,
            "harness metrics must see the model calls"
        );
        assert_eq!(
            m.trajectory_efficiency.total_tokens,
            120 + 30 + 200 + 15,
            "tokens must be the sum of the scripted usage, not an estimate"
        );
        assert!(m.trajectory_efficiency.wall_clock_ms > 0.0);

        // The gate at car_memgine::harness_evolution also needs the ACTION legs
        // (`actions_succeeded > 0` gates `candidate_did_work`, `success_rate` is
        // the only regression guard). The assistant loop routes tool calls
        // through `runtime.execute`, which meters them — assert that here so a
        // regression in either leg surfaces as a failure of THIS test rather
        // than as silently empty candidate metrics at promotion time.
        assert!(
            m.trajectory_efficiency.actions_succeeded > 0,
            "the executed `calculate` call must be recorded as a succeeded action; \
             got {m:?}"
        );
        assert!(
            m.trajectory_efficiency.success_rate.is_some(),
            "success_rate is the evolution gate's only regression guard and must be measured"
        );
    }

    /// The `usage: Option` contract must survive into the journal: a provider
    /// that reports no usage still yields a counted model call, but must NOT
    /// fabricate zero tokens. `model_calls` and `total_tokens` therefore move
    /// independently — which is why the A/B reads both.
    #[tokio::test]
    async fn unmeasured_usage_still_counts_the_call_but_fabricates_no_tokens() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        // `turn()` reports no usage at all.
        let script = Script {
            turns: vec![turn("done, no usage reported", json!([]))],
            cursor: AtomicUsize::new(0),
        };
        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "hi".into(),
            },
        ];
        let outcome = run_assistant_loop(&script, &rt, &cfg(), &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");

        let events = rt.log.lock().await.events().to_vec();
        let metered: Vec<_> = events
            .iter()
            .filter(|e| e.kind == car_eventlog::EventKind::InferenceMetered)
            .collect();
        assert_eq!(metered.len(), 1, "the call happened, so it is counted");
        assert_eq!(
            metered[0]
                .data
                .get("usage_measured")
                .and_then(|v| v.as_bool()),
            Some(false),
            "the journal must say the count was unavailable, not imply a zero"
        );

        let m = car_eventlog::harness_metrics::compute_harness_metrics(&events);
        assert_eq!(m.trajectory_efficiency.model_calls, 1);
        assert_eq!(
            m.trajectory_efficiency.total_tokens, 0,
            "no usage reported means no tokens attributed — absent, not invented"
        );
    }

    fn turn(text: &str, tool_calls: Value) -> InferenceResult {
        serde_json::from_value(json!({
            "text": text,
            "tool_calls": tool_calls,
            "trace_id": "t",
            "model_used": "scripted",
            "latency_ms": 0,
        }))
        .expect("scripted InferenceResult shape")
    }

    struct Script {
        turns: Vec<InferenceResult>,
        cursor: AtomicUsize,
    }

    #[async_trait]
    impl TurnGenerator for Script {
        async fn generate(&self, _req: GenerateRequest) -> Result<InferenceResult, String> {
            let i = self.cursor.fetch_add(1, Ordering::SeqCst);
            self.turns.get(i).cloned().ok_or("script exhausted".into())
        }
    }

    struct CapturingGenerator {
        seen: Arc<StdMutex<Vec<GenerateRequest>>>,
    }

    #[async_trait]
    impl TurnGenerator for CapturingGenerator {
        async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
            self.seen.lock().unwrap().push(req);
            Ok(turn("done", json!([])))
        }
    }

    struct CapturingScript {
        turns: Vec<InferenceResult>,
        cursor: AtomicUsize,
        seen: Arc<StdMutex<Vec<GenerateRequest>>>,
    }

    #[async_trait]
    impl TurnGenerator for CapturingScript {
        async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
            self.seen.lock().unwrap().push(req);
            let i = self.cursor.fetch_add(1, Ordering::SeqCst);
            self.turns.get(i).cloned().ok_or("script exhausted".into())
        }
    }

    /// Build a real Runtime whose executor is a GeneralExecutor over a local
    /// substrate rooted at `dir` — the same wiring `build_assistant_runtime`
    /// produces, minus the network delegate.
    async fn runtime_for(dir: &std::path::Path) -> Runtime {
        let substrate: Arc<dyn Substrate> = Arc::new(LocalSubstrate::new());
        let exec: Arc<dyn ToolExecutor> =
            Arc::new(GeneralExecutor::new(substrate.clone(), dir, true));
        let engine = Arc::new(InferenceEngine::new(Default::default()));
        let rt = Runtime::new()
            .with_inference(engine)
            .with_executor(exec)
            .with_substrate(substrate);
        rt.register_agent_basics().await;
        rt.register_tool_entry(
            car_engine::ToolEntry::new(car_ir::builtins::shell()).with_side_effects(true),
        )
        .await;
        rt
    }

    fn cfg() -> AssistantConfig {
        AssistantConfig {
            model: Some("scripted".into()),
            strict_model: false,
            max_turns: 6,
            tools: GeneralExecutor::tool_defs(),
            gated_tools: Vec::new(),
            approval_policy: None,
            proactive_memory: None,
            // None => built-in labels, which cover the network-reaching
            // commodity tools. A caller that loads .car/tool-labels.json
            // should pass the merged map (car#723).
            tool_labels: None,
            todos: None,
            value_store_previews: false,
            response_format: None,
            context_window_override: None,
            refuse_unadvertised_tools: false,
            response_format_validator: None,
            delegate_budget: None,
        }
    }

    /// What CAR does out of the box is a measured decision, not a literal that
    /// drifts (#813).
    ///
    /// The default used to be a bare `false` written at every production
    /// construction site, so "is it on?" could only be answered by grepping and
    /// hoping the sites agreed. It is now one constant, and this pins it to the
    /// value the A/B in [`VALUE_STORE_PREVIEWS_DEFAULT`]'s docs chose. Flipping
    /// it on without a new measurement fails here, which is the point: the
    /// numbers, not a preference, decide it.
    #[test]
    fn the_shipped_default_is_the_measured_one() {
        assert!(
            !VALUE_STORE_PREVIEWS_DEFAULT,
            "retained previews stay OFF because the 3-replicate car-bench-harness \
             A/B did not meet #813's fewer-calls criterion. Changing this needs a \
             new measurement, not an edit."
        );
    }

    /// Pinning the constant's *value* is not enough — production has to read it
    /// (#813).
    ///
    /// [`the_shipped_default_is_the_measured_one`] fails if the constant flips,
    /// but it says nothing about who consults it. A change that hard-coded
    /// either arm at a construction site would fork the shared default with
    /// every other test still green. So this scans the crate's own production
    /// source for both literals.
    ///
    /// Everything from the first `#[cfg(test)]` onward is excluded: test
    /// scaffolding is entitled to pin either arm explicitly, and one fixture in
    /// this very module does.
    #[test]
    fn no_production_call_site_hard_codes_the_preview_default() {
        let crate_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        for rel in [
            "src/assistant/agent_loop.rs",
            "src/assistant/chat.rs",
            "src/coder/discuss.rs",
            "src/mcp_assistant.rs",
        ] {
            let src = std::fs::read_to_string(crate_dir.join(rel))
                .unwrap_or_else(|e| panic!("reading {rel}: {e}"));
            let production = match src.find("\n#[cfg(test)]") {
                Some(cut) => &src[..cut],
                None => src.as_str(),
            };
            for literal in ["value_store_previews: false", "value_store_previews: true"] {
                assert!(
                    !production.contains(literal),
                    "{rel} hard-codes the preview arm in production code. The \
                     shipped default is VALUE_STORE_PREVIEWS_DEFAULT, chosen from a \
                     measured A/B; a literal here forks it silently."
                );
            }
        }
    }

    /// The toggle must be genuinely inert when off (#813).
    ///
    /// This mattered before the A/B because a default with *any* observable
    /// effect would have spent the measurement's credibility before it was
    /// taken. It matters just as much after: the off arm is what the measured
    /// baseline in [`VALUE_STORE_PREVIEWS_DEFAULT`] was taken against, and a
    /// caller that opts back out is entitled to the old behavior exactly. So
    /// this still asserts the off path produces the destructive-truncation
    /// observation byte for byte.
    #[tokio::test]
    async fn the_off_arm_still_truncates_exactly_as_before() {
        assert!(
            !cfg().value_store_previews,
            "this fixture is the OFF arm — it pins the pre-#813 observation path, \
             not the shipped default (see VALUE_STORE_PREVIEWS_DEFAULT)"
        );

        let dir = tempfile::tempdir().unwrap();
        let big = "x".repeat(OBSERVATION_CAP + 40_000);
        std::fs::write(dir.path().join("big.txt"), &big).unwrap();
        let rt = runtime_for(dir.path()).await;

        let script = Script {
            turns: vec![
                turn(
                    "reading",
                    json!([{ "id": "c1", "name": "read_file", "arguments": { "path": "./big.txt" } }]),
                ),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        };
        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "read it".into(),
            },
        ];
        run_assistant_loop(&script, &rt, &cfg(), &mut messages, |_| {}).await;

        let observation = messages
            .iter()
            .find_map(|m| match m {
                Message::ToolResult { content, .. } => Some(content.clone()),
                _ => None,
            })
            .expect("a tool observation");
        assert!(
            observation.contains("…[truncated:"),
            "off path must still truncate destructively: {}",
            &observation[observation.len().saturating_sub(200)..]
        );
        assert!(
            !observation.contains("[full value retained"),
            "no handle may leak into the default transcript"
        );
    }

    /// The property #813 is named for: with previews on, the data that used to
    /// be destroyed is still reachable *mid-run*.
    ///
    /// Proven end-to-end rather than by inspecting the store: turn 1 reads a
    /// file far larger than the cap, turn 2 passes the handle to `write_file`,
    /// and the bytes that never appeared in the transcript come back out on
    /// disk byte-identical. Under the old `cap()` this is impossible — rows
    /// 3-100, so to speak, were gone.
    #[tokio::test]
    async fn a_retained_value_survives_the_transcript_and_can_be_used_by_a_later_tool() {
        let dir = tempfile::tempdir().unwrap();
        // Distinct head and tail so a truncated copy could not pass.
        let big = format!(
            "HEAD-MARKER\n{}\nTAIL-MARKER",
            "z".repeat(OBSERVATION_CAP + 40_000)
        );
        std::fs::write(dir.path().join("big.txt"), &big).unwrap();
        let rt = runtime_for(dir.path()).await;

        let script = Script {
            turns: vec![
                turn(
                    "reading",
                    json!([{ "id": "c1", "name": "read_file", "arguments": { "path": "./big.txt" } }]),
                ),
                turn(
                    "copying",
                    json!([{ "id": "c2", "name": "write_file",
                             "arguments": { "path": "./copy.txt", "content": "$r1.content" } }]),
                ),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        };
        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "copy it".into(),
            },
        ];
        let mut cfg = cfg();
        cfg.value_store_previews = true;
        cfg.max_turns = 8;
        run_assistant_loop(&script, &rt, &cfg, &mut messages, |_| {}).await;

        let observation = messages
            .iter()
            .find_map(|m| match m {
                Message::ToolResult { content, .. } => Some(content.clone()),
                _ => None,
            })
            .expect("a tool observation");

        // The transcript carries shape, not the payload.
        assert!(
            observation.contains("content: text(len="),
            "the large field must announce its size and shape: {observation}"
        );
        assert!(
            observation.contains("[full value retained"),
            "the model must be told the value is reachable: {observation}"
        );
        assert!(
            observation.len() < 2_000,
            "preview must be bounded, got {} bytes",
            observation.len()
        );
        assert!(
            !observation.contains(&"z".repeat(1_000)),
            "the payload itself must not be in the transcript"
        );

        // …and the elided bytes came back through the handle.
        //
        // Compared against read_file's OWN output rather than the file on disk:
        // that tool returns line-numbered content (`     1\tHEAD-MARKER`), so a
        // byte-identical round-trip against the source was never the property.
        // What matters is that everything past the truncation point survived.
        let copied = std::fs::read_to_string(dir.path().join("copy.txt"))
            .expect("the second tool must have run with the resolved value");
        assert!(
            copied.len() > OBSERVATION_CAP,
            "only {} bytes came back; the value was not retained in full",
            copied.len()
        );
        assert!(
            copied.contains("HEAD-MARKER"),
            "the head — the only part destructive truncation ever kept — is missing"
        );
        assert!(
            copied.contains("TAIL-MARKER"),
            "the TAIL is the part cap() always destroyed; recovering it is the \
             whole point of #813"
        );
        // And it never travelled through the transcript to get there.
        assert!(
            !observation.contains("TAIL-MARKER"),
            "the tail must have come from the store, not the context: {observation}"
        );
    }

    #[tokio::test]
    async fn loop_runs_a_tool_then_finishes() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        // Turn 1: call calculate. Turn 2: finish with prose (no tool calls).
        let script = Script {
            turns: vec![
                turn(
                    "computing",
                    json!([{ "id": "c1", "name": "calculate", "arguments": { "expression": "6*7" } }]),
                ),
                turn("The answer is 42.", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        };
        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "what is 6*7?".into(),
            },
        ];
        let mut events = Vec::new();
        let outcome =
            run_assistant_loop(&script, &rt, &cfg(), &mut messages, |e| events.push(e)).await;

        assert_eq!(outcome.status, "success");
        assert_eq!(outcome.summary, "The answer is 42.");
        assert!(outcome.tools_called.contains(&"calculate".to_string()));
        assert!(events
            .iter()
            .any(|e| matches!(e, AssistantEvent::ToolResult { name, ok: true, .. } if name == "calculate")));
    }

    #[tokio::test]
    async fn loop_replays_managed_responses_continuity_on_second_turn() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let reasoning = json!({
            "type": "reasoning",
            "id": "rs_agent",
            "status": "completed",
            "summary": [{"type": "summary_text", "text": "safe"}],
            "encrypted_content": "opaque-agent",
        });
        let mut first = turn(
            "checking",
            json!([{ "id": "c1", "name": "calculate", "arguments": { "expression": "6*7" } }]),
        );
        first.provider_output_items = vec![reasoning.clone()];
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![first, turn("done", json!([]))],
            cursor: AtomicUsize::new(0),
            seen: seen.clone(),
        };
        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "calculate".into(),
            },
        ];

        let outcome = run_assistant_loop(&script, &rt, &cfg(), &mut messages, |_e| {}).await;

        assert_eq!(outcome.status, "success");
        assert!(
            !outcome.summary.contains("opaque-agent"),
            "opaque continuity must never become user-visible text"
        );
        let seen = seen.lock().unwrap();
        let second = seen[1].messages.as_ref().expect("second-turn history");
        assert!(matches!(
            &second[2],
            Message::ProviderOutputItems { protocol, items }
                if protocol == car_inference::protocol::OPENAI_RESPONSES_PROTOCOL
                    && items == &vec![reasoning]
        ));
        assert!(matches!(
            &second[3],
            Message::Assistant { content, .. } if content == "checking"
        ));
        assert!(matches!(&second[4], Message::ToolResult { .. }));
    }

    #[tokio::test]
    async fn loop_injects_proactive_memory_before_generation() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let memory = Arc::new(crate::assistant::memory::MemoryTools::open(
            dir.path().join("assistant-memory.json"),
        ));
        memory
            .execute(
                "remember",
                &json!({
                    "subject": "phoenix task requirement",
                    "body": "Requirement: for phoenix task work, run pytest before finishing."
                }),
            )
            .await
            .unwrap();
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let generator = CapturingGenerator { seen: seen.clone() };
        let mut cfg = cfg();
        cfg.proactive_memory = Some(memory);
        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "finish the phoenix task".into(),
            },
        ];

        let outcome = run_assistant_loop(&generator, &rt, &cfg, &mut messages, |_| {}).await;

        assert_eq!(outcome.status, "success");
        // Scope the std MutexGuard so it drops before the `.await` below
        // (clippy::await_holding_lock).
        {
            let captured = seen.lock().unwrap();
            let context = captured[0].context.as_deref().unwrap_or("");
            assert!(
                context.contains("## Proactive Memory"),
                "request context should carry proactive memory: {context}"
            );
            assert!(
                context.contains("run pytest before finishing"),
                "selected memory should be injected: {context}"
            );
        }
        let log = rt.log.lock().await;
        assert!(log
            .events()
            .iter()
            .any(|e| e.kind == car_eventlog::EventKind::ProactiveMemoryMaintained));
        assert!(log.events().iter().any(|e| {
            e.kind == car_eventlog::EventKind::ProactiveMemoryIntervention
                && e.data.get("decision") == Some(&json!("inject"))
        }));
    }

    #[tokio::test]
    async fn loop_journals_turn_completed_at_empty_tool_calls_terminal() {
        // The default (ungrounded) path's completion decision must be a durable,
        // queryable event. Drives the loop to the empty-tool-calls terminal and
        // asserts the journaled TurnCompleted — this would FAIL if the emit at
        // agent_loop.rs were removed (the flagship path previously had no such
        // driven-loop assertion, unlike the coder path).
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let script = Script {
            turns: vec![
                turn(
                    "computing",
                    json!([{ "id": "c1", "name": "calculate", "arguments": { "expression": "6*7" } }]),
                ),
                turn("The answer is 42.", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        };
        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "what is 6*7?".into(),
            },
        ];
        let mut events = Vec::new();
        let outcome =
            run_assistant_loop(&script, &rt, &cfg(), &mut messages, |e| events.push(e)).await;
        assert_eq!(outcome.status, "success");
        // Model provenance is threaded out to the outcome (leftover A plumbing).
        assert_eq!(outcome.model_used, "scripted");

        let log = rt.log.lock().await;
        let tc = log
            .events()
            .iter()
            .find(|e| e.kind == car_eventlog::EventKind::TurnCompleted)
            .expect("empty-tool-calls terminal must journal a TurnCompleted");
        assert_eq!(
            tc.data.get("decision"),
            Some(&serde_json::json!("empty_tool_calls"))
        );
        assert_eq!(tc.data.get("turns"), Some(&serde_json::json!(2)));
        assert_eq!(
            tc.data.get("model_id"),
            Some(&serde_json::json!("scripted"))
        );
        // "scripted" has no provider prefix in the allow-list → unknown tier.
        assert_eq!(
            tc.data.get("model_tier"),
            Some(&serde_json::json!("unknown"))
        );
    }

    #[tokio::test]
    async fn loop_journals_turn_completed_at_max_turns_terminal() {
        // The model never finishes — it calls a tool every turn until the cap is
        // hit. The max_turns terminal must journal a TurnCompleted so a run that
        // "stopped after N turns without finishing" is distinguishable from a
        // clean finish in the audit trail.
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let tool_turn = || {
            turn(
                "still going",
                json!([{ "id": "c", "name": "calculate", "arguments": { "expression": "1+1" } }]),
            )
        };
        let script = Script {
            turns: (0..10).map(|_| tool_turn()).collect(),
            cursor: AtomicUsize::new(0),
        };
        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "loop".into(),
            },
        ];
        // Cap below the stall-break threshold so max_turns is the terminal.
        let cfg = AssistantConfig {
            max_turns: 3,
            ..cfg()
        };
        let mut events = Vec::new();
        let outcome =
            run_assistant_loop(&script, &rt, &cfg, &mut messages, |e| events.push(e)).await;
        assert_eq!(outcome.status, "max_turns");

        let log = rt.log.lock().await;
        let tc = log
            .events()
            .iter()
            .find(|e| {
                e.kind == car_eventlog::EventKind::TurnCompleted
                    && e.data.get("decision") == Some(&serde_json::json!("max_turns"))
            })
            .expect("max_turns terminal must journal a TurnCompleted");
        assert_eq!(tc.data.get("turns"), Some(&serde_json::json!(3)));
    }

    #[test]
    fn summary_claim_grounding_requires_matching_receipts() {
        let ungrounded = ungrounded_summary_claims("I ran the tests and they passed.", &[]);
        assert_eq!(ungrounded, vec!["tests were run/passed"]);

        let grounded = ungrounded_summary_claims(
            "I ran the tests and they passed.",
            &[AssistantToolReceipt {
                tool: "shell".into(),
                call_id: Some("s1".into()),
                ok: true,
                params: json!({ "command": "cargo test -q" }),
                via: None,
            }],
        );
        assert!(grounded.is_empty(), "{grounded:?}");

        let failed = ungrounded_summary_claims(
            "I ran the tests and they passed.",
            &[AssistantToolReceipt {
                tool: "shell".into(),
                call_id: Some("s1".into()),
                ok: false,
                params: json!({ "command": "cargo test -q" }),
                via: None,
            }],
        );
        assert_eq!(failed, vec!["tests were run/passed"]);
    }

    #[test]
    fn summary_claim_grounding_catches_verification_and_check_claims() {
        assert_eq!(
            ungrounded_summary_claims("Verified with cargo test.", &[]),
            vec!["tests were run/passed"]
        );
        assert_eq!(
            ungrounded_summary_claims("cargo check passed.", &[]),
            vec!["build succeeded", "checks were run/passed"]
        );
        assert_eq!(
            ungrounded_summary_claims("All checks are green.", &[]),
            vec!["checks were run/passed"]
        );

        let cargo_check = [AssistantToolReceipt {
            tool: "shell".into(),
            call_id: Some("s1".into()),
            ok: true,
            params: json!({ "command": "cargo check -p car-server-core" }),
            via: None,
        }];
        assert!(
            ungrounded_summary_claims("cargo check passed.", &cargo_check).is_empty(),
            "cargo check receipt should ground both build and check claims"
        );

        let diff_check = [AssistantToolReceipt {
            tool: "shell".into(),
            call_id: Some("s2".into()),
            ok: true,
            params: json!({ "command": "git diff --check" }),
            via: None,
        }];
        assert!(
            ungrounded_summary_claims("All checks are green.", &diff_check).is_empty(),
            "diff-check receipt should ground generic check claims"
        );

        let tests = [AssistantToolReceipt {
            tool: "shell".into(),
            call_id: Some("s3".into()),
            ok: true,
            params: json!({ "command": "npm run test -- --watch=false" }),
            via: None,
        }];
        assert!(
            ungrounded_summary_claims("Verified with npm run test.", &tests).is_empty(),
            "npm run test receipt should ground verification test claims"
        );

        assert_eq!(
            ungrounded_summary_claims("ctest passed.", &[]),
            vec!["tests were run/passed"]
        );

        let ctest = [AssistantToolReceipt {
            tool: "shell".into(),
            call_id: Some("s4".into()),
            ok: true,
            params: json!({ "command": "ctest --test-dir build --output-on-failure" }),
            via: None,
        }];
        assert!(
            ungrounded_summary_claims("ctest passed.", &ctest).is_empty(),
            "ctest receipt should ground CMake test claims"
        );

        let cmake_build = [AssistantToolReceipt {
            tool: "shell".into(),
            call_id: Some("s5".into()),
            ok: true,
            params: json!({ "command": "cmake -S . -B build && cmake --build build" }),
            via: None,
        }];
        assert!(
            ungrounded_summary_claims("CMake build succeeded.", &cmake_build).is_empty(),
            "cmake --build receipt should ground CMake build claims"
        );

        let pnpm_check = [AssistantToolReceipt {
            tool: "shell".into(),
            call_id: Some("s6".into()),
            ok: true,
            params: json!({ "command": "pnpm check" }),
            via: None,
        }];
        assert!(
            ungrounded_summary_claims("Checks passed.", &pnpm_check).is_empty(),
            "package check receipts should ground generic check claims"
        );
    }

    #[test]
    fn production_investigation_claims_require_matching_live_receipts() {
        let summary = "Repository is clean and HEAD matches origin. Application Insights telemetry showed no recurrence. The production portal page was inspected.";
        assert_eq!(
            ungrounded_summary_claims(summary, &[]),
            vec![
                "repository cleanliness was verified",
                "repository revision/remote relationship was verified",
                "live Application Insights evidence was observed",
                "production browser state was observed",
            ]
        );

        let receipts = vec![
            AssistantToolReceipt {
                tool: "shell".into(),
                call_id: Some("git".into()),
                ok: true,
                params: json!({"command": "git status && git rev-parse HEAD && git rev-parse origin/main"}),
                via: None,
            },
            AssistantToolReceipt {
                tool: "shell".into(),
                call_id: Some("ai".into()),
                ok: true,
                params: json!({"command": "az monitor app-insights query --analytics-query 'exceptions | summarize count()'"}),
                via: None,
            },
            AssistantToolReceipt {
                tool: "browse_observe".into(),
                call_id: Some("browser".into()),
                ok: true,
                params: json!({}),
                via: None,
            },
        ];
        assert!(ungrounded_summary_claims(summary, &receipts).is_empty());

        let cautious = "Source tests assert Information-level logging without an exception object.\nApplication Insights query: not obtained.\nProduction browser state: not obtained.\nCannot determine whether N744JS is outside the subscription or whether deployment 23708 fixed the issue.";
        assert!(
            ungrounded_summary_claims(cautious, &[]).is_empty(),
            "explicitly source-scoped and negated claims must not be rejected"
        );
    }

    #[test]
    fn summary_file_claim_grounding_requires_matching_named_path() {
        let other_edit = [AssistantToolReceipt {
            tool: "edit_file".into(),
            call_id: Some("e1".into()),
            ok: true,
            params: json!({ "path": "src/other.rs" }),
            via: None,
        }];
        assert_eq!(
            ungrounded_summary_claims("Updated file src/lib.rs.", &other_edit),
            vec!["files were created/updated"]
        );

        let matching_edit = [AssistantToolReceipt {
            tool: "edit_file".into(),
            call_id: Some("e2".into()),
            ok: true,
            params: json!({ "path": "./src/lib.rs" }),
            via: None,
        }];
        assert!(
            ungrounded_summary_claims("Updated file src/lib.rs.", &matching_edit).is_empty(),
            "matching edit_file path should ground the specific update claim"
        );

        let shell_touch = [AssistantToolReceipt {
            tool: "shell".into(),
            call_id: Some("s1".into()),
            ok: true,
            params: json!({ "command": "touch src/lib.rs" }),
            via: None,
        }];
        assert!(
            ungrounded_summary_claims("Created file src/lib.rs.", &shell_touch).is_empty(),
            "matching shell command path should ground the specific creation claim"
        );
    }

    #[test]
    fn summary_read_claim_grounding_requires_matching_named_path() {
        let other_read = [AssistantToolReceipt {
            tool: "read_file".into(),
            call_id: Some("r1".into()),
            ok: true,
            params: json!({ "path": "src/other.rs" }),
            via: None,
        }];
        assert_eq!(
            ungrounded_summary_claims("Inspected file src/lib.rs.", &other_read),
            vec!["files were read/inspected"]
        );

        let matching_read = [AssistantToolReceipt {
            tool: "read_file".into(),
            call_id: Some("r2".into()),
            ok: true,
            params: json!({ "path": "src/lib.rs" }),
            via: None,
        }];
        assert!(
            ungrounded_summary_claims("Inspected file src/lib.rs.", &matching_read).is_empty(),
            "matching read_file path should ground the specific inspection claim"
        );

        let generic_update = [AssistantToolReceipt {
            tool: "edit_file".into(),
            call_id: Some("e1".into()),
            ok: true,
            params: json!({ "path": "src/lib.rs" }),
            via: None,
        }];
        assert!(
            ungrounded_summary_claims("Updated files.", &generic_update).is_empty(),
            "generic file claims should keep the existing tool-class grounding"
        );
    }

    /// End-to-end goal loop over REAL ground truth: the model uses the real
    /// `shell` tool to create a file; the deterministic `Command` condition
    /// reads the real filesystem; the loop re-drives until it converges. This
    /// is the behavior `/goal` cannot guarantee — completion is decided by the
    /// runtime, not a transcript read.
    #[tokio::test]
    async fn goal_loop_converges_when_the_command_check_passes() {
        use car_verify::goal::{GoalCondition, GoalGovernor, GoalSpec, GoalStatus};

        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;

        // Iteration 1: prose only (no tool) — no progress, goal not met.
        // Iteration 2: shell-create the file, then finish. File now exists.
        let create = crate::coder::test_cmds::touch("donefile");
        let script = Script {
            turns: vec![
                turn("Let me start.", json!([])),
                turn(
                    "creating it",
                    json!([{ "id": "s1", "name": "shell", "arguments": { "command": create } }]),
                ),
                turn("Done — created donefile.", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        };

        let spec = GoalSpec {
            goal: "create a file named donefile".into(),
            condition: GoalCondition::Command {
                id: "donefile".into(),
                expect_exit: 0,
            },
            governor: GoalGovernor {
                max_turns: Some(5),
                ..Default::default()
            },
        };

        let mut messages = vec![Message::System {
            content: "sys".into(),
        }];
        let never = std::sync::atomic::AtomicBool::new(false);
        let donefile = dir.path().join("donefile");
        let mut events = Vec::new();

        let result = run_assistant_goal_loop(
            &script,
            &rt,
            &cfg(),
            &mut messages,
            &never,
            None,
            &spec,
            |_outcome| {
                // The deterministic check: does the file exist on disk?
                let exists = donefile.exists();
                async move {
                    let mut g = car_engine::GoalGather::default();
                    g.command_exits
                        .insert("donefile".into(), if exists { 0 } else { 1 });
                    g
                }
            },
            |e| events.push(e),
        )
        .await;

        assert_eq!(
            result.run.status,
            GoalStatus::Achieved,
            "{:?}",
            result.run.last_reason
        );
        assert_eq!(
            result.run.iterations, 2,
            "should converge on the 2nd iteration"
        );
        assert!(
            result.run.grounded,
            "a Command-check completion is grounded"
        );
        assert!(donefile.exists(), "the real file must have been created");
        let checks: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                AssistantEvent::GoalEvaluated {
                    iteration,
                    met,
                    grounded,
                    reason,
                } => Some((*iteration, *met, *grounded, reason.as_str())),
                _ => None,
            })
            .collect();
        assert_eq!(checks.len(), 2, "one verifier event per goal iteration");
        assert_eq!(checks[0].0, 1);
        assert!(
            !checks[0].1,
            "first iteration should not meet the command condition"
        );
        assert_eq!(checks[1].0, 2);
        assert!(
            checks[1].1,
            "second iteration should meet the command condition"
        );
        assert!(checks[1].2, "command-backed completion is grounded");

        let log = rt.log.lock().await;
        let goal_events: Vec<_> = log
            .events()
            .iter()
            .filter(|e| e.kind == car_eventlog::EventKind::GoalEvaluated)
            .collect();
        assert_eq!(
            goal_events.len(),
            2,
            "event log should audit each verifier pass"
        );
        assert_eq!(goal_events[0].data.get("iteration"), Some(&json!(1)));
        assert_eq!(goal_events[0].data.get("met"), Some(&json!(false)));
        assert_eq!(
            goal_events[1].data.get("goal"),
            Some(&json!("create a file named donefile"))
        );
        assert_eq!(
            goal_events[1].data.get("condition"),
            Some(&json!({"kind": "command", "id": "donefile", "expect_exit": 0}))
        );
        assert_eq!(goal_events[1].data.get("iteration"), Some(&json!(2)));
        assert_eq!(goal_events[1].data.get("met"), Some(&json!(true)));
        assert_eq!(goal_events[1].data.get("grounded"), Some(&json!(true)));
    }

    /// F9 regression: a deterministic goal check that PASSED must not be
    /// re-opened just because the final prose named an operational claim with no
    /// matching tool receipt. The loop achieves on the first pass, records the
    /// completion as grounded (ground truth verified it), and the prose mismatch
    /// travels only as a non-authoritative note on the reply text.
    #[tokio::test]
    async fn deterministic_pass_not_reopened_by_ungrounded_prose() {
        use car_verify::goal::{GoalCondition, GoalGovernor, GoalSpec, GoalStatus};

        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        // The deterministic command check exits 0, but the model claims "tests
        // passed" with no matching shell receipt this run.
        let script = Script {
            turns: vec![turn("I ran the tests and they passed.", json!([]))],
            cursor: AtomicUsize::new(0),
        };
        let spec = GoalSpec {
            goal: "make tests pass".into(),
            condition: GoalCondition::Command {
                id: "tests".into(),
                expect_exit: 0,
            },
            governor: GoalGovernor {
                max_turns: Some(3),
                ..Default::default()
            },
        };
        let mut messages = vec![Message::System {
            content: "sys".into(),
        }];
        let never = std::sync::atomic::AtomicBool::new(false);
        let mut events = Vec::new();

        let result = run_assistant_goal_loop(
            &script,
            &rt,
            &cfg(),
            &mut messages,
            &never,
            None,
            &spec,
            |_outcome| async move {
                let mut g = car_engine::GoalGather::default();
                g.command_exits.insert("tests".into(), 0);
                g
            },
            |e| events.push(e),
        )
        .await;

        // Achieved on the FIRST pass — the deterministic command check decided
        // completion; the ungrounded prose did not re-drive the loop.
        assert_eq!(
            result.run.status,
            GoalStatus::Achieved,
            "{:?}",
            result.run.last_reason
        );
        assert_eq!(result.run.iterations, 1);
        assert!(result.run.grounded, "command-backed completion is grounded");
        assert_eq!(result.run.evidence.len(), 1);
        assert!(result.run.evidence[0].met && result.run.evidence[0].grounded);
        // The unverified claim is annotated onto the returned reply text.
        assert!(
            result.outcome.summary.contains("[claim check]")
                && result.outcome.summary.contains("tests were run/passed"),
            "summary should carry the claim-check note: {}",
            result.outcome.summary
        );
        // ...but NEVER into the persisted `messages` thread (would leak into
        // later turns' context via chat.rs's thread persistence).
        assert!(
            !serde_json::to_string(&messages)
                .unwrap_or_default()
                .contains("[claim check]"),
            "the claim-check note must not leak into the thread messages"
        );
        // The streamed GoalEvaluated verdict stays grounded=true.
        let streamed: Vec<_> = events
            .iter()
            .filter_map(|e| match e {
                AssistantEvent::GoalEvaluated { grounded, .. } => Some(*grounded),
                _ => None,
            })
            .collect();
        assert_eq!(streamed, vec![true], "streamed verdict stays grounded=true");
        // The durable GoalEvaluated records grounded=true and a CLEAN reason —
        // the prose mismatch is not folded as a false-completion failure signal.
        let log = rt.log.lock().await;
        let goal_events: Vec<_> = log
            .events()
            .iter()
            .filter(|e| e.kind == car_eventlog::EventKind::GoalEvaluated)
            .collect();
        assert_eq!(goal_events.len(), 1);
        assert_eq!(goal_events[0].data.get("met"), Some(&json!(true)));
        assert_eq!(goal_events[0].data.get("grounded"), Some(&json!(true)));
        assert!(
            !goal_events[0]
                .data
                .get("reason")
                .and_then(|r| r.as_str())
                .unwrap_or("")
                .contains("ungrounded assistant summary claim"),
            "durable reason must not record the prose mismatch as a failure"
        );
    }

    /// The fail-closed path is UNCHANGED when the met verdict is NOT a
    /// deterministic pass: a `ModelJudge`-satisfied goal is `grounded=false`, so
    /// an ungrounded summary claim keeps `grounded=false`, `met && grounded`
    /// never holds, and the loop halts on the governor. The Phase-0 miners keep
    /// receiving the ungrounded `GoalEvaluated` signal.
    #[tokio::test]
    async fn ungrounded_claim_without_deterministic_pass_still_fails_closed() {
        use car_verify::goal::{GoalCondition, GoalGovernor, GoalHalt, GoalSpec, GoalStatus};

        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let script = Script {
            turns: vec![turn("I ran the tests and they passed.", json!([]))],
            cursor: AtomicUsize::new(0),
        };
        // Model-judge completion: met is decided by a transcript-only verdict, so
        // the verdict is grounded=false — NOT a deterministic pass.
        let spec = GoalSpec {
            goal: "make tests pass".into(),
            condition: GoalCondition::ModelJudge { id: "judge".into() },
            governor: GoalGovernor {
                max_turns: Some(1),
                ..Default::default()
            },
        };
        let mut messages = vec![Message::System {
            content: "sys".into(),
        }];
        let never = std::sync::atomic::AtomicBool::new(false);

        let result = run_assistant_goal_loop(
            &script,
            &rt,
            &cfg(),
            &mut messages,
            &never,
            None,
            &spec,
            |_outcome| async move {
                let mut g = car_engine::GoalGather::default();
                g.model_verdicts.insert("judge".into(), true);
                g
            },
            |_| {},
        )
        .await;

        assert_eq!(
            result.run.status,
            GoalStatus::Halted {
                halt: GoalHalt::TurnBudget
            }
        );
        assert_eq!(result.run.evidence.len(), 1);
        assert!(result.run.evidence[0].met);
        assert!(
            !result.run.evidence[0].grounded,
            "a model-judge completion with an ungrounded claim stays ungrounded"
        );
        assert!(result
            .run
            .last_reason
            .contains("ungrounded assistant summary claim"));
        // The claim travels in the verdict reason as before — NOT as a reply note
        // (annotation is exclusive to the deterministic-pass path).
        assert!(!result.outcome.summary.contains("[claim check]"));
    }

    /// On a deterministic pass, prose whose operational claim IS backed by a
    /// same-run receipt is left unannotated — the claim-check note only appears
    /// for genuinely unmatched claims.
    #[tokio::test]
    async fn grounded_prose_on_deterministic_pass_unannotated() {
        use car_verify::goal::{GoalCondition, GoalGovernor, GoalSpec, GoalStatus};

        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        // The model actually creates the file via shell, then claims it — the
        // "files were created/updated" claim is grounded by the create receipt
        // (which is why WRITE_TERMS must know the cmd spelling too, not just
        // POSIX `touch`).
        let create = crate::coder::test_cmds::touch("donefile");
        let script = Script {
            turns: vec![
                turn(
                    "creating it",
                    json!([{ "id": "s1", "name": "shell", "arguments": { "command": create } }]),
                ),
                turn("Done — created donefile.", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        };
        let spec = GoalSpec {
            goal: "create a file named donefile".into(),
            condition: GoalCondition::Command {
                id: "donefile".into(),
                expect_exit: 0,
            },
            governor: GoalGovernor {
                max_turns: Some(3),
                ..Default::default()
            },
        };
        let mut messages = vec![Message::System {
            content: "sys".into(),
        }];
        let never = std::sync::atomic::AtomicBool::new(false);
        let donefile = dir.path().join("donefile");

        let result = run_assistant_goal_loop(
            &script,
            &rt,
            &cfg(),
            &mut messages,
            &never,
            None,
            &spec,
            |_outcome| {
                let exists = donefile.exists();
                async move {
                    let mut g = car_engine::GoalGather::default();
                    g.command_exits
                        .insert("donefile".into(), if exists { 0 } else { 1 });
                    g
                }
            },
            |_| {},
        )
        .await;

        assert_eq!(
            result.run.status,
            GoalStatus::Achieved,
            "{:?}",
            result.run.last_reason
        );
        assert_eq!(result.run.iterations, 1);
        assert!(result.run.grounded);
        // No claim-check note: the file-write claim matched the shell receipt.
        assert_eq!(result.outcome.summary, "Done — created donefile.");
        assert!(!result.outcome.summary.contains("[claim check]"));
    }

    /// A goal that can never be met halts on the governor's turn budget — a
    /// hard bound, not `/goal`'s soft "or stop after N turns" prose.
    #[tokio::test]
    async fn goal_loop_halts_on_turn_budget() {
        use car_verify::goal::{GoalCondition, GoalGovernor, GoalHalt, GoalSpec, GoalStatus};

        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;

        // The model always just finishes with prose; the file is never created.
        struct Idle;
        #[async_trait]
        impl TurnGenerator for Idle {
            async fn generate(&self, _req: GenerateRequest) -> Result<InferenceResult, String> {
                Ok(turn("thinking...", json!([])))
            }
        }

        let spec = GoalSpec {
            goal: "impossible".into(),
            condition: GoalCondition::Command {
                id: "never".into(),
                expect_exit: 0,
            },
            governor: GoalGovernor {
                max_turns: Some(3),
                ..Default::default()
            },
        };
        let mut messages = vec![Message::System {
            content: "sys".into(),
        }];
        let never = std::sync::atomic::AtomicBool::new(false);

        let result = run_assistant_goal_loop(
            &Idle,
            &rt,
            &cfg(),
            &mut messages,
            &never,
            None,
            &spec,
            |_o| async {
                let mut g = car_engine::GoalGather::default();
                g.command_exits.insert("never".into(), 1);
                g
            },
            |_e| {},
        )
        .await;

        assert_eq!(
            result.run.status,
            GoalStatus::Halted {
                halt: GoalHalt::TurnBudget
            }
        );
        assert_eq!(result.run.iterations, 3);
    }

    /// car#1112: a `gather` that never resolves — the stand-in for a stuck
    /// approval wait, a wedged subprocess, or (were `ModelJudge` ever wired
    /// into a caller) an inference call to a dead route — must not hang the
    /// turn forever, and must not discard the primary reply the model already
    /// produced. Before this fix there was no bound on `gather().await` at
    /// all; `#[tokio::test(start_paused = true)]` proves the loop's own
    /// timeout is what ends this run, not a wall-clock coincidence — a real
    /// build would hang here without it.
    #[tokio::test(start_paused = true)]
    async fn goal_loop_fails_open_when_the_check_never_resolves() {
        use car_verify::goal::{GoalCondition, GoalGovernor, GoalHalt, GoalSpec, GoalStatus};

        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;

        // The model answers cleanly on the very first iteration. This reply
        // is what must reach the caller regardless of what the (stuck) check
        // does next.
        struct Answers;
        #[async_trait]
        impl TurnGenerator for Answers {
            async fn generate(&self, _req: GenerateRequest) -> Result<InferenceResult, String> {
                Ok(turn("Here is your answer.", json!([])))
            }
        }

        let spec = GoalSpec {
            goal: "answer the question".into(),
            condition: GoalCondition::Command {
                id: "verify".into(),
                expect_exit: 0,
            },
            governor: GoalGovernor {
                // Deliberately generous — a fix that only works because the
                // turn budget also happens to be tiny isn't the fix under
                // test. If the evaluation timeout weren't wired in, this run
                // would hang forever well before ever spending a 2nd turn.
                max_turns: Some(8),
                ..Default::default()
            },
        };
        let mut messages = vec![Message::System {
            content: "sys".into(),
        }];
        let never = std::sync::atomic::AtomicBool::new(false);
        let mut events = Vec::new();

        let result = run_assistant_goal_loop(
            &Answers,
            &rt,
            &cfg(),
            &mut messages,
            &never,
            None,
            &spec,
            |_outcome| std::future::pending::<car_engine::GoalGather>(),
            |e| events.push(e),
        )
        .await;

        assert_eq!(
            result.run.status,
            GoalStatus::Halted {
                halt: GoalHalt::EvaluationTimeout
            },
            "{:?}",
            result.run.last_reason
        );
        assert_eq!(
            result.run.iterations, 1,
            "must halt on the FIRST stuck evaluation, not burn the rest of the turn budget \
             re-running the model against a check that can never be graded"
        );
        assert!(
            result.run.last_reason.contains("did not complete within"),
            "{}",
            result.run.last_reason
        );
        assert_eq!(
            result.outcome.summary, "Here is your answer.",
            "the primary reply must survive an evaluation pass that never resolves"
        );
        assert!(
            events.iter().any(|e| matches!(
                e,
                AssistantEvent::GoalEvaluated {
                    met: false,
                    grounded: false,
                    ..
                }
            )),
            "the unevaluated outcome must still be streamed as a goal_evaluated event — \
             grounded: false, not true: there is no verdict to be grounded, the check \
             never ran (car#1113 review)"
        );
        assert!(
            !result.run.grounded,
            "GoalRun.grounded must not claim a deterministic verdict exists when the \
             check never got the chance to run"
        );
    }

    struct FixedGate(bool);
    #[async_trait]
    impl ApprovalGate for FixedGate {
        async fn request(&self, _tool: &str, _params: &Value) -> ApprovalDecision {
            if self.0 {
                ApprovalDecision::Approved
            } else {
                ApprovalDecision::Denied("user declined".into())
            }
        }
    }

    struct CapturingGen {
        images_seen: std::sync::Arc<std::sync::Mutex<Option<usize>>>,
    }
    #[async_trait]
    impl TurnGenerator for CapturingGen {
        async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
            *self.images_seen.lock().unwrap() = req.images.as_ref().map(|v| v.len());
            Ok(turn("done", json!([]))) // no tool calls → finish on turn 1
        }
    }

    #[tokio::test]
    async fn images_are_attached_to_the_first_request() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = std::sync::Arc::new(std::sync::Mutex::new(None));
        let generator = CapturingGen {
            images_seen: seen.clone(),
        };
        let img = ContentBlock::ImageUrl {
            url: "https://example.com/x.png".into(),
            detail: "auto".into(),
        };
        let mut messages = vec![
            Message::System {
                content: "s".into(),
            },
            Message::User {
                content: "describe".into(),
            },
        ];
        let never = std::sync::atomic::AtomicBool::new(false);
        let imgs = [img];
        run_assistant_loop_cancellable(
            &generator,
            &rt,
            &cfg(),
            &mut messages,
            &never,
            None,
            Some(&imgs),
            |_| {},
        )
        .await;
        assert_eq!(
            *seen.lock().unwrap(),
            Some(1),
            "the image should reach the first request"
        );
    }

    #[tokio::test]
    async fn gated_tool_is_denied_without_a_gate() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let script = Script {
            turns: vec![
                turn(
                    "",
                    json!([{ "id": "w1", "name": "write_file", "arguments": { "path": "x.txt", "content": "no" } }]),
                ),
                turn("could not write", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        };
        let mut cfg = cfg();
        cfg.gated_tools = vec!["write_file".into()];
        let mut messages = vec![
            Message::System {
                content: "s".into(),
            },
            Message::User {
                content: "write x".into(),
            },
        ];
        let never = std::sync::atomic::AtomicBool::new(false);
        let outcome = run_assistant_loop_cancellable(
            &script,
            &rt,
            &cfg,
            &mut messages,
            &never,
            None,
            None,
            |_| {},
        )
        .await;
        assert_eq!(outcome.status, "success");
        assert!(
            !dir.path().join("x.txt").exists(),
            "gated write must not run"
        );
        assert!(!outcome.tools_called.contains(&"write_file".to_string()));
    }

    #[tokio::test]
    async fn gated_tool_runs_when_approved() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let script = Script {
            turns: vec![
                turn(
                    "",
                    json!([{ "id": "w1", "name": "write_file", "arguments": { "path": "ok.txt", "content": "yes" } }]),
                ),
                turn("wrote it", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        };
        let mut cfg = cfg();
        cfg.gated_tools = vec!["write_file".into()];
        let gate = FixedGate(true);
        let mut messages = vec![
            Message::System {
                content: "s".into(),
            },
            Message::User {
                content: "write ok".into(),
            },
        ];
        let never = std::sync::atomic::AtomicBool::new(false);
        let outcome = run_assistant_loop_cancellable(
            &script,
            &rt,
            &cfg,
            &mut messages,
            &never,
            Some(&gate),
            None,
            |_| {},
        )
        .await;
        assert_eq!(outcome.status, "success");
        assert_eq!(
            std::fs::read_to_string(dir.path().join("ok.txt")).unwrap(),
            "yes"
        );
    }

    #[tokio::test]
    async fn loop_writes_a_file_through_the_runtime() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let script = Script {
            turns: vec![
                turn(
                    "",
                    json!([{ "id": "w1", "name": "write_file", "arguments": { "path": "hi.txt", "content": "hello" } }]),
                ),
                turn("Wrote hi.txt.", json!([])),
            ],
            cursor: AtomicUsize::new(0),
        };
        let mut messages = vec![
            Message::System {
                content: "sys".into(),
            },
            Message::User {
                content: "write hi.txt".into(),
            },
        ];
        let outcome = run_assistant_loop(&script, &rt, &cfg(), &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        assert_eq!(
            std::fs::read_to_string(dir.path().join("hi.txt")).unwrap(),
            "hello"
        );
    }

    // ---- response_format passthrough + one-shot repair ----

    fn json_object_cfg() -> AssistantConfig {
        AssistantConfig {
            response_format: Some(car_inference::ResponseFormat::JsonObject),
            ..cfg()
        }
    }

    fn repair_notices(events: &[AssistantEvent]) -> (usize, usize) {
        let mut fired = 0;
        let mut still_invalid = 0;
        for e in events {
            if let AssistantEvent::Text(t) = e {
                if t == FORMAT_REPAIR_NOTICE {
                    fired += 1;
                }
                if t == FORMAT_REPAIR_STILL_INVALID {
                    still_invalid += 1;
                }
            }
        }
        (fired, still_invalid)
    }

    /// (a) The format is NEVER on a turn that offers tools — it suppresses
    /// tool use on real providers — and appears only on the tool-less repair
    /// turn. A run that offers no tools carries it on every turn.
    #[tokio::test]
    async fn response_format_is_never_on_tool_turns_only_on_the_repair_turn() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let tool_turn = || {
            turn(
                "computing",
                json!([{ "id": "c", "name": "calculate", "arguments": { "expression": "1+1" } }]),
            )
        };

        // With tools: tool turn, non-JSON final, repair.
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                tool_turn(),
                turn("The sum is 2.", json!([])),
                turn(r#"{"sum": 2}"#, json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("add 1 and 1, answer as JSON")];
        let outcome =
            run_assistant_loop(&script, &rt, &json_object_cfg(), &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        assert_eq!(outcome.summary, r#"{"sum": 2}"#);
        {
            let reqs = seen.lock().unwrap();
            assert_eq!(reqs.len(), 3);
            for (i, r) in reqs[..2].iter().enumerate() {
                assert!(r.tools.is_some(), "request {i} offers tools");
                assert!(
                    r.response_format.is_none(),
                    "request {i} offers tools, so it must not be JSON-constrained"
                );
            }
            assert!(reqs[2].tools.is_none(), "the repair turn offers no tools");
            assert_eq!(
                reqs[2].response_format,
                Some(car_inference::ResponseFormat::JsonObject),
                "and is the one request that carries the format"
            );
        }

        // Without tools there is nothing to suppress: every turn carries it.
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![turn(r#"{"sum": 2}"#, json!([]))],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("add 1 and 1, answer as JSON")];
        let no_tools_cfg = AssistantConfig {
            tools: Vec::new(),
            ..json_object_cfg()
        };
        let outcome = run_assistant_loop(&script, &rt, &no_tools_cfg, &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        {
            let reqs = seen.lock().unwrap();
            assert_eq!(reqs.len(), 1, "a valid answer costs no extra call");
            assert!(reqs[0].tools.is_none());
            assert_eq!(
                reqs[0].response_format,
                Some(car_inference::ResponseFormat::JsonObject)
            );
        }

        // No format configured: none anywhere.
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![tool_turn(), turn("two", json!([]))],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("add 1 and 1")];
        let outcome = run_assistant_loop(&script, &rt, &cfg(), &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        let reqs = seen.lock().unwrap();
        assert_eq!(reqs.len(), 2);
        assert!(reqs.iter().all(|r| r.response_format.is_none()));
    }

    /// (b) A final answer that is not the requested shape triggers EXACTLY
    /// one repair call: no tools, the format set, the draft + nudge in the
    /// transcript. The repaired text is the answer and the event stream says
    /// the repair happened.
    #[tokio::test]
    async fn invalid_final_answer_triggers_exactly_one_toolless_repair() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                turn("Sure! The answer is: sum = 2.", json!([])),
                turn(r#"{"sum": 2}"#, json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("add 1 and 1, answer as JSON")];
        let mut events = Vec::new();
        let repair_cfg = AssistantConfig {
            model: Some("newsroom-editor".into()),
            strict_model: true,
            ..json_object_cfg()
        };
        let outcome =
            run_assistant_loop(&script, &rt, &repair_cfg, &mut messages, |e| events.push(e)).await;
        assert_eq!(outcome.status, "success");
        assert_eq!(
            outcome.summary, r#"{"sum": 2}"#,
            "the repaired text is the answer"
        );
        assert_eq!(
            outcome.turns, 1,
            "a repair is a model call, not a loop turn"
        );

        let reqs = seen.lock().unwrap();
        assert_eq!(reqs.len(), 2, "draft + exactly one repair");
        for (index, request) in reqs.iter().enumerate() {
            assert_eq!(
                request.model.as_deref(),
                Some("newsroom-editor"),
                "request {index} must retain the configured editor model"
            );
            assert!(
                request.params.strict_model,
                "request {index} must retain strict model selection"
            );
            assert_eq!(
                request.expected_row_digest, None,
                "assistant config exposes no immutable row precondition"
            );
            assert_eq!(
                request.expected_catalog_revision, None,
                "assistant config exposes no catalog revision precondition"
            );
        }
        let repair = &reqs[1];
        assert!(
            repair.tools.is_none(),
            "the repair turn advertises no tools"
        );
        assert_eq!(
            repair.response_format,
            Some(car_inference::ResponseFormat::JsonObject)
        );
        let history = repair.messages.as_ref().unwrap();
        assert!(
            matches!(history.last(), Some(Message::User { content }) if content == FORMAT_REPAIR_NUDGE),
            "the nudge is the last message the repair sees"
        );
        assert!(
            matches!(&history[history.len() - 2], Message::Assistant { content, .. } if content.contains("sum = 2")),
            "the draft is in the transcript so the model can see what it got wrong"
        );

        let (fired, still_invalid) = repair_notices(&events);
        assert_eq!(fired, 1, "the repair must be visible in the event stream");
        assert_eq!(still_invalid, 0);
        assert!(
            matches!(events.last(), Some(AssistantEvent::Done { text }) if text == r#"{"sum": 2}"#)
        );
        // The durable transcript records the whole exchange: draft, nudge, repair.
        assert!(
            matches!(messages.last(), Some(Message::Assistant { content, .. }) if content == r#"{"sum": 2}"#)
        );
        assert!(
            matches!(&messages[messages.len() - 2], Message::User { content } if content == FORMAT_REPAIR_NUDGE)
        );
    }

    /// (c) A valid final answer triggers no repair — one request, no notice.
    #[tokio::test]
    async fn valid_final_answer_triggers_no_repair() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            // A fenced object is accepted: models emit the fence even under
            // JSON mode, and the payload inside is what the caller parses.
            turns: vec![turn("```json\n{\"sum\": 2}\n```", json!([]))],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("add 1 and 1, answer as JSON")];
        let mut events = Vec::new();
        let outcome = run_assistant_loop(&script, &rt, &json_object_cfg(), &mut messages, |e| {
            events.push(e)
        })
        .await;
        assert_eq!(outcome.status, "success");
        assert_eq!(seen.lock().unwrap().len(), 1);
        assert_eq!(repair_notices(&events), (0, 0));
    }

    /// The contract is ONE repair, not retry-until-valid: a second miss is
    /// reported and the repaired text returned as-is.
    #[tokio::test]
    async fn a_repair_that_still_misses_is_reported_not_retried() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                turn("not json", json!([])),
                turn("still not json", json!([])),
                turn(r#"{"never": "reached"}"#, json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("answer as JSON")];
        let mut events = Vec::new();
        let outcome = run_assistant_loop(&script, &rt, &json_object_cfg(), &mut messages, |e| {
            events.push(e)
        })
        .await;
        assert_eq!(outcome.status, "success");
        assert_eq!(outcome.summary, "still not json");
        assert_eq!(seen.lock().unwrap().len(), 2, "one repair, never a second");
        assert_eq!(repair_notices(&events), (1, 1));
    }

    /// `JsonObject` needs an object; `JsonSchema` needs parseable JSON
    /// (parse-only: this crate carries no schema validator). Fences are
    /// tolerated either way.
    #[test]
    fn final_text_format_check_semantics() {
        use car_inference::ResponseFormat::{JsonObject, JsonSchema};
        let schema = JsonSchema {
            schema: json!({"type": "array"}),
            strict: false,
            name: None,
        };
        assert!(final_text_matches_format(r#"{"a": 1}"#, &JsonObject, None));
        assert!(final_text_matches_format(
            "```json\n{\"a\": 1}\n```",
            &JsonObject,
            None
        ));
        assert!(
            !final_text_matches_format("[1, 2]", &JsonObject, None),
            "an array is not an object"
        );
        assert!(!final_text_matches_format(
            "Here: {\"a\": 1}",
            &JsonObject,
            None
        ));
        assert!(
            final_text_matches_format("[1, 2]", &schema, None),
            "schema mode is parse-only"
        );
        assert!(!final_text_matches_format("nope", &schema, None));
        let requires_legs: ResponseFormatValidator = Arc::new(|v| v.get("legs").is_some());
        assert!(
            final_text_matches_format(r#"{"legs": []}"#, &schema, Some(&requires_legs)),
            "conforming JSON passes the caller's schema check"
        );
        assert!(
            !final_text_matches_format(r#"{"nope": 1}"#, &schema, Some(&requires_legs)),
            "valid JSON of the wrong shape must fail once a validator exists"
        );
        assert_eq!(extract_json_payload("```\n[1]\n```"), "[1]");
        assert_eq!(extract_json_payload("  [1] "), "[1]");
        assert_eq!(
            extract_json_payload("```json\n{}"),
            "```json\n{}",
            "an unclosed fence is left alone"
        );
    }

    // ---- context_window_override ----

    /// A generator that knows its model's window, so the override has
    /// something to be clamped against.
    struct WindowedScript {
        inner: CapturingScript,
        window: usize,
    }

    #[async_trait]
    impl TurnGenerator for WindowedScript {
        async fn generate(&self, req: GenerateRequest) -> Result<InferenceResult, String> {
            self.inner.generate(req).await
        }
        fn context_window(&self, _model: &str) -> usize {
            self.window
        }
    }

    fn windowed(window: usize) -> (WindowedScript, Arc<StdMutex<Vec<GenerateRequest>>>) {
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = WindowedScript {
            inner: CapturingScript {
                turns: vec![turn("done", json!([]))],
                cursor: AtomicUsize::new(0),
                seen: Arc::clone(&seen),
            },
            window,
        };
        (script, seen)
    }

    /// ~60k estimated tokens: fits a 200k window (budget 150k), overflows a
    /// 20k one (budget 15k).
    fn long_history() -> Vec<Message> {
        let big = "x".repeat(20_000);
        let mut m = vec![sys("system"), usr("THE ORIGINAL TASK")];
        for i in 0..12 {
            m.push(asst_call(&format!("c{i}")));
            m.push(tool_res(&format!("c{i}"), &big));
        }
        m
    }

    fn has_compaction_notice(messages: &[Message]) -> bool {
        messages.iter().any(|m| {
            matches!(m, Message::System { content } if content.starts_with(COMPACTION_NOTICE_PREFIX))
        })
    }

    fn window_advisories(events: &[AssistantEvent]) -> usize {
        events
            .iter()
            .filter(|e| matches!(e, AssistantEvent::Text(t) if t.starts_with("[context window:")))
            .count()
    }

    /// Override 20k on a 200k model: compaction fires on a history that the
    /// real window would have carried whole.
    #[tokio::test]
    async fn context_window_override_below_the_registry_window_tightens_compaction() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let (script, seen) = windowed(200_000);
        let mut messages = long_history();
        let cfg = AssistantConfig {
            context_window_override: Some(20_000),
            refuse_unadvertised_tools: false,
            response_format_validator: None,
            delegate_budget: None,
            ..cfg()
        };
        let mut events = Vec::new();
        let outcome =
            run_assistant_loop(&script, &rt, &cfg, &mut messages, |e| events.push(e)).await;
        assert_eq!(outcome.status, "success");
        assert!(
            has_compaction_notice(&messages),
            "the 20k override must compact"
        );
        // The compacted history is what the model saw, not just what was stored.
        let reqs = seen.lock().unwrap();
        assert!(has_compaction_notice(reqs[0].messages.as_ref().unwrap()));
        assert_eq!(window_advisories(&events), 0, "tightening is not clamped");
    }

    /// No override: the registry window governs and this history fits.
    #[tokio::test]
    async fn no_context_window_override_leaves_the_registry_window_in_charge() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let (script, _seen) = windowed(200_000);
        let mut messages = long_history();
        let mut events = Vec::new();
        let outcome =
            run_assistant_loop(&script, &rt, &cfg(), &mut messages, |e| events.push(e)).await;
        assert_eq!(outcome.status, "success");
        assert!(!has_compaction_notice(&messages), "60k fits a 200k window");
        assert_eq!(window_advisories(&events), 0);
    }

    /// Override 400k on a 200k model: clamped back to 200k (no compaction of
    /// a history that fits 200k, but the clamp is announced), because a window
    /// larger than the real one would reintroduce the provider-side truncation
    /// compaction exists to prevent.
    #[tokio::test]
    async fn context_window_override_above_the_registry_window_is_clamped_and_announced() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let (script, _seen) = windowed(200_000);
        let mut messages = long_history();
        let cfg = AssistantConfig {
            context_window_override: Some(400_000),
            refuse_unadvertised_tools: false,
            response_format_validator: None,
            delegate_budget: None,
            ..cfg()
        };
        let mut events = Vec::new();
        let outcome =
            run_assistant_loop(&script, &rt, &cfg, &mut messages, |e| events.push(e)).await;
        assert_eq!(outcome.status, "success");
        assert!(!has_compaction_notice(&messages));
        assert_eq!(window_advisories(&events), 1, "the clamp must be visible");
    }

    #[test]
    fn resolve_context_window_clamps_only_upward_against_a_known_window() {
        assert_eq!(resolve_context_window(None, 200_000), (200_000, None));
        assert_eq!(resolve_context_window(None, 0), (0, None));
        assert_eq!(
            resolve_context_window(Some(20_000), 200_000),
            (20_000, None)
        );
        let (w, advisory) = resolve_context_window(Some(400_000), 200_000);
        assert_eq!(w, 200_000);
        assert!(advisory
            .unwrap()
            .contains("exceeds the model's known window"));
        // Unknown registry window: nothing to clamp against, the override
        // stands (ignoring it would silently disable the compaction asked for).
        assert_eq!(resolve_context_window(Some(400_000), 0), (400_000, None));
    }

    // ---- compaction decides on the provider-reported prompt size ----

    /// A history whose chars/4 estimate is small (~6-7k tokens): the reported
    /// count, not the estimate, must be what trips compaction.
    fn modest_history() -> Vec<Message> {
        let body = "x".repeat(2_000);
        let mut m = vec![sys("system"), usr("THE ORIGINAL TASK")];
        for i in 0..12 {
            m.push(asst_call(&format!("c{i}")));
            m.push(tool_res(&format!("c{i}"), &body));
        }
        m
    }

    /// The live failure: a 150k-window run whose estimate sat under budget
    /// while the provider billed 144k, and compaction never fired. A reported
    /// prompt size far above the estimate must trigger compaction on the
    /// NEXT turn.
    #[tokio::test]
    async fn reported_prompt_tokens_far_above_the_estimate_trigger_compaction_next_turn() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = WindowedScript {
            inner: CapturingScript {
                turns: vec![
                    turn_with_usage(
                        "computing",
                        json!([{ "id": "k", "name": "calculate", "arguments": { "expression": "1+1" } }]),
                        190_000,
                        10,
                    ),
                    turn("done", json!([])),
                ],
                cursor: AtomicUsize::new(0),
                seen: Arc::clone(&seen),
            },
            window: 200_000,
        };
        let mut messages = modest_history();
        let estimate = messages.iter().map(approx_message_tokens).sum::<usize>();
        assert!(
            estimate < 20_000,
            "fixture estimate must sit far under the 150k budget: {estimate}"
        );

        let outcome = run_assistant_loop(&script, &rt, &cfg(), &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");

        let reqs = seen.lock().unwrap();
        assert_eq!(reqs.len(), 2);
        assert!(
            !has_compaction_notice(reqs[0].messages.as_ref().unwrap()),
            "turn 1 has no report yet and the estimate fits"
        );
        assert!(
            has_compaction_notice(reqs[1].messages.as_ref().unwrap()),
            "turn 2 must compact on the 190k the provider reported for turn 1"
        );
        assert!(has_compaction_notice(&messages));
    }

    /// No usage report → the estimate alone decides, exactly as before.
    #[tokio::test]
    async fn no_usage_report_falls_back_to_the_estimate() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = WindowedScript {
            inner: CapturingScript {
                turns: vec![
                    turn(
                        "computing",
                        json!([{ "id": "k", "name": "calculate", "arguments": { "expression": "1+1" } }]),
                    ),
                    turn("done", json!([])),
                ],
                cursor: AtomicUsize::new(0),
                seen: Arc::clone(&seen),
            },
            window: 200_000,
        };
        let mut messages = modest_history();
        let outcome = run_assistant_loop(&script, &rt, &cfg(), &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        assert_eq!(seen.lock().unwrap().len(), 2);
        assert!(!has_compaction_notice(&messages));
    }

    /// The reported count is scaled onto the per-message estimates for the
    /// drop loop, so one compaction lands under budget; the notice accounts
    /// in that same measure and still round-trips.
    #[test]
    fn measured_compaction_scales_the_drop_to_the_reported_size_and_round_trips() {
        let mut m = modest_history();
        let len = m.len();
        let estimate: usize = m.iter().map(approx_message_tokens).sum();
        // ~7k estimated; the provider says 40× that, over a 150k budget.
        let measure = PromptMeasure {
            fixed_overhead: 0,
            reported: Some((estimate * 40, len)),
        };
        compact_history_measured(&mut m, 200_000, measure);
        let notice = m
            .iter()
            .find(|msg| parse_compaction_notice(msg).is_some())
            .expect("must compact on the reported size");
        let (turns, tokens) = parse_compaction_notice(notice).unwrap();
        assert!(turns > 0);
        assert!(
            tokens > estimate,
            "dropped tokens are accounted in the scaled (provider) measure: {tokens} vs raw estimate {estimate}"
        );
        // Unscaled, dropping the same turns would have removed at most the
        // raw estimate — the scale is what makes one pass sufficient.
        let remaining: usize = m.iter().map(approx_message_tokens).sum();
        assert!(remaining < estimate);
    }

    /// The tool definitions are part of every request; a history that fits
    /// the budget on its own but not with the tools must compact.
    #[test]
    fn fixed_overhead_counts_toward_the_budget() {
        let mut m = modest_history();
        let estimate: usize = m.iter().map(approx_message_tokens).sum();
        // Budget is 3/4 of the window: sit just under it on the history alone.
        let window = estimate * 4 / 3 + 40;
        compact_history_measured(&mut m, window, PromptMeasure::default());
        assert!(!has_compaction_notice(&m), "history alone fits");
        compact_history_measured(
            &mut m,
            window,
            PromptMeasure {
                fixed_overhead: 5_000,
                reported: None,
            },
        );
        assert!(has_compaction_notice(&m), "history + tool defs does not");
    }

    /// A reported count within 25% of the estimate does not rescale the
    /// per-message numbers; one further off does.
    #[test]
    fn reported_count_only_rescales_beyond_a_quarter_off() {
        let m = modest_history();
        let len = m.len();
        let estimate: usize = m.iter().map(approx_message_tokens).sum();
        // Within 25%: decide on the reported total, drop by raw estimates.
        let mut close = m.clone();
        compact_history_measured(
            &mut close,
            estimate * 4 / 3,
            PromptMeasure {
                fixed_overhead: 0,
                reported: Some((estimate * 11 / 10, len)),
            },
        );
        let (_, close_tokens) = close
            .iter()
            .find_map(parse_compaction_notice)
            .expect("110% of a budget-sized estimate must compact");
        // Far off: the same drop is accounted ~20x larger.
        let mut far = m.clone();
        compact_history_measured(
            &mut far,
            estimate * 4 / 3,
            PromptMeasure {
                fixed_overhead: 0,
                reported: Some((estimate * 20, len)),
            },
        );
        let (_, far_tokens) = far.iter().find_map(parse_compaction_notice).unwrap();
        assert!(
            far_tokens > close_tokens * 5,
            "{far_tokens} vs {close_tokens}"
        );
    }

    // ---- delegate: loop-intercepted sub-agent ----

    /// The parent's config with `delegate` advertised over its own tools.
    fn delegate_cfg() -> AssistantConfig {
        let mut tools = GeneralExecutor::tool_defs();
        tools.push(delegate_tool_def(&tools));
        AssistantConfig { tools, ..cfg() }
    }

    fn delegate_call(params: Value) -> InferenceResult {
        turn(
            "delegating",
            json!([{ "id": "d1", "name": DELEGATE_TOOL, "arguments": params }]),
        )
    }

    fn calc_call() -> InferenceResult {
        turn(
            "computing",
            json!([{ "id": "k", "name": "calculate", "arguments": { "expression": "1+1" } }]),
        )
    }

    fn tool_names(req: &GenerateRequest) -> Vec<String> {
        req.tools
            .as_deref()
            .unwrap_or_default()
            .iter()
            .filter_map(|d| d.get("name").and_then(Value::as_str))
            .map(str::to_string)
            .collect()
    }

    /// The parent's `ToolResult` for the delegate call.
    fn delegate_result(messages: &[Message]) -> (String, bool) {
        messages
            .iter()
            .find_map(|m| match m {
                Message::ToolResult {
                    tool_use_id,
                    content,
                    provenance,
                } if tool_use_id == "d1" => {
                    Some((content.clone(), *provenance == Provenance::External))
                }
                _ => None,
            })
            .expect("the delegate call must have a tool result")
    }

    #[test]
    fn delegate_tool_def_enumerates_parent_tools_and_excludes_itself() {
        let mut tools = GeneralExecutor::tool_defs();
        let def = delegate_tool_def(&tools);
        assert_eq!(def["name"], DELEGATE_TOOL);
        assert_eq!(def["tier"], "read_only");
        assert_eq!(def["mutating"], true, "a finished delegation is progress");
        assert_eq!(def["parameters"]["required"], json!(["goal"]));
        let en = def["parameters"]["properties"]["tools"]["items"]["enum"]
            .as_array()
            .unwrap()
            .clone();
        assert!(en.iter().any(|v| v == "calculate"));
        assert!(!en.iter().any(|v| v == DELEGATE_TOOL));
        // Built over a set that already carries `delegate`: still excluded.
        tools.push(def);
        let again = delegate_tool_def(&tools);
        assert!(!again["parameters"]["properties"]["tools"]["items"]["enum"]
            .as_array()
            .unwrap()
            .iter()
            .any(|v| v == DELEGATE_TOOL));
        assert!(mutating_tool_names(&tools).contains(DELEGATE_TOOL));
    }

    #[test]
    fn delegate_params_parse_with_defaults_and_cap() {
        let r = parse_delegate_params(&json!({"goal": " count "})).unwrap();
        assert_eq!(r.goal, "count");
        assert_eq!(r.tools, None);
        assert_eq!(r.max_turns, DELEGATE_DEFAULT_MAX_TURNS);
        let r =
            parse_delegate_params(&json!({"goal": "x", "tools": ["calculate"], "max_turns": 500}))
                .unwrap();
        assert_eq!(r.tools.as_deref(), Some(&["calculate".to_string()][..]));
        assert_eq!(r.max_turns, DELEGATE_MAX_TURNS_CAP);
        assert!(parse_delegate_params(&json!({"goal": ""})).is_err());
        assert!(parse_delegate_params(&json!({"goal": "x", "max_turns": 0})).is_err());
        assert!(parse_delegate_params(&json!({"goal": "x", "tools": "calculate"})).is_err());
    }

    /// The child config is the parent's, minus what a child must not have.
    #[test]
    fn delegate_child_config_derives_from_the_parent() {
        let mut parent = delegate_cfg();
        parent.gated_tools = vec!["shell".into()];
        parent.context_window_override = Some(20_000);
        parent.response_format = Some(car_inference::ResponseFormat::JsonObject);
        parent.todos = Some(Arc::new(tokio::sync::Mutex::new(
            super::super::todo::TodoList::new(),
        )));
        let req = parse_delegate_params(&json!({"goal": "g", "tools": ["calculate"]})).unwrap();
        let child = delegate_child_config(&parent, &req).unwrap();
        assert_eq!(
            child
                .tools
                .iter()
                .map(|d| d["name"].as_str().unwrap())
                .collect::<Vec<_>>(),
            vec!["calculate"]
        );
        assert!(child.refuse_unadvertised_tools);
        assert_eq!(child.max_turns, DELEGATE_DEFAULT_MAX_TURNS);
        assert!(child.todos.is_none());
        assert!(child.response_format.is_none(), "children answer in prose");
        assert_eq!(
            child.gated_tools, parent.gated_tools,
            "gates inherited whole"
        );
        assert_eq!(child.context_window_override, Some(20_000));
        assert_eq!(child.model, parent.model);
        // Default subset = everything delegable, still without `delegate`.
        let all = delegate_child_config(
            &parent,
            &parse_delegate_params(&json!({"goal": "g"})).unwrap(),
        )
        .unwrap();
        let names: Vec<&str> = all
            .tools
            .iter()
            .map(|d| d["name"].as_str().unwrap())
            .collect();
        assert!(names.contains(&"calculate"));
        assert!(!names.contains(&DELEGATE_TOOL));
        assert_eq!(names.len(), parent.tools.len() - 1);
    }

    /// Parent issues `delegate` → the child runs with its OWN history (system
    /// prompt + goal, none of the parent's messages), on the parent's tools
    /// minus `delegate`, and the parent receives only the child's final text.
    #[tokio::test]
    async fn delegate_child_runs_with_a_fresh_history_and_returns_only_its_final_text() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "what is 1+1? reply with the number only"})),
                calc_call(),                         // child turn 1
                turn("2", json!([])),                // child turn 2: final
                turn("The answer is 2.", json!([])), // parent turn 2
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![
            sys("PARENT SYSTEM PROMPT"),
            usr("PARENT TASK: add one and one"),
        ];
        let mut events = Vec::new();
        let outcome = run_assistant_loop(&script, &rt, &delegate_cfg(), &mut messages, |e| {
            events.push(e)
        })
        .await;
        assert_eq!(outcome.status, "success");
        assert_eq!(outcome.summary, "The answer is 2.");
        assert_eq!(outcome.turns, 2, "child turns are not the parent's");

        let reqs = seen.lock().unwrap();
        assert_eq!(reqs.len(), 4);
        let child_first = reqs[1].messages.as_ref().unwrap();
        assert_eq!(
            child_first.len(),
            2,
            "exactly system + goal: {child_first:?}"
        );
        assert!(
            matches!(&child_first[0], Message::System { content } if content == "PARENT SYSTEM PROMPT")
        );
        assert!(
            matches!(&child_first[1], Message::User { content } if content.starts_with("what is 1+1?"))
        );
        assert!(
            !serde_json::to_string(child_first)
                .unwrap()
                .contains("PARENT TASK"),
            "nothing from the parent's transcript reaches the child"
        );
        let child_tools = tool_names(&reqs[1]);
        assert!(child_tools.contains(&"calculate".to_string()));
        assert!(
            !child_tools.contains(&DELEGATE_TOOL.to_string()),
            "no nesting"
        );
        assert!(tool_names(&reqs[0]).contains(&DELEGATE_TOOL.to_string()));
        // The parent's second request carries the delegate result and none of
        // the child's transcript.
        let parent_second = reqs[3].messages.as_ref().unwrap();
        assert!(!serde_json::to_string(parent_second)
            .unwrap()
            .contains("computing"));
        drop(reqs);

        let (content, external) = delegate_result(&messages);
        assert_eq!(content, "2", "only the child's final text comes back");
        assert!(!external, "calculate is internal");

        // Receipt + events: the delegation is one tool call and one result.
        assert!(events
            .iter()
            .any(|e| matches!(e, AssistantEvent::ToolCall { name, .. } if name == DELEGATE_TOOL)));
        assert!(events.iter().any(|e| matches!(e, AssistantEvent::ToolResult { name, ok: true, content } if name == DELEGATE_TOOL && content == "2")));
        assert!(events.iter().any(|e| matches!(e, AssistantEvent::Text(t) if t.starts_with("[delegate: what is 1+1?") && t.ends_with("2 turns, ok]"))));
        assert!(
            !events
                .iter()
                .any(|e| matches!(e, AssistantEvent::ToolCall { name, .. } if name == "calculate")),
            "the child's own tool calls are not forwarded"
        );
        let receipt = outcome
            .tool_receipts
            .iter()
            .find(|r| r.tool == DELEGATE_TOOL)
            .unwrap();
        assert!(receipt.ok);
        assert_eq!(receipt.call_id.as_deref(), Some("d1"));
        assert_eq!(outcome.tools_called, vec![DELEGATE_TOOL.to_string()]);
    }

    /// The granted subset holds at EXECUTION: a child call to an ungranted
    /// tool is refused with an error result, never dispatched.
    #[tokio::test]
    async fn delegate_child_tool_subset_is_enforced_at_execution() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "write hi.txt", "tools": ["calculate"]})),
                turn(
                    "writing",
                    json!([{ "id": "w", "name": "write_file", "arguments": { "path": "hi.txt", "content": "hello" } }]),
                ),
                turn("could not write", json!([])),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("task")];
        let outcome =
            run_assistant_loop(&script, &rt, &delegate_cfg(), &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        assert!(
            !dir.path().join("hi.txt").exists(),
            "the ungranted write must not run"
        );
        let reqs = seen.lock().unwrap();
        assert_eq!(tool_names(&reqs[1]), vec!["calculate".to_string()]);
        let child_second = reqs[2].messages.as_ref().unwrap();
        let refusal = child_second
            .iter()
            .find_map(|m| match m {
                Message::ToolResult {
                    tool_use_id,
                    content,
                    ..
                } if tool_use_id == "w" => Some(content.clone()),
                _ => None,
            })
            .unwrap();
        assert!(
            refusal.contains("not granted to this delegate"),
            "{refusal}"
        );
        assert!(
            refusal.contains("calculate"),
            "says what IS allowed: {refusal}"
        );
    }

    /// No nesting: a child that calls `delegate` is refused at execution, and
    /// a parent that tries to GRANT `delegate` is refused as an escalation.
    #[tokio::test]
    async fn delegate_cannot_nest() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "go deeper"})),
                turn(
                    "nesting",
                    json!([{ "id": "n", "name": DELEGATE_TOOL, "arguments": { "goal": "deeper still" } }]),
                ),
                turn("could not nest", json!([])),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("task")];
        let outcome =
            run_assistant_loop(&script, &rt, &delegate_cfg(), &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        {
            let reqs = seen.lock().unwrap();
            assert_eq!(reqs.len(), 4, "the nested call must not spawn a grandchild");
            let child_second = reqs[2].messages.as_ref().unwrap();
            let refusal = serde_json::to_string(child_second).unwrap();
            assert!(
                refusal.contains("not granted to this delegate"),
                "{refusal}"
            );
        }

        // Granting `delegate` explicitly is an escalation.
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "go deeper", "tools": [DELEGATE_TOOL]})),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("task")];
        let mut events = Vec::new();
        run_assistant_loop(&script, &rt, &delegate_cfg(), &mut messages, |e| {
            events.push(e)
        })
        .await;
        assert_eq!(seen.lock().unwrap().len(), 2, "no child ran");
        let (content, _) = delegate_result(&messages);
        assert!(
            content.contains("privilege escalation rejected"),
            "{content}"
        );
        assert!(content.contains("cannot delegate further"), "{content}");
        assert!(events.iter().any(|e| matches!(e, AssistantEvent::ToolResult { name, ok: false, .. } if name == DELEGATE_TOOL)));
    }

    /// A name outside the parent's set is refused before any child runs.
    #[tokio::test]
    async fn delegate_escalation_is_refused_without_spawning() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "x", "tools": ["calculate", "launch_missiles"]})),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("task")];
        let outcome =
            run_assistant_loop(&script, &rt, &delegate_cfg(), &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        assert_eq!(seen.lock().unwrap().len(), 2);
        let (content, _) = delegate_result(&messages);
        assert!(content.contains("launch_missiles"), "{content}");
        let receipt = outcome
            .tool_receipts
            .iter()
            .find(|r| r.tool == DELEGATE_TOOL)
            .unwrap();
        assert!(!receipt.ok);
        assert!(
            outcome.tools_called.is_empty(),
            "a refused delegation is not progress"
        );
    }

    /// A child that runs out of turns comes back as an ERROR result carrying
    /// the reason — the parent must not read an unfinished delegation as an
    /// answer.
    #[tokio::test]
    async fn delegate_turn_cap_is_an_error_result() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "keep computing", "max_turns": 1})),
                calc_call(), // child turn 1 = its whole budget
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("task")];
        let mut events = Vec::new();
        let outcome = run_assistant_loop(&script, &rt, &delegate_cfg(), &mut messages, |e| {
            events.push(e)
        })
        .await;
        assert_eq!(outcome.status, "success");
        assert_eq!(seen.lock().unwrap().len(), 3);
        let (content, _) = delegate_result(&messages);
        assert!(content.contains("did not finish"), "{content}");
        assert!(content.contains("status: max_turns"), "{content}");
        assert!(events
            .iter()
            .any(|e| matches!(e, AssistantEvent::Text(t) if t.ends_with("1 turns, error]"))));
        assert!(events.iter().any(|e| matches!(e, AssistantEvent::ToolResult { name, ok: false, .. } if name == DELEGATE_TOOL)));
        assert!(outcome.tools_called.is_empty());
    }

    /// The child's final text is capped like any other observation.
    #[tokio::test]
    async fn delegate_summary_is_capped() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let long = "y".repeat(OBSERVATION_CAP * 3);
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "dump"})),
                turn(&long, json!([])),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("task")];
        run_assistant_loop(&script, &rt, &delegate_cfg(), &mut messages, |_| {}).await;
        let (content, _) = delegate_result(&messages);
        assert!(content.len() < long.len());
        assert!(
            content.contains("bytes elided"),
            "the cap must say what it dropped"
        );
    }

    /// Approval inheritance by construction: a read-only parent (gated
    /// write/shell, no approver) cannot get a write done through a child —
    /// the child's write is denied by the GATE, not by the subset.
    #[tokio::test]
    async fn delegate_child_inherits_the_parents_approval_gate() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(
                    json!({"goal": "write hi.txt", "tools": ["write_file", "calculate"]}),
                ),
                turn(
                    "writing",
                    json!([{ "id": "w", "name": "write_file", "arguments": { "path": "hi.txt", "content": "hello" } }]),
                ),
                turn("denied", json!([])),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut cfg = delegate_cfg();
        cfg.gated_tools = vec!["write_file".into(), "edit_file".into(), "shell".into()];
        let mut messages = vec![sys("sys"), usr("task")];
        let outcome = run_assistant_loop(&script, &rt, &cfg, &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        assert!(!dir.path().join("hi.txt").exists());
        let reqs = seen.lock().unwrap();
        // The subset DID grant write_file — it is the gate that says no.
        assert!(tool_names(&reqs[1]).contains(&"write_file".to_string()));
        let child_second = serde_json::to_string(reqs[2].messages.as_ref().unwrap()).unwrap();
        assert!(child_second.contains("needs approval"), "{child_second}");
        assert!(!child_second.contains("not granted"), "{child_second}");
    }

    /// A run that never advertised `delegate` treats a `delegate` call as an
    /// unknown tool: no child, no free sub-agent.
    #[tokio::test]
    async fn delegate_is_not_intercepted_unless_advertised() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![delegate_call(json!({"goal": "x"})), turn("done", json!([]))],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("task")];
        run_assistant_loop(&script, &rt, &cfg(), &mut messages, |_| {}).await;
        assert_eq!(seen.lock().unwrap().len(), 2, "no child ran");
        let (content, _) = delegate_result(&messages);
        assert!(!content.is_empty());
        assert!(
            !content.contains("did not finish"),
            "not a delegation at all: {content}"
        );
    }

    // ---- round 4: grounding, budget, schema enforcement, repair failure ----

    /// A parent that delegates "run the tests" and reports the result is NOT
    /// flagged ungrounded: the child's own receipts are merged (tagged) into
    /// the parent's list, so the claim check sees the child's shell call.
    #[tokio::test]
    async fn delegate_child_receipts_ground_the_parents_claims() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "run the test suite and report", "tools": ["shell"]})),
                turn(
                    "running",
                    json!([{ "id": "s", "name": "shell", "arguments": { "command": "echo cargo test ok" } }]),
                ),
                turn("The suite ran.", json!([])),
                turn("I ran the tests and they passed.", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("run the tests")];
        let outcome =
            run_assistant_loop(&script, &rt, &delegate_cfg(), &mut messages, |_| {}).await;
        // Without the merge this is status "error" after two redrives (the
        // script would be exhausted); with it the claim is grounded.
        assert_eq!(outcome.status, "success", "{}", outcome.summary);
        assert_eq!(outcome.summary, "I ran the tests and they passed.");
        let child_shell = outcome
            .tool_receipts
            .iter()
            .find(|r| r.tool == "shell")
            .expect("the child's shell receipt must be in the parent's list");
        assert!(child_shell.ok);
        assert_eq!(child_shell.via.as_deref(), Some("delegate:d1"));
        // The delegate's own receipt is still there, untagged.
        let del = outcome
            .tool_receipts
            .iter()
            .find(|r| r.tool == DELEGATE_TOOL)
            .unwrap();
        assert!(del.via.is_none());
        assert!(
            ungrounded_summary_claims(&outcome.summary, &outcome.tool_receipts).is_empty(),
            "the merged shell receipt grounds the tests-passed claim"
        );
    }

    /// The run-level budget: a delegate call past `max_delegations` is an
    /// error result and no child runs.
    #[tokio::test]
    async fn delegate_budget_caps_delegations() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "first"})),
                turn("one", json!([])), // child 1
                delegate_call(json!({"goal": "second"})),
                // No second child: the budget refusal is synchronous.
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut cfg = delegate_cfg();
        cfg.delegate_budget = Some(DelegateBudget {
            max_delegations: 1,
            max_child_turns: 300,
        });
        let mut messages = vec![sys("sys"), usr("task")];
        let outcome = run_assistant_loop(&script, &rt, &cfg, &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        assert_eq!(seen.lock().unwrap().len(), 4);
        let refusals: Vec<&AssistantToolReceipt> = outcome
            .tool_receipts
            .iter()
            .filter(|r| r.tool == DELEGATE_TOOL && !r.ok)
            .collect();
        assert_eq!(refusals.len(), 1);
        let refusal_text = messages
            .iter()
            .find_map(|m| match m {
                Message::ToolResult { content, .. } if content.contains("budget exhausted") => {
                    Some(content.clone())
                }
                _ => None,
            })
            .expect("the refusal must reach the model");
        assert!(refusal_text.contains("1 delegations"), "{refusal_text}");
    }

    /// The other half of the budget: cumulative child turns.
    #[tokio::test]
    async fn delegate_budget_caps_cumulative_child_turns() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "first"})),
                calc_call(),            // child 1 turn 1
                turn("one", json!([])), // child 1 turn 2
                delegate_call(json!({"goal": "second"})),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut cfg = delegate_cfg();
        cfg.delegate_budget = Some(DelegateBudget {
            max_delegations: 20,
            max_child_turns: 2,
        });
        let mut messages = vec![sys("sys"), usr("task")];
        let outcome = run_assistant_loop(&script, &rt, &cfg, &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        assert_eq!(seen.lock().unwrap().len(), 5, "no second child spawned");
        assert!(
            messages.iter().any(|m| matches!(m, Message::ToolResult { content, .. } if content.contains("2 child turns"))),
            "the refusal names the spent turn budget"
        );
    }

    /// Item 7: with a caller-supplied schema validator, valid JSON of the
    /// WRONG shape triggers the repair (the schema-worded nudge), and the
    /// conforming repaired answer passes.
    #[tokio::test]
    async fn json_schema_shape_mismatch_triggers_the_repair() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                turn(r#"{"nope": 1}"#, json!([])),
                turn(r#"{"legs": []}"#, json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut cfg = cfg();
        cfg.response_format = Some(car_inference::ResponseFormat::JsonSchema {
            schema: json!({"type": "object", "required": ["legs"]}),
            strict: false,
            name: None,
        });
        cfg.response_format_validator = Some(Arc::new(|v| v.get("legs").is_some()));
        let mut messages = vec![sys("sys"), usr("plan the flight, answer as JSON")];
        let mut events = Vec::new();
        let outcome =
            run_assistant_loop(&script, &rt, &cfg, &mut messages, |e| events.push(e)).await;
        assert_eq!(outcome.status, "success");
        assert_eq!(outcome.summary, r#"{"legs": []}"#);
        let reqs = seen.lock().unwrap();
        assert_eq!(reqs.len(), 2, "valid-but-wrong-shape JSON must be repaired");
        assert!(reqs[1].tools.is_none());
        let nudge = reqs[1]
            .messages
            .as_ref()
            .unwrap()
            .last()
            .and_then(|m| match m {
                Message::User { content } => Some(content.clone()),
                _ => None,
            })
            .unwrap();
        assert!(
            nudge.contains("JSON Schema"),
            "schema-worded, not 'object': {nudge}"
        );
        assert_eq!(repair_notices(&events), (1, 0));
    }

    /// Item 4: a repair call that ERRORS (an Anthropic-protocol model
    /// rejecting response_format) keeps the DRAFT as the answer — success,
    /// with a visible failure notice and no dangling nudge in the transcript.
    #[tokio::test]
    async fn a_failed_repair_call_keeps_the_draft_answer() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            // One scripted turn: the repair call hits "script exhausted".
            turns: vec![turn("The answer is 2, not JSON.", json!([]))],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("answer as JSON")];
        let mut events = Vec::new();
        let outcome = run_assistant_loop(&script, &rt, &json_object_cfg(), &mut messages, |e| {
            events.push(e)
        })
        .await;
        assert_eq!(outcome.status, "success", "the draft is still an answer");
        assert_eq!(outcome.summary, "The answer is 2, not JSON.");
        assert!(
            events.iter().any(|e| matches!(e, AssistantEvent::Text(t) if t.starts_with(FORMAT_REPAIR_FAILED_PREFIX))),
            "the failure must be visible"
        );
        assert!(
            matches!(messages.last(), Some(Message::Assistant { content, .. }) if content == "The answer is 2, not JSON."),
            "the transcript ends on the draft answer, not a dangling nudge: {:?}",
            messages.last()
        );
    }

    /// Item 8: a delegate child cannot touch the parent's task list —
    /// `todo_write` outside the child's granted set is refused at execution
    /// (before dispatch), so the shared executor never runs it.
    #[tokio::test]
    async fn delegate_child_cannot_touch_the_parents_todo_list() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let todos = Arc::new(tokio::sync::Mutex::new(super::super::todo::TodoList::new()));
        todos
            .lock()
            .await
            .write(&[json!({"text": "the parent's plan"})])
            .unwrap();
        let before = todos.lock().await.render();

        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "reorganize", "tools": ["calculate"]})),
                turn(
                    "writing todos",
                    json!([{ "id": "t", "name": "todo_write", "arguments": { "todos": [{"text": "hijacked"}] } }]),
                ),
                turn("could not", json!([])),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut cfg = delegate_cfg();
        cfg.todos = Some(Arc::clone(&todos));
        let mut messages = vec![sys("sys"), usr("task")];
        let outcome = run_assistant_loop(&script, &rt, &cfg, &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        assert_eq!(
            todos.lock().await.render(),
            before,
            "the parent's list is untouched"
        );
        let child_second =
            serde_json::to_string(seen.lock().unwrap()[2].messages.as_ref().unwrap()).unwrap();
        assert!(
            child_second.contains("not granted to this delegate"),
            "{child_second}"
        );
    }

    /// Item 9a: the LIVE state of the provenance marking — a child receipt
    /// from an external-labelled tool marks the parent's ToolResult External.
    #[tokio::test]
    async fn delegate_marks_the_parent_result_external_when_a_child_receipt_is() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let mut tools = GeneralExecutor::tool_defs();
        // A network tool the built-in labels mark as crossing the boundary.
        tools.push(json!({
            "name": "http_request",
            "description": "Fetch a URL.",
            "parameters": {"type": "object", "properties": {"url": {"type": "string"}}}
        }));
        tools.push(delegate_tool_def(&tools));
        let cfg = AssistantConfig { tools, ..cfg() };

        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = CapturingScript {
            turns: vec![
                delegate_call(json!({"goal": "fetch the page", "tools": ["http_request"]})),
                turn(
                    "fetching",
                    json!([{ "id": "h", "name": "http_request", "arguments": { "url": "https://example.invalid/" } }]),
                ),
                turn("could not fetch", json!([])),
                turn("done", json!([])),
            ],
            cursor: AtomicUsize::new(0),
            seen: Arc::clone(&seen),
        };
        let mut messages = vec![sys("sys"), usr("task")];
        let outcome = run_assistant_loop(&script, &rt, &cfg, &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        let (_, external) = delegate_result(&messages);
        assert!(
            external,
            "a child receipt from an external-labelled tool must mark the parent's result External"
        );
    }

    /// Item 9b: after a compaction the previous call's reported count is
    /// STALE (it described the pre-compaction history) and must be dropped —
    /// the next decision runs on the fresh estimate, so a short compacted
    /// history is not immediately compacted again on the old 190k number.
    #[tokio::test]
    async fn reported_count_is_reset_after_compaction_not_reused_stale() {
        let dir = tempfile::tempdir().unwrap();
        let rt = runtime_for(dir.path()).await;
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let script = WindowedScript {
            inner: CapturingScript {
                turns: vec![
                    turn_with_usage(
                        "computing",
                        json!([{ "id": "k", "name": "calculate", "arguments": { "expression": "1+1" } }]),
                        190_000,
                        10,
                    ),
                    // Reports NO usage: a stale 190k, if kept, would compact again.
                    turn(
                        "still computing",
                        json!([{ "id": "k2", "name": "calculate", "arguments": { "expression": "2+2" } }]),
                    ),
                    turn("done", json!([])),
                ],
                cursor: AtomicUsize::new(0),
                seen: Arc::clone(&seen),
            },
            window: 200_000,
        };
        let mut messages = modest_history();
        let outcome = run_assistant_loop(&script, &rt, &cfg(), &mut messages, |_| {}).await;
        assert_eq!(outcome.status, "success");
        let reqs = seen.lock().unwrap();
        assert_eq!(reqs.len(), 3);
        let notice_of = |req: &GenerateRequest| {
            req.messages
                .as_ref()
                .unwrap()
                .iter()
                .find_map(parse_compaction_notice)
        };
        let after_first = notice_of(&reqs[1]).expect("turn 2 compacts on the 190k report");
        let after_second = notice_of(&reqs[2]).expect("the notice persists");
        assert_eq!(
            after_first, after_second,
            "no second compaction: the stale 190k report must not survive the first one"
        );
    }
}