choreo-daemon 0.2.0

Agentic coding assistant — daemon, TUI, and bridges
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
// NOTE: the #[serial_test::serial(...)] attribute on this test module
// re-emits it without the #[cfg(test)] marker, so clippy's
// allow-*-in-tests config no longer recognizes it as test code —
// the AGENTS.md test allowances are spelled out here instead.
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::panic_in_result_fn,
    clippy::indexing_slicing
)]
use super::*;
use crate::context::LoadedSkill;
use crate::daemon::DaemonCommand;
use crate::providers::InferenceProvider;
use crate::providers::test_util::{make_failing_provider, make_test_provider};
use crate::reasoning::{
    build_chat_request_messages, initial_prev_resp_id, warn_on_missing_reasoning_artifacts,
};
use crate::tools::context::ToolContext;
use crate::tools::{Tool, ToolError, ToolExecError, ToolRegistry};
use choreo_ai_protocols::openai::{AssistantToolCall, AssistantToolFunction};
use choreo_keystore::ServiceCredential;
use choreo_proto::{ChatReasoningField, ReasoningArtifact};
use std::sync::mpsc;

/// Protected set for the mirror tests: just "core" (no platform tools
/// registered in these unit tests).
fn core_protected() -> std::collections::HashSet<String> {
    std::collections::HashSet::from(["core".into()])
}

fn make_session_with_turns() -> SessionState {
    let mut session = SessionState::empty();
    let (tid0, _) = session.start_turn(Some("hello".into()));
    session.set_assistant_response(
        tid0,
        AssistantResponse {
            text: Some("hi".into()),
            ..Default::default()
        },
    );
    session
}

// Neutral provider/model for structure-only tests: the slug is not in the
// catalog, so the passback policy resolves to None and no artifact is ever
// attached — the exact behavior those tests assert.
const TEST_PROVIDER: &str = "test-stub";
const TEST_MODEL: &str = "test-model";

#[test]
fn build_chat_request_messages_empty() {
    let session = SessionState::empty();
    let result = build_chat_request_messages(&session, None, TEST_PROVIDER, TEST_MODEL);
    assert!(result.is_empty());
}

#[test]
fn build_chat_request_messages_with_system_prompt() {
    let session = SessionState::empty();
    let result =
        build_chat_request_messages(&session, Some("system prompt"), TEST_PROVIDER, TEST_MODEL);
    assert_eq!(result.len(), 1);
    assert_eq!(result[0].role, "system");
    assert_eq!(result[0].content.as_deref(), Some("system prompt"));
}

#[test]
fn build_chat_request_messages_user_and_assistant() {
    let session = make_session_with_turns();
    let result = build_chat_request_messages(&session, None, TEST_PROVIDER, TEST_MODEL);
    assert_eq!(result.len(), 2);
    assert_eq!(result[0].role, "user");
    assert_eq!(result[0].content.as_deref(), Some("hello"));
    assert_eq!(result[1].role, "assistant");
    assert_eq!(result[1].content.as_deref(), Some("hi"));
}

#[test]
fn build_chat_request_messages_with_tool_calls() {
    let mut session = SessionState::empty();
    let (tid, _) = session.start_turn(Some("list files".into()));
    let records = vec![AssistantToolCallRecord {
        call_id: "call_1".into(),
        name: "ls".into(),
        arguments_json: r#"{"path": "."}"#.into(),
    }];
    session.set_assistant_response(
        tid,
        AssistantResponse {
            text: Some("thinking".into()),
            tool_calls: records.clone(),
            ..Default::default()
        },
    );
    // Placeholder results are seeded in call order; the finished tool
    // updates its slot in place.
    session.seed_tool_results(tid, &records, &["".into()]);
    session.update_tool_result(
        tid,
        "call_1",
        "ls".into(),
        &ToolOutput {
            content: "file.txt".into(),
            is_error: false,
            invocation_description: String::new(),
            ..Default::default()
        },
    );

    let result = build_chat_request_messages(&session, None, TEST_PROVIDER, TEST_MODEL);
    assert_eq!(result.len(), 3);
    assert_eq!(result[0].role, "user");
    assert_eq!(result[1].role, "assistant");
    assert!(result[1].tool_calls.is_some());
    assert_eq!(result[2].role, "tool");
    assert_eq!(result[2].tool_call_id.as_deref(), Some("call_1"));
}

/// Write a tiny opaque PNG to a temp file and return the handle plus its path.
fn write_temp_png() -> tempfile::NamedTempFile {
    let buf = image::ImageBuffer::from_fn(3, 2, |x, y| {
        image::Rgb([(x * 80) as u8, (y * 90) as u8, 40])
    });
    let mut file = tempfile::NamedTempFile::new().expect("temp png");
    image::DynamicImage::ImageRgb8(buf)
        .write_to(&mut file, image::ImageFormat::Png)
        .expect("write png");
    file
}

/// Build a session whose single turn's `read_image` tool result carries an
/// image reference to a real temp PNG.
fn session_with_image_result() -> (SessionState, tempfile::NamedTempFile) {
    let file = write_temp_png();
    let mut session = SessionState::empty();
    let (tid, _) = session.start_turn(Some("look at this image".into()));
    session.set_assistant_response(
        tid,
        AssistantResponse {
            text: Some("Reading the image.".into()),
            tool_calls: vec![AssistantToolCallRecord {
                call_id: "call_img".into(),
                name: "read_image".into(),
                arguments_json: r#"{"path": "/tmp/x.png"}"#.into(),
            }],
            ..Default::default()
        },
    );
    let calls = session.turns[&tid].tool_calls.clone();
    session.seed_tool_results(tid, &calls, &["".into()]);
    let img_ref = choreo_proto::ImageReference {
        path: file.path().display().to_string(),
        mime_type: "image/jpeg".into(),
        width: 3,
        height: 2,
        // Non-empty stored bytes so the vision-attach path attaches the image
        // (an empty `data` would degrade to a placeholder).
        data: vec![0u8; 16],
    };
    session.update_tool_result(
        tid,
        "call_img",
        "read_image".into(),
        &ToolOutput {
            content: "read image: (3x2, image/jpeg)".into(),
            is_error: false,
            invocation_description: String::new(),
            image_ref: Some(img_ref),
            ..Default::default()
        },
    );
    (session, file)
}

#[test]
fn build_chat_request_messages_vision_model_attaches_image() {
    // On a vision-capable model, an image-bearing tool result yields a
    // synthetic user message carrying the image, appended after the tool
    // message (tool_use→tool_result adjacency preserved).
    let (session, _file) = session_with_image_result();
    let result =
        build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-flash-vision-exp");
    assert_eq!(result.len(), 4); // user, assistant, tool, image-user
    assert_eq!(result[2].role, "tool");
    assert_eq!(result[3].role, "user");
    assert_eq!(result[3].images.len(), 1);
    assert_eq!(result[3].images[0].mime_type, "image/jpeg");
    assert!(
        result[3]
            .content
            .as_deref()
            .unwrap()
            .contains("[image from")
    );
}

#[test]
fn build_chat_request_messages_non_vision_model_gates_image() {
    // On a text-only model the gate replaces the image with a placeholder
    // text message (no pixels), so the request never 400s.
    let (session, _file) = session_with_image_result();
    let result = build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-pro");
    assert_eq!(result.len(), 4); // user, assistant, tool, placeholder-user
    assert_eq!(result[3].role, "user");
    assert_eq!(result[3].images.len(), 0);
    assert!(
        result[3]
            .content
            .as_deref()
            .unwrap()
            .contains("does not support image input"),
        "{}",
        result[3].content.as_deref().unwrap()
    );
}

#[test]
fn build_chat_request_messages_vision_model_empty_bytes_places_placeholder() {
    // A reference whose stored bytes are empty (e.g. an old persisted turn
    // that predates the bytes, or a non-vision gate) degrades to a placeholder
    // on a vision model (never a panic, never a source-path re-read).
    let mut session = SessionState::empty();
    let (tid, _) = session.start_turn(Some("look".into()));
    session.set_assistant_response(
        tid,
        AssistantResponse {
            text: Some("Reading.".into()),
            tool_calls: vec![AssistantToolCallRecord {
                call_id: "c".into(),
                name: "read_image".into(),
                arguments_json: r#"{}"#.into(),
            }],
            ..Default::default()
        },
    );
    let calls = session.turns[&tid].tool_calls.clone();
    session.seed_tool_results(tid, &calls, &["".into()]);
    session.update_tool_result(
        tid,
        "c",
        "read_image".into(),
        &ToolOutput {
            content: "read image: (3x2)".into(),
            is_error: false,
            invocation_description: String::new(),
            image_ref: Some(choreo_proto::ImageReference {
                path: "/nonexistent/deleted.png".into(),
                mime_type: "image/jpeg".into(),
                width: 3,
                height: 2,
                data: Vec::new(),
            }),
            ..Default::default()
        },
    );
    let result =
        build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-flash-vision-exp");
    assert_eq!(result.len(), 4);
    assert_eq!(result[3].role, "user");
    assert_eq!(result[3].images.len(), 0);
    assert!(
        result[3]
            .content
            .as_deref()
            .unwrap()
            .contains("image bytes are unavailable")
    );
}

#[test]
fn build_chat_request_messages_skips_undone_turns() {
    let mut session = SessionState::empty();
    let (tid0, _) = session.start_turn(Some("visible".into()));
    session.set_assistant_response(
        tid0,
        AssistantResponse {
            text: Some("ok".into()),
            ..Default::default()
        },
    );
    let (tid1, _) = session.start_turn(Some("hidden".into()));
    session.set_assistant_response(
        tid1,
        AssistantResponse {
            text: Some("nope".into()),
            ..Default::default()
        },
    );
    if let Some(turn) = session.turns.get_mut(&tid1) {
        turn.undone = true;
    }

    let result = build_chat_request_messages(&session, None, TEST_PROVIDER, TEST_MODEL);
    assert_eq!(result.len(), 2);
    assert_eq!(result[0].role, "user");
    assert_eq!(result[0].content.as_deref(), Some("visible"));
}

// -- Reasoning passback builder policy (phase 4b) -----------------------

fn tool_call_record(call_id: &str, name: &str) -> AssistantToolCallRecord {
    AssistantToolCallRecord {
        call_id: call_id.into(),
        name: name.into(),
        arguments_json: "{}".into(),
    }
}

fn deepseek_producer() -> ReasoningProducer {
    ReasoningProducer {
        provider_slug: "deepseek".into(),
        model: "deepseek-v4-pro".into(),
    }
}

fn anthropic_producer() -> ReasoningProducer {
    ReasoningProducer {
        provider_slug: "anthropic".into(),
        model: "claude-sonnet-5".into(),
    }
}

/// Non-DeepSeek OpenAI-compat chat provider: ToolLoop passback but no
/// `reasoning_content` injection — the generalized fallback must cover it.
const GROQ_MODEL: &str = "groq/llama-3.3-70b-versatile";

fn groq_producer() -> ReasoningProducer {
    ReasoningProducer {
        provider_slug: "groq".into(),
        model: GROQ_MODEL.into(),
    }
}

/// Pinned to `reasoning_passback = none` by the bundled overlay (the gateway
/// rejects replayed `reasoning_content`) — the fallback must respect it.
fn cerebras_producer() -> ReasoningProducer {
    ReasoningProducer {
        provider_slug: "cerebras".into(),
        model: "gpt-oss-120b".into(),
    }
}

fn artifact(bytes: &[u8]) -> ReasoningArtifact {
    ReasoningArtifact::ChatReasoning {
        field: ChatReasoningField::ReasoningContent,
        bytes: bytes.to_vec(),
    }
}

/// Add a turn with an optional artifact/producer and optional assistant
/// tool calls, returning its turn_id.
fn add_turn(
    session: &mut SessionState,
    user_text: &str,
    assistant_text: &str,
    artifact: Option<ReasoningArtifact>,
    producer: Option<ReasoningProducer>,
    tool_calls: Vec<AssistantToolCallRecord>,
) -> u32 {
    let (tid, _) = session.start_turn(Some(user_text.to_string()));
    session.set_assistant_response(
        tid,
        AssistantResponse {
            text: Some(assistant_text.to_string()),
            tool_calls,
            reasoning_artifact: artifact,
            reasoning_producer: producer,
            ..Default::default()
        },
    );
    tid
}

fn assistant_messages(result: &[ChatRequestMessage]) -> Vec<&ChatRequestMessage> {
    result.iter().filter(|m| m.role == "assistant").collect()
}

