mahbot 0.7.1

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

use anyhow::Context;
use tracing::Instrument;

use crate::providers::reasoning::assistant_replay_payload;
use crate::session::Session;
use crate::tools::{
    ImagePayload, ToolExecutionOutcome, find_tool, format_tool_failure_feedback,
    normalize_tool_call, scrub_tool_output,
};
use crate::util::{
    MEDIA_MARKER_RE, MediaMarkerKind, UnwrapPoison, parse_media_marker, scrub_credentials,
};
use crate::{Agent, ChatMessage, ChatRequest, ChatResponse, Tool, ToolCall};

pub(crate) mod extraction;
pub mod maintainer;
pub mod message_router;
pub mod registry;
pub(crate) mod role;
pub(crate) mod skills;

// ── Tool-batch user context ────────────────────────────────────────
// Set once per tool batch by the Agent work loop's `execute_tool_group`,
// read by tools that need user context (e.g. AnalyzeTool async dispatch).
//
// # Contract
// - Set once per tool batch (per `execute_tool_group` round), not before
//   each individual tool `execute()`.
// - Must be read synchronously (before any `tokio::spawn` boundary) when
//   the value is needed across an async boundary.
// - Falls back to `unwrap_or_default()` → empty string for background
//   agents (management, maintainer, workspace) that have no user context.
//
/// Synchronous read of [`CURRENT_TOOL_USER_NAME`]. See the task-local contract
/// above: reads must happen before any `tokio::spawn` boundary if the value is
/// needed across one.
pub(crate) fn tool_user_name() -> String {
    CURRENT_TOOL_USER_NAME
        .try_with(String::clone)
        .unwrap_or_default()
}

/// Identity of the agent currently executing a tool call: `(agent_id, user_name)`.
/// Errors when the call runs outside a user session — there is no addressable
/// identity to associate side effects with.
pub(crate) fn tool_identity() -> anyhow::Result<(String, String)> {
    let user_name = tool_user_name();
    let agent_id = CURRENT_TOOL_AGENT_ID
        .try_with(Option::clone)
        .ok()
        .flatten()
        .unwrap_or_default();
    anyhow::ensure!(
        !agent_id.is_empty() && !user_name.is_empty(),
        "No agent identity available — the tool must run in a user session."
    );
    Ok((agent_id, user_name))
}

/// The calling agent's identity for a row written STRAIGHT to the log store:
/// `(agent_id, role)`, empty outside an agent run (inbound enrichment, tests).
/// The tracing writer takes this attribution from the current span; a row that
/// bypasses the writer takes it from the same task-local.
pub(crate) fn tool_record_attribution() -> (String, String) {
    CURRENT_TOOL_AGENT_TRACKING
        .try_with(|t| t.as_ref().map(|t| (t.agent_id.clone(), t.role.clone())))
        .ok()
        .flatten()
        .unwrap_or_default()
}

/// Synchronous read of [`CURRENT_TOOL_CHANNEL`]. Same contract as
/// [`tool_user_name`].
pub(crate) fn tool_channel() -> String {
    CURRENT_TOOL_CHANNEL
        .try_with(String::clone)
        .unwrap_or_default()
}

tokio::task_local! {
    pub(crate) static CURRENT_TOOL_USER_NAME: String;
    pub(crate) static CURRENT_TOOL_CHANNEL: String;
    /// The calling agent's DIRECT PARENT INVOCATION grouping key (ticket /
    /// analyze round / research run) — set for the duration of tool execution so
    /// tools that spawn sub-agents (e.g. implement) can propagate the caller's
    /// group to the Running Agents view. `None` = workspace singleton caller.
    pub(crate) static CURRENT_TOOL_PARENT_KEY: Option<crate::agent::registry::ParentKey>;
    /// The calling agent's DIRECT PARENT INVOCATION human-readable label
    /// (ticket title / analyze question / research question) — set alongside
    /// [`CURRENT_TOOL_PARENT_KEY`] for the duration of tool execution so tools
    /// that spawn sub-agents can propagate the caller's group header label to
    /// the Running Agents view. Purely presentational; `None` for workspace
    /// singletons.
    pub(crate) static CURRENT_TOOL_PARENT_LABEL: Option<String>;
    /// The calling agent's background shell session registry — set for the
    /// duration of tool execution so the shell tool (Full roles only) can
    /// register/stop background sessions that are force-killed when the agent
    /// is dropped. `None` outside an agent run (management diagnostics,
    /// tests) — background mode is unavailable there.
    pub(crate) static CURRENT_TOOL_BACKGROUND_SESSIONS:
        Option<std::sync::Arc<crate::tools::shell::BackgroundSessions>>;
    /// The calling agent's id — set for the duration of tool execution so the
    /// shell tool can attribute the spill files it creates to the owning agent
    /// (owner-deletes-at-end: the run's spill files are deleted when the agent
    /// run ends). `None` outside an agent run (management diagnostics, tests).
    pub(crate) static CURRENT_TOOL_AGENT_ID: Option<String>;
    /// The calling agent's registry identity + generation — set for the
    /// duration of tool execution so tool-internal LLM calls (e.g. media
    /// transcription in video tool results) can attribute themselves to the
    /// owning agent's Running Agents card and telemetry. `None` outside an
    /// agent run (inbound enrichment, tests) — such calls register in
    /// [`crate::agent::registry::NON_AGENT_CALLS`] instead.
    pub(crate) static CURRENT_TOOL_AGENT_TRACKING:
        Option<crate::agent::registry::AgentTracking>;
}

/// Maximum number of completed tool rounds before the agent loop bails out.
///
/// A tool round is the LLM call(s) that returned tool calls plus the execution
/// and commit of that tool group. The counter increments only after a committed
/// tool group; the final-answer LLM call and the image-rejection strip
/// `continue` do not increment it, so an agent can legitimately make more LLM
/// calls than this cap. These semantics are deliberate — do not "fix" the
/// counter (or the strip path) to count raw LLM calls while touching this file.
///
/// **DO NOT REDUCE this value without benchmarking against real ticket tool-round
/// distributions in this codebase.**
///
/// # Why this is intentionally generous (1000)
///
/// * Agents routinely consume hundreds of tool rounds in normal, legitimate
///   work: multi-file editing with compile-error feedback loops, research →
///   implement → review cycles, and sequential tool dependencies all require
///   many turns — this is deliberate problem-solving, not a runaway loop.
///
/// * Cost is not a concern. Even a full 1000-round run on the current
///   default models costs well under $1, so there is zero cost reason to
///   lower the limit.
///
/// * Running to the tool-round cap is EXTREMELY rare with modern models. The
///   limit exists only as a safety net for pathological edge cases — it is not
///   protecting against a common or recurring problem.
///
/// * Reducing the cap prematurely would cause legitimate long-running agents to
///   fail mid-task, wasting more time and tokens on restarts than the tool
///   rounds themselves would have consumed.
///
/// Value last intentionally reviewed: 2026-07-11
const MAX_TOOL_ROUNDS: usize = 1000;

/// Maximum length of serialized arguments stored in per-call stats.
/// Longer arguments are truncated at a UTF-8-safe boundary.
const MAX_STATS_ARG_LENGTH: usize = 500;

/// Retry-exhaustion marker shared by the producer contexts
/// (`llm_call`/`summarize`) and the `engineer_failure_comment` match; drift is
/// cosmetic-only (typed classification uses `RetryExhausted`).
pub(crate) const RETRY_EXHAUSTION_MARKER: &str = "exhausted retry budget";

/// Attempts allowed for the summarization call when the model answers with a
/// tool call instead of a summary — the request is re-sent verbatim, so the
/// attempts are byte-identical (prompt-prefix cache preserved) and the tool
/// call is never executed. Bounded on purpose: on exhaustion the compaction is
/// abandoned exactly as before (full history kept, owner not disturbed).
const SUMMARIZE_ATTEMPTS: u32 = 3;

/// Boxed future returned by [`Agent::complete_pending_tool_calls`] — a pinned
/// box so the caller (`Agent::work`) awaits a `dyn Future` instead of a concrete
/// opaque type. Naming the boxed future breaks the async opaque-type Send cycle
/// that a concrete `impl Future` return would create between `agent` and
/// `tools::analyze` (the resume cores re-enter agent sub-agent runs).
type CompletePendingToolCallsFuture<'a> =
    std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<bool>> + Send + 'a>>;

/// Extract file paths from successful media-generation tool outcomes.
///
/// Scans the zipped tool calls and outcomes for media-generation tools,
/// parsing the output for their media marker prefixes (e.g. `[IMAGE:path]`,
/// `[VIDEO:path]`) and returning `(marker_prefix, path)` pairs.
///
/// Only successfully-executed tools with a defined [`Tool::media_marker`] are
/// inspected. Non-media tools and failed outcomes are silently skipped.
///
/// Limitation: file paths containing `]` are truncated by the regex — not a
/// concern in practice, as media-generation tools produce temporary files with safe names.
fn extract_media_from_outcomes(
    tools: &[Box<dyn Tool>],
    tool_calls: &[ToolCall],
    outcomes: &[ToolExecutionOutcome],
) -> Vec<(&'static str, String)> {
    let mut paths = Vec::new();
    for (call, outcome) in tool_calls.iter().zip(outcomes.iter()) {
        if outcome.success
            && let Some(marker_prefix) = find_tool(tools, &call.name).and_then(Tool::media_marker)
        {
            // Derive the regex kind from the marker prefix, e.g. "[IMAGE:" -> "IMAGE".
            // This relies on the documented invariant that media_marker() returns "[KIND:".
            let marker = &marker_prefix[1..marker_prefix.len() - 1];
            let mut matched = false;
            for caps in MEDIA_MARKER_RE.captures_iter(&outcome.output) {
                let (captured_kind, path) = parse_media_marker(&caps);
                if captured_kind.token() == marker {
                    matched = true;
                    paths.push((marker_prefix, path.to_string()));
                }
            }
            if !matched {
                tracing::warn!(
                    media_tool = %call.name,
                    marker = %marker_prefix,
                    "Could not parse media path from tool output — skipping media marker",
                );
            }
        }
    }
    paths
}

/// Iterate the values carried by `[IMAGE:...]` markers in the session's user
/// messages. Only User-role messages are scanned: that is where images are
/// promoted to provider vision parts (`parse_image_markers`).
fn user_image_marker_values(history: &[ChatMessage]) -> impl Iterator<Item = &str> {
    history
        .iter()
        .filter(|msg| msg.role == crate::ChatRole::User)
        .flat_map(|msg| {
            MEDIA_MARKER_RE
                .captures_iter(&msg.content)
                .filter_map(|caps| {
                    let (kind, path) = parse_media_marker(&caps);
                    (kind == MediaMarkerKind::Image).then_some(path)
                })
        })
}

/// Collect the values carried by `[IMAGE:...]` markers already present in the
/// session's user messages (the read tool's synthetic injection data-URIs, or
/// file paths from other tools' media markers). Used as the dedup key for the
/// read tool's synthetic image injection: a repeat read of an already-attached
/// image (same marker value) is not injected again.
fn existing_image_marker_values(history: &[ChatMessage]) -> std::collections::HashSet<String> {
    user_image_marker_values(history)
        .map(str::to_string)
        .collect()
}

/// Count DISTINCT data-URI image markers in the session's user messages —
/// the second summarization trigger
/// ([`crate::session::SUMMARIZATION_IMAGE_COUNT`]). The `data:image/` prefix
/// pre-gate keeps the per-turn scan cheap (no full raster decode per marker)
/// and never undercounts: every marker the provider promotes to a vision
/// part (`is_native_data_uri` accepts PNG/JPEG/WebP only, all
/// `data:image/…`) passes the gate. The gate is deliberately a superset —
/// an invalid `data:image/*` payload may be counted too.
fn session_image_marker_count(history: &[ChatMessage]) -> usize {
    user_image_marker_values(history)
        .filter(|value| value.starts_with("data:image/"))
        .collect::<std::collections::HashSet<_>>()
        .len()
}

/// Derive an [`ImagePayload`] from a successful tool's raw output when the tool
/// did not supply its own payload but returned a real on-disk `[IMAGE:path]`
/// marker, so a tool-produced image (e.g. image_gen) reaches the agent's own
/// context automatically. Fails open (`None`) when the marker path is not
/// absolute or cannot be compressed into a bounded JPEG data-URI (e.g. an SVG,
/// which the compressor cannot rasterize) — the user still receives the file via
/// the marker in the raw output.
///
/// This deliberately does NOT route through the shared classifier: as a
/// *producer* it must emit a bounded compressed payload, so the async
/// full-decode + compression (`local_image_to_compressed_data_uri_with_meta`)
/// is its authoritative validity check. Routing through the classifier would
/// only add a redundant decode — the classifier's local-file validity check
/// (`raster_decode_limits`: 256 MiB / 16384 px) is a bounded decode but adds no
/// encoding value on top of the producer's own decode + resize + JPEG-encode,
/// which is what actually bounds the emitted payload.
async fn derive_image_payload_from_marker(output: &str) -> Option<ImagePayload> {
    // Cheap guard: skip the regex scan for outputs carrying no image marker.
    if !output.contains("[IMAGE:") {
        return None;
    }
    for caps in MEDIA_MARKER_RE.captures_iter(output) {
        let (kind, path) = parse_media_marker(&caps);
        if kind != MediaMarkerKind::Image {
            continue;
        }
        let p = Path::new(path);
        if !p.is_absolute() {
            continue;
        }
        let Ok(meta) = crate::util::local_image_to_compressed_data_uri_with_meta(p).await else {
            // Fail open for this marker (missing file, non-raster e.g. SVG,
            // over-cap input). The marker stays in the raw output for delivery.
            continue;
        };
        return Some(ImagePayload::from_compressed_meta(
            p,
            meta,
            None,
            crate::tools::ImagePayloadSource::Generated,
        ));
    }
    None
}

/// Format a tool's outcome for persistence and derive any fresh image payloads —
/// the shared "outcome → content" step used by both
/// [`Agent::commit_tool_results`] and resume-completion re-execution.
///
/// Reading [`ToolExecutionOutcome::text_is_content`]: content keeps the
/// annotations as an appendix and its own markers literal; a claim is replaced
/// by them.
///
/// `format_output` (or the truncation fallback) first, then the outcome's own
/// image payloads take precedence over a payload derived from a real on-disk
/// `[IMAGE:path]` marker in a successful tool output. When payloads apply, the
/// dedup key `seen` (computed lazily from `history` on first use) decides
/// fresh/attached per payload; the returned vec holds every FRESH attachment,
/// which the caller injects as ONE synthetic user message
/// ([`crate::util::injected_image_user_message`]). The outcome's payloads are
/// taken rather than copied — they carry base64 data URIs, and this runs once
/// per outcome.
async fn tool_result_content(
    tools: &[Box<dyn Tool>],
    call_name: &str,
    outcome: ToolExecutionOutcome,
    seen: &mut Option<std::collections::HashSet<String>>,
    history: &[ChatMessage],
) -> (String, Vec<ImagePayload>) {
    let formatted = match find_tool(tools, call_name) {
        Some(t) => t.format_output(&outcome.output),
        None => crate::util::truncate_tool_output(&outcome.output),
    };

    // The outcome's own payloads (read tool) take precedence; otherwise derive
    // an injected image from a real on-disk `[IMAGE:path]` marker in a
    // successful tool output (image_gen) so a tool-produced image reaches the
    // agent's own context. Only a text that is a claim about its images can be
    // the source of such a claim — in content (a converted document's extracted
    // text) a marker is text, so nothing is derived from it. Derivation fails
    // open: a non-rasterizable path (e.g. SVG) yields no payload while the
    // marker stays in the raw output.
    let mut payloads: Vec<ImagePayload> = outcome.image_payloads;
    if payloads.is_empty() && !outcome.text_is_content && outcome.success {
        payloads.extend(derive_image_payload_from_marker(&outcome.output).await);
    }
    if payloads.is_empty() {
        return (formatted, Vec::new());
    }

    let seen = seen.get_or_insert_with(|| existing_image_marker_values(history));
    let mut fresh = Vec::with_capacity(payloads.len());
    let mut annotations = Vec::with_capacity(payloads.len());
    for payload in payloads {
        if seen.insert(payload.data_uri.clone()) {
            annotations.push(payload.attached_annotation());
            fresh.push(payload);
        } else {
            annotations.push(payload.already_attached_annotation());
        }
    }
    let annotation_block = annotations.join("\n");
    let output = if outcome.text_is_content {
        format!("{formatted}\n{annotation_block}")
    } else {
        annotation_block
    };
    (output, fresh)
}

/// The single synthetic User-role message carrying a round's fresh tool images;
/// `None` when the round attached nothing. Why one message per round rather than
/// one per image or per call: [`crate::util::injected_image_user_message`].
fn injected_images_message(
    agent_id: &str,
    role: crate::Role,
    payloads: Vec<ImagePayload>,
) -> Option<ChatMessage> {
    if payloads.is_empty() {
        return None;
    }
    let mut data_uris = Vec::with_capacity(payloads.len());
    for payload in payloads {
        tracing::debug!(
            agent_id,
            %role,
            path = %payload.path,
            "Injecting tool image as a synthetic user message"
        );
        data_uris.push(payload.data_uri);
    }
    Some(ChatMessage::user(crate::util::injected_image_user_message(
        &data_uris,
    )))
}

/// One-pass derivation of a role's advertised tools and their specs — the single
/// source for both [`Agent::new`] and the research wrap-up snapshot
/// ([`role_tool_specs`]), so the frozen post-deadline replay can never drift from
/// the live agent's tools (KV-cache byte identity). The caller owns the run-scoped
/// tracker of the chrome sessions those tools open, which the run's end releases
/// ([`crate::tools::chrome::ChromeRunSessions::for_run`]).
#[must_use]
pub(crate) fn role_tools_and_specs(
    role: crate::Role,
    ws: &crate::Workspace,
    is_admin: bool,
    chrome_sessions: std::sync::Arc<crate::tools::chrome::ChromeRunSessions>,
) -> (Vec<Box<dyn Tool>>, Vec<crate::ToolSpec>) {
    let tools: Vec<Box<dyn Tool>> = role
        .tools(ws, is_admin, chrome_sessions)
        .into_iter()
        .filter(|t| t.is_advertised())
        .collect();
    let tool_specs = tools.iter().map(|t| t.spec()).collect();
    (tools, tool_specs)
}

/// The advertised tool specs of one role without a run: a caller that builds the
/// tools only to snapshot their schemas has no run to own chrome sessions, so the
/// tools get a tracker with no namespace (`ChromeRunSessions::default`) — one that
/// never claims a run's.
#[must_use]
pub(crate) fn role_tool_specs(
    role: crate::Role,
    ws: &crate::Workspace,
    is_admin: bool,
) -> Vec<crate::ToolSpec> {
    role_tools_and_specs(
        role,
        ws,
        is_admin,
        std::sync::Arc::new(crate::tools::chrome::ChromeRunSessions::default()),
    )
    .1
}

/// A role's derived chat-request triplet (model slot → per-model provider
/// routing → per-role reasoning effort). Named fields keep the order
/// unambiguous across cross-module callers — a bare tuple would have two
/// type-identical `Option<String>` slots.
pub(crate) struct RoleChatParams {
    pub model: String,
    pub provider_order: Option<String>,
    pub reasoning_effort: Option<String>,
}

/// Derive a role's chat-request triplet — the single source of the
/// model/routing/reasoning_effort derivation shared by [`chat_request`],
/// [`crate::pipeline::verdict::synthesis_request`], and
/// [`crate::tools::analyze::consolidate_findings`]. Consumers keep their own
/// `max_tokens`, `tools`, and `meta`; the call sites do not share a KV-cache
/// prefix with each other (distinct conversations/system prompts).
#[must_use]
pub(crate) fn role_chat_params(role: crate::Role) -> RoleChatParams {
    let model = crate::config::CONFIG.role_model(role);
    let routing = crate::config::CONFIG.model_routing(&model);
    RoleChatParams {
        model,
        provider_order: routing.provider_order,
        reasoning_effort: Some(
            crate::agent::role::role_info(&role)
                .default_reasoning_effort
                .to_string(),
        ),
    }
}

/// Build the byte-relevant chat params (model, tools, reasoning_effort,
/// routing, max_tokens) for a role. The model/routing/reasoning_effort
/// triplet comes from [`role_chat_params`] — the single source also used by
/// [`Agent::build_chat_request`], the research wrap-up snapshot and
/// orchestrator params (both in [`crate::tools::research`]),
/// [`crate::pipeline::verdict::synthesis_request`], and
/// [`crate::tools::analyze::consolidate_findings`] — so every consumer derives
/// the same triplet for a role. `meta` is telemetry-only (never part of the
/// provider request body) and attached by call sites.
#[must_use]
pub(crate) fn chat_request(
    role: crate::Role,
    tool_specs: Option<Vec<crate::ToolSpec>>,
    messages: Vec<ChatMessage>,
) -> ChatRequest {
    let RoleChatParams {
        model,
        provider_order,
        reasoning_effort,
    } = role_chat_params(role);
    ChatRequest {
        messages,
        tools: tool_specs,
        model,
        max_tokens: Some(crate::DEFAULT_MAX_TOKENS),
        reasoning_effort,
        provider_order,
        meta: None,
    }
}

impl Agent {
    /// Create a new agent with the given agent_id, role, workspace, and optional ticket.
    ///
    /// Tools are derived from [`crate::Role`] via [`crate::Role::tools`].
    /// Automatically registers with [`crate::agent::registry::AGENT_REGISTRY`] and creates an
    /// internal [`tokio_util::sync::CancellationToken`]. The agent is deregistered on [`Drop`].
    ///
    /// `parent_key` carries the DIRECT PARENT INVOCATION grouping key for the
    /// Running Agents view (ticket / analyze round / research run). `None` means
    /// the agent is a workspace singleton (manager / maintainer / discovery /
    /// direct chat) — ticket agents pass the ticket and get
    /// [`ParentKey::Ticket`] implicitly.
    ///
    /// `parent_label` is the human-readable label of that parent invocation
    /// (ticket title / analyze question / research question) — purely
    /// presentational. `None` falls back to the ticket title when the effective
    /// parent is a ticket; callers of analyze/research rounds pass the
    /// question/task text explicitly.
    #[must_use]
    #[expect(clippy::too_many_arguments)] // one positional arg per construction field; callers use literals
    pub fn new(
        agent_id: String,
        role: crate::Role,
        ws: &crate::Workspace,
        ticket: Option<crate::pipeline::board::Ticket>,
        user_name: String,
        channel: String,
        is_admin: bool,
        parent_key: Option<crate::agent::registry::ParentKey>,
        parent_label: Option<String>,
    ) -> Self {
        let chrome_sessions = crate::tools::chrome::ChromeRunSessions::for_run(&agent_id);
        let (tools, tool_specs) =
            role_tools_and_specs(role, ws, is_admin, std::sync::Arc::clone(&chrome_sessions));

        let cancel_token = tokio_util::sync::CancellationToken::new();
        let pause_stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
        // Ticket agents group by their ticket; an explicit parent key (analyze
        // round / research run) takes precedence when both are present.
        let parent_key = parent_key.or_else(|| {
            ticket
                .as_ref()
                .map(|t| crate::agent::registry::ParentKey::Ticket(t.id.clone()))
        });
        // The group header label: an explicit parent label (analyze/research
        // question) wins; a ticket-parented agent without one falls back to
        // the ticket title. Purely presentational — never affects behavior.
        let parent_label = parent_label.or_else(|| match parent_key {
            Some(crate::agent::registry::ParentKey::Ticket(_)) => {
                ticket.as_ref().map(|t| t.title.clone())
            }
            _ => None,
        });
        // Registration-time manual-cancel check: a sub-agent of a research
        // run whose cancel signal already fired (the user cancelled the run
        // from the Running Agents page) must never run a round — even when it
        // registers AFTER the registry's cancel sweep (the late-register
        // race). The token is pre-cancelled, so the agent's llm_loop bails at
        // its first tool-round-top check and the round yields no response.
        if let Some(crate::agent::registry::ParentKey::Research(run_id)) = &parent_key
            && crate::research_cancel::is_cancelled(run_id)
        {
            cancel_token.cancel();
        }
        let generation = crate::agent::registry::AGENT_REGISTRY.register(
            agent_id.clone(),
            role.to_string(),
            ticket.as_ref().map(|t| t.id.clone()),
            ws,
            cancel_token.clone(),
            parent_key.clone(),
            parent_label.clone(),
            pause_stop.clone(),
        );

        // Register a fresh live-transcript snapshot holder for this agent run
        // and attach it to the session, so the Running Agents GUI can read the
        // in-memory conversation (including the unpersisted tail) at render
        // time. A replacement run reusing the same agent_id gets a fresh holder
        // (see the transcript registry's generation guard).
        let mut session = Session::default();
        session.attach_transcript(
            crate::session::TRANSCRIPT_REGISTRY.register(agent_id.clone(), generation),
        );

        Self {
            agent_id,
            role,
            session,
            workspace: Arc::new(ws.clone()),
            tools,
            tool_specs,
            cancel_token,
            pause_stop,
            paused_frozen: std::sync::atomic::AtomicBool::new(false),
            ticket,
            generation,
            tool_stats: std::sync::Mutex::new(Vec::new()),
            user_name,
            channel,
            is_admin,
            parent_key,
            parent_label,
            incoming_rx: None,
            round_ts: None,
            first_call_notify: None,
            failure: None,
            failure_class: None,
            sleep_ended: false,
            background_sessions: std::sync::Arc::new(
                crate::tools::shell::BackgroundSessions::default(),
            ),
            chrome_sessions,
        }
    }
}

impl Drop for Agent {
    fn drop(&mut self) {
        if self.generation > 0 {
            crate::agent::registry::AGENT_REGISTRY.deregister(&self.agent_id, self.generation);
            crate::session::TRANSCRIPT_REGISTRY.deregister(&self.agent_id, self.generation);
        }
        // Teardown kill: the agent's background shell sessions must not
        // outlive it. Force-kill only (no grace), mirroring the existing
        // teardown-kill behavior for in-flight shell children. Synchronous —
        // SIGKILL to each live process group on unix, one TerminateJobObject per
        // session on Windows ("end the tree", no grace — see
        // `tools::shell::tree`).
        self.background_sessions.terminate_all();
    }
}

/// Render a board ticket comment as a user-visible message for the agent's
/// session. Shared by live delivery ([`Agent::drain_incoming_messages`]) and
/// the empty-message resume catch-up ([`Agent::inject_outstanding_comments`])
/// so both paths produce identical comment rendering.
fn format_comment_message(user_name: &str, content: &str) -> String {
    format!("[Comment from {user_name} on ticket]: {content}")
}

