mahbot 0.11.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! One agent's turn: from a routed job to a finalized session through every tool
//! round in between, plus the role/toolset metadata a turn is built from
//! (`run_agent`, `run_default_agent`). The submodules own what a running agent
//! reads and publishes (`role`, `registry`, `message_router`, `skills`,
//! `extraction`, `maintainer`) — not the conversation store of `crate::session`.

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,
};
use crate::util::{MEDIA_MARKER_RE, MediaMarkerKind, UnwrapPoison, parse_media_marker};
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;

// Set once per tool batch (per `execute_tool_group` round), not per individual
// tool `execute()`, and read synchronously — before any `tokio::spawn` boundary
// when the value must cross one. Background agents (management, maintainer,
// workspace) fall back to an empty string.
/// Synchronous read of [`CURRENT_TOOL_USER_NAME`]; the task-local contract above applies.
pub(crate) fn tool_user_name() -> String {
    CURRENT_TOOL_USER_NAME
        .try_with(String::clone)
        .unwrap_or_default()
}

/// The calling agent's session id alone — the identity a session-scoped action
/// needs when the user is not part of it: a Manager session driven by pipeline
/// ticket notifications carries no user name, so [`tool_identity`] refuses those
/// turns while this one answers them.
pub(crate) fn tool_agent_id() -> anyhow::Result<String> {
    current_agent_id()
        .context("No agent identity available — the tool must run in an agent session.")
}

/// Identity of the agent executing a tool call: `(agent_id, user_name)`. Errors
/// outside a user session — there is no addressable identity to attribute side
/// effects to.
pub(crate) fn tool_identity() -> anyhow::Result<(String, String)> {
    let user_name = tool_user_name();
    let agent_id = current_agent_id()
        .filter(|_| !user_name.is_empty())
        .context("No agent identity available — the tool must run in a user session.")?;
    Ok((agent_id, user_name))
}

/// The calling agent's session id as the task-local carries it: `None` outside an
/// agent run and for the empty id a turn can carry.
pub(crate) fn current_agent_id() -> Option<String> {
    CURRENT_TOOL_AGENT_ID
        .try_with(Option::clone)
        .ok()
        .flatten()
        .filter(|agent_id| !agent_id.is_empty())
}

/// The scope a tool-call row states; the ticket is empty when the run has none.
#[derive(Default)]
pub(crate) struct ToolRecordAttribution {
    pub agent_id: String,
    pub agent_role: String,
    pub ticket: String,
}

/// The attribution [`crate::logs::record_warn_row`] rows carry: empty outside an
/// agent run, ticket empty when the run has none. Read here, synchronously — no
/// task-local is in scope where the row is written.
pub(crate) fn tool_record_attribution() -> ToolRecordAttribution {
    let identity = CURRENT_TOOL_AGENT_TRACKING
        .try_with(|tracking| {
            tracking
                .as_ref()
                .map(|tracking| (tracking.role.clone(), tracking.ticket.clone()))
        })
        .ok()
        .flatten();
    let Some((agent_role, ticket)) = identity else {
        return ToolRecordAttribution::default();
    };
    ToolRecordAttribution {
        agent_id: CURRENT_TOOL_AGENT_ID
            .try_with(Option::clone)
            .unwrap_or_default()
            .unwrap_or_default(),
        agent_role,
        ticket,
    }
}

/// 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()
}

/// Synchronous read of [`CURRENT_TOOL_COMMAND_LINE`]; false outside that call.
pub(crate) fn tool_command_line() -> bool {
    CURRENT_TOOL_COMMAND_LINE
        .try_with(|flag| *flag)
        .unwrap_or(false)
}

/// Synchronous read of [`CURRENT_TOOL_CUSTOM_LAUNCH`]: a tool that dispatches a
/// durable round must read it before its `tokio::spawn` boundary so the round
/// carries the caller's branch.
pub(crate) fn tool_custom_launch() -> Option<crate::Launch> {
    CURRENT_TOOL_CUSTOM_LAUNCH
        .try_with(std::clone::Clone::clone)
        .unwrap_or(None)
}

/// Synchronous read of [`CURRENT_TOOL_OUTPUT_DIR`]: where a command-line call's
/// produced files must land, `None` for every other caller.
pub(crate) fn tool_output_dir() -> Option<std::path::PathBuf> {
    CURRENT_TOOL_OUTPUT_DIR
        .try_with(std::clone::Clone::clone)
        .unwrap_or(None)
}

tokio::task_local! {
    pub(crate) static CURRENT_TOOL_USER_NAME: String;
    pub(crate) static CURRENT_TOOL_CHANNEL: String;
    /// Whether THIS call is the command line's own — `mahbot send …` (see
    /// [`crate::cli`]) in the instance with no agent session behind it. Set ONLY
    /// by [`crate::cli::instance`]; never inferred from values a call carries,
    /// since other executors carry the same ones (a message handed to an agent
    /// runs that agent's turn with the command line's channel like any other).
    pub(crate) static CURRENT_TOOL_COMMAND_LINE: bool;
    /// The caller's DIRECT PARENT INVOCATION key (ticket / analyze round /
    /// research run), so tools that spawn sub-agents (`send`) land in the caller's
    /// Running Agents group. `None` = workspace singleton caller.
    pub(crate) static CURRENT_TOOL_PARENT_KEY: Option<crate::agent::registry::ParentKey>;
    /// The caller's parent invocation label (ticket title / question), set
    /// alongside [`CURRENT_TOOL_PARENT_KEY`] for spawned sub-agents. Purely
    /// presentational; `None` for workspace singletons.
    pub(crate) static CURRENT_TOOL_PARENT_LABEL: Option<String>;
    /// The caller's background shell session registry, so the shell tool (Full
    /// roles only) registers/stops sessions that are force-killed when the agent
    /// drops. `None` outside an agent run — background mode is unavailable there.
    pub(crate) static CURRENT_TOOL_BACKGROUND_SESSIONS:
        Option<std::sync::Arc<crate::tools::shell::BackgroundSessions>>;
    /// The caller's id, so the shell tool attributes its spill files to the owning
    /// agent (deleted when the run ends). `None` outside an agent run.
    pub(crate) static CURRENT_TOOL_AGENT_ID: Option<String>;
    /// The caller's role and ticket, for the warning row a tool makes about itself.
    /// The agent id is `CURRENT_TOOL_AGENT_ID`'s. `None` outside an agent run.
    pub(crate) static CURRENT_TOOL_AGENT_TRACKING:
        Option<crate::agent::registry::AgentTracking>;
    /// The caller's custom-role launch, so a tool dispatching a durable round
    /// (`analyze`/`send`) carries its branch address into the envelope and job
    /// row. `None` for every built-in role.
    pub(crate) static CURRENT_TOOL_CUSTOM_LAUNCH: Option<crate::Launch>;
    /// Where a command-line call's produced files must land — set ONLY by
    /// [`crate::cli::instance`], because the tool's arguments never carry it.
    /// `None` (the whole agent path) means the tool's own workspace directory.
    pub(crate) static CURRENT_TOOL_OUTPUT_DIR: Option<std::path::PathBuf>;
}

/// 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 execution and
/// commit of that group. The counter increments only after a committed group; the
/// final-answer call and the image-rejection strip `continue` do not, so an agent
/// can legitimately make more LLM calls than this cap. Do not "fix" these
/// semantics while touching this file.
///
/// **DO NOT REDUCE without benchmarking against real ticket tool-round
/// distributions.** 1000 is deliberate: legitimate work consumes hundreds of
/// rounds, a full run costs well under $1, and hitting the cap is EXTREMELY rare
/// — it is a safety net, not a common guard. Lowering it fails long-running
/// agents mid-task, wasting more on restarts than the rounds would have cost.
/// Value last intentionally reviewed: 2026-07-11
const MAX_TOOL_ROUNDS: usize = 1000;

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

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

/// The interrupted turn's whole entry in the session — the only place the interruption is
/// recorded. The chat and every bound channel get nothing: the turn simply ends, and the
/// urgent message is answered as the next turn.
const URGENT_INTERRUPT_ENTRY: &str = "interrupted by the user";

/// The result a call the urgent interrupt cut is settled with: an ordinary tool
/// result — not a failure — claiming no knowledge of the call's effect.
fn interrupted_outcome() -> ToolExecutionOutcome {
    ToolExecutionOutcome {
        output: crate::prompt::load_prompt("tool_interrupted.md")
            .trim()
            .to_string(),
        success: true,
        image_payloads: Vec::new(),
        text_is_content: false,
        preserve_text: false,
        suspended: false,
        ends_turn: false,
    }
}

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

/// Count DISTINCT data-URI image markers in the session's user messages — the
/// second summarization trigger ([`crate::session::SUMMARIZATION_IMAGE_COUNT`]).
/// The `data:image/` pre-gate keeps the per-turn scan cheap and never undercounts
/// (every vision-promoted marker carries that prefix); it is a deliberate
/// superset, so an invalid `data:image/*` payload may be counted too.
fn session_image_marker_count(history: &[ChatMessage]) -> usize {
    crate::session::image_cap::user_image_values(history)
        .filter(|value| value.starts_with("data:image/"))
        .collect::<std::collections::HashSet<_>>()
        .len()
}

/// An [`ImagePayload`] derived from a real on-disk `[IMAGE:path]` marker in a
/// successful tool output that supplied none, so the agent sees a picture its own round
/// produced. Fails open (`None`) for a non-absolute or non-compressible path (e.g. an
/// SVG) — the marker still stands in the tool result for the reply to name.
///
/// Deliberately not routed through the shared classifier: as a *producer* it must
/// emit a bounded compressed payload, so the async full decode + resize + JPEG
/// (`local_image_to_compressed_data_uri_with_meta`) is its authoritative check;
/// the classifier would add a redundant decode and no encoding value.
async fn derive_image_payload_from_marker(output: &str) -> Option<ImagePayload> {
    // Cheap guard: skip the regex scan for outputs carrying no image marker.
    if !crate::util::has_media_marker(output, MediaMarkerKind::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 tool result, so the reply can
            // still name it.
            continue;
        };
        return Some(ImagePayload::from_compressed_meta(
            p,
            meta,
            None,
            crate::tools::ImagePayloadSource::Generated,
        ));
    }
    None
}

/// Format a tool's outcome for persistence and derive its fresh image payloads —
/// the shared "outcome → content" step of [`Agent::commit_tool_results`] and
/// resume-completion re-execution.
///
/// [`ToolExecutionOutcome::text_is_content`]: content keeps the annotations as an
/// appendix and its markers literal; a claim is replaced by them. `format_output`
/// (or the truncation fallback) runs first, then the outcome's own payloads take
/// precedence over one derived from a real on-disk `[IMAGE:path]` marker. The dedup
/// key `seen` (lazily the pictures `history` would still send) decides fresh/attached,
/// so a picture the request cap retired is attached again instead of being reported as
/// present. The returned vec is every FRESH attachment, injected as ONE synthetic user
/// message. Payloads are taken, not copied — they carry base64 data URIs.
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 = if outcome.preserve_text {
        outcome.output.clone()
    } else {
        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, image_gen) take precedence; otherwise derive one
    // from a real on-disk `[IMAGE:path]` marker, but only from a claim — in content (a
    // converted document's text) a marker is text. Fails open: a non-rasterizable path
    // 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(|| crate::session::image_cap::sent_picture_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.
///
/// A video's pictures are ordinary images: attached and stored like any other.
fn injected_images_message(
    agent_id: &str,
    role: crate::Role,
    payloads: Vec<ImagePayload>,
) -> Option<ChatMessage> {
    if payloads.is_empty() {
        return None;
    }
    let mut markers = 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"
        );
        markers.push(format!("[IMAGE:{}]", payload.data_uri));
    }
    Some(ChatMessage::user(crate::util::injected_image_user_message(
        &markers,
    )))
}

/// One-pass derivation of a role's advertised tools and their specs — the single
/// source for [`Agent::new`] and [`role_tool_specs`], so the frozen replay can never
/// drift from the live tools (KV-cache byte identity). The caller owns the run-scoped
/// chrome tracker, released at the run's end. `launch` is a branch role's launch (its
/// record's tool subset); `None` for built-ins.
#[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>,
    launch: Option<&crate::Launch>,
) -> (Vec<Box<dyn Tool>>, Vec<crate::ToolSpec>) {
    // A custom role's set is its record's chosen subset of the admin Assistant's
    // tools; every other role keeps the static per-role factory.
    let tools: Vec<Box<dyn Tool>> = if role == crate::Role::Custom {
        crate::Role::custom_role_tools(launch.map(|c| c.tools.as_slice()).unwrap_or_default())
    } else {
        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: the tools get a tracker
/// with no namespace (`ChromeRunSessions::default`), which 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()),
        None,
    )
    .1
}

/// A role's derived chat-request params: the model and the reasoning effort every call of that role
/// shares. The provider is deliberately absent — it belongs to the conversation
/// ([`crate::providers::selection`]), not to the role.
pub(crate) struct RoleChatParams {
    pub model: String,
    pub reasoning_effort: Option<String>,
}

/// Derive a role's chat-request params — the single source shared by [`chat_request`],
/// [`crate::pipeline::verdict::synthesis_request`] and
/// [`crate::tools::analyze::consolidate_findings`]. Consumers keep their own `max_tokens`, `tools`,
/// `provider` and `meta`; the call sites share no KV-cache prefix.
#[must_use]
pub(crate) fn role_chat_params(role: crate::Role) -> RoleChatParams {
    RoleChatParams {
        model: crate::config::CONFIG.role_model(role),
        reasoning_effort: Some(
            crate::agent::role::role_info(&role)
                .default_reasoning_effort
                .to_string(),
        ),
    }
}