#[test]
fn builder_tool_loop_attaches_artifact_only_for_tool_involving_turns() {
    let mut session = SessionState::empty();
    // Plain text turn (no tool involvement) with an artifact: must NOT be
    // replayed under ToolLoop (DeepSeek/Kimi only require it on tool-loop
    // messages).
    add_turn(
        &mut session,
        "hello",
        "hi",
        Some(artifact(b"plain")),
        Some(deepseek_producer()),
        vec![],
    );
    // Tool-call turn with an artifact: must be replayed.
    add_turn(
        &mut session,
        "list files",
        "thinking...",
        Some(artifact(b"tool-thinking")),
        Some(deepseek_producer()),
        vec![tool_call_record("call_1", "ls")],
    );

    // deepseek-v4-pro carries an explicit `tool_loop` passback override.
    let result = build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-pro");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 2);
    assert_eq!(
        assistants[0].reasoning_artifact, None,
        "plain text turn must not replay reasoning under ToolLoop",
    );
    assert_eq!(
        assistants[1].reasoning_artifact,
        Some(artifact(b"tool-thinking")),
        "tool-call turn must replay its artifact under ToolLoop",
    );
}

#[test]
fn builder_tool_loop_attaches_artifact_for_tool_result_turns() {
    let mut session = SessionState::empty();
    // A turn carrying only tool RESULTS (no assistant tool_calls on the
    // message, e.g. a mid-loop state persisted under an earlier request)
    // is tool-involving too: the next request must still echo it.
    let tid = add_turn(
        &mut session,
        "run it",
        "running",
        Some(artifact(b"mid-loop")),
        Some(deepseek_producer()),
        vec![],
    );
    session
        .turns
        .get_mut(&tid)
        .expect("turn exists")
        .tool_results
        .push(choreo_proto::ToolResultRecord {
            call_id: "call_1".into(),
            name: "sh".into(),
            content: "ok".into(),
            is_error: false,
            invocation_description: String::new(),
            image: None,
        });

    let result = build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-pro");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(
        assistants[0].reasoning_artifact,
        Some(artifact(b"mid-loop"))
    );
}

#[test]
fn builder_injects_empty_reasoning_content_for_deepseek_without_artifact() {
    // DeepSeek chat requires `reasoning_content` to be present on every
    // assistant message even when the model produced no reasoning. A tool
    // turn with no artifact must therefore carry an explicit empty string on
    // the wire (mirrors opencode's `{type:"reasoning", text:""}` injection).
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "run it",
        "",
        None,
        Some(deepseek_producer()),
        vec![tool_call_record("call_1", "exec")],
    );

    let result = build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-pro");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(
        assistants[0].reasoning_content,
        Some(String::new()),
        "deepseek assistant message must carry an (empty) reasoning_content"
    );
}

#[test]
fn builder_deepseek_artifact_text_outranks_empty_injection() {
    // When a real artifact exists and is echoed, the explicit reasoning_content
    // field must stay None so the artifact re-emits its text (not an empty
    // placeholder crowding it out).
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "run it",
        "",
        Some(artifact(b"real thinking")),
        Some(deepseek_producer()),
        vec![tool_call_record("call_1", "exec")],
    );

    let result = build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-pro");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(assistants[0].reasoning_content, None);
    assert_eq!(
        assistants[0].reasoning_artifact,
        Some(artifact(b"real thinking"))
    );
}

#[test]
fn builder_does_not_inject_empty_reasoning_content_for_non_deepseek() {
    // Unrelated OpenAI-chat models are untouched: no empty reasoning_content.
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "run it",
        "",
        None,
        Some(ReasoningProducer {
            provider_slug: "openai".into(),
            model: "gpt-4".into(),
        }),
        vec![tool_call_record("call_1", "exec")],
    );

    let result = build_chat_request_messages(&session, None, "openai", "gpt-4");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(assistants[0].reasoning_content, None);
}

#[test]
fn builder_requires_rc_empty_content_turn_echoes_artifact() {
    // A DeepSeek/Kimi turn recorded as reasoning-only — same-model artifact,
    // but empty content and no tool calls. ToolLoop alone would skip the
    // echo (no tool involvement), leaving the wire assistant message wholly
    // empty (`content: ""` + injected empty `reasoning_content`) — the exact
    // shape upstream rejects with "the message ... with role 'assistant'
    // must not be empty". The builder's empty-message fallback must echo the
    // artifact's real reasoning text instead.
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "continue",
        "",
        Some(artifact(b"long reasoning text")),
        Some(deepseek_producer()),
        vec![],
    );

    let result = build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-pro");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(
        assistants[0].reasoning_artifact,
        Some(artifact(b"long reasoning text")),
        "empty-message fallback echoes the same-model artifact",
    );
    // The injected empty string must NOT shadow the artifact: leave the
    // explicit field None so the Serialize impl re-emits the real text.
    assert_eq!(assistants[0].reasoning_content, None);
    assert_eq!(assistants[0].content.as_deref(), Some(""));

    // The wire the provider actually receives carries the non-empty echo.
    let body = serde_json::to_value(&result[1]).unwrap();
    assert_eq!(body["content"], "");
    assert_eq!(body["reasoning_content"], "long reasoning text");
}

#[test]
fn builder_requires_rc_empty_content_turn_keeps_content_turn_bare() {
    // The fallback must NOT change plain-text turns: a non-empty assistant
    // message with a same-model artifact but no tool involvement is still
    // sent bare under ToolLoop (no echo needed — the message is valid).
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "hello",
        "hi",
        Some(artifact(b"plain")),
        Some(deepseek_producer()),
        vec![],
    );

    let result = build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-pro");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(assistants[0].reasoning_artifact, None);
    assert_eq!(assistants[0].reasoning_content, Some(String::new()));
}

#[test]
fn builder_requires_rc_empty_content_turn_foreign_artifact_not_replayed() {
    // Same reasoning-only shape, but the artifact was produced by a DIFFERENT
    // model (mid-session switch scenario): the payload is model-bound and
    // must never be replayed, so the message stays empty on the wire — that
    // is the unfixable case the daemon guard flags as a "must not be empty"
    // risk rather than a silent corruption.
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "continue",
        "",
        Some(artifact(b"claude thinking")),
        Some(anthropic_producer()),
        vec![],
    );

    let result = build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-pro");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(assistants[0].reasoning_artifact, None);
    assert_eq!(assistants[0].reasoning_content, Some(String::new()));

    // And the guard must flag it: wire-empty + requires_rc + nothing
    // replayable.
    assert_eq!(
        warn_on_missing_reasoning_artifacts(&session, 7, "deepseek", "deepseek-v4-pro"),
        1,
        "foreign-producer artifact on a wire-empty requires_rc turn is flagged",
    );
}

#[test]
fn guard_requires_rc_empty_content_turn_with_replayable_artifact_is_clean() {
    // Wire-empty turn whose same-model artifact the builder echoes via the
    // empty-message fallback: the request self-heals, so the guard must NOT
    // count it as a problem.
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "continue",
        "",
        Some(artifact(b"thinking")),
        Some(deepseek_producer()),
        vec![],
    );
    assert_eq!(
        warn_on_missing_reasoning_artifacts(&session, 7, "deepseek", "deepseek-v4-pro"),
        0,
        "empty-message fallback already echoes the same-model artifact",
    );
}

#[test]
fn guard_requires_rc_empty_content_turn_missing_artifact_is_flagged() {
    // Wire-empty turn with NO artifact at all (e.g. reasoning-only response
    // captured before the artifact feature, or a producer that never sent
    // reasoning): nothing can fill the message, so the provider's "must not
    // be empty" 400 is certain — the guard must surface it.
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "continue",
        "",
        None,
        Some(deepseek_producer()),
        vec![],
    );
    assert_eq!(
        warn_on_missing_reasoning_artifacts(&session, 7, "deepseek", "deepseek-v4-pro"),
        1,
        "wire-empty requires_rc turn with no artifact to fill it is flagged",
    );
}

#[test]
fn builder_wire_empty_turn_echoes_artifact_on_non_requires_rc_provider() {
    // The empty-message fallback is provider-agnostic: a content-less,
    // tool-less turn with a same-model artifact must echo it on ANY
    // echo-capable chat provider (here groq — ToolLoop passback, no
    // `reasoning_content` injection) because a wholly empty assistant
    // message is the "must not be empty" 400 on any OpenAI-compatible
    // endpoint, not just DeepSeek/Kimi.
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "continue",
        "",
        Some(artifact(b"reasoned but silent")),
        Some(groq_producer()),
        vec![],
    );

    let result = build_chat_request_messages(&session, None, "groq", GROQ_MODEL);
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(
        assistants[0].reasoning_artifact,
        Some(artifact(b"reasoned but silent")),
        "empty-message fallback echoes the same-model artifact on any echo-capable chat provider",
    );
    // No empty-string injection on non-requires_rc models: the artifact
    // re-emits its text directly.
    assert_eq!(assistants[0].reasoning_content, None);

    let body = serde_json::to_value(&result[1]).unwrap();
    assert_eq!(body["content"], "");
    assert_eq!(body["reasoning_content"], "reasoned but silent");
}

#[test]
fn guard_wire_empty_turn_without_artifact_flagged_on_non_requires_rc() {
    // Wire-empty turn with nothing replayable is flagged on a non-requires_rc
    // ToolLoop provider too — the pre-generalization guard only caught
    // DeepSeek/Kimi turns (the missing-artifact `requires_rc` gate), leaving
    // an equally invalid empty message unflagged on e.g. groq.
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "continue",
        "",
        None,
        Some(groq_producer()),
        vec![],
    );
    assert_eq!(
        warn_on_missing_reasoning_artifacts(&session, 7, "groq", GROQ_MODEL),
        1,
        "wire-empty turn with no artifact to fill it is flagged on any echo-capable chat provider",
    );
    let result = build_chat_request_messages(&session, None, "groq", GROQ_MODEL);
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(assistants[0].reasoning_artifact, None);
    assert_eq!(assistants[0].reasoning_content, None);
}

#[test]
fn builder_wire_empty_turn_never_echoes_under_none_passback() {
    // Cerebras gpt-oss-120b is pinned to `reasoning_passback = none` by the
    // bundled overlay ("the gateway rejects replayed reasoning_content"): the
    // empty-message fallback must NOT override that explicit never-replay
    // policy — echoing would swap the "must not be empty" 400 for a "must
    // not replay" 400. The guard skips None-passback requests entirely
    // (documented policy), so this stays a session_inspect-visible hazard.
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "continue",
        "",
        Some(artifact(b"gpt-oss thinking")),
        Some(cerebras_producer()),
        vec![],
    );

    let result = build_chat_request_messages(&session, None, "cerebras", "gpt-oss-120b");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(assistants[0].reasoning_artifact, None);
    assert_eq!(assistants[0].reasoning_content, None);
    assert_eq!(
        warn_on_missing_reasoning_artifacts(&session, 7, "cerebras", "gpt-oss-120b"),
        0,
        "None-passback requests skip the artifact guard entirely",
    );
}

#[test]
fn builder_all_turns_attaches_always() {
    let mut session = SessionState::empty();
    // Unknown model under the anthropic slug → protocol default AllTurns
    // (no explicit TOML override, unlike claude-sonnet-4-5 which is a
    // last-turn-only `tool_loop` model).
    let producer = ReasoningProducer {
        provider_slug: "anthropic".into(),
        model: "claude-unknown-model".into(),
    };
    add_turn(
        &mut session,
        "hello",
        "hi",
        Some(artifact(b"one")),
        Some(producer.clone()),
        vec![],
    );
    add_turn(
        &mut session,
        "again",
        "bye",
        Some(artifact(b"two")),
        Some(producer),
        vec![],
    );

    // Anthropic → AllTurns: every assistant message replays its artifact,
    // even non-tool turns.
    let result = build_chat_request_messages(&session, None, "anthropic", "claude-unknown-model");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 2);
    assert_eq!(assistants[0].reasoning_artifact, Some(artifact(b"one")));
    assert_eq!(assistants[1].reasoning_artifact, Some(artifact(b"two")));
}

#[test]
fn builder_signature_policy_attaches_always() {
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "hello",
        "hi",
        Some(ReasoningArtifact::GoogleSignatures(b"sig".to_vec())),
        Some(ReasoningProducer {
            provider_slug: "google".into(),
            model: "gemini-2.5-pro".into(),
        }),
        vec![],
    );

    // Google → Signature: every assistant message replays the signatures.
    let result = build_chat_request_messages(&session, None, "google", "gemini-2.5-pro");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(
        assistants[0].reasoning_artifact,
        Some(ReasoningArtifact::GoogleSignatures(b"sig".to_vec())),
    );
}

#[test]
fn builder_none_never_attaches() {
    let mut session = SessionState::empty();
    // A tool-involving turn WITH an artifact under a None-policy provider:
    // the artifact must never be replayed (display-only provider).
    add_turn(
        &mut session,
        "list",
        "thinking",
        Some(artifact(b"payload")),
        Some(ReasoningProducer {
            provider_slug: "unknown-provider".into(),
            model: "m".into(),
        }),
        vec![tool_call_record("call_1", "ls")],
    );

    let result = build_chat_request_messages(&session, None, "unknown-provider", "m");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(assistants[0].reasoning_artifact, None);
}

