trusty-code 0.8.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! End-to-end tests for `tcode run-task` (#1034, #1035) — all offline.
//!
//! Why: The closer must be provable without a live LLM or API key. Every M1
//! acceptance criterion — the PM delegates to the engineer, the engineer's
//! file change shows up in the diff, the transcript carries both roles, usage +
//! cost aggregate, exit codes reflect outcome, and the per-run `--engineer-model`
//! swap routes the engineer — is driven through a scripted `InferenceAdapter` mock
//! so no network call is ever made.
//! What: A `ScriptedLlm` replays a queue of `ChatResponse`s; because the PM and
//! engineer share one inner client, the script is consumed in call order
//! (PM-turn-1, engineer-turn-1, …). Fixtures build agents-dir `.md` agents and a
//! project dir; tests assert on the returned `RunReport`.
//! Test: this module is itself the test surface.

use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use serde_json::{Value, json};
use tempfile::TempDir;

use super::{
    ExitCode, RedelegationCapSignal, RunTaskParams, execute_run_task as real_execute_run_task,
    resolve_agent_model_slug,
};
use crate::agent_loop::AgentLoopError;
use crate::agents::AgentConfig;
use crate::llm::{ChatRequest, ChatResponse, InferenceAdapter, InferenceError};
use crate::runner::RegistryFactory;
use crate::tools::{AgentOutput, EngineerCompletionSignal, RunContext};

// ── Hermeticity (#3361): never let a real ambient daemon reach into these
// tests' sandboxed temp dirs ────────────────────────────────────────────────

/// One-time, process-lifetime isolation of the two ambient daemon endpoints
/// `execute_run_task` reaches for: trusty-search (background indexing, via
/// `ensure_project_indexed_in_background`) and trusty-memory (the PM catch-up
/// digest, via `catchup::pm_catchup_context`).
///
/// Why (#3361): on a machine with a live `trusty-memory` and/or
/// `trusty-search` daemon, `execute_run_task` discovers and contacts them for
/// real — `trusty-memory` because `catchup::pm_catchup_context` resolves its
/// base URL via `resolve_memory_base_url_or_unreachable()`
/// (`TRUSTY_MEMORY_SOCKET` env override, else the derived socket
/// file), and `trusty-search` because
/// `ensure_project_indexed_in_background` -> `ensure_project_indexed` finds
/// the daemon via `resolve_daemon_base_url("trusty-search")` (same on-disk
/// discovery, gated by `TRUSTY_DATA_DIR_OVERRIDE`) and, once found, actually
/// registers + reindexes the test's tempdir `project` against the LIVE
/// daemon — which then writes its own colocated storage (e.g.
/// `.trusty-search/schema_version.json`) INSIDE the sandboxed tempdir. That
/// extra on-disk file shows up in `diff::capture_snapshot`'s before/after
/// diff, so any test asserting an empty diff (`no_changes_yields_no_changes_exit`,
/// `missing_disk_pm_config_falls_back_to_embedded_pm`) or a specific
/// `RunFailure`-vs-`Partial` exit keyed on "no deliverable exists"
/// (`exit_code_reflects_run_failure`) spuriously fails — not because of a
/// product regression, but because the sandbox was never actually hermetic.
///
/// This is the SAME class of bug `catchup::pm_catchup_context_with_memory_url`
/// (#3003) and `session::memory_sink::TurnMemorySink` already fixed for their
/// OWN unit tests by threading the daemon URL through as a parameter instead
/// of touching the process-global env var per test. `execute_run_task` has no
/// such injection seam (it is the black-box entry point under test here), so
/// the fix at THIS layer uses the two seams the production code itself
/// already treats as authoritative overrides — `TRUSTY_MEMORY_SOCKET` (an
/// explicit override always wins over discovery,
/// `resolve_memory_base_url_or_unreachable`'s own doc) and
/// `TRUSTY_DATA_DIR_OVERRIDE` (documented in `trusty_common::data_dir` as
/// "intended for tests only... the only reliable cross-platform way to
/// isolate test data paths") — rather than reaching for `#[serial]` or hoping
/// no daemon happens to be running.
///
/// Both are set EXACTLY ONCE, guarded by `std::sync::Once`, and are NEVER
/// restored. This deliberately differs from a per-test set/restore guard
/// (the pattern #3434 shows is unsafe for a process-global var under
/// `cargo test`'s parallel threads): because every test in this module wants
/// the identical "no ambient daemon is reachable" outcome, and the value is
/// fixed for the remainder of the test binary's lifetime once installed,
/// there is no window in which one thread can observe a different, another
/// thread's transient value — the mutate-once-and-never-restore shape has no
/// race to hide behind slower runs, unlike a mutate/restore pattern would.
/// Test: exercised implicitly by every test that calls
/// [`execute_run_task`] (this module's wrapper) below; the before/after
/// behaviour is demonstrated by `exit_code_reflects_run_failure`,
/// `no_changes_yields_no_changes_exit`, and
/// `missing_disk_pm_config_falls_back_to_embedded_pm`, which fail under a
/// live ambient trusty-memory/trusty-search daemon without this guard and
/// pass with it.
fn isolate_ambient_daemons() {
    static INIT: std::sync::Once = std::sync::Once::new();
    INIT.call_once(|| {
        // A socket path under a directory that cannot exist: a dial is
        // refused by the kernel immediately rather than hanging. Mirrors
        // `catchup::tests::UNREACHABLE_MEMORY_SOCKET` and
        // `trusty_common::memory_rpc`'s own `UNREACHABLE_PLACEHOLDER`
        // convention. An explicit `TRUSTY_MEMORY_SOCKET` always wins over
        // the derived path (see `resolve_memory_socket`), so this alone is
        // sufficient to stop `catchup::pm_catchup_context` from ever
        // dialling the host's real trusty-memory daemon.
        // SAFETY: `Once` guarantees this runs exactly one time, before any
        // reader in this process observes it (no test spawns a thread that
        // reads it before this call happens on the same thread that reaches
        // this line first) — see the doc comment above for why no restore
        // (and thus no unsafe-across-threads mutation) is needed.
        unsafe {
            std::env::set_var(
                trusty_common::memory_rpc::TRUSTY_MEMORY_SOCKET_ENV,
                "/nonexistent/trusty-memory/trusty-memory.sock",
            );
        }

        // An empty, dedicated, never-reused directory: `resolve_data_dir`
        // will create `<this>/trusty-search/` (and `<this>/trusty-memory/`
        // for any code path that falls through to discovery instead of the
        // env override above) with no discovery file inside, so
        // `resolve_daemon_base_url` always resolves to `None` — the daemon
        // is treated as "never started" rather than guessing/reaching a
        // real port.
        let isolated_data_dir = std::env::temp_dir().join(format!(
            "trusty-code-run-task-test-daemon-isolation-{}",
            std::process::id()
        ));
        let _ = std::fs::create_dir_all(&isolated_data_dir);
        unsafe {
            std::env::set_var(trusty_common::DATA_DIR_OVERRIDE_ENV, &isolated_data_dir);
        }
    });
}

/// Test-only wrapper around [`real_execute_run_task`] that installs the
/// hermetic-daemon isolation (#3361) before every call.
///
/// Why: centralising the call here (rather than repeating
/// `isolate_ambient_daemons()` at the top of every test) means a new test
/// added to this file gets the guard automatically just by calling
/// `execute_run_task` like every existing test already does — there is
/// nothing extra to remember.
/// What: calls [`isolate_ambient_daemons`] then forwards to
/// [`real_execute_run_task`] unchanged.
/// Test: see [`isolate_ambient_daemons`].
async fn execute_run_task(
    params: RunTaskParams,
    llm: Arc<dyn InferenceAdapter>,
) -> super::RunReport {
    isolate_ambient_daemons();
    real_execute_run_task(params, llm).await
}

// ── Scripted offline LLM ───────────────────────────────────────────────────────

/// Replays a fixed queue of responses and records every request's model.
///
/// Why: Deterministic, offline substitute for the network client shared by the
/// PM and engineer loops. Recording the per-request model lets the #1035 tests
/// assert which slug drove the engineer's turns (alongside the transcript).
/// What: Holds JSON-deserialised responses, an atomic cursor, and a log of the
/// models seen. Exhaustion yields a transport-style error so a runaway loop fails
/// loudly rather than hanging.
/// Test: Used by every test below.
struct ScriptedLlm {
    responses: Vec<ChatResponse>,
    cursor: AtomicUsize,
    models: Mutex<Vec<String>>,
    /// Every request's `max_tokens`, in call order — lets
    /// `pm_llm_max_tokens_reaches_chat_request` assert the PM's configured
    /// `[llm].max_tokens` reached the wire request rather than being silently
    /// dropped in favour of the agent-loop default (the run_task max-tokens
    /// bug this test guards against).
    max_tokens: Mutex<Vec<Option<u32>>>,
    /// Every request's advertised tool-schema names, in call order (#2348:
    /// lets `run_task_registry_never_registers_recall_session` assert the
    /// one-shot path's actual wire-level tool set, rather than re-deriving
    /// the registration logic in the test).
    tool_names: Mutex<Vec<Vec<String>>>,
}

impl ScriptedLlm {
    fn from_json(fixtures: &[Value]) -> Self {
        let responses = fixtures
            .iter()
            .map(|v| serde_json::from_value(v.clone()).expect("valid ChatResponse fixture"))
            .collect();
        Self {
            responses,
            cursor: AtomicUsize::new(0),
            models: Mutex::new(Vec::new()),
            max_tokens: Mutex::new(Vec::new()),
            tool_names: Mutex::new(Vec::new()),
        }
    }

    /// Every model slug the client was asked to use, in call order.
    fn models_seen(&self) -> Vec<String> {
        self.models.lock().expect("models lock").clone()
    }

    /// The `max_tokens` of the first recorded request (the PM's first turn).
    fn first_max_tokens(&self) -> Option<u32> {
        self.max_tokens
            .lock()
            .expect("max_tokens lock")
            .first()
            .copied()
            .expect("at least one request recorded")
    }

    /// The tool-schema names advertised on the FIRST recorded request (the
    /// PM's first turn, where its own `pm_registry` schemas are attached).
    fn first_tool_names(&self) -> Vec<String> {
        self.tool_names
            .lock()
            .expect("tool_names lock")
            .first()
            .cloned()
            .expect("at least one request recorded")
    }

    /// The tool-schema names advertised on the request at `idx` (0-based, call
    /// order) — lets a test reach a non-first turn's advertised schema, e.g.
    /// the delegated engineer's first turn (request idx 1, right after the
    /// PM's own delegate call at idx 0).
    fn tool_names_at(&self, idx: usize) -> Vec<String> {
        self.tool_names
            .lock()
            .expect("tool_names lock")
            .get(idx)
            .cloned()
            .unwrap_or_else(|| panic!("no request recorded at idx {idx}"))
    }
}

#[async_trait]
impl InferenceAdapter for ScriptedLlm {
    crate::llm::mock_adapter_identity!("mock-scripted");

    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
        self.models
            .lock()
            .expect("models lock")
            .push(req.model.clone());
        self.max_tokens
            .lock()
            .expect("max_tokens lock")
            .push(req.max_tokens);
        let names = req
            .tools
            .as_ref()
            .map(|tools| tools.iter().map(|t| t.function.name.clone()).collect())
            .unwrap_or_default();
        self.tool_names.lock().expect("tool_names lock").push(names);
        let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
        match self.responses.get(idx) {
            Some(resp) => Ok(resp.clone()),
            None => Err(InferenceError::MissingConfig(format!(
                "scripted LLM exhausted at call {idx}"
            ))),
        }
    }
}

// ── Fixture builders ───────────────────────────────────────────────────────────

