trusty-mpm 1.8.2

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

use clap::Parser;

use crate::cli::{AuthAction, Cli, Command, RepairAction, ServicesAction, SessctlAction};
use crate::commands::session::{
    instructions::compose_session_instructions,
    instructions::compose_session_instructions_with_roster,
};
// #6542: the private tmux server every guided-fallback run launches onto, and
// the default-server watch that proves nothing reached the operator's.
use crate::test_support::tmux_session::{
    FixtureTmuxSessions, PrivateTmuxServer, ScratchTmuxSession,
};

/// What one guided-fallback run returned, and what it left on its private
/// tmux server before that server was killed (#6542).
pub(crate) struct FallbackRun {
    pub(crate) result: anyhow::Result<()>,
    /// Sessions alive on the private server when the fallback returned.
    pub(crate) private_sessions: Vec<String>,
    /// The `-L` socket the run used; its server is gone once this is returned.
    pub(crate) socket: String,
}

/// The one way a `tm`-bin test drives the guided fallback (#6542).
///
/// Why: the fallback launches a REAL tmux session, named from a uuid the test
/// never sees, through a dozen call sites that each resolve the tmux binary
/// themselves. A reap-afterwards guard on the shared default server leaked that
/// session onto the operator's live server whenever the reap missed.
/// What: runs `fallback_protected_gated` inside
/// [`trusty_mpm::core::tmux::with_tmux_binary`] with a `tmux -L <private>`
/// shim, so every tmux call the fallback makes lands on a server this call
/// owns. It records that server's sessions, then kills the whole server on
/// every exit path, panic and cancellation included.
/// `every_guided_fallback_call_runs_on_a_private_tmux_server` fails any test
/// that calls the fallback without this wrapper.
/// Test: `guided_fallback_leaves_no_tmux_session_behind`.
pub(crate) async fn run_fallback(
    client: &reqwest::Client,
    url: &str,
    cwd: &std::path::Path,
    gate: &trusty_mpm::core::disk_usage_guard::DiskGate,
    home: Option<&std::path::Path>,
) -> FallbackRun {
    let server = PrivateTmuxServer::new(&fallback_tmux_bin(), "fallback");
    let result = trusty_mpm::core::tmux::with_tmux_binary(
        server.shim_bin().into(),
        crate::commands::guided::fallback_protected_gated(client, url, cwd, gate, home),
    )
    .await;
    let private_sessions = server
        .query(&["list-sessions", "-F", "#{session_name}"])
        .map(|out| out.lines().map(str::to_string).collect())
        .unwrap_or_default();
    FallbackRun {
        result,
        private_sessions,
        socket: server.name().to_string(),
    }
}

/// [`run_fallback`] with `fallback_protected`'s own disk gate and a scratch home.
///
/// #8994: the home is a scratch directory, not the process home — a fallback
/// that reaches worktree creation opens the worktree ledger under it, and a
/// test must never write the operator's `~/.trusty-mpm/worktrees.jsonl`.
pub(crate) async fn run_fallback_default(
    client: &reqwest::Client,
    url: &str,
    cwd: &std::path::Path,
) -> anyhow::Result<()> {
    let gate = trusty_mpm::core::disk_usage_guard::DiskGate::MeasureTarget;
    let home = crate::test_support::hermetic_temp_dir();
    run_fallback(client, url, cwd, &gate, Some(home.path()))
        .await
        .result
}

/// A disk gate pinned to an empty mount, for the fallback tests that provision
/// a worktree (#7603).
///
/// Why: `fallback_protected` gates the worktree it provisions against the REAL
/// mount and the operator's REAL `disk.max_usage_pct`, so the three tests below
/// went red — asserting nothing about disk — once this host crossed 90%.
/// `$HOME` cannot be redirected from a `tm`-bin test (`env_isolation_tests.rs`
/// bans writing it), so the measurement is injected instead. The refusing
/// direction is pinned in `managed_workspace_tests.rs`, so this file only needs
/// the allowing one.
/// What: a synthetic mount at 0.0%, below every threshold
/// `resolve_max_usage_pct` accepts (`1..=100`).
/// Test: used by the three `guided_fallback_*` tests that expect a worktree.
fn empty_disk() -> trusty_mpm::core::disk_usage_guard::DiskGate {
    trusty_mpm::core::disk_usage_guard::DiskGate::Pinned(Some(
        trusty_mpm::core::disk_usage_guard::MeasuredMount {
            mount_point: "/fixture-mount".to_string(),
            usage_pct: 0.0,
            bytes: None,
        },
    ))
}

#[test]
fn cli_parses_attach() {
    let cli = Cli::try_parse_from(["trusty-mpm", "attach", "frontend"]).unwrap();
    match cli.command.unwrap() {
        Command::Attach {
            target,
            json,
            single_pane,
        } => {
            assert_eq!(target, "frontend");
            assert!(!json);
            // #6483: no flag means the multipane dashboard.
            assert!(!single_pane);
        }
        other => panic!("expected Attach, got {other:?}"),
    }
}

#[test]
fn cli_parses_attach_with_json() {
    let cli = Cli::try_parse_from(["trusty-mpm", "attach", "abc-123", "--json"]).unwrap();
    match cli.command.unwrap() {
        Command::Attach { target, json, .. } => {
            assert_eq!(target, "abc-123");
            assert!(json);
        }
        other => panic!("expected Attach, got {other:?}"),
    }
}

#[test]
fn cli_parses_attach_single_pane_opt_in() {
    // #6483: the pre-existing single-pane coordinator chat stays reachable
    // through an explicit opt-in flag.
    let cli = Cli::try_parse_from(["trusty-mpm", "attach", "frontend", "--single-pane"]).unwrap();
    match cli.command.unwrap() {
        Command::Attach { single_pane, .. } => assert!(single_pane),
        other => panic!("expected Attach, got {other:?}"),
    }
}

#[test]
fn cli_attach_requires_target() {
    assert!(Cli::try_parse_from(["trusty-mpm", "attach"]).is_err());
}

#[test]
fn cli_parses_connect() {
    // `tm connect` is the live-checkout session starter; it takes an
    // optional project directory, exactly like `tm launch`.
    let cli = Cli::try_parse_from(["trusty-mpm", "connect"]).unwrap();
    match cli.command.unwrap() {
        Command::Connect { dir } => assert_eq!(dir, None),
        other => panic!("expected Connect, got {other:?}"),
    }
    // Issue #2230: `connect` must carry the same PM system-prompt +
    // isolation-flag carrier every other launch path has — no more bare
    // `claude --dangerously-skip-permissions` with nothing injected.
    assert_connect_claude_cmd_carries_persona_flags();
}

#[test]
fn cli_parses_connect_with_dir() {
    let cli = Cli::try_parse_from(["trusty-mpm", "connect", "/work/p"]).unwrap();
    match cli.command.unwrap() {
        Command::Connect { dir } => assert_eq!(dir.as_deref(), Some("/work/p")),
        other => panic!("expected Connect, got {other:?}"),
    }
    assert_connect_claude_cmd_carries_persona_flags();
}

/// Assert `connect`'s composed `claude` invocation carries both the injected
/// PM system prompt and the shared session-isolation flag (issue #2230).
///
/// Why: `crate::commands::launch::connect_claude_spec` is the exact function
/// `connect()` calls to build the launch spec sent to the pane; asserting
/// on it directly proves the wiring without needing a live daemon/tmux to
/// drive the full async `connect()` end-to-end.
fn assert_connect_claude_cmd_carries_persona_flags() {
    let path = std::path::Path::new("/tmp/trusty-mpm-connect-test-prompt.txt");

    // #4181: `connect` now relocates `CLAUDE_CONFIG_DIR` when the tm-owned config
    // home resolves, and falls back to the pre-#4181 shape when it does not.
    // Both shapes must carry the prompt and an isolation flag, so assert on both
    // rather than narrowing this to whichever one the test machine happens to
    // produce.
    // #8308: the seam returns a spec; `spec_text` renders it for substrings.
    let spec = |dir| {
        let cwd = std::path::Path::new("/work/p");
        let spec =
            crate::commands::launch::connect_claude_spec(cwd, Some(path), dir, &[], None, None);
        crate::test_support::spec_text(&spec)
    };
    let fallback = spec(None);
    assert!(
        fallback.contains("--append-system-prompt-file"),
        "connect claude_cmd must inject the PM system prompt file: {fallback}"
    );
    assert!(
        fallback.contains("--setting-sources project,local"),
        "with no config dir the user tier is the operator's own ~/.claude and \
         must stay excluded (#1269): {fallback}"
    );

    let dir = std::path::Path::new("/tm/claude-config");
    let relocated = spec(Some(dir));
    assert!(
        relocated.contains("--append-system-prompt-file"),
        "connect claude_cmd must inject the PM system prompt file: {relocated}"
    );
    assert!(
        relocated.contains("CLAUDE_CONFIG_DIR=/tm/claude-config "),
        "the relocated shape must redirect the user tier to the tm-owned home: \
         {relocated}"
    );
    assert!(
        relocated.contains("--setting-sources user,project,local"),
        "the relocated shape loads the user tier it just redirected: {relocated}"
    );
}

#[test]
fn cli_sm_aliases_reach_coordinator() {
    // DOC-14 D0.2: `tm coordinator`, `tm sm`, `tm session-manager`, and the
    // hidden `tm coord` must all parse to the SAME `Command::Coordinator`, so
    // every spelling reaches one code path.
    for name in ["coordinator", "sm", "session-manager", "coord"] {
        let cli = Cli::try_parse_from(["trusty-mpm", name, "hello there"])
            .unwrap_or_else(|e| panic!("`tm {name}` must parse: {e}"));
        match cli.command.unwrap() {
            Command::Coordinator { message, action } => {
                assert_eq!(
                    message.as_deref(),
                    Some("hello there"),
                    "`tm {name}` carries the message"
                );
                assert!(action.is_none(), "a plain message has no subcommand");
            }
            other => panic!("`tm {name}` must be Command::Coordinator, got {other:?}"),
        }
    }
}

/// DOC-14 SM-STDIO (#1291): `tm sm serve --stdio` (and via every coordinator
/// alias) must parse to `Command::Coordinator` with the `Serve { stdio: true }`
/// subcommand — the JSON-RPC over STDIO adapter entry point.
#[test]
fn cli_parses_sm_serve_stdio() {
    use crate::cli::CoordinatorAction;
    for name in ["coordinator", "sm", "session-manager", "coord"] {
        let cli = Cli::try_parse_from(["trusty-mpm", name, "serve", "--stdio"])
            .unwrap_or_else(|e| panic!("`tm {name} serve --stdio` must parse: {e}"));
        match cli.command.unwrap() {
            Command::Coordinator { message, action } => {
                assert!(message.is_none(), "the serve subcommand carries no message");
                match action {
                    Some(CoordinatorAction::Serve { stdio }) => {
                        assert!(stdio, "--stdio sets the stdio flag");
                    }
                    other => panic!("`tm {name} serve` must be Serve, got {other:?}"),
                }
            }
            other => panic!("`tm {name} serve` must be Command::Coordinator, got {other:?}"),
        }
    }
}

#[test]
fn cli_parses_daemon_custom_addr() {
    let cli = Cli::try_parse_from(["trusty-mpm", "daemon", "--addr", "0.0.0.0:9000"]).unwrap();
    match cli.command.unwrap() {
        Command::Daemon { addr, .. } => assert_eq!(addr.to_string(), "0.0.0.0:9000"),
        other => panic!("expected Daemon, got {other:?}"),
    }
}

