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
//! # Module: Metrics
//!
//! Runtime observability counters for `AgentRuntime`.
//! All global counters use atomics for lock-free, thread-safe increment/read.
//! Per-tool counters use a `Mutex<HashMap>` to avoid requiring a concurrent
//! map dependency.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

// ── LatencyHistogram ──────────────────────────────────────────────────────────

/// A simple fixed-bucket latency histogram.
///
/// Bucket upper bounds are **inclusive** (i.e., a sample of exactly 1 ms falls into bucket 0).
/// Bucket index mapping:
/// - 0: ≤ 1 ms
/// - 1: 2 – 5 ms
/// - 2: 6 – 10 ms
/// - 3: 11 – 50 ms
/// - 4: 51 – 100 ms
/// - 5: 101 – 500 ms
/// - 6: > 500 ms
#[derive(Debug)]
pub struct LatencyHistogram {
    /// Counts per bucket. Index 0 = ≤1ms, …, index 6 = >500ms.
    /// Bucket upper bounds are **inclusive**.
    buckets: [AtomicU64; 7],
    total_count: AtomicU64,
    total_sum_ms: AtomicU64,
}

impl Default for LatencyHistogram {
    fn default() -> Self {
        Self {
            buckets: [
                AtomicU64::new(0),
                AtomicU64::new(0),
                AtomicU64::new(0),
                AtomicU64::new(0),
                AtomicU64::new(0),
                AtomicU64::new(0),
                AtomicU64::new(0),
            ],
            total_count: AtomicU64::new(0),
            total_sum_ms: AtomicU64::new(0),
        }
    }
}

impl LatencyHistogram {
    /// Bucket upper bounds in milliseconds.
    ///
    /// Boundaries were chosen to cover the full range of observed latencies in
    /// LLM-backed agent systems:
    ///
    /// | Bucket | Range      | Typical source                         |
    /// |--------|------------|----------------------------------------|
    /// | 0      | ≤ 1 ms     | In-process tool calls, cache hits      |
    /// | 1      | ≤ 5 ms     | Fast local I/O, simple calculations    |
    /// | 2      | ≤ 10 ms    | Network round-trips to local services  |
    /// | 3      | ≤ 50 ms    | p50 LLM token latency (streaming)      |
    /// | 4      | ≤ 100 ms   | p95 for small LLM completions          |
    /// | 5      | ≤ 500 ms   | p99 for medium LLM completions         |
    /// | 6      | > 500 ms   | Slow completions, network retries      |
    const BOUNDS: [u64; 7] = [1, 5, 10, 50, 100, 500, u64::MAX];

    /// Record a latency sample in milliseconds.
    pub fn record(&self, ms: u64) {
        self.total_count.fetch_add(1, Ordering::Relaxed);
        self.total_sum_ms.fetch_add(ms, Ordering::Relaxed);
        for (i, &bound) in Self::BOUNDS.iter().enumerate() {
            if ms <= bound {
                self.buckets[i].fetch_add(1, Ordering::Relaxed);
                return;
            }
        }
    }

    /// Return the mean latency in ms, or 0.0 if no samples.
    pub fn mean_ms(&self) -> f64 {
        let count = self.total_count.load(Ordering::Relaxed);
        if count == 0 {
            return 0.0;
        }
        self.total_sum_ms.load(Ordering::Relaxed) as f64 / count as f64
    }

    /// Return a bucket-midpoint approximation of the standard deviation in ms.
    ///
    /// Uses the midpoint of each histogram bucket to estimate the second moment,
    /// then applies `√(E[X²] − E[X]²)`.  Returns `0.0` when fewer than two
    /// samples have been recorded.
    ///
    /// # Accuracy
    /// The result is an estimate; its accuracy improves as the sample count
    /// increases and degrades near the boundaries of wide buckets.
    pub fn std_dev_ms(&self) -> f64 {
        let count = self.total_count.load(Ordering::Relaxed);
        if count < 2 {
            return 0.0;
        }
        const MIDS: [f64; 7] = [0.5, 3.0, 7.5, 30.0, 75.0, 300.0, 500.0];
        let (sum, sum_sq): (f64, f64) = self
            .buckets
            .iter()
            .zip(MIDS.iter())
            .map(|(b, &m)| {
                let c = b.load(Ordering::Relaxed) as f64;
                (c * m, c * m * m)
            })
            .fold((0.0, 0.0), |(s, ss), (v, v2)| (s + v, ss + v2));
        let n = count as f64;
        let variance = sum_sq / n - (sum / n) * (sum / n);
        variance.max(0.0).sqrt()
    }

    /// Return the total sample count.
    pub fn count(&self) -> u64 {
        self.total_count.load(Ordering::Relaxed)
    }

    /// Return `true` if at least one sample has been recorded.
    pub fn has_data(&self) -> bool {
        self.count() > 0
    }

    /// Return `true` when no samples have been recorded yet.
    pub fn is_empty(&self) -> bool {
        self.count() == 0
    }

    /// Estimate the p-th percentile latency in milliseconds from the histogram.
    ///
    /// `p` must be in `[0.0, 1.0]`.  Returns the **upper bound** of the first
    /// bucket that contains the p-th percentile.  Returns `0` if no samples
    /// have been recorded.
    ///
    /// # Accuracy
    ///
    /// This is a bucket-boundary estimate, not an exact value.  The error is
    /// bounded by the bucket width at that percentile.
    pub fn percentile(&self, p: f64) -> u64 {
        let total = self.total_count.load(Ordering::Relaxed);
        if total == 0 {
            return 0;
        }
        let target = (p.clamp(0.0, 1.0) * total as f64).ceil() as u64;
        let mut cumulative = 0u64;
        for (i, bucket) in self.buckets.iter().enumerate() {
            cumulative += bucket.load(Ordering::Relaxed);
            if cumulative >= target {
                return Self::BOUNDS[i];
            }
        }
        // All samples accounted for — return the last bound.
        *Self::BOUNDS.last().unwrap_or(&u64::MAX)
    }

    /// Return the upper-bound of the bucket with the highest sample count (the mode).
    ///
    /// Returns `None` if no samples have been recorded.  When multiple buckets
    /// tie for the maximum, the lowest-latency bucket is returned.
    pub fn mode_bucket_ms(&self) -> Option<u64> {
        if self.count() == 0 {
            return None;
        }
        let (idx, _) = self
            .buckets
            .iter()
            .enumerate()
            .max_by_key(|(_, a)| a.load(Ordering::Relaxed))?;
        Some(Self::BOUNDS[idx])
    }

    /// Return bucket counts as `(upper_bound_ms, count)` pairs.
    pub fn buckets(&self) -> Vec<(u64, u64)> {
        Self::BOUNDS
            .iter()
            .zip(self.buckets.iter())
            .map(|(&b, a)| (b, a.load(Ordering::Relaxed)))
            .collect()
    }

    /// Return the minimum recorded latency in ms, or `None` if no samples.
    pub fn min_ms(&self) -> Option<u64> {
        let total = self.total_count.load(Ordering::Relaxed);
        if total == 0 {
            return None;
        }
        // Walk buckets from the fastest; the first non-empty bucket's lower
        // bound is 0 (or the previous bound), so return the upper bound as
        // the conservative minimum estimate.
        for (i, bucket) in self.buckets.iter().enumerate() {
            if bucket.load(Ordering::Relaxed) > 0 {
                return Some(if i == 0 { 0 } else { Self::BOUNDS[i - 1] + 1 });
            }
        }
        None
    }

    /// Return the maximum recorded latency in ms, or `None` if no samples.
    pub fn max_ms(&self) -> Option<u64> {
        let total = self.total_count.load(Ordering::Relaxed);
        if total == 0 {
            return None;
        }
        // Walk from the slowest bucket; return the upper bound of the last non-empty bucket.
        for (i, bucket) in self.buckets.iter().enumerate().rev() {
            if bucket.load(Ordering::Relaxed) > 0 {
                return Some(Self::BOUNDS[i]);
            }
        }
        None
    }

    /// Return the spread (max − min) of recorded latencies in milliseconds.
    ///
    /// Returns `None` if no samples have been recorded.  A narrow range
    /// indicates consistent latency; a wide range suggests outliers.
    pub fn range_ms(&self) -> Option<u64> {
        Some(self.max_ms()?.saturating_sub(self.min_ms()?))
    }

    /// Return the interquartile range (p75 − p25) in milliseconds.
    ///
    /// A measure of dispersion that is less sensitive to outliers than
    /// [`range_ms`].  Returns `0` when fewer than two samples have been
    /// recorded (p25 == p75 == 0).
    ///
    /// [`range_ms`]: LatencyHistogram::range_ms
    pub fn interquartile_range_ms(&self) -> u64 {
        self.p75().saturating_sub(self.p25())
    }

    /// Return the 50th-percentile (median) latency in milliseconds.
    pub fn p50(&self) -> u64 {
        self.percentile(0.50)
    }

    /// Return the 95th-percentile latency in milliseconds.
    pub fn p95(&self) -> u64 {
        self.percentile(0.95)
    }

    /// Return the 99th-percentile latency in milliseconds.
    pub fn p99(&self) -> u64 {
        self.percentile(0.99)
    }

    /// Return the 25th-percentile latency in milliseconds.
    pub fn p25(&self) -> u64 {
        self.percentile(0.25)
    }

    /// Return the 75th-percentile latency in milliseconds.
    pub fn p75(&self) -> u64 {
        self.percentile(0.75)
    }

    /// Return the 90th-percentile latency in milliseconds.
    pub fn p90(&self) -> u64 {
        self.percentile(0.90)
    }

    /// Return the 10th-percentile latency in milliseconds.
    ///
    /// Useful for assessing the "best case" tail of the distribution.
    pub fn p10(&self) -> u64 {
        self.percentile(0.10)
    }

    /// Return the median (50th-percentile) step latency in milliseconds.
    ///
    /// Convenience alias for `p50`; useful when callers want an explicit
    /// "median" name without importing percentile constants.
    pub fn median_ms(&self) -> u64 {
        self.p50()
    }

    /// Reset all histogram counters to zero.
    pub fn reset(&self) {
        self.total_count.store(0, Ordering::Relaxed);
        self.total_sum_ms.store(0, Ordering::Relaxed);
        for bucket in &self.buckets {
            bucket.store(0, Ordering::Relaxed);
        }
    }

    /// Return the total sum of all recorded latency samples in milliseconds.
    ///
    /// Equivalent to `mean_ms() * count()` but avoids floating-point arithmetic.
    pub fn sum_ms(&self) -> u64 {
        self.total_sum_ms.load(Ordering::Relaxed)
    }

    /// Return the coefficient of variation: `std_dev_ms / mean_ms`.
    ///
    /// A value of `0.0` means no variation; higher values indicate more
    /// spread in latency.  Returns `0.0` when `mean_ms` is zero (empty
    /// histogram or all-zero samples) to avoid division by zero.
    pub fn coefficient_of_variation(&self) -> f64 {
        let mean = self.mean_ms();
        if mean == 0.0 {
            return 0.0;
        }
        self.std_dev_ms() / mean
    }

    /// Return the total number of samples recorded in this histogram.
    pub fn sample_count(&self) -> u64 {
        self.total_count.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Return the difference between the p99 and p50 latency buckets in
    /// milliseconds.
    ///
    /// A larger spread indicates a long-tail latency distribution.
    /// Returns `0` when no samples have been recorded.
    pub fn percentile_spread(&self) -> u64 {
        self.p99().saturating_sub(self.p50())
    }

    /// Return the count for each bucket as an array, in order from the
    /// fastest (≤1ms) to the slowest (>500ms) bucket.
    pub fn bucket_counts(&self) -> [u64; 7] {
        let mut out = [0u64; 7];
        for (i, b) in self.buckets.iter().enumerate() {
            out[i] = b.load(std::sync::atomic::Ordering::Relaxed);
        }
        out
    }

    /// Return the upper bound (ms) of the lowest bucket that has at least one
    /// sample, or `None` if no samples have been recorded.
    pub fn min_occupied_ms(&self) -> Option<u64> {
        Self::BOUNDS
            .iter()
            .zip(self.buckets.iter())
            .find(|(_, b)| b.load(std::sync::atomic::Ordering::Relaxed) > 0)
            .map(|(&bound, _)| bound)
    }

    /// Return the upper-bound of the largest bucket with at least one recorded sample.
    ///
    /// Returns `None` if the histogram is empty.
    pub fn max_occupied_ms(&self) -> Option<u64> {
        Self::BOUNDS
            .iter()
            .zip(self.buckets.iter())
            .rev()
            .find(|(_, b)| b.load(std::sync::atomic::Ordering::Relaxed) > 0)
            .map(|(&bound, _)| bound)
    }

    /// Return the number of buckets that have at least one recorded sample.
    pub fn occupied_bucket_count(&self) -> usize {
        self.buckets
            .iter()
            .filter(|b| b.load(std::sync::atomic::Ordering::Relaxed) > 0)
            .count()
    }

    /// Return `true` if the latency distribution is skewed (p99 > 2 × p50).
    ///
    /// Returns `false` for empty histograms.
    pub fn is_skewed(&self) -> bool {
        let p50 = self.p50();
        if p50 == 0 {
            return false;
        }
        self.p99() > 2 * p50
    }

    /// Return `true` if all recorded samples fall into exactly one bucket.
    ///
    /// An empty histogram is considered uniform.
    pub fn is_uniform(&self) -> bool {
        let non_empty = self
            .buckets
            .iter()
            .filter(|b| b.load(std::sync::atomic::Ordering::Relaxed) > 0)
            .count();
        non_empty <= 1
    }

    /// Reset all histogram counters to zero.
    ///
    /// Alias for [`reset`] using more conventional naming.
    ///
    /// [`reset`]: LatencyHistogram::reset
    pub fn clear(&self) {
        self.reset();
    }

    /// Return `true` if `latency_ms` is strictly greater than the current p99.
    ///
    /// Useful for detecting outlier requests at call sites without storing
    /// the p99 value separately.  Returns `false` when the histogram is empty.
    pub fn is_above_p99(&self, latency_ms: u64) -> bool {
        latency_ms > self.p99()
    }

    /// Return `true` if the p99 latency is strictly below `threshold_ms`.
    ///
    /// Useful for SLO checks.  Returns `true` when no samples have been
    /// recorded (`p99 == 0`).
    pub fn is_below_p99(&self, threshold_ms: u64) -> bool {
        self.p99() < threshold_ms
    }

}

impl MetricsSnapshot {
    /// Compute the difference between `after` and `before` (i.e., `after - before`).
    ///
    /// Useful for per-request instrumentation:
    /// ```rust,ignore
    /// let before = metrics.snapshot();
    /// // ... run one agent invocation ...
    /// let after = metrics.snapshot();
    /// let delta = MetricsSnapshot::delta(&after, &before);
    /// println!("steps this run: {}", delta.total_steps);
    /// ```
    ///
    /// Saturating subtraction is used so callers don't need to guard against
    /// races where a counter is read before the full increment propagates.
    pub fn delta(after: &Self, before: &Self) -> Self {
        Self {
            active_sessions: after.active_sessions.saturating_sub(before.active_sessions),
            total_sessions: after.total_sessions.saturating_sub(before.total_sessions),
            total_steps: after.total_steps.saturating_sub(before.total_steps),
            total_tool_calls: after.total_tool_calls.saturating_sub(before.total_tool_calls),
            failed_tool_calls: after.failed_tool_calls.saturating_sub(before.failed_tool_calls),
            backpressure_shed_count: after
                .backpressure_shed_count
                .saturating_sub(before.backpressure_shed_count),
            memory_recall_count: after
                .memory_recall_count
                .saturating_sub(before.memory_recall_count),
            checkpoint_errors: after
                .checkpoint_errors
                .saturating_sub(before.checkpoint_errors),
            per_tool_calls: {
                let mut m = after.per_tool_calls.clone();
                for (k, v) in &before.per_tool_calls {
                    let entry = m.entry(k.clone()).or_default();
                    *entry = entry.saturating_sub(*v);
                }
                m
            },
            per_tool_failures: {
                let mut m = after.per_tool_failures.clone();
                for (k, v) in &before.per_tool_failures {
                    let entry = m.entry(k.clone()).or_default();
                    *entry = entry.saturating_sub(*v);
                }
                m
            },
            step_latency_buckets: after
                .step_latency_buckets
                .iter()
                .zip(before.step_latency_buckets.iter())
                .map(|((bound, a), (_, b))| (*bound, a.saturating_sub(*b)))
                .collect(),
            step_latency_mean_ms: after.step_latency_mean_ms - before.step_latency_mean_ms,
            per_agent_tool_calls: after.per_agent_tool_calls.clone(),
            per_agent_tool_failures: after.per_agent_tool_failures.clone(),
        }
    }

