llm-agent-runtime 1.74.0

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

use crate::error::AgentRuntimeError;
use crate::metrics::RuntimeMetrics;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fmt::Write as FmtWrite;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

// ── Types ─────────────────────────────────────────────────────────────────────

/// A pinned, boxed future returning a `Value`. Used for async tool handlers.
pub type AsyncToolFuture = Pin<Box<dyn Future<Output = Value> + Send>>;

/// A pinned, boxed future returning `Result<Value, String>`. Used for fallible async tool handlers.
pub type AsyncToolResultFuture = Pin<Box<dyn Future<Output = Result<Value, String>> + Send>>;

/// An async tool handler closure.
pub type AsyncToolHandler = Box<dyn Fn(Value) -> AsyncToolFuture + Send + Sync>;

/// Role of a message in a conversation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Role {
    /// System-level instruction injected before the user turn.
    System,
    /// Message from the human user.
    User,
    /// Message produced by the language model.
    Assistant,
    /// Message produced by a tool invocation.
    Tool,
}

/// A single message in the conversation history.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    /// The role of the speaker who produced this message.
    pub role: Role,
    /// The textual content of the message.
    pub content: String,
}

impl Message {
    /// Create a new `Message` with the given role and content.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn new(role: Role, content: impl Into<String>) -> Self {
        Self {
            role,
            content: content.into(),
        }
    }

    /// Create a `User` role message.
    pub fn user(content: impl Into<String>) -> Self {
        Self::new(Role::User, content)
    }

    /// Create an `Assistant` role message.
    pub fn assistant(content: impl Into<String>) -> Self {
        Self::new(Role::Assistant, content)
    }

    /// Create a `System` role message.
    pub fn system(content: impl Into<String>) -> Self {
        Self::new(Role::System, content)
    }

    /// Return a reference to the message role.
    pub fn role(&self) -> &Role {
        &self.role
    }

    /// Return the message content as a `&str`.
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Return `true` if this is a `User` role message.
    pub fn is_user(&self) -> bool {
        self.role == Role::User
    }

    /// Return `true` if this is an `Assistant` role message.
    pub fn is_assistant(&self) -> bool {
        self.role == Role::Assistant
    }

    /// Return `true` if this is a `System` role message.
    pub fn is_system(&self) -> bool {
        self.role == Role::System
    }

    /// Return `true` if this is a `Tool` role message.
    pub fn is_tool(&self) -> bool {
        self.role == Role::Tool
    }

    /// Return `true` if the message content is empty.
    pub fn is_empty(&self) -> bool {
        self.content.is_empty()
    }

    /// Return the approximate number of whitespace-separated words in the content.
    pub fn word_count(&self) -> usize {
        self.content.split_whitespace().count()
    }

    /// Return the byte length of the content string.
    ///
    /// For ASCII-only content this equals the character count; for multi-byte
    /// UTF-8 sequences it will be larger.  Useful for rough token estimation.
    pub fn byte_len(&self) -> usize {
        self.content.len()
    }

    /// Return `true` if the content string starts with `prefix`.
    ///
    /// The check is byte-exact (case-sensitive).  Returns `true` for an empty
    /// `prefix` regardless of content.
    pub fn content_starts_with(&self, prefix: &str) -> bool {
        self.content.starts_with(prefix)
    }
}

impl std::fmt::Display for Role {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Role::System => write!(f, "system"),
            Role::User => write!(f, "user"),
            Role::Assistant => write!(f, "assistant"),
            Role::Tool => write!(f, "tool"),
        }
    }
}

impl std::fmt::Display for Message {
    /// Render as `"{role}: {content}"`.
    ///
    /// Useful for logging and quick inspection of conversation history.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.role, self.content)
    }
}

impl From<(Role, String)> for Message {
    /// Construct a `Message` from a `(Role, String)` tuple.
    fn from((role, content): (Role, String)) -> Self {
        Self::new(role, content)
    }
}

impl From<(Role, &str)> for Message {
    /// Construct a `Message` from a `(Role, &str)` tuple.
    fn from((role, content): (Role, &str)) -> Self {
        Self::new(role, content)
    }
}

/// A single ReAct step: Thought → Action → Observation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReActStep {
    /// Agent's reasoning about the current state.
    pub thought: String,
    /// The action taken (tool name + JSON arguments, or "FINAL_ANSWER").
    pub action: String,
    /// The result of the action.
    pub observation: String,
    /// Wall-clock duration of this individual step in milliseconds.
    /// Covers the time from the start of the inference call to the end of the
    /// tool invocation (or FINAL_ANSWER detection).  Zero for steps that were
    /// constructed outside the loop (e.g., in tests).
    #[serde(default)]
    pub step_duration_ms: u64,
}

impl ReActStep {
    /// Construct a step with zero `step_duration_ms`.
    ///
    /// Primarily useful in tests that need to build [`AgentSession`] values
    /// without running the full ReAct loop.
    pub fn new(
        thought: impl Into<String>,
        action: impl Into<String>,
        observation: impl Into<String>,
    ) -> Self {
        Self {
            thought: thought.into(),
            action: action.into(),
            observation: observation.into(),
            step_duration_ms: 0,
        }
    }

    /// Returns `true` if this step's action is a `FINAL_ANSWER`.
    pub fn is_final_answer(&self) -> bool {
        self.action.trim().to_ascii_uppercase().starts_with("FINAL_ANSWER")
    }

    /// Returns `true` if this step's action is a tool call (not a FINAL_ANSWER).
    pub fn is_tool_call(&self) -> bool {
        !self.is_final_answer() && !self.action.trim().is_empty()
    }

    /// Set the `step_duration_ms` field, returning `self` for chaining.
    ///
    /// Useful in tests and benchmarks that need to build `AgentSession` values
    /// with realistic timings without running the full ReAct loop.
    pub fn with_duration(mut self, ms: u64) -> Self {
        self.step_duration_ms = ms;
        self
    }

    /// Return `true` if all three text fields are empty strings.
    pub fn is_empty(&self) -> bool {
        self.thought.is_empty() && self.action.is_empty() && self.observation.is_empty()
    }

    /// Return `true` if the observation string is empty.
    ///
    /// Useful for identifying steps where the tool produced no output.
    pub fn observation_is_empty(&self) -> bool {
        self.observation.is_empty()
    }

    /// Return the approximate number of whitespace-separated words in the thought string.
    ///
    /// Returns `0` for steps with an empty thought.
    pub fn thought_word_count(&self) -> usize {
        self.thought.split_whitespace().count()
    }

    /// Return the number of whitespace-delimited words in the observation string.
    ///
    /// Returns `0` for empty or whitespace-only observations.
    pub fn observation_word_count(&self) -> usize {
        self.observation.split_whitespace().count()
    }

    /// Return `true` if the thought string is empty or whitespace-only.
    pub fn thought_is_empty(&self) -> bool {
        self.thought.trim().is_empty()
    }

    /// Return a concise single-line summary of this step.
    ///
    /// Format: `"[{kind}] thought={thought_preview} action={action_preview} obs={obs_preview}"`
    /// where each preview is at most 40 bytes, truncated with `…` if longer.
    /// `{kind}` is `"FINAL"` for a final-answer step and `"TOOL"` otherwise.
    ///
    /// Intended for logging and debugging — not a stable serialization format.
    pub fn summary(&self) -> String {
        fn preview(s: &str) -> String {
            if s.len() <= 40 {
                s.to_owned()
            } else {
                format!("{}", &s[..40])
            }
        }
        let kind = if self.is_final_answer() { "FINAL" } else { "TOOL" };
        format!(
            "[{kind}] thought={t} action={a} obs={o}",
            t = preview(self.thought.trim()),
            a = preview(self.action.trim()),
            o = preview(self.observation.trim()),
        )
    }

    /// Return the total byte length of `thought`, `action`, and `observation`
    /// combined.
    ///
    /// Useful for estimating token cost or bounding memory usage per step.
    pub fn combined_byte_length(&self) -> usize {
        self.thought.len() + self.action.len() + self.observation.len()
    }

    /// Return `true` if the action string is empty or whitespace-only.
    pub fn action_is_empty(&self) -> bool {
        self.action.trim().is_empty()
    }

    /// Return the total number of words across `thought`, `action`, and
    /// `observation`, counted by whitespace splitting.
    ///
    /// Useful for estimating the token cost of a complete ReAct step.
    pub fn total_word_count(&self) -> usize {
        self.thought.split_whitespace().count()
            + self.action.split_whitespace().count()
            + self.observation.split_whitespace().count()
    }

    /// Return `true` if all three fields — `thought`, `action`, and
    /// `observation` — are non-empty.
    ///
    /// A "complete" step is one where the model has produced a thought, taken
    /// an action, and received an observation.  Incomplete steps (missing any
    /// field) typically indicate a parsing failure or an in-progress cycle.
    pub fn is_complete(&self) -> bool {
        !self.thought.is_empty() && !self.action.is_empty() && !self.observation.is_empty()
    }

    /// Return `true` if the `observation` field starts with the given `prefix`.
    ///
    /// Useful for quick pattern checks on the model's last observation without
    /// allocating a new string.
    pub fn observation_starts_with(&self, prefix: &str) -> bool {
        self.observation.starts_with(prefix)
    }

    /// Return the number of whitespace-delimited words in the `action` field.
    ///
    /// Returns `0` for an empty action.
    pub fn action_word_count(&self) -> usize {
        self.action.split_whitespace().count()
    }

    /// Return the number of bytes in the `thought` field (UTF-8 encoded length).
    pub fn thought_byte_len(&self) -> usize {
        self.thought.len()
    }

    /// Return the number of bytes in the `action` field (UTF-8 encoded length).
    pub fn action_byte_len(&self) -> usize {
        self.action.len()
    }

    /// Return `true` if any of `thought`, `action`, or `observation` is empty.
    ///
    /// Useful for detecting incomplete or partially-populated steps before
    /// processing them further.
    pub fn has_empty_fields(&self) -> bool {
        self.thought.is_empty() || self.action.is_empty() || self.observation.is_empty()
    }

    /// Return the number of bytes in the `observation` field (UTF-8 encoded length).
    pub fn observation_byte_len(&self) -> usize {
        self.observation.len()
    }

    /// Return `true` if all three fields (`thought`, `action`, `observation`)
    /// each contain at least one whitespace-delimited word.
    pub fn all_fields_have_words(&self) -> bool {
        self.thought.split_whitespace().next().is_some()
            && self.action.split_whitespace().next().is_some()
            && self.observation.split_whitespace().next().is_some()
    }
}

/// Configuration for the ReAct agent loop.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Maximum number of Thought-Action-Observation cycles.
    pub max_iterations: usize,
    /// Model identifier passed to the inference function.
    pub model: String,
    /// System prompt injected at the start of the conversation.
    pub system_prompt: String,
    /// Maximum number of episodic memories to inject into the prompt.
    /// Keeping this small prevents silent token-budget overruns.  Default: 3.
    pub max_memory_recalls: usize,
    /// Maximum token budget for injected memories.
    ///
    /// Token counting is delegated to the [`TokenEstimator`] configured on
    /// [`AgentRuntimeBuilder`] (default: 1 token ≈ 4 bytes).  `None` means
    /// no limit.
    ///
    /// [`TokenEstimator`]: crate::runtime::TokenEstimator
    /// [`AgentRuntimeBuilder`]: crate::runtime::AgentRuntimeBuilder
    pub max_memory_tokens: Option<usize>,
    /// Optional wall-clock timeout for the entire loop.
    /// If the loop runs longer than this duration, it returns
    /// `Err(AgentRuntimeError::AgentLoop("loop timeout ..."))`.
    pub loop_timeout: Option<std::time::Duration>,
    /// Model sampling temperature.
    pub temperature: Option<f32>,
    /// Maximum output tokens.
    pub max_tokens: Option<usize>,
    /// Per-inference timeout.
    pub request_timeout: Option<std::time::Duration>,
    /// Maximum number of characters allowed in the running context string.
    ///
    /// When set, the oldest Thought/Action/Observation turns are trimmed from
    /// the **beginning** of the context (after the system prompt) to keep the
    /// total length below this limit.  This prevents silent context-window
    /// overruns in long-running agents.  `None` (default) means no limit.
    pub max_context_chars: Option<usize>,
    /// Stop sequences passed to the inference function.
    ///
    /// The model stops generating when it produces any of these strings.
    /// An empty `Vec` (default) means no stop sequences.
    pub stop_sequences: Vec<String>,
}

impl AgentConfig {
    /// Create a new config with sensible defaults.
    pub fn new(max_iterations: usize, model: impl Into<String>) -> Self {
        Self {
            max_iterations,
            model: model.into(),
            system_prompt: "You are a helpful AI agent.".into(),
            max_memory_recalls: 3,
            max_memory_tokens: None,
            loop_timeout: None,
            temperature: None,
            max_tokens: None,
            request_timeout: None,
            max_context_chars: None,
            stop_sequences: vec![],
        }
    }

    /// Override the system prompt.
    pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.system_prompt = prompt.into();
        self
    }

    /// Set the maximum number of episodic memories injected per run.
    pub fn with_max_memory_recalls(mut self, n: usize) -> Self {
        self.max_memory_recalls = n;
        self
    }

    /// Set a maximum token budget for injected memories (~4 chars/token heuristic).
    pub fn with_max_memory_tokens(mut self, n: usize) -> Self {
        self.max_memory_tokens = Some(n);
        self
    }

    /// Set a wall-clock timeout for the entire ReAct loop.
    ///
    /// If the loop has not reached `FINAL_ANSWER` within this duration,
    /// [`ReActLoop::run`] returns `Err(AgentRuntimeError::AgentLoop(...))`.
    pub fn with_loop_timeout(mut self, d: std::time::Duration) -> Self {
        self.loop_timeout = Some(d);
        self
    }

    /// Set a wall-clock timeout for the entire ReAct loop using seconds.
    ///
    /// Convenience wrapper around [`with_loop_timeout`](Self::with_loop_timeout).
    pub fn with_loop_timeout_secs(self, secs: u64) -> Self {
        self.with_loop_timeout(std::time::Duration::from_secs(secs))
    }

    /// Set a wall-clock timeout for the entire ReAct loop using milliseconds.
    ///
    /// Convenience wrapper around [`with_loop_timeout`](Self::with_loop_timeout).
    pub fn with_loop_timeout_ms(self, ms: u64) -> Self {
        self.with_loop_timeout(std::time::Duration::from_millis(ms))
    }

    /// Set the maximum number of ReAct iterations.
    pub fn with_max_iterations(mut self, n: usize) -> Self {
        self.max_iterations = n;
        self
    }

    /// Return the configured maximum number of ReAct iterations.
    pub fn max_iterations(&self) -> usize {
        self.max_iterations
    }

    /// Set the model sampling temperature.
    pub fn with_temperature(mut self, t: f32) -> Self {
        self.temperature = Some(t);
        self
    }

    /// Set the maximum output tokens.
    pub fn with_max_tokens(mut self, n: usize) -> Self {
        self.max_tokens = Some(n);
        self
    }

    /// Set the per-inference timeout.
    pub fn with_request_timeout(mut self, d: std::time::Duration) -> Self {
        self.request_timeout = Some(d);
        self
    }

    /// Set the per-inference timeout using seconds.
    ///
    /// Convenience wrapper around [`with_request_timeout`](Self::with_request_timeout).
    pub fn with_request_timeout_secs(self, secs: u64) -> Self {
        self.with_request_timeout(std::time::Duration::from_secs(secs))
    }

    /// Set the per-inference timeout using milliseconds.
    ///
    /// Convenience wrapper around [`with_request_timeout`](Self::with_request_timeout).
    pub fn with_request_timeout_ms(self, ms: u64) -> Self {
        self.with_request_timeout(std::time::Duration::from_millis(ms))
    }

    /// Set a maximum character limit for the running context string.
    ///
    /// When the context exceeds this length the oldest
    /// Thought/Action/Observation turns are trimmed from the front (after the
    /// initial system prompt + user turn) so the context stays under the limit.
    pub fn with_max_context_chars(mut self, n: usize) -> Self {
        self.max_context_chars = Some(n);
        self
    }

    /// Change the model used for completions.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = model.into();
        self
    }

    /// Clone this config with only the `model` field changed.
    ///
    /// Useful when the same configuration is shared across multiple agents that
    /// differ only in the model used for inference.
    pub fn clone_with_model(&self, model: impl Into<String>) -> Self {
        let mut copy = self.clone();
        copy.model = model.into();
        copy
    }

    /// Clone this config with only the `system_prompt` field changed.
    ///
    /// Useful when the same configuration is shared across multiple agents that
    /// differ only in the system prompt used for their sessions.
    pub fn clone_with_system_prompt(&self, prompt: impl Into<String>) -> Self {
        let mut copy = self.clone();
        copy.system_prompt = prompt.into();
        copy
    }

    /// Clone this config with only the `max_iterations` field changed.
    ///
    /// Useful when the same configuration is shared across multiple agents that
    /// differ only in the iteration budget — for example, a quick draft agent
    /// and a thorough research agent backed by the same model.
    pub fn clone_with_max_iterations(&self, n: usize) -> Self {
        let mut copy = self.clone();
        copy.max_iterations = n;
        copy
    }

    /// Set stop sequences for inference requests.
    ///
    /// The model will stop generating when it produces any of these strings.
    /// Defaults to an empty list (no stop sequences).
    pub fn with_stop_sequences(mut self, sequences: Vec<String>) -> Self {
        self.stop_sequences = sequences;
        self
    }

    /// Return `true` if this configuration is logically valid.
    ///
    /// Specifically, `max_iterations` must be at least 1 and `model` must be
    /// a non-empty string.
    pub fn is_valid(&self) -> bool {
        self.max_iterations >= 1 && !self.model.is_empty()
    }

    /// Validate the configuration, returning a structured error on failure.
    ///
    /// Checks the same invariants as [`is_valid`] but returns
    /// `Err(AgentRuntimeError::AgentLoop)` with a descriptive message instead
    /// of `false`, making it more useful in `?`-propagation chains.
    ///
    /// [`is_valid`]: AgentConfig::is_valid
    pub fn validate(&self) -> Result<(), crate::error::AgentRuntimeError> {
        if self.max_iterations == 0 {
            return Err(crate::error::AgentRuntimeError::AgentLoop(
                "AgentConfig: max_iterations must be >= 1".into(),
            ));
        }
        if self.model.is_empty() {
            return Err(crate::error::AgentRuntimeError::AgentLoop(
                "AgentConfig: model must not be empty".into(),
            ));
        }
        Ok(())
    }

    /// Return `true` if a loop timeout has been configured.
    pub fn has_loop_timeout(&self) -> bool {
        self.loop_timeout.is_some()
    }

    /// Return `true` if at least one stop sequence has been configured.
    pub fn has_stop_sequences(&self) -> bool {
        !self.stop_sequences.is_empty()
    }

    /// Return the number of configured stop sequences.
    pub fn stop_sequence_count(&self) -> usize {
        self.stop_sequences.len()
    }

    /// Return `true` if the agent runs at most one iteration.
    ///
    /// A single-shot agent executes exactly one Thought-Action-Observation
    /// cycle and then terminates regardless of whether a `FINAL_ANSWER` was
    /// produced.
    pub fn is_single_shot(&self) -> bool {
        self.max_iterations == 1
    }

    /// Return `true` if a sampling temperature has been configured.
    pub fn has_temperature(&self) -> bool {
        self.temperature.is_some()
    }

    /// Return the configured sampling temperature, if any.
    pub fn temperature(&self) -> Option<f32> {
        self.temperature
    }

    /// Return the configured maximum output tokens, if any.
    pub fn max_tokens(&self) -> Option<usize> {
        self.max_tokens
    }

    /// Return `true` if a per-inference request timeout has been configured.
    pub fn has_request_timeout(&self) -> bool {
        self.request_timeout.is_some()
    }

    /// Return the configured per-inference request timeout, if any.
    pub fn request_timeout(&self) -> Option<std::time::Duration> {
        self.request_timeout
    }

    /// Return `true` if a maximum context character limit has been configured.
    pub fn has_max_context_chars(&self) -> bool {
        self.max_context_chars.is_some()
    }

    /// Return the configured maximum context character limit, if any.
    pub fn max_context_chars(&self) -> Option<usize> {
        self.max_context_chars
    }

    /// Return the number of iterations still available after `n` have been completed.
    ///
    /// Uses saturating subtraction so values beyond `max_iterations` return `0`
    /// rather than wrapping.
    pub fn remaining_iterations_after(&self, n: usize) -> usize {
        self.max_iterations.saturating_sub(n)
    }

    /// Return the configured system prompt string.
    pub fn system_prompt(&self) -> &str {
        &self.system_prompt
    }

    /// Return `true` if the system prompt is empty or whitespace-only.
    ///
    /// A default `AgentConfig` has an empty system prompt.
    pub fn system_prompt_is_empty(&self) -> bool {
        self.system_prompt.trim().is_empty()
    }

    /// Return the model name this config targets.
    pub fn model(&self) -> &str {
        &self.model
    }

    /// Return the loop-level timeout in milliseconds, or `0` if no timeout is
    /// configured.
    ///
    /// This is the `loop_timeout` field expressed as milliseconds.  Useful for
    /// budget-calculation code that needs a uniform numeric representation of
    /// the timeout budget.
    pub fn loop_timeout_ms(&self) -> u64 {
        self.loop_timeout
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0)
    }

    /// Return the total wall-clock budget for all iterations in milliseconds.
    ///
    /// Computed as `loop_timeout_ms + max_iterations * request_timeout_ms`,
    /// where a missing timeout contributes `0`.  This is a *rough upper bound*
    /// — actual latency depends on model response times and tool execution.
    pub fn total_timeout_ms(&self) -> u64 {
        let loop_ms = self.loop_timeout_ms();
        let req_ms = self
            .request_timeout
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);
        loop_ms.saturating_add(self.max_iterations as u64 * req_ms)
    }

    /// Return `true` if the configured model name equals `name` (case-sensitive).
    ///
    /// A convenience predicate for conditional logic that branches on the model
    /// being used, e.g. choosing different prompt strategies per model family.
    pub fn model_is(&self, name: &str) -> bool {
        self.model == name
    }

    /// Return the number of whitespace-delimited words in `system_prompt`.
    ///
    /// Returns `0` for an empty prompt.
    pub fn system_prompt_word_count(&self) -> usize {
        self.system_prompt.split_whitespace().count()
    }

    /// Return the number of iterations still available after `steps_done`
    /// steps have been completed.
    ///
    /// Saturates at `0` — never returns a negative-equivalent value even if
    /// `steps_done` exceeds `max_iterations`.
    pub fn iteration_budget_remaining(&self, steps_done: usize) -> usize {
        self.max_iterations.saturating_sub(steps_done)
    }

    /// Return `true` if this config is "minimal" — no system prompt and only
    /// one allowed iteration.
    ///
    /// Useful as a quick sanity-check predicate in tests and diagnostics.
    pub fn is_minimal(&self) -> bool {
        self.system_prompt.trim().is_empty() && self.max_iterations == 1
    }

    /// Return `true` if the configured model name starts with `prefix`.
    ///
    /// Useful for branching logic based on provider family without an exact
    /// string match (e.g. `config.model_starts_with("claude")` or
    /// `config.model_starts_with("gpt")`).
    pub fn model_starts_with(&self, prefix: &str) -> bool {
        self.model.starts_with(prefix)
    }

    /// Return `true` if `steps_done` meets or exceeds `max_iterations`.
    ///
    /// Useful as a termination guard in agent loop implementations.
    pub fn exceeds_iteration_limit(&self, steps_done: usize) -> bool {
        steps_done >= self.max_iterations
    }

    /// Return `true` if a token budget is configured via either `max_tokens`
    /// or `max_context_chars`.
    ///
    /// When `false` the agent will not enforce a token ceiling, which may
    /// cause silent overruns for very long conversations.
    pub fn token_budget_configured(&self) -> bool {
        self.max_tokens.is_some() || self.max_context_chars.is_some()
    }

    /// Return `max_tokens` if set, or `default` otherwise.
    ///
    /// Convenience helper for callers that always need a concrete token limit
    /// and want to fall back to a safe default when none has been configured.
    pub fn max_tokens_or_default(&self, default: usize) -> usize {
        self.max_tokens.unwrap_or(default)
    }

    /// Return the configured temperature, or `1.0` if none has been set.
    ///
    /// Provides a safe default for inference calls that always need a concrete
    /// value without requiring callers to unwrap an `Option<f32>`.
    pub fn effective_temperature(&self) -> f32 {
        self.temperature.unwrap_or(1.0)
    }

    /// Return `true` if the system prompt starts with the given `prefix`.
    ///
    /// Useful for routing or classification logic based on prompt preambles.
    pub fn system_prompt_starts_with(&self, prefix: &str) -> bool {
        self.system_prompt.starts_with(prefix)
    }

    /// Return `true` if `max_iterations` is strictly greater than `n`.
    ///
    /// Handy for guard conditions: e.g. `config.max_iterations_above(1)` checks
    /// that multi-step reasoning is allowed.
    pub fn max_iterations_above(&self, n: usize) -> bool {
        self.max_iterations > n
    }

    /// Return `true` if any configured stop sequence equals `s`.
    ///
    /// Returns `false` when no stop sequences have been configured.
    pub fn stop_sequences_contain(&self, s: &str) -> bool {
        self.stop_sequences.iter().any(|seq| seq == s)
    }

    /// Return the byte length of the system prompt string.
    ///
    /// Returns `0` when no system prompt has been configured (the default is an
    /// empty string).
    pub fn system_prompt_byte_len(&self) -> usize {
        self.system_prompt.len()
    }

    /// Return `true` if a temperature has been configured **and** it falls
    /// within the valid range `[0.0, 2.0]` (inclusive).
    ///
    /// Returns `false` when no temperature has been set.
    pub fn has_valid_temperature(&self) -> bool {
        self.temperature.map_or(false, |t| (0.0..=2.0).contains(&t))
    }
}