// ── tm services subcommand parse tests (issue #339) ──────────────────────

#[test]
fn cli_parses_services_list() {
    let cli = Cli::try_parse_from(["trusty-mpm", "services", "list"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Services {
            action: ServicesAction::List { json: false }
        }
    ));
}

#[test]
fn cli_parses_services_list_json() {
    let cli = Cli::try_parse_from(["trusty-mpm", "services", "list", "--json"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Services {
            action: ServicesAction::List { json: true }
        }
    ));
}

#[test]
fn cli_parses_services_status() {
    let cli = Cli::try_parse_from(["trusty-mpm", "services", "status", "trusty-search"]).unwrap();
    match cli.command.unwrap() {
        Command::Services {
            action: ServicesAction::Status { name, json },
        } => {
            assert_eq!(name, "trusty-search");
            assert!(!json);
        }
        other => panic!("expected services status, got {other:?}"),
    }
}

#[test]
fn cli_parses_services_status_json() {
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "services",
        "status",
        "trusty-search",
        "--json",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Services {
            action: ServicesAction::Status { name, json },
        } => {
            assert_eq!(name, "trusty-search");
            assert!(json);
        }
        other => panic!("expected services status --json, got {other:?}"),
    }
}

#[test]
fn cli_parses_services_port() {
    let cli = Cli::try_parse_from(["trusty-mpm", "services", "port", "trusty-search"]).unwrap();
    match cli.command.unwrap() {
        Command::Services {
            action: ServicesAction::Port { name },
        } => assert_eq!(name, "trusty-search"),
        other => panic!("expected services port, got {other:?}"),
    }
}

#[test]
fn cli_parses_services_url() {
    let cli = Cli::try_parse_from(["trusty-mpm", "services", "url", "trusty-search"]).unwrap();
    match cli.command.unwrap() {
        Command::Services {
            action: ServicesAction::Url { name },
        } => assert_eq!(name, "trusty-search"),
        other => panic!("expected services url, got {other:?}"),
    }
}

#[test]
fn cli_parses_services_health() {
    let cli = Cli::try_parse_from(["trusty-mpm", "services", "health", "trusty-search"]).unwrap();
    match cli.command.unwrap() {
        Command::Services {
            action: ServicesAction::Health { name },
        } => assert_eq!(name, "trusty-search"),
        other => panic!("expected services health, got {other:?}"),
    }
}

#[test]
fn cli_parses_services_log() {
    let cli = Cli::try_parse_from(["trusty-mpm", "services", "log", "trusty-search"]).unwrap();
    match cli.command.unwrap() {
        Command::Services {
            action: ServicesAction::Log { name },
        } => assert_eq!(name, "trusty-search"),
        other => panic!("expected services log, got {other:?}"),
    }
}

#[test]
fn cli_parses_services_init() {
    let cli = Cli::try_parse_from(["trusty-mpm", "services", "init"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Services {
            action: ServicesAction::Init { force: false }
        }
    ));
}

#[test]
fn cli_parses_services_init_force() {
    let cli = Cli::try_parse_from(["trusty-mpm", "services", "init", "--force"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Services {
            action: ServicesAction::Init { force: true }
        }
    ));
}

#[test]
fn cli_parses_services_restart() {
    let cli = Cli::try_parse_from(["trusty-mpm", "services", "restart", "trusty-search"]).unwrap();
    match cli.command.unwrap() {
        Command::Services {
            action: ServicesAction::Restart { name },
        } => assert_eq!(name, "trusty-search"),
        other => panic!("expected services restart, got {other:?}"),
    }
}

// ------------------------------------------------------------------
// Regression tests for issue #382: compose_session_instructions must
// display exactly what it stashes and what the live launch prompt is.
// ------------------------------------------------------------------

/// A fixture agent roster, rendered exactly as the live tiers would render it.
///
/// Why (#5544, #4937): the two convergence tests below compare two independently
/// composed prompts, and each composition rescanned the agent roster from tiers
/// rooted in `$HOME` and `$CLAUDE_CONFIG_DIR` — machine-global mutable state, so
/// the two scans could legitimately disagree and the `assert_eq!` failed with a
/// message indistinguishable from a real prompt regression. On this workstation
/// `~/.claude/agents` is the only tier carrying `copyeditor`, `pangram-editor`,
/// `proofreader`, `writer` and `writing-critic`, which is why the diff was
/// always those exact five names and why CI — which has no ambient tier at all —
/// never reproduced it.
///
/// The previous revision pinned `$HOME` and `$CLAUDE_CONFIG_DIR` around the test
/// and took `#[serial]`. That treated the symptom with the disease: a process
/// env write is visible to EVERY test in this binary for its whole duration, and
/// `#[serial]` excludes only other `#[serial]` tests. Injecting one roster into
/// both sides of the comparison removes the shared global entirely, so these
/// tests neither write env nor need serialising.
/// What: seeds one agent into a tempdir tier and renders it through
/// `roster_section_from_dirs` — the same function the live path uses — returning
/// the rendered `## Delegation Authority` block. The `TempDir` is returned so the
/// caller keeps it alive.
/// Test: used by `compose_session_instructions_display_matches_live_prompt` and
/// `compose_session_instructions_display_matches_live_prompt_with_override`.
fn fixture_roster_section() -> (tempfile::TempDir, String) {
    let tiers = tempfile::tempdir().expect("fixture tier root");
    let agents = tiers.path().join("agents");
    std::fs::create_dir_all(&agents).expect("fixture tier");
    // One agent, so the roster-present composer path is the one under test —
    // the same branch the ambient roster used to select.
    std::fs::write(
        agents.join("engineer.md"),
        "---\nname: engineer\nrole: engineer\nmodel: sonnet\n---\n\n# Engineer\n",
    )
    .expect("seed fixture agent");

    let section = trusty_mpm::core::delegation_authority::roster_section_from_dirs(&[agents])
        .expect("a seeded tier renders a roster section");
    (tiers, section)
}

#[test]
fn compose_session_instructions_display_matches_stash() {
    // Why: the #382 bug was that `tm session instructions` printed
    // `output.merged` (old pipeline text) while the stash held the
    // override-resolved PM prompt — a visible divergence. After the fix
    // both come from `resolve_pm_prompt`, so they must be identical.
    // What: calls `compose_session_instructions` and reads the written
    // stash file; asserts the returned display string equals it.
    // Test: the return value is compared byte-for-byte against the
    // on-disk stash to detect any future divergence.
    let tmp = tempfile::tempdir().unwrap();
    let project = tmp.path();

    let (display, _output, stash_path) =
        compose_session_instructions(project).expect("compose succeeds");

    let on_disk =
        std::fs::read_to_string(&stash_path).expect("stash file must be readable after compose");

    assert_eq!(
        display, on_disk,
        "tm session instructions display must equal the stash file (issue #382)"
    );
}

#[test]
fn compose_session_instructions_display_matches_live_prompt() {
    // Why: `tm session instructions` must show exactly what `claude` receives
    // via `--append-system-prompt-file`; the live prompt is produced by
    // `build_system_prompt_for`, which calls `resolve_pm_prompt`. If
    // `compose_session_instructions` ever returns something different from
    // `build_system_prompt_for`, the stash would again diverge from reality.
    // What: runs both composers on the same empty project directory with the
    // SAME injected roster and asserts the outputs match.
    // #5544: the roster is injected rather than rescanned per side — see
    // `fixture_roster_section`. No process env is touched, so this test needs
    // no `#[serial]`.
    // Test: any future change that re-introduces the #382 divergence will
    // break this test immediately.
    let (_tiers, roster) = fixture_roster_section();
    let tmp = tempfile::tempdir().unwrap();
    let project = tmp.path();

    let (display, _output, _stash) =
        compose_session_instructions_with_roster(project, Some(roster.clone()))
            .expect("compose succeeds");

    let live_prompt = trusty_mpm::core::session_launch::build_system_prompt_for_with_roster(
        crate::commands::install::test_content_ref(),
        project,
        Some(roster),
    );

    assert_eq!(
        display, live_prompt,
        "tm session instructions output must match the live launch prompt (issue #382)"
    );
    assert!(
        display.contains("### engineer"),
        "the injected fixture roster must reach the composed prompt, or this \
         test is no longer comparing the roster-present composer path"
    );
}

#[test]
fn compose_session_instructions_display_matches_live_prompt_with_override() {
    // Why: the same convergence guarantee must hold when project-level override
    // files are present — the stash and the display must reflect the override,
    // not the bundled defaults.
    // What: writes a `CLAUDE.md` WORKFLOW named section (#4286 — the retired
    // `.trusty-mpm/WORKFLOW.md` file this used to write is no longer read),
    // then asserts the display and the live prompt both include it (and don't
    // include the bundled heading).
    // #5544: one injected roster feeds both sides — see the test above.
    // Test: if `compose_session_instructions` stops reading overrides for the
    // display path, this test fails.
    let (_tiers, roster) = fixture_roster_section();
    let tmp = tempfile::tempdir().unwrap();
    let project = tmp.path();

    std::fs::write(
        project.join("CLAUDE.md"),
        "<!-- TRUSTY-MPM: WORKFLOW START v=1 -->\n\
         # Custom Workflow\n\nCOMPOSE_OVERRIDE_MARKER\n\
         <!-- TRUSTY-MPM: WORKFLOW END -->\n",
    )
    .unwrap();

    let (display, _output, _stash) =
        compose_session_instructions_with_roster(project, Some(roster.clone()))
            .expect("compose succeeds");

    let live_prompt = trusty_mpm::core::session_launch::build_system_prompt_for_with_roster(
        crate::commands::install::test_content_ref(),
        project,
        Some(roster),
    );

    assert_eq!(
        display, live_prompt,
        "display and live prompt must match with overrides present (issue #382)"
    );
    assert!(
        display.contains("COMPOSE_OVERRIDE_MARKER"),
        "override must be reflected in display"
    );
    assert!(
        !display.contains("# PM Workflow Configuration"),
        "bundled workflow must be replaced in display"
    );
}

#[test]
fn cli_parses_daemon_mcp() {
    let cli = Cli::try_parse_from(["trusty-mpm", "daemon", "--mcp"]).unwrap();
    match cli.command.unwrap() {
        Command::Daemon { mcp, .. } => assert!(mcp),
        other => panic!("expected Daemon, got {other:?}"),
    }
}

#[test]
fn cli_parses_repair_deploy() {
    // `tm repair deploy` must parse to Command::Repair { action: RepairAction::Deploy { force: false } }.
    let cli = Cli::try_parse_from(["trusty-mpm", "repair", "deploy"]).unwrap();
    match cli.command.unwrap() {
        Command::Repair {
            action: RepairAction::Deploy { force },
        } => {
            assert!(!force, "force must default to false");
        }
        other => panic!("expected Repair {{ Deploy }}, got {other:?}"),
    }
}

#[test]
fn cli_parses_repair_deploy_force() {
    // `tm repair deploy --force` must parse with force=true.
    let cli = Cli::try_parse_from(["trusty-mpm", "repair", "deploy", "--force"]).unwrap();
    match cli.command.unwrap() {
        Command::Repair {
            action: RepairAction::Deploy { force },
        } => {
            assert!(force, "force must be true with --force flag");
        }
        other => panic!("expected Repair {{ Deploy {{ force: true }} }}, got {other:?}"),
    }
}

