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
//! ECS components for agent state and execution.
use bevy_ecs::prelude::*;
use leviath_core::Region;
use serde::{Deserialize, Serialize};
/// Agent execution state component.
///
/// Tracks the current state of an agent's execution, including which stage
/// it's in and iteration counts.
#[derive(Component, Debug, Clone)]
pub struct AgentState {
/// Unique identifier for this agent instance
pub agent_id: String,
/// Current execution stage
pub current_stage: String,
/// Number of iterations in current stage
pub iteration: usize,
/// Agent status
pub status: AgentStatus,
/// IDs of child agents spawned by this agent
pub spawned_children_ids: Vec<String>,
/// If set, this agent is blocked waiting for the named child to complete
pub pending_wait: Option<String>,
/// Whether the current stage accepts mid-run user messages.
/// When false, messages stay in the inbox until a stage that accepts them.
pub accepts_messages: bool,
}
/// Reference to a parent agent, making this agent a sub-agent.
#[derive(Component, Debug, Clone)]
pub struct ParentRef {
/// Entity of the parent agent
pub parent_entity: Entity,
/// Agent ID of the parent
pub parent_agent_id: String,
/// Depth in the agent tree (root = 0)
pub depth: usize,
}
/// Tracks child agents spawned by this agent.
#[derive(Component, Debug, Clone)]
pub struct SubAgentChildren {
/// Child agent entities
pub children: Vec<Entity>,
/// Maximum allowed sub-agent tree depth
pub max_child_depth: usize,
}
/// Marker: this agent is blocked on an open user interaction (a tool-approval
/// prompt, an `ask_user_*` question, or a plan-approval review).
///
/// Inserted by [`reflect_interaction_status`](crate::pipeline::reflect_interaction_status)
/// when the shared [`InteractionHub`](crate::interaction_hub::InteractionHub)
/// reports a pending request for the agent, and removed when that request
/// clears. It records that the agent's `Waiting` status is interaction-driven,
/// so the reflection is distinct from fan-out waiting
/// ([`FanOutWaiting`](crate::fanout::FanOutWaiting)).
#[derive(Component, Debug, Clone)]
pub struct AwaitingInteraction;
/// Marker: auto-approve this agent's taint-gate blocks instead of raising a
/// gate prompt.
///
/// Set when an agent is launched with `--yolo` (approve everything, run
/// unattended). The taint gate raises a `MultipleChoice` interaction that the
/// tool-policy `--yolo` wildcard does not cover, so without this a headless run -
/// e.g. one driven over the Agent Client Protocol, where no human can answer -
/// would block forever on a gate no one resolves. When present,
/// [`dispatch_tools`](crate::pipeline::dispatch_tools) still evaluates the gate
/// (so an over-cleared call is recorded in the audit trail as
/// [`YoloAutoApprove`](leviath_core::taint::GateDecisionSource::YoloAutoApprove))
/// but auto-approves the call instead of raising a prompt - enforcement is
/// waived, accountability is kept.
#[derive(Component, Debug, Clone, Copy, Default)]
pub struct GateAutoApprove;
/// `--yolo`'s counterpart for blueprint-declared interaction points: approve
/// them without opening a prompt.
///
/// A stage-boundary checkpoint (`plan_approval` and friends) blocks on the
/// interaction hub exactly like a tool approval does, so an unattended run
/// would park at the first one forever - the same dead end a blocking tool
/// approval poses for a headless run, reached a different way. When present,
/// [`dispatch_interaction_point`](crate::interaction_points::dispatch_interaction_point)
/// still publishes the document to its region (so the decision is inspectable
/// afterwards) but resolves the point as approved.
#[derive(Component, Debug, Clone, Copy, Default)]
pub struct InteractionAutoApprove;
/// Status of an agent.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum AgentStatus {
/// Agent is idle, ready for tasks
Idle,
/// Agent is actively working on a task
Active,
/// Agent is waiting for input or external event
Waiting,
/// Agent has completed its task
Complete,
/// Agent encountered an error
Error { message: String },
/// Agent was cancelled by the user or system
Cancelled,
}
/// Result of an eviction attempt, including tokens freed and regions needing LLM compaction.
#[derive(Debug, Clone)]
pub struct EvictionResult {
/// Number of tokens freed by eviction phases 1-2 (Clearable + Temporary).
pub tokens_freed: usize,
/// Region names that need LLM-based compaction (phase 3).
pub needs_compaction: Vec<String>,
}
/// Per-stage inference configuration overrides.
///
/// Set on the agent entity before each stage to override default inference
/// parameters like temperature and max output tokens. When absent, defaults
/// are used (temperature 0.7, max output 4096).
#[derive(Component, Debug, Clone, Default)]
pub struct InferenceConfig {
/// Temperature override. If None, uses 0.7 (or 0.0 if model doesn't support it).
pub temperature: Option<f32>,
/// Max output tokens override. If None, caps at model's max_output_tokens capability.
pub max_output_tokens: Option<usize>,
/// Extra provider parameters from `[stages.<name>.model.parameters]` beyond
/// `temperature`/`max_output_tokens` (e.g. `top_p`, `stop`, `seed`,
/// `frequency_penalty`). Passed through to the provider request so models can
/// be tuned from the manifest. Empty when none are set.
pub extra_params: serde_json::Map<String, serde_json::Value>,
/// Whether to prepend the batch-tool-calls hint to this stage's system
/// prompt. Resolved from the global config → agent → stage cascade at spawn
/// (see [`leviath_core::taint::resolve_batch_tool_hint`]); `false` by default
/// so an unset config is a no-op.
pub batch_tool_hint: bool,
/// Per-stage cap on the wall-clock time (in seconds) one inference for this
/// stage may run (the whole call including retries). Sourced from
/// `[stages.<name>.model] request_timeout_secs`. When `Some`, it overrides the
/// default inference job timeout at dispatch; when `None`, the default applies.
pub request_timeout_secs: Option<u64>,
}
/// Per-entity tool result routing configuration.
///
/// When present on an entity, tool results are routed to the specified region(s)
/// instead of the default "conversation" region.
#[derive(Component, Debug, Clone)]
pub struct ToolResultRoutingComponent {
/// The routing configuration.
pub routing: leviath_core::ToolResultRouting,
}
/// Result of assembling a context window into system blocks and conversation messages.
///
/// Produced by [`ContextWindow::assemble()`]. System-bound regions (Pinned,
/// CompactHistory, etc.) become `system_blocks`; the messages region
/// (SlidingWindow) becomes typed `messages`.
#[derive(Debug, Clone)]
pub struct AssembledContext {
/// System prompt blocks (from Pinned, CompactHistory, etc. regions).
pub system_blocks: Vec<leviath_providers::SystemBlock>,
/// Conversation messages with proper role typing.
pub messages: Vec<leviath_providers::Message>,
}
/// Sort priority for a system block's cache hint.
///
/// Anthropic caches system content by prefix matching, so the most stable
/// blocks must sort first to form the cacheable prefix. Lower value = earlier.
fn cache_hint_sort_priority(hint: leviath_core::CacheHint) -> u8 {
use leviath_core::CacheHint;
match hint {
CacheHint::Always => 0, // Pinned, CompactHistory - most stable
CacheHint::SlidingPrefix { .. } => 1, // Partially stable
CacheHint::UntilChanged => 2, // Compacting - changes on compaction
CacheHint::Never => 3, // Temporary, Clearable - changes every iteration
}
}
/// Context window component storing the agent's memory regions.
#[derive(Component, Debug, Clone)]
pub struct ContextWindow {
/// All regions in this context window
pub regions: Vec<Region>,
/// Current total token usage
pub current_tokens: usize,
/// Maximum token budget
pub max_tokens: usize,
/// Compiled custom-region scripts, keyed by the script path each
/// `RegionKind::Custom` carries. Populated once at spawn by the CLI
/// (which resolves blueprint-dir-relative paths and compile-checks the
/// files); a stage-layout swap rebuilds `regions` but leaves this table
/// untouched, so per-stage custom regions keep working. Empty when no
/// custom regions exist - every hook lookup then misses and the region
/// renders its fallback shape.
pub region_scripts: std::collections::HashMap<
String,
std::sync::Arc<leviath_scripting::region_hook::RegionScript>,
>,
}
impl ContextWindow {
/// Create a new context window with the specified budget.
pub fn new(max_tokens: usize) -> Self {
Self {
regions: Vec::new(),
current_tokens: 0,
max_tokens,
region_scripts: std::collections::HashMap::new(),
}
}
/// The compiled script backing `region_name`, when it is a custom region
/// whose script path has an entry in [`Self::region_scripts`].
fn custom_script_for(
&self,
region_name: &str,
) -> Option<std::sync::Arc<leviath_scripting::region_hook::RegionScript>> {
let region = self.get_region(region_name)?;
let leviath_core::RegionKind::Custom { script, .. } = ®ion.kind else {
return None;
};
self.region_scripts.get(script).cloned()
}
/// Run a custom region's `on_write` hook (when defined) for an incoming
/// entry. `None` means the script dropped the entry - the write reports
/// success without storing anything. Non-custom regions, missing scripts,
/// and hook failures all accept the entry unchanged.
///
/// Deliberately NOT invoked by the layout-swap carry or restore overlay:
/// those re-add entries the hook already accepted once.
fn on_write_outcome(
&self,
region_name: &str,
content: String,
tokens: usize,
kind: &leviath_core::EntryKind,
) -> Option<(String, usize)> {
let Some(script) = self.custom_script_for(region_name) else {
return Some((content, tokens));
};
if !script.has_on_write() {
return Some((content, tokens));
}
// The region exists - custom_script_for resolved through it.
let region = self
.get_region(region_name)
.expect("custom_script_for resolved through this region");
match crate::custom_region::apply_on_write(&script, region, content, tokens, kind) {
crate::custom_region::OnWriteOutcome::Accept(content, tokens) => {
Some((content, tokens))
}
crate::custom_region::OnWriteOutcome::Drop => None,
}
}
/// Retry hook for a custom-region write that hit `TokenBudgetExceeded`:
/// let the script's `on_overflow` free room, then report whether a single
/// retry is worthwhile. Non-custom regions and hook failures leave the
/// original error standing (the callers' existing truncation ladders
/// apply).
fn try_custom_overflow(&mut self, region_name: &str, incoming_tokens: usize) -> bool {
let Some(script) = self.custom_script_for(region_name) else {
return false;
};
if !script.has_on_overflow() {
return false;
}
let region = self
.get_region_mut(region_name)
.expect("custom_script_for resolved through this region");
let needed = (region.current_tokens + incoming_tokens).saturating_sub(region.max_tokens);
let freed = crate::custom_region::apply_overflow(&script, region, needed);
self.current_tokens = self.calculate_tokens();
freed >= needed && needed > 0
}
/// Get a region by name.
pub fn get_region(&self, name: &str) -> Option<&Region> {
self.regions.iter().find(|r| r.name == name)
}
/// Get a mutable reference to a region by name.
pub fn get_region_mut(&mut self, name: &str) -> Option<&mut Region> {
self.regions.iter_mut().find(|r| r.name == name)
}
/// Add a region to this context window.
pub fn add_region(&mut self, region: Region) {
self.regions.push(region);
self.current_tokens = self.calculate_tokens();
}
/// Add content to a specific region.
pub fn add_to_region(
&mut self,
region_name: &str,
content: String,
tokens: usize,
) -> leviath_core::Result<()> {
let Some((content, tokens)) =
self.on_write_outcome(region_name, content, tokens, &leviath_core::EntryKind::Text)
else {
return Ok(()); // the region's script dropped the entry
};
self.write_to_region(region_name, tokens, &mut |region, tokens| {
region.add_entry(content.clone(), tokens)
})
}
/// Replace a region's entire content with a single entry (clear, then add).
/// Returns `false` (no-op) if the region does not exist. Used to keep an
/// authoritative document region (e.g. the plan) holding only its current
/// version, so revisions build on it instead of accumulating stale copies.
pub fn replace_region(&mut self, region_name: &str, content: String, tokens: usize) -> bool {
// The replacement passes through on_write like any incoming entry - a
// custom region's script sees (and may transform or refuse) it.
let Some((content, tokens)) =
self.on_write_outcome(region_name, content, tokens, &leviath_core::EntryKind::Text)
else {
// Dropped by the script: the region keeps its current content.
return self.get_region(region_name).is_some();
};
if let Some(region) = self.get_region_mut(region_name) {
region.clear();
let _ = region.add_entry(content, tokens);
self.current_tokens = self.calculate_tokens();
true
} else {
false
}
}
/// Add a typed entry to a specific region.
///
/// Like [`add_to_region`](Self::add_to_region) but the entry carries an
/// `EntryKind` so message roles are determined by type, not text-prefix
/// parsing.
pub fn add_typed_entry(
&mut self,
region_name: &str,
kind: leviath_core::EntryKind,
content: String,
tokens: usize,
) -> leviath_core::Result<()> {
let Some((content, tokens)) = self.on_write_outcome(region_name, content, tokens, &kind)
else {
return Ok(());
};
self.write_to_region(region_name, tokens, &mut |region, tokens| {
region.add_typed_entry(content.clone(), tokens, kind.clone())
})
}
/// Shared tail of every region write: run the insert, give a custom
/// region's `on_overflow` one shot at freeing room when the budget
/// rejects it, and recount the window. A `&mut dyn FnMut` (not generic)
/// keeps one instantiation for the coverage gate.
fn write_to_region(
&mut self,
region_name: &str,
tokens: usize,
insert: &mut dyn FnMut(&mut Region, usize) -> leviath_core::Result<()>,
) -> leviath_core::Result<()> {
if self.get_region(region_name).is_none() {
return Err(leviath_core::Error::RegionNotFound(region_name.to_string()));
}
let first = {
let region = self.get_region_mut(region_name).expect("checked above");
insert(region, tokens)
};
match first {
Ok(()) => {
self.current_tokens = self.calculate_tokens();
Ok(())
}
Err(leviath_core::Error::TokenBudgetExceeded { .. })
if self.try_custom_overflow(region_name, tokens) =>
{
let region = self.get_region_mut(region_name).expect("checked above");
let retried = insert(region, tokens);
self.current_tokens = self.calculate_tokens();
retried
}
Err(e) => Err(e),
}
}
/// Calculate current token usage across all regions.
pub fn calculate_tokens(&self) -> usize {
self.regions.iter().map(|r| r.current_tokens).sum()
}
/// Check if the context window needs eviction.
pub fn needs_eviction(&self, threshold: f32) -> bool {
let usage_ratio = self.current_tokens as f32 / self.max_tokens as f32;
usage_ratio >= threshold
}
/// Execute eviction cascade to free up space.
///
/// Returns an `EvictionResult` with tokens freed and any regions that need
/// LLM-based compaction. The caller is responsible for performing compaction
/// on the listed regions (since it requires async LLM access).
pub fn try_evict(&mut self, target_free_tokens: usize) -> leviath_core::Result<EvictionResult> {
use leviath_core::RegionKind;
let initial_tokens = self.current_tokens;
// Check if we have any evictable regions
let has_evictable = self.regions.iter().any(|r| {
matches!(
r.kind,
RegionKind::Clearable
| RegionKind::Temporary
| RegionKind::Custom {
persistent: false,
..
}
)
});
if !has_evictable {
tracing::warn!(
"Context window has no Clearable or Temporary regions. \
This may be intentional, but usually indicates a configuration error."
);
}
// Phase 1: Clear Clearable regions (all-or-nothing)
for region in &mut self.regions {
if matches!(region.kind, RegionKind::Clearable) && !region.content.is_empty() {
let freed = region.current_tokens;
region.clear();
self.current_tokens -= freed;
tracing::debug!(
region = %region.name,
tokens_freed = freed,
"Cleared Clearable region (all-or-nothing)"
);
if self.max_tokens.saturating_sub(self.current_tokens) >= target_free_tokens {
return Ok(EvictionResult {
tokens_freed: initial_tokens - self.current_tokens,
needs_compaction: Vec::new(),
});
}
}
}
// Phase 1.5: Give each non-persistent custom region's on_overflow
// hook first say over what IT loses, before the indiscriminate
// oldest-first cascade below. A script that keeps errors and drops
// successes only works if it runs before oldest-first does. Hook
// absent/failing/insufficient → phase 2 makes the guaranteed
// progress.
let mut custom_freed = 0usize;
for i in 0..self.regions.len() {
let needed = target_free_tokens
.saturating_sub(self.max_tokens.saturating_sub(self.current_tokens));
if needed == 0 {
break;
}
let region = &self.regions[i];
if !matches!(
region.kind,
RegionKind::Custom {
persistent: false,
..
}
) || region.content.is_empty()
{
continue;
}
let Some(script) = self.custom_script_for(®ion.name.clone()) else {
continue;
};
if !script.has_on_overflow() {
continue;
}
let freed = crate::custom_region::apply_overflow(&script, &mut self.regions[i], needed);
self.current_tokens = self.current_tokens.saturating_sub(freed);
custom_freed += freed;
if freed > 0 {
tracing::debug!(
region = %self.regions[i].name,
tokens_freed = freed,
"custom region's on_overflow chose its own evictions"
);
}
}
// Return early ONLY when a script's own drops satisfied the target -
// otherwise phase 2 would immediately evict one more entry (it checks
// the target *after* each eviction), overriding the script's
// retention choice. Windows with no custom drops (custom_freed == 0)
// fall through with phase 2's pre-existing behavior, byte-identical.
if custom_freed > 0
&& self.max_tokens.saturating_sub(self.current_tokens) >= target_free_tokens
{
return Ok(EvictionResult {
tokens_freed: initial_tokens - self.current_tokens,
needs_compaction: Vec::new(),
});
}
// Phase 2: Evict from Temporary regions (oldest first, one at a time).
// Non-persistent Custom regions join this phase: their script's
// on_overflow hook (when present) has already had its say in phase
// 1.5; oldest-first is the guaranteed-progress fallback.
loop {
let mut evicted_any = false;
for region in &mut self.regions {
if matches!(
region.kind,
RegionKind::Temporary
| RegionKind::Custom {
persistent: false,
..
}
) && let Some(entry) = region.remove_oldest()
{
let freed = entry.tokens;
self.current_tokens -= freed;
evicted_any = true;
tracing::debug!(
region = %region.name,
tokens_freed = freed,
"Evicted temporary region entry (oldest first)"
);
if self.max_tokens.saturating_sub(self.current_tokens) >= target_free_tokens {
return Ok(EvictionResult {
tokens_freed: initial_tokens - self.current_tokens,
needs_compaction: Vec::new(),
});
}
}
}
if !evicted_any {
break;
}
}
// Phase 3: If still need space, identify Compacting regions that need compaction
let mut needs_compaction = Vec::new();
if self.max_tokens.saturating_sub(self.current_tokens) < target_free_tokens {
for region in &self.regions {
if region.needs_compaction() {
needs_compaction.push(region.name.clone());
}
}
}
// Phase 4: SlidingWindow regions are NEVER reduced
// Phase 5: Pinned and CompactHistory regions are NEVER touched
// Check for pinned regions over budget
let pinned_tokens: usize = self
.regions
.iter()
.filter(|r| {
matches!(
r.kind,
RegionKind::Pinned
| RegionKind::CompactHistory { .. }
| RegionKind::Custom {
persistent: true,
..
}
)
})
.map(|r| r.current_tokens)
.sum();
if pinned_tokens > self.max_tokens {
return Err(leviath_core::Error::PinnedRegionsOverBudget {
pinned_tokens,
total_budget: self.max_tokens,
});
}
Ok(EvictionResult {
tokens_freed: initial_tokens - self.current_tokens,
needs_compaction,
})
}
/// Result of assembling the context window into system blocks + messages.
///
/// System-bound regions become `system_blocks`; the messages region
/// becomes `messages` with proper typed entries (no text-prefix parsing).
///
/// Thin wrapper over [`assemble_with_meta`](Self::assemble_with_meta) with
/// no stage metadata - custom-region scripts see empty stage fields.
pub fn assemble(&self) -> AssembledContext {
self.assemble_with_meta(&crate::custom_region::AssembleMeta::default())
}
/// [`assemble`](Self::assemble) with stage metadata for custom-region
/// `render(ctx)` hooks (stage name, per-stage iteration count, model).
/// The inference path (`build_request`) threads real values; other
/// callers use the default.
pub fn assemble_with_meta(
&self,
meta: &crate::custom_region::AssembleMeta,
) -> AssembledContext {
use leviath_core::{CacheHint, EntryKind};
let mut system_blocks = Vec::new();
let mut messages: Vec<leviath_providers::Message> = Vec::new();
for region in &self.regions {
// Custom regions render even when empty - a script may emit
// static scaffolding. Every other kind skips an empty region.
let is_custom = matches!(region.kind, leviath_core::RegionKind::Custom { .. });
if region.content.is_empty() && !is_custom {
continue;
}
match ®ion.kind {
// System-level content → system blocks
leviath_core::RegionKind::Pinned => {
let text = region
.content
.iter()
.map(|e| e.content.as_str())
.collect::<Vec<_>>()
.join("\n\n");
system_blocks.push(leviath_providers::SystemBlock {
text,
cache_hint: CacheHint::Always,
});
}
leviath_core::RegionKind::CompactHistory { .. } => {
let text = region
.content
.iter()
.map(|e| e.content.as_str())
.collect::<Vec<_>>()
.join("\n\n");
system_blocks.push(leviath_providers::SystemBlock {
text,
cache_hint: CacheHint::Always,
});
}
// Messages region → Vec<Message> with proper typed entries.
// Consecutive ToolResult entries are merged into a single user
// message with multiple tool_result content blocks (required by
// Anthropic: one assistant tool_use msg → one user tool_result msg).
leviath_core::RegionKind::SlidingWindow { .. } => {
let mut pending_tool_results: Vec<leviath_providers::ContentBlock> = Vec::new();
for entry in ®ion.content {
// Flush any pending tool results when we hit a non-ToolResult entry
if !matches!(entry.kind, EntryKind::ToolResult { .. })
&& !pending_tool_results.is_empty()
{
messages.push(leviath_providers::Message {
role: "user".to_string(),
content: leviath_providers::MessageContent::Blocks(std::mem::take(
&mut pending_tool_results,
)),
cache_breakpoint: false,
});
}
match &entry.kind {
EntryKind::UserMessage => {
messages.push(leviath_providers::Message {
role: "user".to_string(),
content: entry.content.clone().into(),
cache_breakpoint: false,
});
}
EntryKind::AssistantTurn { tool_calls } => {
if tool_calls.is_empty() {
messages.push(leviath_providers::Message {
role: "assistant".to_string(),
content: entry.content.clone().into(),
cache_breakpoint: false,
});
} else {
let mut blocks = Vec::new();
if !entry.content.is_empty() {
blocks.push(leviath_providers::ContentBlock::Text {
text: entry.content.clone(),
});
}
for tc in tool_calls {
blocks.push(leviath_providers::ContentBlock::ToolUse {
id: tc.id.clone(),
name: tc.name.clone(),
input: tc.arguments.clone(),
thought_signature: tc.thought_signature.clone(),
});
}
messages.push(leviath_providers::Message {
role: "assistant".to_string(),
content: leviath_providers::MessageContent::Blocks(blocks),
cache_breakpoint: false,
});
}
}
EntryKind::ToolResult {
tool_call_id,
is_error,
..
} => {
// Accumulate - will be flushed on next non-ToolResult or end
pending_tool_results.push(
leviath_providers::ContentBlock::ToolResult {
tool_use_id: tool_call_id.clone(),
content: entry.content.clone(),
is_error: *is_error,
},
);
}
EntryKind::Text => {
let trimmed = entry.content.trim();
if let Some(rest) = trimmed.strip_prefix("Assistant: ") {
messages.push(leviath_providers::Message {
role: "assistant".to_string(),
content: rest.to_string().into(),
cache_breakpoint: false,
});
} else if let Some(rest) = trimmed.strip_prefix("User: ") {
messages.push(leviath_providers::Message {
role: "user".to_string(),
content: rest.to_string().into(),
cache_breakpoint: false,
});
} else {
messages.push(leviath_providers::Message {
role: "user".to_string(),
content: entry.content.clone().into(),
cache_breakpoint: false,
});
}
}
}
}
// Flush any remaining tool results at the end of the region
if !pending_tool_results.is_empty() {
messages.push(leviath_providers::Message {
role: "user".to_string(),
content: leviath_providers::MessageContent::Blocks(std::mem::take(
&mut pending_tool_results,
)),
cache_breakpoint: false,
});
}
}
// Compacting / Temporary / Clearable → system blocks
leviath_core::RegionKind::Compacting { .. } => {
let text = region
.content
.iter()
.map(|e| e.content.as_str())
.collect::<Vec<_>>()
.join("\n\n");
system_blocks.push(leviath_providers::SystemBlock {
text: format!("[{}]:\n{}", region.name, text),
cache_hint: CacheHint::UntilChanged,
});
}
leviath_core::RegionKind::Temporary => {
let text = region
.content
.iter()
.map(|e| e.content.as_str())
.collect::<Vec<_>>()
.join("\n\n");
system_blocks.push(leviath_providers::SystemBlock {
text: format!("[{}]:\n{}", region.name, text),
cache_hint: CacheHint::Never,
});
}
leviath_core::RegionKind::Clearable => {
let text = region
.content
.iter()
.map(|e| e.content.as_str())
.collect::<Vec<_>>()
.join("\n\n");
system_blocks.push(leviath_providers::SystemBlock {
text: format!("[{}]:\n{}", region.name, text),
cache_hint: CacheHint::Never,
});
}
// Custom (script-backed) regions render through their Rhai
// hook; a missing script or any hook failure falls back to
// the Temporary-style block inside `render_custom_region`,
// so a custom region is never silently dropped.
leviath_core::RegionKind::Custom { script, persistent } => {
crate::custom_region::render_custom_region(
region,
self.region_scripts.get(script),
*persistent,
meta,
self.current_tokens,
self.max_tokens,
&mut system_blocks,
&mut messages,
);
}
// HashMap regions → system blocks with key headers
leviath_core::RegionKind::HashMap { .. } => {
let text = region
.content
.iter()
.map(|e| {
if let Some(key) = &e.key {
format!("### [{}]\n{}", key, e.content)
} else {
e.content.clone()
}
})
.collect::<Vec<_>>()
.join("\n\n");
system_blocks.push(leviath_providers::SystemBlock {
text: format!("[{}]:\n{}", region.name, text),
cache_hint: CacheHint::UntilChanged,
});
}
}
}
// ── Sort system blocks for optimal prefix caching ────────────────
//
// Anthropic caches system content based on prefix matching.
// Stable blocks (Pinned, CompactHistory) should come first so
// they form the cacheable prefix, with volatile blocks
// (Compacting, Temporary, Clearable) after.
system_blocks.sort_by_key(|block| cache_hint_sort_priority(block.cache_hint));
// ── Sanitize orphaned tool_use / tool_result blocks ──────────────
//
// Collect all tool_use IDs from assistant messages and all tool_result
// IDs from user messages. Strip any that don't have a matching pair.
let mut tool_use_ids = std::collections::HashSet::new();
let mut tool_result_ids = std::collections::HashSet::new();
for msg in &messages {
if let leviath_providers::MessageContent::Blocks(blocks) = &msg.content {
for block in blocks {
match block {
leviath_providers::ContentBlock::ToolUse { id, .. } => {
tool_use_ids.insert(id.clone());
}
leviath_providers::ContentBlock::ToolResult { tool_use_id, .. } => {
tool_result_ids.insert(tool_use_id.clone());
}
_ => {}
}
}
}
}
let orphaned_tool_uses: std::collections::HashSet<_> =
tool_use_ids.difference(&tool_result_ids).cloned().collect();
let orphaned_tool_results: std::collections::HashSet<_> =
tool_result_ids.difference(&tool_use_ids).cloned().collect();
if !orphaned_tool_uses.is_empty() || !orphaned_tool_results.is_empty() {
tracing::warn!(
orphaned_tool_uses = orphaned_tool_uses.len(),
orphaned_tool_results = orphaned_tool_results.len(),
"Stripping orphaned tool_use/tool_result blocks from assembled context"
);
messages = messages
.into_iter()
.filter_map(|msg| {
if let leviath_providers::MessageContent::Blocks(blocks) = &msg.content {
let filtered: Vec<_> = blocks
.iter()
.filter(|block| match block {
leviath_providers::ContentBlock::ToolUse { id, .. } => {
!orphaned_tool_uses.contains(id)
}
leviath_providers::ContentBlock::ToolResult {
tool_use_id, ..
} => !orphaned_tool_results.contains(tool_use_id),
_ => true,
})
.cloned()
.collect();
if filtered.is_empty() {
// No content left - drop this message entirely
None
} else {
Some(leviath_providers::Message {
role: msg.role.clone(),
content: leviath_providers::MessageContent::Blocks(filtered),
cache_breakpoint: msg.cache_breakpoint,
})
}
} else {
Some(msg)
}
})
.collect();
}
// ── Set cache breakpoints on stable message prefix ──────────────
//
// In an iterative inference loop, only the last few messages change
// each iteration (new assistant turn + tool results). Everything
// before is stable across iterations and benefits from Anthropic's
// prompt caching. We place a cache breakpoint near the end of the
// stable prefix to maximize cache hits.
//
// Anthropic allows up to 4 breakpoints. We use 1 on messages
// (system blocks already have cache_control via CacheHint).
// Place it on the 4th-from-last message to give a buffer for the
// new messages added each iteration (typically 2-3).
if messages.len() >= 5 {
let bp_idx = messages.len() - 4;
messages[bp_idx].cache_breakpoint = true;
} else if messages.len() >= 2 {
// Small conversation - cache at least the first message
messages[0].cache_breakpoint = true;
}
// Ensure there's at least one user message
if !messages.iter().any(|m| m.role == "user") {
messages.push(leviath_providers::Message {
role: "user".to_string(),
content: "Begin.".into(),
cache_breakpoint: false,
});
}
// The conversation must END with a user message: providers reject a
// request that ends on an assistant turn as an (unsupported) prefill
// ("This model does not support assistant message prefill"). After a
// stage transition that carries the conversation, the last message is
// the previous stage's final assistant turn - hand the turn back to the
// model with a minimal nudge so it acts on the new stage's instructions.
if messages.last().map(|m| m.role.as_str()) == Some("assistant") {
messages.push(leviath_providers::Message {
role: "user".to_string(),
content: "Continue.".into(),
cache_breakpoint: false,
});
}
AssembledContext {
system_blocks,
messages,
}
}
/// Enable taint tracking on all regions in this context window.
pub fn enable_taint_tracking(&mut self) {
for region in &mut self.regions {
region.enable_taint_tracking();
}
}
/// Add tainted content to a specific region.
pub fn add_tainted_to_region(
&mut self,
region_name: &str,
content: String,
tokens: usize,
taint_level: leviath_core::TaintLevel,
) -> leviath_core::Result<()> {
let Some((content, tokens)) =
self.on_write_outcome(region_name, content, tokens, &leviath_core::EntryKind::Text)
else {
return Ok(());
};
self.write_to_region(region_name, tokens, &mut |region, tokens| {
region.add_tainted_entry(content.clone(), tokens, taint_level)
})
}
/// Add a typed entry to a region with a specific taint level.
///
/// The typed+tainted counterpart of [`add_typed_entry`](Self::add_typed_entry)
/// and [`add_tainted_to_region`](Self::add_tainted_to_region): the entry keeps
/// its `EntryKind` (so turn-group eviction stays intact) while contributing
/// the given taint level (so the taint gate sees sensitive tool output).
pub fn add_typed_tainted_to_region(
&mut self,
region_name: &str,
kind: leviath_core::EntryKind,
content: String,
tokens: usize,
taint_level: leviath_core::TaintLevel,
) -> leviath_core::Result<()> {
let Some((content, tokens)) = self.on_write_outcome(region_name, content, tokens, &kind)
else {
return Ok(());
};
self.write_to_region(region_name, tokens, &mut |region, tokens| {
region.add_typed_tainted_entry(content.clone(), tokens, kind.clone(), taint_level)
})
}
/// Get the overall taint level (max across all regions).
/// Returns None if no region has taint tracking enabled.
pub fn overall_taint(&self) -> Option<leviath_core::TaintLevel> {
let mut max_taint = None;
for region in &self.regions {
if let Some(level) = region.taint_level() {
max_taint = Some(match max_taint {
Some(current) => level.max(current),
None => level,
});
}
}
max_taint
}
/// Get a summary of taint levels across all regions (for dashboard/audit).
pub fn taint_summary(&self) -> Vec<(String, leviath_core::TaintLevel)> {
self.regions
.iter()
.filter_map(|r| r.taint_level().map(|t| (r.name.clone(), t)))
.collect()
}
}
/// Inference result component.
///
/// Stores the result of an LLM inference call, including the response
/// and any tool calls that need to be executed.
#[derive(Component, Debug, Clone)]
pub struct InferenceResult {
/// The model's response text
pub response: String,
/// Tool calls requested by the model
pub tool_calls: Vec<ToolCall>,
/// Tokens used in this inference
pub tokens_used: usize,
/// Timestamp of this inference
pub timestamp: i64,
}
/// A tool call requested by the model.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
/// Tool identifier
pub tool_id: String,
/// Tool name
pub name: String,
/// Tool arguments
pub arguments: serde_json::Value,
/// Opaque provider token echoed back with this call on the next request
/// (Gemini's `thought_signature`); `None` when the provider has none.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thought_signature: Option<String>,
}
/// A message that can be sent to a running agent.
#[derive(Debug, Clone)]
pub struct AgentMessage {
/// Target agent ID
pub agent_id: String,
/// Message content
pub content: String,
/// Which region to add the message to (default: "conversation")
pub target_region: Option<String>,
/// Priority (higher = processed sooner)
pub priority: i32,
}
/// Inbox component for receiving messages sent to a running agent.
#[derive(Component, Debug, Clone)]
pub struct MessageInbox {
/// Pending messages waiting to be processed
pub messages: Vec<AgentMessage>,
}
impl MessageInbox {
/// Create a new empty inbox.
pub fn new() -> Self {
Self {
messages: Vec::new(),
}
}
/// Add a message to the inbox.
pub fn push(&mut self, msg: AgentMessage) {
self.messages.push(msg);
// Sort by priority descending so highest priority is first
self.messages.sort_by_key(|m| std::cmp::Reverse(m.priority));
}
/// Drain all messages from the inbox.
pub fn drain_all(&mut self) -> Vec<AgentMessage> {
std::mem::take(&mut self.messages)
}
}
impl Default for MessageInbox {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::with_tracing;
use leviath_core::{EvictionStrategy, Region, RegionKind};
#[test]
fn test_context_window_creation() {
let window = ContextWindow::new(10000);
assert_eq!(window.max_tokens, 10000);
assert_eq!(window.current_tokens, 0);
}
#[test]
fn test_needs_eviction() {
let mut window = ContextWindow::new(10000);
window.current_tokens = 9500;
assert!(window.needs_eviction(0.9));
window.current_tokens = 5000;
assert!(!window.needs_eviction(0.9));
}
#[test]
fn test_add_region() {
let mut window = ContextWindow::new(10000);
let region = Region::new("test".to_string(), RegionKind::Pinned, 1000);
window.add_region(region);
assert_eq!(window.regions.len(), 1);
}
#[test]
fn replace_region_overwrites_existing_and_reports_missing() {
let mut window = ContextWindow::new(10000);
let mut region = Region::new("plan".to_string(), RegionKind::Pinned, 6000);
region.add_entry("old plan".to_string(), 3).unwrap();
window.add_region(region);
// Replacing an existing region overwrites its content wholesale.
assert!(window.replace_region("plan", "new plan".to_string(), 3));
let plan = window.get_region("plan").unwrap();
assert_eq!(plan.content.len(), 1);
assert_eq!(plan.content[0].content, "new plan");
// A missing region is a no-op that reports false.
assert!(!window.replace_region("nope", "x".to_string(), 1));
}
#[test]
fn test_clearable_eviction() {
let mut window = ContextWindow::new(10000);
let mut region = Region::new("scratch".to_string(), RegionKind::Clearable, 5000);
region
.add_entry("test content 1".to_string(), 1000)
.unwrap();
region
.add_entry("test content 2".to_string(), 1000)
.unwrap();
window.add_region(region);
assert_eq!(window.current_tokens, 2000);
// Evict should clear the entire Clearable region
let result = with_tracing(|| window.try_evict(1000)).unwrap();
assert_eq!(result.tokens_freed, 2000);
assert!(result.needs_compaction.is_empty());
assert_eq!(window.current_tokens, 0);
}
#[test]
fn test_temporary_eviction_oldest_first() {
let mut window = ContextWindow::new(10000);
let mut region = Region::new("temp".to_string(), RegionKind::Temporary, 5000);
region.add_entry("old content".to_string(), 1000).unwrap();
region
.add_entry("middle content".to_string(), 1000)
.unwrap();
region.add_entry("new content".to_string(), 1000).unwrap();
window.add_region(region);
assert_eq!(window.current_tokens, 3000);
// Evict should remove oldest first
let result = with_tracing(|| window.try_evict(500)).unwrap();
assert!(result.tokens_freed >= 1000); // Should free at least one entry
assert!(result.needs_compaction.is_empty());
// Check that oldest was removed
let region = window.get_region("temp").unwrap();
assert_eq!(region.content.len(), 2);
assert_eq!(region.content[0].content, "middle content");
}
fn assert_sliding_window_unreduced(initial_count: usize, after_count: usize) {
assert_eq!(
initial_count, after_count,
"SlidingWindow should never be reduced during eviction"
);
}
#[test]
fn test_sliding_window_never_reduced() {
let mut window = ContextWindow::new(10000);
let mut region = Region::new(
"conversation".to_string(),
RegionKind::SlidingWindow {
max_items: 5,
eviction_strategy: EvictionStrategy::PerItem,
},
5000,
);
region.add_entry("msg 1".to_string(), 1000).unwrap();
region.add_entry("msg 2".to_string(), 1000).unwrap();
region.add_entry("msg 3".to_string(), 1000).unwrap();
window.add_region(region);
let initial_count = window.get_region("conversation").unwrap().content.len();
// Try to evict - should not touch SlidingWindow
window.try_evict(1000).ok();
let after_count = window.get_region("conversation").unwrap().content.len();
assert_sliding_window_unreduced(initial_count, after_count);
}
#[test]
#[should_panic(expected = "SlidingWindow should never be reduced during eviction")]
fn test_sliding_window_never_reduced_panics_on_mismatch() {
assert_sliding_window_unreduced(3, 2);
}
fn assert_pinned_unevicted(initial_tokens: usize, after_tokens: usize) {
assert_eq!(
initial_tokens, after_tokens,
"Pinned region should never be evicted"
);
}
#[test]
fn test_pinned_never_touched() {
let mut window = ContextWindow::new(10000);
let mut region = Region::new("architecture".to_string(), RegionKind::Pinned, 3000);
region
.add_entry("architecture diagram".to_string(), 2000)
.unwrap();
window.add_region(region);
let initial_tokens = window.get_region("architecture").unwrap().current_tokens;
// Try to evict - should not touch Pinned
window.try_evict(1000).ok();
let after_tokens = window.get_region("architecture").unwrap().current_tokens;
assert_pinned_unevicted(initial_tokens, after_tokens);
}
#[test]
#[should_panic(expected = "Pinned region should never be evicted")]
fn test_pinned_never_touched_panics_on_mismatch() {
assert_pinned_unevicted(2000, 1000);
}
#[test]
fn test_eviction_cascade_order() {
let mut window = ContextWindow::new(10000);
// Add Clearable region
let mut clearable = Region::new("scratch".to_string(), RegionKind::Clearable, 2000);
clearable
.add_entry("scratch data".to_string(), 1000)
.unwrap();
window.add_region(clearable);
// Add Temporary region
let mut temporary = Region::new("temp".to_string(), RegionKind::Temporary, 3000);
temporary
.add_entry("temp data 1".to_string(), 1000)
.unwrap();
temporary
.add_entry("temp data 2".to_string(), 1000)
.unwrap();
window.add_region(temporary);
assert_eq!(window.current_tokens, 3000);
// Evict with small target - should clear Clearable first
window.try_evict(500).unwrap();
// Clearable should be empty
assert_eq!(window.get_region("scratch").unwrap().current_tokens, 0);
// Temporary should still have content
assert!(window.get_region("temp").unwrap().current_tokens > 0);
}
#[test]
fn test_message_inbox() {
let mut inbox = MessageInbox::new();
assert!(inbox.messages.is_empty());
inbox.push(AgentMessage {
agent_id: "agent-1".to_string(),
content: "hello".to_string(),
target_region: None,
priority: 0,
});
assert_eq!(inbox.messages.len(), 1);
let drained = inbox.drain_all();
assert_eq!(drained.len(), 1);
assert!(inbox.messages.is_empty());
}
#[test]
fn test_message_inbox_priority_ordering() {
let mut inbox = MessageInbox::new();
inbox.push(AgentMessage {
agent_id: "a".to_string(),
content: "low".to_string(),
target_region: None,
priority: 1,
});
inbox.push(AgentMessage {
agent_id: "a".to_string(),
content: "high".to_string(),
target_region: None,
priority: 10,
});
inbox.push(AgentMessage {
agent_id: "a".to_string(),
content: "medium".to_string(),
target_region: None,
priority: 5,
});
let msgs = inbox.drain_all();
assert_eq!(msgs[0].content, "high");
assert_eq!(msgs[1].content, "medium");
assert_eq!(msgs[2].content, "low");
}
#[test]
fn test_eviction_result_identifies_compaction_regions() {
// Small window so compacting region fills most of it
let mut window = ContextWindow::new(1000);
// Add a compacting region that's over threshold
let mut compacting = Region::new(
"impl".to_string(),
RegionKind::Compacting {
threshold_tokens: 500,
},
900,
);
compacting
.add_entry("lots of content".to_string(), 600)
.unwrap();
window.add_region(compacting);
assert_eq!(window.current_tokens, 600);
// Request 500 free tokens - only 400 free, can't free clearable/temporary, so compacting should be identified
let result = window.try_evict(500).unwrap();
assert_eq!(result.tokens_freed, 0);
assert_eq!(result.needs_compaction, vec!["impl".to_string()]);
}
#[test]
fn test_try_evict_returns_needs_compaction_when_full() {
let mut window = ContextWindow::new(1200);
// Fill with compacting region content above threshold
let mut compacting = Region::new(
"analysis".to_string(),
RegionKind::Compacting {
threshold_tokens: 800,
},
1100,
);
compacting.add_entry("data 1".to_string(), 500).unwrap();
compacting.add_entry("data 2".to_string(), 500).unwrap();
window.add_region(compacting);
// 200 free tokens, request 500 → needs compaction
let result = window.try_evict(500).unwrap();
assert_eq!(result.tokens_freed, 0);
assert!(result.needs_compaction.contains(&"analysis".to_string()));
}
#[test]
fn test_try_evict_errors_when_pinned_regions_exceed_budget() {
// Pinned/CompactHistory regions are never evicted - if their combined
// token usage alone exceeds max_tokens, try_evict must report this as
// a configuration error instead of silently doing nothing useful.
let mut window = ContextWindow::new(1000);
let mut pinned = Region::new("architecture".to_string(), RegionKind::Pinned, 2000);
pinned
.add_entry("huge pinned doc".to_string(), 1500)
.unwrap();
window.add_region(pinned);
let result = window.try_evict(100);
assert!(result.is_err());
let err_str = result.unwrap_err().to_string();
assert!(err_str.contains("Pinned regions"));
}
#[test]
fn test_clearable_eviction_continues_past_insufficient_first_region() {
// Phase 1 clears Clearable regions one at a time and returns early as
// soon as enough space has been freed. If clearing the *first*
// Clearable region alone isn't enough, the loop must fall through and
// keep clearing subsequent Clearable regions rather than stopping.
let mut window = ContextWindow::new(2000);
let mut region_a = Region::new("a".to_string(), RegionKind::Clearable, 1000);
region_a.add_entry("small".to_string(), 500).unwrap();
window.add_region(region_a);
let mut region_b = Region::new("b".to_string(), RegionKind::Clearable, 1000);
region_b.add_entry("large".to_string(), 1000).unwrap();
window.add_region(region_b);
assert_eq!(window.current_tokens, 1500);
// After clearing only "a" (frees 500), 2000 - 1000 = 1000 free tokens,
// which is still below the 1400 target, so the loop must continue on
// to clear "b" as well before it can satisfy the request.
let result = with_tracing(|| window.try_evict(1400)).unwrap();
assert_eq!(result.tokens_freed, 1500);
assert_eq!(window.current_tokens, 0);
assert_eq!(window.get_region("a").unwrap().current_tokens, 0);
assert_eq!(window.get_region("b").unwrap().current_tokens, 0);
}
#[test]
fn test_agent_status_cancelled() {
assert_eq!(AgentStatus::Cancelled, AgentStatus::Cancelled);
}
#[test]
fn test_parent_ref_component() {
let parent_ref = super::ParentRef {
parent_entity: Entity::from_raw_u32(42)
.expect("a small literal index is always a valid entity id"),
parent_agent_id: "coder-01".to_string(),
depth: 1,
};
assert_eq!(parent_ref.parent_agent_id, "coder-01");
assert_eq!(parent_ref.depth, 1);
}
#[test]
fn test_children_component() {
let children = super::SubAgentChildren {
children: vec![
Entity::from_raw_u32(1).expect("a small literal index is always a valid entity id"),
Entity::from_raw_u32(2).expect("a small literal index is always a valid entity id"),
],
max_child_depth: 3,
};
assert_eq!(children.children.len(), 2);
assert_eq!(children.max_child_depth, 3);
}
#[test]
fn test_agent_state_with_children_fields() {
let state = AgentState {
agent_id: "test-01".to_string(),
current_stage: "analyze".to_string(),
iteration: 0,
status: AgentStatus::Active,
spawned_children_ids: vec!["child-01".to_string(), "child-02".to_string()],
pending_wait: Some("child-01".to_string()),
accepts_messages: true,
};
assert_eq!(state.spawned_children_ids.len(), 2);
assert_eq!(state.pending_wait, Some("child-01".to_string()));
}
// ── Additional coverage tests ──────────────────────────────────────────
#[test]
fn test_context_window_get_region() {
let mut window = ContextWindow::new(10000);
let region = Region::new("test".to_string(), RegionKind::Pinned, 1000);
window.add_region(region);
assert!(window.get_region("test").is_some());
assert!(window.get_region("nonexistent").is_none());
}
#[test]
fn test_context_window_get_region_mut() {
let mut window = ContextWindow::new(10000);
let region = Region::new("test".to_string(), RegionKind::Temporary, 1000);
window.add_region(region);
let region = window.get_region_mut("test").unwrap();
region.add_entry("new content".to_string(), 50).unwrap();
assert_eq!(region.content.len(), 1);
assert!(window.get_region_mut("nonexistent").is_none());
}
#[test]
fn test_context_window_add_to_region_success() {
let mut window = ContextWindow::new(10000);
let region = Region::new("conv".to_string(), RegionKind::Temporary, 5000);
window.add_region(region);
let result = window.add_to_region("conv", "Hello".to_string(), 10);
assert!(result.is_ok());
assert_eq!(window.current_tokens, 10);
}
#[test]
fn test_context_window_add_to_region_not_found() {
let mut window = ContextWindow::new(10000);
let result = window.add_to_region("nonexistent", "Hello".to_string(), 10);
assert!(result.is_err());
}
#[test]
fn test_context_window_calculate_tokens() {
let mut window = ContextWindow::new(10000);
let mut r1 = Region::new("a".to_string(), RegionKind::Pinned, 5000);
r1.add_entry("x".to_string(), 100).unwrap();
let mut r2 = Region::new("b".to_string(), RegionKind::Temporary, 5000);
r2.add_entry("y".to_string(), 200).unwrap();
window.add_region(r1);
window.add_region(r2);
assert_eq!(window.calculate_tokens(), 300);
}
#[test]
fn test_context_window_needs_eviction_boundary() {
let mut window = ContextWindow::new(100);
// Exactly 90% → should trigger at 0.9 threshold
window.current_tokens = 90;
assert!(window.needs_eviction(0.9));
// Just below 90%
window.current_tokens = 89;
assert!(!window.needs_eviction(0.9));
}
#[test]
fn test_eviction_result_default_fields() {
let result = EvictionResult {
tokens_freed: 0,
needs_compaction: Vec::new(),
};
assert_eq!(result.tokens_freed, 0);
assert!(result.needs_compaction.is_empty());
}
#[test]
fn test_message_inbox_default() {
let inbox = MessageInbox::default();
assert!(inbox.messages.is_empty());
}
#[test]
fn test_message_inbox_drain_all_empties() {
let mut inbox = MessageInbox::new();
inbox.push(AgentMessage {
agent_id: "a".to_string(),
content: "msg".to_string(),
target_region: None,
priority: 0,
});
let _ = inbox.drain_all();
assert!(inbox.messages.is_empty());
// Drain again should return empty vec
let result = inbox.drain_all();
assert!(result.is_empty());
}
#[test]
fn test_agent_message_clone() {
let msg = AgentMessage {
agent_id: "agent-1".to_string(),
content: "hello".to_string(),
target_region: Some("conv".to_string()),
priority: 5,
};
let cloned = msg.clone();
assert_eq!(cloned.agent_id, "agent-1");
assert_eq!(cloned.content, "hello");
assert_eq!(cloned.target_region, Some("conv".to_string()));
assert_eq!(cloned.priority, 5);
}
#[test]
fn test_agent_status_serialization() {
let status = AgentStatus::Active;
let json = serde_json::to_string(&status).unwrap();
assert!(json.contains("Active"));
let error_status = AgentStatus::Error {
message: "boom".to_string(),
};
let json = serde_json::to_string(&error_status).unwrap();
assert!(json.contains("boom"));
}
#[test]
fn test_tool_call_serialization() {
let tc = ToolCall {
tool_id: "tool-1".to_string(),
name: "search".to_string(),
arguments: serde_json::json!({"query": "rust"}),
thought_signature: None,
};
let json = serde_json::to_string(&tc).unwrap();
assert!(json.contains("search"));
assert!(json.contains("rust"));
}
#[test]
fn test_eviction_with_only_pinned_region_frees_nothing() {
// When the only region is Pinned (within budget), eviction frees nothing.
let mut window = ContextWindow::new(10000);
let mut pinned = Region::new("pinned".to_string(), RegionKind::Pinned, 5000);
pinned
.add_entry("important data".to_string(), 2000)
.unwrap();
window.add_region(pinned);
let result = with_tracing(|| window.try_evict(500)).unwrap();
assert_eq!(result.tokens_freed, 0);
assert!(result.needs_compaction.is_empty());
}
#[test]
fn test_inference_result_fields() {
let ir = InferenceResult {
response: "Hello".to_string(),
tool_calls: vec![ToolCall {
tool_id: "t1".to_string(),
name: "search".to_string(),
arguments: serde_json::json!({}),
thought_signature: None,
}],
tokens_used: 100,
timestamp: 99999,
};
assert_eq!(ir.response, "Hello");
assert_eq!(ir.tool_calls.len(), 1);
assert_eq!(ir.tokens_used, 100);
}
#[test]
fn test_sub_agent_children_clone() {
let children = SubAgentChildren {
children: vec![
Entity::from_raw_u32(1).expect("a small literal index is always a valid entity id"),
],
max_child_depth: 2,
};
let cloned = children.clone();
assert_eq!(cloned.children.len(), 1);
assert_eq!(cloned.max_child_depth, 2);
}
// ─── try_evict: FALSE path after each single-entry removal ────────────
// Covers 235:25 (false path of the early-return check) and 242:13 (break).
//
// Setup: max=1000, current=950, target=200.
// Two Temporary entries of 50 tokens each.
//
// Pass 1: remove entry1 (50 tokens) → current=900, available=100 < 200
// → condition FALSE → line 235 covered → outer loop continues
// Pass 2: remove entry2 (50 tokens) → current=850, available=150 < 200
// → condition FALSE → line 235 covered again
// Pass 3: no more entries → evicted_any=false → break → line 242 covered
#[test]
fn try_evict_continues_loop_when_each_entry_removal_is_insufficient() {
let mut window = ContextWindow::new(1000);
let mut temp = Region::new("cache".to_string(), RegionKind::Temporary, 800);
temp.add_entry("entry1".to_string(), 50).unwrap();
temp.add_entry("entry2".to_string(), 50).unwrap();
window.add_region(temp);
window.current_tokens = 950; // 95% full
// Target=200: removing 50 at a time is insufficient each pass
let result = window.try_evict(200).unwrap();
assert_eq!(result.tokens_freed, 100); // freed 50+50, but not enough for target
}
// ─── Context window taint tracking ──────────────────────────────────────
#[test]
fn test_enable_taint_tracking_on_context_window() {
let mut window = ContextWindow::new(10000);
window.add_region(Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 10,
eviction_strategy: EvictionStrategy::PerItem,
},
5000,
));
window.add_region(Region::new(
"tools".to_string(),
RegionKind::Temporary,
3000,
));
assert!(window.overall_taint().is_none());
window.enable_taint_tracking();
assert_eq!(
window.overall_taint(),
Some(leviath_core::TaintLevel::Public)
);
}
#[test]
fn test_add_tainted_to_region() {
let mut window = ContextWindow::new(10000);
let region =
Region::new("tools".to_string(), RegionKind::Temporary, 5000).with_taint_tracking();
window.add_region(region);
window
.add_tainted_to_region(
"tools",
"secret data".to_string(),
10,
leviath_core::TaintLevel::Private,
)
.unwrap();
assert_eq!(
window.get_region("tools").and_then(|r| r.taint_level()),
Some(leviath_core::TaintLevel::Private)
);
assert_eq!(
window.overall_taint(),
Some(leviath_core::TaintLevel::Private)
);
}
#[test]
fn test_add_tainted_to_nonexistent_region() {
let mut window = ContextWindow::new(10000);
let result = window.add_tainted_to_region(
"nope",
"data".to_string(),
10,
leviath_core::TaintLevel::Public,
);
assert!(result.is_err());
}
#[test]
fn test_overall_taint_is_max_across_regions() {
let mut window = ContextWindow::new(10000);
let r1 = Region::new("a".to_string(), RegionKind::Temporary, 5000).with_taint_tracking();
let r2 = Region::new("b".to_string(), RegionKind::Temporary, 5000).with_taint_tracking();
window.add_region(r1);
window.add_region(r2);
window
.add_tainted_to_region("a", "x".to_string(), 5, leviath_core::TaintLevel::Internal)
.unwrap();
window
.add_tainted_to_region("b", "y".to_string(), 5, leviath_core::TaintLevel::Public)
.unwrap();
assert_eq!(
window.overall_taint(),
Some(leviath_core::TaintLevel::Internal)
);
}
#[test]
fn test_taint_summary() {
let mut window = ContextWindow::new(10000);
let r1 = Region::new("conv".to_string(), RegionKind::Temporary, 5000).with_taint_tracking();
let r2 =
Region::new("tools".to_string(), RegionKind::Temporary, 5000).with_taint_tracking();
window.add_region(r1);
window.add_region(r2);
window
.add_tainted_to_region(
"conv",
"x".to_string(),
5,
leviath_core::TaintLevel::Private,
)
.unwrap();
let summary = window.taint_summary();
assert_eq!(summary.len(), 2);
assert!(
summary
.iter()
.any(|(name, level)| name == "conv" && *level == leviath_core::TaintLevel::Private)
);
assert!(
summary
.iter()
.any(|(name, level)| name == "tools" && *level == leviath_core::TaintLevel::Public)
);
}
#[test]
fn test_taint_recovery_through_eviction() {
with_tracing(|| {});
let mut window = ContextWindow::new(100);
let r = Region::new("temp".to_string(), RegionKind::Temporary, 100).with_taint_tracking();
window.add_region(r);
window
.add_tainted_to_region(
"temp",
"private".to_string(),
30,
leviath_core::TaintLevel::Private,
)
.unwrap();
window
.add_tainted_to_region(
"temp",
"public".to_string(),
30,
leviath_core::TaintLevel::Public,
)
.unwrap();
assert_eq!(
window.get_region("temp").and_then(|r| r.taint_level()),
Some(leviath_core::TaintLevel::Private)
);
// Eviction should trigger and remove oldest (private) entry
window.current_tokens = 96; // Push over 0.95 threshold
let result = window.try_evict(10).unwrap();
assert!(result.tokens_freed > 0);
// After evicting the private entry, taint should recover
assert_eq!(
window.get_region("temp").and_then(|r| r.taint_level()),
Some(leviath_core::TaintLevel::Public)
);
}
// ─── Tool-use/tool-result pairing sanitization tests ────────────────
#[test]
fn test_assemble_appends_user_nudge_when_conversation_ends_with_assistant() {
// After a stage transition the carried conversation ends with the prior
// stage's assistant turn; assemble must append a trailing user message so
// the request doesn't end on an assistant turn (rejected as prefill).
let mut window = ContextWindow::new(100_000);
window.add_region(Region::new(
"conversation".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
));
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::UserMessage,
"do the task".to_string(),
10,
)
.unwrap();
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::AssistantTurn { tool_calls: vec![] },
"All done with stage one.".to_string(),
10,
)
.unwrap();
let assembled = window.assemble();
assert_eq!(
assembled.messages.last().map(|m| m.role.as_str()),
Some("user"),
"the assembled conversation must end with a user message"
);
}
#[test]
fn test_assemble_strips_orphaned_tool_use() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conversation".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// Add an assistant turn with a tool_use but no matching tool_result
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::AssistantTurn {
tool_calls: vec![leviath_core::SerializedToolCall {
id: "tc_orphan".to_string(),
name: "read_file".to_string(),
arguments: serde_json::json!({"path": "foo.rs"}),
thought_signature: None,
}],
},
"Let me read that file.".to_string(),
50,
)
.unwrap();
let assembled = with_tracing(|| window.assemble());
// The orphaned tool_use should be stripped; text should remain
for msg in &assembled.messages {
if let leviath_providers::MessageContent::Blocks(blocks) = &msg.content {
for block in blocks {
assert!(
!matches!(block, leviath_providers::ContentBlock::ToolUse { .. }),
"Orphaned tool_use should have been stripped"
);
}
}
}
// The assistant text should still be present
assert!(
assembled
.messages
.iter()
.any(|m| m.role == "assistant" && m.content.as_text().contains("read that file"))
);
}
#[test]
fn test_assemble_strips_orphaned_tool_result() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conversation".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// Add a user message first
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::UserMessage,
"Hello".to_string(),
10,
)
.unwrap();
// Add a tool_result with no preceding tool_use
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::ToolResult {
tool_call_id: "tc_missing".to_string(),
tool_name: "read_file".to_string(),
is_error: false,
},
"file contents here".to_string(),
20,
)
.unwrap();
let assembled = with_tracing(|| window.assemble());
// The orphaned tool_result message is stripped to empty and dropped;
// only the plain user message survives (as Text, carrying no blocks).
assert_eq!(assembled.messages.len(), 1);
assert_eq!(assembled.messages[0].role, "user");
assert_eq!(
assembled.messages[0].content,
leviath_providers::MessageContent::Text("Hello".to_string())
);
}
#[test]
fn test_assemble_paired_tool_use_result_passes_through() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conversation".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// User message
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::UserMessage,
"Fix the bug".to_string(),
10,
)
.unwrap();
// Assistant with tool_use
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::AssistantTurn {
tool_calls: vec![leviath_core::SerializedToolCall {
id: "tc_1".to_string(),
name: "read_file".to_string(),
arguments: serde_json::json!({"path": "main.rs"}),
thought_signature: None,
}],
},
"".to_string(),
10,
)
.unwrap();
// Matching tool_result
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::ToolResult {
tool_call_id: "tc_1".to_string(),
tool_name: "read_file".to_string(),
is_error: false,
},
"fn main() {}".to_string(),
10,
)
.unwrap();
let assembled = window.assemble();
// Both tool_use and tool_result should be present
let has_tool_use = assembled.messages.iter().any(|m| {
if let leviath_providers::MessageContent::Blocks(blocks) = &m.content {
blocks
.iter()
.any(|b| matches!(b, leviath_providers::ContentBlock::ToolUse { id, .. } if id == "tc_1"))
} else {
false
}
});
let has_tool_result = assembled.messages.iter().any(|m| {
if let leviath_providers::MessageContent::Blocks(blocks) = &m.content {
blocks
.iter()
.any(|b| matches!(b, leviath_providers::ContentBlock::ToolResult { tool_use_id, .. } if tool_use_id == "tc_1"))
} else {
false
}
});
assert!(has_tool_use, "Paired tool_use should remain");
assert!(has_tool_result, "Paired tool_result should remain");
}
#[test]
fn test_assemble_removes_empty_assistant_after_stripping() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conversation".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// User message
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::UserMessage,
"Do something".to_string(),
10,
)
.unwrap();
// Assistant with ONLY a tool_use (no text), and no matching result
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::AssistantTurn {
tool_calls: vec![leviath_core::SerializedToolCall {
id: "tc_gone".to_string(),
name: "bash".to_string(),
arguments: serde_json::json!({"command": "ls"}),
thought_signature: None,
}],
},
"".to_string(),
10,
)
.unwrap();
let assembled = with_tracing(|| window.assemble());
// The assistant message should be entirely removed (empty after stripping)
let assistant_msgs: Vec<_> = assembled
.messages
.iter()
.filter(|m| m.role == "assistant")
.collect();
assert!(
assistant_msgs.is_empty(),
"Assistant message with only orphaned tool_use should be removed entirely"
);
}
#[test]
fn test_assemble_strips_multiple_orphaned_tool_uses_in_one_message() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conversation".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// User message first
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::UserMessage,
"Do two things".to_string(),
10,
)
.unwrap();
// Assistant with TWO orphaned tool_uses (no matching results for either)
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::AssistantTurn {
tool_calls: vec![
leviath_core::SerializedToolCall {
id: "tc_orphan_1".to_string(),
name: "read_file".to_string(),
arguments: serde_json::json!({"path": "a.rs"}),
thought_signature: None,
},
leviath_core::SerializedToolCall {
id: "tc_orphan_2".to_string(),
name: "bash".to_string(),
arguments: serde_json::json!({"cmd": "ls"}),
thought_signature: None,
},
],
},
"Let me do both.".to_string(),
50,
)
.unwrap();
let assembled = with_tracing(|| window.assemble());
// Both orphaned tool_uses should be stripped
for msg in &assembled.messages {
if let leviath_providers::MessageContent::Blocks(blocks) = &msg.content {
for block in blocks {
assert!(
!matches!(block, leviath_providers::ContentBlock::ToolUse { .. }),
"All orphaned tool_uses should have been stripped"
);
}
}
}
// The assistant text should still be present
assert!(
assembled
.messages
.iter()
.any(|m| m.role == "assistant" && m.content.as_text().contains("do both"))
);
}
#[test]
fn test_assemble_mixed_valid_and_orphaned_in_same_message() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conversation".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// User message
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::UserMessage,
"Do stuff".to_string(),
10,
)
.unwrap();
// Assistant with one valid tool_use (tc_valid) and one orphaned (tc_orphan)
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::AssistantTurn {
tool_calls: vec![
leviath_core::SerializedToolCall {
id: "tc_valid".to_string(),
name: "read_file".to_string(),
arguments: serde_json::json!({"path": "main.rs"}),
thought_signature: None,
},
leviath_core::SerializedToolCall {
id: "tc_orphan".to_string(),
name: "bash".to_string(),
arguments: serde_json::json!({"cmd": "ls"}),
thought_signature: None,
},
],
},
"".to_string(),
10,
)
.unwrap();
// Only provide tool_result for tc_valid
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::ToolResult {
tool_call_id: "tc_valid".to_string(),
tool_name: "read_file".to_string(),
is_error: false,
},
"fn main() {}".to_string(),
10,
)
.unwrap();
let assembled = with_tracing(|| window.assemble());
// Collect the tool_use ids that survived assembly.
let tool_use_ids: Vec<&str> = assembled
.messages
.iter()
.filter_map(|m| match &m.content {
leviath_providers::MessageContent::Blocks(blocks) => Some(blocks),
_ => None,
})
.flatten()
.filter_map(|b| match b {
leviath_providers::ContentBlock::ToolUse { id, .. } => Some(id.as_str()),
_ => None,
})
.collect();
// tc_valid's tool_use remains; the orphaned tc_orphan is stripped.
assert!(
tool_use_ids.contains(&"tc_valid"),
"Valid tool_use should remain"
);
assert!(
!tool_use_ids.contains(&"tc_orphan"),
"Orphaned tool_use should be stripped"
);
// tc_valid tool_result should remain
let has_result = assembled.messages.iter().any(|m| {
if let leviath_providers::MessageContent::Blocks(blocks) = &m.content {
blocks.iter().any(|b| {
matches!(b, leviath_providers::ContentBlock::ToolResult { tool_use_id, .. } if tool_use_id == "tc_valid")
})
} else {
false
}
});
assert!(has_result, "Valid tool_result should remain");
}
// ─── assemble() region kind coverage ──────────────────────────────────
#[test]
fn test_assemble_compact_history_region_produces_system_block_always() {
let mut window = ContextWindow::new(100_000);
let mut region = Region::new(
"history".to_string(),
RegionKind::CompactHistory {
source_region: "conv".to_string(),
},
10_000,
);
region
.add_entry("summary of earlier conversation".to_string(), 50)
.unwrap();
window.add_region(region);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 1);
assert_eq!(
assembled.system_blocks[0].text,
"summary of earlier conversation"
);
assert_eq!(
assembled.system_blocks[0].cache_hint,
leviath_core::CacheHint::Always
);
}
#[test]
fn test_assemble_compacting_region_produces_system_block_until_changed() {
let mut window = ContextWindow::new(100_000);
let mut region = Region::new(
"impl".to_string(),
RegionKind::Compacting {
threshold_tokens: 500,
},
10_000,
);
region
.add_entry("implementation details".to_string(), 50)
.unwrap();
window.add_region(region);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 1);
assert_eq!(
assembled.system_blocks[0].text,
"[impl]:\nimplementation details"
);
assert_eq!(
assembled.system_blocks[0].cache_hint,
leviath_core::CacheHint::UntilChanged
);
}
#[test]
fn test_assemble_temporary_region_produces_system_block_never() {
let mut window = ContextWindow::new(100_000);
let mut region = Region::new("scratch".to_string(), RegionKind::Temporary, 10_000);
region.add_entry("temp data".to_string(), 20).unwrap();
window.add_region(region);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 1);
assert_eq!(assembled.system_blocks[0].text, "[scratch]:\ntemp data");
assert_eq!(
assembled.system_blocks[0].cache_hint,
leviath_core::CacheHint::Never
);
}
#[test]
fn test_assemble_clearable_region_produces_system_block_never() {
let mut window = ContextWindow::new(100_000);
let mut region = Region::new("cache".to_string(), RegionKind::Clearable, 10_000);
region.add_entry("clearable data".to_string(), 20).unwrap();
window.add_region(region);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 1);
assert_eq!(assembled.system_blocks[0].text, "[cache]:\nclearable data");
assert_eq!(
assembled.system_blocks[0].cache_hint,
leviath_core::CacheHint::Never
);
}
fn custom_kind(script: &str, persistent: bool) -> RegionKind {
RegionKind::Custom {
script: script.to_string(),
persistent,
}
}
#[test]
fn test_assemble_custom_region_falls_back_to_temporary_style_block() {
// Plain `assemble()` has no compiled script available, so a custom
// region renders as the hook-less fallback: a Temporary-style block -
// never silently dropped.
let mut window = ContextWindow::new(100_000);
let mut region = Region::new("brain".to_string(), custom_kind("b.rhai", false), 10_000);
region.add_entry("thought one".to_string(), 10).unwrap();
region.add_entry("thought two".to_string(), 10).unwrap();
window.add_region(region);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 1);
assert_eq!(
assembled.system_blocks[0].text,
"[brain]:\nthought one\n\nthought two"
);
assert_eq!(
assembled.system_blocks[0].cache_hint,
leviath_core::CacheHint::Never
);
}
#[test]
fn try_evict_evicts_non_persistent_custom_regions_oldest_first() {
let mut window = ContextWindow::new(100);
let mut region = Region::new("brain".to_string(), custom_kind("b.rhai", false), 100);
region.add_entry("old".to_string(), 40).unwrap();
region.add_entry("new".to_string(), 40).unwrap();
window.add_region(region);
window.current_tokens = 80;
let result = with_tracing(|| window.try_evict(30).unwrap());
assert!(result.tokens_freed >= 40);
let brain = window.get_region("brain").unwrap();
assert_eq!(brain.content.len(), 1);
assert_eq!(brain.content[0].content, "new");
}
#[test]
fn try_evict_never_touches_persistent_custom_and_counts_it_as_pinned() {
// Persistent custom content survives eviction, and when it alone
// exceeds the whole window budget the pinned over-budget guard fires.
let mut window = ContextWindow::new(50);
let mut vault = Region::new("vault".to_string(), custom_kind("v.rhai", true), 100);
vault.add_entry("precious".to_string(), 60).unwrap();
window.add_region(vault);
window.current_tokens = 60;
let err = with_tracing(|| window.try_evict(10).unwrap_err());
assert_eq!(
err.to_string(),
"Pinned regions (60) exceed total budget (50)"
);
assert_eq!(window.get_region("vault").unwrap().content.len(), 1);
}
/// A window with one custom region (`brain`, budget 100) backed by `src`,
/// compiled and installed in the script table under "s.rhai".
fn custom_window(src: &str, persistent: bool) -> ContextWindow {
let mut window = ContextWindow::new(10_000);
window.add_region(Region::new(
"brain".to_string(),
RegionKind::Custom {
script: "s.rhai".to_string(),
persistent,
},
100,
));
window.region_scripts.insert(
"s.rhai".to_string(),
std::sync::Arc::new(leviath_scripting::region_hook::compile("s.rhai", src).unwrap()),
);
window
}
#[test]
fn custom_region_on_write_fires_across_all_write_methods() {
let src = r#"
fn render(ctx) { "" }
fn on_write(ctx) { `${ctx.entry.kind}:${ctx.entry.content}` }
"#;
let mut window = custom_window(src, false);
window.add_to_region("brain", "a".to_string(), 1).unwrap();
window
.add_typed_entry(
"brain",
leviath_core::EntryKind::UserMessage,
"b".to_string(),
1,
)
.unwrap();
window
.add_tainted_to_region(
"brain",
"c".to_string(),
1,
leviath_core::TaintLevel::Public,
)
.unwrap();
window
.add_typed_tainted_to_region(
"brain",
leviath_core::EntryKind::UserMessage,
"d".to_string(),
1,
leviath_core::TaintLevel::Public,
)
.unwrap();
let contents: Vec<_> = window
.get_region("brain")
.unwrap()
.content
.iter()
.map(|e| e.content.as_str())
.collect();
assert_eq!(
contents,
vec!["text:a", "user_message:b", "text:c", "user_message:d"],
"every write method passes through on_write with the entry kind visible"
);
// Token counts were re-estimated for the replacements.
assert_eq!(window.current_tokens, window.calculate_tokens());
assert!(window.replace_region("brain", "e".to_string(), 1));
let region = window.get_region("brain").unwrap();
assert_eq!(region.content.len(), 1);
assert_eq!(region.content[0].content, "text:e");
}
#[test]
fn custom_region_on_write_drop_reports_success_without_storing() {
let src = r#"
fn render(ctx) { "" }
fn on_write(ctx) { false }
"#;
let mut window = custom_window(src, false);
window
.add_to_region("brain", "spam".to_string(), 1)
.unwrap();
assert!(window.get_region("brain").unwrap().content.is_empty());
// A dropped replacement leaves existing content in place.
assert!(window.replace_region("brain", "more spam".to_string(), 1));
assert!(window.get_region("brain").unwrap().content.is_empty());
}
#[test]
fn custom_region_on_write_drop_covers_typed_and_tainted_methods() {
// Every write method's drop arm, not just add_to_region's.
let src = r#"
fn render(ctx) { "" }
fn on_write(ctx) { false }
"#;
let mut window = custom_window(src, false);
window
.add_typed_entry(
"brain",
leviath_core::EntryKind::UserMessage,
"a".to_string(),
1,
)
.unwrap();
window
.add_tainted_to_region(
"brain",
"b".to_string(),
1,
leviath_core::TaintLevel::Public,
)
.unwrap();
window
.add_typed_tainted_to_region(
"brain",
leviath_core::EntryKind::UserMessage,
"c".to_string(),
1,
leviath_core::TaintLevel::Public,
)
.unwrap();
assert!(window.get_region("brain").unwrap().content.is_empty());
}
#[test]
fn try_evict_skips_custom_region_whose_script_has_no_on_overflow() {
// Phase 1.5 leaves the choice to phase 2 (oldest-first) when the
// script defines no on_overflow.
let mut window = ContextWindow::new(100);
window.add_region(Region::new(
"brain".to_string(),
RegionKind::Custom {
script: "s.rhai".to_string(),
persistent: false,
},
100,
));
window.region_scripts.insert(
"s.rhai".to_string(),
std::sync::Arc::new(
leviath_scripting::region_hook::compile("s.rhai", "fn render(ctx) { \"\" }")
.unwrap(),
),
);
window
.add_to_region("brain", "old".to_string(), 40)
.unwrap();
window
.add_to_region("brain", "new".to_string(), 40)
.unwrap();
let result = with_tracing(|| window.try_evict(30).unwrap());
assert!(result.tokens_freed >= 40);
let brain = window.get_region("brain").unwrap();
assert_eq!(brain.content.len(), 1);
assert_eq!(brain.content[0].content, "new", "oldest-first fallback ran");
}
#[test]
fn try_evict_falls_to_oldest_first_when_script_frees_nothing() {
// on_overflow returns [] under pressure: phase 1.5 frees 0 and phase 2
// makes the progress.
let src = r#"
fn render(ctx) { "" }
fn on_overflow(ctx) { [] }
"#;
let mut window = ContextWindow::new(100);
window.add_region(Region::new(
"brain".to_string(),
RegionKind::Custom {
script: "s.rhai".to_string(),
persistent: false,
},
100,
));
window.region_scripts.insert(
"s.rhai".to_string(),
std::sync::Arc::new(leviath_scripting::region_hook::compile("s.rhai", src).unwrap()),
);
window
.add_to_region("brain", "old".to_string(), 40)
.unwrap();
window
.add_to_region("brain", "new".to_string(), 40)
.unwrap();
let result = with_tracing(|| window.try_evict(30).unwrap());
assert!(result.tokens_freed >= 40);
assert_eq!(window.get_region("brain").unwrap().content.len(), 1);
}
#[test]
fn non_custom_regions_bypass_the_on_write_seam() {
// A script table entry exists, but the region is plain Temporary - the
// hook must not fire for it.
let mut window = custom_window(
"fn render(ctx) { \"\" }\nfn on_write(ctx) { \"MANGLED\" }",
false,
);
window.add_region(Region::new("plain".to_string(), RegionKind::Temporary, 100));
window
.add_to_region("plain", "untouched".to_string(), 2)
.unwrap();
assert_eq!(
window.get_region("plain").unwrap().content[0].content,
"untouched"
);
}
#[test]
fn write_to_missing_region_still_errors() {
let mut window = custom_window("fn render(ctx) { \"\" }", false);
let err = window
.add_to_region("ghost", "x".to_string(), 1)
.unwrap_err();
assert!(err.to_string().contains("ghost"), "{err}");
}
#[test]
fn custom_region_add_time_overflow_retries_after_script_drops() {
// Region budget 100: fill with 90, then add 20 - over budget. The
// script drops entry 0 (90 tokens), freeing room; the retry succeeds.
let src = r#"
fn render(ctx) { "" }
fn on_overflow(ctx) { [0] }
"#;
let mut window = custom_window(src, false);
window
.add_to_region("brain", "big".to_string(), 90)
.unwrap();
window
.add_to_region("brain", "next".to_string(), 20)
.unwrap();
let region = window.get_region("brain").unwrap();
assert_eq!(region.content.len(), 1);
assert_eq!(region.content[0].content, "next");
assert_eq!(window.current_tokens, 20);
}
#[test]
fn custom_region_add_time_overflow_propagates_when_still_too_big() {
// The script frees nothing, so the retry path never runs and the
// original budget error propagates to the caller's ladders.
let src = r#"
fn render(ctx) { "" }
fn on_overflow(ctx) { [] }
"#;
let mut window = custom_window(src, false);
window
.add_to_region("brain", "big".to_string(), 90)
.unwrap();
let err =
with_tracing(|| window.add_to_region("brain", "too much".to_string(), 50)).unwrap_err();
assert_eq!(err.to_string(), "Content exceeds token budget: 140 > 100");
assert_eq!(window.get_region("brain").unwrap().content.len(), 1);
}
#[test]
fn custom_region_without_on_overflow_gets_no_retry() {
let mut window = custom_window("fn render(ctx) { \"\" }", false);
window
.add_to_region("brain", "big".to_string(), 90)
.unwrap();
let err = window
.add_to_region("brain", "too much".to_string(), 50)
.unwrap_err();
assert_eq!(err.to_string(), "Content exceeds token budget: 140 > 100");
}
#[test]
fn try_evict_lets_custom_script_choose_what_to_drop() {
// The script keeps errors, drops successes - the retention choice the
// oldest-first cascade could never make. Window is small so eviction
// has real pressure.
let src = r#"
fn render(ctx) { "" }
fn on_overflow(ctx) {
let drops = [];
for (entry, i) in ctx.entries {
if !entry.content.contains("ERROR") { drops.push(i); }
}
drops
}
"#;
let mut window = ContextWindow::new(100);
window.add_region(Region::new(
"brain".to_string(),
RegionKind::Custom {
script: "s.rhai".to_string(),
persistent: false,
},
100,
));
window.region_scripts.insert(
"s.rhai".to_string(),
std::sync::Arc::new(leviath_scripting::region_hook::compile("s.rhai", src).unwrap()),
);
window
.add_to_region("brain", "ok one".to_string(), 30)
.unwrap();
window
.add_to_region("brain", "ERROR two".to_string(), 30)
.unwrap();
window
.add_to_region("brain", "ok three".to_string(), 30)
.unwrap();
let result = with_tracing(|| window.try_evict(40)).unwrap();
assert!(result.tokens_freed >= 40);
let contents: Vec<_> = window
.get_region("brain")
.unwrap()
.content
.iter()
.map(|e| e.content.as_str())
.collect();
assert_eq!(
contents,
vec!["ERROR two"],
"script retention choice honored"
);
}
// ─── assemble(): custom regions ──────────────────────────────────────
#[test]
fn assemble_custom_region_renders_through_script() {
let src = r#"fn render(ctx) { `<brain iter=${ctx.stage_iterations}>` }"#;
let mut window = custom_window(src, false);
window
.add_to_region("brain", "note".to_string(), 2)
.unwrap();
// Default meta via plain assemble().
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 1);
assert_eq!(assembled.system_blocks[0].text, "<brain iter=0>");
assert_eq!(
assembled.system_blocks[0].cache_hint,
leviath_core::CacheHint::UntilChanged
);
// Real meta via assemble_with_meta.
let assembled = window.assemble_with_meta(&crate::custom_region::AssembleMeta {
stage_name: "plan".to_string(),
stage_iterations: 7,
model: "m".to_string(),
});
assert_eq!(assembled.system_blocks[0].text, "<brain iter=7>");
}
#[test]
fn assemble_custom_region_renders_even_when_empty() {
// Static scaffolding: the script emits structure with no entries.
let src = r#"fn render(ctx) { `<empty count=${ctx.entries.len()}>` }"#;
let window = custom_window(src, false);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 1);
assert_eq!(assembled.system_blocks[0].text, "<empty count=0>");
}
#[test]
fn assemble_custom_conversation_takeover_renders_single_user_message() {
// The 12-factor case: a custom region NAMED conversation holds the
// typed history and renders it as one XML user message. No sliding
// window exists; the request's only message is the script's.
let src = r#"
fn render(ctx) {
let xml = "<context>";
for entry in ctx.entries {
xml += `<event kind="${entry.kind}">${entry.content}</event>`;
}
xml += "</context>";
#{ messages: [ #{ role: "user", content: xml } ] }
}
"#;
let mut window = ContextWindow::new(10_000);
window.add_region(Region::new(
"conversation".to_string(),
RegionKind::Custom {
script: "conv.rhai".to_string(),
persistent: false,
},
5_000,
));
window.region_scripts.insert(
"conv.rhai".to_string(),
std::sync::Arc::new(leviath_scripting::region_hook::compile("conv.rhai", src).unwrap()),
);
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::UserMessage,
"do the task".to_string(),
4,
)
.unwrap();
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::ToolResult {
tool_call_id: "c1".to_string(),
tool_name: "shell".to_string(),
is_error: false,
},
"output".to_string(),
2,
)
.unwrap();
let assembled = window.assemble();
assert!(assembled.system_blocks.is_empty());
assert_eq!(assembled.messages.len(), 1);
assert_eq!(assembled.messages[0].role, "user");
assert_eq!(
assembled.messages[0].content.as_text(),
"<context><event kind=\"user_message\">do the task</event>\
<event kind=\"tool_result\">output</event></context>"
);
}
#[test]
fn assemble_custom_script_emitting_nothing_gets_begin_fallback() {
// A script that emits no messages leaves the request message-less;
// the shared finalization injects the "Begin." user message.
let window = custom_window("fn render(ctx) { \"\" }", false);
let assembled = window.assemble();
assert!(assembled.system_blocks.is_empty());
assert_eq!(assembled.messages.len(), 1);
assert_eq!(assembled.messages[0].content.as_text(), "Begin.");
}
#[test]
fn assemble_custom_unpaired_tool_blocks_are_sanitized() {
// A buggy script emits a tool_result with no matching tool_use; the
// orphan sanitizer strips it instead of sending a provider-invalid
// request.
let src = r#"
fn render(ctx) {
#{ messages: [
#{ role: "user", content: "hello" },
#{ role: "user", tool_results: [
#{ tool_call_id: "ghost", content: "orphan" },
] },
] }
}
"#;
let window = custom_window(src, false);
let assembled = window.assemble();
assert_eq!(assembled.messages.len(), 1, "orphan tool_result stripped");
assert_eq!(assembled.messages[0].content.as_text(), "hello");
}
// ─── assemble() EntryKind::Text prefix parsing ────────────────────────
#[test]
fn test_assemble_text_entry_with_assistant_prefix() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::Text,
"Assistant: I can help with that.".to_string(),
10,
)
.unwrap();
let assembled = window.assemble();
let assistant_msgs: Vec<_> = assembled
.messages
.iter()
.filter(|m| m.role == "assistant")
.collect();
assert_eq!(assistant_msgs.len(), 1);
assert_eq!(assistant_msgs[0].content.as_text(), "I can help with that.");
}
#[test]
fn test_assemble_text_entry_with_user_prefix() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::Text,
"User: What is Rust?".to_string(),
10,
)
.unwrap();
let assembled = window.assemble();
let user_msgs: Vec<_> = assembled
.messages
.iter()
.filter(|m| m.role == "user")
.collect();
assert_eq!(user_msgs.len(), 1);
assert_eq!(user_msgs[0].content.as_text(), "What is Rust?");
}
#[test]
fn test_assemble_text_entry_without_prefix_defaults_to_user() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::Text,
"some plain text".to_string(),
10,
)
.unwrap();
let assembled = window.assemble();
let user_msgs: Vec<_> = assembled
.messages
.iter()
.filter(|m| m.role == "user")
.collect();
assert_eq!(user_msgs.len(), 1);
assert_eq!(user_msgs[0].content.as_text(), "some plain text");
}
// ─── assemble() AssistantTurn variants ────────────────────────────────
#[test]
fn test_assemble_assistant_turn_with_text_and_tool_calls() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// User message first
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::UserMessage,
"Read my file".to_string(),
10,
)
.unwrap();
// Assistant with text + tool_calls
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::AssistantTurn {
tool_calls: vec![leviath_core::SerializedToolCall {
id: "tc_a".to_string(),
name: "read_file".to_string(),
arguments: serde_json::json!({"path": "foo.rs"}),
thought_signature: None,
}],
},
"Sure, let me read it.".to_string(),
20,
)
.unwrap();
// Matching tool result
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::ToolResult {
tool_call_id: "tc_a".to_string(),
tool_name: "read_file".to_string(),
is_error: false,
},
"fn main() {}".to_string(),
10,
)
.unwrap();
let assembled = window.assemble();
// Find the assistant message with blocks
let assistant_msg = assembled
.messages
.iter()
.find(|m| m.role == "assistant")
.expect("should have assistant message");
// Assistant turn with text + a tool call assembles to a Text block
// followed by the ToolUse block.
assert_eq!(
assistant_msg.content,
leviath_providers::MessageContent::Blocks(vec![
leviath_providers::ContentBlock::Text {
text: "Sure, let me read it.".to_string(),
},
leviath_providers::ContentBlock::ToolUse {
id: "tc_a".to_string(),
name: "read_file".to_string(),
input: serde_json::json!({"path": "foo.rs"}),
thought_signature: None,
},
])
);
}
#[test]
fn test_assemble_assistant_turn_no_text_only_tool_calls() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// User message
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::UserMessage,
"Do it".to_string(),
10,
)
.unwrap();
// Assistant with empty text + tool_calls
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::AssistantTurn {
tool_calls: vec![leviath_core::SerializedToolCall {
id: "tc_b".to_string(),
name: "bash".to_string(),
arguments: serde_json::json!({"cmd": "ls"}),
thought_signature: None,
}],
},
"".to_string(),
10,
)
.unwrap();
// Matching tool result
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::ToolResult {
tool_call_id: "tc_b".to_string(),
tool_name: "bash".to_string(),
is_error: false,
},
"file1.rs\nfile2.rs".to_string(),
10,
)
.unwrap();
let assembled = window.assemble();
let assistant_msg = assembled
.messages
.iter()
.find(|m| m.role == "assistant")
.expect("should have assistant message");
// Empty assistant text produces a single ToolUse block, no Text block.
assert_eq!(
assistant_msg.content,
leviath_providers::MessageContent::Blocks(vec![
leviath_providers::ContentBlock::ToolUse {
id: "tc_b".to_string(),
name: "bash".to_string(),
input: serde_json::json!({"cmd": "ls"}),
thought_signature: None,
},
])
);
}
// ─── assemble() consecutive ToolResults flushed ───────────────────────
#[test]
fn test_assemble_consecutive_tool_results_flushed_on_non_tool_result() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// User message
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::UserMessage,
"Run two tools".to_string(),
10,
)
.unwrap();
// Assistant with two tool calls
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::AssistantTurn {
tool_calls: vec![
leviath_core::SerializedToolCall {
id: "tc_1".to_string(),
name: "read_file".to_string(),
arguments: serde_json::json!({"path": "a.rs"}),
thought_signature: None,
},
leviath_core::SerializedToolCall {
id: "tc_2".to_string(),
name: "read_file".to_string(),
arguments: serde_json::json!({"path": "b.rs"}),
thought_signature: None,
},
],
},
"".to_string(),
10,
)
.unwrap();
// Two consecutive ToolResults
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::ToolResult {
tool_call_id: "tc_1".to_string(),
tool_name: "read_file".to_string(),
is_error: false,
},
"content of a.rs".to_string(),
10,
)
.unwrap();
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::ToolResult {
tool_call_id: "tc_2".to_string(),
tool_name: "read_file".to_string(),
is_error: false,
},
"content of b.rs".to_string(),
10,
)
.unwrap();
// Then a UserMessage (should flush the pending tool results first)
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::UserMessage,
"Now fix the bug".to_string(),
10,
)
.unwrap();
let assembled = window.assemble();
// Messages should be: user("Run two tools"), assistant(tool_uses),
// user(tool_result x2), user("Now fix the bug")
assert_eq!(assembled.messages.len(), 4);
// The third message should be a user message with two ToolResult blocks
let tool_result_msg = &assembled.messages[2];
assert_eq!(tool_result_msg.role, "user");
// The two consecutive tool results merge into one user message with two
// ToolResult blocks, in order.
assert_eq!(
tool_result_msg.content,
leviath_providers::MessageContent::Blocks(vec![
leviath_providers::ContentBlock::ToolResult {
tool_use_id: "tc_1".to_string(),
content: "content of a.rs".to_string(),
is_error: false,
},
leviath_providers::ContentBlock::ToolResult {
tool_use_id: "tc_2".to_string(),
content: "content of b.rs".to_string(),
is_error: false,
},
])
);
// The fourth message should be the user follow-up
assert_eq!(assembled.messages[3].role, "user");
assert_eq!(assembled.messages[3].content.as_text(), "Now fix the bug");
}
// ─── assemble() "Begin." fallback ─────────────────────────────────────
#[test]
fn test_assemble_injects_begin_when_no_user_messages() {
let mut window = ContextWindow::new(100_000);
// Only a Pinned region, no SlidingWindow with user messages
let mut pinned = Region::new("system".to_string(), RegionKind::Pinned, 10_000);
pinned
.add_entry("You are a helpful assistant.".to_string(), 20)
.unwrap();
window.add_region(pinned);
let assembled = window.assemble();
// Should have injected a "Begin." fallback user message
assert_eq!(assembled.messages.len(), 1);
assert_eq!(assembled.messages[0].role, "user");
assert_eq!(assembled.messages[0].content.as_text(), "Begin.");
}
// ─── add_typed_entry / add_typed_tainted_to_region error paths ────────
#[test]
fn test_add_typed_entry_to_nonexistent_region() {
let mut window = ContextWindow::new(10000);
let result = window.add_typed_entry(
"nonexistent",
leviath_core::EntryKind::UserMessage,
"hello".to_string(),
10,
);
assert!(result.is_err());
let err_str = result.unwrap_err().to_string();
assert!(
err_str.contains("nonexistent"),
"Error should mention the missing region name"
);
}
#[test]
fn test_add_typed_tainted_to_nonexistent_region() {
let mut window = ContextWindow::new(10000);
let result = window.add_typed_tainted_to_region(
"ghost",
leviath_core::EntryKind::UserMessage,
"data".to_string(),
10,
leviath_core::TaintLevel::Public,
);
assert!(result.is_err());
let err_str = result.unwrap_err().to_string();
assert!(
err_str.contains("ghost"),
"Error should mention the missing region name"
);
}
#[test]
fn test_assemble_tool_result_before_any_tool_use() {
// Edge case: tool_result appears in context but no tool_use exists at all
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conversation".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// A tool_result with no tool_use anywhere
window
.add_typed_entry(
"conversation",
leviath_core::EntryKind::ToolResult {
tool_call_id: "tc_nowhere".to_string(),
tool_name: "read_file".to_string(),
is_error: false,
},
"orphan result".to_string(),
10,
)
.unwrap();
let assembled = with_tracing(|| window.assemble());
// The orphaned tool_result message is stripped to empty and dropped,
// leaving no messages - so the "Begin." user fallback is synthesized.
assert_eq!(assembled.messages.len(), 1);
assert_eq!(assembled.messages[0].role, "user");
assert_eq!(
assembled.messages[0].content,
leviath_providers::MessageContent::Text("Begin.".to_string())
);
}
// ─── Prompt caching tests ────────────────────────────────────────────
#[test]
fn test_assemble_sets_cache_breakpoint_on_stable_prefix() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// Add 10 alternating user/assistant messages
for i in 0..10 {
let kind = if i % 2 == 0 {
leviath_core::EntryKind::UserMessage
} else {
leviath_core::EntryKind::AssistantTurn { tool_calls: vec![] }
};
window
.add_typed_entry("conv", kind, format!("message {i}"), 10)
.unwrap();
}
let assembled = window.assemble();
// 10 alternating messages end on an assistant turn, so assemble appends a
// trailing "Continue." user nudge → 11 messages.
assert_eq!(assembled.messages.len(), 11);
assert_eq!(assembled.messages.last().unwrap().role, "user");
// The breakpoint is placed at the 4th-from-last of the pre-nudge run
// (index 6 of the original 10); the nudge is appended after.
let bp_idx = 6;
for (i, msg) in assembled.messages.iter().enumerate() {
if i == bp_idx {
assert!(
msg.cache_breakpoint,
"Message at index {i} should have cache_breakpoint = true"
);
} else {
assert!(
!msg.cache_breakpoint,
"Message at index {i} should have cache_breakpoint = false"
);
}
}
}
#[test]
fn test_assemble_cache_breakpoint_small_conversation() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// Add 3 messages (user, assistant, user)
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::UserMessage,
"Hello".to_string(),
10,
)
.unwrap();
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::AssistantTurn { tool_calls: vec![] },
"Hi there".to_string(),
10,
)
.unwrap();
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::UserMessage,
"How are you?".to_string(),
10,
)
.unwrap();
let assembled = window.assemble();
assert_eq!(assembled.messages.len(), 3);
// With < 5 messages but >= 2, first message gets the breakpoint
assert!(
assembled.messages[0].cache_breakpoint,
"First message should have cache_breakpoint in small conversation"
);
assert!(!assembled.messages[1].cache_breakpoint);
assert!(!assembled.messages[2].cache_breakpoint);
}
#[test]
fn test_assemble_cache_breakpoint_too_few_messages() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// Add only 1 message
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::UserMessage,
"Solo message".to_string(),
10,
)
.unwrap();
let assembled = window.assemble();
assert_eq!(assembled.messages.len(), 1);
// With only 1 message, no breakpoints should be set
assert!(
!assembled.messages[0].cache_breakpoint,
"Single message should not get a cache breakpoint"
);
}
#[test]
fn test_assemble_system_blocks_sorted_by_cache_stability() {
use leviath_core::CacheHint;
let mut window = ContextWindow::new(100_000);
// Add regions in "wrong" order: volatile first, stable last
let mut clearable = Region::new("scratch".to_string(), RegionKind::Clearable, 10_000);
clearable
.add_entry("clearable data".to_string(), 20)
.unwrap();
window.add_region(clearable);
let mut temporary = Region::new("temp".to_string(), RegionKind::Temporary, 10_000);
temporary
.add_entry("temporary data".to_string(), 20)
.unwrap();
window.add_region(temporary);
let mut compacting = Region::new(
"impl".to_string(),
RegionKind::Compacting {
threshold_tokens: 500,
},
10_000,
);
compacting
.add_entry("compacting data".to_string(), 20)
.unwrap();
window.add_region(compacting);
let mut pinned = Region::new("system".to_string(), RegionKind::Pinned, 10_000);
pinned
.add_entry("pinned system prompt".to_string(), 20)
.unwrap();
window.add_region(pinned);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 4);
// Verify ordering: Always (Pinned) first, UntilChanged (Compacting) second,
// Never (Temporary, Clearable) last
assert_eq!(
assembled.system_blocks[0].cache_hint,
CacheHint::Always,
"First system block should be Always (Pinned)"
);
assert_eq!(
assembled.system_blocks[1].cache_hint,
CacheHint::UntilChanged,
"Second system block should be UntilChanged (Compacting)"
);
assert_eq!(
assembled.system_blocks[2].cache_hint,
CacheHint::Never,
"Third system block should be Never"
);
assert_eq!(
assembled.system_blocks[3].cache_hint,
CacheHint::Never,
"Fourth system block should be Never"
);
}
// ─── Coverage for ContextWindow typed+tainted methods ─────────────────
#[test]
fn test_add_typed_tainted_to_region_success() {
let mut window = ContextWindow::new(10000);
let mut region = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 50,
eviction_strategy: EvictionStrategy::PerItem,
},
5000,
);
region.enable_taint_tracking();
window.add_region(region);
window
.add_typed_tainted_to_region(
"conv",
leviath_core::EntryKind::ToolResult {
tool_call_id: "tc_1".to_string(),
tool_name: "read_file".to_string(),
is_error: false,
},
"secret data".to_string(),
100,
leviath_core::TaintLevel::Private,
)
.unwrap();
assert_eq!(window.current_tokens, 100);
assert_eq!(
window.get_region("conv").and_then(|r| r.taint_level()),
Some(leviath_core::TaintLevel::Private)
);
}
#[test]
fn test_add_typed_tainted_to_region_not_found() {
let mut window = ContextWindow::new(10000);
let result = window.add_typed_tainted_to_region(
"nonexistent",
leviath_core::EntryKind::Text,
"data".to_string(),
10,
leviath_core::TaintLevel::Public,
);
assert!(result.is_err());
}
#[test]
fn test_assemble_consecutive_tool_results_flushed_at_end() {
// Tool results at the END of the region (not followed by a non-ToolResult)
// should still be flushed into a user message.
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
window.add_region(region);
// Add user message, then assistant with tool calls, then tool results at end
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::UserMessage,
"do something".to_string(),
10,
)
.unwrap();
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::AssistantTurn {
tool_calls: vec![leviath_core::SerializedToolCall {
id: "tc_1".to_string(),
name: "read_file".to_string(),
arguments: serde_json::json!({"path": "foo.rs"}),
thought_signature: None,
}],
},
"Let me read that".to_string(),
10,
)
.unwrap();
window
.add_typed_entry(
"conv",
leviath_core::EntryKind::ToolResult {
tool_call_id: "tc_1".to_string(),
tool_name: "read_file".to_string(),
is_error: false,
},
"fn main() {}".to_string(),
10,
)
.unwrap();
let assembled = window.assemble();
// user msg + assistant (with tool_use blocks) + user (with tool_result blocks)
assert_eq!(assembled.messages.len(), 3);
assert_eq!(assembled.messages[2].role, "user");
// The last message is a Blocks message carrying the single ToolResult.
assert_eq!(
assembled.messages[2].content,
leviath_providers::MessageContent::Blocks(vec![
leviath_providers::ContentBlock::ToolResult {
tool_use_id: "tc_1".to_string(),
content: "fn main() {}".to_string(),
is_error: false,
},
])
);
}
#[test]
fn test_assemble_compact_history_with_sliding_prefix_sorting() {
// CompactHistory should sort before Compacting/Temporary in system blocks
use leviath_core::CacheHint;
let mut window = ContextWindow::new(100_000);
let mut temp = Region::new("temp".to_string(), RegionKind::Temporary, 10_000);
temp.add_entry("temp data".to_string(), 10).unwrap();
window.add_region(temp);
let mut history = Region::new(
"history".to_string(),
RegionKind::CompactHistory {
source_region: "impl".to_string(),
},
10_000,
);
history.add_entry("summary data".to_string(), 10).unwrap();
window.add_region(history);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 2);
// CompactHistory (Always) should come before Temporary (Never)
assert_eq!(assembled.system_blocks[0].cache_hint, CacheHint::Always);
assert_eq!(assembled.system_blocks[1].cache_hint, CacheHint::Never);
}
#[test]
fn cache_hint_sort_priority_orders_by_stability() {
use leviath_core::CacheHint;
// Most stable first (lowest priority), volatile last.
assert_eq!(cache_hint_sort_priority(CacheHint::Always), 0);
assert_eq!(
cache_hint_sort_priority(CacheHint::SlidingPrefix {
stable_fraction: 0.75
}),
1
);
assert_eq!(cache_hint_sort_priority(CacheHint::UntilChanged), 2);
assert_eq!(cache_hint_sort_priority(CacheHint::Never), 3);
// The four priorities are strictly increasing by volatility.
assert!(
cache_hint_sort_priority(CacheHint::Always)
< cache_hint_sort_priority(CacheHint::SlidingPrefix {
stable_fraction: 0.5
})
);
}
#[test]
fn test_assemble_empty_regions_skipped() {
let mut window = ContextWindow::new(100_000);
window.add_region(Region::new(
"system".to_string(),
RegionKind::Pinned,
10_000,
));
// Empty pinned region should be skipped
let assembled = window.assemble();
assert!(assembled.system_blocks.is_empty());
}
#[test]
fn test_assemble_hashmap_region_with_keys() {
let mut window = ContextWindow::new(100_000);
let mut region = Region::new(
"files".to_string(),
RegionKind::HashMap { max_entries: None },
10_000,
);
region
.upsert_by_key("src/main.rs", "fn main() {}".to_string(), 10)
.unwrap();
region
.upsert_by_key("src/lib.rs", "pub mod foo;".to_string(), 8)
.unwrap();
window.add_region(region);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 1);
let block_text = &assembled.system_blocks[0].text;
assert!(block_text.contains("[files]:"));
assert!(block_text.contains("### [src/main.rs]"));
assert!(block_text.contains("fn main() {}"));
assert!(block_text.contains("### [src/lib.rs]"));
assert!(block_text.contains("pub mod foo;"));
}
#[test]
fn test_assemble_hashmap_region_cache_hint() {
let mut window = ContextWindow::new(100_000);
let mut region = Region::new(
"files".to_string(),
RegionKind::HashMap { max_entries: None },
10_000,
);
region
.upsert_by_key("a.rs", "content".to_string(), 5)
.unwrap();
window.add_region(region);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 1);
assert_eq!(
assembled.system_blocks[0].cache_hint,
leviath_core::CacheHint::UntilChanged
);
}
// ─── HashMap region assembly tests ──────────────────────────────────
#[test]
fn test_assemble_hashmap_single_keyed_entry() {
let mut window = ContextWindow::new(100_000);
let mut region = Region::new(
"context".to_string(),
RegionKind::HashMap { max_entries: None },
10_000,
);
region
.upsert_by_key("config.toml", "key = \"value\"".to_string(), 10)
.unwrap();
window.add_region(region);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 1);
let block_text = &assembled.system_blocks[0].text;
assert!(
block_text.starts_with("[context]:"),
"System block should start with [region_name]: prefix"
);
assert!(
block_text.contains("### [config.toml]"),
"Entry should have ### [key] header"
);
assert!(
block_text.contains("key = \"value\""),
"Entry content should be present"
);
}
#[test]
fn test_assemble_hashmap_multiple_keyed_entries() {
let mut window = ContextWindow::new(100_000);
let mut region = Region::new(
"tracked_files".to_string(),
RegionKind::HashMap { max_entries: None },
10_000,
);
region
.upsert_by_key("alpha.rs", "fn alpha() {}".to_string(), 10)
.unwrap();
region
.upsert_by_key("beta.rs", "fn beta() {}".to_string(), 10)
.unwrap();
region
.upsert_by_key("gamma.rs", "fn gamma() {}".to_string(), 10)
.unwrap();
window.add_region(region);
let assembled = window.assemble();
assert_eq!(assembled.system_blocks.len(), 1);
let block_text = &assembled.system_blocks[0].text;
assert!(block_text.starts_with("[tracked_files]:"));
assert!(block_text.contains("### [alpha.rs]"));
assert!(block_text.contains("fn alpha() {}"));
assert!(block_text.contains("### [beta.rs]"));
assert!(block_text.contains("fn beta() {}"));
assert!(block_text.contains("### [gamma.rs]"));
assert!(block_text.contains("fn gamma() {}"));
}
#[test]
fn test_assemble_hashmap_empty_region_skipped() {
let mut window = ContextWindow::new(100_000);
let region = Region::new(
"empty_map".to_string(),
RegionKind::HashMap { max_entries: None },
10_000,
);
// No entries added
window.add_region(region);
let assembled = window.assemble();
assert!(
assembled.system_blocks.is_empty(),
"Empty HashMap region should not produce a system block"
);
}
#[test]
fn test_assemble_mixed_pinned_hashmap_sliding_window() {
use leviath_core::CacheHint;
let mut window = ContextWindow::new(100_000);
// Pinned region
let mut pinned = Region::new("system".to_string(), RegionKind::Pinned, 10_000);
pinned
.add_entry("You are a helpful assistant.".to_string(), 20)
.unwrap();
window.add_region(pinned);
// HashMap region
let mut hashmap = Region::new(
"files".to_string(),
RegionKind::HashMap { max_entries: None },
10_000,
);
hashmap
.upsert_by_key("main.rs", "fn main() {}".to_string(), 10)
.unwrap();
window.add_region(hashmap);
// SlidingWindow region with user messages
let mut sliding = Region::new(
"conv".to_string(),
RegionKind::SlidingWindow {
max_items: 100,
eviction_strategy: EvictionStrategy::PerItem,
},
50_000,
);
sliding
.add_typed_entry(
"Hello there".to_string(),
10,
leviath_core::EntryKind::UserMessage,
)
.unwrap();
window.add_region(sliding);
let assembled = window.assemble();
// Pinned and HashMap should produce system blocks (2 total)
assert_eq!(assembled.system_blocks.len(), 2);
// System blocks sorted by cache hint: Pinned (Always) first, HashMap (UntilChanged) second
assert_eq!(
assembled.system_blocks[0].cache_hint,
CacheHint::Always,
"Pinned region should sort first (Always cache hint)"
);
assert!(
assembled.system_blocks[0]
.text
.contains("You are a helpful assistant."),
"First system block should be the pinned content"
);
assert_eq!(
assembled.system_blocks[1].cache_hint,
CacheHint::UntilChanged,
"HashMap region should sort second (UntilChanged cache hint)"
);
assert!(
assembled.system_blocks[1].text.starts_with("[files]:"),
"HashMap system block should have [region_name]: prefix"
);
assert!(
assembled.system_blocks[1].text.contains("### [main.rs]"),
"HashMap system block should contain ### [key] header"
);
// SlidingWindow should produce messages, not system blocks
assert!(
assembled
.messages
.iter()
.any(|m| m.role == "user" && m.content.as_text().contains("Hello there")),
"SlidingWindow entries should appear as messages"
);
}
#[test]
fn test_add_tainted_to_region_propagates_budget_error() {
// Region is found, but the entry exceeds its token budget, so the
// inner `add_tainted_entry` error must propagate through the `?`.
let mut window = ContextWindow::new(10_000);
let mut region = Region::new("conv".to_string(), RegionKind::Temporary, 10);
region.enable_taint_tracking();
window.add_region(region);
let result = window.add_tainted_to_region(
"conv",
"far too many tokens".to_string(),
100,
leviath_core::TaintLevel::Private,
);
assert!(result.is_err());
}
#[test]
fn test_add_typed_tainted_to_region_propagates_budget_error() {
// Region is found, but the entry exceeds its token budget, so the
// inner `add_typed_tainted_entry` error must propagate through the `?`.
let mut window = ContextWindow::new(10_000);
let region = Region::new("conv".to_string(), RegionKind::Temporary, 10);
window.add_region(region);
let result = window.add_typed_tainted_to_region(
"conv",
leviath_core::EntryKind::Text,
"far too many tokens".to_string(),
100,
leviath_core::TaintLevel::Public,
);
assert!(result.is_err());
}
#[test]
fn test_assemble_hashmap_region_entry_without_key() {
// A HashMap-region entry with no key falls back to its raw content
// (rather than a "### [key]" header) when assembled.
let mut window = ContextWindow::new(10_000);
let region = Region::new(
"kv".to_string(),
RegionKind::HashMap { max_entries: None },
5000,
);
window.add_region(region);
// add_to_region stores the entry with key: None.
window
.add_to_region("kv", "keyless content".to_string(), 10)
.unwrap();
let assembled = window.assemble();
assert!(
assembled
.system_blocks
.iter()
.any(|b| b.text.contains("keyless content")),
"keyless HashMap entry should appear verbatim in a system block"
);
}
}