trusty-mpm 1.3.5

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
//! Unit tests for the Claude Code runtime adapter's command builders
//! ([`spawn_command`], [`resume_command`]) and `RuntimeAdapter` impl.
//!
//! Why: split out of `claude_code.rs` (issue #3070) to bring that file back
//! toward its pre-#3040 SLOC budget, mirroring the sibling-`_tests.rs`
//! pattern already established by `claude_code_gh_env_tests.rs` for the same
//! file. Purely mechanical — no behavior or assertion changes.
//! What: exercises every command-builder flag combination (workdir, resume
//! selection, session id export, prompt file, OAuth token, `gh_env` file) and
//! the `ClaudeCodeAdapter::spawn`/`spawn_resume`/`identify` trait methods
//! against a `FakeTmux`.
//! Test: this file IS the test suite; see individual `#[test]` doc comments.

use super::super::test_helpers::FakeTmux;
use super::*;

/// Fixed managed-session UUID string reused across command-builder tests
/// (#2023 component B) — a representative id, not a real session.
const TEST_SESSION_ID: &str = "11111111-2222-3333-4444-555555555555";

/// Fixed workdir reused across command-builder tests (#2250) — a
/// representative cwd, not a real workspace (these tests exercise the
/// string builders directly, never touching the filesystem).
const TEST_CWD: &str = "/tmp/ws";

/// RAII guard that redirects `$HOME` to a temp dir and restores it on drop
/// (including panic).
///
/// Why: the adapter's `spawn`/`spawn_resume` now provision the real managed
/// `CLAUDE_CONFIG_DIR` (resolved under `$HOME`). Tests that drive them must
/// redirect `$HOME` so the provisioning/trust-seed side effects land in a
/// throwaway dir instead of the developer's real `~/.trusty-tools`. Pair with
/// `#[serial_test::serial]` since it mutates process-global env.
struct HomeGuard {
    prev: Option<String>,
    _tmp: tempfile::TempDir,
}
impl HomeGuard {
    fn set() -> Self {
        let tmp = tempfile::tempdir().expect("tempdir");
        let prev = std::env::var("HOME").ok();
        // SAFETY: callers are #[serial], so no other test thread reads HOME
        // concurrently; Drop restores the prior value even on panic.
        unsafe { std::env::set_var("HOME", tmp.path()) };
        Self { prev, _tmp: tmp }
    }
}
impl Drop for HomeGuard {
    fn drop(&mut self) {
        match self.prev {
            Some(ref p) => unsafe { std::env::set_var("HOME", p) },
            None => unsafe { std::env::remove_var("HOME") },
        }
    }
}

#[test]
fn claude_code_adapter_identifies() {
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake);
    assert_eq!(adapter.identify(), "claude-code");
}

#[test]
fn spawn_command_contains_env_scrub() {
    // The spawn command must always strip the API key from the environment
    // so the session falls back to OAuth (keyed by CLAUDE_CONFIG_DIR).
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.contains("env -u ANTHROPIC_API_KEY"),
        "spawn command must contain env scrub: {cmd}"
    );
    assert!(
        cmd.contains(" claude "),
        "spawn command must invoke claude: {cmd}"
    );
}

#[test]
fn spawn_command_exports_managed_session_id() {
    // #2023 component B: the spawn command sent to the pane must export
    // TM_MANAGED_SESSION_ID (single-quoted, terminated by `;`) BEFORE the
    // claude invocation, so a command run in the pane after claude exits
    // can identify which managed session it belongs to. tmux
    // set-environment alone would NOT reach the pane's already-running
    // shell — the export must be part of the literal command line.
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    let expected_prefix = format!("export TM_MANAGED_SESSION_ID='{TEST_SESSION_ID}'; ");
    // #2250: the command now starts with `cd <workdir> && { ...` — the
    // export is the first statement INSIDE that brace group, not literally
    // the first bytes of the string.
    assert!(
        cmd.contains(&format!("{{ {expected_prefix}")),
        "spawn command must export the session id as the first statement \
             inside the cd-group: {cmd}"
    );
    let export_pos = cmd
        .find("export TM_MANAGED_SESSION_ID")
        .expect("export present");
    let claude_pos = cmd.find(" claude ").expect("claude invocation present");
    assert!(
        export_pos < claude_pos,
        "export must precede the claude invocation: {cmd}"
    );
}

#[test]
fn spawn_command_sets_claude_config_dir() {
    // DOC-34 / #1996: when a managed config dir is available the spawn
    // command MUST export it so the framework roster comes from tm's config
    // home, not the project's committed `.claude/`. It must co-exist with the
    // API-key scrub.
    let dir = Path::new("/home/bob/.trusty-tools/trusty-mpm/claude-config");
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        Some(dir),
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    // #4467 inserted the inherited-marker `-u` flags between the API-key scrub
    // and the assignment; both must still precede the first NAME=VALUE per POSIX
    // env grammar, which `env_bin_prefix_orders_scrub_flags_before_assignments`
    // asserts positionally.
    assert!(
        cmd.contains("env -u ANTHROPIC_API_KEY -u "),
        "the API-key scrub must still lead the env prefix: {cmd}"
    );
    assert!(
        cmd.contains("CLAUDE_CONFIG_DIR='/home/bob/.trusty-tools/trusty-mpm/claude-config' claude"),
        "spawn command must scrub the key (via -u, BEFORE the NAME=VALUE assignment per \
             POSIX env grammar) then set (single-quoted) CLAUDE_CONFIG_DIR: {cmd}"
    );
    // #4451: with a config dir the spawn relocates the `user` tier onto tm's
    // own config home, so the flag MUST name that tier — it is where
    // `CLAUDE_CONFIG_DIR/agents` (the bundled roster) lives. Carrying
    // `project,local` here is exactly the regression that left managed
    // sessions with zero specialists.
    assert!(
        cmd.contains("--setting-sources user,project,local"),
        "a relocated spawn must load the `user` tier: {cmd}"
    );
}

#[test]
fn spawn_command_loads_the_user_tier_only_when_config_dir_is_relocated() {
    // #4451 both directions in one test, because the two failures are
    // opposite and each is silent:
    //   - relocated spawn WITHOUT `user` → no bundled agents resolve
    //   - non-relocated spawn WITH `user` → the operator's global
    //     ~/.claude/settings.json hooks bleed back in (#1269)
    let relocated = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        Some(Path::new(
            "/home/bob/.trusty-tools/trusty-mpm/claude-config",
        )),
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        relocated.contains("--setting-sources user,project,local"),
        "relocated spawn must load the tm-owned `user` tier: {relocated}"
    );

    let ambient = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        ambient.contains("--setting-sources project,local"),
        "non-relocated spawn must keep the #1269 exclusion: {ambient}"
    );
    assert!(
        !ambient.contains("user,project,local"),
        "without CLAUDE_CONFIG_DIR the `user` tier is the operator's real \
         ~/.claude and must stay excluded (#1269): {ambient}"
    );
}

#[test]
fn resume_command_loads_the_user_tier_when_config_dir_is_relocated() {
    // #4451: a resumed session is as agent-dependent as a fresh one — the
    // resume path must not be the one that silently keeps the old flag.
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        Some(Path::new(
            "/home/bob/.trusty-tools/trusty-mpm/claude-config",
        )),
        Some("abc-123"),
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.contains("--setting-sources user,project,local"),
        "relocated resume must load the tm-owned `user` tier: {cmd}"
    );
}

#[test]
fn env_bin_prefix_orders_unset_flag_before_config_dir_assignment() {
    // Regression guard (fatal bug): POSIX `env`'s grammar is
    // `env [OPTION]... [NAME=VALUE]... [COMMAND]...` — option flags like
    // `-u NAME` MUST precede any `NAME=VALUE` assignment. Putting
    // `CLAUDE_CONFIG_DIR=<dir>` before `-u` makes `env` stop parsing options
    // at the first NAME=VALUE and try to exec `-u` as a command
    // (`env: -u: No such file or directory`), fatally killing every managed
    // session spawn.
    let dir = Path::new("/home/bob/.trusty-tools/trusty-mpm/claude-config");
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        Some(dir),
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    let u_pos = cmd
        .find("-u ANTHROPIC_API_KEY")
        .expect("cmd must contain -u ANTHROPIC_API_KEY");
    let config_pos = cmd
        .find("CLAUDE_CONFIG_DIR=")
        .expect("cmd must contain CLAUDE_CONFIG_DIR=");
    assert!(
        u_pos < config_pos,
        "-u ANTHROPIC_API_KEY must appear BEFORE CLAUDE_CONFIG_DIR= per POSIX env \
             option-then-assignment grammar: {cmd}"
    );
}

#[test]
fn spawn_command_without_config_dir_omits_it() {
    // When home is unresolvable there is no config dir to point at; the
    // command must fall back to the legacy scrub-only prefix (no bare
    // `CLAUDE_CONFIG_DIR=` token).
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        !cmd.contains("CLAUDE_CONFIG_DIR"),
        "no config dir → must not reference CLAUDE_CONFIG_DIR: {cmd}"
    );
}

// ── issue #2246: CLAUDE_CODE_OAUTH_TOKEN injection ──────────────────────

#[test]
fn spawn_command_sets_oauth_token_when_available() {
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        Some("sk-ant-oat01-fake-token"),
        None,
    );
    assert!(
        cmd.contains("CLAUDE_CODE_OAUTH_TOKEN='sk-ant-oat01-fake-token'"),
        "spawn command must inject a single-quoted CLAUDE_CODE_OAUTH_TOKEN when \
             one is available: {cmd}"
    );
    assert!(
        cmd.contains("-u ANTHROPIC_API_KEY"),
        "the API-key scrub must still be present alongside the token: {cmd}"
    );
}

#[test]
fn spawn_command_omits_oauth_token_when_absent() {
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        !cmd.contains("CLAUDE_CODE_OAUTH_TOKEN"),
        "no token available → must not reference CLAUDE_CODE_OAUTH_TOKEN: {cmd}"
    );
}