// ── ToolSpec ──────────────────────────────────────────────────────────────────

/// Describes and implements a single callable tool.
pub struct ToolSpec {
    /// Short identifier used in action strings (e.g. "search").
    pub name: String,
    /// Human-readable description passed to the model as part of the system prompt.
    pub description: String,
    /// Async handler: receives JSON arguments, returns a future resolving to a JSON result.
    pub(crate) handler: AsyncToolHandler,
    /// Field names that must be present in the JSON args object.
    /// Empty means no validation is performed.
    pub required_fields: Vec<String>,
    /// Custom argument validators run after `required_fields` and before the handler.
    /// All validators must pass; the first failure short-circuits execution.
    pub validators: Vec<Box<dyn ToolValidator>>,
    /// Optional per-tool circuit breaker.
    #[cfg(feature = "orchestrator")]
    pub circuit_breaker: Option<Arc<crate::orchestrator::CircuitBreaker>>,
}

impl std::fmt::Debug for ToolSpec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("ToolSpec");
        s.field("name", &self.name)
            .field("description", &self.description)
            .field("required_fields", &self.required_fields);
        #[cfg(feature = "orchestrator")]
        s.field("has_circuit_breaker", &self.circuit_breaker.is_some());
        s.finish()
    }
}

impl ToolSpec {
    /// Construct a new `ToolSpec` from a synchronous handler closure.
    /// The closure is wrapped in an `async move` block automatically.
    pub fn new(
        name: impl Into<String>,
        description: impl Into<String>,
        handler: impl Fn(Value) -> Value + Send + Sync + 'static,
    ) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            handler: Box::new(move |args| {
                let result = handler(args);
                Box::pin(async move { result })
            }),
            required_fields: Vec::new(),
            validators: Vec::new(),
            #[cfg(feature = "orchestrator")]
            circuit_breaker: None,
        }
    }

    /// Construct a new `ToolSpec` from an async handler closure.
    pub fn new_async(
        name: impl Into<String>,
        description: impl Into<String>,
        handler: impl Fn(Value) -> AsyncToolFuture + Send + Sync + 'static,
    ) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            handler: Box::new(handler),
            required_fields: Vec::new(),
            validators: Vec::new(),
            #[cfg(feature = "orchestrator")]
            circuit_breaker: None,
        }
    }

    /// Construct a new `ToolSpec` from a synchronous fallible handler closure.
    /// `Err(msg)` is converted to `{"error": msg, "ok": false}`.
    pub fn new_fallible(
        name: impl Into<String>,
        description: impl Into<String>,
        handler: impl Fn(Value) -> Result<Value, String> + Send + Sync + 'static,
    ) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            handler: Box::new(move |args| {
                let result = handler(args);
                let value = match result {
                    Ok(v) => v,
                    Err(msg) => serde_json::json!({"error": msg, "ok": false}),
                };
                Box::pin(async move { value })
            }),
            required_fields: Vec::new(),
            validators: Vec::new(),
            #[cfg(feature = "orchestrator")]
            circuit_breaker: None,
        }
    }

    /// Construct a new `ToolSpec` from an async fallible handler closure.
    /// `Err(msg)` is converted to `{"error": msg, "ok": false}`.
    pub fn new_async_fallible(
        name: impl Into<String>,
        description: impl Into<String>,
        handler: impl Fn(Value) -> AsyncToolResultFuture + Send + Sync + 'static,
    ) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            handler: Box::new(move |args| {
                let fut = handler(args);
                Box::pin(async move {
                    match fut.await {
                        Ok(v) => v,
                        Err(msg) => serde_json::json!({"error": msg, "ok": false}),
                    }
                })
            }),
            required_fields: Vec::new(),
            validators: Vec::new(),
            #[cfg(feature = "orchestrator")]
            circuit_breaker: None,
        }
    }

    /// Set the required fields that must be present in the JSON args object.
    ///
    /// Accepts any iterable of string-like values so callers can pass
    /// `&["field1", "field2"]`, `vec!["f".to_string()]`, or any other
    /// `IntoIterator<Item: Into<String>>` without manual conversion.
    pub fn with_required_fields(
        mut self,
        fields: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.required_fields = fields.into_iter().map(Into::into).collect();
        self
    }

    /// Attach custom argument validators.
    ///
    /// Validators run after `required_fields` checks and before the handler.
    /// The first failing validator short-circuits execution.
    pub fn with_validators(mut self, validators: Vec<Box<dyn ToolValidator>>) -> Self {
        self.validators = validators;
        self
    }

    /// Attach a circuit breaker to this tool spec.
    #[cfg(feature = "orchestrator")]
    pub fn with_circuit_breaker(mut self, cb: Arc<crate::orchestrator::CircuitBreaker>) -> Self {
        self.circuit_breaker = Some(cb);
        self
    }

    /// Override the human-readable description after construction.
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    /// Override the tool name after construction.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Return the number of required fields configured for this tool.
    pub fn required_field_count(&self) -> usize {
        self.required_fields.len()
    }

    /// Return `true` if this tool requires at least one field to be present in its args.
    pub fn has_required_fields(&self) -> bool {
        !self.required_fields.is_empty()
    }

    /// Return `true` if this tool has at least one custom argument validator attached.
    pub fn has_validators(&self) -> bool {
        !self.validators.is_empty()
    }

    /// Invoke the tool with the given JSON arguments.
    pub async fn call(&self, args: Value) -> Value {
        (self.handler)(args).await
    }
}

// ── ToolCache ─────────────────────────────────────────────────────────────────

/// Cache for tool call results.
///
/// Implement to deduplicate repeated identical tool calls within a single
/// [`ReActLoop::run`] invocation.
///
/// ## Cache key
/// Implementations should key on `(tool_name, args)`.  The `args` value is the
/// full parsed JSON object passed to the tool.
///
/// ## Thread safety
/// The trait is `Send + Sync`, so implementations must be safe to share across
/// threads.  Wrap mutable state in a `Mutex` or use lock-free atomics.
///
/// ## TTL
/// TTL semantics are implementation-defined.  A simple in-memory cache may
/// keep results for the lifetime of the [`ReActLoop::run`] call; a distributed
/// cache may use Redis with explicit expiry.
///
/// ## Lifetime
/// A cache instance is attached to a `ToolRegistry` and lives for the lifetime
/// of that registry.  Results are **not** automatically cleared between
/// `ReActLoop::run` calls — clear the cache explicitly if cross-run dedup is
/// not desired.
pub trait ToolCache: Send + Sync {
    /// Look up a cached result for `(tool_name, args)`.
    fn get(&self, tool_name: &str, args: &serde_json::Value) -> Option<serde_json::Value>;
    /// Store a result for `(tool_name, args)`.
    fn set(&self, tool_name: &str, args: &serde_json::Value, result: serde_json::Value);
}

// ── InMemoryToolCache ─────────────────────────────────────────────────────────

/// Inner state for [`InMemoryToolCache`], tracking insertion order for eviction.
struct ToolCacheInner {
    map: HashMap<(String, String), serde_json::Value>,
    /// Insertion-ordered keys for FIFO eviction.
    order: std::collections::VecDeque<(String, String)>,
}

/// A simple in-memory [`ToolCache`] backed by a `Mutex<HashMap>`.
///
/// Caches tool results keyed on `(tool_name, args_json_string)`.
/// Optionally bounded by a maximum number of entries; the oldest entry is
/// evicted once the cap is exceeded.
///
/// # Example
/// ```rust,ignore
/// use std::sync::Arc;
/// use llm_agent_runtime::agent::{InMemoryToolCache, ToolRegistry};
///
/// let cache = Arc::new(InMemoryToolCache::new());
/// let registry = ToolRegistry::new().with_cache(cache);
/// ```
pub struct InMemoryToolCache {
    inner: std::sync::Mutex<ToolCacheInner>,
    max_entries: Option<usize>,
}

impl std::fmt::Debug for InMemoryToolCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let len = self.len();
        f.debug_struct("InMemoryToolCache")
            .field("entries", &len)
            .field("max_entries", &self.max_entries)
            .finish()
    }
}

impl InMemoryToolCache {
    /// Create a new unbounded cache.
    pub fn new() -> Self {
        Self {
            inner: std::sync::Mutex::new(ToolCacheInner {
                map: HashMap::new(),
                order: std::collections::VecDeque::new(),
            }),
            max_entries: None,
        }
    }

    /// Create a cache that evicts the oldest entry once `max` entries are reached.
    pub fn with_max_entries(max: usize) -> Self {
        Self {
            inner: std::sync::Mutex::new(ToolCacheInner {
                map: HashMap::new(),
                order: std::collections::VecDeque::new(),
            }),
            max_entries: Some(max),
        }
    }

    /// Remove all cached entries.
    pub fn clear(&self) {
        if let Ok(mut inner) = self.inner.lock() {
            inner.map.clear();
            inner.order.clear();
        }
    }

    /// Return the number of cached entries.
    pub fn len(&self) -> usize {
        self.inner.lock().map(|s| s.map.len()).unwrap_or(0)
    }

    /// Return `true` if the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Return `true` if a cached result exists for `(tool_name, args)`.
    pub fn contains(&self, tool_name: &str, args: &serde_json::Value) -> bool {
        let key = (tool_name.to_owned(), args.to_string());
        self.inner
            .lock()
            .map(|s| s.map.contains_key(&key))
            .unwrap_or(false)
    }

    /// Remove the cached result for `(tool_name, args)`.  Returns `true` if found.
    pub fn remove(&self, tool_name: &str, args: &serde_json::Value) -> bool {
        let key = (tool_name.to_owned(), args.to_string());
        if let Ok(mut inner) = self.inner.lock() {
            if inner.map.remove(&key).is_some() {
                inner.order.retain(|k| k != &key);
                return true;
            }
        }
        false
    }

    /// Return the configured maximum capacity, or `None` if the cache is unbounded.
    pub fn capacity(&self) -> Option<usize> {
        self.max_entries
    }
}

impl Default for InMemoryToolCache {
    fn default() -> Self {
        Self::new()
    }
}

impl ToolCache for InMemoryToolCache {
    fn get(&self, tool_name: &str, args: &serde_json::Value) -> Option<serde_json::Value> {
        let key = (tool_name.to_owned(), args.to_string());
        self.inner.lock().ok()?.map.get(&key).cloned()
    }

    fn set(&self, tool_name: &str, args: &serde_json::Value, result: serde_json::Value) {
        let key = (tool_name.to_owned(), args.to_string());
        if let Ok(mut inner) = self.inner.lock() {
            if !inner.map.contains_key(&key) {
                inner.order.push_back(key.clone());
            }
            inner.map.insert(key, result);
            if let Some(max) = self.max_entries {
                while inner.map.len() > max {
                    if let Some(oldest) = inner.order.pop_front() {
                        inner.map.remove(&oldest);
                    }
                }
            }
        }
    }
}

// ── ToolRegistry ──────────────────────────────────────────────────────────────

/// Registry of available tools for the agent loop.
pub struct ToolRegistry {
    tools: HashMap<String, ToolSpec>,
    /// Optional tool result cache.
    cache: Option<Arc<dyn ToolCache>>,
}

impl std::fmt::Debug for ToolRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ToolRegistry")
            .field("tools", &self.tools.keys().collect::<Vec<_>>())
            .field("has_cache", &self.cache.is_some())
            .finish()
    }
}

impl Default for ToolRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl ToolRegistry {
    /// Create a new empty registry.
    pub fn new() -> Self {
        Self {
            tools: HashMap::new(),
            cache: None,
        }
    }

    /// Attach a tool result cache.
    pub fn with_cache(mut self, cache: Arc<dyn ToolCache>) -> Self {
        self.cache = Some(cache);
        self
    }

    /// Register a tool. Overwrites any existing tool with the same name.
    pub fn register(&mut self, spec: ToolSpec) {
        self.tools.insert(spec.name.clone(), spec);
    }

    /// Register multiple tools at once.
    ///
    /// Equivalent to calling [`register`] for each spec in order.  Duplicate
    /// names overwrite earlier entries.
    ///
    /// [`register`]: ToolRegistry::register
    pub fn register_tools(&mut self, specs: impl IntoIterator<Item = ToolSpec>) {
        for spec in specs {
            self.register(spec);
        }
    }

    /// Fluent builder: register a tool and return `self`.
    ///
    /// Allows chaining multiple registrations:
    /// ```no_run
    /// use llm_agent_runtime::agent::{ToolRegistry, ToolSpec};
    ///
    /// let registry = ToolRegistry::new()
    ///     .with_tool(ToolSpec::new("search", "Search", |args| args.clone()))
    ///     .with_tool(ToolSpec::new("calc", "Calculate", |args| args.clone()));
    /// ```
    pub fn with_tool(mut self, spec: ToolSpec) -> Self {
        self.register(spec);
        self
    }

    /// Call a tool by name.
    ///
    /// # Errors
    /// - `AgentRuntimeError::AgentLoop` — tool not found, required field missing, or
    ///   custom validator rejected the arguments
    /// - `AgentRuntimeError::CircuitOpen` — the tool's circuit breaker is open
    ///   (only possible when the `orchestrator` feature is enabled)
    #[tracing::instrument(skip_all, fields(tool_name = %name))]
    pub async fn call(&self, name: &str, args: Value) -> Result<Value, AgentRuntimeError> {
        let spec = self.tools.get(name).ok_or_else(|| {
            let mut suggestion = String::new();
            let names = self.tool_names();
            if !names.is_empty() {
                if let Some((closest, dist)) = names
                    .iter()
                    .map(|n| (n, levenshtein(name, n)))
                    .min_by_key(|(_, d)| *d)
                {
                    if dist <= 3 {
                        suggestion = format!(" (did you mean '{closest}'?)");
                    }
                }
            }
            AgentRuntimeError::AgentLoop(format!("tool '{name}' not found{suggestion}"))
        })?;

        // Item 3 — required field validation
        if !spec.required_fields.is_empty() {
            if let Some(obj) = args.as_object() {
                for field in &spec.required_fields {
                    if !obj.contains_key(field) {
                        return Err(AgentRuntimeError::AgentLoop(format!(
                            "tool '{}' missing required field '{}'",
                            name, field
                        )));
                    }
                }
            } else {
                return Err(AgentRuntimeError::AgentLoop(format!(
                    "tool '{}' requires JSON object args, got {}",
                    name, args
                )));
            }
        }

        // Custom validators.
        for validator in &spec.validators {
            validator.validate(&args)?;
        }

        // Per-tool circuit breaker check.
        #[cfg(feature = "orchestrator")]
        if let Some(ref cb) = spec.circuit_breaker {
            use crate::orchestrator::CircuitState;
            if let Ok(CircuitState::Open { .. }) = cb.state() {
                return Err(AgentRuntimeError::CircuitOpen {
                    service: format!("tool:{}", name),
                });
            }
        }

        // Check cache before invoking handler.
        if let Some(ref cache) = self.cache {
            if let Some(cached) = cache.get(name, &args) {
                return Ok(cached);
            }
        }

        let result = spec.call(args.clone()).await;

        // Update circuit breaker based on the tool's result.
        // Tools that embed errors as JSON use {"ok": false}; treat those as
        // circuit-breaker failures so the breaker can actually open.
        #[cfg(feature = "orchestrator")]
        if let Some(ref cb) = spec.circuit_breaker {
            let is_failure = result
                .get("ok")
                .and_then(|v| v.as_bool())
                .is_some_and(|ok| !ok);
            if is_failure {
                cb.record_failure();
            } else {
                cb.record_success();
            }
        }

        // Store result in cache.
        if let Some(ref cache) = self.cache {
            cache.set(name, &args, result.clone());
        }

        Ok(result)
    }

    /// Look up a registered tool by name.  Returns `None` if not registered.
    pub fn get(&self, name: &str) -> Option<&ToolSpec> {
        self.tools.get(name)
    }

    /// Return `true` if a tool with the given name is registered.
    pub fn has_tool(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    /// Remove a tool by name.  Returns `true` if the tool was registered.
    pub fn unregister(&mut self, name: &str) -> bool {
        self.tools.remove(name).is_some()
    }

    /// Return the list of registered tool names.
    pub fn tool_names(&self) -> Vec<&str> {
        self.tools.keys().map(|s| s.as_str()).collect()
    }

    /// Return all registered tool names as owned `String`s.
    ///
    /// Unlike [`tool_names`] this does not borrow `self`, making the result
    /// usable after the registry is moved or mutated.
    ///
    /// [`tool_names`]: ToolRegistry::tool_names
    pub fn tool_names_owned(&self) -> Vec<String> {
        self.tools.keys().cloned().collect()
    }

    /// Return all registered tool names sorted alphabetically.
    ///
    /// Useful for deterministic output in help text, diagnostics, or tests.
    pub fn all_tool_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.tools.keys().cloned().collect();
        names.sort();
        names
    }

    /// Return references to all registered `ToolSpec`s.
    pub fn tool_specs(&self) -> Vec<&ToolSpec> {
        self.tools.values().collect()
    }

    /// Return references to all `ToolSpec`s that satisfy the given predicate.
    ///
    /// # Example
    /// ```rust
    /// # use llm_agent_runtime::agent::ToolRegistry;
    /// let registry = ToolRegistry::new();
    /// let long_desc: Vec<_> = registry.filter_tools(|s| s.description.len() > 20);
    /// ```
    pub fn filter_tools<F: Fn(&ToolSpec) -> bool>(&self, pred: F) -> Vec<&ToolSpec> {
        self.tools.values().filter(|s| pred(s)).collect()
    }