// ── issue #2246: `tm auth` CLI parse tests ──────────────────────────────────

#[test]
fn cli_parses_auth_set_token() {
    let cli = Cli::try_parse_from(["trusty-mpm", "auth", "set-token", "--token", "abc"]).unwrap();
    match cli.command.unwrap() {
        Command::Auth {
            action: AuthAction::SetToken { token, stdin },
        } => {
            assert_eq!(token.as_deref(), Some("abc"));
            assert!(!stdin, "stdin flag must default to false");
        }
        other => panic!("expected Auth {{ SetToken }}, got {other:?}"),
    }
}

#[test]
fn cli_parses_auth_set_token_stdin() {
    // No --token: the handler reads from stdin. --stdin is accepted for
    // clarity but does not change behaviour (see AuthAction::SetToken docs).
    let cli = Cli::try_parse_from(["trusty-mpm", "auth", "set-token", "--stdin"]).unwrap();
    match cli.command.unwrap() {
        Command::Auth {
            action: AuthAction::SetToken { token, stdin },
        } => {
            assert_eq!(token, None);
            assert!(stdin);
        }
        other => panic!("expected Auth {{ SetToken }}, got {other:?}"),
    }
}

#[test]
fn cli_parses_auth_clear_token() {
    let cli = Cli::try_parse_from(["trusty-mpm", "auth", "clear-token"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Auth {
            action: AuthAction::ClearToken
        }
    ));
}

#[test]
fn cli_parses_auth_status() {
    let cli = Cli::try_parse_from(["trusty-mpm", "auth", "status"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Auth {
            action: AuthAction::Status
        }
    ));
}

// ── standalone rm / update CLI parse tests ──────────────────────────────────

#[test]
fn cli_parses_rm_standalone() {
    let cli = Cli::try_parse_from(["trusty-mpm", "rm", "my-proj"]).unwrap();
    match cli.command.unwrap() {
        Command::Rm { alias, root } => {
            assert_eq!(alias, "my-proj");
            assert_eq!(root, None);
        }
        other => panic!("expected Rm, got {other:?}"),
    }
}

#[test]
fn cli_parses_rm_with_root() {
    let cli =
        Cli::try_parse_from(["trusty-mpm", "rm", "my-proj", "--root", "/tmp/custom"]).unwrap();
    match cli.command.unwrap() {
        Command::Rm { alias, root } => {
            assert_eq!(alias, "my-proj");
            assert_eq!(root.as_deref(), Some("/tmp/custom"));
        }
        other => panic!("expected Rm, got {other:?}"),
    }
}

#[test]
fn cli_rm_requires_alias() {
    assert!(Cli::try_parse_from(["trusty-mpm", "rm"]).is_err());
}

#[test]
fn cli_parses_update_standalone() {
    let cli = Cli::try_parse_from(["trusty-mpm", "update", "my-proj"]).unwrap();
    match cli.command.unwrap() {
        Command::Update { alias, root } => {
            assert_eq!(alias.as_deref(), Some("my-proj"));
            assert_eq!(root, None);
        }
        other => panic!("expected Update, got {other:?}"),
    }
}

#[test]
fn cli_parses_update_all_standalone() {
    // `tm update` without alias should update all loaded aliases.
    let cli = Cli::try_parse_from(["trusty-mpm", "update"]).unwrap();
    match cli.command.unwrap() {
        Command::Update { alias, root } => {
            assert_eq!(alias, None);
            assert_eq!(root, None);
        }
        other => panic!("expected Update, got {other:?}"),
    }
}

#[test]
fn cli_parses_update_with_root() {
    let cli = Cli::try_parse_from(["trusty-mpm", "update", "--root", "/tmp/r"]).unwrap();
    match cli.command.unwrap() {
        Command::Update { alias, root } => {
            assert_eq!(alias, None);
            assert_eq!(root.as_deref(), Some("/tmp/r"));
        }
        other => panic!("expected Update, got {other:?}"),
    }
}

// ── standalone rm / update handler unit tests ───────────────────────────────

#[test]
fn rm_cmd_removes_registry_entry_and_project_dir() {
    use crate::commands::managed_root::ManagedPaths;
    use crate::commands::standalone::rm_cmd;
    use trusty_mpm::core::standalone::registry::ManagedRegistry;

    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path().to_path_buf();
    let paths = ManagedPaths::from_root(root.clone());

    // Register and set up a fake project dir.
    let mut reg = ManagedRegistry::load(&root).unwrap();
    reg.add("demo", "https://github.com/org/repo", false)
        .unwrap();
    reg.save().unwrap();

    let project_dir = root.join("projects").join("demo");
    std::fs::create_dir_all(&project_dir).unwrap();
    std::fs::write(project_dir.join("sentinel.txt"), b"data").unwrap();

    rm_cmd(&paths, "demo").expect("rm_cmd must succeed");

    // Registry entry must be gone.
    let reg2 = ManagedRegistry::load(&root).unwrap();
    assert!(
        reg2.list().is_empty(),
        "registry must be empty after rm_cmd"
    );
    // Project dir must be deleted.
    assert!(
        !project_dir.exists(),
        "project dir must be deleted by rm_cmd"
    );
}

#[test]
fn rm_cmd_errors_on_unknown_alias() {
    use crate::commands::managed_root::ManagedPaths;
    use crate::commands::standalone::rm_cmd;

    let tmp = tempfile::TempDir::new().unwrap();
    let paths = ManagedPaths::from_root(tmp.path().to_path_buf());

    let result = rm_cmd(&paths, "nonexistent");
    assert!(result.is_err(), "rm_cmd must error on unknown alias");
    let msg = format!("{}", result.unwrap_err());
    assert!(
        msg.contains("nonexistent"),
        "error message must mention the alias"
    );
}

#[test]
fn rm_cmd_leaves_claude_config_intact() {
    use crate::commands::managed_root::ManagedPaths;
    use crate::commands::standalone::rm_cmd;
    use trusty_mpm::core::standalone::registry::ManagedRegistry;

    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path().to_path_buf();
    let paths = ManagedPaths::from_root(root.clone());

    // Create a fake shared claude-config dir.
    let cfg_dir = root.join("claude-config");
    std::fs::create_dir_all(&cfg_dir).unwrap();
    std::fs::write(cfg_dir.join("shared.json"), b"{}").unwrap();

    // Register a project and create its directory.
    let mut reg = ManagedRegistry::load(&root).unwrap();
    reg.add("proj", "https://github.com/org/repo", false)
        .unwrap();
    reg.save().unwrap();
    let project_dir = root.join("projects").join("proj");
    std::fs::create_dir_all(&project_dir).unwrap();

    rm_cmd(&paths, "proj").expect("rm_cmd must succeed");

    // The shared claude-config dir must still be intact.
    assert!(
        cfg_dir.exists(),
        "claude-config dir must NOT be touched by rm_cmd"
    );
    assert!(
        cfg_dir.join("shared.json").exists(),
        "files inside claude-config must survive rm_cmd"
    );
}

#[test]
fn rm_cmd_succeeds_when_project_dir_absent() {
    // If the alias is registered but was never loaded (no project dir), rm must
    // still deregister cleanly — the dir removal is best-effort.
    use crate::commands::managed_root::ManagedPaths;
    use crate::commands::standalone::rm_cmd;
    use trusty_mpm::core::standalone::registry::ManagedRegistry;

    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path().to_path_buf();
    let paths = ManagedPaths::from_root(root.clone());

    let mut reg = ManagedRegistry::load(&root).unwrap();
    reg.add("ghost", "https://github.com/org/repo", false)
        .unwrap();
    reg.save().unwrap();

    // No project dir exists (never loaded).
    assert!(!root.join("projects").join("ghost").exists());

    rm_cmd(&paths, "ghost").expect("rm_cmd must succeed even without project dir");

    let reg2 = ManagedRegistry::load(&root).unwrap();
    assert!(
        reg2.list().is_empty(),
        "registry must be empty after rm_cmd on unloaded alias"
    );
}

#[test]
fn update_cmd_errors_if_alias_not_in_registry() {
    use crate::commands::managed_root::ManagedPaths;
    use crate::commands::standalone::update_cmd_with_exe;

    let tmp = tempfile::TempDir::new().unwrap();
    let paths = ManagedPaths::from_root(tmp.path().to_path_buf());

    let result = update_cmd_with_exe(
        &paths,
        Some("missing-alias"),
        Some(std::path::Path::new(crate::test_support::STABLE_HOOK_EXE)),
    );
    assert!(result.is_err(), "update_cmd must error when alias unknown");
    let msg = format!("{}", result.unwrap_err());
    assert!(
        msg.contains("missing-alias"),
        "error must name the unknown alias"
    );
}

#[test]
fn update_cmd_errors_if_not_loaded() {
    // `tm update <alias>` where alias is registered but project dir does not
    // exist (never loaded) must error IMMEDIATELY with a message that hints to
    // run `tm load <alias>` first — not a generic end-of-loop bail.
    use crate::commands::managed_root::ManagedPaths;
    use crate::commands::standalone::update_cmd_with_exe;
    use trusty_mpm::core::standalone::registry::ManagedRegistry;

    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path().to_path_buf();
    let paths = ManagedPaths::from_root(root.clone());

    // Register the alias but do NOT create the project dir (never loaded).
    let mut reg = ManagedRegistry::load(&root).unwrap();
    reg.add("not-loaded", "https://github.com/org/repo", false)
        .unwrap();
    reg.save().unwrap();
    assert!(!root.join("projects").join("not-loaded").exists());

    let result = update_cmd_with_exe(
        &paths,
        Some("not-loaded"),
        Some(std::path::Path::new(crate::test_support::STABLE_HOOK_EXE)),
    );
    assert!(
        result.is_err(),
        "update_cmd must error when alias is registered but not yet loaded"
    );
    let msg = format!("{}", result.unwrap_err());
    assert!(
        msg.contains("not-loaded"),
        "error must name the alias: {msg}"
    );
    assert!(
        msg.contains("tm load"),
        "error must hint to run `tm load`: {msg}"
    );
}

#[test]
fn update_cmd_all_skips_unloaded_returns_ok_when_none_loaded() {
    // `tm update` (no alias) with zero loaded projects should print a message
    // and return Ok.
    use crate::commands::managed_root::ManagedPaths;
    use crate::commands::standalone::update_cmd_with_exe;
    use trusty_mpm::core::standalone::registry::ManagedRegistry;

    let tmp = tempfile::TempDir::new().unwrap();
    let root = tmp.path().to_path_buf();
    let paths = ManagedPaths::from_root(root.clone());

    // Register an alias but never load it (no project dir).
    let mut reg = ManagedRegistry::load(&root).unwrap();
    reg.add("unloaded", "https://github.com/org/repo", false)
        .unwrap();
    reg.save().unwrap();

    // With no loaded projects, update_cmd should return Ok (nothing to do).
    let result = update_cmd_with_exe(
        &paths,
        None,
        Some(std::path::Path::new(crate::test_support::STABLE_HOOK_EXE)),
    );
    assert!(
        result.is_ok(),
        "update_cmd with no loaded aliases must return Ok"
    );
}

// ── WI-2 #1593: `tm sessctl` CLI parse round-trips ───────────────────────────