#[test]
fn builder_response_id_policy_never_attaches_via_message() {
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "list",
        "thinking",
        Some(artifact(b"payload")),
        Some(ReasoningProducer {
            provider_slug: "openai".into(),
            model: "gpt-4".into(),
        }),
        vec![tool_call_record("call_1", "ls")],
    );

    // gpt-4 is a Responses model → ResponseId policy: continuity flows via
    // previous_response_id, so the message must NOT carry the artifact.
    let result = build_chat_request_messages(&session, None, "openai", "gpt-4");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1);
    assert_eq!(assistants[0].reasoning_artifact, None);
}

#[test]
fn builder_same_model_mismatch_drops_artifact() {
    let mut session = SessionState::empty();
    // Current-model turn (deepseek): artifact kept.
    add_turn(
        &mut session,
        "list",
        "thinking",
        Some(artifact(b"kept")),
        Some(deepseek_producer()),
        vec![tool_call_record("call_1", "ls")],
    );
    // Turn produced by a DIFFERENT model mid-session (e.g. the user
    // switched deepseek → claude): the artifact is model-bound and must be
    // dropped even though the turn is tool-involving (replaying an
    // encrypted ChatReasoning payload into an Anthropic request — or a
    // stale deepseek payload after switching back — would corrupt the
    // conversation).
    add_turn(
        &mut session,
        "old model turn",
        "old thinking",
        Some(artifact(b"dropped")),
        Some(ReasoningProducer {
            provider_slug: "anthropic".into(),
            model: "claude-sonnet-4-5".into(),
        }),
        vec![tool_call_record("call_2", "grep")],
    );

    let result = build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-pro");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 2);
    assert_eq!(assistants[0].reasoning_artifact, Some(artifact(b"kept")));
    assert_eq!(
        assistants[1].reasoning_artifact, None,
        "artifact from a previous model must be dropped",
    );
}

#[test]
fn builder_undone_turn_artifact_is_skipped() {
    let mut session = SessionState::empty();
    // Visible, tool-involving turn: its artifact must be replayed under
    // ToolLoop.
    add_turn(
        &mut session,
        "visible",
        "ok",
        Some(artifact(b"kept")),
        Some(deepseek_producer()),
        vec![tool_call_record("call_0", "pwd")],
    );
    let undone_tid = add_turn(
        &mut session,
        "hidden",
        "nope",
        Some(artifact(b"dropped")),
        Some(deepseek_producer()),
        vec![tool_call_record("call_1", "ls")],
    );
    session
        .turns
        .get_mut(&undone_tid)
        .expect("turn exists")
        .undone = true;

    let result = build_chat_request_messages(&session, None, "deepseek", "deepseek-v4-pro");
    let assistants = assistant_messages(&result);
    assert_eq!(assistants.len(), 1, "undone turn must be skipped entirely");
    assert_eq!(assistants[0].reasoning_artifact, Some(artifact(b"kept")));
}

// -- prev_resp_id persistence (phase 4c) --------------------------------

#[test]
fn initial_prev_resp_id_response_policy_restores_persisted_id() {
    let mut session = SessionState::empty();
    session.config.last_response_id = Some("resp_123".into());
    session.config.last_response_id_producer = Some(ReasoningProducer {
        provider_slug: "openai".into(),
        model: "gpt-4".into(),
    });
    // gpt-4 is an OpenAI Responses model → ResponseId policy AND the
    // persisted id was produced by the same provider+model: the id must
    // be restored to chain reasoning continuity across user turns.
    assert_eq!(
        initial_prev_resp_id(&session, "openai", "gpt-4").as_deref(),
        Some("resp_123"),
    );
}

#[test]
fn initial_prev_resp_id_other_policies_reset_to_none() {
    let mut session = SessionState::empty();
    session.config.last_response_id = Some("resp_123".into());
    session.config.last_response_id_producer = Some(ReasoningProducer {
        provider_slug: "deepseek".into(),
        model: "deepseek-v4-pro".into(),
    });
    // DeepSeek chat → ToolLoop policy: a stale id must NOT leak into a
    // request that does not understand previous_response_id — even when
    // the provenance matches.
    assert_eq!(
        initial_prev_resp_id(&session, "deepseek", "deepseek-v4-pro"),
        None,
    );
    // Unknown provider → None policy.
    assert_eq!(
        initial_prev_resp_id(&session, "unknown-provider", "m"),
        None
    );
}

#[test]
fn initial_prev_resp_id_drops_stale_id_from_other_producer() {
    // The persisted id was produced by a DIFFERENT provider+model (e.g. a
    // mid-session openai → xAI switch): restoring it would replay a stale
    // previous_response_id into a service that does not recognize it →
    // provider 400. Provenance must gate the restore, exactly like
    // reasoning artifacts.
    let mut session = SessionState::empty();
    session.config.last_response_id = Some("resp_openai".into());
    session.config.last_response_id_producer = Some(ReasoningProducer {
        provider_slug: "openai".into(),
        model: "gpt-5.4".into(),
    });
    // Same provider, different model → dropped (model-bound provenance).
    assert_eq!(
        initial_prev_resp_id(&session, "openai", "gpt-4"),
        None,
        "id from gpt-5.4 must not be restored for gpt-4",
    );
    // Matching provider+model → restored.
    assert_eq!(
        initial_prev_resp_id(&session, "openai", "gpt-5.4").as_deref(),
        Some("resp_openai"),
    );
    // No producer recorded (fresh session) → no id is ever restored.
    let fresh = SessionState::empty();
    assert_eq!(initial_prev_resp_id(&fresh, "openai", "gpt-5.4"), None);
}

// -- Precondition guard (phase 4c) --------------------------------------

#[test]
fn guard_warns_when_tool_involving_turn_lacks_artifact() {
    let mut session = SessionState::empty();
    // Tool-involving turn WITHOUT an artifact (pre-migration session state).
    let (tid, _) = session.start_turn(Some("list".into()));
    let records = vec![tool_call_record("call_1", "ls")];
    session.set_assistant_response(
        tid,
        AssistantResponse {
            text: Some("thinking".into()),
            tool_calls: records.clone(),
            ..Default::default()
        },
    );
    session.seed_tool_results(tid, &records, &["".into()]);
    // Tool-involving turn WITH an artifact: clean.
    add_turn(
        &mut session,
        "again",
        "thinking2",
        Some(artifact(b"ok")),
        Some(deepseek_producer()),
        vec![tool_call_record("call_2", "sh")],
    );

    let missing = warn_on_missing_reasoning_artifacts(&session, 7, "deepseek", "deepseek-v4-pro");
    assert_eq!(
        missing, 1,
        "only the artifact-less tool turn should be flagged",
    );
}

#[test]
fn guard_clean_when_all_tool_turns_have_artifacts() {
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "list",
        "thinking",
        Some(artifact(b"ok")),
        Some(deepseek_producer()),
        vec![tool_call_record("call_1", "ls")],
    );
    // Non-tool turns never need an artifact.
    add_turn(
        &mut session,
        "plain",
        "hi",
        None,
        Some(deepseek_producer()),
        vec![],
    );
    assert_eq!(
        warn_on_missing_reasoning_artifacts(&session, 7, "deepseek", "deepseek-v4-pro"),
        0,
    );
}

#[test]
fn guard_all_turns_policy_flags_non_tool_turn_missing_artifact() {
    // AllTurns providers (Anthropic keep-all) echo reasoning on EVERY
    // assistant message, not just tool-involving ones — so a plain
    // assistant turn without its artifact is a violation there too (the
    // ToolLoop scope would have skipped it).
    let mut session = SessionState::empty();
    // Tool-involving turn WITH an artifact from the same producer: clean.
    add_turn(
        &mut session,
        "list",
        "thinking",
        Some(artifact(b"ok")),
        Some(anthropic_producer()),
        vec![tool_call_record("call_1", "ls")],
    );
    // Non-tool assistant turn WITH an artifact from the same producer:
    // clean under AllTurns.
    add_turn(
        &mut session,
        "plain",
        "hi",
        Some(artifact(b"ok")),
        Some(anthropic_producer()),
        vec![],
    );
    // Non-tool assistant turn WITHOUT an artifact: flagged under AllTurns.
    let (tid, _) = session.start_turn(Some("later".into()));
    session.set_assistant_response(
        tid,
        AssistantResponse {
            text: Some("hello".into()),
            ..Default::default()
        },
    );
    assert_eq!(
        warn_on_missing_reasoning_artifacts(&session, 7, "anthropic", "claude-sonnet-5"),
        1,
        "AllTurns flags the artifact-less non-tool assistant turn",
    );
}

#[test]
fn guard_user_only_turn_is_not_flagged() {
    // A turn that never produced an assistant message (in-progress or
    // failed) has no artifact by construction and must not be flagged.
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "list",
        "thinking",
        Some(artifact(b"ok")),
        Some(anthropic_producer()),
        vec![tool_call_record("call_1", "ls")],
    );
    let _ = session.start_turn(Some("pending user text".into()));
    assert_eq!(
        warn_on_missing_reasoning_artifacts(&session, 7, "anthropic", "claude-sonnet-5"),
        0,
    );
}

#[test]
fn guard_flags_foreign_producer_artifact() {
    // A turn whose artifact was produced by a DIFFERENT model (a mid-session
    // switch) has a payload the builder will NOT replay (same-model
    // provenance) — the wire request omits the required echo, so the guard
    // flags it exactly like a missing artifact. Otherwise the provider 400
    // after a model switch would remain a mystery.
    let mut session = SessionState::empty();
    add_turn(
        &mut session,
        "list",
        "thinking",
        Some(artifact(b"ok")),
        Some(deepseek_producer()),
        vec![tool_call_record("call_1", "ls")],
    );
    assert_eq!(
        warn_on_missing_reasoning_artifacts(&session, 7, "anthropic", "claude-sonnet-5"),
        1,
        "foreign-producer artifact flagged under AllTurns",
    );
    // The same turn under its own producer+model is clean (provenance match).
    assert_eq!(
        warn_on_missing_reasoning_artifacts(&session, 7, "deepseek", "deepseek-v4-pro"),
        0,
    );
}

#[test]
fn guard_skipped_for_non_echo_policies() {
    let mut session = SessionState::empty();
    let (tid, _) = session.start_turn(Some("list".into()));
    let records = vec![tool_call_record("call_1", "ls")];
    session.set_assistant_response(
        tid,
        AssistantResponse {
            text: Some("thinking".into()),
            tool_calls: records.clone(),
            ..Default::default()
        },
    );
    session.seed_tool_results(tid, &records, &["".into()]);
    // ResponseId policy: artifacts flow via previous_response_id, so the
    // guard must not flag the missing message artifact.
    assert_eq!(
        warn_on_missing_reasoning_artifacts(&session, 7, "openai", "gpt-4"),
        0,
    );
}

// -- Concurrent tool status label tests --------------------------------

#[test]
fn concurrent_status_label_single_tool_uses_real_name() {
    // A lone non-config tool call still dispatches through the concurrent
    // bucket, so the status must show its real name, not "(parallel)".
    let label = concurrent_tool_status_label(&[config_change_call("sh", "{}")]);
    assert_eq!(label, "sh");
}

#[test]
fn concurrent_status_label_multi_tool_batch_is_parallel() {
    let label = concurrent_tool_status_label(&[
        config_change_call("sh", "{}"),
        config_change_call("grep", "{}"),
    ]);
    assert_eq!(label, "(parallel)");
}

#[test]
fn concurrent_status_label_empty_batch_is_parallel() {
    // Defensive: the caller guards with `!concurrent.is_empty()` before
    // sending, but the label should still be well-defined if reached.
    let label = concurrent_tool_status_label(&[]);
    assert_eq!(label, "(parallel)");
}

// -- Cancellation helper tests -----------------------------------------

#[test]
fn is_cancelled_once_no_signal() {
    let (_tx, rx) = crossbeam_channel::unbounded::<()>();
    assert!(!is_cancelled_once(&rx));
}

#[test]
fn is_cancelled_once_with_signal() {
    let (tx, rx) = crossbeam_channel::unbounded::<()>();
    tx.send(()).unwrap();
    assert!(is_cancelled_once(&rx));
}

// -- pending/apply config-change tests ---------------------------------

fn config_change_call(name: &str, arguments_json: &str) -> ChatToolCall {
    ChatToolCall {
        id: "call_1".into(),
        name: name.into(),
        arguments_json: arguments_json.into(),
        caller: None,
    }
}

/// A successful tool output with the given structured result (or `None`
/// for tools whose result_json wasn't captured).
fn ok_output(result_json: Option<serde_json::Value>) -> ToolOutput {
    ToolOutput {
        content: String::new(),
        is_error: false,
        invocation_description: String::new(),
        image_ref: None,
        result_json,
    }
}

