trusty-mpm 1.3.5

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

use std::path::PathBuf;
use std::sync::Mutex;

use crate::commands::first_run::needs_first_run_clone;

/// Serialises tests that set REPOS_ROOT_ENV via std::env::set_var.
///
/// Why: `std::env::set_var` is not thread-safe across concurrent tests (#1780).
/// Two tests that both manipulate the same env key will race unless they acquire
/// this lock first.
/// What: a module-level Mutex<()>; tests hold it for the duration of their
/// set_var / call / restore cycle so the env change is never visible to another
/// concurrent test.
/// Test: prevents `needs_first_run_clone_returns_none_when_clone_exists` from
/// racing `needs_first_run_clone_returns_some_when_no_clone`.
static ENV_MUTEX: Mutex<()> = Mutex::new(());
use crate::commands::guided::{
    CwdProject, NestedFallbackAction, NonGitFallbackPlan, classify_cwd_project, cwd_owns_git_entry,
    derive_project, fallback_protected, format_project_context_row, github_host,
    guard_managed_sessions, inplace_self_relaunch_hint, is_github_remote,
    ls_tree_reports_tracked_dir, managed_pane_settle_pending_message, nested_fallback_action,
    nested_guard_notice, non_github_refusal_message, plan_non_git_fallback, print_non_tty_hint,
    print_project_context, tty_gate, untracked_ancestor_message,
};
use crate::commands::guided_launch::spawn_progress_message;
use crate::commands::guided_resume::{
    ResumeAction, is_zombie, needs_restart, panes_prove_session_dead, parse_pane_probes,
    plan_resume, resume_classification_state, session_runtime_live,
};
// #3873: the CLI's dead-runtime verdict composes the daemon's OWN liveness
// primitives rather than reimplementing them, so the tests exercise that
// composition directly.
use trusty_mpm::daemon::orphan_gc::AlwaysIdleProbe;
// The picker decision enum + parser moved to the shared `session_picker` module.
use crate::commands::session_picker::{PickerDecision, parse_picker_choice};

// ── parse_picker_choice ───────────────────────────────────────────────────────

#[test]
fn guided_picker_bare_enter_no_sessions_launches_new() {
    // Why: bare Enter with no sessions must launch a new session, not hang.
    assert_eq!(
        parse_picker_choice("", &[], false),
        PickerDecision::LaunchNew
    );
    assert_eq!(
        parse_picker_choice("  \t", &[], false),
        PickerDecision::LaunchNew
    );
}

#[test]
fn guided_picker_bare_enter_live_session_resumes_first() {
    // Why: bare Enter when the most-recent session is LIVE (not needing a
    // restart) must resume it directly — attaching to a live pane is safe,
    // it never destroys anything (#2148).
    assert_eq!(
        parse_picker_choice("", &picker_fixture(1, &[]), false),
        PickerDecision::Resume(0)
    );
    assert_eq!(
        parse_picker_choice("  ", &picker_fixture(3, &[]), false),
        PickerDecision::Resume(0)
    );
}

#[test]
fn guided_picker_bare_enter_stopped_session_requires_confirm() {
    // #2148: bare Enter must NOT silently restart (kill+recreate the tmux pane
    // of) a stopped/errored session — the operator must type the number.
    assert_eq!(
        parse_picker_choice("", &picker_fixture(1, &[]), true),
        PickerDecision::ConfirmRestart(0)
    );
    assert_eq!(
        parse_picker_choice("  ", &picker_fixture(3, &[]), true),
        PickerDecision::ConfirmRestart(0)
    );
}

#[test]
fn guided_picker_bare_enter_unresumable_session_blocked() {
    // #2595: bare Enter must NEVER resume/restart a session whose workspace
    // is gone for good — no confirmation prompt would help, since the resume
    // is guaranteed to fail (#2577/#2594). This takes priority over
    // `ConfirmRestart` (`first_needs_restart=true` here too — a dead session
    // is ALWAYS stopped/errored, so both flags are set; `Unresumable` must win).
    assert_eq!(
        parse_picker_choice("", &picker_fixture(1, &[true]), true),
        PickerDecision::Unresumable(0)
    );
    assert_eq!(
        parse_picker_choice("  ", &picker_fixture(3, &[true, false, false]), true),
        PickerDecision::Unresumable(0)
    );
}

#[test]
fn guided_picker_numeric_unresumable_session_blocked() {
    // #2595: an EXPLICIT numeric choice must ALSO be blocked when it targets a
    // dead session — the pre-#2595 comment on the numeric branch ("always
    // restarts/resumes directly") is no longer true for this one case.
    assert_eq!(
        parse_picker_choice("2", &picker_fixture(3, &[false, true, false]), false),
        PickerDecision::Unresumable(1)
    );
    // A live session at a DIFFERENT index must still resume normally even
    // when another slot in the same menu is dead.
    assert_eq!(
        parse_picker_choice("1", &picker_fixture(3, &[false, true, false]), false),
        PickerDecision::Resume(0)
    );
}

#[test]
fn guided_picker_numeric_deleted_slot_blocked() {
    // #3034: typing a slot number the daemon reports as deleted must be a
    // clear, explicit outcome — never a silent fallthrough to whichever
    // session now occupies a neighboring row.
    let sessions = vec![
        at_slot(make_session("s1", "active", None), 1),
        deleted_slot(2),
        at_slot(make_session("s3", "active", None), 3),
    ];
    assert_eq!(
        parse_picker_choice("2", &sessions, false),
        PickerDecision::SlotDeleted(1)
    );
    // A live neighbor's number must still resolve normally.
    assert_eq!(
        parse_picker_choice("3", &sessions, false),
        PickerDecision::Resume(2)
    );
}

#[test]
fn guided_picker_bare_enter_on_deleted_first_slot_blocked() {
    // #3034: if slot 1 itself was deleted, bare Enter (which defaults to the
    // first displayed row) must report the tombstone, never silently resume
    // whatever now happens to be first in the vec.
    let sessions = vec![
        deleted_slot(1),
        at_slot(make_session("s2", "active", None), 2),
    ];
    assert_eq!(
        parse_picker_choice("", &sessions, false),
        PickerDecision::SlotDeleted(0)
    );
}

#[test]
fn guided_picker_delete_prefix_on_deleted_slot_blocked() {
    // #3034: `d<N>` on an already-deleted slot must not double-delete or
    // silently no-op — it resolves to the same clear `SlotDeleted` outcome.
    let sessions = vec![
        at_slot(make_session("s1", "active", None), 1),
        deleted_slot(2),
    ];
    assert_eq!(
        parse_picker_choice("d2", &sessions, false),
        PickerDecision::SlotDeleted(1)
    );
}

#[test]
fn guided_picker_launch_new_uses_highest_slot_with_gaps() {
    // #3034: the "launch new" marker must be (highest DISPLAYED slot) + 1,
    // not `sessions.len() + 1` — a tombstoned/filtered gap must not shift it.
    let sessions = vec![
        at_slot(make_session("s1", "active", None), 1),
        deleted_slot(5),
    ];
    assert_eq!(
        parse_picker_choice("6", &sessions, false),
        PickerDecision::LaunchNew
    );
    // The old `len()+1` value (3) must NOT be treated as launch-new here.
    assert_eq!(
        parse_picker_choice("3", &sessions, false),
        PickerDecision::Unrecognised
    );
}

#[test]
fn guided_picker_delete_parses_d_prefix() {
    // #2304: `d<N>` / `d <N>` selects the session whose stable slot is N.
    assert_eq!(
        parse_picker_choice("d1", &picker_fixture(1, &[]), false),
        PickerDecision::Delete(0)
    );
    assert_eq!(
        parse_picker_choice("d2", &picker_fixture(3, &[]), true),
        PickerDecision::Delete(1)
    );
    assert_eq!(
        parse_picker_choice("D3\n", &picker_fixture(3, &[]), false),
        PickerDecision::Delete(2)
    );
    assert_eq!(
        parse_picker_choice("d 2", &picker_fixture(3, &[]), false),
        PickerDecision::Delete(1)
    );
}

#[test]
fn guided_picker_delete_out_of_range_unrecognised() {
    // A `d`-prefixed choice matching no displayed slot (or non-numeric) is
    // rejected — never falls through to the resume/launch branches.
    assert_eq!(
        parse_picker_choice("d4", &picker_fixture(3, &[]), false),
        PickerDecision::Unrecognised
    );
    assert_eq!(
        parse_picker_choice("d0", &picker_fixture(3, &[]), false),
        PickerDecision::Unrecognised
    );
    assert_eq!(
        parse_picker_choice("dx", &picker_fixture(3, &[]), false),
        PickerDecision::Unrecognised
    );
}

#[test]
fn guided_picker_q_returns_quit() {
    // Why: "q" must quit cleanly without touching tmux or the daemon.
    assert_eq!(parse_picker_choice("q", &[], false), PickerDecision::Quit);
    assert_eq!(
        parse_picker_choice("q", &picker_fixture(3, &[]), true),
        PickerDecision::Quit
    );
}

#[test]
fn guided_picker_q_uppercase_returns_quit() {
    // Why: "Q" must be treated identically to "q" (case-insensitive).
    assert_eq!(
        parse_picker_choice("Q", &picker_fixture(2, &[]), false),
        PickerDecision::Quit
    );
    assert_eq!(parse_picker_choice("Q\n", &[], false), PickerDecision::Quit);
}

#[test]
fn guided_picker_numeric_valid_resumes() {
    // Why: "[N]" matching a live session's slot must resume it — an EXPLICIT
    // numeric choice always dispatches directly, regardless of
    // `first_needs_restart` (that flag only gates bare Enter).
    assert_eq!(
        parse_picker_choice("1", &picker_fixture(1, &[]), true),
        PickerDecision::Resume(0)
    );
    assert_eq!(
        parse_picker_choice("1", &picker_fixture(3, &[]), true),
        PickerDecision::Resume(0)
    );
    assert_eq!(
        parse_picker_choice("2", &picker_fixture(3, &[]), false),
        PickerDecision::Resume(1)
    );
    assert_eq!(
        parse_picker_choice("3", &picker_fixture(3, &[]), false),
        PickerDecision::Resume(2)
    );
    // With newline (as stdin read_line returns)
    assert_eq!(
        parse_picker_choice("2\n", &picker_fixture(3, &[]), false),
        PickerDecision::Resume(1)
    );
}

#[test]
fn guided_picker_numeric_launch_new() {
    // Why: "[highest slot + 1]" must always launch a new session.
    assert_eq!(
        parse_picker_choice("1", &[], false),
        PickerDecision::LaunchNew
    );
    assert_eq!(
        parse_picker_choice("4", &picker_fixture(3, &[]), false),
        PickerDecision::LaunchNew
    );
}

#[test]
fn guided_picker_stale_daemon_slots_render_distinct_incrementing_choices() {
    // #3678: a daemon that predates #3034 omits `slot`/`deleted` from its
    // response entirely, so `#[serde(default)]` decodes EVERY row's `slot`
    // to the shared `0` sentinel — exactly the shape `make_session` produces
    // by default (slot: 0) when nothing calls `at_slot`/`picker_fixture`.
    // Before the #3678 fix, every choice below would have resolved to
    // `Resume(0)` (the first row) and "launch new" would always sit at a
    // fixed `[1]` regardless of list length. The picker must instead treat
    // this as a stale-daemon menu and fall back to distinct, incrementing
    // 1-based positions for this listing.
    let sessions = vec![
        make_session("s1", "active", None),
        make_session("s2", "active", None),
        make_session("s3", "active", None),
    ];
    assert_eq!(
        parse_picker_choice("1", &sessions, false),
        PickerDecision::Resume(0)
    );
    assert_eq!(
        parse_picker_choice("2", &sessions, false),
        PickerDecision::Resume(1)
    );
    assert_eq!(
        parse_picker_choice("3", &sessions, false),
        PickerDecision::Resume(2)
    );
    // "launch new" follows the last positional row (4 = count + 1), not a
    // fixed `1` (the pre-fix `sessions.last().slot + 1 == 0 + 1` bug).
    assert_eq!(
        parse_picker_choice("4", &sessions, false),
        PickerDecision::LaunchNew
    );
}