#[test]
fn cli_parses_sessctl_run() {
    // Why: `tm sessctl run <project-id>` must parse to Command::Sessctl with
    // SessctlAction::Run carrying the project_id.
    // What: assert parse round-trip for the run subcommand.
    // Test: direct parse via Cli::try_parse_from.
    let cli = Cli::try_parse_from(["trusty-mpm", "sessctl", "run", "my-proj"]).unwrap();
    match cli.command.unwrap() {
        Command::Sessctl {
            action: SessctlAction::Run {
                project_id, tmux, ..
            },
        } => {
            assert_eq!(project_id, "my-proj");
            assert!(!tmux);
        }
        other => panic!("expected sessctl run, got {other:?}"),
    }
}

#[test]
fn cli_parses_sessctl_run_tmux() {
    // Why: `--tmux` must flip the backend to tmux.
    // What: assert `tmux == true` when the flag is present.
    // Test: direct parse via Cli::try_parse_from.
    let cli = Cli::try_parse_from(["trusty-mpm", "sessctl", "run", "--tmux", "proj"]).unwrap();
    match cli.command.unwrap() {
        Command::Sessctl {
            action: SessctlAction::Run { tmux, .. },
        } => assert!(tmux),
        other => panic!("expected sessctl run, got {other:?}"),
    }
}

#[test]
fn cli_parses_sessctl_connect() {
    // Why: `tm sessctl connect <id>` must parse to SessctlAction::Connect.
    // What: assert the session_id field is populated.
    // Test: direct parse via Cli::try_parse_from.
    let cli = Cli::try_parse_from(["trusty-mpm", "sessctl", "connect", "my-proj-0"]).unwrap();
    match cli.command.unwrap() {
        Command::Sessctl {
            action: SessctlAction::Connect { session_id },
        } => assert_eq!(session_id, "my-proj-0"),
        other => panic!("expected sessctl connect, got {other:?}"),
    }
}

#[test]
fn cli_parses_sessctl_stop() {
    // Why: `tm sessctl stop <id>` must parse to SessctlAction::Stop with
    // force=false by default.
    // What: assert force defaults to false.
    // Test: direct parse via Cli::try_parse_from.
    let cli = Cli::try_parse_from(["trusty-mpm", "sessctl", "stop", "my-proj-0"]).unwrap();
    match cli.command.unwrap() {
        Command::Sessctl {
            action: SessctlAction::Stop { session_id, force },
        } => {
            assert_eq!(session_id, "my-proj-0");
            assert!(!force);
        }
        other => panic!("expected sessctl stop, got {other:?}"),
    }
}

#[test]
fn cli_parses_sessctl_stop_force() {
    // Why: `tm sessctl stop --force <id>` must set force=true.
    // What: assert force is true when the flag is present.
    // Test: direct parse via Cli::try_parse_from.
    let cli =
        Cli::try_parse_from(["trusty-mpm", "sessctl", "stop", "--force", "my-proj-0"]).unwrap();
    match cli.command.unwrap() {
        Command::Sessctl {
            action: SessctlAction::Stop { force, .. },
        } => assert!(force),
        other => panic!("expected sessctl stop --force, got {other:?}"),
    }
}

#[test]
fn cli_parses_sessctl_auth() {
    // Why: `tm sessctl auth <id>` must parse to SessctlAction::Auth.
    // What: assert the session_id field is populated.
    // Test: direct parse via Cli::try_parse_from.
    let cli = Cli::try_parse_from(["trusty-mpm", "sessctl", "auth", "my-proj-0"]).unwrap();
    match cli.command.unwrap() {
        Command::Sessctl {
            action: SessctlAction::Auth { session_id },
        } => assert_eq!(session_id, "my-proj-0"),
        other => panic!("expected sessctl auth, got {other:?}"),
    }
}

#[test]
fn cli_parses_sessctl_list() {
    // Why: `tm sessctl list` must parse to SessctlAction::List with default
    // format="table" and no project filter.
    // What: assert defaults are applied.
    // Test: direct parse via Cli::try_parse_from.
    let cli = Cli::try_parse_from(["trusty-mpm", "sessctl", "list"]).unwrap();
    match cli.command.unwrap() {
        Command::Sessctl {
            action: SessctlAction::List { project, format },
        } => {
            assert!(project.is_none());
            assert_eq!(format, "table");
        }
        other => panic!("expected sessctl list, got {other:?}"),
    }
}

#[test]
fn cli_parses_sessctl_list_with_project_and_json() {
    // Why: `tm sessctl list --project foo --format json` must parse both flags.
    // What: assert project filter and json format are set.
    // Test: direct parse via Cli::try_parse_from.
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "sessctl",
        "list",
        "--project",
        "foo",
        "--format",
        "json",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Sessctl {
            action: SessctlAction::List { project, format },
        } => {
            assert_eq!(project.as_deref(), Some("foo"));
            assert_eq!(format, "json");
        }
        other => panic!("expected sessctl list, got {other:?}"),
    }
}

// ── Regression tests for #1724 (guided-default fallback pollution guard) ──────

/// Why (#1724): the guided-default fallback MUST NOT deploy framework files
/// into a GitHub-backed git project's live checkout, even when the daemon is
/// unreachable. This test locks in that guarantee.
/// What: creates a temp directory, initialises a git repo inside it, sets a
/// fake GitHub remote URL, pre-creates a stub base clone (so `ensure_base_clone`
/// short-circuits without a network call), and calls `fallback_protected`
/// directly with the daemon set to an unreachable address. Asserts that no
/// framework files (`.trusty-mpm/`, `CLAUDE.md`, `.mcp.json`, `.claude/`) exist
/// in the temp directory after the call.
/// Test: this is the test. Annotated `serial` because it mutates `TRUSTY_MPM_REPOS_ROOT`.
#[tokio::test]
#[serial_test::serial]
async fn guided_fallback_never_pollutes_github_git_checkout() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    // Build a minimal git repository at `project` with a fake GitHub remote.
    // We use `git init` + `git remote add` so `get_origin_url` (which shells
    // out to `git config --get remote.origin.url`) returns a parseable URL.
    let git_init_ok = std::process::Command::new("git")
        .arg("init")
        .current_dir(project)
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !git_init_ok {
        // git binary unavailable in this environment; skip gracefully.
        eprintln!(
            "guided_fallback_never_pollutes_github_git_checkout: git not available, skipping"
        );
        return;
    }
    let _ = std::process::Command::new("git")
        .args([
            "remote",
            "add",
            "origin",
            "https://github.com/trusty-ci-nonexistent/no-repo-1724.git",
        ])
        .current_dir(project)
        .status();

    // Pre-create a stub base clone so `ensure_base_clone` returns immediately
    // (it checks `base/.git` and returns Ok when found), avoiding any real
    // network call. `create_session_worktree` will fail because the stub is
    // not a real git repository — the error path is the one we want to test.
    //
    // SAFETY: env-var mutation is accepted by the project convention (same
    // pattern as crates/trusty-mpm/src/core/trusty_tools_config.rs tests).
    // The test mutates TRUSTY_MPM_REPOS_ROOT to a unique tempdir so it does
    // not conflict with concurrently-running tests on different paths.
    let repos_root = tempfile::tempdir().unwrap();
    let fake_base = repos_root
        .path()
        .join("trusty-ci-nonexistent")
        .join("no-repo-1724");
    std::fs::create_dir_all(fake_base.join(".git")).unwrap();

    let prev = std::env::var(trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV).ok();
    unsafe {
        std::env::set_var(
            trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV,
            repos_root.path(),
        );
    }

    // Call the protected fallback with an unreachable daemon URL and our fake
    // git project as the working directory.
    let client = reqwest::Client::new();
    let result = run_fallback_default(&client, "http://127.0.0.1:1", project).await;

    // Restore the env var regardless of the outcome.
    unsafe {
        match prev {
            Some(v) => std::env::set_var(
                trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV,
                v,
            ),
            None => {
                std::env::remove_var(trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV)
            }
        }
    }

    // ── Acceptance criterion (#1724) ─────────────────────────────────────────
    // None of the framework files that `prepare_session_with_style` writes must
    // appear inside the live git checkout.
    assert!(
        !project.join("CLAUDE.md").exists(),
        "#1724: CLAUDE.md must NOT be written to the live git checkout"
    );
    assert!(
        !project.join(".mcp.json").exists(),
        "#1724: .mcp.json must NOT be written to the live git checkout"
    );
    assert!(
        !project.join(".trusty-mpm").exists(),
        "#1724: .trusty-mpm dir must NOT be created in the live git checkout"
    );
    assert!(
        !project.join(".claude").exists(),
        "#1724: .claude dir must NOT be created in the live git checkout"
    );

    // The function must return Err (refused to deploy) rather than silently
    // falling through to a live-checkout deploy.
    assert!(
        result.is_err(),
        "#1724: fallback must Err rather than deploy to the live checkout; \
         got Ok which means framework files may have been written"
    );
}

/// Why (#1724 residual gap): the protected-checkout guarantee MUST hold for ANY
/// git project, not only GitHub-backed ones. A git repo with a non-GitHub remote
/// (e.g. a Gitea, GitLab, or bare SSH URL) or with NO remote configured must
/// also be refused — the fallback must return `Err` and leave the live working
/// tree untouched.
/// What: inits a real git repo, adds a non-GitHub remote URL, then calls
/// `fallback_protected` directly. Asserts that the four framework artifacts are
/// absent and the call returns `Err`.
/// Test: this is the test.
#[tokio::test]
async fn guided_fallback_blocks_non_github_git_checkout() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    // Build a minimal git repo with a non-GitHub (Gitea) remote.
    let git_init_ok = std::process::Command::new("git")
        .arg("init")
        .current_dir(project)
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !git_init_ok {
        eprintln!("guided_fallback_blocks_non_github_git_checkout: git not available, skipping");
        return;
    }
    // Add a non-GitHub remote to confirm it is not parsed as a GitHub project.
    let _ = std::process::Command::new("git")
        .args([
            "remote",
            "add",
            "origin",
            "https://gitea.example.com/org/repo.git",
        ])
        .current_dir(project)
        .status();

    // Call the protected fallback with an unreachable daemon URL.
    let client = reqwest::Client::new();
    let result = run_fallback_default(&client, "http://127.0.0.1:1", project).await;

    // ── Acceptance criterion (#1724 residual gap) ────────────────────────────
    // None of the framework files must appear in the live git checkout.
    assert!(
        !project.join("CLAUDE.md").exists(),
        "#1724: CLAUDE.md must NOT be written to a non-GitHub git checkout"
    );
    assert!(
        !project.join(".mcp.json").exists(),
        "#1724: .mcp.json must NOT be written to a non-GitHub git checkout"
    );
    assert!(
        !project.join(".trusty-mpm").exists(),
        "#1724: .trusty-mpm dir must NOT be created in a non-GitHub git checkout"
    );
    assert!(
        !project.join(".claude").exists(),
        "#1724: .claude dir must NOT be created in a non-GitHub git checkout"
    );

    // The fallback must refuse with Err, not silently deploy.
    assert!(
        result.is_err(),
        "#1724: fallback must Err for non-GitHub git checkout; \
         got Ok which means framework files may have been deployed"
    );

    // Verify it's the REFUSAL error, not a network-error from a clone attempt.
    // If is_github_remote() incorrectly accepts non-GitHub URLs, it would try
    // to clone from gitea.example.com and fail with a network error instead.
    let err_msg = format!("{}", result.unwrap_err());
    assert!(
        err_msg.contains("auto-managed clones require a GitHub remote")
            || err_msg.contains("live git checkout"),
        "#1724: error message must explain the protection; got: {err_msg}"
    );
}