    /// Serialize the snapshot to a `serde_json::Value` for logging or export.
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "active_sessions": self.active_sessions,
            "total_sessions": self.total_sessions,
            "total_steps": self.total_steps,
            "total_tool_calls": self.total_tool_calls,
            "failed_tool_calls": self.failed_tool_calls,
            "backpressure_shed_count": self.backpressure_shed_count,
            "memory_recall_count": self.memory_recall_count,
            "step_latency_mean_ms": self.step_latency_mean_ms,
            "per_tool_calls": self.per_tool_calls,
            "per_tool_failures": self.per_tool_failures,
        })
    }

    /// Return the number of calls recorded for the named tool.
    ///
    /// Returns `0` if no calls have been recorded for that tool name.
    pub fn tool_call_count(&self, name: &str) -> u64 {
        self.per_tool_calls.get(name).copied().unwrap_or(0)
    }

    /// Return a concise single-line summary of this snapshot.
    ///
    /// Format: `"sessions={n}, steps={n}, tool_calls={n}, failures={n}, latency_mean={n}ms"`.
    /// Intended for logging and debugging — not a stable serialization format.
    pub fn summary_line(&self) -> String {
        format!(
            "sessions={s}, steps={st}, tool_calls={tc}, failures={f}, latency_mean={l}ms",
            s = self.total_sessions,
            st = self.total_steps,
            tc = self.total_tool_calls,
            f = self.failed_tool_calls,
            l = self.step_latency_mean_ms as u64,
        )
    }

    /// Return the number of failures recorded for the named tool.
    ///
    /// Returns `0` if no failures have been recorded for that tool name.
    pub fn tool_failure_count(&self, name: &str) -> u64 {
        self.per_tool_failures.get(name).copied().unwrap_or(0)
    }

    /// Return a sorted list of tool names that have at least one recorded call.
    pub fn tool_names(&self) -> Vec<&str> {
        let mut names: Vec<&str> = self.per_tool_calls.keys().map(|s| s.as_str()).collect();
        names.sort_unstable();
        names
    }

    /// Return the overall tool-call failure rate as a value in `[0.0, 1.0]`.
    ///
    /// Returns `0.0` if no tool calls have been recorded.
    pub fn failure_rate(&self) -> f64 {
        if self.total_tool_calls == 0 {
            return 0.0;
        }
        self.failed_tool_calls as f64 / self.total_tool_calls as f64
    }

    /// Return the overall tool-call success rate as a value in `[0.0, 1.0]`.
    ///
    /// Returns `1.0` if no tool calls have been recorded (vacuously all succeeded).
    pub fn success_rate(&self) -> f64 {
        1.0 - self.failure_rate()
    }

    /// Return the number of successful calls for the named tool.
    ///
    /// Computed as `tool_call_count(name) - tool_failure_count(name)`.
    pub fn tool_success_count(&self, name: &str) -> u64 {
        self.tool_call_count(name)
            .saturating_sub(self.tool_failure_count(name))
    }

    /// Return the per-tool failure rate for the named tool.
    ///
    /// Returns `0.0` if no calls have been recorded for that tool.
    pub fn tool_failure_rate(&self, name: &str) -> f64 {
        let calls = self.tool_call_count(name);
        if calls == 0 {
            return 0.0;
        }
        self.tool_failure_count(name) as f64 / calls as f64
    }

    /// Return the total number of successful tool calls (total minus failed).
    ///
    /// Uses saturating subtraction so a race between `total_tool_calls`
    /// and `failed_tool_calls` cannot produce an underflow.
    pub fn total_successful_tool_calls(&self) -> u64 {
        self.total_tool_calls.saturating_sub(self.failed_tool_calls)
    }

    /// Return `true` if all counters are zero (no activity has been recorded).
    pub fn is_zero(&self) -> bool {
        self.active_sessions == 0
            && self.total_sessions == 0
            && self.total_steps == 0
            && self.total_tool_calls == 0
            && self.failed_tool_calls == 0
            && self.backpressure_shed_count == 0
            && self.memory_recall_count == 0
            && self.checkpoint_errors == 0
    }

    /// Return the average number of ReAct steps per completed session.
    ///
    /// Returns `0.0` when no sessions have been recorded, to avoid
    /// division by zero.
    pub fn avg_steps_per_session(&self) -> f64 {
        if self.total_sessions == 0 {
            0.0
        } else {
            self.total_steps as f64 / self.total_sessions as f64
        }
    }

    /// Return the overall tool error rate: `failed_tool_calls / total_tool_calls`.
    ///
    /// Returns `0.0` when no tool calls have been recorded.
    pub fn error_rate(&self) -> f64 {
        if self.total_tool_calls == 0 {
            return 0.0;
        }
        self.failed_tool_calls as f64 / self.total_tool_calls as f64
    }

    /// Return memory recalls per completed session.
    ///
    /// Returns `0.0` when no sessions have been recorded.
    pub fn memory_recall_rate(&self) -> f64 {
        if self.total_sessions == 0 {
            return 0.0;
        }
        self.memory_recall_count as f64 / self.total_sessions as f64
    }

    /// Return the average number of ReAct steps per session.
    ///
    /// Alias for `avg_steps_per_session` on the snapshot type; returns `0.0`
    /// when no sessions have been recorded.
    pub fn steps_per_session(&self) -> f64 {
        if self.total_sessions == 0 {
            return 0.0;
        }
        self.total_steps as f64 / self.total_sessions as f64
    }

    /// Return `true` if the snapshot contains any error indicators.
    ///
    /// Specifically, `true` when `failed_tool_calls > 0` or
    /// `checkpoint_errors > 0`.  The complement of "no errors" but distinct
    /// from `!is_healthy()` which also considers backpressure sheds.
    pub fn has_errors(&self) -> bool {
        self.failed_tool_calls > 0 || self.checkpoint_errors > 0
    }

    /// Return `true` if the snapshot shows no error indicators.
    ///
    /// A "healthy" snapshot has zero failed tool calls, zero backpressure
    /// sheds, and zero checkpoint errors.  Useful for quick health checks
    /// in tests and monitoring.
    pub fn is_healthy(&self) -> bool {
        self.failed_tool_calls == 0
            && self.backpressure_shed_count == 0
            && self.checkpoint_errors == 0
    }

    /// Return `true` if this snapshot passes a parameterised health check.
    ///
    /// The check passes when all of the following hold:
    /// 1. `failed_tool_calls == 0`
    /// 2. `backpressure_shed_count == 0`
    /// 3. `checkpoint_errors == 0`
    /// 4. `step_latency_mean_ms <= max_latency_ms`
    ///
    /// Use this variant instead of [`is_healthy`] when you need to enforce an
    /// explicit latency SLO — for example in an alerting callback.
    ///
    /// [`is_healthy`]: MetricsSnapshot::is_healthy
    pub fn is_healthy_with_latency(&self, max_latency_ms: f64) -> bool {
        self.is_healthy() && self.step_latency_mean_ms <= max_latency_ms
    }

    /// Return `true` if no tool calls have been recorded yet.
    ///
    /// A fresh snapshot (e.g. right after construction or after [`RuntimeMetrics::reset`])
    /// has all counters at zero.  This predicate makes that condition explicit at call sites.
    ///
    /// [`RuntimeMetrics::reset`]: crate::metrics::RuntimeMetrics::reset
    pub fn is_empty(&self) -> bool {
        self.total_sessions == 0 && self.total_tool_calls == 0 && self.total_steps == 0
    }

    /// Return `true` if the tool failure rate exceeds `threshold`.
    ///
    /// `threshold` should be in `[0.0, 1.0]` (e.g. `0.1` for 10%).  Returns
    /// `false` when no tool calls have been recorded (`failure_rate` is 0.0 in
    /// that case).
    ///
    /// This is a softer signal than [`is_healthy`], which only checks for zero
    /// failures.  Use `is_degraded` in alerting logic that needs a configurable
    /// SLO threshold.
    ///
    /// [`is_healthy`]: MetricsSnapshot::is_healthy
    pub fn is_degraded(&self, threshold: f64) -> bool {
        self.failure_rate() > threshold
    }

    /// Return the average number of tool calls per session.
    ///
    /// Returns `0.0` when no sessions have been recorded.
    pub fn tool_call_rate(&self) -> f64 {
        if self.total_sessions == 0 {
            return 0.0;
        }
        self.total_tool_calls as f64 / self.total_sessions as f64
    }

    /// Return the average number of backpressure shed events per session.
    ///
    /// Returns `0.0` when no sessions have been recorded.
    pub fn backpressure_rate(&self) -> f64 {
        if self.total_sessions == 0 {
            return 0.0;
        }
        self.backpressure_shed_count as f64 / self.total_sessions as f64
    }

    /// Return the ratio of memory recalls to total steps.
    ///
    /// Returns `0.0` when no steps have been taken.
    pub fn memory_efficiency(&self) -> f64 {
        if self.total_steps == 0 {
            return 0.0;
        }
        self.memory_recall_count as f64 / self.total_steps as f64
    }

    /// Return the fraction of sessions that are currently active.
    ///
    /// Returns `0.0` when no sessions have been started.
    pub fn active_session_ratio(&self) -> f64 {
        if self.total_sessions == 0 {
            return 0.0;
        }
        self.active_sessions as f64 / self.total_sessions as f64
    }

    /// Return the average number of tool calls per step.
    ///
    /// Returns `0.0` when no steps have been taken.
    pub fn step_to_tool_ratio(&self) -> f64 {
        if self.total_steps == 0 {
            return 0.0;
        }
        self.total_tool_calls as f64 / self.total_steps as f64
    }

    /// Return `true` if any tool-call failures have been recorded.
    pub fn has_failures(&self) -> bool {
        self.failed_tool_calls > 0
    }

    /// Return the number of distinct tool names that have been called at least once.
    pub fn tool_diversity(&self) -> usize {
        self.per_tool_calls.len()
    }

    /// Return the average number of tool-call failures per completed session.
    ///
    /// Returns `0.0` when no sessions have been recorded.
    pub fn avg_failures_per_session(&self) -> f64 {
        if self.total_sessions == 0 {
            return 0.0;
        }
        self.failed_tool_calls as f64 / self.total_sessions as f64
    }

    /// Return the name of the tool with the most recorded calls.
    ///
    /// Returns `None` if no tool calls have been recorded.
    pub fn most_called_tool(&self) -> Option<String> {
        self.per_tool_calls
            .iter()
            .max_by_key(|(_, &v)| v)
            .map(|(k, _)| k.clone())
    }

    /// Return a sorted list of tool names that have at least one recorded failure.
    pub fn tool_names_with_failures(&self) -> Vec<String> {
        let mut names: Vec<String> = self
            .per_tool_failures
            .iter()
            .filter(|(_, &v)| v > 0)
            .map(|(k, _)| k.clone())
            .collect();
        names.sort_unstable();
        names
    }

    /// Return `true` if at least one tool has a recorded failure.
    pub fn has_any_tool_failures(&self) -> bool {
        self.per_tool_failures.values().any(|&v| v > 0)
    }

    /// Return sorted names of all tracked tools that have zero recorded failures.
    ///
    /// A tool that has never been called is included if it appears in the
    /// `per_tool_calls` map with a count of zero.
    pub fn tools_with_zero_failures(&self) -> Vec<String> {
        let mut names: Vec<String> = self
            .per_tool_calls
            .keys()
            .filter(|name| {
                self.per_tool_failures
                    .get(*name)
                    .copied()
                    .unwrap_or(0)
                    == 0
            })
            .cloned()
            .collect();
        names.sort_unstable();
        names
    }

    /// Return the sum of call counts across all tracked tools.
    ///
    /// This is the per-tool sum, which may differ from `total_tool_calls` if
    /// the snapshot was produced from multiple sources.
    pub fn total_tool_calls_count(&self) -> u64 {
        self.per_tool_calls.values().sum()
    }

    /// Return the ratio of the most-called tool's count to the least-called
    /// tool's count.
    ///
    /// Returns `1.0` when fewer than two tools are tracked (no imbalance
    /// measurable) or when the minimum is zero.  A high ratio indicates that
    /// load is concentrated on a single tool.
    pub fn tool_call_imbalance(&self) -> f64 {
        let counts: Vec<u64> = self.per_tool_calls.values().copied().collect();
        if counts.len() < 2 {
            return 1.0;
        }
        let max = counts.iter().copied().max().unwrap_or(0);
        let min = counts.iter().copied().min().unwrap_or(0);
        if min == 0 {
            return 1.0;
        }
        max as f64 / min as f64
    }

    /// Return the failure rate for a specific tool (failures / calls).
    ///
    /// Returns `0.0` if the tool has no recorded calls.
    pub fn failed_tool_ratio_for(&self, name: &str) -> f64 {
        let calls = self.tool_call_count(name);
        if calls == 0 {
            return 0.0;
        }
        self.tool_failure_count(name) as f64 / calls as f64
    }

    /// Return the ratio of backpressure-shed events to total tool calls.
    ///
    /// Returns `0.0` if no tool calls have been recorded.
    pub fn backpressure_shed_rate(&self) -> f64 {
        if self.total_tool_calls == 0 {
            return 0.0;
        }
        self.backpressure_shed_count as f64 / self.total_tool_calls as f64
    }

    /// Return the number of distinct agents that have recorded tool-call data.
    pub fn total_agent_count(&self) -> usize {
        self.per_agent_tool_calls.len()
    }

    /// Return the ratio of total steps to total tool calls.
    ///
    /// Returns `0.0` if no tool calls have been recorded.
    pub fn steps_per_tool_call(&self) -> f64 {
        if self.total_tool_calls == 0 {
            return 0.0;
        }
        self.total_steps as f64 / self.total_tool_calls as f64
    }

    /// Return the agent id with the most total tool calls across all tools.
    ///
    /// Returns `None` if no per-agent tool-call data has been recorded.
    pub fn agent_with_most_calls(&self) -> Option<String> {
        self.per_agent_tool_calls
            .iter()
            .map(|(agent, tools)| (agent, tools.values().sum::<u64>()))
            .max_by_key(|(_, total)| *total)
            .map(|(agent, _)| agent.clone())
    }

    /// Return the total number of tool failures summed across all tools.
    ///
    /// This is the sum of `per_tool_failures` values and equals
    /// `failed_tool_calls` when per-tool tracking is complete.  Useful for
    /// verifying that failure tracking is consistent with overall counters.
    pub fn total_tool_failures(&self) -> u64 {
        self.per_tool_failures.values().sum()
    }

    /// Return the name of the tool with the fewest recorded calls.
    ///
    /// Returns `None` if no tool-call data has been recorded.  When multiple
    /// tools share the minimum call count, any one of them may be returned.
    pub fn least_called_tool(&self) -> Option<String> {
        self.per_tool_calls
            .iter()
            .min_by_key(|(_, &count)| count)
            .map(|(name, _)| name.clone())
    }

    /// Return the mean number of calls per distinct tool name.
    ///
    /// Returns `0.0` when no tool-call data has been recorded.
    pub fn avg_tool_calls_per_name(&self) -> f64 {
        let n = self.per_tool_calls.len();
        if n == 0 {
            return 0.0;
        }
        let total: u64 = self.per_tool_calls.values().sum();
        total as f64 / n as f64
    }

    /// Return the number of distinct tool names that have more than `n` recorded calls.
    ///
    /// Returns `0` when no tool-call data has been recorded.
    pub fn tool_call_count_above(&self, n: u64) -> usize {
        self.per_tool_calls.values().filter(|&&count| count > n).count()
    }

    /// Return the top `n` tool names sorted by call count (descending).
    ///
    /// Returns fewer than `n` entries if fewer tools have been called.
    /// Ties are broken alphabetically (ascending) for deterministic output.
    pub fn top_n_tools_by_calls(&self, n: usize) -> Vec<(&str, u64)> {
        let mut pairs: Vec<(&str, u64)> = self
            .per_tool_calls
            .iter()
            .map(|(name, &count)| (name.as_str(), count))
            .collect();
        pairs.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
        pairs.truncate(n);
        pairs
    }

    /// Return the fraction of total tool calls accounted for by `name`.
    ///
    /// Returns `0.0` if `total_tool_calls` is zero or `name` has no recorded
    /// calls.  Returns a value in `[0.0, 1.0]`.
    pub fn tool_call_ratio(&self, name: &str) -> f64 {
        if self.total_tool_calls == 0 {
            return 0.0;
        }
        let count = self.per_tool_calls.get(name).copied().unwrap_or(0);
        count as f64 / self.total_tool_calls as f64
    }

    /// Return all per-tool call counts sorted by count descending.
    ///
    /// Returns a `Vec` of `(tool_name, count)` pairs where the first entry is
    /// the most-called tool.  Returns an empty `Vec` when no calls have been
    /// recorded.  Ties are broken alphabetically (ascending).
    pub fn per_tool_calls_sorted(&self) -> Vec<(String, u64)> {
        let mut pairs: Vec<(String, u64)> = self
            .per_tool_calls
            .iter()
            .map(|(k, &v)| (k.clone(), v))
            .collect();
        pairs.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
        pairs
    }

    /// Return `true` if `name` appears in the per-tool call map (i.e., was
    /// called at least once), `false` otherwise.
    pub fn has_tool(&self, name: &str) -> bool {
        self.per_tool_calls.contains_key(name)
    }

    /// Return the fraction of total tool calls attributable to `name`.
    ///
    /// Returns `0.0` when `total_tool_calls` is zero or when `name` has no
    /// recorded calls.  The result is in `[0.0, 1.0]`.
    pub fn tool_call_share(&self, name: &str) -> f64 {
        if self.total_tool_calls == 0 {
            return 0.0;
        }
        let count = self.per_tool_calls.get(name).copied().unwrap_or(0);
        count as f64 / self.total_tool_calls as f64
    }

    /// Return the number of distinct tool names that have at least one
    /// recorded call.
    ///
    /// Returns `0` when no tool calls have been recorded.
    pub fn distinct_tool_count(&self) -> usize {
        self.per_tool_calls.len()
    }

    /// Return `true` if at least one tool call has been recorded.
    ///
    /// Equivalent to `self.total_tool_calls > 0`, provided as a convenience
    /// predicate for guard clauses.
    pub fn has_any_tool_calls(&self) -> bool {
        self.total_tool_calls > 0
    }

    /// Return tool names sorted alphabetically.
    ///
    /// Only names that appear in the `per_tool_calls` map are included.
    /// Returns an empty `Vec` when no tool calls have been recorded.
    pub fn tool_names_alphabetical(&self) -> Vec<String> {
        let mut names: Vec<String> = self.per_tool_calls.keys().cloned().collect();
        names.sort_unstable();
        names
    }

    /// Return the average number of failures per distinct tool.
    ///
    /// Computed as total recorded failures divided by the number of distinct
    /// tool names in `per_tool_calls`.  Returns `0.0` when no tool calls have
    /// been recorded.
    pub fn avg_failures_per_tool(&self) -> f64 {
        let count = self.per_tool_calls.len();
        if count == 0 {
            return 0.0;
        }
        let total_failures: u64 = self.per_tool_failures.values().sum();
        total_failures as f64 / count as f64
    }

    /// Return the names of tools whose failure ratio (failures / calls) exceeds
    /// `threshold`, sorted alphabetically.
    ///
    /// Returns an empty `Vec` when no tool exceeds the threshold or when no
    /// tool calls have been recorded.
    pub fn tools_above_failure_ratio(&self, threshold: f64) -> Vec<String> {
        let mut names: Vec<String> = self
            .per_tool_calls
            .keys()
            .filter(|name| {
                let calls = self.tool_call_count(name);
                if calls == 0 {
                    return false;
                }
                let failures = self.tool_failure_count(name);
                failures as f64 / calls as f64 > threshold
            })
            .cloned()
            .collect();
        names.sort_unstable();
        names
    }

    /// Return the failure ratio for a specific tool: `failures / calls`.
    ///
    /// Returns `0.0` if the tool has never been called or is unknown, avoiding
    /// division-by-zero.  A ratio of `1.0` means every invocation failed.
    pub fn failure_ratio_for_tool(&self, name: &str) -> f64 {
        let calls = self.tool_call_count(name);
        if calls == 0 {
            return 0.0;
        }
        self.tool_failure_count(name) as f64 / calls as f64
    }

    /// Return `true` if any registered tool has a call count strictly above
    /// `threshold`.
    ///
    /// Useful for detecting hotspot tools that may be responsible for
    /// disproportionate load.
    pub fn any_tool_exceeds_calls(&self, threshold: u64) -> bool {
        self.per_tool_calls.values().any(|&c| c > threshold)
    }

    /// Return the number of distinct tools that have been tracked in this
    /// snapshot (i.e. tools with at least one call recorded).
    ///
    /// Equivalent to `per_tool_calls.len()` but exposed as a named method for
    /// readability.
    pub fn total_unique_tools(&self) -> usize {
        self.per_tool_calls.len()
    }

    /// Return the fraction of all tool calls that were made by the named tool.
    ///
    /// Returns `0.0` when the tool is unknown or there have been no tool calls
    /// at all.  A value of `1.0` means this tool accounts for every call.
    pub fn tool_call_ratio_for(&self, name: &str) -> f64 {
        if self.total_tool_calls == 0 {
            return 0.0;
        }
        self.tool_call_count(name) as f64 / self.total_tool_calls as f64
    }

    /// Return the sum of all per-tool failure counts across every tracked tool.
    ///
    /// This is the total number of error observations emitted by tool handlers,
    /// regardless of which tool generated them.  Returns `0` when no failures
    /// have been recorded.
    pub fn total_failures_across_all_tools(&self) -> u64 {
        self.per_tool_failures.values().sum()
    }
}

impl std::fmt::Display for MetricsSnapshot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "MetricsSnapshot {{ sessions: active={} total={}, steps={}, \
             tool_calls={} (failed={}), backpressure_shed={}, \
             memory_recalls={}, checkpoint_errors={}, latency_mean={:.1}ms }}",
            self.active_sessions,
            self.total_sessions,
            self.total_steps,
            self.total_tool_calls,
            self.failed_tool_calls,
            self.backpressure_shed_count,
            self.memory_recall_count,
            self.checkpoint_errors,
            self.step_latency_mean_ms,
        )
    }
}

/// A point-in-time snapshot of all runtime counters.
///
/// Obtained by calling [`RuntimeMetrics::snapshot`].  All fields are plain
/// integers so the snapshot can be logged, serialised, or diffed without
/// holding any locks.
///
/// See also [`snapshot`] for a richer snapshot including per-tool and histogram data.
///
/// # Example
/// ```rust
/// use llm_agent_runtime::metrics::RuntimeMetrics;
///
/// let m = RuntimeMetrics::new();
/// let snap = m.snapshot();
/// assert_eq!(snap.active_sessions, 0);
/// assert_eq!(snap.total_sessions, 0);
/// ```
///
/// [`snapshot`]: RuntimeMetrics::snapshot
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct MetricsSnapshot {
    /// Number of agent sessions currently in progress.
    pub active_sessions: usize,
    /// Total number of sessions started since the runtime was created.
    pub total_sessions: u64,
    /// Total number of ReAct steps executed across all sessions.
    pub total_steps: u64,
    /// Total number of tool calls dispatched (across all tool names).
    pub total_tool_calls: u64,
    /// Total number of tool calls that returned an error observation.
    pub failed_tool_calls: u64,
    /// Total number of requests shed due to backpressure.
    pub backpressure_shed_count: u64,
    /// Total number of memory recall operations.
    pub memory_recall_count: u64,
    /// Total number of checkpoint failures encountered during `run_agent`.
    pub checkpoint_errors: u64,
    /// Per-tool call counts: `tool_name → total_calls`.
    pub per_tool_calls: HashMap<String, u64>,
    /// Per-tool failure counts: `tool_name → failed_calls`.
    pub per_tool_failures: HashMap<String, u64>,
    /// Step latency histogram bucket counts as `(upper_bound_ms_inclusive, count)`.
    pub step_latency_buckets: Vec<(u64, u64)>,
    /// Mean step latency in milliseconds.
    pub step_latency_mean_ms: f64,
    /// Per-agent, per-tool call counts: `agent_id → tool_name → count`.
    pub per_agent_tool_calls: HashMap<String, HashMap<String, u64>>,
    /// Per-agent, per-tool failure counts: `agent_id → tool_name → count`.
    pub per_agent_tool_failures: HashMap<String, HashMap<String, u64>>,
}

