supercode-harness 0.4.17

The optional native Supercode agent and tool harness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
//! The agent loop.

use std::collections::HashSet;

use crate::config::{CachePlan, Config, SteeringMode, ToolAdvertising};
use crate::error::{Error, Result};
use crate::event::AgentEvent;
use crate::message::{ChatMessage, Role};
use crate::provider::{self, ChatRequest, OpenAiProvider, Provider, ToolSchema};
use crate::reduce::rehydrate::CAP_NOTICE_MARKER;
use crate::reduce::{self, ReductionLog, ReductionPolicy};
use crate::session::Session;
use crate::sidecar::SidecarWriter;
use crate::tools::{ToolContext, ToolRegistry};

/// BP-6: how many skill bodies one user message may pull in through `$slug`
/// mentions — Claude Code caps skill chaining at six per message (cc§7
/// "Skill chaining"); the same ceiling bounds the mention path here.
const MAX_SKILL_LOADS_PER_MESSAGE: usize = 6;

/// BP-5: how many `@path` mentions one message may attach. A prompt is not
/// a bulk loader; past this the user means `--file`.
const MAX_FILE_MENTIONS_PER_MESSAGE: usize = 10;

/// BP-5: ceiling on the bytes one `@path` mention contributes.
const MAX_FILE_MENTION_BYTES: usize = 64 * 1024;

/// Tool name of the `tool_search` agent intrinsic (B6). Never a registered
/// [`crate::tools::Tool`] — intercepted in [`Agent::run_tool`] before registry
/// lookup, so it works under any [`ToolAdvertising`] mode.
const TOOL_SEARCH: &str = "tool_search";

/// Tool name of the `expand_reduction` agent intrinsic (T12/TR-1) — the
/// model-invocable rehydration counterpart to `tool_search`, same
/// interception pattern. Advertised whenever a [`ReductionPolicy`] is
/// installed, regardless of [`ToolAdvertising`] mode (see [`Self::tool_schemas`]).
const EXPAND_REDUCTION: &str = "expand_reduction";

/// Tool name of the `sidecar_search` agent intrinsic (T12/TR-1).
const SIDECAR_SEARCH: &str = "sidecar_search";

/// Tool name of the `spawn_subagent` agent intrinsic (P5-3, §2 module 9 D1
/// "spawn tool"). Same interception pattern as [`TOOL_SEARCH`] — never a
/// registered [`crate::tools::Tool`], intercepted in [`Agent::run_tool`]
/// before registry lookup — but ALSO needs full `&mut self` async access
/// (running a whole child agent loop, or `tokio::spawn`-ing one), which
/// [`Agent::prepare_tool_call`]'s purely-synchronous intrinsics don't, so
/// the interception point is `Self::run_tool`'s top, not
/// `prepare_tool_call`.
const SPAWN_SUBAGENT: &str = "spawn_subagent";

/// BP-7 (catalog §4a "Review mode"): the `[core.prompts]` key the review
/// turn's template lives under. One name for both presets — cc spells the
/// command `/code-review`, cx spells it `/review`, and both resolve to this
/// template, so the row's evidence is one config key, not two.
pub const REVIEW_PROMPT_NAME: &str = "code-review";

/// BP-7 (catalog §4a "Side/ephemeral Q&A"): the instruction prefixed to a
/// side question, so the model knows it is answering ABOUT the session
/// rather than continuing it. The exchange never enters history either way;
/// this keeps the answer from reading like the next assistant turn.
const SIDE_QUESTION_PREAMBLE: &str = "[side question — answer from the conversation above; this exchange is not part of the conversation and you have no tools for it]";

/// Claude Code's native name for [`SPAWN_SUBAGENT`]. It is exposed only when
/// `Config::subagents_claude_agent_alias` is enabled for a Claude import.
const CLAUDE_AGENT: &str = "Agent";

/// Claude Code spellings for core filesystem/shell tools. Imported Claude
/// context frequently continues to call these names even when another model
/// is driving the turn, so emulation must translate execution as well as
/// preserve the original call/result names in the transcript.
const CLAUDE_BASH: &str = "Bash";
const CLAUDE_READ: &str = "Read";
const CLAUDE_WRITE: &str = "Write";
const CLAUDE_EDIT: &str = "Edit";
const CLAUDE_GLOB: &str = "Glob";
const CLAUDE_GREP: &str = "Grep";

/// Claude Code scheduler compatibility intrinsics. They edit an imported
/// [`crate::ClaudeRuntimeManifest`]; actual timer execution belongs to an
/// embedding scheduler driver, never this agent loop.
const CLAUDE_CRON_CREATE: &str = "CronCreate";
const CLAUDE_CRON_DELETE: &str = "CronDelete";
const CLAUDE_CRON_LIST: &str = "CronList";
const CLAUDE_SCHEDULE_WAKEUP: &str = "ScheduleWakeup";

/// Shared SDK steering mailbox. `accepting` and `queue` share one lock so a
/// turn's final boundary can close acceptance atomically with its last drain;
/// a steer can therefore never be acknowledged into the following turn.
#[derive(Default)]
pub(crate) struct SteerInbox {
    queue: std::collections::VecDeque<QueuedSteer>,
    accepting: bool,
}

struct QueuedSteer {
    message: String,
    sdk_bound: bool,
}

impl SteerInbox {
    pub(crate) fn open(&mut self) {
        self.queue.clear();
        self.accepting = true;
    }

    pub(crate) fn enqueue(&mut self, message: String) -> bool {
        if !self.accepting {
            return false;
        }
        self.queue.push_back(QueuedSteer {
            message,
            sdk_bound: true,
        });
        true
    }

    pub(crate) fn close(&mut self) {
        self.accepting = false;
        self.queue.retain(|queued| !queued.sdk_bound);
    }

    fn drain(&mut self, mode: SteeringMode) -> Option<String> {
        if self.queue.is_empty() {
            return None;
        }
        match mode {
            SteeringMode::All => Some(
                self.queue
                    .drain(..)
                    .map(|queued| queued.message)
                    .collect::<Vec<_>>()
                    .join("\n\n"),
            ),
            SteeringMode::OneAtATime => self.queue.pop_front().map(|queued| queued.message),
        }
    }

    fn drain_or_close(&mut self, mode: SteeringMode) -> Option<String> {
        if !self.queue.iter().any(|queued| queued.sdk_bound) {
            self.accepting = false;
            return None;
        }
        self.drain(mode)
    }

    fn queue_unchecked(&mut self, message: String) {
        self.queue.push_back(QueuedSteer {
            message,
            sdk_bound: false,
        });
    }

    fn len(&self) -> usize {
        self.queue.len()
    }
}

struct SteerTurnGuard {
    inbox: std::sync::Arc<std::sync::Mutex<SteerInbox>>,
}

impl SteerTurnGuard {
    fn new(inbox: std::sync::Arc<std::sync::Mutex<SteerInbox>>) -> Self {
        inbox
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .accepting = true;
        Self { inbox }
    }
}

impl Drop for SteerTurnGuard {
    fn drop(&mut self) {
        self.inbox
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .close();
    }
}

/// Tool name of the `subagent_status` agent intrinsic (P5-3, D3
/// "background+resume"): poll (and reap, once finished) a background child
/// spawned via [`SPAWN_SUBAGENT`]. Only advertised when
/// `Config::subagents_background` is on (see [`Agent::tool_schemas`]).
const SUBAGENT_STATUS: &str = "subagent_status";

/// BP-7 (catalog §4a "Background subagents + resume": cc's `SendMessage`,
/// cx's v2 mailbox `send_message`): deliver a message to a STILL-RUNNING
/// background child. Only advertised when `Config::subagents_background`
/// is on.
const SUBAGENT_MESSAGE: &str = "subagent_message";

/// BP-7 (catalog §4a "Background subagents + resume": "resumable with
/// context intact"): continue a FINISHED child with its own transcript
/// restored, rather than starting a fresh one that has to be re-briefed.
const SUBAGENT_RESUME: &str = "subagent_resume";

/// Tool name of the `background_exec` agent intrinsic (P5-6, §2 module 4
/// `tools.background` D1 "background exec"). Unlike [`SPAWN_SUBAGENT`], this
/// needs no async child-agent loop — spawning a process
/// (`tokio::process::Command::spawn`) is itself synchronous — so, like
/// [`TOOL_SEARCH`], it is intercepted in [`Agent::prepare_tool_call`], not
/// [`Agent::run_tool`].
const BACKGROUND_EXEC: &str = "background_exec";

/// Tool name of the `background_status` agent intrinsic (P5-6, D1 "monitor/
/// event feed"): poll a background job's run status, drain its newly
/// captured output as an [`AgentEvent::BackgroundOutput`] event, and reap it
/// (remove it from [`Agent::background_jobs`]) once it has exited or been
/// killed.
const BACKGROUND_STATUS: &str = "background_status";

/// Tool name of the `background_list` agent intrinsic (P5-6, D10
/// "bg-manager"): list every background job this agent is currently
/// tracking (running or finished-but-unreaped), without draining output or
/// reaping anything.
const BACKGROUND_LIST: &str = "background_list";

/// Tool name of the `background_kill` agent intrinsic (P5-6, D10
/// "bg-manager"): kill a background job's real OS process
/// (`tokio::process::Child::start_kill`) and reap it immediately.
const BACKGROUND_KILL: &str = "background_kill";

/// P4e (§3.1 `core.parallel_tool_calls`): the synchronous outcome of
/// [`Agent::prepare_tool_call`] — either a result already in hand (an
/// intrinsic, or a call refused before it ever reached `Tool::execute`), or
/// a plain registry-tool call ready for the (possibly concurrent) async
/// `execute()` step.
enum PreparedCall {
    /// A final `(output, is_error)` result — no `Tool::execute` call is
    /// coming for this one.
    Done((String, bool)),
    /// Passed every synchronous check; `execute(args, &ctx)` on the named
    /// registry tool is the only remaining step.
    Ready {
        name: String,
        args: serde_json::Value,
    },
}

/// Marker prefix of the notice [`Agent::cap_tool_output`] appends to an
/// oversized tool result kept in `history` (the recorder receives the full
/// UX-26 (B7-warn): current wall-clock time as unix milliseconds, the same
/// unit [`crate::sidecar::rfc3339_to_ms`] parses session timestamps into —
/// lets [`Agent::build_request_messages`] compare "now" against a
/// cross-process signal (a loaded session's last message timestamp) on
/// equal footing with an in-process one (this agent's own last annotated
/// send). Saturates to 0 on a pre-epoch clock rather than panicking (never
/// happens on real hardware, but `duration_since` can theoretically error).
fn now_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

/// P5-3: process-wide sequence number backing [`next_subagent_id`] —
/// disambiguates two spawns landing in the same millisecond (which
/// `now_ms()` alone cannot).
static SUBAGENT_ID_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// P5-3: a fresh, process-unique child agent id (`"agent-<hex-ts>-<hex-seq>"`
/// — the native analog of Claude Code's `agent-<id>` naming, see
/// `crate::session::SessionMeta::agent_id`'s doc comment).
fn next_subagent_id() -> String {
    let seq = SUBAGENT_ID_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    format!("agent-{:x}-{:x}", now_ms(), seq)
}

/// P5-4: the shape [`Agent::child_approval_handler_factory`]/
/// [`Agent::set_child_approval_handler_factory`] share — factored into its
/// own alias (clippy `type_complexity`) rather than spelled out inline at
/// both use sites.
type ChildApprovalHandlerFactory = dyn Fn(
        String,
        std::sync::Arc<std::sync::Mutex<Vec<crate::subagents::QueuedApproval>>>,
    ) -> std::sync::Arc<dyn crate::permissions::PermissionsApprovalHandler>
    + Send
    + Sync;

/// BP-4 (catalog:109 "Context-usage introspection"): the live
/// context-window accounting [`Agent::context_usage`] reports — cc's
/// `/context` grid and cx's `/status` + `get_context_remaining` in one
/// shape, over the numbers `resume --dry-run`'s preflight already computes.
///
/// Every token figure is the SAME estimate the context guard enforces
/// (`crate::tokens`), so what this reports and what refuses an oversized
/// turn can never disagree.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ContextUsage {
    /// The model the accounting is against.
    pub model: String,
    /// Messages in the projected request view (reduction stubs included).
    pub messages: usize,
    /// Estimated tokens for those messages.
    pub message_tokens: u64,
    /// Tools advertised on the next request.
    pub tool_count: usize,
    /// Estimated tokens for the serialized tool-schema array — a real part
    /// of the wire request, and the half a message-only count misses.
    pub tool_schema_tokens: u64,
    /// `message_tokens + tool_schema_tokens`.
    pub request_tokens: u64,
    /// `request_tokens` with the guard's safety margin applied — the figure
    /// the context guard actually compares.
    pub projected_tokens: u64,
    /// Headroom the guard reserves for the model's own reply.
    pub response_reserve_tokens: u64,
    /// The model's context window, when known.
    pub context_limit: Option<u64>,
    /// Tokens still available after the reply reserve, `0` when unknown.
    pub remaining_tokens: u64,
    /// `projected_tokens` as a whole percentage of the window (rounded),
    /// `0` when the window is unknown. An integer so this whole struct
    /// stays `Eq`-comparable on the frontend wire.
    pub used_pct: u32,
    /// Whether the next request would pass the context guard.
    pub fits: bool,
}

impl ContextUsage {
    /// One human line, the shape a `/context` command prints.
    pub fn summary_line(&self) -> String {
        match self.context_limit {
            Some(limit) => format!(
                "{} · {}% of {} used ({} projected, {} left) · {} messages {} · {} tool schemas {}",
                self.model,
                self.used_pct,
                crate::tokens::fmt_approx_tokens(limit),
                crate::tokens::fmt_approx_tokens(self.projected_tokens),
                crate::tokens::fmt_approx_tokens(self.remaining_tokens),
                self.messages,
                crate::tokens::fmt_approx_tokens(self.message_tokens),
                self.tool_count,
                crate::tokens::fmt_approx_tokens(self.tool_schema_tokens),
            ),
            None => format!(
                "{} · context window unknown · {} projected · {} messages {} · {} tool schemas {}",
                self.model,
                crate::tokens::fmt_approx_tokens(self.projected_tokens),
                self.messages,
                crate::tokens::fmt_approx_tokens(self.message_tokens),
                self.tool_count,
                crate::tokens::fmt_approx_tokens(self.tool_schema_tokens),
            ),
        }
    }
}

/// A stateful agent: configuration, a model transport, a tool set, and the
/// running conversation. Drive it with [`Agent::send`].
/// BP-13 — one hop the run loop's failure-fallback pass performed: the
/// model it was on, the model it moved to, and the provider failure that
/// made it move.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FallbackHop {
    /// The model that failed.
    pub from: String,
    /// The next chain entry, which the request was re-sent against.
    pub to: String,
    /// The failure, rendered — the record's `reason`.
    pub reason: String,
}

/// BP-13 — whether `error` is the kind of failure ANOTHER MODEL could
/// plausibly answer, i.e. one the fallback chain exists for.
///
/// Deliberately narrow: rate limiting (429) and server-side failures (5xx,
/// which is where "overloaded" lives) are properties of the model/endpoint
/// that was asked, so asking a different one is a real remedy. Everything
/// else — a bad request, a refused key, a decode failure, a tool error —
/// is the CALLER's problem and would fail identically against every entry
/// in the chain, so walking it would only multiply the same error by three.
/// The transport's own retry (`OpenAiProvider::send_with_retry`) has
/// already run and given up by the time this is consulted.
pub fn is_failover_worthy(error: &Error) -> bool {
    matches!(error, Error::Provider { status, .. } if *status == 429 || *status >= 500)
}

pub struct Agent {
    config: Config,
    provider: std::sync::Arc<dyn Provider>,
    registry: ToolRegistry,
    history: Vec<ChatMessage>,
    ctx: ToolContext,
    /// Cumulative output (completion) tokens across every `send` on this agent.
    total_output_tokens: u64,
    /// Names of non-core tools discovered via `tool_search` (B6): advertised
    /// starting with the *next* request once populated.
    activated_tools: HashSet<String>,
    /// The live sidecar writer (A3), if this agent is recording. `None` is
    /// today's behavior, at zero cost: every append point becomes a no-op.
    recorder: Option<SidecarWriter>,
    /// BP-8 (catalog:150 "Append-only durable transcript"): the live
    /// append-only journal, if one is installed
    /// ([`Self::set_journal`], armed by the caller when
    /// [`Config::session_append_only`] is on). Behind an `Arc<Mutex<_>>`
    /// rather than owned outright because the queue doors
    /// ([`Self::queue_steer`]) take `&self` — a pending input has to be
    /// recorded from a shared handle while a turn holds `&mut Agent`.
    /// `None` (the default) is a no-op at every append point: today's
    /// behavior, no file created.
    journal: Option<std::sync::Arc<std::sync::Mutex<crate::session_journal::SessionJournal>>>,
    /// BP-8 (catalog:151 "In-place conversation tree"): the live
    /// `SessionTree` for this session, materialized when
    /// [`Config::session_tree_enabled`] is on. Every recorded message
    /// becomes a node, and [`Self::rewind_conversation`] moves the active
    /// branch's leaf — the tree is what makes a rewind lossless (the old
    /// leaf is preserved under a sibling branch) rather than a truncation.
    /// `None` (the default, and every preset that leaves the module off) is
    /// zero cost: nothing is built and nothing is persisted.
    session_tree: Option<crate::session_tree::SessionTree>,
    /// BP-8 (catalog:152 "Rewind/rollback conversation"): tails removed by
    /// rewinds that have not been undone, newest last. Restored from the
    /// journal on resume, so "undo the rewind" survives a restart.
    rewind_undo: Vec<Vec<ChatMessage>>,
    /// BP-8 (catalog:156): the plan as last written to the journal —
    /// compared against `ctx.plan` so an unchanged plan is not re-journaled
    /// on every loop iteration.
    journaled_plan: Vec<crate::session_journal::PlanEntry>,
    /// Reversible reduction policy (A5/A7/A10). `None` is today's behavior,
    /// at zero cost: every provider request is built from `self.history`
    /// verbatim, exactly as before this landed.
    reduction_policy: Option<ReductionPolicy>,
    /// The accumulating reduction log (A5): fed back into
    /// [`reduce::project_messages`] on every request-build so already-applied
    /// reductions reproduce verbatim across turns and `send` calls (prefix
    /// stability). `history` itself is never touched by this — see
    /// `Self::run_loop`.
    reduction_log: ReductionLog,
    /// B7: length of the stable, byte-identical-across-turns prefix at the
    /// front of [`Self::history`] — this agent's own system message plus
    /// every message of a previously-imported session — set by
    /// [`Self::load_session`]. `None` (the default) means no session has been
    /// loaded, so [`crate::provider::apply_cache_plan`] has nothing to
    /// annotate even under [`CachePlan::ImportedPrefix`].
    imported_prefix_len: Option<usize>,
    /// BP-11: set for the duration of a `/compact` so the `pre_compact`
    /// observer can tell a manual compaction from an automatic trigger.
    compacting_manually: bool,
    /// BP-4 (catalog:90 "Environment context block", cx§2 "re-emitted on
    /// change"): the `# Environment` block currently spliced into
    /// `history[0]`, verbatim — `None` when `core.env_context` is off (or
    /// on a construction path that assembles no prompt). Kept so
    /// [`Self::refresh_env_context`] can locate and replace exactly this
    /// text when cwd, approval/sandbox policy or the git branch moves
    /// mid-session, instead of leaving the model reading a block that
    /// stopped being true.
    env_context_live: Option<String>,
    /// BP-5 (catalog D2 "Per-model-family base-prompt selection"): the base
    /// system prompt currently spliced at the head of `history[0]`,
    /// verbatim. Kept for the same reason [`Self::env_context_live`] is:
    /// when the model changes ([`Self::set_model`]) the family's prompt
    /// changes with it, and the stale text has to be located and REPLACED
    /// rather than left in front of the new model.
    base_prompt_live: String,
    /// BP-5 (catalog D2 "Shell-output injection in templates/skills"): the
    /// permission-engine authorization every `` !`cmd` `` in a skill or
    /// command body runs under. Inert (executes nothing) unless
    /// `[core.skills] shell_injection` is on.
    shell_injection: crate::skills::ShellInjection,
    /// BP-4 (catalog:91): blocks spliced into the context AFTER
    /// construction — see [`Self::inject_context_block`] and
    /// [`crate::context_injection`]. Empty by default, at zero cost.
    spliced_context_blocks: Vec<crate::config::ContextInjectionBlock>,
    /// TR-7 (T20): the injectable side-call ([`reduce::summarize::SpanSummarizer`])
    /// used to summarize an A10 `TurnsCleared` span, if one is installed
    /// ([`Self::set_span_summarizer`]). `None` is today's behavior, at zero
    /// cost: `Self::build_request_messages` never calls
    /// [`reduce::prepare_cleared_turns_summary`] without one, so
    /// `policy.summarize_cleared_turns` being on with no summarizer
    /// installed behaves exactly like it being off (deterministic stub only)
    /// — never a panic, never a blocked request.
    span_summarizer: Option<std::sync::Arc<dyn reduce::summarize::SpanSummarizer + Send + Sync>>,
    /// TR-8 (T5): the tool-schema tier signature (global knob + per-tool
    /// overrides) as of the last request this agent built, or `None` before
    /// the first request. Compared against the CURRENT signature at the top
    /// of every `Self::build_request_messages` call so a tier change made
    /// mid-session (via [`Self::set_schema_tier`] /
    /// [`Self::set_tool_schema_tier`]) is detected and flagged to the B7
    /// cache planner as a cache-bust event (`provider::tier_change_is_cache_bust`).
    last_tool_schema_tier_signature: Option<u64>,
    /// PARITY-18 D4 — the target model's context-window size, if the caller
    /// has armed the guard via [`Self::set_context_limit`]. `None` (the
    /// default) means no guard: every request is sent unconditionally.
    /// CLI entry points arm it for their resolved model; direct SDK callers
    /// retain explicit control through [`Self::set_context_limit`].
    /// Once set, `Self::run_loop` re-checks
    /// [`crate::tokens::context_guard`] before EVERY request it builds —
    /// not just the first — so "never sends an over-context request" holds
    /// for the whole session, not only a one-shot preflight.
    context_limit: Option<u64>,
    /// PARITY-18 D3 — becomes `true` the first time `Self::run_loop`
    /// actually reaches its real send site (immediately before
    /// [`Provider::complete`]). Exposed via [`Self::request_issued`] so a
    /// caller can report "request sent" truthfully — never asserted ahead
    /// of time, so a pre-delivery failure (guard refusal, a build error) or
    /// an interactive session that quits before any turn completes is
    /// reported honestly as "not sent".
    requests_issued: bool,
    /// UX-26 (B7-warn): unix-ms wall-clock time this agent last knew the
    /// active [`CachePlan::ImportedPrefix`] breakpoint to be warm. Seeded by
    /// [`Self::load_session`] from the just-loaded session's OWN last
    /// message timestamp (`metadata["timestamp"]`, parsed via
    /// [`crate::sidecar::rfc3339_to_ms`]) — a cross-process signal: how long
    /// the resumed conversation has sat idle since ANY tool last touched it,
    /// which is exactly when Anthropic's server-side cache entry (if one
    /// ever existed) was last capable of being warm. Refreshed to "now"
    /// every time `Self::run_loop` actually sends a cache-annotated
    /// request (an in-process signal: idle time between this agent's own
    /// turns). `None` when no imported prefix exists yet, or the loaded
    /// session's last message carries no parseable timestamp — never
    /// guessed, so the TTL check in [`provider::cache_cold_reason`] simply
    /// doesn't fire rather than risk a false positive.
    last_cache_activity_ms: Option<i64>,
    /// UX-26: whether a PRIOR request already carried a cache_control
    /// annotation for the current [`Self::imported_prefix_len`] — i.e.
    /// whether reuse is genuinely "expected" on the NEXT annotated request.
    /// `false` until the first annotated request goes out (that one is
    /// establishing the cache entry, a legitimate write, never a "miss") and
    /// reset to `false` by [`Self::load_session`] whenever the imported
    /// prefix itself changes.
    cache_established: bool,
    /// UX-26 scratch: this turn's cache-warmth context, computed once at the
    /// top of `Self::build_request_messages` (before the request is sent,
    /// while `effective_cache_plan`/`busted` are in scope) and consumed once
    /// in `Self::run_loop` right after `usage` comes back — never read
    /// across turns, so a stale value can't leak. `(will_annotate,
    /// cache_established, idle_secs)` — see [`provider::cache_cold_reason`]
    /// for what each of the first two independently gates.
    pending_cache_turn: (bool, bool, Option<i64>),
    /// P4b: the injectable auto-title side-call ([`Self::set_session_titler`]),
    /// mirroring `Self::span_summarizer`'s "installing one alone changes
    /// nothing" contract — `Config::auto_title` is the actual gate a caller
    /// consults before invoking [`Self::auto_title`].
    session_titler: Option<std::sync::Arc<dyn crate::session_title::SessionTitler + Send + Sync>>,
    /// P4b (§1.6, catalog §4a "persisted per-turn usage records"): every
    /// [`crate::usage_log::UsageRecord`] recorded so far this agent's
    /// lifetime. Always accumulated (cheap, small) regardless of whether a
    /// caller ever persists it — see [`Self::usage_records`]/
    /// [`Self::save_usage_log`].
    usage_log: Vec<crate::usage_log::UsageRecord>,
    /// P4b: 0-based index of the NEXT model round-trip, for
    /// [`crate::usage_log::UsageRecord::turn`].
    turn_index: usize,
    /// BP-7 (catalog §4a "Turn/step bracketing records"): the per-round-trip
    /// marker log — context/usage/finish brackets plus the retry, abort,
    /// effort and goal markers. Persisted beside the session as
    /// `<name>.events.jsonl` (see [`Self::save_turn_records`]).
    turn_records: Vec<crate::turn_record::TurnRecord>,
    /// BP-7: retries the transport reported, drained after every
    /// `complete()` so each notice attaches to the round-trip that produced
    /// it. Only the HTTP provider built by [`Self::new`] writes into this;
    /// an injected provider simply never records anything.
    retry_log: std::sync::Arc<crate::provider::RetryLog>,
    /// BP-7 (catalog §4a "Per-turn cost/usage accounting", "Turn/budget
    /// caps"): the price to bill this agent's model at, resolved at
    /// construction from [`Config::price_input_per_mtok`]/
    /// [`Config::price_output_per_mtok`] or [`crate::pricing`]'s table, and
    /// re-resolved by [`Self::set_model`]. `None` = unpriceable, so no cost
    /// is recorded (never a guess).
    model_price: Option<crate::pricing::ModelPrice>,
    /// BP-7: dollars this agent has spent across its whole lifetime — the
    /// counter [`Config::max_budget_usd`] is measured against.
    total_cost_usd: f64,
    /// BP-7: tool calls this agent has executed across its whole lifetime —
    /// the counter [`Config::max_steps`] is measured against.
    total_steps: usize,
    /// BP-7 (catalog §4a "Background subagents + resume"): a finished
    /// child's post-system-prompt transcript, kept after the reap so
    /// `subagent_resume` can restore its context in-process. A session
    /// with a subagent store attached also has it on disk; this makes
    /// resume work for an embedder that never attached one.
    reaped_subagents: std::collections::HashMap<String, Vec<ChatMessage>>,
    /// BP-7 (catalog §4a "Goals"): the session's standing objective, when
    /// `capabilities.todos.goals` is on and one has been set. Restated at
    /// the TAIL of every request while it stands (see
    /// [`crate::goals::GoalRecord::reminder`]) and persisted as
    /// `<session>.goal.json` — never written into `history`, so the
    /// transcript stays exactly what the conversation was.
    goal: Option<crate::goals::GoalRecord>,
    /// P4b (§1.7/§3.1 `core.steering`, pi§3 semantics): queued mid-turn
    /// steering messages — drained at the top of `Self::run_loop`'s next
    /// iteration (pi's "steer = after current tool calls"). Empty by
    /// default, at zero cost: `Self::run_loop` skips the drain entirely
    /// when empty.
    steer_queue: std::sync::Arc<std::sync::Mutex<SteerInbox>>,
    /// P4b: queued follow-up messages — drained only once the loop is
    /// otherwise idle (pi's "follow-up = at idle"), i.e. exactly the point
    /// `Self::run_loop` would otherwise return a final answer.
    follow_up_queue: std::collections::VecDeque<String>,
    /// P4c (§5.2 P4 "doom-loop breaker", §3.1 `core.doom_loop_threshold`):
    /// `(tool name, canonical JSON args)` of the most recent tool call, if
    /// [`Config::doom_loop_threshold`] is armed — `None` before the first
    /// call this agent has run. See [`Self::check_doom_loop`].
    doom_loop_last_call: Option<(String, String)>,
    /// P4c: how many times [`Self::doom_loop_last_call`] has repeated
    /// consecutively so far (starts at 1 on the call that SET it).
    doom_loop_streak: u32,
    /// P4c (§1.10/§3.1 `core.model_switch.allow_switch`): every
    /// [`crate::model_change::ModelChangeRecord`] [`Self::switch_model`] has
    /// created so far this agent's lifetime. Always empty when
    /// `Config::model_switch_allow_switch` is off (the default) or no
    /// switch has happened yet.
    model_change_log: Vec<crate::model_change::ModelChangeRecord>,
    /// P4e (§1.6/§3.1 `core.session.git_metadata`, catalog:331): captured
    /// once at construction when [`Config::session_git_metadata`] is on;
    /// `None` when the gate is off (the default) or the best-effort git
    /// probe found nothing (not a repo, `git` missing). See
    /// [`Self::git_metadata`]/[`Self::save_git_metadata`].
    git_metadata: Option<crate::git_metadata::GitMetadataRecord>,
    /// P5-1 (§2.10, session-scoped "approve for session" cache): populated
    /// only when a [`crate::permissions::PermissionsApprovalHandler`]
    /// returns [`crate::permissions::ApprovalOutcome::AllowForSession`] —
    /// see [`Self::prepare_tool_call`]'s `Config::permissions_enabled`
    /// branch. Always constructed (cheap, empty) regardless of whether the
    /// engine is ever active — the same "zero cost when off" posture as
    /// [`Self::doom_loop_last_call`].
    permissions_approval_cache: crate::permissions::ApprovalCache,
    /// P5-1: the non-interactive decision seam a caller installs via
    /// [`Self::set_permissions_approval_handler`] — mirrors
    /// `Self::span_summarizer`/[`Self::session_titler`]'s "installing one
    /// alone changes nothing, `Config::permissions_enabled` is the actual
    /// gate" pattern. `None` (the default) means every `Ask`-tier decision
    /// is denied (fail-closed — see
    /// `crate::permissions::approval::PermissionsApprovalHandler`'s doc
    /// comment).
    permissions_approval_handler:
        Option<std::sync::Arc<dyn crate::permissions::PermissionsApprovalHandler>>,
    /// P5-2 (§2 module 15 D7 row 4 "prompts-as-commands"): MCP server
    /// prompts registered via [`Self::register_mcp_prompt`], keyed by their
    /// ALREADY-NAMESPACED command name (`mcp__<server>__<prompt>` — see
    /// [`crate::mcp::McpPromptSource`]'s doc comment for why that namespace
    /// is what keeps an untrusted server's prompt from ever colliding with
    /// a trusted `Config::prompts` entry). Empty by default, at zero cost:
    /// [`Self::expand_prompt_async`] only consults this after
    /// `Config::prompts` finds no match.
    mcp_prompts: std::collections::HashMap<String, Box<dyn crate::sdk::SdkPromptSource>>,
    /// BP-6 (catalog D2 "Skills (progressive-disclosure packages)", D7
    /// "Skill discovery from multiple roots"): the SKILL.md packages
    /// discovered for this config, frontmatter only — name, description,
    /// version and the manifest path. Never a body: a body is read from
    /// disk on invocation (`/name`, `/skill:name`, a `$slug` mention, or
    /// the `skill` tool) and nowhere else. Empty unless `[core.skills]` is
    /// on AND names a harness whose roots to read.
    skills: Vec<crate::skills::LoopSkill>,
    /// P5-3 (§2 module 9): how deep in the spawn tree THIS agent is — `0`
    /// for a top-level agent. Set from [`Config::subagent_depth`] at
    /// construction; `Self::run_spawn_subagent` builds a child `Config`
    /// with `subagent_depth = self.subagent_depth + 1` and ALSO overwrites
    /// the freshly-built child `Agent`'s own field to match (belt-and-
    /// suspenders — the child never has to trust its own `Config` alone).
    subagent_depth: usize,
    /// P5-3 (resource bound, "must not fork-bomb"): the shared, tree-wide
    /// concurrency gauge every spawn (this agent's own, and every
    /// descendant's) increments/decrements against
    /// (`crate::subagents::try_acquire`/`ConcurrencyGuard`). A TOP-level
    /// agent gets a fresh `Arc::new(AtomicUsize::new(0))` at construction;
    /// `Self::run_spawn_subagent` clones this SAME `Arc` into every child it
    /// spawns (never a fresh one), so a cap of N holds across the WHOLE
    /// tree regardless of its branching shape — a parent with 3 children
    /// each spawning 3 more shares one counter, not nine independent ones.
    subagent_concurrency_gauge: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    /// P5-3 (D3 "background+resume"): background subagents this agent has
    /// spawned and not yet reaped via `subagent_status`, keyed by their
    /// `child_agent_id`. Each entry's `JoinHandle` moves its own
    /// [`crate::subagents::ConcurrencyGuard`] into the spawned task, so the
    /// concurrency slot is held for exactly as long as the child is
    /// actually running, independent of whether/when the parent polls.
    background_subagents: std::collections::HashMap<String, BackgroundSubagent>,
    /// P5-3 (§2.2 C6 "parent-surfaced queue"): approval requests a
    /// `background_prompts = "parent"` child raised, queued here rather
    /// than blocking (see [`crate::subagents::QueuedApproval`]'s doc
    /// comment — each is already resolved `Deny` by the time it lands
    /// here). Exposed read-only via [`Self::pending_child_approvals`].
    /// Always constructed (cheap, empty) regardless of whether background
    /// spawning is ever used, same "zero cost when off" posture as
    /// [`Self::permissions_approval_cache`].
    pending_child_approvals:
        std::sync::Arc<std::sync::Mutex<Vec<crate::subagents::QueuedApproval>>>,
    /// P5-4 (tui, closes the P5-3 §2.2 C6 deferred chain — see
    /// [`crate::subagents::ParentQueueApprovalHandler`]'s doc comment for
    /// the "never blocks" contract this OVERRIDES only when a factory is
    /// installed): when `Some`, `Self::run_spawn_subagent` uses THIS
    /// factory — instead of constructing the default never-blocking
    /// [`crate::subagents::ParentQueueApprovalHandler`] — to build the
    /// `PermissionsApprovalHandler` a `background_prompts = "parent"`
    /// child gets. Installed via
    /// [`Self::set_child_approval_handler_factory`] by a `tui` embedder
    /// that wants queued child approvals to be genuinely ANSWERABLE
    /// (blocks the child's tool call until the parent resolves it, or
    /// denies if the factory's handler's channel is ever dropped/closed —
    /// still fail-closed, never a hang past process lifetime). `None` (the
    /// default) preserves P5-3's shipped behavior byte-for-byte: every
    /// `background_prompts = "parent"` child still gets the immediate-deny
    /// `ParentQueueApprovalHandler`, and [`Self::pending_child_approvals`]
    /// stays exactly the read-only audit view it already is.
    child_approval_handler_factory: Option<std::sync::Arc<ChildApprovalHandlerFactory>>,
    /// P5-3 (D5 "subagent transcripts… persisted + linked"): an optional
    /// `(store, this agent's own session name)` pair installed via
    /// [`Self::set_subagent_store`] — mirrors [`Self::set_recorder`]/
    /// [`Self::set_span_summarizer`]'s "installing one alone changes
    /// nothing" pattern. `None` (the default) means a spawned child's
    /// transcript/lineage is still joined back into THIS agent's context
    /// (the foreground/background mechanics work either way) but nothing
    /// is written to a [`crate::store::SessionStore`] — no behavior change
    /// for any caller that never installs one (e.g. every pre-P5-3 caller).
    subagent_store: Option<(std::sync::Arc<crate::store::SessionStore>, String)>,
    /// Imported Claude runtime state. The manifest can be paused or active,
    /// but this Agent contains no scheduler or timer handle; an embedding
    /// driver owns execution and persistence.
    claude_runtime_manifest: Option<crate::claude_runtime_state::ClaudeRuntimeManifest>,
    /// P5-6 (§2 module 4 `tools.background`, D10 "bg-manager"): background
    /// OS processes spawned via `background_exec`, keyed by job id, tracked
    /// until reaped (a terminal `background_status` poll, or an explicit
    /// `background_kill`) — see [`BackgroundJob`]'s doc comment. Always
    /// constructed (cheap, empty), same "zero cost when off" posture as
    /// [`Self::background_subagents`].
    background_jobs: std::collections::HashMap<String, BackgroundJob>,
    /// P5-6 (resource bound, mirroring [`Self::subagent_concurrency_gauge`]'s
    /// own precedent): the shared concurrency gauge every `background_exec`
    /// call on this agent increments/decrements against
    /// (`crate::subagents::try_acquire`/`ConcurrencyGuard` — reused
    /// verbatim, a second independent gauge instance scoped to background
    /// JOBS rather than subagent SPAWNS).
    background_concurrency_gauge: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    /// P5-9 (§2 module 20 `checkpoint`): the write-path-interception
    /// observer installed on [`Self::ctx`]'s `write_observer` (as a
    /// `dyn WriteObserver`), held here ADDITIONALLY as its concrete type so
    /// `Self::run_loop` can call
    /// [`crate::checkpoint::CheckpointObserver::begin_turn`] once per turn.
    /// `None` when `Config::checkpoint_enabled` is `false` (the default) or
    /// the shadow store failed to open — see
    /// [`crate::checkpoint::observer_for_config`].
    checkpoint_observer: Option<std::sync::Arc<crate::checkpoint::CheckpointObserver>>,
    /// P5-11 (§2 module 28 `lsp`): the LSP server registry installed (via
    /// `crate::lsp::LspDiagnosticsObserver`) on `Self::ctx`'s
    /// `write_observer` chain, held here ADDITIONALLY as its concrete type
    /// so `impl Drop for Agent` can reach
    /// [`crate::lsp::LspManager::kill_all_sync`] (no orphaned language-
    /// server processes) and a clean-exit caller can reach
    /// [`crate::lsp::LspManager::shutdown_all`] for a graceful handshake.
    /// `None` when `Config::lsp_enabled` is `false` (the default).
    lsp_manager: Option<std::sync::Arc<crate::lsp::LspManager>>,
}

/// P5-6 (§2 module 4 `tools.background`): one background-spawned OS process
/// this agent is tracking, awaiting a `background_status`/`background_list`
/// poll (or `background_kill`/agent drop) to reap or terminate it.
///
/// **Real process, not a child agent.** Unlike [`BackgroundSubagent`] (which
/// wraps a whole recursive child [`Agent`] loop against the SAME mock/real
/// provider), this wraps a plain OS subprocess spawned via
/// `crate::tools::build_sandboxed_sh` — the exact function
/// [`crate::tools::BashTool::execute`] itself calls, so a background
/// command gets byte-identical sandboxing/cwd/env handling to a foreground
/// `bash` call (build brief: "reuse the bash tool's execution + sandbox
/// path").
struct BackgroundJob {
    /// The live process handle — kept directly on the job (not moved into a
    /// spawned task) so [`Agent::run_background_status`]/
    /// [`Agent::run_background_list`] can call the SYNCHRONOUS,
    /// non-blocking `Child::try_wait` to observe exit status, and
    /// [`Agent::run_background_kill`]/[`impl Drop for Agent`] can call the
    /// SYNCHRONOUS `Child::start_kill` for a REAL process kill — never just
    /// a `tokio::task::JoinHandle::abort` (which would only cancel a Rust
    /// future, not the OS process it spawned). `kill_on_drop(true)` was set
    /// at spawn time as defense-in-depth: even a `BackgroundJob` dropped
    /// through some path OTHER than the explicit kill call sites below
    /// still kills its child (a documented tokio behavior; a no-op if the
    /// process already exited).
    child: tokio::process::Child,
    /// The exact command text this job is running — the SAME text that was
    /// already checked against the permissions engine at spawn time (see
    /// [`Agent::background_permission_denial`]).
    command: String,
    /// The OS process id, captured once at spawn time (before `child` is
    /// ever mutated) — surfaced in every status/list/kill result, and the
    /// only thing an OUTSIDE observer (e.g. a test proving real
    /// termination) needs to check liveness independent of this process's
    /// own bookkeeping.
    pid: Option<u32>,
    /// Bounded, incrementally-appended combined stdout+stderr capture —
    /// written to by the reader tasks [`Agent::run_background_exec`] spawns
    /// right after `child.stdout`/`child.stderr` are taken, read by every
    /// status/list poll. Shared via `Arc` since the reader tasks outlive
    /// this method call.
    output: std::sync::Arc<crate::background::CapturedOutput>,
    /// Unix-ms wall-clock time the spawn happened.
    started_at_ms: i64,
    /// Set by [`Agent::run_background_kill`] — [`Agent::run_background_status`]/
    /// [`Agent::run_background_list`] report [`crate::background::JobStatus::Killed`]
    /// unconditionally once this is `true`, rather than racing
    /// `Child::try_wait` to see whether the kill signal has landed yet.
    killed: bool,
    /// The concurrency-gauge slot this job holds for as long as it remains
    /// in [`Agent::background_jobs`] — dropped (freeing the slot) when this
    /// `BackgroundJob` is removed from the map (a terminal reap, or an
    /// explicit kill), exactly mirroring [`BackgroundSubagent`]'s own
    /// "guard held for as long as it's tracked, not just while the process
    /// is alive" posture (§2 module 9 precedent, kept consistent here).
    _guard: crate::subagents::ConcurrencyGuard,
}

/// P5-6: the non-blocking status read [`Agent::run_background_status`]/
/// [`Agent::run_background_list`] share — `job.killed` (set by
/// [`Agent::run_background_kill`]) always wins over a fresh `try_wait`,
/// since a kill signal racing the OS reaping the process is otherwise
/// indistinguishable from "still running" for one poll cycle; reporting
/// `Killed` unconditionally once requested avoids that race entirely. A
/// `try_wait` error (would only happen if this job's id were somehow
/// double-reaped, which the map ownership below already prevents) is
/// treated as "no news yet" — `Running` — rather than inventing a made-up
/// exit code.
fn background_job_status(job: &mut BackgroundJob) -> crate::background::JobStatus {
    if job.killed {
        return crate::background::JobStatus::Killed;
    }
    match job.child.try_wait() {
        Ok(Some(status)) => crate::background::JobStatus::Exited(status.code()),
        Ok(None) | Err(_) => crate::background::JobStatus::Running,
    }
}

/// Fable-5 review (HIGH, "grandchildren orphaned on kill AND agent-drop"):
/// the shared real-kill body for both [`Agent::run_background_kill`] and
/// `impl Drop for Agent` — sends `SIGKILL` to `job`'s ENTIRE process group,
/// not just the one directly-tracked pid, so a surviving `&` job, pipeline
/// stage, or double-forking daemon spawned by the job is killed too, then
/// reaps the group leader so it doesn't linger as a zombie.
///
/// Relies on the spawn site (`Agent::run_background_exec`) having put the
/// job in its OWN new process group via `Command::process_group(0)` — which
/// makes the leader's pgid equal to its own pid, so `job.pid` doubles as the
/// group id here.
#[cfg(unix)]
fn kill_job_process_group(job: &mut BackgroundJob) {
    if let Some(pid) = job.pid {
        // SAFETY: `libc::kill` with a negative pid is `killpg` — it only
        // ever sends a signal (never dereferences memory), so this is safe
        // regardless of whether the group is still alive. A `-1`/`ESRCH`
        // return means the leader (and thus the whole group, since a group
        // can't outlive its leader) already exited — not an error, just
        // "already dead", exactly like `Child::start_kill`'s own documented
        // no-op-on-already-exited contract.
        unsafe {
            libc::kill(-(pid as libc::pid_t), libc::SIGKILL);
        }
    }
    // Belt-and-suspenders for the leader itself — `kill_on_drop(true)` set
    // at spawn time is the same outcome via a different (implicit) path —
    // then reap it so the SIGKILL we just delivered doesn't leave a zombie
    // behind.
    let _ = job.child.start_kill();
    let _ = job.child.try_wait();
}

/// Non-unix fallback: no portable process-group primitive is wired up here
/// (same posture as `crate::tools::build_sandboxed_sh`'s own platform
/// split) — falls back to the pre-fix per-child kill. A background job that
/// spawns a surviving grandchild process on a non-Unix target is a
/// documented residual, not silently claimed fixed by this cfg arm.
#[cfg(not(unix))]
fn kill_job_process_group(job: &mut BackgroundJob) {
    let _ = job.child.start_kill();
}

/// P5-6 (D1 "monitor/event feed", "output captured incrementally +
/// BOUNDED"): spawn a fire-and-forget reader task that continuously drains
/// `reader` (a piped `ChildStdout`/`ChildStderr`) into `output`, bounded at
/// `cap` bytes. Reading NEVER stops at the cap — only what's RETAINED is
/// bounded ([`crate::background::CapturedOutput::append`]'s own contract)
/// — because a background job's child process would otherwise block
/// forever writing to a full, undrained OS pipe once this stopped reading
/// it, silently hanging real work behind an apparently-"running" job. The
/// task exits on its own once the pipe reaches EOF (the process closed the
/// descriptor, whether by exiting or being killed) — no explicit
/// abort/cleanup call site is needed; a detached `tokio::spawn` this short-
/// lived is not the kind of orphaned-task risk `impl Drop for Agent`'s own
/// doc comment is about (that one concerns a whole recursive provider-
/// calling child AGENT loop, not a bounded byte-copy loop that ends the
/// instant its source pipe closes).
fn spawn_output_reader<R>(
    reader: R,
    output: std::sync::Arc<crate::background::CapturedOutput>,
    cap: usize,
) -> tokio::task::JoinHandle<()>
where
    R: tokio::io::AsyncRead + Unpin + Send + 'static,
{
    tokio::spawn(async move {
        use tokio::io::AsyncReadExt;
        let mut reader = reader;
        let mut buf = [0u8; 8192];
        loop {
            match reader.read(&mut buf).await {
                Ok(0) => break,
                Ok(n) => {
                    let chunk = String::from_utf8_lossy(&buf[..n]);
                    output.append(&chunk, cap);
                }
                Err(_) => break,
            }
        }
    })
}

/// BP-7 (catalog §4a "Named agent definitions as data"): merge
/// `<cwd>/.claude/agents/*.md` into `config.subagents_definitions`.
///
/// Runs for every `Agent` whose `subagents` module is on, whatever preset
/// it came from — before BP-7 the `.md` loader was reachable only from the
/// Claude emulate/resume path, so a cc-parity or cx-parity session ignored
/// definitions sitting right there in the repo.
///
/// * A no-op when the module is off (the default), and for every spawned
///   CHILD (`subagent_depth > 0`), which already inherits its parent's
///   resolved definitions verbatim.
/// * A config-table entry WINS over a discovered file of the same name:
///   `[capabilities.subagents.agents.<name>]` is explicit configuration,
///   the file is discovery.
/// * A malformed file is skipped with a warning, never a failed
///   construction: `Agent::with_provider` has no error channel, and a
///   broken agent file in some repo must not make the harness unusable
///   there. (The emulate/resume path keeps its own strict behavior, where
///   a definition the resumed session may depend on going missing IS worth
///   failing over.)
fn merge_project_agent_definitions(config: &mut Config) {
    if !config.subagents_enabled || config.subagent_depth > 0 {
        return;
    }
    match crate::claude_compat::load_project_agents(&config.cwd) {
        Ok(agents) => {
            for agent in agents {
                config
                    .subagents_definitions
                    .entry(agent.definition.name.clone())
                    .or_insert(agent.definition);
            }
        }
        Err(e) => {
            tracing::debug!(
                error = %e,
                "skipping .claude/agents discovery: a definition file could not be parsed"
            );
        }
    }
}

/// P5-3: one background-spawned child this agent is tracking, awaiting a
/// `subagent_status` poll (or agent drop) to reap it.
struct BackgroundSubagent {
    /// Resolves to `(child_agent_id, child's final result, the child's own
    /// post-system-prompt history — for D5 transcript persistence once
    /// reaped)` — the concurrency-guard slot for this child is held INSIDE
    /// the spawned future (moved in at spawn time), so it releases the
    /// instant the child's own run loop finishes, not when the parent gets
    /// around to polling.
    handle: tokio::task::JoinHandle<(String, Result<String>, Vec<ChatMessage>)>,
    /// The task/prompt text the child was spawned with (surfaced by a
    /// `"pending"` status poll, since the handle alone can't answer "what
    /// is it doing").
    task: String,
    /// The named `agent_type` spawned, if any.
    agent_type: Option<String>,
    /// Unix-ms wall-clock time the spawn happened.
    started_at_ms: i64,
    /// BP-7 (catalog §4a "Background subagents + resume"): the child's own
    /// steering inbox, captured before the child moved into its task.
    ///
    /// This IS the mailbox. `SteerInbox` was built (P4b) to be writable
    /// while an active turn holds `&mut Agent` — exactly the property a
    /// message-to-a-running-child needs — so the mailbox is that existing
    /// seam reached from outside, not a second delivery channel with its
    /// own ordering rules. A message lands at the top of the child's next
    /// loop iteration, per `Config::steering_mode`.
    mailbox: std::sync::Arc<std::sync::Mutex<SteerInbox>>,
}

/// P5-3 safety hardening (Fable-5 review, MEDIUM-LOW "orphaned billed
/// spend"): a dropped parent must not leave a detached background child
/// running against a REAL provider. Without this, a parent dropped
/// mid-run (the caller's own process exits the scope, panics, or simply
/// stops polling) leaves every still-running `BackgroundSubagent::handle`
/// as an orphaned `tokio::spawn` task: nothing had ever awaited or
/// aborted it, so it runs to its own (`max_iterations`-bounded)
/// completion regardless — bounded but real provider spend nobody is
/// paying attention to.
///
/// `.abort()` on a [`tokio::task::JoinHandle`] is safe to call
/// unconditionally, including on an ALREADY-finished task (a documented
/// no-op there — see tokio's `JoinHandle::abort` docs) — so this never
/// needs to distinguish "still running" from "already done"; a background
/// child that already finished and is merely awaiting a `subagent_status`
/// reap is untouched in practice (aborting a finished task changes
/// nothing observable). For a task still mid-flight, tokio cancels it at
/// its next `.await` point, which drops that future in place — including
/// the `_guard: ConcurrencyGuard` moved into it at spawn time (see
/// `Self::run_spawn_subagent`'s `tokio::spawn` body) — so the
/// concurrency-gauge slot is released exactly the same way a normal
/// completion releases it (`ConcurrencyGuard`'s own `Drop`, in
/// `crate::subagents`). No separate cleanup call site to forget.
///
/// Deliberately does NOT touch [`Self::pending_child_approvals]` or
/// `Self::subagent_store` — this is purely "stop burning provider
/// calls on behalf of a caller who's gone", not a transcript-persistence
/// path (a child aborted mid-flight has no finished result to persist;
/// see this build's named residual on abort-time transcript loss).
impl Drop for Agent {
    fn drop(&mut self) {
        for (child_id, bg) in self.background_subagents.drain() {
            // Named, not silent: a child that was still running gets its
            // provider calls cut off here — worth a trace even though
            // there's no transcript left to persist (the future is
            // dropped mid-flight, before it ever returns a result).
            if !bg.handle.is_finished() {
                tracing::debug!(
                    child_id = %child_id,
                    "parent Agent dropped: aborting still-running background subagent \
                     to stop further provider spend"
                );
            }
            bg.handle.abort();
        }
        // P5-6 (§2 module 4 `tools.background`, build brief "on agent drop
        // / session end, jobs MUST be killed... real process kill via the
        // child handle's kill(), not just tokio task abort"): a REAL OS
        // process, not a Rust task — `Child::start_kill` (synchronous, no
        // `.await` needed, so callable from this non-async `Drop::drop`)
        // sends the actual kill signal; a no-op, per its own docs, on a
        // job that already exited. `kill_on_drop(true)` (set at spawn
        // time) is a second, independent line of defense for the same
        // outcome, but this explicit loop is what makes the guarantee
        // provable/traceable rather than relying solely on an implicit
        // tokio runtime behavior.
        for (job_id, mut job) in self.background_jobs.drain() {
            if !job.killed {
                tracing::debug!(
                    job_id = %job_id,
                    command = %job.command,
                    "parent Agent dropped: killing still-tracked background job's real \
                     OS process (and its whole process group — see \
                     `kill_job_process_group`)"
                );
            }
            kill_job_process_group(&mut job);
        }
        // P5-11 (§2 module 28 `lsp`, build brief "no orphaned language-
        // server processes"): a REAL OS process, same rationale as the
        // background-job loop just above — `kill_all_sync` is
        // synchronous (`Child::start_kill`, no `.await` needed, so
        // callable from this non-async `Drop::drop`), SIGKILLs each
        // server's WHOLE process group (unix — same `kill_job_process_group`
        // mechanism as the background-job loop above, so worker
        // grandchildren like rust-analyzer's proc-macro server or
        // typescript-language-server's `tsserver` are killed too, not just
        // the one directly-tracked pid), and is provable/traceable rather
        // than relying solely on `kill_on_drop(true)`'s implicit tokio
        // runtime behavior (which remains a second, independent line of
        // defense on every spawned `LspClient`).
        if let Some(lsp) = &self.lsp_manager {
            lsp.kill_all_sync();
        }
    }
}

/// P4 (§1.8 credential-helper indirection, D6 row): run an `api_key_cmd`
/// through the shell and return its trimmed stdout. Runs via `sh -c` (POSIX
/// shell, matching pi's `!command` precedent) so the configured string can
/// use pipes/substitution, e.g. `pass show api-key`. Never panics or
/// propagates an error: a spawn failure or non-zero exit is reported via
/// `tracing::warn!` and returns an empty `String`, which
/// `Agent::new`'s resolution chain treats exactly like an unset helper —
/// falling through to `Config::api_key_env`.
fn run_api_key_cmd(cmd: &str) -> String {
    match std::process::Command::new("sh").arg("-c").arg(cmd).output() {
        Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout).trim().to_string(),
        Ok(out) => {
            tracing::warn!(
                "api_key_cmd exited with status {:?}; falling back to api_key_env",
                out.status.code()
            );
            String::new()
        }
        Err(e) => {
            tracing::warn!("api_key_cmd failed to run ({e}); falling back to api_key_env");
            String::new()
        }
    }
}

/// BP-9 (§3.1 `core.api_key_command`, D6 row "Credential helpers /
/// keyring"): run an ARGV credential helper and return its trimmed stdout.
/// No shell is involved — `argv[0]` is exec'd with the rest as arguments —
/// so a helper path with spaces, or an argument containing `$`/`;`, means
/// what it says. Same never-panics, fall-through-on-failure contract as
/// [`run_api_key_cmd`]: an empty result is treated as "no helper".
pub(crate) fn run_api_key_command(argv: &[String]) -> String {
    let Some((program, args)) = argv.split_first() else {
        return String::new();
    };
    match std::process::Command::new(program).args(args).output() {
        Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout).trim().to_string(),
        Ok(out) => {
            tracing::warn!(
                "api_key_command exited with status {:?}; trying the next credential source",
                out.status.code()
            );
            String::new()
        }
        Err(e) => {
            tracing::warn!(
                "api_key_command failed to run ({e}); trying the next credential source"
            );
            String::new()
        }
    }
}

/// P4c (§1.2/§3.1 `core.shell_env_snapshot`, SPLIT CC+CX row, catalog:338):
/// capture the user's interactive login-shell environment ONCE, best-effort.
/// Runs `$SHELL -lc env` (falling back to `sh -lc env` when `$SHELL` is
/// unset) — a LOGIN shell (`-l`) sources the user's rc files, which is
/// exactly the sourcing `bash` calls should no longer need to repeat once
/// this snapshot is in hand. Never panics: any failure (spawn error,
/// non-zero exit, unparseable output) returns an empty map, which
/// `ToolContext::shell_env`'s "no-op when `None`/empty" contract already
/// treats as harmless.
fn capture_shell_env() -> std::collections::HashMap<String, String> {
    let shell = std::env::var("SHELL").unwrap_or_else(|_| "sh".to_string());
    let out = match std::process::Command::new(&shell)
        .arg("-lc")
        .arg("env")
        .output()
    {
        Ok(o) if o.status.success() => o.stdout,
        Ok(o) => {
            tracing::warn!(
                "shell_env_snapshot: `{shell} -lc env` exited with status {:?}; snapshot is empty",
                o.status.code()
            );
            return std::collections::HashMap::new();
        }
        Err(e) => {
            tracing::warn!(
                "shell_env_snapshot: failed to run `{shell} -lc env` ({e}); snapshot is empty"
            );
            return std::collections::HashMap::new();
        }
    };
    let text = String::from_utf8_lossy(&out);
    let mut map = std::collections::HashMap::new();
    for line in text.lines() {
        if let Some((k, v)) = line.split_once('=') {
            if !k.is_empty() {
                map.insert(k.to_string(), v.to_string());
            }
        }
    }
    map
}

/// Build the [`ToolContext`] an [`Agent`] hands to every tool call, folding
/// in every P4c per-tool config knob (§1.2) alongside the pre-existing
/// `cwd`/`sandbox` — shared by [`Agent::with_parts`]/[`Agent::with_provider_arc`]
/// so the two construction paths can never drift apart on which config
/// fields reach the context. Also builds (P5-9) the
/// [`crate::checkpoint::CheckpointObserver`], if `config.checkpoint_enabled`
/// — installed on the returned context's `write_observer` AND returned
/// separately (as the concrete type) so `Agent::run_loop` can call
/// [`crate::checkpoint::CheckpointObserver::begin_turn`] once per turn.
/// `None`/no-op end to end when the module is off — see
/// [`crate::checkpoint::observer_for_config`]'s own doc comment for the
/// default-off byte-identity guarantee.
///
/// P5-11 (§2 modules 28/29, D-5 "shared write-path interception seam"):
/// `crate::formatters::observer_for_config`/`crate::lsp::manager_for_config`
/// are folded into the SAME `write_observer` slot via
/// [`crate::tools::WriteObserverChain`], in the design's required order —
/// `checkpoint -> formatters -> lsp` (checkpoint's pre-image capture must
/// see the file before ANY mutation; lsp's diagnostics must see the file
/// AFTER formatting, never before). When 0 or 1 of the three modules is
/// active, this degrades to exactly what P5-9 shipped (`None`, or the
/// single concrete observer installed directly) — no chain wrapper is
/// introduced unless there is actually more than one observer to order,
/// keeping every single-module (or all-off) configuration byte-identical
/// to before this function grew multi-observer support. The `lsp` manager
/// is ALSO returned separately (like `checkpoint_observer`), so
/// `Agent`'s `Drop` impl can reach `crate::lsp::LspManager::kill_all_sync`
/// regardless of how the chain is shaped.
/// BP-2: `pub(crate)` so a parity test can build the SAME `ToolContext` an
/// `Agent` would from a resolved preset's `Config` and drive a registry
/// tool through it — a tool's behavior under a preset is exactly the
/// composition of the two, and a test that hand-assembled a context would
/// be proving an unwired function.
pub(crate) fn build_tool_context(
    config: &Config,
) -> (
    ToolContext,
    Option<std::sync::Arc<crate::checkpoint::CheckpointObserver>>,
    Option<std::sync::Arc<crate::lsp::LspManager>>,
) {
    let shell_env = if config.shell_env_snapshot {
        Some(std::sync::Arc::new(capture_shell_env()))
    } else {
        None
    };
    let checkpoint_observer = crate::checkpoint::observer_for_config(config);
    let format_observer = crate::formatters::observer_for_config(config);
    let lsp_manager = crate::lsp::manager_for_config(config);
    let lsp_observer = lsp_manager
        .clone()
        .map(|m| std::sync::Arc::new(crate::lsp::LspDiagnosticsObserver::new(m)));
    let mut observers: Vec<std::sync::Arc<dyn crate::tools::WriteObserver>> = Vec::new();
    if let Some(cp) = &checkpoint_observer {
        observers.push(cp.clone() as std::sync::Arc<dyn crate::tools::WriteObserver>);
    }
    if let Some(f) = &format_observer {
        observers.push(f.clone() as std::sync::Arc<dyn crate::tools::WriteObserver>);
    }
    if let Some(l) = &lsp_observer {
        observers.push(l.clone() as std::sync::Arc<dyn crate::tools::WriteObserver>);
    }
    let write_observer: Option<std::sync::Arc<dyn crate::tools::WriteObserver>> =
        match observers.len() {
            0 => None,
            1 => observers.into_iter().next(),
            _ => Some(std::sync::Arc::new(crate::tools::WriteObserverChain::new(
                observers,
            ))),
        };
    let ctx = ToolContext {
        cwd: config.cwd.clone(),
        // BP-10 (catalog row "Additional working directories"): the
        // `--add-dir`/`core.additional_dirs` roots reach the TOOLS now,
        // not just the project-context walk — `ToolContext::check_write`,
        // the OS backstop's writable set, and the permissions engine's
        // path rules all read them. Empty (the default) is byte-identical
        // to confining everything to `cwd`.
        extra_roots: config.additional_dirs.clone(),
        sandbox: config.sandbox,
        multimodal_read: config.read_file_multimodal,
        // BP-2 (§1.2 `core.tools.read_file.line_numbers`, catalog:26).
        read_line_numbers: config.read_file_line_numbers,
        require_read_before_edit: config.edit_file_require_read_before_edit,
        // BP-2: path → content hash at read time (`ToolContext::read_state`).
        read_paths: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
        notebook_aware: config.edit_file_notebook_aware,
        shell_env,
        nested_instructions: config.nested_instructions,
        injected_instruction_dirs: std::sync::Arc::new(std::sync::Mutex::new(HashSet::new())),
        // BP-5: filled in by `Agent::with_parts` (the one construction path
        // that assembles a prompt, and therefore the one that knows which
        // rules were held back); empty everywhere else.
        path_rules: std::sync::Arc::new(Vec::new()),
        injected_rule_files: std::sync::Arc::new(std::sync::Mutex::new(HashSet::new())),
        // P5-1 (§2 module 12 carry-forward): now sourced from real config
        // (`capabilities.permissions.sandbox.network.*`, wired by
        // `configfile::materialize_config`) instead of always `None`. `None`
        // (the default, unchanged when the config never sets it) is still
        // byte-identical to today's behavior.
        network_policy: config.network_policy.clone(),
        // BP-10 (catalog row "Allow/ask/deny rule language", the DOMAIN
        // subject): the config's own rule arrays reach the network surface
        // too, so a `domain(...)` rule is evaluated by the SAME engine that
        // evaluates `bash(...)`/`write(...)` at the dispatch gate — not by
        // a second matcher over a second list. `None` when the permissions
        // module is off, which is byte-identical to before.
        permission_rules: config.permissions_enabled.then(|| {
            std::sync::Arc::new(crate::permissions::RuleSet {
                deny: config.tool_deny_patterns.clone(),
                ask: config.permissions_ask_patterns.clone(),
                allow: config.tool_allow_patterns.clone(),
            })
        }),
        // P4e (S3.1 `core.tools.bash.timeout_secs`, S14): folds the `bash`
        // `ToolOverride`'s `timeout_secs`, if set, into the context every
        // `BashTool::execute` call receives -- `None` (no override
        // configured) is byte-identical to today's behavior.
        bash_timeout_secs: config
            .tool_overrides
            .get("bash")
            .and_then(|o| o.timeout_secs),
        write_observer,
        // P5-10 (§2 module 12): sourced from real config
        // (`capabilities.permissions.sandbox.{enabled,escalation,env_policy}`,
        // wired by `configfile::materialize_config`). `sandbox_approval_handler`
        // starts `None` here (no handler is installed yet at `Agent`
        // construction time) and is kept in sync by
        // `Agent::set_permissions_approval_handler` — see that method's doc
        // comment.
        sandbox_os_enabled: config.sandbox_os_enabled,
        sandbox_escalation: config.sandbox_escalation,
        sandbox_env_policy: config.sandbox_env_policy,
        sandbox_approval_handler: None,
        // BP-3: both handler seams start `None` (nothing is installed at
        // construction time) and are filled by
        // `Agent::set_permissions_approval_handler` /
        // `Agent::set_user_question_handler`, exactly like
        // `sandbox_approval_handler` above. The two shared states are
        // always present but inert: plan mode starts off (contributing no
        // rules), and the budget starts unpublished.
        question_handler: None,
        approval_handler: None,
        plan_mode: std::sync::Arc::new(crate::tools::PlanModeState::new()),
        context_budget: std::sync::Arc::new(crate::tools::ContextBudget::new()),
        // BP-8 (catalog:156): the shared plan the agent journals and
        // persists. Always present, empty and inert until `update_plan`
        // writes one.
        plan: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
    };
    (ctx, checkpoint_observer, lsp_manager)
}

/// P4b (§1.4/§3.1, catalog §4a "Global/user-level instruction file tier"):
/// where the user/global instruction tier lives — `$SUPERCODE_HOME`, else
/// `$XDG_CONFIG_HOME/supercode`, else `~/.config/supercode`. Deliberately
/// duplicates `crates/cli/src/userconfig.rs::config_home`'s exact precedence
/// rather than depending on the `cli` crate from `core` (wrong dependency
/// direction — `cli` depends on `core`, never the reverse). `pub(crate)`:
/// also the DEFAULT shadow-store root `crate::checkpoint::observer_for_config`
/// (P5-9) derives from when `Config::checkpoint_dir` is unset — one
/// `$SUPERCODE_HOME` resolver, not a second hand-rolled one.
pub(crate) fn global_instructions_dir() -> std::path::PathBuf {
    if let Ok(h) = std::env::var("SUPERCODE_HOME") {
        if !h.is_empty() {
            return std::path::PathBuf::from(h);
        }
    }
    if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
        if !xdg.is_empty() {
            return std::path::PathBuf::from(xdg).join("supercode");
        }
    }
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
    std::path::PathBuf::from(home)
        .join(".config")
        .join("supercode")
}

/// P4b (§1.4, catalog §4a "Instruction imports"): is `rel` (an `@`-import
/// target found inside a PROJECT-sourced instruction file) LEXICALLY safe to
/// resolve? Mirrors `configfile::is_safe_project_dir`'s posture (LOW-1
/// precedent): rejects absolute paths, `~`-relative paths, and any `..`
/// component — an untrusted repo's own CLAUDE.md/AGENTS.md must not be able
/// to `@import` its way to an arbitrary file on disk (e.g. `@/etc/passwd`,
/// `@../../.ssh/id_rsa`). Global-tier files (the user's own machine, same
/// trust level as the user's shell) are NOT run through this check.
///
/// This is a cheap PRE-FILTER only — it operates on the literal token text
/// and cannot see through a symlink committed in the repo whose *target*
/// escapes the root while the *link itself* has a clean, traversal-free
/// relative name (e.g. `@link.md` where `link.md -> /etc/passwd`). See
/// [`import_target_is_contained`] for the canonicalizing check that closes
/// that gap; the project-scoped resolution path runs both.
fn import_path_is_safe(rel: &str) -> bool {
    if rel.is_empty() || rel.contains('\0') {
        return false;
    }
    let path = std::path::Path::new(rel);
    if path.is_absolute() || rel.starts_with('~') {
        return false;
    }
    !path
        .components()
        .any(|c| matches!(c, std::path::Component::ParentDir))
}

/// P4b security fix (Fable-5 review, MEDIUM: symlink bypass of the
/// project-scoped `@`-import boundary): does `candidate` — after resolving
/// symlinks — stay inside `root` — also after resolving symlinks? This is
/// what actually enforces [`import_path_is_safe`]'s doc-comment guarantee
/// ("must not be able to `@import` its way to an arbitrary file on disk"):
/// the lexical check alone rejects `@/etc/passwd` and `@../../secret`, but a
/// repo can commit a symlink (e.g. `link.md -> /etc/passwd`) whose own
/// relative name is perfectly clean, defeating a purely lexical check.
///
/// Both sides are canonicalized before the comparison — not just
/// `candidate` — because `root` itself can legitimately be a symlink (a
/// tempdir under macOS's `/tmp` -> `/private/tmp`, or any other symlinked
/// project checkout); comparing a canonicalized candidate against a
/// non-canonicalized root would falsely reject genuinely-in-root files.
///
/// Fails CLOSED: a `canonicalize()` failure (broken symlink, a target that
/// doesn't exist, a permission error) returns `false` — never inlined,
/// mirroring [`expand_instruction_imports`]'s existing "unreadable file ⇒
/// left as literal text" posture rather than panicking or defaulting open.
pub(crate) fn import_target_is_contained(
    candidate: &std::path::Path,
    root: &std::path::Path,
) -> bool {
    let (Ok(real_root), Ok(real_candidate)) = (
        std::fs::canonicalize(root),
        std::fs::canonicalize(candidate),
    ) else {
        return false;
    };
    real_candidate.starts_with(&real_root)
}

/// P4b (§1.4/§3.1 `core.instruction_imports`, catalog:85): inline `@path`
/// import tokens found in `text` with the referenced file's own (trimmed)
/// content, resolved relative to `dir` (the directory the CONTAINING file
/// lives in — so a chain of imports each resolves relative to its own
/// location, not the original file's). `depth` bounds recursion (CC's own
/// default of 4, cited in the cc-parity preset) so a cyclical or
/// deeply-nested import chain can't blow the stack or loop forever.
/// `project_scoped` gates [`import_path_is_safe`] AND
/// [`import_target_is_contained`] — see their doc comments; `root` is the
/// containment boundary those checks canonicalize against (the SAME root
/// for every level of a nested import chain, even though `dir` itself walks
/// deeper with each level — an import three levels deep must still resolve
/// under the original project root, not merely under its own immediate
/// parent). Ignored when `!project_scoped` (the global/user tier, trusted,
/// unrestricted — see [`append_instruction_file`]'s doc comment).
/// Any token that isn't `@`-prefixed, doesn't resolve to a readable file, or
/// (project-scoped) fails the safety/containment check is left as literal
/// text — an import is best-effort, never a hard error that could make
/// instruction loading fail outright.
fn expand_instruction_imports(
    text: &str,
    dir: &std::path::Path,
    root: &std::path::Path,
    project_scoped: bool,
    depth: u8,
) -> String {
    if depth >= 4 {
        return text.to_string();
    }
    let mut out = String::with_capacity(text.len());
    for token in split_preserving_whitespace(text) {
        if let Some(rel) = token.strip_prefix('@') {
            if !rel.is_empty()
                && !rel.contains(char::is_whitespace)
                && (!project_scoped || import_path_is_safe(rel))
            {
                let candidate = dir.join(rel);
                if !project_scoped || import_target_is_contained(&candidate, root) {
                    if let Ok(imported) = std::fs::read_to_string(&candidate) {
                        let imported = imported.trim();
                        if !imported.is_empty() {
                            let imported_dir = candidate.parent().unwrap_or(dir);
                            out.push_str(&expand_instruction_imports(
                                imported,
                                imported_dir,
                                root,
                                project_scoped,
                                depth + 1,
                            ));
                            continue;
                        }
                    }
                }
            }
        }
        out.push_str(token);
    }
    out
}

/// Split `text` into tokens that, concatenated, reproduce it exactly —
/// alternating runs of non-whitespace and whitespace. Used by
/// [`expand_instruction_imports`] so `@import` tokens can be located and
/// replaced without disturbing surrounding formatting/whitespace.
fn split_preserving_whitespace(text: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let mut start = 0;
    let mut in_ws = None;
    for (i, c) in text.char_indices() {
        let ws = c.is_whitespace();
        match in_ws {
            None => in_ws = Some(ws),
            Some(prev) if prev != ws => {
                out.push(&text[start..i]);
                start = i;
                in_ws = Some(ws);
            }
            _ => {}
        }
    }
    if start < text.len() {
        out.push(&text[start..]);
    }
    out
}

/// BP-4 (catalog:87 "Instruction-file hygiene controls", cc§2
/// `claudeMdExcludes`): whether `path` is excluded from instruction loading
/// by [`Config::project_doc_excludes`]. A pattern matches when it
/// [`crate::config::glob_match`]es the file's NAME (`CLAUDE.md`), its full
/// path, or its path relative to `root` — the three spellings cc's own
/// "glob/absolute-path list" accepts. Empty (the default) excludes nothing.
fn instruction_file_excluded(
    config: &Config,
    path: &std::path::Path,
    root: &std::path::Path,
) -> bool {
    if config.project_doc_excludes.is_empty() {
        return false;
    }
    let full = path.to_string_lossy().to_string();
    let name = path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default();
    let rel = path
        .strip_prefix(root)
        .ok()
        .map(|p| p.to_string_lossy().to_string());
    config.project_doc_excludes.iter().any(|pat| {
        crate::config::glob_match(pat, &full)
            || crate::config::glob_match(pat, &name)
            || rel
                .as_deref()
                .is_some_and(|r| crate::config::glob_match(pat, r))
    })
}

/// BP-4 (catalog:87, cc§2 "HTML comment stripping"): drop block-level
/// `<!-- … -->` spans from an instruction file's text so maintainer notes
/// cost no tokens, exactly as cc does before injection. Unterminated
/// openers drop the remainder (the same reading a markdown renderer takes).
/// Off by default ([`Config::project_doc_strip_comments`]) — cx does NOT
/// strip, so this is a per-preset hygiene lever, not a universal one.
fn strip_html_comments(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(open) = rest.find("<!--") {
        out.push_str(&rest[..open]);
        match rest[open..].find("-->") {
            Some(close) => rest = &rest[open + close + 3..],
            None => return out,
        }
    }
    out.push_str(rest);
    out
}

/// P4b (§1.4): append one instruction file's (trimmed, import-expanded)
/// content to `blob` as a labeled section, exactly like the pre-P4b inline
/// loop did — a no-op when `path` doesn't exist or is empty (the common
/// case). `project_scoped` distinguishes the project tier (imports bounded
/// to `root`, canonicalized-and-contained — see
/// [`import_target_is_contained`]) from the global tier (imports
/// unrestricted, same trust level as the user's own machine — `root` is
/// unused in that case). `root` is normally `path`'s own parent (the tier
/// root `path` was discovered under, e.g. an ancestor of `cwd` or an
/// `additional_dirs` entry) — see [`assemble_project_instructions`]'s call
/// sites.
///
/// BP-4 adds the hygiene controls (catalog:87): the exclude list
/// ([`instruction_file_excluded`]), HTML-comment stripping
/// ([`strip_html_comments`]) and the [`InstructionBudget`] —
/// [`Config::project_doc_max_bytes`] spent INCREMENTALLY as files are
/// concatenated root→cwd, which is how cx's own cap works on its root-down
/// concat, rather than one chop at the end (that chop would silently eat
/// the trailing per-file notices it had just written).
fn append_instruction_file(
    blob: &mut String,
    config: &Config,
    path: &std::path::Path,
    root: &std::path::Path,
    label: &str,
    project_scoped: bool,
    budget: &mut InstructionBudget,
) {
    if budget.exhausted() || instruction_file_excluded(config, path, root) {
        return;
    }
    let Ok(text) = std::fs::read_to_string(path) else {
        return;
    };
    let stripped;
    let text = if config.project_doc_strip_comments {
        stripped = strip_html_comments(&text);
        stripped.trim()
    } else {
        text.trim()
    };
    if text.is_empty() {
        return;
    }
    let dir = path.parent().unwrap_or(std::path::Path::new("."));
    let mut content = if config.instruction_imports {
        expand_instruction_imports(text, dir, root, project_scoped, 0)
    } else {
        text.to_string()
    };
    if !budget.take(&mut content) {
        return;
    }
    blob.push_str(&format!("\n\n# {label}\n{content}"));
}

/// Truncate `s` to at most `max` BYTES, backing off to the nearest char
/// boundary — shared by the per-file and aggregate instruction caps.
fn truncate_at_char_boundary(s: &mut String, max: usize) {
    let mut end = max;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    s.truncate(end);
}

/// BP-4 (catalog:87 "Instruction-file hygiene controls", cx§2
/// `project_doc_max_bytes`): the instruction-content byte budget, spent as
/// files are concatenated root→cwd.
///
/// `None` (the default, and cc-parity's explicit `= 0`) is uncapped, so
/// [`Self::take`] is a no-op and assembly is byte-identical to a config
/// that never heard of the cap. With a cap set, each file is truncated to
/// whatever budget REMAINS (per-file notice), and once the budget is gone
/// the remaining files are skipped entirely (aggregate notice, emitted once
/// by [`Self::aggregate_notice`]) — the total instruction CONTENT can
/// therefore never exceed the cap, and the notices survive because nothing
/// chops the assembled blob afterwards.
struct InstructionBudget {
    remaining: Option<usize>,
    hit: bool,
}

impl InstructionBudget {
    fn new(config: &Config) -> Self {
        InstructionBudget {
            remaining: config.project_doc_max_bytes,
            hit: false,
        }
    }

    /// True once the cap has consumed the whole budget — later files are
    /// skipped rather than partially appended.
    fn exhausted(&self) -> bool {
        self.remaining == Some(0)
    }

    /// Charge `content` against the budget, truncating it (and appending a
    /// per-file notice) when it doesn't fit. Returns whether anything is
    /// left to append.
    fn take(&mut self, content: &mut String) -> bool {
        let Some(remaining) = self.remaining else {
            return true;
        };
        if content.len() <= remaining {
            self.remaining = Some(remaining - content.len());
            return true;
        }
        self.hit = true;
        self.remaining = Some(0);
        if remaining == 0 {
            return false;
        }
        truncate_at_char_boundary(content, remaining);
        content.push_str("\n[supercode: file truncated at core.project_doc_max_bytes]");
        true
    }

    /// The one aggregate notice, appended after assembly when the cap bound
    /// anywhere — the statement that the assembled block is not the whole
    /// instruction set.
    fn aggregate_notice(&self) -> &'static str {
        if self.hit {
            "\n\n[supercode: instruction content truncated at core.project_doc_max_bytes]"
        } else {
            ""
        }
    }
}

/// BP-4 (catalog:81 "Project instruction files w/ directory walk"; cc§2
/// "Directory-walk loading", cx§2 "walk project root (git root) down to
/// cwd"): the ancestor chain instruction files are discovered on, ordered
/// OUTERMOST FIRST so the nearest directory wins precedence by appearing
/// last in the concatenated blob (the root→cwd ordering both inventories
/// document).
///
/// The walk starts at [`Config::cwd`] and climbs until it has included the
/// project root [`crate::config::project_root_for`] identifies (`.git` by
/// default — cx's `project_root_markers`, §3.1), or until the filesystem
/// root, whichever comes first. [`MAX_INSTRUCTION_WALK_DEPTH`] bounds it
/// unconditionally, so a marker-less path deep under `/` can never turn
/// prompt assembly into an unbounded stat storm.
pub(crate) fn instruction_walk_roots(config: &Config) -> Vec<std::path::PathBuf> {
    // BP-9's shared answer to "where does the project stop?" — the same
    // walk the `env_context` git probe and the CLI's `.supercode.toml`
    // discovery use, so one `project_root_markers` value cannot mean three
    // different things. `None` (no marker anywhere, or an empty list) means
    // no root was found, and the climb below then stops at the filesystem
    // root under `MAX_INSTRUCTION_WALK_DEPTH`.
    let root = crate::config::project_root_for(&config.cwd, &config.project_root_markers);
    let mut chain: Vec<std::path::PathBuf> = Vec::new();
    let mut dir = config.cwd.clone();
    loop {
        let at_root = root.as_deref() == Some(dir.as_path());
        chain.push(dir.clone());
        if at_root || chain.len() >= MAX_INSTRUCTION_WALK_DEPTH {
            break;
        }
        match dir.parent() {
            Some(parent) if parent != dir => dir = parent.to_path_buf(),
            _ => break,
        }
    }
    chain.reverse();
    chain
}

/// Hard bound on [`instruction_walk_roots`]'s ancestor climb.
const MAX_INSTRUCTION_WALK_DEPTH: usize = 64;

/// P4b (§1.4, obligation 4 assembly site): the full instruction-file blob —
/// global/user tier (catalog §4a "Global/user-level instruction file tier")
/// FIRST, then the project tier — capped by
/// [`Config::project_doc_max_bytes`] if set (catalog §4a "hygiene caps
/// (`project_doc_max_bytes` analog)").
///
/// BP-4 (catalog:81): the project tier is no longer `cwd` alone. It is the
/// ANCESTOR WALK [`instruction_walk_roots`] returns (cwd's chain up to the
/// git root, outermost first) followed by `additional_dirs` — root-first
/// ordering throughout, so the nearest directory wins by appearing later,
/// which is exactly how both cc§2 ("concatenated root→cwd, closest read
/// last") and cx§2 ("nearer-to-cwd wins by appearing later") describe their
/// own walks. `cwd` is the last element of the walk chain, so a config
/// whose cwd IS the project root assembles byte-identically to the pre-BP-4
/// loop.
/// BP-5 (catalog D2 "Per-model-family base-prompt selection", cx§2
/// "Per-model base instructions": "the system prompt is selected per model
/// family from bundled markdown … the active `base_instructions` are
/// persisted verbatim into the rollout `session_meta`"): the base system
/// prompt for the model this config runs.
///
/// `[capabilities.model_catalog] base_prompts` maps a model-id glob to that
/// family's prompt; the most specific match wins
/// ([`crate::model_catalog::base_prompt_for`]). No table and no match both
/// give [`Config::system_prompt`] verbatim, so this is a no-op for every
/// config that does not set the table.
fn base_prompt_for_config(config: &Config) -> String {
    crate::model_catalog::base_prompt_for(&config.model_family_prompts, &config.model)
        .map(str::to_string)
        .unwrap_or_else(|| config.system_prompt.clone())
}

fn assemble_project_instructions(config: &Config) -> String {
    let mut blob = String::new();
    let mut budget = InstructionBudget::new(config);
    let global_dir = global_instructions_dir();
    for name in ["CLAUDE.md", "AGENTS.md"] {
        append_instruction_file(
            &mut blob,
            config,
            &global_dir.join(name),
            // Global tier is trusted/unrestricted (project_scoped=false
            // below) — `root` is never consulted, but pass `global_dir`
            // rather than a bogus value for clarity.
            &global_dir,
            name,
            false,
            &mut budget,
        );
    }
    // BP-10 (catalog row "Project/workspace trust gate", cc§4/cx§4:
    // "Prompt before loading project-local config/code"): the PROJECT tier
    // is trust-gated. The global/user tier above is not — it is the user's
    // own machine, the same trust level as their shell, exactly as
    // `append_instruction_file`'s `project_scoped = false` argument
    // already says.
    //
    // `crate::trust::is_trusted` asks the `Config::trust_handler` door
    // once per project and records the answer; with no door installed
    // `TrustSurface::Instructions` resolves to LOADED, which is both the
    // pre-BP-10 behavior and what a headless run of either upstream
    // harness does — see `crate::trust`'s doc comment for why the
    // undecided answer differs between text and code.
    if !crate::trust::is_trusted(config, crate::trust::TrustSurface::Instructions) {
        blob.push_str(
            "\n[project instruction files were not loaded: this workspace is not trusted              (capabilities.trust)]\n",
        );
        blob.push_str(budget.aggregate_notice());
        return blob;
    }
    let walk = instruction_walk_roots(config);
    for root in walk.iter().chain(config.additional_dirs.iter()) {
        for name in ["CLAUDE.md", "AGENTS.md"] {
            append_instruction_file(
                &mut blob,
                config,
                &root.join(name),
                // Project tier: `@`-imports from THIS file must stay under
                // THIS root (canonicalized) — see
                // `import_target_is_contained`.
                root,
                name,
                true,
                &mut budget,
            );
        }
        // A repository-native agent package is an additional project
        // instruction tier. It is subject to the same `project_context`
        // switch, import containment, and aggregate byte cap as root
        // AGENTS.md/CLAUDE.md; loading it never executes package code.
        for path in crate::agent_package::workspace_package_instruction_files(root) {
            append_instruction_file(
                &mut blob,
                config,
                &path,
                root,
                "Supercode agent package instructions",
                true,
                &mut budget,
            );
        }
    }
    blob.push_str(budget.aggregate_notice());
    blob
}

/// P4b (§1.4/§3.1 `core.env_context`, catalog §4a "Environment context block
/// injection"): cwd, platform, date, and a best-effort git branch/dirty
/// status (silently absent when `cwd` isn't a git repo or `git` isn't on
/// `PATH` — never blocks agent construction).
///
/// BP-4 (catalog:90): plus the APPROVAL/SANDBOX POLICY line the row's own
/// semantics name ("cwd/git/platform/date/**policy**") and cx's
/// `<environment_context>` supplies — the model is told which approval mode
/// and which filesystem confinement it is operating under, which is what
/// makes "ask before you do X" instructions legible to it. The block is
/// re-derivable at any moment from `config` alone, which is what lets
/// [`Agent::refresh_env_context`] re-emit it mid-session on change.
/// BP-6 (catalog D2 "Skills (progressive-disclosure packages)", §1.4
/// obligation 4): the `# Skills` prompt section — the discovered SKILL.md
/// packages' names and descriptions, plus the `[core.prompts]` template
/// names, and NOTHING else. A skill's body is deliberately absent: it costs
/// its tokens only when something actually invokes it (`docs:skills`
/// "body loads only when used"; cx§7; pi§2 "progressive disclosure").
///
/// A skill whose frontmatter hides it from the model (`enabled: false`,
/// `disable-model-invocation: true`) is left OUT of the index while staying
/// user-invocable — cc§7 "Invocation control", pi§2.
///
/// Empty string when there is nothing to list, so an agent with neither
/// skills nor templates keeps the prompt it had before this existed.
fn skills_prompt_section(config: &Config, skills: &[crate::skills::LoopSkill]) -> String {
    let listed: Vec<&crate::skills::LoopSkill> = skills
        .iter()
        .filter(|skill| skill.model_invocable)
        .collect();
    let mut templates: Vec<&str> = config.prompts.keys().map(String::as_str).collect();
    templates.sort_unstable();
    if listed.is_empty() && templates.is_empty() {
        return String::new();
    }
    let mut out = String::from("\n\n# Skills\n");
    if !listed.is_empty() {
        out.push_str(
            "Installed skill packages. Only each skill's name and description are listed \
             here; call the `skill` tool with a name below to load that skill's full \
             instructions when it applies, then follow them.\n",
        );
        for skill in listed {
            out.push_str(&skill.index_line());
            out.push('\n');
        }
    }
    if !templates.is_empty() {
        if !out.ends_with("# Skills\n") {
            out.push('\n');
        }
        out.push_str("Prompt templates (invoke via `/name args`):\n");
        for name in templates {
            out.push_str(&format!("- {name}\n"));
        }
    }
    out
}

fn env_context_block(config: &Config) -> String {
    let mut lines = vec![
        format!("cwd: {}", config.cwd.display()),
        format!("platform: {}", std::env::consts::OS),
        format!(
            "date: {}",
            crate::sidecar::now_rfc3339().get(..10).unwrap_or("")
        ),
        format!(
            "approval policy: {} · sandbox: {}",
            approval_policy_label(config.approval),
            sandbox_policy_label(config.sandbox),
        ),
    ];
    // BP-9 (§3.1 `core.project_root_markers`, catalog:232): the git probe
    // runs at the PROJECT ROOT the markers define, not at whatever
    // subdirectory the process happens to sit in — the marker knob's whole
    // job is deciding where "the project" starts. Falls back to `cwd` when
    // no ancestor carries a marker (or the list is empty), which is
    // byte-identical to the pre-BP-9 behavior.
    let root = crate::config::project_root_for(&config.cwd, &config.project_root_markers)
        .unwrap_or_else(|| config.cwd.clone());
    if let Some(status) = env_context_git_status(&root) {
        lines.push(status);
    }
    format!("\n\n# Environment\n{}", lines.join("\n"))
}

/// The `[capabilities.permissions] approval` spelling of a policy — the same
/// token the config schema accepts (`configfile::parse_approval_str`), so
/// the block reports the policy in the vocabulary the user configured it in.
fn approval_policy_label(policy: crate::config::ApprovalPolicy) -> &'static str {
    match policy {
        crate::config::ApprovalPolicy::Never => "never",
        crate::config::ApprovalPolicy::OnRequest => "on-request",
        crate::config::ApprovalPolicy::Untrusted => "untrusted",
        crate::config::ApprovalPolicy::ModelRequested => "model-requested",
    }
}

/// The `[capabilities.permissions] sandbox` spelling of a tier — see
/// [`approval_policy_label`].
fn sandbox_policy_label(policy: crate::tools::SandboxPolicy) -> &'static str {
    match policy {
        crate::tools::SandboxPolicy::ReadOnly => "read-only",
        crate::tools::SandboxPolicy::WorkspaceWrite => "workspace-write",
        crate::tools::SandboxPolicy::DangerFullAccess => "danger-full-access",
    }
}

/// Best-effort `git branch (dirty|clean)` for [`env_context_block`]. `None`
/// on anything short of a clean success (not a repo, `git` missing, a
/// detached/errored state) — this is informational context, never worth
/// failing agent construction over.
fn env_context_git_status(cwd: &std::path::Path) -> Option<String> {
    let branch_out = std::process::Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(cwd)
        .output()
        .ok()?;
    if !branch_out.status.success() {
        return None;
    }
    let branch = String::from_utf8_lossy(&branch_out.stdout)
        .trim()
        .to_string();
    if branch.is_empty() {
        return None;
    }
    let dirty = std::process::Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(cwd)
        .output()
        .ok()
        .map(|o| !o.stdout.is_empty())
        .unwrap_or(false);
    Some(format!(
        "git branch: {branch} ({})",
        if dirty { "dirty" } else { "clean" }
    ))
}

impl Agent {
    /// Build an agent backed by an OpenAI-compatible endpoint (OpenRouter by
    /// default). The API key is taken from [`Config::api_key`], then
    /// [`Config::api_key_cmd`] (P4: a credential-helper command, run via the
    /// shell — see `run_api_key_cmd`), then the configured environment
    /// variable ([`Config::api_key_env`]).
    pub fn new(config: Config) -> Result<Self> {
        let api_key = match &config.api_key {
            Some(k) if !k.is_empty() => k.clone(),
            // BP-9: the ARGV helper (`core.api_key_command`) is consulted
            // first — it is the form with no shell in the path, so a config
            // that sets both gets the one with fewer ways to surprise its
            // author. Empty/failed → fall through, same as `api_key_cmd`.
            _ => match config
                .api_key_command
                .as_deref()
                .filter(|argv| !argv.is_empty())
                .map(run_api_key_command)
                .filter(|k| !k.is_empty())
                .or_else(|| {
                    config
                        .api_key_cmd
                        .as_deref()
                        .filter(|c| !c.is_empty())
                        .map(run_api_key_cmd)
                }) {
                // P4 (§1.8 credential-helper indirection, D6 row): the
                // helper ran and produced a non-empty key — use it. A
                // failed/empty helper falls through to `api_key_env` rather
                // than erroring outright, same "try the next source"
                // posture as every other layer in this resolution chain.
                Some(k) if !k.is_empty() => k,
                _ => std::env::var(&config.api_key_env)
                    .ok()
                    .filter(|k| !k.is_empty())
                    .ok_or_else(|| Error::MissingApiKey(config.api_key_env.clone()))?,
            },
        };
        // P4b (§1.1/§3.1 `core.retry`, pi§3 shape): `Config.retry_*` now
        // reaches the pre-existing transport-layer retry mechanism (see
        // `provider::HttpOptions::from_retry_config`'s doc comment for the
        // exact "byte-identical when unset" contract).
        let http_options = provider::HttpOptions::from_retry_config(
            config.retry_enabled,
            config.retry_max_retries,
            config.retry_base_delay_ms,
        );
        // BP-7 (catalog §4a "Turn/budget caps"): a spend cap armed against
        // a model this build cannot price is refused HERE rather than
        // accepted and silently never enforced. See
        // `Config::max_budget_usd`.
        if config.max_budget_usd.is_some_and(|b| b > 0.0)
            && crate::pricing::resolve(
                &config.model,
                config.price_input_per_mtok,
                config.price_output_per_mtok,
            )
            .is_none()
        {
            return Err(Error::UnpriceableBudget {
                model: config.model.clone(),
            });
        }
        // BP-7 (catalog §4a "Auto-retry on transient provider errors"): the
        // shared log the transport's retry loop reports into and
        // `Self::run_loop` drains after every completion.
        let retry_log = std::sync::Arc::new(crate::provider::RetryLog::default());
        let provider = OpenAiProvider::new_with_options(
            config.base_url.clone(),
            api_key,
            config.extra_headers.clone(),
            http_options,
        )
        .with_retry_log(retry_log.clone());
        // P3 (design §5.2): `ToolRegistry::from_config` replaces the
        // unconditional `with_builtins()` call — a no-op when
        // `config.module_registry` is off (the default, §5.3 risk 2).
        let registry = ToolRegistry::from_config(&config);
        let mut agent = Self::with_parts(config, Box::new(provider), registry);
        agent.retry_log = retry_log;
        Ok(agent)
    }

    /// Build an agent with an explicit provider and the built-in tools. Handy
    /// for tests (inject a mock provider) or custom transports.
    pub fn with_provider(config: Config, provider: Box<dyn Provider>) -> Self {
        let registry = ToolRegistry::from_config(&config);
        Self::with_parts(config, provider, registry)
    }

    /// Build an agent from all three parts.
    pub fn with_parts(
        mut config: Config,
        provider: Box<dyn Provider>,
        mut registry: ToolRegistry,
    ) -> Self {
        // P5-12 (§2 module 18 `plugins`, D-10): register every trusted,
        // loaded plugin's declared tools — the same "unconditional, config-
        // gated" wiring `build_tool_context` just below gives
        // checkpoint/formatters/lsp. `crate::plugins::register_into` is a
        // true no-op (no filesystem read, no subprocess) whenever
        // `config.plugins_enabled` is `false` (the default) — byte-identical
        // to before this module existed. Runs here (the one tail every
        // `Agent` construction path funnels through — `new`/`with_provider`
        // both call this) rather than in `ToolRegistry::from_config`, so it
        // is NOT entangled with that function's unrelated `module_registry`
        // experimental gate.
        crate::plugins::register_into(&config, &mut registry);
        let (mut ctx, checkpoint_observer, lsp_manager) = build_tool_context(&config);
        // Auto-load project context files (CLAUDE.md / AGENTS.md) from the
        // working directory (and any extra roots), appending them to the system
        // prompt — the analog of how Claude Code / Codex discover them.
        // P4b (§1.4): also the global/user tier + instruction imports + the
        // `project_doc_max_bytes` hygiene cap — see `assemble_project_instructions`.
        // BP-5 (catalog D2 "Per-model-family base-prompt selection", cx§2
        // "Per-model base instructions"): the base prompt is chosen for the
        // model in force, not fixed before the model is known — the exact
        // residue the ledger row named. `base_prompt_for_config` is
        // `config.system_prompt` verbatim for every config that sets no
        // family table, so this is a no-op by default.
        let base_prompt_live = base_prompt_for_config(&config);
        // BP-5 (catalog D2 "Output style / personality module"): a custom
        // style may REPLACE the base coding instructions rather than append
        // to them (cc§7 `keep-coding-instructions`); every other style is
        // appended at the end of the assembled prompt, below.
        let output_style = crate::output_style::resolve(&config);
        let mut system = match output_style.as_ref() {
            Some(style) if style.replaces_base => style.text.clone(),
            _ => base_prompt_live.clone(),
        };
        if config.load_project_context {
            system.push_str(&assemble_project_instructions(&config));
        }
        // BP-5 (catalog D2 "Path-scoped rules", cc§2 `.claude/rules`): the
        // UNSCOPED rules join the instruction blob here. A rule carrying a
        // `paths:` selector deliberately does not — it waits for a tool to
        // touch a matching file (`tools::builtins::path_rules_notice`).
        let path_rules = crate::path_rules::load(&config);
        system.push_str(&crate::path_rules::always_on_text(&path_rules));
        // P4b (§1.4/§3.1 `core.env_context`, catalog §4a "Environment
        // context block injection"): `false` (the default) is a no-op —
        // byte-identical to today's behavior. BP-4 keeps the rendered block
        // on the agent (`env_context_live`) so `refresh_env_context` can
        // find and REPLACE exactly this text when cwd/policy/branch move,
        // rather than leaving a stale block in the prompt forever.
        let env_context_live = if config.env_context {
            let block = env_context_block(&config);
            system.push_str(&block);
            Some(block)
        } else {
            None
        };
        // P4e (§1.4/§3.1 `core.context_injections`, catalog:91 "Synthetic
        // context-injection blocks"): same assembly site, right after
        // `env_context`. `false` (the default) is a no-op — byte-identical
        // to today's behavior. BP-4 routes it through
        // `crate::context_injection`, so the gate now delivers the built-in
        // ambient blocks the row is about (and stays extensible at runtime
        // through `Self::inject_context_block`) instead of only whatever
        // static list an embedder happened to populate.
        system.push_str(&crate::context_injection::assemble(&config, &[]));
        // P3 (design §5.2, §1.4 obligation 4, D-7): the skills prompt
        // section is a MODULE-GATED prompt section, the design's own
        // illustration of "a disabled module contributes no prompt
        // sections" — only assembled at all under
        // `[experimental] module_registry = true` (§5.3 risk 2: flag-off is
        // byte-for-byte today's behavior, and today's behavior never emits
        // this section, since it doesn't exist pre-P3). Gated further by
        // D-7 itself: `core.skills` requires a read pathway (`read_file` or
        // `bash`) — absent either, no section is appended, matching the
        // hard-dependency shape `configfile::validate_modules` enforces at
        // resolve time.
        //
        // BP-6 (catalog D2 "Skills (progressive-disclosure packages)"): the
        // section is now the discovered SKILL.md INDEX — each package's
        // frontmatter `name` and `description`, nothing else. A body is
        // never assembled here; it is read on invocation only, which is
        // what "progressive disclosure" means. The `[core.prompts]`
        // template names keep their own sub-list below it.
        let skills = crate::skills::load_for_config(&config);
        if config.module_registry && config.skills_enabled {
            let has_read_pathway = config
                .core_tools_enabled
                .iter()
                .any(|t| t == "read_file" || t == "bash");
            if has_read_pathway {
                system.push_str(&skills_prompt_section(&config, &skills));
            }
        }
        // BP-5: the style layer lands LAST, where cc puts it ("output styles
        // append custom instructions to the END of the system prompt").
        // Empty for a neutral style (`default`/`none`) and for a style that
        // already replaced the base above.
        if let Some(style) = output_style.as_ref().filter(|s| !s.replaces_base) {
            system.push_str(&style.section());
        }
        // BP-5: the SCOPED rules travel with the tool context, which is
        // where a "a tool touched a matching file" event can see them.
        ctx.path_rules = std::sync::Arc::new(path_rules);
        let history = vec![ChatMessage::system(system)];
        // P4e (§1.6/§3.1 `core.session.git_metadata`, catalog:331): captured
        // once here, alongside `env_context`'s own git probe — `false` (the
        // default) is a no-op, byte-identical to today's behavior.
        let git_metadata = if config.session_git_metadata {
            crate::git_metadata::capture(&config.cwd, now_ms())
        } else {
            None
        };
        // BP-7 (catalog §4a "Named agent definitions as data"): discover
        // `<cwd>/.claude/agents/*.md` for EVERY harness that turns the
        // subagents module on, not only the Claude emulate/resume path —
        // that restriction was the second half of the ledger row's
        // residue.
        merge_project_agent_definitions(&mut config);
        // P5-3: captured before `config` moves into the literal below (a
        // `usize` field READ, not a move, but it must happen before the
        // `config` shorthand field consumes the binding).
        let subagent_depth = config.subagent_depth;
        // BP-5 (catalog D2 "Shell-output injection in templates/skills"):
        // the authorization every `` !`cmd` `` in a skill/command body is
        // evaluated under — this config's own permission rules, resolved
        // once. Disabled unless `[core.skills] shell_injection` is on.
        let shell_injection = crate::skills::ShellInjection::from_config(&config);
        // BP-8 (catalog:151): `[capabilities.session_tree] enabled` finally
        // has a reader. An armed tree starts empty and grows one node per
        // recorded message — the degenerate single-path case, byte-for-byte
        // the same conversation, until a rewind or branch actually forks it.
        let session_tree = if config.session_tree_enabled {
            Some(crate::session_tree::SessionTree::new())
        } else {
            None
        };
        // BP-7: resolved once here so the request path never re-does the
        // lookup, and so `Self::model_price` is `None` exactly when this
        // build cannot price the model.
        let model_price = crate::pricing::resolve(
            &config.model,
            config.price_input_per_mtok,
            config.price_output_per_mtok,
        );
        // BP-10: same reason — built before `config` moves into the
        // literal. `Config::permissions_approvals_persist` off (the
        // default) makes this the pre-BP-10 in-memory cache and touches no
        // filesystem.
        let permissions_approval_cache = crate::permissions::cache_for_config(&config);
        Agent {
            config,
            provider: std::sync::Arc::from(provider),
            registry,
            history,
            ctx,
            total_output_tokens: 0,
            activated_tools: HashSet::new(),
            recorder: None,
            journal: None,
            session_tree,
            rewind_undo: Vec::new(),
            journaled_plan: Vec::new(),
            reduction_policy: None,
            reduction_log: ReductionLog::default(),
            imported_prefix_len: None,
            compacting_manually: false,
            env_context_live,
            base_prompt_live,
            shell_injection,
            spliced_context_blocks: Vec::new(),
            span_summarizer: None,
            last_tool_schema_tier_signature: None,
            context_limit: None,
            requests_issued: false,
            last_cache_activity_ms: None,
            cache_established: false,
            pending_cache_turn: (false, false, None),
            session_titler: None,
            usage_log: Vec::new(),
            turn_index: 0,
            turn_records: Vec::new(),
            retry_log: std::sync::Arc::new(crate::provider::RetryLog::default()),
            model_price,
            total_cost_usd: 0.0,
            total_steps: 0,
            reaped_subagents: std::collections::HashMap::new(),
            goal: None,
            steer_queue: std::sync::Arc::new(std::sync::Mutex::new(SteerInbox::default())),
            follow_up_queue: std::collections::VecDeque::new(),
            doom_loop_last_call: None,
            doom_loop_streak: 0,
            model_change_log: Vec::new(),
            git_metadata,
            permissions_approval_cache,
            permissions_approval_handler: None,
            mcp_prompts: std::collections::HashMap::new(),
            skills,
            subagent_depth,
            subagent_concurrency_gauge: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            background_subagents: std::collections::HashMap::new(),
            pending_child_approvals: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
            child_approval_handler_factory: None,
            subagent_store: None,
            claude_runtime_manifest: None,
            background_jobs: std::collections::HashMap::new(),
            background_concurrency_gauge: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(
                0,
            )),
            checkpoint_observer,
            lsp_manager,
        }
    }

    /// A handle to this agent's model transport, for sharing with subagents.
    pub fn provider_arc(&self) -> std::sync::Arc<dyn Provider> {
        self.provider.clone()
    }

    /// Read-only access to this agent's resolved [`Config`] — e.g. so a
    /// caller (`crates/cli`'s `attach_mcp`) can consult
    /// [`Config::module_registry`]/[`Config::module_activation`] AFTER
    /// construction without having to separately thread the config through
    /// every call site that builds an `Agent` and later needs it again.
    /// Same trust boundary as every other already-public `Agent` accessor
    /// (`history`, `provider_arc`) — the caller is the same process that
    /// built this `Config` in the first place, not a new exposure surface.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// P5-9 (§2 module 20 `checkpoint`): this agent's checkpoint engine, if
    /// `Config::checkpoint_enabled` is `true` and the shadow store opened
    /// successfully — `None` otherwise (the default-off case, or a
    /// graceful-degrade after an I/O failure). A caller (CLI/TUI/embedder)
    /// uses this to `list`/`turn_diff`/`restore` WITHOUT re-deriving the
    /// shadow-store root itself. Deliberately named `checkpoint_observer`,
    /// not `checkpoint` — [`Self::checkpoint`] already names the unrelated
    /// in-memory conversation-position marker (see that method's doc
    /// comment).
    pub fn checkpoint_observer(&self) -> Option<&crate::checkpoint::CheckpointObserver> {
        self.checkpoint_observer.as_deref()
    }

    /// P5-11 (§2 module 28 `lsp`): this agent's LSP server registry, if
    /// `Config::lsp_enabled` is `true` — `None` otherwise (the default-off
    /// case). `impl Drop for Agent` already covers production teardown via
    /// [`crate::lsp::LspManager::kill_all_sync`] (a real, group-killing OS
    /// process kill — see `crate::lsp`'s module doc). This accessor exists
    /// for an OPTIONAL caller (CLI/TUI/embedder) that manages its own
    /// `Agent` lifecycle and additionally wants to reach
    /// [`crate::lsp::LspManager::shutdown_all`] for a graceful LSP
    /// `shutdown`/`exit` handshake BEFORE dropping the agent — nothing
    /// calls `shutdown_all` automatically today.
    pub fn lsp_manager(&self) -> Option<&crate::lsp::LspManager> {
        self.lsp_manager.as_deref()
    }

    /// Spawn a subagent that shares this agent's model transport, runs `task`
    /// to completion with its own fresh conversation (seeded with `system`), and
    /// returns its final answer. The analog of `Agent` / `spawn_agent`.
    pub async fn run_subagent(
        &self,
        system: impl Into<String>,
        task: impl Into<String>,
    ) -> Result<String> {
        let mut sub_config = Config::builder()
            .model(self.config.model.clone())
            .system_prompt(system)
            .cwd(self.config.cwd.clone())
            .sandbox(self.config.sandbox)
            .max_iterations(self.config.max_iterations)
            .build();
        sub_config.base_url = self.config.base_url.clone();
        let mut sub = Agent::with_provider_arc(sub_config, self.provider.clone());
        sub.send(task).await
    }

    /// Like [`Self::with_provider`] but sharing an existing transport handle.
    pub fn with_provider_arc(mut config: Config, provider: std::sync::Arc<dyn Provider>) -> Self {
        let (ctx, checkpoint_observer, lsp_manager) = build_tool_context(&config);
        let history = vec![ChatMessage::system(config.system_prompt.clone())];
        // P3 (design §5.2): see the `Self::new` doc note — a no-op when
        // `config.module_registry` is off (the default).
        let mut registry = ToolRegistry::from_config(&config);
        // P5-12: see `Self::with_parts`'s identical call — a no-op when
        // `config.plugins_enabled` is `false` (the default).
        crate::plugins::register_into(&config, &mut registry);
        // P4e: see `Self::with_parts`'s identical capture.
        let git_metadata = if config.session_git_metadata {
            crate::git_metadata::capture(&config.cwd, now_ms())
        } else {
            None
        };
        // BP-7 (catalog §4a "Named agent definitions as data"): discover
        // `<cwd>/.claude/agents/*.md` for EVERY harness that turns the
        // subagents module on, not only the Claude emulate/resume path —
        // that restriction was the second half of the ledger row's
        // residue.
        merge_project_agent_definitions(&mut config);
        // P5-3: captured before `config` moves into the literal below (a
        // `usize` field READ, not a move, but it must happen before the
        // `config` shorthand field consumes the binding).
        let subagent_depth = config.subagent_depth;
        // BP-6: this constructor assembles no prompt sections at all (it
        // takes `config.system_prompt` verbatim), so there is no skills
        // INDEX here — but the discovered set still rides along, so an
        // explicit invocation (`/name`, `$slug`, the `skill` tool) resolves
        // the same packages the registry's own `skill` tool holds.
        let skills = crate::skills::load_for_config(&config);
        let base_prompt_live = config.system_prompt.clone();
        let shell_injection = crate::skills::ShellInjection::from_config(&config);
        // BP-8 (catalog:151): `[capabilities.session_tree] enabled` finally
        // has a reader. An armed tree starts empty and grows one node per
        // recorded message — the degenerate single-path case, byte-for-byte
        // the same conversation, until a rewind or branch actually forks it.
        let session_tree = if config.session_tree_enabled {
            Some(crate::session_tree::SessionTree::new())
        } else {
            None
        };
        // BP-7: resolved once here so the request path never re-does the
        // lookup, and so `Self::model_price` is `None` exactly when this
        // build cannot price the model.
        let model_price = crate::pricing::resolve(
            &config.model,
            config.price_input_per_mtok,
            config.price_output_per_mtok,
        );
        // BP-10: see the sibling constructor — built before `config` moves.
        let permissions_approval_cache = crate::permissions::cache_for_config(&config);
        Agent {
            config,
            provider,
            registry,
            history,
            ctx,
            total_output_tokens: 0,
            activated_tools: HashSet::new(),
            recorder: None,
            journal: None,
            session_tree,
            rewind_undo: Vec::new(),
            journaled_plan: Vec::new(),
            reduction_policy: None,
            reduction_log: ReductionLog::default(),
            imported_prefix_len: None,
            compacting_manually: false,
            env_context_live: None,
            // BP-5: this constructor assembles no prompt sections (see the
            // skills note above) — `config.system_prompt` IS the whole
            // system message, so that is what a later `set_model` would
            // have to replace.
            base_prompt_live,
            shell_injection,
            spliced_context_blocks: Vec::new(),
            span_summarizer: None,
            last_tool_schema_tier_signature: None,
            context_limit: None,
            requests_issued: false,
            last_cache_activity_ms: None,
            cache_established: false,
            pending_cache_turn: (false, false, None),
            session_titler: None,
            usage_log: Vec::new(),
            turn_index: 0,
            turn_records: Vec::new(),
            retry_log: std::sync::Arc::new(crate::provider::RetryLog::default()),
            model_price,
            total_cost_usd: 0.0,
            total_steps: 0,
            reaped_subagents: std::collections::HashMap::new(),
            goal: None,
            steer_queue: std::sync::Arc::new(std::sync::Mutex::new(SteerInbox::default())),
            follow_up_queue: std::collections::VecDeque::new(),
            doom_loop_last_call: None,
            doom_loop_streak: 0,
            model_change_log: Vec::new(),
            git_metadata,
            permissions_approval_cache,
            permissions_approval_handler: None,
            mcp_prompts: std::collections::HashMap::new(),
            skills,
            subagent_depth,
            subagent_concurrency_gauge: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            background_subagents: std::collections::HashMap::new(),
            pending_child_approvals: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
            child_approval_handler_factory: None,
            subagent_store: None,
            claude_runtime_manifest: None,
            background_jobs: std::collections::HashMap::new(),
            background_concurrency_gauge: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(
                0,
            )),
            checkpoint_observer,
            lsp_manager,
        }
    }

    /// Run a prompt on a background task, returning a handle that resolves to
    /// the final answer (and the agent, so the caller can continue it). The
    /// analog of background/async agent runs.
    pub fn run_in_background(
        mut self,
        prompt: impl Into<String>,
    ) -> tokio::task::JoinHandle<(Self, Result<String>)>
    where
        Self: Send + 'static,
    {
        let prompt = prompt.into();
        tokio::spawn(async move {
            let result = self.send(prompt).await;
            (self, result)
        })
    }

    /// Build an agent and seed it with a previously-recorded [`Session`] so it
    /// can continue where Claude Code or Codex left off.
    pub fn resume(config: Config, session: Session) -> Result<Self> {
        let mut agent = Agent::new(config)?;
        agent.load_session(session);
        Ok(agent)
    }

    /// Like [`Self::resume`], but also begins recording (A2/A3): a fresh
    /// native-v2 sidecar is created at `sidecar_path` from `session` (header +
    /// `session.raw` verbatim — the imported prefix's own fidelity), and every
    /// subsequent turn this agent produces is appended to it at full fidelity,
    /// independent of whatever `cap_tool_output`/`maybe_compact` (D6) do to
    /// `history`.
    ///
    /// Invariant this establishes ONLY once [`Self::set_reduction_policy`] is
    /// also called (the D6/A7 supersession gate, `Self::run_loop`): at any
    /// instant, `Session::from_native_str(sidecar).messages` equals
    /// `session.messages` (the imported prefix) followed by every message
    /// appended since — i.e. `self.history()[1..]` (`history[0]` is this
    /// agent's own system prompt, per [`Self::load_session`]; it is never
    /// part of `session` and is never written to the sidecar). Recording
    /// alone (no policy) leaves the gate off: `cap_tool_output` still runs on
    /// oversized tool results, and `history` can diverge from the sidecar for
    /// them — honestly, via the notice's "full output in session sidecar"
    /// label, never silently.
    pub fn resume_recorded(
        config: Config,
        session: Session,
        sidecar_path: &std::path::Path,
    ) -> Result<Self> {
        let mut agent = Agent::new(config)?;
        let recorder = SidecarWriter::create(sidecar_path, &session)?;
        agent.load_session(session);
        agent.recorder = Some(recorder);
        Ok(agent)
    }

    /// Install (or replace) this agent's sidecar recorder (A3).
    pub fn set_recorder(&mut self, w: SidecarWriter) {
        self.recorder = Some(w);
    }

    // ---- BP-8: the append-only journal (catalog:150/152/154/156) --------

    /// Install (or replace) this agent's append-only session journal — the
    /// durable, flush-per-record log of every message it produces plus
    /// every queue/rewind/plan operation performed on it. Installing one
    /// alone changes nothing about the conversation; it only makes the
    /// session survive a crash mid-turn.
    pub fn set_journal(&mut self, journal: crate::session_journal::SessionJournal) {
        self.journal = Some(std::sync::Arc::new(std::sync::Mutex::new(journal)));
    }

    /// Whether an append-only journal is installed.
    pub fn has_journal(&self) -> bool {
        self.journal.is_some()
    }

    /// Append one operation to the journal, if installed. Best-effort by
    /// design: losing a durability record must never fail the turn it
    /// describes, so the failure is logged and the loop continues — the
    /// same contract the compaction-marker `record` call keeps.
    fn journal_op(&self, op: crate::session_journal::JournalOp) {
        let Some(journal) = &self.journal else { return };
        let mut guard = journal
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Err(error) = guard.append(op) {
            tracing::warn!("failed to append a session-journal record: {error}");
        }
    }

    /// Declare the durable view caught up: `<name>.jsonl` now holds
    /// `messages` messages and every journal record before this point is
    /// already in it. Everything journaled AFTER the last such record is
    /// exactly what a crash would have lost — see
    /// [`crate::session_journal::JournalState::unpersisted`].
    pub fn journal_checkpoint(&self, messages: usize) {
        self.journal_op(crate::session_journal::JournalOp::Checkpoint { messages });
    }

    /// BP-13: record one per-turn usage entry in the append-only journal.
    pub fn journal_usage(&self, record: &crate::usage_log::UsageRecord) {
        self.journal_op(crate::session_journal::JournalOp::Usage {
            record: record.clone(),
        });
    }

    /// BP-13: record one mid-session model change in the append-only
    /// journal — the ONE persisted home for a routing record (BP-8's
    /// journal), never a second file.
    pub fn journal_model_change(&self, record: &crate::model_change::ModelChangeRecord) {
        self.journal_op(crate::session_journal::JournalOp::ModelChange {
            record: record.clone(),
        });
    }

    /// BP-8 (catalog:151): this session's conversation tree, when the
    /// module is on.
    pub fn session_tree(&self) -> Option<&crate::session_tree::SessionTree> {
        self.session_tree.as_ref()
    }

    /// Install a tree loaded from the store (a resume), replacing whatever
    /// this agent built. A no-op when the module is off — a session whose
    /// preset does not enable `session_tree` must not acquire one through
    /// the back door of an old sidecar.
    pub fn set_session_tree(&mut self, tree: crate::session_tree::SessionTree) {
        if self.config.session_tree_enabled {
            self.session_tree = Some(tree);
        }
    }

    /// BP-8: rebuild the tree from the current linear history — used after
    /// a resume that loaded a transcript but had no `.tree.json` to restore
    /// (every session recorded before the module was on).
    pub fn rebuild_session_tree_from_history(&mut self) {
        if !self.config.session_tree_enabled {
            return;
        }
        let linear: Vec<ChatMessage> = self.history.iter().skip(1).cloned().collect();
        self.session_tree = Some(crate::session_tree::SessionTree::from_linear(
            &linear,
            now_ms(),
        ));
    }

    /// BP-8 (catalog:152 "Rewind/rollback conversation"): move THIS
    /// conversation back to an earlier point — the whole row, not the
    /// last-exchange special case [`Self::rewind_to`] serves and not
    /// `sessions fork --at`, which makes a different session.
    ///
    /// `keep` is a message count (index into `history`), so `keep = 1`
    /// leaves only the system message. Three things happen, in this order:
    ///
    /// 1. the removed tail is pushed onto an undo stack, so
    ///    [`Self::undo_rewind`] can put it back;
    /// 2. a [`crate::session_journal::JournalOp::Rewind`] record is
    ///    APPENDED — nothing is deleted from disk, so the rewound-away
    ///    messages remain recoverable from the log;
    /// 3. when the tree module is on, the active branch's leaf moves to the
    ///    node at `keep`, and the old leaf is preserved under a fresh
    ///    sibling branch — the next message appended forks there rather
    ///    than overwriting.
    ///
    /// Returns what it did. Rewinding to a point at or past the end is a
    /// no-op with `removed = 0`, never an error.
    pub fn rewind_conversation(&mut self, keep: usize) -> RewindOutcome {
        let keep = keep.max(1).min(self.history.len());
        let removed: Vec<ChatMessage> = self.history.split_off(keep);
        if removed.is_empty() {
            return RewindOutcome {
                kept: self.history.len(),
                removed: 0,
                preserved_branch: None,
            };
        }
        let removed_count = removed.len();
        self.rewind_undo.push(removed);
        // `keep` counts the system message; the journal records only
        // `history[1..]`, so its own view is one shorter.
        self.journal_op(crate::session_journal::JournalOp::Rewind { to: keep - 1 });
        let preserved_branch = self.session_tree.as_mut().and_then(|tree| {
            let path = tree.active_path().unwrap_or_default();
            // `keep - 1` messages remain after the system message, so the
            // new leaf is the node at index `keep - 2`.
            match keep.checked_sub(2).and_then(|i| path.get(i).cloned()) {
                Some(node) => tree.rewind(&node, now_ms()).ok().flatten(),
                None => None,
            }
        });
        RewindOutcome {
            kept: self.history.len(),
            removed: removed_count,
            preserved_branch,
        }
    }

    /// BP-8: invert the most recent [`Self::rewind_conversation`] — the
    /// messages come back, and the inversion is itself an appended journal
    /// record. `false` when there is nothing to undo.
    pub fn undo_rewind(&mut self) -> bool {
        let Some(mut tail) = self.rewind_undo.pop() else {
            return false;
        };
        self.history.append(&mut tail);
        self.journal_op(crate::session_journal::JournalOp::Unrewind);
        if self.config.session_tree_enabled {
            self.rebuild_session_tree_from_history();
        }
        true
    }

    /// BP-8 (catalog:150): append messages recovered from the journal
    /// after a crash — they were already recorded, so this deliberately
    /// does NOT re-journal them; it puts the live conversation back where
    /// the interrupted process left it.
    pub fn append_recovered_messages(&mut self, messages: &[ChatMessage]) {
        for msg in messages {
            if let Some(tree) = self.session_tree.as_mut() {
                tree.append_message(msg.clone(), now_ms());
            }
            self.history.push(msg.clone());
        }
    }

    /// BP-8: how many rewinds are currently undoable.
    pub fn undoable_rewinds(&self) -> usize {
        self.rewind_undo.len()
    }

    /// BP-8: restore the undo stack a previous process left in the journal,
    /// so `/rewind undo` works across a restart.
    pub fn restore_rewind_undo(&mut self, stack: Vec<Vec<ChatMessage>>) {
        self.rewind_undo = stack;
    }

    /// BP-8 (catalog:154 "Queued-prompt persistence"): re-queue pending
    /// inputs recovered from the journal WITHOUT re-recording them — they
    /// are already in the log, and journaling them again would double them
    /// on the next restart.
    pub fn restore_queues(&mut self, steer: &[String], follow_up: &[String]) {
        for message in steer {
            self.steer_queue
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .queue_unchecked(message.clone());
        }
        for message in follow_up {
            self.follow_up_queue.push_back(message.clone());
        }
    }

    /// BP-8 (catalog:156 "Todos/plan persisted per session"): the session's
    /// current `update_plan` checklist.
    pub fn plan(&self) -> Vec<crate::session_journal::PlanEntry> {
        self.ctx.plan_snapshot()
    }

    /// BP-8: restore a plan read back from the store on resume. Marked as
    /// already-journaled, so a resume that changes nothing writes nothing.
    pub fn set_plan(&mut self, steps: Vec<crate::session_journal::PlanEntry>) {
        self.ctx.set_plan(steps.clone());
        self.journaled_plan = steps;
    }

    /// BP-8 (catalog:154): record that `count` pending inputs left `queue`
    /// and became conversation. A no-op when nothing was taken, or when
    /// queue persistence is off.
    fn journal_queue_drain(&self, queue: crate::session_journal::QueueKind, count: usize) {
        if count == 0 || !self.config.session_queue_persist {
            return;
        }
        self.journal_op(crate::session_journal::JournalOp::Dequeue { queue, count });
    }

    /// BP-8: journal the plan if `update_plan` changed it since the last
    /// time this ran. Called at every loop boundary — a plan that a crash
    /// would otherwise strand in the tool's memory is on disk within one
    /// iteration of being written.
    fn journal_plan_if_changed(&mut self) {
        if !self.config.todos_persist {
            return;
        }
        let current = self.ctx.plan_snapshot();
        if current == self.journaled_plan {
            return;
        }
        self.journaled_plan.clone_from(&current);
        self.journal_op(crate::session_journal::JournalOp::Plan { steps: current });
    }

    /// Install (or replace) this agent's reduction policy (A5/A7/A10). Once
    /// set, every provider request is built from a *projected* view of
    /// `history[1..]` (`reduce::project_messages`) rather than `history`
    /// verbatim — `history` itself is never shrunk or mutated by this; only
    /// the request view does.
    pub fn set_reduction_policy(&mut self, policy: ReductionPolicy) {
        self.reduction_policy = Some(policy);
    }

    /// This agent's reduction policy, if one is installed.
    pub fn reduction_policy(&self) -> Option<&ReductionPolicy> {
        self.reduction_policy.as_ref()
    }

    /// Change the global tool-schema tier (TR-8/T5) mid-session. Takes effect
    /// starting with the NEXT request this agent builds. Under
    /// [`CachePlan::ImportedPrefix`], the first request built after a change
    /// is flagged as a cache-bust event and its cache-control annotation is
    /// skipped for that one request (see [`provider::tier_change_is_cache_bust`],
    /// consulted in `Self::build_request_messages`) — normal annotation
    /// resumes on the next request if the tier doesn't change again.
    pub fn set_schema_tier(&mut self, tier: crate::tools::SchemaTier) {
        self.config.tool_schema_tier = tier;
    }

    /// Override the schema tier for a single tool (TR-8/T5) mid-session, same
    /// cache-bust interaction as [`Self::set_schema_tier`].
    pub fn set_tool_schema_tier(
        &mut self,
        name: impl Into<String>,
        tier: crate::tools::SchemaTier,
    ) {
        self.config
            .tool_overrides
            .entry(name.into())
            .or_default()
            .schema_tier = Some(tier);
    }

    /// A deterministic fingerprint of the current tool-schema tier
    /// configuration (global knob + every per-tool override), used to detect
    /// a mid-session tier change (TR-8/T5, dev/05). Order-independent over
    /// `tool_overrides` (sorted by name before hashing) so insertion order
    /// never spuriously changes the signature.
    fn schema_tier_signature(&self) -> u64 {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        self.config.tool_schema_tier.hash(&mut hasher);
        let mut overrides: Vec<(&str, crate::tools::SchemaTier)> = self
            .config
            .tool_overrides
            .iter()
            .filter_map(|(name, o)| o.schema_tier.map(|t| (name.as_str(), t)))
            .collect();
        overrides.sort_by_key(|(name, _)| *name);
        for (name, tier) in overrides {
            name.hash(&mut hasher);
            tier.hash(&mut hasher);
        }
        hasher.finish()
    }

    /// Install (or replace) this agent's TR-7 span summarizer — the
    /// injectable side-call `Self::build_request_messages` uses to turn an
    /// A10 `TurnsCleared` span into an LLM-written summary paragraph when
    /// `policy.summarize_cleared_turns` is on. Installing one alone changes
    /// nothing: [`ReductionPolicy::summarize_cleared_turns`] (off by
    /// default) is the actual gate, so tests/callers that want the
    /// deterministic stub can simply never call this.
    pub fn set_span_summarizer(
        &mut self,
        summarizer: impl reduce::summarize::SpanSummarizer + Send + Sync + 'static,
    ) {
        self.span_summarizer = Some(std::sync::Arc::new(summarizer));
    }

    /// Install an already-shared summarizer — same seam as
    /// [`Self::set_span_summarizer`], for callers (and tests) that need to
    /// keep their own handle on it.
    pub fn set_span_summarizer_arc(
        &mut self,
        summarizer: std::sync::Arc<dyn reduce::summarize::SpanSummarizer + Send + Sync>,
    ) {
        self.span_summarizer = Some(summarizer);
    }

    /// Prepare TR-7 metadata with this agent's installed summarizer for a
    /// projection performed by an outer driver before session history/log
    /// are loaded (the CLI foreign-resume preflight). `None` preserves the
    /// deterministic fallback when the gate is off, no summarizer exists,
    /// the span is below the cost floor, or the side-call fails.
    pub fn prepare_cleared_turns_summary(
        &self,
        msgs: &[ChatMessage],
        policy: &ReductionPolicy,
        prior: &ReductionLog,
    ) -> Option<reduce::PreparedClearSummary> {
        let summarizer = self.span_summarizer.as_deref()?;
        reduce::prepare_cleared_turns_summary(msgs, policy, prior, summarizer)
    }

    /// P5-4: install (or replace) this agent's [`crate::EventSink`] AFTER
    /// construction — `Config::event_sink` is otherwise only set at
    /// `Config`-build time (before `Agent::new`), which is too early for a
    /// `tui` embedder that only knows it's activating (and needs to
    /// replace whatever print-mode/REPL sink was already installed with
    /// one that feeds its own render loop instead of writing straight to
    /// stdout) once it already holds a live `Agent`. Mirrors [`Self::
    /// set_permissions_approval_handler`]'s "installing one alone changes
    /// nothing beyond what already consults `Config::event_sink`" pattern
    /// — this is a plain replacement, not a new activation gate.
    pub fn set_event_sink(&mut self, sink: crate::EventSink) {
        self.config.event_sink = Some(sink);
    }

    /// P5-1: install (or replace) this agent's permissions-engine approval
    /// handler — see [`crate::permissions::PermissionsApprovalHandler`].
    /// This is the non-interactive decision seam a CLI/TUI/SDK embedder
    /// implements for the `Ask`-tier prompt; the TUI's actual interactive
    /// UI is a separate module (P5 row 4), not built here. Installing one
    /// alone changes nothing: [`Config::permissions_enabled`] (off by
    /// default) is the actual gate — with no handler installed, every
    /// `Ask`-tier decision denies (fail-closed, see that trait's doc
    /// comment).
    ///
    /// P5-10 (§2 module 12, `escalation = "ask"`): the SAME handler also
    /// backs a sandbox-unenforceable `ask` decision
    /// (`crate::sandbox::decide_fs`'s `approval` parameter) — one installed
    /// seam serves both `permissions.rules`' `Ask` tier and
    /// `permissions.sandbox`'s `escalation = "ask"`, rather than requiring
    /// an embedder to install two near-identical handlers. Kept in sync on
    /// `self.ctx` (not just `self.permissions_approval_handler`) because
    /// `BashTool::execute`/`PersistentShellTool::execute` only ever see
    /// `&ToolContext`, never `&Agent` — see `ToolContext::
    /// sandbox_approval_handler`'s doc comment.
    /// BP-10 (catalog row "Session approval caching"): this agent's
    /// approval cache — the door an embedder/TUI uses to inspect or REVOKE
    /// remembered grants (`ApprovalCache::clear` forgets every one, in
    /// memory and on disk, and the next matching call asks again). Also
    /// how a test proves a grant really did survive the process:
    /// `store_path()` names the file a second agent reads back.
    pub fn permissions_approval_cache(&self) -> &crate::permissions::ApprovalCache {
        &self.permissions_approval_cache
    }

    pub fn set_permissions_approval_handler(
        &mut self,
        handler: impl crate::permissions::PermissionsApprovalHandler + 'static,
    ) {
        let handler: std::sync::Arc<dyn crate::permissions::PermissionsApprovalHandler> =
            std::sync::Arc::new(handler);
        self.permissions_approval_handler = Some(handler.clone());
        self.ctx.sandbox_approval_handler =
            Some(crate::sandbox::SandboxApprovalHandler(handler.clone()));
        // BP-3 (§2 module 8): `exit_plan_mode` presents its plan on this
        // same door — one approval seam for the session, not a second one
        // the operator would have to answer separately.
        self.ctx.approval_handler = Some(crate::tools::ToolApprovalHandler(handler));
    }

    /// BP-3 (§2 module 6 `tools.question`): install the door `ask_user`
    /// asks the human through — the `elicitation/create` handler the design
    /// names as the module's protocol side. SDK-owned frontends pass the
    /// broker-backed handler (`crate::server::FrontendRequestBridge::
    /// elicitation_handler`), which is what makes the question a real
    /// frontend request the turn waits on. `None` (the default, nothing
    /// installed) leaves the tool deny-default: it reports that nobody can
    /// be asked instead of blocking.
    ///
    /// Installing one alone changes nothing about whether the tool EXISTS —
    /// `[capabilities.tools_question]` is that gate, applied by
    /// `crate::tools::ToolRegistry::from_config`.
    pub fn set_user_question_handler(
        &mut self,
        handler: std::sync::Arc<dyn crate::mcp::McpElicitationHandler>,
    ) {
        self.ctx.question_handler = Some(crate::tools::UserQuestionHandler(handler));
    }

    /// BP-3 (§2 module 8): the shared plan-mode state, so a frontend (the
    /// REPL's `/plan`, a TUI toggle) can enter or leave the read-only
    /// research phase the same tools and permission gate see.
    pub fn plan_mode(&self) -> &std::sync::Arc<crate::tools::PlanModeState> {
        &self.ctx.plan_mode
    }

    /// Install the compatibility approval seam used when the composable
    /// permissions engine is disabled. SDK-owned interactive frontends call
    /// this alongside [`Self::set_permissions_approval_handler`] so the same
    /// authenticated request channel works under either policy engine; the
    /// selected engine remains entirely a configuration decision.
    pub fn set_legacy_approval_handler(&mut self, handler: crate::config::ApprovalHandler) {
        self.config.approval_handler = Some(handler);
    }

    /// P5-3 (§2 module 9 D5 "subagent transcripts… persisted + linked"):
    /// install a [`crate::store::SessionStore`] (+ this agent's own session
    /// name in it) so `spawn_subagent` persists each child's transcript
    /// (via [`crate::store::SessionStore::save_subagent_transcript`]) and
    /// lineage record (via
    /// [`crate::store::SessionStore::save_subagent_lineage`]) once the
    /// child finishes. Installing one alone changes nothing about whether
    /// spawning WORKS — [`Config::subagents_enabled`] is the actual gate;
    /// this only controls whether a completed spawn's transcript additionally
    /// lands on disk.
    pub fn set_subagent_store(
        &mut self,
        store: std::sync::Arc<crate::store::SessionStore>,
        session_name: impl Into<String>,
    ) {
        self.subagent_store = Some((store, session_name.into()));
    }

    /// Seed the Claude runtime manifest reconstructed during resume.
    ///
    /// Installing state enables the matching Claude runtime tool schemas so
    /// a disk-reloaded continuation does not lose that vocabulary, but never
    /// starts a timer by itself. The supplied execution posture is preserved:
    /// an embedding scheduler may deliberately activate before installing it.
    pub fn set_claude_runtime_manifest(
        &mut self,
        manifest: crate::claude_runtime_state::ClaudeRuntimeManifest,
    ) {
        // A persisted manifest is itself the compatibility capability marker.
        // Reopening a Supercode session must not retain its timers while
        // silently dropping Claude's Cron*/ScheduleWakeup vocabulary.
        self.config.claude_runtime_tools_enabled = true;
        self.claude_runtime_manifest = Some(manifest);
    }

    /// Reinstall project-scoped Claude named-agent definitions when a
    /// Supercode continuation carrying a Claude runtime manifest is reopened
    /// from disk. The manifest is the durable capability marker; definitions
    /// themselves remain authoritative in `<cwd>/.claude/agents/*.md`.
    pub fn restore_claude_project_agents(&mut self) -> Result<usize> {
        let definitions = crate::claude_compat::load_project_agents(&self.config.cwd)?;
        crate::claude_compat::enable_claude_subagent_compatibility(&mut self.config);
        for imported in &definitions {
            self.config.subagents_definitions.insert(
                imported.definition.name.clone(),
                imported.definition.clone(),
            );
        }
        Ok(definitions.len())
    }

    /// Current imported Claude runtime state, including paused mutations made
    /// by `Cron*`/`ScheduleWakeup`, for persistence by the embedding loop.
    pub fn claude_runtime_manifest(
        &self,
    ) -> Option<&crate::claude_runtime_state::ClaudeRuntimeManifest> {
        self.claude_runtime_manifest.as_ref()
    }

    /// Mutable access for an embedding scheduler driver to atomically claim
    /// due events and persist the resulting manifest. Merely borrowing this
    /// state does not start a timer; execution remains the driver's explicit
    /// responsibility.
    pub fn claude_runtime_manifest_mut(
        &mut self,
    ) -> Option<&mut crate::claude_runtime_state::ClaudeRuntimeManifest> {
        self.claude_runtime_manifest.as_mut()
    }

    /// P5-4 (tui, closes the P5-3 §2.2 C6 deferred chain): install a
    /// factory this agent's `Self::run_spawn_subagent` calls (with the
    /// fresh child's own id and this agent's shared
    /// [`Self::pending_child_approvals`] queue) to build the
    /// `PermissionsApprovalHandler` a `background_prompts = "parent"`
    /// child gets, INSTEAD of the default
    /// [`crate::subagents::ParentQueueApprovalHandler`]. Installing one
    /// alone changes nothing about whether background spawning works —
    /// [`Config::subagents_background_prompts`] being
    /// [`crate::subagents::BackgroundPromptsPolicy::Parent`] is the actual
    /// gate that reaches this factory at all; a `Parent`-policy child
    /// spawned before this is installed (or on an agent that never installs
    /// it) still gets the immediate-deny default, unchanged.
    ///
    /// **Security note.** The factory only controls WHICH handler answers
    /// an `Ask`-tier request — it can never widen what gets asked in the
    /// first place: [`crate::permissions::approval::resolve_ask`] only
    /// calls a handler's `ask` when the rule engine has already resolved
    /// the call to `Ask` (`Deny` short-circuits before any handler is
    /// consulted; `Allow` never needs one), so a parent's "allow" answer
    /// here can only grant what the policy already routed to a prompt —
    /// never override a `Deny` the engine already decided.
    pub fn set_child_approval_handler_factory(
        &mut self,
        factory: impl Fn(
                String,
                std::sync::Arc<std::sync::Mutex<Vec<crate::subagents::QueuedApproval>>>,
            ) -> std::sync::Arc<dyn crate::permissions::PermissionsApprovalHandler>
            + Send
            + Sync
            + 'static,
    ) {
        self.child_approval_handler_factory = Some(std::sync::Arc::new(factory));
    }

    /// P5-3 (§2.2 C6 "parent-surfaced queue"): every approval request a
    /// `background_prompts = "parent"` child has raised so far, oldest
    /// first — a read-only audit view, not a mutable queue the caller
    /// answers. Under P5-3's own default handler (no P5-4 TUI factory
    /// installed) every entry here WAS already resolved `Deny` (a
    /// background call can't wait for an answer with no handler
    /// installed) — but once a `crate::tui::TuiChildApprovalHandler`
    /// factory is installed (P5-4,
    /// [`Self::set_child_approval_handler_factory`]), the underlying call
    /// genuinely blocks and may resolve `Allow`/`AllowForSession`; this
    /// method still records the SAME entry for the audit trail either
    /// way, so "queued here" no longer implies "was denied" in general —
    /// see [`crate::subagents::QueuedApproval`]'s doc comment.
    pub fn pending_child_approvals(&self) -> Vec<crate::subagents::QueuedApproval> {
        self.pending_child_approvals
            .lock()
            .map(|q| q.clone())
            .unwrap_or_default()
    }

    /// P4b: install (or replace) this agent's auto-title side-call — see
    /// [`crate::session_title::SessionTitler`]. Installing one alone changes
    /// nothing: [`Config::auto_title`] (off by default) is the actual gate a
    /// caller should consult before calling [`Self::auto_title`].
    pub fn set_session_titler(
        &mut self,
        titler: impl crate::session_title::SessionTitler + Send + Sync + 'static,
    ) {
        self.session_titler = Some(std::sync::Arc::new(titler));
    }

    /// P4b: produce a title for this agent's current conversation via the
    /// installed [`Self::set_session_titler`] side-call. Returns `None` (never
    /// panics, never blocks longer than the titler itself does) if no
    /// titler is installed, or the side-call itself declined (see
    /// [`crate::session_title::auto_title`]). Does NOT consult
    /// [`Config::auto_title`] itself — that gate is the caller's
    /// responsibility, matching `Self::span_summarizer`'s precedent of
    /// keeping the mechanism and the policy gate separate.
    pub fn auto_title(&self) -> Option<String> {
        let titler = self.session_titler.as_deref()?;
        crate::session_title::auto_title(&self.history, titler)
    }

    /// P4b (§1.6, catalog §4a "persisted per-turn usage records"): every
    /// [`crate::usage_log::UsageRecord`] this agent has accumulated so far.
    pub fn usage_records(&self) -> &[crate::usage_log::UsageRecord] {
        &self.usage_log
    }

    /// P4b: persist this agent's accumulated usage log to `store` under
    /// `name` — a thin wrapper over [`crate::store::SessionStore::save_usage_log`]
    /// so callers don't need to import both types.
    pub fn save_usage_log(&self, store: &crate::store::SessionStore, name: &str) -> Result<()> {
        store.save_usage_log(name, &self.usage_log)
    }

    /// BP-7 (catalog §4a "Turn/step bracketing records"): every
    /// [`crate::turn_record::TurnRecord`] this agent has accumulated —
    /// the context/usage/finish brackets of each model round-trip plus the
    /// retry, abort, effort and goal markers between them.
    pub fn turn_records(&self) -> &[crate::turn_record::TurnRecord] {
        &self.turn_records
    }

    /// BP-7: persist the marker log to `store` under `name`
    /// (`<name>.events.jsonl`), the same thin-wrapper shape
    /// [`Self::save_usage_log`] has.
    pub fn save_turn_records(&self, store: &crate::store::SessionStore, name: &str) -> Result<()> {
        store.save_turn_records(name, &self.turn_records)
    }

    /// BP-7 (catalog §4a "Per-turn cost/usage accounting"): dollars this
    /// agent has spent so far. `0.0` when the model is unpriceable — read
    /// [`Self::model_priced`] to tell "free" from "unknown".
    pub fn total_cost_usd(&self) -> f64 {
        self.total_cost_usd
    }

    /// BP-7: whether this build can price this agent's model, i.e. whether
    /// [`Self::total_cost_usd`] is a real figure rather than a floor.
    pub fn model_priced(&self) -> bool {
        self.model_price.is_some()
    }

    /// BP-7 (catalog §4a "Turn/budget caps"): tool calls this agent has
    /// executed so far — the counter [`Config::max_steps`] bounds.
    pub fn total_steps(&self) -> usize {
        self.total_steps
    }

    /// BP-7 (catalog §4a "Interrupt/abort with state preserved"): record
    /// that the in-flight turn was interrupted.
    ///
    /// Called by whoever owns the cancellation (the CLI's Ctrl-C race), NOT
    /// by the loop itself: a cancelled `send` future is dropped mid-await,
    /// so the loop never runs another line. The partial work already
    /// appended to the transcript stands; this marker is what makes the
    /// interruption a persisted FACT — the residue the ledger row named —
    /// rather than something a reader has to infer from a dangling tool
    /// call on reload. Emits [`AgentEvent::TurnAborted`] as the live
    /// counterpart.
    pub fn note_abort(&mut self, source: &str) {
        let messages = self.history.len();
        self.emit(AgentEvent::TurnAborted {
            source: source.to_string(),
        });
        self.push_turn_marker(crate::turn_record::TurnMarker::Aborted {
            source: source.to_string(),
            messages,
        });
    }

    // ---- BP-7: goals (catalog §4a "Goals — persistent objective across
    // turns"; §2 module 7 `todos`, §3.1 `capabilities.todos.goals`) ----

    /// Set (or revise) this session's standing objective.
    ///
    /// Returns `false`, changing nothing, when `capabilities.todos.goals`
    /// is off — the module gate, not a silent success. A goal restates
    /// itself at the tail of every request until [`Self::clear_goal`], and
    /// each change appends a `goal` marker to the turn-record log.
    pub fn set_goal(&mut self, objective: impl Into<String>) -> bool {
        if !self.config.goals_enabled {
            return false;
        }
        let objective = objective.into();
        let now = now_ms();
        match &mut self.goal {
            Some(goal) => goal.revise(objective.clone(), now),
            slot @ None => *slot = Some(crate::goals::GoalRecord::new(objective.clone(), now)),
        }
        self.push_turn_marker(crate::turn_record::TurnMarker::Goal { objective });
        true
    }

    /// This session's standing objective, if one is set.
    pub fn goal(&self) -> Option<&crate::goals::GoalRecord> {
        self.goal.as_ref()
    }

    /// Drop the standing objective. `true` when there was one to drop.
    pub fn clear_goal(&mut self) -> bool {
        if self.goal.take().is_none() {
            return false;
        }
        self.push_turn_marker(crate::turn_record::TurnMarker::Goal {
            objective: String::new(),
        });
        true
    }

    /// BP-7: persist (or, when cleared, remove) the standing objective
    /// beside the session — same thin-wrapper shape as
    /// [`Self::save_usage_log`].
    pub fn save_goal(&self, store: &crate::store::SessionStore, name: &str) -> Result<()> {
        match &self.goal {
            Some(goal) => store.save_goal(name, goal),
            None => store.clear_goal(name),
        }
    }

    /// BP-7: adopt a goal loaded from the store (a resumed session picks up
    /// exactly where it left off). Bypasses the module gate on purpose: a
    /// goal already persisted is data to restore, not a new capability
    /// being turned on, and dropping it silently would lose session state.
    pub fn restore_goal(&mut self, goal: Option<crate::goals::GoalRecord>) {
        self.goal = goal;
    }

    // ---- BP-7: extended-thinking control (catalog §4a "Extended thinking
    // control": "Reasoning on/off/levels mid-session") ----

    /// The reasoning-effort level in force for the NEXT request, or `None`
    /// when extended thinking is off.
    pub fn effort(&self) -> Option<&str> {
        self.config.effort.as_deref()
    }

    /// Change the reasoning-effort level mid-session.
    ///
    /// `Some(level)` sets the level; `None` turns extended thinking OFF —
    /// the on/off toggle the ledger row named as distinct from the level.
    /// `run_loop` reads `self.config.effort` fresh when it builds each
    /// `ChatRequest`, so this takes effect on the very next request with no
    /// other copy to update (the same contract [`Self::set_model`] has).
    /// The change is appended to the turn-record log as an `effort` marker,
    /// the extended-thinking analog of the `model_change` log.
    ///
    /// Returns the PREVIOUS setting.
    pub fn set_effort(&mut self, effort: Option<String>) -> Option<String> {
        let previous = self.config.effort.clone();
        if previous == effort {
            return previous;
        }
        self.config.effort = effort.clone();
        self.push_turn_marker(crate::turn_record::TurnMarker::Effort {
            from: previous.clone(),
            to: effort,
        });
        previous
    }

    // ---- BP-7: review mode (catalog §4a "Review mode — dedicated
    // code-review flow"; §3.1 `[core.prompts]`) ----

    /// The purpose-built review turn's prompt: the `code-review` template
    /// from [`Config::prompts`] with `{args}` replaced by `args`.
    ///
    /// `None` when the resolved config carries no `code-review` template —
    /// the preset decides whether this harness has a review mode, and the
    /// template IS the report format (both parity presets pin one).
    pub fn review_prompt(&self, args: &str) -> Option<String> {
        self.config
            .prompts
            .get(REVIEW_PROMPT_NAME)
            .map(|template| template.replace("{args}", args.trim()))
    }

    /// Run the review turn: an ordinary [`Self::send`] of
    /// [`Self::review_prompt`], so the review's request, tools, transcript
    /// and records are the session's own — a purpose-built TURN, not a
    /// second agent.
    pub async fn review(&mut self, args: &str) -> Result<String> {
        let prompt = self.review_prompt(args).ok_or_else(|| {
            Error::Other(format!(
                "no `{REVIEW_PROMPT_NAME}` prompt template is configured for this harness"
            ))
        })?;
        self.send(prompt).await
    }

    // ---- BP-7: side/ephemeral Q&A (catalog §4a "Side/ephemeral Q&A":
    // "Tool-less question over full context, never enters history") ----

    /// Answer `question` over this session's FULL current context without
    /// recording anything.
    ///
    /// Three properties, all load-bearing and all asserted by this build's
    /// tests: the request carries the whole conversation as the next turn
    /// would see it; it advertises NO tools, so the model can only answer;
    /// and neither `history`, the sidecar recorder, the usage log nor the
    /// turn-record log is touched — `&self`, not `&mut self`, is the type
    /// system saying so. cc's `/btw` and cx's `/side`.
    pub async fn side_question(&self, question: &str) -> Result<String> {
        let mut messages = self.history.clone();
        if let Some(goal) = &self.goal {
            messages.push(ChatMessage::system(goal.reminder()));
        }
        messages.push(ChatMessage::user(format!(
            "{SIDE_QUESTION_PREAMBLE}

{question}"
        )));
        let mut req = ChatRequest {
            model: self.config.model.clone(),
            messages,
            tools: Vec::new(),
            temperature: self.config.temperature,
            max_tokens: self.config.max_tokens,
            effort: self.config.effort.clone(),
            response_format: None,
            service_tier: None,
            thinking_budget: None,
            extra_body: self.config.extra_body.clone(),
        };
        // BP-13: a side question is still a request to THIS model, so it
        // carries the same routing decisions the loop's own requests do.
        self.apply_routing(&mut req);
        let (assistant, _usage) = self.provider.complete(&req, &|_: &str| {}).await?;
        Ok(assistant.content.unwrap_or_default())
    }

    /// BP-7: append one marker against the NEXT round-trip's index — the
    /// right frame for a marker written between turns (a goal change, an
    /// effort change, an abort).
    fn push_turn_marker(&mut self, marker: crate::turn_record::TurnMarker) {
        self.push_turn_marker_at(self.turn_index, marker);
    }

    /// BP-7: append one marker against an explicit round-trip index — used
    /// inside `Self::run_loop`, where markers are written on both sides of
    /// the `turn_index` advance and must all carry the round-trip they
    /// describe.
    fn push_turn_marker_at(&mut self, turn: usize, marker: crate::turn_record::TurnMarker) {
        self.turn_records.push(crate::turn_record::TurnRecord::new(
            turn,
            &self.config.model,
            now_ms(),
            marker,
        ));
    }

    /// P4b (§1.7, pi§3 semantics): queue a mid-turn steering message —
    /// delivered "after current tool calls" (pi's phrasing): at the top of
    /// `Self::run_loop`'s NEXT iteration, before the next model request is
    /// built, regardless of whether this turn is still mid-flight with
    /// pending tool calls. Drained per [`Config::steering_mode`].
    pub fn queue_steer(&self, message: impl Into<String>) {
        let message = message.into();
        // BP-8 (catalog:154 "Queued-prompt persistence"): the input is
        // recorded BEFORE it is queued, so the window in which a crash
        // could lose it is zero. A no-op when `core.session.queue_persist`
        // is off (cx-parity: stock Codex has no queue-operation records).
        if self.config.session_queue_persist {
            self.journal_op(crate::session_journal::JournalOp::Enqueue {
                queue: crate::session_journal::QueueKind::Steer,
                text: message.clone(),
            });
        }
        self.steer_queue
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .queue_unchecked(message);
    }

    /// Crate-internal shared steering handle used by the canonical SDK
    /// runtime. It remains writable while an active turn holds `&mut Agent`,
    /// allowing local and remote frontends to steer without owning the loop.
    pub(crate) fn steer_queue_handle(&self) -> std::sync::Arc<std::sync::Mutex<SteerInbox>> {
        self.steer_queue.clone()
    }

    /// P4b: queue a follow-up message — delivered "at idle" (pi's phrasing):
    /// only once `Self::run_loop` would otherwise return a final answer
    /// (no more tool calls pending). Drained per [`Config::follow_up_mode`].
    pub fn queue_follow_up(&mut self, message: impl Into<String>) {
        let message = message.into();
        // BP-8 (catalog:154): same record-then-queue order as
        // [`Self::queue_steer`].
        if self.config.session_queue_persist {
            self.journal_op(crate::session_journal::JournalOp::Enqueue {
                queue: crate::session_journal::QueueKind::FollowUp,
                text: message.clone(),
            });
        }
        self.follow_up_queue.push_back(message);
    }

    /// P4b: how many steering messages are currently queued (mid-turn +
    /// follow-up combined) — mostly for tests/diagnostics.
    pub fn queued_steer_count(&self) -> usize {
        self.steer_queue
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len()
            + self.follow_up_queue.len()
    }

    /// The accumulating reduction log (A5) — every reduction applied to any
    /// projected request view so far. Combined with a full-fidelity sidecar
    /// Session, this is enough to `reduce::invert` any projected view back to
    /// the exact original.
    pub fn reduction_log(&self) -> &ReductionLog {
        &self.reduction_log
    }

    /// PARITY-18 D4 — arm the per-send context guard: `Self::run_loop`
    /// will refuse (via [`Error::ContextLimitExceeded`]) to build and issue
    /// ANY request — the first or any later turn — whose
    /// [`crate::tokens::context_guard`] verdict is "does not fit" against
    /// `limit`. Call this once the target model's context-window size is
    /// known (`resume --reduced`'s preflight already computes it). Leaving
    /// this unset (the default) is a no-op: no guard runs, exactly today's
    /// pre-PARITY-18 behavior.
    pub fn set_context_limit(&mut self, limit: u64) {
        self.context_limit = Some(limit);
    }

    /// This agent's armed context limit, if [`Self::set_context_limit`] has
    /// been called.
    pub fn context_limit(&self) -> Option<u64> {
        self.context_limit
    }

    /// The model identifier this agent sends on its next request
    /// ([`Config::model`], as of construction/resume or the last
    /// [`Self::set_model`] call).
    pub fn model(&self) -> &str {
        &self.config.model
    }

    /// UX-30 dev/02 — switch the model this agent sends, starting with the
    /// NEXT request it builds (and every one after, until changed again).
    /// `Self::run_loop` reads `self.config.model` fresh on every request
    /// (see its `ChatRequest` construction), so this alone is enough —
    /// there is no cached/baked-in copy anywhere else to also update.
    /// Takes effect immediately; safe to call only between turns (the
    /// REPL's `/model` picker runs at the prompt, never mid-turn). Touches
    /// nothing else: history, the sidecar, and reduction state are exactly
    /// as untouched as [`Self::set_schema_tier`] leaves them for a
    /// mid-session tier change.
    ///
    /// P4c-review note: this is the LOW-LEVEL primitive — it swaps
    /// [`Config::model`] and nothing else. It does NOT run dep 8's
    /// reasoning-artifact filter
    /// ([`reduce::rehydrate::filter_reasoning_artifacts`]) and does NOT
    /// create a [`crate::model_change::ModelChangeRecord`], so calling it
    /// directly for a mid-session handoff between two DIFFERENT models
    /// leaves model-A's reasoning artifacts in `history` for model-B to
    /// inherit. [`Self::switch_model`] is the safe superset — gated by
    /// [`Config::model_switch_allow_switch`], it filters and records the
    /// switch before delegating to this method — and is what callers
    /// performing a governed mid-session model switch should use instead.
    pub fn set_model(&mut self, model: impl Into<String>) {
        self.config.model = model.into();
        // BP-5 (catalog D2 "Per-model-family base-prompt selection"): the
        // family's base prompt follows the model. Codex re-selects
        // `base_instructions` when the model changes; leaving model-A's
        // base prompt in front of model-B is exactly the mismatch the row
        // exists to prevent. Same locate-and-replace mechanism
        // `refresh_env_context` uses, and a no-op whenever the selection
        // did not actually change (always, for a config with no family
        // table).
        self.refresh_base_prompt();
        // BP-7: the price follows the model, or the per-turn cost figure
        // would keep billing the OLD model's rates after a switch.
        self.model_price = crate::pricing::resolve(
            &self.config.model,
            self.config.price_input_per_mtok,
            self.config.price_output_per_mtok,
        );
    }

    /// P4c (§1.10/§3.1 `core.model_switch.allow_switch`, D9 row, dep 8,
    /// design's "core NEW-significant" item): the mid-session model
    /// switch — a superset of [`Self::set_model`] gated by
    /// [`Config::model_switch_allow_switch`].
    ///
    /// **`allow_switch = false` (the default): EXACTLY [`Self::set_model`]**
    /// — same single field write, nothing else touched, no
    /// [`crate::model_change::ModelChangeRecord`] created. Byte-identical to
    /// calling `set_model` directly.
    ///
    /// **`allow_switch = true`:** additionally, before the swap takes
    /// effect, runs [`reduce::rehydrate::filter_reasoning_artifacts`] over
    /// [`Self::history`] — model-A's reasoning/thinking artifacts (any
    /// [`crate::message::ChatMessage::metadata`] key in
    /// [`reduce::rehydrate::REASONING_METADATA_KEYS`], any `content_parts`
    /// block whose `"type"` is in
    /// [`reduce::rehydrate::REASONING_CONTENT_PART_TYPES`]) are stripped
    /// BEFORE model-B ever builds a request from this history — then
    /// appends a typed, translatable [`crate::model_change::ModelChangeRecord`]
    /// to [`Self::model_change_records`] (persist it via
    /// [`Self::save_model_change_log`]). A switch TO the current model
    /// (`model == Self::model()`) is treated as a no-op — still exactly
    /// `set_model`'s mechanics, no record for a switch that didn't actually
    /// change anything (and nothing to filter FOR, since there was no
    /// handoff).
    pub fn switch_model(&mut self, model: impl Into<String>) {
        let to = model.into();
        if !self.config.model_switch_allow_switch || self.config.model == to {
            self.set_model(to);
            return;
        }
        let from = self.config.model.clone();
        self.record_model_change(&from, &to, None);
    }

    /// BP-13 — the ONE place a mid-session model change is performed and
    /// recorded, shared by [`Self::switch_model`] (a user asked) and the
    /// run loop's fallback pass (a provider failed).
    ///
    /// It does four things, in this order, and nothing else: strips model-A
    /// reasoning artifacts out of the live history (dep 8 — model B must
    /// never inherit them), moves [`Config::model`], appends the typed
    /// [`crate::model_change::ModelChangeRecord`], and writes that same
    /// record into the append-only session journal (BP-8) — which is where
    /// every persisted routing record lives; there is no second file. The
    /// change is also EMITTED, so a surface that renders events shows the
    /// switch instead of silently answering as a different model.
    pub fn record_model_change(&mut self, from: &str, to: &str, reason: Option<&str>) {
        if from == to {
            return;
        }
        let touched = reduce::rehydrate::filter_reasoning_artifacts(&mut self.history);
        self.set_model(to.to_string());
        let record = crate::model_change::ModelChangeRecord::new(
            self.turn_index,
            from,
            to,
            true,
            touched,
            now_ms(),
        )
        .with_reason(reason.map(str::to_string));
        self.journal_model_change(&record);
        self.model_change_log.push(record);
        self.emit(AgentEvent::ModelChanged {
            from: from.to_string(),
            to: to.to_string(),
            reason: reason.map(str::to_string),
        });
        // A switch also re-injects the switch NOTICE when the config asks
        // for one (Codex's own mid-session behavior: the conversation is
        // told the model changed, so the new model reads the handoff rather
        // than inferring it from a style break).
        if self.config.model_switch_notice {
            let notice = ChatMessage::user(format!(
                "[model changed: {from} -> {to}{}]",
                match reason {
                    Some(r) => format!(" ({r})"),
                    None => String::new(),
                }
            ));
            let _ = self.record(&notice);
            self.history.push(notice);
        }
    }

    /// BP-13 (catalog D9 "Fast mode / service tiers"): set or clear the
    /// session-level service-tier override. `Some(tier)` WINS over the
    /// `[capabilities.model_catalog] service_tier` rule for every
    /// subsequent request (it is the live toggle the user just pulled);
    /// `None` puts the configured rule back in charge. Takes effect on the
    /// next request the loop builds, like [`Self::set_model`].
    pub fn set_service_tier(&mut self, tier: Option<String>) {
        self.config.service_tier = tier;
    }

    /// BP-13 — apply the routing table to a request that already names its
    /// model: effort LEVEL (per-model override of `[core] effort`, clamped
    /// by whichever effort cap applies), thinking-token BUDGET, and service
    /// TIER (the live `/fast` override winning over the configured rule).
    /// Called for every request the loop builds AND again for every
    /// fallback hop, so a hop to a different model gets that model's
    /// routing rather than the previous model's.
    fn apply_routing(&self, req: &mut ChatRequest) {
        let routing = &self.config.model_routing;
        let rules = routing.rules_for(&req.model);
        // Plan mode's own effort tier, when the mode is live, is the
        // session level for this request — Codex's `/plan` is effort
        // steering (cx§6), so planning need not think at the executing
        // level. It is still clamped by whatever effort cap applies,
        // because `effective_effort` does the clamping, not this line.
        let session_effort = match (
            self.ctx.plan_mode.is_active(),
            self.config.plan_mode_effort.as_deref(),
        ) {
            (true, Some(effort)) => Some(effort),
            _ => self.config.effort.as_deref(),
        };
        req.effort = routing.effective_effort(&req.model, session_effort);
        req.thinking_budget = rules.thinking_budget;
        req.service_tier = self.config.service_tier.clone().or(rules.service_tier);
    }

    /// BP-13 — send `req`, walking [`Config::model_fallback`] when the
    /// failure is one another model could plausibly answer.
    ///
    /// Returns the final outcome plus the hops actually taken, so the
    /// caller (which owns `&mut self`) can record each one. Each hop
    /// re-applies routing for the new model and strips model-A reasoning
    /// artifacts from the request's own message copy before model B sees
    /// them — the same dep-8 guarantee [`Self::record_model_change`] gives
    /// the live history.
    async fn complete_with_fallback(
        &self,
        req: &mut ChatRequest,
        on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> (Result<(ChatMessage, provider::Usage)>, Vec<FallbackHop>) {
        let mut hops = Vec::new();
        let mut result = self.provider.complete(req, on_delta).await;
        for next in &self.config.model_fallback {
            let Err(error) = &result else {
                break;
            };
            if !is_failover_worthy(error) {
                break;
            }
            if next.is_empty() || next == &req.model {
                continue;
            }
            let reason = error.to_string();
            let from = std::mem::replace(&mut req.model, next.clone());
            reduce::rehydrate::filter_reasoning_artifacts(&mut req.messages);
            self.apply_routing(req);
            hops.push(FallbackHop {
                from,
                to: next.clone(),
                reason,
            });
            result = self.provider.complete(req, on_delta).await;
        }
        (result, hops)
    }

    /// P4c: every [`crate::model_change::ModelChangeRecord`] this agent has
    /// accumulated so far (via [`Self::switch_model`] with `allow_switch`
    /// on). Empty when the knob is off or no switch has happened yet.
    pub fn model_change_records(&self) -> &[crate::model_change::ModelChangeRecord] {
        &self.model_change_log
    }

    /// P4c: persist this agent's accumulated model-change log to `store`
    /// under `name` — the [`crate::model_change::ModelChangeRecord`] analog
    /// of [`Self::save_usage_log`].
    pub fn save_model_change_log(
        &self,
        store: &crate::store::SessionStore,
        name: &str,
    ) -> Result<()> {
        store.save_model_change_log(name, &self.model_change_log)
    }

    /// P4e (§1.6/§3.1 `core.session.git_metadata`, catalog:331): this
    /// agent's captured git provenance, if [`Config::session_git_metadata`]
    /// was on at construction and the best-effort probe found a repo.
    pub fn git_metadata(&self) -> Option<&crate::git_metadata::GitMetadataRecord> {
        self.git_metadata.as_ref()
    }

    /// P4e: persist this agent's captured git metadata to `store` under
    /// `name` — a thin wrapper over
    /// [`crate::store::SessionStore::save_git_metadata`], the
    /// [`crate::git_metadata::GitMetadataRecord`] analog of
    /// [`Self::save_usage_log`]. A no-op (`Ok(())`, nothing written) when
    /// [`Self::git_metadata`] is `None`.
    pub fn save_git_metadata(&self, store: &crate::store::SessionStore, name: &str) -> Result<()> {
        match &self.git_metadata {
            Some(record) => store.save_git_metadata(name, record),
            None => Ok(()),
        }
    }

    /// P4e DEFECT-FIX (independent Fable-5 review of P4e: `core.session.persist`
    /// had a `Config` field and CLI plumbing at `ConfigProfile` → `Config` but
    /// no consumer at all): whether a CLI caller's session-store save sites
    /// (`persist_session`, `persist_full_view`) should actually write to
    /// disk. `true` (the default) is byte-identical to pre-fix behavior —
    /// every session persists. `false` makes a session ephemeral: it runs
    /// exactly as before, but no `<name>.jsonl`/sidecar family is ever
    /// written for it. A plain getter, same posture as [`Self::model`] —
    /// this crate itself never reads or enforces it; the CLI's save sites do.
    pub fn session_persist(&self) -> bool {
        self.config.session_persist
    }

    /// P4e DEFECT-FIX (independent Fable-5 review of P4e: `core.session.name`
    /// had a `Config` field and CLI plumbing but no consumer): the
    /// caller-configured session name, if `[core.session] name` was set.
    /// `None` (the default) leaves session naming exactly as before —
    /// `mint_session_name`'s auto-generated `<tag>-<adjective>-<noun>` shape.
    /// A plain getter, same posture as [`Self::session_persist`].
    pub fn session_name(&self) -> Option<&str> {
        self.config.session_name.as_deref()
    }

    /// PARITY-18 D3 — whether this agent has actually issued at least one
    /// live request to its [`Provider`] so far (set the instant
    /// `Self::run_loop` reaches its real send site, regardless of whether
    /// that call then succeeds or fails). Callers should report
    /// "request sent" from THIS, never from having merely passed the
    /// context guard or having called [`Self::send`] — either of those can
    /// happen with zero requests actually issued (a guard refusal, an
    /// interactive session quit before any turn completes).
    pub fn request_issued(&self) -> bool {
        self.requests_issued
    }

    /// P5-2 (§2.2 C2): whether this agent currently considers its
    /// [`CachePlan::ImportedPrefix`] cache entry warm — mirrors
    /// [`Self::request_issued`]'s read-only-observability precedent, so a
    /// caller (or a test) can confirm [`Self::register_tool`]'s C2
    /// invalidation actually took effect without reaching into private
    /// state.
    pub fn cache_established(&self) -> bool {
        self.cache_established
    }

    /// B7: length of the imported-prefix protected by [`CachePlan::ImportedPrefix`]
    /// (this agent's own system message plus every message of a
    /// previously-imported session), set by [`Self::load_session`]. `None`
    /// until a session has been loaded.
    pub fn imported_prefix_len(&self) -> Option<usize> {
        self.imported_prefix_len
    }

    /// Replace this agent's accumulating reduction log (C4: `/expand`/`/reduce`
    /// mutate the log directly via `reduce::invert_one`/`reduce::project_messages`
    /// and must feed the result back here so the *next* request build or
    /// persist sees the updated state instead of silently recomputing from an
    /// empty log). Also lets a caller (`resume_cmd`, C1) seed the log with the
    /// initial projection it already computed for the entry banner, so
    /// `reduction_log()` reflects reality even before this agent's first
    /// `send()` (which is otherwise the only place `build_request_messages`
    /// populates it).
    pub fn set_reduction_log(&mut self, log: ReductionLog) {
        self.reduction_log = log;
    }

    /// Replace the conversation with a loaded session, keeping this agent's own
    /// system prompt at the front. The session's own system/developer turns are
    /// preserved after it for context.
    pub fn load_session(&mut self, session: Session) {
        let system = self.history.first().cloned();
        self.history.clear();
        if let Some(sys) = system {
            self.history.push(sys);
        }
        self.history.extend(session.messages);
        // B7: the whole of `history` at this point — this agent's own system
        // message plus every imported message — is the stable prefix a
        // resumed session resends byte-identically every turn.
        self.imported_prefix_len = Some(self.history.len());
        // UX-26 (B7-warn): a freshly loaded prefix has no established cache
        // entry of THIS agent's own making yet (even if this agent was
        // resumed once before — that earlier prefix is gone). Seed the
        // activity clock from the loaded session's own last message
        // timestamp (walking backward past any trailing message that
        // carries none), so a session that's been sitting idle since
        // Claude Code/Codex/a prior supercode run last touched it is
        // correctly treated as already-cold on its very first turn here —
        // `None` (no timestamp anywhere in the loaded messages) leaves the
        // TTL check disarmed rather than guessing.
        self.cache_established = false;
        self.last_cache_activity_ms = self
            .history
            .iter()
            .rev()
            .find_map(|m| m.metadata.get("timestamp"))
            .and_then(|ts| crate::sidecar::rfc3339_to_ms(ts));
    }

    /// Append `msg` to the sidecar recorder (A3), if one is installed — a
    /// no-op, at zero cost, when `recorder` is `None` (today's behavior).
    fn record(&mut self, msg: &ChatMessage) -> Result<()> {
        if let Some(recorder) = self.recorder.as_mut() {
            recorder.append(msg)?;
        }
        // BP-8 (catalog:150): the append-only half — written and FLUSHED
        // here, at the moment the message exists, not at the end of the
        // turn. A journal failure is logged, never fatal: durability
        // bookkeeping must not be able to fail a turn.
        if let Some(journal) = &self.journal {
            let mut guard = journal
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if let Err(error) = guard.append_message(msg) {
                tracing::warn!("failed to journal a message: {error}");
            }
        }
        // BP-8 (catalog:151): the same message becomes a tree node, so the
        // tree and the linear history never disagree about what was said.
        if let Some(tree) = self.session_tree.as_mut() {
            tree.append_message(msg.clone(), now_ms());
        }
        Ok(())
    }

    /// Persist the live conversation to `path` as JSONL (one [`ChatMessage`]
    /// per line) so the session can be resumed later — supercode's own sessions
    /// become first-class, resumable artifacts.
    pub fn save_transcript(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
        let mut out = String::new();
        for m in &self.history {
            out.push_str(&serde_json::to_string(m).map_err(Error::Decode)?);
            out.push('\n');
        }
        std::fs::write(path, out)?;
        Ok(())
    }

    /// Restore a conversation previously written with [`Self::save_transcript`],
    /// replacing the current history.
    pub fn load_transcript(&mut self, path: impl AsRef<std::path::Path>) -> Result<()> {
        let text = std::fs::read_to_string(path)?;
        let mut history = Vec::new();
        for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) {
            history.push(serde_json::from_str::<ChatMessage>(line).map_err(Error::Decode)?);
        }
        self.history = history;
        Ok(())
    }

    /// Take a checkpoint of the current conversation position. Pass it to
    /// [`Self::rewind_to`] to discard everything sent since (the rewind/undo
    /// analog of `fork`/checkpoint).
    pub fn checkpoint(&self) -> usize {
        self.history.len()
    }

    /// Rewind the conversation to a [`Self::checkpoint`], discarding later turns.
    pub fn rewind_to(&mut self, checkpoint: usize) {
        self.history.truncate(checkpoint.min(self.history.len()));
    }

    /// Send a message with file inputs attached — the `--file` / `-i` analog.
    /// Each file's contents are injected into the prompt: UTF-8 text inline,
    /// binary (e.g. images) noted with a size marker. (Native image *vision*
    /// would additionally require multimodal content parts.)
    pub async fn send_with_files(
        &mut self,
        text: impl Into<String>,
        files: &[std::path::PathBuf],
    ) -> Result<String> {
        let mut prompt = text.into();
        for path in files {
            let block = match std::fs::read(path) {
                Ok(bytes) => match String::from_utf8(bytes.clone()) {
                    Ok(s) => format!("\n\n[file: {}]\n{}", path.display(), s),
                    Err(_) => format!(
                        "\n\n[file: {}{} bytes, binary content omitted]",
                        path.display(),
                        bytes.len()
                    ),
                },
                Err(e) => format!("\n\n[file: {} — could not read: {e}]", path.display()),
            };
            prompt.push_str(&block);
        }
        let expanded = self.expand_prompt_async(&prompt).await;
        let msg = ChatMessage::user(expanded);
        self.guard_candidate_message(&msg)?;
        self.record(&msg)?;
        self.history.push(msg);
        self.run_loop().await
    }

    /// Send a message with image inputs to a vision model — the `-i/--image`
    /// analog. `image_urls` may be `https://…` links or `data:image/…;base64,…`
    /// URLs; they're attached as multimodal `image_url` content parts.
    pub async fn send_with_images(
        &mut self,
        text: impl Into<String>,
        image_urls: &[String],
    ) -> Result<String> {
        let expanded = self.expand_prompt_async(&text.into()).await;
        let msg = ChatMessage::user_with_images(expanded, image_urls);
        self.guard_candidate_message(&msg)?;
        self.record(&msg)?;
        self.history.push(msg);
        self.run_loop().await
    }

    /// Expand a `/<name> <args>` slash command against the registered prompt
    /// templates (`{args}` is replaced with the trailing text). Non-matching
    /// input is returned unchanged.
    /// BP-6 additionally resolves SKILL.md invocations here, after the
    /// template table misses: `/skill:name args` (pi§2 "Skill commands"),
    /// `/name args` when the config follows Claude Code (cc§7: "a `SKILL.md`
    /// in a directory = a `/name` command"), and `$slug` mentions (cx§7).
    /// `$ARGUMENTS` in the body is replaced with the trailing text.
    pub fn expand_prompt(&self, input: &str) -> String {
        // BP-5 (catalog D2 "@-file mentions / attachments"): `@path`
        // expansion happens FIRST, so a mention works in a bare message, in
        // a slash-command's arguments, and in the text a `$slug` mention
        // appends to — one rule, every prompt shape.
        let input = &self.expand_file_mentions(input);
        let trimmed = input.trim_start();
        let Some(rest) = trimmed.strip_prefix('/') else {
            return self.expand_skill_mentions(input);
        };
        let (name, args) = match rest.split_once(char::is_whitespace) {
            Some((n, a)) => (n, a.trim()),
            None => (rest, ""),
        };
        match self.config.prompts.get(name) {
            Some(template) => template.replace("{args}", args),
            None => match self.expand_skill_command(name, args) {
                Some(expanded) => expanded,
                None => self.expand_skill_mentions(input),
            },
        }
    }

    /// BP-5 (catalog D2 "@-file mentions / attachments"; cc§2 "`@` in the
    /// prompt triggers file-path autocomplete and injects file context …
    /// Read deny rules best-effort apply to `@file` mentions"; cx§2
    /// "`@`-mentions (files)"): replace each `@path` token in `input` with
    /// that file's contents.
    ///
    /// **Deny-rule aware, through the one permissions engine.** Each
    /// mention is resolved with
    /// [`crate::permissions::evaluate_path_safe`] — the same
    /// traversal/symlink-resolving check a `read_file` tool call goes
    /// through — against this config's own rules and protected-path floor.
    /// Anything short of `Allow` inlines the refusal instead of the file, so
    /// `@.env` under a preset whose protected paths cover it says so rather
    /// than quietly leaking it.
    ///
    /// A token that names nothing readable is left exactly as the user typed
    /// it: an email address, a decorator, or a `@`-prefixed word in prose is
    /// not a file mention, and must survive untouched.
    /// Off by default (`[core.file_mentions]`).
    fn expand_file_mentions(&self, input: &str) -> String {
        if !self.config.file_mentions || !input.contains('@') {
            return input.to_string();
        }
        let mut attachments = String::new();
        let mut seen: Vec<String> = Vec::new();
        for token in input.split_whitespace() {
            let Some(rel) = token.strip_prefix('@') else {
                continue;
            };
            let rel = rel.trim_end_matches([',', ';', ':', '.', ')', ']', '"', '\'']);
            if rel.is_empty() || seen.iter().any(|s| s == rel) {
                continue;
            }
            let path = if std::path::Path::new(rel).is_absolute() {
                std::path::PathBuf::from(rel)
            } else {
                self.config.cwd.join(rel)
            };
            if !path.is_file() {
                continue;
            }
            seen.push(rel.to_string());
            attachments.push_str(&self.render_mention(rel, &path));
            if seen.len() >= MAX_FILE_MENTIONS_PER_MESSAGE {
                break;
            }
        }
        if attachments.is_empty() {
            return input.to_string();
        }
        format!("{input}{attachments}")
    }

    /// One mention's block: the permission verdict first, then the bytes.
    /// Text is inlined; a binary file is named with its size, the same
    /// shape [`Self::send_with_files`] already uses for an explicit
    /// attachment, so a mention and a `--file` read the same way.
    fn render_mention(&self, shown: &str, path: &std::path::Path) -> String {
        use crate::permissions::{Decision, PathKind};
        let rules = crate::permissions::rules_for_config(&self.config);
        // BP-10's multi-root form: a mention is checked against every
        // granted root (cwd + `additional_dirs`), folded to the strictest —
        // the same call the tool-dispatch gate makes for a `read_file`
        // path, so a mention can never reach a file a read could not.
        let mut roots = vec![self.config.cwd.clone()];
        roots.extend(self.config.additional_dirs.iter().cloned());
        let decision = crate::permissions::evaluate_path_safe_roots(
            &rules,
            PathKind::Read,
            &roots,
            &path.to_string_lossy(),
            Decision::Allow,
        );
        if decision != Decision::Allow {
            return format!(
                "\n\n[file: {shown} — not attached; the permission rules for this session \
                 resolve reading it to {decision:?}]"
            );
        }
        match std::fs::read(path) {
            Ok(bytes) => match String::from_utf8(bytes) {
                Ok(text) => {
                    let mut text = text;
                    if text.len() > MAX_FILE_MENTION_BYTES {
                        let mut cut = MAX_FILE_MENTION_BYTES;
                        while cut > 0 && !text.is_char_boundary(cut) {
                            cut -= 1;
                        }
                        text.truncate(cut);
                        text.push_str("\n[file truncated]");
                    }
                    format!("\n\n[file: {shown}]\n{text}")
                }
                Err(e) => format!(
                    "\n\n[file: {shown}{} bytes, binary content omitted]",
                    e.into_bytes().len()
                ),
            },
            Err(e) => format!("\n\n[file: {shown} — could not read: {e}]"),
        }
    }

    /// The SKILL.md packages this agent discovered (frontmatter only) — the
    /// exact set its prompt index lists and its `skill` tool can load.
    pub fn skills(&self) -> &[crate::skills::LoopSkill] {
        &self.skills
    }

    /// BP-6: resolve a slash command against the discovered skills.
    ///
    /// `/skill:<name>` is pi's own form and is accepted under every config
    /// (it can never collide with a template name, which cannot contain a
    /// colon-prefixed `skill` segment by construction). The BARE `/<name>`
    /// form is Claude Code's — there, a skill IS a slash command — so it is
    /// honored only when the config reads Claude Code's roots; under
    /// `cx-parity`, where Codex has no skill slash commands, `/deploy` stays
    /// the literal text the user typed.
    fn expand_skill_command(&self, name: &str, args: &str) -> Option<String> {
        if self.skills.is_empty() {
            return None;
        }
        let bare = match name.strip_prefix("skill:") {
            Some(rest) => rest,
            None if self.config.skills_harness.as_deref()
                == Some(crate::HarnessId::CLAUDE_CODE) =>
            {
                name
            }
            None => return None,
        };
        let skill = self.find_skill(bare)?;
        skill
            .body_with_shell(args, &self.shell_injection)
            .ok()
            .map(|body| crate::skills::render_skill(skill, &body))
    }

    /// BP-6: `$slug` mentions (cx§7 `TOOL_MENTION_SIGIL = '$'`) and — only
    /// under `[core.skills] implicit_match` — a description match.
    ///
    /// The user's own text is never replaced: a loaded body is APPENDED, the
    /// way Codex splices a skill into the turn. Mentions are only honored
    /// for a config that reads Codex's roots; `$WORD` is ordinary shell text
    /// everywhere else.
    fn expand_skill_mentions(&self, input: &str) -> String {
        if self.skills.is_empty() {
            return input.to_string();
        }
        let mut loaded: Vec<String> = Vec::new();
        let mut names: Vec<String> = Vec::new();
        if self.config.skills_harness.as_deref() == Some(crate::HarnessId::CODEX) {
            for token in input.split_whitespace() {
                let Some(slug) = token.strip_prefix('$') else {
                    continue;
                };
                let slug =
                    slug.trim_matches(|c: char| !c.is_alphanumeric() && c != '-' && c != ':');
                if slug.is_empty() {
                    continue;
                }
                let Some(skill) = self.find_skill(slug) else {
                    continue;
                };
                if names.contains(&skill.name) || loaded.len() >= MAX_SKILL_LOADS_PER_MESSAGE {
                    continue;
                }
                if let Ok(body) = skill.body_with_shell("", &self.shell_injection) {
                    names.push(skill.name.clone());
                    loaded.push(crate::skills::render_skill(skill, &body));
                }
            }
        }
        if loaded.is_empty() && self.config.skills_implicit_match {
            if let Some(skill) = crate::skills::implicit_skill_match(&self.skills, input) {
                if let Ok(body) = skill.body_with_shell("", &self.shell_injection) {
                    loaded.push(crate::skills::render_skill(skill, &body));
                }
            }
        }
        if loaded.is_empty() {
            return input.to_string();
        }
        format!("{input}\n\n{}", loaded.join("\n\n"))
    }

    /// Resolve one invocation name against the discovered set — the same
    /// resolver the `skill` tool uses, so every door agrees on what a name
    /// means.
    fn find_skill(&self, name: &str) -> Option<&crate::skills::LoopSkill> {
        crate::skills::find_skill(&self.skills, name)
    }

    /// P5-2 (§2 module 15 D7 row 4 "prompts-as-commands"): like
    /// [`Self::expand_prompt`], but also consults MCP-server-sourced
    /// prompts registered via [`Self::register_mcp_prompt`] when the local
    /// `Config::prompts` table has no match — a live `prompts/get`
    /// round-trip, which is why this is async and [`Self::expand_prompt`]
    /// itself stays synchronous (its public sync signature is unchanged,
    /// for every existing caller that doesn't need MCP prompts).
    ///
    /// **Argument mapping (a scope decision, not a protocol requirement —
    /// the MCP spec leaves "how does free CLI text become named prompt
    /// arguments" to the client):** a prompt with zero or one declared
    /// arguments gets the whole trailing text (empty string if the prompt
    /// takes no arguments and none was given); a prompt with two or more
    /// declared arguments expects `key=value` pairs, whitespace-separated
    /// (`/mcp__server__prompt lang=rust topic=async`) — an unparseable pair
    /// (no `=`) is simply skipped, never a hard error (matches this
    /// method's "non-matching input passes through" fail-open posture for
    /// the LOCAL-prompt case above).
    pub async fn expand_prompt_async(&self, input: &str) -> String {
        let local = self.expand_prompt(input);
        if local != input {
            return local; // a local `Config::prompts` template matched
        }
        let trimmed = input.trim_start();
        let Some(rest) = trimmed.strip_prefix('/') else {
            return input.to_string();
        };
        let (name, args) = match rest.split_once(char::is_whitespace) {
            Some((n, a)) => (n, a.trim()),
            None => (rest, ""),
        };
        let Some(source) = self.mcp_prompts.get(name) else {
            return input.to_string();
        };
        let arg_map = match source.arg_names() {
            [] => std::collections::BTreeMap::new(),
            [single] => {
                let mut m = std::collections::BTreeMap::new();
                if !args.is_empty() {
                    m.insert(single.clone(), args.to_string());
                }
                m
            }
            _ => args
                .split_whitespace()
                .filter_map(|pair| pair.split_once('='))
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
        };
        match source.render(arg_map).await {
            Ok(rendered) => rendered,
            Err(e) => format!("Error: mcp prompt `{name}` failed: {e}"),
        }
    }

    /// P5-2 (§2 module 15 D7 row 4): register an MCP server's prompt as a
    /// slash-command source — `command_name` MUST already be the
    /// namespaced `mcp__<server>__<prompt>` form
    /// ([`crate::mcp::McpServerHandle::prompts`] produces exactly that
    /// shape); this method does not re-namespace or validate it, so a
    /// caller that hands it a bare name defeats the collision protection
    /// [`crate::mcp::McpPromptSource`]'s doc comment describes. Overwrites
    /// any prior registration under the same command name (re-attaching
    /// the same server replaces its own earlier prompt list; this can
    /// never touch a NON-`mcp__`-prefixed key, i.e. never a local
    /// `Config::prompts` entry).
    pub fn register_mcp_prompt(
        &mut self,
        command_name: impl Into<String>,
        source: impl crate::sdk::SdkPromptSource + 'static,
    ) {
        self.mcp_prompts
            .insert(command_name.into(), Box::new(source));
    }

    /// P5-2 (§2 module 15 D7 row 5 "instructions"): fold an MCP server's
    /// `initialize`-time instructions (or any other free-text note) into
    /// this agent's system message — the context-assembly site every other
    /// `core.*`/`capabilities.*` prompt-section append already uses
    /// (`Self::with_parts`), except this one fires AFTER construction
    /// (attaching MCP servers happens once the agent already exists — see
    /// `crates/cli/src/main.rs`'s `attach_mcp`). A no-op if `history` is
    /// somehow empty or its first message isn't a system message (never
    /// true for an `Agent` built via `Self::new`/`Self::with_parts`, but
    /// checked rather than assumed).
    pub fn append_system_note(&mut self, text: &str) {
        if let Some(system) = self.history.first_mut() {
            if system.role == Role::System {
                system
                    .content
                    .get_or_insert_with(String::new)
                    .push_str(text);
            }
        }
    }

    /// BP-4 (catalog:90, cx§2 `<environment_context>` "re-emitted on
    /// change"): re-derive the `# Environment` block and, if anything in it
    /// moved — cwd, the approval/sandbox policy, the git branch or its
    /// dirty state, the date — replace the stale copy in the system message
    /// with the fresh one. Returns whether the block changed.
    ///
    /// A no-op (and free — no git subprocess) when `core.env_context` is
    /// off, which is the default and every non-parity config. Replacing in
    /// place rather than appending a second block is deliberate: two
    /// `# Environment` sections disagreeing about cwd is worse context than
    /// one stale one, and the system message is re-sent on every request,
    /// so the rewrite IS the re-emission the model sees.
    pub fn refresh_env_context(&mut self) -> bool {
        if !self.config.env_context {
            return false;
        }
        let fresh = env_context_block(&self.config);
        let Some(stale) = self.env_context_live.clone() else {
            // Nothing was spliced at construction (e.g. `with_provider_arc`);
            // splice it now rather than silently never emitting one.
            self.append_system_note(&fresh);
            self.env_context_live = Some(fresh);
            return true;
        };
        if stale == fresh {
            return false;
        }
        if let Some(system) = self.history.first_mut() {
            if system.role == Role::System {
                if let Some(content) = system.content.as_mut() {
                    if let Some(at) = content.find(&stale) {
                        content.replace_range(at..at + stale.len(), &fresh);
                        self.env_context_live = Some(fresh);
                        return true;
                    }
                }
            }
        }
        false
    }

    /// BP-5 (catalog D2 "Per-model-family base-prompt selection"): re-select
    /// the base prompt for the model now in force and replace the stale one
    /// in place. Returns whether the system message changed.
    ///
    /// A no-op — not even a string search — when the selection is unchanged,
    /// which is every config that sets no `base_prompts` table.
    fn refresh_base_prompt(&mut self) -> bool {
        let fresh = base_prompt_for_config(&self.config);
        if fresh == self.base_prompt_live {
            return false;
        }
        let stale = std::mem::replace(&mut self.base_prompt_live, fresh.clone());
        if stale.is_empty() {
            return false;
        }
        if let Some(system) = self.history.first_mut() {
            if system.role == Role::System {
                if let Some(content) = system.content.as_mut() {
                    if let Some(at) = content.find(&stale) {
                        content.replace_range(at..at + stale.len(), &fresh);
                        return true;
                    }
                }
            }
        }
        false
    }

    /// BP-5: assemble the request from an already-built message list and
    /// tool-schema list. The ONE place a [`ChatRequest`] is constructed from
    /// this agent's config, so the request `Self::run_loop` issues and the
    /// request [`Self::model_input`] renders cannot drift apart.
    fn chat_request(&self, messages: Vec<ChatMessage>, tools: Vec<ToolSchema>) -> ChatRequest {
        let mut req = ChatRequest {
            model: self.config.model.clone(),
            messages,
            tools,
            temperature: self.config.temperature,
            max_tokens: self.config.max_tokens,
            effort: self.config.effort.clone(),
            response_format: self.config.response_format.clone(),
            service_tier: None,
            thinking_budget: None,
            extra_body: self.config.extra_body.clone(),
        };
        // BP-13 (catalog Domain 9): the per-request routing decisions —
        // effort LEVEL, thinking-token BUDGET and service TIER — all come
        // out of `Config::model_routing` keyed by the model this request is
        // actually going to. Applied HERE so `model_input`'s rendering and
        // the loop's own send can never disagree about what would be sent,
        // and so a mid-session switch re-decides all three for the new
        // model on the next pass.
        self.apply_routing(&mut req);
        req
    }

    /// BP-5 (catalog D2 "Prompt-input debugging": *render the exact
    /// model-visible input for inspection*; cx§2 `codex debug prompt-input`,
    /// which "renders the exact model-visible input list as JSON"): the
    /// request this agent would send next.
    ///
    /// Built by the SAME two calls the loop makes
    /// ([`Self::build_request_messages`], [`Self::tool_schemas`]) and
    /// assembled by the SAME [`Self::chat_request`] — it is the real
    /// request, not a reconstruction of one. `&mut self` because
    /// `build_request_messages` is: rendering the input is exactly as
    /// stateful as building it for a send.
    pub fn model_input(&mut self) -> ChatRequest {
        let tools = self.tool_schemas();
        let messages = self.build_request_messages();
        self.chat_request(messages, tools)
    }

    /// BP-5: [`Self::model_input`] for a turn that has not been sent —
    /// `prompt` is expanded exactly as [`Self::send`] would expand it
    /// (slash templates, skills, `@path` mentions, MCP prompts) and appended
    /// to the conversation IN MEMORY, then the request is rendered.
    ///
    /// Deliberately not recorded: this door inspects an input, it does not
    /// take a turn. Nothing is written to the session store, no journal
    /// entry is made, and no request is issued.
    pub async fn model_input_for(&mut self, prompt: &str) -> ChatRequest {
        let expanded = self.expand_prompt_async(prompt).await;
        self.history.push(ChatMessage::user(expanded));
        self.model_input()
    }

    /// BP-5: a [`ChatRequest`] as the JSON a human (or `jq`) inspects — the
    /// system prompt, every message in order, and every advertised tool
    /// schema, plus the sampling controls that travel with them.
    pub fn render_model_input(req: &ChatRequest) -> serde_json::Value {
        serde_json::json!({
            "model": req.model,
            "temperature": req.temperature,
            "max_tokens": req.max_tokens,
            "effort": req.effort,
            "response_format": req.response_format,
            // Serialized through `ChatMessage`'s OWN wire serializer and
            // `ToolSchema`'s own — i.e. the exact bytes the provider is
            // handed, not a second rendering of them.
            "messages": serde_json::to_value(&req.messages).unwrap_or(serde_json::Value::Null),
            "tools": serde_json::to_value(&req.tools).unwrap_or(serde_json::Value::Null),
        })
    }

    /// BP-5 (catalog D2 "Per-model-family base-prompt selection"): the base
    /// system prompt currently in force for this agent's model.
    pub fn base_prompt(&self) -> &str {
        &self.base_prompt_live
    }

    /// BP-4 (catalog:91 "Synthetic context-injection blocks"): splice one
    /// named ambient block into the live context — the seam a hook's
    /// `additionalContext`, a frontend nudge or an orchestrator's brief
    /// enters through, mid-session, after construction.
    ///
    /// Requires `core.context_injections` (returns `false` otherwise): the
    /// gate governs the whole registry, not just its startup half. The
    /// block is appended to the system message and remembered, so it is
    /// carried by every later request and re-rendered by
    /// [`crate::context_injection::assemble`] wherever the prompt is
    /// rebuilt.
    pub fn inject_context_block(
        &mut self,
        name: impl Into<String>,
        content: impl Into<String>,
    ) -> bool {
        if !self.config.context_injections {
            return false;
        }
        let block = crate::config::ContextInjectionBlock::new(name, content);
        let rendered = crate::context_injection::render(std::slice::from_ref(&block));
        self.spliced_context_blocks.push(block);
        self.append_system_note(&rendered);
        true
    }

    /// The blocks spliced in since construction — see
    /// [`Self::inject_context_block`].
    pub fn spliced_context_blocks(&self) -> &[crate::config::ContextInjectionBlock] {
        &self.spliced_context_blocks
    }

    /// Compact the conversation if it has grown past the configured
    /// threshold.
    ///
    /// **Re-founded (A10):** with a [`ReductionPolicy`] installed
    /// ([`Self::set_reduction_policy`]), this no longer touches `self.history`
    /// at all. It derives `policy.clear_turns_older_than` from
    /// `compact_after_messages` so the *next* projected request view
    /// (`reduce::project_messages`, built in `Self::run_loop`) collapses the
    /// old turns into one reversible `TurnsCleared` stub instead —
    /// `history()` and the sidecar keep every message forever; only the view
    /// shrinks. Returns whether the live (unreduced) history currently
    /// exceeds the threshold, i.e. whether a clearing will actually be
    /// visible in the next projected view.
    ///
    /// **Legacy path (no policy) — LOSSY, kept only for byte-identical
    /// backward compatibility (D6):** destructively rewrites `self.history`,
    /// permanently discarding the dropped middle turns (replaced by a single
    /// non-reversible summary marker that becomes their SOLE remaining copy —
    /// exactly the lossy compaction this reduction layer differentiates
    /// against). Once a sidecar/recorder or a [`ReductionPolicy`] is in play,
    /// prefer installing a policy so this method takes the re-founded path
    /// above instead.
    pub fn maybe_compact(&mut self) -> bool {
        // P4e (§1.5/§3.1 `core.compaction.enabled`, "no master gate exists
        // yet"): checked FIRST, before either trigger — `false` disables
        // every auto-compaction trigger unconditionally (message-count AND
        // pressure), composing with them rather than replacing their own
        // logic. `true` (the default, matching today's pre-P4e behavior,
        // where nothing ever gated compaction) falls straight through to
        // the existing trigger checks below, unchanged.
        if !self.config.compaction_enabled {
            return false;
        }
        let threshold = self.config.compact_after_messages;
        // P4b (§1.5/§3.1 `core.compaction.reserve_tokens`, pi§2 shape): a
        // SECOND, independent trigger — context-window pressure — alongside
        // (not instead of) the message-count one above. `None` (the
        // default) is byte-identical to today's message-count-only
        // behavior; this whole block is a no-op then.
        let message_trigger = threshold.is_some_and(|t| self.history.len() > t);
        let pressure_trigger = self.compaction_pressure_triggered();
        if threshold.is_none() && self.config.compaction_reserve_tokens.is_none() {
            return false;
        }
        if !message_trigger && !pressure_trigger {
            return false;
        }
        if let Some(policy) = self.reduction_policy.as_mut() {
            if let Some(t) = threshold {
                policy.clear_turns_older_than = Some(t);
            }
            // P4b scope note: the token-PRESSURE trigger's "how much to
            // clear" derivation (below, for the legacy in-place path) has no
            // `ReductionPolicy`/A10 analog yet — that mechanism decides its
            // own clearing window once `clear_turns_older_than` is set, so
            // pressure firing alone (no message threshold configured) has
            // nothing new to hand it in this pass. Report the message-count
            // verdict only, matching today's pre-P4b behavior exactly when
            // only `threshold` is set.
            return message_trigger;
        }
        // Legacy in-place compaction (no `ReductionPolicy` installed) below.
        // `keep_recent`: the message-count trigger's own `threshold / 2`
        // shape when it's what fired (or both fired); otherwise (pressure
        // fired alone) a token-budget-derived count.
        let keep_recent = if message_trigger {
            (threshold.unwrap() / 2).max(2)
        } else {
            self.keep_recent_count_by_tokens()
        };
        self.compact_in_place(keep_recent, None)
    }

    /// BP-4 (catalog:98 "Manual compact with focus instructions", cc§2 /
    /// cx§2 `/compact [instructions]`): compact NOW, regardless of whether
    /// either automatic trigger has fired — the mechanism behind the REPL's
    /// `/compact [focus]`.
    ///
    /// `focus` is this invocation's steering text: it overrides the standing
    /// `core.compaction.focus_instructions` for this compaction only, is
    /// carried into the SUMMARIZER's input (so the model-written summary
    /// preserves what the user asked for), and is stated on the marker. An
    /// empty/whitespace `focus` falls back to the configured standing value,
    /// which is what a bare `/compact` means.
    ///
    /// Returns whether anything was compacted (`false` when the history is
    /// already at or below the keep-window, or when a [`ReductionPolicy`] is
    /// installed — under a policy the reversible A10 path owns clearing, and
    /// a manual compact would be the lossy one).
    pub fn compact_now(&mut self, focus: Option<&str>) -> bool {
        self.compacting_manually = true;
        let compacted = self.compact_now_inner(focus);
        self.compacting_manually = false;
        compacted
    }

    fn compact_now_inner(&mut self, focus: Option<&str>) -> bool {
        if self.reduction_policy.is_some() {
            return false;
        }
        // A manual compact must actually compact. The token budget alone
        // (`core.compaction.keep_recent_tokens`, 20k) keeps EVERYTHING on
        // any ordinary conversation, which is right for the pressure
        // trigger (it fires only when the window is nearly full) and wrong
        // for `/compact`, whose whole point is compacting before the
        // pressure arrives. So the keep-window is the tighter of the two:
        // the token budget, and the message-count trigger's own established
        // "keep the most recent half" shape (`maybe_compact`'s
        // `threshold / 2`, floor 2).
        let keep_recent = self
            .keep_recent_count_by_tokens()
            .min((self.history.len() / 2).max(2));
        let focus = focus.map(str::trim).filter(|f| !f.is_empty());
        self.compact_in_place(keep_recent, focus)
    }

    /// The legacy (no-[`ReductionPolicy`]) in-place compaction both
    /// [`Self::maybe_compact`] and [`Self::compact_now`] run: collapse
    /// `history[first..cut)` into one marker, keeping the newest
    /// `keep_recent` messages.
    fn compact_in_place(&mut self, keep_recent: usize, focus_override: Option<&str>) -> bool {
        if self.history.len() <= keep_recent {
            return false;
        }
        // Indices: 0 is the system prompt; collapse [first .. len-keep_recent).
        // `first` is 1 (only the system prompt is ever auto-preserved) unless
        // B7's coordination clamp widens it.
        let mut first = 1usize;
        // B7 coordination clamp: this legacy (no-`ReductionPolicy`) path
        // mutates `self.history` directly, so — unlike the re-founded A10
        // path (clamped inside `reduce::project_messages`, threaded from
        // `build_request_messages`) — it must clamp itself. Widening `first`
        // (not `cut`) is what actually protects the imported prefix: the
        // drop range is `[first, cut)`, so raising `cut` alone would only
        // drop MORE messages, not fewer. `imported_prefix_len` is already an
        // absolute `history` index count (it protects `history[0..len]`), so
        // no offset conversion is needed here.
        if matches!(self.config.cache_plan, CachePlan::ImportedPrefix) {
            if let Some(protected) = self.imported_prefix_len {
                first = first.max(protected);
            }
        }
        let mut cut = self.history.len() - keep_recent;
        if cut <= first {
            return false;
        }
        // Never begin the kept window on a tool result: its originating
        // assistant turn (with the matching `tool_calls`) is about to be
        // dropped, which would orphan the tool message and make the replayed
        // conversation invalid. Advance past any leading tool results.
        while cut < self.history.len() && self.history[cut].role == Role::Tool {
            cut += 1;
        }
        if cut >= self.history.len() {
            return false;
        }
        let dropped = cut - first;
        // BP-11: the compaction is decided from here on — the one point both
        // the automatic triggers and `/compact` pass through — so this is
        // where `pre_compact` observers hear about it.
        self.fire_lifecycle(&crate::config::LifecycleEvent::PreCompact {
            messages: self.history.len(),
            dropped,
            manual: focus_override.is_some() || self.compacting_manually,
        });
        // P4b (§1.5/§3.1 `core.compaction.focus_instructions`, catalog D2
        // "no instruction steering" gap): appended to the marker whenever
        // set, regardless of which trigger fired. `None` (the default)
        // leaves this byte-identical to the pre-P4b marker text.
        //
        // BP-4: `focus_override` — the per-invocation `/compact <focus>`
        // text — wins over the standing config value for THIS compaction,
        // which is what "`/compact [instructions]` steers what's preserved"
        // means. Neither is required.
        let focus: Option<String> = focus_override.map(str::to_string).or_else(|| {
            self.config
                .compaction_focus_instructions
                .clone()
                .filter(|f| !f.is_empty())
        });
        // BP-1 (§1.5/§3.1 `core.compaction.summarize`): the verb the marker
        // uses is now the config's to state. `true` (the default, and what
        // every preset sets) keeps the historical "summarized" text
        // byte-identical; `false` says only what actually happened to the
        // span, so a config that turns summarization off does not leave a
        // marker claiming a summary exists.
        let verb = if self.config.compaction_summarize {
            "summarized"
        } else {
            "cleared"
        };
        // BP-4 (catalog:107 "LLM summaries of cleared spans", design §1.5:
        // obligation 5 is "auto-compaction … + a persisted marker + AN LLM
        // SUMMARY OF THE COMPACTED SPAN", knob `[core.compaction] summarize`
        // — "the summary side-call depends on a utility model … core falls
        // back to the main model"). The side-call is therefore CORE, not a
        // reduction-module privilege: when `core.compaction.summarize` is on
        // and a summarizer is installed, the span is summarized by the model
        // and the marker carries that summary instead of only a count.
        //
        // Every failure mode degrades to the count-only marker: no
        // summarizer installed, an `Err` from the side-call, or an empty
        // reply. It never blocks or fails compaction — the same contract
        // TR-7's own side-call site keeps.
        let summary_body = if self.config.compaction_summarize {
            self.summarize_span(first..cut, focus.as_deref())
        } else {
            None
        };
        // BP-4 (catalog:99 "Compaction markers persisted in transcript"):
        // the marker states where the originals went, which is the whole
        // point of a boundary record — a reader must be able to tell a
        // reversible compaction from a lossy one without knowing which
        // modules were on.
        let retention = if self.recorder.is_some() {
            "The compacted messages remain in this session's transcript sidecar."
        } else {
            "No transcript sidecar is attached, so this marker is the only remaining record of them."
        };
        let mut summary_text = format!(
            "[earlier conversation compacted: {dropped} message(s) {verb} to save context]\n{retention}"
        );
        if let Some(focus) = &focus {
            summary_text.push_str(&format!("\n\nFocus: {focus}"));
        }
        if let Some(body) = &summary_body {
            summary_text.push_str(&format!("\n\nSummary of the compacted span:\n{body}"));
        }
        let summary = ChatMessage::system(summary_text);
        // BP-4 (catalog:99): PERSIST the boundary. Before this the legacy
        // path rewrote `self.history` and never called `record`, so the
        // marker existed only in the live window and a resumed session had
        // no on-disk trace that a compaction ever happened. A recorder
        // failure is logged, never fatal — losing the boundary record must
        // not lose the compaction.
        if let Err(error) = self.record(&summary) {
            tracing::warn!("failed to persist the compaction marker: {error}");
        }
        let mut new_history = Vec::with_capacity(first + keep_recent + 2);
        new_history.extend(self.history[..first].iter().cloned());
        new_history.push(summary);
        new_history.extend(self.history.split_off(cut));
        self.history = new_history;
        self.fire_lifecycle(&crate::config::LifecycleEvent::PostCompact {
            messages: self.history.len(),
            dropped,
        });
        // BP-8 (catalog:150): compaction RESHAPES the live view rather than
        // appending to it, so the journal's "everything since the last
        // checkpoint is unpersisted" accounting has to be re-based here —
        // otherwise a crash-recovery replay would re-append messages this
        // compaction deliberately set aside. The set-aside messages' own
        // bytes stay in the log above, untouched.
        self.journal_checkpoint(self.history.len());
        true
    }

    /// BP-4 (catalog:107): run the installed [`reduce::summarize::SpanSummarizer`]
    /// over `history[span]`, with `focus` (the `/compact <focus>` text)
    /// carried into the summarizer's INPUT so the model-written summary
    /// preserves what the user asked to keep.
    ///
    /// `None` — never an error — whenever no summarizer is installed, the
    /// span renders empty, the side-call fails, or it returns nothing. The
    /// caller falls back to the count-only marker.
    fn summarize_span(&self, span: std::ops::Range<usize>, focus: Option<&str>) -> Option<String> {
        let summarizer = self.span_summarizer.as_deref()?;
        let mut span_text = String::new();
        // The focus rides at the head of the span text (the trait's one
        // input) as an explicit, labeled line rather than a silent prompt
        // mutation: the fixed prompt's "do not state anything not present
        // in the span" still holds, because the focus IS present in it.
        if let Some(focus) = focus {
            span_text.push_str(&format!("[compaction focus requested: {focus}]\n\n"));
        }
        for msg in self.history.get(span)? {
            let role = match msg.role {
                Role::System => "system",
                Role::User => "user",
                Role::Assistant => "assistant",
                Role::Tool => "tool",
            };
            span_text.push_str(role);
            span_text.push_str(": ");
            span_text.push_str(msg.content.as_deref().unwrap_or(""));
            span_text.push('\n');
        }
        match summarizer.summarize(&span_text) {
            Ok(text) if !text.trim().is_empty() => Some(text.trim().to_string()),
            Ok(_) => None,
            Err(error) => {
                tracing::warn!("compaction span summarizer failed: {error}");
                None
            }
        }
    }

    /// BP-4 (catalog:106 "Handoff (fresh objective + curated keep-set)",
    /// cx§1 `new_context`): reset the live working view to a fresh
    /// objective plus a curated keep-set, in-session.
    ///
    /// The new view is: the system prompt (plus any imported prefix a
    /// `CachePlan::ImportedPrefix` config protects — same clamp compaction
    /// uses), then a handoff marker stating the objective and what was set
    /// aside, then the most recent `keep_recent` messages (`None` = the
    /// token-budget-derived count `core.compaction.keep_recent_tokens`
    /// already governs, so the keep-set is curated by the same budget the
    /// rest of the compaction machinery uses, not by a magic number). The
    /// keep-set never begins on a tool result, so no tool message is left
    /// orphaned from its originating assistant turn.
    ///
    /// Returns how many messages were set aside. Like compaction, the
    /// marker is PERSISTED through the recorder, so a resumed session can
    /// see where the handoff happened; and like compaction, the set-aside
    /// messages remain in the transcript sidecar whenever one is attached.
    ///
    /// Scope note: this is the in-session `new_context` mechanism, NOT
    /// `Config::handoff_enabled`'s reversible ReductionLog snapshot (the
    /// offline `supercode handoff` projection) — that one is the reduction
    /// module's, and stays there.
    pub fn new_context(&mut self, objective: &str, keep_recent: Option<usize>) -> usize {
        let keep_recent = keep_recent.unwrap_or_else(|| self.keep_recent_count_by_tokens());
        let mut first = 1usize;
        if matches!(self.config.cache_plan, CachePlan::ImportedPrefix) {
            if let Some(protected) = self.imported_prefix_len {
                first = first.max(protected);
            }
        }
        let mut cut = self.history.len().saturating_sub(keep_recent).max(first);
        while cut < self.history.len() && self.history[cut].role == Role::Tool {
            cut += 1;
        }
        let dropped = cut.saturating_sub(first);
        let objective = objective.trim();
        let retention = if self.recorder.is_some() {
            "They remain in this session's transcript sidecar."
        } else {
            "No transcript sidecar is attached, so they are not retained."
        };
        let marker = ChatMessage::system(format!(
            "[handoff: a fresh working context starts here]\nObjective: {objective}\n\
             {dropped} earlier message(s) were set aside; the most recent {kept} were kept. \
             {retention}",
            kept = self.history.len() - cut,
        ));
        if let Err(error) = self.record(&marker) {
            tracing::warn!("failed to persist the handoff marker: {error}");
        }
        let mut new_history = Vec::with_capacity(first + keep_recent + 2);
        new_history.extend(self.history[..first].iter().cloned());
        new_history.push(marker);
        new_history.extend(self.history.split_off(cut));
        self.history = new_history;
        // BP-8: same re-basing as `maybe_compact` — see its comment.
        self.journal_checkpoint(self.history.len());
        dropped
    }

    /// P4b (§1.5/§3.1 `core.compaction.reserve_tokens`, pi§2 shape:
    /// `contextTokens > contextWindow - reserveTokens`): whether the
    /// estimated token size of the live history is within `reserve_tokens`
    /// of the model's context window. `false` when
    /// [`Config::compaction_reserve_tokens`] is unset (the default).
    fn compaction_pressure_triggered(&self) -> bool {
        let Some(reserve) = self.config.compaction_reserve_tokens else {
            return false;
        };
        let limit = provider::model_context_limit(&self.config.model)
            .unwrap_or(provider::UNKNOWN_MODEL_CONTEXT_FLOOR);
        let used = crate::tokens::estimate_view_tokens(&self.history);
        used.saturating_add(reserve) > limit
    }

    /// P4b (§1.5/§3.1 `core.compaction.keep_recent_tokens`): how many of the
    /// most recent messages (walking backward from the end of `self.history`,
    /// skipping the system prompt) fit within the configured token budget
    /// (default 20,000, pi§6 precedent). Always keeps at least 2 messages,
    /// matching the message-count trigger's own floor.
    fn keep_recent_count_by_tokens(&self) -> usize {
        let budget = self.config.compaction_keep_recent_tokens.unwrap_or(20_000);
        let mut used = 0u64;
        let mut count = 0usize;
        for msg in self.history.iter().skip(1).rev() {
            let t = crate::tokens::estimate_view_tokens(std::slice::from_ref(msg));
            if used.saturating_add(t) > budget && count > 0 {
                break;
            }
            used = used.saturating_add(t);
            count += 1;
        }
        count.max(2)
    }

    /// Register an additional tool (e.g. your own capability).
    ///
    /// P5-2 (§2.2 C2 "connect invalidates cache prefix"): registering a
    /// tool AFTER this agent has already issued a request
    /// ([`Self::request_issued`]) changes the tools schema every
    /// subsequent request carries — the exact prefix-churn shape C2
    /// describes, MCP-sourced or not. Resets [`Self::cache_established`] so
    /// the next cache-warmth check (`provider::cache_cold_reason`) doesn't
    /// wrongly assume the entry is still warm. A no-op call before the
    /// first request (the common case: `attach_mcp` registers tools once at
    /// startup, before any turn runs) changes nothing — byte-identical to
    /// today.
    pub fn register_tool(&mut self, tool: impl crate::tools::Tool + 'static) {
        self.registry.register(tool);
        if self.requests_issued {
            self.cache_established = false;
        }
    }

    /// The current conversation, including the system prompt.
    pub fn history(&self) -> &[ChatMessage] {
        &self.history
    }

    /// Send a user message and run the loop until the model produces a final
    /// answer (text with no tool calls) or the iteration budget is exhausted.
    pub async fn send(&mut self, user_input: impl Into<String>) -> Result<String> {
        let expanded = self.expand_prompt_async(&user_input.into()).await;
        let msg = ChatMessage::user(expanded);
        self.guard_candidate_message(&msg)?;
        self.record(&msg)?;
        self.history.push(msg);
        self.run_loop().await
    }

    /// BP-4 (catalog:109 "Context-usage introspection", cc§2 `/context`
    /// grid, cx§8 `/status` + `get_context_remaining`): the LIVE
    /// context-window accounting for this session — the same numbers
    /// `resume --dry-run`'s preflight already computes
    /// (`tokens::estimate_request_tokens` / `tokens::context_guard`), read
    /// out mid-session instead of only before one.
    ///
    /// Pure: it projects the request view exactly as
    /// [`Self::guard_candidate_message`] does (reduction stubs included,
    /// cache annotation included) without mutating the reduction log, so
    /// asking "how full am I?" can never change what the next request
    /// carries.
    pub fn context_usage(&self) -> ContextUsage {
        let messages = self.projected_view(None);
        let tools = self.tool_schemas();
        let message_tokens = crate::tokens::estimate_view_tokens(&messages);
        let request_tokens = crate::tokens::estimate_request_tokens(&messages, &tools);
        let limit = self.context_limit.or_else(|| {
            crate::provider::model_context_limit(&self.config.model)
                .or(Some(crate::provider::UNKNOWN_MODEL_CONTEXT_FLOOR))
        });
        let projected_tokens = crate::tokens::with_guard_margin(request_tokens);
        let reserve = crate::tokens::CONTEXT_RESPONSE_RESERVE_TOKENS;
        let (fits, remaining_tokens, used_pct) = match limit {
            Some(limit) => (
                projected_tokens.saturating_add(reserve) <= limit,
                limit
                    .saturating_sub(reserve)
                    .saturating_sub(projected_tokens),
                if limit == 0 {
                    0
                } else {
                    (projected_tokens as f64 / limit as f64 * 100.0).round() as u32
                },
            ),
            None => (true, 0, 0),
        };
        ContextUsage {
            model: self.config.model.clone(),
            messages: messages.len(),
            message_tokens,
            tool_count: tools.len(),
            tool_schema_tokens: request_tokens.saturating_sub(message_tokens),
            request_tokens,
            projected_tokens,
            response_reserve_tokens: reserve,
            context_limit: limit,
            remaining_tokens,
            used_pct,
            fits,
        }
    }

    /// The messages a request would carry right now — the read-only half of
    /// [`Self::guard_candidate_message`]/[`Self::build_request_messages`],
    /// with `candidate` optionally appended as a not-yet-committed turn.
    /// Never mutates `self`.
    fn projected_view(&self, candidate: Option<&ChatMessage>) -> Vec<ChatMessage> {
        let messages = match &self.reduction_policy {
            None => {
                let mut messages = self.history.clone();
                if let Some(candidate) = candidate {
                    messages.push(candidate.clone());
                }
                messages
            }
            Some(policy) => {
                let has_system = self.history.first().is_some_and(|m| m.role == Role::System);
                let mut reducible = self.history[usize::from(has_system)..].to_vec();
                if let Some(candidate) = candidate {
                    reducible.push(candidate.clone());
                }
                let mut prepared = policy.clone();
                reduce::prepare_read_freshness(&mut prepared, &reducible);
                let (view, _) =
                    reduce::project_messages(&reducible, &prepared, &self.reduction_log);
                let mut messages = Vec::with_capacity(view.len() + usize::from(has_system));
                if has_system {
                    messages.push(self.history[0].clone());
                }
                messages.extend(view);
                messages
            }
        };
        provider::apply_cache_plan(&messages, self.config.cache_plan, self.imported_prefix_len)
    }

    /// Refuse an oversized new user turn before it mutates canonical history
    /// or an attached sidecar. The in-loop guard remains authoritative for
    /// every actual request; this preflight closes the first-request seam
    /// where `send*` used to record/push the message before that guard ran.
    fn guard_candidate_message(&self, msg: &ChatMessage) -> Result<()> {
        let Some(limit) = self.context_limit else {
            return Ok(());
        };

        let messages = self.projected_view(Some(msg));
        let tools = self.tool_schemas();
        let (fits, projected_tokens) = crate::tokens::context_guard(&messages, &tools, limit);
        if !fits {
            return Err(Error::ContextLimitExceeded {
                projected_tokens,
                reserve_tokens: crate::tokens::CONTEXT_RESPONSE_RESERVE_TOKENS,
                context_limit: limit,
                model: self.config.model.clone(),
            });
        }
        Ok(())
    }

    /// The messages a provider request should carry for the CURRENT turn
    /// (A5/A7/A8/A10): with no [`ReductionPolicy`] installed, exactly
    /// `self.history.clone()` — byte-identical to every version of this
    /// method before reduction landed. With a policy installed, `history[0]`
    /// (this agent's own system prompt, never a reduction target) followed by
    /// [`reduce::project_messages`]'s projected view of `history[1..]`, fed
    /// with `self.reduction_log` so already-applied reductions reproduce
    /// verbatim across turns (prefix stability, A5) — the updated log is
    /// stored back onto `self` so the NEXT call (this turn, next turn, or a
    /// later `send`) sees the same accumulating state. `self.history` itself
    /// is never read back into or mutated by this: it stays the full
    /// canonical view, in lockstep with the sidecar (A3).
    ///
    /// When `policy.elide_stale_reads` is set, this re-runs
    /// [`reduce::probe_read_freshness`] (the one place A8's disk I/O happens)
    /// against `history[1..]` before projecting, so every request sees
    /// up-to-date freshness verdicts — `project_messages` itself stays pure.
    ///
    /// Finally, B7's [`provider::apply_cache_plan`] runs over the assembled
    /// view (regardless of whether a [`ReductionPolicy`] is installed) — a
    /// pure, cloning annotation step, so this method's `&mut self` mutations
    /// above (`self.reduction_log`) are already committed before it runs and
    /// its own output is never written back onto `self.history` or the log:
    /// purity for B7's cache breakpoints holds independently of A5's.
    fn build_request_messages(&mut self) -> Vec<ChatMessage> {
        let messages = match self.reduction_policy.clone() {
            None => self.history.clone(),
            Some(mut policy) => {
                reduce::prepare_read_freshness(&mut policy, &self.history[1..]);
                // B7 coordination clamp: while `CachePlan::ImportedPrefix` is
                // active, A10 turn-clearing must never establish a range
                // that dips into the imported prefix (protects the cache
                // breakpoint the request build will place there below).
                // `imported_prefix_len` counts `history[0]` (this agent's own
                // system message) plus the imported messages, but
                // `project_messages` only ever sees `history[1..]` — hence
                // the `- 1`.
                if matches!(self.config.cache_plan, CachePlan::ImportedPrefix) {
                    policy.protect_imported_prefix =
                        self.imported_prefix_len.map(|n| n.saturating_sub(1));
                }
                // TR-7 (T20): the one side-call site, run BEFORE
                // `project_messages` (which stays pure/I-O-free) — mirrors
                // `elide_stale_reads`/`probe_read_freshness` immediately
                // above. Only ever does anything when both the policy gate
                // AND a summarizer are present; either being absent means
                // `cleared_turns_summary` stays `None` and `project_messages`
                // renders the deterministic stub, same as before TR-7
                // existed.
                if policy.summarize_cleared_turns {
                    if let Some(summarizer) = self.span_summarizer.as_deref() {
                        policy.cleared_turns_summary = reduce::prepare_cleared_turns_summary(
                            &self.history[1..],
                            &policy,
                            &self.reduction_log,
                            summarizer,
                        );
                    }
                }
                let (view, log) =
                    reduce::project_messages(&self.history[1..], &policy, &self.reduction_log);
                self.reduction_log = log;
                let mut messages = Vec::with_capacity(view.len() + 1);
                messages.push(self.history[0].clone());
                messages.extend(view);
                messages
            }
        };
        // TR-8 (T5): a tool-schema tier change since the last request is a
        // cache-bust event under `CachePlan::ImportedPrefix` — the `tools`
        // array is part of the cache key alongside `messages`, so flag it by
        // skipping this one request's cache annotation rather than claiming
        // a prefix hit that won't actually land. Recorded unconditionally
        // (even under `CachePlan::Off`) so the signature stays current
        // regardless of which plan is active.
        let tier_sig = self.schema_tier_signature();
        let busted =
            provider::tier_change_is_cache_bust(self.last_tool_schema_tier_signature, tier_sig);
        self.last_tool_schema_tier_signature = Some(tier_sig);
        let effective_cache_plan = if busted {
            CachePlan::Off
        } else {
            self.config.cache_plan
        };
        // UX-26 (B7-warn): mirror `apply_cache_plan`'s own placement gate
        // (`ImportedPrefix` AND a non-zero prefix) to know whether THIS
        // request will actually carry a `cache_control` annotation. `busted`
        // requests (schema-tier change) and `CachePlan::Off` never annotate,
        // so `provider::cache_cold_reason` can never flag them — there was
        // nothing to reuse, by construction. `idle_secs` is computed
        // whenever a signal exists at all (even before this agent's first
        // annotated send — see `Self::last_cache_activity_ms`'s doc comment
        // on why the pre-establishment case matters); `cache_established`
        // additionally gates the usage-ratio check specifically (see
        // `provider::cache_cold_reason`'s doc comment for why those two
        // checks need independent gates).
        let will_annotate = matches!(effective_cache_plan, CachePlan::ImportedPrefix)
            && self.imported_prefix_len.is_some_and(|n| n > 0);
        let idle_secs = self
            .last_cache_activity_ms
            .map(|last| (now_ms() - last).max(0) / 1000);
        self.pending_cache_turn = (will_annotate, self.cache_established, idle_secs);
        let mut messages =
            provider::apply_cache_plan(&messages, effective_cache_plan, self.imported_prefix_len);
        // BP-7 (catalog §4a "Goals"): the standing objective, restated at
        // the TAIL of the request — after the cache annotation, which sits
        // on the PREFIX, so a goal that changes mid-session never busts the
        // cached prefix. Request-view only: `history` is untouched, so the
        // persisted transcript is exactly the conversation and a translator
        // never has to invent a message for a harness-tracked goal.
        if let Some(goal) = &self.goal {
            messages.push(ChatMessage::system(goal.reminder()));
        }
        messages
    }

    /// Run the model/tool loop over the current history until a final answer or
    /// the iteration budget is exhausted. (Shared by `send`, `send_with_files`,
    /// and `send_with_images`.)
    /// P4b (§1.7, pi§3 semantics): pop the next message(s) to deliver from
    /// `queue` per `mode` — `All` drains everything and joins it with a
    /// blank line, `OneAtATime` pops exactly one. `None` when `queue` is
    /// empty (the default state, at zero cost).
    fn drain_steer_queue(
        queue: &mut std::collections::VecDeque<String>,
        mode: SteeringMode,
    ) -> Option<String> {
        if queue.is_empty() {
            return None;
        }
        match mode {
            SteeringMode::All => Some(queue.drain(..).collect::<Vec<_>>().join("\n\n")),
            SteeringMode::OneAtATime => queue.pop_front(),
        }
    }

    async fn run_loop(&mut self) -> Result<String> {
        let _steer_turn = SteerTurnGuard::new(self.steer_queue.clone());
        let mut output_tokens_used: u64 = 0;

        // BP-7 (catalog §4a "Turn/budget caps"): the SPEND cap, checked
        // before this `send` can issue anything. Unlike
        // `max_total_output_tokens` (a per-`send` allowance, unchanged),
        // spend accumulates over the agent's whole lifetime — a dollar
        // budget that resets on every prompt is not a budget. A cap reached
        // MID-loop ends that loop cleanly with a `spend_budget` finish
        // marker (below); a cap already exhausted at entry is an error,
        // because there is nothing to return.
        if let Some(budget) = self.config.max_budget_usd.filter(|b| *b > 0.0) {
            if self.total_cost_usd >= budget {
                return Err(Error::BudgetExhausted {
                    spent_usd: self.total_cost_usd,
                    budget_usd: budget,
                });
            }
        }

        // P5-9 (§2 module 20, cc's "per-prompt file-history-snapshot"):
        // open a fresh checkpoint for THIS turn — `run_loop` is called
        // exactly once per `send`/`send_with_files`/`send_with_images`
        // call (never recursively for the same turn), so this fires once
        // per user prompt, matching the design's per-prompt granularity.
        // `self.history.last()` is the user message that call just pushed.
        // `None` (`checkpoint_observer` unset, the default) is a no-op —
        // zero cost, no disk touched.
        if let Some(cp) = &self.checkpoint_observer {
            let label = self
                .history
                .last()
                .and_then(|m| m.content.as_deref())
                .unwrap_or("")
                .to_string();
            cp.begin_turn(&label);
        }

        // BP-4 (catalog:90, cx§2 "re-emitted on change"): once per user
        // turn — not per loop iteration — re-derive the environment block
        // so a cwd change, an approval/sandbox policy change or a branch
        // switch since the last turn reaches the model instead of leaving
        // it reading the startup snapshot. A no-op, with no subprocess, for
        // every config that doesn't set `core.env_context`.
        self.refresh_env_context();

        for _ in 0..self.config.max_iterations {
            // BP-8 (catalog:156): flush a plan `update_plan` wrote during
            // the previous iteration's tool calls. A no-op when
            // `todos.persist` is off or the plan did not change.
            self.journal_plan_if_changed();
            // BP-7: the index of the round-trip this iteration is about to
            // make. Captured here because `self.turn_index` advances the
            // moment the usage record is written, and every marker in this
            // iteration — including the ones written after that point —
            // must carry the SAME index, or the marker log would not join
            // to the usage log on `turn`.
            let round_trip = self.turn_index;
            self.maybe_compact();
            // P4b (§1.7, pi§3 "steer = after current tool calls"): drain any
            // queued mid-turn steering message(s) BEFORE building the next
            // request — the top of every loop iteration is exactly "after
            // whatever tool calls the previous iteration just ran" (or, on
            // the very first iteration, before anything has happened yet,
            // which is an equally valid "deliver immediately" reading).
            // Empty queue (today's default state) is a no-op.
            let (steer_msg, steer_taken) = {
                let mut inbox = self
                    .steer_queue
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                let before = inbox.len();
                let drained = inbox.drain(self.config.steering_mode);
                let taken = before - inbox.len();
                (drained, taken)
            };
            if let Some(steer_msg) = steer_msg {
                // BP-8 (catalog:154): the queue record's other half —
                // without it a replayed journal would keep re-delivering an
                // input the conversation already consumed.
                self.journal_queue_drain(crate::session_journal::QueueKind::Steer, steer_taken);
                let msg = ChatMessage::user(steer_msg);
                self.record(&msg)?;
                self.history.push(msg);
            }
            // Recomputed every iteration (not hoisted): under `Deferred`
            // advertising, a `tool_search` call earlier in this same loop
            // activates tools that must be advertised starting with the very
            // next request (B6).
            let tools = self.tool_schemas();
            let messages = self.build_request_messages();

            // PARITY-18 D4 — re-check the context guard before EVERY
            // request this loop builds, not just the caller's one-shot
            // preflight: interactive turns 2+, `/expand all`, and any
            // mid-loop tool round-trip that grows `messages` can push a
            // barely-passing session over the limit between sends. Only
            // armed when a caller has opted in via `set_context_limit`.
            // Uses the exact same `tokens::context_guard`
            // formula the CLI preflight uses, so the two can never disagree.
            if let Some(limit) = self.context_limit {
                let (fits, projected_tokens) =
                    crate::tokens::context_guard(&messages, &tools, limit);
                if !fits {
                    return Err(Error::ContextLimitExceeded {
                        projected_tokens,
                        reserve_tokens: crate::tokens::CONTEXT_RESPONSE_RESERVE_TOKENS,
                        context_limit: limit,
                        model: self.config.model.clone(),
                    });
                }
            }

            // BP-7 (catalog §4a "Turn/step bracketing records"): the
            // OPENING bracket, written before the request is issued so it
            // survives a request that never returns (a cancelled turn keeps
            // its `context` marker with no `usage`/`finish` after it).
            // Uses `tokens::estimate_request_tokens` — the same estimator
            // the context guard above uses, so the two can never disagree.
            self.push_turn_marker_at(
                round_trip,
                crate::turn_record::TurnMarker::Context {
                    messages: messages.len(),
                    tools: tools.len(),
                    estimated_tokens: crate::tokens::estimate_request_tokens(&messages, &tools),
                },
            );

            let mut req = self.chat_request(messages, tools);

            let fallback_hops: Vec<FallbackHop>;
            let completion = {
                let sink = self.config.event_sink.as_ref();
                let on_delta = move |s: &str| {
                    if let Some(sink) = sink {
                        sink(AgentEvent::TextDelta(s.to_string()));
                    }
                };
                // PARITY-18 D3 — the real send site: flip the flag
                // immediately before issuing the request, regardless of
                // whether `complete` then succeeds or fails, so
                // `request_issued()` truthfully reflects "a live request
                // was attempted" rather than "the run reached this line and
                // later succeeded."
                self.requests_issued = true;
                // P4b (§1.1/§3.1 `core.retry`, pi§3 shape): retry-with-
                // backoff already lives at the TRANSPORT layer
                // (`provider::OpenAiProvider::send_with_retry`, pre-existing
                // — connection failures and 5xx responses are retried
                // there); `Config.retry_*` (see `Agent::new`) makes that
                // EXISTING mechanism config-file-settable instead of
                // duplicating a second retry loop here, which would nest
                // retries confusingly on top of the transport's own.
                // BP-13 (D9 "Failure fallback model chains"): the chain is
                // EXECUTED here, not merely resolved. On a failure another
                // model could plausibly answer (overload / rate limit /
                // unavailability — `is_failover_worthy`), the request is
                // re-sent against the next entry of
                // `Config::model_fallback`, with routing re-applied for
                // that model. A 4xx that is not a rate limit is the caller's
                // problem, not the model's, and is never retried elsewhere.
                // The transport-level retry above has already run and given
                // up by the time a hop is considered.
                let (result, hops) = self.complete_with_fallback(&mut req, &on_delta).await;
                fallback_hops = hops;
                result
            };
            // BP-7: drained whether the request succeeded or failed, and
            // BEFORE the `?` — a request that exhausted its retries and
            // then errored is exactly the case a retry record exists for.
            for notice in self.retry_log.drain() {
                self.emit(AgentEvent::ProviderRetry {
                    attempt: notice.attempt,
                    delay_ms: notice.delay_ms,
                    reason: notice.reason.clone(),
                });
                self.push_turn_marker_at(
                    round_trip,
                    crate::turn_record::TurnMarker::Retry {
                        attempt: notice.attempt,
                        delay_ms: notice.delay_ms,
                        reason: notice.reason,
                    },
                );
            }
            // The switch the fallback pass performed is a real mid-session
            // model change: it moves `Config::model` for every subsequent
            // request and is recorded exactly like a user-driven `/model`
            // switch (typed record + journal line), never as a silent retry.
            for hop in fallback_hops {
                self.record_model_change(&hop.from, &hop.to, Some(hop.reason.as_str()));
            }
            let (mut assistant, usage) = completion?;
            // Persist the actual generating model on the message itself.
            // A resumed foreign session keeps its original model in
            // `SessionMeta`; using only that session-level value on export
            // misattributes every Supercode continuation turn to the source
            // harness model. Per-message provenance lets native exporters
            // preserve the boundary accurately (for example, Claude history
            // followed by a GLM continuation).
            assistant
                .metadata
                .insert("model".to_string(), self.config.model.clone());
            output_tokens_used += usage.completion_tokens;
            self.total_output_tokens += usage.completion_tokens;

            // UX-26 (B7-warn): consult the verdict computed at build time
            // (before this request was sent) now that `usage` — the only
            // piece that couldn't be known pre-send — is in hand. Gated on
            // `Config::cache_warnings` (default on; `--no-cache-warnings` /
            // `SUPERCODE_CACHE_WARNINGS=0` at the CLI layer, dev/03) so this
            // stays a zero-behavior-change no-op for every caller that
            // hasn't opted into `CachePlan::ImportedPrefix` in the first
            // place (`pending_cache_turn.0` is `false` whenever
            // `CachePlan::Off`, so the predicate always returns `None` then
            // regardless of this flag).
            let (will_annotate, cache_established, idle_secs) = self.pending_cache_turn;
            // UX-26 T2 (accuracy fold-in): `CacheColdReason::message` asserts
            // Anthropic-specific facts (a fixed 5-minute ephemeral TTL, and
            // cache-read-ratio semantics that assume Anthropic's exact-count
            // billing) that are only true for Anthropic-family models. This
            // is a WARNING-only gate, deliberately not folded into
            // `will_annotate`/the breakpoint-placement gate above: whether a
            // `cache_control` breakpoint is safe/inert to send to a
            // non-Anthropic model through OpenRouter is a separate cache-
            // behavior question this ticket doesn't touch (see
            // `.volter/tracker/markdown/UX-26.md`'s T2 note) — narrowing only
            // the warning keeps this fix scoped to warning ACCURACY, with
            // zero change to what gets sent on the wire.
            let warning_applies_to_this_model =
                provider::is_anthropic_family_model(&self.config.model);
            if self.config.cache_warnings && warning_applies_to_this_model {
                if let Some(reason) =
                    provider::cache_cold_reason(will_annotate, cache_established, idle_secs, &usage)
                {
                    self.emit(AgentEvent::CacheWarning {
                        message: reason.message(),
                    });
                }
            }
            // Refresh the activity clock / establish-once flag for the NEXT
            // turn's comparison, but only when THIS request actually carried
            // the annotation — an unannotated (busted/Off) request neither
            // warms nor cools a cache entry it never touched.
            if will_annotate {
                self.last_cache_activity_ms = Some(now_ms());
                self.cache_established = true;
            }

            // UX-23: emitted before `TurnCompleted` so a `--trace`/
            // `stream-json` consumer sees "this round-trip cost N tokens"
            // land right alongside the round-trip it describes, rather than
            // needing to correlate it with a later event.
            self.emit(AgentEvent::Usage(usage.clone()));
            self.emit(AgentEvent::TurnCompleted);
            // P4b (§1.6, catalog §4a "persisted per-turn usage records"):
            // EventSink already streamed `Usage` above — this durably
            // accumulates the same data as a typed record (see
            // `Self::usage_records`/`Self::save_usage_log`), never a lossy
            // display-only channel.
            // BP-7 (catalog §4a "Per-turn cost/usage accounting"): the
            // record now carries the round-trip's DOLLAR cost too — the
            // half the row's semantics name alongside tokens — whenever
            // this build can price the model.
            // BP-13 (D9 "Model-served-vs-requested provenance"): the record
            // now carries BOTH sides — the model this agent asked for and,
            // when the provider reported one, the model that actually
            // answered. They can genuinely differ (a gateway aliasing a
            // name to a dated snapshot, a fallback hop, a routed tier), and
            // a record that can only ever state the request cannot show it.
            let served = assistant
                .metadata
                .get(crate::provider::SERVED_MODEL_KEY)
                .cloned();
            let record = crate::usage_log::UsageRecord::from_usage(
                self.turn_index,
                &self.config.model,
                &usage,
                now_ms(),
            )
            .priced(self.model_price)
            .with_served_model(served);
            self.total_cost_usd += record.cost_usd.unwrap_or(0.0);
            // BP-7: the round-trip's usage bracket, written from the same
            // point as the usage record so the two logs never disagree.
            self.push_turn_marker_at(
                round_trip,
                crate::turn_record::TurnMarker::Usage {
                    prompt_tokens: record.prompt_tokens,
                    completion_tokens: record.completion_tokens,
                    total_tokens: record.total_tokens,
                    cached_tokens: record.cached_tokens,
                    cost_usd: record.cost_usd,
                },
            );
            self.journal_usage(&record);
            self.usage_log.push(record);
            self.turn_index += 1;
            self.record(&assistant)?;
            self.history.push(assistant.clone());

            let calls = assistant.tool_calls().to_vec();
            if calls.is_empty() {
                // Close steering acceptance under the same lock as the last
                // drain. A message accepted before this boundary extends the
                // current turn; anything later is rejected by the SDK and
                // can never leak into a future turn.
                let (steer_msg, steer_taken) = {
                    let mut inbox = self
                        .steer_queue
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    let before = inbox.len();
                    let drained = inbox.drain_or_close(self.config.steering_mode);
                    let taken = before - inbox.len();
                    (drained, taken)
                };
                if let Some(steer_msg) = steer_msg {
                    self.journal_queue_drain(crate::session_journal::QueueKind::Steer, steer_taken);
                    let msg = ChatMessage::user(steer_msg);
                    self.record(&msg)?;
                    self.history.push(msg);
                    continue;
                }
                // P4b (§1.7, pi§3 "follow-up = at idle"): a queued follow-up
                // message takes priority over the stop-gate — it's more
                // input to answer, not a veto of an answer already given.
                let follow_up_before = self.follow_up_queue.len();
                if let Some(follow_up_msg) =
                    Self::drain_steer_queue(&mut self.follow_up_queue, self.config.follow_up_mode)
                {
                    self.journal_queue_drain(
                        crate::session_journal::QueueKind::FollowUp,
                        follow_up_before - self.follow_up_queue.len(),
                    );
                    let msg = ChatMessage::user(follow_up_msg);
                    self.record(&msg)?;
                    self.history.push(msg);
                    continue;
                }
                // P4b (§1.9/§3.1 `[core] stop_gate`, D3 "stop/completion
                // gating"): consulted exactly once per iteration that would
                // otherwise return — computed into an owned `Option<String>`
                // so the immutable borrow of `self.config.stop_gate` ends
                // before the `self.record`/`self.history.push` calls below
                // need `&mut self`.
                let final_content = assistant.content.clone().unwrap_or_default();
                let veto_reason: Option<String> = self
                    .config
                    .stop_gate
                    .as_ref()
                    .and_then(|gate| gate(&final_content));
                if let Some(reason) = veto_reason {
                    let msg = ChatMessage::user(reason);
                    self.record(&msg)?;
                    self.history.push(msg);
                    continue;
                }
                // BP-8 (catalog:156): the last iteration's tool calls are
                // the ones the top-of-loop flush above never sees.
                self.journal_plan_if_changed();
                self.push_turn_marker_at(
                    round_trip,
                    crate::turn_record::TurnMarker::Finish {
                        reason: crate::turn_record::FinishReason::EndTurn,
                    },
                );
                return Ok(assistant.content.unwrap_or_default());
            }

            // BP-7: this round-trip ended by asking for tool calls; the
            // loop continues. The budget arms below mark the LOOP's end
            // separately when one of them stops it here.
            self.push_turn_marker_at(
                round_trip,
                crate::turn_record::TurnMarker::Finish {
                    reason: crate::turn_record::FinishReason::ToolCalls,
                },
            );

            // Output-token budget (output only — input tokens are not counted,
            // so this does not bound cost): stop spawning further model turns
            // once the cumulative output-token budget for this `send` is
            // exhausted.
            if let Some(budget) = self.config.max_total_output_tokens {
                if output_tokens_used >= budget {
                    // The assistant turn we just pushed carries unanswered
                    // tool_calls. Leaving them dangling yields an invalid
                    // history (assistant tool_calls with no tool results) that
                    // the provider rejects on the next `send`/resume. Emit
                    // synthetic results so the transcript stays well-formed.
                    for call in &calls {
                        let msg = ChatMessage::tool_result(
                            call.id.clone(),
                            call.function.name.clone(),
                            "[skipped: output token budget reached]".to_string(),
                        );
                        self.record(&msg)?;
                        self.history.push(msg);
                    }
                    self.push_turn_marker_at(
                        round_trip,
                        crate::turn_record::TurnMarker::Finish {
                            reason: crate::turn_record::FinishReason::OutputTokenBudget,
                        },
                    );
                    return Ok(assistant.content.clone().unwrap_or_default());
                }
            }

            // BP-7 (catalog §4a "Turn/budget caps"): the SPEND and STEP
            // caps, at the same point and with the same shape as the
            // output-token cap above — checked before this turn's tool
            // calls run, with synthetic results so the transcript stays
            // well-formed for a resume.
            let spend_exhausted = self
                .config
                .max_budget_usd
                .is_some_and(|b| b > 0.0 && self.total_cost_usd >= b);
            let steps_exhausted = self
                .config
                .max_steps
                .is_some_and(|n| n > 0 && self.total_steps + calls.len() > n);
            if spend_exhausted || steps_exhausted {
                let (label, reason) = if spend_exhausted {
                    (
                        "[skipped: spend budget reached]",
                        crate::turn_record::FinishReason::SpendBudget,
                    )
                } else {
                    (
                        "[skipped: step budget reached]",
                        crate::turn_record::FinishReason::StepBudget,
                    )
                };
                for call in &calls {
                    let msg = ChatMessage::tool_result(
                        call.id.clone(),
                        call.function.name.clone(),
                        label.to_string(),
                    );
                    self.record(&msg)?;
                    self.history.push(msg);
                }
                self.push_turn_marker_at(
                    round_trip,
                    crate::turn_record::TurnMarker::Finish { reason },
                );
                return Ok(assistant.content.clone().unwrap_or_default());
            }
            self.total_steps += calls.len();

            // P4e (§3.1 `core.parallel_tool_calls`, catalog:59): off (the
            // default) or a single call takes the EXACT pre-P4e sequential
            // path below, byte-identical. Only `true` with 2+ calls in this
            // turn takes `Self::run_tools_concurrently` — see its doc
            // comment for exactly what does and doesn't run concurrently.
            if self.config.parallel_tool_calls && calls.len() > 1 {
                for call in &calls {
                    self.emit(AgentEvent::tool_started(call));
                }
                let results = self.run_tools_concurrently(&calls).await;
                for (call, (output, is_error)) in calls.iter().zip(results) {
                    self.emit(AgentEvent::ToolCallCompleted {
                        id: call.id.clone(),
                        name: call.function.name.clone(),
                        output: output.clone(),
                        is_error,
                    });
                    self.apply_tool_result(call, output, is_error)?;
                }
            } else {
                for call in &calls {
                    self.emit(AgentEvent::tool_started(call));
                    let (output, is_error) = self.run_tool(call).await;
                    self.emit(AgentEvent::ToolCallCompleted {
                        id: call.id.clone(),
                        name: call.function.name.clone(),
                        output: output.clone(),
                        is_error,
                    });
                    self.apply_tool_result(call, output, is_error)?;
                }
            }
            // BP-3 (catalog row "Context-budget tools"): a `new_context`
            // call parks its request on the shared budget; this is where
            // the agent — the one owner of `history` — applies it, so the
            // NEXT request built by this loop is already the fresh window.
            // No parked request (every session that never calls the tool)
            // is a single `Option` check.
            self.apply_pending_new_context();
        }

        self.push_turn_marker_at(
            self.turn_index.saturating_sub(1),
            crate::turn_record::TurnMarker::Finish {
                reason: crate::turn_record::FinishReason::MaxIterations,
            },
        );
        Err(Error::MaxIterations(self.config.max_iterations))
    }

    /// BP-3: apply a parked [`crate::tools::NewContextRequest`], if any.
    ///
    /// The rewrite itself is BP-4's [`Self::new_context`] — the SAME
    /// mechanism the operator's `/handoff` runs, so the model's door and the
    /// human's door can never drift into two different notions of "a fresh
    /// window". This function is only the hand-off point between the tool
    /// that asked and the agent that owns `history`.
    fn apply_pending_new_context(&mut self) {
        let Some(request) = self.ctx.context_budget.take_new_context() else {
            return;
        };
        self.new_context(&request.objective, request.keep_recent);
    }

    /// The exact post-execution handling every tool result gets, regardless
    /// of whether it was produced by the sequential loop or
    /// [`Self::run_tools_concurrently`] — factored out of `Self::run_loop`'s
    /// tool-dispatch section (P4e) so both paths share one copy: multimodal
    /// image-marker detection, A7 output capping (gated exactly as before),
    /// TR-10 error stamping, and the `record`/`history` append. Always
    /// called in ORIGINAL call order, one call at a time, so the lossless
    /// sidecar's append-order invariant (S1.13) holds regardless of which
    /// dispatch path produced the result.
    fn apply_tool_result(
        &mut self,
        call: &crate::message::ToolCall,
        output: String,
        is_error: bool,
    ) -> Result<()> {
        // P4c (§1.2 `core.tools.read_file.multimodal` / `view_image`):
        // a successful tool result carrying the image-data-URL
        // marker becomes a `content_parts` image block instead of
        // plain text — checked BEFORE `cap_tool_output` (a data URL
        // is not meaningfully "capped" by a byte-length text notice)
        // and recorded identically on both the full and history
        // copies, mirroring `ImageRedacted`'s "images are their own
        // axis, orthogonal to A7 text truncation" treatment
        // (reduce.rs). An ERRORED call never carries the marker (a
        // tool only emits it on success), so `is_error` is not
        // re-checked here.
        if let Some(data_url) = output.strip_prefix(crate::tools::MULTIMODAL_IMAGE_MARKER) {
            let notice = format!("[{}: image content attached below]", call.function.name);
            let full_result = ChatMessage::tool_result_with_image(
                call.id.clone(),
                call.function.name.clone(),
                notice.clone(),
                data_url.to_string(),
            );
            let hist_result = ChatMessage::tool_result_with_image(
                call.id.clone(),
                call.function.name.clone(),
                notice,
                data_url.to_string(),
            );
            self.record(&full_result)?;
            self.history.push(hist_result);
            return Ok(());
        }
        // Record the FULL output before capping (A3): what the
        // sidecar keeps must never be the already-lossy, truncated
        // copy (#8/#40) — `history` alone governs what shrinks.
        let mut full_result =
            ChatMessage::tool_result(call.id.clone(), call.function.name.clone(), output.clone());
        // D6/A7 supersession gate (TR-12 land-blocker fix): `history`
        // is the exact slice `reduce::project_messages` mints A7/A10
        // reduction hashes from (`Self::build_request_messages`
        // below). Capping it here — as this unconditionally used to
        // do — would silently shrink the bytes those hashes cover, so
        // a hash minted now could never recompute the same way once
        // the sidecar is reloaded from disk later (`verify_log`/
        // `invert`, offline). Gate `cap_tool_output` off in exactly
        // the combination where reductions can be minted over
        // `history` AND the full bytes are durably retained: a
        // recorder AND a `ReductionPolicy` both installed. A7 then
        // owns tool-output bounding, reversibly, at projection time
        // (SPEC.md D6/A7) — `history`/the sidecar keep everything,
        // only the request view shrinks. With a policy but no
        // recorder (constructible via `set_reduction_policy` alone),
        // nothing durable backs the full bytes, so capping stays on —
        // the same honest-labeling spirit as `cap_tool_output`'s own
        // retention branch below, just applied at the gate instead of
        // the notice text. With no policy at all, this is untouched:
        // today's byte-identical legacy cap.
        let for_history = if self.recorder.is_some() && self.reduction_policy.is_some() {
            output
        } else {
            self.cap_tool_output(output)
        };
        let mut hist_result =
            ChatMessage::tool_result(call.id.clone(), call.function.name.clone(), for_history);
        if is_error {
            // TR-10: the reduction layer's success/failure boundary
            // (`ReductionKind::ToolInputElided` must never target an
            // errored call — TR-6's territory) has no other
            // structural signal on `ChatMessage`; stamp both the
            // recorded copy (so it survives a sidecar round-trip via
            // `NativeTurn`) and the live-history copy (so an
            // in-process `project_messages` sees it immediately).
            reduce::mark_tool_error(&mut full_result);
            reduce::mark_tool_error(&mut hist_result);
        }
        self.record(&full_result)?;
        self.history.push(hist_result);
        Ok(())
    }

    /// Truncate an oversized tool result so a single runaway command can't blow
    /// up the context window. Cuts on a char boundary and appends a notice.
    fn cap_tool_output(&self, output: String) -> String {
        let Some(max) = self.config.max_tool_output_bytes else {
            return output;
        };
        if max == 0 || output.len() <= max {
            return output;
        }
        // Find the largest char boundary <= max.
        let mut end = max;
        while end > 0 && !output.is_char_boundary(end) {
            end -= 1;
        }
        let total = output.len();
        let mut s = output[..end].to_string();
        // BP-2 (catalog:58, `core.tool_output_spill`): write the full bytes
        // to a per-session file the model can read back. Off (the default)
        // leaves the notice byte-identical to before.
        let spill = if self.config.tool_output_spill {
            self.spill_tool_output(&output)
        } else {
            None
        };
        // Honest retention labeling (D6, B10-AC4): only claim the sidecar has
        // the full output when a recorder is actually installed — or, BP-2,
        // that the spill file has it when one was actually written.
        let retention = if self.recorder.is_some() {
            "full output in session sidecar"
        } else if spill.is_some() {
            "full output on disk"
        } else {
            "full output not retained"
        };
        let recovery = match &spill {
            // The door is named in the notice, so it works WITHOUT
            // `capabilities.reduction`: under a preset with a read tool
            // that is `read_file`; under a shell-only preset (cx-parity,
            // whose whole read pathway is the shell) it is `cat`.
            Some(path) => {
                let door = if self.registry.get("read_file").is_some() {
                    "read it with `read_file`"
                } else {
                    "read it with `cat`"
                };
                format!("; full output spilled to {}{door}", path.display())
            }
            None => String::new(),
        };
        s.push_str(&format!(
            "{CAP_NOTICE_MARKER}{total} bytes total, showing first {end}; {retention}{recovery}]"
        ));
        s
    }

    /// BP-2 (catalog:58 "Oversized output truncated; full content kept
    /// reachable"): write `full` to this session's spill directory and
    /// return the path, or `None` if it could not be written (a spill is a
    /// recovery convenience — it must never fail the tool call).
    ///
    /// The file is named by content hash, so the same output spilled twice
    /// costs one file and a re-run of an identical command reuses it.
    fn spill_tool_output(&self, full: &str) -> Option<std::path::PathBuf> {
        let dir = self.spill_dir();
        std::fs::create_dir_all(&dir).ok()?;
        let digest = blake3::hash(full.as_bytes()).to_hex();
        let path = dir.join(format!("tool-output-{}.txt", &digest[..16]));
        if !path.exists() {
            std::fs::write(&path, full).ok()?;
        }
        Some(path)
    }

    /// BP-2: where this agent's spilled outputs live — beside the session
    /// sidecar when one is recording (per-SESSION, the same identity the
    /// sidecar has), else a per-PROCESS temp directory, which is as
    /// specific as an agent with no sidecar can honestly be.
    fn spill_dir(&self) -> std::path::PathBuf {
        if let Some(recorder) = &self.recorder {
            let path = recorder.path();
            if let (Some(parent), Some(stem)) = (path.parent(), path.file_stem()) {
                return parent.join(format!("{}.spill", stem.to_string_lossy()));
            }
        }
        std::env::temp_dir().join(format!("supercode-spill-{}", std::process::id()))
    }

    /// P5-3 note on the signature: written as a plain fn returning an
    /// explicitly boxed future (`Pin<Box<dyn Future + Send>>`) rather than
    /// as `async fn`. `spawn_subagent` makes this function genuinely
    /// recursive at the TYPE level: `run_tool` -> `run_spawn_subagent` ->
    /// (a child) `Agent::send` -> `run_loop` -> `run_tool` again — an
    /// `async fn`'s return type is an anonymous, compiler-inferred
    /// self-referential state machine, and inferring one that embeds
    /// itself (even indirectly, through several other functions) is a
    /// compile error (an infinitely-sized/cyclic opaque type). Declaring
    /// `run_tool`'s return type EXPLICITLY as a boxed trait object breaks
    /// the cycle: every other function on the call graph now embeds a
    /// concrete, already-known type here instead of one the compiler would
    /// otherwise need to (cyclically) infer. Callers are unaffected —
    /// `self.run_tool(call).await` reads identically either way.
    fn run_tool<'a>(
        &'a mut self,
        call: &'a crate::message::ToolCall,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = (String, bool)> + Send + 'a>> {
        Box::pin(async move {
            let translated_builtin = if self.config.claude_runtime_tools_enabled {
                match self.translate_claude_builtin_call(call) {
                    Ok(translated) => translated,
                    Err(error) => return (format!("Error: {error}"), true),
                }
            } else {
                None
            };
            let call = translated_builtin.as_ref().unwrap_or(call);
            if self.config.claude_runtime_tools_enabled
                && matches!(
                    call.function.name.as_str(),
                    CLAUDE_CRON_CREATE
                        | CLAUDE_CRON_DELETE
                        | CLAUDE_CRON_LIST
                        | CLAUDE_SCHEDULE_WAKEUP
                )
            {
                return self.run_claude_runtime_tool(call);
            }
            // P5-3: `spawn_subagent`/`subagent_status` need full async
            // `&mut self` access (running a child agent's loop, or
            // awaiting an already-finished background `JoinHandle`) —
            // `prepare_tool_call` is purely synchronous, so these are
            // intercepted HERE, one level above it, rather than inside it
            // like `TOOL_SEARCH`/`EXPAND_REDUCTION`/`SIDECAR_SEARCH`.
            if call.function.name == CLAUDE_AGENT && self.config.subagents_claude_agent_alias {
                return match self.translate_claude_agent_call(call) {
                    Ok(translated) => self.run_spawn_subagent(&translated).await,
                    Err(error) => (format!("Error: {error}"), true),
                };
            }
            if call.function.name == SPAWN_SUBAGENT {
                return self.run_spawn_subagent(call).await;
            }
            // P5-3 safety-hardening fix (Fable-5 review, LOW "wrong error
            // when disabled"): gated on `subagents_enabled`, matching
            // `run_spawn_subagent`'s own already-correct disabled behavior
            // (that one gates INTERNALLY, at its own top; this one gates
            // HERE, at the interception point, because unlike
            // `spawn_subagent` it has no other reason to run any logic at
            // all when subagents are off). When disabled, a hallucinated
            // `subagent_status` call must NOT be intercepted — it falls
            // through to `prepare_tool_call`'s normal unknown-tool path
            // below, which returns `Error::UnknownTool("subagent_status")`,
            // byte-identical to the pre-P5-3 (and disabled-spawn_subagent)
            // error text — never `Error::SubagentNotFound`'s "unknown
            // subagent id" text, which would wrongly imply subagents are on
            // but this particular id is bogus.
            if call.function.name == SUBAGENT_STATUS && self.config.subagents_enabled {
                return self.run_subagent_status(call).await;
            }
            // BP-7: same interception shape and same `subagents_enabled`
            // gate as `SUBAGENT_STATUS` above — when the module is off a
            // hallucinated call falls through to the ordinary unknown-tool
            // error rather than a misleading "unknown subagent id".
            if call.function.name == SUBAGENT_MESSAGE && self.config.subagents_enabled {
                return self.run_subagent_message(call);
            }
            if call.function.name == SUBAGENT_RESUME && self.config.subagents_enabled {
                return self.run_subagent_resume(call).await;
            }
            match self.prepare_tool_call(call) {
                PreparedCall::Done(result) => result,
                PreparedCall::Ready { name, args } => {
                    // `prepare_tool_call` already confirmed the registry has
                    // this tool.
                    let tool = self.registry.get(&name).expect("prepared as Ready");
                    let (output, is_error) = match tool.execute(args, &self.ctx).await {
                        Ok(out) => (out, false),
                        Err(e) => (format!("Error: {e}"), true),
                    };
                    if let Some(hook) = &self.config.post_tool_hook {
                        hook(&name, &output, is_error);
                    }
                    (output, is_error)
                }
            }
        })
    }

    /// P4e (§3.1 `core.parallel_tool_calls`, catalog:59): the SYNCHRONOUS
    /// half of dispatching one tool call — everything `Self::run_tool` did
    /// BEFORE its single `tool.execute(...).await`, factored out so
    /// [`Self::run_tools_concurrently`] can run these cheap, stateful,
    /// `&mut self` checks (agent intrinsics, unknown-tool, approval,
    /// doom-loop, pre-tool-hook) SEQUENTIALLY and in ORIGINAL call order —
    /// exactly as `run_tool` always has — before handing the remaining
    /// calls' `execute()` futures to `join_all`. `Self::run_tool` itself is
    /// now a thin wrapper over this (a pure refactor: byte-identical
    /// observable behavior, verified by the existing test suite).
    fn prepare_tool_call(&mut self, call: &crate::message::ToolCall) -> PreparedCall {
        let name = &call.function.name;
        // BP-3 (catalog row "Context-budget tools"): hand the model's
        // `get_context_remaining` the agent's OWN accounting — BP-4's
        // [`Self::context_usage`], the same struct `/context` prints and
        // the same estimates the context guard enforces, so what the model
        // reads and what refuses an oversized turn can never disagree.
        // Computed at the moment the question is asked (the freshest
        // possible view) and ONLY then: `context_usage` projects the whole
        // request view, which is not a cost to pay on unrelated calls.
        if name == crate::tools::GET_CONTEXT_REMAINING {
            if let Ok(usage) = serde_json::to_value(self.context_usage()) {
                self.ctx.context_budget.publish(usage);
            }
        }
        if name == TOOL_SEARCH {
            // Agent intrinsic (B6): intercepted before registry lookup, since
            // `Tool::execute` has no access to the registry or `activated_tools`.
            return PreparedCall::Done(self.run_tool_search(call));
        }
        if name == EXPAND_REDUCTION {
            // Agent intrinsic (T12/TR-1): intercepted before registry lookup,
            // same reason — resolves against `self.reduction_log`/`self.history`,
            // which `Tool::execute` has no access to.
            return PreparedCall::Done(self.run_expand_reduction(call));
        }
        if name == SIDECAR_SEARCH {
            return PreparedCall::Done(self.run_sidecar_search(call));
        }
        // P5-6 (§2 module 4 `tools.background`): gated at the interception
        // point itself (not internally, at each method's own top) —
        // mirroring `SUBAGENT_STATUS`'s own fix (Fable-5 review, LOW "wrong
        // error when disabled"): a hallucinated call when the module is off
        // must fall through to the plain `Error::UnknownTool` path below,
        // never a background-specific error that would wrongly imply the
        // module is on. Unlike `SPAWN_SUBAGENT`/`SUBAGENT_STATUS`, none of
        // these four need async `&mut self` access (spawning a process,
        // `Child::try_wait`, and `Child::start_kill` are all synchronous),
        // so they're intercepted here in `prepare_tool_call` rather than in
        // `Self::run_tool`.
        if self.config.tools_background_enabled {
            if name == BACKGROUND_EXEC {
                return PreparedCall::Done(self.run_background_exec(call));
            }
            if name == BACKGROUND_STATUS {
                return PreparedCall::Done(self.run_background_status(call));
            }
            if name == BACKGROUND_LIST {
                return PreparedCall::Done(self.run_background_list(call));
            }
            if name == BACKGROUND_KILL {
                return PreparedCall::Done(self.run_background_kill(call));
            }
        }
        if self.registry.get(name).is_none() {
            let err = Error::UnknownTool(name.clone());
            return PreparedCall::Done((format!("Error: {err}"), true));
        }

        // P5-1 (§2 modules 10-11, integration point named in
        // COMPOSABLE-HARNESS-DESIGN.md's activation set): the permissions
        // ENGINE governs the gate when `capabilities.permissions.enabled`
        // is on; every other config resolves this to `false`
        // (`Config::default`), which takes the `else` branch below —
        // the EXACT pre-P5-1 code, untouched, so the default posture
        // (approval=never/sandbox=none) and every existing test's observed
        // behavior is byte-for-byte unchanged.
        if self.config.permissions_enabled {
            // The engine needs the command/path TEXT the legacy tool-name-
            // only gate below never looked at, so args must be parsed
            // BEFORE the gate here (not after, like the legacy branch).
            let args = match call.function.parsed_arguments() {
                Ok(v) => v,
                Err(e) => {
                    let err = Error::InvalidArguments {
                        tool: name.clone(),
                        message: e.to_string(),
                    };
                    return PreparedCall::Done((format!("Error: {err}"), true));
                }
            };
            // P4c doom-loop breaker, unchanged, still before any gate.
            if let Some(reason) = self.check_doom_loop(name, &args) {
                return PreparedCall::Done((format!("Error: {reason}"), true));
            }
            // BP-10: the hook runs BEFORE the engine on this path, so its
            // rewrite is what the rules see and its allow/ask/deny is a
            // tier inside them — see `run_pre_tool_hook`.
            let (args, hook_decision) = match self.run_pre_tool_hook(name, args) {
                Ok(pair) => pair,
                Err(done) => return done,
            };
            if let Some(reason) = self.permissions_gate_denial(name, &args, hook_decision) {
                return PreparedCall::Done((format!("Error: {reason}"), true));
            }
            PreparedCall::Ready {
                name: name.clone(),
                args,
            }
        } else {
            // ---- pre-P5-1 gate, byte-for-byte unchanged ----
            // Approval gate: if the policy requires it, consult the handler
            // (absent handler denies, so an OnRequest/Untrusted policy is
            // fail-closed).
            if self.config.needs_approval(name) {
                let approved = self
                    .config
                    .approval_handler
                    .as_ref()
                    .map(|h| h(call))
                    .unwrap_or(false);
                if !approved {
                    return PreparedCall::Done((
                        format!("Error: tool `{name}` was not approved for execution"),
                        true,
                    ));
                }
            }
            let args = match call.function.parsed_arguments() {
                Ok(v) => v,
                Err(e) => {
                    let err = Error::InvalidArguments {
                        tool: name.clone(),
                        message: e.to_string(),
                    };
                    return PreparedCall::Done((format!("Error: {err}"), true));
                }
            };
            self.finish_prepare(name.clone(), args)
        }
    }

    /// P5-1: the shared tail of [`Self::prepare_tool_call`] — doom-loop
    /// check, pre-tool hook, `Ready` construction — factored out so both
    /// the legacy gate and the new permissions-engine gate run the exact
    /// same downstream checks in the exact same order (§5.3 risk 1: the
    /// permissions engine changes WHO gets to run, never what happens once
    /// they're approved).
    fn finish_prepare(&mut self, name: String, args: serde_json::Value) -> PreparedCall {
        // P4c (§5.2 P4 "doom-loop breaker", oc UNIQUE `doom_loop` row,
        // catalog D3): a default, always-available veto point distinct from
        // `Config.pre_tool_hook` (a single user-installable slot — the
        // breaker must coexist with a caller's own hook, not compete for the
        // one slot). `None`/`Some(0|1)` is a no-op — byte-identical to
        // today (no repetition tracking, no call is ever refused on this
        // basis).
        if let Some(reason) = self.check_doom_loop(&name, &args) {
            return PreparedCall::Done((format!("Error: {reason}"), true));
        }
        // Pre-tool hook may block the call. BP-10: the pre-P5-1 gate has
        // no permissions engine for a hook's `Allow`/`Ask` to be a tier
        // OF, so only the deny half can mean anything here — an
        // `updated_args` rewrite still applies (it is a property of the
        // call, not of any gate), and `Allow`/`Ask` are no-ops, exactly
        // as `None` was before BP-10.
        let mut args = args;
        if let Some(hook) = &self.config.pre_tool_hook {
            let outcome = hook(&name, &args);
            if let Some(rewritten) = outcome.updated_args {
                args = rewritten;
            }
            if outcome.decision == crate::config::HookDecision::Deny {
                let reason = outcome.reason.unwrap_or_else(|| "denied".to_string());
                return PreparedCall::Done((
                    format!("Error: blocked by pre-tool hook: {reason}"),
                    true,
                ));
            }
        }
        PreparedCall::Ready { name, args }
    }

    /// BP-10 (catalog row "Hook/plugin permission veto"): fire the pre-tool
    /// hook for the permissions-engine path, where it runs BEFORE the gate
    /// (CC's own order: a `PreToolUse` hook answers the permission question
    /// rather than being asked after it). Returns the possibly-REWRITTEN
    /// arguments plus the [`crate::config::HookDecision`] the engine folds
    /// in, or the finished denial when the hook refused outright.
    ///
    /// The rewrite lands BEFORE the gate deliberately: the engine must
    /// evaluate what will actually run, so a hook cannot launder a denied
    /// command by rewriting it past the rules.
    #[allow(clippy::type_complexity)]
    fn run_pre_tool_hook(
        &self,
        name: &str,
        args: serde_json::Value,
    ) -> std::result::Result<(serde_json::Value, crate::config::HookDecision), PreparedCall> {
        let Some(hook) = &self.config.pre_tool_hook else {
            return Ok((args, crate::config::HookDecision::Pass));
        };
        let outcome = hook(name, &args);
        let args = outcome.updated_args.unwrap_or(args);
        if outcome.decision == crate::config::HookDecision::Deny {
            let reason = outcome.reason.unwrap_or_else(|| "denied".to_string());
            return Err(PreparedCall::Done((
                format!("Error: blocked by pre-tool hook: {reason}"),
                true,
            )));
        }
        Ok((args, outcome.decision))
    }

    /// D-2 (Fable-5 delta review — LOW-MEDIUM, "over-grant residual"): the
    /// built-in tools whose `command`/`path`/`patch` arg IS semantically
    /// the whole call — the ONLY tools [`Self::permissions_gate_denial`]
    /// is allowed to turn into an [`permissions::ApprovalRequest::subject`]
    /// (see that method's own doc comment on the `subject` line for the
    /// full story). Bash-family (`bash`, and `shell` —
    /// [`crate::tools::builtins::PersistentShellTool`]'s registered name,
    /// what the review's "persistent-shell" refers to), the file tools
    /// (`read_file`/`write_file`/`edit_file`/`view_image`, whose `path` IS
    /// the subject), and `apply_patch` (whose `patch` envelope is handled
    /// separately but is unconditionally this tool only, see the `patch`
    /// local a few lines below). Deliberately NOT `list_dir`/`glob`/
    /// `search` — this crate's F2 fix (`ApprovalCache::key_for_request`)
    /// already falls back to a full-args digest for anything not on this
    /// list, which is a strictly SAFER (if slightly less cache-granular)
    /// default than guessing at more built-ins that weren't part of this
    /// finding.
    const SUBJECT_BEARING_BUILTIN_TOOLS: &'static [&'static str] = &[
        "bash",
        "shell",
        "read_file",
        "write_file",
        "edit_file",
        "view_image",
        "apply_patch",
    ];

    /// P5-1: evaluate `name`'s call (with parsed `args`) against the
    /// permissions engine (`crate::permissions`) — builds the
    /// [`crate::permissions::RuleSet`] from `Config`'s deny/ask/allow
    /// pattern lists (folding [`Config::permissions_protected_paths`] into
    /// the `deny` tier, module 13), picks a command-, path-, or name-only
    /// evaluation depending on what `args` carries, resolves an `Ask`
    /// decision via the session cache + THIS agent's own installed
    /// [`crate::permissions::PermissionsApprovalHandler`], and returns
    /// `Some(reason)` when the call is refused (`None` = proceed). Thin
    /// wrapper over [`Self::permissions_gate_denial_impl`] — see that
    /// method's doc comment for why the handler is a parameter there.
    fn permissions_gate_denial(
        &self,
        name: &str,
        args: &serde_json::Value,
        hook: crate::config::HookDecision,
    ) -> Option<String> {
        self.permissions_gate_denial_impl(
            name,
            args,
            self.permissions_approval_handler.as_deref(),
            hook,
        )
    }

    /// P5-6 (§2.2 C6, build brief "wire to the P5-1 engine's non-
    /// interactive fail-closed path"): the SAME rule-evaluation body as
    /// [`Self::permissions_gate_denial`], but the approval `handler` is a
    /// PARAMETER instead of always reading `self.permissions_approval_handler`
    /// — `Agent::background_permission_denial` calls this with `handler:
    /// None` (or a [`crate::subagents::ParentQueueApprovalHandler`]) so a
    /// `background_exec` call's `Ask`-tier decisions resolve exactly like a
    /// P5-3 background child's do (`crate::permissions::resolve_ask`'s
    /// pre-existing "no handler ⇒ deny" contract), REGARDLESS of whether
    /// this agent itself has an interactive handler installed for its own
    /// foreground calls — a background job must never block on a prompt it
    /// has no way to answer, even if the agent hosting it could otherwise
    /// answer one. The rule SET and default-policy baseline are otherwise
    /// identical to a foreground call's — only how an `Ask` decision
    /// resolves ever differs, and only in the strictly-narrower direction
    /// (never escalates past what a foreground call of the same command is
    /// allowed).
    fn permissions_gate_denial_impl(
        &self,
        name: &str,
        args: &serde_json::Value,
        handler: Option<&dyn crate::permissions::PermissionsApprovalHandler>,
        hook: crate::config::HookDecision,
    ) -> Option<String> {
        use crate::permissions::{self, Decision, PathKind};

        // `Config.tool_deny_patterns`/`tool_allow_patterns` (P4a) ARE the
        // engine's deny/allow tiers — the same `capabilities.permissions.
        // rules.deny`/`.allow` keys, one source of truth, no duplication.
        // Protected paths (module 13) are an unconditional deny floor,
        // folded in here rather than checked separately, so they benefit
        // from the SAME first-match deny-wins priority every other deny
        // rule gets.
        // BP-5: the rule set itself is `permissions::rules_for_config` —
        // ONE construction shared with every other surface that has to ask
        // this engine a question (see that function's doc comment). Plan
        // mode's narrowing is layered on top of it here, because it is
        // this agent's live state, not the config's.
        let mut rules = permissions::rules_for_config(&self.config);
        // BP-3 (§2 module 8 `plan_mode`, dependency edge `plan_mode →
        // permissions.rules|sandbox`): the read-only research phase IS a
        // narrowing of this rule set — while the mode is active the write
        // and execution tools join the deny tier, and get the same
        // first-match, never-overridable treatment every other deny rule
        // gets. Inactive (the default, and the only state a config without
        // the module can reach) contributes NOTHING, so the rule set is
        // byte-identical to before.
        rules
            .deny
            .extend(crate::tools::plan_mode::deny_rules(&self.ctx.plan_mode));

        // The baseline decision when NO rule matches at all — derived from
        // `ApprovalPolicy`, the same per-policy shape
        // `Config::needs_approval` uses for the legacy gate (see
        // `ApprovalPolicy::ModelRequested`'s doc comment for why this
        // richer gate approximates Codex's real "mostly silent" posture
        // instead of that method's conservative OnRequest-alike treatment
        // — explicit deny/ask rules still apply on top regardless).
        let default = permissions::default_decision(&self.config, name);

        // BP-10: path rules are evaluated relative to EVERY granted root
        // (cwd + `core.additional_dirs`/`--add-dir`), folded to the
        // strictest — see `permissions::evaluate_path_safe_roots`'s doc
        // comment for why a grant must not also remove the root-relative
        // protected-path floor inside the granted directory. With no extra
        // dirs (the default) this is the single `cwd` list, byte-identical
        // to before.
        let mut roots = vec![self.config.cwd.clone()];
        roots.extend(self.config.additional_dirs.iter().cloned());

        let command = args.get("command").and_then(|v| v.as_str());
        let path = args.get("path").and_then(|v| v.as_str());
        // F4 (Fable-5 adversarial review): `apply_patch`'s args carry a
        // patch ENVELOPE body (`args["patch"]`), not a `command` or a
        // `path` — the two branches above never fire for it, which is
        // exactly how a patch touching a protected path bypassed
        // `protected_paths` entirely. Only consulted for the `apply_patch`
        // tool specifically (a `patch`-shaped arg on some other tool is not
        // this envelope format and isn't given this treatment).
        let patch = (name == "apply_patch")
            .then(|| args.get("patch").and_then(|v| v.as_str()))
            .flatten();
        let decision = if let Some(command) = command {
            permissions::evaluate_command(&rules, name, command, default)
        } else if let Some(patch) = patch {
            // Same dual-check shape as the path branch below (pseudo-tool
            // `write(...)` rules from `protected_paths`, AND a rule
            // authored against the real `apply_patch` tool name), applied
            // to EVERY path the envelope's ops touch (`Add`/`Delete`/
            // `Update`'s `path`, plus `*** Move to:`). A patch that fails
            // to parse can't be proven to avoid a protected path — fail
            // closed to at least `Ask`, the same floor an unparseable bash
            // command gets in `permissions::evaluate_command`, rather than
            // silently let it through on `default`.
            let mut d = rules.evaluate(name, None).unwrap_or(default);
            match crate::tools::patch_target_paths(patch) {
                Ok(paths) => {
                    for p in &paths {
                        // SECURITY (CRITICAL fix): route both checks through
                        // the safe-path-resolving variants — a patch target
                        // like `x/../.git/config` must be caught exactly
                        // like a `write_file`/`edit_file` `path` argument
                        // would be (see `evaluate_path_safe`'s doc comment).
                        let pseudo = permissions::evaluate_path_safe_roots(
                            &rules,
                            PathKind::Write,
                            &roots,
                            p,
                            Decision::Allow,
                        );
                        let real_tool = permissions::evaluate_path_subject_safe_roots(
                            &rules,
                            name,
                            &roots,
                            p,
                            Decision::Allow,
                        );
                        d = d.stricter(pseudo).stricter(real_tool);
                    }
                }
                Err(_) => {
                    d = d.stricter(Decision::Ask);
                }
            }
            d
        } else if let Some(path) = path {
            let kind = if matches!(name, "write_file" | "edit_file") {
                PathKind::Write
            } else {
                PathKind::Read
            };
            // TWO independent sources of path-shaped rules can apply to the
            // same call, and BOTH must be checked:
            // (a) the `read(...)`/`write(...)` pseudo-tool (tool-agnostic —
            //     applies no matter WHICH tool touches the path; this is
            //     what `Config::permissions_protected_paths`/module 13
            //     expands into, via `protected_path_deny_rules`);
            // (b) a rule authored against the REAL tool name with the path
            //     as its subject — design §4.4's own oc-parity worked
            //     example writes exactly this shape (`"read_file(*.env)"`,
            //     not a pseudo-tool), matching how `bash(cmdglob)` rules
            //     are authored. `RuleSet::evaluate`'s bare-tool-name-glob
            //     branch (no parens) ALSO fires here regardless of
            //     `subject`, so this one call additionally covers a
            //     blanket "deny this tool entirely" rule — no separate
            //     `rules.evaluate(name, None)` call is needed.
            // SECURITY (CRITICAL fix, guarantor audit): both checks now
            // route through the safe-path-resolving variants (see
            // `evaluate_path_safe`'s doc comment) instead of glob-matching
            // the raw model-supplied `path` string directly — this is what
            // closes the traversal bypass (`write_file
            // path="x/../.git/config"`) and the analogous symlink escape.
            let pseudo_decision =
                permissions::evaluate_path_safe_roots(&rules, kind, &roots, path, default);
            let real_tool_decision =
                permissions::evaluate_path_subject_safe_roots(&rules, name, &roots, path, default);
            pseudo_decision.stricter(real_tool_decision)
        } else {
            rules.evaluate(name, None).unwrap_or(default)
        };

        // BP-10 (catalog row "Hook/plugin permission veto"): the hook's
        // verdict is a TIER of this engine, folded in the one direction
        // that is always safe — `Ask` tightens (`stricter` never loosens),
        // `Deny` is a floor. `Allow` deliberately does NOT change the
        // decision here: it answers the `Ask` tier below (the
        // `PermissionRequest`-class reply CC's hooks give on the user's
        // behalf), so a `deny` rule still refuses the call outright — a
        // hook may skip a prompt, never a floor.
        let decision = match hook {
            crate::config::HookDecision::Deny => Decision::Deny,
            crate::config::HookDecision::Ask => decision.stricter(Decision::Ask),
            crate::config::HookDecision::Allow | crate::config::HookDecision::Pass => decision,
        };

        // BP-10 (catalog row "Sandbox-escalation path", cx§4
        // `sandbox_permissions: "require_escalated"` + justification): the
        // model's channel to ASK for an unsandboxed run is a rule inside
        // this one engine, not a switch beside it. A call carrying
        // `with_escalated_permissions: true` is forced to at least the
        // `Ask` tier — never below whatever the rules already decided, so
        // a denied command cannot escalate its way out (`stricter` only
        // tightens), and never silently allowed under
        // `ApprovalPolicy::ModelRequested`/`Never`, whose `Allow` baseline
        // is exactly what made "the model requests escalation" a no-op
        // before. The `justification` rides in `raw_args` below, so the
        // approval door shows the user the model's own reason.
        let decision = if args
            .get("with_escalated_permissions")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
        {
            decision.stricter(Decision::Ask)
        } else {
            decision
        };

        // D-2 (Fable-5 delta review — LOW-MEDIUM): `command`/`path`/`patch`
        // above are extracted (and used to DRIVE the decision above) for
        // ANY tool that happens to carry one of those arg names — that
        // part is unchanged and correct (a rule authored against, say, an
        // MCP tool's own name legitimately wants to glob-match its
        // `command`-shaped arg too). But the narrower single-field
        // `subject` handed to the cache/handler below must NOT do the
        // same for a non-built-in tool: an MCP (or other) tool's
        // `command`/`path` is just one field among potentially several
        // that together define what the call actually does — collapsing
        // an `AllowForSession` grant down to that one field would silently
        // auto-allow a later call with the SAME `command` but different
        // OTHER args (e.g. `{"command":"sync","target":"staging"}`
        // auto-allowing `{"command":"sync","target":"production"}`).
        // Restricting this to the known built-ins whose `subject` really
        // IS the whole call leaves every other tool with `subject: None`,
        // which routes it through `ApprovalCache::key_for_request`'s
        // full-args-digest fallback (F2) instead.
        let subject = Self::SUBJECT_BEARING_BUILTIN_TOOLS
            .contains(&name)
            .then(|| command.or(path).or(patch))
            .flatten();
        let req = permissions::ApprovalRequest {
            tool: name,
            subject,
            raw_args: args,
        };
        let approved = permissions::decision_to_approved(decision, || {
            // BP-10: a hook `Allow` answers this ask without a prompt (and
            // without a cache entry — the hook is consulted on every call,
            // so caching its answer would be a second, staler copy of the
            // same decision).
            if hook == crate::config::HookDecision::Allow {
                return true;
            }
            permissions::resolve_ask(&self.permissions_approval_cache, handler, &req)
        });
        if approved {
            None
        } else {
            Some(format!(
                "tool `{name}` was not approved for execution (permissions engine: {decision:?})"
            ))
        }
    }

    /// P5-6 (§2.2 C6, build brief "a bg `rm -rf` subject to the same deny
    /// rules... must never escalate past what a foreground exec of the
    /// same command is allowed"): the permission gate `background_exec`
    /// runs BEFORE spawning anything. Evaluated against the tool name
    /// `"bash"` (not `"background_exec"`) deliberately — so any
    /// `bash(...)`-authored deny/ask/allow rule (or protected-path floor)
    /// applies to a background command byte-for-byte identically to a
    /// foreground `bash` call, the SAME rule set + default baseline
    /// [`Self::permissions_gate_denial`] would use for one.
    ///
    /// The one deliberate difference (C6 itself): an `Ask`-tier decision
    /// NEVER reaches an interactive handler here — a background job has no
    /// way to block on a prompt it can't answer. When
    /// [`Config::subagents_background_prompts`] is
    /// [`crate::subagents::BackgroundPromptsPolicy::Parent`], the denied
    /// request is additionally queued onto [`Self::pending_child_approvals`]
    /// (via [`crate::subagents::ParentQueueApprovalHandler`], reused
    /// verbatim — the SAME "parent-surfaced queue" §2.2 C6 names for
    /// `subagents.background`, with the job id standing in for a child
    /// agent id) for later inspection; any other configuration (including
    /// no `background_prompts` set at all) resolves via `handler: None` —
    /// [`crate::permissions::resolve_ask`]'s pre-existing "no handler ⇒
    /// deny" fail-closed default, identical to `subagents`'s own
    /// `AutoPolicy` reading. Either way, `Ask` always denies; only `Allow`
    /// (from the rule engine itself, or a PRIOR interactively-granted
    /// `AllowForSession` cache entry) ever lets a background command run —
    /// so this can only ever be as-or-more restrictive than a foreground
    /// call, never looser, regardless of configuration.
    ///
    /// Covers BOTH gate generations: when [`Config::permissions_enabled`]
    /// is on, the P5-1 engine (above) is used; otherwise the legacy
    /// [`Config::needs_approval`] gate is consulted but its
    /// `approval_handler` closure is NEVER invoked (that closure could
    /// itself block, e.g. a real interactive prompt) — an approval-required
    /// legacy policy simply denies a background command outright, the same
    /// never-hang guarantee under the older gate.
    fn background_permission_denial(
        &self,
        command: &str,
        job_id: &str,
        hook: crate::config::HookDecision,
    ) -> Option<String> {
        let args = serde_json::json!({ "command": command });
        if self.config.permissions_enabled {
            if let Some(crate::subagents::BackgroundPromptsPolicy::Parent) =
                self.config.subagents_background_prompts
            {
                let handler = crate::subagents::ParentQueueApprovalHandler {
                    child_agent_id: format!("bg:{job_id}"),
                    queue: self.pending_child_approvals.clone(),
                };
                self.permissions_gate_denial_impl("bash", &args, Some(&handler), hook)
            } else {
                self.permissions_gate_denial_impl("bash", &args, None, hook)
            }
        } else if self.config.needs_approval("bash") {
            Some(
                "tool `bash` requires approval, which a background job cannot request \
                 interactively (§2.2 C6: auto-policy denies)"
                    .to_string(),
            )
        } else {
            None
        }
    }

    /// P4e (§3.1 `core.parallel_tool_calls`, catalog:59 "Independent
    /// sibling calls run concurrently"): runs `calls`' `Tool::execute()`
    /// futures CONCURRENTLY via `futures::future::join_all`, for whichever
    /// calls [`Self::prepare_tool_call`] resolves to [`PreparedCall::Ready`]
    /// — i.e. every plain (non-intrinsic) registry-tool call that passes
    /// its synchronous approval/doom-loop/pre-tool-hook checks. A call that
    /// resolves to [`PreparedCall::Done`] (an intrinsic, an unknown tool, a
    /// denied/blocked call) is NOT parallelized — its result is already in
    /// hand from the synchronous prepare pass. Every prepare check still
    /// runs sequentially, in original call order, before ANY `execute()`
    /// future starts (only the actual tool I/O overlaps) — so doom-loop
    /// bookkeeping and pre-tool-hook vetoes see the exact same call order
    /// they would under the sequential path. Returns results in the SAME
    /// order as `calls`, so callers can always `zip` the two. Post-tool
    /// hooks fire per call, in original order, once every result is in
    /// hand — a caller-visible timing difference from the sequential path
    /// ONLY when this method runs at all (i.e. only when
    /// `Config::parallel_tool_calls` is on): hooks see "this batch
    /// finished" ordering rather than "this one call finished" ordering.
    /// Documented, not a bug.
    async fn run_tools_concurrently(
        &mut self,
        calls: &[crate::message::ToolCall],
    ) -> Vec<(String, bool)> {
        // P5-3: `spawn_subagent`/`subagent_status` need sequential `&mut
        // self` access `prepare_tool_call`'s synchronous-only signature
        // can't give them (see `Self::run_tool`'s identical interception).
        // A batch that includes one falls back to dispatching the WHOLE
        // batch sequentially via `Self::run_tool` — a documented, narrow
        // simplification (not a partial-parallelization attempt) rather
        // than restructuring `PreparedCall` to carry a future; a batch with
        // no subagent intrinsic is completely unaffected and still
        // parallelizes exactly as before.
        if calls.iter().any(|c| {
            c.function.name == SPAWN_SUBAGENT
                || c.function.name == SUBAGENT_STATUS
                || c.function.name == SUBAGENT_MESSAGE
                || c.function.name == SUBAGENT_RESUME
                || (self.config.claude_runtime_tools_enabled
                    && matches!(
                        c.function.name.as_str(),
                        CLAUDE_CRON_CREATE
                            | CLAUDE_CRON_DELETE
                            | CLAUDE_CRON_LIST
                            | CLAUDE_SCHEDULE_WAKEUP
                    ))
        }) {
            let mut out = Vec::with_capacity(calls.len());
            for call in calls {
                out.push(self.run_tool(call).await);
            }
            return out;
        }
        let prepared: Vec<PreparedCall> = calls.iter().map(|c| self.prepare_tool_call(c)).collect();
        let mut slots: Vec<Option<(String, bool)>> = prepared
            .iter()
            .map(|p| match p {
                PreparedCall::Done(r) => Some(r.clone()),
                PreparedCall::Ready { .. } => None,
            })
            .collect();

        let ready_idxs: Vec<usize> = prepared
            .iter()
            .enumerate()
            .filter(|(_, p)| matches!(p, PreparedCall::Ready { .. }))
            .map(|(i, _)| i)
            .collect();

        if !ready_idxs.is_empty() {
            let futs = ready_idxs.iter().map(|&i| {
                let PreparedCall::Ready { name, args } = &prepared[i] else {
                    unreachable!("filtered to Ready above")
                };
                // `self.registry.get` borrows `self.registry` immutably;
                // `self.ctx` is `Clone` (P4c precedent) so each future owns
                // its own copy rather than borrowing `self` across the
                // `.await` inside `join_all`.
                let tool = self.registry.get(name).expect("prepared as Ready");
                let args = args.clone();
                let ctx = self.ctx.clone();
                async move {
                    match tool.execute(args, &ctx).await {
                        Ok(out) => (out, false),
                        Err(e) => (format!("Error: {e}"), true),
                    }
                }
            });
            let results = futures::future::join_all(futs).await;
            for (idx, result) in ready_idxs.iter().zip(results) {
                slots[*idx] = Some(result);
            }
        }

        let out: Vec<(String, bool)> = slots
            .into_iter()
            .map(|s| s.expect("every call resolved to Some above"))
            .collect();
        // Post-tool hook, in original order — only for calls that actually
        // reached `execute()` (matches `run_tool`'s existing behavior: an
        // intrinsic/denied/blocked call never fires the post-tool hook).
        let ready_set: std::collections::HashSet<usize> = ready_idxs.into_iter().collect();
        for (i, call) in calls.iter().enumerate() {
            if !ready_set.contains(&i) {
                continue;
            }
            let (output, is_error) = &out[i];
            if let Some(hook) = &self.config.post_tool_hook {
                hook(&call.function.name, output, *is_error);
            }
        }
        out
    }

    /// P4c (§5.2 P4 "doom-loop breaker", §3.1 `core.doom_loop_threshold`):
    /// update the consecutive-identical-call streak for `(name, args)` and
    /// return `Some(reason)` the moment the streak reaches
    /// `Config.doom_loop_threshold` (a call whose name AND JSON-canonical
    /// arguments are byte-identical to the immediately preceding call
    /// extends the streak; anything else resets it to 1). `None`
    /// (`Config.doom_loop_threshold` unset, or `Some(n)` with `n < 2` — a
    /// threshold below 2 can never fire since the FIRST call already
    /// "repeats zero times") never touches the streak fields at all.
    fn check_doom_loop(&mut self, name: &str, args: &serde_json::Value) -> Option<String> {
        let threshold = self.config.doom_loop_threshold?;
        if threshold < 2 {
            return None;
        }
        // `serde_json::Value::Object` is a `BTreeMap` in this workspace (no
        // `preserve_order` feature), so `to_string()` is already
        // key-order-canonical — two calls that differ only in argument key
        // order are still treated as identical.
        let key = (name.to_string(), args.to_string());
        if self.doom_loop_last_call.as_ref() == Some(&key) {
            self.doom_loop_streak += 1;
        } else {
            self.doom_loop_last_call = Some(key);
            self.doom_loop_streak = 1;
        }
        if self.doom_loop_streak >= threshold {
            Some(format!(
                "doom-loop breaker: `{name}` called with identical arguments {} times in a row \
                 — try a different approach instead of repeating the same call",
                self.doom_loop_streak
            ))
        } else {
            None
        }
    }

    /// Whether `name` is in the eagerly-advertised "core" set for the current
    /// [`ToolAdvertising`] mode: every enabled tool under `Full`, or the
    /// explicit `core` allowlist under `Deferred`.
    fn is_core_tool(&self, name: &str) -> bool {
        match &self.config.tool_advertising {
            ToolAdvertising::Full => true,
            ToolAdvertising::Deferred { core } => core.iter().any(|c| c == name),
        }
    }

    /// The schema advertised on the wire for `t`: the raw (as-shipped)
    /// schema with TR-8/T5's per-tool schema tier applied. This is what
    /// [`Self::tool_schemas`] sends every request.
    fn schema_for(&self, t: &dyn crate::tools::Tool) -> ToolSchema {
        let raw = self.raw_schema_for(t);
        let tier = self.config.schema_tier_for(t.name());
        let (description, parameters) =
            crate::tools::tiers::minify(&raw.description, &raw.parameters, tier);
        ToolSchema {
            name: raw.name,
            description,
            parameters,
        }
    }

    /// The ORIGINAL, as-shipped schema for `t` — never tier-minified. This is
    /// the full contract [`Self::run_tool_search`] hands back on activation
    /// (TR-8/T5 dev/03: the B6 fetch path is the invert of tiering, so a
    /// model that fetched a tool via `tool_search` always sees the complete
    /// schema, byte-equal to `t.description()`/`t.parameters()` — modulo the
    /// pre-existing [`crate::Config::tool_description`] override, which is
    /// orthogonal to tiering).
    fn raw_schema_for(&self, t: &dyn crate::tools::Tool) -> ToolSchema {
        ToolSchema {
            name: t.name().to_string(),
            description: self
                .config
                .tool_description(t.name(), t.description())
                .to_string(),
            parameters: t.parameters(),
        }
    }

    /// The synthetic `tool_search` schema advertised under `Deferred` (B6).
    fn tool_search_schema() -> ToolSchema {
        ToolSchema {
            name: TOOL_SEARCH.to_string(),
            description: "Search for additional tools not currently advertised (the deferred \
                MCP surface and any other non-core tools). Matches keywords case-insensitively \
                against each tool's name and description. Matched tools become callable starting \
                with your NEXT message, not this one."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Keyword(s) to search for in tool names and descriptions."
                    },
                    "max_results": {
                        "type": "integer",
                        "description": "Maximum number of matching tools to return."
                    }
                },
                "required": ["query"],
                "additionalProperties": false
            }),
        }
    }

    /// The tool-schema array this agent would advertise on its NEXT
    /// request, exactly as `Self::run_loop` computes it. Public
    /// (PARITY-18 D1) so a caller can measure the real request-token cost
    /// of an agent's tool surface — including the current
    /// [`crate::config::ToolAdvertising`] mode's core/deferred split and
    /// the synthetic `tool_search`/`expand_reduction`/`sidecar_search`
    /// schemas — BEFORE ever calling [`Self::send`], e.g. for a preflight
    /// context-guard check.
    pub fn tool_schemas(&self) -> Vec<ToolSchema> {
        let mut out = match &self.config.tool_advertising {
            ToolAdvertising::Full => self
                .registry
                .iter()
                .filter(|t| self.config.tool_enabled(t.name()))
                .map(|t| self.schema_for(t))
                .collect(),
            ToolAdvertising::Deferred { .. } => {
                let mut out: Vec<ToolSchema> = self
                    .registry
                    .iter()
                    .filter(|t| self.config.tool_enabled(t.name()))
                    .filter(|t| {
                        self.is_core_tool(t.name()) || self.activated_tools.contains(t.name())
                    })
                    .map(|t| self.schema_for(t))
                    .collect();
                out.push(Self::tool_search_schema());
                out
            }
        };
        // T12/TR-1: `expand_reduction`/`sidecar_search` are orthogonal to
        // `tool_advertising` (which governs the ordinary tool surface) —
        // advertised whenever a `ReductionPolicy` is installed, regardless of
        // Full/Deferred, since only a reduced session ever has anything to
        // expand or search (SPEC.md TR-1 dev/01).
        if self.reduction_policy.is_some() {
            out.push(Self::expand_reduction_schema());
            out.push(Self::sidecar_search_schema());
        }
        // P5-3 (§2 module 9): `spawn_subagent`/`subagent_status` are
        // orthogonal to `tool_advertising` too, same reasoning as
        // `expand_reduction`/`sidecar_search` above — advertised whenever
        // `Config::subagents_enabled` is on, Full or Deferred alike.
        // `false` (the default) never appends either, so a config that
        // never turns the module on gets byte-identical tool schemas to
        // today.
        if self.config.subagents_enabled {
            out.push(self.spawn_subagent_schema());
            if self.config.subagents_claude_agent_alias {
                out.push(self.claude_agent_schema());
            }
            if self.config.subagents_background {
                out.push(Self::subagent_status_schema());
                // BP-7 (catalog §4a "Background subagents + resume"): the
                // two halves the row named as missing — a mailbox into a
                // still-running child, and a resume of a finished one with
                // its context intact.
                out.push(Self::subagent_message_schema());
                out.push(Self::subagent_resume_schema());
            }
        }
        if self.config.claude_runtime_tools_enabled {
            out.extend(self.claude_builtin_tool_schemas());
            out.push(Self::claude_cron_create_schema());
            out.push(Self::claude_cron_delete_schema());
            out.push(Self::claude_cron_list_schema());
            out.push(Self::claude_schedule_wakeup_schema());
        }
        // P5-6 (§2 module 4 `tools.background`): same orthogonal-to-
        // `tool_advertising` treatment, advertised whenever
        // `Config::tools_background_enabled` is on. `false` (the default)
        // never appends any of the four, so a config that never turns the
        // module on gets byte-identical tool schemas to today.
        if self.config.tools_background_enabled {
            out.push(Self::background_exec_schema());
            out.push(Self::background_status_schema());
            out.push(Self::background_list_schema());
            out.push(Self::background_kill_schema());
        }
        // BP-10 (catalog row "Tool hiding via policy", cc§4 "bare-name
        // deny"): a policy deny does not merely REFUSE the call at
        // dispatch — it removes the tool from the model's view. Applied
        // once, here, over the finished array, so every family appended
        // above (`spawn_subagent`, `background_*`, the Claude aliases,
        // `expand_reduction`, …) is hidden by the same one rule, not by a
        // per-family repeat of it. See [`Self::policy_hides_tool`] for
        // which deny tier is consulted and why.
        out.retain(|schema| !self.policy_hides_tool(&schema.name));
        out
    }

    /// BP-10: whether the CONFIG-DECLARED deny tier hides `name` from the
    /// model's tool surface entirely (cc§4: CC's bare-name deny "removes
    /// the tool from the model's view", where an ordinary rule only
    /// refuses the call).
    ///
    /// The ONE engine decides: this is
    /// [`crate::permissions::RuleSet::evaluate`] with `subject: None`, so
    /// exactly the patterns that can be satisfied by a tool NAME ALONE
    /// (`"bash"`, `"mcp_*"`, `"*"`) hide; a rule that names a
    /// command/path constraint (`"bash(rm -rf*)"`, `"write(.git/**)"`) is
    /// not satisfiable without a subject and therefore never hides a tool
    /// — the same `rule_matches` contract the dispatch gate uses.
    ///
    /// **Which deny tier.** `Config::tool_deny_patterns` — the
    /// `capabilities.permissions.rules.deny` array — and NOT the two
    /// runtime narrowings the dispatch gate folds in beside it:
    /// `protected_paths` expands to `read(...)`/`write(...)` patterns that
    /// carry a subject by construction (so they could never match here
    /// anyway), and `plan_mode::deny_rules` is a MODE, not a policy — CC's
    /// plan mode refuses a write, it does not make Write disappear and
    /// reappear as the mode toggles mid-session. Hiding is a property of
    /// the configured policy, which is fixed for the run.
    ///
    /// Gated on [`Config::permissions_enabled`]: a config that never turns
    /// the module on gets byte-identical schemas to before this existed.
    fn policy_hides_tool(&self, name: &str) -> bool {
        if !self.config.permissions_enabled || self.config.tool_deny_patterns.is_empty() {
            return false;
        }
        let rules = crate::permissions::RuleSet {
            deny: self.config.tool_deny_patterns.clone(),
            ..Default::default()
        };
        rules.evaluate(name, None) == Some(crate::permissions::Decision::Deny)
    }

    fn claude_builtin_tool_schemas(&self) -> Vec<ToolSchema> {
        let mut schemas = Vec::new();
        let mut push = |alias: &str, native: &str, description: &str, parameters| {
            if self.registry.get(native).is_some() && self.config.tool_enabled(native) {
                schemas.push(ToolSchema {
                    name: alias.to_string(),
                    description: description.to_string(),
                    parameters,
                });
            }
        };
        push(
            CLAUDE_BASH,
            "bash",
            "Claude Code-compatible shell command execution.",
            serde_json::json!({
                "type": "object",
                "properties": {
                    "command": {"type": "string"},
                    "timeout": {"type": "integer", "description": "Timeout in milliseconds."},
                    "description": {"type": "string"}
                },
                "required": ["command"],
                "additionalProperties": true
            }),
        );
        push(
            CLAUDE_READ,
            "read_file",
            "Claude Code-compatible file reader.",
            serde_json::json!({
                "type": "object",
                "properties": {
                    "file_path": {"type": "string"},
                    "offset": {"type": "integer"},
                    "limit": {"type": "integer"}
                },
                "required": ["file_path"],
                "additionalProperties": false
            }),
        );
        push(
            CLAUDE_WRITE,
            "write_file",
            "Claude Code-compatible file writer.",
            serde_json::json!({
                "type": "object",
                "properties": {"file_path": {"type": "string"}, "content": {"type": "string"}},
                "required": ["file_path", "content"],
                "additionalProperties": false
            }),
        );
        push(
            CLAUDE_EDIT,
            "edit_file",
            "Claude Code-compatible exact file edit.",
            serde_json::json!({
                "type": "object",
                "properties": {
                    "file_path": {"type": "string"},
                    "old_string": {"type": "string"},
                    "new_string": {"type": "string"},
                    "replace_all": {"type": "boolean"}
                },
                "required": ["file_path", "old_string", "new_string"],
                "additionalProperties": false
            }),
        );
        push(
            CLAUDE_GLOB,
            "glob",
            "Claude Code-compatible file glob.",
            serde_json::json!({
                "type": "object",
                "properties": {"pattern": {"type": "string"}, "path": {"type": "string"}},
                "required": ["pattern"],
                "additionalProperties": false
            }),
        );
        push(
            CLAUDE_GREP,
            "search",
            "Claude Code-compatible content search.",
            serde_json::json!({
                "type": "object",
                "properties": {"pattern": {"type": "string"}, "path": {"type": "string"}},
                "required": ["pattern"],
                "additionalProperties": true
            }),
        );
        schemas
    }

    fn translate_claude_builtin_call(
        &self,
        call: &crate::message::ToolCall,
    ) -> Result<Option<crate::message::ToolCall>> {
        let native = match call.function.name.as_str() {
            CLAUDE_BASH => "bash",
            CLAUDE_READ => "read_file",
            CLAUDE_WRITE => "write_file",
            CLAUDE_EDIT => "edit_file",
            CLAUDE_GLOB => "glob",
            CLAUDE_GREP => "search",
            _ => return Ok(None),
        };
        let mut args = call.function.parsed_arguments()?;
        let object = args
            .as_object_mut()
            .ok_or_else(|| Error::InvalidArguments {
                tool: call.function.name.clone(),
                message: "expected a JSON object".to_string(),
            })?;
        if let Some(path) = object.remove("file_path") {
            object.entry("path".to_string()).or_insert(path);
        }
        if call.function.name == CLAUDE_BASH {
            if let Some(timeout) = object.remove("timeout") {
                object.entry("timeout_ms".to_string()).or_insert(timeout);
            }
        }
        if call.function.name == CLAUDE_GLOB {
            if let Some(path) = object
                .remove("path")
                .and_then(|value| value.as_str().map(str::to_owned))
            {
                if let Some(pattern) = object.get_mut("pattern") {
                    if let Some(value) = pattern.as_str() {
                        if !std::path::Path::new(value).is_absolute() {
                            *pattern = serde_json::Value::String(
                                std::path::Path::new(&path)
                                    .join(value)
                                    .to_string_lossy()
                                    .into_owned(),
                            );
                        }
                    }
                }
            }
        }
        let mut translated = call.clone();
        translated.function.name = native.to_string();
        translated.function.arguments = serde_json::to_string(&args)?;
        Ok(Some(translated))
    }

    fn claude_cron_create_schema() -> ToolSchema {
        ToolSchema {
            name: CLAUDE_CRON_CREATE.to_string(),
            description: "Record a Claude-compatible cron job in the imported runtime manifest. \
                The job inherits the manifest's ACTIVE or PAUSED posture; an embedding scheduler, \
                not this agent loop, owns execution."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "cron": {"type": "string", "description": "Cron expression to preserve."},
                    "prompt": {"type": "string", "description": "Prompt associated with the job."},
                    "recurring": {"type": "boolean", "default": false},
                    "durable": {"type": "boolean", "default": false}
                },
                "required": ["cron", "prompt"],
                "additionalProperties": false
            }),
        }
    }

    fn claude_cron_delete_schema() -> ToolSchema {
        ToolSchema {
            name: CLAUDE_CRON_DELETE.to_string(),
            description: "Delete a Claude-compatible cron job from the imported manifest. \
                This updates state only; an embedding scheduler owns execution."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {"id": {"type": "string"}},
                "required": ["id"],
                "additionalProperties": false
            }),
        }
    }

    fn claude_cron_list_schema() -> ToolSchema {
        ToolSchema {
            name: CLAUDE_CRON_LIST.to_string(),
            description: "List imported Claude cron jobs and their explicit ACTIVE or PAUSED \
                manifest posture. This agent loop itself does not run a scheduler."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {},
                "additionalProperties": false
            }),
        }
    }

    fn claude_schedule_wakeup_schema() -> ToolSchema {
        ToolSchema {
            name: CLAUDE_SCHEDULE_WAKEUP.to_string(),
            description: "Replace the one-shot wakeup stored in the imported Claude manifest. \
                The wakeup inherits the manifest's ACTIVE or PAUSED posture; an embedding scheduler \
                owns timer execution."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "delaySeconds": {"type": "integer", "minimum": 0},
                    "reason": {"type": "string"},
                    "prompt": {"type": "string"}
                },
                "required": ["delaySeconds"],
                "additionalProperties": false
            }),
        }
    }

    /// The `background_exec` schema (P5-6, §2 module 4, D1 "background
    /// exec").
    fn background_exec_schema() -> ToolSchema {
        ToolSchema {
            name: BACKGROUND_EXEC.to_string(),
            description: "Run a shell command in the BACKGROUND: spawns it as a detached \
                process and returns a `job_id` IMMEDIATELY, before the command finishes — this \
                call never returns the command's output. Poll `background_status` with the \
                `job_id` to check progress and retrieve captured output; use `background_kill` \
                to cancel it early. The command goes through the exact same sandbox/permission \
                checks as a foreground `bash` call, and any check that would need an \
                interactive approval is denied automatically (a background job cannot wait for \
                one)."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "command": {
                        "type": "string",
                        "description": "Shell command to run in the background via `sh -c`."
                    }
                },
                "required": ["command"],
                "additionalProperties": false
            }),
        }
    }

    /// The `background_status` schema (P5-6, D1 "monitor/event feed").
    fn background_status_schema() -> ToolSchema {
        ToolSchema {
            name: BACKGROUND_STATUS.to_string(),
            description: "Check on a background job spawned via background_exec: its \
                running/exited/killed status, exit code (once known), and the command's \
                captured stdout/stderr so far (bounded — very large output is truncated with a \
                marker). Once the job has exited or been killed, this call also reaps it (it \
                will no longer appear in background_list or accept further status polls)."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "job_id": {
                        "type": "string",
                        "description": "The id `background_exec` returned when this job was \
                            started."
                    }
                },
                "required": ["job_id"],
                "additionalProperties": false
            }),
        }
    }

    /// The `background_list` schema (P5-6, D10 "bg-manager").
    fn background_list_schema() -> ToolSchema {
        ToolSchema {
            name: BACKGROUND_LIST.to_string(),
            description: "List every background job currently tracked (running, or finished \
                but not yet polled via background_status) — job id, command, status, pid, and \
                start time for each. Does not retrieve output or reap anything."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {},
                "additionalProperties": false
            }),
        }
    }

    /// The `background_kill` schema (P5-6, D10 "bg-manager").
    fn background_kill_schema() -> ToolSchema {
        ToolSchema {
            name: BACKGROUND_KILL.to_string(),
            description: "Kill a background job's real process immediately (a no-op, not an \
                error, if it already exited on its own) and reap it."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "job_id": {
                        "type": "string",
                        "description": "The id `background_exec` returned when this job was \
                            started."
                    }
                },
                "required": ["job_id"],
                "additionalProperties": false
            }),
        }
    }

    /// The `spawn_subagent` schema (P5-3, §2 module 9 D1 "spawn tool").
    /// Lists every configured `agent_type` name so the model knows what's
    /// available, but `agent_type` stays optional — an ad-hoc spawn with an
    /// inline `system_prompt` is always allowed too.
    fn spawn_subagent_schema(&self) -> ToolSchema {
        let mut names: Vec<&str> = self
            .config
            .subagents_definitions
            .keys()
            .map(String::as_str)
            .collect();
        names.sort_unstable();
        let agent_type_desc = if names.is_empty() {
            "Optional named subagent type to run (none configured — omit this and pass \
             `system_prompt` instead)."
                .to_string()
        } else {
            format!(
                "Optional named subagent type to run: {}. Omit to run an ad-hoc subagent with \
                 your own `system_prompt` instead.",
                names.join(", ")
            )
        };
        let background_desc = if self.config.subagents_background {
            "Run this subagent in the background instead of waiting for it — this call \
             returns immediately with a `subagent_id`; poll `subagent_status` with that id for \
             the result."
        } else {
            "Background subagents are disabled for this agent — this must be omitted or false."
        };
        ToolSchema {
            name: SPAWN_SUBAGENT.to_string(),
            description: "Spawn a subagent to work on a self-contained task and (by default) \
                wait for its final answer, which is returned as this call's result. The \
                subagent runs its own independent reasoning/tool loop; it does not see your \
                conversation except for the `task` text you give it here."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "task": {
                        "type": "string",
                        "description": "The self-contained task/prompt for the subagent."
                    },
                    "agent_type": {
                        "type": "string",
                        "description": agent_type_desc
                    },
                    "system_prompt": {
                        "type": "string",
                        "description": "Inline system prompt for an ad-hoc subagent (ignored \
                            if `agent_type` is given — the named type's own prompt is used \
                            instead)."
                    },
                    "background": {
                        "type": "boolean",
                        "description": background_desc
                    }
                },
                "required": ["task"],
                "additionalProperties": false
            }),
        }
    }

    /// Claude Code-compatible alias for [`Self::spawn_subagent_schema`].
    fn claude_agent_schema(&self) -> ToolSchema {
        let mut names: Vec<String> = self.config.subagents_definitions.keys().cloned().collect();
        names.push("general-purpose".into());
        names.sort_unstable();
        names.dedup();
        ToolSchema {
            name: CLAUDE_AGENT.to_string(),
            description: "Claude Code-compatible subagent dispatcher. Runs a named or ad-hoc \
                child agent; children default to background execution in this compatibility mode."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "prompt": {"type": "string", "description": "Self-contained child task."},
                    "subagent_type": {
                        "type": "string",
                        "description": format!("Named agent type. Available: {}", names.join(", "))
                    },
                    "description": {
                        "type": "string",
                        "description": "Short human-facing task label; preserved as descriptive input."
                    },
                    "model": {
                        "type": "string",
                        "description": "Optional model alias or full provider slug for this child."
                    },
                    "run_in_background": {
                        "type": "boolean",
                        "description": "Whether to return immediately with a child id (default true)."
                    }
                },
                "required": ["prompt"],
                "additionalProperties": false
            }),
        }
    }

    /// Translate Claude's `Agent` arguments to the native subagent intrinsic.
    fn translate_claude_agent_call(
        &self,
        call: &crate::message::ToolCall,
    ) -> Result<crate::message::ToolCall> {
        let args = call
            .function
            .parsed_arguments()
            .map_err(|error| Error::InvalidArguments {
                tool: CLAUDE_AGENT.to_string(),
                message: error.to_string(),
            })?;
        let object = args.as_object().ok_or_else(|| Error::InvalidArguments {
            tool: CLAUDE_AGENT.to_string(),
            message: "arguments must be an object".to_string(),
        })?;
        let mut translated = serde_json::Map::new();
        if let Some(value) = object.get("prompt") {
            translated.insert("task".to_string(), value.clone());
        }
        if let Some(value) = object.get("subagent_type") {
            // `general-purpose` is a built-in Claude agent, not a project
            // definition file. Supercode's equivalent is an ad-hoc child
            // using the inherited default system prompt, represented by an
            // omitted `agent_type`.
            if value.as_str() != Some("general-purpose") {
                translated.insert("agent_type".to_string(), value.clone());
            }
        }
        if let Some(value) = object.get("model") {
            translated.insert("model".to_string(), value.clone());
        }
        translated.insert(
            "background".to_string(),
            object
                .get("run_in_background")
                .cloned()
                .unwrap_or(serde_json::Value::Bool(true)),
        );
        Ok(crate::message::ToolCall {
            id: call.id.clone(),
            kind: call.kind.clone(),
            function: crate::message::FunctionCall {
                name: SPAWN_SUBAGENT.to_string(),
                arguments: serde_json::Value::Object(translated).to_string(),
            },
        })
    }

    /// Execute Claude's scheduling vocabulary against the imported manifest.
    ///
    /// This is intentionally a state editor, not a scheduler: it owns no
    /// timer/task handle, nothing downstream of it fires, and every
    /// successful response says so, so the model is never told a job it just
    /// created will run here.
    fn run_claude_runtime_tool(&mut self, call: &crate::message::ToolCall) -> (String, bool) {
        let args = match call.function.parsed_arguments() {
            Ok(value) if value.is_object() => value,
            Ok(_) => {
                return (
                    format!("Error: {} arguments must be an object", call.function.name),
                    true,
                )
            }
            Err(error) => return (format!("Error: {error}"), true),
        };
        let object = args.as_object().expect("checked object above");

        let Some(manifest) = self.claude_runtime_manifest.as_mut() else {
            return (
                "Error: Claude runtime compatibility was enabled without an imported runtime \
                 manifest; refusing to invent scheduler state"
                    .to_string(),
                true,
            );
        };
        // Every imported schedule is carried and inert. `state` is the single
        // fact the model is told about it, in the manifest's own vocabulary.
        let state = "paused";

        match call.function.name.as_str() {
            CLAUDE_CRON_LIST => {
                let jobs: Vec<serde_json::Value> = manifest
                    .active_crons
                    .iter()
                    .map(|job| {
                        serde_json::json!({
                            "id": job.id,
                            "cron": job.schedule,
                            "prompt": job.prompt,
                            "recurring": job.recurring,
                            "durable": job.durable_requested,
                            "state": state
                        })
                    })
                    .collect();
                let notice = "Imported jobs are preserved but no scheduler is running.";
                (
                    serde_json::json!({
                        "execution_state": state,
                        "execution_notice": notice,
                        "jobs": jobs
                    })
                    .to_string(),
                    false,
                )
            }
            CLAUDE_CRON_CREATE => {
                let Some(schedule) = object.get("cron").and_then(serde_json::Value::as_str) else {
                    return ("Error: CronCreate requires string `cron`".to_string(), true);
                };
                let Some(prompt) = object.get("prompt").and_then(serde_json::Value::as_str) else {
                    return (
                        "Error: CronCreate requires string `prompt`".to_string(),
                        true,
                    );
                };
                let recurring = object
                    .get("recurring")
                    .and_then(serde_json::Value::as_bool)
                    .unwrap_or(false);
                let durable_requested = object
                    .get("durable")
                    .and_then(serde_json::Value::as_bool)
                    .unwrap_or(false);
                let mut sequence = 1_u64;
                let id = loop {
                    let candidate = format!("sc{sequence:06}");
                    if !manifest.active_crons.iter().any(|job| job.id == candidate) {
                        break candidate;
                    }
                    sequence += 1;
                };
                let kind = if recurring { "recurring " } else { "" };
                let result = format!(
                    "Scheduled {kind}job {id} ({schedule}) in PAUSED state. The job is preserved \
                     in the continuation manifest but no scheduler is running and it will not execute."
                );
                manifest
                    .active_crons
                    .push(crate::claude_runtime_state::ClaudeCronJob {
                        id: id.clone(),
                        tool_use_id: call.id.clone(),
                        schedule: schedule.to_string(),
                        recurring,
                        durable_requested,
                        prompt: prompt.to_string(),
                        // The creation instant is a fact about this
                        // continuation, recorded like every other manifest
                        // field. Nothing consults it as a due time.
                        created_at: Some(crate::sidecar::ms_to_rfc3339(now_ms())),
                        expires_after_seconds: None,
                        creation_result: result.clone(),
                    });
                manifest
                    .active_crons
                    .sort_by(|left, right| left.id.cmp(&right.id));
                (result, false)
            }
            CLAUDE_CRON_DELETE => {
                let Some(id) = object.get("id").and_then(serde_json::Value::as_str) else {
                    return ("Error: CronDelete requires string `id`".to_string(), true);
                };
                let Some(index) = manifest.active_crons.iter().position(|job| job.id == id) else {
                    return (
                        format!("Error: unknown {state} Claude cron job `{id}`"),
                        true,
                    );
                };
                manifest.active_crons.remove(index);
                (
                    format!("Cancelled job {id}. The job was PAUSED; no execution occurred."),
                    false,
                )
            }
            CLAUDE_SCHEDULE_WAKEUP => {
                let Some(delay_seconds) = object
                    .get("delaySeconds")
                    .and_then(serde_json::Value::as_u64)
                else {
                    return (
                        "Error: ScheduleWakeup requires integer `delaySeconds`".to_string(),
                        true,
                    );
                };
                let reason = object
                    .get("reason")
                    .and_then(serde_json::Value::as_str)
                    .map(str::to_string);
                let prompt = object
                    .get("prompt")
                    .and_then(serde_json::Value::as_str)
                    .map(str::to_string);
                let now = now_ms();
                let created_at = Some(crate::sidecar::ms_to_rfc3339(now));
                // The instant the wakeup asks for, recorded as the request
                // made it. No timer consults it here.
                let delay_ms = i64::try_from(delay_seconds)
                    .unwrap_or(i64::MAX)
                    .saturating_mul(1_000);
                let scheduled_for = crate::sidecar::ms_to_rfc3339(now.saturating_add(delay_ms));
                let result = format!(
                    "Next wakeup recorded for {scheduled_for} (in {delay_seconds}s) in PAUSED \
                     state. The request replaced the prior wakeup in the manifest, but no timer \
                     is running and it will not execute."
                );
                manifest.pending_wakeups.clear();
                manifest
                    .pending_wakeups
                    .push(crate::claude_runtime_state::ClaudeWakeup {
                        tool_use_id: call.id.clone(),
                        delay_seconds,
                        reason,
                        prompt,
                        created_at,
                        scheduled_for: Some(scheduled_for),
                        creation_result: result.clone(),
                    });
                (result, false)
            }
            _ => unreachable!("runtime tool dispatch is name-gated"),
        }
    }

    /// The `subagent_status` schema (P5-3, D3 "background+resume").
    fn subagent_status_schema() -> ToolSchema {
        ToolSchema {
            name: SUBAGENT_STATUS.to_string(),
            description: "Check on (and, once finished, retrieve the result of) a background \
                subagent spawned via spawn_subagent with background=true. Pass the \
                `subagent_id` that spawn returned."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "subagent_id": {
                        "type": "string",
                        "description": "The id `spawn_subagent` returned when this subagent \
                            was spawned."
                    }
                },
                "required": ["subagent_id"],
                "additionalProperties": false
            }),
        }
    }

    /// BP-7: the `subagent_message` schema.
    fn subagent_message_schema() -> ToolSchema {
        ToolSchema {
            name: SUBAGENT_MESSAGE.to_string(),
            description: "Send a message to a background subagent that is STILL RUNNING.                 The message is delivered to that subagent at the start of its next step,                 without interrupting the step it is on. Use `subagent_status` to check                 whether it is still running and to collect its result."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "subagent_id": {
                        "type": "string",
                        "description": "The id `spawn_subagent` returned."
                    },
                    "message": {
                        "type": "string",
                        "description": "What to tell the running subagent."
                    }
                },
                "required": ["subagent_id", "message"],
                "additionalProperties": false
            }),
        }
    }

    /// BP-7: the `subagent_resume` schema.
    fn subagent_resume_schema() -> ToolSchema {
        ToolSchema {
            name: SUBAGENT_RESUME.to_string(),
            description: "Continue a subagent that has already FINISHED, with its own                 previous conversation restored, so it keeps everything it learned instead                 of being briefed again from scratch. Pass the id it was spawned with and                 the next task."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "subagent_id": {
                        "type": "string",
                        "description": "The id of a subagent that has already finished."
                    },
                    "task": {
                        "type": "string",
                        "description": "What the resumed subagent should do next."
                    }
                },
                "required": ["subagent_id", "task"],
                "additionalProperties": false
            }),
        }
    }

    /// BP-7 (catalog §4a "Background subagents + resume"): deliver a
    /// message into a still-running background child's mailbox.
    ///
    /// The mailbox is the child's own `SteerInbox` — the seam P4b built for
    /// mid-turn steering, which is writable while the child's turn holds
    /// `&mut Agent`. So delivery ordering is already defined: the message
    /// arrives at the top of the child's next loop iteration, i.e. after
    /// whatever tool calls it is currently running, per its
    /// `steering_mode`. A child that has already FINISHED is refused with
    /// a pointer at `subagent_resume`, which is the operation for that
    /// case — never silently dropped.
    fn run_subagent_message(&mut self, call: &crate::message::ToolCall) -> (String, bool) {
        let args = match call.function.parsed_arguments() {
            Ok(v) => v,
            Err(e) => {
                let err = Error::InvalidArguments {
                    tool: SUBAGENT_MESSAGE.to_string(),
                    message: e.to_string(),
                };
                return (format!("Error: {err}"), true);
            }
        };
        let Some(id) = args.get("subagent_id").and_then(serde_json::Value::as_str) else {
            let err = Error::InvalidArguments {
                tool: SUBAGENT_MESSAGE.to_string(),
                message: "`subagent_id` is required".to_string(),
            };
            return (format!("Error: {err}"), true);
        };
        let message = args
            .get("message")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("");
        if message.is_empty() {
            let err = Error::InvalidArguments {
                tool: SUBAGENT_MESSAGE.to_string(),
                message: "`message` is required and must be non-empty".to_string(),
            };
            return (format!("Error: {err}"), true);
        }
        let Some(entry) = self.background_subagents.get(id) else {
            let err = Error::SubagentNotFound(id.to_string());
            return (format!("Error: {err}"), true);
        };
        if entry.handle.is_finished() {
            let out = serde_json::json!({
                "subagent_id": id,
                "status": "finished",
                "delivered": false,
                "hint": "this subagent already finished — collect it with subagent_status,                          then continue it with subagent_resume",
            });
            return (out.to_string(), false);
        }
        entry
            .mailbox
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .queue_unchecked(message.to_string());
        let out = serde_json::json!({
            "subagent_id": id,
            "status": "running",
            "delivered": true,
        });
        (out.to_string(), false)
    }

    /// BP-7 (catalog §4a "Background subagents + resume": "resumable with
    /// context intact"): continue a finished child over its OWN transcript.
    ///
    /// The context comes from the reap (kept in-process) or, for a session
    /// that attached a subagent store, from that child's persisted
    /// `<parent>.subagents/<id>.sidecar.jsonl`. Either way the resumed
    /// child is rebuilt through `build_child_config` from the SAME named
    /// definition it was spawned with, so its permission posture on resume
    /// is the one it had originally — never a fresh, looser default.
    async fn run_subagent_resume(&mut self, call: &crate::message::ToolCall) -> (String, bool) {
        let args = match call.function.parsed_arguments() {
            Ok(v) => v,
            Err(e) => {
                let err = Error::InvalidArguments {
                    tool: SUBAGENT_RESUME.to_string(),
                    message: e.to_string(),
                };
                return (format!("Error: {err}"), true);
            }
        };
        let Some(id) = args
            .get("subagent_id")
            .and_then(serde_json::Value::as_str)
            .map(String::from)
        else {
            let err = Error::InvalidArguments {
                tool: SUBAGENT_RESUME.to_string(),
                message: "`subagent_id` is required".to_string(),
            };
            return (format!("Error: {err}"), true);
        };
        let task = args
            .get("task")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("")
            .to_string();
        if task.is_empty() {
            let err = Error::InvalidArguments {
                tool: SUBAGENT_RESUME.to_string(),
                message: "`task` is required and must be non-empty".to_string(),
            };
            return (format!("Error: {err}"), true);
        }
        if self
            .background_subagents
            .get(&id)
            .is_some_and(|e| !e.handle.is_finished())
        {
            let err = Error::tool(
                SUBAGENT_RESUME,
                format!(
                    "subagent `{id}` is still running — send it a message with                      subagent_message, or collect it with subagent_status first"
                ),
            );
            return (format!("Error: {err}"), true);
        }
        let lineage = self
            .subagent_store
            .as_ref()
            .and_then(|(store, parent)| store.load_subagent_lineage(parent, &id).ok().flatten());
        let Some(prior) = self.prior_subagent_transcript(&id) else {
            let err = Error::SubagentNotFound(id.clone());
            return (format!("Error: {err}"), true);
        };

        let agent_type = lineage.as_ref().and_then(|l| l.agent_type.clone());
        let definition = agent_type
            .as_ref()
            .and_then(|name| self.config.subagents_definitions.get(name).cloned());
        let Some(guard) = crate::subagents::try_acquire(
            &self.subagent_concurrency_gauge,
            self.config.subagents_max_concurrent,
        ) else {
            let err = Error::SubagentConcurrencyExceeded {
                max_concurrent: self.config.subagents_max_concurrent,
            };
            return (format!("Error: {err}"), true);
        };
        let child_config = self.build_child_config(
            definition.as_ref(),
            None,
            lineage
                .as_ref()
                .map(|l| l.model.clone())
                .or_else(|| definition.as_ref().and_then(|d| d.model.clone())),
        );
        let mut child = Agent::with_provider_arc(child_config, self.provider.clone());
        child.subagent_depth = self.subagent_depth + 1;
        child.subagent_concurrency_gauge = self.subagent_concurrency_gauge.clone();
        // Context intact: the child's own prior messages, appended after
        // its (re-derived, identical) system prompt.
        child.history.extend(prior);

        let result = child.send(task).await;
        let transcript = child.history()[1..].to_vec();
        if let Some(lineage) = &lineage {
            self.persist_subagent_transcript(&id, lineage, &transcript);
        }
        self.reaped_subagents.insert(id.clone(), transcript);
        drop(guard);
        match result {
            Ok(text) => {
                let out = serde_json::json!({
                    "subagent_id": id,
                    "status": "done",
                    "resumed": true,
                    "result": text,
                });
                (out.to_string(), false)
            }
            Err(e) => {
                let out = serde_json::json!({
                    "subagent_id": id,
                    "status": "error",
                    "resumed": true,
                    "message": e.to_string(),
                });
                (out.to_string(), true)
            }
        }
    }

    /// BP-7 (catalog §4a "Named agent definitions as data"): the child
    /// `Config` a `spawn_subagent` of `agent_type` would build — the
    /// resolved posture a named definition actually produces, including
    /// its [`crate::subagents::AgentPermissions`] bundle applied through
    /// the tightening-only rules. `None` when no definition of that name
    /// is registered or discovered.
    ///
    /// Exposed so a caller (and this build's tests) can ask what a named
    /// agent WOULD run as without spawning it and paying for a turn.
    pub fn child_config_for_agent_type(&self, agent_type: &str) -> Option<Config> {
        let definition = self.config.subagents_definitions.get(agent_type)?.clone();
        Some(self.build_child_config(Some(&definition), None, definition.model.clone()))
    }

    /// BP-7 (catalog §4a "Background subagents + resume"): the ids of
    /// children that have finished and been reaped, and can therefore be
    /// continued with [`SUBAGENT_RESUME`].
    pub fn reaped_subagent_ids(&self) -> Vec<String> {
        let mut ids: Vec<String> = self.reaped_subagents.keys().cloned().collect();
        ids.sort();
        ids
    }

    /// BP-7: a finished child's own messages — from the in-process reap
    /// cache first, then this session's subagent store.
    fn prior_subagent_transcript(&self, id: &str) -> Option<Vec<ChatMessage>> {
        if let Some(messages) = self.reaped_subagents.get(id) {
            return Some(messages.clone());
        }
        let (store, parent) = self.subagent_store.as_ref()?;
        let jsonl = store.load_subagent_transcript(parent, id).ok()??;
        let session = crate::session::Session::from_sidecar_str(&jsonl).ok()?;
        Some(
            session
                .messages
                .into_iter()
                .filter(|m| m.role != crate::message::Role::System)
                .collect(),
        )
    }

    /// Build the CHILD `Config` a `spawn_subagent` call constructs its
    /// [`Agent`] from. The whole point of this method (§5.3-style
    /// "monotonic posture", build-brief "a subagent inherits or narrows —
    /// never widens — the parent's permission posture"): every field that
    /// governs what the child is ALLOWED to do (sandbox, approval,
    /// tool_overrides, deny/allow patterns, protected paths, the subagents
    /// caps themselves) is copied VERBATIM from `self.config` — never
    /// loosened — and the only NARROWING lever is `definition.tools`
    /// (intersected with whatever the parent already had enabled, never
    /// unioned in anything new).
    ///
    /// P5-3 safety hardening (Fable-5 review, LOW-MEDIUM "child safety-limit
    /// inheritance"): the monotonic-posture guarantee above was, before this
    /// fix, scoped to PERMISSION fields only — a child could still silently
    /// get a LOOSER safety BUDGET/BREAKER than its parent, because
    /// `max_total_output_tokens`/`max_tool_output_bytes`/`max_tokens`/
    /// `doom_loop_threshold`/`edit_file_require_read_before_edit` were never
    /// copied and so fell back to `Config::default()`'s (looser/uncapped)
    /// values on every spawn regardless of what the parent had configured.
    /// These are now copied verbatim alongside the permission-posture
    /// fields — a parent that capped its own output/tool-output/doom-loop
    /// exposure, or required read-before-edit, gets a child that is bound
    /// by the exact same ceiling, never a wider one.
    ///
    /// **Full field-by-field accounting** (every [`Config`] field, so this
    /// doc comment stays the single place that answers "did we forget
    /// one?"): fields already copied above/below this note (permission
    /// posture: `sandbox`/`approval`/`tool_overrides`/`auto_approved_tools`/
    /// `tool_deny_patterns`/`tool_allow_patterns`/`permissions_enabled`/
    /// `permissions_ask_patterns`/`permissions_protected_paths`/
    /// `network_policy`/`core_tools_enabled`/`module_registry`/
    /// `module_activation`/every `subagents_*` field; safety limits:
    /// `max_iterations`/`max_total_output_tokens`/`max_tool_output_bytes`/
    /// `max_tokens`/`doom_loop_threshold`/`edit_file_require_read_before_edit`;
    /// identity/transport: `model`/`system_prompt`/`cwd`/`base_url`/
    /// `api_key`/`api_key_env`/`api_key_cmd`) are the ones that gate
    /// harm/spend/hazard exposure. Every OTHER field is deliberately left at
    /// `Config::default()` because none of them is a safety ceiling the
    /// child could "loosen" by missing it:
    /// - `temperature`/`effort`/`response_format`/`extra_body`/`extra_headers`/
    ///   `tool_advertising`/`tool_schema_tier`/`cache_plan`/`cache_warnings`/
    ///   `reduction_policy`/
    ///   `session_*`/`small_model`/`model_fallback`/`env_context`/
    ///   `project_root_markers`/`project_doc_max_bytes`/`instruction_imports`/
    ///   `retry_*`/`compaction_*`/`auto_title`/`steering_mode`/
    ///   `follow_up_mode`/`read_file_multimodal`/`edit_file_notebook_aware`/
    ///   `shell_env_snapshot`/`nested_instructions`/`model_switch_allow_switch`/
    ///   `context_injections`/`context_injection_blocks`/`parallel_tool_calls`
    ///   are behavior/cost-shaping or presentation knobs, not hard guards —
    ///   a child defaulting on any of these can do LESS (e.g. no multimodal
    ///   read, no notebook-aware edits, no proactive compaction) or the same,
    ///   never something the parent hadn't already exposed it to. Several
    ///   default to their OFF/conservative state (`false`/`None`), which is
    ///   the tight direction, not the loose one.
    /// - `additional_dirs`: governs which extra roots are reachable at all
    ///   (`presets.rs`'s `[core] additional_dirs` note) — a child that
    ///   doesn't inherit it has FEWER reachable roots than its parent, i.e.
    ///   strictly tighter, never looser.
    /// - `load_project_context`: whether instruction files are auto-loaded
    ///   into the system prompt — a read-time convenience, not an access
    ///   grant (`sandbox`/`permissions_protected_paths` already gate actual
    ///   file access).
    /// - `prompts`: named `/slash` command templates for THIS agent's own
    ///   user-facing input surface, not something the model can invoke
    ///   against the child's tool surface.
    /// - `stop_gate`/`post_tool_hook`/`approval_handler`/`event_sink`:
    ///   code-only `Box<dyn Fn>` callbacks (see the `pre_tool_hook` note
    ///   immediately below — same non-`Clone` shape) that are observational
    ///   or terminate-only, not a call-time veto over what a tool is allowed
    ///   to do; `approval_handler` specifically is ALREADY documented at
    ///   this method's call site (`Self::run_spawn_subagent`) as
    ///   intentionally never set here — a foreground child gets no handler
    ///   by design, an embedder installs its own after spawn if it wants
    ///   one.
    ///
    /// **`pre_tool_hook` cannot propagate, and this is deliberate + named,
    /// not a silent gap**: `Config::pre_tool_hook` is a `Box<dyn Fn(&str,
    /// &serde_json::Value) -> Option<String> + Send + Sync>` — an
    /// embedder's own call-time veto over every tool call. `Box<dyn Fn>` is
    /// not `Clone` (there is no generic way to duplicate an opaque closure),
    /// so it genuinely CANNOT be copied into a child `Config` the way every
    /// `Clone`-able field above is — there is no fix that makes this one
    /// "verbatim copy" like the others. An embedder relying on a
    /// `pre_tool_hook` veto reaching spawned children as well as the parent
    /// MUST re-install one on the child explicitly (e.g. via a
    /// `spawn_subagent`-adjacent hook of their own, or by not relying on
    /// `pre_tool_hook` alone for anything safety-critical across a spawn
    /// boundary) — named here so this is a documented contract, not a gap
    /// an embedder discovers by a child silently misbehaving.
    fn build_child_config(
        &self,
        definition: Option<&crate::subagents::NamedAgentDefinition>,
        inline_system_prompt: Option<String>,
        model_override: Option<String>,
    ) -> Config {
        let system_prompt = definition
            .map(|d| d.system_prompt.clone())
            .filter(|s| !s.is_empty())
            .or(inline_system_prompt)
            .unwrap_or_else(|| self.config.system_prompt.clone());
        let model = model_override.unwrap_or_else(|| self.config.model.clone());

        let mut child = Config::builder()
            .model(model)
            .system_prompt(system_prompt)
            .cwd(self.config.cwd.clone())
            // Monotonic: verbatim, never loosened.
            .sandbox(self.config.sandbox)
            .approval(self.config.approval)
            .max_iterations(self.config.max_iterations)
            .build();
        child.base_url = self.config.base_url.clone();
        child.api_key = self.config.api_key.clone();
        child.api_key_env = self.config.api_key_env.clone();
        child.api_key_cmd = self.config.api_key_cmd.clone();
        // P5-3 safety hardening (Fable-5 review, LOW-MEDIUM "child
        // safety-limit inheritance"): the monotonic-posture spirit extends
        // to safety BUDGETS/BREAKERS, not just permissions — a child must
        // not get a looser cap/breaker than its parent by simply falling
        // back to `Config::default()`'s (looser) values. See this method's
        // doc comment for the full field-by-field accounting.
        child.max_total_output_tokens = self.config.max_total_output_tokens;
        child.max_tool_output_bytes = self.config.max_tool_output_bytes;
        child.max_tokens = self.config.max_tokens;
        child.doom_loop_threshold = self.config.doom_loop_threshold;
        child.edit_file_require_read_before_edit = self.config.edit_file_require_read_before_edit;
        // Monotonic tool posture: start from the PARENT's own overrides
        // (so anything the parent already disabled stays disabled), then
        // narrow further if a named definition restricts the tool set.
        child.tool_overrides = self.config.tool_overrides.clone();
        child.auto_approved_tools = self.config.auto_approved_tools.clone();
        child.tool_deny_patterns = self.config.tool_deny_patterns.clone();
        child.tool_allow_patterns = self.config.tool_allow_patterns.clone();
        child.permissions_enabled = self.config.permissions_enabled;
        child.permissions_ask_patterns = self.config.permissions_ask_patterns.clone();
        child.permissions_protected_paths = self.config.permissions_protected_paths.clone();
        child.network_policy = self.config.network_policy.clone();
        // P5-10 (§2 module 12): same monotonic-posture treatment as
        // `sandbox`/`approval` above — a subagent must inherit its
        // parent's OS-sandbox posture verbatim, never a looser
        // `Config::default()` fallback (`sandbox_os_enabled: None`,
        // `escalation: Deny`, `env_policy: Inherit` would otherwise be
        // right back to "confine only when the tier itself says so" for a
        // child whose parent explicitly forced the backstop on/off).
        child.sandbox_os_enabled = self.config.sandbox_os_enabled;
        child.sandbox_escalation = self.config.sandbox_escalation;
        child.sandbox_env_policy = self.config.sandbox_env_policy;
        if let Some(def) = definition {
            if let Some(allowed) = &def.tools {
                for name in &self.config.core_tools_enabled {
                    if !allowed.iter().any(|t| t == name) {
                        child
                            .tool_overrides
                            .entry(name.clone())
                            .or_default()
                            .enabled = Some(false);
                    }
                }
            }
            // BP-7 (catalog §4a "Named agent definitions as data": the
            // `permissions` component of `prompt+model+tools+permissions`).
            // Every arm below can only TIGHTEN — the two policy values go
            // through the SAME strictness ranks `configfile::
            // clamp_project_permissions` uses for the untrusted project
            // layer (a looser value is ignored, never honored), the
            // auto-approve list is INTERSECTED with the parent's, and the
            // deny list is a union. A definition may come from a
            // `.claude/agents/*.md` file in the repo, so it sits at the
            // project trust tier and must never be an escalation door.
            if let Some(perms) = &def.permissions {
                if let Some(approval) = perms.approval {
                    if crate::configfile::approval_rank(approval)
                        < crate::configfile::approval_rank(child.approval)
                    {
                        child.approval = approval;
                    }
                }
                if let Some(sandbox) = perms.sandbox {
                    if crate::configfile::sandbox_rank(sandbox)
                        < crate::configfile::sandbox_rank(child.sandbox)
                    {
                        child.sandbox = sandbox;
                    }
                }
                if let Some(allowed) = &perms.auto_approved_tools {
                    child
                        .auto_approved_tools
                        .retain(|tool| allowed.iter().any(|a| a == tool));
                }
                for pattern in &perms.deny {
                    if !child.tool_deny_patterns.iter().any(|p| p == pattern) {
                        child.tool_deny_patterns.push(pattern.clone());
                    }
                }
            }
        }
        child.core_tools_enabled = self.config.core_tools_enabled.clone();
        child.module_registry = self.config.module_registry;
        child.module_activation = self.config.module_activation.clone();
        // The subagents module itself never widens either: a child spawned
        // at depth d+1 inherits the SAME caps (never a looser depth/
        // concurrency/background posture than its own parent).
        child.subagents_enabled = self.config.subagents_enabled;
        child.subagents_max_depth = self.config.subagents_max_depth;
        child.subagents_max_concurrent = self.config.subagents_max_concurrent;
        child.subagents_background = self.config.subagents_background;
        child.subagents_background_prompts = self.config.subagents_background_prompts;
        child.subagents_claude_agent_alias = self.config.subagents_claude_agent_alias;
        child.subagents_definitions = self.config.subagents_definitions.clone();
        child.subagent_depth = self.subagent_depth + 1;
        child
    }

    /// Execute the `spawn_subagent` intrinsic (P5-3, §2 module 9). See
    /// `Self::build_child_config` for the monotonic-posture guarantee and
    /// `crate::subagents` for the depth/concurrency resource bounds and the
    /// §2.2 C6 background-policy enforcement.
    async fn run_spawn_subagent(&mut self, call: &crate::message::ToolCall) -> (String, bool) {
        // BP-11: `subagent_start`/`subagent_stop` bracket a call that passed
        // the same validation the runner applies (subagents on, non-empty
        // task); a refused call fires neither.
        let task = if self.config.subagents_enabled {
            call.function
                .parsed_arguments()
                .ok()
                .and_then(|v| {
                    v.get("task")
                        .and_then(serde_json::Value::as_str)
                        .map(str::to_string)
                })
                .filter(|t| !t.is_empty())
        } else {
            None
        };
        if let Some(task) = &task {
            self.fire_lifecycle(&crate::config::LifecycleEvent::SubagentStart {
                task: task.clone(),
            });
        }
        let (output, is_error) = self.run_spawn_subagent_inner(call).await;
        if let Some(task) = task {
            self.fire_lifecycle(&crate::config::LifecycleEvent::SubagentStop {
                task,
                is_error,
                output_len: output.len(),
            });
        }
        (output, is_error)
    }

    /// Hands a lifecycle moment to the installed observer, if any (BP-11).
    fn fire_lifecycle(&self, event: &crate::config::LifecycleEvent) {
        if let Some(hook) = self.config.lifecycle_hook.as_ref() {
            hook(event);
        }
    }

    /// Installs the lifecycle observer (compaction and subagent boundaries).
    pub fn set_lifecycle_hook(&mut self, hook: crate::config::LifecycleHook) {
        self.config.lifecycle_hook = Some(hook);
    }

    async fn run_spawn_subagent_inner(
        &mut self,
        call: &crate::message::ToolCall,
    ) -> (String, bool) {
        if !self.config.subagents_enabled {
            let err = Error::UnknownTool(SPAWN_SUBAGENT.to_string());
            return (format!("Error: {err}"), true);
        }
        let args = match call.function.parsed_arguments() {
            Ok(v) => v,
            Err(e) => {
                let err = Error::InvalidArguments {
                    tool: SPAWN_SUBAGENT.to_string(),
                    message: e.to_string(),
                };
                return (format!("Error: {err}"), true);
            }
        };
        let task = args
            .get("task")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("")
            .to_string();
        if task.is_empty() {
            let err = Error::InvalidArguments {
                tool: SPAWN_SUBAGENT.to_string(),
                message: "`task` is required and must be non-empty".to_string(),
            };
            return (format!("Error: {err}"), true);
        }
        let agent_type = args
            .get("agent_type")
            .and_then(serde_json::Value::as_str)
            .map(String::from);
        let inline_system_prompt = args
            .get("system_prompt")
            .and_then(serde_json::Value::as_str)
            .map(String::from);
        let background = args
            .get("background")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false);
        let requested_model = args
            .get("model")
            .and_then(serde_json::Value::as_str)
            .map(|model| crate::model_catalog::resolve_alias(model));

        let definition = match &agent_type {
            Some(name) => match self.config.subagents_definitions.get(name) {
                Some(d) => Some(d.clone()),
                None => {
                    let err = Error::SubagentDefinitionNotFound(name.clone());
                    return (format!("Error: {err}"), true);
                }
            },
            None => None,
        };

        if background {
            if !self.config.subagents_background {
                let err = Error::tool(
                    SPAWN_SUBAGENT,
                    "background=true requires capabilities.subagents.background = true",
                );
                return (format!("Error: {err}"), true);
            }
            // §2.2 C6, defensive re-check (belt-and-suspenders — see
            // `Error::SubagentBackgroundPolicyMissing`'s doc comment for why
            // this can't just trust the resolver already checked it).
            if self.config.subagents_background_prompts.is_none() {
                let err = Error::SubagentBackgroundPolicyMissing;
                return (format!("Error: {err}"), true);
            }
        }

        // Resource bounds (fail-closed): depth first (cheap, no side
        // effect on failure), THEN concurrency (holds a slot — must be the
        // LAST check before actually spawning, so a refused spawn never
        // leaves a stray slot held).
        if let Err(e) =
            crate::subagents::check_depth(self.subagent_depth, self.config.subagents_max_depth)
        {
            return (format!("Error: {e}"), true);
        }
        let Some(guard) = crate::subagents::try_acquire(
            &self.subagent_concurrency_gauge,
            self.config.subagents_max_concurrent,
        ) else {
            let err = Error::SubagentConcurrencyExceeded {
                max_concurrent: self.config.subagents_max_concurrent,
            };
            return (format!("Error: {err}"), true);
        };

        let child_id = next_subagent_id();
        let child_config = self.build_child_config(
            definition.as_ref(),
            inline_system_prompt,
            requested_model.or_else(|| definition.as_ref().and_then(|d| d.model.clone())),
        );
        let child_model = child_config.model.clone();
        let mut child = Agent::with_provider_arc(child_config, self.provider.clone());
        child.subagent_depth = self.subagent_depth + 1;
        child.subagent_concurrency_gauge = self.subagent_concurrency_gauge.clone();

        // §2.2 C6: a background child NEVER gets a BLOCKING-BY-DEFAULT
        // interactive approval handler — either no handler at all
        // (`AutoPolicy`: the engine's pre-existing "no handler ⇒ deny"
        // fail-closed default), or (`Parent`) the never-blocking
        // `ParentQueueApprovalHandler`, UNLESS a `tui` embedder has
        // installed [`Self::child_approval_handler_factory`] (P5-4), in
        // which case THAT builds the handler instead — see
        // [`Self::set_child_approval_handler_factory`]'s doc comment for
        // why this can't escalate past what the rule engine already routed
        // to `Ask`. A foreground child also gets no handler here (today's
        // existing default posture; an embedder that wants an interactive
        // child installs its own via `set_permissions_approval_handler`
        // after this call returns, out of this method's scope).
        if background {
            if let Some(crate::subagents::BackgroundPromptsPolicy::Parent) =
                self.config.subagents_background_prompts
            {
                let handler: std::sync::Arc<dyn crate::permissions::PermissionsApprovalHandler> =
                    match &self.child_approval_handler_factory {
                        Some(factory) => {
                            factory(child_id.clone(), self.pending_child_approvals.clone())
                        }
                        None => std::sync::Arc::new(crate::subagents::ParentQueueApprovalHandler {
                            child_agent_id: child_id.clone(),
                            queue: self.pending_child_approvals.clone(),
                        }),
                    };
                child.ctx.sandbox_approval_handler =
                    Some(crate::sandbox::SandboxApprovalHandler(handler.clone()));
                child.permissions_approval_handler = Some(handler);
            }
        }

        let lineage = crate::subagents::SubagentLineage {
            child_agent_id: child_id.clone(),
            parent_session_id: self.subagent_store.as_ref().map(|(_, name)| name.clone()),
            parent_tool_use_id: call.id.clone(),
            depth: self.subagent_depth + 1,
            agent_type: agent_type.clone(),
            task: task.clone(),
            background,
            spawned_at_ms: now_ms(),
            model: child_model,
        };
        if let Some((store, parent_name)) = &self.subagent_store {
            let _ = store.save_subagent_lineage(parent_name, &child_id, &lineage);
        }

        if background {
            let spawned_task_text = task.clone();
            // BP-7: captured BEFORE `child` moves into the task — this is
            // the handle `subagent_message` writes into.
            let mailbox = child.steer_queue_handle();
            self.background_subagents.insert(
                child_id.clone(),
                BackgroundSubagent {
                    handle: tokio::spawn(async move {
                        // The concurrency slot lives for exactly as long as
                        // this future runs — moved in here, dropped when the
                        // child's `send` (and this future) finishes.
                        let _guard = guard;
                        let result = child.send(spawned_task_text).await;
                        let transcript = child.history()[1..].to_vec();
                        (child_id, result, transcript)
                    }),
                    task,
                    agent_type,
                    started_at_ms: lineage.spawned_at_ms,
                    mailbox,
                },
            );
            let out = serde_json::json!({
                "subagent_id": lineage.child_agent_id,
                "status": "spawned",
                "background": true,
            });
            return (out.to_string(), false);
        }

        // Foreground: run to completion now, guard held until this
        // function returns (then drops, freeing the slot).
        let result = child.send(task).await;
        let transcript = child.history()[1..].to_vec();
        self.persist_subagent_transcript(&child_id, &lineage, &transcript);
        // BP-7: kept in-process so `subagent_resume` can restore this
        // child's context even with no session store attached.
        self.reaped_subagents
            .insert(child_id.clone(), transcript.clone());
        drop(guard);
        match result {
            Ok(text) => (text, false),
            Err(e) => (format!("Error: subagent `{child_id}` failed: {e}"), true),
        }
    }

    /// Execute the `subagent_status` intrinsic (P5-3, D3
    /// "background+resume"): poll a background child; once its `JoinHandle`
    /// is finished, reap it (removing it from `Self::background_subagents`
    /// and persisting its transcript, same as the foreground path).
    async fn run_subagent_status(&mut self, call: &crate::message::ToolCall) -> (String, bool) {
        let args = match call.function.parsed_arguments() {
            Ok(v) => v,
            Err(e) => {
                let err = Error::InvalidArguments {
                    tool: SUBAGENT_STATUS.to_string(),
                    message: e.to_string(),
                };
                return (format!("Error: {err}"), true);
            }
        };
        let Some(id) = args.get("subagent_id").and_then(serde_json::Value::as_str) else {
            let err = Error::InvalidArguments {
                tool: SUBAGENT_STATUS.to_string(),
                message: "`subagent_id` is required".to_string(),
            };
            return (format!("Error: {err}"), true);
        };
        let Some(entry) = self.background_subagents.get(id) else {
            let err = Error::SubagentNotFound(id.to_string());
            return (format!("Error: {err}"), true);
        };
        if !entry.handle.is_finished() {
            let out = serde_json::json!({
                "subagent_id": id,
                "status": "pending",
                "task": entry.task,
                "agent_type": entry.agent_type,
                "started_at_ms": entry.started_at_ms,
            });
            return (out.to_string(), false);
        }
        // Finished — reap it. `.await` on an already-finished handle
        // resolves immediately (never actually blocks).
        let entry = self
            .background_subagents
            .remove(id)
            .expect("checked Some above");
        let (child_id, result, transcript) = match entry.handle.await {
            Ok(v) => v,
            Err(join_err) => {
                let err = Error::tool(
                    SUBAGENT_STATUS,
                    format!("subagent `{id}` task panicked: {join_err}"),
                );
                return (format!("Error: {err}"), true);
            }
        };
        // Re-derive the lineage record for persistence (cheap; the fields
        // are all still in hand) — mirrors the foreground path's single
        // `persist_subagent_transcript` call site.
        if let Some((store, parent_name)) = self.subagent_store.clone() {
            if let Ok(Some(lineage)) = store.load_subagent_lineage(&parent_name, &child_id) {
                self.persist_subagent_transcript(&child_id, &lineage, &transcript);
            }
        }
        // BP-7: see the foreground path's identical line.
        self.reaped_subagents
            .insert(child_id.clone(), transcript.clone());
        match result {
            Ok(text) => {
                let out = serde_json::json!({
                    "subagent_id": child_id,
                    "status": "done",
                    "result": text,
                });
                (out.to_string(), false)
            }
            Err(e) => {
                let out = serde_json::json!({
                    "subagent_id": child_id,
                    "status": "error",
                    "message": e.to_string(),
                });
                (out.to_string(), true)
            }
        }
    }

    /// Execute the `background_exec` intrinsic (P5-6, §2 module 4, D1
    /// "background exec"): spawn `args.command` as a detached OS process
    /// via `crate::tools::build_sandboxed_sh` — the SAME sandboxed-spawn
    /// path [`crate::tools::BashTool::execute`] uses — and return its job
    /// id IMMEDIATELY, never the command's output. Gated by the same
    /// permission check a foreground `bash` call gets
    /// ([`Self::background_permission_denial`]), then a fail-closed
    /// concurrency cap ([`Config::tools_background_max_concurrent`]), THEN
    /// the actual spawn — in that order, so a refused call never holds a
    /// concurrency slot and never touches the process table.
    fn run_background_exec(&mut self, call: &crate::message::ToolCall) -> (String, bool) {
        let args = match call.function.parsed_arguments() {
            Ok(v) => v,
            Err(e) => {
                let err = Error::InvalidArguments {
                    tool: BACKGROUND_EXEC.to_string(),
                    message: e.to_string(),
                };
                return (format!("Error: {err}"), true);
            }
        };
        let command = args
            .get("command")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("")
            .to_string();
        if command.is_empty() {
            let err = Error::InvalidArguments {
                tool: BACKGROUND_EXEC.to_string(),
                message: "`command` is required and must be non-empty".to_string(),
            };
            return (format!("Error: {err}"), true);
        }

        // A job id up front (before spawning) — used both as the audit
        // handle for a §2.2 C6 `Parent`-policy queued denial (this call may
        // never actually reach the spawn below) and, if the call proceeds,
        // as `Self::background_jobs`'s real key.
        let job_id = crate::background::next_job_id(now_ms());

        // Fable-5 review (LOW, "pre_tool_hook + doom-loop don't cover
        // background_exec"): this intrinsic is intercepted in
        // `Self::prepare_tool_call` and returns before `Self::finish_prepare`
        // ever runs, so — unlike a foreground `bash` call — it was reaching
        // this real spawn below WITHOUT ever offering `Config.pre_tool_hook`
        // a chance to veto it. `background_exec` runs a REAL command (unlike
        // the purely in-process meta-intrinsics `tool_search`/
        // `expand_reduction`/`sidecar_search`, which have no such gap to
        // close), so it belongs behind the same security-relevant veto a
        // foreground call gets. Scoped to this one call site — the other
        // meta-intrinsics are unchanged. The doom-loop counter
        // (`Self::check_doom_loop`) is deliberately NOT wired here: it is a
        // foreground repetition breaker keyed on `(self.doom_loop_last_call,
        // self.doom_loop_streak)`, a single piece of state shared with the
        // ordinary tool-call loop — folding background jobs into that same
        // streak would make an interleaved foreground/background pattern
        // trip (or fail to trip) the breaker in ways that have nothing to
        // do with the foreground loop actually repeating itself; the
        // pre_tool_hook veto below is the security-relevant half of this
        // fix, the doom-loop breaker is not.
        // BP-10: the hook now runs BEFORE this path's permissions gate, the
        // same order the foreground path uses — so a rewrite is what the
        // rules evaluate and what actually runs, and the hook's
        // `Allow`/`Ask` are tiers inside the engine rather than a second
        // verdict beside it.
        let mut command = command;
        let mut hook_decision = crate::config::HookDecision::Pass;
        if let Some(hook) = &self.config.pre_tool_hook {
            let outcome = hook(BACKGROUND_EXEC, &args);
            if outcome.decision == crate::config::HookDecision::Deny {
                let reason = outcome.reason.unwrap_or_else(|| "denied".to_string());
                return (format!("Error: blocked by pre-tool hook: {reason}"), true);
            }
            if let Some(rewritten) = outcome.updated_args {
                command = rewritten
                    .get("command")
                    .and_then(|v| v.as_str())
                    .unwrap_or(&command)
                    .to_string();
            }
            hook_decision = outcome.decision;
        }

        if let Some(reason) = self.background_permission_denial(&command, &job_id, hook_decision) {
            return (format!("Error: {reason}"), true);
        }

        let Some(guard) = crate::subagents::try_acquire(
            &self.background_concurrency_gauge,
            self.config.tools_background_max_concurrent,
        ) else {
            let err = Error::BackgroundJobConcurrencyExceeded {
                max_concurrent: self.config.tools_background_max_concurrent,
            };
            return (format!("Error: {err}"), true);
        };

        let mut cmd = match crate::tools::build_sandboxed_sh(&command, &self.ctx) {
            Ok(cmd) => cmd,
            Err(e) => return (format!("Error: {e}"), true),
        };
        cmd.current_dir(&self.ctx.cwd)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            // Defense-in-depth for the "must be killed on drop" guarantee —
            // see `impl Drop for Agent`'s doc comment; the EXPLICIT
            // `start_kill()` loop there is what makes the guarantee
            // provable, this is a second, independent line of defense for
            // the same outcome.
            .kill_on_drop(true);
        // Fable-5 review (HIGH, "grandchildren orphaned on kill AND
        // agent-drop"): `Child::start_kill` only signals the DIRECT child.
        // A background command that spawns a surviving subprocess (a `&`
        // job, a pipeline, a double-forking daemon — or, on macOS, the
        // `sandbox-exec` wrapper itself in `build_sandboxed_sh`, whose real
        // `sh` and ITS children are all grandchildren of the tracked pid)
        // leaves those processes running, reparented to init, after the
        // tracked job is "killed". Putting this job in its OWN new process
        // group (`pgid == its own pid`, since every descendant inherits the
        // group unless it explicitly opts out) lets `kill_job_process_group`
        // below signal the WHOLE tree at kill/drop time, not just the one
        // pid we happen to be tracking. No portable equivalent on Windows —
        // see `kill_job_process_group`'s `#[cfg(not(unix))]` fallback.
        #[cfg(unix)]
        cmd.process_group(0);
        // P4c (`core.shell_env_snapshot`)/P5-10 (`env_policy`):
        // `build_sandboxed_sh` (above) already applied both via its own
        // `apply_sandbox_env_policy` last step — no separate `ctx.shell_env`
        // application here (that would re-add a secret `Filtered`/`None`
        // just stripped, on top of the already-`env_clear`'d command).

        let mut child = match cmd.spawn() {
            Ok(c) => c,
            Err(e) => {
                drop(guard);
                let err = Error::tool(
                    BACKGROUND_EXEC,
                    format!("failed to spawn background command: {e}"),
                );
                return (format!("Error: {err}"), true);
            }
        };
        let pid = child.id();
        let output = std::sync::Arc::new(crate::background::CapturedOutput::new());
        let cap = self.config.tools_background_max_output_bytes;
        // Fire-and-forget: the reader tasks outlive this method call and
        // exit on their own at pipe EOF — see `spawn_output_reader`'s doc
        // comment. Bound to named (not `_`) locals only to keep clippy's
        // `let_underscore_future` lint quiet; neither handle is awaited or
        // aborted anywhere.
        if let Some(stdout) = child.stdout.take() {
            let _stdout_reader = spawn_output_reader(stdout, output.clone(), cap);
        }
        if let Some(stderr) = child.stderr.take() {
            let _stderr_reader = spawn_output_reader(stderr, output.clone(), cap);
        }

        let started_at_ms = now_ms();
        self.background_jobs.insert(
            job_id.clone(),
            BackgroundJob {
                child,
                command: command.clone(),
                pid,
                output,
                started_at_ms,
                killed: false,
                _guard: guard,
            },
        );

        let out = serde_json::json!({
            "job_id": job_id,
            "status": "running",
            "pid": pid,
            "command": command,
        });
        (out.to_string(), false)
    }

    /// Execute the `background_status` intrinsic (P5-6, D1 "monitor/event
    /// feed"): non-blocking poll of one job's run status (via
    /// `Child::try_wait`), drain its output captured since the LAST poll
    /// and emit it as an [`AgentEvent::BackgroundOutput`] event (the
    /// "event feed" — a real `EventSink` consumer sees each poll's new
    /// output live), and return the full captured output (bounded, per
    /// [`Config::tools_background_max_output_bytes`]) so far either way.
    /// Once the job is terminal (exited or killed), this reaps it — removes
    /// it from [`Self::background_jobs`], freeing its concurrency slot —
    /// same "poll once more to reap" contract [`Self::run_subagent_status`]
    /// already established for background subagents.
    fn run_background_status(&mut self, call: &crate::message::ToolCall) -> (String, bool) {
        let args = match call.function.parsed_arguments() {
            Ok(v) => v,
            Err(e) => {
                let err = Error::InvalidArguments {
                    tool: BACKGROUND_STATUS.to_string(),
                    message: e.to_string(),
                };
                return (format!("Error: {err}"), true);
            }
        };
        let Some(job_id) = args.get("job_id").and_then(serde_json::Value::as_str) else {
            let err = Error::InvalidArguments {
                tool: BACKGROUND_STATUS.to_string(),
                message: "`job_id` is required".to_string(),
            };
            return (format!("Error: {err}"), true);
        };
        let job_id = job_id.to_string();

        // Scoped so the mutable borrow of `self.background_jobs` ends
        // before `self.emit(...)`/`self.background_jobs.remove(...)` below
        // need their own (mutable) access to `self`.
        let (command, pid, started_at_ms, status, output_so_far, truncated, delta) = {
            let Some(job) = self.background_jobs.get_mut(&job_id) else {
                let err = Error::BackgroundJobNotFound(job_id);
                return (format!("Error: {err}"), true);
            };
            let status = background_job_status(job);
            let (output_so_far, truncated) = job.output.snapshot();
            let delta = job.output.drain_new();
            (
                job.command.clone(),
                job.pid,
                job.started_at_ms,
                status,
                output_so_far,
                truncated,
                delta,
            )
        };

        if !delta.is_empty() {
            self.emit(AgentEvent::BackgroundOutput {
                job_id: job_id.clone(),
                chunk: delta,
                truncated,
            });
        }

        let exit_code = match status {
            crate::background::JobStatus::Exited(code) => code,
            _ => None,
        };
        let out = serde_json::json!({
            "job_id": job_id,
            "command": command,
            "status": status.as_str(),
            "exit_code": exit_code,
            "pid": pid,
            "started_at_ms": started_at_ms,
            "output": output_so_far,
            "output_truncated": truncated,
        });
        if !matches!(status, crate::background::JobStatus::Running) {
            self.background_jobs.remove(&job_id);
        }
        (out.to_string(), false)
    }

    /// Execute the `background_list` intrinsic (P5-6, D10 "bg-manager"):
    /// list every background job this agent is currently tracking, without
    /// draining output or reaping anything (a read-only listing —
    /// `background_status` is the reaping poll).
    fn run_background_list(&mut self, _call: &crate::message::ToolCall) -> (String, bool) {
        let mut jobs = Vec::new();
        for (job_id, job) in self.background_jobs.iter_mut() {
            let status = background_job_status(job);
            jobs.push(serde_json::json!({
                "job_id": job_id,
                "command": job.command,
                "status": status.as_str(),
                "pid": job.pid,
                "started_at_ms": job.started_at_ms,
            }));
        }
        let out = serde_json::json!({ "jobs": jobs });
        (out.to_string(), false)
    }

    /// Execute the `background_kill` intrinsic (P5-6, D10 "bg-manager",
    /// build brief "kill/cancel a job"): request REAL termination of a
    /// background job's OS process AND its whole process group (see
    /// [`kill_job_process_group`] — Fable-5 review, HIGH, "grandchildren
    /// orphaned on kill"; a documented no-op if the process already
    /// exited) and reap it immediately, freeing its concurrency slot.
    fn run_background_kill(&mut self, call: &crate::message::ToolCall) -> (String, bool) {
        let args = match call.function.parsed_arguments() {
            Ok(v) => v,
            Err(e) => {
                let err = Error::InvalidArguments {
                    tool: BACKGROUND_KILL.to_string(),
                    message: e.to_string(),
                };
                return (format!("Error: {err}"), true);
            }
        };
        let Some(job_id) = args.get("job_id").and_then(serde_json::Value::as_str) else {
            let err = Error::InvalidArguments {
                tool: BACKGROUND_KILL.to_string(),
                message: "`job_id` is required".to_string(),
            };
            return (format!("Error: {err}"), true);
        };
        let job_id = job_id.to_string();
        let Some(mut job) = self.background_jobs.remove(&job_id) else {
            let err = Error::BackgroundJobNotFound(job_id);
            return (format!("Error: {err}"), true);
        };
        kill_job_process_group(&mut job);
        job.killed = true;
        let out = serde_json::json!({
            "job_id": job_id,
            "status": "killed",
            "pid": job.pid,
        });
        // `job` (and its `ConcurrencyGuard`) drops here, freeing the slot.
        (out.to_string(), false)
    }

    /// P5-3 (D5 "subagent transcripts… persisted + linked"): write a
    /// finished child's transcript to `Self::subagent_store`, if one is
    /// installed — a no-op otherwise (see that field's doc comment). Builds
    /// the child's `Session` the same way `to_native_jsonl_v2`'s doc
    /// comment describes (an empty imported prefix + `transcript` as
    /// `appended` `NativeTurn`s), with `meta.agent_id`/`parent_tool_use_id`/
    /// `lineage` populated from `lineage` so the native-v2 header carries
    /// the full lineage record on disk (see `Session::to_native_jsonl_v2`'s
    /// P5-3 doc note).
    ///
    /// P5-3 safety-hardening fix (Fable-5 review, LOW "translation-fidelity
    /// cosmetic"): `Session::from_claude_code_str("")` is used ONLY to get
    /// a blank `raw`/`messages` skeleton cheaply (an empty string parses
    /// identically under any loader) — it is NOT claiming this child's
    /// session actually came from Claude Code. Before this fix, that
    /// borrowed constructor's `meta.source` (`SessionSource::ClaudeCode`)
    /// leaked straight through to the persisted sidecar's `source` header,
    /// mislabeling a native `spawn_subagent` child as an imported CC
    /// session. Corrected to `SessionSource::Native` immediately after —
    /// see that variant's doc comment.
    fn persist_subagent_transcript(
        &self,
        child_id: &str,
        lineage: &crate::subagents::SubagentLineage,
        transcript: &[ChatMessage],
    ) {
        let Some((store, parent_name)) = &self.subagent_store else {
            return;
        };
        let mut session = match Session::from_claude_code_str("") {
            Ok(s) => s,
            Err(_) => return,
        };
        session.meta.source = crate::session::SessionSource::Native;
        session.meta.agent_id = Some(lineage.child_agent_id.clone());
        session.meta.parent_tool_use_id = Some(lineage.parent_tool_use_id.clone());
        session.meta.lineage = lineage.to_lineage_map();
        let sidecar_jsonl = session.to_native_jsonl_v2(transcript);
        let _ = store.save_subagent_transcript(parent_name, child_id, &sidecar_jsonl);
        let _ = store.save_subagent_lineage(parent_name, child_id, lineage);
    }

    /// Execute the `tool_search` intrinsic (B6): case-insensitive keyword
    /// match over `name` + `description` of every registered, enabled,
    /// non-core, not-yet-activated tool (builtin and `mcp__*` alike). Matches
    /// are activated (advertised starting with the next request) and
    /// returned as a JSON array of their full [`ToolSchema`]s.
    fn run_tool_search(&mut self, call: &crate::message::ToolCall) -> (String, bool) {
        let args = match call.function.parsed_arguments() {
            Ok(v) => v,
            Err(e) => {
                let err = Error::InvalidArguments {
                    tool: TOOL_SEARCH.to_string(),
                    message: e.to_string(),
                };
                return (format!("Error: {err}"), true);
            }
        };
        let query = args
            .get("query")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("")
            .to_lowercase();
        let max_results = args
            .get("max_results")
            .and_then(serde_json::Value::as_u64)
            .map(|n| n as usize);

        let mut matches: Vec<ToolSchema> = self
            .registry
            .iter()
            .filter(|t| self.config.tool_enabled(t.name()))
            .filter(|t| !self.is_core_tool(t.name()))
            .filter(|t| !self.activated_tools.contains(t.name()))
            .filter(|t| {
                query.is_empty()
                    || t.name().to_lowercase().contains(&query)
                    || self
                        .config
                        .tool_description(t.name(), t.description())
                        .to_lowercase()
                        .contains(&query)
            })
            // TR-8/T5 dev/03: the on-demand fetch always returns the ORIGINAL
            // full schema, never the tier-minified one — that's the invert.
            .map(|t| self.raw_schema_for(t))
            .collect();

        if let Some(max) = max_results {
            matches.truncate(max);
        }

        for m in &matches {
            self.activated_tools.insert(m.name.clone());
        }

        let result = serde_json::to_string(&matches).unwrap_or_else(|_| "[]".to_string());
        (result, false)
    }

    /// The `expand_reduction` schema (T12/TR-1), advertised whenever a
    /// [`ReductionPolicy`] is installed.
    ///
    /// The description deliberately never spells the literal stub sentinel
    /// prefix: A11's export leak guard is unconditional, so an assistant
    /// turn that quoted a stub line verbatim (which teaching the syntax
    /// invites) would permanently fail export for that session. Stubs are
    /// described abstractly and the model is told to pass ids only.
    fn expand_reduction_schema() -> ToolSchema {
        ToolSchema {
            name: EXPAND_REDUCTION.to_string(),
            description: "Fetch back the original content hidden behind a reduction stub in \
                your current view — a truncated tool output, cleared old turns, or an elided \
                file read that was hidden to save context. Each stub line names a reduction id \
                like r0042-9f3c: pass ONLY that id here, and never quote or repeat a stub line \
                itself in your replies. The original is durably kept in the session sidecar. \
                Pass `byte_range` to fetch a slice of a large one at a time instead of all of \
                it at once; ranged results are prefixed with a `bytes start..end of total` \
                header so you can plan the next slice."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "reduction_id": {
                        "type": "string",
                        "description": "The reduction id named in the stub line, e.g. \
                            \"r0042-9f3c\". Pass the id alone."
                    },
                    "byte_range": {
                        "type": "array",
                        "items": {"type": "integer"},
                        "minItems": 2,
                        "maxItems": 2,
                        "description": "Optional [start, end) byte offsets within the original \
                            content to fetch instead of all of it. Exactly two non-negative \
                            integers with start <= end."
                    }
                },
                "required": ["reduction_id"],
                "additionalProperties": false
            }),
        }
    }

    /// The `sidecar_search` schema (T12/TR-1), advertised whenever a
    /// [`ReductionPolicy`] is installed. Same no-literal-sentinel rule as
    /// [`Self::expand_reduction_schema`].
    fn sidecar_search_schema() -> ToolSchema {
        ToolSchema {
            name: SIDECAR_SEARCH.to_string(),
            description: "Search content currently hidden from your view by reduction stubs \
                (large tool outputs, cleared old turns, elided file reads) for a substring or \
                regex. Only hidden content is searched, never what you can already see. \
                Returns match snippets with each match's reduction_id for use with \
                expand_reduction; refer to results by their reduction id rather than quoting \
                stub lines. Results are capped — if `truncated` is true, narrow the query."
                .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Non-empty substring or regex to search for \
                            (case-insensitive)."
                    }
                },
                "required": ["query"],
                "additionalProperties": false
            }),
        }
    }

    /// Reload the recorder's full recorded messages from disk (TR-1's
    /// `recorded` resolution source). Since TR-12's D6/A7 supersession gate
    /// (`Self::run_loop`), a `expand_reduction`/`sidecar_search` call only
    /// ever exists alongside an active [`ReductionPolicy`] (see
    /// [`EXPAND_REDUCTION`]'s doc), and pairing one with a recorder — as the
    /// CLI's reduced mode always does — means the gate is already on and
    /// `history[1..]` holds the same full bytes as this reload: this upgrade
    /// is then a dormant no-op (`reduce::rehydrate::prefer_recorded` sees
    /// `recorded == minted` and keeps `minted`). It stops being a no-op —
    /// defense in depth, not the common path — for a **legacy** sidecar
    /// recorded before this gate existed, or for a policy-without-recorder
    /// agent (gate off, so `history[1..]` still carries
    /// [`Self::cap_tool_output`]-capped copies): only there can `history[1..]`
    /// diverge from the sidecar, and only there does consulting this reload
    /// actually recover bytes `history[1..]` alone couldn't. `Ok(None)` when
    /// no recorder is attached (rehydration then resolves from history alone,
    /// whose capped copies — if any — carry their own honest cap notice). A
    /// disk-level reload is fine here regardless: these intrinsic calls are
    /// rare, model-initiated events, not per-request work.
    fn recorded_messages(&self) -> std::result::Result<Option<Vec<ChatMessage>>, String> {
        let Some(recorder) = &self.recorder else {
            return Ok(None);
        };
        let raw = std::fs::read_to_string(recorder.path())
            .map_err(|e| format!("failed to read the session sidecar: {e}"))?;
        let session = Session::from_sidecar_str(&raw)
            .map_err(|e| format!("failed to parse the session sidecar: {e}"))?;
        Ok(Some(session.messages))
    }

    /// Execute the `expand_reduction` intrinsic (T12/TR-1): resolves against
    /// `self.reduction_log` + `self.history[1..]` (the hash-minting source),
    /// upgraded to the recorder's full recorded bytes for cap-diverged
    /// content ([`Self::recorded_messages`]; the two-source contract is
    /// documented on `reduce::rehydrate`). `byte_range` is validated
    /// strictly — any malformed shape is a model-recoverable error naming
    /// the expected form and the original's true size, never a silent
    /// whole-content (or empty) return.
    fn run_expand_reduction(&mut self, call: &crate::message::ToolCall) -> (String, bool) {
        let args = match call.function.parsed_arguments() {
            Ok(v) => v,
            Err(e) => {
                let err = Error::InvalidArguments {
                    tool: EXPAND_REDUCTION.to_string(),
                    message: e.to_string(),
                };
                return (format!("Error: {err}"), true);
            }
        };
        let Some(id) = args.get("reduction_id").and_then(serde_json::Value::as_str) else {
            return (
                "Error: expand_reduction requires a `reduction_id` string argument".to_string(),
                true,
            );
        };
        let recorded = match self.recorded_messages() {
            Ok(r) => r,
            Err(e) => return (format!("Error: expand_reduction: {e}"), true),
        };
        let recorded = recorded.as_deref();

        // B3: strict shape validation — exactly two non-negative integers.
        // Anything else errors (with the true total when resolvable) rather
        // than silently degrading to a whole-content expand.
        let byte_range = match args.get("byte_range") {
            None | Some(serde_json::Value::Null) => None,
            Some(v) => {
                let parsed = v
                    .as_array()
                    .filter(|a| a.len() == 2)
                    .and_then(|a| Some((a[0].as_u64()? as usize, a[1].as_u64()? as usize)));
                match parsed {
                    Some(range) => Some(range),
                    None => {
                        let total = reduce::rehydrate::reduction_total_bytes(
                            &self.reduction_log,
                            &self.history[1..],
                            recorded,
                            id,
                        )
                        .map(|n| format!("; the original is {n} bytes"))
                        .unwrap_or_default();
                        return (
                            format!(
                                "Error: expand_reduction: malformed byte_range {v} — expected \
                                 [start, end): exactly two non-negative integers with \
                                 start <= end{total}"
                            ),
                            true,
                        );
                    }
                }
            }
        };
        match reduce::rehydrate::expand_reduction(
            &self.reduction_log,
            &self.history[1..],
            recorded,
            id,
            byte_range,
        ) {
            // A ranged result carries a provenance header naming the slice
            // and the true total, so the model can plan its next slice; a
            // whole-content expand stays byte-exact (TR-1 dev/01).
            Ok(outcome) => match outcome.range {
                Some((start, end)) => (
                    format!(
                        "[{id}: bytes {start}..{end} of {total}]\n{content}",
                        total = outcome.total_bytes,
                        content = outcome.content
                    ),
                    false,
                ),
                None => (outcome.content, false),
            },
            Err(e) => (format!("Error: {e}"), true),
        }
    }

    /// Execute the `sidecar_search` intrinsic (T12/TR-1); same two-source
    /// resolution as [`Self::run_expand_reduction`]. The result is bounded
    /// by construction (`reduce::rehydrate::SidecarSearchResult`'s caps), so
    /// a broad query can never re-inflate the context or bloat the sidecar
    /// the recorder appends this result to.
    fn run_sidecar_search(&mut self, call: &crate::message::ToolCall) -> (String, bool) {
        let args = match call.function.parsed_arguments() {
            Ok(v) => v,
            Err(e) => {
                let err = Error::InvalidArguments {
                    tool: SIDECAR_SEARCH.to_string(),
                    message: e.to_string(),
                };
                return (format!("Error: {err}"), true);
            }
        };
        let query = args
            .get("query")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("");
        if query.trim().is_empty() {
            return (
                "Error: sidecar_search requires a non-empty `query` string argument".to_string(),
                true,
            );
        }
        let recorded = match self.recorded_messages() {
            Ok(r) => r,
            Err(e) => return (format!("Error: sidecar_search: {e}"), true),
        };
        match reduce::rehydrate::sidecar_search(
            &self.reduction_log,
            &self.history[1..],
            recorded.as_deref(),
            query,
        ) {
            Ok(result) => (
                serde_json::to_string(&result).unwrap_or_else(|_| "{}".to_string()),
                false,
            ),
            Err(e) => (format!("Error: {e}"), true),
        }
    }

    fn emit(&self, event: AgentEvent) {
        if let Some(sink) = &self.config.event_sink {
            sink(event);
        }
    }

    /// Number of non-system messages exchanged so far.
    pub fn turn_count(&self) -> usize {
        self.history
            .iter()
            .filter(|m| m.role != Role::System)
            .count()
    }

    /// Cumulative output (completion) tokens reported by the provider across
    /// every `send` on this agent. Zero if the provider reports no usage.
    pub fn total_output_tokens(&self) -> u64 {
        self.total_output_tokens
    }
}

#[cfg(test)]
mod bp2_spill_tests {
    //! BP-2 (`.volter/tracker/markdown/BP-2.md`, catalog:58): under the
    //! parity presets a capped tool output stays RECOVERABLE by the model —
    //! without `capabilities.reduction`, which both presets leave off.

    use super::*;
    use crate::configfile::{resolve, ResolveOptions};

    /// Never called — these tests drive `cap_tool_output` directly.
    #[derive(Debug)]
    struct NeverCalledProvider;

    #[async_trait::async_trait]
    impl Provider for NeverCalledProvider {
        async fn complete(
            &self,
            _req: &ChatRequest,
            _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
        ) -> crate::Result<(ChatMessage, crate::provider::Usage)> {
            unreachable!("BP-2 spill tests never issue a request")
        }
    }

    fn resolved(preset: &str) -> crate::configfile::Resolved {
        let toml = crate::presets::lookup(preset).unwrap();
        resolve(toml, None, &ResolveOptions { strict: true })
            .unwrap_or_else(|e| panic!("{preset} resolves: {e}"))
    }

    /// The residue this closes: the cap notice said the full output was
    /// "not retained" / "in session sidecar" and the only door to it —
    /// `expand_reduction` — is advertised solely when a `ReductionPolicy`
    /// is installed, which `capabilities.reduction = false` never does. So
    /// under both parity presets a truncated output was simply lost.
    ///
    /// Now the notice NAMES a spill file, and the door is the preset's own
    /// read pathway: `read_file` under cc-parity, the shell under
    /// cx-parity (which registers no file tools at all).
    #[tokio::test]
    async fn parity_presets_spill_capped_output_and_name_a_door_the_preset_has() {
        for (preset, expected_door) in [
            ("cc-parity", "read it with `read_file`"),
            ("cx-parity", "read it with `cat`"),
        ] {
            let r = resolved(preset);
            assert!(
                r.config.tool_output_spill,
                "{preset} must set `core.tool_output_spill`"
            );
            assert_eq!(
                r.modules.get("reduction"),
                Some(&false),
                "{preset} leaves `capabilities.reduction` off — the spill must not depend on it"
            );
            let mut config = resolved(preset).config;
            config.max_tool_output_bytes = Some(1024);
            let registry = crate::tools::ToolRegistry::from_config(&config);
            let agent = Agent::with_parts(config, Box::new(NeverCalledProvider), registry);
            assert!(
                agent.reduction_policy.is_none(),
                "no reduction policy is installed under {preset}"
            );

            let full = "R".repeat(50_000);
            let capped = agent.cap_tool_output(full.clone());
            assert!(capped.len() < full.len(), "{preset}: output must be capped");
            assert!(capped.contains(expected_door), "{preset}: {capped:?}");

            // The path in the notice must actually hold the full bytes.
            let marker = capped.split("spilled to ").nth(1).unwrap_or_default();
            let path = marker.split("").next().unwrap_or_default();
            assert!(!path.is_empty(), "{preset}: no spill path in {capped:?}");
            assert_eq!(
                std::fs::read_to_string(path).unwrap(),
                full,
                "{preset}: the spill file must hold the FULL output"
            );

            // And the model can actually walk through that door: the
            // preset's own read pathway returns the spilled content.
            let ctx = build_tool_context(agent.config()).0;
            let recovered = match registry_read_tool(&agent) {
                Some(("read_file", tool)) => tool
                    .execute(serde_json::json!({"path": path}), &ctx)
                    .await
                    .unwrap(),
                Some(("bash", tool)) => tool
                    .execute(serde_json::json!({"command": format!("cat {path}")}), &ctx)
                    .await
                    .unwrap(),
                _ => panic!("{preset}: no read door registered"),
            };
            assert!(
                recovered.contains(&"R".repeat(2000)),
                "{preset}: the door must return the spilled output"
            );
            let _ = std::fs::remove_file(path);
        }
    }

    /// The preset's read pathway: `read_file` where it exists, else the
    /// shell — the same choice the cap notice's wording makes.
    fn registry_read_tool<'a>(
        agent: &'a Agent,
    ) -> Option<(&'static str, &'a dyn crate::tools::Tool)> {
        if let Some(tool) = agent.registry.get("read_file") {
            return Some(("read_file", tool));
        }
        agent.registry.get("bash").map(|tool| ("bash", tool))
    }

    /// Off (the default, every non-parity preset and every SDK embedder):
    /// no spill file, and the notice is byte-identical to before BP-2.
    #[test]
    fn spill_off_leaves_the_notice_unchanged_and_writes_nothing() {
        let config = Config::builder().max_tool_output_bytes(1024).build();
        assert!(!config.tool_output_spill);
        let agent = Agent::with_provider(config, Box::new(NeverCalledProvider));
        let capped = agent.cap_tool_output("S".repeat(50_000));
        assert!(capped.contains("full output not retained"), "{capped:?}");
        assert!(!capped.contains("spilled to"), "{capped:?}");
    }
}

#[cfg(test)]
mod bp3_new_core_tool_tests {
    //! BP-3 (`.volter/tracker/markdown/BP-3.md`): the two behaviours the
    //! new tools can only have INSIDE the agent — plan mode narrowing the
    //! permissions engine, and `new_context` re-founding the request view
    //! through `reduce`'s handoff projection — driven over the RESOLVED
    //! parity presets.

    use super::*;
    use crate::configfile::{resolve, ResolveOptions};

    #[derive(Debug)]
    struct NeverCalledProvider;

    #[async_trait::async_trait]
    impl Provider for NeverCalledProvider {
        async fn complete(
            &self,
            _req: &ChatRequest,
            _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
        ) -> crate::Result<(ChatMessage, crate::provider::Usage)> {
            unreachable!("BP-3 tests never issue a request")
        }
    }

    fn resolved(preset: &str) -> Config {
        let toml = crate::presets::lookup(preset).unwrap();
        resolve(toml, None, &ResolveOptions { strict: true })
            .unwrap_or_else(|e| panic!("{preset} resolves: {e}"))
            .config
    }

    fn agent_for(preset: &str) -> Agent {
        Agent::with_provider(resolved(preset), Box::new(NeverCalledProvider))
    }

    /// An approval door that says yes to everything — so a denial in these
    /// tests can only come from the DENY tier, never from cc-parity's
    /// `approval = "untrusted"` ask default.
    struct AlwaysAllow;
    impl crate::permissions::PermissionsApprovalHandler for AlwaysAllow {
        fn ask(
            &self,
            _req: &crate::permissions::ApprovalRequest,
        ) -> crate::permissions::ApprovalOutcome {
            crate::permissions::ApprovalOutcome::Allow
        }
    }

    fn call(name: &str, args: serde_json::Value) -> crate::message::ToolCall {
        crate::message::ToolCall {
            id: format!("call-{name}"),
            kind: "function".to_string(),
            function: crate::message::FunctionCall {
                name: name.to_string(),
                arguments: args.to_string(),
            },
        }
    }

    /// The row `plan-mode-read-only-research-phase` claims: under the
    /// resolved `cc-parity` preset, entering plan mode makes the
    /// permissions engine REFUSE write and execution tools — and the
    /// refusal survives an approval door that allows everything, because
    /// the mode contributes DENY rules, the tier no approval can override.
    #[test]
    fn cc_parity_plan_mode_denies_writes_through_the_permissions_engine() {
        let mut agent = agent_for("cc-parity");
        assert!(
            agent.config.permissions_enabled,
            "cc-parity runs the permissions engine; plan mode narrows it"
        );
        agent.set_permissions_approval_handler(AlwaysAllow);

        let write = serde_json::json!({"path": "notes.txt", "content": "x"});
        let bash = serde_json::json!({"command": "echo hi"});
        assert!(
            agent
                .permissions_gate_denial("write_file", &write, crate::config::HookDecision::Pass)
                .is_none(),
            "outside plan mode an allowed write must pass"
        );
        assert!(agent
            .permissions_gate_denial("bash", &bash, crate::config::HookDecision::Pass)
            .is_none());

        agent.plan_mode().enter(Some("research first"));

        let denial = agent
            .permissions_gate_denial("write_file", &write, crate::config::HookDecision::Pass)
            .expect("plan mode must refuse a write");
        assert!(denial.contains("Deny"), "{denial}");
        assert!(agent
            .permissions_gate_denial("bash", &bash, crate::config::HookDecision::Pass)
            .is_some());
        assert!(agent
            .permissions_gate_denial(
                "apply_patch",
                &serde_json::json!({"patch": "*** Begin Patch\n*** End Patch"}),
                crate::config::HookDecision::Pass
            )
            .is_some());

        // The research surface, and the way out, stay open.
        for (tool, args) in [
            ("read_file", serde_json::json!({"path": "notes.txt"})),
            ("glob", serde_json::json!({"pattern": "*.rs"})),
            ("exit_plan_mode", serde_json::json!({"plan": "the plan"})),
            ("ask_user", serde_json::json!({"questions": []})),
        ] {
            assert!(
                agent
                    .permissions_gate_denial(tool, &args, crate::config::HookDecision::Pass)
                    .is_none(),
                "plan mode must leave `{tool}` reachable"
            );
        }

        agent.plan_mode().exit();
        assert!(
            agent
                .permissions_gate_denial("write_file", &write, crate::config::HookDecision::Pass)
                .is_none(),
            "leaving plan mode restores the write surface"
        );
    }

    /// The `context-budget-tools` row's read half: the figure
    /// `get_context_remaining` reports is the agent's OWN accounting,
    /// computed at the moment the tool asks for it.
    #[test]
    fn cx_parity_publishes_its_context_accounting_when_the_budget_tool_runs() {
        let mut agent = agent_for("cx-parity");
        assert!(agent.ctx.context_budget.snapshot().is_none(), "nothing yet");
        agent
            .history
            .push(ChatMessage::user("x".repeat(4000).to_string()));
        let _ = agent.prepare_tool_call(&call("current_time", serde_json::json!({})));
        assert!(
            agent.ctx.context_budget.snapshot().is_none(),
            "an unrelated tool call must not pay for the accounting"
        );

        let _ = agent.prepare_tool_call(&call("get_context_remaining", serde_json::json!({})));
        let published = agent
            .ctx
            .context_budget
            .snapshot()
            .expect("the budget tool's own call publishes it");
        // What the model reads IS `Agent::context_usage()` — the same
        // struct `/context` prints and the guard enforces, not a second
        // estimate that could disagree with it.
        assert_eq!(
            published,
            serde_json::to_value(agent.context_usage()).unwrap()
        );
        assert!(published["context_limit"].as_u64().unwrap() > 0);
        assert!(published["remaining_tokens"].as_u64().unwrap() > 0);
    }

    /// The `context-budget-tools` row's write half, over the resolved
    /// `cx-parity` preset: a parked `new_context` request re-founds the
    /// request view through `reduce`'s handoff projection — objective in
    /// the leading system message, the tail kept, the rest covered by
    /// `TurnsCleared` spans that land in this agent's own reduction log.
    #[test]
    fn cx_parity_new_context_rebuilds_the_window_through_the_same_handoff_the_operator_gets() {
        let mut agent = agent_for("cx-parity");
        agent.history.push(ChatMessage::system("system"));
        for i in 0..12 {
            agent.history.push(ChatMessage::user(format!("turn {i}")));
        }
        let before = agent.history.clone();

        agent
            .ctx
            .context_budget
            .request_new_context(crate::tools::NewContextRequest {
                objective: "finish the parser".to_string(),
                keep_recent: Some(2),
            });
        agent.apply_pending_new_context();

        // Exactly what `/handoff` produces — the model's door and the
        // operator's door run one mechanism, so this compares against it.
        let mut expected =
            Agent::with_provider(resolved("cx-parity"), Box::new(NeverCalledProvider));
        expected.history = before.clone();
        expected.new_context("finish the parser", Some(2));
        assert_eq!(agent.history, expected.history);

        assert!(
            agent.history.len() < before.len(),
            "the window must actually shrink: {} -> {}",
            before.len(),
            agent.history.len()
        );
        assert_eq!(agent.history[0], before[0], "the system prompt survives");
        let marker = agent.history[1].content.clone().unwrap_or_default();
        assert!(marker.contains("fresh working context"), "{marker}");
        assert!(marker.contains("finish the parser"), "{marker}");
        assert_eq!(
            agent.history[agent.history.len() - 2..],
            before[before.len() - 2..],
            "the requested tail is kept verbatim"
        );
        assert!(
            agent.ctx.context_budget.take_new_context().is_none(),
            "the request is consumed exactly once"
        );
    }

    /// `new_context` never trades recoverability for a smaller window: with
    /// no sidecar recorder the request is refused, the reason is handed
    /// back to the model, and the transcript keeps every turn.
    #[test]
    fn cx_parity_new_context_states_the_retention_it_actually_has() {
        let mut agent = agent_for("cx-parity");
        agent.history.push(ChatMessage::system("system"));
        for i in 0..12 {
            agent.history.push(ChatMessage::user(format!("turn {i}")));
        }
        agent
            .ctx
            .context_budget
            .request_new_context(crate::tools::NewContextRequest {
                objective: "finish the parser".to_string(),
                keep_recent: Some(2),
            });
        agent.apply_pending_new_context();

        // No recorder is installed here, and the marker says so rather than
        // implying the set-aside turns are still somewhere.
        let marker = agent.history[1].content.clone().unwrap_or_default();
        assert!(
            marker.contains("No transcript sidecar is attached"),
            "the marker must not overstate retention: {marker}"
        );
    }
}

/// BP-8 (catalog:152): what [`Agent::rewind_conversation`] did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RewindOutcome {
    /// Messages remaining, including the system message at index 0.
    pub kept: usize,
    /// Messages removed from the live conversation (still on disk, in the
    /// journal, and still in the tree under `preserved_branch`).
    pub removed: usize,
    /// When the tree module is on and the rewind actually moved the leaf:
    /// the sibling branch the old leaf was preserved under, so the rewound
    /// path stays independently addressable.
    pub preserved_branch: Option<String>,
}

#[cfg(test)]
mod bp1_compaction_tests {
    //! BP-1 (`.volter/tracker/markdown/BP-1.md` AC2): `cx-parity` fires
    //! [`Agent::maybe_compact`] at its own trigger, and
    //! `core.compaction.summarize` reaches [`Config`] and is what the
    //! compaction marker says.

    use super::*;
    use crate::configfile::{resolve, ResolveOptions};

    /// Never called — these tests drive `maybe_compact` directly, which
    /// makes no request.
    #[derive(Debug)]
    struct NeverCalledProvider;

    #[async_trait::async_trait]
    impl Provider for NeverCalledProvider {
        async fn complete(
            &self,
            _req: &ChatRequest,
            _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
        ) -> crate::Result<(ChatMessage, crate::provider::Usage)> {
            unreachable!("BP-1 compaction tests never issue a request")
        }
    }

    fn resolved_cx_parity() -> Config {
        let toml = crate::presets::lookup("cx-parity").unwrap();
        resolve(toml, None, &ResolveOptions { strict: true })
            .expect("cx-parity resolves")
            .config
    }

    /// Enough history to sit inside `reserve_tokens` of ANY model context
    /// window (`estimate_view_tokens` is size-proportional, and the largest
    /// window in the catalog is far below this).
    fn stuff_history(agent: &mut Agent) {
        agent.history.push(ChatMessage::system("system"));
        for i in 0..400 {
            agent
                .history
                .push(ChatMessage::user(format!("turn {i}: {}", "x".repeat(8000))));
        }
    }

    /// The defect: `cx-parity` armed NEITHER compaction trigger, so
    /// `maybe_compact` returned `false` on its
    /// `threshold.is_none() && compaction_reserve_tokens.is_none()` guard
    /// no matter how large the conversation grew.
    #[test]
    fn cx_parity_fires_maybe_compact_at_its_pressure_trigger() {
        let config = resolved_cx_parity();
        assert!(config.compaction_enabled);
        assert_eq!(config.compaction_reserve_tokens, Some(16384));
        assert!(config.compaction_summarize);

        let mut agent = Agent::with_provider(config, Box::new(NeverCalledProvider));
        stuff_history(&mut agent);
        let before = agent.history.len();
        assert!(
            agent.maybe_compact(),
            "cx-parity must compact under context pressure"
        );
        assert!(agent.history.len() < before, "history must actually shrink");
        let marker = agent
            .history
            .iter()
            .find(|m| {
                m.content
                    .as_deref()
                    .is_some_and(|c| c.contains("earlier conversation compacted"))
            })
            .expect("a compaction marker must be present");
        assert!(
            marker
                .content
                .as_deref()
                .unwrap()
                .contains("summarized to save context"),
            "cx-parity sets `core.compaction.summarize = true`"
        );
    }

    /// `core.compaction.summarize = false` reaches `Config` too, and the
    /// marker then states only what actually happened to the span.
    #[test]
    fn compaction_summarize_false_reaches_config_and_changes_the_marker() {
        let toml = "extends = \"cx-parity\"\n[core.compaction]\nsummarize = false\n";
        let config = resolve(toml, None, &ResolveOptions::default())
            .expect("resolves")
            .config;
        assert!(!config.compaction_summarize);

        let mut agent = Agent::with_provider(config, Box::new(NeverCalledProvider));
        stuff_history(&mut agent);
        assert!(agent.maybe_compact());
        let marker = agent
            .history
            .iter()
            .find(|m| {
                m.content
                    .as_deref()
                    .is_some_and(|c| c.contains("earlier conversation compacted"))
            })
            .expect("a compaction marker must be present");
        let text = marker.content.as_deref().unwrap();
        assert!(text.contains("cleared to save context"), "got: {text}");
        assert!(!text.contains("summarized"));
    }
}

#[cfg(test)]
mod api_key_cmd_tests {
    //! P4 (design §5.2, §1.8 D6 row): `api_key_cmd` credential-helper
    //! resolution. `Agent::new` never makes a network call, so these tests
    //! exercise the real resolution chain end-to-end without mocking.

    use super::*;

    /// Default-off: with no `api_key`/`api_key_cmd` set and an env var that
    /// isn't set either, resolution fails exactly as it always has —
    /// `api_key_cmd` being a brand-new field changes nothing when unset.
    #[test]
    fn default_none_falls_through_to_missing_api_key_error() {
        let config = Config::builder()
            .api_key_env("SUPERCODE_TEST_UNSET_VAR_API_KEY_CMD")
            .build();
        assert!(config.api_key.is_none());
        assert!(config.api_key_cmd.is_none());
        let err = Agent::new(config).err().expect("no key source configured");
        assert!(matches!(err, Error::MissingApiKey(_)));
    }

    /// Happy path: `api_key_cmd` alone (no `api_key`, no matching env var)
    /// is enough for `Agent::new` to succeed — the helper's stdout is
    /// resolved and used.
    #[test]
    fn api_key_cmd_alone_resolves_successfully() {
        let config = Config::builder()
            .api_key_cmd("echo sk-test-from-helper")
            .api_key_env("SUPERCODE_TEST_UNSET_VAR_API_KEY_CMD_2")
            .build();
        assert!(Agent::new(config).is_ok());
    }

    /// A failing helper command (non-zero exit, or empty stdout) falls
    /// through to `api_key_env` rather than propagating the helper's own
    /// failure — same "try the next source" posture as every other layer.
    #[test]
    fn api_key_cmd_failure_falls_through_to_env() {
        std::env::set_var(
            "SUPERCODE_TEST_API_KEY_CMD_FALLBACK",
            "sk-from-env-fallback",
        );
        let config = Config::builder()
            .api_key_cmd("exit 1")
            .api_key_env("SUPERCODE_TEST_API_KEY_CMD_FALLBACK")
            .build();
        assert!(Agent::new(config).is_ok());
        std::env::remove_var("SUPERCODE_TEST_API_KEY_CMD_FALLBACK");
    }

    /// A failing helper AND no fallback env var still produces the same
    /// `MissingApiKey` error today's no-key path always produced — the new
    /// source never turns a hard failure into a silent empty key.
    #[test]
    fn api_key_cmd_failure_with_no_fallback_still_errors() {
        let config = Config::builder()
            .api_key_cmd("exit 1")
            .api_key_env("SUPERCODE_TEST_UNSET_VAR_API_KEY_CMD_3")
            .build();
        let err = Agent::new(config)
            .err()
            .expect("helper failed, no env fallback");
        assert!(matches!(err, Error::MissingApiKey(_)));
    }

    /// `run_api_key_cmd` directly: happy path trims trailing whitespace/
    /// newline from the command's stdout.
    #[test]
    fn run_api_key_cmd_trims_output() {
        assert_eq!(run_api_key_cmd("echo '  sk-abc123  '"), "sk-abc123");
    }

    /// `run_api_key_cmd` directly: a nonexistent binary fails to spawn and
    /// returns an empty string rather than panicking.
    #[test]
    fn run_api_key_cmd_spawn_failure_returns_empty() {
        // `sh -c` itself always spawns; feed it a command that can't run.
        assert_eq!(
            run_api_key_cmd("/no/such/binary/at/all --flag"),
            String::new()
        );
    }
}

#[cfg(test)]
mod bp4_prompt_context_tests {
    //! BP-4 (`.volter/tracker/markdown/BP-4.md`): the prompt/context knobs
    //! the parity presets never set, proved over the RESOLVED `cc-parity` /
    //! `cx-parity` configs (not over hand-built `Config`s — a preset that
    //! doesn't arm the knob would pass that weaker test).

    use super::*;
    use crate::configfile::{resolve, ResolveOptions};

    fn resolved(preset: &str) -> Config {
        let toml = crate::presets::lookup(preset).unwrap();
        resolve(toml, None, &ResolveOptions { strict: true })
            .unwrap_or_else(|e| panic!("{preset} resolves: {e}"))
            .config
    }

    /// Never called — these tests assemble prompts and drive
    /// `refresh_env_context`/`inject_context_block`, none of which issue a
    /// request.
    #[derive(Debug)]
    struct NoProvider;

    #[async_trait::async_trait]
    impl Provider for NoProvider {
        async fn complete(
            &self,
            _req: &ChatRequest,
            _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
        ) -> crate::Result<(ChatMessage, crate::provider::Usage)> {
            unreachable!("BP-4 prompt/context tests never issue a request")
        }
    }

    fn scratch(tag: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "supercode-bp4-{tag}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// Row `project-instruction-files-w-directory-walk`: a CLAUDE.md above
    /// the working directory is discovered, ordered root→cwd (nearest wins
    /// by appearing last), and the climb STOPS at the `.git` root — the
    /// directory above it is never read.
    #[test]
    fn presets_walk_ancestors_up_to_the_git_root_nearest_last() {
        for preset in ["cc-parity", "cx-parity"] {
            let base = scratch("walk");
            let above = base.join("above");
            let root = above.join("repo");
            let deep = root.join("crates").join("thing");
            std::fs::create_dir_all(&deep).unwrap();
            std::fs::create_dir_all(root.join(".git")).unwrap();
            std::fs::write(above.join("CLAUDE.md"), "ABOVE-THE-ROOT-MARKER").unwrap();
            std::fs::write(above.join("AGENTS.md"), "ABOVE-THE-ROOT-MARKER").unwrap();
            std::fs::write(root.join("CLAUDE.md"), "REPO-ROOT-MARKER").unwrap();
            std::fs::write(root.join("AGENTS.md"), "REPO-ROOT-MARKER").unwrap();
            std::fs::write(deep.join("CLAUDE.md"), "NEAREST-DIR-MARKER").unwrap();
            std::fs::write(deep.join("AGENTS.md"), "NEAREST-DIR-MARKER").unwrap();

            let mut config = resolved(preset);
            config.cwd = deep.clone();
            let blob = assemble_project_instructions(&config);

            let root_at = blob
                .find("REPO-ROOT-MARKER")
                .unwrap_or_else(|| panic!("{preset}: the ancestor repo root was not walked"));
            let near_at = blob
                .find("NEAREST-DIR-MARKER")
                .unwrap_or_else(|| panic!("{preset}: cwd's own file was not loaded"));
            assert!(
                root_at < near_at,
                "{preset}: nearest-to-cwd must win by appearing LAST (root→cwd)"
            );
            assert!(
                !blob.contains("ABOVE-THE-ROOT-MARKER"),
                "{preset}: the walk must stop at the `.git` root"
            );
            let _ = std::fs::remove_dir_all(&base);
        }
    }

    /// The walk is bounded even with no root marker anywhere: it terminates
    /// at the filesystem root instead of looping.
    #[test]
    fn walk_terminates_without_a_root_marker() {
        let base = scratch("nomarker");
        let deep = base.join("a").join("b").join("c");
        std::fs::create_dir_all(&deep).unwrap();
        let mut config = resolved("cx-parity");
        config.cwd = deep.clone();
        let roots = instruction_walk_roots(&config);
        assert!(roots.len() <= MAX_INSTRUCTION_WALK_DEPTH);
        assert_eq!(roots.last().unwrap(), &deep, "cwd is the LAST root");
        let _ = std::fs::remove_dir_all(&base);
    }

    /// Row `instruction-file-hygiene-controls`, cx half: `cx-parity` sets
    /// the documented 32 KiB `project_doc_max_bytes`, and it binds per file
    /// AND over the aggregate, each with its own notice.
    #[test]
    fn cx_parity_enforces_the_documented_instruction_byte_cap() {
        let config = resolved("cx-parity");
        assert_eq!(
            config.project_doc_max_bytes,
            Some(32_768),
            "cx-parity must arm cx§2's documented 32 KiB cap"
        );

        let base = scratch("cap");
        std::fs::create_dir_all(base.join(".git")).unwrap();
        std::fs::write(base.join("CLAUDE.md"), "x".repeat(40_000)).unwrap();
        std::fs::write(base.join("AGENTS.md"), "y".repeat(40_000)).unwrap();
        let mut config = config;
        config.cwd = base.clone();
        let blob = assemble_project_instructions(&config);
        assert!(
            blob.contains("[supercode: file truncated at core.project_doc_max_bytes]"),
            "the per-file cap must fire with a notice"
        );
        assert!(
            blob.contains(
                "[supercode: instruction content truncated at core.project_doc_max_bytes]"
            ),
            "the aggregate cap must fire with a notice"
        );
        assert!(blob.len() < 33_200, "aggregate blob stayed over the cap");
        let _ = std::fs::remove_dir_all(&base);
    }

    /// Row `instruction-file-hygiene-controls`, cc half: `cc-parity` arms
    /// CC's own two levers — HTML-comment stripping and `claudeMdExcludes`
    /// — and arms NO byte cap, because CC documents none.
    #[test]
    fn cc_parity_strips_html_comments_and_honours_excludes() {
        let mut config = resolved("cc-parity");
        assert!(config.project_doc_strip_comments, "cc strips `<!-- … -->`");
        assert_eq!(
            config.project_doc_max_bytes, None,
            "`project_doc_max_bytes = 0` is §3.1's spelling for uncapped"
        );

        let base = scratch("hygiene");
        std::fs::create_dir_all(base.join(".git")).unwrap();
        std::fs::write(
            base.join("CLAUDE.md"),
            "KEEP-THIS<!-- MAINTAINER-NOTE -->AND-THIS",
        )
        .unwrap();
        std::fs::write(base.join("AGENTS.md"), "EXCLUDED-FILE-MARKER").unwrap();
        config.cwd = base.clone();
        config.project_doc_excludes = vec!["AGENTS.md".to_string()];
        let blob = assemble_project_instructions(&config);
        assert!(blob.contains("KEEP-THIS") && blob.contains("AND-THIS"));
        assert!(
            !blob.contains("MAINTAINER-NOTE"),
            "block HTML comments must be stripped before injection"
        );
        assert!(
            !blob.contains("EXCLUDED-FILE-MARKER"),
            "an excluded instruction file must never be read into the prompt"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    /// A project layer must not be able to suppress the user's own global
    /// instruction files by adding an exclude pattern (§3.3 trust boundary).
    #[test]
    fn project_layer_cannot_set_instruction_excludes() {
        let hc = crate::configfile::HarnessConfig::from_toml_str(
            "schema_version = 1\n[core]\nproject_doc_excludes = [\"CLAUDE.md\"]\n",
        )
        .unwrap();
        let (sanitized, dropped) = crate::configfile::sanitize_for_project(&hc);
        assert!(sanitized.core.project_doc_excludes.is_none());
        assert!(dropped.iter().any(|d| d == "core.project_doc_excludes"));
    }

    /// Row `environment-context-block`: both presets emit the policy line
    /// the row's semantics name, and the block is RE-EMITTED when the thing
    /// it describes moves (cx§2 "re-emitted on change").
    #[test]
    fn env_context_block_carries_policy_and_re_emits_on_change() {
        for preset in ["cc-parity", "cx-parity"] {
            let base = scratch("env");
            // A SIBLING, not a child: `contains` assertions below must not
            // be satisfiable by a path prefix.
            let here = base.join("here");
            let other = base.join("elsewhere");
            std::fs::create_dir_all(&here).unwrap();
            std::fs::create_dir_all(&other).unwrap();

            let mut config = resolved(preset);
            config.cwd = here.clone();
            assert!(config.env_context, "{preset} must set core.env_context");
            let expected_policy = format!(
                "approval policy: {} · sandbox: {}",
                approval_policy_label(config.approval),
                sandbox_policy_label(config.sandbox),
            );

            let mut agent = Agent::with_provider(config, Box::new(NoProvider));
            let system = agent.history[0].content.clone().unwrap_or_default();
            assert!(
                system.contains(&expected_policy),
                "{preset}: the environment block must state the approval/sandbox policy — {system}"
            );
            assert!(system.contains(&format!("cwd: {}", here.display())));

            // Nothing moved ⇒ no churn (the prompt cache is not busted for
            // free).
            assert!(!agent.refresh_env_context(), "{preset}: spurious re-emit");

            // cwd + policy move mid-session.
            agent.config.cwd = other.clone();
            agent.config.approval = crate::config::ApprovalPolicy::Untrusted;
            assert!(
                agent.refresh_env_context(),
                "{preset}: change not re-emitted"
            );
            let system = agent.history[0].content.clone().unwrap_or_default();
            assert!(
                system.contains(&format!("cwd: {}", other.display())),
                "{preset}: the fresh cwd must reach the model"
            );
            assert!(system.contains("approval policy: untrusted"));
            assert!(
                !system.contains(&format!("cwd: {}", here.display())),
                "{preset}: the stale block must be REPLACED, not duplicated"
            );
            assert_eq!(
                system.matches("# Environment").count(),
                1,
                "{preset}: exactly one environment block"
            );
            let _ = std::fs::remove_dir_all(&base);
        }
    }

    /// Row `synthetic-context-injection-blocks`: both presets arm the
    /// registry, the built-in blocks reach the assembled system prompt, and
    /// a block spliced mid-session reaches it too.
    #[test]
    fn presets_splice_builtin_and_runtime_context_blocks() {
        for preset in ["cc-parity", "cx-parity"] {
            let config = resolved(preset);
            assert!(
                config.context_injections,
                "{preset} must set core.context_injections"
            );
            let mut agent = Agent::with_provider(config, Box::new(NoProvider));
            let system = agent.history[0].content.clone().unwrap_or_default();
            assert!(
                system.contains("# Task list"),
                "{preset}: a built-in ambient block must reach the prompt"
            );

            assert!(agent.inject_context_block("Mid session", "SPLICED-BODY-MARKER"));
            let system = agent.history[0].content.clone().unwrap_or_default();
            assert!(
                system.contains("# Mid session") && system.contains("SPLICED-BODY-MARKER"),
                "{preset}: a runtime splice must reach the prompt"
            );
            assert_eq!(agent.spliced_context_blocks().len(), 1);
        }
    }

    /// A deterministic stand-in for the CLI's real provider-backed
    /// summarizer: it records exactly what it was asked to summarize, so the
    /// test can prove the `/compact <focus>` text reached the summarizer's
    /// INPUT and not only the marker.
    #[derive(Debug, Default)]
    struct RecordingSummarizer {
        seen: std::sync::Mutex<Vec<String>>,
    }

    impl reduce::summarize::SpanSummarizer for RecordingSummarizer {
        fn summarize(&self, span_text: &str) -> reduce::Result<String> {
            self.seen
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(span_text.to_string());
            Ok("MODEL-WRITTEN-SUMMARY".to_string())
        }

        fn model_id(&self) -> &str {
            "test-summarizer"
        }
    }

    fn stuffed_agent(preset: &str) -> Agent {
        let config = resolved(preset);
        let mut agent = Agent::with_provider(config, Box::new(NoProvider));
        for i in 0..40 {
            agent.history.push(ChatMessage::user(format!("turn {i}")));
            agent
                .history
                .push(ChatMessage::assistant(format!("reply {i}")));
        }
        agent
    }

    /// Row `manual-compact-with-focus-instructions`: `/compact <focus>`
    /// compacts on demand (no trigger needed) and the focus text lands in
    /// BOTH the summarizer's input and the marker.
    #[test]
    fn presets_manual_compact_carries_focus_into_the_summarizer_and_the_marker() {
        for preset in ["cc-parity", "cx-parity"] {
            let config = resolved(preset);
            assert!(
                config.compaction_focus_instructions.is_some(),
                "{preset} must state core.compaction.focus_instructions"
            );
            let mut agent = stuffed_agent(preset);
            let summarizer = std::sync::Arc::new(RecordingSummarizer::default());
            agent.set_span_summarizer_arc(summarizer.clone());

            let before = agent.history().len();
            assert!(
                agent.compact_now(Some("keep the migration steps")),
                "{preset}: /compact must compact on demand"
            );
            assert!(agent.history().len() < before, "{preset}: nothing dropped");

            let marker = agent
                .history()
                .iter()
                .find_map(|m| m.content.as_deref())
                .filter(|c| c.contains("earlier conversation compacted"))
                .or_else(|| {
                    agent
                        .history()
                        .iter()
                        .filter_map(|m| m.content.as_deref())
                        .find(|c| c.contains("earlier conversation compacted"))
                })
                .unwrap_or_else(|| panic!("{preset}: no compaction marker"))
                .to_string();
            assert!(
                marker.contains("Focus: keep the migration steps"),
                "{preset}: {marker}"
            );

            let seen = summarizer
                .seen
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            assert_eq!(seen.len(), 1, "{preset}: exactly one side-call");
            assert!(
                seen[0].contains("keep the migration steps"),
                "{preset}: the focus must reach the summarizer INPUT — {}",
                &seen[0][..seen[0].len().min(200)]
            );
        }
    }

    /// Row `llm-summaries-of-cleared-spans`: the model-written summary is
    /// produced under the presets WITHOUT `capabilities.reduction` — design
    /// §1.5 puts "an LLM summary of the compacted span" in core obligation
    /// 5, knob `[core.compaction] summarize`.
    #[test]
    fn presets_summarize_the_cleared_span_without_the_reduction_module() {
        for preset in ["cc-parity", "cx-parity"] {
            let toml = crate::presets::lookup(preset).unwrap();
            let r = resolve(toml, None, &ResolveOptions { strict: true }).unwrap();
            assert_eq!(
                r.modules.get("reduction"),
                Some(&false),
                "{preset}: this row must hold with the reduction module OFF"
            );
            assert!(r.config.compaction_summarize);

            let mut agent = stuffed_agent(preset);
            agent.set_span_summarizer_arc(std::sync::Arc::new(RecordingSummarizer::default()));
            assert!(agent.compact_now(None));
            let marker = agent
                .history()
                .iter()
                .filter_map(|m| m.content.as_deref())
                .find(|c| c.contains("earlier conversation compacted"))
                .unwrap_or_else(|| panic!("{preset}: no compaction marker"));
            assert!(
                marker.contains("MODEL-WRITTEN-SUMMARY"),
                "{preset}: the marker must carry the model-written summary — {marker}"
            );
        }
    }

    /// BP-11 (catalog "Lifecycle hooks, config-registered"): the compaction
    /// boundary is observable — `pre_compact` fires once the compaction is
    /// decided (with the manual/auto trigger named) and `post_compact` once
    /// the window has been rewritten, under both parity presets.
    #[test]
    fn compaction_fires_pre_and_post_lifecycle_events_under_both_presets() {
        use crate::config::LifecycleEvent;
        for preset in ["cc-parity", "cx-parity"] {
            let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
            let mut agent = stuffed_agent(preset);
            let sink = seen.clone();
            agent.set_lifecycle_hook(Box::new(move |event| {
                sink.lock().unwrap().push(event.clone());
            }));
            let before = agent.history().len();
            assert!(agent.compact_now(Some("keep the plan")), "{preset}");
            let after = agent.history().len();
            let seen = seen.lock().unwrap();
            assert_eq!(seen.len(), 2, "{preset}: exactly pre + post — {seen:?}");
            match &seen[0] {
                LifecycleEvent::PreCompact {
                    messages,
                    dropped,
                    manual,
                } => {
                    assert_eq!(*messages, before, "{preset}");
                    assert!(*dropped > 0, "{preset}");
                    assert!(*manual, "{preset}: /compact is the manual trigger");
                }
                other => panic!("{preset}: first event must be PreCompact, got {other:?}"),
            }
            match &seen[1] {
                LifecycleEvent::PostCompact { messages, dropped } => {
                    assert_eq!(*messages, after, "{preset}");
                    assert_eq!(
                        *dropped,
                        before - after + 1,
                        "{preset}: dropped span + 1 marker"
                    );
                }
                other => panic!("{preset}: second event must be PostCompact, got {other:?}"),
            }
        }
    }

    /// The automatic trigger reports itself as such, and a window too small
    /// to compact fires nothing at all (no pre without a post).
    #[test]
    fn automatic_compaction_reports_the_auto_trigger_and_a_no_op_fires_nothing() {
        use crate::config::LifecycleEvent;
        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut agent = stuffed_agent("cc-parity");
        let sink = seen.clone();
        agent.set_lifecycle_hook(Box::new(move |event| {
            sink.lock().unwrap().push(event.clone());
        }));
        agent.config.compact_after_messages = Some(10);
        assert!(agent.maybe_compact());
        assert!(matches!(
            seen.lock().unwrap()[0],
            LifecycleEvent::PreCompact { manual: false, .. }
        ));
        seen.lock().unwrap().clear();
        let mut small = Agent::with_provider(resolved("cc-parity"), Box::new(NoProvider));
        let sink = seen.clone();
        small.set_lifecycle_hook(Box::new(move |event| {
            sink.lock().unwrap().push(event.clone());
        }));
        assert!(!small.compact_now(None));
        assert!(seen.lock().unwrap().is_empty());
    }

    /// With no summarizer installed the marker degrades to the count-only
    /// form — the side-call never blocks or fails compaction.
    #[test]
    fn compaction_without_a_summarizer_keeps_the_count_only_marker() {
        let mut agent = stuffed_agent("cc-parity");
        assert!(agent.compact_now(None));
        let marker = agent
            .history()
            .iter()
            .filter_map(|m| m.content.as_deref())
            .find(|c| c.contains("earlier conversation compacted"))
            .unwrap();
        assert!(!marker.contains("Summary of the compacted span"));
    }

    /// Row `compaction-markers-persisted-in-transcript`: under the presets
    /// (reduction OFF) the boundary marker is written to the session
    /// sidecar, and says where the originals went.
    #[test]
    fn presets_persist_the_compaction_marker_to_the_transcript() {
        for preset in ["cc-parity", "cx-parity"] {
            let dir = scratch("marker");
            let path = dir.join("session.jsonl");
            let empty = crate::session::Session::from_claude_code_str("").unwrap();
            let writer = crate::sidecar::SidecarWriter::create(&path, &empty).unwrap();
            let mut agent = stuffed_agent(preset);
            agent.set_recorder(writer);
            assert!(agent.reduction_policy().is_none(), "{preset}");

            assert!(agent.compact_now(None));
            let on_disk = std::fs::read_to_string(&path).unwrap();
            assert!(
                on_disk.contains("earlier conversation compacted"),
                "{preset}: the marker must reach the transcript on disk"
            );
            assert!(
                on_disk.contains("remain in this session's transcript sidecar"),
                "{preset}: the marker must say where the originals went"
            );
            let _ = std::fs::remove_dir_all(&dir);
        }
    }

    /// Row `handoff-fresh-objective-curated-keep-set`: an in-session
    /// `new_context` — fresh objective, curated recent keep-set, persisted
    /// marker — under cx-parity, where `capabilities.reduction` is off.
    #[test]
    fn cx_parity_handoff_seeds_a_fresh_objective_with_a_curated_keep_set() {
        let mut agent = stuffed_agent("cx-parity");
        assert!(!agent.config().handoff_enabled, "reduction handoff is off");
        agent.history.push(ChatMessage::user("LAST-USER-TURN"));
        let before = agent.history().len();

        let dropped = agent.new_context("ship the migration", Some(3));
        assert!(dropped > 0, "messages must be set aside");
        assert!(agent.history().len() < before);
        let system_prompt = agent.history()[0].content.clone().unwrap_or_default();
        assert!(
            system_prompt.contains("supercode") || !system_prompt.is_empty(),
            "the system prompt survives a handoff"
        );
        let marker = agent
            .history()
            .iter()
            .filter_map(|m| m.content.as_deref())
            .find(|c| c.contains("[handoff:"))
            .expect("handoff marker");
        assert!(marker.contains("Objective: ship the migration"));
        assert!(
            agent
                .history()
                .iter()
                .any(|m| m.content.as_deref() == Some("LAST-USER-TURN")),
            "the curated keep-set must carry the most recent turns"
        );
    }

    /// Row `context-usage-introspection`: a live breakdown, from the same
    /// estimator the context guard enforces, without sending anything.
    #[test]
    fn presets_report_live_context_usage() {
        for preset in ["cc-parity", "cx-parity"] {
            let agent = stuffed_agent(preset);
            let usage = agent.context_usage();
            assert_eq!(usage.messages, agent.history().len(), "{preset}");
            assert!(usage.message_tokens > 0, "{preset}");
            assert_eq!(
                usage.request_tokens,
                usage.message_tokens + usage.tool_schema_tokens,
                "{preset}: the breakdown must add up"
            );
            assert!(usage.projected_tokens >= usage.request_tokens, "{preset}");
            assert!(usage.context_limit.is_some(), "{preset}: window known");
            assert!(usage.fits, "{preset}");
            let line = usage.summary_line();
            assert!(line.contains('%') && line.contains(&usage.model), "{line}");

            // Pure: asking must not change what the next request carries.
            let again = agent.context_usage();
            assert_eq!(usage, again, "{preset}");
        }
    }
}

#[cfg(test)]
#[path = "agent_bp10_tests.rs"]
mod bp10_permissions_tests;