/// Build the byte-relevant chat params (model, tools, reasoning_effort, max_tokens) for a role;
/// params come from [`role_chat_params`]. The provider is the caller's: a conversation pins its own
/// ([`Agent::build_chat_request`]), a one-off call with no conversation takes
/// [`crate::providers::selection::pick`]. `meta` is telemetry-only (never in the 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,
        reasoning_effort,
    } = role_chat_params(role);
    ChatRequest {
        messages,
        tools: tool_specs,
        model,
        max_tokens: Some(crate::DEFAULT_MAX_TOKENS),
        reasoning_effort,
        provider: None,
        meta: None,
    }
}

impl Agent {
    /// Create an agent (tools from [`crate::Role::tools`]) and register it with
    /// [`crate::agent::registry::AGENT_REGISTRY`]; deregistered on [`Drop`].
    ///
    /// `parent_key` is its DIRECT PARENT INVOCATION grouping key for the Running Agents
    /// view — `None` means a workspace singleton, ticket agents get [`ParentKey::Ticket`]
    /// implicitly; `parent_label` is that invocation's presentational label.
    ///
    /// `launch` is the launch this agent runs under; it is attached to the session so
    /// the system prompt is assembled from it.
    #[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>,
        launch: Option<crate::Launch>,
    ) -> 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),
            launch.as_ref(),
        );

        let cancel_token = tokio_util::sync::CancellationToken::new();
        let pause_stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
        // Ticket agents group by ticket; an explicit parent key takes precedence.
        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 one wins, a ticket-parented agent falls
        // back to the ticket title. Presentational only.
        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 or
        // analyze round whose cancel signal already fired 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 llm_loop bails at its
        // first round-top check.
        if let Some(
            crate::agent::registry::ParentKey::Research(run_id)
            | crate::agent::registry::ParentKey::AnalyzeRound(run_id),
        ) = &parent_key
            && crate::round_cancel::is_cancelled(run_id)
        {
            cancel_token.cancel();
        }
        let interrupt_token = tokio_util::sync::CancellationToken::new();
        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(),
            interrupt_token.clone(),
            parent_key.clone(),
            parent_label.clone(),
            pause_stop.clone(),
        );

        // A fresh live-transcript snapshot holder for this run, so the Running
        // Agents GUI reads the in-memory conversation (including the unpersisted
        // tail) at render time; a replacement run gets a fresh one via the
        // registry's generation guard.
        let mut session = Session::default();
        session.attach_transcript(
            crate::session::TRANSCRIPT_REGISTRY.register(agent_id.clone(), generation),
        );
        // The launch travels with the session: the prompt is assembled from it at the
        // first turn, and the workspace block re-rendered from it later.
        session.launch = launch;

        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,
            provider: crate::providers::selection::ProviderSelection::default(),
            round_ts: None,
            first_call_notify: None,
            failure: None,
            failure_class: None,
            run_failure: None,
            sleep_ended: false,
            turn_recorded: false,
            turn_state: crate::TurnState::default(),
            background_sessions: std::sync::Arc::new(
                crate::tools::shell::BackgroundSessions::default(),
            ),
            chrome_sessions,
            interrupt_token,
        }
    }
}

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: background shell sessions must not outlive the agent —
        // force-kill only, no grace (SIGKILL per process group; one
        // TerminateJobObject per session on Windows).
        self.background_sessions.terminate_all();
    }
}

/// Render a board ticket comment as a user-visible message, shared by live
/// delivery and the resume catch-up so both render identically.
fn format_comment_message(user_name: &str, content: &str) -> String {
    format!("[Comment from {user_name} on ticket]: {content}")
}