#[test]
fn pending_load_tools_captures_groups_and_applies() {
    let tool_call = config_change_call("load_tools", r#"{"groups": ["shell", "x"]}"#);
    let change = pending_config_change(&tool_call, &ok_output(None), None)
        .expect("load_tools should produce a change");
    assert!(matches!(change, PendingConfigChange::LoadTools(ref g) if g == &["shell", "x"]));

    let mut session = SessionState::empty();
    session.config.active_tool_groups = ["core".into(), "git".into()].into_iter().collect();
    apply_pending_config_change(&mut session, &change, &core_protected());
    assert!(session.config.active_tool_groups.contains("shell"));
    assert!(session.config.active_tool_groups.contains("x"));
    assert!(session.config.active_tool_groups.contains("core"));
}

#[test]
fn pending_unload_tools_captures_groups_and_applies() {
    let tool_call = config_change_call("unload_tools", r#"{"groups": ["shell"]}"#);
    let change = pending_config_change(&tool_call, &ok_output(None), None)
        .expect("unload_tools should produce a change");
    assert!(matches!(change, PendingConfigChange::UnloadTools(ref g) if g == &["shell"]));

    let mut session = SessionState::empty();
    session.config.active_tool_groups = ["core".into(), "shell".into()].into_iter().collect();
    apply_pending_config_change(&mut session, &change, &core_protected());
    assert!(!session.config.active_tool_groups.contains("shell"));
    assert!(session.config.active_tool_groups.contains("core"));
}

#[test]
fn pending_set_working_dir_mirrors_executed_result() {
    // The tool executed against a path that has since been deleted.  The
    // mirror must use the EXECUTED result (the canonical path the tool
    // computed and the main loop applied) — no re-resolution, so the
    // deleted directory cannot break the mirror (no TOCTOU).
    let tool_call = config_change_call("set_working_dir", r#"{"path": "sub"}"#);
    let output = ok_output(Some(serde_json::json!({ "path": "/real/canonical/sub" })));
    let change = pending_config_change(&tool_call, &output, None)
        .expect("set_working_dir should produce a change");
    assert!(matches!(
        change,
        PendingConfigChange::SetWorkingDir(Some(ref p)) if p == &PathBuf::from("/real/canonical/sub")
    ));

    let mut session = SessionState::empty();
    session.discovered_skills = Some(Vec::new());
    apply_pending_config_change(&mut session, &change, &core_protected());
    assert_eq!(
        session.config.working_dir.as_deref(),
        Some(PathBuf::from("/real/canonical/sub").as_path())
    );
    assert!(
        session.discovered_skills.is_none(),
        "skill cache must be invalidated by the mirror"
    );
}

#[test]
fn pending_set_working_dir_falls_back_to_shared_resolution() {
    // result_json missing (shouldn't happen on success) — the mirror
    // falls back to the SAME resolution helper the tool uses.
    let base = tempfile::tempdir().unwrap();
    let sub = base.path().join("sub");
    std::fs::create_dir(&sub).unwrap();
    let tool_call = config_change_call("set_working_dir", r#"{"path": "sub"}"#);

    let change = pending_config_change(&tool_call, &ok_output(None), Some(base.path()))
        .expect("set_working_dir should produce a change");

    let mut session = SessionState::empty();
    apply_pending_config_change(&mut session, &change, &core_protected());
    assert_eq!(
        session.config.working_dir.as_deref(),
        Some(sub.canonicalize().unwrap().as_path())
    );
}

#[test]
fn pending_set_working_dir_nonexistent_path_still_invalidates_skills() {
    // The tool succeeded (result_json present) but the path is now gone.
    // The mirror still applies the executed path verbatim — no TOCTOU.
    let tool_call = config_change_call("set_working_dir", r#"{"path": "gone"}"#);
    let output = ok_output(Some(serde_json::json!({ "path": "/gone/dir" })));
    let change = pending_config_change(&tool_call, &output, None)
        .expect("set_working_dir should produce a change");

    let mut session = SessionState::empty();
    session.discovered_skills = Some(Vec::new());
    apply_pending_config_change(&mut session, &change, &core_protected());
    assert_eq!(
        session.config.working_dir.as_deref(),
        Some(PathBuf::from("/gone/dir").as_path())
    );
    assert!(
        session.discovered_skills.is_none(),
        "skill cache must be invalidated even when the path is gone"
    );
}

#[test]
fn pending_set_working_dir_unresolvable_fallback_still_invalidates_skills() {
    // result_json missing AND the fallback resolution fails (path does
    // not exist) — the worker skips the path update but MUST still
    // invalidate its skill cache so stale skills never leak across the
    // request boundary (RequestFinished merges discovered_skills over the
    // main loop's invalidated None).
    let base = tempfile::tempdir().unwrap();
    let tool_call = config_change_call("set_working_dir", r#"{"path": "does-not-exist"}"#);

    let change = pending_config_change(&tool_call, &ok_output(None), Some(base.path()))
        .expect("set_working_dir should still produce a change");
    assert!(matches!(change, PendingConfigChange::SetWorkingDir(None)));

    let mut session = SessionState::empty();
    session.discovered_skills = Some(Vec::new());
    apply_pending_config_change(&mut session, &change, &core_protected());
    assert!(session.config.working_dir.is_none());
    assert!(
        session.discovered_skills.is_none(),
        "skill cache must be invalidated even when no path could be resolved"
    );
}

#[test]
fn pending_unknown_tool_is_noop() {
    let tool_call = config_change_call("read_file", r#"{"path": "x"}"#);
    assert!(pending_config_change(&tool_call, &ok_output(None), None).is_none());
}

#[test]
fn pending_unparseable_args_is_noop() {
    let tool_call = config_change_call("load_tools", "not json");
    assert!(pending_config_change(&tool_call, &ok_output(None), None).is_none());
}

// -- broadcast_turn_appended tests -----------------------------------

#[test]
fn broadcast_turn_appended_sends_when_turn_exists() {
    let (tx, rx) = mpsc::channel::<SessionCommand>();
    let mut session = SessionState::empty();
    let (turn_id, _) = session.start_turn(Some("hello".into()));

    broadcast_turn_appended(&tx, &session, 0, turn_id);

    match rx.try_recv() {
        Ok(SessionCommand::Broadcast(DaemonMessage::Session {
            event: SessionEvent::TurnAppended { turn_id: id, .. },
            ..
        })) => {
            assert_eq!(id, turn_id);
        }
        Ok(_) => panic!("expected TurnAppended broadcast, got different command"),
        Err(e) => panic!("expected TurnAppended broadcast, got error: {e}"),
    }
}

#[test]
fn broadcast_turn_appended_no_turn_no_broadcast() {
    let (tx, rx) = mpsc::channel::<SessionCommand>();
    let session = SessionState::empty();

    broadcast_turn_appended(&tx, &session, 0, 999);

    assert!(rx.try_recv().is_err(), "expected no message");
}

#[test]
fn broadcast_turn_appended_disconnected_receiver_no_panic() {
    let (tx, rx) = mpsc::channel::<SessionCommand>();
    let mut session = SessionState::empty();
    let (turn_id, _) = session.start_turn(Some("hello".into()));
    drop(rx);

    // Disconnected receiver should not panic — warn! is logged instead.
    broadcast_turn_appended(&tx, &session, 0, turn_id);
}

#[test]
fn broadcast_turn_appended_strips_reasoning_artifact() {
    // The client-bound TurnAppended must never carry the opaque reasoning
    // round-trip payload, even when the session's authoritative turn does.
    let (tx, rx) = mpsc::channel::<SessionCommand>();
    let mut session = SessionState::empty();
    let (turn_id, _) = session.start_turn(Some("hello".into()));
    session.set_assistant_response(
        turn_id,
        AssistantResponse {
            text: Some("hi".into()),
            reasoning: Some("thinking out loud".into()),
            reasoning_artifact: Some(ReasoningArtifact::ChatReasoning {
                field: ChatReasoningField::ReasoningContent,
                bytes: b"thinking".to_vec(),
            }),
            reasoning_producer: Some(ReasoningProducer {
                provider_slug: "deepseek".into(),
                model: "deepseek-v4-pro".into(),
            }),
            ..Default::default()
        },
    );

    broadcast_turn_appended(&tx, &session, 0, turn_id);

    match rx.try_recv() {
        Ok(SessionCommand::Broadcast(DaemonMessage::Session {
            event: SessionEvent::TurnAppended {
                turn_id: id, turn, ..
            },
            ..
        })) => {
            assert_eq!(id, turn_id);
            assert_eq!(turn.reasoning_artifact, None);
            assert_eq!(turn.reasoning_producer, None);
            assert_eq!(turn.assistant_text.as_deref(), Some("hi"));
            assert_eq!(
                turn.assistant_reasoning.as_deref(),
                Some("thinking out loud")
            );
        }
        Ok(_) => panic!("expected TurnAppended broadcast, got different command"),
        Err(e) => panic!("expected TurnAppended broadcast, got error: {e}"),
    }
    // The authoritative turn keeps the artifact for the next request's builder.
    assert!(session.turns[&turn_id].reasoning_artifact.is_some());
    assert!(session.turns[&turn_id].reasoning_producer.is_some());
}

#[test]
fn finalize_and_broadcast_turn_strips_reasoning_artifact() {
    // TurnAppended is the final turn snapshot sent to clients — the
    // reasoning artifact must be stripped here too, while the DB write
    // (inside finalize_and_broadcast_turn) persists the full turn.
    let (daemon_tx, _daemon_rx) = mpsc::channel::<DaemonCommand>();
    let (cmd_tx, cmd_rx) = mpsc::channel::<SessionCommand>();
    let dir = tempfile::tempdir().unwrap();
    let db = Arc::new(redb::Database::create(dir.path().join("test.redb")).unwrap());
    let ctx = RequestContext {
        cmd_tx,
        session_id: 1,
        db,
        tool_registry: ToolRegistry::new().build(),
        daemon_tx,
        max_turns: 0,
        lag_limits: crate::broadcast::LagLimits::default(),
        global_lag: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        substrate_credential: None,
    };
    let mut session = SessionState::empty();
    let (turn_id, _) = session.start_turn(Some("hello".into()));
    session.set_assistant_response(
        turn_id,
        AssistantResponse {
            text: Some("hi".into()),
            reasoning: Some("thinking out loud".into()),
            reasoning_artifact: Some(ReasoningArtifact::ChatReasoning {
                field: ChatReasoningField::ReasoningContent,
                bytes: b"thinking".to_vec(),
            }),
            reasoning_producer: Some(ReasoningProducer {
                provider_slug: "deepseek".into(),
                model: "deepseek-v4-pro".into(),
            }),
            ..Default::default()
        },
    );

    finalize_and_broadcast_turn(&mut session, &ctx, turn_id).unwrap();

    match cmd_rx.try_recv() {
        Ok(SessionCommand::Broadcast(DaemonMessage::Session {
            event: SessionEvent::TurnAppended { turn, .. },
            ..
        })) => {
            assert_eq!(turn.reasoning_artifact, None);
            assert_eq!(turn.reasoning_producer, None);
            assert_eq!(turn.assistant_text.as_deref(), Some("hi"));
            assert_eq!(
                turn.assistant_reasoning.as_deref(),
                Some("thinking out loud")
            );
        }
        Ok(_) => panic!("expected TurnAppended broadcast, got different command"),
        Err(e) => panic!("expected TurnAppended broadcast, got error: {e}"),
    }
    // The authoritative turn keeps the artifact after finalize + broadcast.
    assert!(session.turns[&turn_id].reasoning_artifact.is_some());
    assert!(session.turns[&turn_id].reasoning_producer.is_some());
}

#[test]
fn agent_loop_failure_marks_and_finalizes_turn() {
    // A provider-level failure (e.g. 402 Insufficient Balance) must be
    // recorded on the turn and the turn finalized + broadcast so clients
    // render a red "Error:" block in the transcript and the failure
    // survives a daemon restart — while the loop still reports the
    // original inference error to the caller (RequestOutcome::Failed).
    let (daemon_tx, _daemon_rx) = mpsc::channel::<DaemonCommand>();
    let (cmd_tx, cmd_rx) = mpsc::channel::<SessionCommand>();
    let dir = tempfile::tempdir().unwrap();
    let db = Arc::new(redb::Database::create(dir.path().join("test.redb")).unwrap());
    let ctx = RequestContext {
        cmd_tx,
        session_id: 1,
        db,
        tool_registry: ToolRegistry::new().build(),
        daemon_tx,
        max_turns: 0,
        lag_limits: crate::broadcast::LagLimits::default(),
        global_lag: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        substrate_credential: None,
    };
    let provider = make_failing_provider();
    let (_cancel_tx, cancel_rx) = crossbeam_channel::unbounded::<()>();
    let mut session = SessionState::empty();

    let result = run_agent_loop(
        &provider,
        &mut session,
        "test-model",
        7,
        &cancel_rx,
        &ctx,
        Some("hi".into()),
    );

    // The inference error propagates to the caller unchanged.
    let err = result.expect_err("the failing provider must fail the request");
    let msg = err.to_string();
    assert!(
        msg.contains("402") && msg.contains("Insufficient Balance"),
        "expected the 402 client error, got: {msg}"
    );

    // The open turn carries the failure so clients can render it.
    let turn = session.turns.get(&0).expect("turn 0 exists");
    assert_eq!(
        turn.error.as_deref(),
        Some("client error (402): Insufficient Balance")
    );
    assert_eq!(turn.user_text.as_deref(), Some("hi"));

    // The turn was finalized: a TurnAppended broadcast carries the error
    // to clients (the authoritative turn keeps it too, for the DB write).
    // The stream also contains mid-turn TurnAppended broadcasts (the
    // user-text append) that legitimately carry no error, so require only
    // that an error-bearing TurnAppended arrived.
    let mut saw_error_appended = false;
    while let Ok(msg) = cmd_rx.try_recv() {
        if let SessionCommand::Broadcast(DaemonMessage::Session {
            event: SessionEvent::TurnAppended { turn, .. },
            ..
        }) = msg
            && let Some(err) = turn.error
        {
            assert_eq!(err, "client error (402): Insufficient Balance");
            saw_error_appended = true;
        }
    }
    assert!(
        saw_error_appended,
        "expected a TurnAppended broadcast carrying the failure"
    );
}

// -- resolve_reasoning_effort tests ------------------------------------

#[test]
fn resolve_reasoning_effort_off_returns_off() {
    let provider = make_test_provider();
    let result = resolve_reasoning_effort(&provider, "o3-mini", 1, 0, "off");
    assert_eq!(result, "off");
}

#[test]
fn resolve_reasoning_effort_unknown_provider_disables() {
    let provider = make_test_provider();
    let result = resolve_reasoning_effort(&provider, "o3-mini", 1, 0, "low");
    // "test-stub" slug is not in the catalog, so reasoning is unsupported.
    assert_eq!(result, "off");
}

#[test]
fn resolve_reasoning_effort_openai_supported_model_preserves() {
    let config = choreo_ai_protocols::openai::ServiceConfig::default();
    let client = choreo_ai_protocols::openai::OpenAiClient::new(
        config,
        "test-key".into(),
        &choreo_ai_protocols::SocketRegistry::new(),
    )
    .unwrap();
    let provider = InferenceProvider::from_openai(client);

    let result = resolve_reasoning_effort(&provider, "o3-mini", 1, 0, "high");
    assert_eq!(result, "high");
}

#[test]
fn resolve_reasoning_effort_openai_unsupported_model_disables() {
    let config = choreo_ai_protocols::openai::ServiceConfig::default();
    let client = choreo_ai_protocols::openai::OpenAiClient::new(
        config,
        "test-key".into(),
        &choreo_ai_protocols::SocketRegistry::new(),
    )
    .unwrap();
    let provider = InferenceProvider::from_openai(client);

    let result = resolve_reasoning_effort(&provider, "gpt-4.1", 1, 0, "medium");
    assert_eq!(result, "off");
}

// -- estimate_prompt_tokens tests ------------------------------------

#[test]
fn estimate_prompt_tokens_empty() {
    let (encoding, estimated) = estimate_prompt_tokens("gpt-4", &[], &[]);
    assert!(encoding.is_some());
    assert_eq!(estimated, 0);
}

#[test]
fn estimate_prompt_tokens_counts_content() {
    let messages = vec![
        ChatRequestMessage::simple("user", "hello world".into()),
        ChatRequestMessage::simple("assistant", "hi there".into()),
    ];
    let (_, estimated) = estimate_prompt_tokens("gpt-4", &messages, &[]);
    assert!(
        estimated > 0,
        "expected positive token count, got {estimated}"
    );
}

#[test]
fn estimate_prompt_tokens_does_not_count_reasoning_content() {
    let base_messages = vec![
        ChatRequestMessage::simple("user", "hello".into()),
        ChatRequestMessage::simple("assistant", "visible".into()),
    ];
    let mut with_reasoning = base_messages.clone();
    with_reasoning[1].reasoning_content = Some("thinking deep...".into());

    let (_, base_est) = estimate_prompt_tokens("gpt-4", &base_messages, &[]);
    let (_, reason_est) = estimate_prompt_tokens("gpt-4", &with_reasoning, &[]);
    assert_eq!(
        base_est, reason_est,
        "legacy reasoning_content string field is never populated by the daemon and must not count"
    );
}

#[test]
fn estimate_prompt_tokens_counts_reasoning_artifact() {
    let base_messages = vec![
        ChatRequestMessage::simple("user", "hello".into()),
        ChatRequestMessage::simple("assistant", "visible".into()),
    ];
    let mut with_artifact = base_messages.clone();
    with_artifact[1].reasoning_artifact = Some(ReasoningArtifact::ChatReasoning {
        field: ChatReasoningField::ReasoningContent,
        bytes: "thinking deep...".into(),
    });

    let (_, base_est) = estimate_prompt_tokens("gpt-4", &base_messages, &[]);
    let (_, artifact_est) = estimate_prompt_tokens("gpt-4", &with_artifact, &[]);
    assert!(
        artifact_est > base_est,
        "replayed reasoning artifact should count as input: {artifact_est} <= {base_est}",
    );
}

#[test]
fn estimate_prompt_tokens_counts_tool_call_metadata() {
    let messages = vec![ChatRequestMessage {
        role: "assistant",
        content: None,
        images: Vec::new(),
        tool_calls: Some(vec![AssistantToolCall {
            id: "call_abc".into(),
            kind: "function".into(),
            function: AssistantToolFunction {
                name: "read_file".into(),
                arguments: r#"{"path": "/etc/hosts"}"#.into(),
            },
        }]),
        tool_call_id: None,
        reasoning_content: None,
        reasoning: None,
        reasoning_text: None,
        reasoning_artifact: None,
    }];
    let (_, estimated) = estimate_prompt_tokens("gpt-4", &messages, &[]);
    assert!(
        estimated > 0,
        "expected positive token count, got {estimated}"
    );
}

#[test]
fn estimate_prompt_tokens_includes_tool_defs() {
    let tools = vec![ChatToolDefinition::function(
        "read_file",
        "Read a file from disk",
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {"type": "string"}
            }
        }),
    )];
    let messages = vec![ChatRequestMessage::simple("user", "read file".into())];
    let (_, with_tools) = estimate_prompt_tokens("gpt-4", &messages, &tools);
    let (_, without_tools) = estimate_prompt_tokens("gpt-4", &messages, &[]);
    assert!(
        with_tools > without_tools,
        "tool defs should increase token count: {with_tools} <= {without_tools}",
    );
}

#[test]
fn estimate_prompt_tokens_unknown_model_falls_back() {
    let messages = vec![ChatRequestMessage::simple("user", "hello".into())];
    let (encoding, estimated) = estimate_prompt_tokens("nonexistent-model-9000", &messages, &[]);
    assert!(encoding.is_some(), "should fall back to cl100k_base");
    assert!(estimated > 0);
}

#[test]
fn estimate_prompt_tokens_no_chained_context_addend() {
    // The daemon builds `messages` as the FULL conversation, not the
    // chained tail the adapter puts on the wire; the provider bills the
    // whole context it holds in the chain, which the full-conversation
    // count already covers. There is deliberately NO chained-context
    // addend — adding the last request's `prompt_tokens` would count the
    // conversation twice. This pins the counting function's contract: it
    // estimates exactly the messages it is given, nothing more.
    let messages = vec![
        ChatRequestMessage::simple("system", "rebuilt system prompt".into()),
        ChatRequestMessage::simple("user", "turn one".into()),
        ChatRequestMessage::simple("assistant", "answer".into()),
        ChatRequestMessage::simple("user", "turn two".into()),
    ];
    let (_, estimated) = estimate_prompt_tokens("gpt-4", &messages, &[]);
    // Deterministic and equal to the visible-messages count: a hidden
    // chained-context addend would inflate it far beyond the recount.
    let (_, recounted) = estimate_prompt_tokens("gpt-4", &messages, &[]);
    assert_eq!(estimated, recounted, "estimate must be deterministic");
    assert!(
        estimated > 0,
        "full conversation must count: got {estimated}"
    );
}

// -- execute_tool_with_timeout tests -----------------------------------

struct FastTestTool;

impl Tool for FastTestTool {
    type Args = serde_json::Value;
    type Return = String;
    type Error = ToolExecError;

    fn name(&self) -> &'static str {
        "_test_fast"
    }
    fn group(&self) -> &'static str {
        "test"
    }
    fn description(&self) -> &'static str {
        "test tool that completes immediately"
    }
    fn describe_invocation(&self, _args: &Self::Args) -> String {
        format!("{}.", self.description())
    }
    fn return_string(ret: &Self::Return) -> String {
        ret.clone()
    }
    fn schema(&self) -> serde_json::Value {
        serde_json::json!({})
    }
    fn execute(
        &self,
        _args: Self::Args,
        _xc: Option<&ServiceCredential>,
        _working_dir: Option<&Path>,
        _ctx: Option<&ToolContext>,
    ) -> Result<Self::Return, Self::Error> {
        Ok("fast result".into())
    }
}

struct BlockingTestTool {
    proceed: std::sync::Mutex<Option<mpsc::Receiver<()>>>,
}

impl Tool for BlockingTestTool {
    type Args = serde_json::Value;
    type Return = String;
    type Error = ToolExecError;

    fn name(&self) -> &'static str {
        "_test_blocking"
    }
    fn group(&self) -> &'static str {
        "test"
    }
    fn description(&self) -> &'static str {
        "test tool that blocks until proceed"
    }
    fn describe_invocation(&self, _args: &Self::Args) -> String {
        format!("{}.", self.description())
    }
    fn return_string(ret: &Self::Return) -> String {
        ret.clone()
    }
    fn schema(&self) -> serde_json::Value {
        serde_json::json!({})
    }
    fn execute(
        &self,
        _args: Self::Args,
        _xc: Option<&ServiceCredential>,
        _working_dir: Option<&Path>,
        _ctx: Option<&ToolContext>,
    ) -> Result<Self::Return, Self::Error> {
        Ok("ignored".into())
    }
    fn execute_streaming(
        &self,
        _args: Self::Args,
        _xc: Option<&ServiceCredential>,
        _working_dir: Option<&Path>,
        _output_tx: crossbeam_channel::Sender<Vec<u8>>,
        _ctx: Option<&ToolContext>,
    ) -> Result<Self::Return, Self::Error> {
        if let Some(rx) = self.proceed.lock().unwrap().take() {
            let _ = rx.recv();
        }
        Ok("blocked tool done".into())
    }
}