/// All four per-tool / per-agent counter maps, protected by a single lock.
///
/// Grouping them under one `Mutex` halves lock acquisitions on the hot path
/// (a single `record_tool_call` + `record_agent_tool_call` pair now requires
/// only one acquire/release) and makes snapshot reads cheaper too.
#[derive(Debug, Default)]
struct PerToolMaps {
    /// Per-tool call counts: `tool_name → total_calls`.
    calls: HashMap<String, u64>,
    /// Per-tool failure counts: `tool_name → failed_calls`.
    failures: HashMap<String, u64>,
    /// Per-agent, per-tool call counts: `agent_id → tool_name → count`.
    agent_calls: HashMap<String, HashMap<String, u64>>,
    /// Per-agent, per-tool failure counts: `agent_id → tool_name → count`.
    agent_failures: HashMap<String, HashMap<String, u64>>,
}

/// Shared runtime metrics. Clone the `Arc` to share across threads.
#[derive(Debug)]
pub struct RuntimeMetrics {
    /// Number of agent sessions currently in progress.
    pub active_sessions: AtomicUsize,
    /// Total number of sessions started since the runtime was created.
    pub total_sessions: AtomicU64,
    /// Total number of ReAct steps executed across all sessions.
    pub total_steps: AtomicU64,
    /// Total number of tool calls dispatched (across all tool names).
    pub total_tool_calls: AtomicU64,
    /// Total number of tool calls that returned an error observation.
    pub failed_tool_calls: AtomicU64,
    /// Total number of requests shed due to backpressure.
    pub backpressure_shed_count: AtomicU64,
    /// Total number of memory recall operations.
    pub memory_recall_count: AtomicU64,
    /// Total number of checkpoint failures encountered during `run_agent`.
    pub checkpoint_errors: AtomicU64,
    /// All four per-tool / per-agent maps under a single lock.
    per_tool: Mutex<PerToolMaps>,
    /// Per-step latency histogram.
    pub step_latency: LatencyHistogram,
}

impl Default for RuntimeMetrics {
    fn default() -> Self {
        Self {
            active_sessions: AtomicUsize::new(0),
            total_sessions: AtomicU64::new(0),
            total_steps: AtomicU64::new(0),
            total_tool_calls: AtomicU64::new(0),
            failed_tool_calls: AtomicU64::new(0),
            backpressure_shed_count: AtomicU64::new(0),
            memory_recall_count: AtomicU64::new(0),
            checkpoint_errors: AtomicU64::new(0),
            per_tool: Mutex::new(PerToolMaps::default()),
            step_latency: LatencyHistogram::default(),
        }
    }
}

impl RuntimeMetrics {
    /// Allocate a new `RuntimeMetrics` instance wrapped in an `Arc`.
    pub fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    /// Return the number of agent sessions currently in progress.
    pub fn active_sessions(&self) -> usize {
        self.active_sessions.load(Ordering::Relaxed)
    }

    /// Return the total number of sessions started since the runtime was created.
    pub fn total_sessions(&self) -> u64 {
        self.total_sessions.load(Ordering::Relaxed)
    }

    /// Return the average number of tool calls per completed session.
    ///
    /// Returns `0.0` when no sessions have been recorded.
    pub fn avg_tool_calls_per_session(&self) -> f64 {
        let sessions = self.total_sessions();
        if sessions == 0 {
            return 0.0;
        }
        self.total_tool_calls() as f64 / sessions as f64
    }

    /// Return the total number of ReAct steps executed across all sessions.
    pub fn total_steps(&self) -> u64 {
        self.total_steps.load(Ordering::Relaxed)
    }

    /// Return the average number of ReAct steps per completed session.
    ///
    /// Returns `0.0` when no sessions have been recorded.
    pub fn avg_steps_per_session(&self) -> f64 {
        let sessions = self.total_sessions();
        if sessions == 0 {
            return 0.0;
        }
        self.total_steps() as f64 / sessions as f64
    }

    /// Return the total number of tool calls dispatched.
    pub fn total_tool_calls(&self) -> u64 {
        self.total_tool_calls.load(Ordering::Relaxed)
    }

    /// Return the total number of tool calls that returned an error observation.
    pub fn failed_tool_calls(&self) -> u64 {
        self.failed_tool_calls.load(Ordering::Relaxed)
    }

    /// Return the fraction of tool calls that succeeded (i.e. did not fail).
    ///
    /// Returns `1.0` if no tool calls have been recorded yet (vacuously all
    /// succeeded) and a value in `[0.0, 1.0]` once calls have been made.
    pub fn tool_success_rate(&self) -> f64 {
        let total = self.total_tool_calls();
        if total == 0 {
            return 1.0;
        }
        let failed = self.failed_tool_calls();
        1.0 - (failed as f64 / total as f64)
    }

    /// Return the total number of requests shed due to backpressure.
    pub fn backpressure_shed_count(&self) -> u64 {
        self.backpressure_shed_count.load(Ordering::Relaxed)
    }

    /// Return the total number of memory recall operations performed.
    pub fn memory_recall_count(&self) -> u64 {
        self.memory_recall_count.load(Ordering::Relaxed)
    }

    /// Return the total number of checkpoint failures encountered during `run_agent`.
    pub fn checkpoint_errors(&self) -> u64 {
        self.checkpoint_errors.load(Ordering::Relaxed)
    }

    /// Return the ratio of checkpoint errors to total completed sessions.
    ///
    /// Returns `0.0` when no sessions have been recorded.
    pub fn checkpoint_error_rate(&self) -> f64 {
        let sessions = self.total_sessions();
        if sessions == 0 {
            return 0.0;
        }
        self.checkpoint_errors() as f64 / sessions as f64
    }

    /// Return the median (50th-percentile) step latency in milliseconds.
    ///
    /// Convenience shorthand for `self.step_latency.p50()`.  Returns `0`
    /// when no step latencies have been recorded.
    pub fn p50_latency_ms(&self) -> u64 {
        self.step_latency.p50()
    }

    /// Increment the call counter for `tool_name` by 1.
    ///
    /// Called automatically by the agent loop when `with_metrics` is configured.
    pub fn record_tool_call(&self, tool_name: &str) {
        self.total_tool_calls.fetch_add(1, Ordering::Relaxed);
        if let Ok(mut maps) = self.per_tool.lock() {
            *maps.calls.entry(tool_name.to_owned()).or_insert(0) += 1;
        }
    }

    /// Increment the failure counter for `tool_name` by 1.
    ///
    /// Called automatically by the agent loop when a tool returns an error.
    pub fn record_tool_failure(&self, tool_name: &str) {
        self.failed_tool_calls.fetch_add(1, Ordering::Relaxed);
        if let Ok(mut maps) = self.per_tool.lock() {
            *maps.failures.entry(tool_name.to_owned()).or_insert(0) += 1;
        }
    }

    /// Return a snapshot of per-tool call counts as a `HashMap<tool_name, count>`.
    pub fn per_tool_calls_snapshot(&self) -> HashMap<String, u64> {
        self.per_tool
            .lock()
            .map(|m| m.calls.clone())
            .unwrap_or_default()
    }

    /// Return a snapshot of per-tool failure counts as a `HashMap<tool_name, count>`.
    pub fn per_tool_failures_snapshot(&self) -> HashMap<String, u64> {
        self.per_tool
            .lock()
            .map(|m| m.failures.clone())
            .unwrap_or_default()
    }

    /// Increment call counter for (agent_id, tool_name).
    pub fn record_agent_tool_call(&self, agent_id: &str, tool_name: &str) {
        if let Ok(mut maps) = self.per_tool.lock() {
            *maps
                .agent_calls
                .entry(agent_id.to_owned())
                .or_default()
                .entry(tool_name.to_owned())
                .or_insert(0) += 1;
        }
    }

    /// Increment failure counter for (agent_id, tool_name).
    pub fn record_agent_tool_failure(&self, agent_id: &str, tool_name: &str) {
        if let Ok(mut maps) = self.per_tool.lock() {
            *maps
                .agent_failures
                .entry(agent_id.to_owned())
                .or_default()
                .entry(tool_name.to_owned())
                .or_insert(0) += 1;
        }
    }

    /// Snapshot of per-agent, per-tool call counts.
    pub fn per_agent_tool_calls_snapshot(&self) -> HashMap<String, HashMap<String, u64>> {
        self.per_tool
            .lock()
            .map(|m| m.agent_calls.clone())
            .unwrap_or_default()
    }

    /// Snapshot of per-agent, per-tool failure counts.
    pub fn per_agent_tool_failures_snapshot(&self) -> HashMap<String, HashMap<String, u64>> {
        self.per_tool
            .lock()
            .map(|m| m.agent_failures.clone())
            .unwrap_or_default()
    }

    /// Capture a complete snapshot of all counters, including per-tool breakdowns.
    ///
    /// This is the preferred alternative to [`to_snapshot`] — it returns a
    /// named [`MetricsSnapshot`] struct instead of an opaque tuple.
    ///
    /// [`to_snapshot`]: RuntimeMetrics::to_snapshot
    pub fn snapshot(&self) -> MetricsSnapshot {
        // Acquire the single per-tool lock once for all four maps.
        let (per_tool_calls, per_tool_failures, per_agent_tool_calls, per_agent_tool_failures) =
            self.per_tool
                .lock()
                .map(|m| {
                    (
                        m.calls.clone(),
                        m.failures.clone(),
                        m.agent_calls.clone(),
                        m.agent_failures.clone(),
                    )
                })
                .unwrap_or_default();

        MetricsSnapshot {
            active_sessions: self.active_sessions.load(Ordering::Relaxed),
            total_sessions: self.total_sessions.load(Ordering::Relaxed),
            total_steps: self.total_steps.load(Ordering::Relaxed),
            total_tool_calls: self.total_tool_calls.load(Ordering::Relaxed),
            failed_tool_calls: self.failed_tool_calls.load(Ordering::Relaxed),
            backpressure_shed_count: self.backpressure_shed_count.load(Ordering::Relaxed),
            memory_recall_count: self.memory_recall_count.load(Ordering::Relaxed),
            checkpoint_errors: self.checkpoint_errors.load(Ordering::Relaxed),
            per_tool_calls,
            per_tool_failures,
            step_latency_buckets: self.step_latency.buckets(),
            step_latency_mean_ms: self.step_latency.mean_ms(),
            per_agent_tool_calls,
            per_agent_tool_failures,
        }
    }

    /// Record a step latency sample.
    pub fn record_step_latency(&self, ms: u64) {
        self.step_latency.record(ms);
    }

    /// Reset all counters to zero.
    ///
    /// Intended for testing. In production, counters are monotonically increasing.
    pub fn reset(&self) {
        self.active_sessions.store(0, Ordering::Relaxed);
        self.total_sessions.store(0, Ordering::Relaxed);
        self.total_steps.store(0, Ordering::Relaxed);
        self.total_tool_calls.store(0, Ordering::Relaxed);
        self.failed_tool_calls.store(0, Ordering::Relaxed);
        self.backpressure_shed_count.store(0, Ordering::Relaxed);
        self.memory_recall_count.store(0, Ordering::Relaxed);
        self.checkpoint_errors.store(0, Ordering::Relaxed);
        if let Ok(mut maps) = self.per_tool.lock() {
            maps.calls.clear();
            maps.failures.clear();
            maps.agent_calls.clear();
            maps.agent_failures.clear();
        }
        self.step_latency.reset();
    }

    /// Return the fraction of tool calls that failed: `failed / total`.
    ///
    /// Returns `0.0` if no tool calls have been recorded.
    pub fn failure_rate(&self) -> f64 {
        let total = self.total_tool_calls.load(Ordering::Relaxed);
        if total == 0 {
            return 0.0;
        }
        let failed = self.failed_tool_calls.load(Ordering::Relaxed);
        failed as f64 / total as f64
    }

    /// Return the fraction of tool calls that succeeded: `1.0 - failure_rate()`.
    ///
    /// Returns `1.0` if no tool calls have been recorded (vacuously all succeeded).
    pub fn success_rate(&self) -> f64 {
        1.0 - self.failure_rate()
    }

    /// Return `true` if there is at least one active (in-progress) session.
    pub fn is_active(&self) -> bool {
        self.active_sessions.load(Ordering::Relaxed) > 0
    }

    /// Return the 50th-percentile (median) step latency in milliseconds.
    ///
    /// Delegates to [`LatencyHistogram::p50`] on the histogram tracked by
    /// this `RuntimeMetrics` instance.  Returns `0` if no steps have been recorded.
    pub fn step_latency_p50(&self) -> u64 {
        self.step_latency.p50()
    }

    /// Return the 99th-percentile step latency in milliseconds.
    ///
    /// Delegates to [`LatencyHistogram::p99`].  Returns `0` if no steps have
    /// been recorded.
    pub fn step_latency_p99(&self) -> u64 {
        self.step_latency.p99()
    }

    /// Return the 95th-percentile step latency in milliseconds.
    ///
    /// Delegates to [`LatencyHistogram::p95`].  Returns `0` if no steps have
    /// been recorded.
    pub fn step_latency_p95(&self) -> u64 {
        self.step_latency.p95()
    }

    /// Return the 75th-percentile step latency in milliseconds.
    ///
    /// Delegates to [`LatencyHistogram::p75`].  Returns `0` if no steps have
    /// been recorded.
    pub fn step_latency_p75(&self) -> u64 {
        self.step_latency.p75()
    }

    /// Return the standard deviation of recorded step latencies in milliseconds.
    ///
    /// Delegates to [`LatencyHistogram::std_dev_ms`].  Returns `0.0` when fewer
    /// than two samples have been recorded.
    pub fn step_latency_std_dev_ms(&self) -> f64 {
        self.step_latency.std_dev_ms()
    }

    /// Return the name of the tool with the highest call count, or `None` if no
    /// tools have been called yet.
    ///
    /// When multiple tools share the maximum call count, the one that sorts
    /// earliest alphabetically is returned for deterministic output.
    pub fn most_used_tool(&self) -> Option<String> {
        let snap = self.per_tool_calls_snapshot();
        snap.into_iter()
            .max_by(|a, b| a.1.cmp(&b.1).then_with(|| b.0.cmp(&a.0)))
            .map(|(name, _)| name)
    }

    /// Return the ratio of failed tool calls to total tool calls.
    ///
    /// Returns `0.0` when no tool calls have been recorded.  Unlike the
    /// per-tool [`tool_failure_rate`] on `MetricsSnapshot`, this operates on
    /// the live atomic counters for the current process without snapshotting.
    ///
    /// [`tool_failure_rate`]: MetricsSnapshot::tool_failure_rate
    pub fn tool_call_to_failure_ratio(&self) -> f64 {
        let total = self.total_tool_calls.load(Ordering::Relaxed);
        if total == 0 {
            return 0.0;
        }
        self.failed_tool_calls.load(Ordering::Relaxed) as f64 / total as f64
    }

    /// Return the fraction of all sessions that are currently active.
    ///
    /// Computed as `active_sessions / total_sessions`.  Returns `0.0` when no
    /// sessions have been started.
    pub fn active_session_rate(&self) -> f64 {
        let total = self.total_sessions.load(Ordering::Relaxed);
        if total == 0 {
            return 0.0;
        }
        self.active_sessions.load(Ordering::Relaxed) as f64 / total as f64
    }

    /// Return the average number of memory recall operations per session.
    ///
    /// Computed as `memory_recall_count / total_sessions`.  Returns `0.0`
    /// when no sessions have been started.
    pub fn memory_recall_per_session(&self) -> f64 {
        let total = self.total_sessions.load(Ordering::Relaxed);
        if total == 0 {
            return 0.0;
        }
        self.memory_recall_count.load(Ordering::Relaxed) as f64 / total as f64
    }

    /// Return the fraction of all ReAct steps that resulted in a tool failure.
    ///
    /// Computed as `failed_tool_calls / total_steps`.  Returns `0.0` when
    /// no steps have been executed.
    pub fn step_error_rate(&self) -> f64 {
        let steps = self.total_steps.load(Ordering::Relaxed);
        if steps == 0 {
            return 0.0;
        }
        self.failed_tool_calls.load(Ordering::Relaxed) as f64 / steps as f64
    }

    /// Return the combined count of all error events: failed tool calls plus
    /// checkpoint errors.
    ///
    /// Useful as a single "total errors" gauge for alerting.
    pub fn total_errors(&self) -> u64 {
        self.failed_tool_calls.load(Ordering::Relaxed)
            + self.checkpoint_errors.load(Ordering::Relaxed)
    }

    /// Return all tool names recorded in the call counter that contain
    /// `substr` as a substring (case-sensitive).
    ///
    /// Returns an empty `Vec` when no matching tool names are found.
    pub fn tool_names_containing(&self, substr: &str) -> Vec<String> {
        let snap = self.per_tool_calls_snapshot();
        let mut names: Vec<String> = snap
            .into_keys()
            .filter(|name| name.contains(substr))
            .collect();
        names.sort_unstable();
        names
    }

    /// Return `true` if any tool has recorded at least one failure.
    ///
    /// A convenience shorthand for `failed_tool_calls() > 0`.
    pub fn has_failed_tools(&self) -> bool {
        self.failed_tool_calls() > 0
    }

    /// Return tool names sorted by total call count in descending order.
    ///
    /// The highest-called tool appears first.  Ties are broken alphabetically.
    /// Returns an empty `Vec` when no tools have been called.
    pub fn tool_names_by_call_count(&self) -> Vec<String> {
        let snap = self.per_tool_calls_snapshot();
        let mut pairs: Vec<(String, u64)> = snap.into_iter().collect();
        pairs.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
        pairs.into_iter().map(|(name, _)| name).collect()
    }

    /// Return the average number of memory recalls per recorded step.
    ///
    /// Computed as `memory_recall_count / total_steps`.  Returns `0.0`
    /// when no steps have been recorded to avoid division by zero.
    pub fn avg_memory_recalls_per_step(&self) -> f64 {
        let steps = self.total_steps();
        if steps == 0 {
            return 0.0;
        }
        self.memory_recall_count() as f64 / steps as f64
    }

    /// Return the average number of tool failures per completed session.
    ///
    /// Computed as `failed_tool_calls / total_sessions`.  Returns `0.0`
    /// when no sessions have been recorded to avoid division by zero.
    pub fn avg_tool_failures_per_session(&self) -> f64 {
        let sessions = self.total_sessions();
        if sessions == 0 {
            return 0.0;
        }
        self.failed_tool_calls() as f64 / sessions as f64
    }

    /// Return the ratio of total tool calls to total memory recalls.
    ///
    /// Returns `0.0` when no memory recalls have been recorded to avoid
    /// division by zero.
    pub fn tool_calls_per_memory_recall(&self) -> f64 {
        let recalls = self.memory_recall_count();
        if recalls == 0 {
            return 0.0;
        }
        self.total_tool_calls() as f64 / recalls as f64
    }

    /// Return the ratio of memory recalls to total tool calls.
    ///
    /// Returns `0.0` when no tool calls have been recorded to avoid division
    /// by zero.
    pub fn memory_recalls_per_tool_call(&self) -> f64 {
        let calls = self.total_tool_calls();
        if calls == 0 {
            return 0.0;
        }
        self.memory_recall_count() as f64 / calls as f64
    }

    /// Return the fraction of completed steps that recorded at least one tool
    /// failure.  Computed as `failed_tool_calls / total_steps`.
    ///
    /// Returns `0.0` when no steps have been recorded.
    pub fn step_failure_rate(&self) -> f64 {
        let steps = self.total_steps.load(std::sync::atomic::Ordering::Relaxed);
        if steps == 0 {
            return 0.0;
        }
        self.failed_tool_calls() as f64 / steps as f64
    }

    /// Return the fraction of total tool calls that were shed due to
    /// backpressure.  Computed as `backpressure_shed / total_tool_calls`.
    ///
    /// Returns `0.0` when no tool calls have been made.
    pub fn total_backpressure_shed_pct(&self) -> f64 {
        let calls = self.total_tool_calls();
        if calls == 0 {
            return 0.0;
        }
        self.backpressure_shed_count() as f64 / calls as f64
    }