/// A response where the assistant calls `delegate_to_agent(python-engineer, …)`.
fn delegate_response(task: &str) -> Value {
    json!({
        "id": "gen-delegate",
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call-del",
                    "type": "function",
                    "function": {
                        "name": "delegate_to_agent",
                        "arguments": json!({"agent_name": "python-engineer", "task": task}).to_string()
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": {"prompt_tokens": 50, "completion_tokens": 12, "total_tokens": 62}
    })
}

/// A response where the assistant calls `write_file(path, content)`.
fn write_file_response(path: &str, content: &str) -> Value {
    json!({
        "id": "gen-write",
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call-wf",
                    "type": "function",
                    "function": {
                        "name": "write_file",
                        "arguments": json!({"path": path, "content": content}).to_string()
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": {"prompt_tokens": 30, "completion_tokens": 8, "total_tokens": 38}
    })
}

/// A response where the assistant calls `bash(command)` (#2279).
fn bash_response(command: &str) -> Value {
    json!({
        "id": "gen-bash",
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call-bash",
                    "type": "function",
                    "function": {
                        "name": "bash",
                        "arguments": json!({"command": command}).to_string()
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": {"prompt_tokens": 20, "completion_tokens": 10, "total_tokens": 30}
    })
}

/// A response where the assistant calls `finish_task(status, summary)`
/// (#2279).
fn finish_task_response(status: &str, summary: &str) -> Value {
    json!({
        "id": "gen-finish",
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call-finish",
                    "type": "function",
                    "function": {
                        "name": "finish_task",
                        "arguments": json!({"status": status, "summary": summary}).to_string()
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": {"prompt_tokens": 15, "completion_tokens": 8, "total_tokens": 23}
    })
}

/// A response where the assistant emits final text and stops.
fn stop_response(text: &str) -> Value {
    json!({
        "id": "gen-stop",
        "choices": [{
            "message": {"role": "assistant", "content": text, "tool_calls": []},
            "finish_reason": "stop"
        }],
        "usage": {"prompt_tokens": 15, "completion_tokens": 5, "total_tokens": 20}
    })
}

/// A response where the assistant emits final text and stops, ALSO
/// reporting a specific RESOLVED `model` slug — for the #1475 bug 2 test
/// (`transcript_records_resolved_model_not_requested_slug`), which needs a
/// response whose resolved model differs from what was requested.
fn stop_response_with_model(text: &str, model: &str) -> Value {
    json!({
        "id": "gen-stop",
        "model": model,
        "choices": [{
            "message": {"role": "assistant", "content": text, "tool_calls": []},
            "finish_reason": "stop"
        }],
        "usage": {"prompt_tokens": 15, "completion_tokens": 5, "total_tokens": 20}
    })
}

/// Build an agents dir with `pm.md` and `python-engineer.md`.
///
/// Why: `run-task` loads the PM config from `<agents_dir>/pm.md` and the
/// engineer from `<agents_dir>/python-engineer.md` (#2897 Slice D); tests
/// need both on disk.
/// What: Writes both `.md` agents (engineer pinned to `engineer_model`) and
/// returns the tempdir.
///
/// #7948: the PM declares a `tcode_tools:` allowlist that deliberately OMITS
/// `delegate_to_agent`, exactly as stock `pm.md` does, so every test below runs
/// through the gate's allowlist branch rather than past it — see
/// `pm_delegates_through_the_tcode_tools_allowlist`. The engineer declares none,
/// so its own tool use is unrestricted.
fn agents_dir(engineer_model: &str) -> TempDir {
    let tmp = tempfile::tempdir().expect("agents tempdir");
    std::fs::write(
        tmp.path().join("pm.md"),
        "---\nname: pm\nmodel: openai/gpt-4o-mini\ntcode_tools: [read_file, bash, finish_task]\n---\n\nYou are the PM.\n",
    )
    .expect("write pm.md");
    std::fs::write(
        tmp.path().join("python-engineer.md"),
        format!(
            "---\nname: python-engineer\nmodel: {engineer_model}\n---\n\nYou are a Python engineer.\n"
        ),
    )
    .expect("write python-engineer.md");
    tmp
}

/// Build the standard params for a run against the given dirs.
///
/// The `engineer_model` slot carries the per-run `--engineer-model` override
/// (#1035); `None` routes the engineer via its own config model.
fn params(agents: &TempDir, project: &TempDir, engineer_model: Option<&str>) -> RunTaskParams {
    RunTaskParams {
        permission_mode: crate::permissions::PermissionMode::Default,
        agent: "pm".into(),
        task: "write hello.py".into(),
        project: project.path().to_path_buf(),
        agents_dir: agents.path().to_path_buf(),
        engineer_model: engineer_model.map(str::to_string),
        deadline_secs: None,
        no_delegate: false,
        pm_model: None,
        max_turns: None,
    }
}

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

/// Full path: the PM delegates to the engineer, who writes a file; the diff
/// reflects that change, the transcript carries both roles, and exit is Success.
///
/// Why: The core #1034 acceptance criterion — `run-task` actually executes
/// PM→engineer end-to-end and reports the real change.
/// What: Script [PM delegate, engineer write_file, engineer stop, PM stop].
/// Run; assert exit=Success, the diff names `hello.py` with its content, and the
/// transcript has a "pm" turn and a "python-engineer" turn.
/// Test: this test.
#[tokio::test]
async fn end_to_end_pm_delegates_to_engineer() {
    let agents = agents_dir("deepseek/deepseek-chat");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_response("create hello.py"),
        write_file_response("hello.py", "print('hello from engineer')"),
        stop_response("engineer: wrote hello.py"),
        stop_response("pm: task complete"),
    ]));

    let report = execute_run_task(params(&agents, &project, None), llm).await;

    assert_eq!(
        report.exit,
        ExitCode::Success,
        "run with a file change must exit Success; diff was: {}",
        report.diff
    );
    assert!(
        report.diff.contains("hello.py"),
        "diff must name the engineer's file, got: {}",
        report.diff
    );
    assert!(
        report.diff.contains("hello from engineer"),
        "diff must contain the new content, got: {}",
        report.diff
    );

    // File actually landed in the project.
    let written = std::fs::read_to_string(project.path().join("hello.py")).expect("file written");
    assert_eq!(written, "print('hello from engineer')");

    // Transcript carries both roles.
    let roles: Vec<&str> = report.transcript.iter().map(|t| t.role.as_str()).collect();
    assert!(
        roles.contains(&"pm"),
        "transcript must have a PM turn: {roles:?}"
    );
    assert!(
        roles.contains(&"python-engineer"),
        "transcript must have an engineer turn: {roles:?}"
    );
}

/// (#7948 regression) The PM's delegation survives a `tcode_tools:` allowlist
/// that never names `delegate_to_agent`, END TO END through `execute_run_task`.
///
/// Why: the gate's allowlist branch denies a tool the list omits, and the
/// harness — not the agent's author — registers `delegate_to_agent`, so stock
/// `pm.md` would have had its own delegation refused. Until this fixture
/// declared an allowlist, no end-to-end test entered that branch at all; the
/// exemption was pinned only by unit tests over `PermissionGate::evaluate`.
/// What: assert the fixture premise (the allowlist exists and omits
/// `delegate_to_agent`), then script a delegation and assert it DISPATCHED —
/// an engineer turn in the transcript and the engineer's file on disk, neither
/// of which a refused `delegate_to_agent` can produce.
/// Test: this test.
#[tokio::test]
async fn pm_delegates_through_the_tcode_tools_allowlist() {
    let agents = agents_dir("deepseek/deepseek-chat");
    let project = tempfile::tempdir().expect("project tempdir");

    let pm = crate::agents::resolve_agent(agents.path(), "pm").expect("fixture pm.md loads");
    let allowed = pm
        .tools
        .as_ref()
        .and_then(|t| t.allowed.as_ref())
        .expect("fixture premise: the PM must declare a tcode_tools allowlist");
    assert!(
        !allowed.iter().any(|t| t == "delegate_to_agent"),
        "fixture premise: the allowlist must omit delegate_to_agent, got {allowed:?}"
    );

    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_response("create delegated.py"),
        write_file_response("delegated.py", "print('dispatched')"),
        stop_response("engineer: done"),
        stop_response("pm: task complete"),
    ]));

    let report = execute_run_task(params(&agents, &project, None), llm).await;

    let roles: Vec<&str> = report.transcript.iter().map(|t| t.role.as_str()).collect();
    assert!(
        roles.contains(&"python-engineer"),
        "a refused delegate_to_agent never reaches the engineer; roles: {roles:?}"
    );
    assert_eq!(
        std::fs::read_to_string(project.path().join("delegated.py")).ok(),
        Some("print('dispatched')".to_string()),
        "the delegated engineer must have actually run; diff was: {}",
        report.diff
    );
}

/// #8158: a delegated turn is recorded under the agent the PM actually
/// delegated to, not the fixed `python-engineer` label.
///
/// Why: the parity lab's Rust runs reported every engineer turn as
/// `python-engineer` because the engineer's recorder was bound to a constant
/// at construction, while `delegate_to_agent` dispatched to `rust-engineer`.
/// What: an agents dir that also carries `rust-engineer.md`; the PM delegates
/// to it; asserts the transcript (the source of every report role label)
/// carries a `rust-engineer` turn and no `python-engineer` turn. FAILS at
/// c69c8e01be: the only non-PM role is `python-engineer`.
/// Test: this test.
#[tokio::test]
async fn delegated_turns_carry_the_delegated_agents_role() {
    let agents = agents_dir("deepseek/deepseek-chat");
    std::fs::write(
        agents.path().join("rust-engineer.md"),
        "---\nname: rust-engineer\nmodel: deepseek/deepseek-chat\n---\n\nYou are a Rust engineer.\n",
    )
    .expect("write rust-engineer.md");
    let project = tempfile::tempdir().expect("project tempdir");

    let delegate_to_rust = json!({
        "id": "gen-delegate-rust",
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call-del-rust",
                    "type": "function",
                    "function": {
                        "name": "delegate_to_agent",
                        "arguments": json!({"agent_name": "rust-engineer", "task": "create lib.rs"}).to_string()
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": {"prompt_tokens": 50, "completion_tokens": 12, "total_tokens": 62}
    });
    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_to_rust,
        write_file_response("lib.rs", "pub fn f() {}"),
        stop_response("rust-engineer: done"),
        stop_response("pm: task complete"),
    ]));

    let report = execute_run_task(params(&agents, &project, None), llm).await;

    let roles: Vec<&str> = report.transcript.iter().map(|t| t.role.as_str()).collect();
    assert!(
        roles.contains(&"rust-engineer"),
        "the delegated turns must carry the delegated agent's name; roles: {roles:?}"
    );
    assert!(
        !roles.contains(&"python-engineer"),
        "no turn ran as python-engineer, so none may be labelled so; roles: {roles:?}"
    );
}

/// #8288: the legacy path's delegating PM writes no source through its own
/// card either — the sibling of
/// `task::executor::tests::delegating_pm_cannot_write_source_through_itself`.
///
/// What: a disk `pm.md` granting `write_file` as `ask`, `AllowAsks`, the PM
/// delegating to `pm`; asserts the delegation is refused at dispatch (no
/// sub-agent turns) and that no write landed. FAILS at 97038f5a23: the
/// sub-agent runs.
/// Test: this test.
#[tokio::test]
async fn delegating_pm_cannot_write_source_through_itself() {
    let agents = agents_dir("deepseek/deepseek-chat");
    std::fs::write(
        agents.path().join("pm.md"),
        "---\nname: pm\nmodel: openai/gpt-4o-mini\ntcode_tools: [read_file, write_file, finish_task]\npermissions:\n  write_file: ask\n---\n\nYou are the PM.\n",
    )
    .expect("write pm.md");
    let project = tempfile::tempdir().expect("project tempdir");
    let delegate_to_self = json!({
        "id": "gen-delegate-self",
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call-del-self",
                    "type": "function",
                    "function": {
                        "name": "delegate_to_agent",
                        "arguments": json!({"agent_name": "pm", "task": "create self.py"}).to_string()
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": {"prompt_tokens": 50, "completion_tokens": 12, "total_tokens": 62}
    });
    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_to_self,
        write_file_response("self.py", "print('pm')"),
        stop_response("pm sub-agent: done"),
        stop_response("pm: task complete"),
    ]));
    let p = RunTaskParams {
        permission_mode: crate::permissions::PermissionMode::AllowAsks,
        ..params(&agents, &project, None)
    };

    let report = execute_run_task(p, llm).await;

    // Delegate, a refused-then-denied write, stop: three PM turns and no
    // sub-agent turns (a dispatched self-delegation adds a fourth).
    assert_eq!(
        report.transcript.len(),
        3,
        "the self-delegation must be refused, not run: {:?}",
        report.transcript
    );
    assert!(
        !project.path().join("self.py").exists(),
        "a delegating PM must not write source by delegating to its own card"
    );
}