impl Agent {
    /// Flush accumulated tool stats to the logs store, then persist the final
    /// assistant message via `session.finalize(&self.agent_id)`. Flush failures are logged
    /// but do not abort finalization.
    ///
    /// An empty unpersisted tail is logged here with full agent/role/workspace/
    /// ticket attribution: at INFO when the graceful drain cut the turn
    /// (expected and lossless — committed tool frames are durable, ticket
    /// rounds resume at boot), at DEBUG when the turn ended via the `sleep`
    /// tool (equally expected), at INFO otherwise (genuine anomaly).
    pub async fn finalize_session(&mut self) -> anyhow::Result<()> {
        // Drain accumulated tool usage stats
        let stats = {
            let mut guard = self.tool_stats.lock().unwrap_poison();
            std::mem::take(&mut *guard)
        };
        if !stats.is_empty()
            && let Some(store) = crate::logs::LOG_STORE.get()
            && let Err(e) = store
                .flush_batch(
                    &self.agent_id,
                    self.role.as_str(),
                    &self.workspace.path,
                    &stats,
                )
                .await
        {
            tracing::warn!(
                agent_id = %self.agent_id,
                role = %self.role.as_str(),
                error = %e,
                "Failed to flush tool usage stats"
            );
        }

        // When cancelled (deliberate stop or global shutdown), no assistant
        // message is expected — skip finalization to avoid the "finalize called
        // but no assistant message" warning. Tool results were already
        // persisted via commit_tool_results inside llm_loop; any unpersisted
        // tail (failed drain) is in-memory only and dropped at the next init
        // (comments remain recoverable from the board DB).
        if self.cancel_token.is_cancelled() || crate::shutdown::shutdown_token().is_cancelled() {
            tracing::debug!(
                agent_id = %self.agent_id,
                role = %self.role,
                workspace = %self.workspace.name,
                ticket = self.ticket.as_ref().map(|t| t.id.as_str()),
                "Session finalize skipped (agent cancelled or shutdown)"
            );
            return Ok(());
        }

        match self.session.finalize(&self.agent_id).await? {
            crate::session::FinalizeOutcome::Flushed => {}
            crate::session::FinalizeOutcome::NoUnpersistedTail => {
                if crate::shutdown::is_draining() {
                    // Graceful drain cut the turn right after the last
                    // tool-group commit: nothing was left unpersisted.
                    // Expected and lossless — committed tool frames are
                    // durable, ticket rounds resume at boot (job stays
                    // status='launched'), direct sessions resume on the next
                    // user message.
                    tracing::info!(
                        agent_id = %self.agent_id,
                        role = %self.role,
                        workspace = %self.workspace.name,
                        ticket = self.ticket.as_ref().map(|t| t.id.as_str()),
                        "Session finalize no-op: turn cut by graceful drain — \
                         committed frames are durable; resumes at boot or on the next user message"
                    );
                } else if self.sleep_ended {
                    // Turn ended via the sleep tool: the round's tool results are
                    // durable and the Assistant is intentionally silent while waiting
                    // for new input — a normal outcome, not the anomaly below.
                    tracing::debug!(
                        agent_id = %self.agent_id,
                        role = %self.role,
                        workspace = %self.workspace.name,
                        ticket = self.ticket.as_ref().map(|t| t.id.as_str()),
                        "Session finalize no-op: turn ended via sleep — waiting for new input"
                    );
                } else {
                    // Genuine anomaly: the turn ended with no persisted output
                    // outside a drain (e.g. an LLM call failing with no output
                    // produced). Keep the byte-identical historical message so
                    // external correlation keeps working.
                    tracing::info!(
                        agent_id = %self.agent_id,
                        role = %self.role,
                        workspace = %self.workspace.name,
                        ticket = self.ticket.as_ref().map(|t| t.id.as_str()),
                        "finalize called but no new assistant message in history"
                    );
                }
            }
        }
        Ok(())
    }