/// Why (#2534): bare `tm` run from a directory that physically sits inside a
/// GitHub repo's working tree but is NOT part of its tracked tree (the same shape
/// as the APFS `~/Duetto/cto` case-fold collision) must NOT inherit the enclosing
/// repo's identity. It must NOT redirect to that repo's managed clone (which would
/// attempt a real `git clone` of the github.com URL and fail on the network); it
/// must route to the clean non-git fallback and return `Ok(())` without writing
/// any framework files.
/// What: inits a real git repo with a committed file + a github.com remote, then
/// creates an UNTRACKED subdir inside it and calls `fallback_protected` from that
/// subdir. Asserts `Ok(())`, no framework artifacts, and no managed-clone attempt.
/// Test: this is the test.
#[tokio::test]
async fn guided_fallback_untracked_ancestor_does_not_redirect() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    // git init + identity + an initial commit (so HEAD's tree exists).
    let git_ok = std::process::Command::new("git")
        .args(["init", "-q"])
        .current_dir(project)
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !git_ok {
        eprintln!(
            "guided_fallback_untracked_ancestor_does_not_redirect: git unavailable, skipping"
        );
        return;
    }
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        let _ = std::process::Command::new("git")
            .args(["config", k, v])
            .current_dir(project)
            .status();
    }
    std::fs::write(project.join("README.md"), b"x").unwrap();
    let _ = std::process::Command::new("git")
        .args(["add", "-A"])
        .current_dir(project)
        .status();
    let _ = std::process::Command::new("git")
        .args(["commit", "-m", "init", "-q"])
        .current_dir(project)
        .status();
    // A github.com remote — if the ancestor were (wrongly) trusted, the fallback
    // would try to clone THIS into the managed workspace.
    let _ = std::process::Command::new("git")
        .args([
            "remote",
            "add",
            "origin",
            "https://github.com/owner/repo.git",
        ])
        .current_dir(project)
        .status();

    // An UNTRACKED sibling directory inside the working tree — never `git add`ed.
    let untracked = project.join("cto");
    std::fs::create_dir_all(&untracked).unwrap();

    let client = reqwest::Client::new();
    let result = run_fallback_default(&client, "http://127.0.0.1:1", &untracked).await;

    // Must exit cleanly (non-git fallback), NOT Err (non-github refusal) and NOT
    // a redirect (which would network-fail cloning the github remote).
    assert!(
        result.is_ok(),
        "#2534: untracked ancestor subdir must route to the clean non-git \
         fallback (Ok), not the ancestor's managed-clone redirect; got: {result:?}"
    );
    // No framework artifacts anywhere.
    for p in ["CLAUDE.md", ".mcp.json", ".trusty-mpm", ".claude"] {
        assert!(
            !untracked.join(p).exists(),
            "#2534: {p} must NOT be written to the untracked directory"
        );
        assert!(
            !project.join(p).exists(),
            "#2534: {p} must NOT be written to the enclosing repo"
        );
    }
}

/// Why (#1724 non-git path + #1839 Fix 2): the protected-checkout guarantee applies
/// only to git projects. A plain directory (no `.git`) should exit cleanly with a
/// helpful hint rather than attempting `launch()` which would fail with a confusing
/// daemon error. The fallback must NOT blindly block all directories, only git trees.
/// What: creates a temp dir with NO `.git`, calls `fallback_protected`. Since #1839
/// the non-git path returns `Ok(())` after printing a help hint to stderr — no
/// daemon contact is made and no framework files are created.
/// Test: this is the test.
#[tokio::test]
async fn guided_fallback_non_git_dir_reaches_launch_path() {
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    // No git init — plain directory.
    assert!(
        !project.join(".git").exists(),
        "test precondition: must NOT be a git repo"
    );

    // Call the protected fallback with any daemon URL — the non-git path now
    // exits cleanly without contacting the daemon (#1839 Fix 2).
    let client = reqwest::Client::new();
    let result = run_fallback_default(&client, "http://127.0.0.1:1", project).await;

    // The result must be Ok(()) — no git repo means we print a help hint and exit 0.
    assert!(
        result.is_ok(),
        "#1839: non-git dir must exit cleanly (Ok) with a help hint; got: {result:?}"
    );

    // Framework files must NOT have been created.
    assert!(
        !project.join("CLAUDE.md").exists(),
        "CLAUDE.md must not exist for plain non-git directories"
    );
}

// ── #4061: managed-pane settle race vs. the non-git fallback ─────────────────
//
// Root cause: `try_inplace_relaunch` (the FIRST thing bare `tm` tries, at the
// top of `run_guided_default`) is gated on the daemon's session record
// actually reading "stopped" within a small bounded retry budget
// (`FETCH_RETRY_BUDGET`, ~400ms) — the async `SessionEnd` healing step that
// flips a just-exited managed pane's record from "active" to "stopped" can
// still be in flight at that exact moment. When that gate misses, control
// used to fall straight through project detection to `fallback_protected`'s
// `CwdProject::NotGit` arm, which printed the "not in a git project" hint —
// actively misleading for a pane that plainly IS (or very recently was) a
// managed session's own pane. These tests exercise `fallback_protected`
// directly (the layer the fix lives in) with `TM_MANAGED_SESSION_ID` present,
// mirroring the exact "operator's shell already has the env var exported"
// scenario from #2023 component B.

#[tokio::test]
#[serial_test::serial]
async fn guided_fallback_non_git_dir_no_managed_env_is_fast() {
    // Why: the common case — no managed-session signal in the environment at
    // all — must take the ordinary, unaffected fast path: no extra daemon
    // round trip, no added latency (#4061 must not slow down bare `tm` for a
    // genuinely non-managed pane).
    //
    // #6885: "fast" is proven structurally, not by the clock. The old bound
    // (`elapsed < 150ms` against a refused connection) measured how busy the
    // machine was rather than what the code did, and reported 162ms to 434ms
    // on branches that had not touched this path. This aims a REAL listener at
    // `fallback_protected` and asserts it is never connected to. Zero daemon
    // round trips is the property the Why above actually claims, and it holds
    // at any load. Same substitution #6240 made for the sibling test.
    let managed_key = "TM_MANAGED_SESSION_ID";
    let prev = std::env::var(managed_key).ok();
    // SAFETY: serialised by `#[serial_test::serial]`.
    unsafe { std::env::remove_var(managed_key) };
    let prev_tmux = std::env::var("TMUX").ok();
    // SAFETY: serialised by `#[serial_test::serial]`.
    unsafe { std::env::remove_var("TMUX") };

    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();
    assert!(!project.join(".git").exists(), "test precondition");

    // The mock is scripted "stopped" on purpose: were the code to poll, it
    // would get the single most favourable answer and still be caught by the
    // connection count below.
    const UNUSED_ID: &str = "66666666-7777-8888-9999-aaaaaaaaaaaa";
    let (url, hits) = spawn_4061_state_mock(UNUSED_ID, vec!["stopped"]).await;

    let client = reqwest::Client::new();
    // The 5s timeout is an anti-hang guard only — #6070 saw this same path
    // hang outright. Promptness itself is the connection count, never a clock.
    let result = tokio::time::timeout(
        std::time::Duration::from_secs(5),
        run_fallback_default(&client, &url, project),
    )
    .await;

    // Restore before any assertion can panic.
    unsafe {
        match prev {
            Some(ref v) => std::env::set_var(managed_key, v),
            None => std::env::remove_var(managed_key),
        }
        match prev_tmux {
            Some(ref v) => std::env::set_var("TMUX", v),
            None => std::env::remove_var("TMUX"),
        }
    }

    let result = result.expect("#6885: the no-managed-env fallback must never hang");
    assert!(
        result.is_ok(),
        "non-git dir must exit cleanly; got {result:?}"
    );
    // #6885: the deterministic stand-in for the old wall-clock budget.
    let polls = hits.load(std::sync::atomic::Ordering::SeqCst);
    assert_eq!(
        polls, 0,
        "no managed-session signal must never pay the #4061 retry budget: \
         expected 0 daemon round trips, got {polls}"
    );
}

/// Local HTTP mock replying `{"id","name","state"}`, walking through `states`
/// one entry per connection (clamping to the last once exhausted) — mirrors
/// `commands::guided_inplace::tests::spawn_state_mock`'s convention (that
/// helper lives in a sibling test module and is not reachable from this file,
/// hence the small local copy).
async fn spawn_4061_state_mock(
    id: &'static str,
    states: Vec<&'static str>,
) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
    let addr = listener.local_addr().expect("addr");
    let hits = Arc::new(AtomicUsize::new(0));
    let hits_task = hits.clone();
    tokio::spawn(async move {
        loop {
            let Ok((mut sock, _)) = listener.accept().await else {
                break;
            };
            let n = hits_task.fetch_add(1, Ordering::SeqCst);
            // Drain the request before replying (avoids connection-reset
            // flakiness on a naive single read).
            let mut buf = [0u8; 4096];
            loop {
                match tokio::time::timeout(
                    std::time::Duration::from_millis(200),
                    sock.read(&mut buf),
                )
                .await
                {
                    Ok(Ok(n)) if n > 0 => {
                        if buf[..n].windows(4).any(|w| w == b"\r\n\r\n") {
                            break;
                        }
                    }
                    _ => break,
                }
            }
            let idx = n.min(states.len().saturating_sub(1));
            let state = states.get(idx).copied().unwrap_or("active");
            let body = format!(r#"{{"id":"{id}","name":"tm-test-4061","state":"{state}"}}"#);
            let resp = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                body.len(),
                body
            );
            let _ = sock.write_all(resp.as_bytes()).await;
            let _ = sock.shutdown().await;
        }
    });
    (format!("http://{addr}"), hits)
}

#[tokio::test]
#[serial_test::serial]
async fn guided_fallback_non_git_dir_with_managed_env_settles_quickly_returns_promptly() {
    // #4061 race, reproduced: a managed-session id IS present in the
    // environment, and the daemon record settles to "stopped" on the very
    // next poll (simulating the `SessionEnd` healing step catching up a
    // beat after the first bare-`tm` attempt already gave up). The retried
    // `try_inplace_relaunch` this fix adds must observe that promptly —
    // never exhausting the full retry budget once the state resolves — and
    // must exit cleanly rather than ever printing the misleading "not in a
    // git project" hint for this pane.
    const TEST_ID: &str = "11111111-2222-3333-4444-555555555555";
    let (url, hits) = spawn_4061_state_mock(TEST_ID, vec!["active", "stopped"]).await;

    let managed_key = "TM_MANAGED_SESSION_ID";
    let prev = std::env::var(managed_key).ok();
    // SAFETY: serialised by `#[serial_test::serial]`.
    unsafe { std::env::set_var(managed_key, TEST_ID) };

    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    let client = reqwest::Client::new();
    // The 5s timeout is the anti-hang guard; promptness itself is asserted on
    // the poll count below, not on wall clock (#6230).
    let result = tokio::time::timeout(
        std::time::Duration::from_secs(5),
        run_fallback_default(&client, &url, project),
    )
    .await;

    // Restore before any assertion can panic.
    unsafe {
        match prev {
            Some(ref v) => std::env::set_var(managed_key, v),
            None => std::env::remove_var(managed_key),
        }
    }

    let result = result.expect("#4061: fallback_protected must never hang");
    assert!(
        result.is_ok(),
        "a managed pane whose record settles must still exit cleanly; got {result:?}"
    );
    assert!(
        !project.join("CLAUDE.md").exists(),
        "CLAUDE.md must not be written for this non-git cwd"
    );
    // #6230: promptness is how many times the loop polled, not how long the
    // machine took. The mock scripts "active" then "stopped", so a loop that
    // stops the moment the record resolves polls twice; one that pays the full
    // 400ms/80ms retry budget polls about six times. The previous
    // `elapsed < 300ms` bound measured load rather than the loop and failed at
    // 330ms under a concurrent suite run. One poll is also correct: a first
    // fetch slow enough to consume the whole budget returns after a single
    // attempt (see `fetch_managed_session_until_stopped`'s doc, #5840).
    let polls = hits.load(std::sync::atomic::Ordering::SeqCst);
    assert!(
        (1..=2).contains(&polls),
        "the retried in-place check must query the daemon and stop as soon as \
         the record settles: expected 1 or 2 polls, got {polls}"
    );
}