#[test]
fn guided_picker_stale_daemon_numeric_choice_resolves_correct_row() {
    // #3678 selection-mapping regression: previously EVERY numeric choice
    // resolved to the FIRST row, because every session's `.slot` decoded to
    // the same `0` sentinel and the by-slot lookup (`Vec::position`) always
    // returns the first match. Typing "2" must resolve to the SECOND row
    // (index 1), never the first.
    let sessions = vec![
        make_session("s1", "active", None),
        make_session("s2", "active", None),
        make_session("s3", "active", None),
    ];
    assert_eq!(
        parse_picker_choice("2", &sessions, false),
        PickerDecision::Resume(1),
        "typing 2 must resolve to the second row, not always the first"
    );
    assert_ne!(
        parse_picker_choice("2", &sessions, false),
        PickerDecision::Resume(0)
    );
}

#[test]
fn guided_picker_out_of_range_unrecognised() {
    // Why: a number matching no displayed slot and not the launch-new marker
    // must not silently resume or launch — it must be rejected cleanly.
    assert_eq!(
        parse_picker_choice("5", &picker_fixture(3, &[]), false),
        PickerDecision::Unrecognised
    );
    assert_eq!(
        parse_picker_choice("100", &picker_fixture(1, &[]), false),
        PickerDecision::Unrecognised
    );
    assert_eq!(
        parse_picker_choice("0", &picker_fixture(3, &[]), false),
        PickerDecision::Unrecognised
    );
}

#[test]
fn guided_picker_non_numeric_unrecognised() {
    // Why: arbitrary text input must be rejected without panicking.
    assert_eq!(
        parse_picker_choice("abc", &picker_fixture(2, &[]), false),
        PickerDecision::Unrecognised
    );
    assert_eq!(
        parse_picker_choice("exit", &[], false),
        PickerDecision::Unrecognised
    );
    assert_eq!(
        parse_picker_choice("1a", &picker_fixture(3, &[]), false),
        PickerDecision::Unrecognised
    );
}

#[test]
fn guided_picker_ls_returns_list_sessions() {
    // Why: #3863 — "ls" must re-print the list, not resume/launch/quit, and
    // must work regardless of case, surrounding whitespace, or whether the
    // list is empty.
    assert_eq!(
        parse_picker_choice("ls", &picker_fixture(3, &[]), false),
        PickerDecision::ListSessions
    );
    assert_eq!(
        parse_picker_choice("LS", &picker_fixture(3, &[]), false),
        PickerDecision::ListSessions
    );
    assert_eq!(
        parse_picker_choice("ls\n", &[], false),
        PickerDecision::ListSessions
    );
    assert_eq!(
        parse_picker_choice("  ls  ", &picker_fixture(1, &[]), false),
        PickerDecision::ListSessions
    );
}

#[test]
fn guided_picker_list_returns_list_sessions() {
    // Why: #3863 — "list" is the accepted long form, same semantics as "ls".
    assert_eq!(
        parse_picker_choice("list", &picker_fixture(3, &[]), false),
        PickerDecision::ListSessions
    );
    assert_eq!(
        parse_picker_choice("List", &picker_fixture(3, &[]), false),
        PickerDecision::ListSessions
    );
    assert_eq!(
        parse_picker_choice("LIST\n", &[], false),
        PickerDecision::ListSessions
    );
}

#[test]
fn guided_picker_ls_does_not_shadow_launch_new_or_delete_prefix() {
    // Why: guard against a careless implementation matching "ls"/"list" as a
    // substring prefix rather than the whole trimmed token — must not
    // swallow legitimate `d<N>`/`r<N>` input or other look-alikes.
    assert_eq!(
        parse_picker_choice("list1", &picker_fixture(3, &[]), false),
        PickerDecision::Unrecognised
    );
    assert_eq!(
        parse_picker_choice("lsx", &picker_fixture(3, &[]), false),
        PickerDecision::Unrecognised
    );
}

// ── tty_gate ──────────────────────────────────────────────────────────────────

#[test]
fn guided_non_tty_gate_returns_false_skips_stdin() {
    // Why: when is_tty=false the function must return false so the caller
    // returns Ok(()) without ever reading from stdin — the core of AC-7.
    // This test exercises the non-TTY branch without any live stdin.
    let result = tty_gate(false, "owner/repo", &PathBuf::from("/ws/owner/repo"), &[]);
    assert!(
        !result,
        "non-TTY gate must return false (no picker) for empty sessions"
    );
}

#[test]
fn guided_tty_gate_returns_true_for_tty() {
    // Why: when is_tty=true the function must return true so the caller
    // proceeds to run_tty_picker.
    let result = tty_gate(true, "owner/repo", &PathBuf::from("/ws/owner/repo"), &[]);
    assert!(
        result,
        "TTY gate must return true so caller runs the picker"
    );
}

#[test]
fn guided_non_tty_gate_returns_false_with_sessions() {
    // Why: the non-TTY branch must work even when sessions are present —
    // ensuring the hint path handles the session list safely.
    let sessions = vec![make_session("tm-api-1", "running", None)];
    let result = tty_gate(false, "owner/repo", &PathBuf::from("/ws"), &sessions);
    assert!(
        !result,
        "non-TTY gate must return false regardless of session count"
    );
}

// ── derive_project ────────────────────────────────────────────────────────────

#[test]
fn guided_derive_project_returns_none_for_non_git_dir() {
    // Why: a plain temp directory (not a git repo) should not yield a project.
    // What: derive_project(temp_dir) must return None.
    let tmp = std::env::temp_dir();
    let non_git = tmp.join("trusty_test_non_git_dir_1705");
    std::fs::create_dir_all(&non_git).ok();
    let result = derive_project(&non_git);
    assert!(
        result.is_none(),
        "expected None for non-git dir, got {result:?}"
    );
}

#[test]
fn guided_derive_project_rejects_non_github_remote() {
    // Why: if the origin is not a GitHub URL, derive_project must return None
    // so the live-checkout guard fires downstream.
    let tmp = tempdir_with_name("trusty_test_non_github_remote_1705");
    let ok = git_init_quiet(&tmp);
    if !ok {
        return; // git unavailable
    }
    git_remote_add(&tmp, "https://gitlab.com/owner/repo.git");
    let result = derive_project(&tmp);
    assert!(
        result.is_none(),
        "expected None for non-GitHub remote (gitlab), got {result:?}"
    );
}

#[test]
fn guided_derive_project_accepts_github_https_remote() {
    // Why: a valid HTTPS GitHub remote must parse correctly and return the
    // expected source_id, a non-empty workspace path, and the git root.
    let tmp = tempdir_with_name("trusty_test_github_https_1705");
    let ok = git_init_with_commit(&tmp);
    if !ok {
        return;
    }
    git_remote_add(&tmp, "https://github.com/owner/my-repo.git");
    let result = derive_project(&tmp);
    match result {
        Some((source_id, workspace, git_root)) => {
            assert_eq!(source_id, "owner/my-repo");
            assert!(
                !workspace.as_os_str().is_empty(),
                "workspace must be non-empty"
            );
            // workspace must be the managed clone path, not the live checkout
            assert_ne!(workspace, tmp, "workspace must differ from live checkout");
            // git_root must resolve to tmp (the repo root). On macOS /var is a
            // symlink to /private/var; git resolves the canonical path, so compare
            // canonicalized forms.
            let canonical_root = git_root.canonicalize().unwrap_or(git_root);
            let canonical_tmp = tmp.canonicalize().unwrap_or(tmp.clone());
            assert_eq!(
                canonical_root, canonical_tmp,
                "git_root must be the repo root"
            );
        }
        None => panic!("expected Some for GitHub HTTPS remote, got None"),
    }
}

#[test]
fn guided_derive_project_accepts_github_ssh_remote() {
    // Why: SSH-style GitHub remotes (`git@github.com:owner/repo.git`) must be
    // detected in the same way as HTTPS remotes.
    let tmp = tempdir_with_name("trusty_test_github_ssh_1705");
    let ok = git_init_with_commit(&tmp);
    if !ok {
        return;
    }
    git_remote_add(&tmp, "git@github.com:owner/my-repo.git");
    let result = derive_project(&tmp);
    match result {
        Some((source_id, _workspace, _git_root)) => {
            assert_eq!(source_id, "owner/my-repo");
        }
        None => panic!("expected Some for GitHub SSH remote, got None"),
    }
}

#[test]
fn guided_derive_project_returns_some_from_subdir() {
    // Why: derive_project must work when called from a subdirectory of a git
    // repo, and the returned git_root must be the repo root (not the subdir)
    // so that `launch_new_session_and_attach` passes the git root as repo_url
    // and the daemon finds .git, sets source_id correctly (#1705 LOW fix).
    // The subdir here is TRACKED (committed) — an untracked ancestor subdir is
    // deliberately rejected as of #2534 (see the dedicated test below).
    let tmp = tempdir_with_name("trusty_test_subdir_1705");
    let ok = git_init_with_commit(&tmp);
    if !ok {
        return;
    }
    git_remote_add(&tmp, "https://github.com/owner/my-repo.git");

    // Create a nested subdirectory, TRACK it, then call derive_project from it.
    let subdir = tmp.join("src").join("lib");
    std::fs::create_dir_all(&subdir).unwrap();
    git_track_dir(&tmp, "src/lib");

    let result = derive_project(&subdir);
    match result {
        Some((source_id, _workspace, git_root)) => {
            assert_eq!(source_id, "owner/my-repo");
            // git_root must be the repo root (tmp), NOT the subdir. On macOS
            // /var is a symlink to /private/var; compare canonical forms.
            let canonical_root = git_root.canonicalize().unwrap_or(git_root);
            let canonical_tmp = tmp.canonicalize().unwrap_or(tmp.clone());
            assert_eq!(
                canonical_root, canonical_tmp,
                "git_root from subdir must be repo root, not the nested dir"
            );
        }
        None => panic!("expected Some when calling derive_project from a subdir"),
    }
}

// ── Ancestor-repo trust guard (#2534) ─────────────────────────────────────────

#[test]
fn guided_ls_tree_reports_tracked_dir_true_for_named_entry() {
    // Why: git prints the queried path (one line) when it names a tracked tree.
    assert!(ls_tree_reports_tracked_dir("CTO\n"));
    assert!(ls_tree_reports_tracked_dir("src/lib\n"));
}

#[test]
fn guided_ls_tree_reports_tracked_dir_false_for_empty() {
    // Why: an untracked (or case-mismatched) path yields empty stdout — the
    // exact discriminator for the APFS `cto` vs tracked `CTO` collision (#2534).
    assert!(!ls_tree_reports_tracked_dir(""));
}

#[test]
fn guided_ls_tree_reports_tracked_dir_false_for_blank_lines() {
    // Why: whitespace-only output must not be mistaken for a tracked entry.
    assert!(!ls_tree_reports_tracked_dir("\n  \n\t\n"));
}

#[test]
fn guided_untracked_ancestor_message_names_root() {
    // Why: the operator must see WHICH enclosing repo was declined.
    let msg = untracked_ancestor_message(std::path::Path::new("/Users/masa/Duetto"));
    assert!(
        msg.contains("/Users/masa/Duetto"),
        "message must name the enclosing git root: {msg}"
    );
    assert!(
        msg.contains("not part of it"),
        "message must explain the untracked-ancestor reason: {msg}"
    );
}