#[test]
fn spawn_command_without_token_pins_the_exact_command() {
    // Full-string pin for the minimal argument set (no config dir, no prompt
    // file, no token). Supersedes the former
    // `spawn_command_without_token_is_byte_identical_to_pre_2246` guard: #4467
    // intentionally changed this string by adding the inherited-marker scrub, so
    // byte-identity with the pre-#2246 command is no longer the invariant. The
    // scrub segment is interpolated from production code rather than restated —
    // its CONTENT is pinned by `core::claude_env_scrub` tests, while this test
    // pins its POSITION in the assembled command.
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    let scrub = crate::core::claude_env_scrub::env_unset_flags();
    let expected = format!(
        "cd '/tmp/ws' && {{ export TM_MANAGED_SESSION_ID='{TEST_SESSION_ID}'; \
             env -u ANTHROPIC_API_KEY{scrub} claude \
             --setting-sources project,local --dangerously-skip-permissions; \
             echo 'tm: run `tm` to relaunch this session'; }}"
    );
    assert_eq!(cmd, expected, "no-token command shape must stay pinned");
}

#[test]
fn spawn_command_scrubs_inherited_session_markers() {
    // #4467: the marker name is HARD-CODED here on purpose. Deriving it from
    // the constant would make this test pass even if the constant were emptied,
    // which is the silent failure the issue is about — a managed session that
    // saves no transcript and reports nothing.
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.contains("-u CLAUDE_CODE_CHILD_SESSION"),
        "spawn must unset the marker that disables transcript saving: {cmd}"
    );
    assert!(
        cmd.contains("-u CLAUDE_CODE_SESSION_ID"),
        "spawn must unset the parent's session id: {cmd}"
    );
    assert!(
        cmd.contains("-u CLAUDECODE"),
        "spawn must unset the inherited in-Claude-Code marker: {cmd}"
    );
}

#[test]
fn resume_command_scrubs_inherited_session_markers() {
    // #4467: a fix covering `spawn_command` alone would leave every RESUMED
    // session still unable to save transcripts, so the resume path is asserted
    // independently rather than trusted to share `env_bin_prefix`.
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        Some("abc-123"),
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.contains("-u CLAUDE_CODE_CHILD_SESSION"),
        "resume must unset the marker that disables transcript saving: {cmd}"
    );
    assert!(
        cmd.contains("--resume abc-123"),
        "the resume selection must survive the scrub: {cmd}"
    );
}

#[test]
fn spawn_command_keeps_config_dir_out_of_the_scrub() {
    // #4467 over-scrub guard, at the command-string level: `CLAUDE_CONFIG_DIR`
    // must appear as an ASSIGNMENT and never as a `-u` unset. Scrubbing it would
    // move the bundled roster out of the `user` settings tier a managed session
    // loads and silently restore #4451 (every delegation → `general-purpose`).
    let dir = Path::new("/home/bob/.trusty-tools/trusty-mpm/claude-config");
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        Some(dir),
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        !cmd.contains("-u CLAUDE_CONFIG_DIR"),
        "CLAUDE_CONFIG_DIR must never be unset (#4455 depends on it): {cmd}"
    );
    assert!(
        cmd.contains("CLAUDE_CONFIG_DIR='/home/bob/.trusty-tools/trusty-mpm/claude-config' claude"),
        "CLAUDE_CONFIG_DIR must still be assigned right before the binary: {cmd}"
    );
}

#[test]
fn env_bin_prefix_orders_scrub_flags_before_assignments() {
    // POSIX `env` stops parsing options at the first `NAME=VALUE`, so a `-u`
    // appearing after an assignment is exec'd as a command
    // (`env: -u: No such file or directory`) and kills every managed spawn.
    let dir = Path::new("/tm/config");
    let prefix = env_bin_prefix("/abs/claude", Some(dir), Some("tok"));
    let last_unset = prefix
        .rfind("-u ")
        .expect("prefix must contain at least one -u flag");
    let first_assignment = prefix
        .find("CLAUDE_CONFIG_DIR=")
        .expect("prefix must contain the config-dir assignment");
    assert!(
        last_unset < first_assignment,
        "every -u flag must precede the first NAME=VALUE assignment: {prefix}"
    );
    // And the parser the doctor probe relies on must see the marker here.
    let unset = crate::core::claude_env_scrub::parse_env_unset_vars(&prefix);
    assert!(
        unset.contains(&"CLAUDE_CODE_CHILD_SESSION"),
        "the real spawn prefix must unset the suppressing marker: {unset:?}"
    );
    assert!(
        !unset.contains(&"CLAUDE_CONFIG_DIR"),
        "the real spawn prefix must NOT unset CLAUDE_CONFIG_DIR: {unset:?}"
    );
}

#[test]
fn spawn_command_sets_both_config_dir_and_oauth_token() {
    // Both assignments must coexist, config dir first (matching the
    // established assignment order), each independently single-quoted.
    let dir = Path::new("/home/bob/.trusty-tools/trusty-mpm/claude-config");
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        Some(dir),
        TEST_SESSION_ID,
        None,
        Some("sk-ant-oat01-fake-token"),
        None,
    );
    // #4467 inserted the inherited-marker `-u` flags between the API-key scrub
    // and the assignments, so the assignment run is matched on its own.
    assert!(
        cmd.contains(
            "CLAUDE_CONFIG_DIR='/home/bob/.trusty-tools/trusty-mpm/claude-config' \
                 CLAUDE_CODE_OAUTH_TOKEN='sk-ant-oat01-fake-token' claude"
        ),
        "both assignments must coexist, config dir before the token: {cmd}"
    );
    assert!(
        cmd.contains("env -u ANTHROPIC_API_KEY -u "),
        "the API-key scrub must still lead the env prefix: {cmd}"
    );
}

#[test]
fn resume_command_sets_oauth_token_when_available() {
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        Some("abc-123"),
        false,
        TEST_SESSION_ID,
        None,
        Some("sk-ant-oat01-fake-token"),
        None,
    );
    assert!(
        cmd.contains("CLAUDE_CODE_OAUTH_TOKEN='sk-ant-oat01-fake-token'"),
        "resume command must inject the token when available: {cmd}"
    );
    assert!(
        cmd.contains("--resume abc-123"),
        "--resume must still be present alongside the token: {cmd}"
    );
}

#[test]
fn resume_command_omits_oauth_token_when_absent() {
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        Some("abc-123"),
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        !cmd.contains("CLAUDE_CODE_OAUTH_TOKEN"),
        "no token available → must not reference CLAUDE_CODE_OAUTH_TOKEN: {cmd}"
    );
}

#[test]
fn resume_command_without_token_pins_the_exact_command() {
    // Full-string pin, resume-path counterpart to
    // spawn_command_without_token_pins_the_exact_command (see its note on why
    // #4467 replaced the former pre-#2246 byte-identity guard).
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        Some("abc-123"),
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    let scrub = crate::core::claude_env_scrub::env_unset_flags();
    let expected = format!(
        "cd '/tmp/ws' && {{ export TM_MANAGED_SESSION_ID='{TEST_SESSION_ID}'; \
             env -u ANTHROPIC_API_KEY{scrub} claude \
             --setting-sources project,local --dangerously-skip-permissions --resume abc-123; \
             echo 'tm: run `tm` to relaunch this session'; }}"
    );
    assert_eq!(
        cmd, expected,
        "no-token resume command shape must stay pinned"
    );
}

#[test]
fn env_bin_prefix_quotes_config_dir_with_space() {
    // CRITICAL (DOC-34 review): a home dir with a space must NOT word-split
    // the pane command. The path must appear single-quoted and INTACT so
    // `env` receives one CLAUDE_CONFIG_DIR value, not two argv tokens.
    let dir = Path::new("/Users/John Doe/.trusty-tools/trusty-mpm/claude-config");
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        Some(dir),
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.contains(
            "CLAUDE_CONFIG_DIR='/Users/John Doe/.trusty-tools/trusty-mpm/claude-config' claude"
        ),
        "config dir with a space must be single-quoted and intact: {cmd}"
    );
    // The bare unquoted form (which would word-split) must NOT appear.
    assert!(
        !cmd.contains("CLAUDE_CONFIG_DIR=/Users/John Doe"),
        "config dir must never be interpolated unquoted: {cmd}"
    );
    // Resume path shares env_bin_prefix, so it must quote identically.
    let resume = resume_command(
        Path::new(TEST_CWD),
        "claude",
        Some(dir),
        None,
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        resume
            .contains("CLAUDE_CONFIG_DIR='/Users/John Doe/.trusty-tools/trusty-mpm/claude-config'"),
        "resume command must also single-quote a spaced config dir: {resume}"
    );
}

#[test]
fn shell_single_quote_escapes_embedded_quote() {
    // A literal single quote in the path must be escaped via the POSIX
    // close-reopen sequence '\'' so the quoting stays balanced. (A macOS
    // home never contains one, but the escape must be correct regardless.)
    assert_eq!(shell_single_quote("/a/b"), "'/a/b'");
    assert_eq!(
        shell_single_quote("/Users/o'brien/cfg"),
        r"'/Users/o'\''brien/cfg'"
    );
}

#[test]
fn spawn_command_contains_isolation_flags() {
    // Why: the session_manager spawn path must isolate from the user's global
    // settings and run fully unattended (bypass all permission prompts) so
    // multi-agent orchestration never stalls on interactive approval dialogs.
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.contains("--setting-sources project,local"),
        "spawn command must isolate settings: {cmd}"
    );
    assert!(
        cmd.contains("--dangerously-skip-permissions"),
        "spawn command must bypass permissions for unattended orchestration: {cmd}"
    );
    // Must not carry the old acceptEdits flag.
    assert!(
        !cmd.contains("acceptEdits"),
        "old acceptEdits flag must not be present: {cmd}"
    );
}

#[test]
fn spawn_command_uses_resolved_binary() {
    // Why (#1298): under launchd the pane inherits a minimal PATH, so the
    // spawn command must invoke claude by the resolved (absolute) path
    // rather than a bare `claude` that the pane's PATH cannot find.
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "/Users/me/.local/bin/claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    // This test owns BINARY RESOLUTION, so it must not couple to the marker
    // list's contents or order. Matching the bare path (space-delimited on both
    // sides, so a bare `claude` cannot satisfy it) keeps a marker-list reorder
    // from failing here with an unrelated message — the scrub itself is asserted
    // by `spawn_command_scrubs_inherited_session_markers`.
    assert!(
        cmd.contains(" /Users/me/.local/bin/claude "),
        "spawn command must invoke the resolved absolute claude path: {cmd}"
    );
}