    /// Rename a registered tool from `old_name` to `new_name`.
    ///
    /// The tool's `name` field and its registry key are both updated.
    /// Returns `true` if the tool was found and renamed, `false` if `old_name`
    /// is not registered.  If `new_name` is already registered, it is
    /// overwritten.
    pub fn rename_tool(&mut self, old_name: &str, new_name: impl Into<String>) -> bool {
        let Some(mut spec) = self.tools.remove(old_name) else {
            return false;
        };
        let new_name = new_name.into();
        spec.name = new_name.clone();
        self.tools.insert(new_name, spec);
        true
    }

    /// Return the number of registered tools.
    pub fn tool_count(&self) -> usize {
        self.tools.len()
    }

    /// Return `true` if no tools are registered.
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }

    /// Remove all registered tools.
    ///
    /// Useful for resetting the registry between test runs or for dynamic
    /// agent reconfiguration.
    pub fn clear(&mut self) {
        self.tools.clear();
    }

    /// Remove a tool from the registry by name.
    ///
    /// Returns `Some(spec)` if the tool was registered, `None` if not found.
    pub fn remove(&mut self, name: &str) -> Option<ToolSpec> {
        self.tools.remove(name)
    }

    /// Return `true` if a tool with the given name is registered.
    pub fn contains(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    /// Return `(name, description)` pairs for all registered tools, sorted by name.
    ///
    /// Useful for generating help text or logging the tool set at startup.
    pub fn descriptions(&self) -> Vec<(&str, &str)> {
        let mut pairs: Vec<(&str, &str)> = self
            .tools
            .values()
            .map(|s| (s.name.as_str(), s.description.as_str()))
            .collect();
        pairs.sort_unstable_by_key(|(name, _)| *name);
        pairs
    }

    /// Return references to all tool specs whose description contains
    /// `keyword` (case-insensitive).
    pub fn find_by_description_keyword(&self, keyword: &str) -> Vec<&ToolSpec> {
        let lower = keyword.to_ascii_lowercase();
        self.tools
            .values()
            .filter(|s| s.description.to_ascii_lowercase().contains(&lower))
            .collect()
    }

    /// Return the number of tools that have at least one required field.
    pub fn tool_count_with_required_fields(&self) -> usize {
        self.tools.values().filter(|s| s.has_required_fields()).count()
    }

    /// Return the number of registered tools that have at least one attached validator.
    ///
    /// Complements [`tool_count_with_required_fields`]; a tool can have validators
    /// without any required field declarations (for cross-field or range checks).
    ///
    /// [`tool_count_with_required_fields`]: ToolRegistry::tool_count_with_required_fields
    pub fn tool_count_with_validators(&self) -> usize {
        self.tools.values().filter(|s| s.has_validators()).count()
    }

    /// Return the names of all registered tools, sorted alphabetically.
    pub fn names(&self) -> Vec<&str> {
        let mut names: Vec<&str> = self.tools.keys().map(|k| k.as_str()).collect();
        names.sort_unstable();
        names
    }

    /// Return the names of all registered tools whose name starts with `prefix`,
    /// sorted alphabetically.
    pub fn tool_names_starting_with(&self, prefix: &str) -> Vec<&str> {
        let mut names: Vec<&str> = self
            .tools
            .keys()
            .filter(|k| k.starts_with(prefix))
            .map(|k| k.as_str())
            .collect();
        names.sort_unstable();
        names
    }

    /// Return the description of the tool with the given `name`, or `None` if
    /// no such tool is registered.
    pub fn description_for(&self, name: &str) -> Option<&str> {
        self.tools.get(name).map(|s| s.description.as_str())
    }

    /// Return the count of tools whose description contains `keyword`
    /// (case-insensitive).
    pub fn count_with_description_containing(&self, keyword: &str) -> usize {
        let lower = keyword.to_ascii_lowercase();
        self.tools
            .values()
            .filter(|s| s.description.to_ascii_lowercase().contains(&lower))
            .count()
    }

    /// Remove all registered tools.
    pub fn unregister_all(&mut self) {
        self.tools.clear();
    }

    /// Return a sorted list of tool names that contain `substring` (case-insensitive).
    pub fn names_containing(&self, substring: &str) -> Vec<&str> {
        let sub = substring.to_ascii_lowercase();
        let mut names: Vec<&str> = self
            .tools
            .keys()
            .filter(|name| name.to_ascii_lowercase().contains(&sub))
            .map(|s| s.as_str())
            .collect();
        names.sort_unstable();
        names
    }

    /// Return the description of the tool with the shortest description string.
    ///
    /// Returns `None` if the registry is empty.
    pub fn shortest_description(&self) -> Option<&str> {
        self.tools
            .values()
            .min_by_key(|s| s.description.len())
            .map(|s| s.description.as_str())
    }

    /// Return the description of the tool with the longest description string.
    ///
    /// Returns `None` if the registry is empty.
    pub fn longest_description(&self) -> Option<&str> {
        self.tools
            .values()
            .max_by_key(|s| s.description.len())
            .map(|s| s.description.as_str())
    }

    /// Return a sorted list of all tool descriptions.
    pub fn all_descriptions(&self) -> Vec<&str> {
        let mut descs: Vec<&str> = self.tools.values().map(|s| s.description.as_str()).collect();
        descs.sort_unstable();
        descs
    }

    /// Return the names of tools whose description contains `keyword` (case-insensitive).
    pub fn tool_names_with_keyword(&self, keyword: &str) -> Vec<&str> {
        let kw = keyword.to_ascii_lowercase();
        self.tools
            .values()
            .filter(|s| s.description.to_ascii_lowercase().contains(&kw))
            .map(|s| s.name.as_str())
            .collect()
    }

    /// Return the mean byte length of all tool descriptions.
    ///
    /// Returns `0.0` if the registry is empty.
    pub fn avg_description_length(&self) -> f64 {
        if self.tools.is_empty() {
            return 0.0;
        }
        let total: usize = self.tools.values().map(|s| s.description.len()).sum();
        total as f64 / self.tools.len() as f64
    }

    /// Return all registered tool names in ascending sorted order.
    pub fn tool_names_sorted(&self) -> Vec<&str> {
        let mut names: Vec<&str> = self.tools.keys().map(|k| k.as_str()).collect();
        names.sort_unstable();
        names
    }

    /// Return the count of tools whose description contains `keyword` (case-insensitive).
    pub fn description_contains_count(&self, keyword: &str) -> usize {
        let kw = keyword.to_ascii_lowercase();
        self.tools
            .values()
            .filter(|s| s.description.to_ascii_lowercase().contains(&kw))
            .count()
    }

    /// Return the total byte length of all tool description strings combined.
    ///
    /// Useful as a rough measure of how much context the tool registry will
    /// contribute to a prompt when all descriptions are serialized together.
    pub fn total_description_bytes(&self) -> usize {
        self.tools.values().map(|s| s.description.len()).sum()
    }

    /// Return the byte length of the shortest tool description, or `0` if the
    /// registry is empty.
    pub fn shortest_description_length(&self) -> usize {
        self.tools
            .values()
            .map(|s| s.description.len())
            .min()
            .unwrap_or(0)
    }

    /// Return the byte length of the longest tool description, or `0` if the
    /// registry is empty.
    pub fn longest_description_length(&self) -> usize {
        self.tools
            .values()
            .map(|s| s.description.len())
            .max()
            .unwrap_or(0)
    }

    /// Return the count of tools whose description byte length is strictly
    /// greater than `min_bytes`.
    ///
    /// Returns `0` for an empty registry or when no description exceeds
    /// `min_bytes`.
    pub fn tool_count_above_desc_bytes(&self, min_bytes: usize) -> usize {
        self.tools
            .values()
            .filter(|s| s.description.len() > min_bytes)
            .count()
    }

    /// Return references to all `ToolSpec`s that list `field` in their
    /// `required_fields`.
    ///
    /// Returns an empty `Vec` when no tools declare `field` as required.
    pub fn tools_with_required_field(&self, field: &str) -> Vec<&ToolSpec> {
        self.tools
            .values()
            .filter(|s| s.required_fields.iter().any(|f| f == field))
            .collect()
    }

    /// Return references to all `ToolSpec`s that have no required fields.
    ///
    /// Returns an empty `Vec` when every registered tool declares at least one
    /// required field, or when the registry is empty.
    pub fn tools_without_required_fields(&self) -> Vec<&ToolSpec> {
        self.tools
            .values()
            .filter(|s| s.required_fields.is_empty())
            .collect()
    }

    /// Return the average number of required fields per registered tool.
    ///
    /// Returns `0.0` for an empty registry.
    pub fn avg_required_fields_count(&self) -> f64 {
        if self.tools.is_empty() {
            return 0.0;
        }
        let total: usize = self.tools.values().map(|s| s.required_fields.len()).sum();
        total as f64 / self.tools.len() as f64
    }

    /// Return the total word count across all tool descriptions.
    ///
    /// Words are split on ASCII whitespace.  Returns `0` for an empty
    /// registry or when all descriptions are blank.
    pub fn tool_descriptions_total_words(&self) -> usize {
        self.tools
            .values()
            .map(|spec| spec.description.split_ascii_whitespace().count())
            .sum()
    }

    /// Return `true` if any registered tool has a blank description.
    ///
    /// A blank description is one that is empty or contains only whitespace.
    /// Returns `false` for an empty registry (vacuously no blank descriptions).
    pub fn has_tools_with_empty_descriptions(&self) -> bool {
        self.tools.values().any(|s| s.description.trim().is_empty())
    }

    /// Return the total number of required fields across all registered tools.
    ///
    /// Sums the `required_fields` lengths of every `ToolSpec`.
    /// Returns `0` for an empty registry or when no tool has required fields.
    pub fn total_required_fields(&self) -> usize {
        self.tools.values().map(|s| s.required_fields.len()).sum()
    }

    /// Return `true` if at least one registered tool's description contains
    /// `keyword` (case-sensitive substring search).
    pub fn has_tool_with_description_containing(&self, keyword: &str) -> bool {
        self.tools.values().any(|s| s.description.contains(keyword))
    }

    /// Return tool names whose description byte length exceeds `min_bytes`, sorted.
    ///
    /// Returns an empty `Vec` for an empty registry or when no description
    /// exceeds the threshold.
    pub fn tools_with_description_longer_than(&self, min_bytes: usize) -> Vec<&str> {
        let mut names: Vec<&str> = self
            .tools
            .values()
            .filter(|s| s.description.len() > min_bytes)
            .map(|s| s.name.as_str())
            .collect();
        names.sort_unstable();
        names
    }

    /// Return the byte length of the longest tool description, or `0` when empty.
    pub fn max_description_bytes(&self) -> usize {
        self.tools.values().map(|s| s.description.len()).max().unwrap_or(0)
    }

    /// Return the byte length of the shortest tool description, or `0` when empty.
    pub fn min_description_bytes(&self) -> usize {
        self.tools.values().map(|s| s.description.len()).min().unwrap_or(0)
    }

    /// Return `true` if any tool description starts with any of the given `prefixes`.
    ///
    /// Useful for checking whether a set of common description templates is
    /// in use (e.g. `"Search"`, `"Write"`, `"Read"`).  Returns `false` for an
    /// empty registry or empty `prefixes` slice.
    pub fn description_starts_with_any(&self, prefixes: &[&str]) -> bool {
        self.tools
            .values()
            .any(|s| prefixes.iter().any(|p| s.description.starts_with(p)))
    }

    /// Return a reference to the `ToolSpec` with the most required fields.
    ///
    /// When multiple tools share the maximum required-field count, the one that
    /// sorts first alphabetically by name is returned for deterministic output.
    /// Returns `None` for an empty registry.
    pub fn tool_with_most_required_fields(&self) -> Option<&ToolSpec> {
        self.tools.values().max_by(|a, b| {
            a.required_fields
                .len()
                .cmp(&b.required_fields.len())
                .then_with(|| b.name.cmp(&a.name))
        })
    }

    /// Return a reference to the `ToolSpec` with the given `name`, or `None`.
    pub fn tool_by_name(&self, name: &str) -> Option<&ToolSpec> {
        self.tools.get(name)
    }

    /// Return the names of all tools that have no validators, sorted alphabetically.
    ///
    /// Complements [`tool_count_with_validators`] by returning the actual names.
    /// Returns an empty `Vec` for an empty registry.
    ///
    /// [`tool_count_with_validators`]: ToolRegistry::tool_count_with_validators
    pub fn tools_without_validators(&self) -> Vec<&str> {
        let mut names: Vec<&str> = self
            .tools
            .values()
            .filter(|s| s.validators.is_empty())
            .map(|s| s.name.as_str())
            .collect();
        names.sort_unstable();
        names
    }

    /// Return the names of all tools that have at least one required field,
    /// sorted alphabetically.
    ///
    /// Returns an empty `Vec` when no tools have required fields or the
    /// registry is empty.
    pub fn tool_names_with_required_fields(&self) -> Vec<&str> {
        let mut names: Vec<&str> = self
            .tools
            .values()
            .filter(|s| !s.required_fields.is_empty())
            .map(|s| s.name.as_str())
            .collect();
        names.sort_unstable();
        names
    }

    /// Return `true` if **all** of the given `names` are registered in this
    /// registry.
    ///
    /// Returns `true` for an empty `names` slice (vacuously true).
    pub fn has_all_tools(&self, names: &[&str]) -> bool {
        names.iter().all(|n| self.tools.contains_key(*n))
    }

    /// Return the number of tools that have at least one required field defined.
    ///
    /// Returns `0` for an empty registry.
    pub fn tools_with_required_fields_count(&self) -> usize {
        self.tools
            .values()
            .filter(|t| !t.required_fields.is_empty())
            .count()
    }

    /// Return the names of all tools whose name starts with `prefix`, sorted
    /// alphabetically.
    ///
    /// Returns an empty `Vec` for an empty registry or when no tool matches.
    pub fn tool_names_with_prefix<'a>(&'a self, prefix: &str) -> Vec<&'a str> {
        let mut names: Vec<&str> = self
            .tools
            .keys()
            .filter(|n| n.starts_with(prefix))
            .map(|n| n.as_str())
            .collect();
        names.sort_unstable();
        names
    }
}

// ── ReActLoop ─────────────────────────────────────────────────────────────────

/// Parses a ReAct response string into a `ReActStep`.
///
/// Case-insensitive; tolerates spaces around the colon.
/// e.g. `Thought :`, `thought:`, `THOUGHT :` all match.
///
/// **Multi-line sections**: everything between a `Thought:` (or `Action:`)
/// header and the next section header is included verbatim, so JSON arguments
/// that span multiple lines are captured correctly.
pub fn parse_react_step(text: &str) -> Result<ReActStep, AgentRuntimeError> {
    // Track which section we are currently appending into.
    #[derive(PartialEq)]
    enum Section { None, Thought, Action }

    let mut thought_lines: Vec<&str> = Vec::new();
    let mut action_lines: Vec<&str> = Vec::new();
    let mut current = Section::None;

    for line in text.lines() {
        let trimmed = line.trim();
        let lower = trimmed.to_ascii_lowercase();
        if lower.starts_with("thought") {
            if let Some(colon_pos) = trimmed.find(':') {
                current = Section::Thought;
                thought_lines.clear();
                let first = trimmed[colon_pos + 1..].trim();
                if !first.is_empty() {
                    thought_lines.push(first);
                }
                continue;
            }
        } else if lower.starts_with("action") {
            if let Some(colon_pos) = trimmed.find(':') {
                current = Section::Action;
                action_lines.clear();
                let first = trimmed[colon_pos + 1..].trim();
                if !first.is_empty() {
                    action_lines.push(first);
                }
                continue;
            }
        } else if lower.starts_with("observation") {
            // Stop accumulating when we hit Observation (model may include it).
            current = Section::None;
            continue;
        }
        // Continuation line — append to the current section.
        match current {
            Section::Thought => thought_lines.push(trimmed),
            Section::Action => action_lines.push(trimmed),
            Section::None => {}
        }
    }

    let thought = thought_lines.join(" ");
    let action = action_lines.join("\n").trim().to_owned();

    if thought.is_empty() && action.is_empty() {
        return Err(AgentRuntimeError::AgentLoop(
            "could not parse ReAct step from response".into(),
        ));
    }

    Ok(ReActStep {
        thought,
        action,
        observation: String::new(),
        step_duration_ms: 0,
    })
}

/// The ReAct agent loop.
pub struct ReActLoop {
    config: AgentConfig,
    registry: ToolRegistry,
    /// Optional metrics sink; increments `total_tool_calls` / `failed_tool_calls`.
    metrics: Option<Arc<RuntimeMetrics>>,
    /// Optional persistence backend for per-step checkpointing during the loop.
    #[cfg(feature = "persistence")]
    checkpoint_backend: Option<(Arc<dyn crate::persistence::PersistenceBackend>, String)>,
    /// Optional observer for agent loop events.
    observer: Option<Arc<dyn Observer>>,
    /// Optional action hook called before each tool dispatch.
    action_hook: Option<ActionHook>,
}

impl std::fmt::Debug for ReActLoop {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("ReActLoop");
        s.field("config", &self.config)
            .field("registry", &self.registry)
            .field("has_metrics", &self.metrics.is_some())
            .field("has_observer", &self.observer.is_some())
            .field("has_action_hook", &self.action_hook.is_some());
        #[cfg(feature = "persistence")]
        s.field("has_checkpoint_backend", &self.checkpoint_backend.is_some());
        s.finish()
    }
}

impl ReActLoop {
    /// Create a new `ReActLoop` with the given configuration and an empty tool registry.
    pub fn new(config: AgentConfig) -> Self {
        Self {
            config,
            registry: ToolRegistry::new(),
            metrics: None,
            #[cfg(feature = "persistence")]
            checkpoint_backend: None,
            observer: None,
            action_hook: None,
        }
    }

    /// Attach an observer for agent loop events.
    pub fn with_observer(mut self, observer: Arc<dyn Observer>) -> Self {
        self.observer = Some(observer);
        self
    }

    /// Attach an action hook called before each tool dispatch.
    pub fn with_action_hook(mut self, hook: ActionHook) -> Self {
        self.action_hook = Some(hook);
        self
    }

    /// Attach a shared `RuntimeMetrics` instance.
    ///
    /// When set, the loop increments `total_tool_calls` on every tool dispatch
    /// and `failed_tool_calls` whenever a tool returns an error observation.
    pub fn with_metrics(mut self, metrics: Arc<RuntimeMetrics>) -> Self {
        self.metrics = Some(metrics);
        self
    }

    /// Attach a persistence backend for per-step loop checkpointing.
    ///
    /// After each completed step the current `Vec<ReActStep>` is serialised and
    /// saved under the key `"loop:<session_id>:step:<n>"`.  Checkpoint errors
    /// are logged but never abort the loop.
    #[cfg(feature = "persistence")]
    pub fn with_step_checkpoint(
        mut self,
        backend: Arc<dyn crate::persistence::PersistenceBackend>,
        session_id: impl Into<String>,
    ) -> Self {
        self.checkpoint_backend = Some((backend, session_id.into()));
        self
    }

    /// Return a read-only reference to the tool registry.
    pub fn registry(&self) -> &ToolRegistry {
        &self.registry
    }

    /// Return the number of tools currently registered.
    ///
    /// Shorthand for `loop_.registry().tool_count()`.
    pub fn tool_count(&self) -> usize {
        self.registry.tool_count()
    }

    /// Remove a registered tool by name.  Returns `true` if the tool was found.
    pub fn unregister_tool(&mut self, name: &str) -> bool {
        self.registry.unregister(name)
    }

    /// Register a tool that the agent loop can invoke.
    pub fn register_tool(&mut self, spec: ToolSpec) {
        self.registry.register(spec);
    }

    /// Register multiple tools at once.
    ///
    /// Equivalent to calling [`register_tool`] for each spec.
    ///
    /// [`register_tool`]: ReActLoop::register_tool
    pub fn register_tools(&mut self, specs: impl IntoIterator<Item = ToolSpec>) {
        for spec in specs {
            self.registry.register(spec);
        }
    }

    /// Trim `context` to at most `max_chars` characters by dropping the oldest
    /// Thought/Action/Observation turns from the **front** while preserving the
    /// initial system-prompt + user-turn preamble.
    ///
    /// Turns are delineated by leading `\nThought:` markers.  If no second
    /// turn boundary is found the context is left unchanged.
    fn maybe_trim_context(context: &mut String, max_chars: usize) {
        while context.len() > max_chars {
            // Find the second occurrence of "\nThought:" so we preserve the
            // preamble (everything up to the first turn) and drop only the
            // oldest appended turn.
            let first = context.find("\nThought:");
            let second = first.and_then(|pos| {
                context[pos + 1..].find("\nThought:").map(|p| pos + 1 + p)
            });
            if let Some(drop_until) = second {
                context.drain(..drop_until);
            } else {
                break; // Only one turn (or none) — nothing safe to drop.
            }
        }
    }

    /// Emit a blocked-action observation string.
    fn blocked_observation() -> String {
        serde_json::json!({
            "ok": false,
            "error": "action blocked by reviewer",
            "kind": "blocked"
        })
        .to_string()
    }

    /// Build the error observation JSON for a failed tool call.
    fn error_observation(_tool_name: &str, e: &AgentRuntimeError) -> String {
        let kind = match e {
            AgentRuntimeError::AgentLoop(msg) if msg.contains("not found") => "not_found",
            #[cfg(feature = "orchestrator")]
            AgentRuntimeError::CircuitOpen { .. } => "transient",
            _ => "permanent",
        };
        serde_json::json!({ "ok": false, "error": e.to_string(), "kind": kind }).to_string()
    }