    /// Check whether cancellation has been triggered on this agent.
    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.cancel_token.is_cancelled()
    }

    /// Check whether a workspace-pause (strict freeze) cancellation was requested
    /// (distinct from an internal code-driven cancellation).
    #[must_use]
    fn is_cancelled_by_pause(&self) -> bool {
        self.pause_stop.load(std::sync::atomic::Ordering::SeqCst)
    }

    /// IMMUTABLE bail-time snapshot of whether this agent's run was stopped by
    /// a cooperative workspace-pause freeze. Set once at the LLM-round boundary
    /// (never cleared), so a pipeline finalizer can distinguish a frozen run
    /// from a technical failure even if the workspace is resumed before the
    /// finalizer reads it.
    #[must_use]
    pub(crate) fn is_paused_frozen(&self) -> bool {
        self.paused_frozen.load(std::sync::atomic::Ordering::SeqCst)
    }

    /// Human-readable failure reason with the same global-token-first ordering
    /// as [`failure_classification`]: shutdown cancels every per-agent token,
    /// so the global token must be checked before an internal cancel is
    /// reported.
    #[must_use]
    pub(crate) fn failure_reason(&self, fallback: &str) -> String {
        if crate::shutdown::shutdown_token().is_cancelled() {
            "service shutting down".to_string()
        } else if self.is_cancelled() {
            "agent cancelled".to_string()
        } else {
            self.failure.clone().unwrap_or_else(|| fallback.to_string())
        }
    }

    /// Single-sourced shutdown/drain bail guard: the session is durable, so
    /// the round is cut short and resumes when re-driven (boot job replay or
    /// the next dispatch).
    fn bail_on_shutdown() -> anyhow::Result<()> {
        if crate::shutdown::aborting() {
            anyhow::bail!(
                "Agent round cut short by shutdown/drain — session is durable; resumes when re-driven"
            );
        }
        Ok(())
    }

    /// Log-only drain-cut marker for `complete_pending_tool_calls`: drain began
    /// mid-resume/completion — the call stays dangling for the next cycle.
    fn log_drain_cut(tool: &str) {
        tracing::info!(tool = %tool, "Drain-cut during resume-completion — leaving calls dangling");
    }

    /// Live-view activity guard: shows `label` on the agent's card while an
    /// observational LLM call runs (extraction, summarization) — these calls
    /// never register a separate non-agent call row, so the card is the only
    /// tracker. Clears on drop.
    fn activity_guard(&self, label: &'static str) -> crate::agent::registry::ActivityGuard {
        crate::agent::registry::AGENT_REGISTRY.activity_started(
            &self.agent_id,
            self.generation,
            label,
        )
    }

    /// Run a complete agent turn: initialize session, work loop (with shutdown
    /// cancellation), finalize session.
    pub async fn work(&mut self, msg: &str, resume: bool) -> anyhow::Result<String> {
        // Load the session WITHOUT appending the turn message: the universal
        // completion below must settle any dangling tool calls BEFORE the new
        // message lands (results insert directly after their frame, so the
        // history stays provider-valid even when the frame is not the tail).
        self.session.init(&self.agent_id).await?;

        // The session is re-engaging (any job kind: user message, async result,
        // alarm, boot replay): clear a stale sleep-ended flag BEFORE this turn
        // runs, so a genuine crash mid-round on this turn is still recovered
        // normally by the dead-session poller. Only the Assistant and the
        // Manager can write the flag (`sleep` is granted only to them), so
        // other roles skip the read.
        if matches!(self.role, crate::Role::Assistant | crate::Role::Manager)
            && crate::session::store()
                .get_sleep_ended(&self.agent_id)
                .await
            && let Err(e) = crate::session::store()
                .set_sleep_ended(&self.agent_id, false)
                .await
        {
            tracing::warn!(
                agent_id = %self.agent_id,
                error = %e,
                "Failed to clear sleep-ended flag"
            );
        }

        // Universal deterministic resume-completion: settle the session's last
        // tool-call frame's result-less calls BEFORE any LLM call, on every
        // role/path (no resume-flag gating). Drain mid-call, a hard crash and a
        // stage re-drive all go through this identical mechanism.
        let settled = if crate::shutdown::aborting() {
            false
        } else {
            self.complete_pending_tool_calls().await?
        };

        if !msg.is_empty() {
            self.session
                .append_turn_message(
                    &self.agent_id,
                    msg,
                    &self.workspace,
                    &self.role,
                    self.ticket.as_ref(),
                    &self.channel,
                    &self.user_name,
                    self.round_ts.as_deref(),
                    self.is_admin,
                )
                .await?;
        }

        // Pre-maybe_summarize drain check: a fresh dispatch that starts during
        // the graceful drain (or a fired shutdown token) must not destructively
        // compact an over-threshold session before the llm_loop drain
        // check fires. The round is cut before any LLM work; boot resume
        // continues the session.
        Self::bail_on_shutdown()?;

        // A resumed stage-agent round starting with an empty message would
        // otherwise never surface board comments (the session-start ticket block
        // is not re-rendered). Inject any it has not seen.
        self.inject_outstanding_comments(resume, msg).await;

        // Mandatory: destructive over-threshold compaction is SKIPPED on resumed
        // turns AND on turns that just settled dangling tool results — the
        // pre-crash trail the resume was meant to preserve must survive (the
        // design's resume-flag rule; do NOT infer resume from an empty message
        // — RecoveryRetry semantics are unchanged). A settlement is resume-like:
        // the retention window excludes tool frames/results, so over-threshold
        // compaction right after settling would drop the settled result (e.g. a
        // stage re-drive on a >SUMMARIZATION_THRESHOLD session); summarization
        // happens on the next plain turn instead.
        if !resume && !settled {
            self.maybe_summarize().await;
        }

        let shutdown = crate::shutdown::shutdown_token();
        let response_result = tokio::select! {
            () = shutdown.cancelled() => {
                Err(anyhow::anyhow!("Shutting down"))
            }
            result = self.llm_loop() => result,
        };

        // Always finalize session — even on global shutdown, persist progress
        if let Err(e) = self.finalize_session().await {
            tracing::error!(error = %e, "Session finalize failed");
        }

        let response = response_result?;
        Ok(response)
    }

    /// Universal deterministic resume-completion: settle the session's last
    /// tool-call frame's result-less calls BEFORE any LLM call, on every
    /// role/path. Durable sync jobs (analyze/implement) owned by this session
    /// pin are slot-resumed; every other call is re-executed. Result settlement
    /// and job terminalization commit in ONE transaction — a crash rolls back
    /// both, the job stays launched, and the next cycle re-settles
    /// idempotently. Results settle contiguously after their frame — the
    /// history stays provider-valid. No-op when nothing is dangling.
    ///
    /// The single position where dangling calls are completed is intentionally
    /// ungated: a graceful drain mid-call, a hard crash and a stage re-drive all
    /// converge here. Already-completed calls are never re-run (their result is
    /// present, so `pending_tool_frame` excludes them).
    ///
    /// Returns `true` when any results were settled this run (used by `work`
    /// to skip destructive summarization — a turn that just settled dangling
    /// results is resume-like), `false` otherwise.
    ///
    /// Returns a boxed future (rather than an opaque `impl Future`) so the
    /// agent/tools async-opaque Send cycle around the resume cores (which
    /// re-enter agent sub-agent runs) is broken at the box boundary.
    #[expect(clippy::too_many_lines)] // deliberate: one cohesive resume+settle path
    fn complete_pending_tool_calls(&mut self) -> CompletePendingToolCallsFuture<'_> {
        Box::pin(async move {
            let Some(frame) = self.session.pending_tool_frame() else {
                return Ok(false);
            };
            let calls = frame.calls;
            tracing::info!(
                agent_id = %self.agent_id,
                role = %self.role,
                count = calls.len(),
                "Completing pending tool calls before the LLM call"
            );

            let conn = &crate::session::store().conn;
            // Hoist the owned-jobs lookup: if ANY pending call is
            // analyze/implement, fetch the caller-owned launched-jobs pool ONCE
            // before the loop (newest-first). When only non-durable calls are
            // pending, no jobs query runs at all. The pool is CONSUMED per
            // call below, so two same-kind calls in one frame bind to two
            // DISTINCT jobs — and because jobs are newest-first while frame
            // calls are in dispatch order, each call binds the OLDEST remaining
            // job (see the rposition below).
            let has_durable = calls
                .iter()
                .any(|c| crate::tools::SyncDurableCore::from_tool_name(&c.name).is_some());
            let mut owned = if has_durable {
                crate::jobs::find_owned_launched_jobs(conn, &self.agent_id).await?
            } else {
                Vec::new()
            };

            let mut pairs: Vec<(String, String)> = Vec::with_capacity(calls.len());
            let mut follow_up: Vec<ChatMessage> = Vec::new();
            let mut terminalize: Vec<String> = Vec::new();
            // Fresh image payloads of the whole resumed round — injected as ONE
            // synthetic user message after the loop, like the commit path.
            let mut fresh_images: Vec<ImagePayload> = Vec::new();
            // Shared dedup key for fresh-image injection across the re-executed
            // calls (computed lazily on first image payload).
            let mut seen_data_uris: Option<std::collections::HashSet<String>> = None;

            for call in calls {
                // Durable-resume attempt for analyze/implement owned jobs: the
                // JOBS ROW is the source of truth. A terminal job yields content
                // (terminalized after settlement); a DrainCut stops the whole
                // completion; a gone job was explicitly abandoned — the call is
                // not re-executed, it surfaces a short model-facing note.
                let mut resumed_content: Option<String> = None;
                let core = crate::tools::SyncDurableCore::from_tool_name(&call.name);
                if let (Some(core), Some(pos)) =
                    (core, owned.iter().rposition(|j| j.kind == call.name))
                {
                    // `rposition` (not `position`): jobs are newest-first while
                    // frame calls are in dispatch order, so the FIRST call must
                    // bind the OLDEST matching job — position would give the
                    // first call the NEWEST job (crossed results).
                    let job = owned.swap_remove(pos);
                    let outcome = core.resume_sync_core(&self.workspace, &job.id, true).await;
                    match outcome {
                        Ok(crate::jobs::SyncResumeOutcome::Terminal(_, _, res)) => {
                            terminalize.push(job.id);
                            resumed_content = Some(match res {
                                Ok(text) => text,
                                Err(e) => e.to_string(),
                            });
                        }
                        Ok(crate::jobs::SyncResumeOutcome::DrainCut) => {
                            // Drain began mid-resume — leave everything dangling
                            // for the next completion cycle.
                            Self::log_drain_cut(&call.name);
                            return Ok(false);
                        }
                        Ok(crate::jobs::SyncResumeOutcome::Gone) => {
                            // The job was explicitly abandoned (session /clear or
                            // workspace deletion) racing this resume — no result
                            // is available and the row is already gone, so do NOT
                            // push onto `terminalize`. Surface a short note to
                            // the model instead of re-executing or erroring.
                            tracing::info!(
                                job = %job.id,
                                "Job row gone (explicitly abandoned) — surfacing note instead of re-executing"
                            );
                            resumed_content = Some(
                                "The durable job behind this call was explicitly abandoned — \
                                 no result is available. Re-issue the call if the work is still needed."
                                    .to_string(),
                            );
                        }
                        Err(e) => {
                            // A resume-core INFRA failure (roster/checkpoint DB
                            // error) must fail the round rather than spawn a
                            // duplicate fresh job — the job row stays launched
                            // for the next drive.
                            tracing::error!(
                                job = %job.id,
                                error = %e,
                                "Resume-core infra failure — failing the round"
                            );
                            return Err(e).context("resume-core infra failure");
                        }
                    }
                }

                let formatted = if let Some(content) = resumed_content {
                    // Format the resumed raw content exactly like the commit path.
                    find_tool(&self.tools, &call.name)
                        .map(|t| t.format_output(&content))
                        .unwrap_or(content)
                } else if call.name == "sleep"
                    && let Some(reason) =
                        sleep_rejection_reason(frame.has_text, frame.call_count > 1)
                {
                    // Sleep-delivery guard on the resume path: re-executing the
                    // sleep would settle a "Zzz..." result over text the user
                    // never saw — settle the rejection instead so the model
                    // resends the text as a plain round.
                    tracing::warn!(
                        agent_id = %self.agent_id,
                        tool = %call.name,
                        reason,
                        "Sleep call rejected during resume-completion"
                    );
                    self.push_tool_call_record(
                        call.name.clone(),
                        &call.arguments,
                        0,
                        false,
                        Some(reason.to_string()),
                    );
                    Self::failure_outcome(&call.name, &call.arguments, reason)
                        .0
                        .output
                } else {
                    // Re-execute the call (under the tool task-local context).
                    let outcome = self
                        .in_tool_context(async {
                            self.execute_tool(&call.name, call.arguments.clone()).await
                        })
                        .await;
                    if outcome.suspended {
                        // Drain-cut mid-execution — leave the call dangling.
                        Self::log_drain_cut(&call.name);
                        return Ok(false);
                    }
                    // Format through the tool exactly like the commit path and
                    // capture any freshly-derived image payloads. The payloads
                    // are collected across the whole resumed round and injected
                    // as ONE message after the loop, like the commit path.
                    let (formatted, fresh_payloads) = tool_result_content(
                        &self.tools,
                        &call.name,
                        outcome,
                        &mut seen_data_uris,
                        self.session.history(),
                    )
                    .await;
                    fresh_images.extend(fresh_payloads);
                    formatted
                };
                pairs.push((call.id, formatted));
            }

            if let Some(message) = injected_images_message(&self.agent_id, self.role, fresh_images)
            {
                follow_up.push(message);
            }

            // Settle + terminalize in ONE transaction: the settle rewrites the
            // post-frame session rows and the terminalize deletes each resumed
            // job's row, so a crash rolls back BOTH — the job stays launched
            // and the next cycle re-settles idempotently (the settle DELETEs
            // the rows after the frame and reinserts, so re-settling an
            // already-settled frame is a structural no-op). No orphan sweep is
            // needed: the settle-succeeded/terminalize-lost crash window is
            // gone by construction. Every terminalize id also pushed a pair,
            // so the guard only needs the pairs/follow_up terms.
            if !pairs.is_empty() || !follow_up.is_empty() {
                let tx = conn
                    .begin_tx()
                    .await
                    .context("begin settle+terminalize tx")?;
                let settled = crate::session::store()
                    .settle_tool_results_tx(&tx, &self.agent_id, &pairs, &follow_up)
                    .await
                    .context("settle resumed results")?;
                for id in terminalize {
                    tx.execute(
                        "DELETE FROM jobs WHERE id = ?1",
                        crate::db::params![id.as_str()],
                    )
                    .await
                    .with_context(|| format!("terminalize job {id}"))?;
                }
                tx.commit().await.context("commit settle+terminalize tx")?;
                // Mirror into the in-memory history only AFTER the durable
                // commit: a commit failure rolls the DB back, and a pre-commit
                // mirror would leave the history settled while the DB is not.
                self.session
                    .mirror_settled(settled)
                    .context("mirror settled results")?;
            }
            Ok(!pairs.is_empty() || !follow_up.is_empty())
        })
    }

    /// Run the full agent loop: LLM calls → tool execution → loop until final answer.
    async fn llm_loop(&mut self) -> anyhow::Result<String> {
        let span = tracing::info_span!("agent", agent_id = %self.agent_id, role = %self.role, workspace = %self.workspace.path);
        async {
            let mut tool_rounds = 0usize;
            let mut accumulated_media_paths: Vec<(&'static str, String)> = Vec::new();
            loop {
                if self.cancel_token.is_cancelled() {
                    anyhow::bail!("Agent cancelled");
                }
                // Cooperative workspace-pause (strict freeze): the current LLM
                // round ends at this boundary — no new LLM call starts. The
                // pause does NOT fire the per-agent cancel token, so the round
                // that was already in flight completes and commits first. The
                // phase finalizer treats the frozen agent as a no-op (the job
                // stays in place for the unpause re-drive).
                if self.is_cancelled_by_pause() {
                    // Record the freeze IMMUTABLY at the bail so a later
                    // unpause (which clears the live pause_stop) cannot turn a
                    // frozen run into a misclassified hard failure.
                    self.paused_frozen
                        .store(true, std::sync::atomic::Ordering::SeqCst);
                    anyhow::bail!("Agent frozen by workspace pause — resumes at unpause");
                }
                // Shutdown/drain: checked at tool-round top (after the previous
                // tool group's commit) so the CURRENT tool group completes —
                // no new LLM call starts once the drain begins (or the token
                // fires). The round is resumed at boot via the job row
                // (status='launched').
                Self::bail_on_shutdown()?;
                if tool_rounds >= MAX_TOOL_ROUNDS {
                    anyhow::bail!(
                        "Agent exceeded maximum of {MAX_TOOL_ROUNDS} tool rounds \
                         — model may be stuck in a tool-calling loop"
                    );
                }

                // Messages arrive as user messages with a descriptive prefix so
                // the model understands their source (ticket comments get the
                // `format_comment_message` framing).
                self.drain_incoming_messages().await;

                // Leader-stagger signal: fire after the FIRST LLM call
                // completes, success or failure — the wait is fail-open;
                // Notify's stored permit covers a fire-before-wait race.
                let llm_result = self.llm_call().await;
                if tool_rounds == 0
                    && let Some(notify) = &self.first_call_notify
                {
                    notify.notify_one();
                }

                // Provider input-image content-inspection rejection (e.g.
                // OpenRouter HTTP 400 `data_inspection_failed`): the rejected
                // image must not fail the run wholesale nor stay sticky in the
                // session. Strip the image markers from the most recent user
                // message (durable-first) and continue the loop — the next
                // tool round re-runs `llm_call` with the corrected message as
                // part of the NORMAL loop, not a dedicated retry step. No
                // retry guard: a subsequent failure whose most recent user
                // message no longer contains image markers takes the normal
                // failure path (no repeated stripping).
                //
                // The leader-stagger signal above has already fired (first
                // call completed, success or failure): a stripped leader's next
                // request diverges from its followers' byte-stable prefix —
                // fail-open by design, and moot for the direct-chat Assistant
                // scenario that exercises this path (management rounds never
                // send images). Note: the retried call re-runs the tool-round-0
                // `notify_one` above, but the stagger has a single waiter (the
                // `select!` in `spawn_staggered_round`, already consumed) — the
                // second notification stores an unconsumed permit and is
                // dropped with the Notify. No follower is released twice.
                //
                // The downcast is extracted to a local first: `anyhow::Chain`
                // is not `Send`, so it must not be held across the await below
                // (the agent runs inside a spawned, Send-bound task).
                let image_rejection = llm_result.as_ref().err().and_then(|e| {
                    e.chain()
                        .find_map(|cause| cause.downcast_ref::<crate::retry::RetryExhausted>())
                });
                if let Some(exhausted) = image_rejection
                    && self.strip_rejected_input_image(exhausted).await
                {
                    tracing::info!(
                        agent_id = %self.agent_id,
                        role = %self.role,
                        tool_rounds,
                        "Stripped provider-rejected input image from the most recent user \
                         message — continuing the normal loop"
                    );
                    continue;
                }

                let PreparedAssistantTurn {
                    mut display_text,
                    tool_calls,
                    history_content,
                    raw_text,
                } = prepare_assistant_turn(
                    llm_result.with_context(|| {
                        llm_step_failure_context(&self.session, tool_rounds)
                    })?,
                );

                if tool_calls.is_empty() {
                    self.session.push_assistant(history_content);
                    // Append any pending media markers the model may have omitted
                    for (marker_prefix, path) in &accumulated_media_paths {
                        let marker = format!("{marker_prefix}{path}]");
                        if !display_text.contains(&marker) {
                            let _ = write!(display_text, "\n{marker}");
                        }
                    }
                    return Ok(display_text);
                }

                // EMISSION-TIME DURABILITY: the assistant frame with its tool
                // calls is committed BEFORE the calls execute — a crash or drain
                // mid-execution leaves the calls durably recorded with their
                // results absent, and the universal resume-completion step (run
                // before any LLM call on this session) re-runs or resumes them.
                // The end-of-round commit below persists only the results.
                self.session
                    .persist_messages(
                        &self.agent_id,
                        &[ChatMessage::assistant(history_content.clone())],
                    )
                    .await?;                // Sleep-delivery guard: a sleep call in a round with
                // accompanying raw text or bundled with other tool calls is
                // rejected (see `execute_tool_round`) instead of silently
                // swallowing the text or ending the run.
                let has_sleep = tool_calls.iter().any(|c| c.name == "sleep");
                let sleep_rejection = has_sleep
                    .then(|| sleep_rejection_reason(!raw_text.trim().is_empty(), tool_calls.len() > 1))
                    .flatten();
                let all_outcomes = self.execute_tool_round(&tool_calls, sleep_rejection).await;

                // Track media generation outcomes for marker fallback
                accumulated_media_paths.extend(extract_media_from_outcomes(
                    &self.tools,
                    &tool_calls,
                    &all_outcomes,
                ));

                // Read before the commit, which consumes the outcomes' payloads.
                let sleep_ended = all_outcomes.iter().any(|o| o.success && o.ends_turn);

                self.commit_tool_results(&tool_calls, all_outcomes).await?;

                // Sleep stop: a successful `sleep` call ends the run gracefully AFTER
                // this round — every tool result above is already committed, nothing
                // is lost. Ordered before the loop-top MAX_TOOL_ROUNDS guard: the
                // return happens before the next iteration is even evaluated.
                if sleep_ended {
                    self.sleep_ended = true;
                    if let Err(e) = crate::session::store().set_sleep_ended(&self.agent_id, true).await {
                        tracing::warn!(
                            agent_id = %self.agent_id,
                            error = %e,
                            "Failed to persist sleep-ended flag — a stale tool-tail session may be re-recovered (accepted)"
                        );
                    }
                    return Ok(String::new());
                }

                tool_rounds += 1;
            }
        }
        .instrument(span)
        .await
    }

    /// Execute a batch of tool calls respecting side-effect ordering.
    ///
    /// Read-only tools run in parallel within groups; side-effecting tools
    /// run one at a time. Groups execute sequentially in the original call
    /// order. The returned outcomes correspond one-to-one with `tool_calls`.
    async fn execute_tool_group(&self, tool_calls: &[ToolCall]) -> Vec<ToolExecutionOutcome> {
        // Determine side_effects for each tool call. Unknown tools are
        // conservatively treated as side-effecting (default: true).
        let side_flags: Vec<bool> = tool_calls
            .iter()
            .map(|call| find_tool(&self.tools, &call.name).is_none_or(super::Tool::side_effects))
            .collect();

        let mut outcomes: Vec<ToolExecutionOutcome> = Vec::with_capacity(tool_calls.len());
        let mut i = 0usize;

        self.in_tool_context(async {
            while i < tool_calls.len() {
                if side_flags[i] {
                    // Side-effecting: single-call group, executed alone.
                    let outcome = self
                        .execute_tool(&tool_calls[i].name, tool_calls[i].arguments.clone())
                        .await;
                    outcomes.push(outcome);
                    i += 1;
                } else {
                    // Read-only group: extend while consecutive calls are also read-only.
                    let group_start = i;
                    while i < tool_calls.len() && !side_flags[i] {
                        i += 1;
                    }
                    let group_calls = &tool_calls[group_start..i];

                    // Execute the entire read-only group in parallel.
                    let group_outcomes: Vec<_> = futures_util::future::join_all(
                        group_calls
                            .iter()
                            .map(|call| self.execute_tool(&call.name, call.arguments.clone())),
                    )
                    .await;

                    outcomes.extend(group_outcomes);
                }
            }
        })
        .await;

        outcomes
    }

    /// Execute one tool round under the sleep-delivery guard: when a rejection
    /// is active, every `sleep` call in the round is intercepted BEFORE
    /// execution (a successful sleep would end the run silently via
    /// `ends_turn_on_success`) and settled as a synthetic failure outcome at
    /// its original position, while all sibling calls execute normally. The
    /// returned outcomes stay one-to-one with `tool_calls` (consumers
    /// `extract_media_from_outcomes` and `commit_tool_results` rely on the
    /// alignment).
    async fn execute_tool_round(
        &self,
        tool_calls: &[ToolCall],
        sleep_rejection: Option<&'static str>,
    ) -> Vec<ToolExecutionOutcome> {
        let Some(reason) = sleep_rejection else {
            return self.execute_tool_group(tool_calls).await;
        };

        let rejected = tool_calls.iter().filter(|c| c.name == "sleep").count();
        tracing::info!(
            agent_id = %self.agent_id,
            role = %self.role,
            rejected,
            reason,
            "Sleep call rejected — must run alone in a text-free round"
        );

        // Execute only the non-sleep calls; the sleep calls are intercepted
        // and settled as synthetic failures at their original positions so the
        // round stays aligned one-to-one with `tool_calls`.
        let sibling_calls: Vec<ToolCall> = tool_calls
            .iter()
            .filter(|c| c.name != "sleep")
            .cloned()
            .collect();
        let mut sibling_outcomes = self.execute_tool_group(&sibling_calls).await.into_iter();

        let mut outcomes = Vec::with_capacity(tool_calls.len());
        for call in tool_calls {
            if call.name == "sleep" {
                self.push_tool_call_record(
                    call.name.clone(),
                    &call.arguments,
                    0,
                    false,
                    Some(reason.to_string()),
                );
                outcomes.push(Self::failure_outcome(&call.name, &call.arguments, reason).0);
            } else {
                outcomes.push(
                    sibling_outcomes
                        .next()
                        .expect("non-sleep outcomes align one-to-one"),
                );
            }
        }
        outcomes
    }

    /// Run `fut` under the `CURRENT_TOOL_*` task-local context derived from this
    /// agent's fields. Set once per tool batch (not per-call), so concurrent
    /// read-only tools never interleave each other's user context. Reused by
    /// the universal resume-completion step, which re-executes dangling calls
    /// and needs the same context.
    async fn in_tool_context<T>(&self, fut: impl std::future::Future<Output = T>) -> T {
        let user_name = self.user_name.clone();
        let channel = self.channel.clone();
        let parent_key = self.parent_key.clone();
        let parent_label = self.parent_label.clone();
        let background_sessions = Some(self.background_sessions.clone());
        let agent_id = Some(self.agent_id.clone());
        let agent_tracking = Some(crate::agent::registry::AgentTracking {
            agent_id: self.agent_id.clone(),
            generation: self.generation,
            role: self.role.as_str().to_string(),
            workspace: self.workspace.name.clone(),
        });
        CURRENT_TOOL_USER_NAME
            .scope(user_name, async {
                CURRENT_TOOL_CHANNEL
                    .scope(channel, async {
                        CURRENT_TOOL_PARENT_KEY
                            .scope(parent_key, async {
                                CURRENT_TOOL_PARENT_LABEL
                                    .scope(parent_label, async {
                                        CURRENT_TOOL_BACKGROUND_SESSIONS
                                            .scope(background_sessions, async {
                                                CURRENT_TOOL_AGENT_ID
                                                    .scope(agent_id, async {
                                                        CURRENT_TOOL_AGENT_TRACKING
                                                            .scope(agent_tracking, fut)
                                                            .await
                                                    })
                                                    .await
                                            })
                                            .await
                                    })
                                    .await
                            })
                            .await
                    })
                    .await
            })
            .await
    }

    /// Construct a failure outcome tuple for an error reason.
    ///
    /// [`Self::execute_tool`] calls this helper from three arms: the pre-flight
    /// cancellation bail and the two error arms (unknown tool and execution error).
    /// The helper always returns a full `(ToolExecutionOutcome, String)` tuple; the
    /// two error arms consume it as-is, while the cancellation bail unwraps `.0`
    /// and discards the reason string. This centralizes the byte-for-byte duplicated
    /// construction of the two error arms.
    ///
    /// Assumes `reason` may contain sensitive data; scrubs before use in feedback
    /// text, tracing logs, and stats.
    #[must_use]
    fn failure_outcome(
        call_name: &str,
        call_arguments: &serde_json::Value,
        reason: &str,
    ) -> (ToolExecutionOutcome, String) {
        let reason = scrub_credentials(reason);
        (
            ToolExecutionOutcome {
                output: format_tool_failure_feedback(call_name, call_arguments, &reason),
                success: false,
                // No payloads and no derivation on a failure: the flag is unread.
                image_payloads: Vec::new(),
                text_is_content: false,
                suspended: false,
                ends_turn: false,
            },
            reason,
        )
    }

    /// Record one tool invocation into the agent's in-memory stats (flushed to
    /// the logs store on session finalization). The arguments are serialized,
    /// credential-scrubbed, and length-truncated to the stats budget.
    fn push_tool_call_record(
        &self,
        tool_name: String,
        arguments: &serde_json::Value,
        duration_ms: i64,
        success: bool,
        error_message: Option<String>,
    ) {
        let args_str = serde_json::to_string(arguments).expect("Value is always serializable");
        let args_scrubbed = scrub_credentials(&args_str);
        let arguments =
            crate::util::truncate_bytes(&args_scrubbed, MAX_STATS_ARG_LENGTH).to_string();
        let mut guard = self.tool_stats.lock().unwrap_poison();
        guard.push(crate::ToolCallRecord {
            tool_name,
            arguments,
            duration_ms,
            success,
            error_message,
        });
    }

    /// Execute a single tool call and return the result.
    #[expect(clippy::too_many_lines)]
    async fn execute_tool(
        &self,
        call_name: &str,
        call_arguments: serde_json::Value,
    ) -> ToolExecutionOutcome {
        // Pre-flight cancellation check: if the agent has been cancelled (e.g., by
        // user pressing Stop), bail immediately without executing the tool.  This
        // prevents side-effecting tools (shell commands, file edits, sub-agents)
        // from running after cancellation.  The `llm_loop` checks cancellation at
        // the top of each tool round, but tool calls dispatched before that check
        // can still reach this method.
        if self.cancel_token.is_cancelled() {
            let reason = "Agent cancelled — tool execution skipped";
            tracing::debug!(
                tool = %call_name,
                "Agent cancelled — skipping tool execution"
            );
            return Self::failure_outcome(call_name, &call_arguments, reason).0;
        }

        let start = Instant::now();
        let (tool_name, tool_arguments) = normalize_tool_call(call_name, call_arguments);
        if tool_name != call_name {
            tracing::debug!(
                original = %call_name,
                normalized = %tool_name,
                "Repaired tool call name"
            );
        }

        // Two distinct log levels for error arms (info vs debug) distinguish
        // unknown-tool failures from execution errors without string-prefix matching.
        let (outcome, error_reason) = match find_tool(&self.tools, &tool_name) {
            None => {
                let reason = format!("Unknown tool: {tool_name}");
                let duration = start.elapsed();
                tracing::debug!(
                    tool = %tool_name,
                    duration_ms = duration.as_millis(),
                    success = false,
                    "Unknown tool call"
                );
                Self::failure_outcome(&tool_name, &tool_arguments, &reason)
            }
            Some(tool) => {
                let exec_result = tool
                    .execute_with_payloads(&self.workspace, tool_arguments.clone())
                    .await;
                let duration = start.elapsed();
                match exec_result {
                    Ok(result) => {
                        let output_text = if result.text.is_empty() {
                            String::from("(no output)")
                        } else {
                            result.text
                        };
                        tracing::debug!(
                            tool = %tool_name,
                            duration_ms = duration.as_millis(),
                            "Tool execution completed"
                        );
                        (
                            ToolExecutionOutcome {
                                output: scrub_tool_output(tool, &tool_arguments, &output_text),
                                success: true,
                                image_payloads: result.image_payloads,
                                text_is_content: result.text_is_content,
                                suspended: false,
                                ends_turn: tool.ends_turn_on_success(),
                            },
                            String::new(),
                        )
                    }
                    Err(e) => {
                        // Drain-cut suspension: the tool's durable work (e.g. a
                        // sync analyze/implement round) was deliberately left
                        // launched for deterministic resume. The outcome is
                        // marked `suspended` so the tool-result commit SKIPS it
                        // — the call's frame is already durably persisted and
                        // its result is intentionally absent; the universal
                        // resume-completion step re-runs/resumes it.
                        if e.downcast_ref::<crate::tools::CallSuspended>().is_some() {
                            tracing::debug!(
                                tool = %tool_name,
                                duration_ms = duration.as_millis(),
                                success = false,
                                suspended = true,
                                "Tool execution drain-cut — durable work left launched"
                            );
                            (
                                ToolExecutionOutcome {
                                    // Never read: consumers skip suspended
                                    // outcomes before reading their output.
                                    output: String::new(),
                                    success: false,
                                    image_payloads: Vec::new(),
                                    text_is_content: false,
                                    suspended: true,
                                    ends_turn: false,
                                },
                                String::new(),
                            )
                        } else {
                            let (outcome, error_reason) = Self::failure_outcome(
                                &tool_name,
                                &tool_arguments,
                                &format!("Error executing {tool_name}: {e}"),
                            );
                            tracing::debug!(
                                tool = %tool_name,
                                duration_ms = duration.as_millis(),
                                success = false,
                                "Tool execution error: {error_reason}"
                            );
                            (outcome, error_reason)
                        }
                    }
                }
            }
        };

        // Per-call stats recording — each tool invocation produces one record
        // with arguments, duration, success/failure, and error.
        let elapsed_ms = start.elapsed().as_millis();
        let duration_ms = i64::try_from(elapsed_ms).unwrap_or(0);
        self.push_tool_call_record(
            tool_name,
            &tool_arguments,
            duration_ms,
            outcome.success,
            (!error_reason.is_empty()).then_some(error_reason),
        );
        outcome
    }

    async fn llm_call(&mut self) -> anyhow::Result<ChatResponse> {
        let messages = self.session.history().to_vec();
        let request = self.build_chat_request(messages.clone(), "agent");

        let policy = crate::retry::RetryPolicy::current();
        let response = crate::retry::agent_chat(request, &policy)
            .await
            .with_context(|| format!("LLM call {RETRY_EXHAUSTION_MARKER}"))?;

        // Reasoning-only stop: recovered here — before any promotion,
        // persistence or display — via the bounded continuation (leak-safety
        // invariants are documented on `recover_if_reasoning_only_stop`).
        let response = self
            .recover_if_reasoning_only_stop(messages, response, Self::AGENT_REASONING_RECOVERY)
            .await?;

        // A SUCCESSFUL agent-purpose call updates the session length; failures
        // never reach here (the error above propagates), and a reasoning-only
        // turn that exhausted its continuation returned early above without
        // recording anything — so only the response actually returned to the
        // loop updates the value.
        self.record_session_usage(&response).await;
        Ok(response)
    }

    /// Detect a provider input-image content-inspection rejection on the error
    /// trail and durably strip the image from the most recent user message.
    /// Returns `true` when the strip was applied (the caller continues the
    /// normal loop with the corrected message), `false` for a conservative
    /// no-op (the caller keeps the original error path).
    ///
    /// Persist ordering: the store rewrite completes before the in-memory
    /// swap, so a persist failure (or an unpersisted-tail target) leaves the
    /// session untouched and the original LLM error propagates — no
    /// half-stripped continuation, no swallowed errors. Telemetry note: the
    /// rejected attempt already recorded one `non_retryable` `llm_requests`
    /// row (from the retry loop's `fail_exhausted` tail) before this runs;
    /// the corrected call records its own success row — by design, not a
    /// swallowed error.
    async fn strip_rejected_input_image(
        &mut self,
        exhausted: &crate::retry::RetryExhausted,
    ) -> bool {
        let Some(idx) = crate::session::image_strip::detect_input_image_rejection(
            exhausted,
            self.session.history(),
        ) else {
            return false;
        };
        let reason = crate::session::image_strip::extract_provider_reason(exhausted);
        // Invariant guard: detection and the strip share one marker predicate
        // (see `image_strip::has_image_marker`), so a detected rejection always
        // changes the content. If they ever drift — e.g. a malformed `[IMAGE:`
        // fragment passes detection but the regex leaves it verbatim — a
        // no-change rewrite would report `Rewritten` and the loop `continue`
        // below would skip `tool_rounds += 1`, an unbounded retry loop. Treat a
        // no-change strip as a non-strip: keep the original error path.
        let content = {
            let original = &self.session.history()[idx].content;
            let stripped =
                crate::session::image_strip::strip_image_markers(original, reason.as_deref());
            if stripped == *original {
                tracing::warn!(
                    agent_id = %self.agent_id,
                    role = %self.role,
                    "Input-image rejection detected but stripping produced no change — \
                     treating as a non-strip (normal failure path)"
                );
                return false;
            }
            stripped
        };
        match self
            .session
            .rewrite_last_user_message(&self.agent_id, content)
            .await
        {
            Ok(crate::session::RewriteOutcome::Rewritten) => true,
            Ok(crate::session::RewriteOutcome::UnpersistedTailNoop) => {
                tracing::info!(
                    agent_id = %self.agent_id,
                    role = %self.role,
                    "Input-image rejection detected but the most recent user message is in the \
                     unpersisted tail — conservative no-op, normal failure path applies"
                );
                false
            }
            Err(e) => {
                tracing::error!(
                    agent_id = %self.agent_id,
                    role = %self.role,
                    error = %e,
                    "Failed to persist stripped user message — keeping the original error path"
                );
                false
            }
        }
    }

    /// Bounded continuation recovery for the reasoning-only-stop class
    /// (empty content, no parsed tool calls — see [`is_reasoning_only_stop`]).
    ///
    /// Re-requests with the already-generated thinking attached as the
    /// assistant's reasoning for that turn (empty content) plus an appended
    /// continuation prompt. **Strictly appended-only**: the tail is seeded
    /// with the first in-class response's reasoning, and each LATER in-class
    /// response appends its own (assistant reasoning payload + nudge) pair —
    /// a transport failure NEVER grows the tail (the next attempt re-sends
    /// the PREVIOUS request object verbatim, byte-identical even across a
    /// concurrent config hot-reload). The request prefix stays byte-stable
    /// across attempts (prompt-prefix cache preserved). The tail exists only
    /// in the re-request message list — it is never pushed to the session, so
    /// a failed attempt leaves no transcript trace and the raw thinking can
    /// never reach the user.
    ///
    /// Bounded by [`crate::retry::RetryPolicy::continuation`] (3 attempts,
    /// no wall-clock cap — the 600 s idle timeout is the only bound),
    /// checked against [`crate::shutdown::aborting`] and the agent's cancel
    /// token between attempts. Each attempt
    /// is a single [`crate::providers::chat_scoped`] call; retryable provider
    /// errors re-send the same bytes, non-retryable errors break immediately
    /// (a payload-rejecting 400 never burns the budget).
    ///
    /// Telemetry is operation-level — one `llm_requests` row per continuation
    /// operation, matching the single-row-per-operation convention of the
    /// other retry loops: a resolution records one success row with
    /// `retry_attempts` = the resolving attempt index; exhaustion records one
    /// failure row via the shared `fail_exhausted` tail with
    /// `retry_attempts` = the total attempt count and the last attempt's
    /// finish_reason carried on its failure record. Any response with visible
    /// text or parsed tool calls resolves the turn and is persisted normally
    /// by the caller. Each failed attempt additionally persists one
    /// `llm_failures` row under the operation's id (the synthetic
    /// shutdown/cancellation trail entries excepted — no request is made).
    ///
    /// Exhaustion returns a [`crate::retry::RetryExhausted`] with
    /// `last_raw: None` and a final class derived from the last recorded
    /// failure ([`FailureClass::NoResponse`] for a pure thinking-only
    /// exhaustion, [`FailureClass::Shutdown`] when the global abort fired) — the
    /// thinking text is never embedded in the error, so failure
    /// comments/logs cannot leak it, and it is not misclassified as LLM
    /// provider retry exhaustion (no
    /// [`crate::agent::RETRY_EXHAUSTION_MARKER`]).
    async fn recover_reasoning_only_stop(
        &self,
        base: Vec<ChatMessage>,
        first: ChatResponse,
        purpose: &'static str,
    ) -> Result<ChatResponse, crate::retry::RetryExhausted> {
        let policy = crate::retry::RetryPolicy::continuation();
        let operation_started = Instant::now();
        let nudge = crate::prompt::load_prompt("resume_unfinished_turn.md")
            .trim()
            .to_string();
        let mut failures: Vec<crate::retry::RetryFailureRecord> = Vec::new();
        let mut last_request: Option<ChatRequest> = None;
        // Per-attempt `llm_failures` context — derived from the first built
        // request; `None` when the operation carries no metadata (same gating
        // as the `llm_requests` rows).
        let mut operation: Option<crate::stats::LlmOperationCtx> = None;

        // Seed the tail with the FIRST in-class response's reasoning (empty
        // content) + the continuation nudge. Each LATER in-class response
        // appends its own pair — the tail grows only when the model actually
        // produced a new response, so a transport failure never duplicates
        // the previous thinking.
        let mut tail: Vec<ChatMessage> = vec![
            // The payload always carries a string "content" key, so it decodes
            // to Some("") and serializes via the Some arm — never the
            // omitted-content shape (the serializer backstop covers any drift).
            ChatMessage::assistant(
                assistant_replay_payload(None, &[], first.reasoning.as_ref()).to_string(),
            ),
            ChatMessage::user(nudge.clone()),
        ];
        // True when a new pair was appended since the last request was built:
        // the request is rebuilt only then, otherwise the previous request
        // object is re-sent verbatim (a retryable transport error must not
        // pick up a concurrent config hot-reload).
        let mut tail_grew = true;

        for attempt in 1..=policy.max_attempts {
            let attempt_started = Instant::now();
            // The global abort dominates: it also cancels every per-agent
            // token, so classify it as shutdown, not cancellation.
            if crate::shutdown::aborting() {
                failures.push(crate::retry::RetryFailureRecord::new_simple(
                    crate::retry::FailureClass::Shutdown,
                    &anyhow::anyhow!("global shutdown or drain during continuation recovery"),
                    None,
                ));
                break;
            }
            if self.cancel_token.is_cancelled() {
                break;
            }

            let request = if tail_grew {
                tail_grew = false;
                let mut messages = base.clone();
                messages.extend(tail.iter().cloned());
                let built = self.build_chat_request(messages, purpose);
                if operation.is_none() {
                    operation = crate::stats::LlmOperationCtx::from_request(&built);
                }
                last_request = Some(built.clone());
                built
            } else {
                last_request
                    .clone()
                    .expect("the first iteration always builds a request")
            };

            match crate::providers::chat_scoped(request.clone()).await {
                // Still thinking with no answer — record the attempt (with its
                // finish_reason, so the terminal failure row keeps it), append
                // the NEW reasoning as the next tail pair, and continue.
                Ok(resp) if is_reasoning_only_stop(&resp) => {
                    let rec = crate::retry::RetryFailureRecord::with_metadata(
                        crate::retry::FailureClass::NoResponse,
                        &anyhow::anyhow!(
                            "model returned only reasoning with no answer \
                             (continuation attempt {attempt})"
                        ),
                        resp.finish_reason.clone(),
                        None,
                    );
                    record_continuation_failure(operation.as_ref(), attempt, &rec, attempt_started)
                        .await;
                    failures.push(rec);
                    tail.push(ChatMessage::assistant(
                        assistant_replay_payload(None, &[], resp.reasoning.as_ref()).to_string(),
                    ));
                    tail.push(ChatMessage::user(nudge.clone()));
                    tail_grew = true;
                }
                // Real answer or tool calls — the turn resolves normally.
                Ok(resp) => {
                    crate::stats::record_llm_success(&request, operation_started, attempt, &resp)
                        .await;
                    return Ok(resp);
                }
                // Provider failure — break on non-retryable (a payload-rejecting
                // 400 must not burn the budget); otherwise the next iteration
                // re-sends the byte-identical request (tail untouched).
                Err(err) => {
                    record_continuation_failure(
                        operation.as_ref(),
                        attempt,
                        &err.record,
                        attempt_started,
                    )
                    .await;
                    failures.push(err.record);
                    if !err.class.is_retryable() {
                        break;
                    }
                }
            }
        }

        let final_class = failures
            .last()
            .map_or(crate::retry::FailureClass::NoResponse, |r| r.class);
        let exhausted = crate::retry::RetryExhausted::with_last_raw(failures, final_class, None);
        match last_request {
            Some(request) => {
                crate::retry::fail_exhausted(&request, operation_started, exhausted).await
            }
            None => Err(exhausted),
        }
    }

    /// Recovery policy for the agent loop ([`Self::llm_call`]): continuation
    /// exhaustion fails the turn.
    const AGENT_REASONING_RECOVERY: ReasoningOnlyStopRecovery = ReasoningOnlyStopRecovery {
        purpose: "agent-continuation",
        exhausted_ctx: "model returned only reasoning without an answer after continuation attempts",
    };

    /// Recovery policy for summarization ([`Self::summarize`]): continuation
    /// exhaustion fails open with the full history.
    const SUMMARIZE_REASONING_RECOVERY: ReasoningOnlyStopRecovery = ReasoningOnlyStopRecovery {
        purpose: "summarize-continuation",
        exhausted_ctx: "summarization continuation exhausted — failing open with full history",
    };

    /// Recover a reasoning-only stop via the bounded continuation, or pass
    /// the response through unchanged.
    ///
    /// This is the single classification point for the reasoning-only stop
    /// (empty content, no parsed tool calls), reached by both LLM paths before
    /// any promotion, persistence or display. The provider-layer reasoning→text
    /// promotion is gone, so the response is the model's honest output.
    ///
    /// On continuation exhaustion the returned error carries
    /// `recovery.exhausted_ctx` — the caller's failure semantics: the agent
    /// loop fails the turn safely (nothing persisted, nothing displayed; the
    /// existing failure indicators — direct chat emoji / pipeline comment —
    /// fire), while the summarize path fails open, warning and continuing with
    /// the full history.
    ///
    /// Leak-safety invariants (shared by both paths): the continuation is
    /// appended-only and never touches the session transcript, so the thinking
    /// can never leak to the user — and the exhaustion error never embeds the
    /// thinking text either (see [`Self::recover_reasoning_only_stop`]).
    async fn recover_if_reasoning_only_stop(
        &self,
        messages: Vec<ChatMessage>,
        response: ChatResponse,
        recovery: ReasoningOnlyStopRecovery,
    ) -> anyhow::Result<ChatResponse> {
        if !is_reasoning_only_stop(&response) {
            return Ok(response);
        }
        self.recover_reasoning_only_stop(messages, response, recovery.purpose)
            .await
            .map_err(|e| anyhow::Error::new(e).context(recovery.exhausted_ctx))
    }

    /// Record the real provider-reported session length after a SUCCESSFUL
    /// agent-purpose LLM call: `input_tokens + output_tokens` of the full
    /// request envelope plus the response that just arrived.
    ///
    /// Only agent-purpose calls pass through here — extraction, summarize,
    /// consolidate, synthesis, and research sub-calls use other builders and
    /// are excluded (they are not session context).
    ///
    /// Post-compaction note: [`Session::apply_summary`] deliberately does NOT
    /// reset the value — the fixed scope says no logic changes beyond
    /// replacing estimated tokens with real tokens. After a compaction the
    /// stale pre-compaction length may re-fire `maybe_summarize` on a
    /// following turn if no successful agent call lands in between; that
    /// edge is spec-compliant (accepted, not fixed).
    async fn record_session_usage(&mut self, response: &ChatResponse) {
        let Some(usage) = &response.usage else {
            return;
        };
        let (Some(input), Some(output)) = (usage.input_tokens, usage.output_tokens) else {
            return;
        };
        let token_length = input.saturating_add(output);

        self.session.set_token_length(Some(token_length));
        if let Err(e) = crate::session::store()
            .set_token_length(&self.agent_id, Some(token_length))
            .await
        {
            tracing::warn!(
                agent_id = %self.agent_id,
                error = %e,
                "Failed to persist session token length — in-memory value may drift from the store until the next successful call"
            );
        }
    }

    /// Persist tool results to the session store and push them into the
    /// in-memory history (via the session) for the next tool round.
    ///
    /// The assistant frame with its tool calls is already durably persisted at
    /// EMISSION time (before the calls executed), so this commit writes ONLY
    /// the tool-result rows. Suspended outcomes (drain-cut durable work) are
    /// SKIPPED — no row is written, the call stays dangling, and the universal
    /// resume-completion step settles it later. Returns early with no DB write
    /// when every outcome is suspended (nothing to settle this round).
    ///
    /// Takes `outcomes` by value because each one's `image_payloads` are MOVED
    /// into the injected image message (they carry base64 data URIs).
    async fn commit_tool_results(
        &mut self,
        tool_calls: &[ToolCall],
        outcomes: Vec<ToolExecutionOutcome>,
    ) -> anyhow::Result<()> {
        let tools = &self.tools;

        // Data-URIs already attached in the session (prior rounds) — the dedup
        // key for the read-tool's "already attached" reference. Computed lazily
        // (only once the first image payload is encountered) so rounds with no
        // image read skip the full-history scan entirely.
        let mut seen_data_uris: Option<std::collections::HashSet<String>> = None;

        // Synthetic User-role image messages are injected AFTER the whole
        // tool-result block (preserves OpenAI-compatible tool-stream contiguity:
        // assistant(tool_calls) → tool_result_* → user(IMAGE_*)). Injecting one
        // per image inline would interleave a user message between tool results.
        let mut fresh_image_payloads: Vec<ImagePayload> = Vec::new();

        let mut db_messages = Vec::with_capacity(outcomes.len());
        for (call, outcome) in tool_calls.iter().zip(outcomes) {
            // A suspended outcome has no result to commit — the frame is already
            // durable and the durable work is left launched for the universal
            // resume-completion step. Skip it entirely.
            if outcome.suspended {
                continue;
            }
            let (output, fresh_payloads) = tool_result_content(
                tools,
                &call.name,
                outcome,
                &mut seen_data_uris,
                self.session.history(),
            )
            .await;
            fresh_image_payloads.extend(fresh_payloads);

            db_messages.push(ChatMessage::tool_result(&call.id, &output));
        }

        // Inject every fresh image of the round as ONE synthetic user message
        // after the round's tool-result block, tagged so the model can tell a
        // tool-injected image apart from a user-uploaded one.
        if let Some(message) =
            injected_images_message(&self.agent_id, self.role, fresh_image_payloads)
        {
            db_messages.push(message);
        }

        // Nothing to commit (all outcomes suspended — no results, no derived
        // images): the frame is already durable, so no DB write is needed.
        if db_messages.is_empty() {
            return Ok(());
        }

        // Batch-persist the tool results (preceded by any unpersisted history
        // tail) and push them into in-memory history.
        self.session
            .persist_messages(&self.agent_id, &db_messages)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to persist tool results: {e}"))?;

        Ok(())
    }

    /// Drain any incoming messages from the router (e.g., ticket comments)
    /// and inject them into the session history.
    ///
    /// Called at the start of each tool round, before the LLM call.
    /// Messages are persisted to the session DB AND pushed to in-memory
    /// history so they survive crashes and are visible to the model.
    ///
    /// On persist failure the messages are still delivered to the in-memory
    /// history (the model sees them this turn) and left in the unpersisted
    /// tail; the next successful persist — tool round, later drain, or
    /// finalize (which flushes the tail even on aborted turns) — writes
    /// them, so nothing is lost once the turn is finalized. A cancel before
    /// finalize drops the in-memory tail at the next turn — comments remain
    /// in the board DB.
    ///
    /// This is a no-op when no receiver is configured (e.g., chat agents
    /// that use the consumer_loop instead).
    async fn drain_incoming_messages(&mut self) {
        let Some(rx) = &mut self.incoming_rx else {
            return;
        };

        let mut messages = Vec::new();
        loop {
            match rx.try_recv() {
                Ok(job) => {
                    let content = match job.kind {
                        crate::agent::message_router::MessageKind::TicketComment => {
                            format_comment_message(&job.user_name, &job.content)
                        }
                        _ => job.content,
                    };
                    messages.push(crate::session::user_msg_with_ts(&content, None));
                }
                Err(tokio::sync::mpsc::error::TryRecvError::Empty) => break,
                Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {
                    // Channel closed — no more messages will arrive.
                    // Drop the receiver so we don't try again.
                    self.incoming_rx = None;
                    break;
                }
            }
        }

        if messages.is_empty() {
            return;
        }

        // Persist to session DB — fail-open. The comment is already saved in
        // the board DB, so losing the session copy is recoverable; log and
        // continue rather than aborting the tool round.
        self.persist_messages_fail_open(&messages).await;
    }

    /// Persist messages to the session, fail-open: on a persist failure the
    /// messages are still delivered to in-memory history (visible to the model
    /// this turn) and left in the unpersisted tail, flushed by the next persist.
    async fn persist_messages_fail_open(&mut self, messages: &[ChatMessage]) {
        if let Err(e) = self
            .session
            .persist_messages(&self.agent_id, messages)
            .await
        {
            tracing::warn!(
                agent_id = %self.agent_id,
                error = %e,
                "Failed to persist messages to session DB — continuing without persistence",
            );
            self.session.push_messages_unpersisted(messages);
        }
    }

    /// Inject board comments a resumed stage round has not seen.
    ///
    /// A resumed round starts with an empty message when the session already has
    /// content, so it never re-renders the `<current-ticket>` block and would
    /// otherwise miss comments added after the boot snapshot. Re-reads the board
    /// and injects comments absent from the loaded history (content-based dedup,
    /// whether a previously-delivered `[Comment from ...]` message or the
    /// session-start ticket block). Gated to `resume` + empty `msg`: the
    /// bounce-feedback path runs with `resume=false` (non-empty `msg`), so the
    /// `!resume` check excludes it. Runs once per turn, fail-open persist like
    /// live delivery.
    async fn inject_outstanding_comments(&mut self, resume: bool, msg: &str) {
        if !resume || !msg.is_empty() {
            return;
        }

        let Some(ticket_id) = self.ticket.as_ref().map(|t| t.id.clone()) else {
            return;
        };

        // Fresh snapshot — the boot get_ticket is stale. Snapshot the board
        // FIRST, then drain the channel: a comment routed after registration is
        // already in the channel and deduped against the post-drain history. A
        // comment routed after the drain can still be delivered twice; that is
        // the accepted no-watermark limitation (content-based dedup only).
        let comments = match crate::pipeline::board::store()
            .get_comments(&ticket_id)
            .await
        {
            Ok(comments) => comments,
            Err(e) => {
                tracing::warn!(
                    agent_id = %self.agent_id,
                    ticket = %ticket_id,
                    error = %e,
                    "Failed to read board comments for resume catch-up — skipping this round",
                );
                return;
            }
        };
        if comments.is_empty() {
            return;
        }

        self.drain_incoming_messages().await;

        let new_messages: Vec<_> = {
            let history = self.session.history();
            comments
                .iter()
                .filter(|c| {
                    !c.content.trim().is_empty()
                        && !history.iter().any(|m| m.content.contains(&c.content))
                })
                .map(|c| {
                    crate::session::user_msg_with_ts(
                        &format_comment_message(&c.role, &c.content),
                        None,
                    )
                })
                .collect()
        };
        if new_messages.is_empty() {
            return;
        }

        self.persist_messages_fail_open(&new_messages).await;
        tracing::info!(
            agent_id = %self.agent_id,
            role = %self.role,
            ticket = %ticket_id,
            count = new_messages.len(),
            "Injected outstanding board comments into resumed stage-agent session",
        );
    }

    /// Build a [`ChatRequest`] from the given messages, using the agent's
    /// current model, tools, reasoning-effort, and provider-routing settings.
    ///
    /// All parameter sources are lazily resolved each call so that runtime
    /// hot-reload (model, routing) is reflected immediately. Reasoning effort
    /// is baked into the role metadata — it is not
    /// hot-reloadable.
    ///
    /// # KV-cache preservation
    ///
    /// Every call site that produces a chat request for the same logical
    /// conversation *must* use exactly the same parameter sources — model,
    /// reasoning_effort, tools (critically tools!), and provider routing — so
    /// that the provider can reuse the cached prefix computed
    /// during the original agent call.  Any deviation (including dropping
    /// tools) forces the provider to recompute the entire KV-cache prefix.
    ///
    /// [`Self::extract_verdict`] calls this method internally to derive its
    /// parameter set.  [`Self::summarize`] calls this method directly.
    fn build_chat_request(&self, messages: Vec<ChatMessage>, purpose: &'static str) -> ChatRequest {
        ChatRequest {
            meta: Some(crate::ChatRequestMeta {
                purpose,
                agent_id: self.agent_id.clone(),
                role: self.role.as_str().to_string(),
                workspace: self.workspace.name.clone(),
                ticket_id: self.ticket.as_ref().map(|t| t.id.clone()),
            }),
            ..chat_request(self.role, Some(self.tool_specs.clone()), messages)
        }
    }

    // ── Extraction / summarisation ──

    /// Extract a structured verdict with the hardened scoped retry loop.
    ///
    /// KV-cache requirements: the params come from [`Self::build_chat_request`]
    /// (model, reasoning_effort, tools, provider routing) so all
    /// attempts are byte-identical except the parse-failure re-prompt.
    ///
    /// `validate` runs fail-closed on the parsed value (e.g. score ∈ [0,10]):
    /// a rejected value is treated as a parse failure and re-prompted.
    /// Pass `validate = None` for plain structured extraction (diagnostics
    /// discovery). `policy_override` supplies a shorter retry schedule for
    /// fail-open callers; `None` uses the default verdict budget.
    pub(crate) async fn extract_verdict<T: serde::de::DeserializeOwned>(
        &self,
        extraction_prompt: &str,
        validate: Option<&crate::ExtractionValidator<T>>,
        policy_override: Option<&crate::retry::RetryPolicy>,
    ) -> Result<T, crate::retry::RetryExhausted> {
        let _activity = self.activity_guard("extracting");
        let params = self.build_chat_request(vec![], "extraction");
        crate::agent::extraction::retry_extract_structured_scoped(
            self.session.history(),
            extraction_prompt,
            &params,
            validate,
            policy_override,
        )
        .await
    }

    /// Summarise the agent's session history.
    ///
    /// KV-cache requirements: see [`Self::build_chat_request`]. The request is
    /// built once and re-sent verbatim, so every attempt is byte-identical —
    /// same messages, same tool set, same parameters.
    ///
    /// A tool call is not a summary: it carries no summary text, so it is
    /// re-asked (`SUMMARIZE_ATTEMPTS` in total, each attempt a successful
    /// `summarize` request of its own) and never executed. An answer carrying
    /// both text and a tool call needs no re-ask — the text is the summary and
    /// the tool call is discarded as always. Exhaustion raises the
    /// empty-response error as before, so [`Self::maybe_summarize`] fails open
    /// with the full history.
    pub(crate) async fn summarize(&self) -> anyhow::Result<String> {
        let _activity = self.activity_guard("summarizing");
        let mut history = self.session.history().to_vec();
        history.push(crate::ChatMessage::user(self.role.summary_prompt()));

        let request = self.build_chat_request(history.clone(), "summarize");
        let policy = crate::retry::RetryPolicy::current();

        for _ in 1..=SUMMARIZE_ATTEMPTS {
            let chat_resp = crate::retry::agent_chat(request.clone(), &policy)
                .await
                .with_context(|| format!("summarization LLM call {RETRY_EXHAUSTION_MARKER}"))?;

            // Reasoning-only stop: the same bounded continuation as the agent
            // loop (leak-safety invariants on `recover_if_reasoning_only_stop`).
            // On exhaustion, fail open below — the empty-response error path
            // warns and continues with the full history.
            let chat_resp = self
                .recover_if_reasoning_only_stop(
                    history.clone(),
                    chat_resp,
                    Self::SUMMARIZE_REASONING_RECOVERY,
                )
                .await?;

            if let Some(ref u) = chat_resp.usage {
                tracing::debug!(
                    input_tokens = u.input_tokens,
                    cached_input_tokens = u.cached_input_tokens,
                    output_tokens = u.output_tokens,
                    "Summarization token usage",
                );
            }

            if let Some(summary_text) = chat_resp.text.filter(|t| !t.trim().is_empty()) {
                return Ok(crate::util::truncate(&summary_text, 32_000));
            }
            // No summary text — a tool-call answer. Re-ask (or leave the loop
            // with the error when the budget is spent).
        }

        anyhow::bail!("summarization produced empty response")
    }

    /// Check the session against the summarization triggers and summarise if
    /// necessary: the provider-reported session token length exceeding
    /// [`SUMMARIZATION_THRESHOLD`], or the history accumulating
    /// [`SUMMARIZATION_IMAGE_COUNT`] distinct data-URI images (see
    /// [`session_image_marker_count`]). The token length is the REAL
    /// provider-reported value (input + output tokens of the last successful
    /// agent LLM call), loaded at session init; `None` — no successful
    /// usage-bearing call ever recorded a value (new sessions, pre-migration
    /// sessions; approved no-backfill) — only disables the token trigger. A
    /// FAILED call never updates the value (the session did not change).
    ///
    /// KV-cache preservation: [`Agent::summarize`] keeps all parameters
    /// identical (see [`Agent::build_chat_request`]) so the cached prefix is
    /// reusable.
    async fn maybe_summarize(&mut self) {
        let token_length = self.session.token_length();
        let image_count = session_image_marker_count(self.session.history());
        tracing::debug!(
            agent_id = %self.agent_id,
            role = %self.role,
            token_length,
            image_count,
            "Session token length / image count",
        );
        let Some(trigger) = summarization_trigger(token_length, image_count) else {
            return;
        };
        tracing::info!(
            agent_id = %self.agent_id,
            role = %self.role,
            trigger,
            token_length,
            image_count,
            "Session exceeded summarization trigger ({trigger})",
        );
        match self.summarize().await {
            Ok(summary) => {
                self.session
                    .apply_summary(
                        &self.agent_id,
                        &summary,
                        &self.workspace,
                        &self.role,
                        self.ticket.as_ref(),
                        self.is_admin,
                        &self.user_name,
                    )
                    .await;
            }
            Err(e) => {
                tracing::warn!(
                    error_chain = %crate::util::failure_detail(&format!("{e:#}"), "summarization failure"),
                    "Summarization failed — continuing with full history"
                );
            }
        }
    }
}