#[test]
fn claude_code_adapter_binary_check_returns_option() {
    // resolve_claude returns Some(path) or None without panicking; when it
    // resolves, the path must be a non-empty absolute-ish string.
    if let Some(p) = ClaudeCodeAdapter::resolve_claude() {
        assert!(!p.is_empty(), "resolved claude path must be non-empty");
    }
}

#[serial_test::serial]
#[test]
fn spawn_sends_env_scrub_when_binary_available() {
    // Patch: if claude is not available this test is a no-op (we cannot
    // install it in CI). We only assert the send when the binary exists.
    // HOME is redirected so the spawn's config-dir provisioning + trust seed
    // land in a throwaway dir, not the developer's real ~/.trusty-tools.
    let _home = HomeGuard::set();
    let Some(_claude_bin) = ClaudeCodeAdapter::resolve_claude() else {
        return;
    };
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    adapter
        .spawn(
            "tmpm-test",
            Path::new("/tmp"),
            "some task",
            TEST_SESSION_ID,
            &[],
        )
        .expect("spawn");
    let sends = fake.sends.lock().unwrap();
    assert_eq!(sends.len(), 1);
    assert_eq!(sends[0].0, "tmpm-test");
    let cmd = &sends[0].1;
    // Must carry the env scrub regardless (the option must precede any
    // intervening `CLAUDE_CONFIG_DIR=` assignment per POSIX env grammar).
    assert!(cmd.contains("-u ANTHROPIC_API_KEY"));
    // Issue #2125 item 3: the spawn command must inject the PM system
    // prompt via --append-system-prompt-file — the third fail-closed
    // carrier — so this, the default daemon on-ramp, can no longer
    // silently spawn vanilla Claude Code. The prompt file path itself is
    // non-deterministic (fresh UUID per call), so this asserts the flag's
    // presence rather than an exact command match.
    assert!(
        cmd.contains("--append-system-prompt-file"),
        "spawn command must inject the PM system prompt file: {cmd}"
    );
}

#[serial_test::serial]
#[test]
fn spawn_sends_oauth_token_when_available() {
    // #2246: the fresh-spawn path must inject CLAUDE_CODE_OAUTH_TOKEN when
    // resolve_oauth_token() finds one (here, via the process env var — the
    // higher-precedence source). HOME is redirected so the rest of the
    // provisioning stays hermetic.
    let _home = HomeGuard::set();
    let Some(_claude_bin) = ClaudeCodeAdapter::resolve_claude() else {
        return;
    };
    unsafe {
        std::env::set_var(
            crate::core::oauth_token::OAUTH_TOKEN_ENV_VAR,
            "sk-ant-oat01-fake-token",
        );
    }
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    let result = adapter.spawn(
        "tmpm-test",
        Path::new("/tmp"),
        "some task",
        TEST_SESSION_ID,
        &[],
    );
    unsafe {
        std::env::remove_var(crate::core::oauth_token::OAUTH_TOKEN_ENV_VAR);
    }
    result.expect("spawn");
    let sends = fake.sends.lock().unwrap();
    assert_eq!(sends.len(), 1);
    assert!(
        sends[0]
            .1
            .contains("CLAUDE_CODE_OAUTH_TOKEN='sk-ant-oat01-fake-token'"),
        "spawn must inject the resolved oauth token: {}",
        sends[0].1
    );
}

#[test]
fn publish_session_env_sets_id_and_config_dir() {
    // #2157 item 1: exercises publish_session_env directly (no HOME
    // redirection or real `claude` binary needed) so this call-shape
    // assertion runs unconditionally in CI, unlike the full-spawn tests
    // below which are gated on a real `claude` binary being present.
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    adapter.publish_session_env("tmpm-test", TEST_SESSION_ID, Some("/tmp/config-dir"));
    let env_sets = fake.env_sets.lock().unwrap();
    assert_eq!(
        env_sets.len(),
        2,
        "expected id + config-dir sets: {env_sets:?}"
    );
    assert!(env_sets.contains(&(
        "tmpm-test".to_string(),
        "TM_MANAGED_SESSION_ID".to_string(),
        TEST_SESSION_ID.to_string()
    )));
    assert!(env_sets.contains(&(
        "tmpm-test".to_string(),
        "CLAUDE_CONFIG_DIR".to_string(),
        "/tmp/config-dir".to_string()
    )));
}

#[test]
fn publish_session_env_omits_config_dir_when_absent() {
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    adapter.publish_session_env("tmpm-test", TEST_SESSION_ID, None);
    let env_sets = fake.env_sets.lock().unwrap();
    assert_eq!(
        env_sets.len(),
        1,
        "expected only the session-id set: {env_sets:?}"
    );
    assert_eq!(env_sets[0].1, "TM_MANAGED_SESSION_ID");
}

#[serial_test::serial]
#[test]
fn spawn_publishes_session_id_via_set_environment() {
    // #2157 item 1: spawn must durably publish TM_MANAGED_SESSION_ID via
    // `tmux set-environment`, not just the pane-shell export baked into the
    // command line — belt-and-suspenders so a sibling pane/window in the
    // same tmux session (which never ran the export line) can still resolve
    // it via `tmux show-environment`.
    let _home = HomeGuard::set();
    if ClaudeCodeAdapter::resolve_claude().is_none() {
        return;
    }
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    adapter
        .spawn(
            "tmpm-test",
            Path::new("/tmp"),
            "some task",
            TEST_SESSION_ID,
            &[],
        )
        .expect("spawn");
    let env_sets = fake.env_sets.lock().unwrap();
    assert!(
        env_sets.iter().any(|(name, key, value)| name == "tmpm-test"
            && key == "TM_MANAGED_SESSION_ID"
            && value == TEST_SESSION_ID),
        "spawn must call tmux set-environment with TM_MANAGED_SESSION_ID: {env_sets:?}"
    );
}

#[test]
fn spawn_command_with_prompt_file_contains_flag() {
    // #2125 item 3: when a prompt file is supplied, spawn_command must
    // inject --append-system-prompt-file pointing at it, alongside the
    // existing isolation flags — the third fail-closed carrier.
    let path = Path::new("/tmp/trusty-mpm-system-prompt-test.txt");
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        Some(path),
        None,
        None,
    );
    assert!(
        cmd.contains("--append-system-prompt-file '/tmp/trusty-mpm-system-prompt-test.txt'"),
        "spawn command must pass the prompt file via --append-system-prompt-file: {cmd}"
    );
    assert!(
        cmd.contains("--setting-sources project,local"),
        "isolation flags must still be present alongside the prompt file: {cmd}"
    );
}

#[test]
fn spawn_command_without_prompt_file_omits_flag() {
    // #2125 item 3: no prompt file (e.g. the write failed) → the flag must
    // be omitted entirely rather than passed with a bad/empty path.
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        !cmd.contains("--append-system-prompt-file"),
        "no prompt file → flag must be absent: {cmd}"
    );
}

#[test]
#[serial_test::serial]
fn build_prompt_file_writes_resolved_prompt_for_project() {
    // #2125 item 3: build_prompt_file must reuse the SAME
    // build_system_prompt_for_with_style_and_native seam the CLI/client
    // launch paths use, so the daemon adapter's injected prompt is never a
    // divergent copy — proven here by asserting the written file carries
    // the bundled PM_INSTRUCTIONS heading.
    //
    // #4752 added a compiled-prompt refresh resolved from `$HOME`, so this test
    // now needs the HomeGuard + `#[serial]` pairing to keep that write off the
    // developer's real `~/.trusty-mpm` (the #2459/#2460/#2461 hazard class).
    let _home = HomeGuard::set();
    let tmp = tempfile::tempdir().expect("tempdir");
    let path = build_prompt_file(tmp.path(), Some("sess-1")).expect("prompt file written");
    let content = std::fs::read_to_string(&path).expect("prompt file readable");
    assert!(
        content.contains("# PM Agent -- Trusty MPM"),
        "prompt file must contain the resolved PM system prompt: {content}"
    );
    std::fs::remove_file(&path).ok();
}

#[test]
#[serial_test::serial]
fn build_prompt_file_refreshes_the_compiled_prompt() {
    // Why (#4752 review, HIGH 3): `resume_managed` never calls `prepare_session*`
    // on its healthy path — it goes `resume_self_heal` → `ensure_status_line` →
    // `ensure_deployment_complete` → `spawn_resume`, and `spawn_resume` builds
    // its prompt here. Before this fix, every resume, guided-resume and
    // crash-recovery launch ran a prompt that never reached the compiled path.
    //
    // This is the seam ALL THREE spawn paths share, so covering it covers
    // resume. FIXTURE: the compiled file is pre-seeded with stale sentinel
    // content, so "the file exists" cannot pass this — only an actual refresh
    // can. Equality with the prompt file is what makes the artifact the same
    // text the session runs with.
    let _home = HomeGuard::set();
    let tmp = tempfile::tempdir().expect("tempdir");
    let compiled = crate::core::instruction_pipeline::compiled_prompt_path(tmp.path(), "sess-1");
    std::fs::create_dir_all(compiled.parent().unwrap()).expect("create framework dir");
    const STALE: &str = "STALE-FROM-A-PREVIOUS-LAUNCH";
    std::fs::write(&compiled, STALE).expect("seed stale compiled prompt");

    let path = build_prompt_file(tmp.path(), Some("sess-1")).expect("prompt file written");

    let on_disk = std::fs::read_to_string(&compiled).expect("compiled prompt readable");
    assert_ne!(
        on_disk, STALE,
        "the spawn seam must refresh a stale compiled prompt — resume paths \
         depend on this, since they never run prepare_session"
    );
    let launch_prompt = std::fs::read_to_string(&path).expect("prompt file readable");
    assert_eq!(
        on_disk, launch_prompt,
        "the compiled prompt must be byte-identical to the file passed to \
         --append-system-prompt-file"
    );
    std::fs::remove_file(&path).ok();
}