/// The PM's configured `[llm].max_tokens` reaches its `ChatRequest` via
/// `execute_run_task` — the exact entry point of the run_task max-tokens bug.
///
/// Why: `execute_run_task` previously built the PM's `AgentLoopConfig` via
/// `AgentLoopConfig { model: pm_model, ..AgentLoopConfig::default() }`,
/// dropping `pm_config.llm.max_tokens` entirely so every PM turn was capped at
/// the hard-coded default regardless of what `pm.md` declared. This is the
/// end-to-end regression guard: a `pm.md` with `max_tokens: 8192` must
/// produce a `ChatRequest.max_tokens` of `8192`, never the old 1024.
/// What: `pm.md` declares `max_tokens: 8192`; script a single PM stop turn;
/// assert the scripted client observed `Some(8192)`.
/// Test: this test.
#[tokio::test]
async fn pm_llm_max_tokens_reaches_chat_request() {
    let agents = tempfile::tempdir().expect("agents tempdir");
    std::fs::write(
        agents.path().join("pm.md"),
        "---\nname: pm\nmodel: openai/gpt-4o-mini\nmax_tokens: 8192\n---\n\n\
         You are the PM.\n",
    )
    .expect("write pm.md");
    std::fs::write(
        agents.path().join("python-engineer.md"),
        "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\nYou are a Python engineer.\n",
    )
    .expect("write python-engineer.md");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response(
        "pm: nothing to do",
    )]));

    let _report = execute_run_task(params(&agents, &project, None), llm.clone()).await;

    assert_eq!(
        llm.first_max_tokens(),
        Some(8192),
        "PM's configured [llm].max_tokens must reach its ChatRequest, not the old 1024 default"
    );
}

/// The transcript must record the RESOLVED model slug a response reports,
/// not merely the slug that was requested (#1475 bug 2).
///
/// Why: `RecordingLlmClient::chat` previously recorded `req.model` (what was
/// asked for); if the provider remaps/falls back to a different concrete
/// model, that divergence must be visible in the transcript for the #1035
/// cross-model comparison to be trustworthy.
/// What: Script the PM's FINAL (stop) response with a `model` field that
/// differs from the PM agent config's own model
/// (`openai/gpt-4o-mini` vs. the response's `openai/gpt-4o-mini-2024-07-18`);
/// assert the recorded PM turn's `model` is the response's resolved slug.
/// Test: this test.
#[tokio::test]
async fn transcript_records_resolved_model_not_requested_slug() {
    let agents = agents_dir("deepseek/deepseek-chat");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_response("create hello.py"),
        write_file_response("hello.py", "print('hi')"),
        stop_response("engineer: wrote hello.py"),
        stop_response_with_model("pm: task complete", "openai/gpt-4o-mini-2024-07-18"),
    ]));

    let report = execute_run_task(params(&agents, &project, None), llm).await;

    let pm_final_turn = report
        .transcript
        .iter()
        .rev()
        .find(|t| t.role == "pm")
        .expect("a pm turn must be recorded");
    assert_eq!(
        pm_final_turn.model, "openai/gpt-4o-mini-2024-07-18",
        "transcript must record the RESOLVED model, not the requested slug \
         (openai/gpt-4o-mini)"
    );
}

/// Usage and cost aggregate across PM and engineer turns.
///
/// Why: The report must sum token usage over the whole run (criterion c).
/// What: Same script as the happy path; assert the report's prompt/completion
/// totals equal the sum of every scripted turn's usage, and cost is computed.
/// Test: this test.
#[tokio::test]
async fn usage_and_cost_aggregate_end_to_end() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_response("create out.py"),   // 50 + 12
        write_file_response("out.py", "x=1"), // 30 + 8
        stop_response("engineer done"),       // 15 + 5
        stop_response("pm done"),             // 15 + 5
    ]));

    let report = execute_run_task(params(&agents, &project, None), llm).await;

    assert_eq!(
        report.usage.prompt_tokens,
        50 + 30 + 15 + 15,
        "prompt tokens must sum across all PM + engineer turns"
    );
    assert_eq!(
        report.usage.completion_tokens,
        12 + 8 + 5 + 5,
        "completion tokens must sum across all turns"
    );
    assert!(
        report.cost_usd.is_some_and(|c| c >= 0.0),
        "cost must be computed and non-negative"
    );
}

/// A run that changes nothing reports `NoChanges` and an empty diff.
///
/// Why: The distinct no-op exit code must fire when the engineer writes nothing.
/// What: Script [PM stop] only — the PM concludes without delegating, so no file
/// is touched. Assert exit=NoChanges and an empty diff.
/// Test: this test.
#[tokio::test]
async fn no_changes_yields_no_changes_exit() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response(
        "pm: nothing to do",
    )]));

    let report = execute_run_task(params(&agents, &project, None), llm).await;

    assert_eq!(
        report.exit,
        ExitCode::NoChanges,
        "a run that touches no files must exit NoChanges; diff: {}",
        report.diff
    );
    assert!(report.diff.trim().is_empty(), "diff must be empty");
}

/// An agent name with NEITHER a disk config NOR an embedded default is a
/// configuration error (no panic, distinct exit code).
///
/// Why: Bad configuration must produce a faithful `ConfigError`, not a crash.
/// This is the regression pin `missing_pm_config_is_config_error` used to
/// cover with `agent: "pm"` before #3437 added an embedded `pm` default —
/// `"pm"` now ALWAYS resolves (see
/// `missing_disk_pm_config_falls_back_to_embedded_pm` below), so the
/// still-valid "unresolvable agent is a config error" case is exercised here
/// with an agent name that is genuinely absent from both disk and
/// [`crate::assets::DEFAULT_AGENTS`].
/// What: Point the params at an empty agents dir with agent name
/// `"totally-not-a-real-agent"`; assert exit=ConfigError.
/// Test: this test.
#[tokio::test]
async fn missing_agent_config_is_config_error() {
    let empty_agents = tempfile::tempdir().expect("agents tempdir");
    let project = tempfile::tempdir().expect("project tempdir");
    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("unused")]));

    let report = execute_run_task(
        RunTaskParams {
            permission_mode: crate::permissions::PermissionMode::Default,
            agent: "totally-not-a-real-agent".into(),
            task: "anything".into(),
            project: project.path().to_path_buf(),
            agents_dir: empty_agents.path().to_path_buf(),
            engineer_model: None,
            deadline_secs: None,
            no_delegate: false,
            pm_model: None,
            max_turns: None,
        },
        llm,
    )
    .await;

    assert_eq!(
        report.exit,
        ExitCode::ConfigError,
        "an agent name absent from both disk and the embedded roster must be a config error"
    );
}

/// `agent: "pm"` with NO disk `pm.md` now resolves via the embedded default
/// (#3437) instead of failing agent resolution.
///
/// Why: this is the acceptance test for #3437 at the `run_task` level — the
/// exact call shape (`agent: "pm"`, empty `agents_dir`) that used to hit
/// `ConfigError` before the embedded `pm` agent existed must now actually
/// run the PM loop and reach a normal exit code.
/// What: Same empty-agents-dir shape as `missing_agent_config_is_config_error`,
/// but `agent: "pm"` with a scripted `[PM stop]` response; asserts the run
/// reaches `ExitCode::NoChanges` (the PM concluded without delegating), not
/// `ConfigError`.
/// Test: this test.
#[tokio::test]
async fn missing_disk_pm_config_falls_back_to_embedded_pm() {
    let empty_agents = tempfile::tempdir().expect("agents tempdir");
    let project = tempfile::tempdir().expect("project tempdir");
    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response(
        "pm: nothing to do",
    )]));

    let report = execute_run_task(
        RunTaskParams {
            permission_mode: crate::permissions::PermissionMode::Default,
            agent: "pm".into(),
            task: "anything".into(),
            project: project.path().to_path_buf(),
            agents_dir: empty_agents.path().to_path_buf(),
            engineer_model: None,
            deadline_secs: None,
            no_delegate: false,
            pm_model: None,
            max_turns: None,
        },
        llm,
    )
    .await;

    assert_eq!(
        report.exit,
        ExitCode::NoChanges,
        "'pm' with no disk config must resolve via the embedded default (#3437) and run, \
         not fail with ConfigError; report: {report:?}"
    );
}

/// `resolve_agent_model_slug` degrades to `"unknown"` when the agent's `.md`
/// config is missing, rather than panicking or propagating an error.
///
/// Why: pricing (`crate::perf::cost_usd`) must degrade gracefully for an
/// unrecognised model, not abort the whole run over a missing/renamed agent
/// config — see this function's own doc comment.
/// What: an empty agents dir, no `ghost.md`; asserts the literal string
/// `"unknown"`.
/// Test: this test.
#[test]
fn resolve_agent_model_slug_falls_back_when_config_missing() {
    let empty_agents = tempfile::tempdir().expect("agents tempdir");
    let slug = resolve_agent_model_slug(empty_agents.path(), "ghost", None);
    assert_eq!(slug, "unknown");
}

/// `resolve_agent_model_slug`'s `model_override` wins over the agent
/// config's own `model:`.
///
/// Why: mirrors `RunContext`'s override precedence — a per-run
/// `--engineer-model` swap must be reflected in the PRICED model, not just
/// the one that actually drove the loop.
/// What: `python-engineer.md` pins `openai/gpt-4o-mini`; pass
/// `Some("deepseek/deepseek-chat")` as the override; asserts the override
/// slug wins.
/// Test: this test.
#[test]
fn resolve_agent_model_slug_honours_override() {
    let agents = tempfile::tempdir().expect("agents tempdir");
    std::fs::write(
        agents.path().join("python-engineer.md"),
        "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n\nengineer\n",
    )
    .expect("write python-engineer.md");

    let slug = resolve_agent_model_slug(
        agents.path(),
        "python-engineer",
        Some("deepseek/deepseek-chat"),
    );
    assert_eq!(slug, "deepseek/deepseek-chat");
}

/// A PM loop that errors (scripted client exhausts on a tool-call turn) yields
/// `RunFailure`.
///
/// Why: A runtime failure must map to the `RunFailure` exit code (criterion d).
/// What: Script only a delegate turn but no engineer responses, so the engineer
/// loop hits the exhausted client and errors, surfacing back through the PM. With
/// the PM then also exhausted, the PM loop errors. Assert exit=RunFailure.
/// Test: this test.
#[tokio::test]
async fn exit_code_reflects_run_failure() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    // PM delegates, but there are NO further responses: the engineer loop's first
    // chat call exhausts the script and errors; the delegate tool surfaces a
    // recoverable error; the PM's next turn also exhausts → PM loop errors.
    let llm = Arc::new(ScriptedLlm::from_json(&[delegate_response("do work")]));

    let report = execute_run_task(params(&agents, &project, None), llm).await;

    assert_eq!(
        report.exit,
        ExitCode::RunFailure,
        "an LLM/loop error must map to RunFailure"
    );
}

// ── #2207/#2206: configurable deadline + distinct status + telemetry ───────────

/// A response in which the assistant calls `finish_task` with a required
/// field (`summary`) missing — recoverable per #2072's schema-validation
/// path, NOT terminal.
fn malformed_finish_task_response() -> Value {
    json!({
        "id": "gen-finish-malformed",
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call-missing",
                    "type": "function",
                    "function": {
                        "name": "finish_task",
                        "arguments": json!({"status": "completed"}).to_string()
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": {"prompt_tokens": 40, "completion_tokens": 10, "total_tokens": 50}
    })
}

/// An `InferenceAdapter` that sleeps before its Nth `chat` call, then delegates.
///
/// Why: Deterministically drives the PM's own wall-clock deadline past its
/// configured budget — the FIRST call (index 0) completes instantly and is
/// recorded with real usage before the deadline fires, then a later call
/// sleeps well past the remaining budget, so `AgentLoop::run`'s outer
/// `tokio::time::timeout` aborts mid-flight rather than the loop reaching a
/// clean or genuinely failed terminal state.
/// What: Wraps a `ScriptedLlm`; sleeps `stall_for` on the call whose index
/// equals `stall_at_call`, then delegates to the inner scripted client.
/// Test: `exit_code_reflects_deadline_exceeded_distinct_from_run_failure`.
struct DeadlineTriggerLlm {
    inner: ScriptedLlm,
    counter: AtomicUsize,
    stall_at_call: usize,
    stall_for: std::time::Duration,
}

#[async_trait]
impl InferenceAdapter for DeadlineTriggerLlm {
    crate::llm::mock_adapter_identity!("mock-deadline-trigger");

    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
        let idx = self.counter.fetch_add(1, Ordering::SeqCst);
        if idx == self.stall_at_call {
            tokio::time::sleep(self.stall_for).await;
        }
        self.inner.chat(req).await
    }
}