/// Decide whether [`Agent::maybe_summarize`] should compact, and why.
/// Strict `>` for the token threshold, `>=` for the image count — the
/// asymmetry is deliberate (see [`crate::session::SUMMARIZATION_IMAGE_COUNT`]).
/// Returns `None` when no trigger fires.
#[must_use]
fn summarization_trigger(token_length: Option<u64>, image_count: usize) -> Option<&'static str> {
    if token_length.is_some_and(|t| t > crate::session::SUMMARIZATION_THRESHOLD) {
        Some("token threshold")
    } else if image_count >= crate::session::SUMMARIZATION_IMAGE_COUNT {
        Some("image count")
    } else {
        None
    }
}

/// Parameters for a reasoning-only-stop recovery: the telemetry purpose tag
/// forwarded to [`Agent::recover_reasoning_only_stop`] and the context
/// attached to the exhaustion error. The two strings travel as a single
/// named-field struct (rather than two adjacent `&'static str` arguments) so
/// they cannot be silently swapped at a call site — see the per-path
/// constants on [`Agent`].
struct ReasoningOnlyStopRecovery {
    /// Purpose tag for the continuation LLM request (telemetry).
    purpose: &'static str,
    /// Context attached to the `anyhow` error when continuation attempts are
    /// exhausted.
    exhausted_ctx: &'static str,
}

/// Result of preparing an assistant turn from the LLM response.
struct PreparedAssistantTurn {
    display_text: String,
    tool_calls: Vec<ToolCall>,
    history_content: String,
    /// The raw LLM response text (the faithful carrier of accompanying text in
    /// tool rounds, where `history_content` is a JSON payload and
    /// `display_text` is empty). Reasoning content never reaches
    /// `prepare_assistant_turn`, so this excludes it by construction.
    raw_text: String,
}

/// Classify the "reasoning-only stop" class: raw empty content (think tags
/// stripped — they are reasoning, not content) with no parsed tool calls,
/// REGARDLESS of finish reason. The provider-layer reasoning→text promotion
/// is gone, so an empty `text` is the model's honest empty content.
///
/// Tool-call turns (empty text by design) are excluded by the tool-call
/// check. Degenerate members — fully-empty responses (no reasoning attached)
/// and think-tag-only content — are consciously in-class: the continuation
/// then carries just the nudge, and a previously-`Ok("")` silent answer now
/// resolves via the continuation or fails the turn safely (never CoT-as-text).
#[must_use]
fn is_reasoning_only_stop(response: &ChatResponse) -> bool {
    response.tool_calls.is_empty() && response.text.as_deref().is_none_or(|t| t.trim().is_empty())
}

/// Persist one continuation-attempt failure row when the operation is
/// metadata-tracked (fail-open; see
/// [`crate::stats::record_llm_attempt_failure`]). The per-attempt duration is
/// measured from `attempt_started` (the attempt's launch instant).
async fn record_continuation_failure(
    operation: Option<&crate::stats::LlmOperationCtx>,
    attempt: u32,
    rec: &crate::retry::RetryFailureRecord,
    attempt_started: Instant,
) {
    if let Some(op) = operation {
        crate::stats::record_llm_attempt_failure(op, attempt, rec, Some(attempt_started)).await;
    }
}

/// Context for a failed LLM step: the run-local tool-round counter plus the
/// session depth — a resumed long-lived session must not read as freshly
/// started ("tool round 0"). The token segment is omitted when unknown.
fn llm_step_failure_context(session: &Session, tool_rounds: usize) -> String {
    let tokens = session
        .token_length()
        .map_or_else(String::new, |t| format!(", {t} tokens"));
    format!(
        "LLM step failed at tool round {tool_rounds} (run-local counter; \
         session history: {} messages{tokens})",
        session.history().len(),
    )
}

/// Prepare assistant response data from the LLM response.
fn prepare_assistant_turn(response: ChatResponse) -> PreparedAssistantTurn {
    let response_text = response.text_or_empty().to_string();
    let raw_text = response_text.clone();
    let tool_calls = response.tool_calls;
    let reasoning = response.reasoning.as_ref();

    // The structured payload faithfully captures the model's original response
    // (empty content for a reasoning-only return). Reasoning-only stops never
    // reach this point — the agent loop classifies and recovers them in
    // llm_call before any persistence/display — so this builder only ever
    // serializes real answers and tool-call turns.
    let json_payload =
        assistant_replay_payload(Some(&response_text), &tool_calls, reasoning).to_string();

    // Dispatch on whether tool calls and/or reasoning are present.
    // Three arms: plain answer (no tools, no reasoning), reasoning+text
    // (reasoning present alongside visible text), and tool calls (tools
    // present). Reasoning-only responses (reasoning present, empty text) are
    // the recovered class and never arrive here.
    let (display_text, history_content) = match (tool_calls.is_empty(), reasoning.is_some()) {
        // Plain final answer — both display and history use response text directly.
        (true, false) => (response_text.clone(), response_text),
        // Reasoning alongside visible text — show the text to the user,
        // persist structured JSON payload with content + reasoning fields.
        (true, true) => (response_text, json_payload),
        // Tool calls — nothing to display, persist structured JSON payload.
        (false, _) => (String::new(), json_payload),
    };

    PreparedAssistantTurn {
        display_text,
        tool_calls,
        history_content,
        raw_text,
    }
}

/// Rejection message for a `sleep` call made in a round with accompanying
/// raw text: the text is never delivered (tool rounds are never displayed)
/// and the successful sleep would end the run before anything is sent.
const SLEEP_WITH_TEXT_REJECTION: &str = "sleep must be called alone: your text was NOT delivered — text written in any round that contains a tool call never reaches the user. If that text was meant for the user, resend it as a plain-text round with no tool calls and no sleep call: that round ends your turn and delivers it. If it was not meant for the user, call sleep alone, with no text and no other tool call.";

/// Rejection message for a `sleep` call bundled with other tool calls.
const SLEEP_BUNDLED_REJECTION: &str = "sleep must be called alone: it was bundled with other tool calls. Call sleep in its own round with no other tool calls — and no text, since text written in a tool round is never delivered to the user.";

/// Sleep-delivery guard predicate: a `sleep` call must run alone in a
/// text-free round, otherwise the round either swallows the accompanying
/// text or ends the run silently right after it. Returns the model-facing
/// rejection reason for the round, `None` when the round is legal.
#[must_use]
fn sleep_rejection_reason(has_text: bool, bundled: bool) -> Option<&'static str> {
    if has_text {
        Some(SLEEP_WITH_TEXT_REJECTION)
    } else if bundled {
        Some(SLEEP_BUNDLED_REJECTION)
    } else {
        None
    }
}

/// Round-scoped agent options for parallel-round members.
///
/// `round_ts` pins the first user message's timestamp (one value per round —
/// byte-identical task messages across members); `first_call_notify` is the
/// leader-stagger signal — fired after the leader's first LLM call completes
/// (success or failure, after the full retry budget: a leader whose call
/// exceeds the stagger bound releases followers via the sleep arm and misses
/// the cached prefix) or when the leader bails at the phase gate before any
/// LLM call.
#[derive(Clone)]
pub(crate) struct RoundOpts {
    pub(crate) round_ts: String,
    pub(crate) first_call_notify: Option<std::sync::Arc<tokio::sync::Notify>>,
}

/// Default fail-open bound on the leader-stagger wait: how long followers wait
/// for the leader's first LLM call before starting anyway. First calls take
/// ~4-6 s; the bound is a safety cap, not the expected wait. Overridable via
/// env for tuning (mirrors [`crate::tools::analyze::round_timeout`]).
const DEFAULT_STAGGER_WAIT_SECS: u64 = 8;

fn leader_stagger_wait() -> std::time::Duration {
    crate::util::env_duration_secs("MAHBOT_STAGGER_WAIT_SECS", DEFAULT_STAGGER_WAIT_SECS)
}

/// Spawn a round's member tasks with a leader-stagger: member 0 (the leader)
/// starts immediately; the rest start after the leader's first LLM call
/// completes (the notify fires) or the bounded wait elapses — whichever
/// first. The wait is fail-open (a failed/never-starting leader still releases
/// the followers) and interrupted by daemon shutdown or the drain flag.
///
/// Single-member rounds are a no-op stagger, and boot-resumed rounds
/// (`resume = true`) skip the stagger entirely — their sessions already
/// diverged, so the leader's prefix would not be shared anyway and the wait
/// would only add latency.
///
/// Renders the round timestamp once and hands every member factory a
/// ready-made [`RoundOpts`] (only the leader carries the first-call signal).
///
/// The first-call signal has a single waiter — the `select!` below — so
/// `notify_one()` releases all followers at once; its stored permit also
/// covers a fire-before-wait race that `notify_waiters()` would lose.
pub(crate) async fn spawn_staggered_round<T, Fut, F>(
    members: Vec<F>,
    resume: bool,
) -> Vec<tokio::task::JoinHandle<T>>
where
    T: Send + 'static,
    Fut: std::future::Future<Output = T> + Send + 'static,
    F: FnOnce(RoundOpts) -> Fut + Send + 'static,
{
    let mut members = members.into_iter();
    let Some(leader) = members.next() else {
        return Vec::new();
    };
    let followers: Vec<F> = members.collect();
    let round_ts = crate::session::render_timestamp();
    if resume || followers.is_empty() {
        // Resume (sessions already diverged — no shared prefix to hit) or a
        // single-member round: no stagger, spawn everything immediately.
        let opts = RoundOpts {
            round_ts,
            first_call_notify: None,
        };
        let mut handles = Vec::with_capacity(followers.len() + 1);
        handles.push(tokio::spawn(leader(opts.clone())));
        handles.extend(followers.into_iter().map(|m| tokio::spawn(m(opts.clone()))));
        return handles;
    }
    let notify = std::sync::Arc::new(tokio::sync::Notify::new());
    let mut handles = vec![tokio::spawn(leader(RoundOpts {
        round_ts: round_ts.clone(),
        first_call_notify: Some(notify.clone()),
    }))];
    let follower_opts = RoundOpts {
        round_ts,
        first_call_notify: None,
    };
    let shutdown = crate::shutdown::shutdown_token();
    tokio::select! {
        () = notify.notified() => {}
        () = tokio::time::sleep(leader_stagger_wait()) => {}
        () = shutdown.cancelled() => {}
        () = crate::shutdown::drain_wait() => {}
    }
    // Drain/shutdown arms still spawn the followers — their Session::init
    // append runs before the aborting() bail. Deliberate: it pre-seeds the
    // session so boot resume's has_session guard skips the re-append
    // (consistent with the leader's init-then-abort drain path).
    handles.extend(
        followers
            .into_iter()
            .map(|m| tokio::spawn(m(follower_opts.clone()))),
    );
    handles
}

/// Everything an agent run releases for its own temporary use when the run ends:
/// its spill files, its per-agent computer registry entries (there are none on
/// macOS, where computer use is withdrawn), and the chrome sessions it opened.
/// Released from a `Drop` rather than from trailing statements
/// because a run cut off mid-flight never reaches a trailing statement, and
/// everything it used would then be stranded with nothing left that records it. The
/// chrome part is only handed over (the `chrome-run-releases` task does the work,
/// outliving the run).
///
/// The one limit this rule owns: a run still working when the process exits, and
/// a run killed outright (SIGKILL), never run destructors — the self-update path's
/// `exit(0)` bypasses them by design — so nothing is ever queued for that run's
/// chrome sessions and the tabs it opened stay open; nothing else records them,
/// because the shutdown sweep deliberately leaves `agent-tab-*` alone.
struct RunEndCleanup {
    agent_id: String,
    chrome: std::sync::Arc<crate::tools::chrome::ChromeRunSessions>,
    /// Whether [`RunEndCleanup::ended`] held the release back for a resumed segment.
    held: bool,
}

impl RunEndCleanup {
    fn new(
        agent_id: String,
        chrome: std::sync::Arc<crate::tools::chrome::ChromeRunSessions>,
    ) -> Self {
        Self {
            agent_id,
            chrome,
            held: false,
        }
    }

    /// Record how the run ended — which ends hold the release back is
    /// [`holds_run_end`]'s rule.
    ///
    /// [`holds_run_end`]: crate::tools::chrome_release::holds_run_end
    fn ended(&mut self, classification: &str) {
        self.held = crate::tools::chrome_release::holds_run_end(classification);
    }
}

impl Drop for RunEndCleanup {
    fn drop(&mut self) {
        // Owner-deletes-at-end: remove the spill files this agent run created
        // (safe on macOS — the run is over, nothing will read them again).
        crate::tools::shell::cleanup_agent_spills(&self.agent_id);
        // Drop the per-agent computer registry entries (observation/target/
        // capture) so they never leak into a later run. Not on macOS, where the
        // computer tool does not exist, so there is no such state.
        #[cfg(not(target_os = "macos"))]
        crate::tools::computer::cleanup_agent_state(&self.agent_id);
        // Hand the run's chrome sessions to the release queue. The tracker's own
        // `Drop` unregisters the run's namespace once the run's last owner goes.
        crate::tools::chrome_release::queue_run_session_release(&self.chrome, self.held);
    }
}

/// Core agent lifecycle: create agent (auto-registers with its own
/// CancellationToken), run work, handle cancellation and errors.
/// Returns the agent (even on failure) and the response on success.
///
/// `user_name` and `channel` identify the origin of the message being
/// processed — used by tools (e.g. AnalyzeTool async dispatch) to route
/// sub-agent results to the correct user.
///
/// **Cancellation safety**: A completed `Ok` result is never discarded based
/// on cancel cause — downstream consumers (pipeline finalizers, the message
/// router) are the authority on how a cancelled run's result is handled.
///
/// Returns `(agent, Some(response))` on success.
/// Returns `(agent, None)` on error (already logged).
#[expect(clippy::too_many_arguments)]
pub(crate) async fn run_agent(
    agent_id: String,
    role: crate::Role,
    ws: &crate::Workspace,
    ticket: Option<&crate::pipeline::board::Ticket>,
    message: &str,
    user_name: String,
    channel: String,
    is_admin: bool,
    incoming_rx: Option<
        tokio::sync::mpsc::UnboundedReceiver<crate::agent::message_router::AgentJob>,
    >,
    resume: bool,
    round: Option<RoundOpts>,
    parent_key: Option<crate::agent::registry::ParentKey>,
    parent_label: Option<String>,
) -> (Agent, Option<String>) {
    // Unregister from the message router on EVERY exit path, including a
    // panic mid-work (Drop runs during unwind) — a leaked router entry would
    // keep routing comments to a dead agent. Only for caller-registered paths
    // (Some(incoming_rx)): the persistent consumer_loop path (None) owns its
    // router entry via route()'s catch_unwind cleanup and must keep it across
    // jobs. Idempotent.
    struct UnregisterOnDrop(String);
    impl Drop for UnregisterOnDrop {
        fn drop(&mut self) {
            crate::agent::message_router::unregister_agent(&self.0);
        }
    }
    let _router_guard = incoming_rx
        .is_some()
        .then(|| UnregisterOnDrop(agent_id.clone()));
    let mut agent = Agent::new(
        agent_id,
        role,
        ws,
        ticket.cloned(),
        user_name,
        channel,
        is_admin,
        parent_key,
        parent_label,
    );
    agent.incoming_rx = incoming_rx;
    if let Some(round) = round {
        agent.round_ts = Some(round.round_ts);
        agent.first_call_notify = round.first_call_notify;
    }
    // Everything this run owns for its own temporary use is released by this
    // guard — including on the paths that never reach a trailing statement.
    let mut run_end = RunEndCleanup::new(
        agent.agent_id.clone(),
        std::sync::Arc::clone(&agent.chrome_sessions),
    );
    let result = agent.work(message, resume).await;

    // A completed Ok result is kept regardless of cancel cause — the token may
    // have fired just as work() finished; downstream finalizers are the
    // authority on how a cancelled run's result is used.
    match result {
        Ok(response) => (agent, Some(response)),
        Err(e) => {
            // Capture the real cause (full chain) so ticket dispatchers can
            // persist it in failure comments instead of a generic placeholder.
            agent.failure = Some(format!("{e:#}"));
            agent.failure_class = failure_class_from_error(&e);
            let classification = failure_classification(&agent, Some(&e));
            // The chrome release's hold (`holds_run_end`'s rule).
            run_end.ended(classification);
            let error_chain = crate::util::failure_detail(&format!("{e:#}"), "agent failure log");
            // During global (SIGTERM/SIGINT) shutdown, in-flight agents return
            // errors from work() — expected, not real failures. The drain check
            // runs first, so a run force-cancelled once the drain cap is hit
            // also classifies as "drain"; both are non-failures. Log at debug
            // level to avoid misleading ERROR noise on clean shutdown. The
            // cooperative ends (drain, shutdown, pause) and a deliberate
            // cancellation (internal_cancel — user/GUI cancel or a re-dispatch)
            // get the same treatment; this log's own classification decides that.
            let non_failure = matches!(
                classification,
                "drain" | "shutdown" | "pause" | "internal_cancel"
            );
            if non_failure {
                tracing::debug!(
                    agent_id = %agent.agent_id,
                    workspace = %ws.name,
                    role = %role,
                    ticket = ticket.map(|t| t.id.as_str()),
                    classification,
                    error_chain,
                    "Agent stopped by a non-failure cancellation"
                );
            } else {
                tracing::error!(
                    agent_id = %agent.agent_id,
                    workspace = %ws.name,
                    role = %role,
                    ticket = ticket.map(|t| t.id.as_str()),
                    classification,
                    error_chain,
                    "Agent failed"
                );
            }
            (agent, None)
        }
    }
}

/// Default dispatch: no ticket, empty user/channel, no inbox.
///
/// `resume` selects the slot-resume primitive (empty committed-tail
/// continuation, summarization skipped); default `false` for fresh dispatches.
///
/// `parent_key` carries the DIRECT PARENT INVOCATION grouping key for the
/// Running Agents view (ticket / analyze round / research run); `None` for
/// workspace singletons (manager / maintainer / discovery / direct chat).
/// `parent_label` is the human-readable label of that parent invocation
/// (analyze question / research question) — purely presentational.
#[expect(clippy::too_many_arguments)]
pub(crate) async fn run_default_agent(
    agent_id: &str,
    role: crate::Role,
    ws: &crate::Workspace,
    message: &str,
    resume: bool,
    round: Option<RoundOpts>,
    parent_key: Option<crate::agent::registry::ParentKey>,
    parent_label: Option<String>,
) -> (Agent, Option<String>) {
    run_agent(
        agent_id.to_string(),
        role,
        ws,
        None,
        message,
        String::new(),
        String::new(),
        false,
        None,
        resume,
        round,
        parent_key,
        parent_label,
    )
    .await
}

/// Extract the typed provider failure class from an error chain, when the
/// chain carries a [`RetryExhausted`] (the terminal retry-loop error that
/// preserves the granular [`crate::retry::FailureClass`]).
///
/// `None` means the error is not provider-classified (runtime errors, panics,
/// plain I/O failures) — callers treat that as a genuine non-provider failure.
pub(crate) fn failure_class_from_error(
    error: &anyhow::Error,
) -> Option<crate::retry::FailureClass> {
    error
        .chain()
        .find_map(|cause| cause.downcast_ref::<crate::retry::RetryExhausted>())
        .map(|exhausted| exhausted.final_class)
}