#[test]
#[serial_test::serial]
fn build_prompt_file_compiled_write_failure_does_not_block_the_spawn() {
    // Why (#4752 review, HIGH 1's lesson applied here): the compiled file is an
    // INSPECTION artifact. A failure writing it must never cost the session its
    // actual system prompt — that would trade a stale debugging aid for a
    // broken launch, the same inverted priority the review flagged in
    // `prepare_session_inner`.
    //
    // FIXTURE: a directory is planted at the compiled path so only that write
    // fails; the prompt file itself must still be produced and still carry the
    // real PM prompt.
    let _home = HomeGuard::set();
    let tmp = tempfile::tempdir().expect("tempdir");
    let compiled = crate::core::instruction_pipeline::compiled_prompt_path(tmp.path(), "sess-1");
    std::fs::create_dir_all(&compiled).expect("plant a directory at the compiled path");

    let path = build_prompt_file(tmp.path(), Some("sess-1"))
        .expect("spawn must still get its prompt file (non-fatal)");
    let content = std::fs::read_to_string(&path).expect("prompt file readable");
    assert!(
        content.contains("# PM Agent -- Trusty MPM"),
        "the session must still receive the real PM prompt: {content}"
    );
    std::fs::remove_file(&path).ok();
}

#[test]
fn resume_command_with_id_uses_resume_flag() {
    // Why (#1744): --resume <id> restores the exact prior conversation;
    // the test pins the contract so accidental regressions are caught early.
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        Some("abc-123"),
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.contains("--resume abc-123"),
        "resume command must include --resume <id>: {cmd}"
    );
    assert!(
        cmd.contains("env -u ANTHROPIC_API_KEY"),
        "resume command must still scrub API key: {cmd}"
    );
    assert!(
        !cmd.contains("--continue"),
        "resume command must NOT contain --continue when id is set: {cmd}"
    );
}

#[test]
fn resume_command_exports_managed_session_id() {
    // #2023 component B: the resume command must ALSO export
    // TM_MANAGED_SESSION_ID before the claude invocation, for the same
    // reason as the spawn path — the pane's shell must retain the id after
    // claude exits, whichever launch path (fresh spawn or resume) started it.
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        Some("abc-123"),
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    let expected_prefix = format!("export TM_MANAGED_SESSION_ID='{TEST_SESSION_ID}'; ");
    // #2250: the command now starts with `cd <workdir> && { ...` — the
    // export is the first statement INSIDE that brace group, not literally
    // the first bytes of the string.
    assert!(
        cmd.contains(&format!("{{ {expected_prefix}")),
        "resume command must export the session id as the first statement \
             inside the cd-group: {cmd}"
    );
    let export_pos = cmd
        .find("export TM_MANAGED_SESSION_ID")
        .expect("export present");
    let resume_pos = cmd.find("--resume").expect("--resume flag present");
    assert!(
        export_pos < resume_pos,
        "export must precede the --resume flag: {cmd}"
    );
}

#[test]
fn resume_command_sets_claude_config_dir() {
    // DOC-34: the resume path must also carry CLAUDE_CONFIG_DIR so resumed
    // sessions read the same tm-owned roster as fresh spawns.
    let dir = Path::new("/home/bob/.trusty-tools/trusty-mpm/claude-config");
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        Some(dir),
        Some("abc-123"),
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    // #4467 inserted the inherited-marker `-u` flags before the assignment.
    assert!(
        cmd.contains("env -u ANTHROPIC_API_KEY -u "),
        "the API-key scrub must still lead the env prefix: {cmd}"
    );
    assert!(
        cmd.contains("CLAUDE_CONFIG_DIR='/home/bob/.trusty-tools/trusty-mpm/claude-config' claude"),
        "resume command must export (single-quoted) CLAUDE_CONFIG_DIR after the -u option: {cmd}"
    );
    assert!(
        cmd.contains("--resume abc-123"),
        "resume command must still include --resume <id>: {cmd}"
    );
}

#[test]
fn resume_command_without_id_with_prior_conv_uses_continue() {
    // Why (#1744 / #1840): when no claude_session_id is stored but prior
    // conversation history exists, --continue resumes the most-recent
    // conversation in the workspace rather than starting fresh.
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        None,
        true,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.contains("--continue"),
        "resume command without id + prior conv must use --continue: {cmd}"
    );
    assert!(
        !cmd.contains("--resume"),
        "resume command without id must NOT contain --resume: {cmd}"
    );
}

#[test]
fn resume_command_without_id_no_prior_conv_uses_plain_spawn() {
    // Why (#1840): when no claude_session_id is stored AND no prior
    // conversation exists, --continue would error with "No conversation
    // found to continue". The plain spawn starts a fresh session instead.
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        None,
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        !cmd.contains("--continue"),
        "resume command without id + no prior conv must NOT use --continue: {cmd}"
    );
    assert!(
        !cmd.contains("--resume"),
        "resume command without id must NOT use --resume: {cmd}"
    );
    assert!(
        cmd.contains("env -u ANTHROPIC_API_KEY"),
        "plain spawn command must still scrub API key: {cmd}"
    );
}

#[test]
fn has_prior_conversation_returns_false_for_fresh_workspace() {
    // Why (#1840): a fresh worktree has no Claude conversation history;
    // has_prior_conversation must return false to avoid "No conversation found".
    // Uses has_prior_conversation_in with a temp projects_dir — no HOME env
    // mutation, making this test safe for parallel execution.
    let tmp = tempfile::tempdir().expect("tempdir");
    let projects_dir = tmp.path().join("projects");
    // projects_dir does not exist → always returns false.
    assert!(
        !has_prior_conversation_in(tmp.path(), &projects_dir),
        "no projects dir → false"
    );
    // Create the projects dir but with no entry for this workspace → still false.
    std::fs::create_dir_all(&projects_dir).unwrap();
    assert!(
        !has_prior_conversation_in(tmp.path(), &projects_dir),
        "projects dir exists but no entry for this workspace → false"
    );
}

#[test]
fn has_prior_conversation_returns_true_when_jsonl_exists() {
    // Why (#1840): verify the positive path — a workspace with a .jsonl file
    // in its encoded project dir must return true.
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path().join("my-workspace");
    std::fs::create_dir_all(&cwd).unwrap();
    let projects_dir = tmp.path().join("projects");
    // Encode the cwd path as Claude does: replace '/' with '-'.
    let encoded = cwd.to_string_lossy().replace('/', "-");
    let project_dir = projects_dir.join(&encoded);
    std::fs::create_dir_all(&project_dir).unwrap();
    std::fs::write(project_dir.join("session.jsonl"), "{}").unwrap();
    assert!(
        has_prior_conversation_in(&cwd, &projects_dir),
        "workspace with .jsonl must return true"
    );
}

#[serial_test::serial]
#[test]
fn spawn_resume_with_id_uses_resume_flag() {
    // Why (#1744, #2013): ClaudeCodeAdapter::spawn_resume must send
    // --resume <id> to the pane when the claude_session_id is known AND
    // still resolves to a real session on disk. HOME is redirected so the
    // config-dir provisioning is hermetic; a matching session jsonl file
    // is seeded under the resolved CLAUDE_CONFIG_DIR/projects/ so the
    // #2013 existence check passes.
    let _home = HomeGuard::set();
    if ClaudeCodeAdapter::resolve_claude().is_none() {
        return;
    };
    let cwd = Path::new("/tmp");
    let config_dir = crate::core::trusty_tools_config::managed_claude_config_dir()
        .expect("config dir resolves under redirected HOME");
    let encoded = cwd.to_string_lossy().replace('/', "-");
    let project_dir = config_dir.join("projects").join(&encoded);
    std::fs::create_dir_all(&project_dir).unwrap();
    std::fs::write(project_dir.join("my-session-id.jsonl"), "{}").unwrap();

    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    adapter
        .spawn_resume(
            "tmpm-test",
            None,
            cwd,
            "task",
            Some("my-session-id"),
            TEST_SESSION_ID,
            &[],
        )
        .expect("spawn_resume");
    let sends = fake.sends.lock().unwrap();
    assert_eq!(sends.len(), 1);
    assert!(
        sends[0].1.contains("--resume my-session-id"),
        "spawn_resume with an existing id must use --resume: {}",
        sends[0].1
    );
    // #2157 item 1: the RESUME path must ALSO durably publish the id — a
    // fresh tmux session is created on resume, so it starts with no
    // set-environment history at all.
    let env_sets = fake.env_sets.lock().unwrap();
    assert!(
        env_sets.iter().any(|(name, key, value)| name == "tmpm-test"
            && key == "TM_MANAGED_SESSION_ID"
            && value == TEST_SESSION_ID),
        "spawn_resume must call tmux set-environment with TM_MANAGED_SESSION_ID: {env_sets:?}"
    );
}

#[serial_test::serial]
#[test]
fn spawn_resume_sends_prompt_file_when_binary_available() {
    // #2230: spawn_resume must inject --append-system-prompt-file just
    // like spawn() does — before this fix, every resume path (including
    // guided-resume and crash-recovery, which both funnel through this
    // adapter method) silently omitted the PM system prompt carrier.
    // HOME is redirected so build_prompt_file's write lands in a
    // throwaway dir, not the developer's real ~/.trusty-tools.
    let _home = HomeGuard::set();
    let Some(_claude_bin) = ClaudeCodeAdapter::resolve_claude() else {
        return;
    };
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    adapter
        .spawn_resume(
            "tmpm-test",
            None,
            Path::new("/tmp/does-not-exist-2230"),
            "task",
            None,
            TEST_SESSION_ID,
            &[],
        )
        .expect("spawn_resume");
    let sends = fake.sends.lock().unwrap();
    assert_eq!(sends.len(), 1);
    assert!(
        sends[0].1.contains("--append-system-prompt-file"),
        "spawn_resume must inject the PM system prompt file: {}",
        sends[0].1
    );
}

#[serial_test::serial]
#[test]
fn spawn_resume_sends_oauth_token_when_available() {
    // #2246: spawn_resume must inject CLAUDE_CODE_OAUTH_TOKEN when one is
    // resolvable, mirroring spawn()'s carrier — every resumed session
    // funnels through here, so this is the exact path that was silently
    // exposed to the login loop before this fix. HOME is redirected so
    // resolve_oauth_token()'s stored-file check is hermetic; the env var
    // itself is set/cleared around the call.
    let _home = HomeGuard::set();
    let Some(_claude_bin) = ClaudeCodeAdapter::resolve_claude() else {
        return;
    };
    unsafe {
        std::env::set_var(
            crate::core::oauth_token::OAUTH_TOKEN_ENV_VAR,
            "sk-ant-oat01-fake-token",
        );
    }
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    let result = adapter.spawn_resume(
        "tmpm-test",
        None,
        Path::new("/tmp/does-not-exist-2246"),
        "task",
        None,
        TEST_SESSION_ID,
        &[],
    );
    unsafe {
        std::env::remove_var(crate::core::oauth_token::OAUTH_TOKEN_ENV_VAR);
    }
    result.expect("spawn_resume");
    let sends = fake.sends.lock().unwrap();
    assert_eq!(sends.len(), 1);
    assert!(
        sends[0]
            .1
            .contains("CLAUDE_CODE_OAUTH_TOKEN='sk-ant-oat01-fake-token'"),
        "spawn_resume must inject the resolved oauth token: {}",
        sends[0].1
    );
}