impl Agent {
    /// Hand the tool stats to the telemetry queue, then persist the final assistant
    /// message. An empty unpersisted tail is logged: INFO after a drain cut (lossless),
    /// DEBUG after the `sleep` tool, INFO otherwise (genuine anomaly).
    pub async fn finalize_session(&mut self) -> anyhow::Result<()> {
        let stats = {
            let mut guard = self.tool_stats.lock().unwrap_poison();
            std::mem::take(&mut *guard)
        };
        if !stats.is_empty() {
            crate::telemetry::enqueue(crate::telemetry::TelemetryRecord::ToolCalls(
                crate::telemetry::ToolCallBatch {
                    source: crate::stats::CallSource::Agent,
                    agent_id: self.agent_id.clone(),
                    role: self.role.as_str().to_string(),
                    workspace: self.workspace.path.clone(),
                    recorded_at: crate::db::now(),
                    records: stats,
                },
            ));
        }

        // Cancelled (stop or shutdown): no assistant message is expected, so skip
        // finalization. Tool results are durable; a dropped tail loses nothing
        // (comments stay in 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() {
                    // Drain cut the turn right after the last commit: expected and
                    // lossless — committed frames are durable, ticket rounds resume at
                    // boot (job stays 'launched'), direct sessions on the next 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 {
                    // Sleep tool: results are durable and the Assistant is
                    // intentionally silent — normal, 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: no persisted output outside a drain. Keep the
                    // byte-identical 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"
                    );
                }
            }
        }
        // A turn whose first model call ran before the session had a `session_metadata` row recorded
        // no provider then; `finalize` has just created it, so the choice lands now instead of being
        // lost to the next run's re-selection.
        self.persist_provider().await;
        Ok(())
    }

    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.cancel_token.is_cancelled()
    }

    #[must_use]
    fn is_cancelled_by_pause(&self) -> bool {
        self.pause_stop.load(std::sync::atomic::Ordering::SeqCst)
    }

    /// IMMUTABLE bail-time snapshot of a cooperative workspace-pause freeze: set once at
    /// the LLM-round boundary and never cleared, so a finalizer can tell a frozen run from
    /// a technical failure after the workspace is resumed.
    #[must_use]
    pub(crate) fn is_paused_frozen(&self) -> bool {
        self.paused_frozen.load(std::sync::atomic::Ordering::SeqCst)
    }

    /// Failure reason, global-token-first like [`failure_classification`]: shutdown
    /// cancels every per-agent token, so it is checked before an internal cancel.
    #[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())
        }
    }

    /// Whether the last run failed technically — the gate for the destructive reset path.
    #[must_use]
    pub(crate) fn failed_technically(&self) -> bool {
        matches!(self.run_failure, Some(crate::RunFailure::Technical))
    }

    /// The shutdown/drain bail guard: the session is durable, so a cut round resumes
    /// when re-driven.
    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 marker: drain began mid-completion, so the call stays dangling.
    fn log_drain_cut(tool: &str) {
        tracing::info!(tool = %tool, "Drain-cut during resume-completion — leaving calls dangling");
    }

    /// Show `label` on the agent's card while an observational LLM call runs — those
    /// register no non-agent 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: session init, the work loop under shutdown
    /// cancellation, finalize. `messages` arrives in arrival order (several when an
    /// urgent message cut the previous turn); each is its own user message, while the
    /// per-turn blocks ride the first one only. The turn's log scope is one span —
    /// agent, role, workspace name (never its path) and ticket.
    pub async fn work(&mut self, messages: &[&str], resume: bool) -> anyhow::Result<String> {
        let span = tracing::info_span!(
            "agent",
            agent_id = %self.agent_id,
            role = %self.role,
            workspace = %self.workspace.name,
            ticket = self.ticket.as_ref().map(|ticket| ticket.id.as_str())
        );
        self.run_turn(messages, resume).instrument(span).await
    }

    async fn run_turn(&mut self, messages: &[&str], resume: bool) -> anyhow::Result<String> {
        // Whether the turn's message lands decides whether it may advance a personal
        // folder's change baseline; cleared first, so no early return carries the old one.
        self.turn_recorded = false;
        // Load the session WITHOUT the turn message: completion below must settle
        // dangling calls BEFORE the new message lands (results insert right after their
        // frame, keeping the history provider-valid).
        self.session.init(&self.agent_id).await?;

        // The provider this conversation holds: the one stored with the session, kept while it
        // serves the model and its outage is young, re-selected from the top of the list
        // otherwise. Every model call of this turn uses it, so a provider change mid-work never
        // happens by accident.
        self.adopt_session_provider().await;

        // Re-engaging (any job kind): clear a stale sleep-ended flag BEFORE this turn, so
        // a crash mid-round is still recovered by the dead-session poller. Only the
        // Assistant, the Manager and a custom role can write it, so other roles skip it.
        if self.role.is_long_lived_chat()
            && 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"
            );
        }

        // A branch launch also clears the persisted deliberate-stop mark, fail-soft
        // like the sleep mark: relaunching a stopped branch re-enables recovery.
        if self.session.launch.is_some()
            && crate::session::store()
                .get_launch_stopped(&self.agent_id)
                .await
            && let Err(e) = crate::session::store()
                .set_launch_stopped(&self.agent_id, false)
                .await
        {
            tracing::warn!(
                agent_id = %self.agent_id,
                error = %e,
                "Failed to clear launch-stopped flag"
            );
        }

        // Universal resume-completion: settle the last tool-call frame's result-less
        // calls BEFORE any LLM call, ungated — drain mid-call, hard crash and stage
        // re-drive all converge here. Recorded on the agent for the later gate.
        self.turn_state.settled_tool_results = if crate::shutdown::aborting() {
            false
        } else {
            self.complete_pending_tool_calls().await?
        };

        // The index the turn's messages start at: a compaction below must keep every one
        // of them.
        let turn_start = self.session.history().len();
        if messages.iter().any(|msg| !msg.is_empty()) {
            self.session
                .append_turn_messages(
                    &self.agent_id,
                    messages,
                    &self.workspace,
                    &self.role,
                    self.ticket.as_ref(),
                    &self.channel,
                    &self.user_name,
                    self.round_ts.as_deref(),
                    self.is_admin,
                )
                .await?;
            self.turn_recorded = true;
        }

        // Pre-maybe_summarize drain check: a dispatch starting during the drain must not
        // destructively compact an over-threshold session before llm_loop's own check.
        // The round is cut before any LLM work; boot resume continues it.
        Self::bail_on_shutdown()?;
        // Pre-maybe_summarize cancel check, same rule: an agent stopped before its first
        // model call must not spend a summarization call on itself.
        if self.cancel_token.is_cancelled() {
            anyhow::bail!("Agent cancelled");
        }

        // A resumed stage round with an empty message would otherwise never surface
        // board comments (the session-start ticket block is not re-rendered).
        self.inject_outstanding_comments(resume, messages).await;

        // Mandatory: destructive over-threshold compaction is SKIPPED on resumed turns
        // AND on turns that just settled dangling results — the pre-crash trail must
        // survive (do NOT infer resume from an empty message). A settlement is resume-like:
        // the retention window excludes tool frames/results, so compacting right after
        // settling would drop the settled result; the next plain turn summarizes.
        if !resume && !self.turn_state.settled_tool_results {
            self.maybe_summarize(turn_start).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, 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 resume-completion: settle the last tool-call frame's result-less calls
    /// BEFORE any LLM call, on every role/path. Durable sync rounds (`analyze`, `send`)
    /// owned by this session pin are slot-resumed, everything else re-executed. Only
    /// rounds the frame itself dispatched are bindable — an older pool entry belongs to a
    /// settled frame and is abandoned, never bound. Settlement and terminalization commit
    /// in ONE transaction, so a crash rolls back both and the next cycle re-settles
    /// idempotently; results settle contiguously after their frame.
    ///
    /// Intentionally ungated: drain mid-call, hard crash and stage re-drive all converge
    /// here. Completed calls are never re-run (`pending_tool_frame` excludes them).
    /// Returns `true` when anything settled — the [`TurnState::settled_tool_results`] both
    /// summarization gates skip a resume-like turn from. Boxed to break the async-opaque
    /// Send cycle around the resume cores.
    #[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;
            // Launched jobs, fetched ONCE (newest-first) and CONSUMED per call, so two
            // same-kind calls bind DISTINCT jobs; jobs being newest-first while calls are
            // in dispatch order, each call takes the OLDEST remaining one.
            let pool = crate::jobs::find_owned_launched_jobs(conn, &self.agent_id).await?;
            // Bind only rounds THIS frame dispatched: the frame row precedes its calls
            // (emission-time durability), so its own rounds are strictly newer, while a
            // leftover from an earlier frame (an infra-failed dispatch never terminalizes
            // its row) is older and binding it would settle an old report as this call's
            // result. The split is frame OWNERSHIP, not freshness.
            let (pre_frame, mut owned) = match crate::session::store()
                .last_assistant_created_at(&self.agent_id)
                .await?
                .and_then(|frame| crate::db::parse_utc_timestamp(&frame).ok())
            {
                Some(frame) => pool.into_iter().partition(|j| {
                    crate::db::parse_utc_timestamp(&j.created_at).is_ok_and(|c| c < frame)
                }),
                // No frame row to anchor against (unreachable: it is persisted first):
                // NOTHING is bindable, so every call is re-run rather than risk settling
                // another round's report as its result.
                None => (pool, Vec::new()),
            };
            if !pre_frame.is_empty() {
                tracing::info!(
                    agent_id = %self.agent_id,
                    count = pre_frame.len(),
                    "Abandoning launched rounds this frame did not dispatch"
                );
            }

            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 images of the resumed round, injected as ONE message after the loop.
            let mut fresh_images: Vec<ImagePayload> = Vec::new();
            let mut seen_data_uris: Option<std::collections::HashSet<String>> = None;

            for call in calls {
                // Durable-resume attempt: the JOBS ROW is the source of truth. A terminal
                // job yields content (terminalized after settlement), a DrainCut stops the
                // completion, a gone job surfaces a short note. The round kind comes from
                // the call's tool and choice argument, never a stored kind.
                let mut resumed_content: Option<String> = None;
                if let Some(core) =
                    crate::tools::SyncDurableCore::from_call(&call.name, &call.arguments)
                    && let Some(pos) = owned.iter().rposition(|j| j.kind == core.kind_str())
                {
                    // `rposition`, not `position`: the FIRST call must bind the OLDEST
                    // matching job (`position` would cross the 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.
                            Self::log_drain_cut(&call.name);
                            return Ok(false);
                        }
                        Ok(crate::jobs::SyncResumeOutcome::Gone) => {
                            // Explicitly abandoned (session /clear, workspace deletion):
                            // the row is gone, so do NOT push onto `terminalize`.
                            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) => {
                            // An 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 so the model resends it 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 {
                    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);
                    }
                    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 + abandon in ONE transaction: a crash rolls back BOTH,
            // so the jobs stay launched and the next cycle re-settles idempotently (the
            // settle DELETEs the post-frame rows and reinserts, so re-settling is a
            // structural no-op). Every terminalize id also pushed a pair.
            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}"))?;
                }
                // Everything this frame cannot own is abandoned with the settle. Repeating
                // a cut-mid-flight call is the accepted cost; a crossed report is not.
                for job in pre_frame.iter().chain(owned.iter()) {
                    tx.execute(
                        "DELETE FROM jobs WHERE id = ?1",
                        crate::db::params![job.id.as_str()],
                    )
                    .await
                    .with_context(|| format!("abandon job {}", job.id))?;
                }
                tx.commit().await.context("commit settle+terminalize tx")?;
                // Mirror into the history only AFTER the durable commit.
                self.session
                    .mirror_settled(settled)
                    .context("mirror settled results")?;
            }
            Ok(!pairs.is_empty() || !follow_up.is_empty())
        })
    }

    /// The round loop: LLM call → tool execution → repeat until a final answer.
    /// Runs inside [`Self::work`]'s span, which carries the run's log scope.
    async fn llm_loop(&mut self) -> anyhow::Result<String> {
        let mut tool_rounds = 0usize;
        loop {
            if self.cancel_token.is_cancelled() {
                anyhow::bail!("Agent cancelled");
            }
            // Cooperative workspace-pause (strict freeze): the round ends here, no new LLM
            // call starts. The pause does NOT fire the cancel token, so an in-flight round
            // completes and commits first; the finalizer treats the agent as a no-op (the
            // job stays for the unpause re-drive).
            if self.is_cancelled_by_pause() {
                // Record the freeze IMMUTABLY, so a later unpause (which clears the
                // live pause_stop) cannot turn it 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 round top, after the previous group's commit, so
            // the current group completes and no new LLM call starts. The round resumes at
            // boot from the job row.
            Self::bail_on_shutdown()?;
            // Urgent-message interrupt: not a cancellation — the turn ends here, every
            // result already committed, with the phrase as its only session entry. Checked
            // after shutdown/drain (their priority is unchanged) and before another model call.
            if self.interrupt_token.is_cancelled() {
                return Ok(self.end_interrupted_turn());
            }
            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 (`format_comment_message`).
            self.drain_incoming_messages().await;

            // Leader-stagger signal: fired after the FIRST LLM call completes,
            // success or failure — fail-open; Notify's stored permit covers a
            // fire-before-wait race. Raced against the urgent interrupt: cutting a
            // request means dropping it (nothing recorded), which is what makes the
            // cut immediate. The signal is skipped on that path.
            let interrupt = self.interrupt_token.clone();
            let llm_result = tokio::select! {
                biased;
                () = interrupt.cancelled() => return Ok(self.end_interrupted_turn()),
                result = self.llm_call() => result,
            };
            if tool_rounds == 0
                && let Some(notify) = &self.first_call_notify
            {
                notify.notify_one();
            }

            // The downcast is taken into a local first — `anyhow::Chain` is not `Send` and must
            // not be held across the await (a Send-bound spawned task).
            let retry_exhaustion = llm_result.as_ref().err().and_then(|e| {
                e.chain()
                    .find_map(|cause| cause.downcast_ref::<crate::retry::RetryExhausted>())
            });
            // History repairs for a refusal class: an input-image rejection strips the image from
            // the most recent user message, a content refusal neutralizes leaked control tokens.
            // Each reports `false` when nothing changed, so a no-op cannot skip `tool_rounds += 1`.
            if let Some(exhausted) = retry_exhaustion
                && (self.strip_rejected_input_image(exhausted).await
                    || self.neutralize_leaked_control_tokens(exhausted).await)
            {
                continue;
            }

            let PreparedAssistantTurn {
                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);
                return Ok(display_text);
            }

            // EMISSION-TIME DURABILITY: the assistant frame and its tool calls are
            // committed BEFORE the calls execute — a crash or drain mid-execution
            // leaves them recorded with results absent, and resume-completion (run
            // before any LLM call) re-runs or resumes them. The end-of-round commit
            // 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;

            // A call the interrupt cut (`None`) is settled with the fixed synthetic
            // result, in its own place, so every call ends with a result contiguous
            // with it and the exchange stays model-valid. A call already returned
            // keeps its real result.
            let cut = all_outcomes.iter().any(Option::is_none);
            let all_outcomes: Vec<ToolExecutionOutcome> = all_outcomes
                .into_iter()
                .map(|outcome| outcome.unwrap_or_else(interrupted_outcome))
                .collect();

            // 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` ends the run gracefully AFTER this
            // round — every result above is committed. It returns before the next
            // iteration, so the loop-top MAX_TOOL_ROUNDS guard never sees it.
            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());
            }

            // The cut round's results are committed, so the interruption ends the turn here
            // instead of another round. A successful sleep returned above: that round
            // concluded inside its only call, so nothing was cut.
            if cut || self.interrupt_token.is_cancelled() {
                return Ok(self.end_interrupted_turn());
            }

            tool_rounds += 1;
        }
    }

    /// End this turn on an urgent-message interrupt: record the phrase as the session entry
    /// and hand back an empty reply. [`TurnState::interrupted`] keeps the router from
    /// delivering anything — no chat row, no channel message. The interrupted answer is
    /// abandoned: nothing of it is delivered later.
    fn end_interrupted_turn(&mut self) -> String {
        self.session
            .push_assistant(URGENT_INTERRUPT_ENTRY.to_string());
        self.turn_state.interrupted = true;
        String::new()
    }

    /// Execute a batch of tool calls respecting side-effect ordering: read-only
    /// runs of consecutive calls execute in parallel, a side-effecting call runs
    /// alone, and groups keep the original call order. Outcomes stay one-to-one with
    /// `tool_calls`; `None` is a call the urgent interrupt cut before it returned.
    async fn execute_tool_group(
        &self,
        tool_calls: &[ToolCall],
    ) -> Vec<Option<ToolExecutionOutcome>> {
        // Determine side_effects for each tool call. Unknown tools are conservatively treated as
        // side-effecting.
        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<Option<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] {
                    let outcome = self
                        .race_interrupt(
                            self.execute_tool(&tool_calls[i].name, tool_calls[i].arguments.clone()),
                        )
                        .await;
                    outcomes.push(outcome);
                    i += 1;
                } else {
                    let group_start = i;
                    while i < tool_calls.len() && !side_flags[i] {
                        i += 1;
                    }
                    let group_calls = &tool_calls[group_start..i];

                    // The whole group runs in parallel, each call raced on its own, so
                    // one already returned keeps its real result while cut siblings
                    // settle as interrupted.
                    let group_outcomes: Vec<_> =
                        futures_util::future::join_all(group_calls.iter().map(|call| {
                            self.race_interrupt(
                                self.execute_tool(&call.name, call.arguments.clone()),
                            )
                        }))
                        .await;

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

        outcomes
    }

    /// Run one tool call against the urgent interrupt: `None` when the cut came
    /// first, which drops the call and its whole process tree. A cut that already
    /// landed must not start the call at all — one poll is enough to spawn a child or
    /// write a file. Biased on the call, so one completing in the same instant keeps
    /// its real result.
    async fn race_interrupt<F>(&self, call: F) -> Option<ToolExecutionOutcome>
    where
        F: std::future::Future<Output = ToolExecutionOutcome>,
    {
        if self.interrupt_token.is_cancelled() {
            return None;
        }
        let interrupt = self.interrupt_token.clone();
        tokio::select! {
            biased;
            outcome = call => Some(outcome),
            () = interrupt.cancelled() => None,
        }
    }

    /// Execute one tool round under the sleep-delivery guard: with a rejection active,
    /// every `sleep` call is intercepted BEFORE execution and settled as a synthetic
    /// failure at its own position, siblings running normally. Outcomes stay one-to-one
    /// with `tool_calls` — `commit_tool_results` relies on that alignment.
    async fn execute_tool_round(
        &self,
        tool_calls: &[ToolCall],
        sleep_rejection: Option<&'static str>,
    ) -> Vec<Option<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"
        );

        // Only non-sleep calls execute; sleep calls settle as synthetic failures at
        // their own positions, keeping the round aligned one-to-one.
        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<Option<ToolExecutionOutcome>> = 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(Some(
                    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 this agent's `CURRENT_TOOL_*` task-locals, scoped once per tool
    /// batch so concurrent read-only tools never interleave their user 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 {
            role: self.role.as_str().to_string(),
            ticket: self
                .ticket
                .as_ref()
                .map(|ticket| ticket.id.clone())
                .unwrap_or_default(),
        });
        let launch = self.session.launch.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, async {
                                                                CURRENT_TOOL_CUSTOM_LAUNCH
                                                                    .scope(launch, fut)
                                                                    .await
                                                            })
                                                            .await
                                                    })
                                                    .await
                                            })
                                            .await
                                    })
                                    .await
                            })
                            .await
                    })
                    .await
            })
            .await
    }

    /// Construct a failure outcome tuple for an error reason.
    ///
    /// The reason is used verbatim in the feedback text and returned as the recorded
    /// error.
    #[must_use]
    fn failure_outcome(
        call_name: &str,
        call_arguments: &serde_json::Value,
        reason: &str,
    ) -> (ToolExecutionOutcome, String) {
        (
            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,
                preserve_text: false,
                suspended: false,
                ends_turn: false,
            },
            reason.to_string(),
        )
    }

    /// Record one tool invocation into the in-memory stats (sent to telemetry at
    /// finalization); arguments go through [`crate::stats::recorded_arguments`], with the tool's own
    /// answer for a call that carries a credential first ([`crate::Tool::recorded_arguments`]).
    ///
    /// A call naming a tool this agent does not hold has no such answer and is recorded as it was
    /// made: it never ran, and the model invented its name.
    fn push_tool_call_record(
        &self,
        tool_name: String,
        arguments: &serde_json::Value,
        duration_ms: i64,
        success: bool,
        error_message: Option<String>,
    ) {
        let recorded = crate::tools::find_tool(&self.tools, &tool_name)
            .and_then(|tool| tool.recorded_arguments(arguments));
        let arguments = crate::stats::recorded_arguments(recorded.as_ref().unwrap_or(arguments));
        let mut guard = self.tool_stats.lock().unwrap_poison();
        guard.push(crate::ToolCallRecord {
            tool_name,
            arguments,
            duration_ms,
            success,
            error_message,
        });
    }

    #[expect(clippy::too_many_lines)]
    async fn execute_tool(
        &self,
        call_name: &str,
        call_arguments: serde_json::Value,
    ) -> ToolExecutionOutcome {
        // Pre-flight cancellation check: a call dispatched before llm_loop's round-top
        // check can still reach here, and a side-effecting tool (shell, file edits,
        // sub-agents) must not run after a Stop.
        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"
            );
        }

        // The arms log at distinct levels (info vs debug), so unknown-tool failures
        // are distinguishable from execution errors without string 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: output_text,
                                success: true,
                                image_payloads: result.image_payloads,
                                text_is_content: result.text_is_content,
                                preserve_text: result.preserve_text,
                                suspended: false,
                                ends_turn: tool.ends_turn_on_success(),
                            },
                            String::new(),
                        )
                    }
                    Err(e) => {
                        // Drain-cut suspension: the tool's durable work was deliberately
                        // left launched for deterministic resume. `suspended` makes the
                        // result commit SKIP it — the frame is durable and the result
                        // intentionally absent; resume-completion settles it later.
                        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: suspended outcomes are skipped.
                                    output: String::new(),
                                    success: false,
                                    image_payloads: Vec::new(),
                                    text_is_content: false,
                                    preserve_text: false,
                                    suspended: true,
                                    ends_turn: false,
                                },
                                String::new(),
                            )
                        } else {
                            let (outcome, error_reason) = Self::failure_outcome(
                                &tool_name,
                                &tool_arguments,
                                &crate::tools::tool_failure_reason(&tool_name, &e.to_string()),
                            );
                            tracing::debug!(
                                tool = %tool_name,
                                duration_ms = duration.as_millis(),
                                success = false,
                                "Tool execution error: {error_reason}"
                            );
                            (outcome, error_reason)
                        }
                    }
                }
            }
        };

        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> {
        // The provider is chosen in `build_chat_request` (see its doc).
        let messages = self.session.history().to_vec();
        let request = self.build_chat_request(messages.clone(), "agent");

        let policy = crate::retry::RetryPolicy::current();
        let result = crate::retry::agent_chat(request, &mut self.provider, &policy).await;
        // Recorded before the error path can return: a run that moved off a dead provider ends on
        // the new one, and the next run picks it up from there.
        self.persist_provider().await;
        let response = result.with_context(|| format!("LLM call {RETRY_EXHAUSTION_MARKER}"))?;

        // Reasoning-only stop: recovered here, before any promotion, persistence or display, via the
        // bounded continuation. Its own ladder can move the provider too, so the pin is written
        // again before its error path can return.
        let recovered = self
            .recover_if_reasoning_only_stop(messages, response, Self::AGENT_REASONING_RECOVERY)
            .await;
        self.persist_provider().await;
        let response = recovered?;

        // Only a response actually returned to the loop updates the session length:
        // failures propagate above, and an exhausted reasoning-only turn returned
        // early having recorded nothing.
        self.record_session_usage(&response).await;
        Ok(response)
    }

    /// Apply a history repair through the session store, one row at a time: `true` when at least
    /// one row's content actually changed.
    ///
    /// The no-loop guard lives here: the caller `continue`s only on `true`, and `continue` skips
    /// `tool_rounds += 1`, so a repair that changes nothing must report `false` or the loop spins
    /// unbounded. A row whose text is already the target text is skipped, and so is a row in the
    /// unpersisted tail (a positional UPDATE would hit a different row).
    ///
    /// Persist-before-swap: [`crate::session::Session::rewrite_message`] writes the row before
    /// swapping the in-memory copy, so a persist failure leaves the session untouched and the
    /// caller's original error path stands.
    async fn rewrite_history_rows(&mut self, rewrites: Vec<(usize, String)>, what: &str) -> bool {
        let mut rewritten = 0usize;
        for (index, content) in rewrites {
            if self.session.history()[index].content == content {
                tracing::debug!(
                    agent_id = %self.agent_id,
                    role = %self.role,
                    index,
                    what,
                    "History repair produced no change — treating as a no-op"
                );
                continue;
            }
            match self
                .session
                .rewrite_message(&self.agent_id, index, content)
                .await
            {
                Ok(crate::session::RewriteOutcome::Rewritten) => rewritten += 1,
                Ok(crate::session::RewriteOutcome::UnpersistedTailNoop) => {
                    tracing::debug!(
                        agent_id = %self.agent_id,
                        role = %self.role,
                        index,
                        what,
                        "Repair target is in the unpersisted tail — conservative no-op"
                    );
                }
                Err(e) => {
                    tracing::error!(
                        agent_id = %self.agent_id,
                        role = %self.role,
                        index,
                        what,
                        error = %e,
                        "Failed to persist a history repair — keeping the original error path"
                    );
                }
            }
        }
        if rewritten == 0 {
            return false;
        }
        tracing::info!(
            agent_id = %self.agent_id,
            role = %self.role,
            what,
            count = rewritten,
            "Repaired the session history — continuing the normal loop"
        );
        true
    }

    /// Detect a provider input-image content-inspection rejection and durably strip the image from
    /// the most recent user message, then let the normal loop continue — the next round re-runs
    /// `llm_call`, and once the message carries no image marker a failure takes the normal path.
    ///
    /// The leader-stagger signal has already fired, so the stripped leader's next request diverges
    /// from its followers' byte-stable prefix — fail-open, and moot for direct chat (management
    /// rounds never send images). The retried call re-runs the tool-round-0 `notify_one`, but the
    /// stagger's single waiter has consumed it: the extra permit is dropped, no follower released
    /// twice.
    async fn strip_rejected_input_image(
        &mut self,
        exhausted: &crate::retry::RetryExhausted,
    ) -> bool {
        let Some(index) = 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);
        let stripped = crate::session::image_strip::strip_image_markers(
            &self.session.history()[index].content,
            reason.as_deref(),
        );
        self.rewrite_history_rows(vec![(index, stripped)], "input image strip")
            .await
    }

    /// Neutralize every leaked model control token in the history after a provider refusal of the
    /// request's content, rewriting each token-bearing row durably.
    async fn neutralize_leaked_control_tokens(
        &mut self,
        exhausted: &crate::retry::RetryExhausted,
    ) -> bool {
        let rewrites = crate::session::control_token_strip::leaked_token_rewrites(
            exhausted,
            self.session.history(),
        );
        if rewrites.is_empty() {
            return false;
        }
        self.rewrite_history_rows(rewrites, "control token neutralize")
            .await
    }

    /// Bounded continuation recovery for the reasoning-only-stop class (empty content, no
    /// parsed tool calls): re-request with the thinking attached as the assistant's
    /// reasoning plus a continuation prompt. **Appended-only** — a transport failure NEVER
    /// grows the tail (the next attempt re-sends the PREVIOUS request verbatim,
    /// byte-identical even across a config hot-reload), so the prefix stays byte-stable
    /// (prompt-prefix cache preserved). The tail lives only in the re-request list, never
    /// in the session, so a failed attempt leaves no trace and the thinking cannot leak.
    ///
    /// 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 cancel token between attempts; retryable
    /// errors re-send the same bytes, non-retryable ones break at once. Telemetry is
    /// operation-level: one success row, or one failure row via `fail_exhausted`, plus
    /// one `llm_failures` row per failed attempt.
    ///
    /// Exhaustion returns a [`crate::retry::RetryExhausted`] with `last_raw: None` and a
    /// class from the last failure ([`FailureClass::NoResponse`], or
    /// [`FailureClass::Shutdown`] when the global abort fired) — the thinking text is
    /// never embedded, so logs cannot leak it and it is not misclassified as provider
    /// retry exhaustion.
    async fn recover_reasoning_only_stop(
        &mut 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);
                    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;
                }
                Ok(resp) => {
                    crate::stats::record_llm_success(&request, operation_started, attempt, &resp);
                    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,
                    );
                    failures.push(err.record);
                    if !err.class.is_retryable() {
                        break;
                    }
                    // A provider that has been down for the whole window: this attempt and every
                    // rebuild below continue on the next available one, and the recorded operation
                    // follows the move so the failure rows name the serving provider.
                    if let Some(request) = last_request.as_mut() {
                        crate::retry::switch_provider(
                            err.class,
                            &mut self.provider,
                            request,
                            operation.as_mut(),
                        );
                    }
                }
            }
        }

        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),
            None => Err(exhausted),
        }
    }

    /// Agent-loop policy: 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",
    };

    /// Summarization policy: continuation exhaustion fails open with 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 — the single classification point for that class, reached by both
    /// LLM paths before any promotion, persistence or display.
    ///
    /// On exhaustion the error carries `recovery.exhausted_ctx`: the agent loop fails the
    /// turn safely (nothing persisted or displayed), while summarize fails open with the
    /// full history. Leak safety: appended-only, never touching the transcript, and the
    /// exhaustion error never embeds the thinking text.
    async fn recover_if_reasoning_only_stop(
        &mut 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 provider-reported session length after a SUCCESSFUL agent-purpose call:
    /// `input_tokens + output_tokens`. Other builders are not session context and never
    /// pass through here; a compaction clears the value with the history it replaces.
    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 and push them into memory for the next round. The assistant
    /// frame is already durable from EMISSION time, so this writes ONLY the result rows.
    /// Suspended outcomes are SKIPPED, and an all-suspended round writes nothing. Takes
    /// `outcomes` by value: their payloads are MOVED into the injected image message.
    async fn commit_tool_results(
        &mut self,
        tool_calls: &[ToolCall],
        outcomes: Vec<ToolExecutionOutcome>,
    ) -> anyhow::Result<()> {
        let tools = &self.tools;

        let mut seen_data_uris: Option<std::collections::HashSet<String>> = None;

        // Image messages go AFTER the tool-result block, preserving OpenAI-compatible
        // contiguity (assistant(tool_calls) → tool_result_* → user(IMAGE_*)).
        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) {
            // Suspended: nothing to commit; the work is left for resume-completion.
            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));
        }

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

        // Nothing to commit (all suspended): the frame is already durable.
        if db_messages.is_empty() {
            return Ok(());
        }

        self.session
            .persist_messages(&self.agent_id, &db_messages)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to persist tool results: {e}"))?;

        Ok(())
    }

    /// Drain routed messages (ticket comments) into the session history, at the start of
    /// each tool round before the LLM call. Persisted AND pushed to memory so they survive
    /// a crash. On a persist failure they are still visible this turn and stay in the
    /// unpersisted tail the next persist flushes; a cancel before finalize drops them.
    /// No-op without a receiver (chat agents use the consumer loop).
    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: drop the receiver so we never retry.
                    self.incoming_rx = None;
                    break;
                }
            }
        }

        if messages.is_empty() {
            return;
        }

        // Fail-open: the comment is already in the board DB, so log and continue.
        self.persist_messages_fail_open(&messages).await;
    }

    /// Persist fail-open: on failure they still reach the memory and the tail.
    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: it starts with an empty
    /// message, never re-renders `<current-ticket>`, and would miss comments added after
    /// the boot snapshot. Re-reads the board and injects those absent from the history
    /// (content-based dedup). Gated to `resume` + empty `msg`, so the bounce-feedback path
    /// is excluded. Runs once per turn, fail-open persist like live delivery.
    async fn inject_outstanding_comments(&mut self, resume: bool, messages: &[&str]) {
        if !resume || messages.iter().any(|msg| !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: a comment routed after registration is already in the channel and deduped
        // against the post-drain history. One routed after the drain can still arrive
        // twice — the accepted no-watermark limitation.
        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 messages with the agent's current model, tools,
    /// reasoning-effort and held provider.
    ///
    /// Model, tools and reasoning-effort are resolved each call, so a hot-reload is reflected
    /// immediately (reasoning effort is baked into role metadata); the provider is NOT — the run
    /// holds one, and only an outage outlasting [`crate::providers::selection::MOVE_AFTER`] (or a
    /// model change under it) moves it. Selection therefore happens here, once per request, from the
    /// model the request carries: the run keeps its provider while that provider serves it, and a
    /// hot reload that changed the model re-selects (the previous provider may not serve the new
    /// one) with the choice recorded on the run.
    ///
    /// Every call site for the same conversation *must* use exactly the same parameter
    /// sources — model, reasoning_effort, tools (critically tools!) and provider — or the
    /// provider recomputes the whole KV-cache prefix.
    ///
    /// The request never carries more pictures than [`crate::session::SUMMARIZATION_IMAGE_COUNT`]:
    /// the session's recorded count gates the walk, and the oldest pictures step aside in place
    /// ([`crate::session::image_cap`]), so the conversation itself is untouched.
    fn build_chat_request(
        &mut self,
        mut messages: Vec<ChatMessage>,
        purpose: &'static str,
    ) -> ChatRequest {
        crate::session::image_cap::apply(&mut messages, Some(self.session.image_count()));
        let mut request = chat_request(self.role, Some(self.tool_specs.clone()), messages);
        self.provider.apply(&mut request);
        request.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()),
        });
        request
    }

    /// Keep the conversation's stored provider in step with the run's, writing only when it changed,
    /// so the choice survives a restart, a resumed run and a re-dispatched agent. Fail-soft: a
    /// failed write costs the next run a re-selection, never this run its provider.
    async fn persist_provider(&mut self) {
        let stored = self.provider.stored();
        if stored.as_ref() == self.session.provider() {
            return;
        }
        self.session.set_provider(&self.agent_id, stored).await;
    }

    /// Take the provider the conversation holds, re-selected only when its outage has outlasted the
    /// window. A conversation with none keeps whatever selection the agent already holds: its first
    /// request resolves one for the model it carries.
    pub(crate) async fn adopt_session_provider(&mut self) {
        if let Some(stored) = self.session.provider().cloned() {
            self.provider = crate::providers::selection::ProviderSelection::resolve(
                &stored.model,
                Some(&stored),
            );
        }
        self.persist_provider().await;
    }

    /// Extract a structured verdict with the hardened scoped retry loop. KV-cache:
    /// params come from [`Self::build_chat_request`], so attempts are byte-identical
    /// except the parse-failure re-prompt. `validate` runs fail-closed (e.g. score ∈
    /// [0,10]) and a rejected value is re-prompted as a parse failure — `None` for
    /// plain extraction. `policy_override` gives fail-open callers a shorter schedule.
    pub(crate) async fn extract_verdict<T: serde::de::DeserializeOwned>(
        &mut 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 session history. KV-cache: see [`Self::build_chat_request`] — the request is
    /// built once and re-sent verbatim, so every attempt is byte-identical except the provider,
    /// which the run's selection decides per attempt and moves only once the pinned one has been
    /// unavailable for the whole window.
    ///
    /// A tool call is not a summary: it carries no text, so it is re-asked
    /// (`SUMMARIZE_ATTEMPTS` in total, each a successful `summarize` request of its
    /// own) and never executed; text alongside a tool call is the summary. Exhaustion
    /// raises the empty-response error, so [`Self::maybe_summarize`] fails open.
    pub(crate) async fn summarize(&mut 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 mut request = self.build_chat_request(history.clone(), "summarize");
        let policy = crate::retry::RetryPolicy::current();

        for _ in 1..=SUMMARIZE_ATTEMPTS {
            // The run's provider serves the attempt: the ladder and the reasoning-only continuation
            // of the previous one may each have moved it since the request was built.
            self.provider.pin(&mut request);
            let chat_resp = crate::retry::agent_chat(request.clone(), &mut self.provider, &policy)
                .await
                .with_context(|| format!("summarization LLM call {RETRY_EXHAUSTION_MARKER}"))?;

            // Reasoning-only stop: the same bounded continuation as the agent loop; on
            // exhaustion, fail open below 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 summarization triggers and summarise if necessary: the
    /// provider-reported session token length over [`SUMMARIZATION_THRESHOLD`], or
    /// [`SUMMARIZATION_IMAGE_COUNT`] distinct data-URI images. The token length is the
    /// REAL value of the last successful agent call, loaded at session init; `None`
    /// (never recorded — approved no-backfill — or cleared by the last compaction)
    /// only disables the token trigger. A FAILED call never updates it.
    ///
    /// KV-cache preservation: [`Agent::summarize`] keeps all parameters identical, so
    /// the cached prefix stays reusable.
    async fn maybe_summarize(&mut self, turn_start: usize) {
        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,
            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,
                        turn_start,
                    )
                    .await;
            }
            Err(e) => {
                tracing::warn!(
                    error_chain = %crate::util::failure_detail(&format!("{e:#}"), "summarization failure"),
                    "Summarization failed — continuing with full history"
                );
            }
        }
        // The ladder — and the reasoning-only continuation it can run — may move the run off a dead
        // provider. Written here because a cancelled or draining turn ends without another model
        // call, so `finalize_session` may never reach it.
        self.persist_provider().await;
    }

    /// Compact a long-lived chat role's session (Assistant, Manager, custom) right
    /// after its reply was delivered, so the user's next message does not wait. Runs
    /// on the per-session consumer loop — the serialized path that already handles one
    /// turn at a time here.
    ///
    /// [`Self::maybe_summarize`] keeps the same limit, triggers, prompt, result and
    /// retention policy, and its pre-turn call in [`Self::work`] stays the safety net
    /// for everything this skips — settled tool results, cancellation, shutdown.
    /// `resume` needs no clause: this loop runs every job as a plain turn.
    ///
    /// A session over a trigger at delivery compacts whatever put it there, even when
    /// its own compaction failed to persist; a repeat costs at most one extra
    /// summarization call per turn, accepted over the wait it removes.
    pub(crate) async fn maybe_summarize_after_delivery(&mut self) {
        if !self.role.is_long_lived_chat()
            || self.turn_state.settled_tool_results
            || self.is_cancelled()
            || crate::shutdown::aborting()
        {
            return;
        }
        // The turn is over: nothing of it is still owed a full read.
        self.maybe_summarize(self.session.history().len()).await;
    }
}