/// A tiny configured deadline yields `DeadlineExceeded` — distinct from
/// `RunFailure` — AND the report still carries non-zero usage/cost from the
/// turn(s) that DID complete before the deadline fired (#2207 + #2206).
///
/// Why: This is the exact scenario #2207 found blocking the M3 bake-off: a
/// real, otherwise-productive run cut off mid-flight must be distinguishable
/// from a genuine crash, and its accrued cost/usage must not be silently
/// zeroed (#2206) — the bake-off runner needs real telemetry on EVERY
/// terminal path, not just the clean one.
/// What: `deadline_secs: Some(1)`. The scenario stays entirely within the
/// PM's OWN loop (no delegation) to avoid a race against the delegated
/// engineer's own independently-resolved deadline: turn 0 is a malformed
/// `finish_task` call (instant, recoverable, recorded with real usage), then
/// turn 1 sleeps 3s — well past the 1s budget — so the PM's own outer
/// `tokio::time::timeout` fires before that second turn ever completes.
/// Assert `exit == DeadlineExceeded` (not `RunFailure`) and `usage`/`cost_usd`
/// are non-zero/`Some`.
/// Test: this test.
#[tokio::test]
async fn exit_code_reflects_deadline_exceeded_distinct_from_run_failure() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(DeadlineTriggerLlm {
        inner: ScriptedLlm::from_json(&[
            malformed_finish_task_response(),
            stop_response("recovered (never reached in time)"),
        ]),
        counter: AtomicUsize::new(0),
        stall_at_call: 1,
        stall_for: std::time::Duration::from_secs(3),
    });

    let mut task_params = params(&agents, &project, None);
    task_params.deadline_secs = Some(1);

    let started = std::time::Instant::now();
    let report = execute_run_task(task_params, llm).await;
    let elapsed = started.elapsed();

    assert_eq!(
        report.exit,
        ExitCode::DeadlineExceeded,
        "a deadline hit must map to DeadlineExceeded, not RunFailure"
    );
    assert!(
        report.usage.prompt_tokens > 0,
        "the PM's completed first turn must still contribute real usage, got {:?}",
        report.usage
    );
    assert!(
        report.cost_usd.is_some(),
        "cost must be populated (not None) on the deadline-exceeded path"
    );
    assert!(
        elapsed < std::time::Duration::from_secs(3),
        "the 1s deadline must fire well before the mock's 3s delay, elapsed={elapsed:?}"
    );

    let rendered = report.render_json();
    let parsed: Value = serde_json::from_str(&rendered).expect("report JSON must parse");
    assert_eq!(parsed["status"], "deadline_exceeded");
}

/// A generous configured deadline does NOT prematurely kill a normal run
/// (#2207).
///
/// Why: The companion regression guard — raising the deadline (e.g. for the
/// M3 bake-off's L2/L3 multi-hour tasks) must not itself break a run that
/// would otherwise complete quickly.
/// What: `deadline_secs: Some(5)` against the standard instant PM->engineer
/// happy path; assert `exit == Success`.
/// Test: this test.
#[tokio::test]
async fn generous_deadline_does_not_abort_a_normal_run() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_response("create j.py"),
        write_file_response("j.py", "y=2"),
        stop_response("engineer done"),
        stop_response("pm done"),
    ]));

    let mut task_params = params(&agents, &project, None);
    task_params.deadline_secs = Some(5);

    let report = execute_run_task(task_params, llm).await;

    assert_eq!(
        report.exit,
        ExitCode::Success,
        "a generous deadline must not abort a run that finishes well within budget"
    );
}

/// JSON render of the report is clean, parseable, and complete.
///
/// Why: `--json` mode must emit machine-readable output; the report is its source.
/// What: Run the happy path, render JSON, parse it back, assert status + diff +
/// transcript presence.
/// Test: this test.
#[tokio::test]
async fn report_json_is_parseable() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_response("create j.py"),
        write_file_response("j.py", "y=2"),
        stop_response("engineer done"),
        stop_response("pm done"),
    ]));

    let report = execute_run_task(params(&agents, &project, None), llm).await;
    let rendered = report.render_json();
    let parsed: Value = serde_json::from_str(&rendered).expect("report JSON must parse");

    assert_eq!(parsed["status"], "success");
    assert!(parsed["diff"].as_str().unwrap().contains("j.py"));
    assert!(parsed["transcript"].as_array().unwrap().len() >= 2);
}

// ── #1035: per-run engineer model swap ──────────────────────────────────────────

/// `engineer_model` override routes the engineer's turns to the given slug while
/// the PM model stays fixed.
///
/// Why: The #1035 acceptance criterion — a per-run `--engineer-model` reroutes
/// only the engineer; the PM model is unchanged.
/// What: Engineer config pins `deepseek/deepseek-chat`, but the run overrides it
/// to `anthropic/claude-haiku-4-5`. Assert the engineer transcript turns carry the
/// override slug and the PM turns carry the PM model.
/// Test: this test.
#[tokio::test]
async fn engineer_model_swap_routes_engineer() {
    let agents = agents_dir("deepseek/deepseek-chat");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_response("create s.py"),
        write_file_response("s.py", "z=3"),
        stop_response("engineer done"),
        stop_response("pm done"),
    ]));

    let report = execute_run_task(
        params(&agents, &project, Some("anthropic/claude-haiku-4-5")),
        llm,
    )
    .await;

    // Engineer turns must carry the OVERRIDE slug, not the config slug.
    let eng_models: Vec<&str> = report
        .transcript
        .iter()
        .filter(|t| t.role == "python-engineer")
        .map(|t| t.model.as_str())
        .collect();
    assert!(!eng_models.is_empty(), "expected engineer turns");
    assert!(
        eng_models
            .iter()
            .all(|m| *m == "anthropic/claude-haiku-4-5"),
        "engineer turns must route to the override slug, got: {eng_models:?}"
    );

    // PM turns must keep the PM model.
    let pm_models: Vec<&str> = report
        .transcript
        .iter()
        .filter(|t| t.role == "pm")
        .map(|t| t.model.as_str())
        .collect();
    assert!(
        pm_models.iter().all(|m| *m == "openai/gpt-4o-mini"),
        "PM turns must keep the PM model, got: {pm_models:?}"
    );
}

/// Two runs with different `--engineer-model` slugs route the engineer to each.
///
/// Why: Criterion (a) of #1035 — distinct slugs route distinctly across runs.
/// What: Run twice with two different override slugs; assert each run's engineer
/// turns carry its own slug.
/// Test: this test.
#[tokio::test]
async fn two_runs_route_engineer_to_distinct_slugs() {
    for slug in ["openai/gpt-4o", "anthropic/claude-sonnet-4-6"] {
        let agents = agents_dir("deepseek/deepseek-chat");
        let project = tempfile::tempdir().expect("project tempdir");
        let llm = Arc::new(ScriptedLlm::from_json(&[
            delegate_response("create m.py"),
            write_file_response("m.py", "v=1"),
            stop_response("engineer done"),
            stop_response("pm done"),
        ]));

        let report = execute_run_task(params(&agents, &project, Some(slug)), llm.clone()).await;

        let eng_models: Vec<String> = report
            .transcript
            .iter()
            .filter(|t| t.role == "python-engineer")
            .map(|t| t.model.clone())
            .collect();
        assert!(
            eng_models.iter().all(|m| m == slug),
            "engineer must route to {slug}, got: {eng_models:?}"
        );
        // Confirm the model log on the scripted client also saw the slug.
        assert!(
            llm.models_seen().iter().any(|m| m == slug),
            "scripted client must have seen {slug}"
        );
    }
}

// ── #2265: re-delegation cap, reuse-aware Llm hint, partial status ─────────────

/// Repeated `AgentLoopError::Llm` failures from the engineer trigger the
/// re-delegation cap (fix #1) — NOT the PM's own turn cap — producing a
/// report that names the cap explicitly, using only a couple of PM turns
/// regardless of how many internal engineer retries occurred (fix #3,
/// decoupled design).
///
/// Why: This is the exact regression #2265 closes: before this fix, each
/// PM-driven retry could burn up to 40 engineer turns (#2233) while the PM
/// itself had only 8 attempts to notice and react, so a recurring retryable
/// Bedrock/transport error blew up session turn counts (~40 to ~111) and hit
/// the PM's OWN turn cap, reported as an opaque `run_failure`. Now the cap in
/// `run_task::redelegation` governs retry count entirely inside ONE
/// `delegate_to_agent` dispatch.
/// What: Script ONLY the PM's initial `delegate_to_agent` call — every
/// subsequent `chat` call (every engineer retry attempt, and the PM's own
/// follow-up turn) exhausts the scripted queue and returns
/// `InferenceError::MissingConfig`, i.e. a retryable `AgentLoopError::Llm` per
/// fix #2. No file is ever written, so the report is a genuine `RunFailure`
/// (no deliverable) — but assert its `task` text names "re-delegation limit
/// reached" (the fix #1 label), not a bare/opaque failure, and that at most 2
/// PM-role transcript turns were recorded — proof the engineer's internal
/// retries never touched the PM's own turn budget.
/// Test: this test.
#[tokio::test]
async fn repeated_llm_errors_trigger_redelegation_cap_not_pm_turn_cap() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[delegate_response("do work")]));

    let report = execute_run_task(params(&agents, &project, None), llm).await;

    assert_eq!(
        report.exit,
        ExitCode::RunFailure,
        "no deliverable was ever produced, so this must stay a genuine failure"
    );
    assert!(
        report.task.contains("re-delegation limit reached"),
        "the report must name the re-delegation cap (fix #1), not an opaque \
         failure, got: {}",
        report.task
    );

    let pm_turns = report.transcript.iter().filter(|t| t.role == "pm").count();
    assert!(
        pm_turns <= 2,
        "the PM must need only a couple of turns regardless of how many internal \
         engineer retries occurred — decoupling proof (fix #3), got {pm_turns} PM turns"
    );
}

/// `assemble_report` maps a PM-loop `TurnCapExceeded` error to the new
/// `Partial` status (fix #4) — NOT `RunFailure` — when a non-empty diff shows
/// a deliverable was actually produced.
///
/// Why: This is fix #4's core contract: trusty-code cannot generically verify
/// correctness, so a turn-cap hit must not discard a working, on-disk
/// solution as an opaque crash purely because the PM ran out of turns.
/// What: Calls the crate-private `assemble_report` directly with a
/// `TurnCapExceeded` `pm_result` and a before/after `Snapshot::Files` pair
/// that differ (one new file). Assert `exit == ExitCode::Partial`, the
/// rendered diff is non-empty, and the task label mentions the turn cap.
/// Test: this test.
#[test]
fn assemble_report_maps_turn_cap_exceeded_with_deliverable_to_partial() {
    let params = RunTaskParams {
        permission_mode: crate::permissions::PermissionMode::Default,
        agent: "pm".into(),
        task: "write hello.py".into(),
        project: PathBuf::from("/tmp/does-not-matter"),
        agents_dir: PathBuf::from("/tmp/does-not-matter-agents"),
        engineer_model: None,
        deadline_secs: None,
        no_delegate: false,
        pm_model: None,
        max_turns: None,
    };
    let transcript: super::SharedTranscript = Arc::new(Mutex::new(Vec::new()));

    let before = super::diff::Snapshot::Files(std::collections::BTreeMap::new());
    let mut after_map = std::collections::BTreeMap::new();
    after_map.insert("hello.py".to_string(), "print('hi')".to_string());
    let after = super::diff::Snapshot::Files(after_map);

    let pm_result: Result<AgentOutput, AgentLoopError> = Err(AgentLoopError::TurnCapExceeded {
        max_turns: 8,
        partial: Box::new(AgentOutput::from_content("partial pm output")),
    });

    let signal = RedelegationCapSignal::new();
    let completion = EngineerCompletionSignal::new();
    let report = super::assemble_report(
        &params,
        &transcript,
        "openai/gpt-4o-mini",
        "openai/gpt-4o-mini",
        super::RunOutcome {
            before,
            after,
            pm_result,
        },
        &signal,
        &completion,
    );

    assert_eq!(
        report.exit,
        ExitCode::Partial,
        "a TurnCapExceeded PM error with a real deliverable must map to Partial, \
         not RunFailure (fix #4)"
    );
    assert!(
        report.diff.contains("hello.py"),
        "the deliverable's diff must still be rendered, got: {}",
        report.diff
    );
    assert!(
        report.task.contains("turn cap"),
        "the label must explain the turn-cap condition, got: {}",
        report.task
    );
}