fn run_exec_tool(
    tool: impl Tool + 'static,
    tool_name: &str,
    tool_args: &str,
    timeout_dur: Duration,
    cancel_rx: crossbeam_channel::Receiver<()>,
) -> (ToolOutput, bool, mpsc::Receiver<SessionCommand>) {
    let (daemon_tx, _daemon_rx) = mpsc::channel::<DaemonCommand>();
    let (cmd_tx, cmd_rx) = mpsc::channel::<SessionCommand>();

    let dir = tempfile::tempdir().expect("tempdir");
    let db = redb::Database::create(dir.path().join("test.redb")).expect("Database");

    let mut session = SessionState::empty();

    let mut registry = ToolRegistry::new();
    registry.register(tool);
    let registry = registry.build();

    let tool_call = ChatToolCall {
        id: "call_test".into(),
        name: tool_name.into(),
        arguments_json: tool_args.into(),
        caller: None,
    };

    let ctx = RequestContext {
        cmd_tx,
        session_id: 1,
        db: Arc::new(db),
        tool_registry: registry,
        daemon_tx,
        max_turns: 0,
        lag_limits: crate::broadcast::LagLimits::default(),
        global_lag: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        substrate_credential: None,
    };
    let (result, cancelled, _image) = execute_tool_with_timeout(
        &tool_call,
        None,
        None,
        timeout_dur,
        1,
        1,
        &mut session,
        &cancel_rx,
        &ctx,
        "test invocation",
    );
    (result, cancelled, cmd_rx)
}

#[test]
fn execute_tool_normal_completion() {
    let (_cancel_tx, cancel_rx) = crossbeam_channel::unbounded::<()>();
    let (result, cancelled, _cmd_rx) = run_exec_tool(
        FastTestTool,
        "_test_fast",
        "{}",
        Duration::from_secs(60),
        cancel_rx,
    );
    assert!(!result.is_error, "expected success: {}", result.content);
    assert!(result.content.contains("fast result"), "{}", result.content);
    assert!(!cancelled, "completion must not report a cancel");
}