#[tokio::test]
#[serial_test::serial]
async fn guided_fallback_non_git_dir_with_managed_env_unreachable_daemon_does_not_hang() {
    // #4061: even in the worst case — a managed-session id present but the
    // daemon unreachable (or the record never settling) — the fallback must
    // still resolve promptly (bounded by the SAME small retry budget
    // `try_inplace_relaunch` already uses) rather than hang, and must still
    // exit cleanly.
    const TEST_ID: &str = "11111111-2222-3333-4444-555555555555";
    let managed_key = "TM_MANAGED_SESSION_ID";
    let prev = std::env::var(managed_key).ok();
    // SAFETY: serialised by `#[serial_test::serial]`.
    unsafe { std::env::set_var(managed_key, TEST_ID) };

    let dir = tempfile::tempdir().unwrap();
    let project = dir.path();

    let client = reqwest::Client::new();
    let result = tokio::time::timeout(
        std::time::Duration::from_secs(5),
        run_fallback_default(&client, "http://127.0.0.1:1", project),
    )
    .await;

    // Restore before any assertion can panic.
    unsafe {
        match prev {
            Some(ref v) => std::env::set_var(managed_key, v),
            None => std::env::remove_var(managed_key),
        }
    }

    let result = result.expect("#4061: fallback_protected must never hang, even unreachable");
    assert!(
        result.is_ok(),
        "an unreachable daemon must still exit cleanly; got {result:?}"
    );
    assert!(
        !project.join("CLAUDE.md").exists(),
        "CLAUDE.md must not be written for this non-git cwd"
    );
}

/// Why (#1724 HIGH gap): `fallback_protected` previously used `cwd.join(".git").exists()`
/// which only fires when `cwd` IS the repo root. Running `tm` from a subdirectory
/// (e.g. `~/project/src/`) silently bypassed the guard and called `launch(None)`,
/// resolving to `cwd` and deploying framework files into the live tree. This test
/// covers that scenario for a GitHub-backed project: the guard must detect the git
/// repo root at any depth and refuse to deploy.
/// What: creates a real git repo, creates a nested `src/module/` subdir, and calls
/// `fallback_protected` from within that subdir. Asserts no framework files appear
/// anywhere in the repo tree and that the call returns `Err`.
/// Test: this is the test.
#[tokio::test]
#[serial_test::serial]
async fn guided_fallback_blocks_github_git_from_subdirectory() {
    let repo_dir = tempfile::tempdir().unwrap();
    let git_init_ok = std::process::Command::new("git")
        .arg("init")
        .current_dir(repo_dir.path())
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !git_init_ok {
        eprintln!("guided_fallback_blocks_github_git_from_subdirectory: git unavailable, skipping");
        return;
    }
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        let _ = std::process::Command::new("git")
            .args(["config", k, v])
            .current_dir(repo_dir.path())
            .status();
    }
    let _ = std::process::Command::new("git")
        .args([
            "remote",
            "add",
            "origin",
            "https://github.com/trusty-ci-nonexistent/subdir-test-1724.git",
        ])
        .current_dir(repo_dir.path())
        .status();

    // Run from a NESTED, TRACKED subdirectory inside the repo. The subdir is
    // committed so it genuinely belongs to the repo's tracked tree — as of #2534
    // an UNTRACKED ancestor subdir instead routes to the clean non-git fallback
    // (covered by `guided_fallback_untracked_ancestor_does_not_redirect`).
    let subdir = repo_dir.path().join("src").join("module");
    std::fs::create_dir_all(&subdir).unwrap();
    std::fs::write(subdir.join(".keep"), b"").unwrap();
    let _ = std::process::Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo_dir.path())
        .status();
    let _ = std::process::Command::new("git")
        .args(["commit", "-m", "init", "-q"])
        .current_dir(repo_dir.path())
        .status();

    // ── Hermetic base-clone root (#3450) ─────────────────────────────────────
    // Without this override, `fallback_protected` → `ensure_base_clone` resolves
    // `repos_root()` to its PRODUCTION default (`~/trusty-mpm-projects`) and
    // attempts a real (failing) network clone of the fake GitHub URL above,
    // depositing `trusty-ci-nonexistent/subdir-test-1724(.old-layout-backup-*)`
    // directly into the operator's real projects root — every single run, on
    // every machine, regardless of `$TMPDIR`. Mirrors the stub-base-clone
    // pattern in `guided_fallback_never_pollutes_github_git_checkout` above:
    // pre-create a fake `.git` marker so `ensure_base_clone` short-circuits
    // without ever touching the network, and `create_session_worktree` then
    // fails (not a real repo) — the error path this test wants to observe.
    //
    // SAFETY: env-var mutation is accepted by the project convention (same
    // pattern as the sibling tests in this file); `#[serial_test::serial]`
    // above prevents cross-test races on the process-global env var.
    let repos_root = tempfile::tempdir().unwrap();
    let fake_base = repos_root
        .path()
        .join("trusty-ci-nonexistent")
        .join("subdir-test-1724");
    std::fs::create_dir_all(fake_base.join(".git")).unwrap();

    let prev = std::env::var(trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV).ok();
    unsafe {
        std::env::set_var(
            trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV,
            repos_root.path(),
        );
    }

    let client = reqwest::Client::new();
    let result = run_fallback_default(&client, "http://127.0.0.1:1", &subdir).await;

    // Restore the env var regardless of the outcome.
    unsafe {
        match prev {
            Some(v) => std::env::set_var(
                trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV,
                v,
            ),
            None => {
                std::env::remove_var(trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV)
            }
        }
    }

    // ── Acceptance criterion (#1724 HIGH gap) ────────────────────────────────
    // No framework files must exist anywhere in the repo tree.
    assert!(
        !repo_dir.path().join("CLAUDE.md").exists(),
        "#1724: CLAUDE.md must NOT appear in repo root when called from subdir"
    );
    assert!(
        !subdir.join("CLAUDE.md").exists(),
        "#1724: CLAUDE.md must NOT appear in the subdir"
    );
    assert!(
        !repo_dir.path().join(".mcp.json").exists(),
        "#1724: .mcp.json must NOT appear in repo root"
    );
    assert!(
        !subdir.join(".mcp.json").exists(),
        "#1724: .mcp.json must NOT appear in the subdir"
    );
    // The call must return Err (refused or clone attempt failed — not deployed).
    assert!(
        result.is_err(),
        "#1724: fallback from subdir must Err, not deploy to the live tree"
    );
}

/// Why (#1724 success path): proves that when `launch_protected_workspace` succeeds
/// (base clone exists as a real git repo so `create_session_worktree` can create a
/// worktree), `launch()` is called with `Some(worktree)` — not `None` — so
/// framework files go to the worktree, never to the live checkout.
/// What: (1) creates a real git base clone (git init + empty commit); (2) sets
/// `TRUSTY_MPM_REPOS_ROOT` to point at it; (3) creates a live checkout with a
/// matching GitHub remote; (4) calls `fallback_protected`; (5) asserts live
/// checkout is clean AND at least one per-session worktree was created under the
/// base clone (proving `launch(Some(worktree))` was invoked, not `launch(None)`).
/// Test: this is the test. Annotated `serial` because it mutates `TRUSTY_MPM_REPOS_ROOT`.
#[tokio::test]
#[serial_test::serial]
async fn guided_fallback_redirect_success_worktree_not_live_checkout() {
    // ── Set up a real git base clone (minimal: init + one empty commit) ──────
    let repos_root = tempfile::tempdir().unwrap();
    // Repo path must match parse_github_path("https://github.com/test-owner-1724/test-repo-1724.git")
    let base = repos_root
        .path()
        .join("test-owner-1724")
        .join("test-repo-1724");
    std::fs::create_dir_all(&base).unwrap();

    let git_init_ok = std::process::Command::new("git")
        .arg("init")
        .current_dir(&base)
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !git_init_ok {
        eprintln!(
            "guided_fallback_redirect_success_worktree_not_live_checkout: git unavailable, skipping"
        );
        return;
    }
    // Configure minimal git identity so commit doesn't fail.
    let _ = std::process::Command::new("git")
        .args([
            "-C",
            base.to_str().unwrap(),
            "config",
            "user.email",
            "ci@test.invalid",
        ])
        .status();
    let _ = std::process::Command::new("git")
        .args(["-C", base.to_str().unwrap(), "config", "user.name", "CI"])
        .status();
    // One empty commit gives us a HEAD branch so `git worktree add` succeeds.
    let commit_ok = std::process::Command::new("git")
        .args([
            "-C",
            base.to_str().unwrap(),
            "commit",
            "--allow-empty",
            "-m",
            "init",
        ])
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !commit_ok {
        eprintln!(
            "guided_fallback_redirect_success_worktree_not_live_checkout: git commit failed, skipping"
        );
        return;
    }

    // ── Set up a live checkout with the matching GitHub remote ───────────────
    let live_dir = tempfile::tempdir().unwrap();
    let _ = std::process::Command::new("git")
        .arg("init")
        .current_dir(live_dir.path())
        .status();
    let _ = std::process::Command::new("git")
        .args([
            "remote",
            "add",
            "origin",
            "https://github.com/test-owner-1724/test-repo-1724.git",
        ])
        .current_dir(live_dir.path())
        .status();

    let _repos_root_env = ReposRootEnv::set(repos_root.path());

    let client = reqwest::Client::new();
    // #8545: the launch writes its user-home state under a temp home, never
    // the operator's.
    let fw_home = crate::test_support::hermetic_temp_dir();
    // #7603: pin the measurement — this test asserts where the fallback deploys,
    // never anything about the host's volume. #6542: the session it launches
    // lands on `run_fallback`'s private tmux server.
    let _run = run_fallback(
        &client,
        "http://127.0.0.1:1",
        live_dir.path(),
        &empty_disk(),
        Some(fw_home.path()),
    )
    .await;

    // ── Acceptance criteria (#1724 success path) ─────────────────────────────
    // Live checkout must be untouched.
    assert!(
        !live_dir.path().join("CLAUDE.md").exists(),
        "#1724: CLAUDE.md must NOT appear in the live checkout after redirect"
    );
    assert!(
        !live_dir.path().join(".mcp.json").exists(),
        "#1724: .mcp.json must NOT appear in the live checkout after redirect"
    );
    assert!(
        !live_dir.path().join(".trusty-mpm").exists(),
        "#1724: .trusty-mpm must NOT be created in the live checkout"
    );
    assert!(
        !live_dir.path().join(".claude").exists(),
        "#1724: .claude must NOT be created in the live checkout"
    );
    // A per-session worktree must have been created inside the base clone,
    // proving `launch(Some(worktree))` was called, not `launch(None)`.
    let worktrees_dir = base.join(".worktrees");
    assert!(
        worktrees_dir.exists(),
        "#1724 #1803: .worktrees/ dir must exist under base clone after successful redirect"
    );
    let sessions: Vec<_> = std::fs::read_dir(&worktrees_dir)
        .expect(".worktrees dir must be listable")
        .filter_map(|e| e.ok())
        .collect();
    assert!(
        !sessions.is_empty(),
        "#1724 #1803: at least one per-session worktree must be present under .worktrees/, \
         proving launch(Some(worktree)) was invoked rather than launch(None)"
    );
}