/// `assemble_report` maps a retry-exhausted run WITH a deliverable to
/// `Partial`, labelled "re-delegation limit reached" (#2852).
///
/// Why: Post-#2852 this is arguably the most common real-world shape: retry
/// exhaustion is now RECOVERABLE, so the PM keeps its turns and the loop ends
/// on some other error while `retry_budget_exhausted` stays latched. Reporting
/// keys off that flag rather than only `cap_reached` precisely so such runs
/// keep their honest "the engineer was retried to exhaustion" diagnosis instead
/// of silently degrading to an opaque `run_failure` — the exact regression
/// #2852 set out to prevent. Nothing pinned this label's text, so it could have
/// rotted freely; this test is that pin.
/// What: Calls `assemble_report` directly with a signal that has ONLY
/// `retry_budget_exhausted` latched (never `cap_reached`), a non-`TurnCap` PM
/// error, and a before/after pair that differ. Assert `Partial`, and that the
/// label names the re-delegation limit and the attempt count — NOT the
/// invocation ceiling, which did not fire.
/// Test: this test.
#[test]
fn assemble_report_maps_retry_exhausted_with_deliverable_to_partial() {
    let params = RunTaskParams {
        permission_mode: crate::permissions::PermissionMode::Default,
        agent: "pm".into(),
        task: "write hello.py".into(),
        project: PathBuf::from("/tmp/does-not-matter"),
        agents_dir: PathBuf::from("/tmp/does-not-matter-agents"),
        engineer_model: None,
        deadline_secs: None,
        no_delegate: false,
        pm_model: None,
        max_turns: None,
    };
    let transcript: super::SharedTranscript = Arc::new(Mutex::new(Vec::new()));

    let before = super::diff::Snapshot::Files(std::collections::BTreeMap::new());
    let mut after_map = std::collections::BTreeMap::new();
    after_map.insert("hello.py".to_string(), "print('hi')".to_string());
    let after = super::diff::Snapshot::Files(after_map);

    // Deliberately NOT a turn cap: the point is that the retry-exhausted flag
    // alone carries the label, independent of which loop error surfaced.
    let pm_result: Result<AgentOutput, AgentLoopError> =
        Err(AgentLoopError::Llm(InferenceError::Api {
            status: 500,
            body: "upstream exploded".to_string(),
        }));

    let signal = RedelegationCapSignal::retry_exhausted_for_test();
    let completion = EngineerCompletionSignal::new();
    let report = super::assemble_report(
        &params,
        &transcript,
        "openai/gpt-4o-mini",
        "openai/gpt-4o-mini",
        super::RunOutcome {
            before,
            after,
            pm_result,
        },
        &signal,
        &completion,
    );

    assert_eq!(
        report.exit,
        ExitCode::Partial,
        "a retry-exhausted run that still produced a deliverable must map to Partial, \
         not RunFailure (#2852), got label: {}",
        report.task
    );
    assert!(
        report.task.contains("re-delegation limit reached"),
        "the label must name the re-delegation limit so the diagnosis is not lost, \
         got: {}",
        report.task
    );
    assert!(
        report
            .task
            .contains(&super::redelegation::MAX_REDELEGATIONS.to_string()),
        "the label must quote the per-delegation attempt count, got: {}",
        report.task
    );
    assert!(
        !report.task.contains("failure ceiling"),
        "the run-wide ceiling never fired — the label must not claim it did, got: {}",
        report.task
    );
}

/// The mirror negative case: a `TurnCapExceeded` PM error with an EMPTY diff
/// (no deliverable at all) stays `RunFailure` — the gate is purely "was work
/// produced", per fix #4's requirement to not weaken the genuine-failure path.
///
/// Why: Guards against over-broadly reclassifying every turn-cap hit as
/// `Partial` regardless of whether anything was actually produced.
/// What: Same as the positive test, but before == after (no change). Assert
/// `exit == ExitCode::RunFailure`.
/// Test: this test.
#[test]
fn assemble_report_keeps_turn_cap_exceeded_with_no_deliverable_as_run_failure() {
    let params = RunTaskParams {
        permission_mode: crate::permissions::PermissionMode::Default,
        agent: "pm".into(),
        task: "write hello.py".into(),
        project: PathBuf::from("/tmp/does-not-matter"),
        agents_dir: PathBuf::from("/tmp/does-not-matter-agents"),
        engineer_model: None,
        deadline_secs: None,
        no_delegate: false,
        pm_model: None,
        max_turns: None,
    };
    let transcript: super::SharedTranscript = Arc::new(Mutex::new(Vec::new()));

    let before = super::diff::Snapshot::Files(std::collections::BTreeMap::new());
    let after = super::diff::Snapshot::Files(std::collections::BTreeMap::new());

    let pm_result: Result<AgentOutput, AgentLoopError> = Err(AgentLoopError::TurnCapExceeded {
        max_turns: 8,
        partial: Box::new(AgentOutput::from_content("partial pm output")),
    });

    let signal = RedelegationCapSignal::new();
    let completion = EngineerCompletionSignal::new();
    let report = super::assemble_report(
        &params,
        &transcript,
        "openai/gpt-4o-mini",
        "openai/gpt-4o-mini",
        super::RunOutcome {
            before,
            after,
            pm_result,
        },
        &signal,
        &completion,
    );

    assert_eq!(
        report.exit,
        ExitCode::RunFailure,
        "a TurnCapExceeded PM error with NO deliverable must stay RunFailure (fix #4)"
    );
    let _ = &report;
}

// ── #2683: a completed engineer must never be mislabeled `partial`/exit-6 ──────

/// (#2683) `assemble_report` maps a PM-loop `TurnCapExceeded` error to
/// `Success` — NOT `Partial` — when the delegated engineer already reported an
/// explicit successful `finish_task` completion AND a deliverable is on disk.
///
/// Why: This is the exact data-integrity bug the issue's 2026-07-15 recurrence
/// comment reports: the engineer finished with all tests passing, then the PM
/// fired one more gratuitous re-verify `delegate_to_agent` round that ran the
/// PM's loop out of turns, and the complete, correct run was mislabeled
/// `partial`/exit-6, corrupting run status/telemetry. A satisfied task must
/// report success.
/// What: Calls `assemble_report` directly with a `TurnCapExceeded` `pm_result`,
/// a before/after `Snapshot` pair that differ (one new file), and a
/// completion signal that has latched. Assert `exit == Success` and the diff is
/// preserved.
/// Test: this test.
#[test]
fn assemble_report_maps_completed_engineer_with_deliverable_to_success() {
    let params = RunTaskParams {
        permission_mode: crate::permissions::PermissionMode::Default,
        agent: "pm".into(),
        task: "write hello.py".into(),
        project: PathBuf::from("/tmp/does-not-matter"),
        agents_dir: PathBuf::from("/tmp/does-not-matter-agents"),
        engineer_model: None,
        deadline_secs: None,
        no_delegate: false,
        pm_model: None,
        max_turns: None,
    };
    let transcript: super::SharedTranscript = Arc::new(Mutex::new(Vec::new()));

    let before = super::diff::Snapshot::Files(std::collections::BTreeMap::new());
    let mut after_map = std::collections::BTreeMap::new();
    after_map.insert("hello.py".to_string(), "print('hi')".to_string());
    let after = super::diff::Snapshot::Files(after_map);

    // The PM loop ran out of turns on the gratuitous re-verify round …
    let pm_result: Result<AgentOutput, AgentLoopError> = Err(AgentLoopError::TurnCapExceeded {
        max_turns: 8,
        partial: Box::new(AgentOutput::from_content("partial pm output")),
    });

    let signal = RedelegationCapSignal::new();
    // … but the engineer already reported a successful completion.
    let completion = EngineerCompletionSignal::new();
    completion.mark_completed();

    let report = super::assemble_report(
        &params,
        &transcript,
        "openai/gpt-4o-mini",
        "openai/gpt-4o-mini",
        super::RunOutcome {
            before,
            after,
            pm_result,
        },
        &signal,
        &completion,
    );

    assert_eq!(
        report.exit,
        ExitCode::Success,
        "a completed engineer with a real deliverable must report Success, never \
         Partial, even when the PM's loop later hit its turn cap (#2683); task: {}",
        report.task
    );
    assert!(
        report.diff.contains("hello.py"),
        "the completed deliverable's diff must still be rendered, got: {}",
        report.diff
    );
}

/// (#2683) A completed engineer with an EMPTY diff maps to `NoChanges`, not
/// `RunFailure` — a satisfied, no-op task is still a success outcome.
///
/// Why: Guards the empty-diff arm of the completion override so a genuinely
/// completed run that happened to change nothing is not conflated with a crash.
/// What: Same as above but before == after (no change); assert `NoChanges`.
/// Test: this test.
#[test]
fn assemble_report_maps_completed_engineer_without_deliverable_to_no_changes() {
    let params = RunTaskParams {
        permission_mode: crate::permissions::PermissionMode::Default,
        agent: "pm".into(),
        task: "analyze the repo".into(),
        project: PathBuf::from("/tmp/does-not-matter"),
        agents_dir: PathBuf::from("/tmp/does-not-matter-agents"),
        engineer_model: None,
        deadline_secs: None,
        no_delegate: false,
        pm_model: None,
        max_turns: None,
    };
    let transcript: super::SharedTranscript = Arc::new(Mutex::new(Vec::new()));

    let before = super::diff::Snapshot::Files(std::collections::BTreeMap::new());
    let after = super::diff::Snapshot::Files(std::collections::BTreeMap::new());

    let pm_result: Result<AgentOutput, AgentLoopError> = Err(AgentLoopError::TurnCapExceeded {
        max_turns: 8,
        partial: Box::new(AgentOutput::from_content("partial pm output")),
    });

    let signal = RedelegationCapSignal::new();
    let completion = EngineerCompletionSignal::new();
    completion.mark_completed();

    let report = super::assemble_report(
        &params,
        &transcript,
        "openai/gpt-4o-mini",
        "openai/gpt-4o-mini",
        super::RunOutcome {
            before,
            after,
            pm_result,
        },
        &signal,
        &completion,
    );

    assert_eq!(
        report.exit,
        ExitCode::NoChanges,
        "a completed engineer that changed nothing must be NoChanges, not RunFailure (#2683)"
    );
}

/// (#2683) End-to-end: after the engineer completes via `finish_task`, a
/// gratuitous PM re-delegation is REFUSED (the engineer is not re-invoked) and
/// the run reports `Success` rather than `partial`.
///
/// Why: Proves both halves of the fix through the real `execute_run_task`
/// wiring: (b) the `DelegateToAgentTool` refuses re-delegation once the
/// completion signal latches, and the data-integrity half — a complete run is
/// labeled Success even when the PM keeps trying to re-delegate.
/// What: Script [PM delegate, engineer write_file, engineer finish_task
/// (completed), PM delegate AGAIN (must be refused — engineer NOT re-invoked),
/// PM finish_task]. Assert `exit == Success`, the diff names `hello.py`, the
/// engineer was invoked exactly once (exactly two `python-engineer` turns), and
/// no wasted engineer round was spent (exactly five total chat calls).
/// Test: this test.
#[tokio::test]
async fn gratuitous_redelegation_after_finish_is_refused_and_run_succeeds() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_response("create hello.py"),
        write_file_response("hello.py", "print('hi')"),
        finish_task_response("completed", "wrote hello.py, all good"),
        // The PM gratuitously re-delegates to "re-verify" — this must be
        // refused by the delegate tool, so the engineer is NEVER re-invoked
        // (the next scripted response is the PM's own finish_task, not an
        // engineer turn).
        delegate_response("re-verify hello.py once more"),
        finish_task_response("completed", "confirmed complete"),
    ]));

    let report = execute_run_task(params(&agents, &project, None), llm.clone()).await;

    assert_eq!(
        report.exit,
        ExitCode::Success,
        "a completed run must report Success even with a gratuitous re-delegation, \
         never partial; task: {}",
        report.task
    );
    assert!(
        report.diff.contains("hello.py"),
        "the deliverable diff must be preserved, got: {}",
        report.diff
    );

    let engineer_turns = report
        .transcript
        .iter()
        .filter(|t| t.role == "python-engineer")
        .count();
    assert_eq!(
        engineer_turns, 2,
        "the engineer must be invoked exactly once (write_file + finish_task); a \
         second, refused delegation must never reach it, got {engineer_turns} engineer turns"
    );
    assert_eq!(
        llm.models_seen().len(),
        5,
        "no wasted engineer round: the refused re-delegation must not spend a chat call"
    );
}