#[test]
fn guided_untracked_ancestor_message_does_not_claim_launch() {
    // Why: the whole point is that we did NOT launch the ancestor project.
    let msg = untracked_ancestor_message(std::path::Path::new("/repo"));
    assert!(
        msg.contains("not launching that project"),
        "message must state the project was not launched: {msg}"
    );
}

#[test]
fn guided_classify_cwd_not_git_for_plain_dir() {
    // Why: a directory outside any git working tree is NotGit.
    let tmp = tempdir_with_name("trusty_test_classify_plain_2534");
    // Skip if the temp dir happens to be inside a git tree (dev machines vary).
    if find_git_root_via_cli(&tmp).is_some() {
        return;
    }
    assert!(matches!(classify_cwd_project(&tmp), CwdProject::NotGit));
}

#[test]
fn guided_classify_cwd_usable_for_repo_root() {
    // Why: the top-level case is trusted unconditionally — behavior unchanged.
    let tmp = tempdir_with_name("trusty_test_classify_root_2534");
    if !git_init_with_commit(&tmp) {
        return;
    }
    let canonical = tmp.canonicalize().unwrap_or_else(|_| tmp.clone());
    match classify_cwd_project(&canonical) {
        CwdProject::Usable(root) => {
            let root = root.canonicalize().unwrap_or(root);
            assert_eq!(root, canonical, "repo root must classify as Usable(root)");
        }
        _ => panic!("repo root must be Usable"),
    }
}

#[test]
fn guided_classify_cwd_usable_for_tracked_subdir() {
    // Why: a committed subdirectory genuinely belongs to the repo — Usable.
    let tmp = tempdir_with_name("trusty_test_classify_tracked_2534");
    if !git_init_with_commit(&tmp) {
        return;
    }
    git_track_dir(&tmp, "src/lib");
    let subdir = tmp.join("src").join("lib");
    match classify_cwd_project(&subdir) {
        CwdProject::Usable(_) => {}
        _ => panic!("tracked subdir must be Usable"),
    }
}

#[test]
fn guided_classify_cwd_untracked_for_uncommitted_subdir() {
    // Why: the core #2534 regression — a directory that physically exists inside
    // a repo's working tree but is NOT in its tracked tree (the same shape as the
    // APFS `~/Duetto/cto` case-fold collision) must be UntrackedInsideAncestor,
    // NOT trusted as part of the enclosing repo.
    let tmp = tempdir_with_name("trusty_test_classify_untracked_2534");
    if !git_init_with_commit(&tmp) {
        return;
    }
    // Create a subdir but never `git add` it → not in HEAD's tree.
    let untracked = tmp.join("notes");
    std::fs::create_dir_all(&untracked).unwrap();
    match classify_cwd_project(&untracked) {
        CwdProject::UntrackedInsideAncestor(_) => {}
        CwdProject::Usable(_) => {
            panic!("untracked subdir must NOT be trusted as part of the ancestor repo")
        }
        CwdProject::NotGit => panic!("subdir is inside a git tree — must not be NotGit"),
    }
}

#[test]
fn guided_derive_project_returns_none_for_untracked_ancestor_subdir() {
    // Why: the end-to-end #2534 guarantee — bare `tm` from an untracked directory
    // nested inside a GitHub repo must NOT resolve to that ancestor's project.
    let tmp = tempdir_with_name("trusty_test_derive_untracked_2534");
    if !git_init_with_commit(&tmp) {
        return;
    }
    git_remote_add(&tmp, "https://github.com/owner/my-repo.git");
    let untracked = tmp.join("notes");
    std::fs::create_dir_all(&untracked).unwrap();
    assert!(
        derive_project(&untracked).is_none(),
        "derive_project must return None for an untracked ancestor subdir"
    );
}

// ── #2542: own-repo-wins (cwd's own `.git` beats an ancestor's) ───────────────

#[test]
fn guided_cwd_owns_git_entry_true_for_dir() {
    // Why: a `.git` DIRECTORY is the normal repository marker.
    let tmp = tempdir_with_name("trusty_test_owns_git_dir_2542");
    std::fs::create_dir_all(tmp.join(".git")).unwrap();
    assert!(cwd_owns_git_entry(&tmp));
}

#[test]
fn guided_cwd_owns_git_entry_true_for_pointer_file() {
    // Why: a `.git` FILE is a linked-worktree / submodule gitlink — still a
    // working-tree root. Even a dangling pointer (target moved by a rescue)
    // means "this dir is its own repo", so it must count as owned.
    let tmp = tempdir_with_name("trusty_test_owns_git_file_2542");
    std::fs::write(tmp.join(".git"), b"gitdir: ./moved-away\n").unwrap();
    assert!(cwd_owns_git_entry(&tmp));
}

#[test]
fn guided_cwd_owns_git_entry_false_for_dotgit_prefixed_sibling() {
    // Why: the exact-name guarantee — a `.git`-PREFIXED sibling such as
    // `.git.hotstats-backup-20260713` (a preserved gitdir from a rescue) is NOT
    // a repo marker. A `starts_with(".git")`/glob test would be the bug.
    let tmp = tempdir_with_name("trusty_test_owns_git_prefixed_2542");
    std::fs::create_dir_all(tmp.join(".git.hotstats-backup-20260713")).unwrap();
    assert!(
        !cwd_owns_git_entry(&tmp),
        "a `.git`-prefixed sibling must NOT be treated as owning a repo"
    );
}

#[test]
fn guided_cwd_owns_git_entry_false_when_absent() {
    // Why: a plain directory owns no repo.
    let tmp = tempdir_with_name("trusty_test_owns_git_absent_2542");
    assert!(!cwd_owns_git_entry(&tmp));
}

#[test]
fn guided_classify_cwd_own_git_wins_over_ancestor() {
    // Why: the #2542 differential. `cwd` owns a `.git` entry that is present but
    // transiently INVALID (an empty, partially-reconstructed gitdir — the exact
    // shape a concurrent `git` rescue leaves). `git rev-parse --show-toplevel`
    // walks PAST it up to the enclosing `outer` repo (asserted below), so the
    // pre-fix code classified this as `UntrackedInsideAncestor(outer)` and bare
    // `tm` wrongly reported "inside another repository's working tree". Own-repo
    // -wins must classify it as `Usable(cwd)` — its OWN repo, never the ancestor.
    let outer = tempdir_with_name("trusty_test_own_git_wins_2542");
    if !git_init_with_commit(&outer) {
        return; // git unavailable — skip
    }
    let inner = outer.join("inner");
    std::fs::create_dir_all(inner.join(".git")).unwrap(); // present-but-invalid gitdir

    // Precondition: git's upward walk skips the invalid `inner/.git` and lands
    // on `outer` — the exact behavior the fast-path overrides.
    if let Some(walked) = find_git_root_via_cli(&inner) {
        let walked = walked.canonicalize().unwrap_or(walked);
        let outer_c = outer.canonicalize().unwrap_or_else(|_| outer.clone());
        assert_eq!(
            walked, outer_c,
            "precondition: git walks up to the ancestor"
        );
    }

    match classify_cwd_project(&inner) {
        CwdProject::Usable(root) => {
            let root = root.canonicalize().unwrap_or(root);
            let inner_c = inner.canonicalize().unwrap_or_else(|_| inner.clone());
            assert_eq!(
                root, inner_c,
                "must resolve to cwd's OWN repo, not the ancestor"
            );
        }
        other => panic!("cwd owning a `.git` must be Usable(cwd), got {other:?}"),
    }
}

#[test]
fn guided_classify_cwd_own_git_ignores_dotgit_prefixed_sibling() {
    // Why: task guarantee (a)+(b) — an inner repo with a `.git`-suffixed sibling
    // dir in its ancestor resolves to ITSELF, never the sibling or the ancestor.
    let outer = tempdir_with_name("trusty_test_own_git_sibling_2542");
    if !git_init_with_commit(&outer) {
        return;
    }
    // A `.git`-prefixed backup sibling in the ancestor — must be inert.
    std::fs::create_dir_all(outer.join(".git.backup-20260713")).unwrap();
    let inner = outer.join("inner");
    std::fs::create_dir_all(inner.join(".git")).unwrap();
    match classify_cwd_project(&inner) {
        CwdProject::Usable(root) => {
            let root = root.canonicalize().unwrap_or(root);
            let inner_c = inner.canonicalize().unwrap_or_else(|_| inner.clone());
            assert_eq!(root, inner_c);
        }
        other => panic!("inner repo must be Usable(inner), got {other:?}"),
    }
}

#[test]
fn guided_classify_cwd_own_git_worktree_pointer_file() {
    // Why: a `.git` POINTER FILE (linked worktree / submodule gitlink) is a
    // working-tree root just like a `.git` directory — must be Usable(cwd).
    let outer = tempdir_with_name("trusty_test_own_git_ptr_2542");
    if !git_init_with_commit(&outer) {
        return;
    }
    let inner = outer.join("wt");
    std::fs::create_dir_all(&inner).unwrap();
    std::fs::write(inner.join(".git"), b"gitdir: /somewhere/else\n").unwrap();
    match classify_cwd_project(&inner) {
        CwdProject::Usable(root) => {
            let root = root.canonicalize().unwrap_or(root);
            let inner_c = inner.canonicalize().unwrap_or_else(|_| inner.clone());
            assert_eq!(root, inner_c);
        }
        other => panic!("cwd with a `.git` pointer file must be Usable(cwd), got {other:?}"),
    }
}

#[test]
fn guided_classify_cwd_untracked_ancestor_still_refuses_without_own_git() {
    // Why: the #2534 guarantee must survive the #2542 fast-path. An untracked
    // directory that has NO own `.git`, nested in a REAL ancestor repo, must
    // still be `UntrackedInsideAncestor` — the fast-path only fires when cwd
    // owns a `.git`, so this path is unchanged.
    let outer = tempdir_with_name("trusty_test_untracked_still_refuses_2542");
    if !git_init_with_commit(&outer) {
        return;
    }
    let untracked = outer.join("notes");
    std::fs::create_dir_all(&untracked).unwrap();
    assert!(
        !cwd_owns_git_entry(&untracked),
        "precondition: untracked dir owns no `.git`"
    );
    match classify_cwd_project(&untracked) {
        CwdProject::UntrackedInsideAncestor(_) => {}
        other => panic!("#2534 case must still refuse the ancestor, got {other:?}"),
    }
}

/// Local helper: resolve the git working-tree root via the CLI (mirrors the
/// production `find_git_root`) so the NotGit test can skip when a dev machine's
/// temp dir happens to sit inside a git tree.
fn find_git_root_via_cli(dir: &PathBuf) -> Option<PathBuf> {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .ok()
        .filter(|o| o.status.success())?;
    let root = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (!root.is_empty()).then(|| PathBuf::from(root))
}

// ── print_project_context / print_non_tty_hint ────────────────────────────────

#[test]
fn guided_print_project_context_does_not_panic_no_sessions() {
    // Why: the display helper must not panic when the session list is empty.
    print_project_context(
        "owner/repo",
        &PathBuf::from("/home/user/repos/owner/repo"),
        &[],
    );
}

#[test]
fn guided_print_project_context_does_not_panic_with_sessions() {
    // Why: the display helper must not panic when optional fields are None.
    let sessions = vec![make_session(
        "tm-frontend-1",
        "running",
        Some("2026-06-25T12:00:00Z"),
    )];
    print_project_context(
        "owner/repo",
        &PathBuf::from("/home/user/repos/owner/repo"),
        &sessions,
    );
}

// ── format_project_context_row (#3741: no `tm:` prefix on picker-adjacent rows) ──