/// Which trigger fires, if any: strict `>` for the token threshold but `>=` for the
/// image count — the asymmetry is deliberate.
#[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 and the
/// context attached to the exhaustion error. Named fields, not two adjacent
/// `&'static str` arguments, so they cannot be silently swapped at a call site.
struct ReasoningOnlyStopRecovery {
    purpose: &'static str,
    exhausted_ctx: &'static str,
}

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

/// The "reasoning-only stop" class: empty content (think tags stripped — they are
/// reasoning) with no parsed tool calls, REGARDLESS of finish reason. Tool-call turns
/// are excluded by the tool-call check. Degenerate members — fully empty responses and
/// think-tag-only content — are consciously in class: the continuation carries just the
/// nudge, and a silent `Ok("")` now resolves there 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); the duration is measured from `attempt_started`.
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));
    }
}

/// Context for a failed LLM step: the run-local round counter plus session depth — a
/// resumed long-lived session must not read as freshly started. 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(),
    )
}

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 payload captures the model's original response. Reasoning-only stops never
    // reach here — llm_call recovers them before any persistence or display.
    let json_payload =
        assistant_replay_payload(Some(&response_text), &tool_calls, reasoning).to_string();

    // Plain answer, reasoning+text, or tool calls. Reasoning-only responses 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: a `sleep` call must run alone in a text-free round, or it