    /// Execute the ReAct loop for the given prompt.
    ///
    /// # Arguments
    /// * `prompt` — user input passed as the initial context
    /// * `infer`  — async inference function: receives context string, returns response string
    ///
    /// # Errors
    /// - `AgentRuntimeError::AgentLoop("loop timeout …")` — if `loop_timeout` is configured
    ///   and the loop runs past the deadline
    /// - `AgentRuntimeError::AgentLoop("max iterations … reached")` — if the loop exhausts
    ///   `max_iterations` without emitting `FINAL_ANSWER`
    /// - `AgentRuntimeError::AgentLoop("could not parse …")` — if the model response cannot
    ///   be parsed into a `ReActStep`
    #[tracing::instrument(skip(infer))]
    pub async fn run<F, Fut>(
        &self,
        prompt: &str,
        mut infer: F,
    ) -> Result<Vec<ReActStep>, AgentRuntimeError>
    where
        F: FnMut(String) -> Fut,
        Fut: Future<Output = String>,
    {
        let mut steps: Vec<ReActStep> = Vec::new();
        let mut context = format!("{}\n\nUser: {}\n", self.config.system_prompt, prompt);

        // Pre-compute optional deadline once so that each iteration is O(1).
        let deadline = self
            .config
            .loop_timeout
            .map(|d| std::time::Instant::now() + d);

        // Observer: on_loop_start
        if let Some(ref obs) = self.observer {
            obs.on_loop_start(prompt);
        }

        for iteration in 0..self.config.max_iterations {
            let iter_span = tracing::info_span!(
                "react_iteration",
                iteration = iteration,
                model = %self.config.model,
            );
            let _iter_guard = iter_span.enter();

            // Wall-clock timeout check.
            if let Some(dl) = deadline {
                if std::time::Instant::now() >= dl {
                    let ms = self
                        .config
                        .loop_timeout
                        .map(|d| d.as_millis())
                        .unwrap_or(0);
                    let err = AgentRuntimeError::AgentLoop(format!("loop timeout after {ms} ms"));
                    if let Some(ref obs) = self.observer {
                        obs.on_error(&err);
                        obs.on_loop_end(steps.len());
                    }
                    return Err(err);
                }
            }

            let step_start = std::time::Instant::now();
            let response = infer(context.clone()).await;
            let mut step = parse_react_step(&response)?;

            tracing::debug!(
                step = iteration,
                thought = %step.thought,
                action = %step.action,
                "ReAct iteration"
            );

            if step.action.to_ascii_uppercase().starts_with("FINAL_ANSWER") {
                step.observation = step.action.clone();
                step.step_duration_ms = step_start.elapsed().as_millis() as u64;
                if let Some(ref m) = self.metrics {
                    m.record_step_latency(step.step_duration_ms);
                }
                if let Some(ref obs) = self.observer {
                    obs.on_step(iteration, &step);
                }
                steps.push(step);
                tracing::info!(step = iteration, "FINAL_ANSWER reached");
                if let Some(ref obs) = self.observer {
                    obs.on_loop_end(steps.len());
                }
                return Ok(steps);
            }

            // Item 3 — propagate parse errors rather than silently falling back.
            let (tool_name, args) = parse_tool_call(&step.action)?;

            tracing::debug!(
                step = iteration,
                tool_name = %tool_name,
                "dispatching tool call"
            );

            // Action hook check.
            if let Some(ref hook) = self.action_hook {
                if !hook(tool_name.clone(), args.clone()).await {
                    if let Some(ref obs) = self.observer {
                        obs.on_action_blocked(&tool_name, &args);
                    }
                    if let Some(ref m) = self.metrics {
                        m.record_tool_call(&tool_name);
                        m.record_tool_failure(&tool_name);
                    }
                    step.observation = Self::blocked_observation();
                    step.step_duration_ms = step_start.elapsed().as_millis() as u64;
                    if let Some(ref m) = self.metrics {
                        m.record_step_latency(step.step_duration_ms);
                    }
                    let _ = write!(
                        context,
                        "\nThought: {}\nAction: {}\nObservation: {}\n",
                        step.thought, step.action, step.observation
                    );
                    if let Some(max) = self.config.max_context_chars {
                        Self::maybe_trim_context(&mut context, max);
                    }
                    if let Some(ref obs) = self.observer {
                        obs.on_step(iteration, &step);
                    }
                    steps.push(step);
                    continue;
                }
            }

            // Observer: on_tool_call
            if let Some(ref obs) = self.observer {
                obs.on_tool_call(&tool_name, &args);
            }

            // Count every tool dispatch (global + per-tool).
            if let Some(ref m) = self.metrics {
                m.record_tool_call(&tool_name);
            }

            // Structured error categorization in observation.
            let tool_span = tracing::info_span!("tool_dispatch", tool = %tool_name);
            let _tool_guard = tool_span.enter();
            let observation = match self.registry.call(&tool_name, args).await {
                Ok(result) => serde_json::json!({ "ok": true, "data": result }).to_string(),
                Err(e) => {
                    // Count failed tool calls (global + per-tool).
                    if let Some(ref m) = self.metrics {
                        m.record_tool_failure(&tool_name);
                    }
                    Self::error_observation(&tool_name, &e)
                }
            };

            step.observation = observation.clone();
            step.step_duration_ms = step_start.elapsed().as_millis() as u64;
            if let Some(ref m) = self.metrics {
                m.record_step_latency(step.step_duration_ms);
            }
            let _ = write!(
                context,
                "\nThought: {}\nAction: {}\nObservation: {}\n",
                step.thought, step.action, observation
            );
            if let Some(max) = self.config.max_context_chars {
                Self::maybe_trim_context(&mut context, max);
            }
            if let Some(ref obs) = self.observer {
                obs.on_step(iteration, &step);
            }
            steps.push(step);

            // Item 11 — per-step loop checkpoint (behind feature flag).
            #[cfg(feature = "persistence")]
            if let Some((ref backend, ref session_id)) = self.checkpoint_backend {
                let step_idx = steps.len();
                let key = format!("loop:{session_id}:step:{step_idx}");
                match serde_json::to_vec(&steps) {
                    Ok(bytes) => {
                        if let Err(e) = backend.save(&key, &bytes).await {
                            tracing::warn!(
                                key = %key,
                                error = %e,
                                "loop step checkpoint save failed"
                            );
                        }
                    }
                    Err(e) => {
                        tracing::warn!(
                            step = step_idx,
                            error = %e,
                            "loop step checkpoint serialisation failed"
                        );
                    }
                }
            }
        }

        let err = AgentRuntimeError::AgentLoop(format!(
            "max iterations ({}) reached without final answer",
            self.config.max_iterations
        ));
        tracing::warn!(
            max_iterations = self.config.max_iterations,
            "ReAct loop exhausted max iterations without FINAL_ANSWER"
        );
        if let Some(ref obs) = self.observer {
            obs.on_error(&err);
            obs.on_loop_end(steps.len());
        }
        Err(err)
    }

    /// Execute the ReAct loop using a streaming inference function.
    ///
    /// Identical to [`run`] except the inference closure returns a
    /// `tokio::sync::mpsc::Receiver` that streams token chunks.  All chunks
    /// are collected into a single `String` before each iteration's response
    /// is parsed.  Stream errors result in an empty partial response (the
    /// erroring chunk is silently dropped and a warning is logged).
    ///
    /// [`run`]: ReActLoop::run
    #[tracing::instrument(skip(infer_stream))]
    pub async fn run_streaming<F, Fut>(
        &self,
        prompt: &str,
        mut infer_stream: F,
    ) -> Result<Vec<ReActStep>, AgentRuntimeError>
    where
        F: FnMut(String) -> Fut,
        Fut: Future<
            Output = tokio::sync::mpsc::Receiver<Result<String, AgentRuntimeError>>,
        >,
    {
        self.run(prompt, move |ctx| {
            let rx_fut = infer_stream(ctx);
            async move {
                let mut rx = rx_fut.await;
                let mut out = String::new();
                while let Some(chunk) = rx.recv().await {
                    match chunk {
                        Ok(s) => out.push_str(&s),
                        Err(e) => {
                            tracing::warn!(error = %e, "streaming chunk error; skipping");
                        }
                    }
                }
                out
            }
        })
        .await
    }
}

/// Declarative argument validator for a `ToolSpec`.
///
/// Implement this trait to enforce custom argument constraints (type ranges,
/// string patterns, etc.) before the handler is invoked.
///
/// Validators run **after** `required_fields` checks and **before** the handler.
/// The first failing validator short-circuits execution.
///
/// # Basic Example
/// ```no_run
/// use llm_agent_runtime::agent::ToolValidator;
/// use llm_agent_runtime::AgentRuntimeError;
/// use serde_json::Value;
///
/// struct NonEmptyQuery;
/// impl ToolValidator for NonEmptyQuery {
///     fn validate(&self, args: &Value) -> Result<(), AgentRuntimeError> {
///         let q = args.get("q").and_then(|v| v.as_str()).unwrap_or("");
///         if q.is_empty() {
///             return Err(AgentRuntimeError::AgentLoop(
///                 "tool 'search': q must not be empty".into(),
///             ));
///         }
///         Ok(())
///     }
/// }
/// ```
///
/// # Advanced Example — Parameterised validator
/// ```no_run
/// use llm_agent_runtime::agent::{ToolSpec, ToolValidator};
/// use llm_agent_runtime::AgentRuntimeError;
/// use serde_json::Value;
///
/// /// Validates that a named integer field is within [min, max].
/// struct RangeValidator { field: &'static str, min: i64, max: i64 }
///
/// impl ToolValidator for RangeValidator {
///     fn validate(&self, args: &Value) -> Result<(), AgentRuntimeError> {
///         let n = args
///             .get(self.field)
///             .and_then(|v| v.as_i64())
///             .ok_or_else(|| {
///                 AgentRuntimeError::AgentLoop(format!(
///                     "field '{}' must be an integer", self.field
///                 ))
///             })?;
///         if n < self.min || n > self.max {
///             return Err(AgentRuntimeError::AgentLoop(format!(
///                 "field '{}' = {n} is outside [{}, {}]",
///                 self.field, self.min, self.max,
///             )));
///         }
///         Ok(())
///     }
/// }
///
/// // Attach to a tool spec:
/// let spec = ToolSpec::new("roll_dice", "Roll n dice", |args| {
///     serde_json::json!({ "result": args })
/// })
/// .with_validators(vec![
///     Box::new(RangeValidator { field: "n", min: 1, max: 100 }),
/// ]);
/// ```
pub trait ToolValidator: Send + Sync {
    /// Validate `args` before the tool handler is invoked.
    ///
    /// Return `Ok(())` if the arguments are valid, or
    /// `Err(AgentRuntimeError::AgentLoop(...))` with a human-readable message.
    fn validate(&self, args: &Value) -> Result<(), AgentRuntimeError>;
}

/// Compute the Levenshtein edit distance between two strings.
///
/// Used to suggest close matches when a tool name is not found.
fn levenshtein(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let (m, n) = (a.len(), b.len());
    let mut dp = vec![vec![0usize; n + 1]; m + 1];
    for i in 0..=m {
        dp[i][0] = i;
    }
    for j in 0..=n {
        dp[0][j] = j;
    }
    for i in 1..=m {
        for j in 1..=n {
            dp[i][j] = if a[i - 1] == b[j - 1] {
                dp[i - 1][j - 1]
            } else {
                1 + dp[i - 1][j].min(dp[i][j - 1]).min(dp[i - 1][j - 1])
            };
        }
    }
    dp[m][n]
}

/// Split `"tool_name {json}"` into `(tool_name, Value)`.
///
/// Returns `Err(AgentRuntimeError::AgentLoop)` when:
/// - the tool name is empty
/// - the argument portion is non-empty but not valid JSON
fn parse_tool_call(action: &str) -> Result<(String, Value), AgentRuntimeError> {
    let mut parts = action.splitn(2, ' ');
    let name = parts.next().unwrap_or("").to_owned();
    if name.is_empty() {
        return Err(AgentRuntimeError::AgentLoop(
            "tool call has an empty tool name".into(),
        ));
    }
    let args_str = parts.next().unwrap_or("{}");
    let args: Value = serde_json::from_str(args_str).map_err(|e| {
        AgentRuntimeError::AgentLoop(format!(
            "invalid JSON args for tool call '{name}': {e} (raw: {args_str})"
        ))
    })?;
    Ok((name, args))
}

/// Agent-specific errors, mirrors `wasm-agent::AgentError`.
///
/// Converts to `AgentRuntimeError::AgentLoop` via the `From` implementation.
#[derive(Debug, thiserror::Error)]
pub enum AgentError {
    /// The referenced tool name does not exist in the registry.
    #[error("Tool '{0}' not found")]
    ToolNotFound(String),
    /// The ReAct loop consumed all iterations without emitting `FINAL_ANSWER`.
    #[error("Max iterations exceeded: {0}")]
    MaxIterations(usize),
    /// The model response could not be parsed into a `ReActStep`.
    #[error("Parse error: {0}")]
    ParseError(String),
}

impl From<AgentError> for AgentRuntimeError {
    fn from(e: AgentError) -> Self {
        AgentRuntimeError::AgentLoop(e.to_string())
    }
}

// ── Observer ──────────────────────────────────────────────────────────────────

/// Hook trait for observing agent loop events.
///
/// All methods have no-op default implementations so you only override
/// what you care about.
pub trait Observer: Send + Sync {
    /// Called when a ReAct step completes.
    fn on_step(&self, step_index: usize, step: &ReActStep) {
        let _ = (step_index, step);
    }
    /// Called when a tool is about to be dispatched.
    fn on_tool_call(&self, tool_name: &str, args: &serde_json::Value) {
        let _ = (tool_name, args);
    }
    /// Called when an action hook blocks a tool call before dispatch.
    ///
    /// `tool_name` is the name of the blocked tool; `args` are the arguments
    /// that were passed to the hook.  This is called *instead of* `on_tool_call`.
    fn on_action_blocked(&self, tool_name: &str, args: &serde_json::Value) {
        let _ = (tool_name, args);
    }
    /// Called when the loop starts.
    fn on_loop_start(&self, prompt: &str) {
        let _ = prompt;
    }
    /// Called when the loop finishes (success or error).
    fn on_loop_end(&self, step_count: usize) {
        let _ = step_count;
    }
    /// Called when the loop terminates with an error.
    ///
    /// Invoked for timeout, max-iterations, and parse failures.
    /// `on_loop_end` is also called immediately after `on_error`.
    fn on_error(&self, error: &crate::error::AgentRuntimeError) {
        let _ = error;
    }
}

// ── Action ────────────────────────────────────────────────────────────────────

/// A parsed action from a ReAct step.
#[derive(Debug, Clone, PartialEq)]
pub enum Action {
    /// The agent has produced a final answer.
    FinalAnswer(String),
    /// A tool call with a name and JSON arguments.
    ToolCall {
        /// The tool name.
        name: String,
        /// The parsed JSON arguments.
        args: serde_json::Value,
    },
}

impl Action {
    /// Parse an action string into an `Action`.
    ///
    /// Returns `Action::FinalAnswer` if the string starts with `FINAL_ANSWER` (case-insensitive).
    /// Otherwise parses as a tool call via `parse_tool_call`.
    pub fn parse(s: &str) -> Result<Action, AgentRuntimeError> {
        if s.trim().to_ascii_uppercase().starts_with("FINAL_ANSWER") {
            let answer = s.trim()["FINAL_ANSWER".len()..].trim().to_owned();
            return Ok(Action::FinalAnswer(answer));
        }
        let (name, args) = parse_tool_call(s)?;
        Ok(Action::ToolCall { name, args })
    }
}

/// Async hook called before each tool action. Return `true` to proceed, `false` to block.
///
/// When blocked, the loop inserts a synthetic observation
/// `{"ok": false, "error": "action blocked by reviewer", "kind": "blocked"}`
/// and continues to the next iteration without invoking the tool.
///
/// ## Observer interaction
///
/// When a hook **allows** an action (`true`), the normal observer sequence fires:
/// 1. `Observer::on_tool_call` — called before the tool is dispatched
/// 2. `Observer::on_step` — called after the observation is recorded
///
/// When a hook **blocks** an action (`false`), the sequence is:
/// 1. `Observer::on_action_blocked` — called instead of `on_tool_call`
/// 2. `Observer::on_step` — called after the synthetic blocked observation is recorded
///
/// Use [`make_action_hook`] to construct a hook from a plain `async fn` without
/// writing the `Arc<dyn Fn…>` boilerplate by hand.
pub type ActionHook = Arc<dyn Fn(String, serde_json::Value) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send>> + Send + Sync>;