#[test]
fn guided_format_project_context_row_leads_with_index_no_tm_prefix() {
    // Why: pins the exact row text `print_project_context` prints per session
    // (code-critic finding on #3742 — this row still carried the old
    // `tm:   [N] …` prefix after the interactive picker's own rows had
    // already dropped it, so bare-`tm` printed two differently-formatted
    // numbered lists on the same screen).
    let s = make_session("tm-frontend-1", "running", Some("2026-06-25T12:00:00Z"));
    let row = format_project_context_row(0, &s);
    assert_eq!(
        row,
        "[1] tm-frontend-1  state=running  last=2026-06-25T12:00:00Z"
    );
    assert!(!row.starts_with("tm:"), "row must not carry the tm: prefix");
}

#[test]
fn guided_format_project_context_row_missing_activity_uses_em_dash() {
    let s = make_session("tm-api-2", "stopped", None);
    let row = format_project_context_row(4, &s);
    assert_eq!(row, "[5] tm-api-2  state=stopped  last=—");
}

#[test]
fn guided_print_non_tty_hint_does_not_panic_no_sessions() {
    // Why: the non-TTY degradation path must work when there are no sessions.
    print_non_tty_hint("owner/repo", &[]);
}

#[test]
fn guided_print_non_tty_hint_does_not_panic_with_sessions() {
    // Why: the non-TTY hint must print the session name for a resume hint.
    let sessions = vec![make_session("tm-api-2", "stopped", None)];
    print_non_tty_hint("owner/repo", &sessions);
}

// ── fallback_protected in non-git dir ────────────────────────────────────────

#[tokio::test]
async fn guided_fallback_non_git_dir_calls_launch_path() {
    // Why: for a non-git directory, fallback_protected should call launch()
    // which will fail (daemon not running) rather than returning a
    // "live git checkout protected" error.
    let tmp = tempdir_with_name("trusty_test_fallback_nongit_1705");
    let client = reqwest::Client::new();
    let result = fallback_protected(&client, "http://127.0.0.1:19999", &tmp).await;
    // The function should NOT return the live-checkout protection error.
    if let Err(e) = result {
        let msg = e.to_string();
        assert!(
            !msg.contains("live git checkout"),
            "non-git dir should NOT trigger live-checkout guard; got: {msg}"
        );
    }
}

// ── Test helpers ──────────────────────────────────────────────────────────────

/// Create (or replace) a temp directory with the given name under the OS temp dir.
fn tempdir_with_name(name: &str) -> PathBuf {
    let tmp = std::env::temp_dir().join(name);
    if tmp.exists() {
        std::fs::remove_dir_all(&tmp).ok();
    }
    std::fs::create_dir_all(&tmp).expect("create temp dir");
    tmp
}