/// #8157: a `finish_task` call the verify-before-finish gate REJECTS must
/// never latch `EngineerCompletionSignal` — a later PM `delegate_to_agent`
/// must not be refused, and the run must still end `Success`.
///
/// Why: #8157 reported the opposite — a gate-rejected finish somehow latching
/// completion and stranding the run as `NoChanges`. Live scripted repro
/// against the real wiring showed the defect does NOT reproduce: `dispatch_all`
/// (agent_loop/mod.rs:872-896) only sets `finish_args` on the gate's `Accept`/
/// `AcceptWithNote` arms, so `build_finish_output` (mod.rs:1318-1330) — the
/// sole setter of `finish_status` — never runs on a `Reject`, and
/// `DelegateToAgentTool::mark_completion_if_finished` (tools/delegate.rs:
/// 406-412) latches only on `Some(FinishStatus::Completed)`. This pins that
/// correct behaviour permanently so a future regression is caught here rather
/// than live.
/// What: A project with a `pytest.ini` (so the engineer's `default_finish_gate`
/// can detect a runnable suite). Script [PM delegates naming `pytest tests/
/// -v`, engineer calls `finish_task` prematurely (no test run — REJECTED),
/// engineer stops without finishing again, PM re-delegates (must NOT be
/// refused by the #2683 completion latch), engineer writes `parser.py`, runs
/// the named test, then finishes for real (gate now satisfied), PM finishes
/// (its own `pm_finish_gate` sees the engineer's recorded test run)]. Asserts
/// `exit == Success`, all eight scripted turns are consumed (proving the
/// second delegation actually reached the engineer rather than being refused
/// outright), and the engineer was invoked across both delegations (five
/// `python-engineer` transcript turns, not two).
///
/// Hermeticity (#8157, PR #8691 CI): the scripted `bash` call really executes.
/// A bare `pytest tests/ -v` ran the host's pytest wherever one was on `PATH`,
/// and its `.pytest_cache/` was the run's only diff — `Success` locally,
/// `NoChanges` on a runner without pytest. The command now points `PATH` at a
/// dead directory so no host pytest ever runs, the gate still matches it
/// (`is_test_command`), and the scripted `parser.py` write is the deliverable
/// on every host.
/// Test: this test.
#[tokio::test]
async fn gate_refused_finish_task_never_latches_completion() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");
    std::fs::write(project.path().join("pytest.ini"), "[pytest]\n").expect("write pytest.ini");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        // 1. PM delegates, naming the runnable suite.
        delegate_response("implement the parser; then run `pytest tests/ -v`"),
        // 2. Engineer finishes prematurely — no matching `bash` call has run
        //    yet, so the engineer's own `default_finish_gate` REJECTS this.
        finish_task_response("completed", "premature — no tests run"),
        // 3. Engineer stops WITHOUT finishing again — this delegation ends
        //    with no successful finish_task, so `finish_status` stays `None`.
        stop_response("engineer: giving up without finishing"),
        // 4. PM re-delegates. This MUST NOT be refused: the completion signal
        //    never latched, because step 2's finish was rejected, not accepted.
        delegate_response("re-verify: run `pytest tests/ -v` and finish"),
        // 5. Engineer writes the deliverable — the run's only diff.
        write_file_response("parser.py", "def parse(s):\n    return s\n"),
        // 6. Engineer runs the named test. A dead `PATH` keeps any host
        //    pytest from running (its `.pytest_cache/` would enter the diff);
        //    the gate matches on the command text alone.
        bash_response("PATH=/nonexistent pytest tests/ -v"),
        // 7. Engineer finishes — the gate is now satisfied, so this ACCEPTS.
        finish_task_response("completed", "ran pytest, all good"),
        // 8. PM finishes — its own `pm_finish_gate` sees the shared
        //    transcript's recorded test run and accepts on the first attempt.
        finish_task_response("completed", "confirmed complete"),
    ]));

    let mut task_params = params(&agents, &project, None);
    task_params.task = "implement the parser; run `pytest tests/ -v` before finishing".into();

    let report = execute_run_task(task_params, llm.clone()).await;

    assert_eq!(
        report.exit,
        ExitCode::Success,
        "a gate-rejected finish that never latched completion must still let \
         the run complete Success, not strand as NoChanges; task: {}",
        report.task
    );
    assert!(
        report.diff.contains("parser.py") && !report.diff.contains(".pytest_cache"),
        "the diff must be exactly the scripted deliverable, never a host \
         pytest's cache; got: {}",
        report.diff
    );
    assert_eq!(
        llm.models_seen().len(),
        8,
        "every scripted turn must be consumed — a wrongly-latched completion \
         signal would refuse the second delegate_to_agent and strand the run \
         well short of all eight turns"
    );

    let engineer_turns = report
        .transcript
        .iter()
        .filter(|t| t.role == "python-engineer")
        .count();
    assert_eq!(
        engineer_turns, 5,
        "the second delegation must actually reach the engineer (3 more turns \
         on top of the first delegation's 2), proving it was not refused by a \
         stray completion latch; got {engineer_turns} engineer turns"
    );
}

// ── #2265 fix #5 / #2852: PM stops re-delegating once the run-wide ceiling ─────
// ── latches (a single delegation's retry exhaustion must NOT stop it) ──────────

/// Answers every PM turn with a `delegate_to_agent` call; lets the engineer's
/// very first call write the deliverable, then fails every engineer call after
/// it with a retryable transport error.
///
/// Why: The #2852 ceiling test needs a PM that keeps delegating while every
/// engineer invocation ultimately fails — a scenario `FlakyThenRepeatLlm`'s
/// global call-index scripting cannot express, because the PM's and engineer's
/// calls interleave unpredictably once retries are in play. Keying off the
/// request's advertised tool schema (only the PM is offered
/// `delegate_to_agent`) makes the roles unambiguous and the test fully
/// deterministic regardless of how many retries occur.
/// What: Inspects `req.tools` to classify the caller. PM requests get a canned
/// delegate call. The engineer's first request replays `first` (a `write_file`
/// that puts a real deliverable on disk); every later engineer request returns
/// `InferenceError::Api`, which `redelegation_hint` classifies as retryable.
/// Test: `run_wide_ceiling_stops_the_pm_loop_and_ends_partial_promptly`.
struct FirstEngineerCallWritesThenAllFail {
    first: Arc<ScriptedLlm>,
    delegate: ChatResponse,
    pm_calls: AtomicUsize,
    engineer_calls: AtomicUsize,
}

#[async_trait]
impl InferenceAdapter for FirstEngineerCallWritesThenAllFail {
    crate::llm::mock_adapter_identity!("mock-first-write-then-fail");

    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
        let is_pm = req
            .tools
            .as_ref()
            .is_some_and(|tools| tools.iter().any(|t| t.function.name == "delegate_to_agent"));
        if is_pm {
            self.pm_calls.fetch_add(1, Ordering::SeqCst);
            return Ok(self.delegate.clone());
        }
        if self.engineer_calls.fetch_add(1, Ordering::SeqCst) == 0 {
            return self.first.chat(req).await;
        }
        Err(InferenceError::Api {
            status: 500,
            body: "synthetic retryable transport failure".to_string(),
        })
    }
}

/// Once the run-wide engineer-failure ceiling latches, the PM must stop
/// issuing `delegate_to_agent` calls (bounded well under its `max_turns` of 8)
/// and the run must still end `Partial` with the deliverable preserved.
///
/// Why: This is #2265 fix #5's regression, re-based onto #2852's split. Fix #5
/// stops the PM burning its remaining `max_turns` on doomed calls once the cap
/// latches (bake-off L1 evidence: "re-delegation limit reached after 10
/// attempts … turn cap of 8 exceeded", 3 productive attempts + 7 wasted PM
/// turns). #2852 narrowed WHICH condition may fire that unrecoverable hook to
/// the one a fresh delegation cannot clear — the run-wide
/// `MAX_FAILED_INVOCATIONS` ceiling — so this test now drives the ceiling
/// rather than a single delegation's retry exhaustion.
///
/// This test previously asserted `pm_turns == 1`: that a PM whose FIRST
/// delegation exhausted its retries never got a second turn. That assertion is
/// dropped as a deliberate POLICY change, and the record is worth stating
/// precisely: the old scenario (one delegation whose engineer failed its own
/// retries three times) was the cap's original, still-valid purpose — a
/// genuinely struggling engineer — NOT run-6's bug, which was several separate
/// SUCCESSFUL delegations starving a later one. So the old assertion was not
/// itself defective, and an earlier version of this comment overstated the case
/// by claiming it "encoded the bug". What actually changed is the policy: under
/// #2852 that scenario now latches `retry_budget_exhausted` (recoverable), so
/// the PM does get a second turn — which is the intended behaviour, because a
/// fresh delegation with a full budget may well succeed. The scenario is
/// therefore rebuilt around the ceiling, and the bound is now "well under
/// max_turns" rather than "exactly 1".
/// What: The engineer writes the deliverable on its first turn, then every
/// engineer call fails retryably forever while the PM keeps delegating. That
/// first success costs no ceiling budget (#2852 — only failures count);
/// each subsequent delegation burns `MAX_REDELEGATIONS` failures, so the
/// ceiling latches on delegation 5. Assert: `exit == Partial`, the diff still names `hello.py`,
/// the report names the ceiling, and the PM stopped strictly before its own
/// 8-turn cap — proof the stop signal, not the turn cap, ended the run.
/// Test: this test.
#[tokio::test]
async fn run_wide_ceiling_stops_the_pm_loop_and_ends_partial_promptly() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    // The engineer's FIRST invocation writes the deliverable, then fails; every
    // later invocation fails outright. Delegating the write via a one-shot
    // scripted response keeps a real diff on disk to assert Partial against.
    let first = Arc::new(ScriptedLlm::from_json(&[write_file_response(
        "hello.py", "print(1)",
    )]));
    let llm = Arc::new(FirstEngineerCallWritesThenAllFail {
        first,
        delegate: serde_json::from_value(delegate_response("do work"))
            .expect("valid delegate fixture"),
        pm_calls: AtomicUsize::new(0),
        engineer_calls: AtomicUsize::new(0),
    });

    let report = execute_run_task(params(&agents, &project, None), llm.clone()).await;

    assert_eq!(
        report.exit,
        ExitCode::Partial,
        "the ceiling latched but the engineer's write_file already produced a \
         deliverable, so this must be Partial, not RunFailure; got task: {}",
        report.task
    );
    assert!(
        report.diff.contains("hello.py"),
        "the deliverable diff must be preserved, got: {}",
        report.diff
    );
    assert!(
        report.task.contains("engineer failure ceiling reached"),
        "the report must name the run-wide ceiling (#2852) as the terminal \
         condition, got: {}",
        report.task
    );

    let pm_turns = report.transcript.iter().filter(|t| t.role == "pm").count();
    assert!(
        pm_turns < 8,
        "the stop signal — not the PM's own 8-turn cap — must have ended the \
         run, got {pm_turns} PM turns"
    );
    // Precise invocation bounding is asserted at the unit level in
    // `redelegation::tests::failure_ceiling_latches_cap_reached`;
    // here it is enough that the PM stopped delegating rather than spinning
    // out its whole turn budget on calls the ceiling would only refuse.
    assert!(
        llm.pm_calls.load(Ordering::SeqCst) < 8,
        "the PM must stop delegating once the ceiling latches, got {} PM calls",
        llm.pm_calls.load(Ordering::SeqCst)
    );
}

// ── #2279: PM-side verify-before-finish gate (symmetric with the engineer's) ────

/// (#2279) The PM's verify-before-finish gate is SATISFIED — its
/// `finish_task` call succeeds on the FIRST attempt — when the delegated
/// engineer's OWN transcript shows a matching `bash` test invocation, even
/// though the PM never calls `bash` itself.
///
/// Why: This is #2279's PM-symmetric acceptance criterion proven end to end
/// (not just at the `verify_gate::pm_finish_gate` unit level): the real
/// wiring in `execute_run_task` — the shared `SharedTranscript` both the PM's
/// and the engineer's `RecordingLlmClient` record into — must actually carry
/// the engineer's `ran_test_command` signal through to the PM's gate.
/// What: The task names `pytest tests/ -v`. Script [PM delegates, engineer
/// runs `pytest tests/ -v` via `bash`, engineer stops (D3), PM finish_task];
/// assert the scripted client saw EXACTLY four calls — proving the PM's
/// single `finish_task` attempt was accepted, not rejected into a fifth
/// retry turn — and the run did not surface as a failure.
/// Test: this test.
#[tokio::test]
async fn pm_finish_gate_satisfied_when_engineer_ran_named_tests() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_response("implement the parser; then run `pytest tests/ -v`"),
        bash_response("pytest tests/ -v"),
        stop_response("engineer: ran the suite"),
        finish_task_response("completed", "verified via the named test suite"),
    ]));

    let mut task_params = params(&agents, &project, None);
    task_params.task = "implement the parser; run `pytest tests/ -v` before finishing".into();

    let report = execute_run_task(task_params, llm.clone()).await;

    assert_eq!(
        llm.models_seen().len(),
        4,
        "the PM's single finish_task attempt must be accepted, not rejected \
         into a fifth retry turn; task: {}",
        report.task
    );
    assert_ne!(
        report.exit,
        ExitCode::RunFailure,
        "an accepted finish must not surface as a run failure; task: {}",
        report.task
    );
}

