zeph-core 0.18.0

Core agent loop, configuration, context builder, metrics, and vault for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::fmt::Write;

use futures::StreamExt as _;
use zeph_llm::provider::{LlmProvider, Message, MessageMetadata, MessagePart, Role};
use zeph_memory::AnchoredSummary;

use super::super::Agent;
use super::super::context_manager::CompactionTier;
use super::super::tool_execution::OVERFLOW_NOTICE_PREFIX;
use super::CompactionOutcome;
use crate::channel::Channel;
use crate::context::ContextBudget;

/// Extract the overflow UUID from a tool output body, if present.
///
/// The overflow notice has the format:
/// `\n[full output stored — ID: {uuid} — {bytes} bytes, use read_overflow tool to retrieve]`
///
/// Returns the UUID substring on success, or `None` if the notice is absent.
fn extract_overflow_ref(body: &str) -> Option<&str> {
    let start = body.find(OVERFLOW_NOTICE_PREFIX)?;
    let rest = &body[start + OVERFLOW_NOTICE_PREFIX.len()..];
    let end = rest.find(" \u{2014} ")?;
    Some(&rest[..end])
}

impl<C: Channel> Agent<C> {
    pub(super) fn build_chunk_prompt(messages: &[Message], guidelines: &str) -> String {
        let estimated_len: usize = messages
            .iter()
            .map(|m| "[assistant]: ".len() + m.content.len() + 2)
            .sum();
        let mut history_text = String::with_capacity(estimated_len);
        for (i, m) in messages.iter().enumerate() {
            if i > 0 {
                history_text.push_str("\n\n");
            }
            let role = match m.role {
                Role::User => "user",
                Role::Assistant => "assistant",
                Role::System => "system",
            };
            let _ = write!(history_text, "[{role}]: {}", m.content);
        }

        let guidelines_section = if guidelines.is_empty() {
            String::new()
        } else {
            format!("\n<compression-guidelines>\n{guidelines}\n</compression-guidelines>\n")
        };

        format!(
            "<analysis>\n\
             Analyze this conversation and produce a structured compaction note for self-consumption.\n\
             This note replaces the original messages in your context window — be thorough.\n\
             Longer is better if it preserves actionable detail.\n\
             </analysis>\n\
             {guidelines_section}\n\
             Produce exactly these 9 sections:\n\
             1. User Intent — what the user is ultimately trying to accomplish\n\
             2. Technical Concepts — key technologies, patterns, constraints discussed\n\
             3. Files & Code — file paths, function names, structs, enums touched or relevant\n\
             4. Errors & Fixes — every error encountered and whether/how it was resolved\n\
             5. Problem Solving — approaches tried, decisions made, alternatives rejected\n\
             6. User Messages — verbatim user requests that are still pending or relevant\n\
             7. Pending Tasks — items explicitly promised or left TODO\n\
             8. Current Work — the exact task in progress at the moment of compaction\n\
             9. Next Step — the single most important action to take immediately after compaction\n\
             \n\
             Conversation:\n{history_text}"
        )
    }

    /// Build a prompt for structured `AnchoredSummary` output.
    pub(super) fn build_anchored_summary_prompt(messages: &[Message], guidelines: &str) -> String {
        let estimated_len: usize = messages
            .iter()
            .map(|m| "[assistant]: ".len() + m.content.len() + 2)
            .sum();
        let mut history_text = String::with_capacity(estimated_len);
        for (i, m) in messages.iter().enumerate() {
            if i > 0 {
                history_text.push_str("\n\n");
            }
            let role = match m.role {
                Role::User => "user",
                Role::Assistant => "assistant",
                Role::System => "system",
            };
            let _ = write!(history_text, "[{role}]: {}", m.content);
        }

        let guidelines_section = if guidelines.is_empty() {
            String::new()
        } else {
            format!("\n<compression-guidelines>\n{guidelines}\n</compression-guidelines>\n")
        };

        format!(
            "<analysis>\n\
             You are compacting a conversation into a structured summary for self-consumption.\n\
             This summary replaces the original messages in your context window.\n\
             Every field MUST be populated — empty fields mean lost information.\n\
             </analysis>\n\
             {guidelines_section}\n\
             Produce a JSON object with exactly these 5 fields:\n\
             - session_intent: string — what the user is trying to accomplish\n\
             - files_modified: string[] — file paths, function names, structs touched\n\
             - decisions_made: string[] — each entry: \"Decision: X — Reason: Y\"\n\
             - open_questions: string[] — unresolved questions or blockers\n\
             - next_steps: string[] — concrete next actions\n\
             \n\
             Be thorough. Preserve all file paths, line numbers, error messages, \
             and specific identifiers — they cannot be recovered.\n\
             \n\
             Conversation:\n{history_text}"
        )
    }

    /// Attempt structured summarization via `chat_typed_erased::<AnchoredSummary>()`.
    ///
    /// Returns `Ok(AnchoredSummary)` on success, `Err` when mandatory fields are missing
    /// or the LLM fails. The caller is responsible for falling back to prose on `Err`.
    async fn try_summarize_structured(
        &self,
        messages: &[Message],
        guidelines: &str,
    ) -> Result<AnchoredSummary, zeph_llm::LlmError> {
        let prompt = Self::build_anchored_summary_prompt(messages, guidelines);
        let msgs = [Message {
            role: Role::User,
            content: prompt,
            parts: vec![],
            metadata: MessageMetadata::default(),
        }];
        let llm_timeout = std::time::Duration::from_secs(self.runtime.timeouts.llm_seconds);
        let summary: AnchoredSummary = tokio::time::timeout(
            llm_timeout,
            self.summary_or_primary_provider()
                .chat_typed_erased::<AnchoredSummary>(&msgs),
        )
        .await
        .map_err(|_| zeph_llm::LlmError::Timeout)??;

        if !summary.files_modified.is_empty() && summary.decisions_made.is_empty() {
            tracing::warn!("structured summary: decisions_made is empty");
        } else if summary.files_modified.is_empty() {
            tracing::warn!(
                "structured summary: files_modified is empty (may be a pure discussion session)"
            );
        }

        if !summary.is_complete() {
            tracing::warn!(
                session_intent_empty = summary.session_intent.trim().is_empty(),
                next_steps_empty = summary.next_steps.is_empty(),
                "structured summary incomplete: mandatory fields missing, falling back to prose"
            );
            return Err(zeph_llm::LlmError::Other(
                "structured summary missing mandatory fields".into(),
            ));
        }

        if let Err(msg) = summary.validate() {
            tracing::warn!(
                error = %msg,
                "structured summary failed field validation, falling back to prose"
            );
            return Err(zeph_llm::LlmError::Other(msg));
        }

        Ok(summary)
    }

    /// Build a metadata-only summary without calling the LLM.
    /// Used as last-resort fallback when LLM summarization repeatedly fails.
    pub(super) fn build_metadata_summary(messages: &[Message]) -> String {
        let mut user_count = 0usize;
        let mut assistant_count = 0usize;
        let mut system_count = 0usize;
        let mut last_user = String::new();
        let mut last_assistant = String::new();

        for m in messages {
            match m.role {
                Role::User => {
                    user_count += 1;
                    if !m.content.is_empty() {
                        last_user.clone_from(&m.content);
                    }
                }
                Role::Assistant => {
                    assistant_count += 1;
                    if !m.content.is_empty() {
                        last_assistant.clone_from(&m.content);
                    }
                }
                Role::System => system_count += 1,
            }
        }

        let last_user_preview = super::truncate_chars(&last_user, 200);
        let last_assistant_preview = super::truncate_chars(&last_assistant, 200);

        format!(
            "[metadata summary — LLM compaction unavailable]\n\
             Messages compacted: {} ({} user, {} assistant, {} system)\n\
             Last user message: {last_user_preview}\n\
             Last assistant message: {last_assistant_preview}",
            messages.len(),
            user_count,
            assistant_count,
            system_count,
        )
    }

    async fn single_pass_summary(
        &self,
        messages: &[Message],
        guidelines: &str,
        timeout: std::time::Duration,
    ) -> Result<String, zeph_llm::LlmError> {
        let prompt = Self::build_chunk_prompt(messages, guidelines);
        let msgs = [Message {
            role: Role::User,
            content: prompt,
            parts: vec![],
            metadata: MessageMetadata::default(),
        }];
        tokio::time::timeout(timeout, self.summary_or_primary_provider().chat(&msgs))
            .await
            .map_err(|_| zeph_llm::LlmError::Timeout)?
    }

    #[allow(clippy::too_many_lines)]
    async fn try_summarize_with_llm(
        &self,
        messages: &[Message],
        guidelines: &str,
    ) -> Result<String, zeph_llm::LlmError> {
        const CHUNK_TOKEN_BUDGET: usize = 4096;
        const OVERSIZED_THRESHOLD: usize = CHUNK_TOKEN_BUDGET / 2;

        let chunks = super::chunk_messages(
            messages,
            CHUNK_TOKEN_BUDGET,
            OVERSIZED_THRESHOLD,
            &self.metrics.token_counter,
        );

        let llm_timeout = std::time::Duration::from_secs(self.runtime.timeouts.llm_seconds);

        if chunks.len() <= 1 {
            return self
                .single_pass_summary(messages, guidelines, llm_timeout)
                .await;
        }

        // Summarize chunks with bounded concurrency to prevent runaway API calls
        let provider = self.summary_or_primary_provider();
        let guidelines_owned = guidelines.to_string();
        let results: Vec<_> = futures::stream::iter(chunks.iter().map(|chunk| {
            let prompt = Self::build_chunk_prompt(chunk, &guidelines_owned);
            let p = provider.clone();
            async move {
                tokio::time::timeout(
                    llm_timeout,
                    p.chat(&[Message {
                        role: Role::User,
                        content: prompt,
                        parts: vec![],
                        metadata: MessageMetadata::default(),
                    }]),
                )
                .await
                .map_err(|_| zeph_llm::LlmError::Timeout)?
            }
        }))
        .buffer_unordered(4)
        .collect()
        .await;

        let partial_summaries: Vec<String> = results
            .into_iter()
            .collect::<Result<Vec<_>, zeph_llm::LlmError>>()
            .unwrap_or_else(|e| {
                tracing::warn!("chunked compaction: one or more chunks failed: {e:#}, falling back to single-pass");
                Vec::new()
            });

        if partial_summaries.is_empty() {
            // Fallback: single-pass on full messages
            return self
                .single_pass_summary(messages, guidelines, llm_timeout)
                .await;
        }

        // Consolidate partial summaries
        let numbered = {
            use std::fmt::Write as _;
            let cap: usize = partial_summaries.iter().map(|s| s.len() + 8).sum();
            let mut buf = String::with_capacity(cap);
            for (i, s) in partial_summaries.iter().enumerate() {
                if i > 0 {
                    buf.push_str("\n\n");
                }
                let _ = write!(buf, "{}. {s}", i + 1);
            }
            buf
        };

        // IMP-01: for the final consolidation, apply structured output when enabled.
        // Per-chunk summaries remain prose; only the consolidation becomes AnchoredSummary.
        if self.memory_state.structured_summaries {
            let anchored_prompt = format!(
                "<analysis>\n\
                 Merge these partial conversation summaries into a single structured summary.\n\
                 </analysis>\n\
                 \n\
                 Produce a JSON object with exactly these 5 fields:\n\
                 - session_intent: string — what the user is trying to accomplish\n\
                 - files_modified: string[] — file paths, function names, structs touched\n\
                 - decisions_made: string[] — each entry: \"Decision: X — Reason: Y\"\n\
                 - open_questions: string[] — unresolved questions or blockers\n\
                 - next_steps: string[] — concrete next actions\n\
                 \n\
                 Partial summaries:\n{numbered}"
            );
            let anchored_msgs = [Message {
                role: Role::User,
                content: anchored_prompt,
                parts: vec![],
                metadata: MessageMetadata::default(),
            }];
            match tokio::time::timeout(
                llm_timeout,
                self.summary_or_primary_provider()
                    .chat_typed_erased::<AnchoredSummary>(&anchored_msgs),
            )
            .await
            {
                Ok(Ok(anchored)) if anchored.is_complete() => {
                    if let Some(ref d) = self.debug_state.debug_dumper {
                        d.dump_anchored_summary(&anchored, false, &self.metrics.token_counter);
                    }
                    return Ok(super::cap_summary(anchored.to_markdown(), 16_000));
                }
                Ok(Ok(anchored)) => {
                    tracing::warn!(
                        "chunked consolidation: structured summary incomplete, falling back to prose"
                    );
                    if let Some(ref d) = self.debug_state.debug_dumper {
                        d.dump_anchored_summary(&anchored, true, &self.metrics.token_counter);
                    }
                }
                Ok(Err(e)) => {
                    tracing::warn!(error = %e, "chunked consolidation: structured output failed, falling back to prose");
                }
                Err(_) => {
                    tracing::warn!(
                        "chunked consolidation: structured output timed out, falling back to prose"
                    );
                }
            }
        }

        let consolidation_prompt = format!(
            "<analysis>\n\
             Merge these partial conversation summaries into a single structured compaction note.\n\
             Produce exactly these 9 sections covering all partial summaries:\n\
             1. User Intent\n2. Technical Concepts\n3. Files & Code\n4. Errors & Fixes\n\
             5. Problem Solving\n6. User Messages\n7. Pending Tasks\n8. Current Work\n9. Next Step\n\
             </analysis>\n\n\
             Partial summaries:\n{numbered}"
        );

        let consolidation_msgs = [Message {
            role: Role::User,
            content: consolidation_prompt,
            parts: vec![],
            metadata: MessageMetadata::default(),
        }];
        tokio::time::timeout(
            llm_timeout,
            self.summary_or_primary_provider().chat(&consolidation_msgs),
        )
        .await
        .map_err(|_| zeph_llm::LlmError::Timeout)?
    }