/// The guided fallback prepares the session IN the worktree it provisioned,
/// not in the shared base clone (#5836 critic HIGH).
///
/// Why: `guided_fallback_redirect_success_worktree_not_live_checkout` above
/// asserts only that a worktree EXISTS under `<base>/.worktrees`, and
/// `provision_for_fallback` creates that worktree before `launch()` runs — so
/// that test passes whether the session then runs in the worktree or somewhere
/// else entirely. It stayed green while `provision_for_launch`'s managed-checkout
/// redirect discarded the worktree and collapsed the placement onto `<base>`,
/// which puts two concurrent daemon-unreachable sessions in one tree.
/// What: same fixture as the test above, then asserts on the DIRECTORY the
/// session was prepared in — `prepare_isolated_session` deploys `.claude/` into
/// the placement `launch()` resolved, so the worktree must carry it and the base
/// clone must not.
/// Test: this is the test. RED at 34da769f: `.claude` appeared in `<base>`.
#[tokio::test]
#[serial_test::serial]
async fn guided_fallback_prepares_the_session_in_the_worktree_not_the_base_clone() {
    let origin = "https://github.com/test-owner-5836/test-repo-5836.git";
    let repos_root = tempfile::tempdir().unwrap();
    // Canonical because `find_git_root` resolves the macOS `/var` symlink and
    // the placement rule compares paths by plain equality (ADR-0037).
    let repos_root_path = repos_root.path().canonicalize().unwrap();
    // Must match `parse_github_path(origin)`.
    let base = repos_root_path
        .join("test-owner-5836")
        .join("test-repo-5836");
    fallback_git_repo(&base);
    // The base clone carries the origin its worktrees inherit — without it
    // `launch()` stops at "no git origin remote found" and never reaches
    // placement at all.
    fallback_git_remote(&base, origin);

    let live_dir = tempfile::tempdir().unwrap();
    fallback_git_repo(live_dir.path());
    fallback_git_remote(live_dir.path(), origin);

    let _repos_root_env = ReposRootEnv::set(&repos_root_path);

    let client = reqwest::Client::new();
    // #8545: the launch writes its user-home state under a temp home, never
    // the operator's.
    let fw_home = crate::test_support::hermetic_temp_dir();
    // #7603: pin the measurement — this test asserts where the fallback deploys,
    // never anything about the host's volume. #6542: the session it launches
    // lands on `run_fallback`'s private tmux server.
    let _run = run_fallback(
        &client,
        "http://127.0.0.1:1",
        live_dir.path(),
        &empty_disk(),
        Some(fw_home.path()),
    )
    .await;

    // Exactly one worktree, and it is the directory the session must run in.
    let worktrees_dir = base.join(".worktrees");
    let mut sessions: Vec<std::path::PathBuf> = std::fs::read_dir(&worktrees_dir)
        .expect(".worktrees must be listable — the fallback provisions it")
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .collect();
    sessions.sort();
    assert_eq!(
        sessions.len(),
        1,
        "the fallback provisions exactly one per-session worktree, found {sessions:?}"
    );
    let worktree = &sessions[0];

    assert!(
        !base.join(".claude").exists(),
        "the shared base clone must NOT become the session directory — the \
         fallback already resolved placement to {}",
        worktree.display()
    );
    assert!(
        !base.join("CLAUDE.md").exists(),
        "the shared base clone must NOT be deployed into: {}",
        base.join("CLAUDE.md").display()
    );
    assert!(
        worktree.join(".claude").is_dir(),
        "the session must be prepared in the worktree the fallback provisioned: {} \
         has no .claude",
        worktree.display()
    );
    // #8545: the session-scoped MCP config is composed under the injected home,
    // not the process home's `~/.trusty-tools/trusty-mpm/session-mcp/`.
    let session_mcp = trusty_mpm::core::paths::FrameworkPaths::under(fw_home.path())
        .crate_config_root()
        .join(trusty_mpm::core::session_mcp_scope::SESSION_MCP_DIR);
    let composed = std::fs::read_dir(&session_mcp).map_or(0, |d| d.count());
    assert_eq!(
        composed,
        1,
        "the launch must compose exactly one session MCP config under {}",
        session_mcp.display()
    );
}

/// The real tmux binary, resolved outside any `with_tmux_binary` scope.
fn fallback_tmux_bin() -> String {
    trusty_mpm::core::tmux::resolve_tmux_binary_or_bare()
}

/// The guided fallback launches onto its private tmux server, never the
/// default one, and that server dies with the run (#6542).
///
/// Why: #6579 reaped the fallback's session from the SHARED default server by
/// matching its pane path under the fixture root. A reap that misses leaves a
/// live `tm-<uuid>` session on the operator's server, and one did on
/// 2026-09-27 (`tm-f6f37ec5-c119-4fd5-9`). Nothing asserted where the
/// session was created, only that a reap ran.
/// What: watches the default server for sessions whose pane sits under the
/// fixture root, runs the fallback through [`run_fallback`], then asserts the
/// launch reached tmux on the private server, created nothing under the root on
/// the default server, and left no private session alive. `NestedTmuxPaneEnv`
/// keeps the launched session alive past `launch()` so the first assertion has
/// something to see; the default-server watch still reaps on drop if the second
/// assertion fails.
/// Test: this is the test. RED at 62b6f29e1's launch path (no
/// `with_tmux_binary` scope): the session appears on the default server.
#[tokio::test]
#[serial_test::serial]
async fn guided_fallback_leaves_no_tmux_session_behind() {
    let tmux = fallback_tmux_bin();
    if !ScratchTmuxSession::tmux_available(&tmux) {
        eprintln!("guided_fallback_leaves_no_tmux_session_behind: tmux unavailable, skipping");
        return;
    }
    // #6542: pin the nested-attach branch instead of inheriting it from the
    // host, or this test asserts on nothing wherever `$TMUX` is unset.
    let _nested_tmux = NestedTmuxPaneEnv::pin();

    let origin = "https://github.com/test-owner-6542/test-repo-6542.git";
    let repos_root = tempfile::tempdir().unwrap();
    let repos_root_path = repos_root.path().canonicalize().unwrap();
    let base = repos_root_path
        .join("test-owner-6542")
        .join("test-repo-6542");
    fallback_git_repo(&base);
    fallback_git_remote(&base, origin);

    let live_dir = tempfile::tempdir().unwrap();
    fallback_git_repo(live_dir.path());
    fallback_git_remote(live_dir.path(), origin);

    let _repos_root_env = ReposRootEnv::set(&repos_root_path);
    // Only sessions under this test's own root count, so the operator's other
    // sessions coming and going cannot flake it.
    let default_server = FixtureTmuxSessions::watch(&tmux, &repos_root_path);

    let client = reqwest::Client::new();
    // #8545: the launch writes its user-home state under a temp home, never
    // the operator's.
    let fw_home = crate::test_support::hermetic_temp_dir();
    // #7603: pin the measurement — this test asserts where the fallback deploys,
    // never anything about the host's volume.
    let run = run_fallback(
        &client,
        "http://127.0.0.1:1",
        live_dir.path(),
        &empty_disk(),
        Some(fw_home.path()),
    )
    .await;

    let leaked = default_server.spawned();
    assert!(
        leaked.is_empty(),
        "the fallback created {leaked:?} on the DEFAULT tmux server under {} — \
         this is #6542; every launch must land on run_fallback's private server",
        repos_root_path.display()
    );
    assert!(
        !run.private_sessions.is_empty(),
        "fixture precondition: the fallback must have launched a tmux session on \
         the private server, or the assertions around it prove nothing. \
         `NestedTmuxPaneEnv::pin` sets $TMUX_PANE so `tmux_attach` takes its \
         nested branch, fails closed, and leaves the session alive; an empty set \
         means that branch was not taken. result: {:?}",
        run.result
    );
    for name in &run.private_sessions {
        assert!(
            !ScratchTmuxSession::exists_on_socket(&tmux, Some(&run.socket), name),
            "session '{name}' outlived its private server — the tm-<uuid> pty \
             leak tracked in #6523"
        );
    }
}

/// No `tm`-bin test calls the guided fallback except through [`run_fallback`]
/// (#6542).
///
/// Why: #6579 fixed the leak per test, so the next test that called the
/// fallback directly could leak again by forgetting a guard. Binding the call
/// sites makes forgetting a test failure.
/// What: scans every `.rs` file under `src/bin/tm/` except `commands/guided.rs`
/// (the definitions and the production caller) for a call to either fallback
/// entry point outside a `//` comment. The only one allowed is the single call
/// inside `run_fallback` in this file.
/// Test: this is the test. RED at 62b6f29e1: 11 direct calls in this file and
/// 2 in `tests_behavior_c_tests.rs`.
#[test]
fn every_guided_fallback_call_runs_on_a_private_tmux_server() {
    // Spelled in pieces so this test's own source does not match itself.
    let needles = [
        concat!("fallback_protected", "("),
        concat!("fallback_protected_gated", "("),
    ];
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/bin/tm");
    let mut pending = vec![root.clone()];
    let mut calls = Vec::new();
    while let Some(dir) = pending.pop() {
        for entry in std::fs::read_dir(&dir).expect("src/bin/tm is listable") {
            let path = entry.expect("dir entry").path();
            if path.is_dir() {
                pending.push(path);
                continue;
            }
            let rel = path.strip_prefix(&root).expect("under root").to_path_buf();
            if path.extension().is_none_or(|e| e != "rs") || rel.ends_with("commands/guided.rs") {
                continue;
            }
            let text = std::fs::read_to_string(&path).expect("source is readable");
            for (i, line) in text.lines().enumerate() {
                let code = line.trim_start();
                if !code.starts_with("//") && needles.iter().any(|n| code.contains(n)) {
                    calls.push(format!("{}:{}: {}", rel.display(), i + 1, code));
                }
            }
        }
    }
    assert!(
        calls.len() == 1 && calls[0].starts_with("tests_behavior_b_tests.rs:"),
        "expected exactly one guided-fallback call, inside `run_fallback`; found \
         {calls:#?}. Drive the fallback through `run_fallback` or \
         `run_fallback_default` so its tmux session lands on a private server (#6542)"
    );
}

/// A git repository with one empty commit at `path`, created or asserted.
///
/// Why: `git worktree add` needs a HEAD commit, and a fixture that cannot be
/// built is a test failure rather than a skip — the older fallback tests above
/// return early when git is missing, which hides a broken fixture as a pass.
/// What: `git init` + identity + `commit --allow-empty`, asserting each step.
/// Test: used by `guided_fallback_prepares_the_session_in_the_worktree_not_the_base_clone`.
fn fallback_git_repo(path: &std::path::Path) {
    std::fs::create_dir_all(path).unwrap();
    let run = |args: &[&str]| {
        let status = std::process::Command::new("git")
            .args(args)
            .current_dir(path)
            .status()
            .unwrap_or_else(|e| panic!("git {args:?} failed to spawn: {e}"));
        assert!(
            status.success(),
            "git {args:?} failed in {}",
            path.display()
        );
    };
    run(&["init"]);
    run(&["config", "user.email", "ci@test.invalid"]);
    run(&["config", "user.name", "CI"]);
    run(&["commit", "--allow-empty", "-m", "init"]);
}