/// Stable failure classification for the agent-failure log.
///
/// Order matters: the global shutdown token fires on any stop request — SIGTERM/SIGINT, the
/// dashboard's window close or a macOS quit, a Windows console or session-end request, a
/// self-update — and when a graceful drain completes; the per-agent token on a deliberate stop —
/// check the global token first so shutdown isn't mislabeled as an internal cancel. The global
/// token also cancels every per-agent token via
/// [`crate::agent::registry::AgentRegistry::shutdown_all`]. `error` is the raw
/// error source when one is present at the call site (the `run_agent` `Err`
/// arm); `None` only in tests, where the classifier falls through to the token
/// checks. [`RetryExhausted`] (kept as an error source by
/// [`llm_call`]/[`summarize`]) carries the granular
/// [`crate::retry::FailureClass`]; everything else (I/O, tool errors, panics)
/// falls back to `runtime`.
fn failure_classification(agent: &Agent, error: Option<&anyhow::Error>) -> &'static str {
    if crate::shutdown::is_draining() {
        // The graceful drain cut the round short — not a failure. Checked
        // before the token so drained agents are never mislabeled as
        // cancelled/shutdown (no AGENT_FAILURE_EMOJI, no exit rollback).
        "drain"
    } else if crate::shutdown::shutdown_token().is_cancelled() {
        "shutdown"
    } else if agent.is_paused_frozen() {
        // A strictly-frozen (paused-workspace) run — not a failure. The
        // immutable bail-time snapshot (not the live pause_stop, which an
        // unpause can clear) is authoritative.
        "pause"
    } else if agent.is_cancelled() {
        "internal_cancel"
    } else if let Some(class) = error.and_then(failure_class_from_error) {
        class.label()
    } else {
        "runtime"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Tool;
    use crate::tools::chrome_release;
    use crate::util::test::{FakeProvider, install_fake_provider, install_test_retry_policy};
    use async_trait::async_trait;
    use tokio_util::sync::CancellationToken;

    struct TestTool {
        output: String,
        scrub: bool,
    }

    #[async_trait]
    impl Tool for TestTool {
        fn name(&self) -> &'static str {
            if self.scrub {
                "always_scrub"
            } else {
                "never_scrub"
            }
        }

        fn description(&self) -> String {
            "test".into()
        }

        fn parameters_schema(&self) -> serde_json::Value {
            serde_json::json!({})
        }

        async fn execute(
            &self,
            _ws: &crate::Workspace,
            _args: serde_json::Value,
        ) -> anyhow::Result<String> {
            Ok(self.output.clone())
        }

        fn should_scrub_output(&self, _args: &serde_json::Value) -> bool {
            self.scrub
        }
    }

    /// Secret-like line that `scrub_credentials` always redacts.
    const SCRUBBABLE_LINE: &str = "API_KEY=sk-1234567890abcdef";

    fn make_agent(tools: Vec<Box<dyn Tool>>) -> Agent {
        make_agent_with_role(tools, crate::Role::Engineer)
    }

    fn make_agent_with_role(tools: Vec<Box<dyn Tool>>, role: crate::Role) -> Agent {
        let tool_specs = tools.iter().map(|t| t.spec()).collect();
        Agent {
            agent_id: "test-agent".into(),
            role,
            session: Session::default(),
            workspace: std::sync::Arc::new(crate::Workspace::default()),
            tools,
            tool_specs,
            cancel_token: CancellationToken::new(),
            pause_stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            paused_frozen: std::sync::atomic::AtomicBool::new(false),
            ticket: None,
            generation: 0,
            tool_stats: std::sync::Mutex::new(Vec::new()),
            user_name: String::new(),
            channel: String::new(),
            is_admin: false,
            parent_key: None,
            parent_label: None,
            incoming_rx: None,
            round_ts: None,
            first_call_notify: None,
            failure: None,
            failure_class: None,
            sleep_ended: false,
            background_sessions: std::sync::Arc::new(
                crate::tools::shell::BackgroundSessions::default(),
            ),
            chrome_sessions: std::sync::Arc::new(crate::tools::chrome::ChromeRunSessions::default()),
        }
    }

    /// Construct an agent with an explicit workspace and id (for tools that
    /// resolve paths against a real directory, e.g. the read tool).
    fn make_agent_on(tools: Vec<Box<dyn Tool>>, agent_id: &str, ws: crate::Workspace) -> Agent {
        let mut agent = make_agent_with_role(tools, crate::Role::Engineer);
        agent.agent_id = agent_id.to_string();
        agent.workspace = std::sync::Arc::new(ws);
        agent
    }

    #[tokio::test]
    async fn tool_with_scrub_disabled_preserves_output() {
        assert_scrubbed(false).await;
    }

    #[test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    fn failure_classification_recovers_retry_exhaustion() {
        // failure_classification consults the process-global drain flag before
        // everything else — serialize against the drain-flag writers.
        // Mirror llm_call's error construction: the RetryExhausted must
        // survive as a source (via .context, not string flattening) so the
        // granular FailureClass is recoverable from the chain.
        let exhausted = crate::retry::RetryExhausted::with_last_raw(
            vec![],
            crate::retry::FailureClass::NonRetryable,
            None,
        );
        let err = anyhow::Error::new(exhausted).context("LLM call exhausted retry budget");
        // The {:#} chain must keep the marker engineer_failure_comment matches.
        assert!(format!("{err:#}").contains("exhausted retry budget"));

        let agent = make_agent(vec![]);
        assert_eq!(
            failure_classification(&agent, Some(&err)),
            "non_retryable",
            "RetryExhausted final_class must be recovered from the chain",
        );

        // Non-retry-loop errors (I/O, tool, panic) fall back to runtime.
        let runtime_err = anyhow::anyhow!("tool panicked");
        assert_eq!(
            failure_classification(&agent, Some(&runtime_err)),
            "runtime"
        );

        // A code-driven (internal) cancellation fires the generic token — it
        // must classify as an internal cancel (there is no separate user stop
        // anymore; all non-shutdown/non-pause cancellations are internal).
        let internally_cancelled = make_agent(vec![]);
        internally_cancelled.cancel_token.cancel();
        assert_eq!(
            failure_classification(&internally_cancelled, Some(&runtime_err)),
            "internal_cancel"
        );
        assert_eq!(
            failure_classification(&internally_cancelled, None),
            "internal_cancel"
        );
    }

    /// The graceful-drain cut is classified as "drain" (NOT cancelled/
    /// shutdown/failure) — the consumer suppresses the failure emoji and the
    /// dispatch tails skip the exit-time ticket rollback for drained agents.
    /// Serialized against other tests: the drain flag is process-global, so a
    /// concurrent test consulting is_draining() could be misclassified during
    /// the assertion window.
    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn failure_classification_recognizes_drain() {
        let agent = make_agent(vec![]);
        // Drain flag unset: normal classification.
        assert_eq!(failure_classification(&agent, None), "runtime");
        // Set the drain flag for the duration of the assertion.
        crate::shutdown::drain_begin();
        assert_eq!(
            failure_classification(&agent, None),
            "drain",
            "a drained agent must classify as drain, never failure",
        );
        // A per-agent cancel during drain still classifies as drain — the
        // drain is checked first so no failure emoji fires on exit.
        agent.cancel_token.cancel();
        assert_eq!(failure_classification(&agent, None), "drain");
        // Restore isolation — the drain flag is process-global; the token
        // must never be fired from a test (it would cancel every parallel
        // retry loop).
        crate::shutdown::drain_clear();
    }

    /// Shared helper: create an agent with a TestTool, execute_tool it, and assert scrubbing behavior.
    async fn assert_scrubbed(should_scrub: bool) {
        let tool: Box<dyn Tool> = Box::new(TestTool {
            output: SCRUBBABLE_LINE.into(),
            scrub: should_scrub,
        });
        let name = tool.name();
        let agent = make_agent(vec![tool]);
        let out = agent.execute_tool(name, serde_json::json!({})).await;

        assert!(out.success, "{name} should succeed");
        if should_scrub {
            assert!(out.output.contains("[REDACTED]"), "{name} should redact");
            assert!(
                !out.output.contains("abcdef"),
                "{name} should not leak original"
            );
        } else {
            assert!(
                !out.output.contains("[REDACTED]"),
                "{name} should not redact"
            );
            assert!(
                out.output.contains(SCRUBBABLE_LINE),
                "{name} should preserve output"
            );
        }
    }

    #[tokio::test]
    async fn tool_with_scrub_enabled_scrubs_sensitive_output() {
        assert_scrubbed(true).await;
    }

    /// A media-generation test tool that returns a configurable [`Tool::media_marker`].
    ///
    /// Used to test [`extract_media_from_outcomes`] without real image/video generation.
    struct MediaTestTool {
        name: &'static str,
        marker: &'static str,
    }

    #[async_trait]
    impl Tool for MediaTestTool {
        fn name(&self) -> &'static str {
            self.name
        }

        fn description(&self) -> String {
            "media test tool".into()
        }

        fn parameters_schema(&self) -> serde_json::Value {
            serde_json::json!({})
        }

        async fn execute(
            &self,
            _ws: &crate::Workspace,
            _args: serde_json::Value,
        ) -> anyhow::Result<String> {
            Ok(String::new())
        }

        fn media_marker(&self) -> Option<&'static str> {
            Some(self.marker)
        }
    }

    // ── extract_media_from_outcomes tests ───────────────────────────────────

    #[test]
    #[expect(clippy::too_many_lines)]
    fn extract_media_outcomes_consolidated() {
        enum ToolDef {
            /// [`Media`] carries a marker prefix; [`NonMedia`] uses a unit variant because
            /// `extract_media_from_outcomes` only consults [`Tool::media_marker`], never
            /// [`Tool::execute`] — the output value on [`TestTool`] has no behavioral effect.
            Media {
                name: &'static str,
                marker: &'static str,
            },
            NonMedia,
        }

        struct OutcomeDef {
            output: &'static str,
            success: bool,
        }

        struct TestCase {
            name: &'static str,
            msg: &'static str,
            tools: Vec<ToolDef>,
            outcomes: Vec<OutcomeDef>,
            expected: Vec<(&'static str, &'static str)>,
        }

        let cases = vec![
            TestCase {
                name: "parses_valid_marker",
                msg: "valid marker with success=true should extract the path",
                tools: vec![ToolDef::Media {
                    name: "image_gen",
                    marker: "[IMAGE:",
                }],
                outcomes: vec![OutcomeDef {
                    output: "[IMAGE:/tmp/img.png]",
                    success: true,
                }],
                expected: vec![("[IMAGE:", "/tmp/img.png")],
            },
            // Marker prefix with nothing parseable after it (e.g. at end of output)
            // produces an empty path which the filter rejects.
            TestCase {
                name: "skips_malformed_marker",
                msg: "malformed marker should be skipped",
                tools: vec![ToolDef::Media {
                    name: "image_gen",
                    marker: "[IMAGE:",
                }],
                outcomes: vec![OutcomeDef {
                    output: "description text [IMAGE:",
                    success: true,
                }],
                expected: vec![],
            },
            TestCase {
                name: "skips_empty_marker",
                msg: "empty marker '[IMAGE:]' should be skipped",
                tools: vec![ToolDef::Media {
                    name: "image_gen",
                    marker: "[IMAGE:",
                }],
                outcomes: vec![OutcomeDef {
                    output: "[IMAGE:]",
                    success: true,
                }],
                expected: vec![],
            },
            TestCase {
                name: "skips_no_closing_bracket_non_empty_path",
                msg: "output with '[IMAGE:bogus' (no closing bracket, non-empty path) should be skipped",
                tools: vec![ToolDef::Media {
                    name: "image_gen",
                    marker: "[IMAGE:",
                }],
                outcomes: vec![OutcomeDef {
                    output: "oops [IMAGE:bogus",
                    success: true,
                }],
                expected: vec![],
            },
            TestCase {
                name: "skips_non_media_tool",
                msg: "non-media tool should not be inspected for media markers",
                tools: vec![ToolDef::NonMedia],
                outcomes: vec![OutcomeDef {
                    output: "[IMAGE:path]",
                    success: true,
                }],
                expected: vec![],
            },
            TestCase {
                name: "skips_failed_outcome",
                msg: "failed outcomes should not produce media paths",
                tools: vec![ToolDef::Media {
                    name: "image_gen",
                    marker: "[IMAGE:",
                }],
                outcomes: vec![OutcomeDef {
                    output: "[IMAGE:/tmp/img.png]",
                    success: false,
                }],
                expected: vec![],
            },
            TestCase {
                name: "handles_mixed_tools",
                msg: "mixed tools with valid outcomes should extract only media paths",
                tools: vec![
                    ToolDef::Media {
                        name: "image_gen",
                        marker: "[IMAGE:",
                    },
                    ToolDef::NonMedia,
                    ToolDef::Media {
                        name: "video_gen",
                        marker: "[VIDEO:",
                    },
                ],
                outcomes: vec![
                    OutcomeDef {
                        output: "[IMAGE:/tmp/img.png]",
                        success: true,
                    },
                    OutcomeDef {
                        output: "non-media output",
                        success: true,
                    },
                    OutcomeDef {
                        output: "[VIDEO:/tmp/vid.mp4]",
                        success: true,
                    },
                ],
                expected: vec![("[IMAGE:", "/tmp/img.png"), ("[VIDEO:", "/tmp/vid.mp4")],
            },
        ];

        for case in cases {
            let tools: Vec<Box<dyn Tool>> = case
                .tools
                .iter()
                .map(|t| match t {
                    ToolDef::Media { name, marker } => {
                        Box::new(MediaTestTool { name, marker }) as Box<dyn Tool>
                    }
                    ToolDef::NonMedia => Box::new(TestTool {
                        // Output value is irrelevant — extract_media_from_outcomes
                        // only consults media_marker(), never execute().
                        output: String::new(),
                        scrub: false,
                    }) as Box<dyn Tool>,
                })
                .collect();

            let calls: Vec<ToolCall> = case
                .tools
                .iter()
                .enumerate()
                .map(|(i, t)| {
                    let name = match t {
                        ToolDef::Media { name, .. } => *name,
                        ToolDef::NonMedia => "never_scrub",
                    };
                    ToolCall {
                        id: (i + 1).to_string(),
                        name: name.to_string(),
                        arguments: serde_json::json!({}),
                    }
                })
                .collect();

            let outcomes: Vec<ToolExecutionOutcome> = case
                .outcomes
                .iter()
                .map(|o| ToolExecutionOutcome {
                    output: o.output.to_string(),
                    success: o.success,
                    image_payloads: Vec::new(),
                    text_is_content: false,
                    suspended: false,
                    ends_turn: false,
                })
                .collect();

            let expected: Vec<(&'static str, String)> = case
                .expected
                .iter()
                .map(|(n, p)| (*n, p.to_string()))
                .collect();

            let result = extract_media_from_outcomes(&tools, &calls, &outcomes);
            assert_eq!(result, expected, "case '{}': {}", case.name, case.msg);
        }
    }

    #[tokio::test]
    async fn finalize_session_skipped_when_cancelled() {
        let mut agent = make_agent(vec![]);
        agent.cancel_token.cancel();
        let result = agent.finalize_session().await;
        assert!(
            result.is_ok(),
            "finalize_session should return Ok when cancelled, \
             skipping the 'no assistant message' warning"
        );
    }

    #[tokio::test]
    async fn execute_tool_skips_when_cancelled() {
        let tool: Box<dyn Tool> = Box::new(TestTool {
            output: "should not run".into(),
            scrub: false,
        });
        let name = tool.name();
        let agent = make_agent(vec![tool]);
        agent.cancel_token.cancel();
        let out = agent.execute_tool(name, serde_json::json!({})).await;

        assert!(!out.success, "cancelled agent should not execute tool");
        assert!(
            out.output.contains("Agent cancelled"),
            "failure output should mention cancellation: {}",
            out.output
        );
    }

    #[tokio::test]
    async fn task_locals_propagate_to_parallel_tool_execution() {
        /// Tool that reads CURRENT_TOOL_USER_NAME and CURRENT_TOOL_CHANNEL
        /// from task-locals and returns them in its output.
        struct ReadTaskLocalsTool;
        #[async_trait]
        impl Tool for ReadTaskLocalsTool {
            fn name(&self) -> &'static str {
                "read_task_locals"
            }
            fn description(&self) -> String {
                "test tool that reads task-local user context".into()
            }
            fn parameters_schema(&self) -> serde_json::Value {
                serde_json::json!({})
            }
            async fn execute(
                &self,
                _ws: &crate::Workspace,
                _args: serde_json::Value,
            ) -> anyhow::Result<String> {
                let user_name = tool_user_name();
                let channel = tool_channel();
                Ok(format!("user={user_name},channel={channel}"))
            }
        }

        let tool: Box<dyn Tool> = Box::new(ReadTaskLocalsTool);
        let name = tool.name();
        let mut agent = make_agent(vec![tool]);
        agent.user_name = "alice".into();
        agent.channel = "gui".into();

        // Call through execute_tool_group so task-locals are set once for
        // the entire batch — this is the path used by the agent work loop.
        let call = ToolCall {
            id: "call_1".into(),
            name: name.to_string(),
            arguments: serde_json::json!({}),
        };
        let outcomes = agent.execute_tool_group(&[call]).await;

        assert_eq!(
            outcomes.len(),
            1,
            "one tool call should produce one outcome"
        );
        assert!(outcomes[0].success, "ReadTaskLocalsTool should succeed");
        assert!(
            outcomes[0].output.contains("user=alice"),
            "should propagate user_name: {}",
            outcomes[0].output
        );
        assert!(
            outcomes[0].output.contains("channel=gui"),
            "should propagate channel: {}",
            outcomes[0].output
        );
    }

    // ── drain_incoming_messages tests ─────────────────────────────────

    /// drain_incoming_messages injects TicketComment messages into the session
    /// as user messages with the correct prefix.
    #[tokio::test]
    async fn test_drain_incoming_messages_injects_ticket_comment() {
        crate::util::test::init_management_test_stores().await;
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        let mut agent = make_agent(vec![]);
        agent.incoming_rx = Some(rx);
        agent.agent_id = "_test_drain_ticket_comment".into();

        // Send a TicketComment job
        let job = crate::agent::message_router::AgentJob {
            content: "Please fix the formatting".to_string(),
            workspace_name: "test_ws".to_string(),
            user_name: "manager".to_string(),
            channel: String::new(),
            kind: crate::agent::message_router::MessageKind::TicketComment,
            role: crate::Role::Manager,
            reply_target: None,
            pending_job_id: None,
            originating_workspace: None,
        };
        let _ = tx.send(job);

        agent.drain_incoming_messages().await;

        let history = agent.session.history();
        assert!(!history.is_empty(), "should have at least one message");
        let last = history.last().unwrap();
        assert_eq!(last.role, crate::ChatRole::User, "should be a user message");
        assert!(
            last.content.contains("Please fix the formatting"),
            "should contain the comment content: {}",
            last.content,
        );
        assert!(
            last.content.contains("[Comment from manager on ticket]"),
            "should include comment prefix: {}",
            last.content,
        );
    }

    /// drain_incoming_messages handles unregistered job kinds by passing
    /// content through without prefix formatting.
    #[tokio::test]
    async fn test_drain_incoming_messages_non_comment() {
        crate::util::test::init_management_test_stores().await;
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        let mut agent = make_agent(vec![]);
        agent.incoming_rx = Some(rx);
        agent.agent_id = "_test_drain_non_comment".into();

        // Send a plain UserMessage job
        let job = crate::agent::message_router::AgentJob {
            content: "Hello agent".to_string(),
            workspace_name: "test_ws".to_string(),
            user_name: "user".to_string(),
            channel: String::new(),
            kind: crate::agent::message_router::MessageKind::UserMessage,
            role: crate::Role::Assistant,
            reply_target: None,
            pending_job_id: None,
            originating_workspace: None,
        };
        let _ = tx.send(job);

        agent.drain_incoming_messages().await;

        let history = agent.session.history();
        assert!(!history.is_empty(), "should have at least one message");
        let last = history.last().unwrap();
        assert!(
            last.content.contains("Hello agent"),
            "should contain the raw content: {}",
            last.content,
        );
    }

    /// drain_incoming_messages handles a closed receiver gracefully
    /// (sets incoming_rx to None, no panic).
    #[tokio::test]
    async fn test_drain_incoming_messages_disconnected() {
        let (tx, rx) =
            tokio::sync::mpsc::unbounded_channel::<crate::agent::message_router::AgentJob>();
        let mut agent = make_agent(vec![]);
        agent.incoming_rx = Some(rx);
        agent.agent_id = "_test_drain_disconnected".into();

        // Drop the sender so the channel is disconnected
        drop(tx);

        // Should not panic or error
        agent.drain_incoming_messages().await;
        assert!(
            agent.incoming_rx.is_none(),
            "incoming_rx should be set to None after disconnect",
        );
    }

    // ── inject_outstanding_comments tests ──────────────────────────

    /// Build an agent (with the given role) whose ticket is attached and whose
    /// session is seeded with one `sessions` row (when `seed_content` is
    /// `Some`) and then initialized with an empty message — mirroring the
    /// empty-message resume dispatch for a deterministic stage round.
    async fn make_inject_agent(
        agent_id: &str,
        role: crate::Role,
        ticket: crate::pipeline::board::Ticket,
        seed_content: Option<&str>,
    ) -> Agent {
        if let Some(content) = seed_content {
            let now = crate::db::now();
            crate::session::store()
                .conn
                .execute(
                    "INSERT INTO sessions (agent_id, role, content, created_at) \
                     VALUES (?1, 'user', ?2, ?3)",
                    crate::db::params![agent_id, content, now],
                )
                .await
                .unwrap();
        }
        let mut agent = make_agent_with_role(vec![], role);
        agent.agent_id = agent_id.to_string();
        agent.session.init(agent_id).await.unwrap();
        agent.ticket = Some(ticket);
        agent
    }

    /// A comment added during a no-agent window is injected into the session for
    /// an empty-message resume, across the in-scope stage roles (engineer,
    /// sanitation).
    #[tokio::test]
    async fn test_inject_outstanding_comments_injects_for_stage_roles() {
        crate::util::test::init_management_test_stores().await;
        let cases: &[(
            &str,
            crate::Role,
            &str,
            &str,
            crate::pipeline::board::TicketPhase,
        )] = &[
            (
                "inject-new-agent",
                crate::Role::Engineer,
                "inject_new",
                "please fix the formatting",
                crate::pipeline::board::TicketPhase::InDevelopment,
            ),
            (
                "inject-sanitation-agent",
                crate::Role::Sanitation,
                "inject_sanitation",
                "please verify the cleanup",
                crate::pipeline::board::TicketPhase::InSanitation,
            ),
        ];
        for &(agent_id, role, ws_name, comment, phase) in cases {
            let ws = crate::workspace::test_ws_named("/tmp/test", ws_name);
            let ticket_id = crate::util::test::make_ticket(
                crate::pipeline::board::store(),
                &ws,
                "Inject Comment",
                phase,
            )
            .await;
            crate::pipeline::board::store()
                .add_comment(&ticket_id, "manager", comment)
                .await
                .unwrap();
            let ticket =
                crate::util::test::expect_ticket(crate::pipeline::board::store(), &ticket_id).await;

            let mut agent = make_inject_agent(agent_id, role, ticket, Some("round 1 task")).await;
            agent.inject_outstanding_comments(true, "").await;

            let history = agent.session.history();
            assert!(
                history.iter().any(|m| {
                    m.content.contains("[Comment from manager on ticket]")
                        && m.content.contains(comment)
                }),
                "a new board comment should be injected into a resumed {role} session",
            );
        }
    }

    /// A comment whose content already appears in the loaded session history is
    /// NOT re-injected (content-based dedup).
    #[tokio::test]
    async fn test_inject_outstanding_comments_dedups_existing_content() {
        crate::util::test::init_management_test_stores().await;
        let ws = crate::workspace::test_ws_named("/tmp/test", "inject_dedup");
        let ticket_id = crate::util::test::make_ticket(
            crate::pipeline::board::store(),
            &ws,
            "Inject Dedup",
            crate::pipeline::board::TicketPhase::InDevelopment,
        )
        .await;
        let content = "the comment content already seen";
        crate::pipeline::board::store()
            .add_comment(&ticket_id, "manager", content)
            .await
            .unwrap();
        let ticket =
            crate::util::test::expect_ticket(crate::pipeline::board::store(), &ticket_id).await;

        // Seed a history row that already carries the comment content (as a
        // previously delivered `[Comment from ...]` message) — the dedup must
        // skip it.
        let seed = format!("[Comment from manager on ticket]: {content}");
        let mut agent = make_inject_agent(
            "inject-dedup-agent",
            crate::Role::Engineer,
            ticket,
            Some(&seed),
        )
        .await;
        agent.inject_outstanding_comments(true, "").await;

        let history = agent.session.history();
        assert_eq!(
            history.len(),
            1,
            "an already-seen comment must not be re-injected",
        );
    }

    /// Dedup is purely content-based (the ticket's rule): a comment authored by
    /// the agent's own role is NOT special-cased — it is injected when its
    /// content is absent from the loaded history (only content-in-history
    /// dedup suppresses it).
    #[tokio::test]
    async fn test_inject_outstanding_comments_does_not_special_case_own_role() {
        crate::util::test::init_management_test_stores().await;
        let ws = crate::workspace::test_ws_named("/tmp/test", "inject_own_role");
        let ticket_id = crate::util::test::make_ticket(
            crate::pipeline::board::store(),
            &ws,
            "Inject Own Role",
            crate::pipeline::board::TicketPhase::InDevelopment,
        )
        .await;
        crate::pipeline::board::store()
            .add_comment(&ticket_id, "engineer", "note from the engineer")
            .await
            .unwrap();
        let ticket =
            crate::util::test::expect_ticket(crate::pipeline::board::store(), &ticket_id).await;

        let mut agent = make_inject_agent(
            "inject-own-role-agent",
            crate::Role::Engineer,
            ticket,
            Some("round 1 task"),
        )
        .await;
        agent.inject_outstanding_comments(true, "").await;

        let history = agent.session.history();
        assert!(
            history
                .iter()
                .any(|m| m.content.contains("[Comment from engineer on ticket]")),
            "an own-role comment absent from history must still be injected",
        );
    }

    /// The bounce-feedback path (non-empty `msg`) and a non-resumed round
    /// (`resume=false`) are no-ops — no injection.
    #[tokio::test]
    async fn test_inject_outstanding_comments_noop_for_feedback_and_fresh() {
        crate::util::test::init_management_test_stores().await;
        let ws = crate::workspace::test_ws_named("/tmp/test", "inject_noop");
        let ticket_id = crate::util::test::make_ticket(
            crate::pipeline::board::store(),
            &ws,
            "Inject Noop",
            crate::pipeline::board::TicketPhase::InDevelopment,
        )
        .await;
        crate::pipeline::board::store()
            .add_comment(&ticket_id, "manager", "please fix the formatting")
            .await
            .unwrap();
        let ticket =
            crate::util::test::expect_ticket(crate::pipeline::board::store(), &ticket_id).await;

        let mut agent = make_inject_agent(
            "inject-noop-agent",
            crate::Role::Engineer,
            ticket,
            Some("round 1 task"),
        )
        .await;
        // Bounce-feedback path: non-empty msg.
        agent
            .inject_outstanding_comments(true, "round 2 feedback")
            .await;
        // Fresh (non-resumed) round.
        agent.inject_outstanding_comments(false, "").await;

        let history = agent.session.history();
        assert!(
            !history
                .iter()
                .any(|m| m.content.contains("[Comment from manager on ticket]")),
            "feedback path and fresh round must not inject comments",
        );
    }

    /// Comment injection is not role-gated: the role flag was removed as dead
    /// weight (only stage rounds resume with an empty message in production),
    /// so a non-stage role reaching the resume path injects too.
    #[tokio::test]
    async fn test_inject_outstanding_comments_injects_for_non_stage_role() {
        crate::util::test::init_management_test_stores().await;
        let ws = crate::workspace::test_ws_named("/tmp/test", "inject_analyst");
        let ticket_id = crate::util::test::make_ticket(
            crate::pipeline::board::store(),
            &ws,
            "Inject Analyst",
            crate::pipeline::board::TicketPhase::InDevelopment,
        )
        .await;
        crate::pipeline::board::store()
            .add_comment(&ticket_id, "manager", "please fix the formatting")
            .await
            .unwrap();
        let ticket =
            crate::util::test::expect_ticket(crate::pipeline::board::store(), &ticket_id).await;

        let mut agent = make_inject_agent(
            "inject-analyst-agent",
            crate::Role::Analyst,
            ticket,
            Some("round 1 task"),
        )
        .await;
        agent.inject_outstanding_comments(true, "").await;

        let history = agent.session.history();
        assert!(
            history
                .iter()
                .any(|m| m.content.contains("[Comment from manager on ticket]")),
            "injection is no longer role-gated — non-stage roles reaching the resume path inject",
        );
    }

    // ── Leader-stagger mechanics ───────────────────────────────────

    /// Single-member rounds are a no-op stagger: the sole member starts
    /// immediately with no first-call signal.
    #[tokio::test]
    async fn spawn_staggered_round_single_member_is_noop() {
        let handles = crate::agent::spawn_staggered_round(
            vec![move |round: crate::agent::RoundOpts| async move {
                assert!(
                    round.first_call_notify.is_none(),
                    "sole member must not receive a signal"
                );
                1u8
            }],
            false,
        )
        .await;
        assert_eq!(handles.len(), 1);
        assert_eq!(handles.into_iter().next().unwrap().await.unwrap(), 1);
    }

    /// Boot-resumed rounds skip the stagger entirely: every member starts
    /// immediately with no first-call signal (their sessions already
    /// diverged — staggering would only add latency).
    #[tokio::test]
    async fn spawn_staggered_round_resume_skips_stagger() {
        let handles = crate::agent::spawn_staggered_round(
            (0..3)
                .map(|i| {
                    move |round: crate::agent::RoundOpts| async move {
                        assert!(
                            round.first_call_notify.is_none(),
                            "resume must not stagger (member {i})"
                        );
                        i
                    }
                })
                .collect(),
            true,
        )
        .await;
        assert_eq!(handles.len(), 3);
        let mut out = Vec::new();
        for h in handles {
            out.push(h.await.unwrap());
        }
        assert_eq!(out, vec![0, 1, 2]);
    }

    /// The leader's first-call signal releases the followers: once the notify
    /// fires (before or during the wait), the remaining members start and the
    /// round completes. All members share one round-fixed timestamp.
    #[tokio::test]
    async fn spawn_staggered_round_leader_notify_releases_followers() {
        let handles = crate::agent::spawn_staggered_round(
            (0..3)
                .map(|i| {
                    move |round: crate::agent::RoundOpts| async move {
                        let tag = if i == 0 {
                            round
                                .first_call_notify
                                .expect("leader receives the signal")
                                .notify_one();
                            "leader".to_string()
                        } else {
                            assert!(
                                round.first_call_notify.is_none(),
                                "followers must not receive the signal"
                            );
                            "follower".to_string()
                        };
                        (tag, round.round_ts)
                    }
                })
                .collect(),
            false,
        )
        .await;
        assert_eq!(handles.len(), 3);
        let mut out = Vec::new();
        for h in handles {
            out.push(h.await.unwrap());
        }
        assert!(out.iter().any(|(tag, _)| tag == "leader"));
        assert_eq!(out.iter().filter(|(tag, _)| tag == "follower").count(), 2);
        assert_eq!(
            out.iter()
                .map(|(_, ts)| ts)
                .collect::<std::collections::HashSet<_>>()
                .len(),
            1,
            "all members share one round-fixed timestamp"
        );
    }

    /// Fail-open: a leader that never fires its signal (stuck first call)
    /// still releases the followers after the bounded wait — the round never
    /// hangs.
    #[tokio::test]
    async fn spawn_staggered_round_leader_timeout_fail_open() {
        // 0 → immediate timeout (deliberate test seam, see env_duration_secs).
        let _guard = crate::util::test::set_env_var("MAHBOT_STAGGER_WAIT_SECS", Some("0"));
        let handles = crate::agent::spawn_staggered_round(
            (0..2)
                .map(|i| {
                    move |round: crate::agent::RoundOpts| async move {
                        if i == 0 {
                            let _ = round; // never fires — stuck leader
                            "stuck-leader".to_string()
                        } else {
                            assert!(
                                round.first_call_notify.is_none(),
                                "released follower gets no signal"
                            );
                            "released".to_string()
                        }
                    }
                })
                .collect(),
            false,
        )
        .await;
        assert_eq!(
            handles.len(),
            2,
            "followers must be released despite the stuck leader"
        );
        for h in handles {
            h.await.unwrap();
        }
    }

    /// Fail-open on leader FAILURE: a leader whose first LLM call errors (the
    /// retry budget exhausts) still fires the first-call signal — followers
    /// are released immediately instead of waiting out the bound.
    // Joins the `provider` serial group: the seam swaps the process-global
    // provider, so the test must not interleave with the other provider-group
    // tests (same exclusion the pipeline/retry tests rely on).
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn leader_first_call_failure_still_fires_signal() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let ws = crate::workspace::test_ws_named("/tmp/ws_leader_fail", "leader_fail");
        let notify = std::sync::Arc::new(tokio::sync::Notify::new());
        // 3 scripted failures = the tiny policy's full budget → exhausted.
        let provider = FakeProvider::new()
            .err(crate::retry::FailureClass::Transport, "boom")
            .err(crate::retry::FailureClass::Transport, "boom")
            .err(crate::retry::FailureClass::Transport, "boom");
        let _provider = install_fake_provider(std::sync::Arc::new(provider));
        let (_agent, response) = run_agent(
            "leader_fail_agent".to_string(),
            crate::Role::Analyst,
            &ws,
            None,
            "task",
            String::new(),
            String::new(),
            false,
            None,
            false,
            Some(RoundOpts {
                round_ts: crate::session::render_timestamp(),
                first_call_notify: Some(notify.clone()),
            }),
            None,
            None,
        )
        .await;
        assert!(
            response.is_none(),
            "leader round must fail with an exhausted budget"
        );
        tokio::time::timeout(std::time::Duration::from_secs(5), notify.notified())
            .await
            .expect("first-call signal must fire even when the call fails");
    }

    /// A successful `sleep` call ends the run gracefully: the round's tool
    /// result commits as a normal tool result, the loop stops WITHOUT a
    /// follow-up LLM call (the empty response is the intended silent end,
    /// never the failure path), and the durable sleep-ended flag is set. The
    /// next turn on the session (any wake-up: user message, async result,
    /// alarm) clears the flag and runs normally.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn sleep_call_ends_the_run_gracefully_and_flag_resets_on_reengage() {
        crate::util::test::init_test_stores().await;
        // Script exactly ONE sleep tool call; a follow-up LLM call would pop
        // the second scripted item and the first turn would end with a text
        // response instead of the silent empty one.
        let fake = std::sync::Arc::new(FakeProvider::new().ok_tool_call("sleep").ok("back online"));
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let ws = crate::workspace::test_ws_named("/tmp/ws_sleep_stop", "sleep_stop");
        let agent_id = "sleep_stop_agent".to_string();

        // ── Turn 1: the sleep call ends the run ──────────────────────
        let (agent, response) = run_agent(
            agent_id.clone(),
            crate::Role::Assistant,
            &ws,
            None,
            "hello",
            "sleep_user".to_string(),
            "gui".to_string(),
            false,
            None,
            false,
            None,
            None,
            None,
        )
        .await;
        assert!(agent.sleep_ended, "sleep must mark the turn sleep-ended");
        assert_eq!(
            response.as_deref(),
            Some(""),
            "the turn must end silently — any text would mean the loop continued"
        );
        assert_eq!(
            fake.request_messages.lock().unwrap().len(),
            1,
            "no LLM call may follow the committed sleep round"
        );
        // The round committed: the session tail is the sleep tool result.
        let (tail_role, tail_content) = crate::session::store()
            .get_last_message_tail(&agent_id)
            .await
            .expect("session must have history");
        assert_eq!(tail_role, crate::ChatRole::Tool);
        // The tool tail is the raw tool-result payload (JSON with the call id
        // and content) — the committed "Zzz..." result.
        assert!(
            tail_content.contains("\"tool_call_id\":\"call_test\"")
                && tail_content.contains("\"content\":\"Zzz...\""),
            "sleep tool result must be committed as a normal tool result: {tail_content}"
        );
        assert!(
            crate::session::store().get_sleep_ended(&agent_id).await,
            "the durable sleep-ended flag must be set"
        );

        // ── Turn 2: re-engagement clears the flag and runs normally ──
        let (agent2, response2) = run_agent(
            agent_id.clone(),
            crate::Role::Assistant,
            &ws,
            None,
            "wake up",
            "sleep_user".to_string(),
            "gui".to_string(),
            false,
            None,
            false,
            None,
            None,
            None,
        )
        .await;
        assert_eq!(response2.as_deref(), Some("back online"));
        assert!(!agent2.sleep_ended);
        assert!(
            !crate::session::store().get_sleep_ended(&agent_id).await,
            "the flag must be cleared when the session re-engages"
        );
    }

    /// A `sleep` call written in a round that also carries text is rejected at
    /// runtime (the text is never delivered in a tool round and the successful
    /// sleep ends the run silently) — the loop continues and the model resends
    /// the text as a plain round.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn sleep_with_text_is_rejected_and_resend_is_delivered() {
        crate::util::test::init_test_stores().await;
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_text_and_tool_calls("here is the answer", &[("sleep", serde_json::json!({}))])
                .ok("here is the answer"),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let ws = crate::workspace::test_ws_named("/tmp/ws_sleep_text", "sleep_text");
        let agent_id = "sleep_text_agent".to_string();

        let (agent, response) = run_agent(
            agent_id.clone(),
            crate::Role::Assistant,
            &ws,
            None,
            "hello",
            "sleep_text_user".to_string(),
            "gui".to_string(),
            false,
            None,
            false,
            None,
            None,
            None,
        )
        .await;

        assert_eq!(
            response.as_deref(),
            Some("here is the answer"),
            "the text must be resent as a plain round after the rejection"
        );
        assert!(!agent.sleep_ended, "a rejected sleep must not end the run");
        assert_eq!(
            fake.request_messages.lock().unwrap().len(),
            2,
            "the rejection round plus the plain resend round"
        );

        // The sleep round committed a rejection Tool result, not a "Zzz..." one.
        let history = agent.session.history();
        let rejection_tools: Vec<String> = history
            .iter()
            .filter(|m| m.role == crate::ChatRole::Tool)
            .map(|m| {
                serde_json::from_str::<crate::ToolResultPayload>(&m.content)
                    .expect("tool message must be a ToolResultPayload")
                    .content
            })
            .collect();
        assert!(
            rejection_tools
                .iter()
                .any(|c| c.contains("NOT delivered") && !c.contains("Zzz...")),
            "the sleep rejection must be committed without a Zzz... result: {rejection_tools:?}"
        );

        assert!(
            !crate::session::store().get_sleep_ended(&agent_id).await,
            "the durable sleep-ended flag must stay clear"
        );
    }

    /// A `sleep` call bundled with another tool call is rejected at runtime
    /// (subsequent silent end), while the sibling call executes normally — the
    /// loop continues and the model can resend as a plain round.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn sleep_bundled_with_other_tool_is_rejected_but_sibling_executes() {
        crate::util::test::init_test_stores().await;
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("seed.txt"), "bundle-marker\n").unwrap();
        let ws = crate::Workspace::from_path(dir.path());

        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_text_and_tool_calls(
                    "",
                    &[
                        ("read", serde_json::json!({"path": "seed.txt"})),
                        ("sleep", serde_json::json!({})),
                    ],
                )
                .ok("done"),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let agent_id = "sleep_bundle_agent".to_string();

        let (agent, response) = run_agent(
            agent_id.clone(),
            crate::Role::Assistant,
            &ws,
            None,
            "hello",
            "sleep_bundle_user".to_string(),
            "gui".to_string(),
            false,
            None,
            false,
            None,
            None,
            None,
        )
        .await;

        assert_eq!(response.as_deref(), Some("done"));
        assert!(!agent.sleep_ended, "a bundled sleep must not end the run");
        assert_eq!(fake.request_messages.lock().unwrap().len(), 2);

        let history = agent.session.history();
        let tool_results: Vec<String> = history
            .iter()
            .filter(|m| m.role == crate::ChatRole::Tool)
            .map(|m| {
                serde_json::from_str::<crate::ToolResultPayload>(&m.content)
                    .expect("tool message must be a ToolResultPayload")
                    .content
            })
            .collect();
        assert!(
            tool_results.iter().any(|c| c.contains("bundle-marker")),
            "the read sibling must execute normally: {tool_results:?}"
        );
        assert!(
            tool_results
                .iter()
                .any(|c| c.contains("bundled with other tool calls")),
            "the bundled sleep must be rejected: {tool_results:?}"
        );
    }

    /// The sleep-delivery guard also covers the resume-completion path: a
    /// dangling tool-call frame carrying text alongside a `sleep` call settles
    /// the rejection (the ORIGINAL call id) instead of re-executing it into a
    /// "Zzz..." result over text the user never saw.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn resume_completion_rejects_text_sleep_frame() {
        crate::util::test::init_test_stores().await;
        let dir = tempfile::tempdir().unwrap();
        let ws = crate::Workspace::from_path(dir.path());

        let mut session = Session::default();
        let frame = crate::providers::reasoning::assistant_replay_payload(
            Some("the answer"),
            &[crate::ToolCall {
                id: "call_sleep_r".to_string(),
                name: "sleep".to_string(),
                arguments: serde_json::json!({}),
            }],
            None,
        )
        .to_string();
        session
            .persist_messages(
                "test-sleep-resume",
                &[ChatMessage::user("wake"), ChatMessage::assistant(frame)],
            )
            .await
            .unwrap();

        let mut agent = make_agent_on(
            vec![Box::new(crate::tools::SleepTool)],
            "test-sleep-resume",
            ws,
        );
        agent.session = session;
        let settled = agent.complete_pending_tool_calls().await.unwrap();
        assert!(
            settled,
            "a text-accompanied sleep frame settles the rejection"
        );

        let history = agent.session.history();
        let roles: Vec<crate::ChatRole> = history.iter().map(|m| m.role).collect();
        assert_eq!(
            roles,
            vec![
                crate::ChatRole::User,
                crate::ChatRole::Assistant,
                crate::ChatRole::Tool
            ],
            "result contiguous after the frame: {roles:?}"
        );
        let payload: crate::ToolResultPayload = serde_json::from_str(&history[2].content).unwrap();
        assert_eq!(
            payload.tool_call_id, "call_sleep_r",
            "rejection keeps the ORIGINAL call id"
        );
        assert!(
            payload.content.contains("NOT delivered"),
            "sleep rejection content: {}",
            payload.content
        );
        assert!(!payload.content.contains("Zzz..."));
        assert!(agent.session.pending_tool_frame().is_none());
    }

    // ── Reasoning-only stop recovery ─────────────────────────────────

    /// The class predicate: raw empty content + no parsed tool calls,
    /// regardless of finish reason. Tool-call turns (empty text by design)
    /// and real answers are excluded. Degenerate members (fully-empty, no
    /// reasoning) are consciously in-class.
    #[test]
    fn reasoning_only_stop_classification() {
        let reasoning = || {
            Some(crate::Reasoning {
                reasoning: Some("thinking".into()),
                reasoning_content: Some("thinking".into()),
                reasoning_details: None,
            })
        };

        // Empty/absent content, no tools → in class for ANY finish reason.
        for finish in [None, Some("stop"), Some("length"), Some("tool_calls")] {
            let resp = crate::ChatResponse {
                text: None,
                reasoning: reasoning(),
                finish_reason: finish.map(str::to_string),
                ..crate::ChatResponse::default()
            };
            assert!(is_reasoning_only_stop(&resp), "finish_reason={finish:?}");
        }
        // Explicit empty-string content → in class.
        let resp = crate::ChatResponse {
            text: Some(String::new()),
            reasoning: reasoning(),
            ..crate::ChatResponse::default()
        };
        assert!(is_reasoning_only_stop(&resp));
        // Whitespace-only content → in class.
        let resp = crate::ChatResponse {
            text: Some("   \n ".into()),
            ..crate::ChatResponse::default()
        };
        assert!(is_reasoning_only_stop(&resp));
        // Fully-empty response (no reasoning attached) → in class.
        let resp = crate::ChatResponse::default();
        assert!(is_reasoning_only_stop(&resp));
        // Tool calls with empty text → NOT in class (valid tool-call turn).
        let resp = crate::ChatResponse {
            text: None,
            tool_calls: vec![crate::ToolCall {
                id: "t1".into(),
                name: "read".into(),
                arguments: serde_json::json!({}),
            }],
            ..crate::ChatResponse::default()
        };
        assert!(!is_reasoning_only_stop(&resp));
        // Real visible text (even with reasoning present) → NOT in class.
        let resp = crate::ChatResponse {
            text: Some("real answer".into()),
            reasoning: reasoning(),
            ..crate::ChatResponse::default()
        };
        assert!(!is_reasoning_only_stop(&resp));
    }

    /// A reasoning-only stop resolves via the continuation: the final answer
    /// is returned, the continuation request carries the appended tail
    /// (assistant reasoning payload + the resume nudge), and the nudge never
    /// appears in the original request.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn llm_call_recovers_reasoning_only_stop_via_continuation() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_reasoning_only("draft plan then execute tool", Some("stop"))
                .ok("final answer"),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let mut agent = make_agent(vec![]);
        let resp = agent.llm_call().await.expect("continuation must resolve");
        assert_eq!(resp.text_or_empty(), "final answer");

        let fingerprints = fake.request_fingerprints.lock().unwrap().clone();
        assert_eq!(fingerprints.len(), 2, "original call + one continuation");
        assert!(
            !fingerprints[0].contains("Resume your unfinished turn"),
            "original request must not carry the continuation tail"
        );
        assert!(
            fingerprints[1].contains("Resume your unfinished turn"),
            "continuation request must carry the appended nudge"
        );
        assert!(
            fingerprints[1].contains("draft plan then execute tool"),
            "continuation must echo the previous reasoning as the assistant turn"
        );
    }

    /// Consecutive reasoning-only responses accumulate: each failed attempt
    /// appends its own (assistant reasoning + nudge) pair, so the request
    /// prefix stays byte-stable and only the tail grows.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn llm_call_continuation_accumulates_tail_until_answer() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_reasoning_only("thinking 1", Some("stop"))
                .ok_reasoning_only("thinking 2", Some("stop"))
                .ok("answer after two continuations"),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let mut agent = make_agent(vec![]);
        let resp = agent.llm_call().await.expect("continuation must resolve");
        assert_eq!(resp.text_or_empty(), "answer after two continuations");

        let fingerprints = fake.request_fingerprints.lock().unwrap().clone();
        assert_eq!(fingerprints.len(), 3);
        // Strictly appended-only: one nudge after the first continuation, two
        // after the second (the first pair is part of the byte-stable prefix).
        assert_eq!(
            fingerprints[1]
                .matches("Resume your unfinished turn")
                .count(),
            1,
            "attempt 2 carries exactly the first appended pair"
        );
        assert_eq!(
            fingerprints[2]
                .matches("Resume your unfinished turn")
                .count(),
            2,
            "attempt 3 carries both appended pairs"
        );
        assert!(fingerprints[2].contains("thinking 1"));
        assert!(fingerprints[2].contains("thinking 2"));

        // Direct byte-prefix pin of the KV-cache property: attempt 3's message
        // list begins with attempt 2's messages verbatim (append-only growth,
        // nothing rewritten). The capture joins per-message Debug with NUL, so
        // a plain prefix check holds.
        let messages = fake.request_messages.lock().unwrap().clone();
        assert_eq!(messages.len(), 3);
        assert!(
            messages[2].starts_with(&messages[1]),
            "byte-stable prefix: attempt 3's messages begin with attempt 2's verbatim"
        );
    }

    /// Continuation exhaustion fails the turn safely: a NoResponse
    /// [`RetryExhausted`] with `last_raw: None`, no reasoning text in the
    /// error, no provider-retry-exhaustion marker, no transcript trace, and
    /// granular "no_response" classification.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn llm_call_continuation_exhaustion_fails_safely_without_leaking() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_reasoning_only("secret thinking alpha", Some("stop"))
                .ok_reasoning_only("secret thinking beta", Some("stop"))
                .ok_reasoning_only("secret thinking gamma", Some("stop"))
                .ok_reasoning_only("secret thinking delta", Some("stop")),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let mut agent = make_agent(vec![]);
        let err = agent
            .llm_call()
            .await
            .expect_err("continuation must exhaust");
        let exhausted = err
            .chain()
            .find_map(|c| c.downcast_ref::<crate::retry::RetryExhausted>())
            .expect("RetryExhausted must survive in the error chain");
        assert_eq!(
            exhausted.final_class,
            crate::retry::FailureClass::NoResponse,
            "granular no-response classification"
        );
        assert_eq!(
            exhausted.last_raw, None,
            "no raw text on the exhausted error"
        );
        let last_failure = exhausted
            .failures
            .last()
            .expect("failure trail is non-empty");
        assert_eq!(
            last_failure.finish_reason.as_deref(),
            Some("stop"),
            "in-class NoResponse records carry the response finish_reason into the telemetry trail"
        );
        let rendered = format!("{err:#}");
        assert!(
            !rendered.contains("secret thinking"),
            "the thinking must never leak into the failure error"
        );
        assert!(
            !rendered.contains(RETRY_EXHAUSTION_MARKER),
            "must not be misclassified as LLM provider retry exhaustion"
        );
        assert!(
            agent.session.history().is_empty(),
            "the continuation tail must never reach the session transcript"
        );
        assert_eq!(failure_classification(&agent, Some(&err)), "no_response");
    }

    /// A transport error mid-recovery never duplicates the thinking tail: the
    /// retried request is byte-identical, and exhaustion derives the final
    /// class from the last recorded failure (Transport, not NoResponse).
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn llm_call_continuation_transport_error_does_not_duplicate_tail() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_reasoning_only("thinking 1", Some("stop"))
                .err(crate::retry::FailureClass::Transport, "connection reset")
                .err(crate::retry::FailureClass::Transport, "connection reset")
                .err(crate::retry::FailureClass::Transport, "connection reset"),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let mut agent = make_agent(vec![]);
        let err = agent
            .llm_call()
            .await
            .expect_err("continuation must exhaust");
        let exhausted = err
            .chain()
            .find_map(|c| c.downcast_ref::<crate::retry::RetryExhausted>())
            .expect("RetryExhausted must survive in the error chain");
        assert_eq!(
            exhausted.final_class,
            crate::retry::FailureClass::Transport,
            "final class derives from the last recorded failure, not NoResponse"
        );

        let fingerprints = fake.request_fingerprints.lock().unwrap().clone();
        assert_eq!(
            fingerprints.len(),
            4,
            "original call + 3 continuation attempts"
        );
        assert_eq!(
            fingerprints[1], fingerprints[2],
            "attempt 2 re-sends the byte-identical request after a transport error"
        );
        assert_eq!(fingerprints[2], fingerprints[3]);
        let rendered = format!("{err:#}");
        assert!(
            !rendered.contains("thinking"),
            "the thinking must never leak into the failure error"
        );
    }

    /// A non-retryable provider error mid-recovery breaks immediately instead
    /// of burning the remaining attempts, and keeps the granular class.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn llm_call_continuation_non_retryable_error_breaks_immediately() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_reasoning_only("thinking 1", Some("stop"))
                .err(crate::retry::FailureClass::NonRetryable, "invalid model"),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let mut agent = make_agent(vec![]);
        let err = agent.llm_call().await.expect_err("continuation must fail");
        let exhausted = err
            .chain()
            .find_map(|c| c.downcast_ref::<crate::retry::RetryExhausted>())
            .expect("RetryExhausted must survive in the error chain");
        assert_eq!(
            exhausted.final_class,
            crate::retry::FailureClass::NonRetryable,
            "non-retryable class survives to the terminal error"
        );
        assert_eq!(
            fake.request_fingerprints.lock().unwrap().len(),
            2,
            "original call + exactly one continuation attempt (no budget burn)"
        );
    }

    /// A global abort (drain) between recovery attempts classifies the
    /// terminal error as Shutdown, not NoResponse — the real cause must not be
    /// masked, even when the break happens before the first attempt (no
    /// request was ever sent, so there is also nothing to record in telemetry).
    #[tokio::test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    async fn recover_reasoning_only_stop_abort_classifies_as_shutdown() {
        let agent = make_agent(vec![]);
        let first = crate::ChatResponse {
            text: None,
            reasoning: Some(crate::Reasoning {
                reasoning: Some("thinking".into()),
                reasoning_content: Some("thinking".into()),
                reasoning_details: None,
            }),
            finish_reason: Some("stop".into()),
            ..crate::ChatResponse::default()
        };

        // The drain flag is process-global — set it for the duration of the
        // recovery, then restore (never fire the global token from a test).
        crate::shutdown::drain_begin();
        let exhausted = agent
            .recover_reasoning_only_stop(vec![], first, "agent-continuation")
            .await
            .expect_err("the drain must break the continuation immediately");
        crate::shutdown::drain_clear();

        assert_eq!(
            exhausted.final_class,
            crate::retry::FailureClass::Shutdown,
            "a global abort must classify as shutdown, never no_response"
        );
    }

    /// A reasoning-only turn whose continuation exhausts is a FAILED call: it
    /// must never update the session token length (the `maybe_summarize`
    /// "a FAILED call never updates the value" invariant), even though the
    /// invisible in-class response carried real usage.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn llm_call_continuation_exhaustion_does_not_update_session_length() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_reasoning_only_with_usage("thinking a", Some("stop"), 1_000, 500)
                .ok_reasoning_only_with_usage("thinking b", Some("stop"), 1_000, 500)
                .ok_reasoning_only_with_usage("thinking c", Some("stop"), 1_000, 500)
                .ok_reasoning_only_with_usage("thinking d", Some("stop"), 1_000, 500),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let mut agent = make_agent(vec![]);
        assert_eq!(agent.session.token_length(), None);
        let err = agent
            .llm_call()
            .await
            .expect_err("continuation must exhaust");
        assert_eq!(
            agent.session.token_length(),
            None,
            "a failed turn (continuation exhaustion) must not update the session length"
        );
        let rendered = format!("{err:#}");
        assert!(
            !rendered.contains("thinking"),
            "the thinking must never leak into the failure error"
        );
    }

    /// On continuation success, the session length is updated from the
    /// RESOLVING response only — the in-class response the continuation
    /// consumed is never recorded (no inflated value, no wasted double write).
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn llm_call_continuation_success_records_only_resolving_usage() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_reasoning_only_with_usage("thinking a", Some("stop"), 1_000, 500)
                .ok_with_usage("final answer", 200, 300),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let mut agent = make_agent(vec![]);
        let resp = agent.llm_call().await.expect("continuation must resolve");
        assert_eq!(resp.text_or_empty(), "final answer");
        assert_eq!(
            agent.session.token_length(),
            Some(500),
            "only the resolving continuation response (200 + 300) updates the session length"
        );
    }

    /// A normal answer or a tool-call turn never enters the continuation path.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn llm_call_skips_continuation_for_normal_and_tool_call_turns() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());

        {
            let fake = std::sync::Arc::new(FakeProvider::new().ok("normal answer"));
            let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
            let _provider_guard = install_fake_provider(provider);
            let mut agent = make_agent(vec![]);
            let resp = agent.llm_call().await.expect("normal answer");
            assert_eq!(resp.text_or_empty(), "normal answer");
            assert_eq!(
                fake.request_fingerprints.lock().unwrap().len(),
                1,
                "normal answer must not trigger continuation"
            );
        }
        {
            let fake = std::sync::Arc::new(FakeProvider::new().ok_tool_call("read"));
            let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
            let _provider_guard = install_fake_provider(provider);
            let mut agent = make_agent(vec![]);
            let resp = agent.llm_call().await.expect("tool-call turn");
            assert!(resp.text_or_empty().is_empty());
            assert_eq!(resp.tool_calls.len(), 1);
            assert_eq!(
                fake.request_fingerprints.lock().unwrap().len(),
                1,
                "tool-call turn (empty text) must not trigger continuation"
            );
        }
    }

    /// Summarize recovers a reasoning-only stop via the same bounded
    /// continuation; the continuation answer becomes the summary.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn summarize_recovers_reasoning_only_stop_via_continuation() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_reasoning_only("thinking about the summary", Some("stop"))
                .ok("the summary"),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let agent = make_agent(vec![]);
        let summary = agent.summarize().await.expect("continuation must resolve");
        assert_eq!(summary, "the summary");

        let fingerprints = fake.request_fingerprints.lock().unwrap().clone();
        assert_eq!(
            fingerprints.len(),
            2,
            "original summary call + one continuation"
        );
        assert!(fingerprints[1].contains("Resume your unfinished turn"));
    }

    /// Summarize continuation exhaustion keeps the fail-open behavior: the
    /// empty-response error fires (warn + full history in `maybe_summarize`),
    /// and the thinking never leaks into the error.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn summarize_continuation_exhaustion_fails_open_without_leaking() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_reasoning_only("summary thinking", Some("stop"))
                .ok_reasoning_only("summary thinking", Some("stop"))
                .ok_reasoning_only("summary thinking", Some("stop"))
                .ok_reasoning_only("summary thinking", Some("stop")),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let agent = make_agent(vec![]);
        let err = agent
            .summarize()
            .await
            .expect_err("continuation must exhaust");
        let rendered = format!("{err:#}");
        assert!(
            rendered.contains("summarization"),
            "fail-open path surfaces the summarization error for maybe_summarize"
        );
        assert!(
            !rendered.contains("summary thinking"),
            "the thinking must never leak into the summarization error"
        );
    }

    /// A summarisation answer that is a tool call carries no summary text: it
    /// is re-asked byte-identically (the request is re-sent verbatim, tool set
    /// included) instead of being accepted as the summary.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn summarize_reasks_a_tool_call_answer_byte_identically() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(FakeProvider::new().ok_tool_call("read").ok("the summary"));
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let agent = make_agent(vec![]);
        let summary = agent.summarize().await.expect("the re-ask must resolve");
        assert_eq!(summary, "the summary");

        let fingerprints = fake.request_fingerprints.lock().unwrap().clone();
        assert_eq!(fingerprints.len(), 2, "tool-call answer + one re-ask");
        assert_eq!(
            fingerprints[0], fingerprints[1],
            "the re-ask must re-send the identical request"
        );
    }

    /// Tool-call answers exhaust the bounded re-ask budget at
    /// [`SUMMARIZE_ATTEMPTS`] attempts without changing today's outcome: the
    /// empty-response error fires (fail-open in `maybe_summarize`).
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn summarize_tool_call_exhaustion_keeps_the_empty_response_error() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .ok_tool_call("read")
                .ok_tool_call("read")
                .ok_tool_call("read"),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let agent = make_agent(vec![]);
        let err = agent
            .summarize()
            .await
            .expect_err("the budget must exhaust");
        assert!(
            format!("{err:#}").contains("summarization produced empty response"),
            "the fail-open error is unchanged: {err:#}"
        );
        assert_eq!(
            fake.request_fingerprints.lock().unwrap().len(),
            SUMMARIZE_ATTEMPTS as usize,
            "the re-ask must stop at the attempt bound"
        );
    }

    // ── Real provider-token session length semantics ───────────────────

    /// Both-or-nothing / keep-last / never-zero rule of
    /// [`Agent::record_session_usage`].
    #[tokio::test]
    async fn record_session_usage_keeps_last_on_missing_or_partial_usage() {
        crate::util::test::init_test_stores().await;
        let mut agent = make_agent(vec![]);
        agent.session.set_token_length(Some(7_000));

        // No usage data at all → keep the last known value.
        agent
            .record_session_usage(&crate::ChatResponse::default())
            .await;
        assert_eq!(agent.session.token_length(), Some(7_000));

        // Only one side present → keep the last known value.
        let partial_input = crate::ChatResponse {
            usage: Some(crate::ProviderUsage {
                input_tokens: Some(1_000),
                ..crate::ProviderUsage::default()
            }),
            ..crate::ChatResponse::default()
        };
        agent.record_session_usage(&partial_input).await;
        assert_eq!(agent.session.token_length(), Some(7_000));

        let partial_output = crate::ChatResponse {
            usage: Some(crate::ProviderUsage {
                output_tokens: Some(1_000),
                ..crate::ProviderUsage::default()
            }),
            ..crate::ChatResponse::default()
        };
        agent.record_session_usage(&partial_output).await;
        assert_eq!(agent.session.token_length(), Some(7_000));

        // Both present → input + output; a later usage-less response never
        // resets the value to zero.
        let full = crate::ChatResponse {
            usage: Some(crate::ProviderUsage {
                input_tokens: Some(12_000),
                output_tokens: Some(300),
                ..crate::ProviderUsage::default()
            }),
            ..crate::ChatResponse::default()
        };
        agent.record_session_usage(&full).await;
        assert_eq!(agent.session.token_length(), Some(12_300));
        agent
            .record_session_usage(&crate::ChatResponse::default())
            .await;
        assert_eq!(
            agent.session.token_length(),
            Some(12_300),
            "a usage-less response must never reset the length to zero"
        );
    }

    /// Saturating sum: an overflowing usage pair cannot wrap into a small
    /// bogus session length.
    #[tokio::test]
    async fn record_session_usage_overflow_saturates() {
        crate::util::test::init_test_stores().await;
        let mut agent = make_agent(vec![]);
        let huge = crate::ChatResponse {
            usage: Some(crate::ProviderUsage {
                input_tokens: Some(u64::MAX),
                output_tokens: Some(u64::MAX),
                ..crate::ProviderUsage::default()
            }),
            ..crate::ChatResponse::default()
        };
        agent.record_session_usage(&huge).await;
        assert_eq!(agent.session.token_length(), Some(u64::MAX));
    }

    /// The LLM-step failure context carries BOTH the run-local tool round and
    /// the session depth (history length + token length, the latter omitted
    /// when unknown) — a resumed 100-round-deep session must not read as
    /// freshly started.
    #[tokio::test]
    async fn llm_step_failure_context_reports_run_round_and_session_depth() {
        crate::util::test::init_test_stores().await;
        let mut agent = make_agent(vec![]);
        agent
            .session
            .push_messages_unpersisted(&[ChatMessage::user("hello"), ChatMessage::assistant("hi")]);
        agent.session.set_token_length(Some(42_110));

        let ctx = llm_step_failure_context(&agent.session, 0);
        assert!(ctx.contains("tool round 0"), "run-local round: {ctx}");
        assert!(ctx.contains("2 messages"), "session depth: {ctx}");
        assert!(ctx.contains("42110 tokens"), "token segment: {ctx}");

        agent.session.set_token_length(None);
        let ctx = llm_step_failure_context(&agent.session, 3);
        assert!(ctx.contains("tool round 3"), "round after increment: {ctx}");
        assert!(ctx.contains("2 messages"), "session depth: {ctx}");
        assert!(
            !ctx.contains("tokens"),
            "None omits the token segment: {ctx}"
        );
    }

    /// An unknown session length (`None` — no successful usage-bearing call
    /// ever recorded) only disables the token trigger; with no images present
    /// it is still a no-op: the check exits before the summarize LLM call. No
    /// provider is installed on purpose — reaching [`Agent::summarize`] would
    /// panic on the unset provider.
    #[tokio::test]
    async fn maybe_summarize_none_and_below_threshold_are_noops() {
        crate::util::test::init_test_stores().await;
        let mut agent = make_agent(vec![]);

        // None (new / pre-migration session): early exit, nothing fires.
        agent.maybe_summarize().await;
        assert_eq!(agent.session.token_length(), None);

        // A real value below the fixed threshold is equally a no-op.
        agent
            .session
            .set_token_length(Some(crate::session::SUMMARIZATION_THRESHOLD / 2));
        agent.maybe_summarize().await;
    }

    // ── Provider input-image rejection strip ────────

    /// The observed provider rejection body (OpenRouter HTTP 400
    /// `data_inspection_failed`, image variant).
    const IMAGE_REJECTION_BODY: &str = r#"{"error":{"message":"Input image data may contain inappropriate content.","code":"data_inspection_failed","type":"invalid_request_error"}}"#;

    /// Same code, text variant — must NOT trigger the strip.
    const TEXT_REJECTION_BODY: &str = r#"{"error":{"message":"Input data may contain inappropriate content.","code":"data_inspection_failed","type":"invalid_request_error"}}"#;

    /// Seed empty model catalogs so the Assistant active-models block renders
    /// nothing and performs no network fetch (hermetic e2e).
    fn seed_empty_catalogs() {
        crate::tools::media_catalog::image::seed_cache(Some(std::sync::Arc::new(
            crate::tools::media_catalog::image::ImageCatalog::default(),
        )));
        crate::tools::media_catalog::video::seed_cache(Some(std::sync::Arc::new(
            crate::tools::media_catalog::video::VideoCatalog::default(),
        )));
    }

    /// A rejected input image must not fail the run: the image is durably
    /// stripped from the most recent user message (replaced by the explanatory
    /// phrase) and the run continues through its normal loop — the retried
    /// call carries the corrected message and the agent answers.
    #[tokio::test]
    #[serial_test::serial(active_models, provider, drain)] // seeds the process-global catalog caches + process-global fake provider + shutdown drain flag
    async fn rejected_input_image_is_stripped_and_run_continues() {
        crate::util::test::init_test_stores().await;
        seed_empty_catalogs();
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());

        let agent_id = "e2e_assistant_image_reject";
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .err_http(400, IMAGE_REJECTION_BODY)
                .ok("The image was rejected by the provider's content check."),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let mut agent = make_agent_with_role(vec![], crate::Role::Assistant);
        agent.agent_id = agent_id.to_string();
        let resp = agent
            .work("[IMAGE:/tmp/photo.png] describe this photo", false)
            .await
            .expect("the run must not fail wholesale on a rejected input image");
        assert_eq!(
            resp,
            "The image was rejected by the provider's content check."
        );

        // The corrected message reached the model: the second request's
        // message list carries the phrase and no image marker in the user
        // message (the Assistant system prompt mentions "[IMAGE:path]" markers
        // literally — the assertion must target the user segment).
        let messages = fake.request_messages.lock().unwrap().clone();
        assert_eq!(messages.len(), 2, "rejected attempt + normal-loop retry");
        assert!(
            messages[0].contains("[IMAGE:/tmp/photo.png]"),
            "first request carried the image"
        );
        let retried_user = messages[1]
            .split('\u{0}')
            .next_back()
            .expect("retried request has a user segment");
        assert!(
            !retried_user.contains("[IMAGE:"),
            "retried user message no longer carries the image"
        );
        assert!(
            retried_user.contains("rejected by the provider's content-inspection check"),
            "retried user message carries the explanatory phrase"
        );
        assert!(
            retried_user.contains("Input image data may contain inappropriate content."),
            "phrase embeds the provider reason"
        );

        // Durable rewrite: the session DB no longer holds the rejected image.
        let history = crate::session::store().load(agent_id).await;
        let last_user = history
            .iter()
            .rev()
            .find(|m| m.role == crate::ChatRole::User)
            .expect("user message exists");
        assert!(
            !last_user.content.contains("[IMAGE:"),
            "rejected image durably removed from the session"
        );
        assert!(
            last_user.content.contains("describe this photo"),
            "user's accompanying text preserved"
        );
        // The user's original text plus the phrase, and NO extra assistant/system
        // message was injected for the rejection (single phrase inside the
        // user's own message).
        assert_eq!(
            history
                .iter()
                .filter(|m| m.role == crate::ChatRole::User)
                .count(),
            1,
            "no separate notification message was added"
        );
    }

    /// A text-content rejection with the same provider code ("Input data ..."
    /// without "image") does not trigger the strip — the run takes the normal
    /// failure path and the image stays in the session.
    #[tokio::test]
    #[serial_test::serial(active_models, provider, drain)] // seeds the process-global catalog caches + process-global fake provider + shutdown drain flag
    async fn text_content_rejection_follows_normal_failure_path() {
        crate::util::test::init_test_stores().await;
        seed_empty_catalogs();
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());

        let agent_id = "e2e_assistant_text_reject";
        let fake = std::sync::Arc::new(FakeProvider::new().err_http(400, TEXT_REJECTION_BODY));
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let mut agent = make_agent_with_role(vec![], crate::Role::Assistant);
        agent.agent_id = agent_id.to_string();
        let result = agent
            .work("[IMAGE:/tmp/photo.png] describe this photo", false)
            .await;
        assert!(
            result.is_err(),
            "text-content rejection must fail the run normally"
        );

        // No strip: the image marker survives in the session.
        let history = crate::session::store().load(agent_id).await;
        let last_user = history
            .iter()
            .rev()
            .find(|m| m.role == crate::ChatRole::User)
            .expect("user message exists");
        assert!(
            last_user.content.contains("[IMAGE:/tmp/photo.png]"),
            "image untouched on a text-content rejection"
        );
    }

    /// After a successful strip, a subsequent failure in the same run does NOT
    /// re-strip: the most recent user message no longer contains image markers,
    /// so the normal failure path applies (no repeated stripping, no infinite
    /// retry loop).
    #[tokio::test]
    #[serial_test::serial(active_models, provider, drain)] // seeds the process-global catalog caches + process-global fake provider + shutdown drain flag
    async fn subsequent_failure_after_strip_takes_normal_failure_path() {
        crate::util::test::init_test_stores().await;
        seed_empty_catalogs();
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());

        let agent_id = "e2e_assistant_second_failure";
        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .err_http(400, IMAGE_REJECTION_BODY)
                .err_http(400, IMAGE_REJECTION_BODY),
        );
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let mut agent = make_agent_with_role(vec![], crate::Role::Assistant);
        agent.agent_id = agent_id.to_string();
        let result = agent
            .work("[IMAGE:/tmp/photo.png] describe this photo", false)
            .await;
        assert!(
            result.is_err(),
            "a second failure after the strip must fail normally"
        );

        let messages = fake.request_messages.lock().unwrap().clone();
        assert_eq!(
            messages.len(),
            2,
            "exactly one strip, then the normal failure"
        );
        let retried_user = messages[1]
            .split('\u{0}')
            .next_back()
            .expect("retried request has a user segment");
        assert!(
            !retried_user.contains("[IMAGE:"),
            "retried user message is already stripped"
        );

        // The message was stripped exactly once (phrase present, no marker).
        let history = crate::session::store().load(agent_id).await;
        let last_user = history
            .iter()
            .rev()
            .find(|m| m.role == crate::ChatRole::User)
            .expect("user message exists");
        assert!(!last_user.content.contains("[IMAGE:"));
        assert!(
            last_user
                .content
                .contains("rejected by the provider's content-inspection check"),
            "phrase present after a single strip"
        );
    }

    /// Collect IMAGE marker data-URIs from user messages — the dedup key for the
    /// read tool's synthetic image injection. Only IMAGE markers are collected;
    /// AUDIO/VIDEO markers and plain text are ignored.
    #[test]
    fn existing_image_marker_values_extracts_image_markers() {
        let history = vec![
            ChatMessage::system("sys"),
            ChatMessage::user("[IMAGE:data:image/jpeg;base64,aaa] see this"),
            ChatMessage::assistant("ok"),
            ChatMessage::user("plain text, no marker"),
            ChatMessage::user("[AUDIO:data:audio/ogg;base64,zzz]"),
        ];
        let set = existing_image_marker_values(&history);
        assert_eq!(
            set.len(),
            1,
            "only IMAGE markers are collected, got: {set:?}"
        );
        assert!(set.contains("data:image/jpeg;base64,aaa"));
    }

    /// `session_image_marker_count` counts DISTINCT `data:image/`-prefixed
    /// IMAGE markers in User-role messages. The gate is prefix-only (no full
    /// raster decode): real PNG data-URIs count, duplicates collapse to one,
    /// while file-path markers, non-IMAGE kinds, and assistant-role messages
    /// do not count.
    #[test]
    fn session_image_marker_count_prefix_gate() {
        let png = crate::util::test::tiny_png_data_uri();
        let history = vec![
            ChatMessage::system("sys"),
            ChatMessage::user(format!("[IMAGE:{png}] first")),
            ChatMessage::user(format!("[IMAGE:{png}] duplicate — same URI")),
            ChatMessage::user("[IMAGE:/local/path.png] file path"),
            ChatMessage::user("[AUDIO:data:audio/ogg;base64,zzz]"),
            ChatMessage::assistant(format!("[IMAGE:{png}] assistant role must not count")),
        ];
        assert_eq!(
            session_image_marker_count(&history),
            1,
            "only the distinct native data-URI IMAGE marker in User messages counts"
        );
    }

    /// The trigger decision is asymmetric by design: strict `>` for the token
    /// threshold, `>=` for the image count; the token trigger reports as the
    /// reason when both fire (both still lead to one summarize).
    #[test]
    fn summarization_trigger_decides_reason() {
        use crate::session::{SUMMARIZATION_IMAGE_COUNT, SUMMARIZATION_THRESHOLD};
        let nine = SUMMARIZATION_IMAGE_COUNT - 1;
        assert_eq!(summarization_trigger(None, nine), None);
        assert_eq!(
            summarization_trigger(None, SUMMARIZATION_IMAGE_COUNT),
            Some("image count")
        );
        assert_eq!(
            summarization_trigger(Some(SUMMARIZATION_THRESHOLD), 0),
            None
        );
        assert_eq!(
            summarization_trigger(Some(SUMMARIZATION_THRESHOLD + 1), 0),
            Some("token threshold")
        );
        assert_eq!(
            summarization_trigger(Some(SUMMARIZATION_THRESHOLD + 1), SUMMARIZATION_IMAGE_COUNT,),
            Some("token threshold")
        );
        assert_eq!(summarization_trigger(Some(1), nine), None);
        assert_eq!(
            summarization_trigger(Some(1), SUMMARIZATION_IMAGE_COUNT),
            Some("image count")
        );
    }

    /// `commit_tool_results` injects the synthetic image user message AFTER the
    /// round's tool-result block (preserving tool-message contiguity) and dedups
    /// a repeat read of an already-attached image.
    #[tokio::test]
    #[expect(clippy::too_many_lines)]
    async fn commit_tool_results_injects_image_after_tool_results_with_dedup() {
        crate::util::test::init_test_stores().await;

        let mut agent = make_agent(vec![]);
        // Seed a prior round: an image with this data-URI is already attached.
        agent.session.push_messages_unpersisted(&[ChatMessage::user(
            "[IMAGE:data:image/jpeg;base64,prior]",
        )]);
        // Mirror the emission-time durability: the assistant frame with the tool
        // calls is persisted (in-memory here) before the results commit.
        agent
            .session
            .push_assistant("assistant with tool_calls".to_string());

        let tool_calls = vec![
            ToolCall {
                id: "call1".into(),
                name: "read".into(),
                arguments: serde_json::json!({"path": "a.png"}),
            },
            ToolCall {
                id: "call2".into(),
                name: "read".into(),
                arguments: serde_json::json!({"path": "b.png"}),
            },
        ];
        let outcomes = vec![
            ToolExecutionOutcome {
                output: "Read image file /a.png (1x1, PNG).".into(),
                success: true,
                image_payloads: vec![ImagePayload {
                    path: "/a.png".into(),
                    data_uri: "data:image/jpeg;base64,prior".into(),
                    width: 1,
                    height: 1,
                    format: "PNG".into(),
                    recovery_note: None,
                    source: crate::tools::ImagePayloadSource::Read,
                }],
                text_is_content: false,
                suspended: false,
                ends_turn: false,
            },
            ToolExecutionOutcome {
                output: "Read image file /b.png (1x1, PNG).".into(),
                success: true,
                image_payloads: vec![ImagePayload {
                    path: "/b.png".into(),
                    data_uri: "data:image/jpeg;base64,fresh".into(),
                    width: 1,
                    height: 1,
                    format: "PNG".into(),
                    recovery_note: None,
                    source: crate::tools::ImagePayloadSource::Read,
                }],
                text_is_content: false,
                suspended: false,
                ends_turn: false,
            },
        ];

        agent
            .commit_tool_results(&tool_calls, outcomes)
            .await
            .expect("commit_tool_results must succeed");

        let history = agent.session.history();
        let roles: Vec<crate::ChatRole> = history.iter().map(|m| m.role).collect();
        // Order: [prior user, assistant(tool_calls), tool_result(call1),
        // tool_result(call2), user(fresh)] — the fresh image is injected AFTER
        // both tool results, and the 'prior' image is NOT re-injected.
        assert_eq!(
            roles,
            vec![
                crate::ChatRole::User,
                crate::ChatRole::Assistant,
                crate::ChatRole::Tool,
                crate::ChatRole::Tool,
                crate::ChatRole::User,
            ],
            "unexpected message ordering: {roles:?}"
        );

        let image_users: Vec<&str> = history
            .iter()
            .filter(|m| m.role == crate::ChatRole::User && m.content.contains("[IMAGE:data:"))
            .map(|m| m.content.as_str())
            .collect();
        assert_eq!(
            image_users.len(),
            2,
            "prior + fresh image messages, got: {image_users:?}"
        );
        assert!(
            image_users.contains(&"[IMAGE:data:image/jpeg;base64,prior]"),
            "prior image survives in history: {image_users:?}"
        );
        assert!(
            image_users
                .iter()
                .any(|s| s.contains("[IMAGE:data:image/jpeg;base64,fresh]")),
            "fresh image injected once: {image_users:?}"
        );
        let fresh_msg = image_users
            .iter()
            .find(|s| s.contains("base64,fresh"))
            .expect("fresh image message present");
        assert!(
            fresh_msg.starts_with("<injected-tool-result-image>\n[IMAGE:data:image/jpeg;base64,"),
            "injected image carries the provenance tag: {fresh_msg:?}"
        );
        // Dedup: the repeat read of the already-attached 'prior' image is not
        // re-injected; the fresh image is injected exactly once.
        let fresh_count = history
            .iter()
            .filter(|m| m.role == crate::ChatRole::User && m.content.contains("base64,fresh"))
            .count();
        assert_eq!(fresh_count, 1, "a fresh image is injected exactly once");
        // The persisted tool-result text is built from the payload metadata (no
        // brittle string rewrite): the deduped repeat read returns the
        // 'already attached' reference and the fresh read returns the 'attached'
        // wording. Tool-result content is a JSON envelope (`{"tool_call_id",
        // "content"}`), so parse out the `content` field.
        let tool_results: Vec<String> = history
            .iter()
            .filter(|m| m.role == crate::ChatRole::Tool)
            .map(|m| {
                let v: serde_json::Value =
                    serde_json::from_str(&m.content).expect("tool result is valid JSON");
                crate::util::json::get_str(&v, "content")
                    .expect("tool result has content")
                    .to_string()
            })
            .collect();
        assert_eq!(
            tool_results,
            vec![
                "Read image file /a.png (1x1, PNG). Image content is already attached to the conversation as a native image.",
                "Read image file /b.png (1x1, PNG). Image content attached to the conversation as a native image.",
            ],
            "unexpected tool-result text: {tool_results:?}"
        );
    }

    /// Two identical image reads within the SAME round (same data-URI) are
    /// deduped by `seen_data_uris`: only the first is injected; the second
    /// returns the 'already-attached' reference.
    #[tokio::test]
    async fn commit_tool_results_dedups_identical_reads_in_same_round() {
        crate::util::test::init_test_stores().await;

        let mut agent = make_agent(vec![]);

        let tool_calls = vec![
            ToolCall {
                id: "callA".into(),
                name: "read".into(),
                arguments: serde_json::json!({"path": "a.png"}),
            },
            ToolCall {
                id: "callB".into(),
                name: "read".into(),
                arguments: serde_json::json!({"path": "a.png"}),
            },
        ];
        let outcomes = vec![
            ToolExecutionOutcome {
                output: "Read image file /a.png (PNG).".into(),
                success: true,
                image_payloads: vec![ImagePayload {
                    path: "/a.png".into(),
                    data_uri: "data:image/jpeg;base64,same".into(),
                    width: 1,
                    height: 1,
                    format: "PNG".into(),
                    recovery_note: None,
                    source: crate::tools::ImagePayloadSource::Read,
                }],
                text_is_content: false,
                suspended: false,
                ends_turn: false,
            },
            ToolExecutionOutcome {
                output: "Read image file /a.png (PNG).".into(),
                success: true,
                image_payloads: vec![ImagePayload {
                    path: "/a.png".into(),
                    data_uri: "data:image/jpeg;base64,same".into(),
                    width: 1,
                    height: 1,
                    format: "PNG".into(),
                    recovery_note: None,
                    source: crate::tools::ImagePayloadSource::Read,
                }],
                text_is_content: false,
                suspended: false,
                ends_turn: false,
            },
        ];

        agent
            .commit_tool_results(&tool_calls, outcomes)
            .await
            .expect("commit_tool_results must succeed");

        let history = agent.session.history();
        let image_users: Vec<&str> = history
            .iter()
            .filter(|m| {
                m.role == crate::ChatRole::User
                    && m.content.contains("[IMAGE:data:image/jpeg;base64,same]")
            })
            .map(|m| m.content.as_str())
            .collect();
        assert_eq!(
            image_users.len(),
            1,
            "identical reads in one round inject exactly once, got: {image_users:?}"
        );

        // The first tool result claims a fresh attachment; the second returns a
        // reference (already attached).
        let tool_results: Vec<String> = history
            .iter()
            .filter(|m| m.role == crate::ChatRole::Tool)
            .map(|m| {
                let v: serde_json::Value =
                    serde_json::from_str(&m.content).expect("tool result is valid JSON");
                crate::util::json::get_str(&v, "content")
                    .expect("tool result has content")
                    .to_string()
            })
            .collect();
        assert_eq!(tool_results.len(), 2, "two tool results persisted");
        assert!(
            tool_results[0].contains("attached to the conversation as a native image")
                && !tool_results[0].contains("already"),
            "first read claims a fresh attachment: {tool_results:?}"
        );
        assert!(
            tool_results[1].contains("already attached to the conversation"),
            "second read returns a reference: {tool_results:?}"
        );
    }

    /// Every fresh image of one round lands in a SINGLE synthetic user message,
    /// so a rejected page from any call of the round is clearable —
    /// [`crate::util::injected_image_user_message`].
    #[tokio::test]
    async fn commit_tool_results_injects_one_image_message_per_round() {
        crate::util::test::init_test_stores().await;

        let mut agent = make_agent(vec![]);
        let tool_calls = vec![
            ToolCall {
                id: "callA".into(),
                name: "read".into(),
                arguments: serde_json::json!({"path": "a.pdf"}),
            },
            ToolCall {
                id: "callB".into(),
                name: "read".into(),
                arguments: serde_json::json!({"path": "b.pdf"}),
            },
        ];
        let payload = |suffix: &str| ImagePayload {
            path: format!("/tmp/{suffix}.jpg"),
            data_uri: format!("data:image/jpeg;base64,{suffix}"),
            width: 1,
            height: 1,
            format: "JPEG".into(),
            recovery_note: None,
            source: crate::tools::ImagePayloadSource::Read,
        };
        let outcomes = vec![
            ToolExecutionOutcome {
                output: "Read image file /tmp/a.jpg.".into(),
                success: true,
                image_payloads: vec![payload("a1"), payload("a2")],
                text_is_content: false,
                suspended: false,
                ends_turn: false,
            },
            ToolExecutionOutcome {
                output: "Read image file /tmp/b.jpg.".into(),
                success: true,
                image_payloads: vec![payload("b1")],
                text_is_content: false,
                suspended: false,
                ends_turn: false,
            },
        ];

        agent
            .commit_tool_results(&tool_calls, outcomes)
            .await
            .expect("commit_tool_results must succeed");

        let history = agent.session.history();
        let image_messages: Vec<&str> = history
            .iter()
            .filter(|m| m.role == crate::ChatRole::User && m.content.contains("[IMAGE:"))
            .map(|m| m.content.as_str())
            .collect();
        assert_eq!(
            image_messages.len(),
            1,
            "one message for the whole round, got: {image_messages:?}"
        );
        let message = image_messages[0];
        assert!(
            message.starts_with("<injected-tool-result-image>"),
            "the batch keeps the provenance tag: {message:?}"
        );
        for suffix in ["a1", "a2", "b1"] {
            assert!(
                message.contains(&format!("[IMAGE:data:image/jpeg;base64,{suffix}]")),
                "every fresh image of the round is in the batch: {message:?}"
            );
        }
    }

    /// The content side of the same invariant: a result whose flag says its text
    /// is content — a converted document's extracted text — is neither replaced
    /// by an annotation nor read as a claim, so an `[IMAGE:path]` marker inside
    /// it stays literal text and injects nothing.
    #[tokio::test]
    async fn commit_tool_results_leaves_a_marker_in_content_text_alone() {
        crate::util::test::init_test_stores().await;

        // A real on-disk raster, so derivation would succeed if it were allowed.
        let dir = tempfile::TempDir::new().expect("tempdir");
        let png_path = dir.path().join("page.png");
        std::fs::write(&png_path, crate::util::test::noisy_png(4, 4)).expect("write png");
        let abs = std::fs::canonicalize(&png_path).expect("canonicalize");

        let mut agent = make_agent(vec![]);
        let marker = format!("[IMAGE:{}]", abs.display());
        let body = format!("[scan.pdf: extracted text follows]\n\nsee {marker} in the report");
        let tool_calls = vec![ToolCall {
            id: "call1".into(),
            name: "read".into(),
            arguments: serde_json::json!({"path": "scan.pdf"}),
        }];
        let outcomes = vec![ToolExecutionOutcome {
            output: body.clone(),
            success: true,
            image_payloads: Vec::new(),
            text_is_content: true,
            suspended: false,
            ends_turn: false,
        }];

        agent
            .commit_tool_results(&tool_calls, outcomes)
            .await
            .expect("commit_tool_results must succeed");

        let history = agent.session.history();
        let tool_result = history
            .iter()
            .find(|m| m.role == crate::ChatRole::Tool)
            .map(|m| {
                let v: serde_json::Value =
                    serde_json::from_str(&m.content).expect("tool result is valid JSON");
                crate::util::json::get_str(&v, "content")
                    .expect("tool result has content")
                    .to_string()
            })
            .expect("the tool result is persisted");
        assert!(
            tool_result.contains(&marker),
            "a marker inside content text stays literal: {tool_result:?}"
        );
        assert!(
            !history
                .iter()
                .any(|m| m.role == crate::ChatRole::User && m.content.contains("[IMAGE:")),
            "nothing is derived from a marker in content text: {history:?}"
        );
    }

    /// A converted document's images SUPPLEMENT its text: the annotations are
    /// appended to the tool result, so the extracted text (and the converter's
    /// notes) survive into the persisted round.
    #[tokio::test]
    async fn commit_tool_results_appends_annotations_for_content_text() {
        crate::util::test::init_test_stores().await;

        let mut agent = make_agent(vec![]);
        let tool_calls = vec![ToolCall {
            id: "call1".into(),
            name: "read".into(),
            arguments: serde_json::json!({"path": "scan.pdf"}),
        }];
        let outcomes = vec![ToolExecutionOutcome {
            output: "[scan.pdf: no text could be extracted — the pages were provided as images]"
                .into(),
            success: true,
            image_payloads: vec![ImagePayload {
                path: "/tmp/read_1/page_1.jpg".into(),
                data_uri: "data:image/jpeg;base64,page1".into(),
                width: 800,
                height: 1000,
                format: "JPEG".into(),
                recovery_note: None,
                source: crate::tools::ImagePayloadSource::Generated,
            }],
            text_is_content: true,
            suspended: false,
            ends_turn: false,
        }];

        agent
            .commit_tool_results(&tool_calls, outcomes)
            .await
            .expect("commit_tool_results must succeed");

        let history = agent.session.history();
        let tool_result = history
            .iter()
            .find(|m| m.role == crate::ChatRole::Tool)
            .map(|m| {
                let v: serde_json::Value =
                    serde_json::from_str(&m.content).expect("tool result is valid JSON");
                crate::util::json::get_str(&v, "content")
                    .expect("tool result has content")
                    .to_string()
            })
            .expect("the tool result is persisted");
        assert_eq!(
            tool_result,
            "[scan.pdf: no text could be extracted — the pages were provided as images]\n\
             Generated image file /tmp/read_1/page_1.jpg (800x1000, JPEG). Image content attached \
             to the conversation as a native image.",
            "the answer keeps its text and gains the image annotation: {tool_result:?}"
        );
        assert!(
            history.iter().any(|m| m.role == crate::ChatRole::User
                && m.content.contains("[IMAGE:data:image/jpeg;base64,page1]")),
            "the page is injected as a synthetic user message"
        );
    }

    #[tokio::test]
    async fn commit_tool_results_derives_generated_image_and_tags_it() {
        crate::util::test::init_test_stores().await;

        // A real on-disk raster at an absolute path so the derivation can compress it.
        let dir = tempfile::TempDir::new().expect("tempdir");
        let png_path = dir.path().join("generated.png");
        std::fs::write(&png_path, crate::util::test::noisy_png(4, 4)).expect("write png");
        let abs = std::fs::canonicalize(&png_path).expect("canonicalize");

        let tool = Box::new(MediaTestTool {
            name: "image_gen",
            marker: "[IMAGE:",
        }) as Box<dyn Tool>;
        let mut agent = make_agent(vec![tool]);

        let marker = format!("[IMAGE:{}]", abs.display());
        let tool_calls = vec![ToolCall {
            id: "callgen".into(),
            name: "image_gen".into(),
            arguments: serde_json::json!({}),
        }];
        // `MediaTestTool` does not override the hook, so this round takes the
        // trait default: a media tool's marker line is a claim about its image,
        // not content.
        let outcomes = vec![ToolExecutionOutcome {
            output: marker.clone(),
            success: true,
            image_payloads: Vec::new(),
            text_is_content: false,
            suspended: false,
            ends_turn: false,
        }];

        // User delivery via the marker in the raw output is preserved — read
        // before the commit, which consumes the outcomes.
        let media = extract_media_from_outcomes(&agent.tools, &tool_calls, &outcomes);
        assert_eq!(
            media,
            vec![("[IMAGE:", abs.display().to_string())],
            "marker preserved for user delivery: {media:?}"
        );

        agent
            .commit_tool_results(&tool_calls, outcomes)
            .await
            .expect("commit_tool_results must succeed");

        let history = agent.session.history();
        // The derived image is injected as a synthetic user message AFTER the tool result.
        let image_users: Vec<&str> = history
            .iter()
            .filter(|m| {
                m.role == crate::ChatRole::User
                    && m.content.contains("[IMAGE:data:image/jpeg;base64,")
            })
            .map(|m| m.content.as_str())
            .collect();
        assert_eq!(
            image_users.len(),
            1,
            "generated image injected once: {image_users:?}"
        );
        assert!(
            image_users[0]
                .starts_with("<injected-tool-result-image>\n[IMAGE:data:image/jpeg;base64,"),
            "injected image carries the provenance tag: {image_users:?}"
        );

        // The tool-result uses the Generated verb, not "Read".
        let tool_results: Vec<String> = history
            .iter()
            .filter(|m| m.role == crate::ChatRole::Tool)
            .map(|m| {
                let v: serde_json::Value =
                    serde_json::from_str(&m.content).expect("tool result JSON");
                crate::util::json::get_str(&v, "content")
                    .expect("content")
                    .to_string()
            })
            .collect();
        assert_eq!(tool_results.len(), 1);
        assert!(
            tool_results[0].starts_with("Generated image file"),
            "generated annotation: {tool_results:?}"
        );
        assert!(
            !tool_results[0].starts_with("Read image file"),
            "must not be a Read annotation: {tool_results:?}"
        );
    }

    // ── Universal resume-completion ──────────────────────────────────────

    /// The resume-completion path batches a re-executed round exactly like the
    /// commit path: two calls that each produce images still inject ONE
    /// synthetic user message, so the provider-rejection recovery — which
    /// rewrites only the most recent message — can clear every image the
    /// rejected request carried.
    #[tokio::test]
    async fn complete_pending_tool_calls_injects_one_image_message_per_round() {
        crate::util::test::init_test_stores().await;
        let dir = tempfile::tempdir().unwrap();
        // Different sizes, so the two pages hash to different data URIs and
        // neither is deduped away as an already-attached image.
        for (page, size) in [("page-a.png", 4), ("page-b.png", 5)] {
            std::fs::write(
                dir.path().join(page),
                crate::util::test::noisy_png(size, size),
            )
            .unwrap();
        }
        let ws = crate::Workspace::from_path(dir.path());

        let calls: Vec<crate::ToolCall> = ["page-a.png", "page-b.png"]
            .iter()
            .enumerate()
            .map(|(index, page)| crate::ToolCall {
                id: format!("call_img_{index}"),
                name: "read".to_string(),
                arguments: serde_json::json!({ "path": page }),
            })
            .collect();
        let frame = crate::providers::reasoning::assistant_replay_payload(Some(""), &calls, None)
            .to_string();
        let mut session = Session::default();
        session
            .persist_messages(
                "test-resume-image-batch",
                &[
                    ChatMessage::user("read both images"),
                    ChatMessage::assistant(frame),
                ],
            )
            .await
            .unwrap();

        let mut agent = make_agent_on(
            vec![Box::new(crate::tools::ReadTool::general())],
            "test-resume-image-batch",
            ws,
        );
        agent.session = session;
        assert!(
            agent.complete_pending_tool_calls().await.unwrap(),
            "both dangling calls settle a result"
        );

        let history = agent.session.history();
        let image_messages: Vec<&str> = history
            .iter()
            .filter(|m| m.role == crate::ChatRole::User && m.content.contains("[IMAGE:"))
            .map(|m| m.content.as_str())
            .collect();
        assert_eq!(
            image_messages.len(),
            1,
            "one message for the whole re-executed round, got: {image_messages:?}"
        );
        assert_eq!(
            image_messages[0]
                .matches("[IMAGE:data:image/jpeg;base64,")
                .count(),
            2,
            "both pages of the round are in the batch: {:?}",
            image_messages[0]
        );
    }

    /// (c) `complete_pending_tool_calls` re-executes a non-durable dangling call
    /// and settles the real output as its tool result with the ORIGINAL call id,
    /// contiguously after the frame.
    #[tokio::test]
    async fn complete_pending_tool_calls_reexecutes_non_durable_call() {
        crate::util::test::init_test_stores().await;
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("seed.txt"), "completion-marker\n").unwrap();
        let ws = crate::Workspace::from_path(dir.path());

        // Emission-time frame: the caller's session durably records the read
        // call; its result is absent (the "dangling" state).
        let mut session = Session::default();
        let frame = crate::providers::reasoning::assistant_replay_payload(
            Some(""),
            &[crate::ToolCall {
                id: "call_read_c".to_string(),
                name: "read".to_string(),
                arguments: serde_json::json!({"path": "seed.txt"}),
            }],
            None,
        )
        .to_string();
        session
            .persist_messages(
                "test-read-reexec",
                &[
                    ChatMessage::user("read the file"),
                    ChatMessage::assistant(frame),
                ],
            )
            .await
            .unwrap();

        let mut agent = make_agent_on(
            vec![Box::new(crate::tools::ReadTool::general())],
            "test-read-reexec",
            ws,
        );
        agent.session = session;
        let settled = agent.complete_pending_tool_calls().await.unwrap();
        assert!(settled, "a re-executed non-durable call settles a result");

        // The result sits contiguous after the frame with the ORIGINAL call id.
        let history = agent.session.history();
        let roles: Vec<crate::ChatRole> = history.iter().map(|m| m.role).collect();
        assert_eq!(
            roles,
            vec![
                crate::ChatRole::User,
                crate::ChatRole::Assistant,
                crate::ChatRole::Tool
            ],
            "result contiguous after the frame: {roles:?}"
        );
        let payload: crate::ToolResultPayload = serde_json::from_str(&history[2].content).unwrap();
        assert_eq!(
            payload.tool_call_id, "call_read_c",
            "re-execution keeps the ORIGINAL call id"
        );
        assert!(
            payload.content.contains("completion-marker"),
            "real tool output recorded: {}",
            payload.content
        );
        assert!(agent.session.pending_tool_frame().is_none());
    }

    /// (d) Full drain lifecycle: a sync analyze dispatch under an active drain
    /// leaves the frame durably persisted with NO tool-result row and the
    /// caller-owned job `launched` (the result is absent); after `drain_clear`,
    /// the completion resumes the durable job — a reconstructable Done slot is
    /// replayed (zero LLM calls), the consolidated tool result settles
    /// contiguously after the frame, and only then is the resumed job
    /// terminalized.
    #[tokio::test]
    #[serial_test::serial(provider, drain)] // serializes the process-global fake provider (providers::PROVIDER) + shutdown drain flag
    async fn drain_mid_sync_analyze_leaves_call_dangling_then_completion_resumes() {
        let fake = std::sync::Arc::new(crate::util::test::FakeProvider::new());
        let _seam = crate::util::test::install_retry_seam_dyn(fake.clone());
        crate::util::test::init_test_stores().await;
        let ws = crate::workspace::test_ws("/tmp/test_ws_drain_analyze");
        let pin = "drain_sync_analyze_pin";
        let conn = &crate::session::store().conn;

        // Emission-time frame: the caller's session durably records the analyze
        // call BEFORE the drain-cut execution leaves its result absent.
        let mut session = Session::default();
        let frame = crate::providers::reasoning::assistant_replay_payload(
            Some(""),
            &[crate::ToolCall {
                id: "call_analyze_d".to_string(),
                name: "analyze".to_string(),
                arguments: serde_json::json!({"analyze": "analyze this"}),
            }],
            None,
        )
        .to_string();
        session
            .persist_messages(
                pin,
                &[
                    ChatMessage::user("analyze this"),
                    ChatMessage::assistant(frame),
                ],
            )
            .await
            .unwrap();

        // Drive the sync analyze dispatch under the caller's task-local pin with
        // an active drain: it leaves the durable job launched (DrainCut).
        crate::shutdown::drain_begin();
        let tool = crate::tools::analyze::AnalyzeTool::new(
            crate::tools::analyze::DispatchMode::Sync,
            crate::Role::Engineer,
        );
        let res = crate::agent::CURRENT_TOOL_AGENT_ID
            .scope(Some(pin.to_string()), async {
                tool.execute(&ws, serde_json::json!({"analyze": "analyze this"}))
                    .await
            })
            .await;
        crate::shutdown::drain_clear();
        let err = res.expect_err("drain must cut the sync analyze dispatch");
        assert!(
            err.downcast_ref::<crate::tools::CallSuspended>().is_some(),
            "CallSuspended carrier expected: {err:#}"
        );

        // The frame row is persisted, NO tool-result row, job launched caller-owned.
        let jobs = conn
            .query(
                "SELECT id, status, caller_agent_id FROM jobs WHERE caller_agent_id = ?1 AND kind = 'analyze'",
                crate::db::params![pin],
            )
            .await
            .unwrap();
        assert_eq!(jobs.len(), 1, "one launched analyze job");
        assert_eq!(jobs[0].get::<String>(1).unwrap(), "launched");
        assert_eq!(
            jobs[0].get::<String>(2).unwrap(),
            pin,
            "job is caller-owned by the session pin"
        );
        let job_id = jobs[0].get::<String>(0).unwrap();
        let session_rows = conn
            .query(
                "SELECT role FROM sessions WHERE agent_id = ?1 ORDER BY id",
                crate::db::params![pin],
            )
            .await
            .unwrap();
        let roles: Vec<String> = session_rows
            .iter()
            .map(|r| r.get::<String>(0).unwrap())
            .collect();
        assert_eq!(
            roles,
            vec!["user", "assistant"],
            "frame persisted with NO tool-result row: {roles:?}"
        );

        // Simulate the durable checkpoint: exactly one analyst slot reconstructed
        // as Done (its outcome) while the other slots produced no valid response.
        let roster = crate::jobs::list_agents_for_job(conn, &job_id)
            .await
            .unwrap();
        assert!(
            roster.len() >= 2,
            "analyze round spawns multiple analysts: {}",
            roster.len()
        );
        for (i, row) in roster.iter().enumerate() {
            let outcome = if i == 0 { "ANALYST_RAW" } else { "" };
            crate::jobs::write_agent_outcome(
                conn,
                &job_id,
                &row.agent_id,
                crate::jobs::RowStatus::Done,
                Some(outcome),
            )
            .await
            .unwrap();
        }

        // Run the completion: it resumes the durable job (Done slot replayed)
        // and settles the consolidated result after the frame, then
        // terminalizes the resumed job.
        let mut agent = make_agent_on(vec![], pin, ws);
        agent.session = session;
        let settled = agent.complete_pending_tool_calls().await.unwrap();
        assert!(settled, "resumed durable job settles a result");

        // The resumed job is terminalized; zero LLM calls were made.
        let jobs = conn
            .query(
                "SELECT id FROM jobs WHERE id = ?1",
                crate::db::params![job_id.clone()],
            )
            .await
            .unwrap();
        assert!(jobs.is_empty(), "resumed job must be terminalized");
        assert!(
            fake.request_fingerprints.lock().unwrap().is_empty(),
            "replaying a Done slot must not call the model"
        );

        // Tool result contiguous after the frame (in-memory + durable).
        let history = agent.session.history();
        let roles: Vec<crate::ChatRole> = history.iter().map(|m| m.role).collect();
        assert_eq!(
            roles,
            vec![
                crate::ChatRole::User,
                crate::ChatRole::Assistant,
                crate::ChatRole::Tool
            ],
            "tool result after the frame: {roles:?}"
        );
        let payload: crate::ToolResultPayload = serde_json::from_str(&history[2].content).unwrap();
        assert_eq!(payload.tool_call_id, "call_analyze_d");
        assert!(
            payload.content.contains("ANALYST_RAW"),
            "{}",
            payload.content
        );
        let pending_jobs = conn
            .query(
                "SELECT id FROM pending_jobs WHERE id = ?1",
                crate::db::params![job_id],
            )
            .await
            .unwrap();
        assert!(pending_jobs.is_empty(), "no envelope pending after resume");
    }

    /// (e) Two same-kind (analyze) calls in one dangling frame bind to the two
    /// OLDEST matching caller-owned jobs (rposition — jobs are newest-first,
    /// frame calls are in dispatch order), so the first frame call carries the
    /// older job's result and the second the newer; each resumed job is
    /// terminalized and its checkpointed outcome settles against its own call
    /// id. A THIRD launched job for the pin that binds no call stays launched
    /// (unfinished jobs are never deleted except by explicit abandon).
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn complete_pending_tool_calls_binds_same_kind_calls_to_distinct_jobs() {
        let fake = std::sync::Arc::new(crate::util::test::FakeProvider::new());
        let _seam = crate::util::test::install_retry_seam_dyn(fake.clone());
        crate::util::test::init_test_stores().await;
        let ws = crate::workspace::test_ws("/tmp/test_ws_two_analyze_jobs");
        let pin = "two_analyze_jobs_pin";
        let conn = &crate::session::store().conn;

        // Caller session with a TWO-call analyze frame (both ids dangling).
        let mut session = Session::default();
        let frame = assistant_replay_payload(
            Some(""),
            &[
                crate::ToolCall {
                    id: "call_analyze_g1".to_string(),
                    name: "analyze".to_string(),
                    arguments: serde_json::json!({"analyze": "analyze task one"}),
                },
                crate::ToolCall {
                    id: "call_analyze_g2".to_string(),
                    name: "analyze".to_string(),
                    arguments: serde_json::json!({"analyze": "analyze task two"}),
                },
            ],
            None,
        )
        .to_string();
        session
            .persist_messages(
                pin,
                &[
                    ChatMessage::user("analyze this"),
                    ChatMessage::assistant(frame),
                ],
            )
            .await
            .unwrap();

        // Backdate nothing: the gate is gone. Seed THREE caller-owned analyze
        // jobs, each with an all-Done roster slot (distinct stored outcomes)
        // so each resume core replays Terminal with zero LLM calls. The two
        // frame calls bind the two OLDEST jobs (first call →
        // `two_analyze_job_0`, second → `two_analyze_job_1`);
        // `two_analyze_job_2` binds no call and stays launched.
        let jobs: [(&str, &str); 3] = [
            ("two_analyze_job_0", "RESULT_ONE"),
            ("two_analyze_job_1", "RESULT_TWO"),
            ("two_analyze_job_2", "RESULT_THREE"),
        ];
        for (i, (job_id, outcome)) in jobs.iter().copied().enumerate() {
            let task = format!("analyze task {i}");
            let analyst_id = format!("{job_id}_analyst");
            crate::jobs::spawn_job(
                conn,
                job_id,
                &task,
                &ws.name,
                "caller-user",
                "telegram",
                crate::Role::Engineer,
                &[crate::jobs::NewAgent {
                    agent_id: analyst_id.clone(),
                    kind: crate::jobs::AgentKind::Analyst,
                    idx: Some(0),
                    task: task.clone(),
                }],
                &crate::jobs::SpawnChild::Analyze,
                Some(pin),
            )
            .await
            .unwrap();
            crate::jobs::write_agent_outcome(
                conn,
                job_id,
                &analyst_id,
                crate::jobs::RowStatus::Done,
                Some(outcome),
            )
            .await
            .unwrap();
            // Distinct, strictly-increasing created_at so the rposition
            // newest-first binding is deterministic at second precision.
            let created = format!("2024-01-0{}T00:00:00+00:00", i + 2);
            conn.execute(
                "UPDATE jobs SET created_at = ?1 WHERE id = ?2",
                crate::db::params![created, job_id],
            )
            .await
            .unwrap();
        }

        // Run the completion: both frame calls are resumed (one per call,
        // DISTINCT — the OLDEST first), the two bound jobs terminalized, and
        // the two results settled with their own call ids.
        let mut agent = make_agent_on(vec![], pin, ws);
        agent.session = session;
        let settled = agent.complete_pending_tool_calls().await.unwrap();
        assert!(settled, "two resumed jobs settle results");

        assert!(
            fake.request_fingerprints.lock().unwrap().is_empty(),
            "replaying Done slots must not call the model"
        );
        assert!(agent.session.pending_tool_frame().is_none());

        // Only the two bound jobs are terminalized; the unbound third job
        // stays launched (no orphan sweep — unfinished jobs survive unless
        // explicitly abandoned).
        let jobs = conn
            .query(
                "SELECT id FROM jobs WHERE caller_agent_id = ?1 AND kind = 'analyze' AND status = 'launched'",
                crate::db::params![pin],
            )
            .await
            .unwrap();
        assert_eq!(jobs.len(), 1, "only the unbound job remains launched");
        assert_eq!(jobs[0].get::<String>(0).unwrap(), "two_analyze_job_2");

        // Both results settled with the frame's ORIGINAL call ids and the
        // per-call mapping is exact: the FIRST frame call (call_analyze_g1)
        // carries the OLDEST job's result (RESULT_ONE), the second
        // (call_analyze_g2) the newer job's (RESULT_TWO) — rposition binding,
        // not set equality.
        let history = agent.session.history();
        let mut per_call: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        for msg in history {
            if msg.role != crate::ChatRole::Tool {
                continue;
            }
            let payload: crate::ToolResultPayload = serde_json::from_str(&msg.content).unwrap();
            per_call.insert(payload.tool_call_id, payload.content);
        }
        assert_eq!(per_call.len(), 2, "both calls settled");
        assert_eq!(
            per_call.get("call_analyze_g1").map(String::as_str),
            Some("RESULT_ONE"),
            "first frame call binds the OLDEST job"
        );
        assert_eq!(
            per_call.get("call_analyze_g2").map(String::as_str),
            Some("RESULT_TWO"),
            "second frame call binds the newer job"
        );
    }

    // ── Run-end cleanup guard ────────────────────────────────────────

    /// Seed a spill file owned by a fresh test-only agent id, plus a run
    /// session tracker holding one name. The temp dir is returned so it
    /// outlives the guard: only the guard may reclaim the spill file.
    async fn seed_run_owned_state(
        agent_id: &str,
    ) -> (
        tempfile::TempDir,
        std::path::PathBuf,
        std::sync::Arc<crate::tools::chrome::ChromeRunSessions>,
    ) {
        let dir = tempfile::tempdir().unwrap();
        let spill = dir.path().join("spill.txt");
        std::fs::write(&spill, "spilled output").unwrap();
        CURRENT_TOOL_AGENT_ID
            .scope(Some(agent_id.to_string()), async {
                crate::tools::shell::record_spill_owner(spill.clone());
            })
            .await;
        // The run's own tracker (`for_run`, not `default`), holding a name the way a
        // `ChromeTool` dispatch would.
        let sessions = crate::tools::chrome::ChromeRunSessions::for_run(agent_id);
        sessions.track(&format!("{}default", sessions.namespace()));
        (dir, spill, sessions)
    }

    /// A run whose future is dropped — a round/research deadline abort or a
    /// panic, the paths that never reach a trailing statement — still reclaims
    /// its spill files and hands its chrome sessions to the release queue.
    #[tokio::test]
    #[serial_test::serial(chrome_release)]
    async fn run_end_guard_cleans_up_a_dropped_run() {
        let agent_id = format!("run-end-guard-{:016x}", rand::random::<u64>());
        let (_dir, spill, sessions) = seed_run_owned_state(&agent_id).await;
        chrome_release::clear_pending_releases();
        // The hand-off persists its record, and this test has no store of its own.
        let _no_store = chrome_release::no_release_store();

        drop(RunEndCleanup::new(
            agent_id,
            std::sync::Arc::clone(&sessions),
        ));

        assert!(!spill.exists(), "the run's spill file is reclaimed");
        assert_eq!(
            chrome_release::pending_names_and_attempts(),
            vec![(vec![format!("{}default", sessions.namespace())], 0)],
            "the ended run handed its session over for release"
        );
        chrome_release::clear_pending_releases();
    }

    /// The run-end decision wired to the guard: every end hands its sessions over
    /// (the dropped-run test covers that half), and the ends that
    /// `chrome_release::holds_run_end` names hold them back.
    #[tokio::test]
    #[serial_test::serial(chrome_release)]
    async fn an_ended_run_hands_its_sessions_over_and_holds_only_a_resumed_run() {
        use crate::tools::chrome_release::RELEASE_HOLD_REDRIVEN_RUN;

        chrome_release::clear_pending_releases();
        // Every end here persists its record, and this test has no store of its own.
        let _no_store = chrome_release::no_release_store();
        let cut_id = format!("run-end-keep-{:016x}", rand::random::<u64>());
        let (_cut_dir, _cut_spill, cut_sessions) = seed_run_owned_state(&cut_id).await;
        let mut cut = RunEndCleanup::new(cut_id, std::sync::Arc::clone(&cut_sessions));
        cut.ended("drain");
        drop(cut);
        assert!(
            chrome_release::pending_release_delays()[0]
                >= RELEASE_HOLD_REDRIVEN_RUN.saturating_sub(std::time::Duration::from_secs(5)),
            "a run the daemon cut off holds its release back for its resumed segment"
        );

        chrome_release::clear_pending_releases();
        let pause_id = format!("run-end-pause-{:016x}", rand::random::<u64>());
        let (_pause_dir, _pause_spill, paused_sessions) = seed_run_owned_state(&pause_id).await;
        let mut paused = RunEndCleanup::new(pause_id, std::sync::Arc::clone(&paused_sessions));
        paused.ended("pause");
        drop(paused);
        assert!(
            chrome_release::pending_release_delays()[0]
                >= RELEASE_HOLD_REDRIVEN_RUN.saturating_sub(std::time::Duration::from_secs(5)),
            "a run frozen by a workspace pause resumes at unpause under its own id"
        );

        chrome_release::clear_pending_releases();
        let final_id = format!("run-end-release-{:016x}", rand::random::<u64>());
        let (_dir, _spill, sessions) = seed_run_owned_state(&final_id).await;
        let mut ended = RunEndCleanup::new(final_id, std::sync::Arc::clone(&sessions));
        ended.ended("transport");
        drop(ended);
        assert!(
            chrome_release::pending_release_delays()[0] < std::time::Duration::from_secs(1),
            "an end that is final releases at once"
        );
        chrome_release::clear_pending_releases();
    }
}