#[serial_test::serial]
#[test]
fn spawn_resume_with_missing_id_falls_back_gracefully() {
    // Why (#2013): a stale/unknown claude_session_id must NOT be passed to
    // `--resume` (which would fail hard) — it must fall back the same way
    // a `None` id does. HOME is redirected so the config dir is hermetic
    // and no session jsonl is seeded, so the id is guaranteed missing.
    let _home = HomeGuard::set();
    if ClaudeCodeAdapter::resolve_claude().is_none() {
        return;
    };
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    adapter
        .spawn_resume(
            "tmpm-test",
            None,
            Path::new("/tmp/does-not-exist-2013"),
            "task",
            Some("stale-session-id"),
            TEST_SESSION_ID,
            &[],
        )
        .expect("spawn_resume must not hard-fail on a missing id");
    let sends = fake.sends.lock().unwrap();
    assert_eq!(sends.len(), 1);
    assert!(
        !sends[0].1.contains("--resume"),
        "a missing id must NOT be passed to --resume: {}",
        sends[0].1
    );
    assert!(
        !sends[0].1.contains("--continue"),
        "a missing id with no prior conversation history must fall back to a \
             plain spawn, not --continue: {}",
        sends[0].1
    );
    assert!(
        sends[0].1.contains("env -u ANTHROPIC_API_KEY"),
        "fallback command must still scrub the API key: {}",
        sends[0].1
    );
}

#[serial_test::serial]
#[test]
fn spawn_resume_targets_stored_pane_id_when_known() {
    // Sibling-window hijack fix, follow-up to #2456: when the caller
    // supplies `record.pane_id`, spawn_resume MUST target that SPECIFIC
    // pane (via `send_line_to_pane`), never the bare session name (via
    // `send_line`, which tmux resolves to whichever pane/window happens
    // to be active — e.g. a sibling window opened after the original
    // pane). This is the exact regression that let a resume/restart
    // respawn `claude` into an unrelated active pane while the original
    // pane sat at a bare shell.
    let _home = HomeGuard::set();
    if ClaudeCodeAdapter::resolve_claude().is_none() {
        return;
    };
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    adapter
        .spawn_resume(
            "tmpm-test",
            Some("%6015"),
            Path::new("/tmp/does-not-exist-pane-target"),
            "task",
            None,
            TEST_SESSION_ID,
            &[],
        )
        .expect("spawn_resume with known pane_id");

    let pane_sends = fake.pane_sends.lock().unwrap();
    assert_eq!(
        pane_sends.len(),
        1,
        "spawn_resume with a known pane_id must call send_line_to_pane exactly once: \
             {pane_sends:?}"
    );
    assert_eq!(
        pane_sends[0].0, "tmpm-test",
        "pane-scoped send must target the record's tmux session name"
    );
    assert_eq!(
        pane_sends[0].1, "%6015",
        "pane-scoped send must target the record's STORED pane_id, not whatever pane \
             tmux considers active"
    );

    let sends = fake.sends.lock().unwrap();
    assert!(
        sends.is_empty(),
        "spawn_resume with a known pane_id must NEVER fall back to the session-scoped \
             send_line (which tmux resolves to the active pane): {sends:?}"
    );
}

#[serial_test::serial]
#[test]
fn spawn_resume_falls_back_to_session_target_when_pane_id_unknown() {
    // The inverse of the above: a legacy record that predates pane-id
    // capture (`pane_id: None`) has no stronger signal to target than the
    // session name — spawn_resume must fall back to the pre-existing
    // session-scoped `send_line`, not silently drop the command.
    let _home = HomeGuard::set();
    if ClaudeCodeAdapter::resolve_claude().is_none() {
        return;
    };
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    adapter
        .spawn_resume(
            "tmpm-test",
            None,
            Path::new("/tmp/does-not-exist-no-pane"),
            "task",
            None,
            TEST_SESSION_ID,
            &[],
        )
        .expect("spawn_resume with no pane_id");

    let sends = fake.sends.lock().unwrap();
    assert_eq!(
        sends.len(),
        1,
        "spawn_resume with no pane_id must fall back to session-scoped send_line: {sends:?}"
    );
    let pane_sends = fake.pane_sends.lock().unwrap();
    assert!(
        pane_sends.is_empty(),
        "spawn_resume with no pane_id must never call send_line_to_pane: {pane_sends:?}"
    );
}

#[test]
fn session_id_exists_true_for_real_jsonl_file() {
    // Why (#2013): the positive path — a session file present under the
    // encoded project dir must resolve as existing.
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path().join("my-workspace");
    std::fs::create_dir_all(&cwd).unwrap();
    let projects_dir = tmp.path().join("projects");
    let encoded = cwd.to_string_lossy().replace('/', "-");
    let project_dir = projects_dir.join(&encoded);
    std::fs::create_dir_all(&project_dir).unwrap();
    std::fs::write(project_dir.join("abc-123.jsonl"), "{}").unwrap();
    assert!(
        session_id_exists_in(&cwd, &projects_dir, "abc-123"),
        "existing session file must resolve as present"
    );
}

#[test]
fn session_id_exists_false_for_missing_id() {
    // Why (#2013): a stale id — no matching .jsonl for this id, even
    // though the workspace has OTHER conversation history — must resolve
    // as absent so the caller falls back instead of hard-failing.
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path().join("my-workspace");
    std::fs::create_dir_all(&cwd).unwrap();
    let projects_dir = tmp.path().join("projects");
    let encoded = cwd.to_string_lossy().replace('/', "-");
    let project_dir = projects_dir.join(&encoded);
    std::fs::create_dir_all(&project_dir).unwrap();
    std::fs::write(project_dir.join("other-session.jsonl"), "{}").unwrap();
    assert!(
        !session_id_exists_in(&cwd, &projects_dir, "stale-id-not-present"),
        "id with no matching file must resolve as absent"
    );
}

#[test]
fn session_id_exists_false_when_projects_dir_absent() {
    // Why (#2013): a fresh workspace / unresolved config dir must never
    // panic or hard-fail — best-effort false is the safe default.
    let tmp = tempfile::tempdir().expect("tempdir");
    let missing_projects_dir = tmp.path().join("does-not-exist");
    assert!(
        !session_id_exists_in(tmp.path(), &missing_projects_dir, "any-id"),
        "missing projects dir must resolve as absent, not panic"
    );
    assert!(
        !session_id_exists(tmp.path(), None, "any-id"),
        "session_id_exists with no config dir falls back to home resolution \
             and must never panic even if HOME is unusual in the test env"
    );
}

#[test]
fn encode_project_dir_replaces_slashes() {
    // Why (#2013 cleanup): pins the shared encoding helper's contract
    // directly, independent of either call site.
    assert_eq!(
        encode_project_dir(Path::new("/private/tmp/foo")),
        "-private-tmp-foo"
    );
}

#[test]
fn session_id_exists_finds_hardcoded_dir_name_for_known_cwd() {
    // Why (#2013 cleanup, MEDIUM): the other session_id_exists tests build
    // their expected path via the SAME formula the implementation uses
    // (`cwd.to_string_lossy().replace('/', "-")` / `encode_project_dir`),
    // so they cannot catch a future drift in the encoding scheme — the
    // test and the code would drift together. This test instead types the
    // expected directory name BY HAND as a literal, so if the encoding
    // scheme ever changes (e.g. Claude Code starts hashing paths instead
    // of dash-joining them), this assertion breaks independently of the
    // implementation.
    let tmp = tempfile::tempdir().expect("tempdir");
    let projects_dir = tmp.path().join("projects");
    // Hand-typed literal for cwd "/tmp/my-workspace" — NOT derived by
    // calling encode_project_dir/replace('/', "-") here.
    let project_dir = projects_dir.join("-tmp-my-workspace");
    std::fs::create_dir_all(&project_dir).unwrap();
    std::fs::write(project_dir.join("known-id.jsonl"), "{}").unwrap();
    assert!(
        session_id_exists_in(Path::new("/tmp/my-workspace"), &projects_dir, "known-id"),
        "session_id_exists_in must find the seeded session under the \
             hand-typed expected dir name '-tmp-my-workspace'"
    );
}

#[test]
fn projects_dir_for_prefers_config_dir_when_present() {
    // Why (#2013): CLAUDE_CONFIG_DIR relocates the entire config home,
    // including session storage — the projects dir must be resolved
    // UNDER it, not always under ~/.claude, or the existence check would
    // never find managed sessions.
    let config_dir = Path::new("/tmp/some-managed-config-dir");
    assert_eq!(
        projects_dir_for(Some(config_dir)),
        Some(config_dir.join("projects")),
        "projects_dir_for must nest under the given config dir"
    );
}