/// (#2279) The PM's verify-before-finish gate TRIPS — its `finish_task` call
/// is rejected as a RECOVERABLE retry, not a run failure — when the task
/// names a runnable test command but the delegated engineer's transcript
/// shows no matching invocation, and the PM's run still recovers/completes
/// via its OWN next turn.
///
/// Why: The negative half of the PM-symmetric acceptance criterion, proving
/// (a) the gate actually rejects a premature finish sourced from the
/// engineer's silence, and (b) that rejection is recoverable — the PM gets
/// exactly one more turn, not a hung loop or a hard failure.
/// What: The task names `pytest tests/ -v`. Script [PM delegates, engineer
/// writes a file WITHOUT running `bash` at all, engineer stops (D3), PM's
/// FIRST finish_task attempt (must be rejected), PM's SECOND turn (a plain
/// D3 stop — unaffected by the gate, proving recovery)]; assert the scripted
/// client saw exactly FIVE calls — one more than the satisfied-gate test's
/// four, precisely the one recoverable retry turn the gate forced — and the
/// run did not surface as a failure.
/// Test: this test.
#[tokio::test]
async fn pm_finish_gate_trips_when_engineer_never_ran_named_tests() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_response("implement the parser; then run `pytest tests/ -v`"),
        write_file_response("parser.py", "def parse():\n    pass\n"),
        stop_response("engineer: wrote the parser (did not run tests)"),
        finish_task_response("completed", "premature — tests never ran"),
        stop_response("pm: recovered after the rejected finish_task"),
    ]));

    let mut task_params = params(&agents, &project, None);
    task_params.task = "implement the parser; run `pytest tests/ -v` before finishing".into();

    let report = execute_run_task(task_params, llm.clone()).await;

    assert_eq!(
        llm.models_seen().len(),
        5,
        "the PM's premature finish_task must be rejected into exactly one \
         recoverable retry turn, not accepted outright and not looped \
         indefinitely; task: {}",
        report.task
    );
    assert_ne!(
        report.exit,
        ExitCode::RunFailure,
        "a gate rejection must be a recoverable retry, not a run failure; \
         task: {}",
        report.task
    );
}

/// #2348: `run-task`'s one-shot/bake-off path (`execute_run_task`) must
/// NEVER register `recall_session` — it has no session_id to scope a memory
/// query to, and Parity mode requires byte-identical prompts to the
/// pre-#2343 baseline (epic #2343 scope note: "run_task one-shot/bake-off
/// path explicitly untouched"). Registration lives only in
/// `task::executor::run_and_record`'s daemon-session `pm_registry`.
///
/// Why: asserts the ACTUAL wire-level tool schemas the PM's `AgentLoop`
/// sends (via `ScriptedLlm::first_tool_names`), not a re-derivation of the
/// registration logic, so this is a real regression guard against
/// `recall_session` ever being wired into this module by mistake.
/// What: Script [PM stop] only — no delegation needed to observe the PM's
/// own advertised tool set on its first (only) turn.
/// Test: this test.
#[tokio::test]
async fn run_task_registry_never_registers_recall_session() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response(
        "pm: nothing to do",
    )]));
    let _report = execute_run_task(params(&agents, &project, None), llm.clone()).await;

    let names = llm.first_tool_names();
    assert!(
        names.contains(&"finish_task".to_string()),
        "sanity: finish_task must still be registered; got {names:?}"
    );
    assert!(
        !names.contains(&"recall_session".to_string()),
        "run_task's one-shot registry must never register recall_session; got {names:?}"
    );
}

/// Build `params` with `no_delegate` set, for the #8031 pair below.
fn params_no_delegate(agents: &TempDir, project: &TempDir) -> RunTaskParams {
    RunTaskParams {
        no_delegate: true,
        ..params(agents, project, None)
    }
}

/// #8031: a `no_delegate` run must not advertise `delegate_to_agent` at all.
///
/// Why: the closure condition — `tcode run-task engineer --no-delegate
/// "<task>"` completes with no `delegate_to_agent` call in the transcript.
/// A tool the model is never shown is a tool it cannot call, so asserting on
/// the wire-level schema set is the strongest form of that guarantee.
/// What: Script [PM stop] only, run with `no_delegate: true`, and assert the
/// PM's first (only) turn advertises `finish_task` but not
/// `delegate_to_agent`. Fails on `origin/main`, where the tool is registered
/// unconditionally.
/// Test: this test.
#[tokio::test]
async fn no_delegate_run_omits_delegate_tool() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response(
        "pm: nothing to do",
    )]));
    let _report = execute_run_task(params_no_delegate(&agents, &project), llm.clone()).await;

    let names = llm.first_tool_names();
    assert!(
        names.contains(&"finish_task".to_string()),
        "sanity: finish_task must still be registered; got {names:?}"
    );
    assert!(
        !names.contains(&"delegate_to_agent".to_string()),
        "a no_delegate run must not advertise delegate_to_agent; got {names:?}"
    );
}

/// #8031: on the legacy in-process path a `no_delegate` run must register the
/// NAMED agent's own tcode tools and be able to write a file with them.
///
/// Why: round 1 dropped `delegate_to_agent` here too, leaving this path's
/// `pm_registry` as `finish_task` (+ `use_skill`) — no file tools at all, so
/// `--legacy-in-process --no-delegate` could not do the work either. The
/// closure condition must hold on BOTH execution paths.
/// What: an on-disk `engineer.md` whose `tcode_tools` allows `write_file` but
/// NOT `bash`/`edit`; scripts one `write_file` call then a stop. Asserts the
/// file landed in the project, the advertised set carries `write_file` but not
/// `delegate_to_agent`, and the denied tools never reached the wire — the same
/// `tools.allowed` gate a delegated run of that agent goes through.
/// FAILS at 7cdc3b562: `write_file` is unregistered, so nothing is written.
/// Test: this test.
#[tokio::test]
async fn no_delegate_run_registers_the_agents_own_tools() {
    let agents = agents_dir("openai/gpt-4o-mini");
    std::fs::write(
        agents.path().join("engineer.md"),
        "---\nname: engineer\nmodel: openai/gpt-4o-mini\ntcode_tools: [read_file, write_file, finish_task]\n---\n\nYou are the engineer.\n",
    )
    .expect("write engineer.md");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        write_file_response("hello.txt", "hello"),
        stop_response("engineer: wrote hello.txt"),
    ]));
    let p = RunTaskParams {
        no_delegate: true,
        agent: "engineer".into(),
        task: "create hello.txt containing hello".into(),
        ..params(&agents, &project, None)
    };
    let _report = execute_run_task(p, llm.clone()).await;

    let written = std::fs::read_to_string(project.path().join("hello.txt"))
        .expect("#8031: the legacy-path single-agent run must write the file itself");
    assert_eq!(
        written, "hello",
        "the file must carry the requested content"
    );

    let names = llm.first_tool_names();
    assert!(
        names.contains(&"write_file".to_string()),
        "the named agent's own write_file must be advertised; got {names:?}"
    );
    assert!(
        !names.contains(&"delegate_to_agent".to_string()),
        "a no_delegate run must not advertise delegate_to_agent; got {names:?}"
    );
    for denied in ["bash", "edit", "glob", "grep"] {
        assert!(
            !names.contains(&denied.to_string()),
            "{denied} is outside the agent's tcode_tools allowlist and must not be \
             advertised on a no_delegate run; got {names:?}"
        );
    }
}

/// #8031 companion: the DEFAULT run still advertises `delegate_to_agent`.
///
/// Why: without this, `no_delegate_run_omits_delegate_tool` would also pass
/// if the tool were dropped from every run — the fix would be indistinguishable
/// from a regression.
/// What: same script and fixture, `no_delegate` left at its `false` default.
/// Test: this test.
#[tokio::test]
async fn default_run_registers_delegate_tool() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response(
        "pm: nothing to do",
    )]));
    let _report = execute_run_task(params(&agents, &project, None), llm.clone()).await;

    let names = llm.first_tool_names();
    assert!(
        names.contains(&"delegate_to_agent".to_string()),
        "the default run must keep advertising delegate_to_agent; got {names:?}"
    );
}

/// `ensure_project_indexed_in_background` spawns its indexing thread even when
/// the project path is NOT inside a git repository.
///
/// Why: regression guard for the removed `find_git_root` short-circuit (owner
/// directive: git is a nice-to-have for tcode, not a requirement — trusty-search
/// should index scratch directories same as any other project). Before this
/// fix, a project with no `.git` anywhere up its tree caused the function to
/// return before ever spawning the thread.
/// What: calls the function with a plain tempdir that has no `.git`, and
/// asserts it returns promptly (proving it did not skip out early nor block on
/// the network) without panicking. The spawned thread is detached and
/// fail-open, so no running trusty-search daemon is required for this test.
/// Test: this test.
#[test]
fn spawns_indexing_thread_for_non_git_project_path() {
    // Hermeticity (#3361, #2914): this test calls
    // `ensure_project_indexed_in_background` DIRECTLY rather than through the
    // `execute_run_task` wrapper, so it must install the same ambient-daemon
    // isolation itself — otherwise, on a machine with a live trusty-search
    // daemon, this genuinely registers `tmp`'s throwaway tempdir against it
    // (with `allow_sensitive_path: true`, since this is tcode's legitimate
    // opt-in caller), which is exactly the ephemeral-index leak issue #2914
    // reports.
    isolate_ambient_daemons();
    let tmp = tempfile::tempdir().expect("tempdir");
    // No `.git` anywhere under `tmp` — exactly the scratch/bake-off case the
    // old guard used to skip.
    let start = std::time::Instant::now();
    super::ensure_project_indexed_in_background(tmp.path().to_path_buf(), None);
    assert!(
        start.elapsed() < std::time::Duration::from_millis(500),
        "must return immediately (spawn-and-detach), never block on the network"
    );
}

/// The readiness observer must be invoked exactly once, on the detached
/// thread, even when nothing is probeable.
///
/// Why: the daemon path publishes `Event::IndexReadiness` from this observer.
/// If it were skipped whenever the probe returned `None`, a session with no
/// reachable trusty-search daemon would emit NO readiness event at all — and
/// the UI would silently fall back to rendering "no results found" for an
/// index it cannot even see, which is the precise confusion #2784 exists to
/// remove. `None` is a reportable state, not a reason to stay silent.
/// What: calls the function against a `.git`-less tempdir with an observer
/// that latches into a channel; asserts the observer ran. It deliberately does
/// NOT assert WHICH state was observed — that depends on whether a
/// trusty-search daemon happens to be up on the machine running the tests, and
/// the contract under test is "the observer is always invoked, whatever the
/// probe found", not the probe's result (which
/// `trusty_common::search_readiness`'s own tests already pin).
/// Test: this test.
#[test]
fn background_indexing_invokes_readiness_observer() {
    // Hermeticity (#3361, #2914): see the identical guard in
    // `spawns_indexing_thread_for_non_git_project_path` — this test also
    // calls `ensure_project_indexed_in_background` directly, bypassing
    // `execute_run_task`'s isolation.
    isolate_ambient_daemons();
    let tmp = tempfile::tempdir().expect("tempdir");
    let (tx, rx) = std::sync::mpsc::channel();

    super::ensure_project_indexed_in_background(
        tmp.path().to_path_buf(),
        Some(Box::new(move |readiness| {
            let _ = tx.send(readiness.is_some());
        })),
    );

    // The detached thread does one short-timeout probe; 10s is far beyond its
    // ~1.5s cap while still failing fast on a genuine "never called" bug.
    rx.recv_timeout(std::time::Duration::from_secs(10))
        .expect("the readiness observer must be invoked, even when nothing is probeable");
}