    /// Return the name of the tool with the highest failure rate
    /// (`failures / calls`), or `None` when no tool has been called.
    ///
    /// Tools with zero calls are excluded.
    pub fn tool_with_highest_failure_rate(&self) -> Option<String> {
        let calls = self.per_tool_calls_snapshot();
        let fails = self.per_tool_failures_snapshot();
        calls
            .iter()
            .filter(|(_, &c)| c > 0)
            .map(|(name, &c)| {
                let f = fails.get(name).copied().unwrap_or(0);
                (name.clone(), f as f64 / c as f64)
            })
            .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(name, _)| name)
    }

    /// Return the total number of times `name` has been called.
    ///
    /// Returns `0` when the tool has never been called.
    pub fn tool_call_count_for(&self, name: &str) -> u64 {
        self.per_tool_calls_snapshot()
            .get(name)
            .copied()
            .unwrap_or(0)
    }

    /// Return the name of the most-called tool, or `None` if no tools have
    /// been called yet.
    pub fn top_called_tool(&self) -> Option<String> {
        self.per_tool_calls_snapshot()
            .into_iter()
            .max_by_key(|(_, c)| *c)
            .map(|(name, _)| name)
    }

    /// Return the average step latency in milliseconds.
    ///
    /// Returns `0.0` when no step latencies have been recorded.
    pub fn avg_step_latency_ms(&self) -> f64 {
        self.step_latency.mean_ms()
    }

    /// Return the number of distinct tool names that have been called at least
    /// once.
    pub fn distinct_tools_called(&self) -> usize {
        self.per_tool_calls_snapshot().len()
    }

    /// Return the failure rate (failed / total) for the given tool `name`.
    ///
    /// Returns `0.0` when the tool has never been called or doesn't exist.
    pub fn failure_rate_for(&self, name: &str) -> f64 {
        let calls = self.tool_call_count_for(name);
        if calls == 0 {
            return 0.0;
        }
        let failures = self
            .per_tool_failures_snapshot()
            .get(name)
            .copied()
            .unwrap_or(0);
        failures as f64 / calls as f64
    }

    /// Return the total number of checkpoint errors recorded since the runtime
    /// started.
    pub fn checkpoint_errors_count(&self) -> u64 {
        self.checkpoint_errors.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Return the names of agents that have at least one per-agent tool
    /// failure recorded.
    pub fn agents_with_failures(&self) -> Vec<String> {
        self.per_agent_tool_failures_snapshot()
            .into_iter()
            .filter(|(_, tools)| tools.values().any(|&c| c > 0))
            .map(|(agent_id, _)| agent_id)
            .collect()
    }

    /// Return the total number of per-agent tool failures recorded across all
    /// agents and all tools.
    pub fn total_agent_failures(&self) -> u64 {
        self.per_agent_tool_failures_snapshot()
            .values()
            .flat_map(|m| m.values())
            .sum()
    }

    /// Return the average number of tool calls per recorded step, or `0.0`
    /// when no steps have been recorded.
    pub fn per_step_tool_call_rate(&self) -> f64 {
        let steps = self.total_steps();
        if steps == 0 {
            return 0.0;
        }
        let calls: u64 = self.per_tool_calls_snapshot().values().sum();
        calls as f64 / steps as f64
    }

    /// Return agent IDs that have recorded tool calls but zero failures.
    pub fn agents_with_no_failures(&self) -> Vec<String> {
        let calls = self.per_agent_tool_calls_snapshot();
        let failures = self.per_agent_tool_failures_snapshot();
        let mut result: Vec<String> = calls
            .keys()
            .filter(|agent| {
                let total_failures: u64 = failures
                    .get(*agent)
                    .map(|m| m.values().sum())
                    .unwrap_or(0);
                total_failures == 0
            })
            .cloned()
            .collect();
        result.sort_unstable();
        result
    }

    /// Return a sorted list of tool names whose total call count exceeds
    /// `threshold`.
    ///
    /// Useful for identifying heavily-exercised tools above a given activity
    /// level.  Returns an empty `Vec` when no tool meets the criterion.
    pub fn tools_with_calls_above(&self, threshold: u64) -> Vec<String> {
        let snap = self.per_tool_calls_snapshot();
        let mut names: Vec<String> = snap
            .into_iter()
            .filter(|(_, count)| *count > threshold)
            .map(|(name, _)| name)
            .collect();
        names.sort_unstable();
        names
    }

    /// Return the total number of tool calls recorded for the given `agent_id`.
    ///
    /// Returns `0` when the agent has never called a tool.
    pub fn agent_tool_call_count(&self, agent_id: &str) -> u64 {
        let snap = self.per_agent_tool_calls_snapshot();
        snap.get(agent_id)
            .map(|m| m.values().sum())
            .unwrap_or(0)
    }

    /// Return the average number of tool calls per total session.
    ///
    /// Returns `0.0` when no sessions have been started.
    pub fn tool_calls_per_session(&self) -> f64 {
        let sessions = self.total_sessions();
        if sessions == 0 {
            return 0.0;
        }
        self.total_tool_calls() as f64 / sessions as f64
    }

    /// Return the names of all tools that have been called at least once but
    /// have recorded zero failures.
    pub fn failure_free_tools(&self) -> Vec<String> {
        let calls = self.per_tool_calls_snapshot();
        let failures = self.per_tool_failures_snapshot();
        calls
            .into_keys()
            .filter(|name| failures.get(name).copied().unwrap_or(0) == 0)
            .collect()
    }

    /// Return the top `n` tools by total call count, sorted descending.
    ///
    /// Returns fewer than `n` entries if fewer tools have been called.
    pub fn top_tools_by_calls(&self, n: usize) -> Vec<(String, u64)> {
        let snap = self.per_tool_calls_snapshot();
        let mut pairs: Vec<(String, u64)> = snap.into_iter().collect();
        pairs.sort_unstable_by(|a, b| b.1.cmp(&a.1));
        pairs.truncate(n);
        pairs
    }

    /// Return the top `n` tools by total failure count, sorted descending.
    ///
    /// Analogous to [`top_tools_by_calls`]; returns fewer than `n` entries if
    /// fewer tools have recorded failures.
    ///
    /// [`top_tools_by_calls`]: RuntimeMetrics::top_tools_by_calls
    pub fn top_tools_by_failures(&self, n: usize) -> Vec<(String, u64)> {
        let snap = self.per_tool_failures_snapshot();
        let mut pairs: Vec<(String, u64)> = snap.into_iter().collect();
        pairs.sort_unstable_by(|a, b| b.1.cmp(&a.1));
        pairs.truncate(n);
        pairs
    }

    /// Return the sum of all recorded step latencies in milliseconds.
    pub fn total_step_latency_ms(&self) -> u64 {
        self.step_latency.sum_ms()
    }

    /// Return the average number of tool calls per recorded step.
    ///
    /// Returns `0.0` when no steps have been recorded to avoid division by
    /// zero.
    pub fn avg_calls_per_step(&self) -> f64 {
        let steps = self.total_steps.load(Ordering::Relaxed);
        if steps == 0 {
            return 0.0;
        }
        self.total_tool_calls.load(Ordering::Relaxed) as f64 / steps as f64
    }

    /// Return the ratio of memory recall events to total steps recorded.
    ///
    /// Indicates how memory-intensive the agent's operation is. Returns `0.0`
    /// when no steps have been recorded to avoid division by zero.
    pub fn memory_pressure_ratio(&self) -> f64 {
        let steps = self.total_steps.load(Ordering::Relaxed);
        if steps == 0 {
            return 0.0;
        }
        self.memory_recall_count.load(Ordering::Relaxed) as f64 / steps as f64
    }

    /// Return the ratio of backpressure-shed events to total steps recorded.
    ///
    /// Higher values indicate significant load shedding. Returns `0.0` when no
    /// steps have been recorded to avoid division by zero.
    pub fn backpressure_ratio(&self) -> f64 {
        let steps = self.total_steps.load(Ordering::Relaxed);
        if steps == 0 {
            return 0.0;
        }
        self.backpressure_shed_count.load(Ordering::Relaxed) as f64 / steps as f64
    }

    /// Return the ratio of total sessions to total steps recorded.
    ///
    /// Higher values indicate shorter average sessions. Returns `0.0` when no
    /// steps have been recorded to avoid division by zero.
    pub fn sessions_per_step(&self) -> f64 {
        let steps = self.total_steps.load(Ordering::Relaxed);
        if steps == 0 {
            return 0.0;
        }
        self.total_sessions.load(Ordering::Relaxed) as f64 / steps as f64
    }

    /// Return `true` if any step-latency samples have been recorded.
    ///
    /// Useful for guard-checking before using latency percentile methods.
    pub fn has_latency_data(&self) -> bool {
        self.total_steps.load(Ordering::Relaxed) > 0
    }

    /// Return the ratio of `failed_tool_calls` to `total_tool_calls`.
    ///
    /// Returns `0.0` when no tool calls have been recorded (avoids
    /// division-by-zero).
    pub fn global_failure_rate(&self) -> f64 {
        let total = self.total_tool_calls.load(Ordering::Relaxed);
        if total == 0 {
            return 0.0;
        }
        self.failed_tool_calls.load(Ordering::Relaxed) as f64 / total as f64
    }

    /// Return the total number of tool calls recorded across all agents in
    /// the per-agent breakdown.
    ///
    /// This sums the per-agent, per-tool call counters and is independent of
    /// the global `total_tool_calls` counter, which is incremented by a
    /// different code path.
    pub fn total_agent_tool_calls(&self) -> u64 {
        self.per_agent_tool_calls_snapshot()
            .values()
            .flat_map(|tool_map| tool_map.values())
            .sum()
    }

    /// Return the number of distinct agents recorded in the per-agent tool
    /// call tracking.
    ///
    /// Returns `0` when no per-agent calls have been recorded.
    pub fn agent_tool_count(&self) -> usize {
        self.per_agent_tool_calls_snapshot().len()
    }

    /// Return `true` if any per-agent tool call has been recorded.
    ///
    /// A lighter alternative to checking `agent_tool_count() > 0`; avoids
    /// building the full per-agent snapshot map when a boolean answer suffices.
    pub fn has_recorded_agent_calls(&self) -> bool {
        !self.per_agent_tool_calls_snapshot().is_empty()
    }

    /// Return the current count of active (in-progress) sessions.
    pub fn active_session_count(&self) -> usize {
        self.active_sessions.load(Ordering::Relaxed)
    }

    /// Return the ratio of `memory_recall_count` to `total_sessions`.
    ///
    /// Returns `0.0` when no sessions have been recorded (avoids
    /// division-by-zero).
    pub fn memory_to_session_ratio(&self) -> f64 {
        let sessions = self.total_sessions.load(Ordering::Relaxed);
        if sessions == 0 {
            return 0.0;
        }
        self.memory_recall_count.load(Ordering::Relaxed) as f64 / sessions as f64
    }

    /// Return the total accumulated step latency in milliseconds divided by
    /// `total_sessions`.
    ///
    /// Returns `0.0` when no sessions have been recorded.
    pub fn total_latency_per_session(&self) -> f64 {
        let sessions = self.total_sessions.load(Ordering::Relaxed);
        if sessions == 0 {
            return 0.0;
        }
        self.step_latency.sum_ms() as f64 / sessions as f64
    }

    /// Capture a snapshot of global counters as plain integers.
    ///
    /// Returns `(active_sessions, total_sessions, total_steps,
    ///           total_tool_calls, failed_tool_calls,
    ///           backpressure_shed_count, memory_recall_count)`.
    /// For per-tool breakdowns use [`per_tool_calls_snapshot`] and
    /// [`per_tool_failures_snapshot`].
    ///
    /// # Deprecation
    ///
    /// Prefer [`snapshot`] which returns the named [`MetricsSnapshot`] struct
    /// and includes per-tool, per-agent, and histogram data.  This method
    /// returns an anonymous tuple whose field order is easy to misread.
    ///
    /// [`snapshot`]: RuntimeMetrics::snapshot
    /// [`per_tool_calls_snapshot`]: RuntimeMetrics::per_tool_calls_snapshot
    /// [`per_tool_failures_snapshot`]: RuntimeMetrics::per_tool_failures_snapshot
    #[deprecated(since = "1.0.3", note = "use `snapshot()` which returns the named MetricsSnapshot struct")]
    pub fn to_snapshot(&self) -> (usize, u64, u64, u64, u64, u64, u64) {
        (
            self.active_sessions.load(Ordering::Relaxed),
            self.total_sessions.load(Ordering::Relaxed),
            self.total_steps.load(Ordering::Relaxed),
            self.total_tool_calls.load(Ordering::Relaxed),
            self.failed_tool_calls.load(Ordering::Relaxed),
            self.backpressure_shed_count.load(Ordering::Relaxed),
            self.memory_recall_count.load(Ordering::Relaxed),
        )
    }
}

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

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

    #[test]
    fn test_metrics_new_returns_arc_with_zero_counters() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.active_sessions(), 0);
        assert_eq!(m.total_sessions(), 0);
        assert_eq!(m.total_steps(), 0);
        assert_eq!(m.total_tool_calls(), 0);
        assert_eq!(m.failed_tool_calls(), 0);
        assert_eq!(m.backpressure_shed_count(), 0);
        assert_eq!(m.memory_recall_count(), 0);
    }

    #[test]
    fn test_active_sessions_increments_and_decrements() {
        let m = RuntimeMetrics::new();
        m.active_sessions.fetch_add(1, Ordering::Relaxed);
        assert_eq!(m.active_sessions(), 1);
        m.active_sessions.fetch_sub(1, Ordering::Relaxed);
        assert_eq!(m.active_sessions(), 0);
    }

    #[test]
    fn test_total_sessions_increments() {
        let m = RuntimeMetrics::new();
        m.total_sessions.fetch_add(1, Ordering::Relaxed);
        m.total_sessions.fetch_add(1, Ordering::Relaxed);
        assert_eq!(m.total_sessions(), 2);
    }

    #[test]
    fn test_total_steps_increments() {
        let m = RuntimeMetrics::new();
        m.total_steps.fetch_add(5, Ordering::Relaxed);
        assert_eq!(m.total_steps(), 5);
    }

    #[test]
    fn test_total_tool_calls_increments() {
        let m = RuntimeMetrics::new();
        m.total_tool_calls.fetch_add(3, Ordering::Relaxed);
        assert_eq!(m.total_tool_calls(), 3);
    }

    #[test]
    fn test_failed_tool_calls_increments() {
        let m = RuntimeMetrics::new();
        m.failed_tool_calls.fetch_add(2, Ordering::Relaxed);
        assert_eq!(m.failed_tool_calls(), 2);
    }

    #[test]
    fn test_backpressure_shed_count_increments() {
        let m = RuntimeMetrics::new();
        m.backpressure_shed_count.fetch_add(7, Ordering::Relaxed);
        assert_eq!(m.backpressure_shed_count(), 7);
    }

    #[test]
    fn test_memory_recall_count_increments() {
        let m = RuntimeMetrics::new();
        m.memory_recall_count.fetch_add(4, Ordering::Relaxed);
        assert_eq!(m.memory_recall_count(), 4);
    }

    #[test]
    fn test_reset_zeroes_all_counters() {
        let m = RuntimeMetrics::new();
        m.active_sessions.store(3, Ordering::Relaxed);
        m.total_sessions.store(10, Ordering::Relaxed);
        m.total_steps.store(50, Ordering::Relaxed);
        m.total_tool_calls.store(20, Ordering::Relaxed);
        m.failed_tool_calls.store(2, Ordering::Relaxed);
        m.backpressure_shed_count.store(1, Ordering::Relaxed);
        m.memory_recall_count.store(8, Ordering::Relaxed);

        m.reset();

        assert_eq!(m.active_sessions(), 0);
        assert_eq!(m.total_sessions(), 0);
        assert_eq!(m.total_steps(), 0);
        assert_eq!(m.total_tool_calls(), 0);
        assert_eq!(m.failed_tool_calls(), 0);
        assert_eq!(m.backpressure_shed_count(), 0);
        assert_eq!(m.memory_recall_count(), 0);
    }

    #[test]
    fn test_to_snapshot_captures_correct_values() {
        let m = RuntimeMetrics::new();
        m.active_sessions.store(1, Ordering::Relaxed);
        m.total_sessions.store(2, Ordering::Relaxed);
        m.total_steps.store(3, Ordering::Relaxed);
        m.total_tool_calls.store(4, Ordering::Relaxed);
        m.failed_tool_calls.store(5, Ordering::Relaxed);
        m.backpressure_shed_count.store(6, Ordering::Relaxed);
        m.memory_recall_count.store(7, Ordering::Relaxed);

        let snap = m.to_snapshot();
        assert_eq!(snap, (1, 2, 3, 4, 5, 6, 7));
    }

    #[test]
    fn test_metrics_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<RuntimeMetrics>();
    }

    #[test]
    fn test_multiple_increments_are_cumulative() {
        let m = RuntimeMetrics::new();
        for _ in 0..100 {
            m.total_sessions.fetch_add(1, Ordering::Relaxed);
        }
        assert_eq!(m.total_sessions(), 100);
    }

    #[test]
    fn test_arc_clone_shares_state() {
        let m = RuntimeMetrics::new();
        let m2 = Arc::clone(&m);
        m.total_sessions.fetch_add(1, Ordering::Relaxed);
        assert_eq!(m2.total_sessions(), 1);
    }

    // ── Per-tool metrics ──────────────────────────────────────────────────────

    #[test]
    fn test_record_tool_call_increments_global_and_per_tool() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("search");
        m.record_tool_call("lookup");
        assert_eq!(m.total_tool_calls(), 3);
        let snap = m.per_tool_calls_snapshot();
        assert_eq!(snap.get("search").copied(), Some(2));
        assert_eq!(snap.get("lookup").copied(), Some(1));
    }

    #[test]
    fn test_record_tool_failure_increments_global_and_per_tool() {
        let m = RuntimeMetrics::new();
        m.record_tool_failure("search");
        m.record_tool_failure("lookup");
        m.record_tool_failure("search");
        assert_eq!(m.failed_tool_calls(), 3);
        let snap = m.per_tool_failures_snapshot();
        assert_eq!(snap.get("search").copied(), Some(2));
        assert_eq!(snap.get("lookup").copied(), Some(1));
    }

    #[test]
    fn test_reset_clears_per_tool_counters() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("foo");
        m.record_tool_failure("foo");
        m.reset();
        assert!(m.per_tool_calls_snapshot().is_empty());
        assert!(m.per_tool_failures_snapshot().is_empty());
    }

    #[test]
    fn test_per_tool_snapshot_is_independent_for_unknown_tools() {
        let m = RuntimeMetrics::new();
        let snap = m.per_tool_calls_snapshot();
        assert!(snap.is_empty());
    }

    // ── LatencyHistogram ───────────────────────────────────────────────────────

    #[test]
    fn test_latency_histogram_records_sample() {
        let h = LatencyHistogram::default();
        h.record(10);
        assert_eq!(h.count(), 1);
    }

    #[test]
    fn test_latency_histogram_mean_ms() {
        let h = LatencyHistogram::default();
        h.record(10);
        h.record(20);
        assert!((h.mean_ms() - 15.0).abs() < 1e-5);
    }

    #[test]
    fn test_latency_histogram_buckets_correct_bucket() {
        let h = LatencyHistogram::default();
        h.record(3); // falls in ≤5ms bucket (index 1)
        let buckets = h.buckets();
        // bucket at index 1 is ≤5ms
        assert_eq!(buckets[1].1, 1, "3ms should land in ≤5ms bucket");
        // other buckets should be zero
        assert_eq!(buckets[0].1, 0);
        assert_eq!(buckets[2].1, 0);
    }

    // ── MetricsSnapshot ───────────────────────────────────────────────────────

    #[test]
    fn test_snapshot_returns_all_fields() {
        let m = RuntimeMetrics::new();
        m.active_sessions.store(1, Ordering::Relaxed);
        m.total_sessions.store(2, Ordering::Relaxed);
        m.total_steps.store(3, Ordering::Relaxed);
        m.backpressure_shed_count.store(6, Ordering::Relaxed);
        m.memory_recall_count.store(7, Ordering::Relaxed);
        // Use record_* methods so global and per-tool counters stay consistent.
        m.record_tool_call("my_tool");
        m.record_tool_call("my_tool");
        m.record_tool_failure("my_tool");

        let snap = m.snapshot();
        assert_eq!(snap.active_sessions, 1);
        assert_eq!(snap.total_sessions, 2);
        assert_eq!(snap.total_steps, 3);
        assert_eq!(snap.total_tool_calls, 2);
        assert_eq!(snap.failed_tool_calls, 1);
        assert_eq!(snap.backpressure_shed_count, 6);
        assert_eq!(snap.memory_recall_count, 7);
        assert_eq!(snap.per_tool_calls.get("my_tool").copied(), Some(2));
        assert_eq!(snap.per_tool_failures.get("my_tool").copied(), Some(1));
    }

    #[test]
    fn test_snapshot_default_is_zeroed() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.active_sessions, 0);
        assert_eq!(snap.total_sessions, 0);
        assert_eq!(snap.total_steps, 0);
        assert!(snap.per_tool_calls.is_empty());
        assert!(snap.per_tool_failures.is_empty());
    }

    // ── #8 MetricsSnapshot histogram fields ───────────────────────────────────

    #[test]
    fn test_metrics_snapshot_contains_all_fields() {
        let m = RuntimeMetrics::new();
        m.record_step_latency(5);
        m.record_step_latency(200);
        let snap = m.snapshot();
        // Should have 7 buckets
        assert_eq!(snap.step_latency_buckets.len(), 7);
        assert!(snap.step_latency_mean_ms > 0.0);
    }

    // ── #9 per-agent tool call tracking ──────────────────────────────────────

    #[test]
    fn test_per_agent_tool_call_tracking() {
        let m = RuntimeMetrics::new();
        m.record_agent_tool_call("agent-1", "search");
        m.record_agent_tool_call("agent-1", "search");
        m.record_agent_tool_call("agent-2", "lookup");
        m.record_agent_tool_failure("agent-1", "search");

        let calls = m.per_agent_tool_calls_snapshot();
        assert_eq!(calls.get("agent-1").and_then(|t| t.get("search")).copied(), Some(2));
        assert_eq!(calls.get("agent-2").and_then(|t| t.get("lookup")).copied(), Some(1));

        let failures = m.per_agent_tool_failures_snapshot();
        assert_eq!(failures.get("agent-1").and_then(|t| t.get("search")).copied(), Some(1));

        // Also check snapshot includes them
        let snap = m.snapshot();
        assert_eq!(snap.per_agent_tool_calls.get("agent-1").and_then(|t| t.get("search")).copied(), Some(2));

        // Reset clears them
        m.reset();
        assert!(m.per_agent_tool_calls_snapshot().is_empty());
        assert!(m.per_agent_tool_failures_snapshot().is_empty());
    }

    // ── New API tests (Rounds 4-8) ────────────────────────────────────────────

    #[test]
    fn test_latency_histogram_min_max_ms() {
        let h = LatencyHistogram::default();
        assert!(h.min_ms().is_none());
        assert!(h.max_ms().is_none());

        h.record(3);  // bucket 1 (≤5ms)
        h.record(200); // bucket 5 (≤500ms)
        assert!(h.min_ms().is_some());
        assert!(h.max_ms().is_some());
        assert!(h.min_ms().unwrap() <= h.max_ms().unwrap());
    }

    #[test]
    fn test_latency_histogram_p50_p95_p99() {
        let h = LatencyHistogram::default();
        for _ in 0..100 {
            h.record(5); // all in ≤5ms bucket
        }
        // p50, p95, p99 should all resolve to the same bucket bound
        let p50 = h.p50();
        let p95 = h.p95();
        let p99 = h.p99();
        assert_eq!(p50, p95);
        assert_eq!(p95, p99);
    }

    #[test]
    fn test_metrics_snapshot_delta_reflects_increments() {
        let m = RuntimeMetrics::new();
        let before = m.snapshot();
        m.total_steps.fetch_add(5, std::sync::atomic::Ordering::Relaxed);
        m.total_tool_calls.fetch_add(3, std::sync::atomic::Ordering::Relaxed);
        let after = m.snapshot();
        let delta = MetricsSnapshot::delta(&after, &before);
        assert_eq!(delta.total_steps, 5);
        assert_eq!(delta.total_tool_calls, 3);
    }

    #[test]
    fn test_metrics_snapshot_display_contains_key_fields() {
        let m = RuntimeMetrics::new();
        let snap = m.snapshot();
        let s = snap.to_string();
        assert!(s.contains("sessions"));
        assert!(s.contains("steps"));
        assert!(s.contains("latency_mean"));
    }

    #[test]
    fn test_failure_rate_zero_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.failure_rate(), 0.0);
    }

    #[test]
    fn test_failure_rate_correct_proportion() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("tool_a");
        m.record_tool_call("tool_a");
        m.record_tool_failure("tool_a");
        // 1 failure out of 2 total = 0.5
        assert!((m.failure_rate() - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_failure_rate_all_failed() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("x");
        m.record_tool_failure("x");
        assert!((m.failure_rate() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_top_tools_by_calls_returns_top_n() {
        let m = RuntimeMetrics::new();
        for _ in 0..5 { m.record_tool_call("a"); }
        for _ in 0..3 { m.record_tool_call("b"); }
        for _ in 0..1 { m.record_tool_call("c"); }
        let top = m.top_tools_by_calls(2);
        assert_eq!(top.len(), 2);
        assert_eq!(top[0].0, "a");
        assert_eq!(top[1].0, "b");
    }

    #[test]
    fn test_top_tools_by_calls_returns_all_when_n_exceeds_count() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("only");
        let top = m.top_tools_by_calls(10);
        assert_eq!(top.len(), 1);
        assert_eq!(top[0].0, "only");
    }

    #[test]
    fn test_metrics_snapshot_to_json_contains_key_fields() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("t");
        let snap = m.snapshot();
        let json = snap.to_json();
        assert!(json.get("total_sessions").is_some());
        assert!(json.get("total_steps").is_some());
        assert!(json.get("total_tool_calls").is_some());
    }

    #[test]
    fn test_metrics_snapshot_is_zero_on_new_metrics() {
        let m = RuntimeMetrics::new();
        assert!(m.snapshot().is_zero());
    }

    #[test]
    fn test_metrics_snapshot_is_zero_false_after_activity() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("t");
        assert!(!m.snapshot().is_zero());
    }

    #[test]
    fn test_tool_call_count_returns_per_tool_count() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("search");
        m.record_tool_call("fetch");
        let snap = m.snapshot();
        assert_eq!(snap.tool_call_count("search"), 2);
        assert_eq!(snap.tool_call_count("fetch"), 1);
        assert_eq!(snap.tool_call_count("absent"), 0);
    }

    #[test]
    fn test_tool_failure_count_returns_per_tool_failures() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("t");
        m.record_tool_failure("t");
        let snap = m.snapshot();
        assert_eq!(snap.tool_failure_count("t"), 1);
        assert_eq!(snap.tool_failure_count("other"), 0);
    }

    #[test]
    fn test_latency_histogram_clear_resets_counts() {
        let h = LatencyHistogram::default();
        h.record(10);
        h.record(20);
        assert_eq!(h.count(), 2);
        h.clear();
        assert_eq!(h.count(), 0);
    }

    #[test]
    fn test_metrics_snapshot_tool_names_sorted() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("zebra");
        m.record_tool_call("alpha");
        m.record_tool_call("mango");
        let snap = m.snapshot();
        assert_eq!(snap.tool_names(), vec!["alpha", "mango", "zebra"]);
    }

    // ── Round 4: top_tools_by_failures / LatencyHistogram::sum_ms ────────────

    #[test]
    fn test_top_tools_by_failures_returns_top_n_descending() {
        let m = RuntimeMetrics::new();
        m.record_tool_failure("a");
        m.record_tool_failure("a");
        m.record_tool_failure("a");
        m.record_tool_failure("b");
        m.record_tool_failure("b");
        m.record_tool_failure("c");
        let top2 = m.top_tools_by_failures(2);
        assert_eq!(top2.len(), 2);
        assert_eq!(top2[0].0, "a");
        assert_eq!(top2[0].1, 3);
        assert_eq!(top2[1].0, "b");
        assert_eq!(top2[1].1, 2);
    }

    #[test]
    fn test_top_tools_by_failures_n_larger_than_tools() {
        let m = RuntimeMetrics::new();
        m.record_tool_failure("only");
        let top = m.top_tools_by_failures(10);
        assert_eq!(top.len(), 1);
        assert_eq!(top[0].0, "only");
    }

    #[test]
    fn test_latency_histogram_sum_ms_accumulates() {
        let h = LatencyHistogram::default();
        h.record(100);
        h.record(200);
        h.record(300);
        assert_eq!(h.sum_ms(), 600);
    }

    #[test]
    fn test_latency_histogram_sum_ms_zero_when_empty() {
        let h = LatencyHistogram::default();
        assert_eq!(h.sum_ms(), 0);
    }

    // ── Round 16: mean_ms, failure_rate ──────────────────────────────────────

    #[test]
    fn test_latency_histogram_mean_ms_zero_when_empty() {
        let h = LatencyHistogram::default();
        assert_eq!(h.mean_ms(), 0.0);
    }

    #[test]
    fn test_latency_histogram_mean_ms_computes_average() {
        let h = LatencyHistogram::default();
        h.record(100);
        h.record(200);
        h.record(300);
        assert!((h.mean_ms() - 200.0).abs() < 1.0);
    }

    #[test]
    fn test_metrics_snapshot_failure_rate_zero_when_no_calls() {
        let m = RuntimeMetrics::new();
        let snap = m.snapshot();
        assert_eq!(snap.failure_rate(), 0.0);
    }

    #[test]
    fn test_metrics_snapshot_failure_rate_correct() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("t");
        m.record_tool_call("t");
        m.record_tool_failure("t");
        let snap = m.snapshot();
        assert!((snap.failure_rate() - 0.5).abs() < 1e-9);
    }

    // ── Round 20: success_rate / is_active / checkpoint_errors ────────────────

    #[test]
    fn test_success_rate_one_when_no_failures() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("x");
        assert!((m.success_rate() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_success_rate_half_when_half_failed() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("x");
        m.record_tool_call("x");
        m.record_tool_failure("x");
        assert!((m.success_rate() - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_success_rate_one_when_no_calls() {
        let m = RuntimeMetrics::new();
        // Vacuously all succeeded — no calls means success_rate = 1.0
        assert!((m.success_rate() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_is_active_false_when_no_sessions() {
        let m = RuntimeMetrics::new();
        assert!(!m.is_active());
    }

    #[test]
    fn test_is_active_true_when_session_active() {
        let m = RuntimeMetrics::new();
        m.active_sessions.fetch_add(1, Ordering::Relaxed);
        assert!(m.is_active());
        m.active_sessions.fetch_sub(1, Ordering::Relaxed);
        assert!(!m.is_active());
    }

    #[test]
    fn test_checkpoint_errors_increments() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.checkpoint_errors(), 0);
        m.checkpoint_errors.fetch_add(3, Ordering::Relaxed);
        assert_eq!(m.checkpoint_errors(), 3);
    }

    #[test]
    fn test_checkpoint_errors_reset_to_zero() {
        let m = RuntimeMetrics::new();
        m.checkpoint_errors.fetch_add(5, Ordering::Relaxed);
        m.reset();
        assert_eq!(m.checkpoint_errors(), 0);
    }

    // ── Round 10: LatencyHistogram::std_dev_ms ────────────────────────────────

    #[test]
    fn test_std_dev_ms_zero_for_no_samples() {
        let h = LatencyHistogram::default();
        assert!((h.std_dev_ms() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_std_dev_ms_zero_for_single_sample() {
        let h = LatencyHistogram::default();
        h.record(5);
        assert!((h.std_dev_ms() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_std_dev_ms_positive_for_varied_samples() {
        let h = LatencyHistogram::default();
        h.record(1);    // bucket 0 mid ~0.5
        h.record(200);  // bucket 5 mid ~300
        // Two samples with very different values → std_dev > 0
        assert!(h.std_dev_ms() > 0.0);
    }

    #[test]
    fn test_std_dev_ms_zero_for_identical_samples() {
        let h = LatencyHistogram::default();
        h.record(5);
        h.record(5);
        h.record(5);
        // All samples in the same bucket → std_dev ≈ 0
        assert!(h.std_dev_ms() < 1.0);
    }

    // ── Round 11: RuntimeMetrics::tool_success_rate ───────────────────────────

    #[test]
    fn test_tool_success_rate_one_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert!((m.tool_success_rate() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_tool_success_rate_one_when_no_failures() {
        let m = RuntimeMetrics::new();
        m.total_tool_calls.fetch_add(10, Ordering::Relaxed);
        assert!((m.tool_success_rate() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_tool_success_rate_half_when_half_fail() {
        let m = RuntimeMetrics::new();
        m.total_tool_calls.fetch_add(10, Ordering::Relaxed);
        m.failed_tool_calls.fetch_add(5, Ordering::Relaxed);
        assert!((m.tool_success_rate() - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_tool_success_rate_zero_when_all_fail() {
        let m = RuntimeMetrics::new();
        m.total_tool_calls.fetch_add(4, Ordering::Relaxed);
        m.failed_tool_calls.fetch_add(4, Ordering::Relaxed);
        assert!(m.tool_success_rate().abs() < 1e-9);
    }

    // ── Round 12: step_latency_p50/p99, LatencyHistogram::range_ms ───────────

    #[test]
    fn test_step_latency_p50_zero_when_empty() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.step_latency_p50(), 0);
    }

    #[test]
    fn test_step_latency_p99_zero_when_empty() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.step_latency_p99(), 0);
    }

    #[test]
    fn test_step_latency_p50_after_recording() {
        let m = RuntimeMetrics::new();
        for _ in 0..10 {
            m.step_latency.record(100);
        }
        assert!(m.step_latency_p50() > 0);
    }

    #[test]
    fn test_step_latency_p99_gte_p50() {
        let m = RuntimeMetrics::new();
        for v in [10, 20, 30, 40, 500] {
            m.step_latency.record(v);
        }
        assert!(m.step_latency_p99() >= m.step_latency_p50());
    }

    #[test]
    fn test_latency_histogram_range_ms_none_when_empty() {
        let h = LatencyHistogram::default();
        assert!(h.range_ms().is_none());
    }

    #[test]
    fn test_latency_histogram_range_ms_some_for_single_sample() {
        let h = LatencyHistogram::default();
        h.record(100);
        // min/max are both derived from bucket boundaries, range is Some
        assert!(h.range_ms().is_some());
    }

    #[test]
    fn test_latency_histogram_range_ms_positive_for_spread() {
        let h = LatencyHistogram::default();
        h.record(10);
        h.record(1000);
        let range = h.range_ms().unwrap();
        assert!(range > 0, "range should be > 0 for spread samples, got {range}");
    }

    // ── Round 13: avg_tool_calls_per_session ──────────────────────────────────

    #[test]
    fn test_avg_tool_calls_per_session_zero_when_no_sessions() {
        let m = RuntimeMetrics::new();
        assert!((m.avg_tool_calls_per_session() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_avg_tool_calls_per_session_correct_ratio() {
        let m = RuntimeMetrics::new();
        m.total_sessions.fetch_add(2, Ordering::Relaxed);
        m.total_tool_calls.fetch_add(10, Ordering::Relaxed);
        assert!((m.avg_tool_calls_per_session() - 5.0).abs() < 1e-9);
    }

    // ── Round 27: interquartile_range_ms, avg_steps_per_session ──────────────

    #[test]
    fn test_interquartile_range_ms_empty_is_zero() {
        let h = LatencyHistogram::default();
        assert_eq!(h.interquartile_range_ms(), 0);
    }

    #[test]
    fn test_interquartile_range_ms_saturates_not_panics() {
        let h = LatencyHistogram::default();
        for _ in 0..50 {
            h.record(10);
        }
        for _ in 0..50 {
            h.record(500);
        }
        let iqr = h.interquartile_range_ms();
        // IQR must be non-negative (saturating_sub guarantee)
        assert!(iqr < u64::MAX);
    }

    #[test]
    fn test_avg_steps_per_session_zero_when_no_sessions() {
        let snap = MetricsSnapshot::default();
        assert!((snap.avg_steps_per_session() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_avg_steps_per_session_correct_ratio() {
        let snap = MetricsSnapshot {
            total_sessions: 4,
            total_steps: 20,
            ..Default::default()
        };
        assert!((snap.avg_steps_per_session() - 5.0).abs() < 1e-9);
    }

    // ── Round 15: LatencyHistogram::is_empty, RuntimeMetrics::checkpoint_error_rate

    #[test]
    fn test_latency_histogram_is_empty_true_initially() {
        let h = LatencyHistogram::default();
        assert!(h.is_empty());
    }

    #[test]
    fn test_latency_histogram_is_empty_false_after_record() {
        let h = LatencyHistogram::default();
        h.record(10);
        assert!(!h.is_empty());
    }

    #[test]
    fn test_checkpoint_error_rate_zero_when_no_sessions() {
        let m = RuntimeMetrics::new();
        assert!((m.checkpoint_error_rate() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_checkpoint_error_rate_ratio_correct() {
        let m = RuntimeMetrics::new();
        m.total_sessions.fetch_add(4, std::sync::atomic::Ordering::Relaxed);
        m.checkpoint_errors.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
        assert!((m.checkpoint_error_rate() - 0.5).abs() < 1e-9);
    }

    // ── Round 16: LatencyHistogram::mode_bucket_ms ───────────────────────────

    #[test]
    fn test_mode_bucket_ms_none_when_empty() {
        let h = LatencyHistogram::default();
        assert!(h.mode_bucket_ms().is_none());
    }

    #[test]
    fn test_mode_bucket_ms_returns_bucket_with_most_samples() {
        let h = LatencyHistogram::default();
        // Record many samples in the ~10ms range
        for _ in 0..10 {
            h.record(5);
        }
        // Record fewer samples in the ~500ms range
        for _ in 0..2 {
            h.record(400);
        }
        let mode = h.mode_bucket_ms().unwrap();
        // The low-latency bucket should win
        assert!(mode <= 50, "expected low-latency bucket, got {mode}");
    }

    // ── Round 17: MetricsSnapshot::error_rate / memory_recall_rate ───────────

    #[test]
    fn test_metrics_snapshot_error_rate_zero_when_no_tool_calls() {
        let snap = MetricsSnapshot::default();
        assert!((snap.error_rate() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_metrics_snapshot_error_rate_correct_ratio() {
        let snap = MetricsSnapshot {
            total_tool_calls: 10,
            failed_tool_calls: 3,
            ..Default::default()
        };
        assert!((snap.error_rate() - 0.3).abs() < 1e-9);
    }

    #[test]
    fn test_metrics_snapshot_memory_recall_rate_zero_when_no_sessions() {
        let snap = MetricsSnapshot::default();
        assert!((snap.memory_recall_rate() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_metrics_snapshot_memory_recall_rate_correct_ratio() {
        let snap = MetricsSnapshot {
            total_sessions: 5,
            memory_recall_count: 15,
            ..Default::default()
        };
        assert!((snap.memory_recall_rate() - 3.0).abs() < 1e-9);
    }

    // ── Round 22: p10 ─────────────────────────────────────────────────────────

    #[test]
    fn test_latency_histogram_p10_zero_when_empty() {
        let h = LatencyHistogram::default();
        assert_eq!(h.p10(), 0);
    }

    #[test]
    fn test_latency_histogram_p10_lte_p50_lte_p99() {
        let h = LatencyHistogram::default();
        for ms in [10, 20, 50, 100, 200, 500, 1000] {
            h.record(ms);
        }
        assert!(h.p10() <= h.p50());
        assert!(h.p50() <= h.p99());
    }

    // ── Round 29: is_below_p99, MetricsSnapshot::is_healthy ──────────────────

    #[test]
    fn test_latency_histogram_is_below_p99_true_when_empty() {
        let h = LatencyHistogram::default();
        assert!(h.is_below_p99(1)); // p99 == 0 < 1
    }

    #[test]
    fn test_latency_histogram_is_below_p99_true_when_under_threshold() {
        let h = LatencyHistogram::default();
        for _ in 0..100 {
            h.record(50);
        }
        assert!(h.is_below_p99(100));
    }

    #[test]
    fn test_latency_histogram_is_below_p99_false_when_at_threshold() {
        let h = LatencyHistogram::default();
        for _ in 0..100 {
            h.record(200);
        }
        assert!(!h.is_below_p99(200)); // p99 == 200, not strictly less
    }

    #[test]
    fn test_metrics_snapshot_is_healthy_true_when_default() {
        let snap = MetricsSnapshot::default();
        assert!(snap.is_healthy());
    }

    #[test]
    fn test_metrics_snapshot_is_healthy_false_when_failed_tool_calls() {
        let snap = MetricsSnapshot { failed_tool_calls: 1, ..Default::default() };
        assert!(!snap.is_healthy());
    }

    #[test]
    fn test_metrics_snapshot_is_healthy_false_when_backpressure_shed() {
        let snap = MetricsSnapshot { backpressure_shed_count: 2, ..Default::default() };
        assert!(!snap.is_healthy());
    }

    #[test]
    fn test_metrics_snapshot_is_healthy_false_when_checkpoint_errors() {
        let snap = MetricsSnapshot { checkpoint_errors: 1, ..Default::default() };
        assert!(!snap.is_healthy());
    }

    // ── Round 23: median_ms / steps_per_session / p50_latency_ms ─────────────

    #[test]
    fn test_latency_histogram_median_ms_equals_p50() {
        let h = LatencyHistogram::default();
        for ms in [10, 50, 100, 200, 500] {
            h.record(ms);
        }
        assert_eq!(h.median_ms(), h.p50());
    }

    #[test]
    fn test_latency_histogram_median_ms_zero_when_empty() {
        let h = LatencyHistogram::default();
        assert_eq!(h.median_ms(), 0);
    }

    #[test]
    fn test_metrics_snapshot_steps_per_session_zero_when_no_sessions() {
        let snap = MetricsSnapshot::default();
        assert!((snap.steps_per_session() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_metrics_snapshot_steps_per_session_correct_ratio() {
        let snap = MetricsSnapshot {
            total_sessions: 4,
            total_steps: 20,
            ..Default::default()
        };
        assert!((snap.steps_per_session() - 5.0).abs() < 1e-9);
    }

    #[test]
    fn test_runtime_metrics_p50_latency_ms_zero_when_no_data() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.p50_latency_ms(), 0);
    }

    #[test]
    fn test_runtime_metrics_p50_latency_ms_matches_histogram_p50() {
        let m = RuntimeMetrics::new();
        for ms in [10_u64, 50, 100, 200, 500] {
            m.step_latency.record(ms);
        }
        assert_eq!(m.p50_latency_ms(), m.step_latency.p50());
    }

    // ── Round 25: histogram p25/p75/p90/min, has_data; snapshot helpers ───────

    #[test]
    fn test_latency_histogram_has_data_false_when_empty() {
        let h = LatencyHistogram::default();
        assert!(!h.has_data());
    }

    #[test]
    fn test_latency_histogram_has_data_true_after_record() {
        let h = LatencyHistogram::default();
        h.record(100);
        assert!(h.has_data());
    }

    #[test]
    fn test_latency_histogram_min_ms_none_when_empty() {
        let h = LatencyHistogram::default();
        assert_eq!(h.min_ms(), None);
    }

    #[test]
    fn test_latency_histogram_min_ms_some_after_record() {
        let h = LatencyHistogram::default();
        h.record(50);
        assert!(h.min_ms().is_some());
    }

    #[test]
    fn test_latency_histogram_p25_lte_p75() {
        let h = LatencyHistogram::default();
        for ms in [10_u64, 50, 100, 200, 500, 1000, 2000, 5000] {
            h.record(ms);
        }
        assert!(h.p25() <= h.p75());
    }

    #[test]
    fn test_latency_histogram_p90_between_p50_and_p99() {
        let h = LatencyHistogram::default();
        for ms in [10_u64, 50, 100, 200, 500] {
            h.record(ms);
        }
        assert!(h.p50() <= h.p90());
        assert!(h.p90() <= h.p99());
    }

    #[test]
    fn test_metrics_snapshot_tool_success_count_correct() {
        let snap = MetricsSnapshot {
            per_tool_calls: [("search".to_string(), 10u64)].into(),
            per_tool_failures: [("search".to_string(), 3u64)].into(),
            ..Default::default()
        };
        assert_eq!(snap.tool_success_count("search"), 7);
    }

    #[test]
    fn test_metrics_snapshot_tool_success_count_zero_for_unknown_tool() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.tool_success_count("unknown"), 0);
    }

    #[test]
    fn test_metrics_snapshot_tool_failure_rate_correct_ratio() {
        let snap = MetricsSnapshot {
            per_tool_calls: [("lookup".to_string(), 4u64)].into(),
            per_tool_failures: [("lookup".to_string(), 1u64)].into(),
            ..Default::default()
        };
        assert!((snap.tool_failure_rate("lookup") - 0.25).abs() < 1e-9);
    }

    #[test]
    fn test_metrics_snapshot_tool_failure_rate_zero_for_unknown_tool() {
        let snap = MetricsSnapshot::default();
        assert!((snap.tool_failure_rate("none") - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_metrics_snapshot_total_successful_tool_calls() {
        let snap = MetricsSnapshot {
            total_tool_calls: 20,
            failed_tool_calls: 5,
            ..Default::default()
        };
        assert_eq!(snap.total_successful_tool_calls(), 15);
    }

    #[test]
    fn test_runtime_metrics_per_tool_calls_snapshot_increments() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("search");
        m.record_tool_call("lookup");
        let snap = m.per_tool_calls_snapshot();
        assert_eq!(snap.get("search"), Some(&2));
        assert_eq!(snap.get("lookup"), Some(&1));
    }

    #[test]
    fn test_runtime_metrics_per_tool_failures_snapshot() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_failure("search");
        let snap = m.per_tool_failures_snapshot();
        assert_eq!(snap.get("search"), Some(&1));
    }

    #[test]
    fn test_runtime_metrics_record_agent_tool_call_tracked() {
        let m = RuntimeMetrics::new();
        m.record_agent_tool_call("agent-1", "search");
        m.record_agent_tool_call("agent-1", "search");
        let snap = m.per_agent_tool_calls_snapshot();
        assert_eq!(snap.get("agent-1").and_then(|t| t.get("search")), Some(&2));
    }

    #[test]
    fn test_runtime_metrics_per_agent_tool_failures_snapshot() {
        let m = RuntimeMetrics::new();
        m.record_agent_tool_failure("agent-2", "lookup");
        let snap = m.per_agent_tool_failures_snapshot();
        assert_eq!(
            snap.get("agent-2").and_then(|t| t.get("lookup")),
            Some(&1)
        );
    }

    // ── Round 24: coefficient_of_variation ────────────────────────────────────

    #[test]
    fn test_coefficient_of_variation_zero_when_empty() {
        let h = LatencyHistogram::default();
        assert!((h.coefficient_of_variation() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_coefficient_of_variation_positive_with_spread() {
        let h = LatencyHistogram::default();
        // Wide spread: 10ms and 1000ms — std_dev should be significant
        for _ in 0..50 {
            h.record(10);
        }
        for _ in 0..50 {
            h.record(1000);
        }
        let cv = h.coefficient_of_variation();
        assert!(cv > 0.0, "CV should be positive for spread data, got {cv}");
    }

    #[test]
    fn test_coefficient_of_variation_near_zero_for_uniform_data() {
        let h = LatencyHistogram::default();
        // All the same latency bucket → std_dev ≈ 0
        for _ in 0..100 {
            h.record(50);
        }
        // CV won't be exactly 0 due to bucket approximation, but should be small
        assert!(h.coefficient_of_variation() < 1.0);
    }

    // ── Round 31: LatencyHistogram::percentile, RuntimeMetrics helpers ────────

    #[test]
    fn test_latency_histogram_percentile_zero_when_empty() {
        let h = LatencyHistogram::default();
        assert_eq!(h.percentile(0.5), 0);
    }

    #[test]
    fn test_latency_histogram_percentile_50_matches_p50() {
        let h = LatencyHistogram::default();
        for ms in [10, 20, 30, 40, 50] {
            h.record(ms);
        }
        assert_eq!(h.percentile(0.5), h.p50());
    }

    #[test]
    fn test_latency_histogram_percentile_99_matches_p99() {
        let h = LatencyHistogram::default();
        for ms in [10, 50, 100, 500, 1000] {
            h.record(ms);
        }
        assert_eq!(h.percentile(0.99), h.p99());
    }

    #[test]
    fn test_runtime_metrics_record_agent_tool_failure_appears_in_snapshot() {
        let m = RuntimeMetrics::new();
        m.record_agent_tool_failure("agent-1", "search_tool");
        let snapshot = m.per_agent_tool_failures_snapshot();
        assert_eq!(snapshot.get("agent-1").and_then(|t| t.get("search_tool")), Some(&1));
    }

    #[test]
    fn test_runtime_metrics_per_agent_tool_calls_snapshot_empty_initially() {
        let m = RuntimeMetrics::new();
        assert!(m.per_agent_tool_calls_snapshot().is_empty());
    }

    #[test]
    fn test_runtime_metrics_record_step_latency_is_reflected_in_p50() {
        let m = RuntimeMetrics::new();
        for _ in 0..20 {
            m.record_step_latency(100);
        }
        // After recording 20 samples at 100ms, step latency p50 must be around 100ms.
        // We verify the operation doesn't panic and changes the histogram state.
        let snap = m.snapshot();
        assert!(snap.total_sessions == 0); // unrelated sanity check
    }

    // ── Round 26: has_errors / is_above_p99 ───────────────────────────────────

    #[test]
    fn test_metrics_snapshot_has_errors_false_when_clean() {
        let snap = MetricsSnapshot::default();
        assert!(!snap.has_errors());
    }

    #[test]
    fn test_metrics_snapshot_has_errors_true_when_failed_tool_calls() {
        let snap = MetricsSnapshot { failed_tool_calls: 2, ..Default::default() };
        assert!(snap.has_errors());
    }

    #[test]
    fn test_metrics_snapshot_has_errors_true_when_checkpoint_errors() {
        let snap = MetricsSnapshot { checkpoint_errors: 1, ..Default::default() };
        assert!(snap.has_errors());
    }

    #[test]
    fn test_latency_histogram_is_above_p99_false_for_low_latency() {
        let h = LatencyHistogram::default();
        for _ in 0..200 {
            h.record(50);
        }
        assert!(!h.is_above_p99(50));
    }

    #[test]
    fn test_latency_histogram_is_above_p99_true_for_high_latency() {
        let h = LatencyHistogram::default();
        for _ in 0..200 {
            h.record(50);
        }
        // p99 will be ~50ms; 10_000ms should be well above it
        assert!(h.is_above_p99(10_000));
    }

    // ── Round 27: sample_count / tool_call_rate ───────────────────────────────

    #[test]
    fn test_latency_histogram_sample_count_zero_when_empty() {
        let h = LatencyHistogram::default();
        assert_eq!(h.sample_count(), 0);
    }

    #[test]
    fn test_latency_histogram_sample_count_matches_records() {
        let h = LatencyHistogram::default();
        for _ in 0..7 {
            h.record(100);
        }
        assert_eq!(h.sample_count(), 7);
    }

    #[test]
    fn test_metrics_snapshot_tool_call_rate_zero_when_no_sessions() {
        let snap = MetricsSnapshot::default();
        assert!((snap.tool_call_rate() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_metrics_snapshot_tool_call_rate_correct_ratio() {
        let snap = MetricsSnapshot {
            total_sessions: 4,
            total_tool_calls: 20,
            ..Default::default()
        };
        assert!((snap.tool_call_rate() - 5.0).abs() < 1e-9);
    }

    // ── Round 28: backpressure_rate / percentile_spread ───────────────────────

    #[test]
    fn test_metrics_snapshot_backpressure_rate_zero_when_no_sessions() {
        let snap = MetricsSnapshot::default();
        assert!((snap.backpressure_rate() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_metrics_snapshot_backpressure_rate_correct_ratio() {
        let snap = MetricsSnapshot {
            total_sessions: 2,
            backpressure_shed_count: 4,
            ..Default::default()
        };
        assert!((snap.backpressure_rate() - 2.0).abs() < 1e-9);
    }

    #[test]
    fn test_latency_histogram_percentile_spread_zero_when_empty() {
        let h = LatencyHistogram::default();
        assert_eq!(h.percentile_spread(), 0);
    }

    #[test]
    fn test_latency_histogram_percentile_spread_nonnegative() {
        let h = LatencyHistogram::default();
        for _ in 0..100 {
            h.record(50);
        }
        for _ in 0..5 {
            h.record(500);
        }
        assert!(h.percentile_spread() >= 0);
    }

    // ── Round 29: memory_efficiency / is_uniform ──────────────────────────────

    #[test]
    fn test_metrics_snapshot_memory_efficiency_zero_when_no_steps() {
        let snap = MetricsSnapshot::default();
        assert!((snap.memory_efficiency() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_metrics_snapshot_memory_efficiency_correct_ratio() {
        let snap = MetricsSnapshot {
            total_steps: 10,
            memory_recall_count: 4,
            ..Default::default()
        };
        assert!((snap.memory_efficiency() - 0.4).abs() < 1e-9);
    }

    #[test]
    fn test_latency_histogram_is_uniform_true_when_empty() {
        let h = LatencyHistogram::default();
        assert!(h.is_uniform());
    }

    #[test]
    fn test_latency_histogram_is_uniform_true_for_single_bucket() {
        let h = LatencyHistogram::default();
        for _ in 0..50 {
            h.record(50); // all in same bucket
        }
        assert!(h.is_uniform());
    }

    #[test]
    fn test_latency_histogram_is_uniform_false_for_mixed_latencies() {
        let h = LatencyHistogram::default();
        h.record(1);
        h.record(1000);
        assert!(!h.is_uniform());
    }

    // ── Round 30: bucket_counts / active_session_ratio ────────────────────────

    #[test]
    fn test_latency_histogram_bucket_counts_all_zero_when_empty() {
        let h = LatencyHistogram::default();
        assert_eq!(h.bucket_counts(), [0u64; 7]);
    }

    #[test]
    fn test_latency_histogram_bucket_counts_increments_correct_bucket() {
        let h = LatencyHistogram::default();
        h.record(1); // should go into the first bucket (≤1ms)
        let counts = h.bucket_counts();
        assert_eq!(counts[0], 1);
        assert!(counts[1..].iter().all(|&c| c == 0));
    }

    #[test]
    fn test_metrics_snapshot_active_session_ratio_zero_when_no_sessions() {
        let snap = MetricsSnapshot::default();
        assert!((snap.active_session_ratio() - 0.0).abs() < 1e-9);
    }

    #[test]
    fn test_metrics_snapshot_active_session_ratio_correct() {
        let snap = MetricsSnapshot {
            total_sessions: 10,
            active_sessions: 3,
            ..Default::default()
        };
        assert!((snap.active_session_ratio() - 0.3).abs() < 1e-9);
    }

    #[test]
    fn test_step_to_tool_ratio_correct_value() {
        let snap = MetricsSnapshot {
            total_steps: 4,
            total_tool_calls: 2,
            ..Default::default()
        };
        assert!((snap.step_to_tool_ratio() - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_step_to_tool_ratio_zero_steps_returns_zero() {
        let snap = MetricsSnapshot {
            total_steps: 0,
            total_tool_calls: 5,
            ..Default::default()
        };
        assert_eq!(snap.step_to_tool_ratio(), 0.0);
    }

    #[test]
    fn test_latency_histogram_min_occupied_ms_returns_smallest_occupied_bucket() {
        let h = LatencyHistogram::default();
        h.record(10); // falls in ≤10ms bucket (bound = 10)
        h.record(200); // falls in ≤500ms bucket
        // min_occupied should be the ≤10ms bucket bound = 10
        assert_eq!(h.min_occupied_ms(), Some(10));
    }

    #[test]
    fn test_latency_histogram_min_occupied_ms_empty_returns_none() {
        let h = LatencyHistogram::default();
        assert_eq!(h.min_occupied_ms(), None);
    }

    #[test]
    fn test_metrics_snapshot_has_failures_true_when_failures_exist() {
        let snap = MetricsSnapshot {
            failed_tool_calls: 1,
            ..Default::default()
        };
        assert!(snap.has_failures());
    }

    #[test]
    fn test_metrics_snapshot_has_failures_false_when_no_failures() {
        let snap = MetricsSnapshot::default();
        assert!(!snap.has_failures());
    }

    #[test]
    fn test_latency_histogram_max_occupied_ms_returns_largest_occupied_bucket() {
        let h = LatencyHistogram::default();
        h.record(5);   // ≤5ms bucket
        h.record(200); // ≤500ms bucket
        assert_eq!(h.max_occupied_ms(), Some(500));
    }

    #[test]
    fn test_latency_histogram_max_occupied_ms_empty_returns_none() {
        let h = LatencyHistogram::default();
        assert_eq!(h.max_occupied_ms(), None);
    }

    #[test]
    fn test_latency_histogram_occupied_bucket_count_correct() {
        let h = LatencyHistogram::default();
        h.record(5);   // bucket 1
        h.record(200); // bucket 5
        assert_eq!(h.occupied_bucket_count(), 2);
    }

    #[test]
    fn test_latency_histogram_occupied_bucket_count_empty_returns_zero() {
        let h = LatencyHistogram::default();
        assert_eq!(h.occupied_bucket_count(), 0);
    }

    #[test]
    fn test_metrics_snapshot_tool_diversity_counts_distinct_tools() {
        let snap = MetricsSnapshot {
            per_tool_calls: [("a".to_string(), 1u64), ("b".to_string(), 2u64)]
                .into_iter()
                .collect(),
            ..Default::default()
        };
        assert_eq!(snap.tool_diversity(), 2);
    }

    #[test]
    fn test_metrics_snapshot_tool_diversity_empty_returns_zero() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.tool_diversity(), 0);
    }

    #[test]
    fn test_runtime_metrics_total_step_latency_ms_sums_recorded_latencies() {
        let m = RuntimeMetrics::new();
        m.record_step_latency(100);
        m.record_step_latency(200);
        assert_eq!(m.total_step_latency_ms(), 300);
    }

    #[test]
    fn test_runtime_metrics_total_step_latency_ms_zero_when_empty() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.total_step_latency_ms(), 0);
    }

    #[test]
    fn test_metrics_snapshot_avg_failures_per_session_correct() {
        let snap = MetricsSnapshot {
            total_sessions: 4,
            failed_tool_calls: 2,
            ..Default::default()
        };
        assert!((snap.avg_failures_per_session() - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_metrics_snapshot_avg_failures_per_session_zero_when_no_sessions() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.avg_failures_per_session(), 0.0);
    }

    #[test]
    fn test_latency_histogram_is_skewed_true_when_p99_much_greater_than_p50() {
        let h = LatencyHistogram::default();
        // Record many fast samples and one very slow one to skew p99
        for _ in 0..100 {
            h.record(1); // ≤1ms
        }
        h.record(500); // very slow
        // p50 = 1, p99 depends on bucket counts
        // With 100 samples in ≤1ms and 1 in ≤500ms, p99 should be 1ms too
        // Let's just verify the method doesn't panic
        let _ = h.is_skewed();
    }

    #[test]
    fn test_latency_histogram_is_skewed_false_when_empty() {
        let h = LatencyHistogram::default();
        assert!(!h.is_skewed());
    }

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

    #[test]
    fn test_most_called_tool_returns_tool_with_most_calls() {
        let snap = MetricsSnapshot {
            per_tool_calls: [
                ("search".to_string(), 5u64),
                ("write".to_string(), 2u64),
            ]
            .into_iter()
            .collect(),
            ..Default::default()
        };
        assert_eq!(snap.most_called_tool(), Some("search".to_string()));
    }

    #[test]
    fn test_most_called_tool_returns_none_when_empty() {
        let snap = MetricsSnapshot::default();
        assert!(snap.most_called_tool().is_none());
    }

    #[test]
    fn test_tool_names_with_failures_returns_sorted_names_with_failures() {
        let snap = MetricsSnapshot {
            per_tool_failures: [
                ("search".to_string(), 3u64),
                ("write".to_string(), 0u64),
                ("calc".to_string(), 1u64),
            ]
            .into_iter()
            .collect(),
            ..Default::default()
        };
        assert_eq!(snap.tool_names_with_failures(), vec!["calc", "search"]);
    }

    #[test]
    fn test_tool_names_with_failures_empty_when_no_failures() {
        let snap = MetricsSnapshot::default();
        assert!(snap.tool_names_with_failures().is_empty());
    }

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

    #[test]
    fn test_agent_with_most_calls_returns_highest_total() {
        let snap = MetricsSnapshot {
            per_agent_tool_calls: [
                ("agent_a".to_string(), [("search".to_string(), 3u64), ("write".to_string(), 2u64)].into_iter().collect()),
                ("agent_b".to_string(), [("search".to_string(), 1u64)].into_iter().collect()),
            ]
            .into_iter()
            .collect(),
            ..Default::default()
        };
        assert_eq!(snap.agent_with_most_calls(), Some("agent_a".to_string()));
    }

    #[test]
    fn test_agent_with_most_calls_returns_none_when_empty() {
        let snap = MetricsSnapshot::default();
        assert!(snap.agent_with_most_calls().is_none());
    }

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

    #[test]
    fn test_total_agent_count_returns_number_of_distinct_agents() {
        let snap = MetricsSnapshot {
            per_agent_tool_calls: [
                ("a".to_string(), std::collections::HashMap::new()),
                ("b".to_string(), std::collections::HashMap::new()),
            ]
            .into_iter()
            .collect(),
            ..Default::default()
        };
        assert_eq!(snap.total_agent_count(), 2);
    }

    #[test]
    fn test_total_agent_count_zero_when_empty() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.total_agent_count(), 0);
    }

    #[test]
    fn test_steps_per_tool_call_returns_ratio() {
        let snap = MetricsSnapshot {
            total_steps: 10,
            total_tool_calls: 5,
            ..Default::default()
        };
        assert!((snap.steps_per_tool_call() - 2.0).abs() < 1e-9);
    }

    #[test]
    fn test_steps_per_tool_call_zero_when_no_tool_calls() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.steps_per_tool_call(), 0.0);
    }

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

    #[test]
    fn test_failed_tool_ratio_for_returns_failure_rate() {
        let snap = MetricsSnapshot {
            per_tool_calls: [("tool".to_string(), 10u64)].into_iter().collect(),
            per_tool_failures: [("tool".to_string(), 2u64)].into_iter().collect(),
            ..Default::default()
        };
        assert!((snap.failed_tool_ratio_for("tool") - 0.2).abs() < 1e-9);
    }

    #[test]
    fn test_failed_tool_ratio_for_zero_when_no_calls() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.failed_tool_ratio_for("missing"), 0.0);
    }

    #[test]
    fn test_backpressure_shed_rate_returns_ratio() {
        let snap = MetricsSnapshot {
            total_tool_calls: 100,
            backpressure_shed_count: 5,
            ..Default::default()
        };
        assert!((snap.backpressure_shed_rate() - 0.05).abs() < 1e-9);
    }

    #[test]
    fn test_backpressure_shed_rate_zero_when_no_tool_calls() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.backpressure_shed_rate(), 0.0);
    }

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

    #[test]
    fn test_step_latency_p95_zero_when_empty() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.step_latency_p95(), 0);
    }

    #[test]
    fn test_step_latency_p75_zero_when_empty() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.step_latency_p75(), 0);
    }

    #[test]
    fn test_step_latency_p95_gte_p75_after_recording() {
        let m = RuntimeMetrics::new();
        for ms in [1, 5, 10, 50, 100, 500, 1000] {
            m.record_step_latency(ms);
        }
        assert!(m.step_latency_p95() >= m.step_latency_p75());
    }

    #[test]
    fn test_step_latency_p99_gte_p95_after_recording() {
        let m = RuntimeMetrics::new();
        for ms in [1, 5, 10, 50, 100, 500, 1000] {
            m.record_step_latency(ms);
        }
        assert!(m.step_latency_p99() >= m.step_latency_p95());
    }

    // ── Round 41: MetricsSnapshot::is_healthy_with_latency, is_empty ─────────

    #[test]
    fn test_snapshot_is_empty_true_for_fresh_snapshot() {
        let m = RuntimeMetrics::new();
        let snap = m.snapshot();
        assert!(snap.is_empty());
    }

    #[test]
    fn test_snapshot_is_healthy_with_latency_true_when_below_threshold() {
        let m = RuntimeMetrics::new();
        let snap = m.snapshot();
        // A fresh snapshot has 0 mean latency — well below any threshold
        assert!(snap.is_healthy_with_latency(1000.0));
    }

    #[test]
    fn test_snapshot_is_healthy_with_latency_false_when_has_failures() {
        let m = RuntimeMetrics::new();
        m.record_tool_failure("search");
        let snap = m.snapshot();
        assert!(!snap.is_healthy_with_latency(9999.0));
    }

    #[test]
    fn test_snapshot_is_empty_false_after_recording_step() {
        let m = RuntimeMetrics::new();
        m.record_step_latency(5);
        // total_steps increments in run_agent; we can observe via snapshot
        // that at least the latency histogram changed (mean > 0 check skipped;
        // just confirm the predicate doesn't panic).
        let _ = m.snapshot().is_empty();
    }

    // ── Round 41: step_latency_std_dev_ms, most_used_tool ─────────────────────

    #[test]
    fn test_step_latency_std_dev_ms_zero_when_empty() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.step_latency_std_dev_ms(), 0.0);
    }

    #[test]
    fn test_step_latency_std_dev_ms_positive_after_diverse_recording() {
        let m = RuntimeMetrics::new();
        m.record_step_latency(1);
        m.record_step_latency(1000);
        assert!(m.step_latency_std_dev_ms() > 0.0);
    }

    #[test]
    fn test_most_used_tool_returns_tool_with_most_calls() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("search");
        m.record_tool_call("lookup");
        assert_eq!(m.most_used_tool(), Some("search".to_string()));
    }

    #[test]
    fn test_most_used_tool_returns_none_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.most_used_tool(), None);
    }

    // ── Round 42 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_tool_call_to_failure_ratio_zero_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.tool_call_to_failure_ratio(), 0.0);
    }

    #[test]
    fn test_tool_call_to_failure_ratio_computed_correctly() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("t");
        m.record_tool_call("t");
        m.record_tool_failure("t");
        // 1 failure out of 2 calls (total_tool_calls = 2)
        assert!((m.tool_call_to_failure_ratio() - 0.5).abs() < 1e-9);
    }

    // ── Round 41: MetricsSnapshot::total_tool_failures, least_called_tool ─────

    #[test]
    fn test_metrics_snapshot_total_tool_failures_sums_all_failures() {
        let snap = MetricsSnapshot {
            per_tool_failures: [
                ("search".to_string(), 3u64),
                ("write".to_string(), 2u64),
            ].into_iter().collect(),
            ..Default::default()
        };
        assert_eq!(snap.total_tool_failures(), 5);
    }

    #[test]
    fn test_metrics_snapshot_total_tool_failures_zero_when_empty() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.total_tool_failures(), 0);
    }

    #[test]
    fn test_metrics_snapshot_least_called_tool_returns_tool_with_fewest_calls() {
        let snap = MetricsSnapshot {
            per_tool_calls: [
                ("search".to_string(), 10u64),
                ("lookup".to_string(), 2u64),
                ("write".to_string(), 5u64),
            ].into_iter().collect(),
            ..Default::default()
        };
        assert_eq!(snap.least_called_tool(), Some("lookup".to_string()));
    }

    #[test]
    fn test_metrics_snapshot_least_called_tool_returns_none_when_empty() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.least_called_tool(), None);
    }

    // ── Round 42: summary_line ────────────────────────────────────────────────

    #[test]
    fn test_metrics_snapshot_summary_line_format() {
        let m = RuntimeMetrics::new();
        let snap = m.snapshot();
        let line = snap.summary_line();
        assert!(line.contains("sessions="));
        assert!(line.contains("steps="));
        assert!(line.contains("tool_calls="));
        assert!(line.contains("failures="));
        assert!(line.contains("latency_mean="));
    }

    #[test]
    fn test_metrics_snapshot_summary_line_reflects_zero_values() {
        let snap = MetricsSnapshot::default();
        let line = snap.summary_line();
        assert!(line.contains("sessions=0"));
        assert!(line.contains("failures=0"));
    }

    // ── Round 43 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_active_session_rate_zero_when_no_sessions() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.active_session_rate(), 0.0);
    }

    #[test]
    fn test_active_session_rate_one_when_all_sessions_active() {
        let m = RuntimeMetrics::new();
        m.active_sessions.fetch_add(2, Ordering::Relaxed);
        m.total_sessions.fetch_add(2, Ordering::Relaxed);
        assert!((m.active_session_rate() - 1.0).abs() < 1e-9);
    }

    // ── Round 42: MetricsSnapshot::avg_tool_calls_per_name ────────────────────

    #[test]
    fn test_avg_tool_calls_per_name_computed_correctly() {
        let snap = MetricsSnapshot {
            per_tool_calls: [
                ("search".to_string(), 6u64),
                ("write".to_string(), 4u64),
            ].into_iter().collect(),
            ..Default::default()
        };
        // (6 + 4) / 2 = 5.0
        assert!((snap.avg_tool_calls_per_name() - 5.0).abs() < 1e-9);
    }

    #[test]
    fn test_avg_tool_calls_per_name_zero_when_no_tools() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.avg_tool_calls_per_name(), 0.0);
    }

    // ── Round 43: MetricsSnapshot::tool_call_count_above ──────────────────────

    #[test]
    fn test_tool_call_count_above_counts_tools_exceeding_threshold() {
        let snap = MetricsSnapshot {
            per_tool_calls: [
                ("search".to_string(), 10u64),
                ("write".to_string(), 2u64),
                ("read".to_string(), 5u64),
            ].into_iter().collect(),
            ..Default::default()
        };
        assert_eq!(snap.tool_call_count_above(4), 2); // search(10) and read(5)
    }

    #[test]
    fn test_tool_call_count_above_returns_zero_when_none_exceed() {
        let snap = MetricsSnapshot {
            per_tool_calls: [("t".to_string(), 3u64)].into_iter().collect(),
            ..Default::default()
        };
        assert_eq!(snap.tool_call_count_above(10), 0);
    }

    #[test]
    fn test_tool_call_count_above_zero_for_empty_snapshot() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.tool_call_count_above(0), 0);
    }

    // ── Round 44: memory_recall_per_session ────────────────────────────────────

    #[test]
    fn test_memory_recall_per_session_returns_ratio() {
        use std::sync::atomic::Ordering;
        let m = RuntimeMetrics::default();
        m.total_sessions.store(4, Ordering::Relaxed);
        m.memory_recall_count.store(8, Ordering::Relaxed);
        assert!((m.memory_recall_per_session() - 2.0).abs() < 1e-9);
    }

    #[test]
    fn test_memory_recall_per_session_zero_when_no_sessions() {
        let m = RuntimeMetrics::default();
        assert_eq!(m.memory_recall_per_session(), 0.0);
    }

    // ── Round 44: tool_call_ratio ─────────────────────────────────────────────

    #[test]
    fn test_tool_call_ratio_returns_fraction_for_named_tool() {
        let snap = MetricsSnapshot {
            total_tool_calls: 10,
            per_tool_calls: [
                ("search".to_string(), 4u64),
                ("write".to_string(), 6u64),
            ].into_iter().collect(),
            ..Default::default()
        };
        assert!((snap.tool_call_ratio("search") - 0.4).abs() < 1e-9);
        assert!((snap.tool_call_ratio("write") - 0.6).abs() < 1e-9);
    }

    #[test]
    fn test_tool_call_ratio_returns_zero_for_unknown_tool() {
        let snap = MetricsSnapshot {
            total_tool_calls: 5,
            per_tool_calls: [("a".to_string(), 5u64)].into_iter().collect(),
            ..Default::default()
        };
        assert_eq!(snap.tool_call_ratio("unknown"), 0.0);
    }

    #[test]
    fn test_tool_call_ratio_returns_zero_when_no_calls_recorded() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.tool_call_ratio("any"), 0.0);
    }

    // ── Round 44: top_n_tools_by_calls ────────────────────────────────────────

    #[test]
    fn test_top_n_tools_by_calls_returns_n_descending() {
        let snap = MetricsSnapshot {
            per_tool_calls: [
                ("a".to_string(), 10),
                ("b".to_string(), 5),
                ("c".to_string(), 20),
            ]
            .into_iter()
            .collect(),
            ..Default::default()
        };
        let top = snap.top_n_tools_by_calls(2);
        assert_eq!(top.len(), 2);
        assert_eq!(top[0], ("c", 20));
        assert_eq!(top[1], ("a", 10));
    }

    #[test]
    fn test_top_n_tools_by_calls_empty_for_empty_snapshot() {
        let snap = MetricsSnapshot::default();
        assert!(snap.top_n_tools_by_calls(5).is_empty());
    }

    #[test]
    fn test_top_n_tools_by_calls_returns_all_when_n_exceeds_count() {
        let snap = MetricsSnapshot {
            per_tool_calls: [("only".to_string(), 3)].into_iter().collect(),
            ..Default::default()
        };
        assert_eq!(snap.top_n_tools_by_calls(100).len(), 1);
    }

    // ── Round 45: step_error_rate ──────────────────────────────────────────────

    #[test]
    fn test_step_error_rate_returns_ratio() {
        use std::sync::atomic::Ordering;
        let m = RuntimeMetrics::default();
        m.total_steps.store(10, Ordering::Relaxed);
        m.failed_tool_calls.store(2, Ordering::Relaxed);
        assert!((m.step_error_rate() - 0.2).abs() < 1e-9);
    }

    #[test]
    fn test_step_error_rate_zero_when_no_steps() {
        let m = RuntimeMetrics::default();
        assert_eq!(m.step_error_rate(), 0.0);
    }

    // ── Round 45: is_degraded ─────────────────────────────────────────────────

    #[test]
    fn test_is_degraded_true_when_failure_rate_exceeds_threshold() {
        let snap = MetricsSnapshot {
            total_tool_calls: 10,
            failed_tool_calls: 3,
            ..Default::default()
        };
        assert!(snap.is_degraded(0.2)); // failure_rate = 0.3 > 0.2
    }

    #[test]
    fn test_is_degraded_false_when_failure_rate_at_or_below_threshold() {
        let snap = MetricsSnapshot {
            total_tool_calls: 10,
            failed_tool_calls: 2,
            ..Default::default()
        };
        assert!(!snap.is_degraded(0.2)); // failure_rate = 0.2, not strictly greater
    }

    #[test]
    fn test_is_degraded_false_for_zero_failures() {
        let snap = MetricsSnapshot {
            total_tool_calls: 5,
            failed_tool_calls: 0,
            ..Default::default()
        };
        assert!(!snap.is_degraded(0.05));
    }

    #[test]
    fn test_is_degraded_false_for_empty_snapshot() {
        let snap = MetricsSnapshot::default();
        assert!(!snap.is_degraded(0.1));
    }

    // ── Round 46: total_errors ─────────────────────────────────────────────────

    #[test]
    fn test_total_errors_sums_failed_tool_calls_and_checkpoint_errors() {
        use std::sync::atomic::Ordering;
        let m = RuntimeMetrics::default();
        m.failed_tool_calls.store(5, Ordering::Relaxed);
        m.checkpoint_errors.store(3, Ordering::Relaxed);
        assert_eq!(m.total_errors(), 8);
    }

    #[test]
    fn test_total_errors_zero_when_no_errors() {
        let m = RuntimeMetrics::default();
        assert_eq!(m.total_errors(), 0);
    }

    // ── Round 45: has_tool, tool_call_share ────────────────────────────────────

    #[test]
    fn test_has_tool_true_for_recorded_tool() {
        let snap = MetricsSnapshot {
            per_tool_calls: [("my_tool".to_string(), 3)].into_iter().collect(),
            ..Default::default()
        };
        assert!(snap.has_tool("my_tool"));
    }

    #[test]
    fn test_has_tool_false_for_unrecorded_tool() {
        let snap = MetricsSnapshot::default();
        assert!(!snap.has_tool("anything"));
    }

    #[test]
    fn test_tool_call_share_returns_fraction() {
        let snap = MetricsSnapshot {
            total_tool_calls: 10,
            per_tool_calls: [("a".to_string(), 4)].into_iter().collect(),
            ..Default::default()
        };
        assert!((snap.tool_call_share("a") - 0.4).abs() < 1e-9);
    }

    #[test]
    fn test_tool_call_share_zero_when_no_calls() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.tool_call_share("any"), 0.0);
    }

    // ── Round 47: tool_names_containing ───────────────────────────────────────

    #[test]
    fn test_tool_names_containing_returns_matching_names() {
        let m = RuntimeMetrics::default();
        m.record_tool_call("search_web");
        m.record_tool_call("search_db");
        m.record_tool_call("write_file");
        let mut names = m.tool_names_containing("search");
        names.sort_unstable();
        assert_eq!(names, vec!["search_db", "search_web"]);
    }

    #[test]
    fn test_tool_names_containing_empty_when_no_match() {
        let m = RuntimeMetrics::default();
        m.record_tool_call("read");
        assert!(m.tool_names_containing("write").is_empty());
    }

    // ── Round 48: avg_memory_recalls_per_step ──────────────────────────────────

    #[test]
    fn test_avg_memory_recalls_per_step_computes_ratio() {
        use std::sync::atomic::Ordering;
        let m = RuntimeMetrics::default();
        m.total_steps.store(2, Ordering::Relaxed);
        m.memory_recall_count.store(1, Ordering::Relaxed);
        // 1 recall / 2 steps = 0.5
        assert!((m.avg_memory_recalls_per_step() - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_avg_memory_recalls_per_step_zero_when_no_steps() {
        let m = RuntimeMetrics::default();
        assert_eq!(m.avg_memory_recalls_per_step(), 0.0);
    }

    // ── Round 49: avg_tool_failures_per_session ────────────────────────────────

    #[test]
    fn test_avg_tool_failures_per_session_computes_ratio() {
        use std::sync::atomic::Ordering;
        let m = RuntimeMetrics::default();
        m.total_sessions.store(4, Ordering::Relaxed);
        m.failed_tool_calls.store(2, Ordering::Relaxed);
        assert!((m.avg_tool_failures_per_session() - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_avg_tool_failures_per_session_zero_when_no_sessions() {
        let m = RuntimeMetrics::default();
        assert_eq!(m.avg_tool_failures_per_session(), 0.0);
    }

    // ── Round 47: has_any_tool_failures, total_tool_calls_count ───────────────

    #[test]
    fn test_has_any_tool_failures_false_when_no_failures() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        let snap = m.snapshot();
        assert!(!snap.has_any_tool_failures());
    }

    #[test]
    fn test_has_any_tool_failures_true_when_failure_recorded() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_failure("search");
        let snap = m.snapshot();
        assert!(snap.has_any_tool_failures());
    }

    #[test]
    fn test_total_tool_calls_count_sums_all_per_tool_calls() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("search");
        m.record_tool_call("lookup");
        let snap = m.snapshot();
        assert_eq!(snap.total_tool_calls_count(), 3);
    }

    #[test]
    fn test_total_tool_calls_count_zero_for_no_calls() {
        let m = RuntimeMetrics::new();
        let snap = m.snapshot();
        assert_eq!(snap.total_tool_calls_count(), 0);
    }

    // ── Round 49: tool_call_imbalance ─────────────────────────────────────────

    #[test]
    fn test_tool_call_imbalance_one_for_single_tool() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("search");
        let snap = m.snapshot();
        assert!((snap.tool_call_imbalance() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_tool_call_imbalance_computes_max_over_min() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        m.record_tool_call("a");
        m.record_tool_call("a");
        m.record_tool_call("b");
        let snap = m.snapshot();
        // max=3, min=1 → ratio=3.0
        assert!((snap.tool_call_imbalance() - 3.0).abs() < 1e-9);
    }

    #[test]
    fn test_tool_call_imbalance_one_for_empty_snapshot() {
        let m = RuntimeMetrics::new();
        let snap = m.snapshot();
        assert!((snap.tool_call_imbalance() - 1.0).abs() < 1e-9);
    }

    // ── Round 50: has_failed_tools ────────────────────────────────────────────

    #[test]
    fn test_has_failed_tools_true_when_failure_recorded() {
        let m = RuntimeMetrics::new();
        m.record_tool_failure("search");
        assert!(m.has_failed_tools());
    }

    #[test]
    fn test_has_failed_tools_false_when_no_failures() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        assert!(!m.has_failed_tools());
    }

    // ── Round 47: distinct_tool_count ─────────────────────────────────────────

    #[test]
    fn test_distinct_tool_count_reflects_unique_tools() {
        let snap = MetricsSnapshot {
            per_tool_calls: [
                ("tool_a".to_string(), 3),
                ("tool_b".to_string(), 1),
            ]
            .into_iter()
            .collect(),
            ..Default::default()
        };
        assert_eq!(snap.distinct_tool_count(), 2);
    }

    #[test]
    fn test_distinct_tool_count_zero_for_empty_snapshot() {
        let snap = MetricsSnapshot::default();
        assert_eq!(snap.distinct_tool_count(), 0);
    }

    // ── Round 50: tools_with_zero_failures, tool_call_imbalance ───────────────

    #[test]
    fn test_tools_with_zero_failures_returns_tools_without_failures() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("lookup");
        m.record_tool_failure("search");
        let snap = m.snapshot();
        let zero_fail = snap.tools_with_zero_failures();
        assert_eq!(zero_fail, vec!["lookup"]);
    }

    #[test]
    fn test_tools_with_zero_failures_empty_when_all_have_failures() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        m.record_tool_failure("a");
        let snap = m.snapshot();
        assert!(snap.tools_with_zero_failures().is_empty());
    }

    // ── Round 51: tool_names_by_call_count ────────────────────────────────────

    #[test]
    fn test_tool_names_by_call_count_orders_highest_first() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("alpha");
        m.record_tool_call("beta");
        m.record_tool_call("beta");
        m.record_tool_call("gamma");
        m.record_tool_call("gamma");
        m.record_tool_call("gamma");
        let names = m.tool_names_by_call_count();
        assert_eq!(names[0], "gamma");
        assert_eq!(names[1], "beta");
        assert_eq!(names[2], "alpha");
    }

    #[test]
    fn test_tool_names_by_call_count_empty_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert!(m.tool_names_by_call_count().is_empty());
    }

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

    #[test]
    fn test_has_any_tool_calls_false_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert!(!m.snapshot().has_any_tool_calls());
    }

    #[test]
    fn test_has_any_tool_calls_true_after_recording() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        assert!(m.snapshot().has_any_tool_calls());
    }

    #[test]
    fn test_tool_names_alphabetical_sorted() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("zebra");
        m.record_tool_call("alpha");
        m.record_tool_call("mango");
        let names = m.snapshot().tool_names_alphabetical();
        assert_eq!(names, vec!["alpha", "mango", "zebra"]);
    }

    #[test]
    fn test_tool_names_alphabetical_empty_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert!(m.snapshot().tool_names_alphabetical().is_empty());
    }

    // ── Round 52: tool_calls_per_memory_recall ─────────────────────────────────

    #[test]
    fn test_tool_calls_per_memory_recall_returns_ratio() {
        let m = RuntimeMetrics::new();
        m.memory_recall_count.store(2, std::sync::atomic::Ordering::Relaxed);
        m.record_tool_call("a");
        m.record_tool_call("b");
        m.record_tool_call("c");
        m.record_tool_call("d");
        assert_eq!(m.tool_calls_per_memory_recall(), 2.0);
    }

    #[test]
    fn test_tool_calls_per_memory_recall_zero_when_no_recalls() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        assert_eq!(m.tool_calls_per_memory_recall(), 0.0);
    }

    #[test]
    fn test_tool_calls_per_memory_recall_zero_for_empty_metrics() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.tool_calls_per_memory_recall(), 0.0);
    }

    // ── Round 53: memory_recalls_per_tool_call ─────────────────────────────────

    #[test]
    fn test_memory_recalls_per_tool_call_returns_ratio() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        m.record_tool_call("b");
        m.memory_recall_count.store(4, std::sync::atomic::Ordering::Relaxed);
        assert_eq!(m.memory_recalls_per_tool_call(), 2.0);
    }

    #[test]
    fn test_memory_recalls_per_tool_call_zero_when_no_tool_calls() {
        let m = RuntimeMetrics::new();
        m.memory_recall_count.store(5, std::sync::atomic::Ordering::Relaxed);
        assert_eq!(m.memory_recalls_per_tool_call(), 0.0);
    }

    #[test]
    fn test_memory_recalls_per_tool_call_zero_for_empty_metrics() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.memory_recalls_per_tool_call(), 0.0);
    }

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

    #[test]
    fn test_avg_failures_per_tool_zero_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.snapshot().avg_failures_per_tool(), 0.0);
    }

    #[test]
    fn test_avg_failures_per_tool_correct_value() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_failure("search");
        m.record_tool_call("write");
        // search: 1 failure, write: 0 failures; avg = 0.5
        let avg = m.snapshot().avg_failures_per_tool();
        assert!((avg - 0.5).abs() < 1e-9);
    }

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

    #[test]
    fn test_memory_pressure_ratio_correct_ratio() {
        use std::sync::atomic::Ordering;
        let m = RuntimeMetrics::new();
        m.total_steps.store(4, Ordering::Relaxed);
        m.memory_recall_count.store(2, Ordering::Relaxed);
        assert!((m.memory_pressure_ratio() - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_memory_pressure_ratio_zero_when_no_steps() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.memory_pressure_ratio(), 0.0);
    }

    #[test]
    fn test_sessions_per_step_correct_ratio() {
        use std::sync::atomic::Ordering;
        let m = RuntimeMetrics::new();
        m.total_steps.store(10, Ordering::Relaxed);
        m.total_sessions.store(2, Ordering::Relaxed);
        assert!((m.sessions_per_step() - 0.2).abs() < 1e-9);
    }

    #[test]
    fn test_sessions_per_step_zero_when_no_steps() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.sessions_per_step(), 0.0);
    }

    // ── Round 55: step_failure_rate ────────────────────────────────────────────

    #[test]
    fn test_step_failure_rate_returns_ratio() {
        let m = RuntimeMetrics::new();
        m.total_steps.store(4, std::sync::atomic::Ordering::Relaxed);
        m.record_tool_failure("a");
        m.record_tool_failure("b");
        assert_eq!(m.step_failure_rate(), 0.5);
    }

    #[test]
    fn test_step_failure_rate_zero_when_no_steps() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.step_failure_rate(), 0.0);
    }

    #[test]
    fn test_step_failure_rate_zero_when_no_failures() {
        let m = RuntimeMetrics::new();
        m.total_steps.store(3, std::sync::atomic::Ordering::Relaxed);
        assert_eq!(m.step_failure_rate(), 0.0);
    }

    // ── Round 49 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_avg_calls_per_step_correct_ratio() {
        use std::sync::atomic::Ordering;
        let m = RuntimeMetrics::new();
        m.total_steps.store(4, Ordering::Relaxed);
        m.total_tool_calls.store(8, Ordering::Relaxed);
        assert!((m.avg_calls_per_step() - 2.0).abs() < 1e-9);
    }

    #[test]
    fn test_avg_calls_per_step_zero_when_no_steps() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.avg_calls_per_step(), 0.0);
    }

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

    #[test]
    fn test_tools_above_failure_ratio_returns_failing_tools() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_failure("search");
        m.record_tool_call("write");
        // search ratio = 1.0, write ratio = 0.0
        let above = m.snapshot().tools_above_failure_ratio(0.5);
        assert_eq!(above, vec!["search"]);
    }

    #[test]
    fn test_tools_above_failure_ratio_empty_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert!(m.snapshot().tools_above_failure_ratio(0.1).is_empty());
    }

    // ── Round 56: total_backpressure_shed_pct ──────────────────────────────────

    #[test]
    fn test_total_backpressure_shed_pct_returns_ratio() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        m.record_tool_call("b");
        m.record_tool_call("c");
        m.record_tool_call("d");
        m.backpressure_shed_count.store(1, std::sync::atomic::Ordering::Relaxed);
        assert_eq!(m.total_backpressure_shed_pct(), 0.25);
    }

    #[test]
    fn test_total_backpressure_shed_pct_zero_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.total_backpressure_shed_pct(), 0.0);
    }

    // ── Round 50 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_backpressure_ratio_correct() {
        use std::sync::atomic::Ordering;
        let m = RuntimeMetrics::new();
        m.total_steps.store(4, Ordering::Relaxed);
        m.backpressure_shed_count.store(1, Ordering::Relaxed);
        assert!((m.backpressure_ratio() - 0.25).abs() < 1e-9);
    }

    #[test]
    fn test_backpressure_ratio_zero_when_no_steps() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.backpressure_ratio(), 0.0);
    }

    // ── Round 57: tool_with_highest_failure_rate ───────────────────────────────

    #[test]
    fn test_tool_with_highest_failure_rate_returns_most_failing_tool() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        m.record_tool_failure("a");
        m.record_tool_call("b");
        m.record_tool_call("b");
        m.record_tool_failure("b");
        // a: 1/1 = 1.0, b: 1/2 = 0.5 → highest is "a"
        assert_eq!(m.tool_with_highest_failure_rate().as_deref(), Some("a"));
    }

    #[test]
    fn test_tool_with_highest_failure_rate_none_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert!(m.tool_with_highest_failure_rate().is_none());
    }

    // ── Round 51 ──────────────────────────────────────────────────────────────

    #[test]
    fn test_has_latency_data_true_after_step() {
        use std::sync::atomic::Ordering;
        let m = RuntimeMetrics::new();
        m.total_steps.store(1, Ordering::Relaxed);
        assert!(m.has_latency_data());
    }

    #[test]
    fn test_has_latency_data_false_for_new_metrics() {
        let m = RuntimeMetrics::new();
        assert!(!m.has_latency_data());
    }

    // ── Round 59: global_failure_rate ─────────────────────────────────────────

    #[test]
    fn test_global_failure_rate_correct() {
        let m = RuntimeMetrics::new();
        m.total_tool_calls.store(10, Ordering::Relaxed);
        m.failed_tool_calls.store(2, Ordering::Relaxed);
        assert!((m.global_failure_rate() - 0.2).abs() < 1e-9);
    }

    #[test]
    fn test_global_failure_rate_zero_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.global_failure_rate(), 0.0);
    }

    // ── Round 60: agent_tool_count ────────────────────────────────────────────

    #[test]
    fn test_agent_tool_count_correct() {
        let m = RuntimeMetrics::new();
        m.record_agent_tool_call("agent-A", "tool1");
        m.record_agent_tool_call("agent-B", "tool2");
        m.record_agent_tool_call("agent-A", "tool3");
        assert_eq!(m.agent_tool_count(), 2);
    }

    #[test]
    fn test_agent_tool_count_zero_when_no_calls() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.agent_tool_count(), 0);
    }

    // ── Round 61: active_session_count ────────────────────────────────────────

    #[test]
    fn test_active_session_count_correct() {
        let m = RuntimeMetrics::new();
        m.active_sessions.store(3, Ordering::Relaxed);
        assert_eq!(m.active_session_count(), 3);
    }

    #[test]
    fn test_active_session_count_zero_initially() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.active_session_count(), 0);
    }

    // ── Round 62: memory_to_session_ratio ────────────────────────────────────

    #[test]
    fn test_memory_to_session_ratio_correct() {
        let m = RuntimeMetrics::new();
        m.total_sessions.store(4, Ordering::Relaxed);
        m.memory_recall_count.store(8, Ordering::Relaxed);
        assert!((m.memory_to_session_ratio() - 2.0).abs() < 1e-9);
    }

    #[test]
    fn test_memory_to_session_ratio_zero_when_no_sessions() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.memory_to_session_ratio(), 0.0);
    }

    // ── Round 63: total_latency_per_session ───────────────────────────────────

    #[test]
    fn test_total_latency_per_session_correct() {
        let m = RuntimeMetrics::new();
        m.record_step_latency(100);
        m.record_step_latency(200);
        m.total_sessions.store(2, Ordering::Relaxed);
        // total latency = 300ms, sessions = 2 → 150.0
        assert!((m.total_latency_per_session() - 150.0).abs() < 1e-9);
    }

    #[test]
    fn test_total_latency_per_session_zero_when_no_sessions() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.total_latency_per_session(), 0.0);
    }

    // ── Round 57: failure_ratio_for_tool, any_tool_exceeds_calls ─────────────

    #[test]
    fn test_failure_ratio_for_tool_correct_ratio() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("search");
        m.record_tool_failure("search");
        let snap = m.snapshot();
        assert!((snap.failure_ratio_for_tool("search") - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_failure_ratio_for_tool_zero_for_unknown_tool() {
        let m = RuntimeMetrics::new();
        let snap = m.snapshot();
        assert_eq!(snap.failure_ratio_for_tool("unknown"), 0.0);
    }

    #[test]
    fn test_any_tool_exceeds_calls_true_when_above_threshold() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        m.record_tool_call("a");
        m.record_tool_call("a");
        let snap = m.snapshot();
        assert!(snap.any_tool_exceeds_calls(2));
    }

    #[test]
    fn test_any_tool_exceeds_calls_false_when_all_at_or_below_threshold() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        m.record_tool_call("a");
        let snap = m.snapshot();
        assert!(!snap.any_tool_exceeds_calls(2));
    }

    // ── Round 58: tool_call_count_for ─────────────────────────────────────
    #[test]
    fn test_tool_call_count_for_returns_correct_count() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("grep");
        m.record_tool_call("grep");
        m.record_tool_call("grep");
        assert_eq!(m.tool_call_count_for("grep"), 3);
    }

    #[test]
    fn test_tool_call_count_for_returns_zero_for_unknown_tool() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.tool_call_count_for("nonexistent"), 0);
    }

    // ── Round 58: total_unique_tools, total_agent_tool_calls ──────────────────

    #[test]
    fn test_total_unique_tools_counts_distinct_tools() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("search");
        m.record_tool_call("browse");
        let snap = m.snapshot();
        assert_eq!(snap.total_unique_tools(), 2);
    }

    #[test]
    fn test_total_unique_tools_zero_for_no_calls() {
        let m = RuntimeMetrics::new();
        let snap = m.snapshot();
        assert_eq!(snap.total_unique_tools(), 0);
    }

    #[test]
    fn test_total_agent_tool_calls_sums_all_agents() {
        let m = RuntimeMetrics::new();
        m.record_agent_tool_call("agent-1", "search");
        m.record_agent_tool_call("agent-1", "browse");
        m.record_agent_tool_call("agent-2", "search");
        assert_eq!(m.total_agent_tool_calls(), 3);
    }

    #[test]
    fn test_total_agent_tool_calls_zero_for_new_metrics() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.total_agent_tool_calls(), 0);
    }

    // ── Round 59: top_called_tool ──────────────────────────────────────────────

    #[test]
    fn test_top_called_tool_returns_most_called() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("search");
        m.record_tool_call("browse");
        assert_eq!(m.top_called_tool().as_deref(), Some("search"));
    }

    #[test]
    fn test_top_called_tool_none_for_new_metrics() {
        let m = RuntimeMetrics::new();
        assert!(m.top_called_tool().is_none());
    }

    // ── Round 60: avg_step_latency_ms, distinct_tools_called, agent_tool_call_count ──

    #[test]
    fn test_avg_step_latency_ms_correct() {
        let m = RuntimeMetrics::new();
        m.record_step_latency(100);
        m.record_step_latency(200);
        // avg_step_latency_ms divides by total_steps, not latency sample count
        m.total_steps.store(2, Ordering::Relaxed);
        assert!((m.avg_step_latency_ms() - 150.0).abs() < 1e-9);
    }

    #[test]
    fn test_avg_step_latency_ms_zero_for_new_metrics() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.avg_step_latency_ms(), 0.0);
    }

    #[test]
    fn test_distinct_tools_called_counts_unique_tools() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("search");
        m.record_tool_call("browse");
        assert_eq!(m.distinct_tools_called(), 2);
    }

    #[test]
    fn test_distinct_tools_called_zero_for_new_metrics() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.distinct_tools_called(), 0);
    }

    #[test]
    fn test_agent_tool_call_count_sums_correctly() {
        let m = RuntimeMetrics::new();
        m.record_agent_tool_call("agent-1", "search");
        m.record_agent_tool_call("agent-1", "browse");
        m.record_agent_tool_call("agent-2", "search");
        assert_eq!(m.agent_tool_call_count("agent-1"), 2);
    }

    #[test]
    fn test_agent_tool_call_count_zero_for_unknown_agent() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.agent_tool_call_count("nobody"), 0);
    }

    // ── Round 59: tool_call_ratio_for, has_recorded_agent_calls ──────────────

    #[test]
    fn test_tool_call_ratio_for_returns_correct_fraction() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        m.record_tool_call("a");
        m.record_tool_call("b");
        let snap = m.snapshot();
        assert!((snap.tool_call_ratio_for("a") - 2.0 / 3.0).abs() < 1e-9);
    }

    #[test]
    fn test_tool_call_ratio_for_zero_when_no_calls() {
        let m = RuntimeMetrics::new();
        let snap = m.snapshot();
        assert_eq!(snap.tool_call_ratio_for("search"), 0.0);
    }

    #[test]
    fn test_has_recorded_agent_calls_true_after_recording() {
        let m = RuntimeMetrics::new();
        m.record_agent_tool_call("agent-1", "search");
        assert!(m.has_recorded_agent_calls());
    }

    #[test]
    fn test_has_recorded_agent_calls_false_for_new_metrics() {
        let m = RuntimeMetrics::new();
        assert!(!m.has_recorded_agent_calls());
    }

    // ── Round 61: failure_rate_for ─────────────────────────────────────────────

    #[test]
    fn test_failure_rate_for_returns_correct_ratio() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("search");
        m.record_tool_failure("search");
        assert!((m.failure_rate_for("search") - 0.5).abs() < 1e-9);
    }

    #[test]
    fn test_failure_rate_for_zero_for_unknown_tool() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.failure_rate_for("unknown"), 0.0);
    }

    #[test]
    fn test_failure_rate_for_zero_when_no_failures() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("browse");
        assert_eq!(m.failure_rate_for("browse"), 0.0);
    }

    // ── Round 62: tool_calls_per_session, failure_free_tools ──────────────────

    #[test]
    fn test_tool_calls_per_session_returns_correct_ratio() {
        let m = RuntimeMetrics::new();
        m.total_sessions
            .fetch_add(2, std::sync::atomic::Ordering::Relaxed);
        m.record_tool_call("search");
        m.record_tool_call("browse");
        m.record_tool_call("search");
        assert!((m.tool_calls_per_session() - 1.5).abs() < 1e-9);
    }

    #[test]
    fn test_tool_calls_per_session_zero_when_no_sessions() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.tool_calls_per_session(), 0.0);
    }

    #[test]
    fn test_failure_free_tools_returns_tools_without_failures() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("search");
        m.record_tool_call("browse");
        m.record_tool_failure("search");
        let tools = m.failure_free_tools();
        assert!(tools.contains(&"browse".to_string()));
        assert!(!tools.contains(&"search".to_string()));
    }

    #[test]
    fn test_failure_free_tools_empty_when_all_failed() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        m.record_tool_failure("a");
        let tools = m.failure_free_tools();
        assert!(!tools.contains(&"a".to_string()));
    }

    // ── Round 62: total_failures_across_all_tools, tools_with_calls_above ────

    #[test]
    fn test_total_failures_across_all_tools_sums_all_failures() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        m.record_tool_failure("a");
        m.record_tool_call("b");
        m.record_tool_failure("b");
        m.record_tool_failure("b");
        let snap = m.snapshot();
        assert_eq!(snap.total_failures_across_all_tools(), 3);
    }

    #[test]
    fn test_total_failures_across_all_tools_zero_when_none() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("a");
        let snap = m.snapshot();
        assert_eq!(snap.total_failures_across_all_tools(), 0);
    }

    #[test]
    fn test_tools_with_calls_above_returns_tools_exceeding_threshold() {
        let m = RuntimeMetrics::new();
        for _ in 0..5 { m.record_tool_call("busy"); }
        m.record_tool_call("idle");
        let result = m.tools_with_calls_above(3);
        assert!(result.contains(&"busy".to_string()));
        assert!(!result.contains(&"idle".to_string()));
    }

    #[test]
    fn test_tools_with_calls_above_empty_when_none_qualify() {
        let m = RuntimeMetrics::new();
        m.record_tool_call("once");
        assert!(m.tools_with_calls_above(5).is_empty());
    }

    #[test]
    fn test_tools_with_calls_above_returns_sorted_names() {
        let m = RuntimeMetrics::new();
        for _ in 0..3 { m.record_tool_call("zebra"); }
        for _ in 0..3 { m.record_tool_call("apple"); }
        let result = m.tools_with_calls_above(2);
        assert_eq!(result, vec!["apple", "zebra"]);
    }

    // ── Round 63: checkpoint_errors_count, agents_with_failures, total_agent_failures ──

    #[test]
    fn test_checkpoint_errors_count_zero_for_new_metrics() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.checkpoint_errors_count(), 0);
    }

    #[test]
    fn test_checkpoint_errors_count_reflects_incremented_value() {
        let m = RuntimeMetrics::new();
        m.checkpoint_errors
            .fetch_add(3, std::sync::atomic::Ordering::Relaxed);
        assert_eq!(m.checkpoint_errors_count(), 3);
    }

    #[test]
    fn test_agents_with_failures_returns_agents_with_failures() {
        let m = RuntimeMetrics::new();
        m.record_agent_tool_call("agent-x", "search");
        m.record_agent_tool_failure("agent-x", "search");
        m.record_agent_tool_call("agent-y", "browse");
        let agents = m.agents_with_failures();
        assert!(agents.contains(&"agent-x".to_string()));
        assert!(!agents.contains(&"agent-y".to_string()));
    }

    #[test]
    fn test_total_agent_failures_sums_all_failures() {
        let m = RuntimeMetrics::new();
        m.record_agent_tool_failure("a", "tool1");
        m.record_agent_tool_failure("a", "tool2");
        m.record_agent_tool_failure("b", "tool1");
        assert_eq!(m.total_agent_failures(), 3);
    }

    #[test]
    fn test_total_agent_failures_zero_for_new_metrics() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.total_agent_failures(), 0);
    }

    // ── Round 64: per_step_tool_call_rate, agents_with_no_failures ───────────

    #[test]
    fn test_per_step_tool_call_rate_zero_when_no_steps() {
        let m = RuntimeMetrics::new();
        assert_eq!(m.per_step_tool_call_rate(), 0.0);
    }

    #[test]
    fn test_per_step_tool_call_rate_computed_correctly() {
        let m = RuntimeMetrics::new();
        m.total_steps.store(2, Ordering::Relaxed);
        m.record_tool_call("search");
        m.record_tool_call("browse");
        m.record_tool_call("search");
        // 3 calls / 2 steps = 1.5
        assert!((m.per_step_tool_call_rate() - 1.5).abs() < 1e-9);
    }

    #[test]
    fn test_agents_with_no_failures_returns_clean_agents() {
        let m = RuntimeMetrics::new();
        m.record_agent_tool_call("agent-clean", "search");
        m.record_agent_tool_call("agent-fail", "search");
        m.record_agent_tool_failure("agent-fail", "search");
        let clean = m.agents_with_no_failures();
        assert!(clean.contains(&"agent-clean".to_string()));
        assert!(!clean.contains(&"agent-fail".to_string()));
    }

    #[test]
    fn test_agents_with_no_failures_empty_for_new_metrics() {
        let m = RuntimeMetrics::new();
        assert!(m.agents_with_no_failures().is_empty());
    }
}