#[serial_test::serial]
#[test]
fn spawn_resume_without_id_no_prior_conv_sends_plain_spawn() {
    // Why (#1840, #1845 item 3): when no claude_session_id is available AND the
    // workspace has no prior conversation, spawn_resume must send a plain spawn
    // (no --continue, no --resume) to avoid "No conversation found to continue".
    //
    // The command construction is tested via resume_command() directly with a fake
    // binary so assertions ALWAYS run even when the `claude` binary is absent in CI.
    // The adapter merely calls resume_command() with the same arguments; testing the
    // function directly proves the selection logic without CI depending on claude.
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "__fake_claude__",
        None,
        None,
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        !cmd.contains("--continue"),
        "plain-spawn path must NOT use --continue: {cmd}"
    );
    assert!(
        !cmd.contains("--resume"),
        "plain-spawn path must NOT use --resume: {cmd}"
    );
    assert!(
        cmd.contains("env -u ANTHROPIC_API_KEY"),
        "plain-spawn path must still scrub API key: {cmd}"
    );

    // Additionally verify the adapter-level plumbing when the binary is present.
    // HOME is redirected so the config-dir provisioning is hermetic.
    let _home = HomeGuard::set();
    let Some(_claude_bin) = ClaudeCodeAdapter::resolve_claude() else {
        return; // core assertions above already ran; adapter path requires binary
    };
    let tmp = tempfile::tempdir().expect("tempdir");
    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    adapter
        .spawn_resume(
            "test-tmux-session",
            None,
            tmp.path(),
            "task",
            None,
            TEST_SESSION_ID,
            &[],
        )
        .expect("spawn_resume without id");
    let sends = fake.sends.lock().unwrap();
    assert_eq!(sends.len(), 1);
    assert!(
        !sends[0].1.contains("--continue"),
        "adapter plain-spawn must NOT use --continue: {}",
        sends[0].1
    );
    assert!(
        !sends[0].1.contains("--resume"),
        "adapter plain-spawn must NOT use --resume: {}",
        sends[0].1
    );
}

// ── #2250: cd-prefix belt-and-suspenders ────────────────────────────────

#[test]
fn spawn_command_prefixes_cd_to_workdir() {
    // #2250: the emitted command must be correct regardless of the pane
    // shell's actual starting directory — an explicit `cd` must lead the
    // whole line, and the exported session id / claude invocation must be
    // wrapped in a brace GROUP (not a subshell) so the env survives.
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.starts_with("cd '/tmp/ws' && { "),
        "spawn command must start with an explicit cd into the workdir: {cmd}"
    );
    assert!(
        cmd.trim_end().ends_with('}'),
        "spawn command must close the brace group it opened: {cmd}"
    );
}

#[test]
fn resume_command_prefixes_cd_to_workdir() {
    // #2250: same cd-prefix guarantee on the resume path — the one most
    // directly implicated by a stale/removed workspace_path silently
    // rooting a recreated pane at $HOME.
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        Some("abc-123"),
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.starts_with("cd '/tmp/ws' && { "),
        "resume command must start with an explicit cd into the workdir: {cmd}"
    );
    assert!(
        cmd.trim_end().ends_with('}'),
        "resume command must close the brace group it opened: {cmd}"
    );
}

#[test]
fn cd_and_group_quotes_workdir_with_space() {
    // A workdir with a space must not word-split the pane command — same
    // invariant env_bin_prefix already enforces for CLAUDE_CONFIG_DIR.
    let cmd = cd_and_group(Path::new("/Users/John Doe/work"), "echo hi");
    assert_eq!(cmd, "cd '/Users/John Doe/work' && { echo hi; }");
}

// ── #2023 component D: on-exit relaunch hint ────────────────────────────

#[test]
fn spawn_command_prints_relaunch_hint_after_claude_exits() {
    // The hint must appear AFTER the claude invocation, separated by `;` so
    // it only runs once claude exits and control returns to the pane shell.
    let cmd = spawn_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.contains("; echo 'tm: run `tm` to relaunch this session'"),
        "spawn command must print the relaunch hint after claude exits: {cmd}"
    );
    let claude_pos = cmd.find(" claude ").expect("claude invocation present");
    let hint_pos = cmd.find("; echo").expect("relaunch hint present");
    assert!(
        claude_pos < hint_pos,
        "relaunch hint must come AFTER the claude invocation: {cmd}"
    );
}

#[test]
fn resume_command_prints_relaunch_hint_after_claude_exits() {
    // Same invariant for the resume path (--resume branch here; the
    // --continue/plain-spawn branches share the same trailing suffix).
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        Some("abc-123"),
        false,
        TEST_SESSION_ID,
        None,
        None,
        None,
    );
    assert!(
        cmd.contains("; echo 'tm: run `tm` to relaunch this session'"),
        "resume command must print the relaunch hint after claude exits: {cmd}"
    );
    let resume_pos = cmd.find("--resume").expect("--resume flag present");
    let hint_pos = cmd.find("; echo").expect("relaunch hint present");
    assert!(
        resume_pos < hint_pos,
        "relaunch hint must come AFTER --resume: {cmd}"
    );
}

#[test]
fn resume_command_with_prompt_file_contains_flag() {
    // #2230: the resume path must carry the same --append-system-prompt-file
    // carrier as spawn_command — before this fix, resumed / guided-resume /
    // crash-recovery sessions had no way to inject the PM system prompt at all.
    let path = Path::new("/tmp/trusty-mpm-system-prompt-resume-test.txt");
    let cmd = resume_command(
        Path::new(TEST_CWD),
        "claude",
        None,
        Some("abc-123"),
        false,
        TEST_SESSION_ID,
        Some(path),
        None,
        None,
    );
    assert!(
        cmd.contains("--append-system-prompt-file '/tmp/trusty-mpm-system-prompt-resume-test.txt'"),
        "resume command must pass the prompt file via --append-system-prompt-file: {cmd}"
    );
    assert!(
        cmd.contains("--resume abc-123"),
        "--resume must still be present alongside the prompt file: {cmd}"
    );
}

// ── #2023 component C: in-place relaunch command builder ───────────────

#[test]
fn compose_inplace_args_uses_resume_for_existing_id() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path().join("workspace");
    std::fs::create_dir_all(&cwd).unwrap();
    let config_dir = tmp.path().join("config");
    let encoded = cwd.to_string_lossy().replace('/', "-");
    let project_dir = config_dir.join("projects").join(&encoded);
    std::fs::create_dir_all(&project_dir).unwrap();
    std::fs::write(project_dir.join("existing-id.jsonl"), "{}").unwrap();

    let args = compose_inplace_args(&cwd, Some(&config_dir), Some("existing-id"), None);
    assert!(
        args.windows(2).any(|w| w == ["--resume", "existing-id"]),
        "must select --resume <id> for an id that exists on disk: {args:?}"
    );
    assert!(
        !args.contains(&"--continue".to_owned()),
        "must not ALSO pass --continue when --resume is used: {args:?}"
    );
}

#[test]
fn compose_inplace_args_falls_back_for_missing_id() {
    // #2013 parity: a stale id (no matching .jsonl) with no prior
    // conversation history falls back to a fresh spawn — neither
    // --resume nor --continue.
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path().join("workspace-missing");
    std::fs::create_dir_all(&cwd).unwrap();
    let config_dir = tmp.path().join("config");

    let args = compose_inplace_args(&cwd, Some(&config_dir), Some("stale-id"), None);
    assert!(
        !args.contains(&"--resume".to_owned()),
        "a stale id must not be passed to --resume: {args:?}"
    );
    assert!(
        !args.contains(&"--continue".to_owned()),
        "no prior conversation history: must not fall back to --continue: {args:?}"
    );
    assert!(
        args.contains(&"--setting-sources".to_owned()),
        "isolation flags must still be present: {args:?}"
    );
}

#[serial_test::serial]
#[test]
fn compose_inplace_args_uses_continue_when_no_id_but_prior_conv() {
    // has_prior_conversation (unlike session_id_exists) always looks under
    // `~/.claude/projects` regardless of `config_dir` — mirroring exactly
    // what `resume_command`'s own `has_prior_conv` computation does — so
    // this test redirects $HOME rather than seeding under a config dir.
    let _home = HomeGuard::set();
    let home = dirs::home_dir().expect("home resolves under redirected HOME");
    let cwd = std::path::PathBuf::from("/tmp/inplace-continue-test");
    // Seed prior conversation history (a .jsonl under the encoded cwd dir)
    // WITHOUT seeding the specific stale id, so has_prior_conversation is
    // true but session_id_exists for "stale-id" is false.
    let encoded = cwd.to_string_lossy().replace('/', "-");
    let project_dir = home.join(".claude").join("projects").join(&encoded);
    std::fs::create_dir_all(&project_dir).unwrap();
    std::fs::write(project_dir.join("some-other-session.jsonl"), "{}").unwrap();

    let args = compose_inplace_args(&cwd, None, Some("stale-id"), None);
    assert!(
        !args.contains(&"--resume".to_owned()),
        "a stale id must not be passed to --resume: {args:?}"
    );
    assert!(
        args.contains(&"--continue".to_owned()),
        "prior conversation history exists: must fall back to --continue: {args:?}"
    );
}

#[test]
fn compose_inplace_args_carries_prompt_file_unquoted() {
    // #4336: the in-place relaunch execs claude directly — no shell splits
    // this argv — so the prompt path must be its OWN token and must NOT be
    // shell-quoted the way `prompt_file_flag` quotes it for the pane-string
    // paths. A path with a space is the case that would break if the quoting
    // helper were reused here.
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path().join("workspace-prompt");
    std::fs::create_dir_all(&cwd).unwrap();
    let prompt = tmp.path().join("system prompt.txt");
    std::fs::write(&prompt, "PM").unwrap();

    let args = compose_inplace_args(&cwd, None, None, Some(&prompt));

    let idx = args
        .iter()
        .position(|a| a == "--append-system-prompt-file")
        .expect("prompt flag must be present");
    assert_eq!(
        args[idx + 1],
        prompt.display().to_string(),
        "the path must be a single, UNQUOTED argv token: {args:?}"
    );
    assert!(
        !args[idx + 1].contains('\''),
        "shell quoting must not leak into an execv argv token: {args:?}"
    );
    assert!(
        args.contains(&"--dangerously-skip-permissions".to_owned()),
        "the isolation flags must still follow the prompt file: {args:?}"
    );
}

#[test]
fn compose_inplace_args_omits_prompt_flag_when_absent() {
    // A prompt-file write failure is non-fatal: the flag is omitted rather
    // than passed with an empty path (which claude would fail to open).
    let tmp = tempfile::tempdir().expect("tempdir");
    let args = compose_inplace_args(tmp.path(), None, None, None);
    assert!(
        !args.contains(&"--append-system-prompt-file".to_owned()),
        "no prompt file → no flag: {args:?}"
    );
    assert!(
        args.contains(&"--setting-sources".to_owned()),
        "isolation flags are unconditional: {args:?}"
    );
}