    /// Remove tool response parts from messages using middle-out order.
    /// `fraction` is in range (0.0, 1.0] — fraction of tool responses to remove.
    /// Returns the modified message list.
    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_possible_wrap
    )]
    pub(super) fn remove_tool_responses_middle_out(
        mut messages: Vec<Message>,
        fraction: f32,
    ) -> Vec<Message> {
        // Collect indices of messages that have ToolResult or ToolOutput parts
        let tool_indices: Vec<usize> = messages
            .iter()
            .enumerate()
            .filter(|(_, m)| {
                m.parts.iter().any(|p| {
                    matches!(
                        p,
                        MessagePart::ToolResult { .. } | MessagePart::ToolOutput { .. }
                    )
                })
            })
            .map(|(i, _)| i)
            .collect();

        if tool_indices.is_empty() {
            return messages;
        }

        let n = tool_indices.len();
        let to_remove = ((n as f32 * fraction).ceil() as usize).min(n);

        // Middle-out: start from center, alternate outward
        let center = n / 2;
        let mut remove_set: Vec<usize> = Vec::with_capacity(to_remove);
        let mut left = center as isize - 1;
        let mut right = center;
        let mut count = 0;

        while count < to_remove {
            if right < n {
                remove_set.push(tool_indices[right]);
                count += 1;
                right += 1;
            }
            if count < to_remove && left >= 0 {
                let idx = left as usize;
                if !remove_set.contains(&tool_indices[idx]) {
                    remove_set.push(tool_indices[idx]);
                    count += 1;
                }
            }
            left -= 1;
            if left < 0 && right >= n {
                break;
            }
        }

        for &msg_idx in &remove_set {
            let msg = &mut messages[msg_idx];
            for part in &mut msg.parts {
                match part {
                    MessagePart::ToolResult { content, .. } => {
                        let ref_notice = extract_overflow_ref(content).map_or_else(
                            || String::from("[compacted]"),
                            |uuid| {
                                format!(
                                    "[tool output pruned; use read_overflow {uuid} to retrieve]"
                                )
                            },
                        );
                        *content = ref_notice;
                    }
                    MessagePart::ToolOutput {
                        body, compacted_at, ..
                    } => {
                        if compacted_at.is_none() {
                            let ref_notice = extract_overflow_ref(body)
                                .map(|uuid| {
                                    format!(
                                        "[tool output pruned; use read_overflow {uuid} to retrieve]"
                                    )
                                })
                                .unwrap_or_default();
                            *body = ref_notice;
                            *compacted_at = Some(
                                std::time::SystemTime::now()
                                    .duration_since(std::time::UNIX_EPOCH)
                                    .unwrap_or_default()
                                    .as_secs()
                                    .cast_signed(),
                            );
                        }
                    }
                    _ => {}
                }
            }
            msg.rebuild_content();
        }
        messages
    }

    async fn summarize_messages(
        &self,
        messages: &[Message],
        guidelines: &str,
    ) -> Result<String, super::super::error::AgentError> {
        // Structured path: attempt AnchoredSummary when enabled, fall back to prose on failure.
        if self.memory_state.structured_summaries {
            match self.try_summarize_structured(messages, guidelines).await {
                Ok(anchored) => {
                    if let Some(ref d) = self.debug_state.debug_dumper {
                        d.dump_anchored_summary(&anchored, false, &self.metrics.token_counter);
                    }
                    return Ok(super::cap_summary(anchored.to_markdown(), 16_000));
                }
                Err(e) => {
                    tracing::warn!(error = %e, "structured summarization failed, falling back to prose");
                    if let Some(ref d) = self.debug_state.debug_dumper {
                        let empty = AnchoredSummary {
                            session_intent: String::new(),
                            files_modified: vec![],
                            decisions_made: vec![],
                            open_questions: vec![],
                            next_steps: vec![],
                        };
                        d.dump_anchored_summary(&empty, true, &self.metrics.token_counter);
                    }
                }
            }
        }

        // Try direct summarization first
        match self.try_summarize_with_llm(messages, guidelines).await {
            Ok(summary) => return Ok(summary),
            Err(e) if !e.is_context_length_error() => return Err(e.into()),
            Err(e) => {
                tracing::warn!(
                    "summarization hit context length error ({e}), trying progressive tool response removal"
                );
            }
        }

        // Progressive tool response removal tiers: 10%, 20%, 50%, 100%
        for fraction in [0.10f32, 0.20, 0.50, 1.0] {
            let reduced = Self::remove_tool_responses_middle_out(messages.to_vec(), fraction);
            tracing::debug!(
                fraction,
                "retrying summarization with reduced tool responses"
            );
            match self.try_summarize_with_llm(&reduced, guidelines).await {
                Ok(summary) => {
                    tracing::info!(
                        fraction,
                        "summarization succeeded after tool response removal"
                    );
                    return Ok(summary);
                }
                Err(e) if e.is_context_length_error() => {
                    tracing::warn!(fraction, "still context length error, trying next tier");
                }
                Err(e) => return Err(e.into()),
            }
        }

        // Final fallback: metadata-only summary without LLM
        tracing::warn!("all LLM summarization attempts failed, using metadata fallback");
        Ok(Self::build_metadata_summary(messages))
    }

    /// Load the current compression guidelines from `SQLite` if the feature is enabled.
    ///
    /// Returns an empty string when the feature is disabled, memory is not initialized,
    /// or the database query fails (non-fatal).
    #[cfg(feature = "compression-guidelines")]
    async fn load_compression_guidelines_if_enabled(&self) -> String {
        let config = &self.memory_state.compression_guidelines_config;
        if !config.enabled {
            return String::new();
        }
        let Some(memory) = &self.memory_state.memory else {
            return String::new();
        };
        match memory
            .sqlite()
            .load_compression_guidelines(self.memory_state.conversation_id)
            .await
        {
            Ok((_, text)) => text,
            Err(e) => {
                tracing::warn!("failed to load compression guidelines: {e:#}");
                String::new()
            }
        }
    }

    #[allow(clippy::too_many_lines)]
    pub(in crate::agent) async fn compact_context(
        &mut self,
    ) -> Result<CompactionOutcome, super::super::error::AgentError> {
        // Force-apply any pending deferred summaries before draining to avoid losing them (CRIT-01).
        let _ = self.apply_deferred_summaries();

        let preserve_tail = self.context_manager.compaction_preserve_tail;

        if self.msg.messages.len() <= preserve_tail + 1 {
            return Ok(CompactionOutcome::NoChange);
        }

        let compact_end = self.msg.messages.len() - preserve_tail;

        // S1 fix: extract focus-pinned messages before draining so they survive compaction.
        // These are Knowledge block messages created by the Focus Agent (#1850).
        let pinned_messages: Vec<Message> = self.msg.messages[1..compact_end]
            .iter()
            .filter(|m| m.metadata.focus_pinned)
            .cloned()
            .collect();

        // S2 fix (#2022): extract active-subgoal messages before draining so they survive
        // compaction. Mirrors the focus_pinned pattern exactly. Only applies when a subgoal
        // strategy is active and the registry has tagged active messages.
        #[cfg(feature = "context-compression")]
        let active_subgoal_messages: Vec<Message> = if self
            .context_manager
            .compression
            .pruning_strategy
            .is_subgoal()
        {
            use crate::agent::compaction_strategy::SubgoalState;
            self.msg.messages[1..compact_end]
                .iter()
                .enumerate()
                .filter(|(slice_i, m)| {
                    // slice_i is 0-based within [1..compact_end]; actual index = slice_i + 1.
                    let actual_i = slice_i + 1;
                    !m.metadata.focus_pinned
                        && matches!(
                            self.compression.subgoal_registry.subgoal_state(actual_i),
                            Some(SubgoalState::Active)
                        )
                })
                .map(|(_, m)| m.clone())
                .collect()
        } else {
            vec![]
        };
        #[cfg(not(feature = "context-compression"))]
        let active_subgoal_messages: Vec<Message> = vec![];

        // Summarize only the non-pinned, non-active-subgoal messages in the compaction range.
        let to_compact: Vec<Message> = {
            #[cfg(feature = "context-compression")]
            let is_subgoal = self
                .context_manager
                .compression
                .pruning_strategy
                .is_subgoal();
            #[cfg(not(feature = "context-compression"))]
            let is_subgoal = false;

            if is_subgoal {
                #[cfg(feature = "context-compression")]
                {
                    use crate::agent::compaction_strategy::SubgoalState;
                    self.msg.messages[1..compact_end]
                        .iter()
                        .enumerate()
                        .filter(|(slice_i, m)| {
                            let actual_i = slice_i + 1;
                            !m.metadata.focus_pinned
                                && !matches!(
                                    self.compression.subgoal_registry.subgoal_state(actual_i),
                                    Some(SubgoalState::Active)
                                )
                        })
                        .map(|(_, m)| m.clone())
                        .collect()
                }
                #[cfg(not(feature = "context-compression"))]
                {
                    self.msg.messages[1..compact_end]
                        .iter()
                        .filter(|m| !m.metadata.focus_pinned)
                        .cloned()
                        .collect()
                }
            } else {
                self.msg.messages[1..compact_end]
                    .iter()
                    .filter(|m| !m.metadata.focus_pinned)
                    .cloned()
                    .collect()
            }
        };
        if to_compact.is_empty() {
            return Ok(CompactionOutcome::NoChange);
        }

        // Load compression guidelines if the feature is enabled and configured.
        #[cfg(feature = "compression-guidelines")]
        let guidelines = self.load_compression_guidelines_if_enabled().await;
        #[cfg(not(feature = "compression-guidelines"))]
        let guidelines = String::new();

        let summary = self.summarize_messages(&to_compact, &guidelines).await?;

        // Compaction probe: validate summary quality before committing it.
        if self.context_manager.compression.probe.enabled {
            let _ = self
                .channel
                .send_status("Validating compaction quality...")
                .await;
            let probe_result = match zeph_memory::validate_compaction(
                self.probe_or_summary_provider(),
                &to_compact,
                &summary,
                &self.context_manager.compression.probe,
            )
            .await
            {
                Ok(result) => result,
                Err(e) => {
                    tracing::warn!("compaction probe error (non-blocking): {e:#}");
                    self.update_metrics(|m| {
                        m.compaction_probe_errors += 1;
                        m.last_probe_verdict = Some(zeph_memory::ProbeVerdict::Error);
                        m.last_probe_score = None;
                        m.last_probe_category_scores = None;
                    });
                    None
                }
            };

            if let Some(ref result) = probe_result {
                if let Some(ref d) = self.debug_state.debug_dumper {
                    d.dump_compaction_probe(result);
                }

                let cat_scores = result.category_scores.clone();
                let probe_threshold = result.threshold;
                let probe_hard_fail_threshold = result.hard_fail_threshold;
                match result.verdict {
                    zeph_memory::ProbeVerdict::HardFail => {
                        tracing::warn!(
                            score = result.score,
                            threshold = result.hard_fail_threshold,
                            "compaction probe HARD FAIL — keeping original messages"
                        );
                        self.update_metrics(|m| {
                            m.compaction_probe_failures += 1;
                            m.last_probe_verdict = Some(zeph_memory::ProbeVerdict::HardFail);
                            m.last_probe_score = Some(result.score);
                            m.last_probe_category_scores = Some(cat_scores.clone());
                            m.compaction_probe_threshold = probe_threshold;
                            m.compaction_probe_hard_fail_threshold = probe_hard_fail_threshold;
                        });
                        return Ok(CompactionOutcome::ProbeRejected);
                    }
                    zeph_memory::ProbeVerdict::SoftFail => {
                        tracing::warn!(
                            score = result.score,
                            threshold = result.threshold,
                            "compaction probe SOFT FAIL — proceeding with warning"
                        );
                        self.update_metrics(|m| {
                            m.compaction_probe_soft_failures += 1;
                            m.last_probe_verdict = Some(zeph_memory::ProbeVerdict::SoftFail);
                            m.last_probe_score = Some(result.score);
                            m.last_probe_category_scores = Some(cat_scores.clone());
                            m.compaction_probe_threshold = probe_threshold;
                            m.compaction_probe_hard_fail_threshold = probe_hard_fail_threshold;
                        });
                    }
                    zeph_memory::ProbeVerdict::Pass => {
                        tracing::info!(score = result.score, "compaction probe passed");
                        self.update_metrics(|m| {
                            m.compaction_probe_passes += 1;
                            m.last_probe_verdict = Some(zeph_memory::ProbeVerdict::Pass);
                            m.last_probe_score = Some(result.score);
                            m.last_probe_category_scores = Some(cat_scores.clone());
                            m.compaction_probe_threshold = probe_threshold;
                            m.compaction_probe_hard_fail_threshold = probe_hard_fail_threshold;
                        });
                    }
                    zeph_memory::ProbeVerdict::Error => {
                        // Unreachable: validate_compaction returns Err on errors, not Ok(Error).
                        // If this fires, the error-handling path in validate_compaction changed.
                        debug_assert!(false, "ProbeVerdict::Error reached inside Ok path");
                    }
                }
            }
        }

        let compacted_count = to_compact.len();
        let summary_content =
            format!("[conversation summary — {compacted_count} messages compacted]\n{summary}");
        // Drain the original range (includes pinned, active-subgoal, and non-pinned messages).
        self.msg.messages.drain(1..compact_end);
        // Insert the compaction summary at position 1.
        self.msg.messages.insert(
            1,
            Message {
                role: Role::System,
                content: summary_content.clone(),
                parts: vec![],
                metadata: MessageMetadata::agent_only(),
            },
        );
        // Re-insert pinned messages right after the summary (position 2+).
        // They are placed before the preserved tail so the LLM always sees them.
        let pinned_count = pinned_messages.len();
        for (i, pinned) in pinned_messages.into_iter().enumerate() {
            self.msg.messages.insert(2 + i, pinned);
        }
        // Re-insert active-subgoal messages after pinned messages (#2022 S2 fix).
        // Active-subgoal messages are protected from summarization — they carry the current
        // working context and must not be lost during compaction.
        for (i, active_msg) in active_subgoal_messages.into_iter().enumerate() {
            self.msg.messages.insert(2 + pinned_count + i, active_msg);
        }

        // S1 fix (#2022): rebuild subgoal index map from scratch after drain + reinsert.
        // Arithmetic offset is fragile because the final positions depend on pinned_count
        // and active_subgoal_count. Rebuild is O(subgoals * avg_span) — negligible.
        #[cfg(feature = "context-compression")]
        if self
            .context_manager
            .compression
            .pruning_strategy
            .is_subgoal()
        {
            self.compression
                .subgoal_registry
                .rebuild_after_compaction(&self.msg.messages, compact_end);
        }

        tracing::info!(
            compacted_count,
            summary_tokens = self.metrics.token_counter.count_tokens(&summary),
            "compacted context"
        );

        self.recompute_prompt_tokens();
        self.update_metrics(|m| {
            m.context_compactions += 1;
        });

        if let (Some(memory), Some(cid)) =
            (&self.memory_state.memory, self.memory_state.conversation_id)
        {
            // Persist compaction: mark originals as user_only, insert summary as agent_only.
            // Assumption: the system prompt is always the first (oldest) row for this conversation
            // in SQLite — i.e., ids[0] corresponds to self.msg.messages[0] (the system prompt).
            // This holds for normal sessions but may not hold after cross-session restore if a
            // non-system message was persisted first. MVP assumption; document if changed.
            // oldest_message_ids returns ascending order; ids[1..=compacted_count] are the messages
            // that were drained from self.msg.messages[1..compact_end].
            let sqlite = memory.sqlite();
            let ids = sqlite
                .oldest_message_ids(cid, u32::try_from(compacted_count + 1).unwrap_or(u32::MAX))
                .await;
            match ids {
                Ok(ids) if ids.len() >= 2 => {
                    // ids[0] is the system prompt; compact ids[1..=compacted_count]
                    let start = ids[1];
                    let end = ids[compacted_count.min(ids.len() - 1)];
                    if let Err(e) = sqlite
                        .replace_conversation(cid, start..=end, "system", &summary_content)
                        .await
                    {
                        tracing::warn!("failed to persist compaction in sqlite: {e:#}");
                    } else if let Err(e) = memory.store_session_summary(cid, &summary).await {
                        tracing::warn!("failed to store session summary in Qdrant: {e:#}");
                    }
                }
                Ok(_) => {
                    // Not enough messages in DB — fall back to legacy summary storage
                    if let Err(e) = memory.store_session_summary(cid, &summary).await {
                        tracing::warn!("failed to store session summary: {e:#}");
                    }
                }
                Err(e) => {
                    tracing::warn!("failed to get message ids for compaction: {e:#}");
                    if let Err(e) = memory.store_session_summary(cid, &summary).await {
                        tracing::warn!("failed to store session summary: {e:#}");
                    }
                }
            }
        }

        Ok(CompactionOutcome::Compacted)
    }

    /// Prune tool output bodies.
    ///
    /// Dispatches to scored pruning when `context-compression` is enabled and the configured
    /// pruning strategy is not `Reactive`. Falls back to oldest-first when the feature is
    /// disabled or the strategy is `Reactive`.
    ///
    /// Returns the number of tokens freed.
    pub(in crate::agent) fn prune_tool_outputs(&mut self, min_to_free: usize) -> usize {
        #[cfg(feature = "context-compression")]
        {
            use crate::config::PruningStrategy;
            match &self.context_manager.compression.pruning_strategy {
                PruningStrategy::TaskAware => {
                    return self.prune_tool_outputs_scored(min_to_free);
                }
                PruningStrategy::Mig => {
                    return self.prune_tool_outputs_mig(min_to_free);
                }
                PruningStrategy::Subgoal => {
                    return self.prune_tool_outputs_subgoal(min_to_free);
                }
                PruningStrategy::SubgoalMig => {
                    return self.prune_tool_outputs_subgoal_mig(min_to_free);
                }
                PruningStrategy::Reactive => {} // fall through to oldest-first
            }
        }
        self.prune_tool_outputs_oldest_first(min_to_free)
    }

    /// Oldest-first (Reactive) tool output pruning.
    ///
    /// This is the non-dispatching inner implementation. Called directly by the dispatcher
    /// when strategy is `Reactive` and by scored strategies as their fallback — the latter
    /// avoids the infinite recursion that would occur if they called `prune_tool_outputs`.
    #[allow(clippy::cast_precision_loss)]
    fn prune_tool_outputs_oldest_first(&mut self, min_to_free: usize) -> usize {
        let protect = self.context_manager.prune_protect_tokens;
        let mut tail_tokens = 0usize;
        let mut protection_boundary = self.msg.messages.len();
        if protect > 0 {
            for (i, msg) in self.msg.messages.iter().enumerate().rev() {
                tail_tokens += self.metrics.token_counter.count_message_tokens(msg);
                if tail_tokens >= protect {
                    protection_boundary = i;
                    break;
                }
                if i == 0 {
                    protection_boundary = 0;
                }
            }
        }

        let mut freed = 0usize;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
            .cast_signed();
        for msg in &mut self.msg.messages[..protection_boundary] {
            if freed >= min_to_free {
                break;
            }
            // S1 fix: never prune pinned Knowledge block messages (#1850).
            if msg.metadata.focus_pinned {
                continue;
            }
            let mut modified = false;
            for part in &mut msg.parts {
                if let &mut MessagePart::ToolOutput {
                    ref mut body,
                    ref mut compacted_at,
                    ..
                } = part
                    && compacted_at.is_none()
                    && !body.is_empty()
                {
                    freed += self.metrics.token_counter.count_tokens(body);
                    let ref_notice = extract_overflow_ref(body)
                        .map(|p| format!("[tool output pruned; use read_overflow {p} to retrieve]"))
                        .unwrap_or_default();
                    freed -= self.metrics.token_counter.count_tokens(&ref_notice);
                    *compacted_at = Some(now);
                    *body = ref_notice;
                    modified = true;
                }
            }
            if modified {
                msg.rebuild_content();
            }
        }

        if freed > 0 {
            self.update_metrics(|m| m.tool_output_prunes += 1);
            tracing::info!(freed, protection_boundary, "pruned tool outputs");
        }
        freed
    }

    /// Compute the protection boundary index for `prune_protect_tokens`.
    ///
    /// Messages at or after the returned index must not be evicted. This mirrors the logic in
    /// `prune_tool_outputs_oldest_first` so all pruning paths enforce the same tail protection.
    #[cfg(feature = "context-compression")]
    fn prune_protection_boundary(&self) -> usize {
        let protect = self.context_manager.prune_protect_tokens;
        if protect == 0 {
            return self.msg.messages.len();
        }
        let mut tail_tokens = 0usize;
        let mut boundary = self.msg.messages.len();
        for (i, msg) in self.msg.messages.iter().enumerate().rev() {
            tail_tokens += self.metrics.token_counter.count_message_tokens(msg);
            if tail_tokens >= protect {
                boundary = i;
                break;
            }
            if i == 0 {
                boundary = 0;
            }
        }
        boundary
    }

    /// Task-aware / MIG pruning: score tool outputs by relevance to the current task goal,
    /// then evict lowest-scoring blocks until `min_to_free` tokens are freed.
    ///
    /// Requires `context-compression` feature. Falls back to `prune_tool_outputs()` otherwise.
    ///
    /// ## `SideQuest` interaction contract (S3 from critic review)
    ///
    /// When both `TaskAware` pruning and `SideQuest` are enabled, `SideQuest` is expected to be
    /// disabled by the caller (set `sidequest.enabled = false` when `pruning_strategy` != Reactive).
    /// This is the "Option A" documented in the critic review: the two systems do not share state
    /// at the pruning level. `SideQuest` uses the same `focus_pinned` protection to avoid evicting
    /// Knowledge block content.
    #[cfg(feature = "context-compression")]
    pub(in crate::agent) fn prune_tool_outputs_scored(&mut self, min_to_free: usize) -> usize {
        use crate::agent::compaction_strategy::score_blocks_task_aware;
        use crate::config::PruningStrategy;

        let goal = match &self.context_manager.compression.pruning_strategy {
            PruningStrategy::TaskAware => self.compression.current_task_goal.clone(),
            _ => None,
        };

        let scores = if let Some(ref goal) = goal {
            score_blocks_task_aware(&self.msg.messages, goal, &self.metrics.token_counter)
        } else {
            // No goal available: fall back to oldest-first directly (not through the
            // dispatcher, which would recurse back here — S4 fix).
            return self.prune_tool_outputs_oldest_first(min_to_free);
        };

        if let Some(ref d) = self.debug_state.debug_dumper {
            d.dump_pruning_scores(&scores);
        }

        // Sort ascending by score: lowest relevance first (best eviction candidates)
        let mut sorted_scores = scores;
        sorted_scores.sort_unstable_by(|a, b| {
            a.relevance
                .partial_cmp(&b.relevance)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        let protection_boundary = self.prune_protection_boundary();

        let mut freed = 0usize;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
            .cast_signed();

        let mut pruned_indices = Vec::new();
        for block in &sorted_scores {
            if freed >= min_to_free {
                break;
            }
            // Respect prune_protect_tokens: skip messages in the protected tail.
            if block.msg_index >= protection_boundary {
                continue;
            }
            let msg = &mut self.msg.messages[block.msg_index];
            if msg.metadata.focus_pinned {
                continue;
            }
            let mut modified = false;
            for part in &mut msg.parts {
                if let MessagePart::ToolOutput {
                    body, compacted_at, ..
                } = part
                    && compacted_at.is_none()
                    && !body.is_empty()
                {
                    freed += self.metrics.token_counter.count_tokens(body);
                    let ref_notice = extract_overflow_ref(body)
                        .map(|p| format!("[tool output pruned; use read_overflow {p} to retrieve]"))
                        .unwrap_or_default();
                    freed -= self.metrics.token_counter.count_tokens(&ref_notice);
                    *compacted_at = Some(now);
                    *body = ref_notice;
                    modified = true;
                }
            }
            if modified {
                pruned_indices.push(block.msg_index);
            }
        }

        for &idx in &pruned_indices {
            self.msg.messages[idx].rebuild_content();
        }

        if freed > 0 {
            tracing::info!(
                freed,
                pruned = pruned_indices.len(),
                strategy = "task_aware",
                "task-aware pruned tool outputs"
            );
            self.update_metrics(|m| m.tool_output_prunes += 1);
        }
        freed
    }

    /// MIG-scored pruning. Uses relevance − redundancy scoring to identify the best eviction
    /// candidates. Requires `context-compression` feature.
    #[cfg(feature = "context-compression")]
    pub(in crate::agent) fn prune_tool_outputs_mig(&mut self, min_to_free: usize) -> usize {
        use crate::agent::compaction_strategy::score_blocks_mig;

        let goal = self.compression.current_task_goal.as_deref();
        let mut scores = score_blocks_mig(&self.msg.messages, goal, &self.metrics.token_counter);

        if let Some(ref d) = self.debug_state.debug_dumper {
            d.dump_pruning_scores(&scores);
        }

        // Sort ascending by MIG: most negative MIG = highest eviction priority
        scores.sort_unstable_by(|a, b| {
            a.mig
                .partial_cmp(&b.mig)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        let protection_boundary = self.prune_protection_boundary();

        let mut freed = 0usize;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
            .cast_signed();

        let mut pruned_indices = Vec::new();
        for block in &scores {
            if freed >= min_to_free {
                break;
            }
            // Respect prune_protect_tokens: skip messages in the protected tail.
            if block.msg_index >= protection_boundary {
                continue;
            }
            let msg = &mut self.msg.messages[block.msg_index];
            if msg.metadata.focus_pinned {
                continue;
            }
            let mut modified = false;
            for part in &mut msg.parts {
                if let MessagePart::ToolOutput {
                    body, compacted_at, ..
                } = part
                    && compacted_at.is_none()
                    && !body.is_empty()
                {
                    freed += self.metrics.token_counter.count_tokens(body);
                    let ref_notice = extract_overflow_ref(body)
                        .map(|p| format!("[tool output pruned; use read_overflow {p} to retrieve]"))
                        .unwrap_or_default();
                    freed -= self.metrics.token_counter.count_tokens(&ref_notice);
                    *compacted_at = Some(now);
                    *body = ref_notice;
                    modified = true;
                }
            }
            if modified {
                pruned_indices.push(block.msg_index);
            }
        }

        for &idx in &pruned_indices {
            self.msg.messages[idx].rebuild_content();
        }

        if freed > 0 {
            tracing::info!(
                freed,
                pruned = pruned_indices.len(),
                strategy = "mig",
                "MIG-pruned tool outputs"
            );
            self.update_metrics(|m| m.tool_output_prunes += 1);
        }
        freed
    }

    /// Subgoal-aware pruning: score tool outputs by subgoal tier membership and evict
    /// lowest-scoring blocks (outdated first, then completed, never active).
    ///
    /// Active-subgoal tool outputs receive relevance 1.0 and are effectively protected
    /// from eviction as long as lower-tier outputs can satisfy `min_to_free`.
    #[cfg(feature = "context-compression")]
    pub(in crate::agent) fn prune_tool_outputs_subgoal(&mut self, min_to_free: usize) -> usize {
        use crate::agent::compaction_strategy::score_blocks_subgoal;

        if let Some(ref d) = self.debug_state.debug_dumper {
            d.dump_subgoal_registry(&self.compression.subgoal_registry);
        }

        let scores = score_blocks_subgoal(
            &self.msg.messages,
            &self.compression.subgoal_registry,
            &self.metrics.token_counter,
        );

        if let Some(ref d) = self.debug_state.debug_dumper {
            d.dump_pruning_scores(&scores);
        }

        // Sort ascending: lowest relevance = highest eviction priority.
        let mut sorted = scores;
        sorted.sort_unstable_by(|a, b| {
            a.relevance
                .partial_cmp(&b.relevance)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        self.evict_sorted_blocks(&sorted, min_to_free, "subgoal")
    }

    /// Subgoal + MIG hybrid pruning: combines subgoal tier relevance with pairwise
    /// redundancy scoring (MIG = relevance − redundancy).
    #[cfg(feature = "context-compression")]
    pub(in crate::agent) fn prune_tool_outputs_subgoal_mig(&mut self, min_to_free: usize) -> usize {
        use crate::agent::compaction_strategy::score_blocks_subgoal_mig;

        if let Some(ref d) = self.debug_state.debug_dumper {
            d.dump_subgoal_registry(&self.compression.subgoal_registry);
        }

        let mut scores = score_blocks_subgoal_mig(
            &self.msg.messages,
            &self.compression.subgoal_registry,
            &self.metrics.token_counter,
        );

        if let Some(ref d) = self.debug_state.debug_dumper {
            d.dump_pruning_scores(&scores);
        }

        // Sort ascending by MIG: most negative MIG = highest eviction priority.
        scores.sort_unstable_by(|a, b| {
            a.mig
                .partial_cmp(&b.mig)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        self.evict_sorted_blocks(&scores, min_to_free, "subgoal_mig")
    }

    /// Shared eviction loop: given a sorted `BlockScore` slice (ascending priority = most evictable
    /// first), evict tool outputs until `min_to_free` tokens are freed or all candidates are
    /// exhausted. Returns tokens freed.
    ///
    /// Extracted to eliminate duplicate code between `prune_tool_outputs_scored`,
    /// `prune_tool_outputs_mig`, and the new subgoal pruning variants.
    #[cfg(feature = "context-compression")]
    fn evict_sorted_blocks(
        &mut self,
        sorted_scores: &[crate::agent::compaction_strategy::BlockScore],
        min_to_free: usize,
        strategy: &str,
    ) -> usize {
        let mut freed = 0usize;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
            .cast_signed();

        let mut pruned_indices = Vec::new();
        for block in sorted_scores {
            if freed >= min_to_free {
                break;
            }
            let msg = &mut self.msg.messages[block.msg_index];
            if msg.metadata.focus_pinned {
                continue;
            }
            let mut modified = false;
            for part in &mut msg.parts {
                if let MessagePart::ToolOutput {
                    body, compacted_at, ..
                } = part
                    && compacted_at.is_none()
                    && !body.is_empty()
                {
                    freed += self.metrics.token_counter.count_tokens(body);
                    let ref_notice = extract_overflow_ref(body)
                        .map(|p| format!("[tool output pruned; use read_overflow {p} to retrieve]"))
                        .unwrap_or_default();
                    freed -= self.metrics.token_counter.count_tokens(&ref_notice);
                    *compacted_at = Some(now);
                    *body = ref_notice;
                    modified = true;
                }
            }
            if modified {
                pruned_indices.push(block.msg_index);
            }
        }

        for &idx in &pruned_indices {
            self.msg.messages[idx].rebuild_content();
        }

        if freed > 0 {
            tracing::info!(
                freed,
                pruned = pruned_indices.len(),
                strategy,
                "pruned tool outputs"
            );
            self.update_metrics(|m| m.tool_output_prunes += 1);
        }
        freed
    }

    /// Inline pruning for tool loops: clear tool output bodies from messages
    /// older than the last `keep_recent` messages. Called after each tool iteration
    /// to prevent context growth during long tool loops.
    ///
    /// # Invariant
    ///
    /// This method MUST be called AFTER `maybe_summarize_tool_pair()`. The summarizer
    /// reads `msg.content` to build the LLM prompt; pruning replaces that content with
    /// `"[pruned]"`. Calling prune first would cause the summarizer to produce useless
    /// summaries. After summarization, the processed pair has `deferred_summary` set and
    /// is skipped by `count_unsummarized_pairs`. The pruning loop may still clear their
    /// bodies for token savings, but the content has already been captured in the summary.
    pub(crate) fn prune_stale_tool_outputs(&mut self, keep_recent: usize) -> usize {
        if self.msg.messages.len() <= keep_recent + 1 {
            return 0;
        }
        let boundary = self.msg.messages.len().saturating_sub(keep_recent);
        let mut freed = 0usize;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
            .cast_signed();
        // Skip system prompt (index 0), prune from 1..boundary.
        // Also skip focus-pinned Knowledge block messages (#1850 S1 fix).
        for msg in &mut self.msg.messages[1..boundary] {
            if msg.metadata.focus_pinned {
                continue;
            }
            let mut modified = false;
            for part in &mut msg.parts {
                match part {
                    MessagePart::ToolOutput {
                        body, compacted_at, ..
                    } if compacted_at.is_none() && !body.is_empty() => {
                        freed += self.metrics.token_counter.count_tokens(body);
                        let ref_notice = extract_overflow_ref(body)
                            .map(|p| {
                                format!("[tool output pruned; use read_overflow {p} to retrieve]")
                            })
                            .unwrap_or_default();
                        freed -= self.metrics.token_counter.count_tokens(&ref_notice);
                        *compacted_at = Some(now);
                        *body = ref_notice;
                        modified = true;
                    }
                    MessagePart::ToolResult { content, .. } => {
                        let tokens = self.metrics.token_counter.count_tokens(content);
                        if tokens > 20 {
                            freed += tokens;
                            let ref_notice = extract_overflow_ref(content).map_or_else(
                                || String::from("[pruned]"),
                                |p| {
                                    format!(
                                        "[tool output pruned; use read_overflow {p} to retrieve]"
                                    )
                                },
                            );
                            freed -= self.metrics.token_counter.count_tokens(&ref_notice);
                            *content = ref_notice;
                            modified = true;
                        }
                    }
                    _ => {}
                }
            }
            if modified {
                msg.rebuild_content();
            }
        }
        if freed > 0 {
            self.update_metrics(|m| m.tool_output_prunes += 1);
            tracing::debug!(
                freed,
                boundary,
                keep_recent,
                "inline pruned stale tool outputs"
            );
        }
        freed
    }

    pub(super) fn count_unsummarized_pairs(&self) -> usize {
        let mut count = 0usize;
        let mut i = 1; // skip system prompt
        while i < self.msg.messages.len() {
            let msg = &self.msg.messages[i];
            if !msg.metadata.agent_visible {
                i += 1;
                continue;
            }
            let is_tool_request = msg.role == Role::Assistant
                && msg
                    .parts
                    .iter()
                    .any(|p| matches!(p, MessagePart::ToolUse { .. }));
            if is_tool_request && i + 1 < self.msg.messages.len() {
                let next = &self.msg.messages[i + 1];
                if next.metadata.agent_visible
                    && next.role == Role::User
                    && next.parts.iter().any(|p| {
                        matches!(
                            p,
                            MessagePart::ToolResult { .. } | MessagePart::ToolOutput { .. }
                        )
                    })
                    && next.metadata.deferred_summary.is_none()
                {
                    count += 1;
                    i += 2;
                    continue;
                }
            }
            i += 1;
        }
        count
    }

    /// Find the oldest tool request/response pair that has not yet been summarized.
    ///
    /// Skips pairs where:
    /// - `deferred_summary` is already set (already queued for application), or
    /// - the response content was pruned (all ToolResult/ToolOutput bodies are empty or
    ///   contain only `"[pruned]"`), which would produce a useless summary (IMP-03 fix).
    pub(super) fn find_oldest_unsummarized_pair(&self) -> Option<(usize, usize)> {
        let mut i = 1; // skip system prompt
        while i < self.msg.messages.len() {
            let msg = &self.msg.messages[i];
            if !msg.metadata.agent_visible {
                i += 1;
                continue;
            }
            let is_tool_request = msg.role == Role::Assistant
                && msg
                    .parts
                    .iter()
                    .any(|p| matches!(p, MessagePart::ToolUse { .. }));
            if is_tool_request && i + 1 < self.msg.messages.len() {
                let next = &self.msg.messages[i + 1];
                if next.metadata.agent_visible
                    && next.role == Role::User
                    && next.parts.iter().any(|p| {
                        matches!(
                            p,
                            MessagePart::ToolResult { .. } | MessagePart::ToolOutput { .. }
                        )
                    })
                    && next.metadata.deferred_summary.is_none()
                {
                    // Skip pairs whose response content has been fully pruned — summarizing
                    // "[pruned]" produces a useless result (IMP-03).
                    let all_pruned = next.parts.iter().all(|p| match p {
                        MessagePart::ToolOutput { body, .. } => body.is_empty(),
                        MessagePart::ToolResult { content, .. } => {
                            content.trim() == "[pruned]" || content.is_empty()
                        }
                        _ => true,
                    });
                    if !all_pruned {
                        return Some((i, i + 1));
                    }
                }
            }
            i += 1;
        }
        None
    }

    pub(super) fn count_deferred_summaries(&self) -> usize {
        self.msg
            .messages
            .iter()
            .filter(|m| m.metadata.deferred_summary.is_some())
            .count()
    }

    pub(super) fn build_tool_pair_summary_prompt(req: &Message, res: &Message) -> String {
        format!(
            "Produce a concise but technically precise summary of this tool invocation.\n\
             Preserve all facts that would be needed to continue work without re-running the tool:\n\
             - Tool name and key input parameters (file paths, function names, patterns, line ranges)\n\
             - Exact findings: line numbers, struct/enum/function names, error messages, numeric values\n\
             - Outcome: what was found, changed, created, or confirmed\n\
             Do NOT omit specific identifiers, paths, or numbers — they cannot be recovered later.\n\
             Use 2-4 sentences maximum.\n\n\
             <tool_request>\n{}\n</tool_request>\n\n<tool_response>\n{}\n</tool_response>",
            req.content, res.content
        )
    }

    pub(in crate::agent) async fn maybe_summarize_tool_pair(&mut self) {
        // Drain the entire backlog above cutoff in one turn so that a resumed session
        // with many accumulated pairs catches up before Tier 1 pruning fires.
        let cutoff = self.memory_state.tool_call_cutoff;
        let llm_timeout = std::time::Duration::from_secs(self.runtime.timeouts.llm_seconds);
        let mut summarized = 0usize;
        loop {
            let pair_count = self.count_unsummarized_pairs();
            if pair_count <= cutoff {
                break;
            }
            let Some((req_idx, resp_idx)) = self.find_oldest_unsummarized_pair() else {
                break;
            };
            let prompt = Self::build_tool_pair_summary_prompt(
                &self.msg.messages[req_idx],
                &self.msg.messages[resp_idx],
            );
            let msgs = [Message {
                role: Role::User,
                content: prompt,
                parts: vec![],
                metadata: MessageMetadata::default(),
            }];
            let _ = self.channel.send_status("summarizing output...").await;
            let chat_fut = self.summary_or_primary_provider().chat(&msgs);
            let summary = match tokio::time::timeout(llm_timeout, chat_fut).await {
                Ok(Ok(s)) => s,
                Ok(Err(e)) => {
                    tracing::warn!(%e, "tool pair summarization failed, stopping batch");
                    let _ = self.channel.send_status("").await;
                    break;
                }
                Err(_elapsed) => {
                    tracing::warn!(
                        timeout_secs = self.runtime.timeouts.llm_seconds,
                        "tool pair summarization timed out, stopping batch"
                    );
                    let _ = self.channel.send_status("").await;
                    break;
                }
            };
            // DEFERRED: store summary on response metadata instead of immediately mutating the
            // array. Applied lazily by apply_deferred_summaries() when context pressure rises,
            // preserving the message prefix for Claude API cache hits.
            let summary = super::cap_summary(self.maybe_redact(&summary).into_owned(), 8_000);
            self.msg.messages[resp_idx].metadata.deferred_summary = Some(summary.clone());
            summarized += 1;
            tracing::debug!(
                pair_count,
                cutoff,
                req_idx,
                resp_idx,
                summary_len = summary.len(),
                "deferred tool pair summary stored"
            );
        }
        let _ = self.channel.send_status("").await;
        if summarized > 0 {
            tracing::info!(summarized, "batch-summarized tool pairs above cutoff");
        }
    }

    /// Batch-apply all pending deferred tool pair summaries.
    ///
    /// Processes in reverse index order (highest first) so that inserting a summary message
    /// at `resp_idx + 1` does not shift the indices of not-yet-processed pairs.
    ///
    /// Returns the number of summaries applied.
    pub(in crate::agent) fn apply_deferred_summaries(&mut self) -> usize {
        // Phase 1: collect (resp_idx, req_idx, summary) for all messages with deferred_summary.
        let mut targets: Vec<(usize, usize, String)> = Vec::new();
        for i in 1..self.msg.messages.len() {
            if self.msg.messages[i].metadata.deferred_summary.is_none() {
                continue;
            }
            // Verify the structural invariant: tool response preceded by matching tool request.
            if self.msg.messages[i].role == Role::User
                && self.msg.messages[i].metadata.agent_visible
                && i > 0
                && self.msg.messages[i - 1].role == Role::Assistant
                && self.msg.messages[i - 1].metadata.agent_visible
                && self.msg.messages[i - 1]
                    .parts
                    .iter()
                    .any(|p| matches!(p, MessagePart::ToolUse { .. }))
            {
                let summary = self.msg.messages[i]
                    .metadata
                    .deferred_summary
                    .clone()
                    .expect("checked above");
                targets.push((i, i - 1, summary));
            } else {
                tracing::warn!(
                    resp_idx = i,
                    "deferred summary orphaned: req message not found at resp_idx={i}"
                );
            }
        }

        if targets.is_empty() {
            return 0;
        }

        // Phase 2: sort descending by resp_idx so insertions do not invalidate lower indices.
        targets.sort_by(|a, b| b.0.cmp(&a.0));

        let count = targets.len();
        for (resp_idx, req_idx, summary) in targets {
            let req_db_id = self.msg.messages[req_idx].metadata.db_id;
            let resp_db_id = self.msg.messages[resp_idx].metadata.db_id;

            self.msg.messages[req_idx].metadata.agent_visible = false;
            self.msg.messages[resp_idx].metadata.agent_visible = false;
            self.msg.messages[resp_idx].metadata.deferred_summary = None;

            if let (Some(req_id), Some(resp_id)) = (req_db_id, resp_db_id) {
                self.deferred_db_hide_ids.push(req_id);
                self.deferred_db_hide_ids.push(resp_id);
                self.deferred_db_summaries.push(summary.clone());
            }

            let content = format!("[tool summary] {summary}");
            let summary_msg = Message {
                role: Role::Assistant,
                content,
                parts: vec![MessagePart::Summary { text: summary }],
                metadata: MessageMetadata::agent_only(),
            };
            self.msg.messages.insert(resp_idx + 1, summary_msg);
        }

        self.recompute_prompt_tokens();
        tracing::info!(count, "applied deferred tool pair summaries");
        count
    }

    pub(in crate::agent) async fn flush_deferred_summaries(&mut self) {
        if self.deferred_db_hide_ids.is_empty() {
            return;
        }
        let (Some(memory), Some(cid)) =
            (&self.memory_state.memory, self.memory_state.conversation_id)
        else {
            self.deferred_db_hide_ids.clear();
            self.deferred_db_summaries.clear();
            return;
        };
        let hide_ids = std::mem::take(&mut self.deferred_db_hide_ids);
        let summaries = std::mem::take(&mut self.deferred_db_summaries);
        if let Err(e) = memory
            .sqlite()
            .apply_tool_pair_summaries(cid, &hide_ids, &summaries)
            .await
        {
            tracing::warn!(error = %e, "failed to flush deferred summary batch to DB");
        }
    }

    /// Apply deferred summaries if context usage exceeds the soft compaction threshold,
    /// or when enough summaries have accumulated to prevent content loss from pruning.
    ///
    /// Two triggers:
    /// - Token pressure: `cached_prompt_tokens > budget * soft_compaction_threshold`
    /// - Count pressure: `pending >= tool_call_cutoff` (guards against pruning replacing
    ///   summaries with `[pruned]` when `prepare_context` recomputes tokens to a low value)
    ///
    /// This is Tier 0 — a pure in-memory operation with no LLM call. Intentionally
    /// does NOT set `compacted_this_turn` so that proactive/reactive compaction may
    /// also fire in the same turn if tokens remain above their respective thresholds.
    /// Called from tool execution loops on every iteration to apply summaries eagerly.
    pub(in crate::agent) fn maybe_apply_deferred_summaries(&mut self) {
        let pending = self.count_deferred_summaries();
        if pending == 0 {
            return;
        }
        let token_pressure = matches!(
            self.compaction_tier(),
            CompactionTier::Soft | CompactionTier::Hard
        );
        let count_pressure = pending >= self.memory_state.tool_call_cutoff;
        if !token_pressure && !count_pressure {
            return;
        }
        let applied = self.apply_deferred_summaries();
        if applied > 0 {
            tracing::info!(
                applied,
                token_pressure,
                count_pressure,
                "tier-0: batch-applied deferred tool summaries"
            );
        }
    }

    /// Tiered compaction: Soft tier prunes tool outputs + applies deferred summaries (no LLM),
    /// Hard tier falls back to full LLM summarization.
    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::too_many_lines
    )]
    pub(in crate::agent) async fn maybe_compact(
        &mut self,
    ) -> Result<(), super::super::error::AgentError> {
        // Increment the turn counter unconditionally so every user-message turn is counted
        // regardless of early-return guards (exhaustion, server compaction, cooldown).
        if let Some(ref mut count) = self.context_manager.turns_since_last_hard_compaction {
            *count += 1;
        }

        // Guard 3 — Exhaustion: stop compaction permanently when it cannot reduce context.
        // One-shot warning: flip warned → true on first visit, no-op on subsequent calls.
        if let crate::agent::context_manager::CompactionState::Exhausted { ref mut warned } =
            self.context_manager.compaction
            && !*warned
        {
            *warned = true;
            tracing::warn!("compaction exhausted: context budget too tight for this session");
            let _ = self
                .channel
                .send(
                    "Warning: context budget is too tight — compaction cannot free enough \
                     space. Consider increasing [memory] context_budget_tokens or starting \
                     a new session.",
                )
                .await;
        }
        if self.context_manager.compaction.is_exhausted() {
            return Ok(());
        }

        // S1: skip client-side compaction when server compaction is active — unless context
        // has grown past 95% of the budget without a server compaction event (safety fallback).
        if self.providers.server_compaction_active {
            let budget = self
                .context_manager
                .budget
                .as_ref()
                .map_or(0, ContextBudget::max_tokens);
            if budget > 0 {
                let total_tokens: usize = self
                    .msg
                    .messages
                    .iter()
                    .map(|m| self.metrics.token_counter.count_message_tokens(m))
                    .sum();
                let fallback_threshold = budget * 95 / 100;
                if total_tokens < fallback_threshold {
                    return Ok(());
                }
                tracing::warn!(
                    total_tokens,
                    fallback_threshold,
                    "server compaction active but context at 95%+ — falling back to client-side"
                );
            } else {
                return Ok(());
            }
        }
        // Skip if hard compaction already ran this turn (CRIT-03).
        if self.context_manager.compaction.is_compacted_this_turn() {
            return Ok(());
        }
        // Guard 1 — Cooldown: skip Hard-tier LLM compaction for N turns after the last successful
        // compaction. Soft compaction (pruning only) is still allowed during cooldown.
        let in_cooldown = self.context_manager.compaction.cooldown_remaining() > 0;
        if in_cooldown {
            // Decrement the Cooling counter in place.
            if let crate::agent::context_manager::CompactionState::Cooling {
                ref mut turns_remaining,
            } = self.context_manager.compaction
            {
                *turns_remaining -= 1;
                if *turns_remaining == 0 {
                    self.context_manager.compaction =
                        crate::agent::context_manager::CompactionState::Ready;
                }
            }
        }

        match self.compaction_tier() {
            CompactionTier::None => Ok(()),
            CompactionTier::Soft => {
                let _ = self.channel.send_status("soft compacting context...").await;

                // Step 0 (context-compression): apply any completed background goal extraction
                // and schedule a new one if the user message has changed (#1909, #2022).
                #[cfg(feature = "context-compression")]
                {
                    use crate::config::PruningStrategy;
                    match &self.context_manager.compression.pruning_strategy {
                        PruningStrategy::Subgoal | PruningStrategy::SubgoalMig => {
                            self.maybe_refresh_subgoal();
                        }
                        _ => self.maybe_refresh_task_goal(),
                    }
                }

                // Step 1: apply deferred tool summaries (free tokens without LLM).
                #[cfg(feature = "context-compression")]
                let applied = self.apply_deferred_summaries();
                #[cfg(not(feature = "context-compression"))]
                let _ = self.apply_deferred_summaries();

                // Step 1b (S5 fix): rebuild subgoal index map if deferred summaries were applied.
                // Deferred summaries insert messages (shifting indices), invalidating msg_to_subgoal.
                #[cfg(feature = "context-compression")]
                if applied > 0
                    && self
                        .context_manager
                        .compression
                        .pruning_strategy
                        .is_subgoal()
                {
                    self.compression.subgoal_registry.rebuild_after_compaction(
                        &self.msg.messages,
                        0, // 0 = no drain, just repair shifted indices
                    );
                }

                // Step 2: prune tool outputs down to soft threshold.
                let budget = self
                    .context_manager
                    .budget
                    .as_ref()
                    .map_or(0, ContextBudget::max_tokens);
                let soft_threshold =
                    (budget as f32 * self.context_manager.soft_compaction_threshold) as usize;
                let cached =
                    usize::try_from(self.providers.cached_prompt_tokens).unwrap_or(usize::MAX);
                let min_to_free = cached.saturating_sub(soft_threshold);
                if min_to_free > 0 {
                    self.prune_tool_outputs(min_to_free);
                }

                let _ = self.channel.send_status("").await;
                tracing::info!(
                    cached_tokens = self.providers.cached_prompt_tokens,
                    soft_threshold,
                    "soft compaction complete"
                );
                // Soft compaction does NOT set compacted_this_turn, allowing Hard to fire
                // in the same turn if context is still above the hard threshold.
                Ok(())
            }
            CompactionTier::Hard => {
                // Track hard compaction event: finalize the previous segment's turn count
                // and start a new one. Counted regardless of cooldown — captures pressure,
                // not just action. When compaction_hard_count == 0, compaction_turns_after_hard
                // is expected to be empty.
                if let Some(turns) = self.context_manager.turns_since_last_hard_compaction {
                    self.update_metrics(|m| {
                        m.compaction_turns_after_hard.push(turns);
                    });
                }
                self.context_manager.turns_since_last_hard_compaction = Some(0);
                self.update_metrics(|m| {
                    m.compaction_hard_count += 1;
                });

                // Cooldown guard: skip LLM summarization while cooling down.
                if in_cooldown {
                    tracing::debug!(
                        turns_remaining = self.context_manager.compaction.cooldown_remaining(),
                        "hard compaction skipped: cooldown active"
                    );
                    return Ok(());
                }

                let budget = self
                    .context_manager
                    .budget
                    .as_ref()
                    .map_or(0, ContextBudget::max_tokens);
                let hard_threshold =
                    (budget as f32 * self.context_manager.hard_compaction_threshold) as usize;
                let cached =
                    usize::try_from(self.providers.cached_prompt_tokens).unwrap_or(usize::MAX);
                let min_to_free = cached.saturating_sub(hard_threshold);

                let _ = self.channel.send_status("compacting context...").await;

                // Step 1: apply deferred summaries first (free tokens without LLM).
                self.apply_deferred_summaries();

                // Step 2: prune tool outputs.
                let freed = self.prune_tool_outputs(min_to_free);
                if freed >= min_to_free {
                    tracing::info!(freed, "hard compaction: pruning sufficient");
                    self.context_manager.compaction =
                        crate::agent::context_manager::CompactionState::CompactedThisTurn {
                            cooldown: self.context_manager.compaction_cooldown_turns,
                        };
                    self.flush_deferred_summaries().await;
                    let _ = self.channel.send_status("").await;
                    return Ok(());
                }

                // Step 3: Guard 2 — Counterproductive: check if there are enough messages
                // to make LLM summarization worthwhile.
                let preserve_tail = self.context_manager.compaction_preserve_tail;
                let compactable = self.msg.messages.len().saturating_sub(preserve_tail + 1);
                if compactable <= 1 {
                    tracing::warn!(
                        compactable,
                        "hard compaction: too few messages to compact, marking exhausted"
                    );
                    // Only reachable from Ready state (Cooling is guarded by in_cooldown above).
                    self.context_manager.compaction =
                        crate::agent::context_manager::CompactionState::Exhausted { warned: false };
                    let _ = self.channel.send_status("").await;
                    return Ok(());
                }

                // Step 4: fall back to full LLM summarization.
                tracing::info!(
                    freed,
                    min_to_free,
                    "hard compaction: pruning insufficient, falling back to LLM summarization"
                );
                let tokens_before = self.providers.cached_prompt_tokens;
                let outcome = self.compact_context().await?;
                match outcome {
                    CompactionOutcome::ProbeRejected => {
                        // Probe rejected the summary. This is NOT exhaustion — the compactor
                        // can still summarize, but the summary was too lossy.
                        // Set cooldown to prevent immediate retry, but do NOT mark Exhausted.
                        tracing::info!("compaction probe rejected summary — setting cooldown");
                        self.context_manager.compaction =
                            crate::agent::context_manager::CompactionState::CompactedThisTurn {
                                cooldown: self.context_manager.compaction_cooldown_turns,
                            };
                    }
                    CompactionOutcome::Compacted => {
                        // Guard 2 — Counterproductive: net freed tokens is zero (summary ate all
                        // freed space — no net reduction).
                        let freed_tokens =
                            tokens_before.saturating_sub(self.providers.cached_prompt_tokens);
                        if freed_tokens == 0 {
                            tracing::warn!(
                                "hard compaction: summary consumed all freed tokens — no net \
                                 reduction, marking exhausted"
                            );
                            // Only reachable from Ready state (Cooling is guarded by in_cooldown).
                            self.context_manager.compaction =
                                crate::agent::context_manager::CompactionState::Exhausted {
                                    warned: false,
                                };
                            let _ = self.channel.send_status("").await;
                            return Ok(());
                        }
                        // Guard 3 — Still above threshold: compaction freed some tokens but context
                        // remains above the hard threshold; further LLM attempts are unlikely to help.
                        if matches!(self.compaction_tier(), CompactionTier::Hard) {
                            tracing::warn!(
                                freed_tokens,
                                "hard compaction: context still above hard threshold after \
                                 compaction, marking exhausted"
                            );
                            // Only reachable from Ready state (Cooling is guarded by in_cooldown).
                            self.context_manager.compaction =
                                crate::agent::context_manager::CompactionState::Exhausted {
                                    warned: false,
                                };
                            let _ = self.channel.send_status("").await;
                            return Ok(());
                        }
                        self.context_manager.compaction =
                            crate::agent::context_manager::CompactionState::CompactedThisTurn {
                                cooldown: self.context_manager.compaction_cooldown_turns,
                            };
                    }
                    CompactionOutcome::NoChange => {
                        // compact_context() decided there was nothing to compact.
                        // The compactable <= 1 guard above should have caught this, but handle
                        // it gracefully if the messages changed during the async call.
                    }
                }
                let _ = self.channel.send_status("").await;
                Ok(())
            }
        }
    }

    /// Soft-only compaction for mid-iteration use inside tool execution loops.
    ///
    /// Applies deferred tool summaries and prunes tool outputs down to the soft threshold.
    /// Never triggers Hard tier (no LLM call), never increments
    /// `turns_since_last_hard_compaction`, and never decrements the cooldown counter.
    /// Returns immediately when `compacted_this_turn` is set (hard compaction ran earlier
    /// in this turn) or when context usage is below the soft threshold.
    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss
    )]
    pub(in crate::agent) fn maybe_soft_compact_mid_iteration(&mut self) {
        if self.context_manager.compaction.is_compacted_this_turn() {
            return;
        }
        if !matches!(
            self.compaction_tier(),
            CompactionTier::Soft | CompactionTier::Hard
        ) {
            return;
        }
        let budget = self
            .context_manager
            .budget
            .as_ref()
            .map_or(0, ContextBudget::max_tokens);
        let soft_threshold =
            (budget as f32 * self.context_manager.soft_compaction_threshold) as usize;
        let cached = usize::try_from(self.providers.cached_prompt_tokens).unwrap_or(usize::MAX);
        // Step 1: apply deferred summaries.
        self.apply_deferred_summaries();
        // Step 2: prune tool outputs down to soft threshold.
        let min_to_free = cached.saturating_sub(soft_threshold);
        if min_to_free > 0 {
            self.prune_tool_outputs(min_to_free);
        }
        tracing::debug!(
            cached_tokens = self.providers.cached_prompt_tokens,
            soft_threshold,
            "mid-iteration soft compaction complete"
        );
    }

    /// Proactive context compression: fires before reactive compaction when context exceeds
    /// the configured `threshold_tokens`. Mutually exclusive with reactive compaction per turn
    /// (guarded by `compacted_this_turn`).
    pub(in crate::agent) async fn maybe_proactive_compress(
        &mut self,
    ) -> Result<(), super::super::error::AgentError> {
        // S1: skip proactive compression when server compaction is active — unless context
        // has grown past 95% of the budget without a server compaction event (safety fallback).
        if self.providers.server_compaction_active {
            let budget = self
                .context_manager
                .budget
                .as_ref()
                .map_or(0, ContextBudget::max_tokens);
            if budget > 0 {
                let fallback_threshold = (budget * 95 / 100) as u64;
                if self.providers.cached_prompt_tokens <= fallback_threshold {
                    return Ok(());
                }
                tracing::warn!(
                    cached_prompt_tokens = self.providers.cached_prompt_tokens,
                    fallback_threshold,
                    "server compaction active but context at 95%+ — falling back to client-side proactive"
                );
            } else {
                return Ok(());
            }
        }
        let Some((_threshold, max_summary_tokens)) = self
            .context_manager
            .should_proactively_compress(self.providers.cached_prompt_tokens)
        else {
            return Ok(());
        };

        let tokens_before = self.providers.cached_prompt_tokens;
        let _ = self.channel.send_status("compressing context...").await;
        tracing::info!(
            max_summary_tokens,
            cached_tokens = tokens_before,
            "proactive compression triggered"
        );

        let result = self
            .compact_context_with_budget(Some(max_summary_tokens))
            .await;

        if result.is_ok() {
            // Proactive compression does not impose a post-compaction cooldown.
            self.context_manager.compaction =
                crate::agent::context_manager::CompactionState::CompactedThisTurn { cooldown: 0 };
            let tokens_saved = tokens_before.saturating_sub(self.providers.cached_prompt_tokens);
            self.update_metrics(|m| {
                m.compression_events += 1;
                m.compression_tokens_saved += tokens_saved;
            });
        }

        let _ = self.channel.send_status("").await;
        result
    }

    /// Run LLM compaction with an optional chunk budget hint for the summary.
    ///
    /// When `max_summary_tokens` is `Some(n)`, the chunk budget used by `chunk_messages`
    /// is capped at `n`, limiting how much context is summarized per LLM call.
    async fn compact_context_with_budget(
        &mut self,
        max_summary_tokens: Option<usize>,
    ) -> Result<(), super::super::error::AgentError> {
        // Force-apply any pending deferred summaries before draining to avoid losing them (CRIT-01).
        let _ = self.apply_deferred_summaries();

        let preserve_tail = self.context_manager.compaction_preserve_tail;

        if self.msg.messages.len() <= preserve_tail + 1 {
            return Ok(());
        }

        let compact_end = self.msg.messages.len() - preserve_tail;
        let to_compact = &self.msg.messages[1..compact_end];
        if to_compact.is_empty() {
            return Ok(());
        }

        let summary = self
            .summarize_messages_with_budget(to_compact, max_summary_tokens)
            .await?;

        let compacted_count = to_compact.len();
        let summary_content =
            format!("[conversation summary — {compacted_count} messages compacted]\n{summary}");
        self.msg.messages.drain(1..compact_end);
        self.msg.messages.insert(
            1,
            Message {
                role: Role::System,
                content: summary_content.clone(),
                parts: vec![],
                metadata: zeph_llm::provider::MessageMetadata::agent_only(),
            },
        );

        tracing::info!(
            compacted_count,
            summary_tokens = self.metrics.token_counter.count_tokens(&summary),
            "compacted context (with budget)"
        );

        self.recompute_prompt_tokens();
        self.update_metrics(|m| {
            m.context_compactions += 1;
        });

        if let (Some(memory), Some(cid)) =
            (&self.memory_state.memory, self.memory_state.conversation_id)
        {
            let sqlite = memory.sqlite();
            let ids = sqlite
                .oldest_message_ids(cid, u32::try_from(compacted_count + 1).unwrap_or(u32::MAX))
                .await;
            match ids {
                Ok(ids) if ids.len() >= 2 => {
                    let start = ids[1];
                    let end = ids[compacted_count.min(ids.len() - 1)];
                    if let Err(e) = sqlite
                        .replace_conversation(cid, start..=end, "system", &summary_content)
                        .await
                    {
                        tracing::warn!("failed to persist compaction in sqlite: {e:#}");
                    } else if let Err(e) = memory.store_session_summary(cid, &summary).await {
                        tracing::warn!("failed to store session summary in Qdrant: {e:#}");
                    }
                }
                Ok(_) => {
                    if let Err(e) = memory.store_session_summary(cid, &summary).await {
                        tracing::warn!("failed to store session summary: {e:#}");
                    }
                }
                Err(e) => {
                    tracing::warn!("failed to get message ids for compaction: {e:#}");
                    if let Err(e) = memory.store_session_summary(cid, &summary).await {
                        tracing::warn!("failed to store session summary: {e:#}");
                    }
                }
            }
        }

        Ok(())
    }

    /// Summarize messages with an optional chunk-size budget.
    ///
    /// When `chunk_budget` is `Some(n)`, the token budget per chunk is `n` instead of
    /// the default 4096. This indirectly limits how long summaries are by reducing
    /// how much context is fed to each LLM call.
    async fn summarize_messages_with_budget(
        &self,
        messages: &[Message],
        chunk_budget: Option<usize>,
    ) -> Result<String, super::super::error::AgentError> {
        // Try direct summarization first
        let chunk_token_budget = chunk_budget.unwrap_or(4096);
        let oversized_threshold = chunk_token_budget / 2;

        #[cfg(feature = "compression-guidelines")]
        let guidelines = self.load_compression_guidelines_if_enabled().await;
        #[cfg(not(feature = "compression-guidelines"))]
        let guidelines = String::new();

        let chunks = super::chunk_messages(
            messages,
            chunk_token_budget,
            oversized_threshold,
            &self.metrics.token_counter,
        );

        let llm_timeout = std::time::Duration::from_secs(self.runtime.timeouts.llm_seconds);

        let try_llm = |msgs: &[Message]| {
            let prompt = Self::build_chunk_prompt(msgs, &guidelines);
            let provider = self.summary_or_primary_provider().clone();
            async move {
                tokio::time::timeout(
                    llm_timeout,
                    provider.chat(&[Message {
                        role: Role::User,
                        content: prompt,
                        parts: vec![],
                        metadata: zeph_llm::provider::MessageMetadata::default(),
                    }]),
                )
                .await
                .map_err(|_| zeph_llm::LlmError::Timeout)?
            }
        };

        // For single chunk, summarize directly
        if chunks.len() <= 1 {
            // Structured path for single-chunk (IMP-02): mirrors summarize_messages().
            if self.memory_state.structured_summaries {
                match self.try_summarize_structured(messages, &guidelines).await {
                    Ok(anchored) => {
                        if let Some(ref d) = self.debug_state.debug_dumper {
                            d.dump_anchored_summary(&anchored, false, &self.metrics.token_counter);
                        }
                        return Ok(super::cap_summary(anchored.to_markdown(), 16_000));
                    }
                    Err(e) => {
                        tracing::warn!(
                            error = %e,
                            "structured summarization (budget path) failed, falling back to prose"
                        );
                        if let Some(ref d) = self.debug_state.debug_dumper {
                            let empty = AnchoredSummary {
                                session_intent: String::new(),
                                files_modified: vec![],
                                decisions_made: vec![],
                                open_questions: vec![],
                                next_steps: vec![],
                            };
                            d.dump_anchored_summary(&empty, true, &self.metrics.token_counter);
                        }
                    }
                }
            }

            match try_llm(messages).await {
                Ok(s) => {
                    // SEC-02: cap summary length to avoid LLM output expanding context.
                    // Estimate 4 chars per token; cap at 2× the requested budget or 8000 tokens.
                    let cap_chars = chunk_budget.unwrap_or(8_000).saturating_mul(8);
                    return Ok(super::cap_summary(s, cap_chars));
                }
                Err(e) if !e.is_context_length_error() => return Err(e.into()),
                Err(_) => {
                    tracing::warn!(
                        "summarization hit context length error, using metadata fallback"
                    );
                }
            }
            return Ok(Self::build_metadata_summary(messages));
        }

        // Multi-chunk: use the existing summarize_messages logic (chunk_budget only applied to
        // chunk splitting above; consolidated summary uses the default path)
        self.summarize_messages(messages, &guidelines).await
    }

    /// Refresh the cached task goal when the last user message has changed (#1850, #1909).
    ///
    /// Two-phase non-blocking design (mirrors `maybe_sidequest_eviction`):
    ///
    /// - Phase 1 (apply): if a background extraction task spawned last compaction has finished,
    ///   apply its result to `current_task_goal`.
    /// - Phase 2 (schedule): if the user message hash has changed and no task is in-flight,
    ///   spawn a new background `tokio::spawn` for goal extraction. The current compaction uses
    ///   whatever goal was cached from the previous extraction — never blocks.
    ///
    /// This eliminates the 5-second latency spike on every Soft tier compaction that made
    /// `task_aware`/`mig` strategies non-functional for cloud LLM providers.
    #[cfg(feature = "context-compression")]
    #[allow(clippy::too_many_lines)]
    pub(in crate::agent) fn maybe_refresh_task_goal(&mut self) {
        use std::hash::Hash as _;

        use crate::config::PruningStrategy;

        // Only needed when a task-aware or MIG strategy is active.
        match &self.context_manager.compression.pruning_strategy {
            PruningStrategy::Reactive | PruningStrategy::Subgoal | PruningStrategy::SubgoalMig => {
                return;
            }
            PruningStrategy::TaskAware | PruningStrategy::Mig => {}
        }

        // Phase 1: apply background result if the task has completed.
        if self
            .compression
            .pending_task_goal
            .as_ref()
            .is_some_and(tokio::task::JoinHandle::is_finished)
        {
            use futures::FutureExt as _;
            if let Some(handle) = self.compression.pending_task_goal.take() {
                if let Some(Ok(Some(goal))) = handle.now_or_never() {
                    tracing::debug!("extract_task_goal: background result applied");
                    self.compression.current_task_goal = Some(goal);
                }
                // Clear spinner on ALL completion paths (success, None result, or task panic).
                if let Some(ref tx) = self.session.status_tx {
                    let _ = tx.send(String::new());
                }
            }
        }

        // Phase 2: do not spawn a second task while one is already in-flight.
        if self.compression.pending_task_goal.is_some() {
            return;
        }

        // Find the last user message content.
        let last_user_content = self
            .msg
            .messages
            .iter()
            .rev()
            .find(|m| m.role == zeph_llm::provider::Role::User)
            .map(|m| m.content.as_str())
            .unwrap_or_default();

        if last_user_content.is_empty() {
            return;
        }

        // Compute a hash of the last user message to detect changes (S5).
        let hash = {
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            last_user_content.hash(&mut hasher);
            std::hash::Hasher::finish(&hasher)
        };

        // Cache hit: extraction already scheduled or completed for this user message.
        if self.compression.task_goal_user_msg_hash == Some(hash) {
            return;
        }

        // Cache miss: update hash and spawn background extraction.
        self.compression.task_goal_user_msg_hash = Some(hash);

        // Clone only the data needed by the background task (avoids borrowing self).
        let recent: Vec<(zeph_llm::provider::Role, String)> = self
            .msg
            .messages
            .iter()
            .filter(|m| {
                matches!(
                    m.role,
                    zeph_llm::provider::Role::User | zeph_llm::provider::Role::Assistant
                )
            })
            .rev()
            .take(10)
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .map(|m| (m.role, m.content.clone()))
            .collect();

        let provider = self.summary_or_primary_provider().clone();

        let handle = tokio::spawn(async move {
            use zeph_llm::provider::{Message, MessageMetadata, Role};

            if recent.is_empty() {
                return None;
            }

            let mut context_text = String::new();
            for (role, content) in &recent {
                let role_str = match role {
                    Role::User => "user",
                    Role::Assistant => "assistant",
                    Role::System => "system",
                };
                let preview = if content.len() > 300 {
                    let end = content.floor_char_boundary(300);
                    &content[..end]
                } else {
                    content.as_str()
                };
                let _ =
                    std::fmt::write(&mut context_text, format_args!("[{role_str}]: {preview}\n"));
            }

            let prompt = format!(
                "Extract the current task goal from this conversation excerpt in one concise \
                 sentence.\nFocus on what the user is trying to accomplish right now.\n\
                 Respond with only the goal sentence, no preamble.\n\n\
                 <conversation>\n{context_text}</conversation>"
            );

            let msgs = [Message {
                role: Role::User,
                content: prompt,
                parts: vec![],
                metadata: MessageMetadata::default(),
            }];

            match tokio::time::timeout(std::time::Duration::from_secs(30), provider.chat(&msgs))
                .await
            {
                Ok(Ok(goal)) => {
                    let trimmed = goal.trim();
                    if trimmed.is_empty() {
                        None
                    } else {
                        const MAX_GOAL_CHARS: usize = 500;
                        let capped = if trimmed.len() > MAX_GOAL_CHARS {
                            tracing::warn!(
                                len = trimmed.len(),
                                "extract_task_goal: LLM returned oversized goal; truncating to {MAX_GOAL_CHARS} chars"
                            );
                            let end = trimmed.floor_char_boundary(MAX_GOAL_CHARS);
                            &trimmed[..end]
                        } else {
                            trimmed
                        };
                        Some(capped.to_string())
                    }
                }
                Ok(Err(e)) => {
                    tracing::debug!("extract_task_goal: LLM error: {e:#}");
                    None
                }
                Err(_) => {
                    tracing::debug!("extract_task_goal: timed out");
                    None
                }
            }
        });

        // TODO(I3): this JoinHandle is never `.abort()`ed on agent shutdown. The background task
        // will run to completion (or until the 30-second timeout) even after the agent is dropped.
        // Proper cancellation requires surfacing the handle to the shutdown path — tracked as a
        // separate issue (background tasks not cancelled on agent shutdown).
        self.compression.pending_task_goal = Some(handle);
        tracing::debug!("extract_task_goal: background task spawned");
        if let Some(ref tx) = self.session.status_tx {
            let _ = tx.send("Extracting task goal...".into());
        }
    }

    /// Refresh the subgoal registry when the last user message has changed (#2022).
    ///
    /// Mirrors the two-phase `maybe_refresh_task_goal` pattern exactly:
    ///
    /// - Phase 1 (apply): if the background extraction task from last turn has finished,
    ///   parse the result and update the subgoal registry.
    /// - Phase 2 (schedule): if the user message hash has changed and no task is in-flight,
    ///   spawn a new background extraction. Current compaction uses the cached registry state.
    ///
    /// Transition detection: the LLM's `COMPLETED:` signal drives transitions (S3 fix).
    /// When `COMPLETED: NONE`, the same subgoal continues (`extend_active`).
    /// When `COMPLETED:` is non-NONE, a new subgoal is created (`complete_active` + `push_active`).
    #[cfg(feature = "context-compression")]
    #[allow(clippy::too_many_lines)]
    pub(in crate::agent) fn maybe_refresh_subgoal(&mut self) {
        use std::hash::Hash as _;

        use crate::config::PruningStrategy;

        // Only needed when a subgoal-aware strategy is active.
        match &self.context_manager.compression.pruning_strategy {
            PruningStrategy::Subgoal | PruningStrategy::SubgoalMig => {}
            _ => return,
        }

        let msg_len = self.msg.messages.len();

        // Phase 1: apply background result if the task has completed.
        if self
            .compression
            .pending_subgoal
            .as_ref()
            .is_some_and(tokio::task::JoinHandle::is_finished)
        {
            use futures::FutureExt as _;
            if let Some(handle) = self.compression.pending_subgoal.take() {
                if let Some(Ok(Some(result))) = handle.now_or_never() {
                    // Detect subgoal transition via LLM signal (S3 fix).
                    let is_transition = result.completed.is_some();

                    if is_transition {
                        // Complete the current active subgoal and start a new one.
                        if let Some(completed_desc) = &result.completed {
                            tracing::debug!(
                                completed = completed_desc.as_str(),
                                "subgoal transition detected"
                            );
                        }
                        self.compression
                            .subgoal_registry
                            .complete_active(msg_len.saturating_sub(1));
                        let new_id = self
                            .compression
                            .subgoal_registry
                            .push_active(result.current.clone(), msg_len.saturating_sub(1));
                        self.compression
                            .subgoal_registry
                            .extend_active(msg_len.saturating_sub(1));
                        tracing::debug!(
                            current = result.current.as_str(),
                            id = new_id.0,
                            "new active subgoal registered"
                        );
                    } else {
                        // Same subgoal continues — extend or create first subgoal.
                        let is_first = self.compression.subgoal_registry.subgoals.is_empty();
                        if is_first {
                            // First extraction result: create initial subgoal.
                            let id = self
                                .compression
                                .subgoal_registry
                                .push_active(result.current.clone(), msg_len.saturating_sub(1));
                            // S4 fix: retroactively tag all pre-extraction messages [1..msg_len-1].
                            if msg_len > 2 {
                                self.compression
                                    .subgoal_registry
                                    .tag_range(1, msg_len - 2, id);
                            }
                            self.compression
                                .subgoal_registry
                                .extend_active(msg_len.saturating_sub(1));
                            tracing::debug!(
                                current = result.current.as_str(),
                                id = id.0,
                                retroactive_msgs = msg_len.saturating_sub(2),
                                "first subgoal registered with retroactive tagging"
                            );
                        } else {
                            // Extend existing active subgoal.
                            self.compression
                                .subgoal_registry
                                .extend_active(msg_len.saturating_sub(1));
                            tracing::debug!(
                                current = result.current.as_str(),
                                "active subgoal extended"
                            );
                        }
                    }
                }
                // Clear spinner on ALL completion paths (success, None, or panic).
                if let Some(ref tx) = self.session.status_tx {
                    let _ = tx.send(String::new());
                }
            }
        }

        // Phase 2: do not spawn a second task while one is in-flight.
        if self.compression.pending_subgoal.is_some() {
            return;
        }

        // Find the last user message content and check for hash change.
        let last_user_content = self
            .msg
            .messages
            .iter()
            .rev()
            .find(|m| m.role == zeph_llm::provider::Role::User && m.metadata.agent_visible)
            .map(|m| m.content.as_str())
            .unwrap_or_default();

        if last_user_content.is_empty() {
            return;
        }

        let hash = {
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            last_user_content.hash(&mut hasher);
            std::hash::Hasher::finish(&hasher)
        };

        if self.compression.subgoal_user_msg_hash == Some(hash) {
            return;
        }
        self.compression.subgoal_user_msg_hash = Some(hash);

        // Clone the last 6 agent-visible messages (M2 fix: only agent_visible, not invisible
        // [tool summary] placeholders) for the extraction prompt.
        let recent: Vec<(zeph_llm::provider::Role, String)> = self
            .msg
            .messages
            .iter()
            .filter(|m| {
                m.metadata.agent_visible
                    && matches!(
                        m.role,
                        zeph_llm::provider::Role::User | zeph_llm::provider::Role::Assistant
                    )
            })
            .rev()
            .take(6)
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .map(|m| (m.role, m.content.clone()))
            .collect();

        let provider = self.summary_or_primary_provider().clone();

        let handle = tokio::spawn(async move {
            use zeph_llm::provider::{Message, MessageMetadata, Role};

            if recent.is_empty() {
                return None;
            }

            let mut context_text = String::new();
            for (role, content) in &recent {
                let role_str = match role {
                    Role::User => "user",
                    Role::Assistant => "assistant",
                    Role::System => "system",
                };
                let preview = if content.len() > 300 {
                    let end = content.floor_char_boundary(300);
                    &content[..end]
                } else {
                    content.as_str()
                };
                let _ =
                    std::fmt::write(&mut context_text, format_args!("[{role_str}]: {preview}\n"));
            }

            let prompt = format!(
                "Given this conversation excerpt, identify the agent's CURRENT subgoal in one \
                 sentence. A subgoal is the immediate objective the agent is working toward right \
                 now, not the overall task.\n\n\
                 If the agent just completed a subgoal (answered a question, finished a subtask), \
                 also state the COMPLETED subgoal.\n\n\
                 Respond in this exact format:\n\
                 CURRENT: <one sentence describing current subgoal>\n\
                 COMPLETED: <one sentence describing just-completed subgoal, or NONE>\n\n\
                 <conversation>\n{context_text}</conversation>"
            );

            let msgs = [Message {
                role: Role::User,
                content: prompt,
                parts: vec![],
                metadata: MessageMetadata::default(),
            }];

            let response = match tokio::time::timeout(
                std::time::Duration::from_secs(30),
                provider.chat(&msgs),
            )
            .await
            {
                Ok(Ok(r)) => r,
                Ok(Err(e)) => {
                    tracing::debug!("subgoal_extraction: LLM error: {e:#}");
                    return None;
                }
                Err(_) => {
                    tracing::debug!("subgoal_extraction: timed out");
                    return None;
                }
            };

            Some(parse_subgoal_extraction_response(&response))
        });

        self.compression.pending_subgoal = Some(handle);
        tracing::debug!("subgoal_extraction: background task spawned");
        if let Some(ref tx) = self.session.status_tx {
            let _ = tx.send("Tracking subgoal...".into());
        }
    }
}

/// Parse the structured LLM response for subgoal extraction.
///
/// Expected format:
/// ```text
/// CURRENT: <description>
/// COMPLETED: <description or NONE>
/// ```
///
/// Falls back to treating the entire response as the current subgoal on malformed input.
#[cfg(feature = "context-compression")]
fn parse_subgoal_extraction_response(
    response: &str,
) -> crate::agent::state::SubgoalExtractionResult {
    use crate::agent::state::SubgoalExtractionResult;

    let trimmed = response.trim();

    // Try to extract CURRENT: and COMPLETED: prefixes.
    if let Some(current_pos) = trimmed.find("CURRENT:") {
        let after_current = &trimmed[current_pos + "CURRENT:".len()..];
        let (current_line_raw, remainder_raw) = after_current
            .split_once('\n')
            .map_or((after_current, ""), |(l, r)| (l, r));
        let current_line = current_line_raw.trim();
        let remainder = remainder_raw.trim();

        if current_line.is_empty() {
            // Malformed: treat entire response as current subgoal.
            return SubgoalExtractionResult {
                current: trimmed.to_string(),
                completed: None,
            };
        }

        let current = current_line.to_string();

        let completed = if let Some(comp_pos) = remainder.find("COMPLETED:") {
            let comp_text = remainder[comp_pos + "COMPLETED:".len()..].trim();
            let comp_line = comp_text
                .split('\n')
                .next()
                .unwrap_or("")
                .trim()
                .to_string();
            if comp_line.is_empty() || comp_line.eq_ignore_ascii_case("none") {
                None
            } else {
                Some(comp_line)
            }
        } else {
            None
        };

        return SubgoalExtractionResult { current, completed };
    }

    // Malformed response: treat entire response as current subgoal.
    SubgoalExtractionResult {
        current: trimmed.to_string(),
        completed: None,
    }
}

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

    #[test]
    fn extract_overflow_ref_returns_uuid_when_present() {
        let uuid = "550e8400-e29b-41d4-a716-446655440000";
        let body = format!(
            "some output\n[full output stored \u{2014} ID: {uuid} \u{2014} 12345 bytes, use read_overflow tool to retrieve]"
        );
        assert_eq!(extract_overflow_ref(&body), Some(uuid));
    }

    #[test]
    fn extract_overflow_ref_returns_none_when_absent() {
        let body = "normal small output without overflow notice";
        assert_eq!(extract_overflow_ref(body), None);
    }

    #[test]
    fn extract_overflow_ref_returns_none_for_empty_body() {
        assert_eq!(extract_overflow_ref(""), None);
    }

    #[test]
    fn extract_overflow_ref_handles_notice_at_start() {
        let uuid = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
        let body = format!(
            "[full output stored \u{2014} ID: {uuid} \u{2014} 9999 bytes, use read_overflow tool to retrieve]"
        );
        assert_eq!(extract_overflow_ref(&body), Some(uuid));
    }

    // T-CRIT-01: prune_tool_outputs must skip focus_pinned messages.
    #[test]
    fn prune_tool_outputs_skips_focus_pinned_messages() {
        use crate::agent::tests::agent_tests::{
            MockChannel, MockToolExecutor, create_test_registry, mock_provider,
        };
        use zeph_llm::provider::{Message, MessageMetadata, MessagePart, Role};

        let mut agent = Agent::new(
            mock_provider(vec![]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        // Disable tail protection so the pruner can evict all messages in the test.
        agent.context_manager.prune_protect_tokens = 0;
        // Agent::new prepopulates messages[0] with a system prompt.

        // Pinned knowledge block with a large tool output part
        let mut pinned_meta = MessageMetadata::focus_pinned();
        pinned_meta.focus_pinned = true;
        let big_body = "x".repeat(5000);
        let mut pinned_msg = Message {
            role: Role::System,
            content: big_body.clone(),
            parts: vec![MessagePart::ToolOutput {
                tool_name: "read".into(),
                body: big_body.clone(),
                compacted_at: None,
            }],
            metadata: pinned_meta,
        };
        pinned_msg.rebuild_content();
        agent.msg.messages.push(pinned_msg);

        // Non-pinned message with a large tool output
        let big_body2 = "y".repeat(5000);
        let mut normal_msg = Message {
            role: Role::User,
            content: big_body2.clone(),
            parts: vec![MessagePart::ToolOutput {
                tool_name: "shell".into(),
                body: big_body2.clone(),
                compacted_at: None,
            }],
            metadata: MessageMetadata::default(),
        };
        normal_msg.rebuild_content();
        agent.msg.messages.push(normal_msg);

        let freed = agent.prune_tool_outputs(1);

        // messages[0] = agent system prompt, messages[1] = pinned, messages[2] = normal.
        let pinned = &agent.msg.messages[1];
        if let MessagePart::ToolOutput {
            body, compacted_at, ..
        } = &pinned.parts[0]
        {
            assert_eq!(*body, "x".repeat(5000), "pinned body must not be evicted");
            assert!(
                compacted_at.is_none(),
                "pinned compacted_at must remain None"
            );
        }

        // Non-pinned body must be evicted
        let normal = &agent.msg.messages[2];
        if let MessagePart::ToolOutput { compacted_at, .. } = &normal.parts[0] {
            assert!(compacted_at.is_some(), "non-pinned body must be evicted");
        }

        assert!(freed > 0, "must free tokens from non-pinned message");
    }

    // T-CRIT-03: prune_tool_outputs_oldest_first basic ordering.
    #[test]
    fn prune_tool_outputs_oldest_first_evicts_from_front() {
        use crate::agent::tests::agent_tests::{
            MockChannel, MockToolExecutor, create_test_registry, mock_provider,
        };
        use zeph_llm::provider::{Message, MessagePart, Role};

        let mut agent = Agent::new(
            mock_provider(vec![]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        // Disable tail protection so the pruner can evict all messages in the test.
        agent.context_manager.prune_protect_tokens = 0;
        // Agent::new puts system prompt at messages[0]; tool outputs go to indices 1..=3.

        for i in 0..3 {
            let body = format!("tool output {i} {}", "z".repeat(500));
            let mut msg = Message {
                role: Role::User,
                content: body.clone(),
                parts: vec![MessagePart::ToolOutput {
                    tool_name: "shell".into(),
                    body: body.clone(),
                    compacted_at: None,
                }],
                metadata: MessageMetadata::default(),
            };
            msg.rebuild_content();
            agent.msg.messages.push(msg);
        }

        // Evict just enough for the first message; the last two should be intact.
        agent.prune_tool_outputs_oldest_first(1);

        // messages[0] = agent system prompt, messages[1..=3] = ToolOutput messages.
        if let MessagePart::ToolOutput { compacted_at, .. } = &agent.msg.messages[1].parts[0] {
            assert!(
                compacted_at.is_some(),
                "oldest tool output must be evicted first"
            );
        }
        // Second should be intact (we only freed enough for 1)
        if let MessagePart::ToolOutput { compacted_at, .. } = &agent.msg.messages[2].parts[0] {
            assert!(
                compacted_at.is_none(),
                "second tool output must still be intact"
            );
        }
    }

    // --- Structured summarization tests ---

    // T-STR-01: build_anchored_summary_prompt embeds conversation and all 5 JSON field names.
    #[test]
    fn build_anchored_summary_prompt_contains_required_fields_and_history() {
        use zeph_llm::provider::{Message, MessageMetadata, Role};

        let messages = vec![
            Message {
                role: Role::User,
                content: "refactor the auth middleware".into(),
                parts: vec![],
                metadata: MessageMetadata::default(),
            },
            Message {
                role: Role::Assistant,
                content: "I will split it into two modules".into(),
                parts: vec![],
                metadata: MessageMetadata::default(),
            },
        ];

        let prompt =
            Agent::<crate::agent::tests::agent_tests::MockChannel>::build_anchored_summary_prompt(
                &messages, "",
            );

        // All 5 JSON field names must appear in the prompt.
        assert!(prompt.contains("session_intent"), "missing session_intent");
        assert!(prompt.contains("files_modified"), "missing files_modified");
        assert!(prompt.contains("decisions_made"), "missing decisions_made");
        assert!(prompt.contains("open_questions"), "missing open_questions");
        assert!(prompt.contains("next_steps"), "missing next_steps");

        // Conversation content must be embedded.
        assert!(
            prompt.contains("refactor the auth middleware"),
            "user message not in prompt"
        );
        assert!(
            prompt.contains("I will split it into two modules"),
            "assistant message not in prompt"
        );
    }

    // T-STR-02: build_anchored_summary_prompt injects guidelines when non-empty.
    #[test]
    fn build_anchored_summary_prompt_includes_guidelines() {
        use zeph_llm::provider::{Message, MessageMetadata, Role};

        let messages = vec![Message {
            role: Role::User,
            content: "hello".into(),
            parts: vec![],
            metadata: MessageMetadata::default(),
        }];
        let prompt =
            Agent::<crate::agent::tests::agent_tests::MockChannel>::build_anchored_summary_prompt(
                &messages,
                "focus on file paths",
            );

        assert!(
            prompt.contains("compression-guidelines"),
            "guidelines section missing"
        );
        assert!(
            prompt.contains("focus on file paths"),
            "guidelines content missing"
        );
    }

    // T-STR-03: try_summarize_structured returns Ok(AnchoredSummary) when mock returns valid JSON.
    #[tokio::test]
    async fn try_summarize_structured_returns_anchored_summary_on_valid_json() {
        use crate::agent::tests::agent_tests::{
            MockChannel, MockToolExecutor, create_test_registry, mock_provider,
        };
        use zeph_llm::provider::{Message, MessageMetadata, Role};
        use zeph_memory::AnchoredSummary;

        let valid_json = serde_json::to_string(&AnchoredSummary {
            session_intent: "Implement auth middleware".into(),
            files_modified: vec!["src/auth.rs".into()],
            decisions_made: vec!["Decision: use JWT — Reason: stateless".into()],
            open_questions: vec![],
            next_steps: vec!["Write tests".into()],
        })
        .unwrap();

        let mut agent = Agent::new(
            mock_provider(vec![valid_json]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        agent.memory_state.structured_summaries = true;

        let messages = vec![Message {
            role: Role::User,
            content: "implement auth".into(),
            parts: vec![],
            metadata: MessageMetadata::default(),
        }];

        let result = agent.try_summarize_structured(&messages, "").await;
        assert!(result.is_ok(), "expected Ok, got: {result:?}");
        let summary = result.unwrap();
        assert_eq!(summary.session_intent, "Implement auth middleware");
        assert_eq!(summary.files_modified, vec!["src/auth.rs"]);
        assert!(summary.is_complete());
    }

    // T-STR-04: try_summarize_structured returns Err when mandatory fields are missing.
    #[tokio::test]
    async fn try_summarize_structured_returns_err_when_incomplete() {
        use crate::agent::tests::agent_tests::{
            MockChannel, MockToolExecutor, create_test_registry, mock_provider,
        };
        use zeph_llm::provider::{Message, MessageMetadata, Role};
        use zeph_memory::AnchoredSummary;

        // next_steps is empty → is_complete() returns false → method must return Err.
        let incomplete_json = serde_json::to_string(&AnchoredSummary {
            session_intent: "Some intent".into(),
            files_modified: vec![],
            decisions_made: vec![],
            open_questions: vec![],
            next_steps: vec![], // missing → incomplete
        })
        .unwrap();

        let mut agent = Agent::new(
            mock_provider(vec![incomplete_json]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        agent.memory_state.structured_summaries = true;

        let messages = vec![Message {
            role: Role::User,
            content: "do something".into(),
            parts: vec![],
            metadata: MessageMetadata::default(),
        }];

        let result = agent.try_summarize_structured(&messages, "").await;
        assert!(
            result.is_err(),
            "expected Err for incomplete summary, got Ok"
        );
    }

    // T-STR-05: try_summarize_structured returns Err when LLM returns invalid JSON.
    #[tokio::test]
    async fn try_summarize_structured_returns_err_on_malformed_json() {
        use crate::agent::tests::agent_tests::{
            MockChannel, MockToolExecutor, create_test_registry, mock_provider,
        };
        use zeph_llm::provider::{Message, MessageMetadata, Role};

        // chat_typed retries once then returns StructuredParse error on bad JSON.
        let bad_json = "this is not json at all".to_string();
        let mut agent = Agent::new(
            mock_provider(vec![bad_json.clone(), bad_json]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        agent.memory_state.structured_summaries = true;

        let messages = vec![Message {
            role: Role::User,
            content: "summarize".into(),
            parts: vec![],
            metadata: MessageMetadata::default(),
        }];

        let result = agent.try_summarize_structured(&messages, "").await;
        assert!(result.is_err(), "expected Err for malformed JSON, got Ok");
    }

    // T-STR-06: summarize_messages uses prose path when structured_summaries = false.
    #[tokio::test]
    async fn summarize_messages_uses_prose_when_flag_disabled() {
        use crate::agent::tests::agent_tests::{
            MockChannel, MockToolExecutor, create_test_registry, mock_provider,
        };
        use zeph_llm::provider::{Message, MessageMetadata, Role};

        let prose_response = "1. User Intent: test\n2. Files: none".to_string();
        let agent = Agent::new(
            mock_provider(vec![prose_response.clone()]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        // structured_summaries = false by default in Agent::new()

        let messages = vec![Message {
            role: Role::User,
            content: "do a thing".into(),
            parts: vec![],
            metadata: MessageMetadata::default(),
        }];

        let result = agent.summarize_messages(&messages, "").await;
        assert!(result.is_ok(), "prose path must succeed");
        // Prose path returns the raw LLM output (no markdown section headers from AnchoredSummary).
        assert!(
            !result.unwrap().contains("[anchored summary]"),
            "prose path must not produce anchored summary header"
        );
    }

    // T-STR-07: summarize_messages returns markdown with anchored headers when flag enabled.
    #[tokio::test]
    async fn summarize_messages_returns_anchored_markdown_when_flag_enabled() {
        use crate::agent::tests::agent_tests::{
            MockChannel, MockToolExecutor, create_test_registry, mock_provider,
        };
        use zeph_llm::provider::{Message, MessageMetadata, Role};
        use zeph_memory::AnchoredSummary;

        let valid_json = serde_json::to_string(&AnchoredSummary {
            session_intent: "Build a CLI tool".into(),
            files_modified: vec!["src/cli.rs".into()],
            decisions_made: vec!["Decision: use clap — Reason: ergonomic API".into()],
            open_questions: vec![],
            next_steps: vec!["Add help text".into()],
        })
        .unwrap();

        let mut agent = Agent::new(
            mock_provider(vec![valid_json]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        agent.memory_state.structured_summaries = true;

        let messages = vec![Message {
            role: Role::User,
            content: "build CLI".into(),
            parts: vec![],
            metadata: MessageMetadata::default(),
        }];

        let result = agent.summarize_messages(&messages, "").await;
        assert!(result.is_ok(), "structured path must succeed");
        let md = result.unwrap();
        assert!(
            md.contains("[anchored summary]"),
            "output must start with anchored summary header"
        );
        assert!(md.contains("## Session Intent"), "missing Session Intent");
        assert!(md.contains("## Next Steps"), "missing Next Steps");
        assert!(
            md.contains("Build a CLI tool"),
            "session_intent content missing"
        );
    }

    // T-STR-08: dump_anchored_summary creates a file with required JSON fields.
    #[test]
    fn dump_anchored_summary_creates_file_with_required_fields() {
        use crate::debug_dump::{DebugDumper, DumpFormat};
        use zeph_memory::{AnchoredSummary, TokenCounter};

        let dir = tempfile::tempdir().expect("tempdir");
        let dumper = DebugDumper::new(dir.path(), DumpFormat::Raw).expect("dumper creation");
        let summary = AnchoredSummary {
            session_intent: "Test dump".into(),
            files_modified: vec!["a.rs".into(), "b.rs".into()],
            decisions_made: vec!["Decision: async — Reason: performance".into()],
            open_questions: vec![],
            next_steps: vec!["Run tests".into()],
        };
        let counter = TokenCounter::new();
        dumper.dump_anchored_summary(&summary, false, &counter);

        // Find the anchored-summary file.
        let entries: Vec<_> = std::fs::read_dir(dumper.dir())
            .expect("read_dir")
            .filter_map(std::result::Result::ok)
            .map(|e| e.path())
            .filter(|p| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|n| n.ends_with("-anchored-summary.json"))
            })
            .collect();
        assert_eq!(
            entries.len(),
            1,
            "exactly one anchored-summary.json expected"
        );

        let content = std::fs::read_to_string(&entries[0]).expect("read file");
        let v: serde_json::Value = serde_json::from_str(&content).expect("valid JSON");
        assert!(
            v.get("section_completeness").is_some(),
            "missing section_completeness"
        );
        assert!(v.get("total_items").is_some(), "missing total_items");
        assert!(v.get("token_estimate").is_some(), "missing token_estimate");
        assert!(v.get("fallback").is_some(), "missing fallback field");
        assert_eq!(v["fallback"], false, "fallback must be false");

        let sc = &v["section_completeness"];
        assert_eq!(sc["session_intent"], true);
        assert_eq!(sc["files_modified"], true);
        assert_eq!(sc["decisions_made"], true);
        assert_eq!(sc["open_questions"], false);
        assert_eq!(sc["next_steps"], true);
    }

    // T-STR-09: dump_anchored_summary with fallback=true sets fallback field correctly.
    #[test]
    fn dump_anchored_summary_fallback_flag_propagated() {
        use crate::debug_dump::{DebugDumper, DumpFormat};
        use zeph_memory::{AnchoredSummary, TokenCounter};

        let dir = tempfile::tempdir().expect("tempdir");
        let dumper = DebugDumper::new(dir.path(), DumpFormat::Raw).expect("dumper creation");
        let empty = AnchoredSummary {
            session_intent: String::new(),
            files_modified: vec![],
            decisions_made: vec![],
            open_questions: vec![],
            next_steps: vec![],
        };
        let counter = TokenCounter::new();
        dumper.dump_anchored_summary(&empty, true, &counter);

        let entries: Vec<_> = std::fs::read_dir(dumper.dir())
            .expect("read_dir")
            .filter_map(std::result::Result::ok)
            .map(|e| e.path())
            .filter(|p| {
                p.file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|n| n.ends_with("-anchored-summary.json"))
            })
            .collect();
        assert_eq!(
            entries.len(),
            1,
            "exactly one anchored-summary.json expected"
        );

        let content = std::fs::read_to_string(&entries[0]).expect("read file");
        let v: serde_json::Value = serde_json::from_str(&content).expect("valid JSON");
        assert_eq!(v["fallback"], true, "fallback flag must be true");
        assert_eq!(
            v["total_items"], 0,
            "total_items must be 0 for empty summary"
        );
    }

    // T-CRIT-03: prune_tool_outputs_scored basic — lowest-relevance block evicted first.
    #[cfg(feature = "context-compression")]
    #[test]
    fn prune_tool_outputs_scored_evicts_lowest_relevance_first() {
        use crate::agent::tests::agent_tests::{
            MockChannel, MockToolExecutor, create_test_registry, mock_provider,
        };
        use crate::config::PruningStrategy;
        use zeph_llm::provider::{Message, MessagePart, Role};

        let mut agent = Agent::new(
            mock_provider(vec![]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        agent.context_manager.compression.pruning_strategy = PruningStrategy::TaskAware;
        agent.compression.current_task_goal =
            Some("authentication middleware session token".to_string());
        // Disable tail protection so the pruner can evict all messages in the test.
        agent.context_manager.prune_protect_tokens = 0;
        // Agent::new puts system prompt at messages[0]; rel_msg goes to index 1, irrel_msg to 2.

        // High-relevance: contains goal keywords
        let rel_body = "authentication middleware session token implementation ".repeat(50);
        let mut rel_msg = Message {
            role: Role::User,
            content: rel_body.clone(),
            parts: vec![MessagePart::ToolOutput {
                tool_name: "read".into(),
                body: rel_body.clone(),
                compacted_at: None,
            }],
            metadata: MessageMetadata::default(),
        };
        rel_msg.rebuild_content();
        agent.msg.messages.push(rel_msg);

        // Low-relevance: unrelated content
        let irrel_body = "database migration schema table column index ".repeat(50);
        let mut irrel_msg = Message {
            role: Role::User,
            content: irrel_body.clone(),
            parts: vec![MessagePart::ToolOutput {
                tool_name: "read".into(),
                body: irrel_body.clone(),
                compacted_at: None,
            }],
            metadata: MessageMetadata::default(),
        };
        irrel_msg.rebuild_content();
        agent.msg.messages.push(irrel_msg);

        agent.prune_tool_outputs_scored(1);

        // messages[0] = agent system prompt, messages[1] = rel_msg, messages[2] = irrel_msg.
        if let MessagePart::ToolOutput { compacted_at, .. } = &agent.msg.messages[2].parts[0] {
            assert!(
                compacted_at.is_some(),
                "low-relevance block must be evicted"
            );
        }
        if let MessagePart::ToolOutput { compacted_at, .. } = &agent.msg.messages[1].parts[0] {
            assert!(compacted_at.is_none(), "high-relevance block must survive");
        }
    }

    // T-CRIT-04: prune_tool_outputs_mig evicts blocks with lowest MIG score first.
    #[cfg(feature = "context-compression")]
    #[test]
    fn prune_tool_outputs_mig_evicts_lowest_mig_first() {
        use crate::agent::tests::agent_tests::{
            MockChannel, MockToolExecutor, create_test_registry, mock_provider,
        };
        use crate::config::PruningStrategy;
        use zeph_llm::provider::{Message, MessagePart, Role};

        let mut agent = Agent::new(
            mock_provider(vec![]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        agent.context_manager.compression.pruning_strategy = PruningStrategy::Mig;
        // Set a goal so MIG scorer has context for relevance scoring.
        agent.compression.current_task_goal = Some("authentication token".to_string());
        // Disable tail protection so the pruner can evict all messages in the test.
        agent.context_manager.prune_protect_tokens = 0;

        // High-relevance: repeated goal keywords → high relevance, low redundancy relative to goal
        let rel_body = "authentication token session middleware ".repeat(50);
        let mut rel_msg = Message {
            role: Role::User,
            content: rel_body.clone(),
            parts: vec![MessagePart::ToolOutput {
                tool_name: "read".into(),
                body: rel_body.clone(),
                compacted_at: None,
            }],
            metadata: MessageMetadata::default(),
        };
        rel_msg.rebuild_content();
        agent.msg.messages.push(rel_msg);

        // Low-relevance: unrelated content → low relevance → low MIG → evicted first
        let irrel_body = "database schema table column index ".repeat(50);
        let mut irrel_msg = Message {
            role: Role::User,
            content: irrel_body.clone(),
            parts: vec![MessagePart::ToolOutput {
                tool_name: "read".into(),
                body: irrel_body.clone(),
                compacted_at: None,
            }],
            metadata: MessageMetadata::default(),
        };
        irrel_msg.rebuild_content();
        agent.msg.messages.push(irrel_msg);

        // Ask to free only 1 token — should evict the lowest-MIG block.
        agent.prune_tool_outputs_mig(1);

        // messages[0] = system prompt, messages[1] = rel_msg, messages[2] = irrel_msg.
        if let MessagePart::ToolOutput { compacted_at, .. } = &agent.msg.messages[2].parts[0] {
            assert!(
                compacted_at.is_some(),
                "low-MIG (irrelevant) block must be evicted"
            );
        } else {
            panic!("expected ToolOutput at messages[2]");
        }
        if let MessagePart::ToolOutput { compacted_at, .. } = &agent.msg.messages[1].parts[0] {
            assert!(
                compacted_at.is_none(),
                "high-MIG (relevant) block must survive"
            );
        } else {
            panic!("expected ToolOutput at messages[1]");
        }
    }

    // T-CRIT-05: scored pruning respects prune_protect_tokens.
    #[cfg(feature = "context-compression")]
    #[test]
    fn prune_tool_outputs_scored_respects_protect_tokens() {
        use crate::agent::tests::agent_tests::{
            MockChannel, MockToolExecutor, create_test_registry, mock_provider,
        };
        use crate::config::PruningStrategy;
        use zeph_llm::provider::{Message, MessagePart, Role};

        let mut agent = Agent::new(
            mock_provider(vec![]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        agent.context_manager.compression.pruning_strategy = PruningStrategy::TaskAware;
        agent.compression.current_task_goal = Some("irrelevant goal".to_string());
        // Protect the entire tail (999_999 tokens) — nothing should be evicted.
        agent.context_manager.prune_protect_tokens = 999_999;

        let body = "unrelated content database schema ".repeat(50);
        let mut msg = Message {
            role: Role::User,
            content: body.clone(),
            parts: vec![MessagePart::ToolOutput {
                tool_name: "read".into(),
                body: body.clone(),
                compacted_at: None,
            }],
            metadata: MessageMetadata::default(),
        };
        msg.rebuild_content();
        agent.msg.messages.push(msg);

        let freed = agent.prune_tool_outputs_scored(1);
        assert_eq!(
            freed, 0,
            "no tokens should be freed when everything is protected"
        );

        if let MessagePart::ToolOutput { compacted_at, .. } = &agent.msg.messages[1].parts[0] {
            assert!(
                compacted_at.is_none(),
                "protected block must not be evicted"
            );
        } else {
            panic!("expected ToolOutput at messages[1]");
        }
    }

    // T-CRIT-06: MIG pruning respects prune_protect_tokens.
    #[cfg(feature = "context-compression")]
    #[test]
    fn prune_tool_outputs_mig_respects_protect_tokens() {
        use crate::agent::tests::agent_tests::{
            MockChannel, MockToolExecutor, create_test_registry, mock_provider,
        };
        use crate::config::PruningStrategy;
        use zeph_llm::provider::{Message, MessagePart, Role};

        let mut agent = Agent::new(
            mock_provider(vec![]),
            MockChannel::new(vec![]),
            create_test_registry(),
            None,
            5,
            MockToolExecutor::no_tools(),
        );
        agent.context_manager.compression.pruning_strategy = PruningStrategy::Mig;
        agent.compression.current_task_goal = Some("irrelevant goal".to_string());
        // Protect the entire tail (999_999 tokens) — nothing should be evicted.
        agent.context_manager.prune_protect_tokens = 999_999;

        let body = "unrelated content database schema ".repeat(50);
        let mut msg = Message {
            role: Role::User,
            content: body.clone(),
            parts: vec![MessagePart::ToolOutput {
                tool_name: "read".into(),
                body: body.clone(),
                compacted_at: None,
            }],
            metadata: MessageMetadata::default(),
        };
        msg.rebuild_content();
        agent.msg.messages.push(msg);

        let freed = agent.prune_tool_outputs_mig(1);
        assert_eq!(
            freed, 0,
            "no tokens should be freed when everything is protected"
        );

        if let MessagePart::ToolOutput { compacted_at, .. } = &agent.msg.messages[1].parts[0] {
            assert!(
                compacted_at.is_none(),
                "protected block must not be evicted"
            );
        } else {
            panic!("expected ToolOutput at messages[1]");
        }
    }
}

#[cfg(test)]
#[cfg(feature = "context-compression")]
mod subgoal_extraction_tests {
    use super::*;

    #[test]
    fn parse_well_formed_with_both() {
        let response = "CURRENT: Implement login\nCOMPLETED: Setup database";
        let result = parse_subgoal_extraction_response(response);
        assert_eq!(result.current, "Implement login");
        assert_eq!(result.completed, Some("Setup database".to_string()));
    }

    #[test]
    fn parse_well_formed_no_completed() {
        let response = "CURRENT: Fetch user data\nCOMPLETED: NONE";
        let result = parse_subgoal_extraction_response(response);
        assert_eq!(result.current, "Fetch user data");
        assert_eq!(result.completed, None);
    }

    #[test]
    fn parse_malformed_no_current_prefix() {
        let response = "Just some random text about subgoals";
        let result = parse_subgoal_extraction_response(response);
        assert_eq!(result.current, "Just some random text about subgoals");
        assert_eq!(result.completed, None);
    }

    #[test]
    fn parse_malformed_empty_current() {
        let response = "CURRENT: \nCOMPLETED: Setup";
        let result = parse_subgoal_extraction_response(response);
        // Empty CURRENT falls back to treating entire response as current
        assert_eq!(result.current.trim(), "CURRENT: \nCOMPLETED: Setup");
        assert_eq!(result.completed, None);
    }
}