/// swallows the accompanying text or ends the run silently. `None` when 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 options for parallel-round members: `round_ts` pins the first user
/// message's timestamp (byte-identical task messages across members), and
/// `first_call_notify` is the leader-stagger signal, fired after the leader's first
/// LLM call — a leader exceeding the stagger bound misses the cached prefix.
#[derive(Clone)]
pub(crate) struct RoundOpts {
    pub(crate) round_ts: String,
    pub(crate) first_call_notify: Option<std::sync::Arc<tokio::sync::Notify>>,
}

/// Fail-open bound on the leader-stagger wait — a safety cap, not the expected wait
/// (first calls take ~4-6 s). Overridable via env for tuning, like
/// [`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 members with a leader-stagger: member 0 starts immediately, the
/// rest once the leader's first LLM call completes or the bounded wait elapses —
/// whichever first. The wait is fail-open (a failed or never-starting leader still
/// releases the followers) and interrupted by shutdown or drain.
///
/// Single-member rounds are a no-op stagger, and boot-resumed rounds (`resume = true`)
/// skip it: their sessions already diverged, so the wait would only add latency.
/// The round timestamp is rendered once and every member gets a ready-made
/// [`RoundOpts`] (only the leader carries the first-call signal, which has a single
/// waiter, so `notify_one()` releases all followers and its stored permit covers a
/// fire-before-wait race `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() {
        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, pre-seeding the session so boot resume's
    // has_session guard skips the re-append (as on the leader's path).
    handles.extend(
        followers
            .into_iter()
            .map(|m| tokio::spawn(m(follower_opts.clone()))),
    );
    handles
}

/// Everything a run releases for its own temporary use when it ends: its spill files,
/// its per-agent computer registry entries, and the chrome sessions it opened. A `Drop`
/// rather than trailing statements, because a run cut off mid-flight never reaches one;
/// the chrome part is only handed over (the `chrome-run-releases` task outlives the run).
///
/// Accepted limit: a run still working at process exit, or killed outright (`exit(0)`
/// bypasses destructors by design), queues nothing. The reclaim pass still closes its
/// tabs — it sweeps the browser's live `agent-tab-*` groups ([`crate::tools::chrome_tabs`]'s
/// honest limits) and closes any namespace no guard claims: not a live run's, not inside a
/// record's hold, not one a queued or parked record claims, not one durable state names for
/// a non-terminalized job ([`crate::tools::chrome_release::ProtectedNamespaces`]). It asks
/// the browser at a run end that queued names, at a revisit a leftover owes, and — when the
/// durable record file handed it something — at process start.
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
    /// [`crate::tools::chrome_release::holds_run_end`]'s rule.
    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 this run's spill files (the run is over).
        crate::tools::shell::cleanup_agent_spills(&self.agent_id);
        // Drop what this turn's computer use owns; app/window ids last for the session.
        crate::tools::computer::cleanup_turn_state(&self.agent_id);
        // Hand the chrome sessions to the release queue under the run's own agent id,
        // so a leftover report names its run; the tracker's own `Drop` unregisters the
        // namespace once its last owner goes.
        crate::tools::chrome_release::queue_run_session_release(
            &self.chrome,
            self.held,
            &self.agent_id,
        );
    }
}

/// Core agent lifecycle: create the agent (auto-registered with its own
/// CancellationToken), run work, handle cancellation and errors. Returns the agent
/// even on failure, with the response only on success (an error is already logged).
///
/// **Cancellation safety**: a completed `Ok` result is never discarded on cancel
/// cause — downstream consumers (pipeline finalizers, the message router) decide how
/// a cancelled run's result is handled.
///
/// `user_name` and `channel` identify the message's origin, so tools route sub-agent
/// results to the right user. `launch` is the launch this run executes — `Some` for a
/// branch role, `None` for built-ins. `messages` arrives in arrival order (see
/// [`Agent::work`]).
#[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>,
    messages: &[&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>,
    launch: Option<crate::Launch>,
) -> (Agent, Option<String>) {
    // Unregister from the message router on EVERY exit path, a mid-work panic
    // included — a leaked entry keeps routing comments to a dead agent. Only for
    // caller-registered paths: the consumer_loop path owns its entry via route()'s
    // catch_unwind cleanup and keeps 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,
        launch,
    );
    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 is released by this guard, on every path.
    let mut run_end = RunEndCleanup::new(
        agent.agent_id.clone(),
        std::sync::Arc::clone(&agent.chrome_sessions),
    );
    let result = agent.work(messages, resume).await;

    // Absorb the product's own writes into a personal folder before the turn ends, or
    // a later change report blames the user for them. Every returning turn passes here;
    // the gate matches the report's.
    crate::session::personal_changes::refresh_after_turn(
        &agent.role,
        &agent.workspace,
        agent.turn_recorded,
    )
    .await;

    // A completed Ok is kept regardless of cancel cause — the token may have fired
    // just as work() finished.
    match result {
        Ok(response) => (agent, Some(response)),
        Err(e) => {
            // Capture the full chain, so dispatchers report the real cause instead of
            // a generic placeholder.
            agent.failure = Some(format!("{e:#}"));
            agent.failure_class = failure_class_from_error(&e);
            // A refusal class fails the same way over the same bytes: remember the durable history
            // tail so the dead-session poller can tell "the history changed, one restart is worth
            // it" from "restarting would re-send exactly what was just refused".
            if agent
                .failure_class
                .is_some_and(crate::retry::FailureClass::is_deterministic)
            {
                crate::session::dead_session::record_deterministic_failure(
                    &agent.agent_id,
                    agent.session.persisted_tail(),
                );
            }
            let classification = failure_classification(&agent, Some(&e));
            agent.run_failure = Some(if is_cooperative_stop(classification) {
                crate::RunFailure::CooperativeStop
            } else {
                crate::RunFailure::Technical
            });
            // 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");
            // Cooperative ends and a deliberate cancel get the same treatment; the
            // classification above decides which log fires.
            if is_cooperative_stop(classification) {
                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),
/// `false` for fresh dispatches. `parent_key`/`parent_label` are the Running Agents
/// grouping key and its presentational label; `None` for workspace singletons.
#[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,
        None,
    )
    .await
}

/// The typed provider failure class from an error chain, when it carries a
/// [`RetryExhausted`]. `None` means the error is not provider-classified (runtime
/// errors, panics, plain I/O) — 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)
}

/// Labels meaning the run stopped cooperatively rather than failing technically.
const COOPERATIVE_STOP_CLASSES: [&str; 4] = ["drain", "shutdown", "pause", "internal_cancel"];

fn is_cooperative_stop(classification: &str) -> bool {
    COOPERATIVE_STOP_CLASSES.contains(&classification)
}