/// A response where the assistant calls `use_skill(name)` (#2924).
fn use_skill_response(name: &str) -> Value {
    json!({
        "id": "gen-use-skill",
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call-use-skill",
                    "type": "function",
                    "function": {
                        "name": "use_skill",
                        "arguments": json!({"name": name}).to_string()
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": {"prompt_tokens": 25, "completion_tokens": 6, "total_tokens": 31}
    })
}

/// The `--legacy-in-process`/bake-off `run_task` path (`execute_run_task`)
/// wires the skill catalog and `use_skill` tool into the PM's registry the
/// same way the daemon path (`task::executor::run_and_record`) already does
/// (#2924) — before this fix, `daily_driver_skills_catalog` and
/// `UseSkillTool` registration existed ONLY on the daemon path, so a PM
/// running through this CLI path could never discover or invoke a project
/// skill at all.
///
/// Why: mirrors `runner::tests::skills_catalog_reaches_daily_driver_prompt`,
/// but proves the wiring at the `execute_run_task` orchestration layer
/// (config → prompt → registry → transcript), not just at the
/// `InProcessAgentRunner` builder layer that test already covers.
/// What: seeds a project with `.claude/skills/demo/SKILL.md`; scripts the PM
/// to call `use_skill(name: "demo")` on its first turn, then stop; asserts
/// the resolved skill body reached the tool result (via the recorded
/// transcript's tool call) and that some `TurnRecord.tool_calls` contains
/// `"use_skill"`.
/// Test: this test.
#[tokio::test]
async fn use_skill_on_legacy_path_reaches_pm_and_transcript() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");
    let skills_dir = project.path().join(".claude").join("skills").join("demo");
    std::fs::create_dir_all(&skills_dir).expect("mkdir skill dir");
    std::fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: demo\ndescription: Demo skill\n---\nfull demo body\n",
    )
    .expect("write SKILL.md");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        use_skill_response("demo"),
        stop_response("pm: loaded the demo skill"),
    ]));

    let report = execute_run_task(params(&agents, &project, None), llm.clone()).await;

    // The PM's own prompt must have advertised the catalog and the tool.
    let names = llm.first_tool_names();
    assert!(
        names.contains(&"use_skill".to_string()),
        "PM registry must advertise use_skill when a skill catalog resolves; got {names:?}"
    );

    // The recorded transcript must show the PM actually calling use_skill.
    let saw_use_skill = report
        .transcript
        .iter()
        .any(|turn| turn.tool_calls.iter().any(|name| name == "use_skill"));
    assert!(
        saw_use_skill,
        "some TurnRecord.tool_calls must contain \"use_skill\"; transcript was: {:?}",
        report.transcript
    );
}

/// Experimental (refs #2892): the delegated ENGINEER's own per-delegation
/// registry (`ProjectToolFactory::build`) now also registers `use_skill`,
/// backed by the SAME resolver the PM's catalog/tool were built from —
/// mirrors `use_skill_on_legacy_path_reaches_pm_and_transcript` above, but
/// scripts the ENGINEER (not the PM) to be the one that calls `use_skill`.
///
/// Why: before this change, only the PM could fetch a skill's full body on
/// this legacy/bake-off CLI path; the delegated engineer received the
/// catalog text in its prompt (`build_engineer_runner`'s
/// `.with_skills_catalog`) but had no tool to act on it.
/// What: seeds a project with `.claude/skills/demo/SKILL.md`; scripts
/// [PM delegate, engineer use_skill, engineer stop, PM stop]. Asserts (1) the
/// tool schema advertised on the engineer's first request (call idx 1, right
/// after the PM's own delegate call at idx 0) includes `"use_skill"`, and (2)
/// some `TurnRecord` tagged `"python-engineer"` has a `tool_calls` entry for
/// `"use_skill"`.
/// Test: this test.
#[tokio::test]
async fn use_skill_on_legacy_path_reaches_engineer_and_transcript() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");
    let skills_dir = project.path().join(".claude").join("skills").join("demo");
    std::fs::create_dir_all(&skills_dir).expect("mkdir skill dir");
    std::fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: demo\ndescription: Demo skill\n---\nfull demo body\n",
    )
    .expect("write SKILL.md");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        delegate_response("use the demo skill"),
        use_skill_response("demo"),
        stop_response("engineer: loaded the demo skill"),
        stop_response("pm: task complete"),
    ]));

    let report = execute_run_task(params(&agents, &project, None), llm.clone()).await;

    // The engineer's own registry (advertised on its first request, idx 1 —
    // idx 0 is the PM's delegate_to_agent turn) must include use_skill.
    let names = llm.tool_names_at(1);
    assert!(
        names.contains(&"use_skill".to_string()),
        "engineer registry must advertise use_skill when a skill catalog resolves; got {names:?}"
    );

    // The recorded transcript must show the ENGINEER (not just the PM)
    // actually calling use_skill.
    let saw_engineer_use_skill = report.transcript.iter().any(|turn| {
        turn.role == "python-engineer" && turn.tool_calls.iter().any(|name| name == "use_skill")
    });
    assert!(
        saw_engineer_use_skill,
        "some \"python-engineer\" TurnRecord.tool_calls must contain \"use_skill\"; \
         transcript was: {:?}",
        report.transcript
    );
}

/// Negative counterpart to `use_skill_on_legacy_path_reaches_engineer_and_transcript`
/// (code-critic finding on PR #2943): asserts the ELSE branch of
/// `ProjectToolFactory::build` — when `skill_resolver` is `None`, the
/// engineer's advertised registry must NOT include `use_skill`.
///
/// Why: the positive test above proves `Some(resolver)` registers `use_skill`;
/// nothing asserted the inverse. Driving this end-to-end via `execute_run_task`
/// is impractical/flaky here because the #2895 embedded-skill fallback (see
/// `skills::mod`'s `FsSkillResolver`/`format_skill_catalog` docs) makes
/// `daily_driver_skills_catalog` resolve a non-empty catalog for almost any
/// real project directory, so `skill_resolver` is virtually never `None` on
/// the full end-to-end path. Constructing `ProjectToolFactory` directly and
/// calling `RegistryFactory::build` is the clean, direct way to exercise the
/// `None` branch in isolation without fighting that fallback.
/// What: builds a `ProjectToolFactory` with `skill_resolver: None` against an
/// empty project tempdir, calls `.build()` with default `AgentConfig`/
/// `RunContext`, and asserts the resulting `ToolRegistry` does not contain
/// `"use_skill"`, while sanity-checking a known-always-present tool
/// (`"finish_task"`) IS present — guarding against a broken/empty registry
/// vacuously satisfying the absence assertion.
/// Test: this test.
#[tokio::test]
async fn use_skill_absent_from_engineer_when_no_skills() {
    let project = tempfile::tempdir().expect("project tempdir");
    let factory = super::ProjectToolFactory {
        project: project.path().to_path_buf(),
        skill_resolver: None,
        mcp: tokio::sync::OnceCell::new(),
    };

    let registry = factory
        .build(&AgentConfig::default(), &RunContext::default())
        .await;

    assert!(
        !registry.contains("use_skill"),
        "engineer registry must NOT advertise use_skill when skill_resolver is None"
    );
    assert!(
        registry.contains("finish_task"),
        "sanity check: registry should still contain other always-present tools"
    );
}

/// #7727 review HIGH 1: an embedded roster agent resolved with no disk config
/// carries skill pointers the engineer registry's `read_file` opens, although
/// they lie outside the project root.
#[tokio::test]
async fn engineer_registry_reads_embedded_agent_skill_pointers() {
    use crate::agents::skill_refs::user_skill_refs_dir;

    let project = tempfile::tempdir().expect("project tempdir");
    let agent = crate::agents::resolve_agent(project.path(), "rust-engineer")
        .expect("embedded rust-engineer resolves");
    let factory = super::ProjectToolFactory {
        project: project.path().to_path_buf(),
        skill_resolver: None,
        mcp: tokio::sync::OnceCell::new(),
    };
    let registry = factory.build(&agent, &RunContext::default()).await;
    for (relative, content) in crate::agents::skill_refs::tests::test_refs().iter() {
        let pointer = user_skill_refs_dir().join(relative).display().to_string();
        assert!(agent.system_prompt.content.contains(&pointer), "{pointer}");
        let out = registry
            .dispatch("read_file", serde_json::json!({ "path": pointer }))
            .await;
        assert!(!out.is_error(), "{pointer}: {}", out.content());
        assert_eq!(out.content(), content);
    }
}

// ── #8030 / #8128: top-level model + turn-cap overrides ─────────────────────

/// A response calling a tool the PM registry does not carry, so the loop
/// answers it with a recoverable error and takes another turn.
///
/// Why: the turn-cap test below needs a PM that never terminates and never
/// spends a script entry on a delegated engineer turn — an unregistered tool
/// name is the cheapest such turn.
/// What: one `tool_calls` response naming a tool registered nowhere.
/// Test: `max_turns_override_raises_the_pm_turn_cap`.
fn unregistered_tool_response() -> Value {
    json!({
        "id": "gen-unknown",
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call-unknown",
                    "type": "function",
                    "function": {
                        "name": "definitely_not_a_registered_tool",
                        "arguments": "{}"
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": {"prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10}
    })
}

/// `RunTaskParams.pm_model` pins the PM loop's model ahead of the agent's own
/// front-matter `model:`, normalising a short alias on the way (#8030).
///
/// Why: `--engineer-model` only ever rewired the delegated runner, so the
/// top-level agent's own calls kept reaching whatever its deployed `.md`
/// named — the concrete failure #8030 records. This asserts at the wire: the
/// slug the client was ASKED to use on the PM's first turn.
/// What: `pm.md` pins `openai/gpt-4o-mini`; the run passes
/// `pm_model: Some("opus")`; assert the first request's model is the concrete
/// Claude 5 Opus slug, neither the alias nor the config value.
/// Test: this test.
#[tokio::test]
async fn pm_model_override_pins_the_pm_loops_model() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");
    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("pm: done")]));

    let p = RunTaskParams {
        pm_model: Some("opus".to_string()),
        ..params(&agents, &project, None)
    };
    let _report = execute_run_task(p, llm.clone()).await;

    let models = llm.models_seen();
    assert_eq!(
        models.first().map(String::as_str),
        Some("anthropic/claude-opus-5"),
        "the PM's first turn must use the pinned override, normalised; got {models:?}"
    );
}

/// With no `pm_model`, the PM loop still uses the agent config's own model
/// (#8030 — the override is additive).
///
/// Why: this is the control that makes the test above meaningful, and the
/// guard that every pre-#8030 run keeps its behaviour byte-for-byte.
/// What: same fixture, `pm_model: None`; assert the first request carries
/// `pm.md`'s declared `openai/gpt-4o-mini`.
/// Test: this test.
#[tokio::test]
async fn absent_pm_model_override_uses_the_agent_config_model() {
    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");
    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("pm: done")]));

    let _report = execute_run_task(params(&agents, &project, None), llm.clone()).await;

    let models = llm.models_seen();
    assert_eq!(
        models.first().map(String::as_str),
        Some("openai/gpt-4o-mini"),
        "an absent override must leave the agent config's model in place; got {models:?}"
    );
}

/// `RunTaskParams.max_turns` replaces the PM loop's built-in turn cap, and its
/// absence leaves that cap at 8 (#8128).
///
/// Why: the cap was `AgentLoopConfig::default()`'s 8 with no override at all,
/// so a multi-step delivery task could not be given more turns. Counting the
/// requests the loop actually issued is the only observation that proves the
/// value reached `AgentLoopConfig`, and it fails loudly if the field is ever
/// dropped from the config literal.
/// What: scripts more never-terminating turns than either cap consumes, runs
/// once with `max_turns: Some(3)` and once with `None`, and asserts the
/// request counts are exactly 3 and exactly 8.
/// Test: this test.
#[tokio::test]
async fn max_turns_override_raises_the_pm_turn_cap() {
    let script: Vec<Value> = (0..12).map(|_| unregistered_tool_response()).collect();

    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");
    let capped = Arc::new(ScriptedLlm::from_json(&script));
    let p = RunTaskParams {
        max_turns: Some(3),
        ..params(&agents, &project, None)
    };
    let _ = execute_run_task(p, capped.clone()).await;
    assert_eq!(
        capped.models_seen().len(),
        3,
        "the PM loop must stop after the overridden cap"
    );

    let agents = agents_dir("openai/gpt-4o-mini");
    let project = tempfile::tempdir().expect("project tempdir");
    let defaulted = Arc::new(ScriptedLlm::from_json(&script));
    let _ = execute_run_task(params(&agents, &project, None), defaulted.clone()).await;
    assert_eq!(
        defaulted.models_seen().len(),
        8,
        "an absent override must leave AgentLoopConfig::default()'s cap of 8"
    );
}