#[test]
fn execute_tool_cancelled_before_execution() {
    let (cancel_tx, cancel_rx) = crossbeam_channel::unbounded::<()>();
    cancel_tx.send(()).expect("send cancel");
    drop(cancel_tx);

    // A blocking tool makes the outcome deterministic: the cancel is
    // pre-sent, so the wait-loop's biased cancel arm fires first and,
    // with the tool still running, the "cancelled" output is produced
    // (a just-completed fast tool could otherwise race the cancel drain
    // and return its real result alongside the sticky cancel flag).
    let (proceed_tx, proceed_rx) = mpsc::channel::<()>();
    let (result, cancelled, _cmd_rx) = run_exec_tool(
        BlockingTestTool {
            proceed: std::sync::Mutex::new(Some(proceed_rx)),
        },
        "_test_blocking",
        "{}",
        Duration::from_secs(60),
        cancel_rx,
    );
    assert!(result.is_error, "expected error: {}", result.content);
    assert!(result.content.contains("cancelled"), "{}", result.content);
    // The wait observed the cancellation signal; the caller must stop the
    // request (the sticky-cancel contract).
    assert!(cancelled, "cancel must be reported to the caller");
    // The serial path now carries the invocation description onto the
    // synthesized cancel output (the concurrent path always did), so the
    // transcript renders the same invocation context for both phases.
    assert_eq!(result.invocation_description, "test invocation");

    // Release the still-blocked tool so its execution thread exits.
    drop(proceed_tx);
}

#[test]
fn execute_tool_timeout() {
    let (_cancel_tx, cancel_rx) = crossbeam_channel::unbounded::<()>();
    let (proceed_tx, proceed_rx) = mpsc::channel::<()>();

    // A zero-duration timeout is deterministic: `crossbeam_channel::after`
    // with a deadline that is already in the past is immediately ready in
    // the biased select's fast path (the `at` flavor's `try_recv` checks
    // `Instant::now() >= delivery_time`), so the deadline arm fires
    // without any time-based wait — no sleeps in unit tests (AGENTS.md).
    // The blocking tool can never win the race (it has not finished), and
    // no cancel is pending, so the deadline arm is the only ready one.
    let (result, cancelled, _cmd_rx) = run_exec_tool(
        BlockingTestTool {
            proceed: std::sync::Mutex::new(Some(proceed_rx)),
        },
        "_test_blocking",
        "{}",
        Duration::ZERO,
        cancel_rx,
    );

    assert!(result.is_error, "expected error: {}", result.content);
    assert!(result.content.contains("timed out"), "{}", result.content);
    assert!(!cancelled, "a timeout is not a cancellation");

    drop(proceed_tx);
}

// -- drain_queued_or_synthesize tests ---------------------------------
//
// Deterministic: each test fully populates (or deliberately leaves
// empty / disconnects) the exec channel before calling the function, so
// the outcome is fully ordered — no time-based waits (AGENTS.md).

#[test]
fn drain_queued_result_beats_stop_message() {
    // A result that queued in the same instant the stop fired must win
    // over the synthesized stop message — the finish-vs-stop race is
    // resolved in favor of the real outcome.
    let (tx, rx) = crossbeam_channel::unbounded::<Result<ToolOutput, ToolError>>();
    tx.send(Ok(ToolOutput {
        content: "real result".into(),
        invocation_description: "real desc".into(),
        ..Default::default()
    }))
    .expect("send result");

    let (output, cancelled) = drain_queued_or_synthesize(
        "_test",
        std::time::Instant::now(),
        "test invocation",
        &rx,
        "tool '_test' cancelled".to_string(),
        true,
    );
    assert_eq!(output.content, "real result");
    assert!(!output.is_error);
    assert_eq!(output.invocation_description, "real desc");
    // The sticky-cancel flag still travels with a drained result: the
    // cancel signal was consumed, so the caller must stop the request.
    assert!(cancelled, "sticky cancel must survive a drained result");
}

#[test]
fn drain_queued_empty_synthesizes_stop_message() {
    // No result queued (sender alive, tool still running): the stop
    // message is synthesized with the caller's invocation description.
    let (_tx, rx) = crossbeam_channel::unbounded::<Result<ToolOutput, ToolError>>();
    let (output, cancelled) = drain_queued_or_synthesize(
        "_test",
        std::time::Instant::now(),
        "test invocation",
        &rx,
        "tool '_test' timed out after 60s".to_string(),
        false,
    );
    assert_eq!(output.content, "tool '_test' timed out after 60s");
    assert!(output.is_error);
    assert_eq!(output.invocation_description, "test invocation");
    assert!(!cancelled, "a timeout is not a request cancel");
}

#[test]
fn drain_queued_disconnected_reports_panic_not_stop() {
    // The execution thread died (sender dropped) at the stop instant: the
    // real cause is a panic, not the stop message — a deadline/cancel arm
    // must not mislabel a dead execution thread as "timed out" or
    // "cancelled".
    let (tx, rx) = crossbeam_channel::unbounded::<Result<ToolOutput, ToolError>>();
    drop(tx);
    let (output, cancelled) = drain_queued_or_synthesize(
        "_test",
        std::time::Instant::now(),
        "test invocation",
        &rx,
        "tool '_test' cancelled".to_string(),
        true,
    );
    assert_eq!(output.content, "tool execution thread panicked");
    assert!(output.is_error);
    assert_eq!(output.invocation_description, "test invocation");
    assert!(cancelled, "sticky flag still applies on the panic path");
}

struct StreamingTestTool;

impl Tool for StreamingTestTool {
    type Args = serde_json::Value;
    type Return = String;
    type Error = ToolExecError;

    fn name(&self) -> &'static str {
        "_test_streaming"
    }
    fn group(&self) -> &'static str {
        "test"
    }
    fn description(&self) -> &'static str {
        "test tool that sends streaming output"
    }
    fn describe_invocation(&self, _args: &Self::Args) -> String {
        format!("{}.", self.description())
    }
    fn return_string(ret: &Self::Return) -> String {
        ret.clone()
    }
    fn schema(&self) -> serde_json::Value {
        serde_json::json!({})
    }
    fn execute(
        &self,
        _args: Self::Args,
        _xc: Option<&ServiceCredential>,
        _working_dir: Option<&Path>,
        _ctx: Option<&ToolContext>,
    ) -> Result<Self::Return, Self::Error> {
        Ok("exec result".into())
    }
    fn supports_streaming_output() -> bool {
        true
    }

    fn execute_streaming(
        &self,
        _args: Self::Args,
        _xc: Option<&ServiceCredential>,
        _working_dir: Option<&Path>,
        output_tx: crossbeam_channel::Sender<Vec<u8>>,
        _ctx: Option<&ToolContext>,
    ) -> Result<Self::Return, Self::Error> {
        let _ = output_tx.send(b"streamed payload".to_vec());
        Ok("streaming done".into())
    }
}

#[test]
fn execute_tool_forwards_streaming_output() {
    let (_cancel_tx, cancel_rx) = crossbeam_channel::unbounded::<()>();
    let (result, cancelled, cmd_rx) = run_exec_tool(
        StreamingTestTool,
        "_test_streaming",
        "{}",
        Duration::from_secs(60),
        cancel_rx,
    );

    assert!(!result.is_error, "expected success: {}", result.content);
    assert!(
        result.content.contains("streaming done"),
        "{}",
        result.content
    );
    assert!(!cancelled, "completion must not report a cancel");

    // The invocation description is no longer streamed as a chunk (it
    // rides on ToolCallStarted + the seeded placeholder); the only chunk
    // is the tool's own payload from execute_streaming.
    match cmd_rx.recv() {
        Ok(SessionCommand::Broadcast(DaemonMessage::Session {
            event: SessionEvent::ToolResultChunk { data, .. },
            ..
        })) => {
            assert_eq!(data, b"streamed payload");
        }
        Ok(_other) => panic!("expected ToolResultChunk, got unexpected SessionCommand"),
        Err(e) => panic!("channel disconnected while waiting for streaming output: {e}"),
    }
}

// -- forwarding-thread tests -----------------------------------------
//
// These exercise `spawn_forwarding_thread` directly and deterministically:
// the returned `JoinHandle` lets the test observe thread exit without any
// time-based waits (AGENTS.md forbids sleeps in unit tests).

#[test]
fn forwarding_thread_drains_queued_output_before_kill() {
    let (cmd_tx, cmd_rx) = mpsc::channel::<SessionCommand>();
    let (output_tx, output_rx) = crossbeam_channel::unbounded::<Vec<u8>>();
    let (kill_tx, kill_rx) = crossbeam_channel::unbounded::<()>();

    let handle = spawn_forwarding_thread(cmd_tx, 1, 1, "call_1".into(), output_rx, kill_rx);

    // Queue a chunk and then a kill back-to-back. The test sends the chunk
    // BEFORE the kill, so the forwarder can never observe the kill arm as
    // ready while the output arm is still pending — the biased select
    // (output first) must therefore forward the chunk before honoring the
    // kill, in any interleaving.
    output_tx
        .send(b"queued chunk".to_vec())
        .expect("send chunk");
    kill_tx.send(()).expect("send kill");

    match cmd_rx.recv() {
        Ok(SessionCommand::Broadcast(DaemonMessage::Session {
            event: SessionEvent::ToolResultChunk { data, .. },
            ..
        })) => {
            assert_eq!(data, b"queued chunk");
        }
        Ok(_other) => panic!("expected ToolResultChunk, got unexpected SessionCommand"),
        Err(e) => panic!("channel disconnected while waiting for chunk: {e}"),
    }
    // Only the kill can terminate the forwarder now (output_tx still alive),
    // so a successful join proves the kill was honored after the drain.
    handle.join().expect("forwarder should exit after kill");
}

#[test]
fn forwarding_thread_exits_when_output_disconnects() {
    let (cmd_tx, cmd_rx) = mpsc::channel::<SessionCommand>();
    let (output_tx, output_rx) = crossbeam_channel::unbounded::<Vec<u8>>();
    let (_kill_tx, kill_rx) = crossbeam_channel::unbounded::<()>();

    let handle = spawn_forwarding_thread(cmd_tx, 1, 1, "call_2".into(), output_rx, kill_rx);

    output_tx.send(b"last chunk".to_vec()).expect("send chunk");
    // Tool finished: dropping the output sender makes the forwarder's next
    // `recv(output_rx)` return Err (disconnect) → drain → exit.
    drop(output_tx);

    match cmd_rx.recv() {
        Ok(SessionCommand::Broadcast(DaemonMessage::Session {
            event: SessionEvent::ToolResultChunk { data, .. },
            ..
        })) => {
            assert_eq!(data, b"last chunk");
        }
        Ok(_other) => panic!("expected ToolResultChunk, got unexpected SessionCommand"),
        Err(e) => panic!("channel disconnected while waiting for chunk: {e}"),
    }
    handle
        .join()
        .expect("forwarder should exit on output disconnect");
}

#[test]
fn forwarding_thread_exits_when_kill_sender_dropped() {
    let (cmd_tx, _cmd_rx) = mpsc::channel::<SessionCommand>();
    let (output_tx, output_rx) = crossbeam_channel::unbounded::<Vec<u8>>();
    let (kill_tx, kill_rx) = crossbeam_channel::unbounded::<()>();

    let handle = spawn_forwarding_thread(cmd_tx, 1, 1, "call_3".into(), output_rx, kill_rx);

    // Dropping the kill sender disconnects kill_rx; with no output traffic
    // the select returns on the kill arm immediately and the thread exits.
    drop(kill_tx);
    handle
        .join()
        .expect("forwarder should exit when kill sender dropped");
    drop(output_tx);
}

#[test]
fn forwarding_thread_honors_kill_while_output_is_still_alive() {
    // A tool that keeps streaming keeps the output arm always-ready, which
    // would starve the biased-last kill arm if the forwarder only checked
    // the kill channel via the select.  The between-chunk kill re-check
    // must stop the thread even though the output sender is still alive
    // and has chunks queued — otherwise a busy stream would forward
    // forever after the caller stopped waiting.  Deterministic: the test
    // sends chunks and then a kill; the forwarder forwards the queued
    // burst (bounded by the queue length at kill time) and then exits,
    // never waiting on the output channel to disconnect.
    let (cmd_tx, cmd_rx) = mpsc::channel::<SessionCommand>();
    let (output_tx, output_rx) = crossbeam_channel::unbounded::<Vec<u8>>();
    let (kill_tx, kill_rx) = crossbeam_channel::unbounded::<()>();

    let handle = spawn_forwarding_thread(cmd_tx, 1, 1, "call_4".into(), output_rx, kill_rx);

    for i in 0..5 {
        output_tx
            .send(format!("chunk {i}").into_bytes())
            .expect("send chunk");
    }
    kill_tx.send(()).expect("send kill");

    // The first queued chunk is forwarded (FIFO) before the kill is
    // honored; the rest of the kill-time burst may be drained too.
    match cmd_rx.recv() {
        Ok(SessionCommand::Broadcast(DaemonMessage::Session {
            event: SessionEvent::ToolResultChunk { data, .. },
            ..
        })) => {
            assert_eq!(data, b"chunk 0", "first queued chunk should be forwarded");
        }
        Ok(_other) => panic!("expected ToolResultChunk, got unexpected SessionCommand"),
        Err(e) => panic!("channel disconnected while waiting for chunk: {e}"),
    }
    // output_tx is still alive, so the thread can only terminate by
    // honoring the kill between chunks — a successful join proves the
    // busy-stream kill starvation is closed.
    handle
        .join()
        .expect("forwarder should exit on kill while output is still live");
    drop(output_tx);
    drop(kill_tx);
}