#[test]
fn compose_inplace_args_loads_the_user_tier_when_config_dir_is_relocated() {
    // #4451: the in-place relaunch (bare `tm` inside a managed pane) is a
    // third spawn path with its own argv builder — it must pick the same
    // relocated-tier flag, or a relaunched session silently loses every
    // bundled specialist the pane had before.
    let tmp = tempfile::tempdir().expect("tempdir");
    let cwd = tmp.path().join("workspace-inplace-tier");
    std::fs::create_dir_all(&cwd).unwrap();
    let config_dir = tmp.path().join("claude-config");

    let relocated = compose_inplace_args(&cwd, Some(&config_dir), None, None);
    let idx = relocated
        .iter()
        .position(|a| a == "--setting-sources")
        .expect("setting-sources flag must be present");
    assert_eq!(
        relocated[idx + 1],
        "user,project,local",
        "relocated in-place relaunch must load the tm-owned `user` tier: {relocated:?}"
    );

    let ambient = compose_inplace_args(&cwd, None, None, None);
    let idx = ambient
        .iter()
        .position(|a| a == "--setting-sources")
        .expect("setting-sources flag must be present");
    assert_eq!(
        ambient[idx + 1],
        "project,local",
        "without a relocated config dir the #1269 exclusion stands: {ambient:?}"
    );
}

#[serial_test::serial]
#[test]
fn build_inplace_resume_command_carries_prompt_file() {
    // #4336: the PM persona must reach the in-place relaunch through the same
    // `build_prompt_file` carrier `spawn`/`spawn_resume` use. Requires a real
    // claude install (resolve_claude gates the builder); skip otherwise.
    let _home = HomeGuard::set();
    if ClaudeCodeAdapter::resolve_claude().is_none() {
        return;
    }
    let tmp = tempfile::tempdir().expect("tempdir");
    let result = build_inplace_resume_command(tmp.path(), None).expect("build succeeds");
    let idx = result
        .args
        .iter()
        .position(|a| a == "--append-system-prompt-file")
        .expect("in-place relaunch must carry the PM system prompt");
    assert!(
        std::path::Path::new(&result.args[idx + 1]).is_file(),
        "the prompt token must name a written file: {:?}",
        result.args
    );
}

#[serial_test::serial]
#[test]
fn build_inplace_resume_command_resolves_claude_binary() {
    // Integration-style check that build_inplace_resume_command wires
    // resolve_claude + prepare_managed_config + compose_inplace_args
    // together; the pure selection logic is covered exhaustively above
    // without needing a real claude binary.
    let _home = HomeGuard::set();
    let Some(claude_bin) = ClaudeCodeAdapter::resolve_claude() else {
        return;
    };
    let tmp = tempfile::tempdir().expect("tempdir");
    let result = build_inplace_resume_command(tmp.path(), Some("some-id")).expect("build succeeds");
    assert_eq!(result.claude_bin, claude_bin);
    assert!(
        result.args.contains(&"--setting-sources".to_owned()),
        "isolation flags must be present: {:?}",
        result.args
    );
}

#[serial_test::serial]
#[test]
fn build_inplace_resume_command_carries_oauth_token_when_available() {
    // #2246: the in-place relaunch (bare-`tm` inside a managed pane) must
    // carry the same resolved oauth token as the tmux-pane spawn/resume
    // paths, so the caller (guided_inplace.rs) can set the env var on the
    // relaunched process the same way it already does for CLAUDE_CONFIG_DIR.
    let _home = HomeGuard::set();
    if ClaudeCodeAdapter::resolve_claude().is_none() {
        return;
    }
    unsafe {
        std::env::set_var(
            crate::core::oauth_token::OAUTH_TOKEN_ENV_VAR,
            "sk-ant-oat01-fake-token",
        );
    }
    let tmp = tempfile::tempdir().expect("tempdir");
    let result = build_inplace_resume_command(tmp.path(), None);
    unsafe {
        std::env::remove_var(crate::core::oauth_token::OAUTH_TOKEN_ENV_VAR);
    }
    let result = result.expect("build succeeds");
    assert_eq!(
        result.oauth_token.as_deref(),
        Some("sk-ant-oat01-fake-token")
    );
}

/// Issue #3950 residual-gap fix, critic follow-up: `prepare_managed_config`
/// used to trust `trusty-mpm`/`trusty-review` unconditionally and
/// `trusty-memory`/`trusty-search` off a bare manifest-toggle read — none of
/// the four reflected whether this run's write actually succeeded. It now
/// pins all four itself and derives `enabledMcpjsonServers` from their real
/// `Result`s (mirroring `session_launch::prepare_session_inner`).
///
/// Why: this is the complementary non-regression case for
/// `prepare_managed_config_excludes_builtins_when_mcp_json_write_fails`
/// below — a normal, unobstructed run must still pin and approve all four,
/// proving the fix does not over-correct into never trusting them. `HOME` is
/// redirected (serial) so the managed `<config_dir>/.claude.json` this
/// exercises is a throwaway tempdir, not the developer's real
/// `~/.trusty-tools`.
/// What: calls `prepare_managed_config` directly against a clean `cwd` and
/// asserts (1) all four canonical entries are written to `cwd/.mcp.json`,
/// and (2) all four names appear in the resolved config dir's
/// `.claude.json` `enabledMcpjsonServers` for `cwd`.
/// Test: itself; `prepare_managed_config_excludes_builtins_when_mcp_json_write_fails`
/// covers the write-failure regression.
#[serial_test::serial]
#[test]
fn prepare_managed_config_pins_all_builtins_on_success() {
    let _home = HomeGuard::set();
    let cwd_root = tempfile::tempdir().expect("tempdir");
    let cwd = cwd_root.path();

    let config_dir = prepare_managed_config("test-session", cwd)
        .expect("prepare_managed_config must resolve a config dir under the redirected HOME");

    let mcp: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(cwd.join(".mcp.json"))
            .expect("prepare_managed_config must write cwd/.mcp.json"),
    )
    .expect("cwd/.mcp.json must be valid JSON");
    for name in [
        "trusty-mpm",
        "trusty-review",
        "trusty-memory",
        "trusty-search",
    ] {
        assert_eq!(
            mcp["mcpServers"][name]["command"],
            serde_json::json!(name),
            "{name} must be pinned to its canonical command on a clean run: {mcp}"
        );
    }

    let value: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(config_dir.join(".claude.json"))
            .expect("prepare_managed_config must write <config_dir>/.claude.json"),
    )
    .expect("<config_dir>/.claude.json must be valid JSON");
    let key = cwd.to_string_lossy().to_string();
    let enabled: Vec<&str> = value["projects"][&key]["enabledMcpjsonServers"]
        .as_array()
        .expect("enabledMcpjsonServers is an array")
        .iter()
        .filter_map(|v| v.as_str())
        .collect();
    for name in [
        "trusty-mpm",
        "trusty-review",
        "trusty-memory",
        "trusty-search",
    ] {
        assert!(
            enabled.contains(&name),
            "{name} must be approved when its pin succeeds on a clean run: {enabled:?}"
        );
    }
}

/// Issue #4181, code-critic HIGH on PR #5070: the SECOND `.mcp.json` write
/// site must git-exclude the file too.
///
/// Why: `prepare_session_inner` is not the only place the four injectors run.
/// `prepare_managed_config` re-runs all four on every spawn/resume, and two of
/// its three callers reach it with no `prepare_session*` anywhere in their
/// chain — `spawn_resume` (see `claude_code.rs`'s own doc: "NO corresponding
/// `prepare_session*` call anywhere in its own request chain") and
/// `build_inplace_resume_command` (`guided_inplace.rs`, "the THIRD entry
/// point … it calls neither of those two"). Before this fix those paths wrote
/// a machine-specific `.mcp.json` into a git workspace with no exclusion, so
/// every resume re-dirtied a tracked file — the exact defect PR #5070 exists
/// to close, reachable by the two paths it originally missed.
/// What: `git init`s `cwd`, calls `prepare_managed_config` directly, and
/// asserts `.git/info/exclude` names `.mcp.json` afterwards. Deliberately
/// asserts on the exclude file rather than on `git status`, because the point
/// is that the guard RAN on this path, not that a fresh tempdir happens to be
/// clean.
/// Test: itself; the guard's own behavior is pinned by
/// `core::session_launch::native_mcp_tests::ensure_git_excluded_adds_mcp_json`.
#[serial_test::serial]
#[test]
fn prepare_managed_config_excludes_mcp_json_from_git() {
    let _home = HomeGuard::set();
    let cwd_root = tempfile::tempdir().expect("tempdir");
    let cwd = cwd_root.path();
    let status = std::process::Command::new("git")
        .arg("init")
        .arg("-q")
        .arg(cwd)
        .status()
        .expect("git must be on PATH to run this test");
    assert!(status.success(), "git init failed");

    prepare_managed_config("test-session", cwd)
        .expect("prepare_managed_config must resolve a config dir under the redirected HOME");

    let exclude = std::fs::read_to_string(cwd.join(".git").join("info").join("exclude"))
        .expect("git init must create .git/info/exclude");
    assert!(
        exclude.lines().any(|l| l.trim() == ".mcp.json"),
        "prepare_managed_config must git-exclude .mcp.json before the injectors write it \
         (#4181) — the resume paths reach this function with no prepare_session; \
         exclude file was:\n{exclude}"
    );
}