/// Run `git init -q` in `dir`. Returns true on success, false if git unavailable.
fn git_init_quiet(dir: &PathBuf) -> bool {
    std::process::Command::new("git")
        .args(["init", "-q"])
        .current_dir(dir)
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// `git init` + minimal identity config + empty initial commit.
/// Returns true on success, false if git is unavailable in this environment.
fn git_init_with_commit(dir: &PathBuf) -> bool {
    if !git_init_quiet(dir) {
        return false;
    }
    // Configure a minimal identity so `git commit` doesn't fail.
    for (k, v) in [("user.email", "test@example.com"), ("user.name", "Test")] {
        std::process::Command::new("git")
            .args(["config", k, v])
            .current_dir(dir)
            .status()
            .ok();
    }
    // Empty initial commit so the repo has a valid HEAD ref.
    std::process::Command::new("git")
        .args(["commit", "--allow-empty", "-m", "init", "-q"])
        .current_dir(dir)
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Add `remote.origin` with the given URL.
fn git_remote_add(dir: &PathBuf, url: &str) {
    std::process::Command::new("git")
        .args(["remote", "add", "origin", url])
        .current_dir(dir)
        .status()
        .ok();
}

/// Create `<repo>/<rel>/.keep`, stage it, and commit so `<rel>` becomes a
/// tracked directory in the repo's HEAD tree. Used to distinguish a genuinely
/// tracked subdir from an untracked ancestor subdir (#2534).
fn git_track_dir(repo: &PathBuf, rel: &str) {
    let dir = repo.join(rel);
    std::fs::create_dir_all(&dir).expect("create tracked subdir");
    std::fs::write(dir.join(".keep"), b"").expect("write .keep");
    std::process::Command::new("git")
        .args(["add", "-A"])
        .current_dir(repo)
        .status()
        .ok();
    std::process::Command::new("git")
        .args(["commit", "-m", "track", "-q"])
        .current_dir(repo)
        .status()
        .ok();
}

/// Construct a minimal `ManagedSessionSummary` for tests.
fn make_session(
    name: &str,
    state: &str,
    last_activity_at: Option<&str>,
) -> trusty_mpm::client::ManagedSessionSummary {
    trusty_mpm::client::ManagedSessionSummary {
        id: format!("{name}-id"),
        name: name.to_string(),
        state: state.to_string(),
        persisted_state: None,
        workspace_path: None,
        repo_url: None,
        branch: None,
        created_at: None,
        last_activity_at: last_activity_at.map(str::to_owned),
        pending_decision: None,
        proposed_default: None,
        source_id: None,
        task: None,
        cwd: None,
        claude_session_id: None,
        deliverable_id: None,
        pane_id: None,
        injection_status: None,
        unresumable: false,
        stale_assets: false,
        stale_assets_unchecked: false,
        attached: false,
        slot: 0,
        deleted: false,
    }
}

/// Construct a `ManagedSessionSummary` with a DISPLAYED `state` that diverges
/// from the daemon's `persisted_state` (#3531) — the exact zombie shape the
/// #3302 display-reconciliation can produce: an `active`/`provisioning`
/// record whose tmux pane is gone reads `state = "stopped"` for display while
/// `persisted_state` still carries the true, authoritative value.
fn make_session_with_persisted_state(
    name: &str,
    displayed_state: &str,
    persisted_state: &str,
) -> trusty_mpm::client::ManagedSessionSummary {
    trusty_mpm::client::ManagedSessionSummary {
        persisted_state: Some(persisted_state.to_string()),
        ..make_session(name, displayed_state, None)
    }
}

/// Build `count` LIVE sessions with sequential stable slots `1..=count`, for
/// `parse_picker_choice` tests (#3034) — the daemon-assigned numbering the
/// picker resolves typed input against, rather than a recomputed positional
/// index.
///
/// Why: pre-#3034 tests called `parse_picker_choice` with a bare
/// `session_count: usize`; the daemon-numbered rewrite takes the full
/// `&[ManagedSessionSummary]` menu instead, so every test needs a slotted
/// fixture. `unresumable[i]` (when present) flags that session dead, matching
/// the old tests' `&[bool]` parameter.
fn picker_fixture(
    count: usize,
    unresumable: &[bool],
) -> Vec<trusty_mpm::client::ManagedSessionSummary> {
    (0..count)
        .map(|i| {
            let mut s = make_session(&format!("s{}", i + 1), "active", None);
            s.slot = (i + 1) as u32;
            s.unresumable = unresumable.get(i).copied().unwrap_or(false);
            s
        })
        .collect()
}

/// Build a tombstoned (`deleted: true`) row at `slot`, for the #3034
/// slot-resolution tests.
fn deleted_slot(slot: u32) -> trusty_mpm::client::ManagedSessionSummary {
    let mut s = make_session("gone", "deleted", None);
    s.slot = slot;
    s.deleted = true;
    s
}

/// Set `slot` on a `ManagedSessionSummary` fixture and return it, for tests
/// that build a hand-assembled menu with tombstones interspersed among live
/// rows (#3034) rather than using the uniform [`picker_fixture`].
fn at_slot(
    mut s: trusty_mpm::client::ManagedSessionSummary,
    slot: u32,
) -> trusty_mpm::client::ManagedSessionSummary {
    s.slot = slot;
    s
}

// ── needs_restart (#1742) ─────────────────────────────────────────────────────
// `needs_restart` is now state-only: it returns true iff the daemon's /resume
// endpoint can accept the session (Stopped/Errored only). The active-but-tmux-
// absent case is handled by `is_zombie` below.

#[test]
fn guided_resume_needs_restart_stopped() {
    // Why: stopped state means no live runtime; daemon restart is required (#1742).
    // tmux liveness is irrelevant — the daemon makes the decision based on state.
    assert!(needs_restart("stopped"), "stopped state must need restart");
}

#[test]
fn guided_resume_needs_restart_errored() {
    // Why: errored sessions are resumable through the daemon (Stopped|Errored are
    // the only accepted states for /resume); direct attach would fail.
    assert!(needs_restart("errored"), "errored state must need restart");
}

#[test]
fn guided_resume_no_restart_active() {
    // Why: active state — daemon's /resume rejects it with 409; not the restart path.
    // (The active-but-tmux-absent case is caught by is_zombie before we'd POST.)
    assert!(
        !needs_restart("active"),
        "active state must not need daemon restart"
    );
}

#[test]
fn guided_resume_no_restart_provisioning() {
    // Why: provisioning state — daemon is already setting up the session.
    assert!(
        !needs_restart("provisioning"),
        "provisioning must not need restart"
    );
}

#[test]
fn guided_resume_no_restart_decommissioned() {
    // Why: decommissioned sessions have no workspace; /resume returns 409.
    // is_zombie handles the absent-tmux case before we'd attempt a POST.
    assert!(
        !needs_restart("decommissioned"),
        "decommissioned must not need restart"
    );
}

// ── is_zombie (#1742 adversarial follow-up) ───────────────────────────────────
// A zombie is a session whose daemon state is NOT stopped/errored (i.e., active
// or provisioning) but whose tmux session has disappeared. The daemon's /resume
// endpoint would return 409 for these — leading to a permanent dead end. The
// correct recovery is: `tm session stop <id>` then `tm` again.

#[test]
fn guided_resume_is_zombie_active_no_tmux() {
    // Why: active + tmux absent is the canonical zombie case — daemon thinks it's
    // running but tmux is gone. We must bail with an actionable message, not POST.
    assert!(
        is_zombie("active", false),
        "active + no tmux must be detected as zombie"
    );
}

#[test]
fn guided_resume_is_zombie_provisioning_no_tmux() {
    // Why: provisioning + tmux absent is also a zombie (daemon is setting up a
    // session whose tmux vanished). Same actionable bail applies.
    assert!(
        is_zombie("provisioning", false),
        "provisioning + no tmux must be detected as zombie"
    );
}

#[test]
fn guided_resume_not_zombie_stopped_no_tmux() {
    // Why: stopped + no tmux is NOT a zombie — it is the normal restart case where
    // the daemon's /resume will recreate the tmux session. Must not bail.
    assert!(
        !is_zombie("stopped", false),
        "stopped + no tmux is a restart case, not a zombie"
    );
}

#[test]
fn guided_resume_not_zombie_errored_no_tmux() {
    // Why: errored + no tmux is also a restart case, not a zombie.
    assert!(
        !is_zombie("errored", false),
        "errored + no tmux is a restart case, not a zombie"
    );
}

#[test]
fn guided_resume_not_zombie_active_with_tmux() {
    // Why: active + tmux live is the happy-path attach case — no zombie, no restart.
    assert!(
        !is_zombie("active", true),
        "active + live tmux is the normal attach path, not a zombie"
    );
}

// ── plan_resume (#2001 zombie auto-reconcile) ─────────────────────────────────
// `plan_resume` is the pure branch-selection seam that drives resume_guided_session.
// It composes is_zombie + needs_restart into the three concrete actions the I/O
// driver takes. The zombie case must now select ReconcileThenRestart (auto-stop
// then restart) rather than bailing — the operator does nothing.

#[test]
fn guided_resume_plan_active_live_tmux_attaches() {
    // Why: active state with a live tmux pane AND a live runtime is the happy
    // path — attach directly, no daemon round-trip, no stop, no resume. #3873
    // added `runtime_live`; this case MUST keep attaching when it is true, or a
    // genuinely-running agent would get its pane killed and restarted.
    assert_eq!(
        plan_resume(
            "active", /* tmux_live */ true, /* runtime_live */ true
        ),
        ResumeAction::Attach,
        "active + live tmux + live runtime must attach directly"
    );
}

#[test]
fn guided_resume_plan_active_live_tmux_dead_runtime_reconciles_then_restarts() {
    // Why (#3873): the reported defect. The daemon record says `active` and the
    // tmux SESSION exists, but the inner `claude` has exited and the pane fell
    // back to a bare login shell. `tmux_live` cannot see that difference, so the
    // plan used to be `Attach` — bare `tm` switched the operator into an idle
    // shell and did nothing useful, forcing a second `tm` from inside that pane
    // to actually get a runtime back. The recovery is the SAME auto-stop-then-
    // restart the tmux-gone zombie already uses, so invocation #1 does the whole
    // job.
    assert_eq!(
        plan_resume(
            "active", /* tmux_live */ true, /* runtime_live */ false
        ),
        ResumeAction::ReconcileThenRestart
    );
}

#[test]
fn guided_resume_plan_provisioning_live_tmux_dead_runtime_reconciles_then_restarts() {
    // Why (#3873): `provisioning` is the other non-terminal, non-restartable
    // state that reaches the Attach branch, and a provisioning session whose
    // runtime died is just as unusable as an active one. Pins that the fix keys
    // off the same `!needs_restart` family rather than a hard-coded "active".
    assert_eq!(
        plan_resume(
            "provisioning",
            /* tmux_live */ true,
            /* runtime_live */ false
        ),
        ResumeAction::ReconcileThenRestart,
        "provisioning + live tmux + dead runtime must reconcile then restart"
    );
}

#[test]
fn guided_resume_plan_stopped_live_tmux_dead_runtime_still_plain_restarts() {
    // Why (#3873 branch ordering): a Stopped record's pane is an idle shell too,
    // so it also reports `runtime_live = false`. It must KEEP taking the plain
    // `Restart` path — `/resume` already accepts Stopped, and routing it through
    // `ReconcileThenRestart` would add a pointless `/runtime-stop` round-trip
    // against a record that is already stopped. Guards that the new gate sits
    // BELOW `needs_restart`, not above it.
    assert_eq!(
        plan_resume(
            "stopped", /* tmux_live */ true, /* runtime_live */ false
        ),
        ResumeAction::Restart,
        "stopped + dead runtime must still take the plain Restart path"
    );
}

#[test]
fn plan_resume_refuses_terminal_states_even_with_dead_runtime() {
    // Why (#3873): the terminal tombstone refusal must stay FIRST. A
    // decommissioned/deleted record whose pane is an idle shell must never be
    // resurrected through the new dead-runtime reconcile path.
    for state in ["deleted", "decommissioned"] {
        assert_eq!(
            plan_resume(
                state, /* tmux_live */ true, /* runtime_live */ false
            ),
            ResumeAction::Terminal,
            "{state} + dead runtime must still be refused as Terminal"
        );
    }
}

#[test]
fn session_runtime_live_assumes_live_for_blank_session_name() {
    // Why (#3873 fail-open contract): `runtime_live = false` now drives a
    // `/runtime-stop` whose `kill_session` destroys the WHOLE tmux session. A
    // blank session name gives us NO evidence either way, so it must assume live
    // and preserve the pre-#3873 Attach behavior. Pure: takes the early return
    // before any tmux shell-out.
    assert!(
        session_runtime_live(""),
        "an empty session name must fail OPEN (assume the runtime is live)"
    );
    assert!(
        session_runtime_live("   "),
        "a whitespace-only session name is no evidence either — must fail OPEN"
    );
}

// ── parse_pane_probes (#3873) ────────────────────────────────────────────────
// Rows come from `tmux list-panes -s -t <session> -F
// '#{session_name}\t#{pane_current_command}\t#{pane_pid}'`. Anything this seam
// cannot fully adjudicate must return None, which the caller treats as fail-open
// — because the only thing a `false` verdict can cause here is a session kill.

#[test]
fn parse_pane_probes_reads_every_pane() {
    // Why (#3873): the happy shape — one row per pane, all three fields present.
    let panes = parse_pane_probes("tm-apex-01\tzsh\t41234\ntm-apex-01\tclaude\t41999\n")
        .expect("a well-formed two-pane listing must parse");
    assert_eq!(panes.len(), 2, "both panes must be returned");
    assert_eq!(panes[0].session_name, "tm-apex-01");
    assert_eq!(panes[0].pane_current_command, "zsh");
    assert_eq!(panes[0].pane_pid, Some(41234));
    assert_eq!(panes[1].pane_current_command, "claude");
    assert_eq!(panes[1].pane_pid, Some(41999));
}

#[test]
fn parse_pane_probes_rejects_non_numeric_pid() {
    // Why (#3873 round 2, code-critic MEDIUM): this is THE regression this
    // parse tightening exists to prevent. A non-numeric pid used to degrade to
    // `pane_pid: None`; `ProcessTreeProbe::has_live_child(None)` returns `false`,
    // so the documented two-gate check silently collapsed to `is_idle_shell`
    // alone and an unparseable row could satisfy the destructive dead-runtime
    // branch on the strength of the command word by itself. `None → false` is
    // correct calibration for the DAEMON, whose reconcile is non-destructive
    // (#2023 A: record flips, pane survives); the CLI reuses that same gate to
    // drive a `kill_session`, so it must be STRICTER than the daemon, not equal.
    assert_eq!(
        parse_pane_probes("tm-apex-01\tzsh\tnotanumber\n"),
        None,
        "a non-numeric pid must read as CANNOT DETERMINE (None), never as a \
         one-gate dead verdict"
    );
}

#[test]
fn parse_pane_probes_rejects_missing_pid() {
    // Why (#3873 round 2): same MEDIUM, short-row variant — a row that stops
    // after the command word leaves the child gate with nothing to inspect.
    assert_eq!(
        parse_pane_probes("tm-apex-01\tzsh\n"),
        None,
        "a row missing the pid column must yield None"
    );
}

#[test]
fn parse_pane_probes_rejects_smeared_row() {
    // Why (#3873): the #1813 composite-key shape that broke the daemon's own
    // `list-panes -a` enumeration — the whole row collapsed into one field. The
    // TAB delimiter makes it unparseable rather than silently mis-columned.
    assert_eq!(
        parse_pane_probes("tm-apex-01_zsh_41234\n"),
        None,
        "a smeared single-field row must yield None, never a guessed split"
    );
}

#[test]
fn parse_pane_probes_rejects_extra_fields() {
    // Why (#3873): more columns than the format asked for means the reply is not
    // the shape we requested — refuse rather than guess which column is which.
    assert_eq!(
        parse_pane_probes("tm-apex-01\tzsh\t41234\textra\n"),
        None,
        "an over-long row must yield None"
    );
}

#[test]
fn parse_pane_probes_rejects_empty_or_blank_listing() {
    // Why (#3873): an empty listing means tmux told us nothing. It must NOT read
    // as "no live panes, therefore dead" — that is exactly the fail-closed shape
    // that would kill a session on a failed query.
    assert_eq!(parse_pane_probes(""), None, "empty output must yield None");
    assert_eq!(
        parse_pane_probes("   \n\n"),
        None,
        "whitespace-only output must yield None"
    );
}

#[test]
fn parse_pane_probes_rejects_empty_command_field() {
    // Why (#3873): the other half of the #1813 shape — `pane_current_command`
    // came back EMPTY. An empty command must never be handed to `is_idle_shell`.
    assert_eq!(
        parse_pane_probes("tm-apex-01\t\t41234\n"),
        None,
        "an empty command field must yield None"
    );
}

// ── panes_prove_session_dead (#3873 rounds 2–3 / #2463) ──────────────────
// The single predicate between a parsed tmux listing and a `kill_session`. It is
// phrased as "prove DEAD", so every uncertain input must fall out as `false`.
// `AlwaysIdleProbe` isolates the command-word gate from the real process tree.

#[test]
fn panes_prove_session_dead_when_every_pane_is_a_bare_shell() {
    // Why (#3873): the actual defect shape, and the ONLY configuration allowed to
    // reach the destructive reconcile branch.
    let panes = parse_pane_probes("tm-apex-01\tzsh\t41234\ntm-apex-01\tbash\t41999\n")
        .expect("listing must parse");
    assert!(
        panes_prove_session_dead("tm-apex-01", &panes, &AlwaysIdleProbe),
        "a session whose every pane is a bare shell must be proven dead"
    );
}

#[test]
fn panes_prove_session_dead_refuses_when_a_sibling_pane_is_live() {
    // Why (#2463): a manually-split managed session can have an idle pane
    // alongside a live agent pane. Convicting on the idle one would kill the live
    // agent with it. `claude` is not an idle shell, so the session is not dead.
    let panes = parse_pane_probes("tm-apex-01\tzsh\t41234\ntm-apex-01\tclaude\t41999\n")
        .expect("listing must parse");
    assert!(
        !panes_prove_session_dead("tm-apex-01", &panes, &AlwaysIdleProbe),
        "a sibling pane still running the agent must block the dead verdict"
    );
}

#[test]
fn panes_prove_session_dead_refuses_a_prefix_matched_listing() {
    // Why (#3873 round 3, code-critic MEDIUM): THE case the membership check
    // exists for, and it is reachable rather than hypothetical. tmux
    // PREFIX-MATCHES session targets: with only `tm-apex-01` alive,
    // `has-session -t tm-apex` succeeds and `list-panes -s -t tm-apex` returns
    // `tm-apex-01`'s panes. A record named `tm-apex` would then be handed a
    // well-formed listing describing a DIFFERENT, live session. Without the
    // membership check, `session_has_live_pane`'s filter matches nothing, reports
    // `false` ("no live pane"), and that reads as "dead" — and the `kill_session`
    // that follows prefix-matches onto that same live session. Deleting the check
    // in `panes_prove_session_dead` must turn this test RED.
    let panes = parse_pane_probes("tm-apex-01\tzsh\t41234\n").expect("listing must parse");
    assert!(
        !panes_prove_session_dead("tm-apex", &panes, &AlwaysIdleProbe),
        "a prefix-matched listing describes ANOTHER session — it must never \
         convict ours, whose own panes we have not actually seen"
    );
}

#[test]
fn panes_prove_session_dead_refuses_a_wholly_foreign_listing() {
    // Why (#3873 round 3): the general form of the same hazard — whatever the
    // cause (prefix match, a renamed session, a racing kill), a listing with no
    // pane attributable to the session we asked about tells us NOTHING about it,
    // and "nothing" must never be convicted as "dead".
    let panes = parse_pane_probes("tm-other-99\tzsh\t41234\n").expect("listing must parse");
    assert!(
        !panes_prove_session_dead("tm-apex-01", &panes, &AlwaysIdleProbe),
        "a listing belonging entirely to another session must not prove ours dead"
    );
}

#[test]
fn panes_prove_session_dead_ignores_foreign_rows_beside_our_own() {
    // Why (#3873 round 3): the membership check must not over-correct into
    // "any foreign row blocks the verdict" — our own panes, when present, are
    // still the ones that decide. A foreign LIVE pane must not rescue a session
    // whose own panes are all idle shells.
    let panes = parse_pane_probes("tm-other-99\tclaude\t41000\ntm-apex-01\tzsh\t41234\n")
        .expect("listing must parse");
    assert!(
        panes_prove_session_dead("tm-apex-01", &panes, &AlwaysIdleProbe),
        "our own idle pane decides; a live pane in an unrelated session is not ours"
    );
}

#[test]
fn guided_resume_plan_stopped_restarts() {
    // Why: stopped state must go straight to the daemon /resume restart path —
    // NOT reconcile (there is nothing to stop) and NOT a bare attach.
    assert_eq!(
        plan_resume(
            "stopped", /* tmux_live */ false, /* runtime_live */ true
        ),
        ResumeAction::Restart,
        "stopped must select the plain Restart path"
    );
}

#[test]
fn guided_resume_plan_errored_restarts() {
    // Why: errored is resumable via /resume just like stopped.
    assert_eq!(
        plan_resume(
            "errored", /* tmux_live */ false, /* runtime_live */ true
        ),
        ResumeAction::Restart,
        "errored must select the plain Restart path"
    );
}

#[test]
fn guided_resume_plan_active_no_tmux_reconciles_then_restarts() {
    // Why (#2001): the canonical zombie — daemon says active but tmux is gone. The
    // fix is to auto-stop (reset the record to Stopped) THEN restart, so the plan
    // must be ReconcileThenRestart, not a bail and not a plain Restart (a bare
    // /resume would 409 because the record is still active).
    assert_eq!(
        plan_resume(
            "active", /* tmux_live */ false, /* runtime_live */ true
        ),
        ResumeAction::ReconcileThenRestart,
        "active + no tmux must reconcile (auto-stop) then restart"
    );
}

#[test]
fn guided_resume_plan_provisioning_no_tmux_reconciles_then_restarts() {
    // Why (#2001): provisioning + tmux gone is also a zombie and follows the same
    // auto-stop-then-restart recovery.
    assert_eq!(
        plan_resume(
            "provisioning",
            /* tmux_live */ false,
            /* runtime_live */ true
        ),
        ResumeAction::ReconcileThenRestart,
        "provisioning + no tmux must reconcile then restart"
    );
}

#[test]
fn plan_resume_refuses_terminal_states() {
    // code-critic CRITICAL: a terminal tombstone must NEVER be resumed —
    // neither via the zombie-reconcile path (tmux_live=false, which used to
    // resurrect a Deleted record) NOR via a bare Attach (tmux_live=true, the
    // "force-deleted-while-live" variant). Both must resolve to Terminal.
    for state in ["deleted", "decommissioned"] {
        for tmux_live in [false, true] {
            assert_eq!(
                plan_resume(state, tmux_live, /* runtime_live */ true),
                ResumeAction::Terminal,
                "{state} (tmux_live={tmux_live}) must be refused as Terminal, never resumed"
            );
        }
    }
}

#[test]
fn is_zombie_false_for_terminal_states() {
    // A terminal tombstone with no live tmux must NOT read as a resurrectable
    // zombie (the exact chain that resurrected a Deleted session).
    assert!(!is_zombie("deleted", false), "deleted is never a zombie");
    assert!(
        !is_zombie("decommissioned", false),
        "decommissioned is never a zombie"
    );
}

#[test]
fn guided_resume_plan_stopped_with_stale_tmux_still_restarts() {
    // Why: a stopped record whose stale tmux pane is somehow still alive is NOT a
    // zombie (needs_restart is true) — it takes the plain Restart path (the daemon
    // kills the stale pane). Guards the branch ordering in plan_resume.
    assert_eq!(
        plan_resume(
            "stopped", /* tmux_live */ true, /* runtime_live */ true
        ),
        ResumeAction::Restart,
        "stopped + stale live tmux must still take the Restart path, not reconcile"
    );
}

// ── resume_classification_state / persisted_state (#3531) ────────────────────
// Root cause: #3302 made the list/get endpoints reconcile the DISPLAYED
// `state` against live tmux — an `active`-but-tmux-dead zombie then reads
// `state = "stopped"`, identical to a session that is GENUINELY stopped.
// Classifying off that display value made `is_zombie` unable to tell the two
// apart, so the interactive picker's "restart (stopped)" selection fell
// through to a plain `Restart` that the daemon's `/resume` (validated against
// the REAL persisted state) rejected with a 409. These tests pin the fix:
// classification must always run on `persisted_state`, not `state`.

#[test]
fn resume_classification_state_prefers_persisted_state() {
    // The exact #3531 repro shape: displayed state says "stopped" (tmux is
    // absent, so the list endpoint reconciled it that way), but the daemon's
    // authoritative persisted state is still "active".
    let session = make_session_with_persisted_state("tm-writing-01", "stopped", "active");
    assert_eq!(
        resume_classification_state(&session),
        "active",
        "classification must use persisted_state, not the display-reconciled state"
    );
}

#[test]
fn resume_classification_state_falls_back_to_display_state_when_absent() {
    // An older daemon that predates `persisted_state` sends `None` — fall back
    // to `state` (pre-#3531 behavior), never panic or silently misclassify.
    let session = make_session("tm-legacy-01", "stopped", None);
    assert_eq!(
        resume_classification_state(&session),
        "stopped",
        "must fall back to display state when persisted_state is absent"
    );
}

#[test]
fn guided_resume_plan_resume_prefers_persisted_state_over_display_state() {
    // #3531 end-to-end (still pure): feeding `resume_classification_state`'s
    // output into `plan_resume` for the zombie repro shape must select
    // ReconcileThenRestart, not a plain Restart that would 409 against the
    // daemon's authoritative state.
    let session = make_session_with_persisted_state("tm-writing-01", "stopped", "active");
    let tmux_live = false; // the picker's "(stopped)" label implies tmux is gone
    let action = plan_resume(
        resume_classification_state(&session),
        tmux_live,
        /* runtime_live */ true,
    );
    assert_eq!(
        action,
        ResumeAction::ReconcileThenRestart,
        "a zombie session displayed as 'stopped' but persisted 'active' must \
         reconcile then restart, never a plain Restart that 409s"
    );

    // Sanity check: classifying off the (buggy, pre-#3531) DISPLAY state alone
    // reproduces the reported dead-end — proving this test would have caught
    // the regression.
    assert_eq!(
        plan_resume(&session.state, tmux_live, /* runtime_live */ true),
        ResumeAction::Restart,
        "classifying off the display-reconciled state alone reproduces the bug"
    );
}

// ── is_github_remote (Change 2: SSH alias support) ───────────────────────────

#[test]
fn is_github_remote_accepts_github_com_ssh() {
    // Why: `git@github.com:o/r.git` is the canonical SSH GitHub URL.
    assert!(
        is_github_remote("git@github.com:o/r.git"),
        "github.com SSH must be recognised as GitHub"
    );
}

#[test]
fn is_github_remote_accepts_github_com_https() {
    // Why: `https://github.com/o/r.git` is the canonical HTTPS GitHub URL.
    assert!(
        is_github_remote("https://github.com/o/r.git"),
        "github.com HTTPS must be recognised as GitHub"
    );
}

#[test]
fn is_github_remote_accepts_github_hyphen_alias() {
    // Why: `git@github-duetto:duettoresearch/aria.git` is the real-world repro
    // case from the issue. Multi-account SSH aliases use `github-<name>`.
    assert!(
        is_github_remote("git@github-duetto:duettoresearch/aria.git"),
        "github-<alias> SSH remote must be recognised as GitHub"
    );
}

#[test]
fn is_github_remote_accepts_github_alias_ssh_url_style() {
    // Why: `ssh://git@github-work/o/r` uses scheme-URL form with an alias host.
    assert!(
        is_github_remote("ssh://git@github-work/o/r"),
        "ssh:// github-<alias> must be recognised as GitHub"
    );
}

#[test]
fn is_github_remote_accepts_github_underscore_alias() {
    // Why: some operators use underscores in their SSH config host aliases
    // (e.g. `github_personal`). The rule covers `-` and `_` separators.
    assert!(
        is_github_remote("git@github_personal:user/repo.git"),
        "github_<alias> SSH remote must be recognised as GitHub"
    );
}

#[test]
fn is_github_remote_rejects_gitlab() {
    // Why: GitLab URLs must NEVER be treated as GitHub to avoid an unexpected
    // managed-clone redirect for non-GitHub projects.
    assert!(
        !is_github_remote("git@gitlab.com:o/r.git"),
        "gitlab.com must NOT be recognised as GitHub"
    );
}

#[test]
fn is_github_remote_rejects_bitbucket() {
    // Why: Bitbucket is not GitHub; the guard must block it.
    assert!(
        !is_github_remote("https://bitbucket.org/o/r"),
        "bitbucket.org must NOT be recognised as GitHub"
    );
}

#[test]
fn is_github_remote_rejects_githubusercontent() {
    // Why: `raw.githubusercontent.com` contains `github` but is a content
    // delivery host, not a clone remote. The host does NOT start with
    // `github-` or `github_`, and it is not `github.com`, so it must be
    // blocked. (Cloning from this host would fail anyway, but blocking it
    // prevents a misleading redirect attempt.)
    assert!(
        !is_github_remote("https://raw.githubusercontent.com/o/r/file"),
        "githubusercontent.com must NOT be recognised as GitHub"
    );
}

#[test]
fn is_github_remote_accepts_github_com_https_with_port() {
    // Why: `https://github.com:443/o/r.git` is a valid remote URL (explicit
    // port). The old substring-match handled this; the host-based approach
    // regressed on it because `split('/').next()` returned `"github.com:443"`.
    // This is the regression guard for the port-stripping fix.
    assert!(
        is_github_remote("https://github.com:443/o/r.git"),
        "https://github.com:443/… must be recognised as GitHub (port stripped)"
    );
}

#[test]
fn is_github_remote_rejects_gitea_with_github_in_path() {
    // Why: a self-hosted Gitea whose URL happens to mention "github" in the
    // path (e.g. a mirror) must not be treated as GitHub.
    assert!(
        !is_github_remote("https://gitea.example.com/mirrors/github-fork.git"),
        "gitea host with github in path must NOT match"
    );
}

// ── github_host extraction ────────────────────────────────────────────────────

#[test]
fn github_host_extracts_scp_style() {
    // Why: the most common GitHub remote form is scp-style `git@HOST:path`.
    assert_eq!(
        github_host("git@github-duetto:duettoresearch/aria.git"),
        "github-duetto"
    );
    assert_eq!(github_host("git@github.com:owner/repo.git"), "github.com");
}

#[test]
fn github_host_extracts_https() {
    // Why: HTTPS remotes use scheme-URL form `https://HOST/path`.
    assert_eq!(
        github_host("https://github.com/owner/repo.git"),
        "github.com"
    );
    assert_eq!(github_host("https://gitlab.com/o/r"), "gitlab.com");
}

#[test]
fn github_host_extracts_ssh_url_with_user() {
    // Why: `ssh://git@HOST/path` is the RFC-compliant SSH URL form.
    assert_eq!(github_host("ssh://git@github-work/o/r"), "github-work");
}

// ── derive_project accepts SSH alias remote ──────────────────────────────────

#[test]
fn guided_derive_project_accepts_github_ssh_alias() {
    // Why: `derive_project` uses `is_github_remote` internally. With the
    // SSH-alias fix, a repo whose origin is `git@github-duetto:owner/repo.git`
    // must return Some with the correct source_id.
    let tmp = tempdir_with_name("trusty_test_github_alias_derive_1705");
    let ok = git_init_with_commit(&tmp);
    if !ok {
        return;
    }
    git_remote_add(&tmp, "git@github-duetto:duettoresearch/aria.git");
    let result = derive_project(&tmp);
    match result {
        Some((source_id, _workspace, _git_root)) => {
            assert_eq!(
                source_id, "duettoresearch/aria",
                "source_id must be parsed correctly from alias remote"
            );
        }
        None => panic!("expected Some for GitHub SSH alias remote, got None"),
    }
}

// ── fallback_protected with SSH alias does not hit GitHub-remote refusal ─────

#[tokio::test]
#[serial_test::serial]
async fn guided_fallback_does_not_refuse_github_ssh_alias_remote() {
    // Why: before this fix, `git@github-duetto:duettoresearch/aria.git`
    // triggered the "Auto-protected managed clones require a GitHub remote"
    // error because `is_github_remote` only matched `github.com`. The SSH alias
    // host `github-duetto` was not recognised, so `fallback_protected` fell
    // into the non-GitHub refusal path. This test locks in the fix.
    // What: creates a real git repo, sets the SSH-alias remote, and calls
    // `fallback_protected`. Asserts the result is NOT the GitHub-remote
    // refusal error. (It may still be an Err from the clone attempt failing
    // due to the daemon being unreachable — that is expected and acceptable.)
    // Deliberately uses a fixture-only host/owner/repo (NOT the real
    // `github-duetto` alias from the regression report above) — a developer
    // machine may have a real, reachable SSH config entry with that exact
    // name (as this repo's own maintainer's machine does), which would let
    // `ensure_base_clone` actually succeed and make this test flaky/order-
    // dependent on local SSH config instead of hermetic (discovered while
    // fixing the nested-tmux attach bug, #1873).
    // Test: this is the test; annotated `serial` because it may set REPOS_ROOT.
    let dir = tempdir_with_name("trusty_test_github_alias_fallback_1705");
    let ok = std::process::Command::new("git")
        .arg("init")
        .current_dir(&dir)
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if !ok {
        eprintln!(
            "guided_fallback_does_not_refuse_github_ssh_alias_remote: git unavailable, skipping"
        );
        return;
    }
    let _ = std::process::Command::new("git")
        .args([
            "remote",
            "add",
            "origin",
            "git@github-test-fixture-alias-nonexistent:acmetest/repo-fixture.git",
        ])
        .current_dir(&dir)
        .status();

    // Point REPOS_ROOT at a tempdir so we don't pollute the real repos root
    // and to make `ensure_base_clone` fail fast (base/.git absent → clone
    // attempt → network failure → Err, which is what we want to assert on).
    let repos_root = tempfile::tempdir().unwrap();
    let repos_root_key = trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV;
    let prev = std::env::var(repos_root_key).ok();
    unsafe { std::env::set_var(repos_root_key, repos_root.path()) };

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

    unsafe {
        match prev {
            Some(v) => std::env::set_var(repos_root_key, v),
            None => std::env::remove_var(repos_root_key),
        }
    }

    // The call must fail (daemon unreachable + clone fails), but NOT with the
    // "requires a GitHub remote" refusal message.
    assert!(
        result.is_err(),
        "fallback must Err (daemon unreachable / clone fails)"
    );
    let err_msg = format!("{}", result.unwrap_err());
    assert!(
        !err_msg.contains("auto-managed clones require a GitHub remote"),
        "SSH alias remote must NOT trigger GitHub-remote refusal; got: {err_msg}"
    );
    // Also confirm no framework files landed in the live checkout.
    assert!(
        !dir.join("CLAUDE.md").exists(),
        "CLAUDE.md must NOT appear in the live checkout"
    );
    assert!(
        !dir.join(".mcp.json").exists(),
        ".mcp.json must NOT appear in the live checkout"
    );
}

// ── needs_first_run_clone (#1780) ─────────────────────────────────────────────

/// Why: a non-directory path (URL, non-existent path) must return None — no git
/// operation is attempted; the check is a fast-path guard.
/// Test: itself.
#[test]
fn needs_first_run_clone_returns_none_for_non_dir() {
    assert!(needs_first_run_clone("https://github.com/owner/repo.git").is_none());
    assert!(needs_first_run_clone("/nonexistent/path/that/does/not/exist").is_none());
    assert!(needs_first_run_clone("").is_none());
}

/// Why: when the base clone directory already exists, the fn must return None
/// so the "first run" message is NOT emitted on subsequent `tm` invocations.
/// Test: itself. Marked `#[serial_test::serial]` so it cannot run concurrently
/// with other env-mutating tests (especially b-tests that also mutate
/// TRUSTY_MPM_REPOS_ROOT without holding ENV_MUTEX).
#[test]
#[serial_test::serial]
fn needs_first_run_clone_returns_none_when_clone_exists() {
    use std::process::Command;
    let tmp = tempfile::TempDir::new().unwrap();
    let dir = tmp.path();

    // Init git and add a GitHub origin.
    let git = |args: &[&str]| {
        Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    };
    if !git(&["init"]) {
        return; // no git on runner
    }
    git(&[
        "remote",
        "add",
        "origin",
        "git@github.com:owner/already-cloned.git",
    ]);

    // Simulate the base clone already being present by creating the expected dir.
    let repos_env_key = trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV;
    let tmp_repos = tempfile::TempDir::new().unwrap();
    let base = tmp_repos.path().join("owner").join("already-cloned");
    std::fs::create_dir_all(base.join(".git")).unwrap();

    let prev = std::env::var(repos_env_key).ok();
    let result = {
        let _env_guard = ENV_MUTEX.lock().unwrap();
        unsafe { std::env::set_var(repos_env_key, tmp_repos.path()) };
        let r = needs_first_run_clone(&dir.to_string_lossy());
        unsafe {
            match prev {
                Some(v) => std::env::set_var(repos_env_key, v),
                None => std::env::remove_var(repos_env_key),
            }
        }
        r
    };
    assert!(
        result.is_none(),
        "base clone exists → must return None (no first-run message)"
    );
}

/// Why: the first `tm` invocation returns Some when the clone directory is absent,
/// giving the caller the project id and path to emit a "cloning…" message before
/// the blocking daemon request. This is the primary FIX 2 path (#1780).
/// Test: itself. Marked `#[serial_test::serial]` so it cannot run concurrently
/// with other env-mutating tests (especially b-tests that also mutate
/// TRUSTY_MPM_REPOS_ROOT without holding ENV_MUTEX).
#[test]
#[serial_test::serial]
fn needs_first_run_clone_returns_some_when_no_clone() {
    use std::process::Command;
    let tmp = tempfile::TempDir::new().unwrap();
    let dir = tmp.path();

    let git = |args: &[&str]| {
        Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    };
    if !git(&["init"]) {
        return;
    }
    git(&[
        "remote",
        "add",
        "origin",
        "git@github.com:myorg/my-new-project.git",
    ]);

    // Point repos root at an empty temp dir so the base clone definitely does NOT exist.
    let repos_env_key = trusty_mpm::daemon::managed_routes::inproject::REPOS_ROOT_ENV;
    let tmp_repos = tempfile::TempDir::new().unwrap();
    let prev = std::env::var(repos_env_key).ok();
    let result = {
        let _env_guard = ENV_MUTEX.lock().unwrap();
        unsafe { std::env::set_var(repos_env_key, tmp_repos.path()) };
        let r = needs_first_run_clone(&dir.to_string_lossy());
        unsafe {
            match prev {
                Some(v) => std::env::set_var(repos_env_key, v),
                None => std::env::remove_var(repos_env_key),
            }
        }
        r
    };
    let (proj, _path) = result.expect("must return Some for a first-run scenario");
    assert_eq!(proj, "myorg/my-new-project");
}

// ── spawn_progress_message (#1904) ────────────────────────────────────────────
// The blocking managed-spawn POST previously left the operator with zero
// feedback for the whole (potentially multi-minute) first-run clone; a spinner
// now wraps the call, and this is the pure message-formatting helper behind it.

#[test]
fn spawn_progress_message_first_run() {
    // Why: the first-run case must name the project and the destination path so
    // the operator understands why the wait is long.
    let path = PathBuf::from("/home/user/trusty-mpm-projects/owner/repo");
    let msg = spawn_progress_message(Some(&("owner/repo".to_string(), path.clone())));
    assert!(msg.contains("owner/repo"));
    assert!(msg.contains(&path.display().to_string()));
    assert!(msg.contains("first run"));
}

#[test]
fn spawn_progress_message_reuse() {
    // Why: a non-first-run launch (worktree already cloned) should show the
    // generic launching message, not the cloning-specific one.
    let msg = spawn_progress_message(None);
    assert_eq!(msg, "tm: launching new session…");
}

// ── non_github_refusal_message (#1777) ───────────────────────────────────────
// These tests verify the message helper introduced to fix the misleading
// "daemon unreachable" wording shown when the actual reason for refusal is
// "not a GitHub remote". The helper is pure — no stderr capture needed.

#[test]
fn guided_non_github_refusal_message_does_not_mention_daemon_or_start() {
    // Why: the old message wrongly said "daemon unreachable" even when the
    // daemon is running. The new message must never reference daemon
    // reachability or the `tm start` command (#1777).
    // What: call the helper with a GitLab remote and assert forbidden phrases
    // are absent.
    // Test: this is the test.
    let msg = non_github_refusal_message("git@gitlab.com:org/repo.git");
    assert!(
        !msg.contains("daemon unreachable"),
        "refusal message must NOT blame the daemon: {msg}"
    );
    assert!(
        !msg.contains("tm start"),
        "refusal message must NOT instruct to start the daemon: {msg}"
    );
    assert!(
        !msg.contains("Start the daemon"),
        "refusal message must NOT mention starting the daemon: {msg}"
    );
}

#[test]
fn guided_non_github_refusal_message_explains_github_only_policy() {
    // Why: operators need to understand the actual reason — `tm` auto-manages
    // GitHub repositories only, not Gitea/GitLab/bare-SSH remotes.
    // What: asserts the message names "GitHub" as the requirement.
    // Test: this is the test.
    let msg = non_github_refusal_message("https://gitea.example.com/org/repo.git");
    assert!(
        msg.contains("GitHub"),
        "refusal must name GitHub as the auto-management requirement: {msg}"
    );
    assert!(
        msg.to_lowercase().contains("auto-manag"),
        "refusal must mention auto-management scope: {msg}"
    );
}

#[test]
fn guided_non_github_refusal_message_includes_detected_remote() {
    // Why: showing the detected remote URL in the message lets the operator
    // immediately confirm which remote triggered the refusal — useful when
    // running `tm` in a repo with multiple or aliased remotes.
    // What: asserts the passed-in remote string appears verbatim in the output.
    // Test: this is the test.
    let remote = "git@gitlab.com:myorg/myrepo.git";
    let msg = non_github_refusal_message(remote);
    assert!(
        msg.contains(remote),
        "refusal must echo the detected remote ({remote}): {msg}"
    );
}

#[test]
fn guided_non_github_refusal_message_reassures_live_checkout_untouched() {
    // Why: the operator may be anxious that `tm` modified their working tree.
    // The message must clearly state the live checkout was not touched.
    // What: asserts the reassurance phrase appears in the output.
    // Test: this is the test.
    let msg = non_github_refusal_message("https://bitbucket.org/org/repo.git");
    assert!(
        msg.contains("live checkout"),
        "refusal must reassure that the live checkout was not touched: {msg}"
    );
    assert!(
        msg.contains("not touched"),
        "refusal must use the phrase 'not touched': {msg}"
    );
}

// ── #4061: bare-`tm` "not in a git project" vs. managed-pane settle race ─────

#[test]
fn plan_non_git_fallback_retries_when_env_id_present() {
    // Why: a managed-session id resolved from the environment (process or
    // tmux SESSION table) is evidence THIS pane belongs to a managed session
    // — the fallback must retry `try_inplace_relaunch` rather than
    // immediately declaring "not in a git project" (#4061).
    assert_eq!(
        plan_non_git_fallback(Some("11111111-2222-3333-4444-555555555555")),
        NonGitFallbackPlan::RetryInPlace("11111111-2222-3333-4444-555555555555".to_string())
    );
}

#[test]
fn plan_non_git_fallback_ordinary_when_no_env_id() {
    // Why: the common case — a genuinely unmanaged pane/directory — must take
    // the ordinary fast path with no extra daemon round trip (no added
    // latency, no behavior change from pre-#4061).
    assert_eq!(
        plan_non_git_fallback(None),
        NonGitFallbackPlan::OrdinaryNotGit
    );
}

#[test]
fn managed_pane_settle_pending_message_names_id() {
    // Why: the operator must see the specific session id this pane is bound
    // to, and the message must NOT read like the misleading "not in a git
    // project" hint it replaces for this case.
    let id = "11111111-2222-3333-4444-555555555555";
    let msg = managed_pane_settle_pending_message(id);
    assert!(msg.contains(id), "message must name the session id: {msg}");
    assert!(
        !msg.to_ascii_lowercase().contains("not in a git project"),
        "must not reuse the misleading non-git wording: {msg}"
    );
    assert!(
        msg.contains("run `tm` again"),
        "message must give the operator an actionable retry hint: {msg}"
    );
}

// `picker_filter_*` / `is_live_session_state_*` (#1809, #3034/#3044) moved to
// `tests_behavior_e_tests.rs` (#1916-style line-cap rebalance) — this file
// was pushed over the 1500-SLOC test cap by the #3044 reconciliation's added
// coverage; that sibling file had headroom under the same split convention
// this repo already uses for `tests_behavior_c/d/e`.

// ── #1808: daily banner uses two-panel renderer ───────────────────────────────

#[test]
fn daily_banner_two_panel_version_in_title_bar_not_content() {
    // Why (#1808): the daily `tm` banner must use `render_two_panel_banner`
    // so the version appears in the title bar (first line, starts with ╭) and
    // NOT as a separate content row. The compact `render_welcome_panel` path
    // always puts `"trusty-mpm vX.Y.Z"` in the first content row, which is the
    // old behaviour we are replacing.
    // What: builds WelcomeData (same shape the daily banner path uses) and checks
    // the two-panel output for the invariants that distinguish the new path.
    use crate::formatters::banner::two_panel::{render_two_panel_banner, strip_ansi};
    use crate::formatters::info_box::{DaemonInfo, WelcomeData};

    colored::control::set_override(false);
    let data = WelcomeData {
        project: "owner/repo".to_string(),
        workspace: "/home/alice/trusty-mpm-projects/owner/repo".to_string(),
        user: "alice".to_string(),
        reconnecting: false,
        session_name: String::new(),
        daemon: DaemonInfo::default(),
        recent_commits: vec![],
        memory_status: "(not detected)".to_string(),
        search_status: "(not detected)".to_string(),
        review_status: "(not detected)".to_string(),
    };

    let version = env!("CARGO_PKG_VERSION");
    let banner =
        render_two_panel_banner(&data, 120, false).expect("120-col terminal must produce banner");
    let bare = strip_ansi(&banner);

    // 1. Version appears exactly once — in the title bar, never in content rows.
    let count = bare.matches(version).count();
    assert_eq!(
        count, 1,
        "version must appear exactly once (title bar only); found {count}"
    );

    // 2. First line (title bar) starts with ╭ and contains the version.
    let first = bare.lines().next().unwrap_or("");
    assert!(
        first.starts_with('╭'),
        "title bar must start with ╭: {first:?}"
    );
    assert!(
        first.contains(version),
        "title bar must contain the version: {first:?}"
    );

    // 3. Content rows must NOT contain the version string as a standalone line.
    // (The title bar is line 0; content rows follow.)
    for (i, line) in bare.lines().enumerate().skip(1) {
        // Content lines must not reproduce the version outside the border.
        let inner = line.trim_start_matches('│').trim_end_matches('│').trim();
        assert!(
            !inner.starts_with(&format!("trusty-mpm v{version}")),
            "content row {i} must not carry the version line: {line:?}"
        );
    }
    colored::control::unset_override();
}

// ── pane_identity_confirmed (#2456 review finding 1, ROUND 2) ────────────────
// Moved to `commands::pane_identity` (issue #3600) — that module is now the
// ONE shared pane-identity cross-check primitive used by this guard AND by
// `rename.rs`/`pm_guard_deny_by_default.rs`. See its module doc and test
// module for the full coverage (including this exact hijack scenario).

// ── nested_fallback_action (#2777 decommissioned-relaunch dead-end fix) ──────
// When the nested-session guard matched by tmux SESSION name but could NOT
// confirm pane identity, the pre-#2777 fallback ALWAYS reconnected
// (switch-client) — a no-op dead-end when the session is DEAD (the operator is
// already inside the session being "reconnected" to, and nothing live is there).
// `nested_fallback_action` splits dead states (relaunch in place) from
// possibly-live states (reconnect a sibling window).

#[test]
fn nested_fallback_action_relaunches_dead_states() {
    // The reported bug: bare `tm` inside a `decommissioned` session must NOT
    // switch-client to itself. Stopped/errored share the "no live runtime" trait
    // and must relaunch in place too rather than take the destructive daemon
    // /resume path a plain reconnect would reach.
    for state in ["decommissioned", "stopped", "errored"] {
        assert_eq!(
            nested_fallback_action(state),
            NestedFallbackAction::RelaunchInPlace,
            "dead state {state:?} must relaunch in place, not switch-client to self"
        );
    }
}

#[test]
fn nested_fallback_action_reconnects_live_states() {
    // A possibly-live session (its runtime may be in a genuinely different
    // sibling window of the same tmux session) must keep the switch-client
    // reconnect — that is NOT a self no-op, it brings the live pane forward.
    for state in ["active", "provisioning", "running", "some-future-state"] {
        assert_eq!(
            nested_fallback_action(state),
            NestedFallbackAction::Reconnect,
            "possibly-live state {state:?} must reconnect (default), not relaunch"
        );
    }
}

// ── nested_guard_notice (sibling-window hijack fix, follow-up to #2456) ─────

#[test]
fn nested_guard_notice_never_says_refusing() {
    // Regression guard: the old wording ("…refusing to launch a nested
    // session here.") read as a hard failure even when the immediately
    // following reconcile-relaunch succeeded. The reworded notice must never
    // contain that alarming phrasing.
    let msg = nested_guard_notice("my-session");
    assert!(
        !msg.to_lowercase().contains("refus"),
        "nested_guard_notice must not read as a refusal: {msg:?}"
    );
}

#[test]
fn nested_guard_notice_mentions_reconnect_target() {
    // The notice replaces two previously-separate lines (the refusal line and
    // a standalone "reconnecting to '{name}' instead…" line) with one — the
    // session name must still be present so the operator knows where they are
    // being reconnected.
    let msg = nested_guard_notice("my-session");
    assert!(
        msg.contains("my-session"),
        "nested_guard_notice must name the session being reconnected to: {msg:?}"
    );
    assert!(
        msg.contains("reconnecting"),
        "nested_guard_notice must still communicate the reconnect action: {msg:?}"
    );
}

#[test]
fn inplace_self_relaunch_hint_suggests_managed_resume() {
    // #2794: the honest self-relaunch hint must point at the MANAGED relaunch
    // `tm sessions resume <managed-id>` — re-spawning the runtime with the
    // tm-owned CLAUDE_CONFIG_DIR, roster, and persona intact — keyed on the
    // managed session id (`record.id`), NOT the claude conversation id.
    let mut record = make_session("tm-cto-01", "active", None);
    // A claude_session_id must NOT leak into the hint — the managed id is what
    // `tm sessions resume` takes.
    record.claude_session_id = Some("bfc69db6-cb98-4aa7-a07d-89fd69ba710b".to_string());
    let hint = inplace_self_relaunch_hint(&record);
    assert!(
        hint.contains(&format!("tm sessions resume {}", record.id)),
        "hint must suggest the managed `tm sessions resume <id>`: {hint:?}"
    );
    assert!(
        hint.contains("already inside this session's pane"),
        "hint must explain why a reconnect would be a no-op: {hint:?}"
    );
}

#[test]
fn inplace_self_relaunch_hint_never_suggests_bare_claude() {
    // #2794 regression guard: a bare `claude` (or `claude --resume <id>`)
    // launches OUTSIDE the managed session, dropping the tm-owned config —
    // the hint must NEVER suggest it, with or without a claude_session_id.
    for sid in [None, Some("abc123".to_string()), Some("   ".to_string())] {
        let mut record = make_session("tm-cto-01", "active", None);
        record.claude_session_id = sid.clone();
        let hint = inplace_self_relaunch_hint(&record);
        assert!(
            !hint.contains("claude"),
            "hint must never mention a bare `claude` (loses managed config); \
             sid={sid:?}: {hint:?}"
        );
        assert!(
            hint.contains("tm sessions resume"),
            "hint must always point at the managed resume; sid={sid:?}: {hint:?}"
        );
    }
}

// ── #4335: the nested-session guard's fail-open arm ───────────────────────

/// Serve one canned HTTP response on an ephemeral port, then stop.
///
/// Why: `guard_managed_sessions` is a thin I/O wrapper whose ONE interesting
/// behaviour — what it does when the managed-list call fails — cannot be
/// exercised without a server that fails. A real socket keeps reqwest's own
/// status/decode handling in the loop, which is where the failure modes #4335
/// cares about (5xx, unreachable, malformed body) actually surface.
/// What: binds `127.0.0.1:0`, accepts exactly one connection, drains the
/// request, writes `response`, and returns the base URL.
/// Test: used by the `guard_managed_sessions_*` cases below.
async fn serve_once(response: &'static str) -> String {
    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind");
    let addr = listener.local_addr().expect("addr");
    tokio::spawn(async move {
        if let Ok((mut sock, _)) = listener.accept().await {
            let mut buf = [0u8; 2048];
            let _ = sock.read(&mut buf).await;
            let _ = sock.write_all(response.as_bytes()).await;
            let _ = sock.flush().await;
        }
    });
    format!("http://{addr}")
}

#[tokio::test]
async fn guard_managed_sessions_returns_none_when_the_list_call_errors() {
    // #4335 core regression: a failing managed-list call must fail OPEN
    // (None → the guard no-ops → bare `tm` still proceeds) rather than
    // propagating an error or panicking. The behaviour is unchanged from the
    // old `.ok()?`; what changed is that it is now LOGGED, and that this arm
    // has a test at all — the absence of one is why the guard could stop
    // guarding on a cold daemon without anyone noticing.
    let url = serve_once("HTTP/1.1 500 Internal Server Error\r\ncontent-length: 0\r\n\r\n").await;
    let client = reqwest::Client::new();

    let result = guard_managed_sessions(&client, &url).await;

    assert!(
        result.is_none(),
        "a 5xx from the daemon must fail open to None, not error out"
    );
}

#[tokio::test]
async fn guard_managed_sessions_returns_none_when_the_daemon_is_unreachable() {
    // The other cold-daemon shape: nothing listening at all. Same fail-open
    // contract — a down daemon must never block bare `tm`.
    let client = reqwest::Client::new();

    // Port 1 on loopback: reserved, never bound by a normal process.
    let result = guard_managed_sessions(&client, "http://127.0.0.1:1").await;

    assert!(
        result.is_none(),
        "an unreachable daemon must fail open to None"
    );
}

#[tokio::test]
async fn guard_managed_sessions_returns_sessions_on_success() {
    // The positive half: a well-formed listing must reach the guard intact,
    // so the fail-open arms above are proven to be FAILURE paths and not the
    // function's only behaviour.
    let body = concat!(
        r#"{"sessions":[{"id":"11111111-2222-3333-4444-555555555555","#,
        r#""name":"tm-demo-01","state":"active","#,
        r#""created_at":"2026-07-29T00:00:00Z"}]}"#
    );
    let response: &'static str = Box::leak(
        format!(
            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
            body.len(),
            body
        )
        .into_boxed_str(),
    );
    let url = serve_once(response).await;
    let client = reqwest::Client::new();

    let sessions = guard_managed_sessions(&client, &url)
        .await
        .expect("a well-formed listing must reach the guard");

    assert_eq!(sessions.len(), 1, "the listing must survive intact");
    assert_eq!(sessions[0].name, "tm-demo-01");
}