// -- determine_tool_timeout tests ----------------------------------

#[test]
fn determine_tool_timeout_subsession_none() {
    assert!(determine_tool_timeout("spawn_subsession", "{}").is_none());
}

#[test]
fn determine_tool_timeout_shell_300() {
    for name in &["sh", "nushell", "fish", "exec"] {
        assert_eq!(
            determine_tool_timeout(name, "{}"),
            Some(Duration::from_secs(300)),
            "tool {name} should have 300s timeout",
        );
    }
}

#[test]
fn determine_tool_timeout_default_60() {
    for name in &[
        "read_file",
        "write_file",
        "run_riscv",
        "grep",
        "http_request",
    ] {
        assert_eq!(
            determine_tool_timeout(name, "{}"),
            Some(Duration::from_secs(60)),
            "tool {name} should have 60s timeout",
        );
    }
}

#[test]
fn determine_tool_timeout_requested_below_base_keeps_base() {
    // The name-based default is a FLOOR: a shell tool requesting its default
    // (or anything below it) still gets the full 300s outer deadline.
    assert_eq!(
        determine_tool_timeout("sh", r#"{"timeout": 30000}"#),
        Some(Duration::from_secs(300)),
    );
}

#[test]
fn determine_tool_timeout_requested_above_base_raises_deadline() {
    // A long legitimate command (a full workspace build) must be allowed to
    // run to its requested timeout: the outer deadline is raised to the
    // request plus the teardown grace (5s).
    assert_eq!(
        determine_tool_timeout("sh", r#"{"timeout": 1800000}"#),
        Some(Duration::from_millis(1_800_000) + TOOL_TIMEOUT_GRACE),
    );
}

#[test]
fn determine_tool_timeout_missing_or_malformed_falls_back_to_base() {
    // Missing field, non-numeric, zero, and non-JSON args all fall back to
    // the name-based default — the guard always exists.
    for args in ["{}", r#"{"timeout": 0}"#, r#"{"timeout": "big"}"#, "oops"] {
        assert_eq!(
            determine_tool_timeout("sh", args),
            Some(Duration::from_secs(300)),
            "args {args} should fall back to the 300s default",
        );
    }
}

#[test]
fn determine_tool_timeout_ignored_for_non_shell_tools() {
    // Non-shell tools have no `timeout` field in their schema; a stray field
    // (if a model ever sends one) must not raise their deadline.
    assert_eq!(
        determine_tool_timeout("grep", r#"{"timeout": 999999999}"#),
        Some(Duration::from_secs(60)),
    );
}

#[test]
fn determine_tool_timeout_generate_image_covers_adapter_worst_case() {
    // glm-image `hd` renders ~20 s per the z.ai docs, but the adapters own
    // bounded worst cases (2 POST attempts × the 180 s agent deadline, plus
    // the z.ai URL download's 3-fetch budget) that the generic 60 s default
    // discards as a timeout AFTER a paid generation completes. The floor is
    // DERIVED from the shared adapter constants plus a headroom margin —
    // asserted here against the same computation rather than a pinned
    // literal, so the floor always covers the adapters' configured worst
    // case by construction — and it must be name-gated ONLY on
    // generate_image, not reach other tools.
    let adapter_worst_case = u64::from(
        choreo_ai_protocols::images::IMAGE_MAX_ATTEMPTS
            + choreo_ai_protocols::images::IMAGE_DOWNLOAD_ATTEMPTS,
    ) * choreo_ai_protocols::images::IMAGE_TOTAL_TIMEOUT_SECS;
    let derived = Duration::from_secs(adapter_worst_case + 60);
    assert_eq!(
        determine_tool_timeout("generate_image", "{}"),
        Some(derived),
    );
    // Non-shell tools still cannot raise their deadline via a stray
    // `timeout` argument, generate_image included (no raise path). And
    // other image-adjacent tool names do NOT inherit the derived floor —
    // the branches are name-exact, not prefix-matched.
    assert_eq!(
        determine_tool_timeout("generate_image", r#"{"timeout": 999999999}"#),
        Some(derived),
    );
    assert_eq!(
        determine_tool_timeout("display_image", "{}"),
        Some(Duration::from_secs(60)),
    );
}

// -- spawn_single_tool tests ---------------------------------------

/// Build a throwaway `ToolContext` and command channel for
/// `spawn_single_tool` tests. Receivers are dropped, which is fine — no
/// assertion inspects the daemon or session command streams here.
fn spawn_test_ctx() -> (ToolContext, mpsc::Sender<SessionCommand>) {
    let (cmd_tx, _cmd_rx) = mpsc::channel::<SessionCommand>();
    let (_daemon_tx, _daemon_rx) = mpsc::channel::<DaemonCommand>();
    let dir = tempfile::tempdir().expect("tempdir");
    let db = Arc::new(redb::Database::create(dir.path().join("test.redb")).expect("Database"));
    let ctx = ToolContext {
        session_id: 1,
        db,
        daemon_tx: _daemon_tx,
        active_tool_groups: std::collections::HashSet::new(),
        reasoning_effort: None,
        selected_model: None,
        working_dir: None,
        cancelled: Arc::new(AtomicBool::new(false)),
        account_name: None,
        discovered_skills: None,
    };
    (ctx, cmd_tx)
}

fn run_spawn_single_tool(
    tool: impl Tool + 'static,
    tool_name: &str,
    tool_args: &str,
    timeout: Option<Duration>,
) -> ToolHandle {
    let (ctx, cmd_tx) = spawn_test_ctx();

    let mut registry = ToolRegistry::new();
    registry.register(tool);
    let registry = registry.build();

    let tool_call = ChatToolCall {
        id: "call_test".into(),
        name: tool_name.into(),
        arguments_json: tool_args.into(),
        caller: None,
    };

    let invocation_description = registry
        .describe_invocation_for(&tool_call.name, &tool_call.arguments_json)
        .unwrap_or_default();

    let (result_tx, result_rx) = crossbeam_channel::unbounded::<ToolHandle>();
    // Hold the kill sender for the duration of this wait — dropping it
    // would disconnect the kill channel and stop the wait-loop early.
    let _kill_tx = spawn_single_tool(SpawnToolArgs {
        tool_call,
        timeout,
        request_id: 1,
        session_id: 1,
        registry,
        cmd_tx,
        x_credentials: None,
        working_dir: None,
        ctx,
        invocation_description,
        started_at: Instant::now(),
        result_tx,
    });

    result_rx.recv().expect("tool did not deliver a result")
}

#[test]
fn spawn_single_tool_fast_returns_result() {
    let handle = run_spawn_single_tool(
        FastTestTool,
        "_test_fast",
        "{}",
        Some(Duration::from_secs(60)),
    );
    assert!(
        !handle.output.is_error,
        "expected success: {}",
        handle.output.content
    );
    assert!(
        handle.output.content.contains("fast result"),
        "{}",
        handle.output.content
    );
    assert!(handle.image.is_none(), "expected no image from fast tool");
}

#[test]
fn spawn_single_tool_no_timeout_still_completes() {
    let handle = run_spawn_single_tool(FastTestTool, "_test_fast", "{}", None);
    assert!(
        !handle.output.is_error,
        "expected success: {}",
        handle.output.content
    );
    assert!(
        handle.output.content.contains("fast result"),
        "{}",
        handle.output.content
    );
}

#[test]
fn concurrent_tools_deliver_in_completion_order() {
    // Tool A (dispatched first) blocks until released; tool B (dispatched
    // second) completes immediately. B must arrive through the shared
    // batch channel before A — a fast tool is no longer gated by the
    // slowest tool the model listed before it.
    let (proceed_tx, proceed_rx) = mpsc::channel::<()>();
    let (ctx, cmd_tx) = spawn_test_ctx();

    let mut registry = ToolRegistry::new();
    registry.register(BlockingTestTool {
        proceed: std::sync::Mutex::new(Some(proceed_rx)),
    });
    registry.register(FastTestTool);
    let registry = registry.build();

    let slow_call = ChatToolCall {
        id: "call_slow".into(),
        name: "_test_blocking".into(),
        arguments_json: "{}".into(),
        caller: None,
    };
    let fast_call = ChatToolCall {
        id: "call_fast".into(),
        name: "_test_fast".into(),
        arguments_json: "{}".into(),
        caller: None,
    };

    let (batch_tx, batch_rx) = crossbeam_channel::unbounded::<ToolHandle>();

    // Dispatch the slow tool first, then the fast one.  The slow tool's
    // 5s timeout is a deadlock guard only: in the correct implementation
    // the fast result arrives immediately and the slow tool is released
    // well before its deadline, so the blocking `recv`s below never wait
    // on a timer — they are deterministic (AGENTS.md forbids time-based
    // waits in unit tests).  If a regression made the collector wait in
    // dispatch order, the slow tool would hit its timeout instead and
    // the name assertion below would fail the test rather than hang it.
    // The kill senders are held for the drain's lifetime — dropping them
    // would disconnect the kill channels and stop the wait-loops early.
    let _slow_kill = spawn_single_tool(SpawnToolArgs {
        tool_call: slow_call,
        timeout: Some(Duration::from_secs(5)),
        request_id: 1,
        session_id: 1,
        registry: Arc::clone(&registry),
        cmd_tx: cmd_tx.clone(),
        x_credentials: None,
        working_dir: None,
        ctx: ctx.clone(),
        invocation_description: String::new(),
        started_at: Instant::now(),
        result_tx: batch_tx.clone(),
    });
    let _fast_kill = spawn_single_tool(SpawnToolArgs {
        tool_call: fast_call,
        timeout: Some(Duration::from_secs(60)),
        request_id: 1,
        session_id: 1,
        registry,
        cmd_tx,
        x_credentials: None,
        working_dir: None,
        ctx,
        invocation_description: String::new(),
        started_at: Instant::now(),
        result_tx: batch_tx,
    });

    // The fast tool must arrive first despite being dispatched second.
    let first = batch_rx.recv().expect("expected a first tool result");
    assert_eq!(first.tool_call.name, "_test_fast");
    assert!(
        first.output.content.contains("fast result"),
        "{}",
        first.output.content
    );

    // Release the slow tool; its result arrives second.
    drop(proceed_tx);
    let second = batch_rx.recv().expect("expected the slow tool result");
    assert_eq!(second.tool_call.name, "_test_blocking");
    assert!(
        second.output.content.contains("blocked tool done"),
        "{}",
        second.output.content
    );
}

#[test]
fn wait_loop_honors_kill_while_tool_is_still_running() {
    // A tool that blocks until released; a collector kill must stop the
    // wait-loop (forwarder + cooperative flag) and deliver a "cancelled"
    // result immediately, without waiting for the tool to finish — even
    // with NO timeout, where the wait-loop would otherwise block on the
    // tool's result channel forever.
    let (proceed_tx, proceed_rx) = mpsc::channel::<()>();
    let (ctx, cmd_tx) = spawn_test_ctx();
    let cancel_flag = Arc::clone(&ctx.cancelled);

    let mut registry = ToolRegistry::new();
    registry.register(BlockingTestTool {
        proceed: std::sync::Mutex::new(Some(proceed_rx)),
    });
    let registry = registry.build();

    let tool_call = ChatToolCall {
        id: "call_kill".into(),
        name: "_test_blocking".into(),
        arguments_json: "{}".into(),
        caller: None,
    };

    let (result_tx, result_rx) = crossbeam_channel::unbounded::<ToolHandle>();
    let kill_tx = spawn_single_tool(SpawnToolArgs {
        tool_call,
        timeout: None, // unbounded — the kill is the only wakeup
        request_id: 1,
        session_id: 1,
        registry,
        cmd_tx,
        x_credentials: None,
        working_dir: None,
        ctx,
        invocation_description: String::new(),
        started_at: Instant::now(),
        result_tx,
    });

    // The tool is blocked inside execute_streaming_json; the kill must
    // reach the wait-loop and produce a cancelled result without the tool
    // finishing.  Deterministic: `recv` blocks until the cancelled handle
    // arrives, and the wait-loop sends it only after setting the flag.
    kill_tx.send(()).expect("send kill");

    let handle = result_rx
        .recv()
        .expect("cancelled result must be delivered");
    assert!(handle.output.is_error, "{}", handle.output.content);
    assert!(
        handle.output.content.contains("cancelled"),
        "{}",
        handle.output.content
    );
    // The cooperative flag must be set so the tool itself can stop early.
    assert!(
        cancel_flag.load(Ordering::Relaxed),
        "cooperative cancel flag must be set"
    );

    // Release the still-blocked tool so its execution thread exits.
    drop(proceed_tx);
}

// -- missing_calls tests ------------------------------------------------

#[test]
fn missing_calls_skips_delivered_by_id_not_index() {
    // A (slow, dies before delivering), B (fast, delivered), C (slow,
    // dies): handles arrive in completion order, so B is delivered first
    // and received == 1.  Skipping the first 1 entry by *index* would
    // mark A delivered and synthesize C in its place — misattributing the
    // panic to the wrong tool.  Filtering by call_id must synthesize A
    // and C (in dispatch order), never B.
    let call_infos = vec![
        CallInfo {
            call_id: "a".into(),
            tool_name: "slow_1".into(),
            arguments_json: "{}".into(),
            invocation_description: "a".into(),
            started_at: Instant::now(),
            // Never sent to — the kill channel is irrelevant to the
            // missing-call filter under test.
            kill_tx: crossbeam_channel::unbounded().0,
        },
        CallInfo {
            call_id: "b".into(),
            tool_name: "fast".into(),
            arguments_json: "{}".into(),
            invocation_description: "b".into(),
            started_at: Instant::now(),
            kill_tx: crossbeam_channel::unbounded().0,
        },
        CallInfo {
            call_id: "c".into(),
            tool_name: "slow_2".into(),
            arguments_json: "{}".into(),
            invocation_description: "c".into(),
            started_at: Instant::now(),
            kill_tx: crossbeam_channel::unbounded().0,
        },
    ];
    let delivered = HashSet::from(["b".to_string()]);
    let missing: Vec<&str> = missing_calls(&call_infos, &delivered)
        .map(|info| info.call_id.as_str())
        .collect();
    assert_eq!(missing, vec!["a", "c"]);
}

#[test]
fn missing_calls_empty_when_all_delivered() {
    let call_infos = vec![CallInfo {
        call_id: "a".into(),
        tool_name: "read_file".into(),
        arguments_json: "{}".into(),
        invocation_description: "a".into(),
        started_at: Instant::now(),
        // Never sent to — the kill channel is irrelevant to the
        // missing-call filter under test.
        kill_tx: crossbeam_channel::unbounded().0,
    }];
    let delivered = HashSet::from(["a".to_string()]);
    assert_eq!(missing_calls(&call_infos, &delivered).count(), 0);
}

// -- sort_by_call_order tests -----------------------------------------

#[test]
fn sort_by_call_order_restores_model_order() {
    // Model issued calls a, b, c; the tools completed in the reverse order
    // (c first). The next-call accumulator must be restored to a, b, c so
    // tool messages mirror the assistant's tool_calls array.
    let tool_calls = vec![
        AssistantToolCallRecord {
            call_id: "a".into(),
            name: "read_file".into(),
            arguments_json: "{}".into(),
        },
        AssistantToolCallRecord {
            call_id: "b".into(),
            name: "grep".into(),
            arguments_json: "{}".into(),
        },
        AssistantToolCallRecord {
            call_id: "c".into(),
            name: "sh".into(),
            arguments_json: "{}".into(),
        },
    ];
    let mut items = vec![
        ToolResultItem {
            call_id: "c".into(),
            output: "c-out".into(),
            caller: None,
        },
        ToolResultItem {
            call_id: "a".into(),
            output: "a-out".into(),
            caller: None,
        },
        ToolResultItem {
            call_id: "b".into(),
            output: "b-out".into(),
            caller: None,
        },
    ];
    sort_by_call_order(&tool_calls, &mut items, |r| r.call_id.as_str());
    let order: Vec<_> = items.iter().map(|r| r.call_id.as_str()).collect();
    assert_eq!(order, vec!["a", "b", "c"]);
}

#[test]
fn sort_by_call_order_sinks_unknown_call_ids() {
    // A streaming stub created before its start event arrived has no
    // matching tool_call; it must sink to the end, keeping relative order.
    let tool_calls = vec![AssistantToolCallRecord {
        call_id: "a".into(),
        name: "read_file".into(),
        arguments_json: "{}".into(),
    }];
    let mut items = vec![
        ToolResultItem {
            call_id: "ghost".into(),
            output: "g-out".into(),
            caller: None,
        },
        ToolResultItem {
            call_id: "a".into(),
            output: "a-out".into(),
            caller: None,
        },
    ];
    sort_by_call_order(&tool_calls, &mut items, |r| r.call_id.as_str());
    let order: Vec<_> = items.iter().map(|r| r.call_id.as_str()).collect();
    assert_eq!(order, vec!["a", "ghost"]);
}

// -- extract_json_string tests ------------------------------------------

#[test]
fn extract_json_string_gets_value() {
    let json = r#"{"name": "test-skill", "path": "src/main.rs"}"#;
    assert_eq!(
        extract_json_string(json, "name").as_deref(),
        Some("test-skill")
    );
    assert_eq!(
        extract_json_string(json, "path").as_deref(),
        Some("src/main.rs")
    );
}

#[test]
fn extract_json_string_missing_key() {
    assert_eq!(extract_json_string(r#"{"other": "val"}"#, "name"), None);
}

#[test]
fn extract_json_string_invalid_json() {
    assert_eq!(extract_json_string("not json", "name"), None);
}

// -- persist_loaded_skill tests -----------------------------------------

#[test]
fn persist_loaded_skill_adds_to_session() {
    let dir = tempfile::tempdir().unwrap();
    let skill_dir = dir.path().join(".agents/skills/test-skill");
    std::fs::create_dir_all(&skill_dir).unwrap();
    std::fs::write(
        skill_dir.join("SKILL.md"),
        "\
---\n\
name: test-skill\n\
description: A test skill\n\
---\n\
Hello, this is the skill body.\n\
---\n",
    )
    .unwrap();

    let mut session = SessionState::empty();
    session.config.working_dir = Some(dir.path().to_path_buf());
    assert!(session.loaded_skill_bodies.is_empty());

    persist_loaded_skill(&mut session, "load_skill", r#"{"name": "test-skill"}"#);

    assert_eq!(session.loaded_skill_bodies.len(), 1);
    assert_eq!(session.loaded_skill_bodies[0].name, "test-skill");
    assert!(session.loaded_skill_bodies[0].body.contains("skill body"));
}

#[test]
fn persist_loaded_skill_skips_non_load_skill() {
    let mut session = SessionState::empty();
    persist_loaded_skill(&mut session, "read_file", r#"{"path": "Cargo.toml"}"#);
    assert!(session.loaded_skill_bodies.is_empty());
}

#[test]
fn persist_loaded_skill_skips_missing_name() {
    let mut session = SessionState::empty();
    session.config.working_dir = Some(PathBuf::from("/tmp"));
    persist_loaded_skill(&mut session, "load_skill", r#"{}"#);
    assert!(session.loaded_skill_bodies.is_empty());
}

#[test]
fn persist_loaded_skill_without_working_dir_unknown_skill_not_added() {
    // A dir-less session has no project scope, but the load path must not
    // panic; an obviously absent skill name leaves the accumulator empty. The
    // discovered-skill cache is seeded EMPTY so the persistence path resolves
    // against the cached (production) snapshot instead of falling back to
    // ambient discovery — the test is deterministic and never touches the
    // developer's real ~/.agents/skills.
    let mut session = SessionState::empty();
    session.discovered_skills = Some(Vec::new());
    persist_loaded_skill(
        &mut session,
        "load_skill",
        r#"{"name": "definitely-no-such-skill-xyz"}"#,
    );
    assert!(session.loaded_skill_bodies.is_empty());
}

#[test]
fn persist_loaded_skill_reads_body_from_cached_skills() {
    // The persistence path must reuse the session's discovered-skill cache
    // rather than re-walking the filesystem: populate the cache with a meta
    // whose SKILL.md lives in a temp dir and confirm its body is read.
    let dir = tempfile::tempdir().unwrap();
    let skill_md = dir.path().join("SKILL.md");
    std::fs::write(
        &skill_md,
        "---\nname: cached-skill\ndescription: cached\n---\n\ncached body text\n---\n",
    )
    .unwrap();

    let mut session = SessionState::empty();
    session.discovered_skills = Some(vec![crate::context::SkillMeta {
        name: "cached-skill".into(),
        description: "cached".into(),
        path: skill_md,
    }]);

    persist_loaded_skill(&mut session, "load_skill", r#"{"name": "cached-skill"}"#);

    assert_eq!(session.loaded_skill_bodies.len(), 1);
    assert_eq!(session.loaded_skill_bodies[0].name, "cached-skill");
    assert!(
        session.loaded_skill_bodies[0]
            .body
            .contains("cached body text"),
        "body: {}",
        session.loaded_skill_bodies[0].body
    );
}

// -- build_system_content tests -----------------------------------------

fn setup_build_system_content_session() -> (SessionState, Arc<ToolRegistry>, tempfile::TempDir) {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("AGENTS.md"), "Project rules").unwrap();

    let mut registry = ToolRegistry::new();
    registry.register(FastTestTool);
    let registry = registry.build();

    let mut session = SessionState::empty();
    session.config.working_dir = Some(dir.path().to_path_buf());
    (session, registry, dir)
}

/// Call build_system_content with standard defaults derived from the
/// session state and optional pending_hints overrides.
fn test_build_content(
    session: &mut SessionState,
    registry: &ToolRegistry,
    pending_hints: &[String],
) -> String {
    build_system_content(
        SystemContentParams {
            working_dir: session.config.working_dir.as_deref(),
            context_config: &session.config.context_config,
            skills: &[],
            loaded_skill_bodies: &session.loaded_skill_bodies,
            tool_registry: registry,
            pending_hints,
            session_title: session.config.title.as_deref(),
        },
        &mut session.context_cache,
    )
}

#[test]
fn build_system_content_with_working_dir() {
    let (mut session, registry, _dir) = setup_build_system_content_session();
    let content = test_build_content(&mut session, &registry, &[]);
    assert!(content.contains("Tool groups"));
    assert!(content.contains("core"));
    assert!(content.contains("Project rules"));
}

#[test]
fn build_system_content_without_working_dir() {
    // A dir-less session still receives the full base prompt (identity, tool
    // groups, skills, title); only project context files are absent.
    let mut session = SessionState::empty();
    let registry = ToolRegistry::new().build();
    let content = test_build_content(&mut session, &registry, &[]);
    assert!(content.contains("Tool groups"));
    // The structural marker for injected project-context files is absent —
    // a stronger, more durable check than grepping for a filename that the
    // base prompt could legitimately mention someday.
    assert!(!content.contains("<agent_instructions"));
}

#[test]
fn build_system_content_includes_loaded_skills() {
    let (mut session, registry, _dir) = setup_build_system_content_session();
    session.loaded_skill_bodies.push(LoadedSkill {
        name: "loaded-test".to_string(),
        body: "Loaded body text.".to_string(),
    });
    let content = test_build_content(&mut session, &registry, &[]);
    assert!(content.contains("Loaded skills"));
    assert!(content.contains("loaded-test"));
    assert!(content.contains("Loaded body text."));
}

#[test]
fn build_system_content_populates_context_cache() {
    let (mut session, registry, _dir) = setup_build_system_content_session();
    assert!(session.context_cache.is_none());

    let _ = test_build_content(&mut session, &registry, &[]);
    assert!(
        session.context_cache.is_some(),
        "context_cache should be populated after first call"
    );
    let (fp, _) = session.context_cache.as_ref().unwrap();
    assert!(*fp > 0, "fingerprint should be non-zero");
}

#[test]
fn build_system_content_includes_pending_hints() {
    let (mut session, registry, _dir) = setup_build_system_content_session();
    let pending_hints = vec!["Hint about subdirectory config.".to_string()];
    let content = test_build_content(&mut session, &registry, &pending_hints);
    assert!(content.contains("New context from project subdirectories"));
    assert!(content.contains("Hint about subdirectory config."));
}

#[test]
fn build_system_content_includes_session_title() {
    let (mut session, registry, _dir) = setup_build_system_content_session();
    session.config.title = Some("Refactoring the database layer".into());
    let content = test_build_content(&mut session, &registry, &[]);
    assert!(content.contains("## Current Session Title"));
    assert!(content.contains("Refactoring the database layer"));
}

#[test]
fn build_system_content_omits_empty_title() {
    let (mut session, registry, _dir) = setup_build_system_content_session();
    // Title is None by default — no "Current Session Title" section.
    let content = test_build_content(&mut session, &registry, &[]);
    assert!(!content.contains("## Current Session Title"));

    // Also omit when the title is an empty string.
    session.config.title = Some("".into());
    let content2 = test_build_content(&mut session, &registry, &[]);
    assert!(!content2.contains("## Current Session Title"));
}