/// Issue #3950 residual-gap fix (code-critic HIGH follow-up on PR #3951).
///
/// Why: the critic traced every production caller of `RuntimeAdapter::spawn`/
/// `spawn_resume` and found `resume_managed`/`spawn_resume` reaches
/// `prepare_managed_config` with ZERO `prepare_session*` call anywhere in
/// that request's chain (see that function's own doc: "the broader prep
/// pipeline … is intentionally NOT re-run here") — so the pre-fix hardcoded
/// `true, true` (unconditional pair) and bare manifest-toggle read
/// (conditional pair) asserted pinning with NO same-run evidence at all on
/// the headless resume path, the sharpest case across all five instances of
/// this vulnerability class. This test forces a REAL write failure — not a
/// mocked boolean — by making `cwd/.mcp.json` an existing DIRECTORY before
/// calling `prepare_managed_config`: `settings::inject_mcp_server`'s shared
/// `std::fs::write` then fails with a genuine IO error (`Is a directory`)
/// regardless of permission bits, exactly mirroring
/// `session_launch::tests_mcp_trust_seed_e2e::prepare_session_excludes_all_builtins_from_trust_when_mcp_json_write_fails`
/// and `standalone::load::tests::load_alias_excludes_builtins_from_managed_trust_when_mcp_json_write_fails`
/// — this is the third and last of the three call sites that derive
/// `enabledMcpjsonServers` membership, now all covered by the identical
/// regression shape.
/// What: asserts none of the four builtin names appear in the resolved
/// config dir's `.claude.json` `enabledMcpjsonServers` for `cwd` after a
/// forced write failure — `prepare_managed_config` itself must still
/// succeed (return `Some(config_dir)`), since a pin failure is non-fatal to
/// launch.
/// Test: itself; `prepare_managed_config_pins_all_builtins_on_success`
/// covers the complementary non-regression case.
#[serial_test::serial]
#[test]
fn prepare_managed_config_excludes_builtins_when_mcp_json_write_fails() {
    let _home = HomeGuard::set();
    let cwd_root = tempfile::tempdir().expect("tempdir");
    let cwd = cwd_root.path();
    // Force EVERY builtin injector's write to fail: `.mcp.json` is a
    // directory, not a file — all four share this one file via
    // `settings::inject_mcp_server`'s read-merge-write helper.
    std::fs::create_dir_all(cwd.join(".mcp.json")).expect("mkdir .mcp.json");

    let config_dir = prepare_managed_config("test-session", cwd).expect(
        "prepare_managed_config must still resolve a config dir even when every pin write fails",
    );

    let value: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(config_dir.join(".claude.json"))
            .expect("prepare_managed_config must write <config_dir>/.claude.json"),
    )
    .expect("<config_dir>/.claude.json must be valid JSON");
    let key = cwd.to_string_lossy().to_string();
    let enabled: Vec<&str> = value["projects"][&key]["enabledMcpjsonServers"]
        .as_array()
        .expect("enabledMcpjsonServers is an array")
        .iter()
        .filter_map(|v| v.as_str())
        .collect();
    for name in [
        "trusty-mpm",
        "trusty-review",
        "trusty-memory",
        "trusty-search",
    ] {
        assert!(
            !enabled.contains(&name),
            "{name} must not be approved when its pin write failed this run \
             (headless resume path, no human to decline a consent dialog): {enabled:?}"
        );
    }
}

// ─── issue #4206: the trust seed must stay inside the redirected $HOME ────

/// RAII guard that prepends `dir` to `PATH` and restores it on drop.
struct PathGuard {
    prev: Option<std::ffi::OsString>,
}
impl PathGuard {
    fn prepend(dir: &Path) -> Self {
        let prev = std::env::var_os("PATH");
        let mut entries = vec![dir.to_path_buf()];
        if let Some(ref p) = prev {
            entries.extend(std::env::split_paths(p));
        }
        let joined = std::env::join_paths(entries).expect("join PATH");
        // SAFETY: callers are #[serial].
        unsafe { std::env::set_var("PATH", joined) };
        Self { prev }
    }
}
impl Drop for PathGuard {
    fn drop(&mut self) {
        match self.prev.take() {
            Some(v) => unsafe { std::env::set_var("PATH", v) },
            None => unsafe { std::env::remove_var("PATH") },
        }
    }
}

/// Every `.claude.json` found anywhere beneath `root`.
///
/// Why (issue #4206): the leak assertion must catch the seeded config wherever
/// it lands under a redirected `$HOME`, not only at the one path the current
/// resolver happens to compute — a future refactor that moved the managed dir
/// would otherwise silently stop being covered.
/// What: a depth-bounded recursive walk (symlinks are not followed, so a
/// self-referential link cannot spin), returning display paths.
fn find_claude_json_files(root: &Path) -> Vec<String> {
    fn walk(dir: &Path, depth: usize, out: &mut Vec<String>) {
        if depth > 8 {
            return;
        }
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let Ok(meta) = std::fs::symlink_metadata(&path) else {
                continue;
            };
            if meta.is_dir() {
                walk(&path, depth + 1, out);
            } else if entry.file_name() == std::ffi::OsStr::new(".claude.json") {
                out.push(path.display().to_string());
            }
        }
    }
    let mut out = Vec::new();
    walk(root, 0, &mut out);
    out
}

/// Plant an executable stub named `claude` in `dir` and return its directory.
///
/// Why: `ClaudeCodeAdapter::spawn_resume` calls `resolve_claude()` FIRST and
/// returns `BinaryNotFound` before ever reaching `prepare_managed_config`. The
/// pre-existing tests in this file handle that with
/// `if resolve_claude().is_none() { return; }` — a silent skip that makes them
/// vacuous on any machine without Claude Code installed (most CI runners).
/// A leak test that can silently pass by not running is worse than no test, so
/// this plants a stub and prepends its directory to `PATH`
/// (`bin_resolve::resolve_binary` honours the live `PATH` first), guaranteeing
/// the spawn path is actually entered on every platform.
#[cfg(unix)]
fn plant_fake_claude(dir: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let bin = dir.join("claude");
    std::fs::write(&bin, b"#!/bin/sh\nexit 0\n").expect("write fake claude");
    std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755))
        .expect("chmod fake claude");
}

// Issue #4206 TEST 1 — THE ISOLATION INVARIANT, locked at the REAL call chain
// (`ClaudeCodeAdapter::spawn_resume` → `prepare_managed_config` →
// `preseed_managed_trust`): with `$HOME` redirected, trust seeding must write
// NOTHING outside that redirected `$HOME`.
//
// Why this test exists, and what the #4206 investigation actually established:
// the reported root cause was that `managed_claude_config_dir()` "takes no
// injectable base". That is NOT correct. It resolves via `dirs::home_dir()`,
// which reads `$HOME` on Unix — so `$HOME` IS the injectable base, and
// redirecting it genuinely confines the seeder (proven by running this very
// test against unpatched code: the seed landed in the redirected temp home,
// not the operator's real one). There is no production defect here; a daemon
// running with the operator's real `$HOME` correctly targets the operator's
// real config dir.
//
// The actual defect was TEST HYGIENE: several tests reach this production
// seeding path without redirecting `$HOME` at all, so they wrote straight into
// `~/.trusty-tools/trusty-mpm/claude-config/.claude.json` — which is how 2,443
// `tempfile::TempDir` entries accumulated there. Those tests are fixed in this
// same change (`daemon::managed_routes::lifecycle_tests`,
// `tests/session_manager_mvp.rs`); this test locks the invariant they were
// missing, at the layer they all funnel through, so the next test to drive
// `spawn`/`spawn_resume` has an executable statement of the rule.
//
// Note the pre-existing isolation test
// (`standalone::trust_seed_tests::test_preseed_managed_trust_no_home_write`)
// calls `preseed_managed_trust` DIRECTLY with an explicit `claude_config_dir`,
// so it can never observe what the production call chain resolves. Only a test
// that enters through `spawn_resume` covers that resolution step.
#[serial_test::serial]
#[test]
#[cfg(unix)]
fn spawn_resume_trust_seed_stays_within_redirected_home() {
    let home = tempfile::tempdir().expect("home tempdir");
    let bindir = tempfile::tempdir().expect("bin tempdir");
    let workspace = tempfile::tempdir().expect("workspace tempdir");

    plant_fake_claude(bindir.path());
    let _path = PathGuard::prepend(bindir.path());

    // Redirect HOME to an EMPTY dir — the isolation seam every test that
    // drives this path must use.
    let prev_home = std::env::var_os("HOME");
    // SAFETY: #[serial].
    unsafe { std::env::set_var("HOME", home.path()) };
    struct RestoreHome(Option<std::ffi::OsString>);
    impl Drop for RestoreHome {
        fn drop(&mut self) {
            match self.0.take() {
                Some(v) => unsafe { std::env::set_var("HOME", v) },
                None => unsafe { std::env::remove_var("HOME") },
            }
        }
    }
    let _home_guard = RestoreHome(prev_home);

    // The managed dir this run must resolve to, derived the same way
    // production does, AFTER the redirect above.
    let base = crate::core::trusty_tools_config::managed_claude_config_dir()
        .expect("managed config dir resolves under the redirected HOME");
    assert!(
        base.starts_with(home.path()),
        "precondition: the resolved managed dir must sit under the redirected \
         HOME, else this test is not isolated at all (resolved {})",
        base.display()
    );

    // Sanity: the binary really is resolvable, so the spawn path below is
    // genuinely entered and this test can never pass by skipping.
    assert!(
        ClaudeCodeAdapter::resolve_claude().is_some(),
        "fake claude must be resolvable on PATH — otherwise this test is vacuous"
    );

    let fake = FakeTmux::new();
    let adapter = ClaudeCodeAdapter::new(fake.clone());
    adapter
        .spawn_resume(
            "tmpm-4206",
            None,
            workspace.path(),
            "task",
            None,
            TEST_SESSION_ID,
            &[],
        )
        .expect("spawn_resume must succeed against the fake tmux");

    // THE ISOLATION ASSERTION: every `.claude.json` written by this run must
    // sit under the redirected $HOME — none anywhere else.
    //
    // Scoped to `.claude.json` rather than "HOME is empty": other, unrelated
    // parts of the launch path legitimately resolve under `$HOME` (the
    // framework roster at `~/.trusty-mpm/framework`, and macOS's own
    // `~/Library` caches). Those are out of scope; asserting on them would
    // make this test fail for reasons unrelated to the config leak.
    let found = find_claude_json_files(home.path());
    assert!(
        found.iter().all(|p| Path::new(p).starts_with(home.path())),
        "every seeded .claude.json must live under the redirected HOME: {found:?}"
    );

    // Positive counterpart: the seed really did happen, at the resolved
    // managed dir. Without this the test could pass simply by never seeding
    // anything — the exact way an isolation test goes vacuous.
    let seeded = base.join(".claude.json");
    let text = std::fs::read_to_string(&seeded).unwrap_or_else(|e| {
        panic!(
            ".claude.json must be seeded at the resolved managed dir {}: {e}",
            seeded.display()
        )
    });
    let val: serde_json::Value = serde_json::from_str(&text).expect("seeded config is valid JSON");
    let key = workspace.path().to_string_lossy().to_string();
    assert_eq!(
        val["projects"][&key]["hasTrustDialogAccepted"],
        serde_json::Value::Bool(true),
        "the workspace must actually be trust-seeded under the redirected HOME: {text}"
    );
}