/// Create an [`ActionHook`] from a plain `async fn` or closure.
///
/// This helper eliminates the need to manually write
/// `Arc::new(|name, args| Box::pin(async move { … }))`.
///
/// # Example
/// ```no_run
/// use llm_agent_runtime::agent::make_action_hook;
///
/// let hook = make_action_hook(|tool_name: String, _args| async move {
///     // Block any tool called "dangerous"
///     tool_name != "dangerous"
/// });
/// ```
pub fn make_action_hook<F, Fut>(f: F) -> ActionHook
where
    F: Fn(String, serde_json::Value) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = bool> + Send + 'static,
{
    Arc::new(move |name, args| Box::pin(f(name, args)))
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    #[tokio::test]
    async fn test_final_answer_on_first_step() {
        let config = AgentConfig::new(5, "test-model");
        let loop_ = ReActLoop::new(config);

        let steps = loop_
            .run("Say hello", |_ctx| async {
                "Thought: I will answer directly\nAction: FINAL_ANSWER hello".to_string()
            })
            .await
            .unwrap();

        assert_eq!(steps.len(), 1);
        assert!(steps[0]
            .action
            .to_ascii_uppercase()
            .starts_with("FINAL_ANSWER"));
    }

    #[tokio::test]
    async fn test_tool_call_then_final_answer() {
        let config = AgentConfig::new(5, "test-model");
        let mut loop_ = ReActLoop::new(config);

        loop_.register_tool(ToolSpec::new("greet", "Greets someone", |_args| {
            serde_json::json!("hello!")
        }));

        let mut call_count = 0;
        let steps = loop_
            .run("Say hello", |_ctx| {
                call_count += 1;
                let count = call_count;
                async move {
                    if count == 1 {
                        "Thought: I will greet\nAction: greet {}".to_string()
                    } else {
                        "Thought: done\nAction: FINAL_ANSWER done".to_string()
                    }
                }
            })
            .await
            .unwrap();

        assert_eq!(steps.len(), 2);
        assert_eq!(steps[0].action, "greet {}");
        assert!(steps[1]
            .action
            .to_ascii_uppercase()
            .starts_with("FINAL_ANSWER"));
    }

    #[tokio::test]
    async fn test_max_iterations_exceeded() {
        let config = AgentConfig::new(2, "test-model");
        let loop_ = ReActLoop::new(config);

        let result = loop_
            .run("loop forever", |_ctx| async {
                "Thought: thinking\nAction: noop {}".to_string()
            })
            .await;

        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("max iterations"));
    }

    #[tokio::test]
    async fn test_parse_react_step_valid() {
        let text = "Thought: I should check\nAction: lookup {\"key\":\"val\"}";
        let step = parse_react_step(text).unwrap();
        assert_eq!(step.thought, "I should check");
        assert_eq!(step.action, "lookup {\"key\":\"val\"}");
    }

    #[tokio::test]
    async fn test_parse_react_step_empty_fails() {
        let result = parse_react_step("no prefix lines here");
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_tool_not_found_returns_error_observation() {
        let config = AgentConfig::new(3, "test-model");
        let loop_ = ReActLoop::new(config);

        let mut call_count = 0;
        let steps = loop_
            .run("test", |_ctx| {
                call_count += 1;
                let count = call_count;
                async move {
                    if count == 1 {
                        "Thought: try missing tool\nAction: missing_tool {}".to_string()
                    } else {
                        "Thought: done\nAction: FINAL_ANSWER done".to_string()
                    }
                }
            })
            .await
            .unwrap();

        assert_eq!(steps.len(), 2);
        assert!(steps[0].observation.contains("\"ok\":false"));
    }

    #[tokio::test]
    async fn test_new_async_tool_spec() {
        let spec = ToolSpec::new_async("async_tool", "An async tool", |args| {
            Box::pin(async move { serde_json::json!({"echo": args}) })
        });

        let result = spec.call(serde_json::json!({"input": "test"})).await;
        assert!(result.get("echo").is_some());
    }

    // Item 1 — Robust ReAct Parser tests

    #[tokio::test]
    async fn test_parse_react_step_case_insensitive() {
        let text = "THOUGHT: done\nACTION: FINAL_ANSWER";
        let step = parse_react_step(text).unwrap();
        assert_eq!(step.thought, "done");
        assert_eq!(step.action, "FINAL_ANSWER");
    }

    #[tokio::test]
    async fn test_parse_react_step_space_before_colon() {
        let text = "Thought : done\nAction : go";
        let step = parse_react_step(text).unwrap();
        assert_eq!(step.thought, "done");
        assert_eq!(step.action, "go");
    }

    // Item 3 — Tool required field validation tests

    #[tokio::test]
    async fn test_tool_required_fields_missing_returns_error() {
        let config = AgentConfig::new(3, "test-model");
        let mut loop_ = ReActLoop::new(config);

        loop_.register_tool(
            ToolSpec::new(
                "search",
                "Searches for something",
                |args| serde_json::json!({ "result": args }),
            )
            .with_required_fields(vec!["q".to_string()]),
        );

        let mut call_count = 0;
        let steps = loop_
            .run("test", |_ctx| {
                call_count += 1;
                let count = call_count;
                async move {
                    if count == 1 {
                        // Call with empty object — missing "q"
                        "Thought: searching\nAction: search {}".to_string()
                    } else {
                        "Thought: done\nAction: FINAL_ANSWER done".to_string()
                    }
                }
            })
            .await
            .unwrap();

        assert_eq!(steps.len(), 2);
        assert!(
            steps[0].observation.contains("missing required field"),
            "observation was: {}",
            steps[0].observation
        );
    }

    // Item 9 — Structured error observation tests

    #[tokio::test]
    async fn test_tool_error_observation_includes_kind() {
        let config = AgentConfig::new(3, "test-model");
        let loop_ = ReActLoop::new(config);

        let mut call_count = 0;
        let steps = loop_
            .run("test", |_ctx| {
                call_count += 1;
                let count = call_count;
                async move {
                    if count == 1 {
                        "Thought: try missing\nAction: nonexistent_tool {}".to_string()
                    } else {
                        "Thought: done\nAction: FINAL_ANSWER done".to_string()
                    }
                }
            })
            .await
            .unwrap();

        assert_eq!(steps.len(), 2);
        let obs = &steps[0].observation;
        assert!(obs.contains("\"ok\":false"), "observation: {obs}");
        assert!(obs.contains("\"kind\":\"not_found\""), "observation: {obs}");
    }

    // ── step_duration_ms ──────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_step_duration_ms_is_set() {
        let config = AgentConfig::new(5, "test-model");
        let loop_ = ReActLoop::new(config);

        let steps = loop_
            .run("time it", |_ctx| async {
                "Thought: done\nAction: FINAL_ANSWER ok".to_string()
            })
            .await
            .unwrap();

        // step_duration_ms may be 0 on very fast systems but must be a valid u64.
        let _ = steps[0].step_duration_ms; // just verify the field exists and is accessible
    }

    // ── ToolValidator ─────────────────────────────────────────────────────────

    struct RequirePositiveN;
    impl ToolValidator for RequirePositiveN {
        fn validate(&self, args: &Value) -> Result<(), AgentRuntimeError> {
            let n = args.get("n").and_then(|v| v.as_i64()).unwrap_or(0);
            if n <= 0 {
                return Err(AgentRuntimeError::AgentLoop(
                    "n must be a positive integer".into(),
                ));
            }
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_tool_validator_blocks_invalid_args() {
        let mut registry = ToolRegistry::new();
        registry.register(
            ToolSpec::new("calc", "compute", |args| serde_json::json!({"n": args}))
                .with_validators(vec![Box::new(RequirePositiveN)]),
        );

        // n = -1 should be rejected by the validator.
        let result = registry
            .call("calc", serde_json::json!({"n": -1}))
            .await;
        assert!(result.is_err(), "validator should reject n=-1");
        assert!(result.unwrap_err().to_string().contains("positive integer"));
    }

    #[tokio::test]
    async fn test_tool_validator_passes_valid_args() {
        let mut registry = ToolRegistry::new();
        registry.register(
            ToolSpec::new("calc", "compute", |_| serde_json::json!(42))
                .with_validators(vec![Box::new(RequirePositiveN)]),
        );

        let result = registry
            .call("calc", serde_json::json!({"n": 5}))
            .await;
        assert!(result.is_ok(), "validator should accept n=5");
    }

    // ── Empty tool name ───────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_empty_tool_name_is_rejected() {
        // parse_tool_call("") → error because name is empty
        let result = parse_tool_call("");
        assert!(result.is_err());
        assert!(
            result.unwrap_err().to_string().contains("empty tool name"),
            "expected 'empty tool name' error"
        );
    }

    // ── Bulk register_tools ───────────────────────────────────────────────────

    #[tokio::test]
    async fn test_register_tools_bulk() {
        let mut registry = ToolRegistry::new();
        registry.register_tools(vec![
            ToolSpec::new("tool_a", "A", |_| serde_json::json!("a")),
            ToolSpec::new("tool_b", "B", |_| serde_json::json!("b")),
        ]);
        assert!(registry.call("tool_a", serde_json::json!({})).await.is_ok());
        assert!(registry.call("tool_b", serde_json::json!({})).await.is_ok());
    }

    // ── run_streaming parity ──────────────────────────────────────────────────

    #[tokio::test]
    async fn test_run_streaming_parity_with_run() {
        use tokio::sync::mpsc;

        let config = AgentConfig::new(5, "test-model");
        let loop_ = ReActLoop::new(config);

        let steps = loop_
            .run_streaming("Say hello", |_ctx| async {
                let (tx, rx) = mpsc::channel(4);
                // Send the response in chunks
                tokio::spawn(async move {
                    tx.send(Ok("Thought: done\n".to_string())).await.ok();
                    tx.send(Ok("Action: FINAL_ANSWER hi".to_string())).await.ok();
                });
                rx
            })
            .await
            .unwrap();

        assert_eq!(steps.len(), 1);
        assert!(steps[0]
            .action
            .to_ascii_uppercase()
            .starts_with("FINAL_ANSWER"));
    }

    #[tokio::test]
    async fn test_run_streaming_error_chunk_is_skipped() {
        use tokio::sync::mpsc;
        use crate::error::AgentRuntimeError;

        let config = AgentConfig::new(5, "test-model");
        let loop_ = ReActLoop::new(config);

        // Even with an error chunk, the loop recovers and returns the valid parts.
        let steps = loop_
            .run_streaming("test", |_ctx| async {
                let (tx, rx) = mpsc::channel(4);
                tokio::spawn(async move {
                    tx.send(Err(AgentRuntimeError::Provider("stream error".into())))
                        .await
                        .ok();
                    tx.send(Ok("Thought: recovered\nAction: FINAL_ANSWER ok".to_string()))
                        .await
                        .ok();
                });
                rx
            })
            .await
            .unwrap();

        assert_eq!(steps.len(), 1);
    }

    // ── Circuit breaker test (only compiled when feature is active) ────────────

    #[cfg(feature = "orchestrator")]
    #[tokio::test]
    async fn test_tool_with_circuit_breaker_passes_when_closed() {
        use std::sync::Arc;

        let cb = Arc::new(
            crate::orchestrator::CircuitBreaker::new(
                "echo-tool",
                5,
                std::time::Duration::from_secs(30),
            )
            .unwrap(),
        );

        let spec = ToolSpec::new(
            "echo",
            "Echoes args",
            |args| serde_json::json!({ "echoed": args }),
        )
        .with_circuit_breaker(cb);

        let registry = {
            let mut r = ToolRegistry::new();
            r.register(spec);
            r
        };

        let result = registry
            .call("echo", serde_json::json!({ "msg": "hi" }))
            .await;
        assert!(result.is_ok(), "expected Ok, got {:?}", result);
    }

    // ── Improvement 1: AgentConfig builder methods ────────────────────────────

    #[test]
    fn test_agent_config_builder_methods_set_fields() {
        let config = AgentConfig::new(3, "model")
            .with_temperature(0.7)
            .with_max_tokens(512)
            .with_request_timeout(std::time::Duration::from_secs(10));
        assert_eq!(config.temperature, Some(0.7));
        assert_eq!(config.max_tokens, Some(512));
        assert_eq!(config.request_timeout, Some(std::time::Duration::from_secs(10)));
    }

    // ── Improvement 2: Fallible tool handlers ─────────────────────────────────

    #[tokio::test]
    async fn test_fallible_tool_returns_error_json_on_err() {
        let spec = ToolSpec::new_fallible(
            "fail",
            "always fails",
            |_| Err::<Value, String>("something went wrong".to_string()),
        );
        let result = spec.call(serde_json::json!({})).await;
        assert_eq!(result["ok"], serde_json::json!(false));
        assert_eq!(result["error"], serde_json::json!("something went wrong"));
    }

    #[tokio::test]
    async fn test_fallible_tool_returns_value_on_ok() {
        let spec = ToolSpec::new_fallible(
            "succeed",
            "always succeeds",
            |_| Ok::<Value, String>(serde_json::json!(42)),
        );
        let result = spec.call(serde_json::json!({})).await;
        assert_eq!(result, serde_json::json!(42));
    }

    // ── Improvement 4: Did you mean ───────────────────────────────────────────

    #[tokio::test]
    async fn test_did_you_mean_suggestion_for_typo() {
        let mut registry = ToolRegistry::new();
        registry.register(ToolSpec::new("search", "search", |_| serde_json::json!("ok")));
        let result = registry.call("searc", serde_json::json!({})).await;
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("did you mean"), "expected suggestion in: {msg}");
    }

    #[tokio::test]
    async fn test_no_suggestion_for_very_different_name() {
        let mut registry = ToolRegistry::new();
        registry.register(ToolSpec::new("search", "search", |_| serde_json::json!("ok")));
        let result = registry.call("xxxxxxxxxxxxxxx", serde_json::json!({})).await;
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(!msg.contains("did you mean"), "unexpected suggestion in: {msg}");
    }

    // ── Improvement 11: Action enum ───────────────────────────────────────────

    #[test]
    fn test_action_parse_final_answer() {
        let action = Action::parse("FINAL_ANSWER hello world").unwrap();
        assert_eq!(action, Action::FinalAnswer("hello world".to_string()));
    }

    #[test]
    fn test_action_parse_tool_call() {
        let action = Action::parse("search {\"q\": \"rust\"}").unwrap();
        match action {
            Action::ToolCall { name, args } => {
                assert_eq!(name, "search");
                assert_eq!(args["q"], "rust");
            }
            _ => panic!("expected ToolCall"),
        }
    }

    #[test]
    fn test_action_parse_invalid_returns_err() {
        let result = Action::parse("");
        assert!(result.is_err());
    }

    // ── Improvement 13: Observer ──────────────────────────────────────────────

    #[tokio::test]
    async fn test_observer_on_step_called_for_each_step() {
        use std::sync::{Arc, Mutex};

        struct CountingObserver {
            step_count: Mutex<usize>,
        }
        impl Observer for CountingObserver {
            fn on_step(&self, _step_index: usize, _step: &ReActStep) {
                let mut c = self.step_count.lock().unwrap_or_else(|e| e.into_inner());
                *c += 1;
            }
        }

        let obs = Arc::new(CountingObserver { step_count: Mutex::new(0) });
        let config = AgentConfig::new(5, "test-model");
        let mut loop_ = ReActLoop::new(config).with_observer(obs.clone() as Arc<dyn Observer>);
        loop_.register_tool(ToolSpec::new("noop", "noop", |_| serde_json::json!("ok")));

        let mut call_count = 0;
        let _steps = loop_.run("test", |_ctx| {
            call_count += 1;
            let count = call_count;
            async move {
                if count == 1 {
                    "Thought: call noop\nAction: noop {}".to_string()
                } else {
                    "Thought: done\nAction: FINAL_ANSWER done".to_string()
                }
            }
        }).await.unwrap();

        let count = *obs.step_count.lock().unwrap_or_else(|e| e.into_inner());
        assert_eq!(count, 2, "observer should have seen 2 steps");
    }

    // ── Improvement 14: ToolCache ─────────────────────────────────────────────

    #[tokio::test]
    async fn test_tool_cache_returns_cached_result_on_second_call() {
        use std::collections::HashMap;
        use std::sync::Mutex;

        struct InMemCache {
            map: Mutex<HashMap<String, Value>>,
        }
        impl ToolCache for InMemCache {
            fn get(&self, tool_name: &str, args: &Value) -> Option<Value> {
                let key = format!("{tool_name}:{args}");
                let map = self.map.lock().unwrap_or_else(|e| e.into_inner());
                map.get(&key).cloned()
            }
            fn set(&self, tool_name: &str, args: &Value, result: Value) {
                let key = format!("{tool_name}:{args}");
                let mut map = self.map.lock().unwrap_or_else(|e| e.into_inner());
                map.insert(key, result);
            }
        }

        let call_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let call_count_clone = call_count.clone();

        let cache = Arc::new(InMemCache { map: Mutex::new(HashMap::new()) });
        let registry = ToolRegistry::new()
            .with_cache(cache as Arc<dyn ToolCache>);
        let mut registry = registry;

        registry.register(ToolSpec::new("count", "count calls", move |_| {
            call_count_clone.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            serde_json::json!({"calls": 1})
        }));

        let args = serde_json::json!({});
        let r1 = registry.call("count", args.clone()).await.unwrap();
        let r2 = registry.call("count", args.clone()).await.unwrap();

        assert_eq!(r1, r2);
        // The handler should only be called once; second call hits cache.
        assert_eq!(call_count.load(std::sync::atomic::Ordering::Relaxed), 1);
    }

    // ── Task 12: Chained validator short-circuit ──────────────────────────────

    #[tokio::test]
    async fn test_validators_short_circuit_on_first_failure() {
        use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
        use std::sync::Arc;

        let second_called = Arc::new(AtomicUsize::new(0));
        let second_called_clone = Arc::clone(&second_called);

        struct AlwaysFail;
        impl ToolValidator for AlwaysFail {
            fn validate(&self, _args: &Value) -> Result<(), AgentRuntimeError> {
                Err(AgentRuntimeError::AgentLoop("first validator failed".into()))
            }
        }

        struct CountCalls(Arc<AtomicUsize>);
        impl ToolValidator for CountCalls {
            fn validate(&self, _args: &Value) -> Result<(), AgentRuntimeError> {
                self.0.fetch_add(1, AOrdering::SeqCst);
                Ok(())
            }
        }

        let mut registry = ToolRegistry::new();
        registry.register(
            ToolSpec::new("guarded", "A guarded tool", |args| args.clone())
                .with_validators(vec![
                    Box::new(AlwaysFail),
                    Box::new(CountCalls(second_called_clone)),
                ]),
        );

        let result = registry.call("guarded", serde_json::json!({})).await;
        assert!(result.is_err(), "should fail due to first validator");
        assert_eq!(
            second_called.load(AOrdering::SeqCst),
            0,
            "second validator must not be called when first fails"
        );
    }

    // ── Task 14: loop_timeout integration test ────────────────────────────────

    #[tokio::test]
    async fn test_loop_timeout_fires_between_iterations() {
        let mut config = AgentConfig::new(100, "test-model");
        // 30 ms deadline; each infer call sleeps 20 ms, so timeout fires after 2 iterations.
        config.loop_timeout = Some(std::time::Duration::from_millis(30));
        let loop_ = ReActLoop::new(config);

        let result = loop_
            .run("test", |_ctx| async {
                // Sleep just long enough that the cumulative time exceeds the deadline.
                tokio::time::sleep(std::time::Duration::from_millis(20)).await;
                // Return a valid step that keeps the loop going (unknown tool → error observation → next iter).
                "Thought: still working\nAction: noop {}".to_string()
            })
            .await;

        assert!(result.is_err(), "loop should time out");
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("loop timeout"), "unexpected error: {msg}");
    }

    // ── Improvement 15: ActionHook ────────────────────────────────────────────

    // ── #2 ReActStep::is_final_answer / is_tool_call ──────────────────────────

    #[test]
    fn test_react_step_is_final_answer() {
        let step = ReActStep {
            thought: "".into(),
            action: "FINAL_ANSWER done".into(),
            observation: "".into(),
            step_duration_ms: 0,
        };
        assert!(step.is_final_answer());
        assert!(!step.is_tool_call());
    }

    #[test]
    fn test_react_step_is_tool_call() {
        let step = ReActStep {
            thought: "".into(),
            action: "search {}".into(),
            observation: "".into(),
            step_duration_ms: 0,
        };
        assert!(!step.is_final_answer());
        assert!(step.is_tool_call());
    }

    // ── #6 Role Display ───────────────────────────────────────────────────────

    #[test]
    fn test_role_display() {
        assert_eq!(Role::System.to_string(), "system");
        assert_eq!(Role::User.to_string(), "user");
        assert_eq!(Role::Assistant.to_string(), "assistant");
        assert_eq!(Role::Tool.to_string(), "tool");
    }

    // ── #12 Message accessors ─────────────────────────────────────────────────

    #[test]
    fn test_message_accessors() {
        let msg = Message::new(Role::User, "hello");
        assert_eq!(msg.role(), &Role::User);
        assert_eq!(msg.content(), "hello");
    }

    // ── #25 Action parse round-trips ──────────────────────────────────────────

    #[test]
    fn test_action_parse_final_answer_round_trip() {
        let step = ReActStep {
            thought: "done".into(),
            action: "FINAL_ANSWER Paris".into(),
            observation: "".into(),
            step_duration_ms: 0,
        };
        assert!(step.is_final_answer());
        let action = Action::parse(&step.action).unwrap();
        assert!(matches!(action, Action::FinalAnswer(ref s) if s == "Paris"));
    }

    #[test]
    fn test_action_parse_tool_call_round_trip() {
        let step = ReActStep {
            thought: "searching".into(),
            action: "search {\"q\":\"hello\"}".into(),
            observation: "".into(),
            step_duration_ms: 0,
        };
        assert!(step.is_tool_call());
        let action = Action::parse(&step.action).unwrap();
        assert!(matches!(action, Action::ToolCall { ref name, .. } if name == "search"));
    }

    // ── #26 Observer step indices ─────────────────────────────────────────────

    #[tokio::test]
    async fn test_observer_receives_correct_step_indices() {
        use std::sync::{Arc, Mutex};

        struct IndexCollector(Arc<Mutex<Vec<usize>>>);
        impl Observer for IndexCollector {
            fn on_step(&self, step_index: usize, _step: &ReActStep) {
                self.0.lock().unwrap_or_else(|e| e.into_inner()).push(step_index);
            }
        }

        let indices = Arc::new(Mutex::new(Vec::new()));
        let obs = Arc::new(IndexCollector(Arc::clone(&indices)));

        let config = AgentConfig::new(5, "test");
        let mut loop_ = ReActLoop::new(config).with_observer(obs as Arc<dyn Observer>);
        loop_.register_tool(ToolSpec::new("noop", "no-op", |_| serde_json::json!({})));

        let mut call_count = 0;
        loop_.run("test", |_ctx| {
            call_count += 1;
            let count = call_count;
            async move {
                if count == 1 {
                    "Thought: step1\nAction: noop {}".to_string()
                } else {
                    "Thought: done\nAction: FINAL_ANSWER ok".to_string()
                }
            }
        }).await.unwrap();

        let collected = indices.lock().unwrap_or_else(|e| e.into_inner()).clone();
        assert_eq!(collected, vec![0, 1], "expected step indices 0 and 1");
    }

    #[tokio::test]
    async fn test_action_hook_blocking_inserts_blocked_observation() {
        let hook: ActionHook = Arc::new(|_name, _args| {
            Box::pin(async move { false }) // always block
        });

        let config = AgentConfig::new(5, "test-model");
        let mut loop_ = ReActLoop::new(config).with_action_hook(hook);
        loop_.register_tool(ToolSpec::new("noop", "noop", |_| serde_json::json!("ok")));

        let mut call_count = 0;
        let steps = loop_.run("test", |_ctx| {
            call_count += 1;
            let count = call_count;
            async move {
                if count == 1 {
                    "Thought: try tool\nAction: noop {}".to_string()
                } else {
                    "Thought: done\nAction: FINAL_ANSWER done".to_string()
                }
            }
        }).await.unwrap();

        assert!(steps[0].observation.contains("blocked"), "expected blocked observation, got: {}", steps[0].observation);
    }

    #[test]
    fn test_react_step_new_constructor() {
        let s = ReActStep::new("think", "act", "obs");
        assert_eq!(s.thought, "think");
        assert_eq!(s.action, "act");
        assert_eq!(s.observation, "obs");
        assert_eq!(s.step_duration_ms, 0);
    }

    #[test]
    fn test_react_step_new_is_tool_call() {
        let s = ReActStep::new("think", "search {}", "result");
        assert!(s.is_tool_call());
        assert!(!s.is_final_answer());
    }

    #[test]
    fn test_react_step_new_is_final_answer() {
        let s = ReActStep::new("done", "FINAL_ANSWER 42", "");
        assert!(s.is_final_answer());
        assert!(!s.is_tool_call());
    }

    #[test]
    fn test_agent_config_is_valid_with_valid_config() {
        let cfg = AgentConfig::new(5, "my-model");
        assert!(cfg.is_valid());
    }

    #[test]
    fn test_agent_config_is_valid_with_zero_iterations() {
        let mut cfg = AgentConfig::new(1, "my-model");
        cfg.max_iterations = 0;
        assert!(!cfg.is_valid());
    }

    #[test]
    fn test_agent_config_is_valid_with_empty_model() {
        let mut cfg = AgentConfig::new(5, "my-model");
        cfg.model = String::new();
        assert!(!cfg.is_valid());
    }

    #[test]
    fn test_react_loop_tool_count_delegates_to_registry() {
        let cfg = AgentConfig::new(5, "model");
        let mut loop_ = ReActLoop::new(cfg);
        assert_eq!(loop_.tool_count(), 0);
        loop_.register_tool(ToolSpec::new("t1", "desc", |_| serde_json::json!("ok")));
        loop_.register_tool(ToolSpec::new("t2", "desc", |_| serde_json::json!("ok")));
        assert_eq!(loop_.tool_count(), 2);
    }

    #[test]
    fn test_tool_registry_has_tool_returns_true_when_registered() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("my-tool", "desc", |_| serde_json::json!("ok")));
        assert!(reg.has_tool("my-tool"));
        assert!(!reg.has_tool("other-tool"));
    }

    // ── Round 3: AgentConfig::validate ───────────────────────────────────────

    #[test]
    fn test_agent_config_validate_ok_for_valid_config() {
        let cfg = AgentConfig::new(5, "my-model");
        assert!(cfg.validate().is_ok());
    }

    #[test]
    fn test_agent_config_validate_err_for_zero_iterations() {
        let cfg = AgentConfig::new(0, "my-model");
        let err = cfg.validate().unwrap_err();
        assert!(err.to_string().contains("max_iterations"));
    }

    #[test]
    fn test_agent_config_validate_err_for_empty_model() {
        let cfg = AgentConfig::new(5, "");
        let err = cfg.validate().unwrap_err();
        assert!(err.to_string().contains("model"));
    }

    // ── Round 4: AgentConfig::clone_with_model / ToolSpec::with_name ─────────

    #[test]
    fn test_clone_with_model_produces_new_model_string() {
        let cfg = AgentConfig::new(5, "gpt-4");
        let new_cfg = cfg.clone_with_model("claude-3");
        assert_eq!(new_cfg.model, "claude-3");
        // Original unchanged
        assert_eq!(cfg.model, "gpt-4");
    }

    #[test]
    fn test_clone_with_model_preserves_other_fields() {
        let cfg = AgentConfig::new(10, "gpt-4").with_stop_sequences(vec!["STOP".to_string()]);
        let new_cfg = cfg.clone_with_model("o1");
        assert_eq!(new_cfg.max_iterations, 10);
        assert_eq!(new_cfg.stop_sequences, cfg.stop_sequences);
    }

    #[tokio::test]
    async fn test_tool_spec_with_name_changes_name() {
        let spec = ToolSpec::new("original", "desc", |_| serde_json::json!("ok"))
            .with_name("renamed");
        assert_eq!(spec.name, "renamed");
    }

    #[tokio::test]
    async fn test_tool_spec_with_name_and_description_chainable() {
        let spec = ToolSpec::new("old", "old desc", |_| serde_json::json!("ok"))
            .with_name("new")
            .with_description("new desc");
        assert_eq!(spec.name, "new");
        assert_eq!(spec.description, "new desc");
    }

    // ── Round 16: Message constructors, parse_react_step ─────────────────────

    #[test]
    fn test_message_user_sets_role_and_content() {
        let m = Message::user("hello");
        assert_eq!(m.content(), "hello");
        assert!(m.is_user());
        assert!(!m.is_assistant());
    }

    #[test]
    fn test_message_assistant_sets_role() {
        let m = Message::assistant("reply");
        assert!(m.is_assistant());
        assert!(!m.is_user());
        assert!(!m.is_system());
    }

    #[test]
    fn test_message_system_sets_role() {
        let m = Message::system("system prompt");
        assert!(m.is_system());
        assert_eq!(m.content(), "system prompt");
    }

    #[test]
    fn test_parse_react_step_valid_input() {
        let text = "Thought: I need to search\nAction: search[query]";
        let step = parse_react_step(text).unwrap();
        assert!(step.thought.contains("search"));
        assert!(step.action.contains("search"));
    }

    #[test]
    fn test_parse_react_step_missing_fields_returns_err() {
        let text = "no structured content here";
        assert!(parse_react_step(text).is_err());
    }

    // ── Round 18: ReActStep predicates, ToolRegistry ops, AgentConfig builders

    #[test]
    fn test_react_step_is_final_answer_true() {
        let step = ReActStep::new("t", "FINAL_ANSWER Paris", "");
        assert!(step.is_final_answer());
        assert!(!step.is_tool_call());
    }

    #[test]
    fn test_react_step_is_tool_call_true() {
        let step = ReActStep::new("t", "search {}", "result");
        assert!(step.is_tool_call());
        assert!(!step.is_final_answer());
    }

    #[test]
    fn test_tool_registry_unregister_returns_true_when_present() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("tool-x", "desc", |_| serde_json::json!("ok")));
        assert!(reg.unregister("tool-x"));
        assert!(!reg.has_tool("tool-x"));
    }

    #[test]
    fn test_tool_registry_unregister_returns_false_when_absent() {
        let mut reg = ToolRegistry::new();
        assert!(!reg.unregister("ghost"));
    }

    #[test]
    fn test_tool_registry_contains_matches_has_tool() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("alpha", "desc", |_| serde_json::json!("ok")));
        assert!(reg.contains("alpha"));
        assert!(!reg.contains("beta"));
    }

    #[test]
    fn test_agent_config_with_system_prompt() {
        let cfg = AgentConfig::new(5, "model")
            .with_system_prompt("You are helpful.");
        assert_eq!(cfg.system_prompt, "You are helpful.");
    }

    #[test]
    fn test_agent_config_with_temperature_and_max_tokens() {
        let cfg = AgentConfig::new(3, "model")
            .with_temperature(0.7)
            .with_max_tokens(512);
        assert!((cfg.temperature.unwrap() - 0.7).abs() < 1e-6);
        assert_eq!(cfg.max_tokens, Some(512));
    }

    #[test]
    fn test_agent_config_clone_with_model() {
        let orig = AgentConfig::new(5, "gpt-4");
        let cloned = orig.clone_with_model("claude-3");
        assert_eq!(cloned.model, "claude-3");
        assert_eq!(cloned.max_iterations, 5);
    }

    // ── Round 19: more AgentConfig builder methods, Message::is_tool ─────────

    #[test]
    fn test_agent_config_with_loop_timeout_secs() {
        let cfg = AgentConfig::new(5, "model").with_loop_timeout_secs(30);
        assert_eq!(cfg.loop_timeout, Some(std::time::Duration::from_secs(30)));
    }

    #[test]
    fn test_agent_config_with_max_context_chars() {
        let cfg = AgentConfig::new(5, "model").with_max_context_chars(4096);
        assert_eq!(cfg.max_context_chars, Some(4096));
    }

    #[test]
    fn test_agent_config_with_stop_sequences() {
        let cfg = AgentConfig::new(5, "model")
            .with_stop_sequences(vec!["STOP".to_string(), "END".to_string()]);
        assert_eq!(cfg.stop_sequences, vec!["STOP", "END"]);
    }

    #[test]
    fn test_message_is_tool_false_for_non_tool_roles() {
        assert!(!Message::user("hi").is_tool());
        assert!(!Message::assistant("reply").is_tool());
        assert!(!Message::system("prompt").is_tool());
    }

    // ── Round 6: AgentConfig::with_max_iterations / ToolRegistry::tool_names_owned

    #[test]
    fn test_agent_config_with_max_iterations() {
        let cfg = AgentConfig::new(5, "m").with_max_iterations(20);
        assert_eq!(cfg.max_iterations, 20);
    }

    #[test]
    fn test_tool_registry_tool_names_owned_returns_strings() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("alpha", "d", |_| serde_json::json!("ok")));
        reg.register(ToolSpec::new("beta", "d", |_| serde_json::json!("ok")));
        let mut names = reg.tool_names_owned();
        names.sort();
        assert_eq!(names, vec!["alpha".to_string(), "beta".to_string()]);
    }

    #[test]
    fn test_tool_registry_tool_names_owned_empty_when_no_tools() {
        let reg = ToolRegistry::new();
        assert!(reg.tool_names_owned().is_empty());
    }

    // ── Round 7: ToolRegistry::tool_specs ────────────────────────────────────

    #[test]
    fn test_tool_registry_tool_specs_returns_all_specs() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "desc1", |_| serde_json::json!("ok")));
        reg.register(ToolSpec::new("t2", "desc2", |_| serde_json::json!("ok")));
        let specs = reg.tool_specs();
        assert_eq!(specs.len(), 2);
    }

    #[test]
    fn test_tool_registry_tool_specs_empty_when_no_tools() {
        let reg = ToolRegistry::new();
        assert!(reg.tool_specs().is_empty());
    }

    // ── Round 8: ToolRegistry::rename_tool ───────────────────────────────────

    #[test]
    fn test_rename_tool_updates_name_and_key() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("old", "desc", |_| serde_json::json!("ok")));
        assert!(reg.rename_tool("old", "new"));
        assert!(reg.has_tool("new"));
        assert!(!reg.has_tool("old"));
        let spec = reg.get("new").unwrap();
        assert_eq!(spec.name, "new");
    }

    #[test]
    fn test_rename_tool_returns_false_for_unknown_name() {
        let mut reg = ToolRegistry::new();
        assert!(!reg.rename_tool("ghost", "other"));
    }

    // ── Round 9: filter_tools ─────────────────────────────────────────────────

    #[test]
    fn test_filter_tools_returns_matching_specs() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("short_desc", "hi", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("long_desc", "a longer description here", |_| serde_json::json!({})));
        let long_ones = reg.filter_tools(|s| s.description.len() > 10);
        assert_eq!(long_ones.len(), 1);
        assert_eq!(long_ones[0].name, "long_desc");
    }

    #[test]
    fn test_filter_tools_returns_empty_when_none_match() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "desc", |_| serde_json::json!({})));
        let none: Vec<_> = reg.filter_tools(|_| false);
        assert!(none.is_empty());
    }

    #[test]
    fn test_filter_tools_returns_all_when_predicate_always_true() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("a", "d1", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("b", "d2", |_| serde_json::json!({})));
        let all = reg.filter_tools(|_| true);
        assert_eq!(all.len(), 2);
    }

    // ── Round 10: AgentConfig::max_iterations getter ──────────────────────────

    #[test]
    fn test_agent_config_max_iterations_getter_returns_configured_value() {
        let cfg = AgentConfig::new(5, "model-x");
        assert_eq!(cfg.max_iterations(), 5);
    }

    #[test]
    fn test_agent_config_with_max_iterations_updates_getter() {
        let cfg = AgentConfig::new(3, "m").with_max_iterations(10);
        assert_eq!(cfg.max_iterations(), 10);
    }

    // ── Round 11: ToolRegistry::is_empty / clear / remove ─────────────────────

    #[test]
    fn test_tool_registry_is_empty_true_when_new() {
        let reg = ToolRegistry::new();
        assert!(reg.is_empty());
    }

    #[test]
    fn test_tool_registry_is_empty_false_after_register() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t", "d", |_| serde_json::json!({})));
        assert!(!reg.is_empty());
    }

    #[test]
    fn test_tool_registry_clear_empties_registry() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "d", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("t2", "d", |_| serde_json::json!({})));
        reg.clear();
        assert!(reg.is_empty());
        assert_eq!(reg.tool_count(), 0);
    }

    #[test]
    fn test_tool_registry_remove_returns_spec_and_decrements_count() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("myTool", "desc", |_| serde_json::json!({})));
        assert_eq!(reg.tool_count(), 1);
        let removed = reg.remove("myTool");
        assert!(removed.is_some());
        assert_eq!(reg.tool_count(), 0);
    }

    #[test]
    fn test_tool_registry_remove_returns_none_for_absent_tool() {
        let mut reg = ToolRegistry::new();
        assert!(reg.remove("ghost").is_none());
    }

    // ── Round 12: all_tool_names ──────────────────────────────────────────────

    #[test]
    fn test_all_tool_names_returns_sorted_names() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("zebra", "d", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("apple", "d", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("mango", "d", |_| serde_json::json!({})));
        let names = reg.all_tool_names();
        assert_eq!(names, vec!["apple", "mango", "zebra"]);
    }

    #[test]
    fn test_all_tool_names_empty_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert!(reg.all_tool_names().is_empty());
    }

    // ── Round 13: AgentConfig::remaining_iterations_after, ToolSpec predicates ──

    #[test]
    fn test_remaining_iterations_after_full_budget() {
        let cfg = AgentConfig::new(10, "m");
        assert_eq!(cfg.remaining_iterations_after(0), 10);
    }

    #[test]
    fn test_remaining_iterations_after_partial_use() {
        let cfg = AgentConfig::new(10, "m");
        assert_eq!(cfg.remaining_iterations_after(3), 7);
    }

    #[test]
    fn test_remaining_iterations_after_saturates_at_zero() {
        let cfg = AgentConfig::new(5, "m");
        assert_eq!(cfg.remaining_iterations_after(10), 0);
    }

    #[test]
    fn test_tool_spec_required_field_count_zero_by_default() {
        let spec = ToolSpec::new("t", "d", |_| serde_json::json!({}));
        assert_eq!(spec.required_field_count(), 0);
    }

    #[test]
    fn test_tool_spec_required_field_count_after_adding() {
        let spec = ToolSpec::new("t", "d", |_| serde_json::json!({}))
            .with_required_fields(["query", "limit"]);
        assert_eq!(spec.required_field_count(), 2);
    }

    #[test]
    fn test_tool_spec_has_required_fields_false_by_default() {
        let spec = ToolSpec::new("t", "d", |_| serde_json::json!({}));
        assert!(!spec.has_required_fields());
    }

    #[test]
    fn test_tool_spec_has_required_fields_true_after_adding() {
        let spec = ToolSpec::new("t", "d", |_| serde_json::json!({}))
            .with_required_fields(["key"]);
        assert!(spec.has_required_fields());
    }

    #[test]
    fn test_tool_spec_has_validators_false_by_default() {
        let spec = ToolSpec::new("t", "d", |_| serde_json::json!({}));
        assert!(!spec.has_validators());
    }

    // ── Round 14: ToolRegistry::contains, descriptions, tool_count ───────────

    #[test]
    fn test_tool_registry_contains_true_for_registered_tool() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("search", "d", |_| serde_json::json!({})));
        assert!(reg.contains("search"));
    }

    #[test]
    fn test_tool_registry_contains_false_for_unknown_tool() {
        let reg = ToolRegistry::new();
        assert!(!reg.contains("missing"));
    }

    #[test]
    fn test_tool_registry_descriptions_sorted_by_name() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("zebra", "z-desc", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("apple", "a-desc", |_| serde_json::json!({})));
        let descs = reg.descriptions();
        assert_eq!(descs[0], ("apple", "a-desc"));
        assert_eq!(descs[1], ("zebra", "z-desc"));
    }

    #[test]
    fn test_tool_registry_descriptions_empty_when_no_tools() {
        let reg = ToolRegistry::new();
        assert!(reg.descriptions().is_empty());
    }

    #[test]
    fn test_tool_registry_tool_count_increments_on_register() {
        let mut reg = ToolRegistry::new();
        assert_eq!(reg.tool_count(), 0);
        reg.register(ToolSpec::new("t1", "d", |_| serde_json::json!({})));
        assert_eq!(reg.tool_count(), 1);
        reg.register(ToolSpec::new("t2", "d", |_| serde_json::json!({})));
        assert_eq!(reg.tool_count(), 2);
    }

    // ── Round 16: ReActStep::observation_is_empty ─────────────────────────────

    #[test]
    fn test_observation_is_empty_true_for_empty_string() {
        let step = ReActStep::new("think", "search", "");
        assert!(step.observation_is_empty());
    }

    #[test]
    fn test_observation_is_empty_false_for_non_empty() {
        let step = ReActStep::new("think", "search", "found results");
        assert!(!step.observation_is_empty());
    }

    // ── Round 17: AgentConfig::temperature / max_tokens / request_timeout ────

    #[test]
    fn test_agent_config_temperature_getter_none_by_default() {
        let cfg = AgentConfig::new(5, "gpt-4");
        assert!(cfg.temperature().is_none());
    }

    #[test]
    fn test_agent_config_temperature_getter_some_when_set() {
        let cfg = AgentConfig::new(5, "gpt-4").with_temperature(0.7);
        assert!((cfg.temperature().unwrap() - 0.7).abs() < 1e-5);
    }

    #[test]
    fn test_agent_config_max_tokens_getter_none_by_default() {
        let cfg = AgentConfig::new(5, "gpt-4");
        assert!(cfg.max_tokens().is_none());
    }

    #[test]
    fn test_agent_config_max_tokens_getter_some_when_set() {
        let cfg = AgentConfig::new(5, "gpt-4").with_max_tokens(512);
        assert_eq!(cfg.max_tokens(), Some(512));
    }

    #[test]
    fn test_agent_config_request_timeout_getter_none_by_default() {
        let cfg = AgentConfig::new(5, "gpt-4");
        assert!(cfg.request_timeout().is_none());
    }

    #[test]
    fn test_agent_config_request_timeout_getter_some_when_set() {
        let cfg = AgentConfig::new(5, "gpt-4")
            .with_request_timeout(std::time::Duration::from_secs(10));
        assert_eq!(cfg.request_timeout(), Some(std::time::Duration::from_secs(10)));
    }

    // ── Round 22: has_max_context_chars, max_context_chars, system_prompt, model

    #[test]
    fn test_agent_config_has_max_context_chars_false_by_default() {
        let cfg = AgentConfig::new(5, "gpt-4");
        assert!(!cfg.has_max_context_chars());
    }

    #[test]
    fn test_agent_config_has_max_context_chars_true_after_setting() {
        let cfg = AgentConfig::new(5, "gpt-4").with_max_context_chars(8192);
        assert!(cfg.has_max_context_chars());
    }

    #[test]
    fn test_agent_config_max_context_chars_none_by_default() {
        let cfg = AgentConfig::new(5, "gpt-4");
        assert_eq!(cfg.max_context_chars(), None);
    }

    #[test]
    fn test_agent_config_max_context_chars_some_after_setting() {
        let cfg = AgentConfig::new(5, "gpt-4").with_max_context_chars(4096);
        assert_eq!(cfg.max_context_chars(), Some(4096));
    }

    #[test]
    fn test_agent_config_system_prompt_returns_configured_prompt() {
        let cfg = AgentConfig::new(5, "gpt-4").with_system_prompt("Be concise.");
        assert_eq!(cfg.system_prompt(), "Be concise.");
    }

    #[test]
    fn test_agent_config_model_returns_configured_model() {
        let cfg = AgentConfig::new(5, "claude-3");
        assert_eq!(cfg.model(), "claude-3");
    }

    // ── Round 23: Message::is_system, word_count; AgentConfig flags ───────────

    #[test]
    fn test_message_is_system_true_for_system_role() {
        let m = Message::system("context");
        assert!(m.is_system());
    }

    #[test]
    fn test_message_is_system_false_for_user_role() {
        let m = Message::user("hello");
        assert!(!m.is_system());
    }

    #[test]
    fn test_message_word_count_counts_whitespace_words() {
        let m = Message::user("hello world foo");
        assert_eq!(m.word_count(), 3);
    }

    #[test]
    fn test_message_word_count_zero_for_empty_content() {
        let m = Message::user("");
        assert_eq!(m.word_count(), 0);
    }

    #[test]
    fn test_agent_config_has_loop_timeout_false_by_default() {
        let cfg = AgentConfig::new(5, "m");
        assert!(!cfg.has_loop_timeout());
    }

    #[test]
    fn test_agent_config_has_loop_timeout_true_after_setting() {
        let cfg = AgentConfig::new(5, "m")
            .with_loop_timeout(std::time::Duration::from_secs(30));
        assert!(cfg.has_loop_timeout());
    }

    #[test]
    fn test_agent_config_has_stop_sequences_false_by_default() {
        let cfg = AgentConfig::new(5, "m");
        assert!(!cfg.has_stop_sequences());
    }

    #[test]
    fn test_agent_config_has_stop_sequences_true_after_adding() {
        let cfg = AgentConfig::new(5, "m").with_stop_sequences(vec!["STOP".to_string()]);
        assert!(cfg.has_stop_sequences());
    }

    #[test]
    fn test_agent_config_is_single_shot_true_when_max_iterations_one() {
        let cfg = AgentConfig::new(1, "m");
        assert!(cfg.is_single_shot());
    }

    #[test]
    fn test_agent_config_is_single_shot_false_when_max_iterations_gt_one() {
        let cfg = AgentConfig::new(5, "m");
        assert!(!cfg.is_single_shot());
    }

    #[test]
    fn test_agent_config_has_temperature_false_by_default() {
        let cfg = AgentConfig::new(5, "m");
        assert!(!cfg.has_temperature());
    }

    #[test]
    fn test_agent_config_has_temperature_true_after_setting() {
        let cfg = AgentConfig::new(5, "m").with_temperature(0.7);
        assert!(cfg.has_temperature());
    }

    // ── Round 26: ToolSpec builders ───────────────────────────────────────────

    #[test]
    fn test_tool_spec_new_fallible_returns_ok_value() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let tool = ToolSpec::new_fallible(
            "add",
            "adds numbers",
            |_args| Ok(serde_json::json!({"result": 42})),
        );
        let result = rt.block_on(tool.call(serde_json::json!({})));
        assert_eq!(result["result"], 42);
    }

    #[test]
    fn test_tool_spec_new_fallible_wraps_error_as_json() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let tool = ToolSpec::new_fallible(
            "fail",
            "always fails",
            |_| Err("bad input".to_string()),
        );
        let result = rt.block_on(tool.call(serde_json::json!({})));
        assert_eq!(result["error"], "bad input");
        assert_eq!(result["ok"], false);
    }

    #[test]
    fn test_tool_spec_new_async_fallible_wraps_error() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let tool = ToolSpec::new_async_fallible(
            "async_fail",
            "async error",
            |_| Box::pin(async { Err("async bad".to_string()) }),
        );
        let result = rt.block_on(tool.call(serde_json::json!({})));
        assert_eq!(result["error"], "async bad");
    }

    #[test]
    fn test_tool_spec_with_required_fields_sets_fields() {
        let tool = ToolSpec::new("t", "d", |_| serde_json::json!({}))
            .with_required_fields(["name", "value"]);
        assert_eq!(tool.required_field_count(), 2);
    }

    #[test]
    fn test_tool_spec_with_description_overrides_description() {
        let tool = ToolSpec::new("t", "original", |_| serde_json::json!({}))
            .with_description("updated description");
        assert_eq!(tool.description, "updated description");
    }

    // ── Round 25: stop_sequence_count / find_by_description_keyword ───────────

    #[test]
    fn test_agent_config_stop_sequence_count_zero_by_default() {
        let cfg = AgentConfig::new(5, "gpt-4");
        assert_eq!(cfg.stop_sequence_count(), 0);
    }

    #[test]
    fn test_agent_config_stop_sequence_count_reflects_configured_count() {
        let cfg = AgentConfig::new(5, "gpt-4")
            .with_stop_sequences(vec!["STOP".to_string(), "END".to_string()]);
        assert_eq!(cfg.stop_sequence_count(), 2);
    }

    #[test]
    fn test_tool_registry_find_by_description_keyword_empty_when_no_match() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("calc", "Performs arithmetic", |_| serde_json::json!({})));
        let results = reg.find_by_description_keyword("weather");
        assert!(results.is_empty());
    }

    #[test]
    fn test_tool_registry_find_by_description_keyword_case_insensitive() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("calc", "Performs ARITHMETIC operations", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("search", "Searches the web", |_| serde_json::json!({})));
        let results = reg.find_by_description_keyword("arithmetic");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "calc");
    }

    #[test]
    fn test_tool_registry_find_by_description_keyword_multiple_matches() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "query the database", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("t2", "query the cache", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("t3", "send a message", |_| serde_json::json!({})));
        let results = reg.find_by_description_keyword("query");
        assert_eq!(results.len(), 2);
    }

    // ── Round 31: Message::is_user/is_assistant,
    //             AgentConfig::stop_sequence_count/has_request_timeout ─────────

    #[test]
    fn test_message_is_user_true_for_user_role_r31() {
        let msg = Message::user("hello");
        assert!(msg.is_user());
        assert!(!msg.is_assistant());
    }

    #[test]
    fn test_message_is_assistant_true_for_assistant_role_r31() {
        let msg = Message::assistant("hi there");
        assert!(msg.is_assistant());
        assert!(!msg.is_user());
    }

    #[test]
    fn test_agent_config_stop_sequence_count_zero_for_new_config() {
        let cfg = AgentConfig::new(5, "model");
        assert_eq!(cfg.stop_sequence_count(), 0);
    }

    #[test]
    fn test_agent_config_stop_sequence_count_after_setting() {
        let cfg = AgentConfig::new(5, "model")
            .with_stop_sequences(vec!["<stop>".to_string(), "END".to_string()]);
        assert_eq!(cfg.stop_sequence_count(), 2);
    }

    #[test]
    fn test_agent_config_has_request_timeout_false_by_default() {
        let cfg = AgentConfig::new(5, "model");
        assert!(!cfg.has_request_timeout());
    }

    #[test]
    fn test_agent_config_has_request_timeout_true_after_setting() {
        let cfg = AgentConfig::new(5, "model")
            .with_request_timeout(std::time::Duration::from_secs(30));
        assert!(cfg.has_request_timeout());
    }

    // ── Round 29: ReActLoop::unregister_tool ──────────────────────────────────

    #[test]
    fn test_react_loop_unregister_tool_removes_registered_tool() {
        let mut agent = ReActLoop::new(AgentConfig::new(5, "m"));
        agent.register_tool(ToolSpec::new("t1", "desc", |_| serde_json::json!({})));
        assert!(agent.unregister_tool("t1"));
        assert_eq!(agent.tool_count(), 0);
    }

    #[test]
    fn test_react_loop_unregister_tool_returns_false_for_unknown() {
        let mut agent = ReActLoop::new(AgentConfig::new(5, "m"));
        assert!(!agent.unregister_tool("nonexistent"));
    }

    // ── Round 26: tool_count_with_required_fields ─────────────────────────────

    #[test]
    fn test_tool_count_with_required_fields_zero_when_empty() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.tool_count_with_required_fields(), 0);
    }

    #[test]
    fn test_tool_count_with_required_fields_excludes_tools_without_fields() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "d", |_| serde_json::json!({})));
        assert_eq!(reg.tool_count_with_required_fields(), 0);
    }

    #[test]
    fn test_tool_count_with_required_fields_counts_only_tools_with_fields() {
        let mut reg = ToolRegistry::new();
        reg.register(
            ToolSpec::new("t1", "d", |_| serde_json::json!({}))
                .with_required_fields(["query"]),
        );
        reg.register(ToolSpec::new("t2", "d", |_| serde_json::json!({}))); // no required
        reg.register(
            ToolSpec::new("t3", "d", |_| serde_json::json!({}))
                .with_required_fields(["url", "method"]),
        );
        assert_eq!(reg.tool_count_with_required_fields(), 2);
    }

    // ── Round 27: ToolRegistry::names ─────────────────────────────────────────

    #[test]
    fn test_tool_registry_names_empty_when_no_tools() {
        let reg = ToolRegistry::new();
        assert!(reg.names().is_empty());
    }

    #[test]
    fn test_tool_registry_names_sorted_alphabetically() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("zebra", "d", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("alpha", "d", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("mango", "d", |_| serde_json::json!({})));
        assert_eq!(reg.names(), vec!["alpha", "mango", "zebra"]);
    }

    // ── Round 28: tool_names_starting_with ────────────────────────────────────

    #[test]
    fn test_tool_names_starting_with_empty_when_no_match() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("search", "d", |_| serde_json::json!({})));
        assert!(reg.tool_names_starting_with("calc").is_empty());
    }

    #[test]
    fn test_tool_names_starting_with_returns_sorted_matches() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("db_write", "d", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("db_read", "d", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("cache_get", "d", |_| serde_json::json!({})));
        let results = reg.tool_names_starting_with("db_");
        assert_eq!(results, vec!["db_read", "db_write"]);
    }

    // ── Round 29: description_for ─────────────────────────────────────────────

    #[test]
    fn test_tool_registry_description_for_none_when_missing() {
        let reg = ToolRegistry::new();
        assert!(reg.description_for("unknown").is_none());
    }

    #[test]
    fn test_tool_registry_description_for_returns_description() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("search", "Find web results", |_| serde_json::json!({})));
        assert_eq!(reg.description_for("search"), Some("Find web results"));
    }

    // ── Round 30: count_with_description_containing ───────────────────────────

    #[test]
    fn test_count_with_description_containing_zero_when_no_match() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "database query", |_| serde_json::json!({})));
        assert_eq!(reg.count_with_description_containing("weather"), 0);
    }

    #[test]
    fn test_count_with_description_containing_case_insensitive() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "Search the WEB", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("t2", "web scraper tool", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("t3", "database lookup", |_| serde_json::json!({})));
        assert_eq!(reg.count_with_description_containing("web"), 2);
    }

    #[test]
    fn test_unregister_all_clears_all_tools() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "tool one", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("t2", "tool two", |_| serde_json::json!({})));
        assert_eq!(reg.tool_count(), 2);
        reg.unregister_all();
        assert_eq!(reg.tool_count(), 0);
    }

    #[test]
    fn test_tool_names_with_keyword_returns_matching_tool_names() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("search", "search the web for info", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("db", "query database records", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("web-fetch", "fetch a WEB page", |_| serde_json::json!({})));
        let mut names = reg.tool_names_with_keyword("web");
        names.sort_unstable();
        assert_eq!(names, vec!["search", "web-fetch"]);
    }

    #[test]
    fn test_tool_names_with_keyword_no_match_returns_empty() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t", "some tool", |_| serde_json::json!({})));
        assert!(reg.tool_names_with_keyword("missing").is_empty());
    }

    #[test]
    fn test_all_descriptions_returns_sorted_descriptions() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "z description", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("t2", "a description", |_| serde_json::json!({})));
        assert_eq!(reg.all_descriptions(), vec!["a description", "z description"]);
    }

    #[test]
    fn test_all_descriptions_empty_registry_returns_empty() {
        let reg = ToolRegistry::new();
        assert!(reg.all_descriptions().is_empty());
    }

    #[test]
    fn test_longest_description_returns_longest() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "short", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("t2", "a much longer description here", |_| serde_json::json!({})));
        assert_eq!(reg.longest_description(), Some("a much longer description here"));
    }

    #[test]
    fn test_longest_description_empty_registry_returns_none() {
        let reg = ToolRegistry::new();
        assert!(reg.longest_description().is_none());
    }

    #[test]
    fn test_names_containing_returns_sorted_matching_names() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("search-web", "search tool", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("web-fetch", "fetch tool", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("db-query", "database tool", |_| serde_json::json!({})));
        let names = reg.names_containing("web");
        assert_eq!(names, vec!["search-web", "web-fetch"]);
    }

    #[test]
    fn test_names_containing_no_match_returns_empty() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t", "tool", |_| serde_json::json!({})));
        assert!(reg.names_containing("missing").is_empty());
    }

    // ── Round 36 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_avg_description_length_returns_mean_byte_length() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("a", "ab", |_| serde_json::json!({})));    // 2 bytes
        reg.register(ToolSpec::new("b", "abcd", |_| serde_json::json!({}))); // 4 bytes
        let avg = reg.avg_description_length();
        assert!((avg - 3.0).abs() < 1e-9);
    }

    #[test]
    fn test_avg_description_length_returns_zero_when_empty() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.avg_description_length(), 0.0);
    }

    // ── Round 37 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_shortest_description_returns_shortest_string() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("a", "hello world", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("b", "hi", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("c", "greetings", |_| serde_json::json!({})));
        assert_eq!(reg.shortest_description(), Some("hi"));
    }

    #[test]
    fn test_shortest_description_returns_none_when_empty() {
        let reg = ToolRegistry::new();
        assert!(reg.shortest_description().is_none());
    }

    // ── Round 38 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_tool_names_sorted_returns_names_in_alphabetical_order() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("zap", "z tool", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("alpha", "a tool", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("middle", "m tool", |_| serde_json::json!({})));
        assert_eq!(reg.tool_names_sorted(), vec!["alpha", "middle", "zap"]);
    }

    #[test]
    fn test_tool_names_sorted_empty_returns_empty() {
        let reg = ToolRegistry::new();
        assert!(reg.tool_names_sorted().is_empty());
    }

    // ── Round 39 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_description_contains_count_counts_matching_descriptions() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("a", "search the web", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("b", "write to disk", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("c", "search and filter", |_| serde_json::json!({})));
        assert_eq!(reg.description_contains_count("search"), 2);
        assert_eq!(reg.description_contains_count("SEARCH"), 2);
        assert_eq!(reg.description_contains_count("missing"), 0);
    }

    #[test]
    fn test_description_contains_count_zero_when_empty() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.description_contains_count("anything"), 0);
    }

    // ── Round 40: ReActStep::summary ─────────────────────────────────────────

    #[test]
    fn test_react_step_summary_tool_kind() {
        let step = ReActStep::new("I need to search", r#"{"tool":"search","q":"rust"}"#, "results");
        let s = step.summary();
        assert!(s.starts_with("[TOOL]"));
        assert!(s.contains("I need to search"));
        assert!(s.contains("results"));
    }

    #[test]
    fn test_react_step_summary_final_kind() {
        let step = ReActStep::new("Done", "FINAL_ANSWER hello", "");
        let s = step.summary();
        assert!(s.starts_with("[FINAL]"));
        assert!(s.contains("FINAL_ANSWER hello"));
    }

    #[test]
    fn test_react_step_summary_truncates_long_fields() {
        let long = "a".repeat(100);
        let step = ReActStep::new(long.clone(), long.clone(), long.clone());
        let s = step.summary();
        // Each preview is capped at 40 chars plus "…"
        assert!(s.contains(''));
    }

    #[test]
    fn test_react_step_summary_empty_fields() {
        let step = ReActStep::new("", "", "");
        let s = step.summary();
        assert!(s.contains("[TOOL]"));
    }

    // ── Round 40 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_tool_registry_total_description_bytes_sums_correctly() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("a", "hello", |_| serde_json::json!({}))); // 5 bytes
        reg.register(ToolSpec::new("b", "world!", |_| serde_json::json!({}))); // 6 bytes
        assert_eq!(reg.total_description_bytes(), 11);
    }

    #[test]
    fn test_tool_registry_total_description_bytes_empty_returns_zero() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.total_description_bytes(), 0);
    }

    // ── Round 40 (continued): thought_word_count, clone_with_system_prompt, clone_with_max_iterations ──

    #[test]
    fn test_react_step_thought_word_count_counts_words() {
        let step = ReActStep::new("hello world foo", "act", "obs");
        assert_eq!(step.thought_word_count(), 3);
    }

    #[test]
    fn test_react_step_thought_word_count_empty_thought_returns_zero() {
        let step = ReActStep::new("", "act", "obs");
        assert_eq!(step.thought_word_count(), 0);
    }

    #[test]
    fn test_agent_config_clone_with_system_prompt_changes_only_prompt() {
        let original = AgentConfig::new(5, "gpt-4");
        let cloned = original.clone_with_system_prompt("Custom prompt.");
        assert_eq!(cloned.system_prompt, "Custom prompt.");
        assert_eq!(cloned.model, "gpt-4");
        assert_eq!(cloned.max_iterations, 5);
    }

    #[test]
    fn test_agent_config_clone_with_system_prompt_leaves_original_unchanged() {
        let original = AgentConfig::new(3, "claude").with_system_prompt("Original.");
        let _cloned = original.clone_with_system_prompt("New.");
        assert_eq!(original.system_prompt, "Original.");
    }

    #[test]
    fn test_agent_config_clone_with_max_iterations_changes_only_iterations() {
        let original = AgentConfig::new(5, "claude-3");
        let cloned = original.clone_with_max_iterations(20);
        assert_eq!(cloned.max_iterations, 20);
        assert_eq!(cloned.model, "claude-3");
    }

    #[test]
    fn test_agent_config_clone_with_max_iterations_leaves_original_unchanged() {
        let original = AgentConfig::new(5, "claude-3");
        let _cloned = original.clone_with_max_iterations(10);
        assert_eq!(original.max_iterations, 5);
    }

    // ── Round 41: Message Display and From tuples ─────────────────────────────

    #[test]
    fn test_message_display_user_role() {
        let m = Message::user("hello world");
        assert_eq!(m.to_string(), "user: hello world");
    }

    #[test]
    fn test_message_display_assistant_role() {
        let m = Message::assistant("I can help");
        assert_eq!(m.to_string(), "assistant: I can help");
    }

    #[test]
    fn test_message_display_system_role() {
        let m = Message::system("Be helpful");
        assert_eq!(m.to_string(), "system: Be helpful");
    }

    #[test]
    fn test_message_from_role_string_tuple() {
        let m = Message::from((Role::User, "hello".to_owned()));
        assert_eq!(m.role, Role::User);
        assert_eq!(m.content, "hello");
    }

    #[test]
    fn test_message_from_role_str_ref_tuple() {
        let m = Message::from((Role::Assistant, "ok"));
        assert_eq!(m.role, Role::Assistant);
        assert_eq!(m.content, "ok");
    }

    #[test]
    fn test_message_into_from_system_tuple() {
        let m: Message = (Role::System, "sys prompt").into();
        assert!(m.is_system());
        assert_eq!(m.content(), "sys prompt");
    }

    // ── Round 41 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_tool_registry_shortest_description_length_returns_min_bytes() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("a", "hello world", |_| serde_json::json!({}))); // 11
        reg.register(ToolSpec::new("b", "hi", |_| serde_json::json!({}))); // 2
        reg.register(ToolSpec::new("c", "greetings!", |_| serde_json::json!({}))); // 10
        assert_eq!(reg.shortest_description_length(), 2);
    }

    #[test]
    fn test_tool_registry_shortest_description_length_empty_returns_zero() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.shortest_description_length(), 0);
    }

    // ── Round 41: ToolRegistry::tool_count_with_validators ────────────────────

    struct AlwaysOk;
    impl ToolValidator for AlwaysOk {
        fn validate(&self, _args: &Value) -> Result<(), AgentRuntimeError> {
            Ok(())
        }
    }

    #[test]
    fn test_tool_count_with_validators_counts_tools_that_have_validators() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("a", "desc", |_| serde_json::json!({}))
            .with_validators(vec![Box::new(AlwaysOk)]));
        reg.register(ToolSpec::new("b", "desc", |_| serde_json::json!({}))); // no validators
        reg.register(ToolSpec::new("c", "desc", |_| serde_json::json!({}))
            .with_validators(vec![Box::new(AlwaysOk)]));
        assert_eq!(reg.tool_count_with_validators(), 2);
    }

    #[test]
    fn test_tool_count_with_validators_zero_when_none_have_validators() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("a", "desc", |_| serde_json::json!({})));
        assert_eq!(reg.tool_count_with_validators(), 0);
    }

    #[test]
    fn test_tool_count_with_validators_zero_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.tool_count_with_validators(), 0);
    }

    // ── Round 42: ToolRegistry::longest_description_length ────────────────────

    #[test]
    fn test_longest_description_length_returns_max_bytes() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("a", "hi", |_| serde_json::json!({}))); // 2
        reg.register(ToolSpec::new("b", "hello world", |_| serde_json::json!({}))); // 11
        reg.register(ToolSpec::new("c", "yo", |_| serde_json::json!({}))); // 2
        assert_eq!(reg.longest_description_length(), 11);
    }

    #[test]
    fn test_longest_description_length_zero_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.longest_description_length(), 0);
    }

    // ── Round 43: ToolRegistry::tools_with_required_field ─────────────────────

    #[test]
    fn test_tools_with_required_field_returns_matching_tools() {
        let mut reg = ToolRegistry::new();
        reg.register(
            ToolSpec::new("a", "desc", |_| serde_json::json!({}))
                .with_required_fields(vec!["query".to_string()]),
        );
        reg.register(ToolSpec::new("b", "desc", |_| serde_json::json!({}))); // no required fields
        reg.register(
            ToolSpec::new("c", "desc", |_| serde_json::json!({}))
                .with_required_fields(vec!["query".to_string(), "limit".to_string()]),
        );
        let result = reg.tools_with_required_field("query");
        assert_eq!(result.len(), 2);
        assert!(result.iter().any(|t| t.name == "a"));
        assert!(result.iter().any(|t| t.name == "c"));
    }

    #[test]
    fn test_tools_with_required_field_empty_when_no_match() {
        let mut reg = ToolRegistry::new();
        reg.register(
            ToolSpec::new("a", "desc", |_| serde_json::json!({}))
                .with_required_fields(vec!["x".to_string()]),
        );
        assert!(reg.tools_with_required_field("missing").is_empty());
    }

    #[test]
    fn test_tools_with_required_field_empty_registry_returns_empty() {
        let reg = ToolRegistry::new();
        assert!(reg.tools_with_required_field("any").is_empty());
    }

    // ── Round 45: observation_word_count, tool_with_most_required_fields ───────

    #[test]
    fn test_observation_word_count_counts_words() {
        let step = ReActStep {
            thought: "t".into(),
            action: "a".into(),
            observation: "hello world foo".into(),
            step_duration_ms: 0,
        };
        assert_eq!(step.observation_word_count(), 3);
    }

    #[test]
    fn test_observation_word_count_zero_for_empty() {
        let step = ReActStep {
            thought: "t".into(),
            action: "a".into(),
            observation: "".into(),
            step_duration_ms: 0,
        };
        assert_eq!(step.observation_word_count(), 0);
    }

    #[test]
    fn test_tool_with_most_required_fields_returns_correct_tool() {
        let mut reg = ToolRegistry::new();
        reg.register(
            ToolSpec::new("few", "d", |_| serde_json::json!({}))
                .with_required_fields(vec!["a".to_string()]),
        );
        reg.register(
            ToolSpec::new("many", "d", |_| serde_json::json!({}))
                .with_required_fields(vec!["a".to_string(), "b".to_string(), "c".to_string()]),
        );
        let winner = reg.tool_with_most_required_fields().unwrap();
        assert_eq!(winner.name, "many");
    }

    #[test]
    fn test_tool_with_most_required_fields_returns_none_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert!(reg.tool_with_most_required_fields().is_none());
    }

    // ── Round 45: tool_count_above_desc_bytes ──────────────────────────────────

    #[test]
    fn test_tool_count_above_desc_bytes_counts_tools_with_long_descriptions() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("short", "hi", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("long", "a much longer description here", |_| serde_json::json!({})));
        assert_eq!(reg.tool_count_above_desc_bytes(2), 1);
    }

    #[test]
    fn test_tool_count_above_desc_bytes_zero_when_none_exceed() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t", "ab", |_| serde_json::json!({})));
        assert_eq!(reg.tool_count_above_desc_bytes(100), 0);
    }

    #[test]
    fn test_tool_count_above_desc_bytes_zero_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.tool_count_above_desc_bytes(0), 0);
    }

    // ── Round 44: tool_names_with_required_fields ──────────────────────────────

    #[test]
    fn test_tool_names_with_required_fields_returns_sorted_names() {
        let mut reg = ToolRegistry::new();
        reg.register(
            ToolSpec::new("b", "desc", |_| serde_json::json!({}))
                .with_required_fields(vec!["x".to_string()]),
        );
        reg.register(
            ToolSpec::new("a", "desc", |_| serde_json::json!({}))
                .with_required_fields(vec!["y".to_string()]),
        );
        reg.register(ToolSpec::new("c", "desc", |_| serde_json::json!({}))); // no required fields
        assert_eq!(reg.tool_names_with_required_fields(), vec!["a", "b"]);
    }

    #[test]
    fn test_tool_names_with_required_fields_empty_when_none_have_fields() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("a", "desc", |_| serde_json::json!({})));
        assert!(reg.tool_names_with_required_fields().is_empty());
    }

    #[test]
    fn test_tool_names_with_required_fields_empty_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert!(reg.tool_names_with_required_fields().is_empty());
    }

    // ── Round 46: tools_without_required_fields ────────────────────────────────

    #[test]
    fn test_tools_without_required_fields_returns_tools_with_no_required_fields() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("no-req", "desc", |_| serde_json::json!({})));
        reg.register(
            ToolSpec::new("with-req", "desc", |_| serde_json::json!({}))
                .with_required_fields(vec!["x".to_string()]),
        );
        let result = reg.tools_without_required_fields();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "no-req");
    }

    #[test]
    fn test_tools_without_required_fields_empty_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert!(reg.tools_without_required_fields().is_empty());
    }

    // ── Round 47: avg_required_fields_count ───────────────────────────────────

    #[test]
    fn test_avg_required_fields_count_computes_mean() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "d", |_| serde_json::json!({})));
        reg.register(
            ToolSpec::new("t2", "d", |_| serde_json::json!({}))
                .with_required_fields(vec!["a".to_string(), "b".to_string()]),
        );
        // 0 + 2 = 2 total, 2 tools → avg = 1.0
        assert!((reg.avg_required_fields_count() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_avg_required_fields_count_zero_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.avg_required_fields_count(), 0.0);
    }

    // ── Round 47: thought_is_empty, model_is, loop_timeout_ms, total_timeout_ms ──

    #[test]
    fn test_thought_is_empty_true_for_empty_thought() {
        let step = ReActStep::new("", "action", "obs");
        assert!(step.thought_is_empty());
    }

    #[test]
    fn test_thought_is_empty_true_for_whitespace_only() {
        let step = ReActStep::new("   ", "action", "obs");
        assert!(step.thought_is_empty());
    }

    #[test]
    fn test_thought_is_empty_false_for_nonempty_thought() {
        let step = ReActStep::new("I need to search", "action", "obs");
        assert!(!step.thought_is_empty());
    }

    #[test]
    fn test_model_is_true_for_matching_name() {
        let config = AgentConfig::new(10, "claude-sonnet-4-6");
        assert!(config.model_is("claude-sonnet-4-6"));
    }

    #[test]
    fn test_model_is_false_for_different_name() {
        let config = AgentConfig::new(10, "claude-opus-4-6");
        assert!(!config.model_is("claude-sonnet-4-6"));
    }

    #[test]
    fn test_loop_timeout_ms_returns_zero_when_not_configured() {
        let config = AgentConfig::new(10, "m");
        assert_eq!(config.loop_timeout_ms(), 0);
    }

    #[test]
    fn test_loop_timeout_ms_returns_millis_when_configured() {
        let config = AgentConfig::new(10, "m")
            .with_loop_timeout(std::time::Duration::from_millis(5000));
        assert_eq!(config.loop_timeout_ms(), 5000);
    }

    #[test]
    fn test_total_timeout_ms_zero_when_neither_configured() {
        let config = AgentConfig::new(10, "m");
        assert_eq!(config.total_timeout_ms(), 0);
    }

    #[test]
    fn test_total_timeout_ms_includes_loop_and_request_budgets() {
        let config = AgentConfig::new(4, "m")
            .with_loop_timeout(std::time::Duration::from_millis(1000))
            .with_request_timeout(std::time::Duration::from_millis(500));
        // 1000 + 4 * 500 = 3000
        assert_eq!(config.total_timeout_ms(), 3000);
    }

    // ── Round 48: tool_descriptions_total_words ────────────────────────────────

    #[test]
    fn test_tool_descriptions_total_words_sums_words() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "one two three", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("t2", "four five", |_| serde_json::json!({})));
        assert_eq!(reg.tool_descriptions_total_words(), 5);
    }

    #[test]
    fn test_tool_descriptions_total_words_zero_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.tool_descriptions_total_words(), 0);
    }

    // ── Round 49: content_starts_with, system_prompt_is_empty ─────────────────

    #[test]
    fn test_content_starts_with_true_for_matching_prefix() {
        let msg = Message::user("Hello, world!");
        assert!(msg.content_starts_with("Hello"));
    }

    #[test]
    fn test_content_starts_with_false_for_non_matching_prefix() {
        let msg = Message::user("Hello, world!");
        assert!(!msg.content_starts_with("World"));
    }

    #[test]
    fn test_content_starts_with_empty_prefix_always_true() {
        let msg = Message::assistant("anything");
        assert!(msg.content_starts_with(""));
    }

    #[test]
    fn test_system_prompt_is_empty_true_for_blank_prompt() {
        let cfg = AgentConfig::new(5, "m").with_system_prompt("");
        assert!(cfg.system_prompt_is_empty());
    }

    #[test]
    fn test_system_prompt_is_empty_false_when_set() {
        let cfg = AgentConfig::new(5, "m").with_system_prompt("You are helpful.");
        assert!(!cfg.system_prompt_is_empty());
    }

    // ── Round 49: has_tools_with_empty_descriptions, total_required_fields ─────

    #[test]
    fn test_has_tools_with_empty_descriptions_true_when_blank_present() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "  ", |_| serde_json::json!({})));
        assert!(reg.has_tools_with_empty_descriptions());
    }

    #[test]
    fn test_has_tools_with_empty_descriptions_false_when_all_filled() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "desc", |_| serde_json::json!({})));
        assert!(!reg.has_tools_with_empty_descriptions());
    }

    #[test]
    fn test_total_required_fields_sums_across_tools() {
        let mut reg = ToolRegistry::new();
        reg.register(
            ToolSpec::new("t1", "d", |_| serde_json::json!({}))
                .with_required_fields(vec!["a".to_string(), "b".to_string()]),
        );
        reg.register(
            ToolSpec::new("t2", "d", |_| serde_json::json!({}))
                .with_required_fields(vec!["c".to_string()]),
        );
        assert_eq!(reg.total_required_fields(), 3);
    }

    #[test]
    fn test_total_required_fields_zero_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.total_required_fields(), 0);
    }

    // ── Round 50: tools_with_description_longer_than, max/min_description_bytes ─

    #[test]
    fn test_tools_with_description_longer_than_returns_matching_tools() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("short", "hi", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("long", "a much longer description", |_| serde_json::json!({})));
        let names = reg.tools_with_description_longer_than(5);
        assert_eq!(names, vec!["long"]);
    }

    #[test]
    fn test_max_description_bytes_returns_longest() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "hi", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("t2", "hello world", |_| serde_json::json!({})));
        assert_eq!(reg.max_description_bytes(), 11);
    }

    #[test]
    fn test_min_description_bytes_returns_shortest() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "hi", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("t2", "hello world", |_| serde_json::json!({})));
        assert_eq!(reg.min_description_bytes(), 2);
    }

    #[test]
    fn test_max_description_bytes_zero_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert_eq!(reg.max_description_bytes(), 0);
    }

    // ── Round 50: has_tool_with_description_containing ────────────────────────

    #[test]
    fn test_has_tool_with_description_containing_true_when_keyword_found() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("search", "search the web", |_| serde_json::json!({})));
        assert!(reg.has_tool_with_description_containing("web"));
    }

    #[test]
    fn test_has_tool_with_description_containing_false_when_keyword_absent() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("search", "search the web", |_| serde_json::json!({})));
        assert!(!reg.has_tool_with_description_containing("database"));
    }

    #[test]
    fn test_has_tool_with_description_containing_false_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert!(!reg.has_tool_with_description_containing("anything"));
    }

    // ── Round 47: system_prompt_word_count ────────────────────────────────────

    #[test]
    fn test_system_prompt_word_count_counts_words() {
        let cfg = AgentConfig::new(10, "m")
            .with_system_prompt("You are a helpful AI agent.");
        assert_eq!(cfg.system_prompt_word_count(), 6);
    }

    #[test]
    fn test_system_prompt_word_count_zero_for_empty_prompt() {
        let cfg = AgentConfig::new(10, "m").with_system_prompt("");
        assert_eq!(cfg.system_prompt_word_count(), 0);
    }

    // ── Round 51: description_starts_with_any ─────────────────────────────────

    #[test]
    fn test_description_starts_with_any_true_when_prefix_matches() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "Search the web", |_| serde_json::json!({})));
        assert!(reg.description_starts_with_any(&["Search", "Write"]));
    }

    #[test]
    fn test_description_starts_with_any_false_when_no_prefix_matches() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("t1", "Read a file", |_| serde_json::json!({})));
        assert!(!reg.description_starts_with_any(&["Search", "Write"]));
    }

    #[test]
    fn test_description_starts_with_any_false_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert!(!reg.description_starts_with_any(&["Search"]));
    }

    // ── Round 52 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_combined_byte_length_sums_all_fields() {
        let step = ReActStep::new("hello", "search", "result");
        assert_eq!(step.combined_byte_length(), 5 + 6 + 6);
    }

    #[test]
    fn test_combined_byte_length_zero_for_empty_step() {
        let step = ReActStep::new("", "", "");
        assert_eq!(step.combined_byte_length(), 0);
    }

    #[test]
    fn test_iteration_budget_remaining_full_when_no_steps_done() {
        let cfg = AgentConfig::new(10, "m");
        assert_eq!(cfg.iteration_budget_remaining(0), 10);
    }

    #[test]
    fn test_iteration_budget_remaining_decreases_with_steps() {
        let cfg = AgentConfig::new(10, "m");
        assert_eq!(cfg.iteration_budget_remaining(7), 3);
    }

    #[test]
    fn test_iteration_budget_remaining_saturates_at_zero() {
        let cfg = AgentConfig::new(5, "m");
        assert_eq!(cfg.iteration_budget_remaining(10), 0);
    }

    #[test]
    fn test_has_all_tools_true_when_all_registered() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("search", "Search", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("write", "Write", |_| serde_json::json!({})));
        assert!(reg.has_all_tools(&["search", "write"]));
    }

    #[test]
    fn test_has_all_tools_false_when_one_missing() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("search", "Search", |_| serde_json::json!({})));
        assert!(!reg.has_all_tools(&["search", "write"]));
    }

    #[test]
    fn test_has_all_tools_true_for_empty_slice() {
        let reg = ToolRegistry::new();
        assert!(reg.has_all_tools(&[]));
    }

    // ── Round 52: tool_by_name, tools_without_validators ──────────────────────

    #[test]
    fn test_tool_by_name_returns_tool_when_present() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("search", "Search the web", |_| serde_json::json!({})));
        assert!(reg.tool_by_name("search").is_some());
        assert_eq!(reg.tool_by_name("search").unwrap().name, "search");
    }

    #[test]
    fn test_tool_by_name_returns_none_when_absent() {
        let reg = ToolRegistry::new();
        assert!(reg.tool_by_name("missing").is_none());
    }

    #[test]
    fn test_tools_without_validators_returns_unvalidated_tools() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("a", "Tool A", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("b", "Tool B", |_| serde_json::json!({})));
        let names = reg.tools_without_validators();
        assert!(names.contains(&"a"));
        assert!(names.contains(&"b"));
    }

    #[test]
    fn test_tools_without_validators_empty_for_empty_registry() {
        let reg = ToolRegistry::new();
        assert!(reg.tools_without_validators().is_empty());
    }

    // ── Round 53 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_action_is_empty_true_for_empty_action() {
        let step = ReActStep::new("thought", "", "obs");
        assert!(step.action_is_empty());
    }

    #[test]
    fn test_action_is_empty_false_for_nonempty_action() {
        let step = ReActStep::new("thought", "search", "obs");
        assert!(!step.action_is_empty());
    }

    #[test]
    fn test_action_is_empty_true_for_whitespace_only() {
        let step = ReActStep::new("thought", "   ", "obs");
        assert!(step.action_is_empty());
    }

    #[test]
    fn test_is_minimal_true_for_single_iteration_no_prompt() {
        let cfg = AgentConfig::new(1, "m").with_system_prompt("");
        assert!(cfg.is_minimal());
    }

    #[test]
    fn test_is_minimal_false_when_max_iterations_above_one() {
        let cfg = AgentConfig::new(5, "m");
        assert!(!cfg.is_minimal());
    }

    #[test]
    fn test_is_minimal_false_when_system_prompt_set() {
        let cfg = AgentConfig::new(1, "m").with_system_prompt("prompt");
        assert!(!cfg.is_minimal());
    }

    // ── Round 48 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_model_starts_with_true_when_prefix_matches() {
        let cfg = AgentConfig::new(3, "claude-3-opus");
        assert!(cfg.model_starts_with("claude"));
    }

    #[test]
    fn test_model_starts_with_false_when_prefix_differs() {
        let cfg = AgentConfig::new(3, "gpt-4o");
        assert!(!cfg.model_starts_with("claude"));
    }

    #[test]
    fn test_tools_with_required_fields_count_correct() {
        let mut registry = ToolRegistry::new();
        registry.register(ToolSpec::new(
            "search",
            "desc",
            |_| serde_json::json!("ok"),
        ).with_required_fields(vec!["query".to_string()]));
        registry.register(ToolSpec::new(
            "noop",
            "desc",
            |_| serde_json::json!("ok"),
        ));
        assert_eq!(registry.tools_with_required_fields_count(), 1);
    }

    #[test]
    fn test_tools_with_required_fields_count_zero_for_empty_registry() {
        let registry = ToolRegistry::new();
        assert_eq!(registry.tools_with_required_fields_count(), 0);
    }

    // ── Round 54 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_tool_names_with_prefix_returns_matching_names() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("search_web", "desc", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("search_code", "desc", |_| serde_json::json!({})));
        reg.register(ToolSpec::new("write_file", "desc", |_| serde_json::json!({})));
        let names = reg.tool_names_with_prefix("search_");
        assert_eq!(names, vec!["search_code", "search_web"]);
    }

    #[test]
    fn test_tool_names_with_prefix_empty_when_no_match() {
        let mut reg = ToolRegistry::new();
        reg.register(ToolSpec::new("write_file", "desc", |_| serde_json::json!({})));
        assert!(reg.tool_names_with_prefix("search_").is_empty());
    }

    #[test]
    fn test_exceeds_iteration_limit_true_when_at_limit() {
        let cfg = AgentConfig::new(5, "m");
        assert!(cfg.exceeds_iteration_limit(5));
        assert!(cfg.exceeds_iteration_limit(10));
    }

    #[test]
    fn test_exceeds_iteration_limit_false_when_below_limit() {
        let cfg = AgentConfig::new(5, "m");
        assert!(!cfg.exceeds_iteration_limit(4));
        assert!(!cfg.exceeds_iteration_limit(0));
    }

    // ── Round 57 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_total_word_count_sums_all_fields() {
        let step = ReActStep::new("one two", "three", "four five six");
        assert_eq!(step.total_word_count(), 6);
    }

    #[test]
    fn test_total_word_count_zero_for_empty_step() {
        let step = ReActStep::new("", "", "");
        assert_eq!(step.total_word_count(), 0);
    }

    #[test]
    fn test_token_budget_configured_true_when_max_tokens_set() {
        let cfg = AgentConfig::new(3, "m").with_max_tokens(100);
        assert!(cfg.token_budget_configured());
    }

    #[test]
    fn test_token_budget_configured_true_when_max_context_chars_set() {
        let cfg = AgentConfig::new(3, "m").with_max_context_chars(200);
        assert!(cfg.token_budget_configured());
    }

    #[test]
    fn test_token_budget_configured_false_when_neither_set() {
        let cfg = AgentConfig::new(3, "m");
        assert!(!cfg.token_budget_configured());
    }

    // ── Round 58 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_is_complete_true_when_all_fields_nonempty() {
        let step = ReActStep::new("thought", "action", "observation");
        assert!(step.is_complete());
    }

    #[test]
    fn test_is_complete_false_when_observation_empty() {
        let step = ReActStep::new("thought", "action", "");
        assert!(!step.is_complete());
    }

    #[test]
    fn test_is_complete_false_when_action_empty() {
        let step = ReActStep::new("thought", "", "obs");
        assert!(!step.is_complete());
    }

    #[test]
    fn test_max_tokens_or_default_returns_value_when_set() {
        let cfg = AgentConfig::new(3, "m").with_max_tokens(512);
        assert_eq!(cfg.max_tokens_or_default(100), 512);
    }

    #[test]
    fn test_max_tokens_or_default_returns_default_when_unset() {
        let cfg = AgentConfig::new(3, "m");
        assert_eq!(cfg.max_tokens_or_default(256), 256);
    }

    // ── Round 59 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_observation_starts_with_true_for_matching_prefix() {
        let step = ReActStep::new("t", "a", "Result: ok");
        assert!(step.observation_starts_with("Result:"));
    }

    #[test]
    fn test_observation_starts_with_false_for_non_matching_prefix() {
        let step = ReActStep::new("t", "a", "Error: failed");
        assert!(!step.observation_starts_with("Result:"));
    }

    #[test]
    fn test_effective_temperature_returns_configured_value() {
        let cfg = AgentConfig::new(3, "m").with_temperature(0.5);
        assert!((cfg.effective_temperature() - 0.5_f32).abs() < 1e-6);
    }

    #[test]
    fn test_effective_temperature_returns_default_when_unset() {
        let cfg = AgentConfig::new(3, "m");
        assert!((cfg.effective_temperature() - 1.0_f32).abs() < 1e-6);
    }

    // ── Round 62: ReActStep helpers ───────────────────────────────────────────

    #[test]
    fn test_action_word_count_returns_words_in_action() {
        let step = ReActStep::new("think", "do this now", "ok");
        assert_eq!(step.action_word_count(), 3);
    }

    #[test]
    fn test_action_word_count_zero_for_empty_action() {
        let step = ReActStep::new("think", "", "ok");
        assert_eq!(step.action_word_count(), 0);
    }

    #[test]
    fn test_thought_byte_len_matches_string_len() {
        let step = ReActStep::new("hello", "act", "obs");
        assert_eq!(step.thought_byte_len(), "hello".len());
    }

    #[test]
    fn test_action_byte_len_matches_string_len() {
        let step = ReActStep::new("think", "do it", "obs");
        assert_eq!(step.action_byte_len(), "do it".len());
    }

    #[test]
    fn test_has_empty_fields_true_when_observation_empty() {
        let step = ReActStep::new("think", "act", "");
        assert!(step.has_empty_fields());
    }

    #[test]
    fn test_has_empty_fields_false_when_all_populated() {
        let step = ReActStep::new("think", "act", "obs");
        assert!(!step.has_empty_fields());
    }

    // ── Round 62: AgentConfig helpers ─────────────────────────────────────────

    #[test]
    fn test_system_prompt_starts_with_true_for_matching_prefix() {
        let cfg = AgentConfig::new(3, "m").with_system_prompt("You are a helpful assistant.");
        assert!(cfg.system_prompt_starts_with("You are"));
    }

    #[test]
    fn test_system_prompt_starts_with_false_for_non_matching_prefix() {
        let cfg = AgentConfig::new(3, "m").with_system_prompt("Hello world");
        assert!(!cfg.system_prompt_starts_with("Goodbye"));
    }

    #[test]
    fn test_max_iterations_above_true_when_greater() {
        let cfg = AgentConfig::new(5, "m");
        assert!(cfg.max_iterations_above(4));
    }

    #[test]
    fn test_max_iterations_above_false_when_equal() {
        let cfg = AgentConfig::new(5, "m");
        assert!(!cfg.max_iterations_above(5));
    }

    #[test]
    fn test_stop_sequences_contain_true_for_present_sequence() {
        let cfg = AgentConfig::new(3, "m")
            .with_stop_sequences(vec!["STOP".to_string(), "END".to_string()]);
        assert!(cfg.stop_sequences_contain("STOP"));
    }

    #[test]
    fn test_stop_sequences_contain_false_for_absent_sequence() {
        let cfg = AgentConfig::new(3, "m")
            .with_stop_sequences(vec!["STOP".to_string()]);
        assert!(!cfg.stop_sequences_contain("END"));
    }

    #[test]
    fn test_stop_sequences_contain_false_for_empty_config() {
        let cfg = AgentConfig::new(3, "m");
        assert!(!cfg.stop_sequences_contain("STOP"));
    }

    // ── Round 63: observation_byte_len, all_fields_have_words, system_prompt_byte_len, has_valid_temperature ──

    #[test]
    fn test_observation_byte_len_matches_string_len() {
        let step = ReActStep::new("t", "a", "result");
        assert_eq!(step.observation_byte_len(), "result".len());
    }

    #[test]
    fn test_observation_byte_len_zero_for_empty() {
        let step = ReActStep::new("t", "a", "");
        assert_eq!(step.observation_byte_len(), 0);
    }

    #[test]
    fn test_all_fields_have_words_true_when_all_populated() {
        let step = ReActStep::new("think", "act", "obs");
        assert!(step.all_fields_have_words());
    }

    #[test]
    fn test_all_fields_have_words_false_when_action_empty() {
        let step = ReActStep::new("think", "", "obs");
        assert!(!step.all_fields_have_words());
    }

    #[test]
    fn test_system_prompt_byte_len_returns_length() {
        let cfg = AgentConfig::new(3, "m").with_system_prompt("Hello!");
        assert_eq!(cfg.system_prompt_byte_len(), "Hello!".len());
    }

    #[test]
    fn test_system_prompt_byte_len_default_is_nonzero() {
        let cfg = AgentConfig::new(3, "m");
        // Default system prompt is "You are a helpful AI agent."
        assert_eq!(cfg.system_prompt_byte_len(), "You are a helpful AI agent.".len());
    }

    #[test]
    fn test_has_valid_temperature_true_for_in_range() {
        let cfg = AgentConfig::new(3, "m").with_temperature(0.7);
        assert!(cfg.has_valid_temperature());
    }

    #[test]
    fn test_has_valid_temperature_false_when_unset() {
        let cfg = AgentConfig::new(3, "m");
        assert!(!cfg.has_valid_temperature());
    }

    #[test]
    fn test_has_valid_temperature_true_at_boundaries() {
        assert!(AgentConfig::new(3, "m").with_temperature(0.0).has_valid_temperature());
        assert!(AgentConfig::new(3, "m").with_temperature(2.0).has_valid_temperature());
    }
}