/// Stable failure classification for the agent-failure log.
///
/// Order matters: the global shutdown token fires on any stop request (SIGTERM/SIGINT,
/// the dashboard's quit, a console or session-end, a self-update) and on a completed
/// drain, so it is checked first — shutdown must never be mislabeled an internal
/// cancel. `error` is the raw source when present (`run_agent`'s `Err` arm), `None`
/// only in tests. A [`RetryExhausted`] carries the granular
/// [`crate::retry::FailureClass`]; everything else falls back to `runtime`. The
/// cooperative labels live in [`COOPERATIVE_STOP_CLASSES`], consumed by both the exit
/// log and [`Agent::failed_technically`].
fn failure_classification(agent: &Agent, error: Option<&anyhow::Error>) -> &'static str {
    if crate::shutdown::is_draining() {
        // The drain cut the round short — not a failure. Checked before the token, so
        // a drained agent is never mislabeled cancelled/shutdown (no failure emoji,
        // no exit rollback).
        "drain"
    } else if crate::shutdown::shutdown_token().is_cancelled() {
        "shutdown"
    } else if agent.is_paused_frozen() {
        // A strictly-frozen run — not a failure. The immutable bail-time snapshot is
        // authoritative, not the live pause_stop an unpause can clear.
        "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,
    }

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

        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 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,
            provider: crate::providers::selection::ProviderSelection::default(),
            round_ts: None,
            first_call_notify: None,
            failure: None,
            failure_class: None,
            run_failure: None,
            sleep_ended: false,
            turn_recorded: false,
            turn_state: crate::TurnState::default(),
            background_sessions: std::sync::Arc::new(
                crate::tools::shell::BackgroundSessions::default(),
            ),
            chrome_sessions: std::sync::Arc::new(crate::tools::chrome::ChromeRunSessions::default()),
            interrupt_token: CancellationToken::new(),
        }
    }

    /// Construct an agent with an explicit workspace and id, for path-resolving tools.
    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
    }

    #[test]
    #[serial_test::serial(drain)] // serializes the process-global drain flag
    fn failure_classification_recovers_retry_exhaustion() {
        // Serialize against the drain-flag writers: failure_classification reads the
        // process-global flag first. Mirror llm_call's error construction — via
        // .context, not string flattening — so the granular FailureClass survives.
        let exhausted = crate::retry::RetryExhausted::with_last_raw(
            vec![],
            crate::retry::FailureClass::InvalidRequest,
            None,
        );
        let err = anyhow::Error::new(exhausted).context("LLM call exhausted retry budget");
        // The {:#} chain must keep the marker engineer_failure_notice matches.
        assert!(format!("{err:#}").contains("exhausted retry budget"));

        let agent = make_agent(vec![]);
        assert_eq!(
            failure_classification(&agent, Some(&err)),
            "invalid_request",
            "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"
        );

        // An internal cancellation fires the generic token and must classify as an
        // internal cancel — every non-shutdown/non-pause stop is one.
        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 classifies as "drain", NOT cancelled/shutdown/failure: no
    /// failure emoji, and the dispatch tails skip the exit-time rollback. Serialized —
    /// the drain flag is process-global.
    #[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 (checked first).
        agent.cancel_token.cancel();
        assert_eq!(failure_classification(&agent, None), "drain");
        // Restore isolation: the drain flag is process-global, and the token must never
        // be fired from a test — it would cancel every parallel retry loop.
        crate::shutdown::drain_clear();
    }

    /// A stand-in media tool with a fixed answer, so a tool round can be driven without real
    /// generation.
    struct MediaTestTool {
        name: &'static str,
        output: String,
    }

    #[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(self.output.clone())
        }
    }

    /// Three real on-disk rasters — their display paths — and the one tool answer that names them
    /// all, so a round renders without generation and its derived-image step runs on real files.
    fn three_rendered_pictures(dir: &Path) -> (Vec<String>, String) {
        let pictures: Vec<String> = ["first.png", "second.png", "third.png"]
            .iter()
            .map(|name| {
                let path = dir.join(name);
                std::fs::write(&path, crate::util::test::noisy_png(4, 4)).expect("write png");
                std::fs::canonicalize(&path)
                    .expect("canonicalize")
                    .display()
                    .to_string()
            })
            .collect();
        let rendered = pictures
            .iter()
            .map(|picture| format!("[IMAGE:{picture}]"))
            .collect::<Vec<_>>()
            .join("\n");
        (pictures, rendered)
    }

    /// One Assistant turn over a tool round that answers `tool_answer` and a model that answers
    /// `answer`; the reply the owner receives.
    async fn turn_answering(agent_id: &str, tool_answer: &str, answer: &str) -> String {
        let tool = Box::new(MediaTestTool {
            name: "media_probe",
            output: tool_answer.to_string(),
        }) as Box<dyn Tool>;
        let fake = std::sync::Arc::new(FakeProvider::new().ok_tool_call("media_probe").ok(answer));
        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![tool], crate::Role::Assistant);
        agent.agent_id = agent_id.to_string();
        agent
            .work(&["draw me three pictures"], false)
            .await
            .expect("turn")
    }

    /// The reply the owner receives is the assistant's own text: a produced file is delivered only
    /// when the reply names it, so of three renders a reply that names one delivers that one.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn a_reply_that_names_one_of_three_renders_delivers_that_one() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());

        let dir = tempfile::TempDir::new().expect("tempdir");
        let (pictures, rendered) = three_rendered_pictures(dir.path());
        let answer = format!("The second one is the cut.\n[IMAGE:{}]", pictures[1]);
        let reply = turn_answering("named_render_agent", &rendered, &answer).await;

        assert_eq!(
            reply, answer,
            "the reply reaches the owner exactly as the assistant wrote it"
        );
        assert_eq!(
            reply.matches("[IMAGE:").count(),
            1,
            "the two renders the reply did not name are not delivered: {reply}"
        );
    }

    /// A turn that names none of its renders adds nothing to its reply, and the reply the owner
    /// receives is the message the session persisted.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn a_turn_that_names_none_of_its_renders_delivers_its_reply_unchanged() {
        crate::util::test::init_test_stores().await;
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());

        let dir = tempfile::TempDir::new().expect("tempdir");
        let (_pictures, rendered) = three_rendered_pictures(dir.path());
        let agent_id = "unnamed_render_agent";
        let reply = turn_answering(agent_id, &rendered, "Three pictures are ready.").await;

        assert_eq!(
            reply, "Three pictures are ready.",
            "the reply reaches the owner exactly as the assistant wrote it"
        );
        let history = crate::session::store().load(agent_id).await;
        let persisted = history
            .iter()
            .rev()
            .find(|m| m.role == crate::ChatRole::Assistant)
            .expect("assistant message");
        assert_eq!(
            persisted.content, reply,
            "a reasoning-free answer is persisted exactly as it is delivered"
        );
    }

    #[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(),
        });
        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() {
        /// Reads CURRENT_TOOL_USER_NAME and CURRENT_TOOL_CHANNEL from the task-locals.
        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();

        // Through execute_tool_group: the task-locals are set once per batch, as in 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"
        );
        let outcome = outcomes[0]
            .as_ref()
            .expect("the call should produce an outcome");
        assert!(outcome.success, "ReadTaskLocalsTool should succeed");
        assert!(
            outcome.output.contains("user=alice"),
            "should propagate user_name: {}",
            outcome.output
        );
        assert!(
            outcome.output.contains("channel=gui"),
            "should propagate channel: {}",
            outcome.output
        );
    }

    /// A queued job becomes a user message: a ticket comment carries its author prefix,
    /// any other kind passes its content through unformatted.
    #[tokio::test]
    async fn test_drain_incoming_messages_injects_the_job_as_a_user_message() {
        crate::util::test::init_management_test_stores().await;
        let cases = [
            (
                "_test_drain_ticket_comment",
                crate::agent::message_router::MessageKind::TicketComment,
                crate::Role::Manager,
                "manager",
                "Please fix the formatting",
                Some("[Comment from manager on ticket]"),
            ),
            (
                "_test_drain_non_comment",
                crate::agent::message_router::MessageKind::UserMessage,
                crate::Role::Assistant,
                "user",
                "Hello agent",
                None,
            ),
        ];
        for (agent_id, kind, role, user_name, content, prefix) in cases {
            let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
            let mut agent = make_agent(vec![]);
            agent.incoming_rx = Some(rx);
            agent.agent_id = agent_id.into();

            let job = crate::agent::message_router::AgentJob {
                content: content.to_string(),
                workspace_name: "test_ws".to_string(),
                user_name: user_name.to_string(),
                channel: String::new(),
                kind,
                role,
                reply_target: None,
                pending_job_id: None,
                originating_workspace: None,
                custom_role: None,
                reply_to_custom: None,
                urgent: false,
            };
            let _ = tx.send(job);

            agent.drain_incoming_messages().await;

            let history = agent.session.history();
            assert!(!history.is_empty(), "{agent_id}: at least one message");
            let last = history.last().unwrap();
            assert_eq!(
                last.role,
                crate::ChatRole::User,
                "{agent_id}: a drained job is a user message"
            );
            assert!(
                last.content.contains(content),
                "{agent_id}: content is carried: {}",
                last.content,
            );
            if let Some(prefix) = prefix {
                assert!(
                    last.content.contains(prefix),
                    "{agent_id}: comment prefix present: {}",
                    last.content,
                );
            }
        }
    }

    /// An agent with the given role and ticket attached, its session seeded with one
    /// `sessions` row (when `seed_content` is `Some`) and initialized with an empty
    /// message — mirroring the empty-message resume dispatch.
    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 — for a stage role and a non-stage role alike,
    /// with no special case for a comment the agent's own role authored (only a
    /// content already present in the loaded history suppresses it).
    #[tokio::test]
    async fn test_inject_outstanding_comments_injects_for_every_role() {
        crate::util::test::init_management_test_stores().await;
        // (agent id, role, workspace name, author, comment, phase)
        let cases: &[(
            &str,
            crate::Role,
            &str,
            &str,
            &str,
            crate::pipeline::board::TicketPhase,
        )] = &[
            (
                "inject-new-agent",
                crate::Role::Engineer,
                "inject_new",
                "manager",
                "please fix the formatting",
                crate::pipeline::board::TicketPhase::InDevelopment,
            ),
            (
                "inject-sanitation-agent",
                crate::Role::Sanitation,
                "inject_sanitation",
                "manager",
                "please verify the cleanup",
                crate::pipeline::board::TicketPhase::InSanitation,
            ),
            (
                "inject-own-role-agent",
                crate::Role::Engineer,
                "inject_own_role",
                "engineer",
                "note from the engineer",
                crate::pipeline::board::TicketPhase::InDevelopment,
            ),
            (
                "inject-analyst-agent",
                crate::Role::Analyst,
                "inject_analyst",
                "manager",
                "please fix the formatting",
                crate::pipeline::board::TicketPhase::InDevelopment,
            ),
        ];
        for &(agent_id, role, ws_name, author, 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, author, 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 prefix = format!("[Comment from {author} on ticket]");
            let history = agent.session.history();
            assert!(
                history
                    .iter()
                    .any(|m| m.content.contains(&prefix) && m.content.contains(comment)),
                "{agent_id}: 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",
        );
    }

    /// 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,
            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,
    /// automation) 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();

        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,
            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"
        );

        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,
            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,
            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,
            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());
    }

    /// The class predicate: raw empty content + no parsed tool calls, regardless of finish
    /// reason. Tool-call turns and real answers are excluded; fully-empty responses 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,
            })
        };

        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:?}");
        }
        let resp = crate::ChatResponse {
            text: Some(String::new()),
            reasoning: reasoning(),
            ..crate::ChatResponse::default()
        };
        assert!(is_reasoning_only_stop(&resp));
        let resp = crate::ChatResponse {
            text: Some("   \n ".into()),
            ..crate::ChatResponse::default()
        };
        assert!(is_reasoning_only_stop(&resp));
        let resp = crate::ChatResponse::default();
        assert!(is_reasoning_only_stop(&resp));
        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));
        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 answer is returned, the
    /// continuation request carries the appended tail (reasoning payload + 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 one pair each, 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.
        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 messages begin with
        // attempt 2's verbatim (nothing rewritten).
        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"
        );
    }

    /// Exhaustion fails the turn safely: a NoResponse [`RetryExhausted`] with
    /// `last_raw: None`, no reasoning text, no retry marker, no transcript trace, and a
    /// granular "no_response" class.
    #[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 tail: the retried request is
    /// byte-identical, and the final class comes from the last failure (Transport).
    #[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 error breaks immediately 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::InvalidRequest, "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::InvalidRequest,
            "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 between attempts classifies the terminal error as Shutdown, not
    /// NoResponse — the real cause must not be masked, even before the first attempt (no
    /// request sent, nothing 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 mut 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, then restore (never fire the token here).
        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"
        );
    }

    /// On success the session length comes from the RESOLVING response only — the
    /// in-class response is never recorded.
    #[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 exhaustion keeps failing open: the empty-response error fires and the
    /// thinking never leaks into it.
    #[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 mut 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"
        );
    }

    /// Tool-call answers exhaust the budget at [`SUMMARIZE_ATTEMPTS`] with the same
    /// outcome: the empty-response error fires.
    #[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 mut 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"
        );
    }

    /// 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));

        agent
            .record_session_usage(&crate::ChatResponse::default())
            .await;
        assert_eq!(agent.session.token_length(), Some(7_000));

        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));

        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"
        );
    }

    /// An unknown session length only disables the token trigger; with no images present
    /// the check exits before the summarize call. No provider is installed on purpose —
    /// reaching [`Agent::summarize`] would panic.
    #[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![]);

        agent.maybe_summarize(agent.session.history().len()).await;
        assert_eq!(agent.session.token_length(), None);

        agent
            .session
            .set_token_length(Some(crate::session::SUMMARIZATION_THRESHOLD / 2));
        agent.maybe_summarize(agent.session.history().len()).await;
    }

    /// Post-delivery compaction for the long-lived chat roles: only they may compact with
    /// the reply delivered, and never on a turn that settled dangling results, was
    /// cancelled, or ran while going down. Both triggers fire on the next turn's own
    /// terms, and the recorded length goes with the compacted history in one transaction.
    #[tokio::test]
    #[serial_test::serial(active_models, provider, drain)]
    async fn post_delivery_summarization_compacts_chat_roles_and_clears_the_length() {
        crate::util::test::init_test_stores().await;
        seed_empty_catalogs();
        let _policy_guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        let fake = std::sync::Arc::new(FakeProvider::new().ok("the summary"));
        let provider: std::sync::Arc<dyn crate::Provider> = fake.clone();
        let _provider_guard = install_fake_provider(provider);

        let over_threshold = |role| {
            let mut agent = make_agent_with_role(vec![], role);
            agent
                .session
                .set_token_length(Some(crate::session::SUMMARIZATION_THRESHOLD + 1));
            agent
        };
        let calls = || fake.request_fingerprints.lock().unwrap().len();

        // Pipeline working roles and worker branches keep the pre-turn behaviour.
        for role in [
            crate::Role::Engineer,
            crate::Role::Analyst,
            crate::Role::Worker,
            crate::Role::Maintainer,
        ] {
            over_threshold(role).maybe_summarize_after_delivery().await;
        }

        // A settled turn is resume-like: the window would drop the just-settled result.
        let mut settled = over_threshold(crate::Role::Assistant);
        settled.turn_state.settled_tool_results = true;
        settled.maybe_summarize_after_delivery().await;

        // A cancelled run never spends a summarization call on itself.
        let mut cancelled = over_threshold(crate::Role::Assistant);
        cancelled.cancel_token.cancel();
        cancelled.maybe_summarize_after_delivery().await;

        // Going down: no destructive compaction during the drain window.
        crate::shutdown::drain_begin();
        over_threshold(crate::Role::Assistant)
            .maybe_summarize_after_delivery()
            .await;
        crate::shutdown::drain_clear();

        assert_eq!(
            calls(),
            0,
            "no excluded role or turn may spend a summarization call"
        );

        // Each chat role does compact, and its recorded length goes with the history,
        // through the production writer.
        for (role, agent_id) in [
            (crate::Role::Assistant, "e2e_post_delivery_assistant"),
            (crate::Role::Manager, "e2e_post_delivery_manager"),
            (crate::Role::Custom, "e2e_post_delivery_custom"),
        ] {
            let mut agent = make_agent_with_role(vec![], role);
            agent.agent_id = agent_id.to_string();
            agent.session.push_messages_unpersisted(&[
                ChatMessage::user("hello"),
                ChatMessage::assistant("hi"),
            ]);
            agent
                .record_session_usage(&crate::ChatResponse {
                    usage: Some(crate::ProviderUsage {
                        input_tokens: Some(crate::session::SUMMARIZATION_THRESHOLD),
                        output_tokens: Some(1),
                        ..crate::ProviderUsage::default()
                    }),
                    ..crate::ChatResponse::default()
                })
                .await;
            assert_eq!(
                reload_token_length(agent_id).await,
                Some(crate::session::SUMMARIZATION_THRESHOLD + 1),
                "the over-limit length is the one the next turn loads"
            );

            let before = calls();
            agent.maybe_summarize_after_delivery().await;
            assert_eq!(
                calls(),
                before + 1,
                "an over-limit {role} session must compact here"
            );
            assert_eq!(
                agent.session.token_length(),
                None,
                "the pre-compaction length must be cleared"
            );
            assert_eq!(
                reload_token_length(agent_id).await,
                None,
                "the next turn must compact nothing again"
            );

            // The image trigger fires on its own terms: images pushed after the compaction
            // leave the session over the count, and delivery carries no "already
            // compacted" clause.
            agent.session.push_messages_unpersisted(
                &(0..crate::session::SUMMARIZATION_IMAGE_COUNT)
                    .map(|i| ChatMessage::user(format!("[IMAGE:data:image/jpeg;base64,img{i}]")))
                    .collect::<Vec<_>>(),
            );
            let image_count = session_image_marker_count(agent.session.history());
            assert_eq!(
                summarization_trigger(agent.session.token_length(), image_count),
                Some("image count"),
                "the image trigger must be the one firing here"
            );
            agent.maybe_summarize_after_delivery().await;
            assert_eq!(
                calls(),
                before + 2,
                "an over-image-count {role} session must compact here too"
            );
        }
    }

    /// The cap holds on the request the agent actually sends: the conversation keeps every picture,
    /// the request carries the newest ones and no more, and the retired ones read as the omission
    /// note.
    #[tokio::test]
    async fn build_chat_request_bounds_the_pictures_it_sends() {
        crate::util::test::init_test_stores().await;
        let mut agent = make_agent_with_role(vec![], crate::Role::Assistant);
        let total = crate::session::SUMMARIZATION_IMAGE_COUNT + 11;
        let pictures: Vec<ChatMessage> = (0..total)
            .map(|serial| {
                ChatMessage::user(format!(
                    "shot {serial} [IMAGE:data:image/png;base64,{serial:0>8}]"
                ))
            })
            .collect();
        agent.session.push_messages_unpersisted(&pictures);

        let request = agent.build_chat_request(agent.session.history().to_vec(), "agent");

        // Past thirty pictures the cap is crossed twice over, so two whole batches step aside.
        assert_eq!(
            crate::session::image_cap::count(&request.messages),
            total - 2 * crate::session::image_cap::RETIRE_BATCH
        );
        assert!(
            request.messages[total - 1]
                .content
                .contains("data:image/png;base64,00000030"),
            "the newest picture is always among the ones sent"
        );
        assert!(!request.messages[0].content.contains("data:image/"));
        assert!(request.messages[0].content.contains("data-uri omitted"));
        assert_eq!(
            crate::session::image_cap::count(agent.session.history()),
            total,
            "the conversation itself keeps every picture"
        );
    }

    /// The run holds one provider: every request it builds carries the conversation's provider, a
    /// stored provider that no longer serves the model is replaced by a fresh choice from the top of
    /// the list, and a model change under the run re-selects. Durability is
    /// [`the_first_turn_records_its_provider_once_finalize_creates_the_row`]'s subject.
    #[tokio::test]
    async fn a_run_holds_one_provider_and_follows_a_model_change() {
        use crate::providers::selection;

        crate::util::test::init_test_stores().await;
        let mut agent = make_agent(vec![]);
        agent.agent_id = "provider-wiring".into();
        let model = crate::config::CONFIG.role_model(agent.role);
        // The outage map is process-global and production `chat_scoped` calls elsewhere in this
        // binary write to it, so the model starts from a clock this test controls.
        selection::clear_outages(&model);
        let expected = selection::pick(&model)
            .expect("the default routing pins the default chat model to a provider");

        let stale = selection::StoredProvider {
            model: model.clone(),
            provider: "no-longer-listed".into(),
        };
        agent.provider = selection::ProviderSelection::resolve(&model, Some(&stale));
        assert_eq!(agent.provider.slug(), Some(expected.as_str()));

        // Every request of the run carries it.
        let request = agent.build_chat_request(vec![crate::ChatMessage::user("hi")], "agent");
        assert_eq!(request.provider.as_deref(), Some(expected.as_str()));

        // A model change under the run re-selects: a live provider chosen for another model says
        // nothing about this one, so the request re-picks for the model it carries and the run
        // records it.
        agent.provider =
            selection::ProviderSelection::for_test("selection/some-other-model", &["live"], "live");
        let request = agent.build_chat_request(vec![crate::ChatMessage::user("hi")], "agent");
        assert_eq!(
            request.provider.as_deref(),
            Some(expected.as_str()),
            "another model's live provider is not reused"
        );
        assert_eq!(
            agent.provider.stored().map(|stored| stored.model),
            Some(model.clone()),
            "the run's selection follows the model the request carries"
        );
    }

    /// A conversation whose first turn makes a single model call still records its provider: the
    /// write lands nowhere before the session has a metadata row, and `finalize` retries it once it
    /// has one. Without that, the choice would survive neither a restart nor a resumed run.
    #[tokio::test]
    async fn the_first_turn_records_its_provider_once_finalize_creates_the_row() {
        use crate::providers::selection;

        crate::util::test::init_test_stores().await;
        let mut agent = make_agent(vec![]);
        agent.agent_id = "provider-first-turn".into();
        let model = crate::config::CONFIG.role_model(agent.role);
        // As above: the outage clock is process-global, so this test starts from a clean model.
        selection::clear_outages(&model);
        let expected = selection::pick(&model)
            .expect("the default routing pins the default chat model to a provider");

        agent.provider = selection::ProviderSelection::resolve(&model, None);
        assert_eq!(agent.provider.slug(), Some(expected.as_str()));
        // No metadata row exists yet, so the write lands nowhere and records nothing.
        agent.persist_provider().await;
        assert_eq!(
            crate::session::store().get_provider(&agent.agent_id).await,
            None,
        );

        // `finalize` flushes the tail (creating the row) and the retry records the provider.
        agent.session.push_messages_unpersisted(&[
            crate::ChatMessage::user("hi"),
            crate::ChatMessage::assistant("hello"),
        ]);
        agent
            .finalize_session()
            .await
            .expect("finalize persists the unpersisted tail");
        let recorded = crate::session::store()
            .get_provider(&agent.agent_id)
            .await
            .map(|stored| stored.provider);
        // The row is real: remove it, so the shared test store is left as this test found it.
        let _ = crate::session::store().delete(&agent.agent_id).await;
        assert_eq!(
            recorded,
            Some(expected),
            "the first turn's provider must not be lost to the next run's re-selection"
        );
    }

    /// 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"}}"#;

    /// The recorded session length as a fresh turn's session init would load it.
    async fn reload_token_length(agent_id: &str) -> Option<u64> {
        let mut session = crate::session::Session::default();
        session.init(agent_id).await.expect("session init");
        session.token_length()
    }

    /// 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 image must not fail the run: it is durably stripped from the most recent
    /// user message (replaced by the phrase) and the loop continues — 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 phrase and no marker in the user
        // message (the system prompt mentions "[IMAGE:path]" literally, so assert on 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"
        );

        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 original text plus the phrase, with NO extra message injected.
        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 code does not trigger the strip: the run
    /// takes the normal failure path and the image stays.
    #[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"
        );

        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 later failure does NOT re-strip: the message carries no
    /// marker, so the normal path applies (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"
        );

        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"
        );
    }

    /// A provider refusal over a history carrying a leaked control token is repaired durably and the
    /// normal loop continues: the second round succeeds and the persisted history no longer holds a
    /// token. The token sits in an ASSISTANT reply, which is where a model emits one — and which the
    /// old "most recent user message" rewrite could never reach.
    #[tokio::test]
    #[serial_test::serial(active_models, provider, drain)] // seeds the process-global catalog caches + process-global fake provider + shutdown drain flag
    async fn leaked_control_token_in_a_reply_is_neutralized_and_the_round_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_leaked_token";
        // A previous turn left a control token in a model reply: it is persisted, so every later
        // request re-sends it and the provider refuses the content.
        let mut seed = crate::session::Session::default();
        seed.persist_messages(
            agent_id,
            &[
                ChatMessage::system("role description"),
                ChatMessage::user("what is this?"),
                ChatMessage::assistant("it is an <|image|> token"),
            ],
        )
        .await
        .unwrap();

        let fake = std::sync::Arc::new(
            FakeProvider::new()
                .err(
                    crate::retry::FailureClass::ContentRejection,
                    "Input data may not contain model control tokens.",
                )
                .ok("Recovered: the token is gone."),
        );
        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(&["and now?"], false)
            .await
            .expect("a leaked token must not fail the run wholesale");
        assert_eq!(resp, "Recovered: the token is gone.");

        // The repaired history reached the model on the retry.
        let messages = fake.request_messages.lock().unwrap().clone();
        assert_eq!(messages.len(), 2, "refused attempt + normal-loop retry");
        assert!(
            messages[0].contains("<|image|>"),
            "the refused request still carried the token"
        );
        assert!(
            !messages[1].contains("<|"),
            "the retried request carries no token at all"
        );

        let history = crate::session::store().load(agent_id).await;
        assert!(
            history.iter().all(|m| !m.content.contains("<|")),
            "the token is durably gone from the session: {history:?}"
        );
        assert!(
            history
                .iter()
                .any(|m| m.content.contains(crate::util::control_token::PLACEHOLDER)),
            "the reply is preserved with the placeholder in the token's place"
        );
    }

    /// A token that sits only in the UNPERSISTED tail cannot be rewritten positionally (a store
    /// UPDATE would hit a different row), so the repair reports no rewrite and the original failure
    /// propagates — the loop must not `continue`, which would skip `tool_rounds += 1` and retry
    /// forever.
    #[tokio::test]
    async fn leaked_token_in_the_unpersisted_tail_keeps_the_original_failure() {
        crate::util::test::init_test_stores().await;

        let agent_id = "e2e_assistant_leaked_token_tail";
        let mut agent = make_agent_with_role(vec![], crate::Role::Assistant);
        agent.agent_id = agent_id.to_string();
        // Memory only: `push_messages_unpersisted` is the path a failed store append takes.
        agent.session.push_messages_unpersisted(&[
            ChatMessage::system("role description"),
            ChatMessage::assistant("it is an <|image|> token"),
        ]);

        let inner = anyhow::anyhow!("Input data may not contain model control tokens.");
        let exhausted = crate::retry::RetryExhausted::with_last_raw(
            vec![crate::retry::RetryFailureRecord::new_simple(
                crate::retry::FailureClass::ContentRejection,
                &inner,
                None,
            )],
            crate::retry::FailureClass::ContentRejection,
            None,
        );

        assert!(
            !agent.neutralize_leaked_control_tokens(&exhausted).await,
            "an unpersisted tail is a no-op, so the loop must not continue"
        );
        assert_eq!(
            agent.session.history()[1].content,
            "it is an <|image|> token",
            "in-memory history untouched"
        );
        assert!(
            crate::session::store().load(agent_id).await.is_empty(),
            "nothing was written for a tail the store never saw"
        );
    }

    /// DISTINCT `data:image/`-prefixed IMAGE markers in User-role messages. The gate is
    /// prefix-only: real PNG data-URIs count, duplicates collapse, file paths, non-IMAGE
    /// kinds and assistant messages do not.
    #[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 decision is asymmetric: strict `>` for tokens, `>=` for images; the token
    /// trigger reports the reason when both fire.
    #[test]
    fn summarization_trigger_decides_reason() {
        use crate::session::{SUMMARIZATION_IMAGE_COUNT, SUMMARIZATION_THRESHOLD};
        let just_below = SUMMARIZATION_IMAGE_COUNT - 1;
        assert_eq!(summarization_trigger(None, just_below), 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), just_below), None);
        assert_eq!(
            summarization_trigger(Some(1), SUMMARIZATION_IMAGE_COUNT),
            Some("image count")
        );
    }

    /// The synthetic image message lands AFTER the round's tool-result block and dedups a
    /// repeat read of an 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 in the conversation.
        agent.session.push_messages_unpersisted(&[ChatMessage::user(
            "[IMAGE:data:image/jpeg;base64,prior]",
        )]);
        // Emission-time durability: the frame is persisted 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(),
                    picture_size: (1, 1),
                    copy_size: (1, 1),
                    format: "PNG".into(),
                    recovery_note: None,
                    note: None,
                    source: crate::tools::ImagePayloadSource::Read,
                }],
                text_is_content: false,
                preserve_text: 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(),
                    picture_size: (1, 1),
                    copy_size: (1, 1),
                    format: "PNG".into(),
                    recovery_note: None,
                    note: None,
                    source: crate::tools::ImagePayloadSource::Read,
                }],
                text_is_content: false,
                preserve_text: 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), both tool results, then user(fresh) —
        // 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:?}"
        );
        // The repeat read of 'prior' is not re-injected; the fresh image 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 text comes from the payload metadata: the deduped read returns the
        // 'already in the conversation' reference, the fresh one the 'attached' wording. Content is a
        // JSON envelope, 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 in the conversation as a native image and is not attached again.",
                "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 reads within one round are deduped by `seen_data_uris`: only the
    /// first is injected.
    #[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(),
                    picture_size: (1, 1),
                    copy_size: (1, 1),
                    format: "PNG".into(),
                    recovery_note: None,
                    note: None,
                    source: crate::tools::ImagePayloadSource::Read,
                }],
                text_is_content: false,
                preserve_text: 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(),
                    picture_size: (1, 1),
                    copy_size: (1, 1),
                    format: "PNG".into(),
                    recovery_note: None,
                    note: None,
                    source: crate::tools::ImagePayloadSource::Read,
                }],
                text_is_content: false,
                preserve_text: 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 claims a fresh attachment; the second an already-attached reference.
        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 in 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 is clearable.
    #[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}"),
            picture_size: (1, 1),
            copy_size: (1, 1),
            format: "JPEG".into(),
            recovery_note: None,
            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,
                preserve_text: 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,
                preserve_text: 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 persisted content of the history's tool results, parsed out of their JSON envelope.
    fn tool_result_texts(history: &[ChatMessage]) -> 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()
    }

    /// The content side of the image invariant: a result whose text is content — a
    /// document's extracted text — is neither read as a claim nor replaced by an
    /// annotation. A marker inside it stays literal and injects nothing, while a real
    /// payload SUPPLEMENTS the text: the annotation is appended.
    #[tokio::test]
    async fn commit_tool_results_handles_content_text() {
        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,
            preserve_text: 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 tool_result = tool_result_texts(history).remove(0);
        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:?}"
        );

        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 content was 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(),
                picture_size: (800, 1000),
                copy_size: (800, 1000),
                format: "JPEG".into(),
                recovery_note: None,
                note: None,
                source: crate::tools::ImagePayloadSource::Generated,
            }],
            text_is_content: true,
            preserve_text: 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 tool_result = tool_result_texts(history).remove(0);
        assert_eq!(
            tool_result,
            "[scan.pdf: no text could be extracted — the content was 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");

        // A media tool with no payload of its own: the derived-image path exists for such
        // output — image_gen, chrome and computer ship their own and never reach it.
        let tool = Box::new(MediaTestTool {
            name: "media_probe",
            output: String::new(),
        }) 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: "media_probe".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.
        let outcomes = vec![ToolExecutionOutcome {
            output: marker.clone(),
            success: true,
            image_payloads: Vec::new(),
            text_is_content: false,
            preserve_text: 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();
        // 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:?}"
        );
    }

    /// (c) A non-durable dangling call is re-executed and settles 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!({"message": "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!({"message": "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 is dropped with the
    /// settle, so a later, unrelated call can never bind it.
    #[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!({"message": "analyze task one"}),
                },
                crate::ToolCall {
                    id: "call_analyze_g2".to_string(),
                    name: "analyze".to_string(),
                    arguments: serde_json::json!({"message": "analyze task two"}),
                },
            ],
            None,
        )
        .to_string();
        session
            .persist_messages(
                pin,
                &[
                    ChatMessage::user("analyze this"),
                    ChatMessage::assistant(frame),
                ],
            )
            .await
            .unwrap();

        // The frame row is backdated so all three seeded jobs fall inside the
        // frame's OWN window (created after it): the pool itself has no age gate,
        // but a pool entry older than the frame belongs to an earlier frame and
        // is abandoned with the settle rather than bound. 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 is dropped with the settle.
        conn.execute(
            "UPDATE sessions SET created_at = '2024-01-01T00:00:00+00:00' \
             WHERE agent_id = ?1 AND role = 'assistant'",
            crate::db::params![pin],
        )
        .await
        .unwrap();
        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),
                None,
                None,
            )
            .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());

        // Both bound jobs are terminalized and the third is dropped with the
        // settle — no call can ever bind it (a call's round kind is resolved from
        // the call itself), so it must not stay in the pool.
        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!(
            jobs.is_empty(),
            "the unbound job is dropped with the settle: a later call must never bind it"
        );

        // 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"
        );
    }

    /// (f) A frame whose calls bind no job at all still drops the pool's
    /// leftovers: the launched row of a cut-mid-flight call the tool no longer
    /// knows is unreachable (nothing matches it by name any more), so it is
    /// abandoned with the settle instead of staying in the pool for a later,
    /// unrelated call to bind and settle an old report as its own result. The cut
    /// call itself is simply repeated — never aliased.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn complete_pending_tool_calls_drops_a_leftover_no_call_can_bind() {
        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_leftover_pool");
        let pin = "leftover_pool_pin";
        let conn = &crate::session::store().conn;

        // One dangling call to a tool this build does not have.
        let mut session = Session::default();
        let frame = assistant_replay_payload(
            Some(""),
            &[crate::ToolCall {
                id: "call_retired".to_string(),
                name: "retired_tool".to_string(),
                arguments: serde_json::json!({"message": "old work"}),
            }],
            None,
        )
        .to_string();
        session
            .persist_messages(
                pin,
                &[
                    ChatMessage::user("do the old thing"),
                    ChatMessage::assistant(frame),
                ],
            )
            .await
            .unwrap();

        // The launched row that call left behind.
        crate::jobs::spawn_job(
            conn,
            "leftover_job",
            "old work",
            &ws.name,
            "caller-user",
            "telegram",
            crate::Role::Engineer,
            &[crate::jobs::NewAgent {
                agent_id: "leftover_job_analyst".to_string(),
                kind: crate::jobs::AgentKind::Analyst,
                idx: Some(0),
                task: "old work".to_string(),
            }],
            &crate::jobs::SpawnChild::Analyze,
            Some(pin),
            None,
            None,
        )
        .await
        .unwrap();

        let mut agent = make_agent_on(vec![], pin, ws);
        agent.session = session;
        let settled = agent.complete_pending_tool_calls().await.unwrap();
        assert!(settled, "the re-executed call settles its own result");

        let jobs = conn
            .query(
                "SELECT id FROM jobs WHERE id = 'leftover_job'",
                crate::db::params![],
            )
            .await
            .unwrap();
        assert!(
            jobs.is_empty(),
            "the unbound launched row is abandoned with the settle, not left for a later call"
        );
    }

    /// (g) A pool entry OLDER than the frame belongs to an earlier frame, and this
    /// frame's call must never bind it — that would settle the old round's report as its
    /// own result. It is abandoned with the settle and the call runs fresh.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn complete_pending_tool_calls_never_binds_a_job_older_than_its_frame() {
        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_frame_window");
        let pin = "frame_window_pin";
        let conn = &crate::session::store().conn;

        // One dangling `send` worker call, emitted AFTER the stale round below.
        let mut session = Session::default();
        let frame = assistant_replay_payload(
            Some(""),
            &[crate::ToolCall {
                id: "call_worker_now".to_string(),
                name: "send".to_string(),
                arguments: serde_json::json!({"message": "the new task", "addressee": "worker"}),
            }],
            None,
        )
        .to_string();
        session
            .persist_messages(
                pin,
                &[
                    ChatMessage::user("code the new task"),
                    ChatMessage::assistant(frame),
                ],
            )
            .await
            .unwrap();

        // The leftover of an EARLIER frame: a launched round with a stored outcome.
        crate::jobs::spawn_job(
            conn,
            "stale_frame_job",
            "the old task",
            &ws.name,
            "caller-user",
            "telegram",
            crate::Role::Engineer,
            &[crate::jobs::NewAgent {
                agent_id: "stale_frame_job_worker".to_string(),
                kind: crate::jobs::AgentKind::Worker,
                idx: Some(0),
                task: "the old task".to_string(),
            }],
            &crate::jobs::SpawnChild::Implement,
            Some(pin),
            None,
            None,
        )
        .await
        .unwrap();
        crate::jobs::write_agent_outcome(
            conn,
            "stale_frame_job",
            "stale_frame_job_worker",
            crate::jobs::RowStatus::Done,
            Some("STALE_RESULT"),
        )
        .await
        .unwrap();
        conn.execute(
            "UPDATE jobs SET created_at = '2024-01-01T00:00:00+00:00' WHERE id = 'stale_frame_job'",
            crate::db::params![],
        )
        .await
        .unwrap();

        let mut agent = make_agent_on(vec![], pin, ws);
        agent.session = session;
        let settled = agent.complete_pending_tool_calls().await.unwrap();
        assert!(settled, "the call settles a result of its own");

        let mut per_call: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        for msg in agent.session.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);
        }
        let content = per_call.get("call_worker_now").expect("the call settles");
        assert!(
            !content.contains("STALE_RESULT"),
            "the earlier frame's report must never become this call's result: {content}"
        );

        let jobs = conn
            .query(
                "SELECT id FROM jobs WHERE caller_agent_id = ?1 AND status = 'launched'",
                crate::db::params![pin],
            )
            .await
            .unwrap();
        assert!(
            jobs.is_empty(),
            "the pre-frame row is abandoned with the settle, not left for a later call"
        );
    }

    /// Seed a spill file for a fresh test-only agent id plus a run session tracker
    /// holding one name; the temp dir outlives the guard that reclaims it.
    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`), holding a name as a `ChromeTool` 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 deadline abort or a panic — 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();
    }

    /// Every end hands its sessions over, and the ends `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();
    }

    /// Both read-only, so they run in one parallel group; `hang` never returns and
    /// announces that it started.
    struct UrgentTestTool {
        tool_name: &'static str,
        result: String,
        started: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
    }

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

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

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

        fn side_effects(&self) -> bool {
            false
        }

        async fn execute(
            &self,
            _ws: &crate::Workspace,
            _args: serde_json::Value,
        ) -> anyhow::Result<String> {
            match &self.started {
                Some(started) => {
                    started.store(true, std::sync::atomic::Ordering::SeqCst);
                    std::future::pending().await
                }
                None => Ok(self.result.clone()),
            }
        }
    }

    /// A turn cut by an urgent message: the returned call keeps its result, the in-flight
    /// one settles with the fixed interrupted result, nothing is replayed, and the phrase is
    /// the session's whole record of the interruption — the reply is empty, not a failure,
    /// not a cancellation.
    #[tokio::test]
    #[serial_test::serial(provider, drain)]
    async fn urgent_interrupt_records_the_phrase_and_returns_no_reply() {
        crate::util::test::init_test_stores().await;
        let started = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let fake = std::sync::Arc::new(FakeProvider::new().ok_text_and_tool_calls(
            "",
            &[
                ("quick", serde_json::json!({})),
                ("hang", serde_json::json!({})),
            ],
        ));
        let _provider_guard = install_fake_provider(fake);
        let mut agent = make_agent_with_role(
            vec![
                Box::new(UrgentTestTool {
                    tool_name: "quick",
                    result: "the sibling's own result".into(),
                    started: None,
                }),
                Box::new(UrgentTestTool {
                    tool_name: "hang",
                    result: String::new(),
                    started: Some(std::sync::Arc::clone(&started)),
                }),
            ],
            crate::Role::Engineer,
        );
        agent.agent_id = "e2e_urgent_interrupt".to_string();
        let interrupt = agent.interrupt_token.clone();
        let turn = tokio::spawn(async move {
            let answer = agent.work(&["do two things"], false).await;
            (agent, answer)
        });
        while !started.load(std::sync::atomic::Ordering::SeqCst) {
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
        interrupt.cancel();

        let (agent, answer) = turn.await.expect("the turn task must not panic");
        assert_eq!(
            answer.expect("an interrupted turn is not a failure"),
            "",
            "the turn hands back no reply: nothing is delivered"
        );
        assert!(
            agent.turn_state.interrupted,
            "the router must skip delivery for this turn"
        );
        assert!(
            !agent.cancel_token.is_cancelled(),
            "the interrupt is not a cancellation"
        );

        let history = agent.session.history().to_vec();
        let results: Vec<String> = history
            .iter()
            .filter(|message| message.role == crate::ChatRole::Tool)
            .map(|message| {
                let payload: serde_json::Value =
                    serde_json::from_str(&message.content).expect("tool result is JSON");
                crate::util::json::get_str(&payload, "content")
                    .expect("tool result has content")
                    .to_string()
            })
            .collect();
        assert_eq!(results.len(), 2, "every call of the cut round has a result");
        assert_eq!(
            results[0], "the sibling's own result",
            "a call that had already returned keeps its real result"
        );
        assert_eq!(
            results[1],
            crate::prompt::load_prompt("tool_interrupted.md").trim(),
            "the cut call is settled with the one fixed interrupted result"
        );
        assert_eq!(
            history.last().map(|message| message.content.as_str()),
            Some("interrupted by the user"),
            "the phrase is the session's whole record of the interruption"
        );
        assert!(
            agent.session.pending_tool_frame().is_none(),
            "no call is left dangling for a later turn to replay"
        );
    }
}