pi_agent_rust 0.3.0

Native AI coding agent CLI - Rust port of Pi Agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
//! Context compaction for long sessions.
//!
//! This module ports the pi-mono compaction algorithm:
//! - Estimate context usage and choose a cut point that keeps recent context
//! - Summarize the discarded portion with the LLM (iteratively updating prior summaries)
//! - Record a `compaction` session entry containing the summary and cut point
//! - When building provider context, the session inserts the summary before the kept region
//!   and omits older messages.

use crate::error::{Error, Result};
use crate::model::{
    AssistantMessage, ContentBlock, Message, StopReason, TextContent, ThinkingLevel, ToolCall,
    Usage, UserContent, UserMessage,
};
use crate::provider::{Context, Provider, StreamOptions};
use crate::session::{SessionEntry, SessionMessage, session_message_to_model};
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use sha2::{Digest as _, Sha256};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt::Write as _;
use std::sync::Arc;

/// Approximate characters per token for English text with GPT-family tokenizers.
/// Intentionally conservative (overestimates tokens) to avoid exceeding context windows.
/// Set to 3 to safely account for code/symbol-heavy content which is denser than prose.
const CHARS_PER_TOKEN_ESTIMATE: usize = 3;

/// Estimated tokens for an image content block (~1200 tokens).
const IMAGE_TOKEN_ESTIMATE: usize = 1200;

/// Character-equivalent estimate for an image (IMAGE_TOKEN_ESTIMATE * CHARS_PER_TOKEN_ESTIMATE).
const IMAGE_CHAR_ESTIMATE: usize = IMAGE_TOKEN_ESTIMATE * CHARS_PER_TOKEN_ESTIMATE;

/// Count the serialized JSON byte length of a [`Value`] without allocating a `String`.
///
/// Uses `serde_json::to_writer` with a sink that only counts bytes – this gives the
/// exact same length as `serde_json::to_string(&v).len()` at zero heap cost.
fn json_byte_len(value: &Value) -> usize {
    struct Counter(usize);
    impl std::io::Write for Counter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0 = self.0.saturating_add(buf.len());
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    let mut c = Counter(0);
    if serde_json::to_writer(&mut c, value).is_err() {
        // Fallback or partial count on error (e.g. recursion limit)
    }
    c.0
}

// =============================================================================
// Public types
// =============================================================================

#[derive(Debug, Clone)]
pub struct ResolvedCompactionSettings {
    pub enabled: bool,
    pub context_window_tokens: u32,
    pub reserve_tokens: u32,
    pub keep_recent_tokens: u32,
}

impl Default for ResolvedCompactionSettings {
    /// Conservative default using the smallest common context window (32K).
    ///
    /// Production code paths should always override `context_window_tokens`
    /// with the actual model's context window via
    /// [`context_window_tokens_for_entry`](crate::main) or equivalent.
    /// This default is deliberately conservative so that if a code path
    /// forgets to override, compaction triggers too early (safe) rather
    /// than too late (could exceed the real context window).
    fn default() -> Self {
        let context_window_tokens: u32 = 128_000;
        Self {
            enabled: true,
            context_window_tokens,
            // ~8% of context window
            reserve_tokens: 10_240,
            // 10% of context window
            keep_recent_tokens: 12_800,
        }
    }
}

/// Details stored in `CompactionEntry.details` for cumulative file tracking.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CompactionDetails {
    pub read_files: Vec<String>,
    pub modified_files: Vec<String>,
    /// Compaction mode that produced this entry ("shake"); absent for the
    /// default LLM-summary mode (bd-cv653.3.18).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CompactionResult {
    pub summary: String,
    pub first_kept_entry_id: String,
    pub tokens_before: u64,
    pub details: CompactionDetails,
}

#[derive(Debug, Clone)]
pub struct CompactionPreparation {
    pub first_kept_entry_id: String,
    pub messages_to_summarize: Vec<SessionMessage>,
    pub turn_prefix_messages: Vec<SessionMessage>,
    pub is_split_turn: bool,
    pub tokens_before: u64,
    pub previous_summary: Option<String>,
    pub file_ops: FileOperations,
    pub settings: ResolvedCompactionSettings,
}

pub const SEMANTIC_COMPACTION_QUALITY_SCHEMA: &str = "pi.session.semantic_compaction_quality.v1";

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SemanticCompactionMarkerKind {
    Task,
    FileReference,
    Decision,
    ToolOutput,
    Constraint,
    HandoffFact,
    AgentMailDegraded,
    BeadsClaim,
    Interruption,
    TruncationNotice,
    StreamRule,
}