/// RAII override of `TRUSTY_MPM_REPOS_ROOT`, restored on drop (unwind included).
///
/// Why: the two fallback tests here each open-coded a set + two-arm restore, and
/// each restored BEFORE its assertions so a panicking assertion could not leak
/// the variable — six process-global writes to work around a problem `Drop`
/// does not have. One guard covers both and shrinks this file's
/// `ENV_MUTATION_BUDGET` row rather than growing it.
/// What: sets the var on construction, restores the previous value (or removes
/// it) on drop. Callers MUST be `#[serial_test::serial]` — the variable is
/// process-global.
/// Test: used by the two `guided_fallback_*` tests above.
struct ReposRootEnv {
    prev: Option<std::ffi::OsString>,
}

impl ReposRootEnv {
    fn set(path: &std::path::Path) -> Self {
        let key = trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV;
        let prev = std::env::var_os(key);
        // SAFETY: every caller is `#[serial_test::serial]`, so no other test
        // thread races this set/restore.
        unsafe { std::env::set_var(key, path) };
        Self { prev }
    }
}

impl Drop for ReposRootEnv {
    fn drop(&mut self) {
        let key = trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV;
        // SAFETY: see `set`.
        match self.prev.take() {
            Some(v) => unsafe { std::env::set_var(key, v) },
            None => unsafe { std::env::remove_var(key) },
        }
    }
}

/// A `$TMUX_PANE` value no live tmux server can resolve (#6542).
///
/// Pane ids count up from `%0`, so nine digits is out of reach of any real
/// server. `pane_tty_for` therefore returns `None` and `switch_client_to` fails
/// closed without ever running `switch-client` — which also stops this test
/// retargeting the operator's own terminal when someone runs it from a real
/// tty inside tmux.
const UNRESOLVABLE_TMUX_PANE: &str = "%999999999";

/// RAII override of `$TMUX_PANE`, restored on drop (unwind included) (#6542).
///
/// Why: the leak `guided_fallback_leaves_no_tmux_session_behind` exists to
/// catch only happens on the nested-tmux attach branch. With `$TMUX_PANE` set,
/// `tmux_attach` calls `switch_client_to`, which fails closed and returns
/// `Ok(AttachOutcome::TargetUnresolved)`; `launch` reads that `Ok` as a
/// successful attach, disarms its `LaunchSessionGuard`, and the session
/// survives. With `$TMUX_PANE` unset — every GitHub runner — `tmux_attach`
/// runs `attach-session`, which exits `open terminal failed: not a terminal`,
/// so `launch` bails and its own guard reaps the session before the test can
/// see it. The test inherited that variable from the host, so it passed on the
/// owner's tmux-hosted shell and panicked on its fixture precondition in CI.
/// What: sets `$TMUX_PANE` to [`UNRESOLVABLE_TMUX_PANE`] on construction and
/// restores the previous value (or removes it) on drop. Callers MUST be
/// `#[serial_test::serial]` — the variable is process-global.
/// Test: `guided_fallback_leaves_no_tmux_session_behind`.
struct NestedTmuxPaneEnv {
    prev: Option<std::ffi::OsString>,
}

impl NestedTmuxPaneEnv {
    fn pin() -> Self {
        let prev = std::env::var_os("TMUX_PANE");
        // SAFETY: every caller is `#[serial_test::serial]`, so no other test
        // thread races this set/restore.
        unsafe { std::env::set_var("TMUX_PANE", UNRESOLVABLE_TMUX_PANE) };
        Self { prev }
    }
}

impl Drop for NestedTmuxPaneEnv {
    fn drop(&mut self) {
        // SAFETY: see `pin`.
        match self.prev.take() {
            Some(v) => unsafe { std::env::set_var("TMUX_PANE", v) },
            None => unsafe { std::env::remove_var("TMUX_PANE") },
        }
    }
}

/// Point `path`'s `origin` remote at `url`.
fn fallback_git_remote(path: &std::path::Path, url: &str) {
    let status = std::process::Command::new("git")
        .args(["remote", "add", "origin", url])
        .current_dir(path)
        .status()
        .expect("git remote add must spawn");
    assert!(
        status.success(),
        "git remote add failed in {}",
        path.display()
    );
}

/// Issue #4203: every CLI path whose spawn carries `--setting-sources
/// project,local` must deploy through `prepare_isolated_session`, never through
/// a self-resolved `FrameworkPaths::default()`.
///
/// Why a SOURCE-TEXT guard rather than a behavioural one: `launch()`,
/// `connect()`, and `launch_and_wait()` are async functions that create tmux
/// sessions, register with the daemon over HTTP, and then block on
/// `attach-session`, so none of them is reachable from a unit test. A test that
/// exercises the deploy layout alone proves the layout is right while staying
/// completely silent if a call site stops using it — which is exactly how the
/// first version of this guard shipped green with the bug reintroduced in both
/// call sites. Binding the CALL SITES is the whole point, so the guard reads the
/// call sites. Source-text guards are the established idiom here
/// (`scripts/check_line_cap.sh` and the tracked-file CI guards are the same
/// shape).
///
/// What: asserts neither file constructs `FrameworkPaths::default()`, and that
/// each still routes through the isolated seam the expected number of times.
/// The counts are deliberately exact — a call site deleted or a fourth one added
/// without thought fails here and forces the author to confirm its spawn posture.
#[test]
fn launch_paths_prepare_through_the_isolated_seam() {
    // `include_str!` is relative to THIS file (`src/bin/tm/`).
    const LAUNCH_SRC: &str = include_str!("commands/launch.rs");
    const META_LAUNCH_SRC: &str = include_str!("commands/meta/launch.rs");

    for (name, src, expected_calls) in [
        ("commands/launch.rs", LAUNCH_SRC, 2usize),
        ("commands/meta/launch.rs", META_LAUNCH_SRC, 1usize),
    ] {
        assert!(
            !src.contains("FrameworkPaths::default()"),
            "{name} spawns `claude` with a `--setting-sources` flag \
             (`{}` when it cannot relocate `CLAUDE_CONFIG_DIR`, `{}` when it can \
             — #4181), and the non-relocated one excludes the `user` tier \
             `FrameworkPaths::default()` deploys into — deploy via \
             `session_launch::prepare_isolated_session` instead (issue #4203)",
            trusty_mpm::core::model_inject::SETTING_SOURCES_FLAG,
            trusty_mpm::core::model_inject::SETTING_SOURCES_FLAG_RELOCATED
        );
        // #8545: `_under` is the same seam with the home named.
        assert_eq!(
            src.matches("prepare_isolated_session(").count()
                + src.matches("prepare_isolated_session_under(").count(),
            expected_calls,
            "{name} must deploy through `prepare_isolated_session` exactly \
             {expected_calls}x (issue #4203); if a call site was added or removed, \
             confirm its spawn's `--setting-sources` posture and update this count"
        );
    }

    // `commands/session/start.rs` is deliberately NOT in the list above: it
    // spawns a bare `claude {PERMISSION_MODE_FLAG}` with no `--setting-sources`,
    // so Claude Code reads its default tiers INCLUDING `user` and
    // `FrameworkPaths::default()` is correct there. Pin that premise — if
    // `start.rs` ever gains the flag, it acquires this defect and this
    // assertion is what says so.
    const START_SRC: &str = include_str!("commands/session/start.rs");
    assert!(
        !START_SRC.contains("SETTING_SOURCES_FLAG"),
        "commands/session/start.rs now carries a `--setting-sources` flag, so its \
         `FrameworkPaths::default()` deploy has become the #4203 defect — route it \
         through `prepare_isolated_session` and add it to the list above"
    );
}

/// `tm commit-trailers` takes an optional `--message-file`; bare, it prints the
/// trailers. The bundled `prepare-commit-msg` hook passes the path git hands
/// it, so a rename of that flag silently stops every commit being stamped
/// (#7074).
#[test]
fn cli_parses_commit_trailers() {
    let bare = Cli::try_parse_from(["trusty-mpm", "commit-trailers"]).unwrap();
    match bare.command.unwrap() {
        Command::CommitTrailers(args) => assert_eq!(args.message_file, None),
        other => panic!("expected CommitTrailers, got {other:?}"),
    }

    let with_file = Cli::try_parse_from([
        "trusty-mpm",
        "commit-trailers",
        "--message-file",
        "/tmp/COMMIT_EDITMSG",
    ])
    .unwrap();
    match with_file.command.unwrap() {
        Command::CommitTrailers(args) => assert_eq!(
            args.message_file.as_deref(),
            Some(std::path::Path::new("/tmp/COMMIT_EDITMSG"))
        ),
        other => panic!("expected CommitTrailers, got {other:?}"),
    }
}

/// The default must touch NO binary and clobber NOTHING — a `tm reinstall`
/// typed with no flags refreshes assets only.
#[test]
fn cli_parses_reinstall() {
    let cli = Cli::try_parse_from(["trusty-mpm", "reinstall"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Reinstall(crate::cli::ReinstallArgs {
            force: false,
            binary: false,
            yes: false
        })
    ));
}

/// `--yes` only means "skip the binary prompt", so clap must reject it on its
/// own rather than let it read as blanket consent.
#[test]
fn cli_parses_reinstall_binary() {
    let cli = Cli::try_parse_from(["trusty-mpm", "reinstall", "--binary", "--yes"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Reinstall(crate::cli::ReinstallArgs {
            binary: true,
            yes: true,
            ..
        })
    ));
    assert!(Cli::try_parse_from(["trusty-mpm", "reinstall", "--yes"]).is_err());
}

/// #8405: `tm connect` turns the config under its root into the renderer, both
/// directions. Fails if the seam ignores the config (e.g. a hard-coded `false`).
#[test]
fn connect_claude_spec_follows_the_configured_renderer() {
    let cwd = std::path::Path::new("/work/p");
    for alternate_screen in [true, false] {
        let root = crate::test_support::config_root_with_alternate_screen(alternate_screen);
        let spec = crate::commands::launch::connect_claude_spec(
            cwd,
            None,
            None,
            &[],
            None,
            Some(root.path()),
        );
        let line = crate::test_support::spec_text(&spec);
        let want = crate::test_support::renderer_operand(alternate_screen);
        assert!(line.contains(want), "want {want:?} in: {line}");
    }
}

/// #8405: the `tm launch` seam, both directions.
#[test]
fn launch_claude_spec_follows_the_configured_renderer() {
    let cwd = std::path::Path::new("/work/p");
    for alternate_screen in [true, false] {
        let root = crate::test_support::config_root_with_alternate_screen(alternate_screen);
        let spec = crate::commands::launch::launch_claude_spec(
            cwd,
            Some(root.path()),
            "opus",
            None,
            None,
            &[],
            None,
        );
        let line = crate::test_support::spec_text(&spec);
        let want = crate::test_support::renderer_operand(alternate_screen);
        assert!(line.contains(want), "want {want:?} in: {line}");
    }
}