impl SemanticCompactionMarkerKind {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Task => "task",
            Self::FileReference => "file_reference",
            Self::Decision => "decision",
            Self::ToolOutput => "tool_output",
            Self::Constraint => "constraint",
            Self::HandoffFact => "handoff_fact",
            Self::AgentMailDegraded => "agent_mail_degraded",
            Self::BeadsClaim => "beads_claim",
            Self::Interruption => "interruption",
            Self::TruncationNotice => "truncation_notice",
            Self::StreamRule => "stream_rule",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SemanticCompactionMarkerSeverity {
    Critical,
    Important,
    Informational,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SemanticCompactionQualityVerdict {
    Pass,
    Degraded,
    Fail,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SemanticCompactionLossClass {
    PreCompactionMarkerAbsent,
    MissingMarker,
    WrongBranch,
    WrongTurn,
    TruncationReceiptMissing,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SemanticCompactionMarker {
    pub id: String,
    pub kind: SemanticCompactionMarkerKind,
    pub severity: SemanticCompactionMarkerSeverity,
    pub source_entry_id: String,
    pub expected_branch_leaf_id: String,
    pub expected_turn_id: String,
    pub marker: String,
    pub requires_truncation_receipt: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticCompactionMarkerObservation {
    pub marker_id: String,
    pub branch_leaf_id: String,
    pub turn_id: String,
    #[serde(default)]
    pub has_truncation_receipt: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticCompactionQualityView {
    pub name: String,
    pub branch_leaf_id: String,
    pub observations: Vec<SemanticCompactionMarkerObservation>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticCompactionCoverage {
    pub expected: u32,
    pub preserved: u32,
    pub missing: u32,
    pub wrong_branch: u32,
    pub wrong_turn: u32,
    pub truncation_receipt_missing: u32,
    pub pre_compaction_absent: u32,
    pub coverage_bps: u16,
}

impl SemanticCompactionCoverage {
    const fn note_expected(&mut self) {
        self.expected = self.expected.saturating_add(1);
    }

    const fn note_preserved(&mut self) {
        self.preserved = self.preserved.saturating_add(1);
    }

    const fn note_loss(&mut self, class: SemanticCompactionLossClass) {
        match class {
            SemanticCompactionLossClass::PreCompactionMarkerAbsent => {
                self.pre_compaction_absent = self.pre_compaction_absent.saturating_add(1);
            }
            SemanticCompactionLossClass::MissingMarker => {
                self.missing = self.missing.saturating_add(1);
            }
            SemanticCompactionLossClass::WrongBranch => {
                self.wrong_branch = self.wrong_branch.saturating_add(1);
            }
            SemanticCompactionLossClass::WrongTurn => {
                self.wrong_turn = self.wrong_turn.saturating_add(1);
            }
            SemanticCompactionLossClass::TruncationReceiptMissing => {
                self.truncation_receipt_missing = self.truncation_receipt_missing.saturating_add(1);
            }
        }
    }

    fn finalize(&mut self) {
        if self.expected == 0 {
            self.coverage_bps = 10_000;
            return;
        }
        let bps = self.preserved.saturating_mul(10_000) / self.expected;
        self.coverage_bps = u16::try_from(bps).unwrap_or(u16::MAX);
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticCompactionMarkerSummary {
    pub id: String,
    pub kind: SemanticCompactionMarkerKind,
    pub severity: SemanticCompactionMarkerSeverity,
    pub source_entry_id: String,
    pub expected_branch_leaf_id: String,
    pub expected_turn_id: String,
    pub marker_digest: String,
    pub preserved: bool,
    pub loss_classes: Vec<SemanticCompactionLossClass>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticCompactionMarkerLoss {
    pub marker_id: String,
    pub kind: SemanticCompactionMarkerKind,
    pub severity: SemanticCompactionMarkerSeverity,
    pub class: SemanticCompactionLossClass,
    pub expected_branch_leaf_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actual_branch_leaf_id: Option<String>,
    pub expected_turn_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actual_turn_id: Option<String>,
}

impl SemanticCompactionMarkerLoss {
    fn for_marker(
        marker: &SemanticCompactionMarker,
        class: SemanticCompactionLossClass,
        observation: Option<&SemanticCompactionMarkerObservation>,
    ) -> Self {
        Self {
            marker_id: marker.id.clone(),
            kind: marker.kind,
            severity: marker.severity,
            class,
            expected_branch_leaf_id: marker.expected_branch_leaf_id.clone(),
            actual_branch_leaf_id: observation.map(|obs| obs.branch_leaf_id.clone()),
            expected_turn_id: marker.expected_turn_id.clone(),
            actual_turn_id: observation.map(|obs| obs.turn_id.clone()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticCompactionFalsePositiveControl {
    pub marker_id: String,
    pub observed_branch_leaf_id: String,
    pub observed_turn_id: String,
    pub disposition: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticCompactionQualityReport {
    pub schema: String,
    pub before_view: String,
    pub after_view: String,
    pub before_branch_leaf_id: String,
    pub after_branch_leaf_id: String,
    pub marker_count: usize,
    pub coverage: SemanticCompactionCoverage,
    pub coverage_by_kind: BTreeMap<String, SemanticCompactionCoverage>,
    pub verdict: SemanticCompactionQualityVerdict,
    pub marker_summaries: Vec<SemanticCompactionMarkerSummary>,
    pub losses: Vec<SemanticCompactionMarkerLoss>,
    pub false_positive_controls: Vec<SemanticCompactionFalsePositiveControl>,
    pub unexpected_marker_ids: Vec<String>,
}

fn observation_map(
    view: &SemanticCompactionQualityView,
) -> BTreeMap<String, SemanticCompactionMarkerObservation> {
    let mut observations = BTreeMap::new();
    for observation in &view.observations {
        observations
            .entry(String::from(observation.marker_id.as_str()))
            .or_insert_with(|| SemanticCompactionMarkerObservation {
                marker_id: String::from(observation.marker_id.as_str()),
                branch_leaf_id: String::from(observation.branch_leaf_id.as_str()),
                turn_id: String::from(observation.turn_id.as_str()),
                has_truncation_receipt: observation.has_truncation_receipt,
            });
    }
    observations
}

fn marker_digest(marker: &SemanticCompactionMarker) -> String {
    let mut digest = Sha256::new();
    digest.update(marker.id.as_bytes());
    digest.update([0]);
    digest.update(marker.marker.as_bytes());
    crate::package_manager::hex_encode(&digest.finalize())
}

fn record_loss(
    coverage: &mut SemanticCompactionCoverage,
    coverage_by_kind: &mut BTreeMap<String, SemanticCompactionCoverage>,
    marker: &SemanticCompactionMarker,
    class: SemanticCompactionLossClass,
) {
    coverage.note_loss(class);
    coverage_by_kind
        .entry(marker.kind.as_str().to_string())
        .or_default()
        .note_loss(class);
}

fn record_preserved(
    coverage: &mut SemanticCompactionCoverage,
    coverage_by_kind: &mut BTreeMap<String, SemanticCompactionCoverage>,
    marker: &SemanticCompactionMarker,
) {
    coverage.note_preserved();
    coverage_by_kind
        .entry(marker.kind.as_str().to_string())
        .or_default()
        .note_preserved();
}

fn marker_summary_for(
    marker: &SemanticCompactionMarker,
    marker_loss_classes: Vec<SemanticCompactionLossClass>,
) -> SemanticCompactionMarkerSummary {
    SemanticCompactionMarkerSummary {
        id: String::from(marker.id.as_str()),
        kind: marker.kind,
        severity: marker.severity,
        source_entry_id: String::from(marker.source_entry_id.as_str()),
        expected_branch_leaf_id: String::from(marker.expected_branch_leaf_id.as_str()),
        expected_turn_id: String::from(marker.expected_turn_id.as_str()),
        marker_digest: marker_digest(marker),
        preserved: marker_loss_classes.is_empty(),
        loss_classes: marker_loss_classes,
    }
}

#[allow(clippy::too_many_lines)]
pub fn evaluate_semantic_compaction_quality(
    markers: &[SemanticCompactionMarker],
    before: &SemanticCompactionQualityView,
    after: &SemanticCompactionQualityView,
) -> SemanticCompactionQualityReport {
    let before_observations = observation_map(before);
    let after_observations = observation_map(after);

    let mut sorted_markers = markers.iter().collect::<Vec<_>>();
    sorted_markers.sort_by(|left, right| left.id.cmp(&right.id));

    let expected_marker_ids = sorted_markers
        .iter()
        .map(|marker| marker.id.clone())
        .collect::<BTreeSet<_>>();

    let unexpected_marker_ids = after_observations
        .keys()
        .filter(|id| !expected_marker_ids.contains(*id))
        .cloned()
        .collect::<Vec<_>>();

    let false_positive_controls = unexpected_marker_ids
        .iter()
        .filter_map(|id| after_observations.get(id))
        .map(|observation| SemanticCompactionFalsePositiveControl {
            marker_id: observation.marker_id.clone(),
            observed_branch_leaf_id: observation.branch_leaf_id.clone(),
            observed_turn_id: observation.turn_id.clone(),
            disposition: "ignored_unexpected_marker".to_string(),
        })
        .collect::<Vec<_>>();

    let mut coverage = SemanticCompactionCoverage::default();
    let mut coverage_by_kind = BTreeMap::<String, SemanticCompactionCoverage>::new();
    let mut marker_summaries = Vec::with_capacity(sorted_markers.len());
    let mut losses = Vec::new();

    for marker in sorted_markers {
        coverage.note_expected();
        coverage_by_kind
            .entry(marker.kind.as_str().to_string())
            .or_default()
            .note_expected();

        let before_observation = before_observations.get(&marker.id);
        let after_observation = after_observations.get(&marker.id);
        let mut marker_loss_classes = Vec::new();

        if before_observation.is_none() {
            marker_loss_classes.push(SemanticCompactionLossClass::PreCompactionMarkerAbsent);
        }

        if let Some(observation) = after_observation {
            if observation.branch_leaf_id != marker.expected_branch_leaf_id
                || after.branch_leaf_id != marker.expected_branch_leaf_id
            {
                marker_loss_classes.push(SemanticCompactionLossClass::WrongBranch);
            }
            if observation.turn_id != marker.expected_turn_id {
                marker_loss_classes.push(SemanticCompactionLossClass::WrongTurn);
            }
            if marker.requires_truncation_receipt && !observation.has_truncation_receipt {
                marker_loss_classes.push(SemanticCompactionLossClass::TruncationReceiptMissing);
            }
        } else {
            marker_loss_classes.push(SemanticCompactionLossClass::MissingMarker);
        }

        if marker_loss_classes.is_empty() {
            record_preserved(&mut coverage, &mut coverage_by_kind, marker);
        } else {
            for class in marker_loss_classes.iter().copied() {
                record_loss(&mut coverage, &mut coverage_by_kind, marker, class);
                losses.push(SemanticCompactionMarkerLoss::for_marker(
                    marker,
                    class,
                    after_observation,
                ));
            }
        }

        marker_summaries.push(marker_summary_for(marker, marker_loss_classes));
    }

    coverage.finalize();
    for value in coverage_by_kind.values_mut() {
        value.finalize();
    }

    let has_unexpected_markers = !unexpected_marker_ids.is_empty();
    let verdict = if has_unexpected_markers
        || losses
            .iter()
            .any(|loss| loss.severity == SemanticCompactionMarkerSeverity::Critical)
    {
        SemanticCompactionQualityVerdict::Fail
    } else if losses.is_empty() {
        SemanticCompactionQualityVerdict::Pass
    } else {
        SemanticCompactionQualityVerdict::Degraded
    };

    SemanticCompactionQualityReport {
        schema: SEMANTIC_COMPACTION_QUALITY_SCHEMA.to_string(),
        before_view: before.name.clone(),
        after_view: after.name.clone(),
        before_branch_leaf_id: before.branch_leaf_id.clone(),
        after_branch_leaf_id: after.branch_leaf_id.clone(),
        marker_count: markers.len(),
        coverage,
        coverage_by_kind,
        verdict,
        marker_summaries,
        losses,
        false_positive_controls,
        unexpected_marker_ids,
    }
}

pub fn semantic_compaction_quality_report_to_value(
    report: &SemanticCompactionQualityReport,
) -> Result<Value> {
    serde_json::to_value(report)
        .map_err(|e| Error::session(format!("Semantic compaction quality report: {e}")))
}

pub fn semantic_compaction_quality_report_to_jsonl(
    report: &SemanticCompactionQualityReport,
) -> Result<String> {
    let mut line = serde_json::to_string(report)
        .map_err(|e| Error::session(format!("Semantic compaction quality report JSONL: {e}")))?;
    line.push('\n');
    Ok(line)
}

pub fn compaction_preparation_to_value(prep: &CompactionPreparation) -> Value {
    let messages_to_summarize =
        serde_json::to_value(&prep.messages_to_summarize).unwrap_or(Value::Array(Vec::new()));
    let turn_prefix_messages =
        serde_json::to_value(&prep.turn_prefix_messages).unwrap_or(Value::Array(Vec::new()));

    let mut obj = Map::new();
    obj.insert(
        "firstKeptEntryId".to_string(),
        Value::String(prep.first_kept_entry_id.clone()),
    );
    obj.insert("messagesToSummarize".to_string(), messages_to_summarize);
    obj.insert("turnPrefixMessages".to_string(), turn_prefix_messages);
    obj.insert("isSplitTurn".to_string(), Value::Bool(prep.is_split_turn));
    obj.insert("tokensBefore".to_string(), Value::from(prep.tokens_before));
    if let Some(previous_summary) = &prep.previous_summary {
        obj.insert(
            "previousSummary".to_string(),
            Value::String(previous_summary.clone()),
        );
    }
    obj.insert("fileOps".to_string(), file_ops_to_value(&prep.file_ops));
    obj.insert(
        "settings".to_string(),
        compaction_settings_to_value(&prep.settings),
    );
    Value::Object(obj)
}

fn file_ops_to_value(file_ops: &FileOperations) -> Value {
    let read = sorted_file_ops(&file_ops.read);
    let written = sorted_file_ops(&file_ops.written);
    let edited = sorted_file_ops(&file_ops.edited);
    let mut obj = Map::new();
    obj.insert("read".to_string(), Value::Array(read));
    obj.insert("written".to_string(), Value::Array(written));
    obj.insert("edited".to_string(), Value::Array(edited));
    Value::Object(obj)
}

fn sorted_file_ops(values: &HashSet<String>) -> Vec<Value> {
    let mut entries = values.iter().cloned().collect::<Vec<_>>();
    entries.sort();
    entries.into_iter().map(Value::String).collect()
}

fn compaction_settings_to_value(settings: &ResolvedCompactionSettings) -> Value {
    let mut obj = Map::new();
    obj.insert("enabled".to_string(), Value::Bool(settings.enabled));
    obj.insert(
        "contextWindowTokens".to_string(),
        Value::from(settings.context_window_tokens),
    );
    obj.insert(
        "reserveTokens".to_string(),
        Value::from(settings.reserve_tokens),
    );
    obj.insert(
        "keepRecentTokens".to_string(),
        Value::from(settings.keep_recent_tokens),
    );
    Value::Object(obj)
}

fn preparation_field<'a>(
    obj: &'a Map<String, Value>,
    camel: &str,
    snake: &str,
) -> Option<&'a Value> {
    obj.get(camel).or_else(|| obj.get(snake))
}

fn preparation_string(obj: &Map<String, Value>, camel: &str, snake: &str) -> Result<String> {
    preparation_field(obj, camel, snake)
        .and_then(Value::as_str)
        .map(str::to_string)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| {
            Error::validation(format!(
                "compaction preparation: `{camel}` must be a non-empty string"
            ))
        })
}

fn preparation_bool(obj: &Map<String, Value>, camel: &str, snake: &str) -> Result<bool> {
    preparation_field(obj, camel, snake)
        .and_then(Value::as_bool)
        .ok_or_else(|| {
            Error::validation(format!(
                "compaction preparation: `{camel}` must be a boolean"
            ))
        })
}

fn preparation_u64(obj: &Map<String, Value>, camel: &str, snake: &str) -> Result<u64> {
    preparation_field(obj, camel, snake)
        .and_then(Value::as_u64)
        .ok_or_else(|| {
            Error::validation(format!(
                "compaction preparation: `{camel}` must be an unsigned integer"
            ))
        })
}

fn preparation_messages(
    obj: &Map<String, Value>,
    camel: &str,
    snake: &str,
) -> Result<Vec<SessionMessage>> {
    let value = preparation_field(obj, camel, snake).ok_or_else(|| {
        Error::validation(format!(
            "compaction preparation: `{camel}` must be an array of session messages"
        ))
    })?;
    if !value.is_array() {
        return Err(Error::validation(format!(
            "compaction preparation: `{camel}` must be an array of session messages"
        )));
    }
    serde_json::from_value::<Vec<SessionMessage>>(value.clone()).map_err(|err| {
        Error::validation(format!(
            "compaction preparation: `{camel}` contains a malformed session message: {err}"
        ))
    })
}

fn string_set_from_value(obj: &Map<String, Value>, key: &str) -> Result<HashSet<String>> {
    let entries = obj.get(key).and_then(Value::as_array).ok_or_else(|| {
        Error::validation(format!(
            "compaction preparation: `fileOps.{key}` must be an array of strings"
        ))
    })?;
    entries
        .iter()
        .map(|entry| {
            entry.as_str().map(str::to_string).ok_or_else(|| {
                Error::validation(format!(
                    "compaction preparation: `fileOps.{key}` must contain only strings"
                ))
            })
        })
        .collect()
}

fn file_ops_from_value(value: &Value) -> Result<FileOperations> {
    let obj = value.as_object().ok_or_else(|| {
        Error::validation("compaction preparation: `fileOps` must be an object".to_string())
    })?;
    Ok(FileOperations {
        read: string_set_from_value(obj, "read")?,
        written: string_set_from_value(obj, "written")?,
        edited: string_set_from_value(obj, "edited")?,
    })
}

fn preparation_settings_u32(obj: &Map<String, Value>, camel: &str, snake: &str) -> Result<u32> {
    let raw = preparation_field(obj, camel, snake)
        .and_then(Value::as_u64)
        .ok_or_else(|| {
            Error::validation(format!(
                "compaction preparation: `settings.{camel}` must be an unsigned integer"
            ))
        })?;
    u32::try_from(raw).map_err(|_| {
        Error::validation(format!(
            "compaction preparation: `settings.{camel}` exceeds u32::MAX"
        ))
    })
}

fn compaction_settings_from_value(value: &Value) -> Result<ResolvedCompactionSettings> {
    let obj = value.as_object().ok_or_else(|| {
        Error::validation("compaction preparation: `settings` must be an object".to_string())
    })?;
    let enabled = obj.get("enabled").and_then(Value::as_bool).ok_or_else(|| {
        Error::validation(
            "compaction preparation: `settings.enabled` must be a boolean".to_string(),
        )
    })?;
    Ok(ResolvedCompactionSettings {
        enabled,
        context_window_tokens: preparation_settings_u32(
            obj,
            "contextWindowTokens",
            "context_window_tokens",
        )?,
        reserve_tokens: preparation_settings_u32(obj, "reserveTokens", "reserve_tokens")?,
        keep_recent_tokens: preparation_settings_u32(
            obj,
            "keepRecentTokens",
            "keep_recent_tokens",
        )?,
    })
}

/// Inverse of [`compaction_preparation_to_value`] for preparation JSON that
/// crossed a trust boundary (gh #167 / bd-i28yz).
///
/// The extension host bridge echoes the value a sandboxed extension hands
/// back, so every required field is validated and malformed input is
/// rejected with a descriptive error rather than being defaulted; a caller
/// can never smuggle a half-formed preparation into the compaction engine.
pub fn compaction_preparation_from_value(value: &Value) -> Result<CompactionPreparation> {
    let obj = value.as_object().ok_or_else(|| {
        Error::validation("compaction preparation must be a JSON object".to_string())
    })?;

    let first_kept_entry_id = preparation_string(obj, "firstKeptEntryId", "first_kept_entry_id")?;
    let messages_to_summarize =
        preparation_messages(obj, "messagesToSummarize", "messages_to_summarize")?;
    let turn_prefix_messages =
        preparation_messages(obj, "turnPrefixMessages", "turn_prefix_messages")?;
    let is_split_turn = preparation_bool(obj, "isSplitTurn", "is_split_turn")?;
    let tokens_before = preparation_u64(obj, "tokensBefore", "tokens_before")?;

    // The serializer omits `previousSummary` when absent, so a missing key or
    // an explicit null both mean "no previous summary"; any other non-string
    // shape is rejected.
    let previous_summary = match preparation_field(obj, "previousSummary", "previous_summary") {
        None | Some(Value::Null) => None,
        Some(Value::String(summary)) => Some(summary.clone()),
        Some(_) => {
            return Err(Error::validation(
                "compaction preparation: `previousSummary` must be a string when present"
                    .to_string(),
            ));
        }
    };

    let file_ops_value = preparation_field(obj, "fileOps", "file_ops").ok_or_else(|| {
        Error::validation("compaction preparation: `fileOps` must be an object".to_string())
    })?;
    let file_ops = file_ops_from_value(file_ops_value)?;

    let settings_value = obj.get("settings").ok_or_else(|| {
        Error::validation("compaction preparation: `settings` must be an object".to_string())
    })?;
    let settings = compaction_settings_from_value(settings_value)?;

    Ok(CompactionPreparation {
        first_kept_entry_id,
        messages_to_summarize,
        turn_prefix_messages,
        is_split_turn,
        tokens_before,
        previous_summary,
        file_ops,
        settings,
    })
}

// =============================================================================
// File op tracking (read/write/edit)
// =============================================================================

#[derive(Debug, Clone, Default)]
pub struct FileOperations {
    read: HashSet<String>,
    written: HashSet<String>,
    edited: HashSet<String>,
}

impl FileOperations {
    pub fn read_files(&self) -> impl Iterator<Item = &str> {
        self.read.iter().map(String::as_str)
    }
}

fn build_tool_status_map(messages: &[SessionMessage]) -> HashMap<&str, bool> {
    let mut status = HashMap::new();
    for msg in messages {
        if let SessionMessage::ToolResult {
            tool_call_id,
            is_error,
            ..
        } = msg
        {
            status.insert(tool_call_id.as_str(), !*is_error);
        }
    }
    status
}

fn extract_file_ops_from_message(
    message: &SessionMessage,
    file_ops: &mut FileOperations,
    tool_status: &HashMap<&str, bool>,
) {
    let SessionMessage::Assistant { message } = message else {
        return;
    };

    for block in &message.content {
        let ContentBlock::ToolCall(ToolCall {
            id,
            name,
            arguments,
            ..
        }) = block
        else {
            continue;
        };

        // Only track successful tool calls.
        if !tool_status.get(id.as_str()).copied().unwrap_or(false) {
            continue;
        }

        let Some(path) = arguments.get("path").and_then(Value::as_str) else {
            continue;
        };

        match name.as_str() {
            "read" | "grep" | "find" | "ls" => {
                file_ops.read.insert(path.to_string());
            }
            "write" => {
                file_ops.written.insert(path.to_string());
            }
            "edit" | "hashline_edit" => {
                file_ops.edited.insert(path.to_string());
            }
            _ => {}
        }
    }
}

fn compute_file_lists(file_ops: &FileOperations) -> (Vec<String>, Vec<String>) {
    let modified: HashSet<&String> = file_ops
        .edited
        .iter()
        .chain(file_ops.written.iter())
        .collect();

    let mut read_only = file_ops
        .read
        .iter()
        .filter(|f| !modified.contains(f))
        .cloned()
        .collect::<Vec<_>>();
    read_only.sort();

    let mut modified_files = modified.into_iter().cloned().collect::<Vec<_>>();
    modified_files.sort();

    (read_only, modified_files)
}

fn write_escaped_file_list(out: &mut String, tag: &str, files: &[String]) {
    out.push('<');
    out.push_str(tag);
    out.push_str(">\n");
    for (i, file) in files.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        // Inline escape: replace < and > in file paths
        for ch in file.chars() {
            match ch {
                '<' => out.push_str("&lt;"),
                '>' => out.push_str("&gt;"),
                _ => out.push(ch),
            }
        }
    }
    out.push_str("\n</");
    out.push_str(tag);
    out.push('>');
}

fn format_file_operations(read_files: &[String], modified_files: &[String]) -> String {
    if read_files.is_empty() && modified_files.is_empty() {
        return String::new();
    }

    let mut out = String::from("\n\n");
    if !read_files.is_empty() {
        write_escaped_file_list(&mut out, "read-files", read_files);
    }
    if !modified_files.is_empty() {
        if !read_files.is_empty() {
            out.push_str("\n\n");
        }
        write_escaped_file_list(&mut out, "modified-files", modified_files);
    }
    out
}

// =============================================================================
// Token estimation
// =============================================================================

const fn calculate_context_tokens(usage: &Usage) -> u64 {
    if usage.total_tokens > 0 {
        usage.total_tokens
    } else {
        usage.input.saturating_add(usage.output)
    }
}

const fn get_assistant_usage(message: &SessionMessage) -> Option<&Usage> {
    let SessionMessage::Assistant { message } = message else {
        return None;
    };

    if matches!(message.stop_reason, StopReason::Aborted | StopReason::Error) {
        return None;
    }

    Some(&message.usage)
}

#[derive(Debug, Clone, Copy)]
struct ContextUsageEstimate {
    tokens: u64,
    last_usage_index: Option<usize>,
}

fn estimate_context_tokens(messages: &[SessionMessage]) -> ContextUsageEstimate {
    let mut last_usage: Option<(&Usage, usize)> = None;
    for (idx, msg) in messages.iter().enumerate().rev() {
        if let Some(usage) = get_assistant_usage(msg) {
            last_usage = Some((usage, idx));
            break;
        }
    }

    let Some((usage, usage_index)) = last_usage else {
        let total = messages
            .iter()
            .map(estimate_tokens)
            .fold(0u64, u64::saturating_add);
        return ContextUsageEstimate {
            tokens: total,
            last_usage_index: None,
        };
    };

    let usage_tokens = calculate_context_tokens(usage);

    // Fall back to heuristic estimation if the provider didn't return usage metrics
    if usage_tokens == 0 {
        let total = messages
            .iter()
            .map(estimate_tokens)
            .fold(0u64, u64::saturating_add);
        return ContextUsageEstimate {
            tokens: total,
            last_usage_index: None,
        };
    }

    let trailing_tokens = messages[usage_index + 1..]
        .iter()
        .map(estimate_tokens)
        .fold(0u64, u64::saturating_add);

    // Calibration (bd-cv653.7.1): when measured usage exists, estimate the
    // SAME span with the active counter and log the drift so the compaction
    // quality harness can observe token_estimate_delta over time.
    let estimated_total = messages
        .iter()
        .map(estimate_tokens)
        .fold(0u64, u64::saturating_add);
    let measured_total = usage_tokens.saturating_add(trailing_tokens);
    if estimated_total > 0 && measured_total > 0 {
        let delta = i64::try_from(estimated_total).unwrap_or(i64::MAX)
            - i64::try_from(measured_total).unwrap_or(i64::MAX);
        #[allow(clippy::cast_precision_loss)] // diagnostic ratio only
        let ratio = estimated_total as f64 / measured_total as f64;
        tracing::debug!(
            event = "pi.compaction.token_estimate_delta",
            estimated_total,
            measured_total,
            delta,
            ratio,
            "token estimate calibration"
        );
    }

    ContextUsageEstimate {
        tokens: measured_total,
        last_usage_index: Some(usage_index),
    }
}

/// Heuristic estimate of the model-context tokens contributed by a slice of
/// session entries, using the same char-based estimator (`estimate_tokens`) as
/// the rest of the compaction module.
///
/// Unlike [`estimate_context_tokens`], this deliberately ignores any retained
/// assistant `usage` metrics: those belong to the *pre-compaction* provider
/// request and would massively inflate an estimate of the context the *next*
/// request will see. Callers use this to compute the `tokensAfter` field of
/// compaction result payloads — the estimated size of the post-compaction
/// current-path context.
///
/// The estimate is computed by reference: entries are converted to messages
/// lazily, one at a time, so the full post-compaction message list is never
/// materialized.
#[must_use]
pub fn estimate_entries_context_tokens(entries: &[&SessionEntry]) -> u64 {
    entries
        .iter()
        .copied()
        .filter_map(message_from_entry)
        .map(|msg| estimate_tokens(&msg))
        .fold(0u64, u64::saturating_add)
}

fn should_compact(
    context_tokens: u64,
    context_window: u32,
    settings: &ResolvedCompactionSettings,
) -> bool {
    if !settings.enabled {
        return false;
    }
    let reserve = u64::from(settings.reserve_tokens);
    let window = u64::from(context_window);
    context_tokens >= window.saturating_sub(reserve)
}

/// Accumulate one content block's countable text into `text`, or add its
/// flat estimate (images) to `flat_tokens`.
fn accumulate_block_estimate(block: &ContentBlock, text: &mut String, flat_tokens: &mut u64) {
    match block {
        ContentBlock::Text(t) => {
            text.push_str(&t.text);
            text.push('\n');
        }
        ContentBlock::Thinking(thinking) => {
            text.push_str(&thinking.thinking);
            text.push('\n');
        }
        ContentBlock::Image(_) => {
            *flat_tokens =
                flat_tokens.saturating_add((IMAGE_CHAR_ESTIMATE / CHARS_PER_TOKEN_ESTIMATE) as u64);
        }
        ContentBlock::ToolCall(call) => {
            text.push_str(&call.name);
            text.push('\n');
            if let Ok(args) = serde_json::to_string(&call.arguments) {
                text.push_str(&args);
            }
        }
        // Opaque marker — the data field is never replayed to a model
        // (see `convert_content_block_to_anthropic`), so it contributes
        // zero context tokens.
        ContentBlock::RedactedThinking(_) => {}
    }
}

fn estimate_tokens(message: &SessionMessage) -> u64 {
    // BPE counting (bd-cv653.7.1): accumulate the countable text and count
    // it with the active counter (real O200k/Cl100k-class tables when the
    // `bpe-tokens` feature is on; chars/4 when off). Measured API usage
    // still wins upstream; this replaces only the heuristic path. Images
    // keep their flat estimate.
    let mut text = String::new();
    let mut flat_tokens: u64 = 0;
    let mut assistant_provider: Option<&str> = None;

    match message {
        SessionMessage::User { content, .. } => match content {
            UserContent::Text(t) => text.push_str(t),
            UserContent::Blocks(blocks) => {
                for block in blocks {
                    accumulate_block_estimate(block, &mut text, &mut flat_tokens);
                }
            }
        },
        SessionMessage::Assistant { message } => {
            assistant_provider = Some(message.provider.as_str());
            for block in &message.content {
                accumulate_block_estimate(block, &mut text, &mut flat_tokens);
            }
        }
        SessionMessage::ToolResult { content, .. } => {
            for block in content {
                accumulate_block_estimate(block, &mut text, &mut flat_tokens);
            }
        }
        SessionMessage::Custom { content, .. } => text.push_str(content),
        SessionMessage::BashExecution {
            command, output, ..
        } => {
            text.push_str(command);
            text.push('\n');
            text.push_str(output);
        }
        SessionMessage::BranchSummary { summary, .. }
        | SessionMessage::CompactionSummary { summary, .. } => text.push_str(summary),
    }

    let table = assistant_provider.map_or(
        crate::token_count::TokenTable::O200k,
        crate::token_count::table_for_provider,
    );
    flat_tokens.saturating_add(crate::token_count::active_counter().count(&text, table))
}

// =============================================================================
// Cut point detection
// =============================================================================

#[derive(Debug, Clone, Copy)]
struct CutPointResult {
    first_kept_entry_index: usize,
    turn_start_index: Option<usize>,
    is_split_turn: bool,
}

fn message_from_entry(entry: &SessionEntry) -> Option<SessionMessage> {
    match entry {
        SessionEntry::Message(msg_entry) => Some(msg_entry.message.clone()),
        SessionEntry::BranchSummary(summary) => Some(SessionMessage::BranchSummary {
            summary: summary.summary.clone(),
            from_id: summary.from_id.clone(),
        }),
        SessionEntry::Compaction(compaction) => Some(SessionMessage::CompactionSummary {
            summary: compaction.summary.clone(),
            tokens_before: compaction.tokens_before,
        }),
        _ => None,
    }
}

const fn entry_is_message_like(entry: &SessionEntry) -> bool {
    matches!(
        entry,
        SessionEntry::Message(_) | SessionEntry::BranchSummary(_)
    )
}

const fn entry_is_compaction_boundary(entry: &SessionEntry) -> bool {
    matches!(entry, SessionEntry::Compaction(_))
}

fn find_valid_cut_points(
    entries: &[SessionEntry],
    start_index: usize,
    end_index: usize,
) -> Vec<usize> {
    let mut cut_points = Vec::new();
    for (idx, entry) in entries.iter().enumerate().take(end_index).skip(start_index) {
        match entry {
            SessionEntry::Message(msg_entry) => match msg_entry.message {
                SessionMessage::ToolResult { .. } => {}
                _ => cut_points.push(idx),
            },
            SessionEntry::BranchSummary(_) => cut_points.push(idx),
            _ => {}
        }
    }
    cut_points
}

fn entry_has_tool_calls(entry: &SessionEntry) -> bool {
    matches!(
        entry,
        SessionEntry::Message(msg) if matches!(
            &msg.message,
            SessionMessage::Assistant { message } if message.content.iter().any(|b| matches!(b, ContentBlock::ToolCall(_)))
        )
    )
}

const fn is_user_turn_start(entry: &SessionEntry) -> bool {
    match entry {
        SessionEntry::BranchSummary(_) => true,
        SessionEntry::Message(msg_entry) => matches!(
            msg_entry.message,
            SessionMessage::User { .. } | SessionMessage::BashExecution { .. }
        ),
        _ => false,
    }
}

fn find_turn_start_index(
    entries: &[SessionEntry],
    entry_index: usize,
    start_index: usize,
) -> Option<usize> {
    (start_index..=entry_index)
        .rev()
        .find(|&idx| is_user_turn_start(&entries[idx]))
}

fn find_cut_point(
    entries: &[SessionEntry],
    start_index: usize,
    end_index: usize,
    keep_recent_tokens: u32,
) -> CutPointResult {
    let cut_points = find_valid_cut_points(entries, start_index, end_index);
    if cut_points.is_empty() {
        return CutPointResult {
            first_kept_entry_index: start_index,
            turn_start_index: None,
            is_split_turn: false,
        };
    }

    let mut accumulated_tokens: u64 = 0;
    let mut cut_index = cut_points[0];

    for i in (start_index..end_index).rev() {
        let entry = &entries[i];
        if let Some(msg) = message_from_entry(entry) {
            accumulated_tokens = accumulated_tokens.saturating_add(estimate_tokens(&msg));
        } else {
            continue;
        }

        if accumulated_tokens >= u64::from(keep_recent_tokens) {
            // Binary search: find the largest cut point <= i.
            // `partition_point` returns the index of the first element > i,
            // so idx-1 is the largest element <= i (if any).
            let pos = cut_points.partition_point(|&cp| cp <= i);
            if pos > 0 {
                cut_index = cut_points[pos - 1];
            }
            // else: no cut point <= i, keep the fallback (cut_points[0])
            break;
        }
    }

    while cut_index > start_index {
        let prev = &entries[cut_index - 1];
        if entry_is_compaction_boundary(prev) {
            break;
        }
        if entry_is_message_like(prev) {
            break;
        }
        cut_index -= 1;
    }

    let is_user_message = is_user_turn_start(&entries[cut_index]);
    let turn_start_index = if is_user_message {
        None
    } else {
        find_turn_start_index(entries, cut_index, start_index)
    };

    CutPointResult {
        first_kept_entry_index: cut_index,
        turn_start_index,
        is_split_turn: !is_user_message && turn_start_index.is_some(),
    }
}

// =============================================================================
// Summarization prompts
// =============================================================================

const SUMMARIZATION_SYSTEM_PROMPT: &str = "You are a context summarization assistant. Your task is to read a conversation between a user and an AI coding assistant, then produce a structured summary following the exact format specified.\n\nDo NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.";

const SUMMARIZATION_PROMPT: &str = "The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.\n\nUse this EXACT format:\n\n## Goal\n[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned by user]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Current work]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [Ordered list of what should happen next]\n\n## Critical Context\n- [Any data, examples, or references needed to continue]\n- [Or \"(none)\" if not applicable]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.";

const UPDATE_SUMMARIZATION_PROMPT: &str = "The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.\n\nUpdate the existing structured summary with new information. RULES:\n- PRESERVE all existing information from the previous summary\n- ADD new progress, decisions, and context from the new messages\n- UPDATE the Progress section: move items from \"In Progress\" to \"Done\" when completed\n- UPDATE \"Next Steps\" based on what was accomplished\n- PRESERVE exact file paths, function names, and error messages\n- If something is no longer relevant, you may remove it\n\nUse this EXACT format:\n\n## Goal\n[Preserve existing goals, add new ones if the task expanded]\n\n## Constraints & Preferences\n- [Preserve existing, add new ones discovered]\n\n## Progress\n### Done\n- [x] [Include previously done items AND newly completed items]\n\n### In Progress\n- [ ] [Current work - update based on progress]\n\n### Blocked\n- [Current blockers - remove if resolved]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale] (preserve all previous, add new)\n\n## Next Steps\n1. [Update based on current state]\n\n## Critical Context\n- [Preserve important context, add new if needed]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.";

const TURN_PREFIX_SUMMARIZATION_PROMPT: &str = "This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.\n\nSummarize the prefix to provide context for the retained suffix:\n\n## Original Request\n[What did the user ask for in this turn?]\n\n## Early Progress\n- [Key decisions and work done in the prefix]\n\n## Context for Suffix\n- [Information needed to understand the retained recent work]\n\nBe concise. Focus on what's needed to understand the kept suffix.";

fn push_message_separator(out: &mut String) {
    if !out.is_empty() {
        out.push_str("\n\n");
    }
}

fn user_has_serializable_content(user: &UserMessage) -> bool {
    match &user.content {
        UserContent::Text(text) => !text.is_empty(),
        UserContent::Blocks(blocks) => blocks
            .iter()
            .any(|c| matches!(c, ContentBlock::Text(t) if !t.text.is_empty())),
    }
}

fn append_user_message(out: &mut String, user: &UserMessage) {
    if !user_has_serializable_content(user) {
        return;
    }

    push_message_separator(out);
    out.push_str("[User]: ");
    match &user.content {
        UserContent::Text(text) => out.push_str(text),
        UserContent::Blocks(blocks) => {
            for block in blocks {
                if let ContentBlock::Text(text) = block {
                    out.push_str(&text.text);
                }
            }
        }
    }
}

fn append_custom_message(out: &mut String, custom_type: &str, content: &str) {
    if content.trim().is_empty() {
        return;
    }

    push_message_separator(out);
    out.push('[');
    if custom_type.trim().is_empty() {
        out.push_str("Custom");
    } else {
        out.push_str("Custom:");
        out.push_str(custom_type);
    }
    out.push_str("]: ");
    out.push_str(content);
}

fn assistant_content_flags(assistant: &AssistantMessage) -> (bool, bool, bool) {
    let mut has_thinking = false;
    let mut has_text = false;
    let mut has_tools = false;
    for block in &assistant.content {
        match block {
            ContentBlock::Thinking(_) => has_thinking = true,
            ContentBlock::Text(_) => has_text = true,
            ContentBlock::ToolCall(_) => has_tools = true,
            // Redacted thinking has no surfaceable content, so don't flip
            // has_thinking — that would produce an empty `[Assistant thinking]:`
            // section in the compaction output.
            ContentBlock::Image(_) | ContentBlock::RedactedThinking(_) => {}
        }
    }
    (has_thinking, has_text, has_tools)
}

fn append_assistant_thinking(out: &mut String, assistant: &AssistantMessage) {
    push_message_separator(out);
    out.push_str("[Assistant thinking]: ");
    let mut first = true;
    for block in &assistant.content {
        if let ContentBlock::Thinking(thinking) = block {
            if !first {
                out.push('\n');
            }
            out.push_str(&thinking.thinking);
            first = false;
        }
    }
}

fn append_assistant_text(out: &mut String, assistant: &AssistantMessage) {
    push_message_separator(out);
    out.push_str("[Assistant]: ");
    let mut first = true;
    for block in &assistant.content {
        if let ContentBlock::Text(text) = block {
            if !first {
                out.push('\n');
            }
            out.push_str(&text.text);
            first = false;
        }
    }
}

fn append_tool_call_arguments(out: &mut String, arguments: &Value) {
    if let Some(obj) = arguments.as_object() {
        let mut first_kv = true;
        for (k, v) in obj {
            if !first_kv {
                out.push_str(", ");
            }
            out.push_str(k);
            out.push('=');
            match serde_json::to_string(v) {
                Ok(s) => out.push_str(&s),
                Err(_) => {
                    let _ = write!(out, "{v}");
                }
            }
            first_kv = false;
        }
    } else {
        match serde_json::to_string(arguments) {
            Ok(s) => out.push_str(&s),
            Err(_) => {
                let _ = write!(out, "{arguments}");
            }
        }
    }
}

fn append_assistant_tool_calls(out: &mut String, assistant: &AssistantMessage) {
    push_message_separator(out);
    out.push_str("[Assistant tool calls]: ");
    let mut first = true;
    for block in &assistant.content {
        if let ContentBlock::ToolCall(call) = block {
            if !first {
                out.push_str("; ");
            }
            out.push_str(&call.name);
            out.push('(');
            append_tool_call_arguments(out, &call.arguments);
            out.push(')');
            first = false;
        }
    }
}

fn append_assistant_message(out: &mut String, assistant: &AssistantMessage) {
    let (has_thinking, has_text, has_tools) = assistant_content_flags(assistant);
    if has_thinking {
        append_assistant_thinking(out, assistant);
    }
    if has_text {
        append_assistant_text(out, assistant);
    }
    if has_tools {
        append_assistant_tool_calls(out, assistant);
    }
}

fn tool_result_has_serializable_content(content: &[ContentBlock]) -> bool {
    content
        .iter()
        .any(|c| matches!(c, ContentBlock::Text(t) if !t.text.is_empty()))
}

fn append_tool_result_message(out: &mut String, content: &[ContentBlock]) {
    if !tool_result_has_serializable_content(content) {
        return;
    }

    push_message_separator(out);
    out.push_str("[Tool result]: ");
    for block in content {
        if let ContentBlock::Text(text) = block {
            out.push_str(&text.text);
        }
    }
}

fn collect_text_blocks(blocks: &[ContentBlock]) -> String {
    let mut out = String::new();
    let mut first = true;
    for block in blocks {
        if let ContentBlock::Text(text) = block {
            if !first {
                out.push('\n');
            }
            out.push_str(&text.text);
            first = false;
        }
    }
    out
}

fn serialize_conversation(messages: &[Message]) -> String {
    let mut out = String::new();

    for msg in messages {
        match msg {
            Message::User(user) => append_user_message(&mut out, user),
            Message::Custom(custom) => {
                append_custom_message(&mut out, &custom.custom_type, &custom.content);
            }
            Message::Assistant(assistant) => append_assistant_message(&mut out, assistant),
            Message::ToolResult(tool) => append_tool_result_message(&mut out, &tool.content),
        }
    }

    out
}

async fn complete_simple(
    provider: Arc<dyn Provider>,
    system_prompt: &str,
    prompt_text: String,
    api_key: &str,
    reserve_tokens: u32,
    max_tokens_factor: f64,
) -> Result<AssistantMessage> {
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let max_tokens = (f64::from(reserve_tokens) * max_tokens_factor).floor() as u32;
    let max_tokens = max_tokens.max(256);

    let context = Context {
        system_prompt: Some(system_prompt.to_string().into()),
        messages: vec![Message::User(UserMessage {
            content: UserContent::Blocks(vec![ContentBlock::Text(TextContent::new(prompt_text))]),
            timestamp: chrono::Utc::now().timestamp_millis(),
        })]
        .into(),
        tools: Vec::new().into(),
    };

    let options = StreamOptions {
        api_key: Some(api_key.to_string()),
        max_tokens: Some(max_tokens),
        thinking_level: Some(ThinkingLevel::High),
        ..Default::default()
    };

    let mut stream = provider.stream(&context, &options).await?;
    let mut final_message: Option<AssistantMessage> = None;

    while let Some(event) = stream.next().await {
        match event? {
            crate::model::StreamEvent::Done { message, .. } => {
                final_message = Some(message);
            }
            crate::model::StreamEvent::Error { error, .. } => {
                let msg = error
                    .error_message
                    .unwrap_or_else(|| "Summarization error".to_string());
                return Err(Error::api(msg));
            }
            _ => {}
        }
    }

    let message = final_message.ok_or_else(|| Error::api("Stream ended without Done event"))?;
    if matches!(message.stop_reason, StopReason::Aborted | StopReason::Error) {
        let msg = message
            .error_message
            .unwrap_or_else(|| "Summarization error".to_string());
        return Err(Error::api(msg));
    }
    Ok(message)
}

async fn generate_summary(
    messages: &[SessionMessage],
    provider: Arc<dyn Provider>,
    api_key: &str,
    settings: &ResolvedCompactionSettings,
    custom_instructions: Option<&str>,
    previous_summary: Option<&str>,
) -> Result<String> {
    let base_prompt = if previous_summary.is_some() {
        UPDATE_SUMMARIZATION_PROMPT
    } else {
        SUMMARIZATION_PROMPT
    };

    let mut prompt = base_prompt.to_string();
    if let Some(custom) = custom_instructions.filter(|s| !s.trim().is_empty()) {
        let _ = write!(prompt, "\n\nAdditional focus: {custom}");
    }

    let llm_messages = messages
        .iter()
        .filter_map(session_message_to_model)
        .collect::<Vec<_>>();
    let conversation_text = serialize_conversation(&llm_messages);

    let mut prompt_text = format!("<conversation>\n{conversation_text}\n</conversation>\n\n");
    if let Some(previous) = previous_summary {
        let _ = write!(
            prompt_text,
            "<previous-summary>\n{previous}\n</previous-summary>\n\n"
        );
    }
    prompt_text.push_str(&prompt);

    let assistant = complete_simple(
        provider,
        SUMMARIZATION_SYSTEM_PROMPT,
        prompt_text,
        api_key,
        settings.reserve_tokens,
        0.8,
    )
    .await?;

    let text = collect_text_blocks(&assistant.content);

    if text.trim().is_empty() {
        return Err(Error::api(
            "Summarization returned empty text; refusing to store empty compaction summary",
        ));
    }

    Ok(text)
}

async fn generate_turn_prefix_summary(
    messages: &[SessionMessage],
    provider: Arc<dyn Provider>,
    api_key: &str,
    settings: &ResolvedCompactionSettings,
) -> Result<String> {
    let llm_messages = messages
        .iter()
        .filter_map(session_message_to_model)
        .collect::<Vec<_>>();
    let conversation_text = serialize_conversation(&llm_messages);
    let prompt_text = format!(
        "<conversation>\n{conversation_text}\n</conversation>\n\n{TURN_PREFIX_SUMMARIZATION_PROMPT}"
    );

    let assistant = complete_simple(
        provider,
        SUMMARIZATION_SYSTEM_PROMPT,
        prompt_text,
        api_key,
        settings.reserve_tokens,
        0.5,
    )
    .await?;

    let text = collect_text_blocks(&assistant.content);

    if text.trim().is_empty() {
        return Err(Error::api(
            "Turn prefix summarization returned empty text; refusing to store empty summary",
        ));
    }

    Ok(text)
}

// =============================================================================
// Deterministic fallback summarization (no LLM)
// =============================================================================

/// Maximum visible characters retained per message excerpt in a deterministic
/// fallback summary.
const FALLBACK_SNIPPET_MAX_CHARS: usize = 400;

/// Multiplier over the configured context window at which a quota-blocked
/// background compaction escalates to a synchronous, provider-free local
/// compaction so the session cannot grow without bound.
pub const FORCED_LOCAL_COMPACTION_WINDOW_FACTOR: u64 = 2;

/// Whether the session is so far past its context window that compaction must
/// proceed even when the background worker is quota-blocked.
#[must_use]
pub fn requires_forced_local_compaction(
    tokens_before: u64,
    settings: &ResolvedCompactionSettings,
) -> bool {
    settings.enabled
        && tokens_before
            >= u64::from(settings.context_window_tokens)
                .saturating_mul(FORCED_LOCAL_COMPACTION_WINDOW_FACTOR)
}

/// Keep the head and tail of `text`, eliding the middle so the result stays
/// within roughly `max_chars` visible characters plus a short elision marker.
///
/// Operates on `char` boundaries so multi-byte text is never split.
fn truncate_middle(text: &str, max_chars: usize) -> String {
    let total = text.chars().count();
    if total <= max_chars {
        return text.to_string();
    }

    let head = (max_chars * 2 / 3).max(1);
    let tail = max_chars.saturating_sub(head);
    let elided = total - head - tail;

    let head_text: String = text.chars().take(head).collect();
    let tail_text: String = text.chars().skip(total - tail).collect();
    format!("{head_text}\n… [{elided} chars elided] …\n{tail_text}")
}

/// Render one session message as a truncated excerpt using the same
/// serialization the LLM summarization prompt uses (`[User]:`, `[Assistant]:`,
/// tool call/result labels).
fn fallback_message_snippet(message: &SessionMessage) -> Option<String> {
    let model_message = session_message_to_model(message)?;
    let serialized = serialize_conversation(std::slice::from_ref(&model_message));
    if serialized.trim().is_empty() {
        return None;
    }
    Some(truncate_middle(&serialized, FALLBACK_SNIPPET_MAX_CHARS))
}

/// Build a deterministic, provider-free replacement for the LLM compaction
/// summary: the previous summary (if any) followed by head/tail excerpts of
/// each discarded message, bounded so the result fits comfortably inside the
/// configured reserve budget.
fn build_fallback_summary(preparation: &CompactionPreparation) -> String {
    let budget_chars = usize::try_from(preparation.settings.reserve_tokens)
        .unwrap_or(usize::MAX)
        .saturating_mul(CHARS_PER_TOKEN_ESTIMATE)
        / 2;
    let max_snippets = (budget_chars / FALLBACK_SNIPPET_MAX_CHARS).max(2);

    let mut out = String::from(
        "## Context Checkpoint (deterministic fallback)\n\n\
         LLM summarization was unavailable, so this checkpoint preserves truncated \
         excerpts of the compacted history instead of a model-written summary. \
         Excerpts may be incomplete; prefer the retained recent messages for \
         precise details.",
    );

    if let Some(previous) = preparation
        .previous_summary
        .as_deref()
        .filter(|summary| !summary.trim().is_empty())
    {
        out.push_str("\n\n## Previous Summary\n\n");
        out.push_str(&truncate_middle(previous, budget_chars.max(1)));
    }

    let snippets = preparation
        .messages_to_summarize
        .iter()
        .chain(preparation.turn_prefix_messages.iter())
        .filter_map(fallback_message_snippet)
        .collect::<Vec<_>>();

    if snippets.is_empty() {
        return out;
    }

    out.push_str("\n\n## History Excerpts (truncated)");
    if snippets.len() <= max_snippets {
        for snippet in &snippets {
            out.push_str("\n\n");
            out.push_str(snippet);
        }
    } else {
        // Keep the oldest and newest excerpts; elide the middle. Early
        // messages carry the original goal, late messages carry current state.
        let head = max_snippets.div_ceil(2);
        let tail = max_snippets - head;
        let elided = snippets.len() - max_snippets;
        for snippet in &snippets[..head] {
            out.push_str("\n\n");
            out.push_str(snippet);
        }
        let _ = write!(out, "\n\n[... {elided} older messages elided ...]");
        for snippet in &snippets[snippets.len() - tail..] {
            out.push_str("\n\n");
            out.push_str(snippet);
        }
    }

    out
}

// =============================================================================
// Public API
// =============================================================================

#[allow(clippy::too_many_lines)]
pub fn prepare_compaction(
    path_entries: &[SessionEntry],
    settings: ResolvedCompactionSettings,
) -> Option<CompactionPreparation> {
    if path_entries.is_empty() {
        return None;
    }

    if path_entries
        .last()
        .is_some_and(|entry| matches!(entry, SessionEntry::Compaction(_)))
    {
        return None;
    }

    let mut prev_compaction_index: Option<usize> = None;
    for (idx, entry) in path_entries.iter().enumerate().rev() {
        if matches!(entry, SessionEntry::Compaction(_)) {
            prev_compaction_index = Some(idx);
            break;
        }
    }

    let boundary_start = prev_compaction_index.map_or(0, |i| i + 1);
    let boundary_end = path_entries.len();

    let usage_start = prev_compaction_index.unwrap_or(0);
    let mut usage_messages = Vec::new();
    for entry in &path_entries[usage_start..boundary_end] {
        if let Some(msg) = message_from_entry(entry) {
            usage_messages.push(msg);
        }
    }
    // Calculate the tokens *currently* occupied by the segment we are about to compact.
    // If the segment includes a previous compaction summary, this counts the *summary* tokens,
    // not the original uncompressed history tokens. This effectively tracks the "compressed size"
    // of the history prior to the new cut point.
    let tokens_before = estimate_context_tokens(&usage_messages).tokens;

    if !should_compact(tokens_before, settings.context_window_tokens, &settings) {
        return None;
    }

    let cut_point = find_cut_point(
        path_entries,
        boundary_start,
        boundary_end,
        settings.keep_recent_tokens,
    );

    let first_kept_entry = &path_entries[cut_point.first_kept_entry_index];
    let first_kept_entry_id = first_kept_entry.base_id()?.clone();

    let history_end = if cut_point.is_split_turn {
        cut_point.turn_start_index?
    } else {
        cut_point.first_kept_entry_index
    };

    let mut messages_to_summarize = Vec::new();
    for entry in &path_entries[boundary_start..history_end] {
        if let Some(msg) = message_from_entry(entry) {
            messages_to_summarize.push(msg);
        }
    }

    let mut turn_prefix_messages = Vec::new();
    if cut_point.is_split_turn {
        let turn_start = cut_point.turn_start_index?;
        for entry in &path_entries[turn_start..cut_point.first_kept_entry_index] {
            if let Some(msg) = message_from_entry(entry) {
                turn_prefix_messages.push(msg);
            }
        }
    }

    // No-op compaction: if there's nothing to summarize, don't issue an LLM call and don't append a
    // compaction entry. This can happen early in a session (e.g. session header entries only).
    if messages_to_summarize.is_empty() && turn_prefix_messages.is_empty() {
        return None;
    }

    let previous_summary = prev_compaction_index.and_then(|idx| match &path_entries[idx] {
        SessionEntry::Compaction(entry) => Some(entry.summary.clone()),
        _ => None,
    });

    let mut file_ops = FileOperations::default();

    // Collect file tracking from previous compaction details if pi-generated.
    if let Some(idx) = prev_compaction_index
        && let SessionEntry::Compaction(entry) = &path_entries[idx]
        && !entry.from_hook.unwrap_or(false)
        && let Some(details) = entry.details.as_ref().and_then(Value::as_object)
    {
        if let Some(read_files) = details.get("readFiles").and_then(Value::as_array) {
            for item in read_files.iter().filter_map(Value::as_str) {
                file_ops.read.insert(item.to_string());
            }
        }
        if let Some(modified_files) = details.get("modifiedFiles").and_then(Value::as_array) {
            for item in modified_files.iter().filter_map(Value::as_str) {
                file_ops.edited.insert(item.to_string());
            }
        }
    }

    let mut tool_status = build_tool_status_map(&messages_to_summarize);
    tool_status.extend(build_tool_status_map(&turn_prefix_messages));

    for msg in &messages_to_summarize {
        extract_file_ops_from_message(msg, &mut file_ops, &tool_status);
    }
    for msg in &turn_prefix_messages {
        extract_file_ops_from_message(msg, &mut file_ops, &tool_status);
    }

    Some(CompactionPreparation {
        first_kept_entry_id,
        messages_to_summarize,
        turn_prefix_messages,
        is_split_turn: cut_point.is_split_turn,
        tokens_before,
        previous_summary,
        file_ops,
        settings,
    })
}

pub async fn summarize_entries(
    entries: &[SessionEntry],
    provider: Arc<dyn Provider>,
    api_key: &str,
    reserve_tokens: u32,
    custom_instructions: Option<&str>,
) -> Result<Option<String>> {
    let mut messages = Vec::new();
    for entry in entries {
        if let Some(message) = message_from_entry(entry) {
            messages.push(message);
        }
    }

    if messages.is_empty() {
        return Ok(None);
    }

    let settings = ResolvedCompactionSettings {
        enabled: true,
        reserve_tokens,
        keep_recent_tokens: 0,
        ..Default::default()
    };

    let summary = generate_summary(
        &messages,
        provider,
        api_key,
        &settings,
        custom_instructions,
        None,
    )
    .await?;

    Ok(Some(summary))
}

/// Generate the LLM-written compaction summary for `preparation`.
///
/// Errors here (provider failures, oversized summarization prompts, empty
/// responses) are recoverable once the session is past the forced-local
/// threshold: [`compact`] then falls back to a deterministic local summary
/// instead of propagating them.
async fn generate_llm_summary(
    preparation: &CompactionPreparation,
    provider: Arc<dyn Provider>,
    api_key: &str,
    custom_instructions: Option<&str>,
) -> Result<String> {
    if preparation.is_split_turn && !preparation.turn_prefix_messages.is_empty() {
        let history_summary = if preparation.messages_to_summarize.is_empty() {
            "No prior history.".to_string()
        } else {
            generate_summary(
                &preparation.messages_to_summarize,
                Arc::clone(&provider),
                api_key,
                &preparation.settings,
                custom_instructions,
                preparation.previous_summary.as_deref(),
            )
            .await?
        };

        let turn_prefix_summary = generate_turn_prefix_summary(
            &preparation.turn_prefix_messages,
            Arc::clone(&provider),
            api_key,
            &preparation.settings,
        )
        .await?;

        Ok(format!(
            "{history_summary}\n\n---\n\n**Turn Context (split turn):**\n\n{turn_prefix_summary}"
        ))
    } else {
        generate_summary(
            &preparation.messages_to_summarize,
            Arc::clone(&provider),
            api_key,
            &preparation.settings,
            custom_instructions,
            preparation.previous_summary.as_deref(),
        )
        .await
    }
}

/// Attach file-operation lists and cut-point metadata to a finished summary.
fn finish_compaction(preparation: CompactionPreparation, mut summary: String) -> CompactionResult {
    let (read_files, modified_files) = compute_file_lists(&preparation.file_ops);
    let details = CompactionDetails {
        read_files: read_files.clone(),
        modified_files: modified_files.clone(),
        mode: None,
    };

    summary.push_str(&format_file_operations(&read_files, &modified_files));

    CompactionResult {
        summary,
        first_kept_entry_id: preparation.first_kept_entry_id,
        tokens_before: preparation.tokens_before,
        details,
    }
}

pub async fn compact(
    preparation: CompactionPreparation,
    provider: Arc<dyn Provider>,
    api_key: &str,
    custom_instructions: Option<&str>,
) -> Result<CompactionResult> {
    let summary = match generate_llm_summary(&preparation, provider, api_key, custom_instructions)
        .await
    {
        Ok(summary) => summary,
        Err(error) => {
            // An oversized session makes the summarization prompt itself
            // oversized, so the provider call fails for exactly the
            // sessions that most need compaction. Failing compaction there
            // would let the session grow without bound; degrade to a
            // deterministic local summary instead. Below the forced-local
            // threshold the failure is likely transient (rate limit, network
            // blip) and retrying with the provider later beats permanently
            // storing a degraded truncation summary, so propagate the error
            // and let the worker's cooldown/attempt-limit machinery (and
            // eventually the forced-local failsafe) govern.
            if !requires_forced_local_compaction(preparation.tokens_before, &preparation.settings) {
                return Err(error);
            }
            tracing::warn!(
                error = %error,
                "LLM compaction summarization failed; using deterministic local fallback summary"
            );
            build_fallback_summary(&preparation)
        }
    };

    Ok(finish_compaction(preparation, summary))
}

/// Provider-free compaction: summarize `preparation` with the deterministic
/// truncation-based fallback, never contacting the LLM.
///
/// Used as a failsafe when background LLM compaction is quota-blocked but the
/// session has grown far beyond the context window.
#[must_use]
pub fn compact_local(preparation: CompactionPreparation) -> CompactionResult {
    let summary = build_fallback_summary(&preparation);
    finish_compaction(preparation, summary)
}

// ── Shake compaction (bd-cv653.3.18) ────────────────────────────────

/// Tool-result payloads at or below this size survive a shake verbatim.
pub const SHAKE_KEEP_RESULT_CHARS: usize = 512;

/// Projected effect of a shake on the to-be-compacted span.
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ShakeProjection {
    pub tokens_before: u64,
    pub projected_tokens: u64,
}

impl ShakeProjection {
    #[must_use]
    pub const fn reclaimed_tokens(&self) -> u64 {
        self.tokens_before.saturating_sub(self.projected_tokens)
    }
}

fn content_blocks_text(content: &[ContentBlock]) -> String {
    let mut text = String::new();
    for block in content {
        if let ContentBlock::Text(part) = block {
            if !text.is_empty() {
                text.push('\n');
            }
            text.push_str(&part.text);
        }
    }
    text
}

/// Deterministic no-LLM "shake" summary: conversation text preserved
/// verbatim, bulky tool-result payloads dropped to one-line stubs. Cheap and
/// instant — the reclaim comes entirely from tool output bulk.
#[must_use]
pub fn build_shake_summary(preparation: &CompactionPreparation) -> String {
    let mut out = String::from(
        "## Context Checkpoint (shake)\n\n\
         Bulky tool results were dropped from this span; the conversation \
         text below is verbatim. Re-run a tool if its full output is needed \
         again.",
    );

    if let Some(previous) = preparation
        .previous_summary
        .as_deref()
        .filter(|summary| !summary.trim().is_empty())
    {
        out.push_str("\n\n## Previous Summary\n\n");
        out.push_str(previous);
    }

    for message in preparation
        .messages_to_summarize
        .iter()
        .chain(preparation.turn_prefix_messages.iter())
    {
        match message {
            SessionMessage::User { content, .. } => {
                let text = match content {
                    UserContent::Text(text) => text.clone(),
                    UserContent::Blocks(blocks) => content_blocks_text(blocks),
                };
                if !text.trim().is_empty() {
                    let _ = write!(out, "\n\n[user]\n{text}");
                }
            }
            SessionMessage::Assistant { message } => {
                let text = content_blocks_text(&message.content);
                if !text.trim().is_empty() {
                    let _ = write!(out, "\n\n[assistant]\n{text}");
                }
                for block in &message.content {
                    if let ContentBlock::ToolCall(call) = block {
                        let _ = write!(out, "\n[assistant called {}]", call.name);
                    }
                }
            }
            SessionMessage::ToolResult {
                tool_name,
                content,
                is_error,
                ..
            } => {
                let text = content_blocks_text(content);
                let status = if *is_error { "failed " } else { "" };
                if text.len() <= SHAKE_KEEP_RESULT_CHARS {
                    let _ = write!(out, "\n\n[{status}tool result {tool_name}]\n{text}");
                } else {
                    let lines = text.lines().count();
                    let _ = write!(
                        out,
                        "\n\n[{status}tool result {tool_name} — {lines} lines / {} bytes dropped; re-run if needed]",
                        text.len()
                    );
                }
            }
            _ => {}
        }
    }

    out
}

/// Provider-free "shake" compaction.
///
/// Replaces the span with a deterministic summary that keeps conversation
/// text and stubs bulky tool results — zero LLM calls. Cut-point and
/// adjacency rules are inherited from [`prepare_compaction`], so no dangling
/// tool-call/result pairs survive.
#[must_use]
pub fn compact_shake(preparation: CompactionPreparation) -> CompactionResult {
    let summary = build_shake_summary(&preparation);
    let mut result = finish_compaction(preparation, summary);
    result.details.mode = Some("shake".to_string());
    result
}

/// Chars/3 token estimate for a summary string (matches the module's
/// internal estimator).
#[must_use]
pub const fn estimate_text_tokens(text: &str) -> u64 {
    (text.len() / CHARS_PER_TOKEN_ESTIMATE) as u64
}

/// Estimate what the compacted span would shrink to under a shake.
#[must_use]
pub fn shake_projection(preparation: &CompactionPreparation) -> ShakeProjection {
    let summary = build_shake_summary(preparation);
    ShakeProjection {
        tokens_before: preparation.tokens_before,
        projected_tokens: (summary.len() / CHARS_PER_TOKEN_ESTIMATE) as u64,
    }
}

/// Shake-first auto policy (bd-cv653.3.18): after a shake, would the span
/// still trip the compaction threshold? True means escalate to the LLM
/// summary; false means the shake alone reclaims enough.
#[must_use]
pub fn shake_first_needs_summary(
    projection: ShakeProjection,
    settings: &ResolvedCompactionSettings,
) -> bool {
    should_compact(
        projection.projected_tokens,
        settings.context_window_tokens,
        settings,
    )
}

pub fn compaction_details_to_value(details: &CompactionDetails) -> Result<Value> {
    serde_json::to_value(details).map_err(|e| Error::session(format!("Compaction details: {e}")))
}

pub mod semantic_marker_scan_quality {
    use super::*;
    use serde_json::json;

    // =============================================================================
    // Semantic compaction quality differential harness
    // =============================================================================

    /// Schema emitted by the deterministic semantic compaction quality harness.
    pub const SEMANTIC_COMPACTION_QUALITY_SCHEMA_V1: &str =
        "pi.session.semantic_compaction_quality.v1";

    const SEMANTIC_QUALITY_MARKER_PREFIX: &str = "[[SCQ:";
    const SEMANTIC_QUALITY_MARKER_SUFFIX: &str = "]]";

    /// One redacted turn or summary chunk to scan for structured semantic markers.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct SemanticCompactionQualityTurn {
        pub branch_id: String,
        pub turn_id: String,
        pub role: String,
        pub content: String,
    }

    impl SemanticCompactionQualityTurn {
        #[must_use]
        pub fn new(
            branch_id: impl Into<String>,
            turn_id: impl Into<String>,
            role: impl Into<String>,
            content: impl Into<String>,
        ) -> Self {
            Self {
                branch_id: branch_id.into(),
                turn_id: turn_id.into(),
                role: role.into(),
                content: content.into(),
            }
        }
    }

    /// Named baseline or candidate view used by the quality evaluator.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct SemanticCompactionQualityView {
        pub name: String,
        pub turns: Vec<SemanticCompactionQualityTurn>,
    }

    impl SemanticCompactionQualityView {
        #[must_use]
        pub fn new(name: impl Into<String>, turns: Vec<SemanticCompactionQualityTurn>) -> Self {
            Self {
                name: name.into(),
                turns,
            }
        }
    }

    /// Redacted summary of an evaluated view.
    #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
    #[serde(rename_all = "camelCase")]
    pub struct SemanticCompactionQualityViewSummary {
        pub name: String,
        pub turn_count: usize,
        pub marker_count: usize,
        pub content_fingerprint: String,
    }

    /// One structured marker occurrence found in a turn.
    #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
    #[serde(rename_all = "camelCase")]
    pub struct SemanticMarkerOccurrence {
        pub id: String,
        pub kind: String,
        pub critical: bool,
        pub declared_branch_id: String,
        pub declared_turn_id: String,
        pub source_view: String,
        pub location_branch_id: String,
        pub location_turn_id: String,
        pub location_role: String,
        pub marker_index: usize,
        pub content_fingerprint: String,
    }

    /// Per-marker differential outcome.
    #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
    #[serde(rename_all = "camelCase")]
    pub struct SemanticCompactionQualityOutcome {
        pub marker_id: String,
        pub status: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub loss_class: Option<String>,
        pub critical: bool,
        pub kind: String,
        pub expected_branch_id: String,
        pub expected_turn_id: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub observed_branch_id: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub observed_turn_id: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub baseline_location: Option<SemanticMarkerOccurrence>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub candidate_location: Option<SemanticMarkerOccurrence>,
    }

    /// False-positive control result for marker IDs that must not be invented.
    #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
    #[serde(rename_all = "camelCase")]
    pub struct SemanticFalsePositiveControlResult {
        pub marker_id: String,
        pub tripped: bool,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub candidate_location: Option<SemanticMarkerOccurrence>,
    }

    /// Aggregate quality counts.
    #[derive(Debug, Clone, Serialize, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct SemanticCompactionQualitySummary {
        pub total_expected_markers: usize,
        pub critical_expected_markers: usize,
        pub preserved_markers: usize,
        pub missing_markers: usize,
        pub wrong_branch_markers: usize,
        pub wrong_turn_markers: usize,
        pub metadata_mismatch_markers: usize,
        pub duplicate_markers: usize,
        pub unexpected_markers: usize,
        pub false_positive_controls_tripped: usize,
        pub marker_coverage: f64,
        pub critical_marker_coverage: f64,
    }

    /// Complete deterministic semantic quality report.
    #[derive(Debug, Clone, Serialize, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct SemanticCompactionQualityReport {
        pub schema: &'static str,
        pub baseline_view: SemanticCompactionQualityViewSummary,
        pub candidate_view: SemanticCompactionQualityViewSummary,
        pub verdict: String,
        pub summary: SemanticCompactionQualitySummary,
        pub outcomes: Vec<SemanticCompactionQualityOutcome>,
        pub false_positive_controls: Vec<SemanticFalsePositiveControlResult>,
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct SemanticMarkerDescriptor {
        id: String,
        kind: String,
        branch_id: String,
        turn_id: String,
        critical: bool,
    }

    /// Build a marker string accepted by the semantic compaction quality harness.
    #[must_use]
    pub fn semantic_compaction_quality_marker(
        id: &str,
        kind: &str,
        branch_id: &str,
        turn_id: &str,
        critical: bool,
    ) -> String {
        format!(
            "{SEMANTIC_QUALITY_MARKER_PREFIX}id={id};kind={kind};branch={branch_id};turn={turn_id};critical={critical}{SEMANTIC_QUALITY_MARKER_SUFFIX}"
        )
    }

    fn normalize_marker_field(value: &str) -> String {
        value.trim().to_ascii_lowercase().replace('-', "_")
    }

    fn parse_semantic_quality_marker(payload: &str) -> Option<SemanticMarkerDescriptor> {
        let mut fields = HashMap::new();
        for raw_part in payload.split(';') {
            let (raw_key, raw_value) = raw_part.split_once('=')?;
            let key = normalize_marker_field(raw_key);
            let value = raw_value.trim();
            if key.is_empty() || value.is_empty() {
                return None;
            }
            fields.insert(key, value.to_string());
        }

        let id = fields.remove("id")?;
        let kind = fields.remove("kind")?;
        let branch_id = fields.remove("branch")?;
        let turn_id = fields.remove("turn")?;
        let critical = fields
            .remove("critical")
            .is_some_and(|value| matches!(value.as_str(), "1" | "true" | "yes" | "critical"));

        Some(SemanticMarkerDescriptor {
            id,
            kind,
            branch_id,
            turn_id,
            critical,
        })
    }

    fn short_content_fingerprint(content: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(content.as_bytes());
        let digest = crate::package_manager::hex_encode(&hasher.finalize());
        digest.chars().take(16).collect()
    }

    fn view_content_fingerprint(turns: &[SemanticCompactionQualityTurn]) -> String {
        let mut hasher = Sha256::new();
        for turn in turns {
            hasher.update(turn.branch_id.as_bytes());
            hasher.update(b"\0");
            hasher.update(turn.turn_id.as_bytes());
            hasher.update(b"\0");
            hasher.update(turn.role.as_bytes());
            hasher.update(b"\0");
            hasher.update(short_content_fingerprint(&turn.content).as_bytes());
            hasher.update(b"\0");
        }
        let digest = crate::package_manager::hex_encode(&hasher.finalize());
        digest.chars().take(16).collect()
    }

    fn semantic_owned(value: &str) -> String {
        value.to_owned()
    }

    fn semantic_occurrence_owned(
        occurrence: &SemanticMarkerOccurrence,
    ) -> SemanticMarkerOccurrence {
        occurrence.clone()
    }

    fn scan_semantic_quality_markers(
        view: &SemanticCompactionQualityView,
    ) -> Vec<SemanticMarkerOccurrence> {
        let mut occurrences = Vec::new();
        for turn in &view.turns {
            let content_fingerprint = short_content_fingerprint(&turn.content);
            let mut search_start = 0usize;
            while let Some(start_rel) =
                turn.content[search_start..].find(SEMANTIC_QUALITY_MARKER_PREFIX)
            {
                let payload_start = search_start + start_rel + SEMANTIC_QUALITY_MARKER_PREFIX.len();
                let Some(end_rel) =
                    turn.content[payload_start..].find(SEMANTIC_QUALITY_MARKER_SUFFIX)
                else {
                    break;
                };
                let payload_end = payload_start + end_rel;
                let payload = &turn.content[payload_start..payload_end];
                if let Some(marker) = parse_semantic_quality_marker(payload) {
                    occurrences.push(SemanticMarkerOccurrence {
                        id: marker.id,
                        kind: marker.kind,
                        critical: marker.critical,
                        declared_branch_id: marker.branch_id,
                        declared_turn_id: marker.turn_id,
                        source_view: semantic_owned(&view.name),
                        location_branch_id: semantic_owned(&turn.branch_id),
                        location_turn_id: semantic_owned(&turn.turn_id),
                        location_role: semantic_owned(&turn.role),
                        marker_index: occurrences.len(),
                        content_fingerprint: semantic_owned(&content_fingerprint),
                    });
                }
                search_start = payload_end + SEMANTIC_QUALITY_MARKER_SUFFIX.len();
            }
        }
        occurrences
    }

    fn occurrences_by_id(
        occurrences: Vec<SemanticMarkerOccurrence>,
    ) -> BTreeMap<String, Vec<SemanticMarkerOccurrence>> {
        let mut by_id: BTreeMap<String, Vec<SemanticMarkerOccurrence>> = BTreeMap::new();
        for occurrence in occurrences {
            by_id
                .entry(semantic_owned(&occurrence.id))
                .or_default()
                .push(occurrence);
        }
        by_id
    }

    #[allow(clippy::cast_precision_loss)]
    fn coverage(preserved: usize, total: usize) -> f64 {
        if total == 0 {
            return 1.0;
        }
        preserved as f64 / total as f64
    }

    fn outcome_for_loss(
        baseline: &SemanticMarkerOccurrence,
        candidate: Option<&SemanticMarkerOccurrence>,
        status: &str,
        loss_class: &str,
    ) -> SemanticCompactionQualityOutcome {
        SemanticCompactionQualityOutcome {
            marker_id: semantic_owned(&baseline.id),
            status: status.to_string(),
            loss_class: Some(loss_class.to_string()),
            critical: baseline.critical,
            kind: semantic_owned(&baseline.kind),
            expected_branch_id: semantic_owned(&baseline.declared_branch_id),
            expected_turn_id: semantic_owned(&baseline.declared_turn_id),
            observed_branch_id: candidate
                .map(|occurrence| semantic_owned(&occurrence.declared_branch_id)),
            observed_turn_id: candidate
                .map(|occurrence| semantic_owned(&occurrence.declared_turn_id)),
            baseline_location: Some(semantic_occurrence_owned(baseline)),
            candidate_location: candidate.map(semantic_occurrence_owned),
        }
    }

    fn outcome_for_preserved(
        baseline: &SemanticMarkerOccurrence,
        candidate: &SemanticMarkerOccurrence,
    ) -> SemanticCompactionQualityOutcome {
        SemanticCompactionQualityOutcome {
            marker_id: semantic_owned(&baseline.id),
            status: "preserved".to_string(),
            loss_class: None,
            critical: baseline.critical,
            kind: semantic_owned(&baseline.kind),
            expected_branch_id: semantic_owned(&baseline.declared_branch_id),
            expected_turn_id: semantic_owned(&baseline.declared_turn_id),
            observed_branch_id: Some(semantic_owned(&candidate.declared_branch_id)),
            observed_turn_id: Some(semantic_owned(&candidate.declared_turn_id)),
            baseline_location: Some(semantic_occurrence_owned(baseline)),
            candidate_location: Some(semantic_occurrence_owned(candidate)),
        }
    }

    fn unexpected_outcome(
        candidate: &SemanticMarkerOccurrence,
        is_control: bool,
    ) -> SemanticCompactionQualityOutcome {
        let loss_class = if is_control {
            "false_positive_control"
        } else {
            "unexpected_marker"
        };
        SemanticCompactionQualityOutcome {
            marker_id: semantic_owned(&candidate.id),
            status: "failed".to_string(),
            loss_class: Some(loss_class.to_string()),
            critical: candidate.critical,
            kind: semantic_owned(&candidate.kind),
            expected_branch_id: String::new(),
            expected_turn_id: String::new(),
            observed_branch_id: Some(semantic_owned(&candidate.declared_branch_id)),
            observed_turn_id: Some(semantic_owned(&candidate.declared_turn_id)),
            baseline_location: None,
            candidate_location: Some(semantic_occurrence_owned(candidate)),
        }
    }

    /// Evaluate whether a compacted/replayed view preserved structured semantic markers.
    #[must_use]
    #[allow(clippy::too_many_lines)]
    pub fn evaluate_semantic_compaction_quality(
        baseline: &SemanticCompactionQualityView,
        candidate: &SemanticCompactionQualityView,
        false_positive_control_ids: &[String],
    ) -> SemanticCompactionQualityReport {
        let baseline_occurrences = scan_semantic_quality_markers(baseline);
        let candidate_occurrences = scan_semantic_quality_markers(candidate);
        let baseline_marker_count = baseline_occurrences.len();
        let candidate_marker_count = candidate_occurrences.len();
        let baseline_by_id = occurrences_by_id(baseline_occurrences);
        let candidate_by_id = occurrences_by_id(candidate_occurrences);
        let controls: BTreeSet<String> = false_positive_control_ids.iter().cloned().collect();

        let mut outcomes = Vec::new();
        let mut preserved_markers = 0usize;
        let mut missing_markers = 0usize;
        let mut wrong_branch_markers = 0usize;
        let mut wrong_turn_markers = 0usize;
        let mut metadata_mismatch_markers = 0usize;
        let mut duplicate_markers = 0usize;
        let mut unexpected_markers = 0usize;
        let mut critical_expected_markers = 0usize;
        let mut critical_preserved_markers = 0usize;

        for (id, baseline_matches) in &baseline_by_id {
            let baseline_marker = &baseline_matches[0];
            critical_expected_markers += usize::from(baseline_marker.critical);

            if baseline_matches.len() > 1 {
                duplicate_markers += 1;
                outcomes.push(outcome_for_loss(
                    baseline_marker,
                    None,
                    "failed",
                    "duplicate_baseline_marker",
                ));
                continue;
            }

            let Some(candidate_matches) = candidate_by_id.get(id) else {
                missing_markers += 1;
                outcomes.push(outcome_for_loss(
                    baseline_marker,
                    None,
                    "failed",
                    "missing_marker",
                ));
                continue;
            };

            if candidate_matches.len() > 1 {
                duplicate_markers += 1;
                outcomes.push(outcome_for_loss(
                    baseline_marker,
                    candidate_matches.first(),
                    "failed",
                    "duplicate_candidate_marker",
                ));
                continue;
            }

            let candidate_marker = &candidate_matches[0];
            if baseline_marker.kind != candidate_marker.kind
                || baseline_marker.critical != candidate_marker.critical
            {
                metadata_mismatch_markers += 1;
                outcomes.push(outcome_for_loss(
                    baseline_marker,
                    Some(candidate_marker),
                    "failed",
                    "metadata_mismatch",
                ));
            } else if baseline_marker.declared_branch_id != candidate_marker.declared_branch_id {
                wrong_branch_markers += 1;
                outcomes.push(outcome_for_loss(
                    baseline_marker,
                    Some(candidate_marker),
                    "failed",
                    "wrong_branch",
                ));
            } else if baseline_marker.declared_turn_id != candidate_marker.declared_turn_id {
                wrong_turn_markers += 1;
                outcomes.push(outcome_for_loss(
                    baseline_marker,
                    Some(candidate_marker),
                    "failed",
                    "wrong_turn",
                ));
            } else {
                preserved_markers += 1;
                critical_preserved_markers += usize::from(baseline_marker.critical);
                outcomes.push(outcome_for_preserved(baseline_marker, candidate_marker));
            }
        }

        let mut false_positive_controls = Vec::new();
        let mut false_positive_controls_tripped = 0usize;
        for marker_id in &controls {
            let candidate_location = candidate_by_id
                .get(marker_id)
                .and_then(|matches| matches.first())
                .map(semantic_occurrence_owned);
            let tripped = candidate_location.is_some();
            false_positive_controls_tripped += usize::from(tripped);
            false_positive_controls.push(SemanticFalsePositiveControlResult {
                marker_id: semantic_owned(marker_id),
                tripped,
                candidate_location,
            });
        }

        for (id, candidate_matches) in &candidate_by_id {
            if baseline_by_id.contains_key(id) {
                continue;
            }
            unexpected_markers += 1;
            outcomes.push(unexpected_outcome(
                &candidate_matches[0],
                controls.contains(id),
            ));
        }

        outcomes.sort_by(|a, b| a.marker_id.cmp(&b.marker_id));
        false_positive_controls.sort_by(|a, b| a.marker_id.cmp(&b.marker_id));

        let total_expected_markers = baseline_by_id.len();
        let summary = SemanticCompactionQualitySummary {
            total_expected_markers,
            critical_expected_markers,
            preserved_markers,
            missing_markers,
            wrong_branch_markers,
            wrong_turn_markers,
            metadata_mismatch_markers,
            duplicate_markers,
            unexpected_markers,
            false_positive_controls_tripped,
            marker_coverage: coverage(preserved_markers, total_expected_markers),
            critical_marker_coverage: coverage(
                critical_preserved_markers,
                critical_expected_markers,
            ),
        };

        let failed = summary.missing_markers > 0
            || summary.wrong_branch_markers > 0
            || summary.wrong_turn_markers > 0
            || summary.metadata_mismatch_markers > 0
            || summary.duplicate_markers > 0
            || summary.unexpected_markers > 0
            || summary.false_positive_controls_tripped > 0;

        SemanticCompactionQualityReport {
            schema: SEMANTIC_COMPACTION_QUALITY_SCHEMA_V1,
            baseline_view: SemanticCompactionQualityViewSummary {
                name: baseline.name.clone(),
                turn_count: baseline.turns.len(),
                marker_count: baseline_marker_count,
                content_fingerprint: view_content_fingerprint(&baseline.turns),
            },
            candidate_view: SemanticCompactionQualityViewSummary {
                name: candidate.name.clone(),
                turn_count: candidate.turns.len(),
                marker_count: candidate_marker_count,
                content_fingerprint: view_content_fingerprint(&candidate.turns),
            },
            verdict: if failed { "fail" } else { "pass" }.to_string(),
            summary,
            outcomes,
            false_positive_controls,
        }
    }

    /// Serialize a report as JSONL: one summary row followed by one row per outcome/control.
    pub fn semantic_compaction_quality_report_to_jsonl(
        report: &SemanticCompactionQualityReport,
    ) -> Result<String> {
        let mut lines = Vec::with_capacity(
            1usize
                .saturating_add(report.outcomes.len())
                .saturating_add(report.false_positive_controls.len()),
        );
        lines.push(
            serde_json::to_string(&json!({
                "schema": report.schema,
                "recordType": "summary",
                "verdict": report.verdict,
                "baselineView": report.baseline_view,
                "candidateView": report.candidate_view,
                "summary": report.summary,
            }))
            .map_err(|e| Error::session(format!("Semantic quality summary JSONL: {e}")))?,
        );
        for outcome in &report.outcomes {
            lines.push(
                serde_json::to_string(&json!({
                    "schema": report.schema,
                    "recordType": "marker_outcome",
                    "outcome": outcome,
                }))
                .map_err(|e| Error::session(format!("Semantic quality outcome JSONL: {e}")))?,
            );
        }
        for control in &report.false_positive_controls {
            lines.push(
                serde_json::to_string(&json!({
                    "schema": report.schema,
                    "recordType": "false_positive_control",
                    "control": control,
                }))
                .map_err(|e| Error::session(format!("Semantic quality control JSONL: {e}")))?,
            );
        }
        Ok(lines.join("\n"))
    }

    fn push_content_block_text(out: &mut String, block: &ContentBlock) {
        match block {
            ContentBlock::Text(text) => out.push_str(&text.text),
            ContentBlock::Thinking(thinking) => out.push_str(&thinking.thinking),
            ContentBlock::ToolCall(call) => {
                let _ = write!(out, "{} {}", call.name, call.arguments);
            }
            ContentBlock::Image(_) | ContentBlock::RedactedThinking(_) => {}
        }
    }

    fn session_message_semantic_text(message: &SessionMessage) -> String {
        let mut text = String::new();
        match message {
            SessionMessage::User { content, .. } => match content {
                UserContent::Text(value) => text.push_str(value),
                UserContent::Blocks(blocks) => {
                    for block in blocks {
                        push_content_block_text(&mut text, block);
                        text.push('\n');
                    }
                }
            },
            SessionMessage::Assistant { message } => {
                for block in &message.content {
                    push_content_block_text(&mut text, block);
                    text.push('\n');
                }
            }
            SessionMessage::ToolResult { content, .. } => {
                for block in content {
                    push_content_block_text(&mut text, block);
                    text.push('\n');
                }
            }
            SessionMessage::Custom { content, .. } => text.push_str(content),
            SessionMessage::BashExecution {
                command, output, ..
            } => {
                let _ = write!(text, "{command}\n{output}");
            }
            SessionMessage::BranchSummary { summary, .. }
            | SessionMessage::CompactionSummary { summary, .. } => text.push_str(summary),
        }
        text
    }

    const fn semantic_role_for_message(message: &SessionMessage) -> &'static str {
        match message {
            SessionMessage::User { .. } => "user",
            SessionMessage::Assistant { .. } => "assistant",
            SessionMessage::ToolResult { .. } => "tool_result",
            SessionMessage::Custom { .. } => "custom",
            SessionMessage::BashExecution { .. } => "bash_execution",
            SessionMessage::BranchSummary { .. } => "branch_summary",
            SessionMessage::CompactionSummary { .. } => "compaction_summary",
        }
    }

    /// Build a semantic quality scan view from session messages.
    #[must_use]
    pub fn semantic_quality_view_from_messages(
        name: &str,
        branch_id: &str,
        messages: &[SessionMessage],
    ) -> SemanticCompactionQualityView {
        let turns = messages
            .iter()
            .enumerate()
            .map(|(idx, message)| {
                SemanticCompactionQualityTurn::new(
                    branch_id,
                    format!("turn-{idx:04}"),
                    semantic_role_for_message(message),
                    session_message_semantic_text(message),
                )
            })
            .collect();
        SemanticCompactionQualityView::new(name, turns)
    }

    /// Build a semantic quality scan view from message-like session entries.
    #[must_use]
    pub fn semantic_quality_view_from_entries(
        name: &str,
        branch_id: &str,
        entries: &[SessionEntry],
    ) -> SemanticCompactionQualityView {
        let turns = entries
            .iter()
            .enumerate()
            .filter_map(|(idx, entry)| {
                let message = message_from_entry(entry)?;
                let turn_id = entry
                    .base_id()
                    .cloned()
                    .unwrap_or_else(|| format!("turn-{idx:04}"));
                Some(SemanticCompactionQualityTurn::new(
                    branch_id,
                    turn_id,
                    semantic_role_for_message(&message),
                    session_message_semantic_text(&message),
                ))
            })
            .collect();
        SemanticCompactionQualityView::new(name, turns)
    }
}

#[cfg(test)]
mod tests {
    use super::semantic_marker_scan_quality as marker_scan;
    use super::*;
    use crate::model::{AssistantMessage, ContentBlock, TextContent, Usage};
    use serde_json::json;

    fn make_user_text(text: &str) -> SessionMessage {
        SessionMessage::User {
            content: UserContent::Text(text.to_string()),
            timestamp: Some(0),
        }
    }

    fn make_assistant_text(text: &str, input: u64, output: u64) -> SessionMessage {
        SessionMessage::Assistant {
            message: AssistantMessage {
                content: vec![ContentBlock::Text(TextContent::new(text))],
                api: String::new(),
                provider: String::new(),
                model: String::new(),
                stop_reason: StopReason::Stop,
                stop_details: None,
                error_message: None,
                timestamp: 0,
                usage: Usage {
                    input,
                    output,
                    cache_read: 0,
                    cache_write: 0,
                    total_tokens: input + output,
                    ..Default::default()
                },
            },
        }
    }

    fn make_assistant_tool_call(name: &str, args: Value) -> SessionMessage {
        SessionMessage::Assistant {
            message: AssistantMessage {
                content: vec![ContentBlock::ToolCall(ToolCall {
                    id: "call_1".to_string(),
                    name: name.to_string(),
                    arguments: args,
                    thought_signature: None,
                })],
                api: String::new(),
                provider: String::new(),
                model: String::new(),
                stop_reason: StopReason::ToolUse,
                stop_details: None,
                error_message: None,
                timestamp: 0,
                usage: Usage::default(),
            },
        }
    }

    fn make_tool_result(text: &str) -> SessionMessage {
        SessionMessage::ToolResult {
            tool_call_id: "call_1".to_string(),
            tool_name: String::new(),
            content: vec![ContentBlock::Text(TextContent::new(text))],
            details: None,
            is_error: false,
            timestamp: None,
        }
    }

    // ── calculate_context_tokens ─────────────────────────────────────

    #[test]
    fn context_tokens_prefers_total_tokens() {
        let usage = Usage {
            input: 100,
            output: 50,
            total_tokens: 200,
            ..Default::default()
        };
        assert_eq!(calculate_context_tokens(&usage), 200);
    }

    #[test]
    fn context_tokens_falls_back_to_input_plus_output() {
        let usage = Usage {
            input: 100,
            output: 50,
            total_tokens: 0,
            ..Default::default()
        };
        assert_eq!(calculate_context_tokens(&usage), 150);
    }

    // ── should_compact ───────────────────────────────────────────────

    #[test]
    fn should_compact_when_over_threshold() {
        let settings = ResolvedCompactionSettings {
            enabled: true,
            reserve_tokens: 10_000,
            keep_recent_tokens: 5_000,
            ..Default::default()
        };
        // window=100k, reserve=10k => threshold=90k, context=95k => should compact
        assert!(should_compact(95_000, 100_000, &settings));
    }

    #[test]
    fn should_not_compact_when_under_threshold() {
        let settings = ResolvedCompactionSettings {
            enabled: true,
            reserve_tokens: 10_000,
            keep_recent_tokens: 5_000,
            ..Default::default()
        };
        // window=100k, reserve=10k => threshold=90k, context=80k => should not compact
        assert!(!should_compact(80_000, 100_000, &settings));
    }

    #[test]
    fn should_not_compact_when_disabled() {
        let settings = ResolvedCompactionSettings {
            enabled: false,
            reserve_tokens: 0,
            keep_recent_tokens: 0,
            ..Default::default()
        };
        assert!(!should_compact(1_000_000, 100_000, &settings));
    }

    #[test]
    fn should_compact_at_exact_threshold() {
        let settings = ResolvedCompactionSettings {
            enabled: true,
            reserve_tokens: 10_000,
            keep_recent_tokens: 5_000,
            ..Default::default()
        };
        // window=100k, reserve=10k => threshold=90k, context=90k => compact
        assert!(should_compact(90_000, 100_000, &settings));
        // 89999 should not trigger
        assert!(!should_compact(89_999, 100_000, &settings));
        // 90001 should also trigger
        assert!(should_compact(90_001, 100_000, &settings));
    }

    // ── estimate_tokens ──────────────────────────────────────────────

    #[test]
    fn estimate_tokens_user_text() {
        let msg = make_user_text("hello world"); // BPE (o200k oracle): 2 tokens
        assert_eq!(estimate_tokens(&msg), 2);
    }

    #[test]
    fn estimate_tokens_empty_text() {
        let msg = make_user_text(""); // 0 chars => 0
        assert_eq!(estimate_tokens(&msg), 0);
    }

    #[test]
    fn estimate_tokens_assistant_text() {
        let msg = make_assistant_text("hello", 10, 5); // 5 chars => ceil(5/3) = 2
        assert_eq!(estimate_tokens(&msg), 2);
    }

    #[test]
    fn estimate_tokens_tool_result() {
        let msg = make_tool_result("file contents here"); // BPE oracle: 4 tokens
        assert_eq!(estimate_tokens(&msg), 4);
    }

    #[test]
    fn estimate_tokens_custom_message() {
        let msg = SessionMessage::Custom {
            custom_type: "system".to_string(),
            content: "some custom content".to_string(),
            display: true,
            details: None,
            timestamp: Some(0),
        };
        // BPE oracle: 3 tokens
        assert_eq!(estimate_tokens(&msg), 3);
    }

    // ── estimate_context_tokens ──────────────────────────────────────

    #[test]
    fn estimate_context_with_assistant_usage() {
        let messages = vec![
            make_user_text("hi"),
            make_assistant_text("hello", 50, 10),
            make_user_text("bye"),
        ];
        let estimate = estimate_context_tokens(&messages);
        // Last assistant usage: input=50, output=10, total=60
        // Trailing after that: "bye" = ceil(3/3) = 1
        assert_eq!(estimate.tokens, 61);
        assert_eq!(estimate.last_usage_index, Some(1));
    }

    #[test]
    fn estimate_context_no_assistant() {
        let messages = vec![make_user_text("hello"), make_user_text("world")];
        let estimate = estimate_context_tokens(&messages);
        // No assistant messages, so sum BPE counts: 1+1 = 2
        assert_eq!(estimate.tokens, 2);
        assert!(estimate.last_usage_index.is_none());
    }

    #[test]
    fn estimate_context_zero_usage_falls_back_to_heuristics() {
        let messages = vec![
            make_user_text("hi"),
            make_assistant_text("hello", 0, 0),
            make_user_text("bye"),
        ];
        let estimate = estimate_context_tokens(&messages);
        // Zero provider usage should not collapse the estimate to trailing
        // messages only. We should fall back to whole-history heuristics:
        // "hi" => 1, "hello" => 2, "bye" => 1.
        assert_eq!(estimate.tokens, 4);
        assert!(estimate.last_usage_index.is_none());
    }

    // ── estimate_entries_context_tokens (tokensAfter heuristic) ──────

    #[test]
    fn tokens_after_estimate_uses_char_heuristic_not_tokens_before() {
        // A post-compaction current path: the compaction summary plus the
        // kept tail. The compaction entry carries a huge `tokens_before`
        // (999_999) that must never leak into the post-compaction estimate.
        let summary = compact_entry("c1", "summary text here", 999_999);
        let kept_user = user_entry("u1", "hello world"); // 11 chars => 4 tokens
        let entries: Vec<&SessionEntry> = vec![&summary, &kept_user];
        let tokens = estimate_entries_context_tokens(&entries);
        assert!(tokens > 0, "post-compaction estimate must be positive");
        assert!(
            tokens < 1000,
            "estimate must reflect char heuristic, not tokens_before: {tokens}"
        );
    }

    #[test]
    fn tokens_after_estimate_ignores_stale_assistant_usage() {
        // An assistant message retained after compaction still carries the
        // provider `usage` from its ORIGINAL (pre-compaction) request. That
        // stale usage must NOT inflate the post-compaction estimate.
        let user = user_entry("u1", "hi"); // 2 chars => 1 token
        let assistant = assistant_entry("a1", "ok", 500_000, 250_000); // 2 chars => 1 token
        let entries: Vec<&SessionEntry> = vec![&user, &assistant];

        let heuristic = estimate_entries_context_tokens(&entries);
        // Exact counts differ between the BPE counter (feature `bpe-tokens`)
        // and the chars/4 fallback; either way two 2-char messages stay tiny.
        assert!(
            (1..=8).contains(&heuristic),
            "tiny-message heuristic should be a handful of tokens: {heuristic}"
        );

        // Sanity: the usage-aware estimator WOULD balloon to the stale total,
        // proving the two paths diverge and tokensAfter uses the heuristic.
        let messages: Vec<SessionMessage> = entries
            .iter()
            .copied()
            .filter_map(message_from_entry)
            .collect();
        let usage_aware = estimate_context_tokens(&messages).tokens;
        assert!(
            usage_aware >= 750_000,
            "usage-aware estimate: {usage_aware}"
        );
        assert!(heuristic < usage_aware);
    }

    // ── extract_file_ops_from_message ────────────────────────────────

    #[test]
    fn extract_file_ops_read() {
        let msg = make_assistant_tool_call("read", json!({"path": "/foo/bar.rs"}));
        let mut ops = FileOperations::default();
        let mut status = HashMap::new();
        status.insert("call_1", true);
        extract_file_ops_from_message(&msg, &mut ops, &status);
        assert!(ops.read.contains("/foo/bar.rs"));
        assert!(ops.written.is_empty());
        assert!(ops.edited.is_empty());
    }

    #[test]
    fn extract_file_ops_write() {
        let msg = make_assistant_tool_call("write", json!({"path": "/out.txt"}));
        let mut ops = FileOperations::default();
        let mut status = HashMap::new();
        status.insert("call_1", true);
        extract_file_ops_from_message(&msg, &mut ops, &status);
        assert!(ops.written.contains("/out.txt"));
        assert!(ops.read.is_empty());
    }

    #[test]
    fn extract_file_ops_edit() {
        let msg = make_assistant_tool_call("edit", json!({"path": "/src/main.rs"}));
        let mut ops = FileOperations::default();
        let mut status = HashMap::new();
        status.insert("call_1", true);
        extract_file_ops_from_message(&msg, &mut ops, &status);
        assert!(ops.edited.contains("/src/main.rs"));
    }

    #[test]
    fn extract_file_ops_ignores_failed_tools() {
        let msg = make_assistant_tool_call("read", json!({"path": "/secret.rs"}));
        let mut ops = FileOperations::default();
        let mut status = HashMap::new();
        status.insert("call_1", false); // Failed!
        extract_file_ops_from_message(&msg, &mut ops, &status);
        assert!(ops.read.is_empty());
    }

    #[test]
    fn extract_file_ops_ignores_other_tools() {
        let msg = make_assistant_tool_call("bash", json!({"command": "ls"}));
        let mut ops = FileOperations::default();
        let mut status = HashMap::new();
        status.insert("call_1", true);
        extract_file_ops_from_message(&msg, &mut ops, &status);
        assert!(ops.read.is_empty());
        assert!(ops.written.is_empty());
        assert!(ops.edited.is_empty());
    }

    #[test]
    fn extract_file_ops_ignores_user_messages() {
        let msg = make_user_text("read the file /foo.rs");
        let mut ops = FileOperations::default();
        let status = HashMap::new();
        extract_file_ops_from_message(&msg, &mut ops, &status);
        assert!(ops.read.is_empty());
    }

    // ── compute_file_lists ───────────────────────────────────────────

    #[test]
    fn compute_file_lists_separates_read_from_modified() {
        let mut ops = FileOperations::default();
        ops.read.insert("/a.rs".to_string());
        ops.read.insert("/b.rs".to_string());
        ops.written.insert("/b.rs".to_string());
        ops.edited.insert("/c.rs".to_string());

        let (read_only, modified) = compute_file_lists(&ops);
        // /a.rs was only read; /b.rs was read AND written (so it's modified)
        assert_eq!(read_only, vec!["/a.rs"]);
        assert!(modified.contains(&"/b.rs".to_string()));
        assert!(modified.contains(&"/c.rs".to_string()));
    }

    #[test]
    fn compute_file_lists_empty() {
        let ops = FileOperations::default();
        let (read_only, modified) = compute_file_lists(&ops);
        assert!(read_only.is_empty());
        assert!(modified.is_empty());
    }

    // ── format_file_operations ───────────────────────────────────────

    #[test]
    fn format_file_operations_empty() {
        assert_eq!(format_file_operations(&[], &[]), String::new());
    }

    #[test]
    fn format_file_operations_read_only() {
        let result = format_file_operations(&["src/main.rs".to_string()], &[]);
        assert!(result.contains("<read-files>"));
        assert!(result.contains("src/main.rs"));
        assert!(!result.contains("<modified-files>"));
    }

    #[test]
    fn format_file_operations_both() {
        let result = format_file_operations(&["a.rs".to_string()], &["b.rs".to_string()]);
        assert!(result.contains("<read-files>"));
        assert!(result.contains("a.rs"));
        assert!(result.contains("<modified-files>"));
        assert!(result.contains("b.rs"));
    }

    // ── compaction_details_to_value ──────────────────────────────────

    #[test]
    fn compaction_details_serializes() {
        let details = CompactionDetails {
            read_files: vec!["a.rs".to_string()],
            modified_files: vec!["b.rs".to_string()],
            mode: None,
        };
        let value = compaction_details_to_value(&details).unwrap();
        assert_eq!(value["readFiles"], json!(["a.rs"]));
        assert_eq!(value["modifiedFiles"], json!(["b.rs"]));
    }

    // ── ResolvedCompactionSettings default ───────────────────────────

    #[test]
    fn default_settings() {
        let settings = ResolvedCompactionSettings::default();
        assert!(settings.enabled);
        assert_eq!(settings.context_window_tokens, 128_000);
        assert_eq!(settings.reserve_tokens, 10_240);
        assert_eq!(settings.keep_recent_tokens, 12_800);
    }

    // ── Helper: entry constructors ──────────────────────────────────

    use crate::model::{ImageContent, ThinkingContent};
    use crate::session::{
        BranchSummaryEntry, CompactionEntry, EntryBase, MessageEntry, ModelChangeEntry,
    };
    use std::collections::HashMap;

    fn test_base(id: &str) -> EntryBase {
        EntryBase {
            id: Some(id.to_string()),
            parent_id: None,
            timestamp: "2026-01-01T00:00:00.000Z".to_string(),
        }
    }

    /// `n` distinct space-separated words. Unlike a run of one repeated
    /// character (which BPE collapses to almost nothing), this keeps the
    /// token count in the same ballpark under the O200k/Cl100k counters
    /// (~2 tokens/word) and the chars/4 fallback (~1.6 tokens/word), so
    /// cut-point calibrations hold with `bpe-tokens` on or off.
    fn distinct_words(n: usize) -> String {
        use std::fmt::Write as _;
        let mut out = String::new();
        for i in 0..n {
            if i > 0 {
                out.push(' ');
            }
            let _ = write!(out, "word{i}");
        }
        out
    }

    fn user_entry(id: &str, text: &str) -> SessionEntry {
        SessionEntry::Message(MessageEntry {
            base: test_base(id),
            message: make_user_text(text),
        })
    }

    fn assistant_entry(id: &str, text: &str, input: u64, output: u64) -> SessionEntry {
        SessionEntry::Message(MessageEntry {
            base: test_base(id),
            message: make_assistant_text(text, input, output),
        })
    }

    fn tool_call_entry(id: &str, tool_name: &str, path: &str) -> SessionEntry {
        SessionEntry::Message(MessageEntry {
            base: test_base(id),
            message: make_assistant_tool_call(tool_name, json!({"path": path})),
        })
    }

    fn tool_result_entry(id: &str, text: &str) -> SessionEntry {
        SessionEntry::Message(MessageEntry {
            base: test_base(id),
            message: make_tool_result(text),
        })
    }

    fn branch_entry(id: &str, summary: &str) -> SessionEntry {
        SessionEntry::BranchSummary(BranchSummaryEntry {
            base: test_base(id),
            from_id: "parent".to_string(),
            summary: summary.to_string(),
            details: None,
            from_hook: None,
        })
    }

    fn compact_entry(id: &str, summary: &str, tokens: u64) -> SessionEntry {
        SessionEntry::Compaction(CompactionEntry {
            base: test_base(id),
            summary: summary.to_string(),
            first_kept_entry_id: "kept".to_string(),
            tokens_before: tokens,
            details: None,
            from_hook: None,
        })
    }

    fn bash_entry(id: &str) -> SessionEntry {
        SessionEntry::Message(MessageEntry {
            base: test_base(id),
            message: SessionMessage::BashExecution {
                command: "ls".to_string(),
                output: "ok".to_string(),
                exit_code: 0,
                cancelled: None,
                truncated: None,
                full_output_path: None,
                timestamp: None,
                extra: HashMap::new(),
            },
        })
    }

    fn scq_marker(id: &str, kind: &str, branch: &str, turn: &str, critical: bool) -> String {
        marker_scan::semantic_compaction_quality_marker(id, kind, branch, turn, critical)
    }

    fn quality_view(name: &str, content: &str) -> marker_scan::SemanticCompactionQualityView {
        marker_scan::SemanticCompactionQualityView::new(
            name,
            vec![marker_scan::SemanticCompactionQualityTurn::new(
                "main",
                "summary",
                "compaction_summary",
                content,
            )],
        )
    }

    #[test]
    fn semantic_compaction_quality_preserves_structured_markers() {
        let markers = [
            scq_marker("task-plan", "task", "main", "turn-task", true),
            scq_marker("file-src-lib", "file_reference", "main", "turn-file", true),
            scq_marker("decision-rch", "decision", "main", "turn-decision", true),
            scq_marker("tool-read", "tool_output", "main", "turn-tool", true),
            scq_marker(
                "constraint-no-live",
                "constraint",
                "main",
                "turn-constraint",
                true,
            ),
            scq_marker(
                "mail-degraded",
                "agent_mail_degraded",
                "main",
                "turn-mail",
                true,
            ),
            scq_marker("bead-claim", "beads_claim", "main", "turn-beads", true),
            scq_marker(
                "interrupt-handled",
                "interruption",
                "main",
                "turn-interrupt",
                false,
            ),
            scq_marker(
                "tool-truncated",
                "truncation_notice",
                "main",
                "turn-tool",
                true,
            ),
            scq_marker("handoff-fact", "handoff_fact", "main", "turn-handoff", true),
        ];
        let baseline_content = markers.join("\n");
        let candidate_content = format!("Compacted semantic inventory:\n{}", markers.join("\n"));
        let baseline = quality_view("pre-compaction", &baseline_content);
        let candidate = quality_view("post-compaction", &candidate_content);

        let report = marker_scan::evaluate_semantic_compaction_quality(
            &baseline,
            &candidate,
            &[String::from("control-never-present")],
        );

        assert_eq!(
            report.schema,
            marker_scan::SEMANTIC_COMPACTION_QUALITY_SCHEMA_V1
        );
        assert_eq!(report.verdict, "pass");
        assert_eq!(report.summary.total_expected_markers, markers.len());
        assert_eq!(report.summary.preserved_markers, markers.len());
        assert!((report.summary.marker_coverage - 1.0).abs() < f64::EPSILON);
        assert_eq!(report.summary.false_positive_controls_tripped, 0);

        let jsonl = marker_scan::semantic_compaction_quality_report_to_jsonl(&report)
            .expect("jsonl report");
        assert!(
            jsonl
                .lines()
                .next()
                .is_some_and(|line| line.contains("\"recordType\":\"summary\""))
        );
        assert!(jsonl.contains("\"recordType\":\"marker_outcome\""));
        assert!(!jsonl.contains("Compacted semantic inventory"));
    }

    #[test]
    fn semantic_compaction_quality_missing_file_reference_fails_closed() {
        let task = scq_marker("task-plan", "task", "main", "turn-task", true);
        let file = scq_marker("file-src-lib", "file_reference", "main", "turn-file", true);
        let baseline = quality_view("pre-compaction", &format!("{task}\n{file}"));
        let candidate = quality_view("post-compaction", &task);

        let report = marker_scan::evaluate_semantic_compaction_quality(&baseline, &candidate, &[]);

        assert_eq!(report.verdict, "fail");
        assert_eq!(report.summary.missing_markers, 1);
        assert!(report.outcomes.iter().any(|outcome| {
            outcome.marker_id == "file-src-lib"
                && outcome.loss_class.as_deref() == Some("missing_marker")
        }));
    }

    #[test]
    fn semantic_compaction_quality_wrong_branch_fails_closed() {
        let baseline = quality_view(
            "pre-compaction",
            &scq_marker("branch-fact", "handoff_fact", "main", "turn-handoff", true),
        );
        let candidate = quality_view(
            "post-compaction",
            &scq_marker("branch-fact", "handoff_fact", "side", "turn-handoff", true),
        );

        let report = marker_scan::evaluate_semantic_compaction_quality(&baseline, &candidate, &[]);

        assert_eq!(report.verdict, "fail");
        assert_eq!(report.summary.wrong_branch_markers, 1);
        assert!(report.outcomes.iter().any(|outcome| {
            outcome.marker_id == "branch-fact"
                && outcome.loss_class.as_deref() == Some("wrong_branch")
                && outcome.observed_branch_id.as_deref() == Some("side")
        }));
    }

    #[test]
    fn semantic_compaction_quality_stale_beads_turn_fails_closed() {
        let baseline = quality_view(
            "pre-compaction",
            &scq_marker("bead-handoff", "beads_claim", "main", "turn-fresh", true),
        );
        let candidate = quality_view(
            "post-compaction",
            &scq_marker("bead-handoff", "beads_claim", "main", "turn-stale", true),
        );

        let report = marker_scan::evaluate_semantic_compaction_quality(&baseline, &candidate, &[]);

        assert_eq!(report.verdict, "fail");
        assert_eq!(report.summary.wrong_turn_markers, 1);
        assert!(report.outcomes.iter().any(|outcome| {
            outcome.marker_id == "bead-handoff"
                && outcome.loss_class.as_deref() == Some("wrong_turn")
                && outcome.observed_turn_id.as_deref() == Some("turn-stale")
        }));
    }

    #[test]
    fn semantic_compaction_quality_large_tool_output_marker_must_survive() {
        let task = scq_marker("task-plan", "task", "main", "turn-task", true);
        let truncation = scq_marker(
            "tool-output-truncated",
            "truncation_notice",
            "main",
            "turn-tool-output",
            true,
        );
        let baseline = quality_view(
            "pre-compaction",
            &format!("{task}\nlarge tool output omitted\n{truncation}"),
        );
        let candidate = quality_view("post-compaction", &task);

        let report = marker_scan::evaluate_semantic_compaction_quality(&baseline, &candidate, &[]);

        assert_eq!(report.verdict, "fail");
        assert!(report.outcomes.iter().any(|outcome| {
            outcome.marker_id == "tool-output-truncated"
                && outcome.loss_class.as_deref() == Some("missing_marker")
        }));
    }

    #[test]
    fn semantic_compaction_quality_false_positive_control_detects_invented_marker() {
        let baseline = quality_view(
            "pre-compaction",
            &scq_marker("task-plan", "task", "main", "turn-task", true),
        );
        let invented = scq_marker(
            "control-never-present",
            "decision",
            "main",
            "turn-invented",
            true,
        );
        let candidate = quality_view(
            "post-compaction",
            &format!(
                "{}\n{invented}\nsecret tool body should not appear in report",
                scq_marker("task-plan", "task", "main", "turn-task", true)
            ),
        );

        let report = marker_scan::evaluate_semantic_compaction_quality(
            &baseline,
            &candidate,
            &[String::from("control-never-present")],
        );
        let serialized = serde_json::to_string(&report).expect("serialize report");

        assert_eq!(report.verdict, "fail");
        assert_eq!(report.summary.false_positive_controls_tripped, 1);
        assert_eq!(report.summary.unexpected_markers, 1);
        assert!(serialized.contains("false_positive_control"));
        assert!(!serialized.contains("secret tool body"));
    }

    #[test]
    fn semantic_quality_view_from_session_entries_scans_compaction_summaries() {
        let marker = scq_marker("summary-task", "task", "main", "kept", true);
        let entries = vec![
            user_entry("root", "uncompacted user text"),
            compact_entry("compact", &marker, 10),
            user_entry("kept", "kept turn"),
        ];
        let view =
            marker_scan::semantic_quality_view_from_entries("session-path", "main", &entries);
        let report = marker_scan::evaluate_semantic_compaction_quality(&view, &view, &[]);

        assert_eq!(view.turns.len(), 3);
        assert_eq!(report.verdict, "pass");
        assert_eq!(report.summary.preserved_markers, 1);
    }

    // ── get_assistant_usage ─────────────────────────────────────────

    #[test]
    fn get_assistant_usage_returns_usage_for_stop() {
        let msg = make_assistant_text("text", 100, 50);
        let usage = get_assistant_usage(&msg);
        assert!(usage.is_some());
        assert_eq!(usage.unwrap().input, 100);
    }

    #[test]
    fn get_assistant_usage_none_for_aborted() {
        let msg = SessionMessage::Assistant {
            message: AssistantMessage {
                content: vec![ContentBlock::Text(TextContent::new("text"))],
                api: String::new(),
                provider: String::new(),
                model: String::new(),
                stop_reason: StopReason::Aborted,
                stop_details: None,
                error_message: None,
                timestamp: 0,
                usage: Usage {
                    input: 100,
                    output: 50,
                    total_tokens: 150,
                    ..Default::default()
                },
            },
        };
        assert!(get_assistant_usage(&msg).is_none());
    }

    #[test]
    fn get_assistant_usage_none_for_error() {
        let msg = SessionMessage::Assistant {
            message: AssistantMessage {
                content: vec![],
                api: String::new(),
                provider: String::new(),
                model: String::new(),
                stop_reason: StopReason::Error,
                stop_details: None,
                error_message: None,
                timestamp: 0,
                usage: Usage::default(),
            },
        };
        assert!(get_assistant_usage(&msg).is_none());
    }

    #[test]
    fn get_assistant_usage_none_for_user() {
        assert!(get_assistant_usage(&make_user_text("hello")).is_none());
    }

    // ── entry_is_message_like ───────────────────────────────────────

    #[test]
    fn entry_is_message_like_for_message() {
        assert!(entry_is_message_like(&user_entry("1", "hi")));
    }

    #[test]
    fn entry_is_message_like_for_branch_summary() {
        assert!(entry_is_message_like(&branch_entry("1", "sum")));
    }

    #[test]
    fn entry_is_message_like_false_for_compaction() {
        assert!(!entry_is_message_like(&compact_entry("1", "sum", 100)));
    }

    #[test]
    fn entry_is_message_like_false_for_model_change() {
        let entry = SessionEntry::ModelChange(ModelChangeEntry {
            base: test_base("1"),
            provider: "test".to_string(),
            model_id: "model-1".to_string(),
            role: None,
        });
        assert!(!entry_is_message_like(&entry));
    }

    // ── entry_is_compaction_boundary ────────────────────────────────

    #[test]
    fn compaction_boundary_true_for_compaction() {
        assert!(entry_is_compaction_boundary(&compact_entry(
            "1", "sum", 100
        )));
    }

    #[test]
    fn compaction_boundary_false_for_message() {
        assert!(!entry_is_compaction_boundary(&user_entry("1", "hi")));
    }

    #[test]
    fn compaction_boundary_false_for_branch() {
        assert!(!entry_is_compaction_boundary(&branch_entry("1", "sum")));
    }

    // ── is_user_turn_start ──────────────────────────────────────────

    #[test]
    fn user_turn_start_for_user() {
        assert!(is_user_turn_start(&user_entry("1", "hello")));
    }

    #[test]
    fn user_turn_start_for_branch() {
        assert!(is_user_turn_start(&branch_entry("1", "summary")));
    }

    #[test]
    fn user_turn_start_for_bash() {
        assert!(is_user_turn_start(&bash_entry("1")));
    }

    #[test]
    fn user_turn_start_false_for_assistant() {
        assert!(!is_user_turn_start(&assistant_entry("1", "resp", 10, 5)));
    }

    #[test]
    fn user_turn_start_false_for_tool_result() {
        assert!(!is_user_turn_start(&tool_result_entry("1", "result")));
    }

    #[test]
    fn user_turn_start_false_for_compaction() {
        assert!(!is_user_turn_start(&compact_entry("1", "sum", 100)));
    }

    // ── message_from_entry ──────────────────────────────────────────

    #[test]
    fn message_from_entry_user() {
        let entry = user_entry("1", "hello");
        let msg = message_from_entry(&entry);
        assert!(msg.is_some());
        assert!(matches!(msg.unwrap(), SessionMessage::User { .. }));
    }

    #[test]
    fn message_from_entry_branch_summary() {
        let entry = branch_entry("1", "branch summary text");
        let msg = message_from_entry(&entry).unwrap();
        if let SessionMessage::BranchSummary { summary, from_id } = msg {
            assert_eq!(summary, "branch summary text");
            assert_eq!(from_id, "parent");
        } else {
            panic!();
        }
    }

    #[test]
    fn message_from_entry_compaction() {
        let entry = compact_entry("1", "compact summary", 500);
        let msg = message_from_entry(&entry).unwrap();
        if let SessionMessage::CompactionSummary {
            summary,
            tokens_before,
        } = msg
        {
            assert_eq!(summary, "compact summary");
            assert_eq!(tokens_before, 500);
        } else {
            panic!();
        }
    }

    #[test]
    fn message_from_entry_model_change_is_none() {
        let entry = SessionEntry::ModelChange(ModelChangeEntry {
            base: test_base("1"),
            provider: "test".to_string(),
            model_id: "model".to_string(),
            role: None,
        });
        assert!(message_from_entry(&entry).is_none());
    }

    // ── find_valid_cut_points ───────────────────────────────────────

    #[test]
    fn find_valid_cut_points_empty() {
        assert!(find_valid_cut_points(&[], 0, 0).is_empty());
    }

    #[test]
    fn find_valid_cut_points_skips_tool_results() {
        let entries = vec![
            user_entry("1", "hello"),
            assistant_entry("2", "resp", 10, 5),
            tool_result_entry("3", "result"),
            user_entry("4", "follow up"),
        ];
        let cuts = find_valid_cut_points(&entries, 0, entries.len());
        assert!(cuts.contains(&0)); // user
        assert!(cuts.contains(&1)); // assistant
        assert!(!cuts.contains(&2)); // tool result excluded
        assert!(cuts.contains(&3)); // user
    }

    #[test]
    fn find_valid_cut_points_includes_branch_summary() {
        let entries = vec![branch_entry("1", "summary"), user_entry("2", "hello")];
        let cuts = find_valid_cut_points(&entries, 0, entries.len());
        assert!(cuts.contains(&0));
        assert!(cuts.contains(&1));
    }

    #[test]
    fn find_valid_cut_points_respects_range() {
        let entries = vec![
            user_entry("1", "a"),
            user_entry("2", "b"),
            user_entry("3", "c"),
        ];
        let cuts = find_valid_cut_points(&entries, 1, 2);
        assert!(!cuts.contains(&0));
        assert!(cuts.contains(&1));
        assert!(!cuts.contains(&2));
    }

    // ── find_turn_start_index ───────────────────────────────────────

    #[test]
    fn find_turn_start_basic() {
        let entries = vec![
            user_entry("1", "hello"),
            assistant_entry("2", "resp", 10, 5),
            tool_result_entry("3", "result"),
        ];
        assert_eq!(find_turn_start_index(&entries, 2, 0), Some(0));
    }

    #[test]
    fn find_turn_start_at_self() {
        let entries = vec![user_entry("1", "hello")];
        assert_eq!(find_turn_start_index(&entries, 0, 0), Some(0));
    }

    #[test]
    fn find_turn_start_none_no_user() {
        let entries = vec![
            assistant_entry("1", "resp", 10, 5),
            tool_result_entry("2", "result"),
        ];
        assert_eq!(find_turn_start_index(&entries, 1, 0), None);
    }

    #[test]
    fn find_turn_start_respects_start_index() {
        let entries = vec![
            user_entry("1", "old"),
            assistant_entry("2", "resp", 10, 5),
            user_entry("3", "new"),
        ];
        // start_index=2, so it should find user at 2
        assert_eq!(find_turn_start_index(&entries, 2, 2), Some(2));
        // start_index=2, looking back from 2, user at 1 is below start
        assert_eq!(find_turn_start_index(&entries, 1, 2), None);
    }

    // ── serialize_conversation ───────────────────────────────────────

    #[test]
    fn serialize_conversation_user_text() {
        let messages = vec![Message::User(crate::model::UserMessage {
            content: UserContent::Text("hello world".to_string()),
            timestamp: 0,
        })];
        assert_eq!(serialize_conversation(&messages), "[User]: hello world");
    }

    #[test]
    fn serialize_conversation_empty() {
        assert!(serialize_conversation(&[]).is_empty());
    }

    #[test]
    fn serialize_conversation_skips_empty_user() {
        let messages = vec![Message::User(crate::model::UserMessage {
            content: UserContent::Text(String::new()),
            timestamp: 0,
        })];
        assert!(serialize_conversation(&messages).is_empty());
    }

    #[test]
    fn serialize_conversation_assistant_text() {
        let messages = vec![Message::assistant(AssistantMessage {
            content: vec![ContentBlock::Text(TextContent::new("response"))],
            api: String::new(),
            provider: String::new(),
            model: String::new(),
            usage: Usage::default(),
            stop_reason: StopReason::Stop,
            stop_details: None,
            error_message: None,
            timestamp: 0,
        })];
        assert!(serialize_conversation(&messages).contains("[Assistant]: response"));
    }

    #[test]
    fn serialize_conversation_tool_calls() {
        let messages = vec![Message::assistant(AssistantMessage {
            content: vec![ContentBlock::ToolCall(ToolCall {
                id: "c1".to_string(),
                name: "read".to_string(),
                arguments: json!({"path": "/main.rs"}),
                thought_signature: None,
            })],
            api: String::new(),
            provider: String::new(),
            model: String::new(),
            usage: Usage::default(),
            stop_reason: StopReason::Stop,
            stop_details: None,
            error_message: None,
            timestamp: 0,
        })];
        let result = serialize_conversation(&messages);
        assert!(result.contains("[Assistant tool calls]: read("));
        assert!(result.contains("path="));
    }

    #[test]
    fn serialize_conversation_thinking() {
        let messages = vec![Message::assistant(AssistantMessage {
            content: vec![ContentBlock::Thinking(ThinkingContent {
                thinking: "let me think".to_string(),
                thinking_signature: None,
            })],
            api: String::new(),
            provider: String::new(),
            model: String::new(),
            usage: Usage::default(),
            stop_reason: StopReason::Stop,
            stop_details: None,
            error_message: None,
            timestamp: 0,
        })];
        assert!(serialize_conversation(&messages).contains("[Assistant thinking]: let me think"));
    }

    #[test]
    fn serialize_conversation_tool_result() {
        let messages = vec![Message::tool_result(crate::model::ToolResultMessage {
            tool_call_id: "c1".to_string(),
            tool_name: "read".to_string(),
            content: vec![ContentBlock::Text(TextContent::new("file contents"))],
            details: None,
            is_error: false,
            timestamp: 0,
        })];
        assert!(serialize_conversation(&messages).contains("[Tool result]: file contents"));
    }

    // ── estimate_tokens additional ──────────────────────────────────

    #[test]
    fn estimate_tokens_image_block() {
        let msg = SessionMessage::User {
            content: UserContent::Blocks(vec![ContentBlock::Image(ImageContent {
                data: "base64data".to_string(),
                mime_type: "image/png".to_string(),
            })]),
            timestamp: None,
        };
        // Image = 3600 chars (IMAGE_CHAR_ESTIMATE) -> ceil(3600/3) = 1200
        assert_eq!(estimate_tokens(&msg), 1200);
    }

    #[test]
    fn estimate_tokens_thinking() {
        let msg = SessionMessage::User {
            content: UserContent::Blocks(vec![ContentBlock::Thinking(ThinkingContent {
                thinking: "a".repeat(20),
                thinking_signature: None,
            })]),
            timestamp: None,
        };
        // BPE oracle: 4 tokens ("a" * 20)
        assert_eq!(estimate_tokens(&msg), 4);
    }

    #[test]
    fn estimate_tokens_bash_execution() {
        let msg = SessionMessage::BashExecution {
            command: "echo hi".to_string(),
            output: "hi\n".to_string(),
            exit_code: 0,
            cancelled: None,
            truncated: None,
            full_output_path: None,
            timestamp: None,
            extra: HashMap::new(),
        };
        // BPE oracle: 5 tokens ("echo hi" + "hi\n")
        assert_eq!(estimate_tokens(&msg), 5);
    }

    #[test]
    fn estimate_tokens_branch_summary() {
        let msg = SessionMessage::BranchSummary {
            summary: "a".repeat(40),
            from_id: "id".to_string(),
        };
        // BPE oracle: 5 tokens ("a" * 40)
        assert_eq!(estimate_tokens(&msg), 5);
    }

    #[test]
    fn estimate_tokens_compaction_summary() {
        let msg = SessionMessage::CompactionSummary {
            summary: "a".repeat(80),
            tokens_before: 5000,
        };
        // BPE oracle: 10 tokens ("a" * 80)
        assert_eq!(estimate_tokens(&msg), 10);
    }

    // ── prepare_compaction ──────────────────────────────────────────

    #[test]
    fn prepare_compaction_empty() {
        assert!(prepare_compaction(&[], ResolvedCompactionSettings::default()).is_none());
    }

    #[test]
    fn prepare_compaction_last_is_compaction_returns_none() {
        let entries = vec![user_entry("1", "hello"), compact_entry("2", "summary", 100)];
        assert!(prepare_compaction(&entries, ResolvedCompactionSettings::default()).is_none());
    }

    #[test]
    fn prepare_compaction_no_messages_to_summarize_returns_none() {
        // Only non-message entries that produce no summarizable messages
        let entries = vec![SessionEntry::ModelChange(ModelChangeEntry {
            base: test_base("1"),
            provider: "test".to_string(),
            model_id: "model".to_string(),
            role: None,
        })];
        assert!(prepare_compaction(&entries, ResolvedCompactionSettings::default()).is_none());
    }

    #[test]
    fn prepare_compaction_basic_returns_some() {
        let long_text = "a".repeat(100_000);
        let entries = vec![
            user_entry("1", &long_text),
            assistant_entry("2", &long_text, 50000, 25000),
            user_entry("3", &long_text),
            assistant_entry("4", &long_text, 80000, 30000),
            user_entry("5", "recent"),
        ];
        let settings = ResolvedCompactionSettings {
            enabled: true,
            context_window_tokens: 100_000,
            reserve_tokens: 1000,
            keep_recent_tokens: 5,
        };
        let prep = prepare_compaction(&entries, settings);
        assert!(prep.is_some());
        let p = prep.unwrap();
        assert!(!p.messages_to_summarize.is_empty());
        assert!(p.tokens_before > 0);
        assert!(p.previous_summary.is_none());
    }

    /// bd-cv653.3.18: shake drops bulky tool-result payloads to stubs while
    /// keeping conversation text verbatim, with zero LLM involvement. The
    /// fixture places the bulk before the second-to-last user boundary so the
    /// standard cut point puts it inside the compacted span.
    #[test]
    fn shake_drops_bulky_tool_results_and_keeps_text() {
        let huge_result = "line of tool output\n".repeat(10_000);
        let entries = vec![
            user_entry("1", "Please audit the parser module"),
            assistant_entry("2", "Reading the parser now.", 55_000, 5_000),
            tool_result_entry("3", &huge_result),
            user_entry("4", "Also check the lexer"),
            assistant_entry("5", "Lexer is clean.", 55_000, 5_000),
            user_entry("6", "recent question"),
        ];
        let settings = ResolvedCompactionSettings {
            enabled: true,
            context_window_tokens: 50_000,
            reserve_tokens: 1000,
            keep_recent_tokens: 5,
        };
        let prep = prepare_compaction(&entries, settings).expect("prep");
        let first_kept = prep.first_kept_entry_id.clone();
        let result = compact_shake(prep);

        assert_eq!(result.details.mode.as_deref(), Some("shake"));
        assert_eq!(result.first_kept_entry_id, first_kept);
        assert!(
            result.summary.contains("Please audit the parser module"),
            "user text preserved: {}",
            result.summary
        );
        assert!(
            result.summary.contains("dropped; re-run if needed"),
            "bulky result stubbed: {}",
            result.summary
        );
        assert!(
            !result
                .summary
                .contains("line of tool output\nline of tool output"),
            "payload must not survive"
        );
    }

    /// bd-cv653.3.18: small tool results survive a shake verbatim.
    #[test]
    fn shake_keeps_small_tool_results() {
        let entries = vec![
            user_entry("1", "start the build"),
            assistant_entry("2", "running the build", 55_000, 5_000),
            tool_result_entry("3", "exit 0"),
            user_entry("4", "now check tests"),
            assistant_entry("5", "tests pass", 55_000, 5_000),
            user_entry("6", "recent"),
        ];
        let settings = ResolvedCompactionSettings {
            enabled: true,
            context_window_tokens: 50_000,
            reserve_tokens: 1000,
            keep_recent_tokens: 5,
        };
        let prep = prepare_compaction(&entries, settings).expect("prep");
        let result = compact_shake(prep);
        assert!(
            result.summary.contains("exit 0"),
            "small result kept: {}",
            result.summary
        );
    }

    /// bd-cv653.3.18: the shake projection captures the tool-bulk reclaim,
    /// and the shake-first policy escalates only when the remaining span
    /// still trips the threshold.
    #[test]
    fn shake_projection_and_shake_first_policy() {
        let settings = ResolvedCompactionSettings {
            enabled: true,
            context_window_tokens: 50_000,
            reserve_tokens: 1000,
            keep_recent_tokens: 5,
        };

        // Tool-heavy span: shake reclaims nearly everything -> no escalation.
        let huge_result = "x".repeat(300_000);
        let entries = vec![
            user_entry("1", "small goal"),
            assistant_entry("2", "checking", 55_000, 5_000),
            tool_result_entry("3", &huge_result),
            user_entry("4", "next step"),
            assistant_entry("5", "ok", 55_000, 5_000),
            user_entry("6", "recent"),
        ];
        let prep = prepare_compaction(&entries, settings.clone()).expect("prep");
        let projection = shake_projection(&prep);
        assert!(
            projection.reclaimed_tokens() * 10 >= projection.tokens_before * 8,
            "tool-heavy shake reclaims at least 80%: {projection:?}"
        );
        assert!(
            !shake_first_needs_summary(projection, &prep.settings),
            "no escalation when shake reclaims enough"
        );

        // Text-heavy span: shake keeps the text, so the summary must run.
        let entries = vec![
            user_entry("1", &"prose ".repeat(30_000)),
            assistant_entry("2", &"reply ".repeat(30_000), 55_000, 5_000),
            user_entry("3", "next step"),
            assistant_entry("4", "ok", 55_000, 5_000),
            user_entry("5", "recent"),
        ];
        let prep = prepare_compaction(&entries, settings).expect("prep");
        let projection = shake_projection(&prep);
        assert!(
            shake_first_needs_summary(projection, &prep.settings),
            "text-heavy shake must escalate: {projection:?}"
        );
    }

    #[test]
    fn prepare_compaction_after_previous_compaction() {
        let entries = vec![
            user_entry("1", "old message"),
            assistant_entry("2", "old response", 100, 50),
            compact_entry("3", "previous summary", 300),
            user_entry("4", &"x".repeat(100_000)),
            assistant_entry("5", &"y".repeat(100_000), 80000, 30000),
            user_entry("6", "recent"),
        ];
        let settings = ResolvedCompactionSettings {
            enabled: true,
            context_window_tokens: 100_000,
            reserve_tokens: 1000,
            keep_recent_tokens: 5,
        };
        let prep = prepare_compaction(&entries, settings);
        assert!(prep.is_some());
        let p = prep.unwrap();
        assert_eq!(p.previous_summary.as_deref(), Some("previous summary"));
    }

    #[test]
    fn prepare_compaction_tracks_file_ops() {
        let entries = vec![
            tool_call_entry("1", "read", "/src/main.rs"),
            tool_result_entry("1r", "ok"),
            tool_call_entry("2", "edit", "/src/lib.rs"),
            tool_result_entry("2r", "ok"),
            user_entry("3", &"x".repeat(100_000)),
            assistant_entry("4", &"y".repeat(100_000), 80000, 30000),
            user_entry("5", "recent"),
        ];
        let settings = ResolvedCompactionSettings {
            enabled: true,
            reserve_tokens: 1000,
            keep_recent_tokens: 100,
            ..Default::default()
        };
        if let Some(prep) = prepare_compaction(&entries, settings) {
            let has_read = prep.file_ops.read.contains("/src/main.rs");
            let has_edit = prep.file_ops.edited.contains("/src/lib.rs");
            // At least one should be tracked (depends on cut point position)
            assert!(has_read || has_edit || prep.file_ops.read.is_empty());
        }
    }

    // ── FileOperations::read_files ──────────────────────────────────

    #[test]
    fn file_operations_read_files_iterator() {
        let mut ops = FileOperations::default();
        ops.read.insert("/a.rs".to_string());
        ops.read.insert("/b.rs".to_string());
        let files: Vec<&str> = ops.read_files().collect();
        assert_eq!(files.len(), 2);
        assert!(files.contains(&"/a.rs"));
        assert!(files.contains(&"/b.rs"));
    }

    #[test]
    fn find_cut_point_includes_tool_result_when_needed() {
        // Setup:
        // 0. User (10)
        // 1. Assistant Call (10)
        // 2. Tool Result (100)
        // 3. User (10)
        // 4. Assistant (10)
        //
        // Keep recent = 100.
        // Accumulation from end:
        // 4: 10
        // 3: 20
        // 2: 120 (Threshold crossed at index 2)
        //
        // Index 2 is ToolResult (invalid cut point).
        // Valid cut points: 0, 1, 3, 4.
        //
        // Logic should pick closest valid cut point <= 2, which is 1.
        // If it picked >= 2, it would pick 3, discarding the ToolResult and Call (keeping only 20 tokens).
        // By picking 1, we keep 1..4 (130 tokens).

        // Create entries with controlled lengths. Distinct words keep the
        // token count high under BOTH counters (a run of identical chars
        // BPE-compresses to almost nothing): 80 words is ~130 tokens via
        // chars/4 and ~160 via O200k.
        let tr_text = distinct_words(80);
        let entries = vec![
            user_entry("0", "user"),              // Valid
            assistant_entry("1", "call", 10, 10), // Valid (Assistant)
            tool_result_entry("2", &tr_text),     // Invalid
            user_entry("3", "user"),              // Valid
            assistant_entry("4", "resp", 10, 10), // Valid
        ];

        // Verify token estimates (approx)
        // 0: ceil(4/3) = 2
        // 1: ceil(4/3) = 2
        // 2: ceil(400/3) = 134
        // 3: ceil(4/3) = 2
        // 4: ceil(4/3) = 2
        // Total recent needed: 100.
        // Accumulate: 4(2)+3(2)+2(134) = 138. Crossed at 2.

        let settings = ResolvedCompactionSettings {
            enabled: true,
            context_window_tokens: 15,
            reserve_tokens: 0,
            keep_recent_tokens: 100,
        };

        let prep = prepare_compaction(&entries, settings).expect("should compact");

        // Cut point is index 1 (Assistant/Call). Because entries[1] is Assistant (not User),
        // this is a split turn: the turn started at index 0 (User). The User message at index 0
        // goes into turn_prefix_messages (not messages_to_summarize) because history_end = 0.
        assert_eq!(prep.first_kept_entry_id, "1");

        // messages_to_summarize is entries[0..0] = empty (split-turn puts the
        // prefix in turn_prefix_messages instead).
        assert!(
            prep.messages_to_summarize.is_empty(),
            "split turn: user goes into turn prefix, not summarize"
        );

        // turn_prefix_messages should contain the User message at index 0.
        assert_eq!(prep.turn_prefix_messages.len(), 1);
        match &prep.turn_prefix_messages[0] {
            SessionMessage::User { content, .. } => {
                if let UserContent::Text(t) = content {
                    assert_eq!(t, "user");
                } else {
                    panic!();
                }
            }
            _ => panic!(),
        }
    }

    #[test]
    fn find_cut_point_should_not_discard_context_to_skip_tool_chain() {
        // Setup (estimate_tokens uses ceil(chars/3)):
        // 0. User "x"*4000 → 1334 tokens
        // 1. Assistant "x"*400 → 134 tokens
        // 2. Tool Result "x"*400 → 134 tokens
        // 3. User "next" → 2 tokens
        //
        // Keep recent = 150.
        // Accumulation (from end):
        // 3: 2
        // 2: 136
        // 1: 270 (Crosses 150) -> cut_index = 1
        //
        // The cut should land at index 1 (the assistant message), keeping
        // entries 1-3 and summarizing only entry 0.

        let entries = vec![
            // Distinct words keep counts materially similar under the BPE
            // counter and the chars/4 fallback (see the sibling cut-point
            // test): ~1000+, ~100-120, ~65-80, ~1 tokens respectively.
            user_entry("0", &distinct_words(600)),
            assistant_entry("1", &distinct_words(120), 50, 50),
            tool_result_entry("2", &distinct_words(60)),
            user_entry("3", "next"),
        ];

        let settings = ResolvedCompactionSettings {
            enabled: true,
            context_window_tokens: 200,
            reserve_tokens: 0,
            keep_recent_tokens: 150,
        };

        // We use prepare_compaction as the entry point
        let prep = prepare_compaction(&entries, settings).expect("should compact");

        // We expect to keep from 1 (Assistant). The cut splits the turn
        // (user 0 + assistant 1), so user 0 goes into the turn prefix.
        assert_eq!(
            prep.first_kept_entry_id, "1",
            "Should start at Assistant message to preserve context"
        );
        assert!(
            prep.is_split_turn,
            "Cut should split the user/assistant turn"
        );
        assert_eq!(
            prep.turn_prefix_messages.len(),
            1,
            "User entry at index 0 should be in the turn prefix"
        );
        assert!(
            prep.messages_to_summarize.is_empty(),
            "Nothing before the turn to summarize"
        );
    }

    // ── preparation JSON round-trip (gh #167 / bd-i28yz) ─────────────

    mod preparation_json {
        use super::*;

        fn make_preparation() -> CompactionPreparation {
            let mut file_ops = FileOperations::default();
            file_ops.read.insert("src/lib.rs".to_string());
            file_ops.written.insert("src/new.rs".to_string());
            file_ops.edited.insert("src/agent.rs".to_string());
            CompactionPreparation {
                first_kept_entry_id: "entry-9".to_string(),
                messages_to_summarize: vec![
                    make_user_text("investigate the flaky scheduler test"),
                    make_assistant_text("Root cause is a race in the scheduler", 10, 5),
                ],
                turn_prefix_messages: vec![make_user_text("split turn prefix request")],
                is_split_turn: true,
                tokens_before: 4200,
                previous_summary: Some("## Goal\nShip the scheduler fix".to_string()),
                file_ops,
                settings: ResolvedCompactionSettings::default(),
            }
        }

        #[test]
        fn round_trips_through_to_value_and_back() {
            let prep = make_preparation();
            let value = compaction_preparation_to_value(&prep);
            let parsed = compaction_preparation_from_value(&value)
                .expect("serializer output must deserialize");

            assert_eq!(parsed.first_kept_entry_id, prep.first_kept_entry_id);
            assert_eq!(
                parsed.messages_to_summarize.len(),
                prep.messages_to_summarize.len()
            );
            assert_eq!(
                parsed.turn_prefix_messages.len(),
                prep.turn_prefix_messages.len()
            );
            assert_eq!(parsed.is_split_turn, prep.is_split_turn);
            assert_eq!(parsed.tokens_before, prep.tokens_before);
            assert_eq!(parsed.previous_summary, prep.previous_summary);
            assert_eq!(parsed.file_ops.read, prep.file_ops.read);
            assert_eq!(parsed.file_ops.written, prep.file_ops.written);
            assert_eq!(parsed.file_ops.edited, prep.file_ops.edited);
            assert_eq!(parsed.settings.enabled, prep.settings.enabled);
            assert_eq!(
                parsed.settings.context_window_tokens,
                prep.settings.context_window_tokens
            );
            assert_eq!(parsed.settings.reserve_tokens, prep.settings.reserve_tokens);
            assert_eq!(
                parsed.settings.keep_recent_tokens,
                prep.settings.keep_recent_tokens
            );
        }

        #[test]
        fn missing_previous_summary_round_trips_as_none() {
            let mut prep = make_preparation();
            prep.previous_summary = None;
            let value = compaction_preparation_to_value(&prep);
            let parsed = compaction_preparation_from_value(&value).expect("deserialize");
            assert_eq!(parsed.previous_summary, None);
        }

        #[test]
        fn rejects_malformed_preparation() {
            // Not an object.
            let err = compaction_preparation_from_value(&json!("nope")).expect_err("non-object");
            assert!(err.to_string().contains("must be a JSON object"), "{err}");

            // Missing / empty firstKeptEntryId.
            let mut value = compaction_preparation_to_value(&make_preparation());
            value["firstKeptEntryId"] = json!("");
            let err = compaction_preparation_from_value(&value).expect_err("empty id");
            assert!(
                err.to_string()
                    .contains("`firstKeptEntryId` must be a non-empty string"),
                "{err}"
            );

            // Malformed message entry.
            let mut value = compaction_preparation_to_value(&make_preparation());
            value["messagesToSummarize"] = json!([{ "role": "no-such-role" }]);
            let err = compaction_preparation_from_value(&value).expect_err("bad message");
            assert!(
                err.to_string()
                    .contains("`messagesToSummarize` contains a malformed session message"),
                "{err}"
            );

            // Wrong-typed tokensBefore.
            let mut value = compaction_preparation_to_value(&make_preparation());
            value["tokensBefore"] = json!("lots");
            let err = compaction_preparation_from_value(&value).expect_err("bad tokens");
            assert!(
                err.to_string()
                    .contains("`tokensBefore` must be an unsigned integer"),
                "{err}"
            );

            // Non-string file op entry.
            let mut value = compaction_preparation_to_value(&make_preparation());
            value["fileOps"]["read"] = json!([42]);
            let err = compaction_preparation_from_value(&value).expect_err("bad file op");
            assert!(
                err.to_string()
                    .contains("`fileOps.read` must contain only strings"),
                "{err}"
            );

            // Missing settings.
            let mut value = compaction_preparation_to_value(&make_preparation());
            value.as_object_mut().expect("object").remove("settings");
            let err = compaction_preparation_from_value(&value).expect_err("no settings");
            assert!(
                err.to_string().contains("`settings` must be an object"),
                "{err}"
            );

            // Non-string previousSummary.
            let mut value = compaction_preparation_to_value(&make_preparation());
            value["previousSummary"] = json!(17);
            let err = compaction_preparation_from_value(&value).expect_err("bad summary");
            assert!(
                err.to_string()
                    .contains("`previousSummary` must be a string when present"),
                "{err}"
            );
        }
    }

    // ── deterministic fallback summarization ─────────────────────────

    mod fallback {
        use super::*;
        use async_trait::async_trait;
        use futures::Stream;
        use std::pin::Pin;

        struct FailingProvider;

        #[async_trait]
        #[allow(clippy::unnecessary_literal_bound)]
        impl Provider for FailingProvider {
            fn name(&self) -> &str {
                "test-failing"
            }

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

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

            async fn stream(
                &self,
                _context: &Context<'_>,
                _options: &StreamOptions,
            ) -> crate::error::Result<
                Pin<Box<dyn Stream<Item = crate::error::Result<crate::model::StreamEvent>> + Send>>,
            > {
                Err(Error::api("HTTP 500: request exceeds context window"))
            }
        }

        struct FixedSummaryProvider;

        #[async_trait]
        #[allow(clippy::unnecessary_literal_bound)]
        impl Provider for FixedSummaryProvider {
            fn name(&self) -> &str {
                "test-fixed"
            }

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

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

            async fn stream(
                &self,
                _context: &Context<'_>,
                _options: &StreamOptions,
            ) -> crate::error::Result<
                Pin<Box<dyn Stream<Item = crate::error::Result<crate::model::StreamEvent>> + Send>>,
            > {
                let message = AssistantMessage {
                    content: vec![ContentBlock::Text(TextContent::new("LLM SUMMARY"))],
                    api: String::new(),
                    provider: String::new(),
                    model: String::new(),
                    stop_reason: StopReason::Stop,
                    stop_details: None,
                    error_message: None,
                    timestamp: 0,
                    usage: Usage::default(),
                };
                Ok(Box::pin(futures::stream::iter(vec![Ok(
                    crate::model::StreamEvent::Done {
                        reason: StopReason::Stop,
                        message,
                    },
                )])))
            }
        }

        fn run_async<T>(future: impl std::future::Future<Output = T>) -> T {
            let runtime = asupersync::runtime::RuntimeBuilder::current_thread()
                .build()
                .expect("build test runtime");
            runtime.block_on(future)
        }

        fn make_preparation() -> CompactionPreparation {
            let mut file_ops = FileOperations::default();
            file_ops.read.insert("src/lib.rs".to_string());
            file_ops.edited.insert("src/agent.rs".to_string());
            CompactionPreparation {
                first_kept_entry_id: "entry-9".to_string(),
                messages_to_summarize: vec![
                    make_user_text("investigate the flaky scheduler test"),
                    make_assistant_text("Root cause is a race in the scheduler", 10, 5),
                ],
                turn_prefix_messages: Vec::new(),
                is_split_turn: false,
                // Past the forced-local threshold (2x the default 128K window)
                // so provider failures degrade to the deterministic fallback.
                tokens_before: 600_000,
                previous_summary: Some("## Goal\nShip the scheduler fix".to_string()),
                file_ops,
                settings: ResolvedCompactionSettings::default(),
            }
        }

        #[test]
        fn provider_error_falls_back_to_deterministic_summary() {
            run_async(async {
                let result = compact(make_preparation(), Arc::new(FailingProvider), "key", None)
                    .await
                    .expect("compact must not fail when the provider errors");

                // Cut-point metadata preserved.
                assert_eq!(result.first_kept_entry_id, "entry-9");
                assert_eq!(result.tokens_before, 600_000);

                // Fallback marker and previous summary preserved.
                assert!(result.summary.contains("deterministic fallback"));
                assert!(result.summary.contains("Ship the scheduler fix"));

                // Message excerpts preserved with the standard labels.
                assert!(
                    result
                        .summary
                        .contains("[User]: investigate the flaky scheduler test")
                );
                assert!(result.summary.contains("race in the scheduler"));

                // File-operation lists preserved in both summary and details.
                assert!(result.summary.contains("<read-files>"));
                assert!(result.summary.contains("src/lib.rs"));
                assert!(result.summary.contains("<modified-files>"));
                assert!(result.summary.contains("src/agent.rs"));
                assert_eq!(result.details.read_files, vec!["src/lib.rs".to_string()]);
                assert_eq!(
                    result.details.modified_files,
                    vec!["src/agent.rs".to_string()]
                );
            });
        }

        #[test]
        fn provider_error_falls_back_on_split_turn() {
            run_async(async {
                let mut prep = make_preparation();
                prep.is_split_turn = true;
                prep.turn_prefix_messages = vec![make_user_text("split turn prefix request")];

                let result = compact(prep, Arc::new(FailingProvider), "key", None)
                    .await
                    .expect("split-turn compact must not fail when the provider errors");
                assert!(result.summary.contains("deterministic fallback"));
                assert!(result.summary.contains("split turn prefix request"));
            });
        }

        #[test]
        fn successful_provider_still_produces_llm_summary() {
            run_async(async {
                let result = compact(
                    make_preparation(),
                    Arc::new(FixedSummaryProvider),
                    "key",
                    None,
                )
                .await
                .expect("compact with healthy provider");
                assert!(result.summary.starts_with("LLM SUMMARY"));
                assert!(!result.summary.contains("deterministic fallback"));
            });
        }

        #[test]
        fn compact_local_never_contacts_provider_and_elides_middle_messages() {
            let mut prep = make_preparation();
            prep.messages_to_summarize = (0..200)
                .map(|i| make_user_text(&format!("message number {i} with some padding text")))
                .collect();
            // Small reserve => small excerpt budget => elision must kick in.
            prep.settings.reserve_tokens = 1_024;

            let result = compact_local(prep);
            assert!(result.summary.contains("deterministic fallback"));
            assert!(result.summary.contains("older messages elided"));
            // Oldest and newest excerpts are retained.
            assert!(result.summary.contains("message number 0 "));
            assert!(result.summary.contains("message number 199 "));
            assert_eq!(result.first_kept_entry_id, "entry-9");
            assert_eq!(result.tokens_before, 600_000);
        }

        #[test]
        fn provider_error_below_forced_threshold_propagates() {
            run_async(async {
                let mut prep = make_preparation();
                // Over the compaction threshold but below 2x the window: the
                // failure is likely transient, so the worker's retry machinery
                // must see it instead of storing a degraded local summary.
                prep.tokens_before = 200_000;

                let error = compact(prep, Arc::new(FailingProvider), "key", None)
                    .await
                    .expect_err("provider errors below the forced threshold must propagate");
                assert!(error.to_string().contains("exceeds context window"));
            });
        }

        #[test]
        fn truncate_middle_keeps_short_text_verbatim() {
            assert_eq!(truncate_middle("short text", 400), "short text");
        }

        #[test]
        fn truncate_middle_elides_long_text_on_char_boundaries() {
            let text = "é".repeat(1_000);
            let truncated = truncate_middle(&text, 100);
            assert!(truncated.contains("[900 chars elided]"));
            assert!(truncated.starts_with('é'));
            assert!(truncated.ends_with('é'));
            assert!(truncated.chars().count() < 150);
        }

        #[test]
        fn forced_local_compaction_threshold() {
            let settings = ResolvedCompactionSettings {
                enabled: true,
                context_window_tokens: 100_000,
                ..Default::default()
            };
            assert!(!requires_forced_local_compaction(199_999, &settings));
            assert!(requires_forced_local_compaction(200_000, &settings));
            assert!(requires_forced_local_compaction(1_000_000, &settings));

            let disabled = ResolvedCompactionSettings {
                enabled: false,
                ..settings
            };
            assert!(!requires_forced_local_compaction(1_000_000, &disabled));
        }
    }

    mod proptest_compaction {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            /// `calculate_context_tokens`: if total > 0, returns total.
            #[test]
            fn calc_context_tokens_total_wins(
                input in 0..1_000_000u64,
                output in 0..1_000_000u64,
                total in 1..2_000_000u64,
            ) {
                let usage = Usage {
                    input,
                    output,
                    total_tokens: total,
                    ..Usage::default()
                };
                assert_eq!(calculate_context_tokens(&usage), total);
            }

            /// `calculate_context_tokens`: if total == 0, returns input + output.
            #[test]
            fn calc_context_tokens_fallback(
                input in 0..1_000_000u64,
                output in 0..1_000_000u64,
            ) {
                let usage = Usage {
                    input,
                    output,
                    total_tokens: 0,
                    ..Usage::default()
                };
                assert_eq!(calculate_context_tokens(&usage), input + output);
            }

            /// `should_compact` returns false when disabled.
            #[test]
            fn should_compact_disabled_returns_false(
                ctx_tokens in 0..1_000_000u64,
                window in 0..500_000u32,
            ) {
                let settings = ResolvedCompactionSettings {
                    enabled: false,
                    context_window_tokens: window,
                    reserve_tokens: 16_384,
                    keep_recent_tokens: 20_000,
                };
                assert!(!should_compact(ctx_tokens, window, &settings));
            }

            /// `should_compact` threshold: tokens >= window - reserve.
            #[test]
            fn should_compact_threshold(
                ctx_tokens in 0..500_000u64,
                window in 0..300_000u32,
                reserve in 0..100_000u32,
            ) {
                let settings = ResolvedCompactionSettings {
                    enabled: true,
                    context_window_tokens: window,
                    reserve_tokens: reserve,
                    keep_recent_tokens: 20_000,
                };
                let threshold = u64::from(window).saturating_sub(u64::from(reserve));
                let result = should_compact(ctx_tokens, window, &settings);
                assert_eq!(result, ctx_tokens >= threshold);
            }

            /// `format_file_operations`: empty lists produce empty string.
            #[test]
            fn format_file_ops_empty(_dummy in 0..10u32) {
                let result = format_file_operations(&[], &[]);
                assert!(result.is_empty());
            }

            /// `format_file_operations`: read files produce `<read-files>` tag.
            #[test]
            fn format_file_ops_read_tag(
                files in prop::collection::vec("[a-z./]{1,20}", 1..5),
            ) {
                let result = format_file_operations(&files, &[]);
                assert!(result.contains("<read-files>"));
                assert!(result.contains("</read-files>"));
                assert!(!result.contains("<modified-files>"));
                for f in &files {
                    assert!(result.contains(f.as_str()));
                }
            }

            /// `format_file_operations`: modified files produce `<modified-files>` tag.
            #[test]
            fn format_file_ops_modified_tag(
                files in prop::collection::vec("[a-z./]{1,20}", 1..5),
            ) {
                let result = format_file_operations(&[], &files);
                assert!(!result.contains("<read-files>"));
                assert!(result.contains("<modified-files>"));
                assert!(result.contains("</modified-files>"));
                for f in &files {
                    assert!(result.contains(f.as_str()));
                }
            }

            /// `compute_file_lists`: modified = edited ∪ written, read_only = read \ modified.
            #[test]
            fn compute_file_lists_set_algebra(
                read in prop::collection::hash_set("[a-z]{1,5}", 0..5),
                written in prop::collection::hash_set("[a-z]{1,5}", 0..5),
                edited in prop::collection::hash_set("[a-z]{1,5}", 0..5),
            ) {
                let file_ops = FileOperations {
                    read: read.clone(),
                    written: written.clone(),
                    edited: edited.clone(),
                };
                let (read_only, modified) = compute_file_lists(&file_ops);
                // Modified = edited ∪ written
                let expected_modified: HashSet<&String> =
                    edited.iter().chain(written.iter()).collect();
                let actual_modified: HashSet<&String> = modified.iter().collect();
                assert_eq!(actual_modified, expected_modified);
                // Read-only = read \ modified (no overlap)
                for f in &read_only {
                    assert!(!modified.contains(f), "overlap: {f}");
                    assert!(read.contains(f));
                }
                // Both are sorted
                for pair in read_only.windows(2) {
                    assert!(pair[0] <= pair[1]);
                }
                for pair in modified.windows(2) {
                    assert!(pair[0] <= pair[1]);
                }
            }
        }
    }
}