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
//! CLI parse tests and formatter unit tests for `tm` / `trusty-mpm`.
//!
//! Why: tests live in dedicated files so main.rs stays thin. This file
//! covers short-id / banner / formatter tests and the first half of the
//! CLI parse round-trips. Install / hook / session / services / compose
//! tests live in `tests_behavior_a.rs` and `tests_behavior_b_tests.rs`; the
//! managed session-manager verb surface (`session new`/`ls`/`activity`/
//! `send`/`answer`/`attach`/lifecycle aliases/`prune*`/`catchup`) lives in
//! `tests_behavior_d_tests.rs` (split out under the #1916 line-cap rebalance).
//! What: parse round-trips for short_id, banners, daemon, project, session
//! subcommands (up through daemon flag parsing).
//! Test: `cargo test -p trusty-mpm` to run all fast tests.

use clap::Parser;

use crate::cli::{
    AgentAction, CatalogAction, Cli, Command, DEFAULT_URL, DoctorFlags, McpCmd, McpTransportArg,
    MemoryAction, MetaAction, ProjectAction, SessionAction, ShellArg, SlackCmd, TelegramCmd,
};
use crate::commands::misc::{CATALOG_STALE_MSG, CATALOG_UNKNOWN_MSG, NON_GIT_FALLBACK_HINT};
use crate::formatters::banner::{
    fallback_session_name, normalize_workdir, print_launch_banner,
    print_launch_banner_reconnecting, terminal_width,
};
use crate::formatters::session::{deploy_summary_line, short_id};

#[test]
fn deploy_summary_line_formats_counts() {
    // #1917: `session start` prints this exact shape for both the Agents and
    // the (previously missing) Skills deploy summary lines.
    assert_eq!(
        deploy_summary_line("Skills", 3, 1, 2),
        "Skills: 3 deployed, 1 skipped, 2 unchanged"
    );
    assert_eq!(
        deploy_summary_line("Agents", 0, 0, 0),
        "Agents: 0 deployed, 0 skipped, 0 unchanged"
    );
}

#[test]
fn short_id_extracts_uuid_prefix() {
    // SessionId newtype shape `{"0": "<uuid>"}` → first 8 chars of the uuid.
    let value = serde_json::json!({"0": "abcd1234-5678-90ab-cdef-1234567890ab"});
    assert_eq!(short_id(&value), "abcd1234");
}

#[test]
fn short_id_truncates_to_eight_chars() {
    // Any inner uuid string must collapse to exactly 8 characters.
    let value = serde_json::json!({"0": "0123456789abcdef-rest-ignored"});
    assert_eq!(short_id(&value).chars().count(), 8);
}

#[test]
fn short_id_falls_back_when_field_missing() {
    // Missing `0` key or a scalar value → the placeholder.
    assert_eq!(short_id(&serde_json::json!({})), "--------");
    assert_eq!(short_id(&serde_json::json!("scalar")), "--------");
}

#[test]
fn short_id_falls_back_when_value_not_str() {
    // `0` present but not a string → the placeholder.
    assert_eq!(short_id(&serde_json::json!({"0": 42})), "--------");
}

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

#[test]
fn cli_parses_internal_spawn_disclaimed() {
    // #2997: the hidden pane shim collects `<program> <args...>` as a trailing
    // var-arg, including hyphen-led flags — exactly the pane-command shape.
    let cli =
        Cli::try_parse_from(["trusty-mpm", "internal-spawn-disclaimed", "claude", "-p"]).unwrap();
    let Some(Command::InternalSpawnDisclaimed { argv }) = cli.command else {
        panic!("expected internal-spawn-disclaimed");
    };
    assert_eq!(argv, ["claude", "-p"]);
}

#[test]
fn cli_parses_mcp_add() {
    // stdio (default transport): `tm mcp add echo -- echo hi`
    let cli =
        Cli::try_parse_from(["trusty-mpm", "mcp", "add", "echo", "--", "echo", "hi"]).unwrap();
    let Some(Command::Mcp {
        cmd:
            McpCmd::Add {
                name,
                transport,
                env,
                header,
                command_and_args,
                root,
            },
    }) = cli.command
    else {
        panic!("expected mcp add");
    };
    assert_eq!(name, "echo");
    assert_eq!(transport, McpTransportArg::Stdio);
    assert!(env.is_empty() && header.is_empty() && root.is_none());
    assert_eq!(command_and_args, vec!["echo", "hi"]);
}

#[test]
fn cli_parses_mcp_add_env_and_root() {
    // `tm mcp add srv -e A=1 -e B=2 --root /x -- npx pkg`
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "mcp",
        "add",
        "srv",
        "-e",
        "A=1",
        "-e",
        "B=2",
        "--root",
        "/x",
        "--",
        "npx",
        "pkg",
    ])
    .unwrap();
    let Some(Command::Mcp {
        cmd:
            McpCmd::Add {
                env,
                root,
                command_and_args,
                ..
            },
    }) = cli.command
    else {
        panic!("expected mcp add");
    };
    assert_eq!(env, vec!["A=1", "B=2"]);
    assert_eq!(root.as_deref(), Some("/x"));
    assert_eq!(command_and_args, vec!["npx", "pkg"]);
}

#[test]
fn cli_parses_mcp_add_http() {
    // `tm mcp add sentry -t http -H "Authorization: Bearer t" https://x/mcp`
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "mcp",
        "add",
        "sentry",
        "-t",
        "http",
        "-H",
        "Authorization: Bearer t",
        "https://x/mcp",
    ])
    .unwrap();
    let Some(Command::Mcp {
        cmd:
            McpCmd::Add {
                transport,
                header,
                command_and_args,
                ..
            },
    }) = cli.command
    else {
        panic!("expected mcp add http");
    };
    assert_eq!(transport, McpTransportArg::Http);
    assert_eq!(header, vec!["Authorization: Bearer t"]);
    assert_eq!(command_and_args, vec!["https://x/mcp"]);
}

#[test]
fn cli_parses_mcp_remove_list_get() {
    let rm = Cli::try_parse_from(["trusty-mpm", "mcp", "remove", "echo"]).unwrap();
    assert!(matches!(
        rm.command,
        Some(Command::Mcp {
            cmd: McpCmd::Remove { .. }
        })
    ));
    let ls = Cli::try_parse_from(["trusty-mpm", "mcp", "list", "--json"]).unwrap();
    let Some(Command::Mcp {
        cmd: McpCmd::List { json, .. },
    }) = ls.command
    else {
        panic!("expected mcp list");
    };
    assert!(json);
    let get = Cli::try_parse_from(["trusty-mpm", "mcp", "get", "echo"]).unwrap();
    assert!(matches!(
        get.command,
        Some(Command::Mcp {
            cmd: McpCmd::Get { .. }
        })
    ));
}

#[test]
fn cli_parses_mcp_test() {
    // Bare sweep: no name, no flags.
    let bare = Cli::try_parse_from(["trusty-mpm", "mcp", "test"]).unwrap();
    let Some(Command::Mcp {
        cmd: McpCmd::Test { name, json, root },
    }) = bare.command
    else {
        panic!("expected mcp test");
    };
    assert!(name.is_none() && !json && root.is_none());

    // Named + --json + --root.
    let named = Cli::try_parse_from([
        "trusty-mpm",
        "mcp",
        "test",
        "trusty-memory",
        "--json",
        "--root",
        "/x",
    ])
    .unwrap();
    let Some(Command::Mcp {
        cmd: McpCmd::Test { name, json, root },
    }) = named.command
    else {
        panic!("expected mcp test named");
    };
    assert_eq!(name.as_deref(), Some("trusty-memory"));
    assert!(json);
    assert_eq!(root.as_deref(), Some("/x"));
}

#[test]
fn cli_parses_start() {
    let cli = Cli::try_parse_from(["trusty-mpm", "start"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Start));
}

#[test]
fn cli_parses_serve() {
    // Bare `serve` defaults to the non-stdio (start-like) behaviour.
    let cli = Cli::try_parse_from(["trusty-mpm", "serve"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Serve { stdio: false }
    ));
}

#[test]
fn cli_parses_serve_stdio() {
    // `serve --stdio` selects the MCP stdio bridge (#1221).
    let cli = Cli::try_parse_from(["trusty-mpm", "serve", "--stdio"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Serve { stdio: true }
    ));
}

#[test]
fn cli_parses_stop() {
    let cli = Cli::try_parse_from(["trusty-mpm", "stop"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Stop));
}

#[test]
fn cli_parses_doctor() {
    let cli = Cli::try_parse_from(["trusty-mpm", "doctor"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Doctor {
            flags: DoctorFlags {
                prune_stale_skills: false,
                fix_skills: false,
                fix: false,
                yes: false,
                include_frozen: false,
            }
        }
    ));
}

#[test]
fn cli_parses_doctor_prune_stale_skills() {
    let cli = Cli::try_parse_from(["trusty-mpm", "doctor", "--prune-stale-skills"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Doctor {
            flags: DoctorFlags {
                prune_stale_skills: true,
                fix_skills: false,
                fix: false,
                yes: false,
                include_frozen: false,
            }
        }
    ));
}

/// #4604: `--fix-skills` is opt-in, and overwriting a FROZEN (hand-edited)
/// skill needs a second, explicit opt-in on top of it.
///
/// Why: a frozen file is deliberate user customization; the CLI must make
/// overwriting one impossible to reach by accident. `--include-frozen` alone
/// must be REJECTED, not silently interpreted as a fix request.
/// Test: this test.
#[test]
fn cli_parses_doctor_fix_skills() {
    let cli = Cli::try_parse_from(["trusty-mpm", "doctor", "--fix-skills"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Doctor {
            flags: DoctorFlags {
                prune_stale_skills: false,
                fix_skills: true,
                fix: false,
                yes: false,
                include_frozen: false,
            }
        }
    ));

    let cli =
        Cli::try_parse_from(["trusty-mpm", "doctor", "--fix-skills", "--include-frozen"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Doctor {
            flags: DoctorFlags {
                fix_skills: true,
                include_frozen: true,
                ..
            }
        }
    ));

    assert!(
        Cli::try_parse_from(["trusty-mpm", "doctor", "--include-frozen"]).is_err(),
        "--include-frozen without --fix-skills must be rejected"
    );
}

/// #4948: `--fix` is a DRY RUN, and writing needs `--yes` on top of it.
///
/// Why: `--fix` rewrites project settings files and deployed skills. The CLI
/// is where "the default cannot write" is actually enforced, so it gets a test
/// — a `--yes` that parses without `--fix` would let a future refactor reach a
/// write path from a flag the operator thinks is inert.
/// Test: this test.
#[test]
fn cli_parses_doctor_fix() {
    let cli = Cli::try_parse_from(["trusty-mpm", "doctor", "--fix"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Doctor {
            flags: DoctorFlags {
                fix: true,
                yes: false,
                fix_skills: false,
                ..
            }
        }
    ));

    let cli = Cli::try_parse_from(["trusty-mpm", "doctor", "--fix", "--yes"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Doctor {
            flags: DoctorFlags {
                fix: true,
                yes: true,
                ..
            }
        }
    ));

    assert!(
        Cli::try_parse_from(["trusty-mpm", "doctor", "--yes"]).is_err(),
        "--yes without --fix must be rejected"
    );

    // `--include-frozen` requires EITHER repair flag (issue #4948 widened the
    // `requires` from `--fix-skills` alone to the `repair` group).
    let cli = Cli::try_parse_from(["trusty-mpm", "doctor", "--fix", "--include-frozen"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Doctor {
            flags: DoctorFlags {
                fix: true,
                include_frozen: true,
                ..
            }
        }
    ));
}

#[test]
fn cli_parses_validate() {
    let cli = Cli::try_parse_from(["trusty-mpm", "validate"]).unwrap();
    match cli.command.unwrap() {
        Command::Validate { path, repair } => {
            assert_eq!(path, None);
            assert!(!repair);
        }
        other => panic!("expected Command::Validate, got {other:?}"),
    }
}

#[test]
fn cli_parses_validate_with_path_and_repair() {
    let cli =
        Cli::try_parse_from(["trusty-mpm", "validate", "--path", "/tmp/ws", "--repair"]).unwrap();
    match cli.command.unwrap() {
        Command::Validate { path, repair } => {
            assert_eq!(path, Some(std::path::PathBuf::from("/tmp/ws")));
            assert!(repair);
        }
        other => panic!("expected Command::Validate, got {other:?}"),
    }
}

#[test]
fn cli_parses_health() {
    let cli = Cli::try_parse_from(["trusty-mpm", "health"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Health));
}

#[test]
fn cli_parses_agent_list() {
    // DOC-42 / issue #2889.
    let cli = Cli::try_parse_from(["trusty-mpm", "agent", "list"]).unwrap();
    match cli.command.unwrap() {
        Command::Agent {
            action: AgentAction::List { json },
        } => assert!(!json),
        other => panic!("expected Command::Agent list, got {other:?}"),
    }
}

#[test]
fn cli_parses_agent_list_json() {
    let cli = Cli::try_parse_from(["trusty-mpm", "agent", "list", "--json"]).unwrap();
    match cli.command.unwrap() {
        Command::Agent {
            action: AgentAction::List { json },
        } => assert!(json),
        other => panic!("expected Command::Agent list --json, got {other:?}"),
    }
}

#[test]
fn cli_parses_agent_show() {
    let cli = Cli::try_parse_from(["trusty-mpm", "agent", "show", "code-critic"]).unwrap();
    match cli.command.unwrap() {
        Command::Agent {
            action: AgentAction::Show { name, json },
        } => {
            assert_eq!(name, "code-critic");
            assert!(!json);
        }
        other => panic!("expected Command::Agent show, got {other:?}"),
    }
}

#[test]
fn cli_parses_project_init() {
    let cli = Cli::try_parse_from(["trusty-mpm", "project", "init"]).unwrap();
    match cli.command.unwrap() {
        Command::Project {
            action: ProjectAction::Init { dir },
        } => assert_eq!(dir, None),
        other => panic!("expected project init, got {other:?}"),
    }
}

#[test]
fn cli_parses_project_init_with_dir() {
    let cli = Cli::try_parse_from(["trusty-mpm", "project", "init", "--dir", "/work/p"]).unwrap();
    match cli.command.unwrap() {
        Command::Project {
            action: ProjectAction::Init { dir },
        } => assert_eq!(dir.as_deref(), Some("/work/p")),
        other => panic!("expected project init, got {other:?}"),
    }
}

#[test]
fn cli_parses_project_list() {
    let cli = Cli::try_parse_from(["trusty-mpm", "project", "list"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Project {
            action: ProjectAction::List
        }
    ));
}

#[test]
fn cli_parses_project_info() {
    let cli = Cli::try_parse_from(["trusty-mpm", "project", "info"]).unwrap();
    match cli.command.unwrap() {
        Command::Project {
            action: ProjectAction::Info { dir },
        } => assert_eq!(dir, None),
        other => panic!("expected project info, got {other:?}"),
    }
}

// `cli_parses_project_trust`/`cli_parses_project_trust_revoke` and the
// `project trust` behavioral coverage live in
// `tests_project_trust_tests.rs` instead of here, to stay under this file's
// 1500-SLOC test cap (issue #3033).

#[test]
fn cli_project_requires_action() {
    // `project` with no action is an error.
    assert!(Cli::try_parse_from(["trusty-mpm", "project"]).is_err());
}

#[test]
fn cli_parses_meta_run() {
    // Bare `meta run` defaults to no demo, no explicit project, no-provision off,
    // and no explicit timeout (#1049/#1051).
    let cli = Cli::try_parse_from(["trusty-mpm", "meta", "run"]).unwrap();
    match cli.command.unwrap() {
        Command::Meta {
            action:
                MetaAction::Run {
                    demo,
                    project,
                    no_provision,
                    timeout_secs,
                },
        } => {
            assert!(!demo);
            assert_eq!(project, None);
            assert!(!no_provision);
            assert_eq!(timeout_secs, None);
        }
        other => panic!("expected meta run, got {other:?}"),
    }
}

#[test]
fn cli_parses_meta_run_demo() {
    // `meta run --demo` sets the demo flag.
    let cli = Cli::try_parse_from(["trusty-mpm", "meta", "run", "--demo"]).unwrap();
    match cli.command.unwrap() {
        Command::Meta {
            action: MetaAction::Run { demo, project, .. },
        } => {
            assert!(demo);
            assert_eq!(project, None);
        }
        other => panic!("expected meta run --demo, got {other:?}"),
    }
}

#[test]
fn cli_parses_meta_run_project() {
    // `meta run --demo --project <PATH>` captures both the flag and the path.
    let cli =
        Cli::try_parse_from(["trusty-mpm", "meta", "run", "--demo", "--project", "/tmp"]).unwrap();
    match cli.command.unwrap() {
        Command::Meta {
            action: MetaAction::Run { demo, project, .. },
        } => {
            assert!(demo);
            assert_eq!(project.as_deref(), Some(std::path::Path::new("/tmp")));
        }
        other => panic!("expected meta run --project, got {other:?}"),
    }
}

#[test]
fn cli_parses_meta_run_no_provision() {
    // `meta run --no-provision` sets the clone-skip flag (#1049).
    let cli = Cli::try_parse_from(["trusty-mpm", "meta", "run", "--no-provision"]).unwrap();
    match cli.command.unwrap() {
        Command::Meta {
            action: MetaAction::Run { no_provision, .. },
        } => assert!(no_provision),
        other => panic!("expected meta run --no-provision, got {other:?}"),
    }
}

#[test]
fn cli_parses_meta_run_timeout() {
    // `meta run --timeout-secs 30` overrides the poll budget (#1051).
    let cli = Cli::try_parse_from(["trusty-mpm", "meta", "run", "--timeout-secs", "30"]).unwrap();
    match cli.command.unwrap() {
        Command::Meta {
            action: MetaAction::Run { timeout_secs, .. },
        } => assert_eq!(timeout_secs, Some(30)),
        other => panic!("expected meta run --timeout-secs, got {other:?}"),
    }
}

#[test]
fn cli_meta_requires_action() {
    // `meta` with no action is an error.
    assert!(Cli::try_parse_from(["trusty-mpm", "meta"]).is_err());
}

#[test]
fn cli_parses_launch() {
    let cli = Cli::try_parse_from(["trusty-mpm", "launch"]).unwrap();
    match cli.command.unwrap() {
        Command::Launch {
            dir,
            style,
            worktree,
        } => {
            assert_eq!(dir, None);
            assert_eq!(style, None);
            assert!(!worktree, "#5274: a bare `tm launch` requests no worktree");
        }
        other => panic!("expected launch, got {other:?}"),
    }
}

#[test]
fn cli_parses_launch_with_dir() {
    let cli = Cli::try_parse_from(["trusty-mpm", "launch", "/work/p"]).unwrap();
    match cli.command.unwrap() {
        Command::Launch {
            dir,
            style,
            worktree,
        } => {
            assert_eq!(dir.as_deref(), Some("/work/p"));
            assert_eq!(style, None);
            assert!(!worktree);
        }
        other => panic!("expected launch, got {other:?}"),
    }
}

#[test]
fn cli_parses_launch_with_style() {
    // HR-4: `--style <id>` selects the active output style for this launch.
    let cli =
        Cli::try_parse_from(["trusty-mpm", "launch", "--style", "trusty-mpm-teacher"]).unwrap();
    match cli.command.unwrap() {
        Command::Launch {
            dir,
            style,
            worktree,
        } => {
            assert_eq!(dir, None);
            assert_eq!(style.as_deref(), Some("trusty-mpm-teacher"));
            assert!(!worktree);
        }
        other => panic!("expected launch, got {other:?}"),
    }
}

/// `tm launch --worktree` must reach the parser as a real, distinct request
/// (#5274 — contract row 3).
///
/// Why: rule 2 of the #5274 placement contract says an EXPLICIT user request
/// can put a session in a worktree, and rule 1 says nothing else can. That only
/// holds if such a request is expressible at launch time. Without this flag the
/// contract's third row has no way to be entered at all, and the earlier attempt
/// at this change reached for a `const fn` that no user could override.
/// What: parses `tm launch --worktree` and asserts the flag arrives `true`,
/// while `cli_parses_launch` above pins the bare form at `false`. The pair is
/// what makes "explicit" mean explicit rather than "always on".
/// Test: itself.
#[test]
fn cli_parses_launch_with_worktree() {
    let cli = Cli::try_parse_from(["trusty-mpm", "launch", "--worktree"]).unwrap();
    match cli.command.unwrap() {
        Command::Launch {
            dir,
            style,
            worktree,
        } => {
            assert_eq!(dir, None);
            assert_eq!(style, None);
            assert!(
                worktree,
                "`--worktree` must surface as an explicit worktree request (#5274)"
            );
        }
        other => panic!("expected launch, got {other:?}"),
    }
}

#[test]
fn fallback_session_name_has_tm_prefix() {
    let name = fallback_session_name(std::path::Path::new("/work/p"));
    assert!(name.starts_with("tm-"), "got {name}");
}

#[test]
fn fallback_session_name_uses_folder() {
    // The offline fallback name reflects the project folder, not a UUID.
    let name = fallback_session_name(std::path::Path::new("/Users/x/trusty-mpm"));
    assert_eq!(name, "tm-trusty-mpm");
}

#[test]
fn launch_banner_does_not_panic() {
    // Why: the banner does width math and probes PATH; exercise it to catch
    // arithmetic underflow or formatting regressions.
    print_launch_banner("/Users/test/project", "tmpm-quiet-falcon", None, None);
    print_launch_banner(
        "/Users/test/project",
        "tmpm-quiet-falcon",
        Some(std::path::Path::new("/tmp/system-prompt.txt")),
        None,
    );
}

#[test]
fn launch_reconnect_banner_does_not_panic() {
    // Why: the reconnect banner shares the render path with the launch
    // banner; exercise it to catch formatting regressions.
    print_launch_banner_reconnecting("/Users/test/project", "tmpm-quiet-falcon");
}

#[test]
fn terminal_width_is_positive() {
    // Why: callers use the width for layout; a zero or absurd value would
    // break formatting. The probe must always yield a usable column count.
    assert!(terminal_width() > 0);
}

#[test]
fn banner_title_bar_contains_version() {
    // Why: the single-box banner embeds the crate version in the title bar;
    // this ensures the version is always visible to the operator at a glance.
    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: "my-project".to_string(),
        workspace: "/Users/test/project".to_string(),
        user: "operator".to_string(),
        reconnecting: false,
        session_name: "tmpm-my-project".to_string(),
        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 out = render_two_panel_banner(&data, 120, false).expect("wide banner");
    let first_line = out.lines().next().unwrap_or("");
    let bare = strip_ansi(first_line);
    assert!(
        bare.contains(env!("CARGO_PKG_VERSION")),
        "title bar must contain CARGO_PKG_VERSION: {bare:?}"
    );
    assert!(
        bare.starts_with('╭'),
        "title bar must start with outer box corner ╭: {bare:?}"
    );
    colored::control::unset_override();
}

#[test]
fn banner_reconnect_label_in_wide_mode() {
    // Why: the reconnect label in the wide single-box banner must say
    // "Reconnecting..." so the operator knows no new session was started.
    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: "my-project".to_string(),
        workspace: "/Users/test/project".to_string(),
        user: "operator".to_string(),
        reconnecting: true,
        session_name: "tmpm-quiet-falcon".to_string(),
        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 out = render_two_panel_banner(&data, 120, true).expect("wide reconnect banner");
    let bare = strip_ansi(&out);
    assert!(
        bare.contains("Reconnecting..."),
        "wide reconnect banner must contain 'Reconnecting...': {bare:.200}"
    );
    colored::control::unset_override();
}

#[test]
fn normalize_workdir_strips_trailing_slash() {
    // Why: a daemon-stored workdir and the resolved cwd may differ only by a
    // trailing slash; reconnect detection must treat them as equal. Use a
    // path that does not exist so canonicalize falls through to the
    // string-normalization branch deterministically.
    let with = normalize_workdir("/no/such/dir/");
    let without = normalize_workdir("/no/such/dir");
    assert_eq!(with, without);
    assert_eq!(without, "/no/such/dir");
}

#[test]
fn cli_parses_session_start() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "start"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Start { dir },
        } => assert_eq!(dir, None),
        other => panic!("expected session start, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_start_with_dir() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "start", "--dir", "/work/p"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Start { dir },
        } => assert_eq!(dir.as_deref(), Some("/work/p")),
        other => panic!("expected session start, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_stop() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "stop", "tmpm-quiet-falcon"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Stop { id_or_name },
        } => assert_eq!(id_or_name, "tmpm-quiet-falcon"),
        other => panic!("expected session stop, got {other:?}"),
    }
}

#[test]
fn cli_session_stop_requires_arg() {
    // `session stop` without an id-or-name is an error.
    assert!(Cli::try_parse_from(["trusty-mpm", "session", "stop"]).is_err());
}

#[test]
fn cli_parses_session_kill() {
    // `kill` is a visible alias (#2191) for `stop` — it parses to the same
    // `SessionAction::Stop` variant so it dispatches through the identical
    // managed-aware handler with zero other changes.
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "kill", "tmpm-quiet-falcon"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Stop { id_or_name },
        } => assert_eq!(id_or_name, "tmpm-quiet-falcon"),
        other => panic!("expected session kill (stop), got {other:?}"),
    }
}

#[test]
fn cli_parses_session_list() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "list"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::List { dir },
        } => assert_eq!(dir, None),
        other => panic!("expected session list, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_clean() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "clean"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Clean { dir },
        } => assert_eq!(dir, None),
        other => panic!("expected session clean, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_info() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "info", "abc-123"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Info { id_or_name },
        } => assert_eq!(id_or_name, "abc-123"),
        other => panic!("expected session info, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_instructions() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "instructions"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Instructions { dir },
        } => assert_eq!(dir, None),
        other => panic!("expected session instructions, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_instructions_with_dir() {
    let cli =
        Cli::try_parse_from(["trusty-mpm", "session", "instructions", "--dir", "/tmp"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Instructions { dir },
        } => assert_eq!(dir.as_deref(), Some("/tmp")),
        other => panic!("expected session instructions, got {other:?}"),
    }
}

#[test]
fn cli_parses_events() {
    let cli = Cli::try_parse_from(["trusty-mpm", "events"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Events));
}

#[test]
fn cli_url_flag_overrides_default() {
    let cli = Cli::try_parse_from(["trusty-mpm", "--url", "http://x:9", "status"]).unwrap();
    assert_eq!(cli.url.as_deref(), Some("http://x:9"));
}

#[test]
fn cli_url_flag_equal_to_default_is_still_some() {
    // Regression test for issue #2487: `cli.url` must distinguish "the operator
    // explicitly passed --url <DEFAULT_URL>" from "nothing was passed at all".
    // Before the fix, `cli.url` was a plain `String` with
    // `default_value = DEFAULT_URL`, so both cases produced the identical
    // string and every downstream resolver had to guess — incorrectly, in
    // this exact case — which one actually happened.
    let cli = Cli::try_parse_from(["trusty-mpm", "--url", DEFAULT_URL, "status"]).unwrap();
    assert_eq!(
        cli.url.as_deref(),
        Some(DEFAULT_URL),
        "an explicit --url equal to the default must still parse as Some, not be lost"
    );
}

#[test]
fn cli_bare_invocation_uses_guided_default() {
    // Since #1708, a bare `tm` invocation is valid: clap parses it with
    // command = None and the guided default fires at runtime.
    let cli = Cli::try_parse_from(["trusty-mpm"]).expect("bare tm must parse");
    assert!(
        cli.command.is_none(),
        "bare tm should produce command = None"
    );
}

#[test]
fn cli_parses_tui_defaults() {
    // The `--url` flag is passed explicitly: the `tui` subcommand's `url`
    // arg carries `env = "TRUSTY_MPM_URL"`, so an ambient `TRUSTY_MPM_URL`
    // in the test runner's environment would otherwise override the clap
    // `default_value` and make this assertion environment-dependent.
    // `interval_ms` has no env binding, so its default is asserted bare.
    let cli = Cli::try_parse_from(["trusty-mpm", "tui", "--url", DEFAULT_URL]).unwrap();
    match cli.command.unwrap() {
        Command::Tui { url, interval_ms } => {
            assert_eq!(url.as_deref(), Some(DEFAULT_URL));
            assert_eq!(interval_ms, 1000);
        }
        other => panic!("expected Tui, got {other:?}"),
    }
}

#[test]
fn cli_parses_tui_with_interval() {
    let cli = Cli::try_parse_from(["trusty-mpm", "tui", "--interval-ms", "500"]).unwrap();
    match cli.command.unwrap() {
        Command::Tui { interval_ms, .. } => assert_eq!(interval_ms, 500),
        other => panic!("expected Tui, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_tui() {
    // #1392: the coordinator TUI is the `tm session tui` subcommand (renamed
    // from the former top-level `tm coordinator-tui`). Its `--interval-ms`
    // defaults to 1500. The `url` arg carries `env = "TRUSTY_MPM_URL"`, so an
    // ambient `TRUSTY_MPM_URL` in the test runner would override the (absent)
    // default — assert only the env-independent interval default here, and the
    // url plumbing in `cli_parses_session_tui_with_flags`.
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "tui"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Tui { interval_ms, .. },
        } => {
            assert_eq!(interval_ms, 1500);
        }
        other => panic!("expected Session::Tui, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_tui_with_flags() {
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "session",
        "tui",
        "--url",
        "http://127.0.0.1:9999",
        "--interval-ms",
        "750",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Tui { url, interval_ms },
        } => {
            assert_eq!(url.as_deref(), Some("http://127.0.0.1:9999"));
            assert_eq!(interval_ms, 750);
        }
        other => panic!("expected Session::Tui, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_singular() {
    // #1916 made `session` (singular) canonical with no plural alias. #2116
    // (DOC-35 §2.2/§3.2) reverses that: `sessions` (plural) is now canonical,
    // sibling to `tm projects`, and `session` is kept as a hidden deprecated
    // alias rather than retired — so this exact invocation must keep parsing
    // identically to before, into the same `Command::Session` variant.
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "list"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::List { dir },
        } => assert_eq!(dir, None),
        other => panic!("expected session list, got {other:?}"),
    }
}

// #2116 note: the mirror-plural parse test, the full-verb-surface parity
// sweep, and the alias-notice message-text assertion moved to
// `tests_behavior_e_tests.rs` to keep this file under the 1500-SLOC test cap
// (`cli_parses_sessions_plural_canonical`, `cli_session_and_sessions_agree_for_every_verb`,
// `top_level_alias_notice_message`).

#[test]
fn cli_rejects_removed_coordinator_tui() {
    // #1392: the old top-level `tm coordinator-tui` was deleted (not aliased).
    // Parsing it must now fail with an unrecognized-subcommand error.
    let err = Cli::try_parse_from(["trusty-mpm", "coordinator-tui"]).unwrap_err();
    assert_eq!(
        err.kind(),
        clap::error::ErrorKind::InvalidSubcommand,
        "expected InvalidSubcommand, got {:?}",
        err.kind()
    );
}

#[test]
fn cli_parses_telegram_pair() {
    let cli = Cli::try_parse_from(["trusty-mpm", "telegram", "pair"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Telegram {
            cmd: TelegramCmd::Pair
        }
    ));
}

#[test]
fn cli_parses_telegram_status() {
    let cli = Cli::try_parse_from(["trusty-mpm", "telegram", "status"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Telegram {
            cmd: TelegramCmd::Status
        }
    ));
}

#[test]
fn cli_parses_telegram_stop() {
    let cli = Cli::try_parse_from(["trusty-mpm", "telegram", "stop"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Telegram {
            cmd: TelegramCmd::Stop
        }
    ));
}

#[test]
fn cli_telegram_requires_subcommand() {
    // `telegram` with no action is an error now that it is a group.
    assert!(Cli::try_parse_from(["trusty-mpm", "telegram"]).is_err());
}

#[test]
fn cli_parses_telegram_start_with_check() {
    let cli = Cli::try_parse_from(["trusty-mpm", "telegram", "start", "--check"]).unwrap();
    match cli.command.unwrap() {
        Command::Telegram {
            cmd: TelegramCmd::Start { check, token, .. },
        } => {
            assert!(check);
            assert_eq!(token, None);
        }
        other => panic!("expected Telegram start, got {other:?}"),
    }
}

#[test]
fn cli_parses_telegram_start_with_token() {
    let cli =
        Cli::try_parse_from(["trusty-mpm", "telegram", "start", "--token", "secret"]).unwrap();
    match cli.command.unwrap() {
        Command::Telegram {
            cmd: TelegramCmd::Start { token, check, .. },
        } => {
            assert_eq!(token.as_deref(), Some("secret"));
            assert!(!check);
        }
        other => panic!("expected Telegram start, got {other:?}"),
    }
}

#[test]
fn cli_parses_telegram_start_alert_and_user_flags() {
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "telegram",
        "start",
        "--alert-chat-id",
        "12345",
        "--allowed-user-id",
        "67890",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Telegram {
            cmd:
                TelegramCmd::Start {
                    alert_chat_id,
                    allowed_user_id,
                    ..
                },
        } => {
            assert_eq!(alert_chat_id, Some(12345));
            assert_eq!(allowed_user_id, Some(67890));
        }
        other => panic!("expected Telegram start, got {other:?}"),
    }
}

#[test]
fn cli_parses_slack_stop() {
    let cli = Cli::try_parse_from(["trusty-mpm", "slack", "stop"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Slack {
            cmd: SlackCmd::Stop
        }
    ));
}

#[test]
fn cli_slack_requires_subcommand() {
    // `slack` with no action is an error — it is a command group.
    assert!(Cli::try_parse_from(["trusty-mpm", "slack"]).is_err());
}

#[test]
fn cli_parses_slack_start_with_check() {
    let cli = Cli::try_parse_from(["trusty-mpm", "slack", "start", "--check"]).unwrap();
    match cli.command.unwrap() {
        Command::Slack {
            cmd:
                SlackCmd::Start {
                    check,
                    bot_token,
                    app_token,
                    ..
                },
        } => {
            assert!(check);
            assert_eq!(bot_token, None);
            assert_eq!(app_token, None);
        }
        other => panic!("expected Slack start, got {other:?}"),
    }
}

#[test]
fn cli_parses_slack_start_with_tokens() {
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "slack",
        "start",
        "--bot-token",
        "xoxb-secret",
        "--app-token",
        "xapp-secret",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Slack {
            cmd:
                SlackCmd::Start {
                    bot_token,
                    app_token,
                    check,
                    ..
                },
        } => {
            assert_eq!(bot_token.as_deref(), Some("xoxb-secret"));
            assert_eq!(app_token.as_deref(), Some("xapp-secret"));
            assert!(!check);
        }
        other => panic!("expected Slack start, got {other:?}"),
    }
}

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

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

/// Issue #4397: `tm daemon --force` must parse — the bare-CLI opt-in past the
/// #2486 unsupervised-launchd guard.
#[test]
fn cli_parses_daemon_force() {
    let cli = Cli::try_parse_from(["trusty-mpm", "daemon", "--force"]).unwrap();
    match cli.command.unwrap() {
        Command::Daemon { force, .. } => assert!(force),
        other => panic!("expected Daemon, got {other:?}"),
    }
}

/// Issue #4398: `infer_subcommands` lets an unambiguous prefix of a
/// subcommand name stand in for the full spelling, at every nesting level.
#[test]
fn cli_infers_abbreviated_subcommands() {
    // Top level, no nested action: "doc" only ever prefixes "doctor".
    let cli = Cli::try_parse_from(["trusty-mpm", "doc"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Doctor {
            flags: DoctorFlags {
                prune_stale_skills: false,
                ..
            }
        }
    ));

    // Top level, no other command starts with "heal".
    let cli = Cli::try_parse_from(["trusty-mpm", "heal"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Health));

    // Top level, no other command starts with "rest" ("register" is "reg").
    let cli = Cli::try_parse_from(["trusty-mpm", "rest"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Restart));

    // Inference also propagates into a nested action subcommand.
    let cli = Cli::try_parse_from(["trusty-mpm", "gen", "cap"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Generate { .. }));

    // Inference applies at the nested-action level too: "project ini" for
    // "project init".
    let cli = Cli::try_parse_from(["trusty-mpm", "project", "ini"]).unwrap();
    match cli.command.unwrap() {
        Command::Project {
            action: ProjectAction::Init { dir },
        } => assert_eq!(dir, None),
        other => panic!("expected Command::Project(Init), got {other:?}"),
    }
}

/// Issue #4398: `infer_subcommands` must never break an EXACT match, even
/// when that exact name is also a valid prefix of a sibling command name
/// (`hook`/`hooks`, `project`/`projects`, `session`/`sessions`,
/// `status`/`statusline`). clap resolves exact matches before falling back
/// to prefix inference, so all 8 of these keep resolving to their own
/// command rather than erroring out as an ambiguous prefix.
#[test]
fn cli_exact_match_wins_over_prefix_ambiguity() {
    let cli = Cli::try_parse_from(["trusty-mpm", "status"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Status));

    let cli = Cli::try_parse_from(["trusty-mpm", "statusline"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Statusline));

    let cli = Cli::try_parse_from(["trusty-mpm", "hook"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Hook { pm_guard: false }
    ));

    let cli = Cli::try_parse_from(["trusty-mpm", "hooks", "clean"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Hooks { .. }));

    let cli = Cli::try_parse_from(["trusty-mpm", "project", "list"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Project {
            action: ProjectAction::List
        }
    ));

    let cli = Cli::try_parse_from(["trusty-mpm", "projects", "list"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Projects { .. }));

    let cli = Cli::try_parse_from(["trusty-mpm", "session", "start"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Session { .. }));

    let cli = Cli::try_parse_from(["trusty-mpm", "sessions", "start"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Sessions { .. }));
}

/// #4431 critic HIGH fix: proves the vulnerability precondition AND the
/// runtime guard together close the gap. clap's `infer_subcommands` still
/// resolves every one of these abbreviated prefixes to the HIDDEN
/// `Command::InternalSpawnDisclaimed` variant (`hide = true` only suppresses
/// `--help`, it does not exempt a subcommand from prefix inference) — but
/// `commands::spawn_disclaimed::invoked_literally`, which `main` calls on the
/// RAW argv before ever reaching the disclaimed-spawn leaf, rejects every one
/// of them because the operator did not type the exact, full subcommand
/// name. The exact spelling still parses AND passes the guard, so
/// `disclaim_pane_command`'s own literal self-invocation keeps working.
#[test]
fn cli_infers_internal_spawn_disclaimed_but_runtime_guard_rejects_abbreviations() {
    for prefix in ["int", "inte", "internal"] {
        let raw_argv: Vec<String> = vec!["trusty-mpm".into(), prefix.into(), "claude".into()];
        let cli = Cli::try_parse_from(raw_argv.clone()).unwrap();
        assert!(
            matches!(cli.command, Some(Command::InternalSpawnDisclaimed { .. })),
            "expected clap to still infer {prefix:?} to InternalSpawnDisclaimed"
        );
        assert!(
            !crate::commands::spawn_disclaimed::invoked_literally(&raw_argv),
            "the runtime guard must reject the abbreviated prefix {prefix:?}"
        );
    }

    let raw_argv: Vec<String> = vec![
        "trusty-mpm".into(),
        "internal-spawn-disclaimed".into(),
        "claude".into(),
    ];
    let cli = Cli::try_parse_from(raw_argv.clone()).unwrap();
    assert!(matches!(
        cli.command,
        Some(Command::InternalSpawnDisclaimed { .. })
    ));
    assert!(crate::commands::spawn_disclaimed::invoked_literally(
        &raw_argv
    ));
}

/// #4431 critic MEDIUM: `tm ins` (an unambiguous prefix of `install` only —
/// no other top-level command starts with "ins") must keep resolving to
/// `Command::Install`, confirming the new disclaim-shim guard is scoped to
/// that one hidden variant and does not collaterally affect ordinary
/// abbreviation elsewhere on the CLI surface.
#[test]
fn cli_infers_ins_to_install_unaffected_by_disclaim_guard() {
    let cli = Cli::try_parse_from(["trusty-mpm", "ins"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Install { .. }));
}

#[test]
fn cli_parses_supervisor() {
    let cli = Cli::try_parse_from(["trusty-mpm", "supervisor"]).unwrap();
    match cli.command.unwrap() {
        Command::Supervisor {
            interval,
            auto_resume,
            no_classify,
            ..
        } => {
            assert_eq!(interval, None);
            assert!(!auto_resume);
            assert!(!no_classify);
        }
        other => panic!("expected Supervisor, got {other:?}"),
    }
}

#[test]
fn cli_parses_supervisor_flags() {
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "supervisor",
        "--interval",
        "60",
        "--auto-resume",
        "--no-classify",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Supervisor {
            interval,
            auto_resume,
            no_classify,
            ..
        } => {
            assert_eq!(interval, Some(60));
            assert!(auto_resume);
            assert!(no_classify);
        }
        other => panic!("expected Supervisor, got {other:?}"),
    }
}

#[test]
fn deprecation_notice_format() {
    // The deprecation helper renders a stable, single-line message (#1205).
    // We assert the pure message builder since the eprintln side-effect itself
    // is untestable without capturing process stderr.
    use crate::commands::managed::deprecation_message;
    assert_eq!(
        deprecation_message("runtime-stop", "stop"),
        "warning: 'runtime-stop' is deprecated; use 'stop'"
    );
    assert_eq!(
        deprecation_message("managed-resume", "resume"),
        "warning: 'managed-resume' is deprecated; use 'resume'"
    );
}

// The bespoke `classify_managed_target` resolver was retired in Phase 1B
// (refs #1283); the managed-vs-project routing decision for `stop`/`resume` now
// goes through the ONE canonical `client::resolve_target`. These tests assert the
// SAME routing semantics they did before, but against that shared resolver — the
// `.map(|s| s.id.clone())` mirroring what `managed_route::resolve_managed_match`
// returns to the dispatcher.

#[test]
fn resolve_managed_target_matches_by_id() {
    // #1218: the canonical `stop`/`resume` verbs must recognize a managed
    // session by its UUID and route to the managed endpoint, not project-sessions.
    use trusty_mpm::client::{ManagedSessionSummary, resolve_target};
    let uuid = "11111111-2222-3333-4444-555555555555";
    let sessions: Vec<ManagedSessionSummary> = serde_json::from_value(serde_json::json!([
        { "id": uuid, "name": "tmpm-quiet-falcon", "state": "running" }
    ]))
    .unwrap();
    assert_eq!(
        resolve_target(&sessions, uuid).map(|s| s.id.clone()),
        Some(uuid.to_string()),
        "a managed UUID must resolve to the managed id (routes to managed endpoint)"
    );
}

#[test]
fn resolve_managed_target_matches_by_name_returns_id() {
    // A friendly managed name must resolve to the canonical UUID the managed
    // endpoints require, so `tm session stop <name>` works for managed sessions.
    use trusty_mpm::client::{ManagedSessionSummary, resolve_target};
    let uuid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
    let sessions: Vec<ManagedSessionSummary> = serde_json::from_value(serde_json::json!([
        { "id": uuid, "name": "tmpm-brave-otter", "state": "stopped" }
    ]))
    .unwrap();
    assert_eq!(
        resolve_target(&sessions, "tmpm-brave-otter").map(|s| s.id.clone()),
        Some(uuid.to_string()),
        "a managed name must resolve to its id, not be passed through verbatim"
    );
}

#[test]
fn resolve_managed_target_unknown_falls_back_to_none() {
    // A non-managed id/name must NOT match — the caller then falls back to the
    // project-session path, preserving the local/project-session family (#1218).
    use trusty_mpm::client::{ManagedSessionSummary, resolve_target};
    let sessions: Vec<ManagedSessionSummary> = serde_json::from_value(serde_json::json!([
        { "id": "11111111-2222-3333-4444-555555555555", "name": "tmpm-quiet-falcon", "state": "running" }
    ]))
    .unwrap();
    assert_eq!(
        resolve_target(&sessions, "some-local-session-name").map(|s| s.id.clone()),
        None,
        "an unknown id/name must yield None so `stop`/`resume` fall back to project-sessions"
    );
}

#[test]
fn resolve_managed_target_empty_list_is_none() {
    // With no managed sessions, every argument falls back to project-sessions.
    use trusty_mpm::client::{ManagedSessionSummary, resolve_target};
    let sessions: Vec<ManagedSessionSummary> = Vec::new();
    assert_eq!(
        resolve_target(&sessions, "anything").map(|s| s.id.clone()),
        None
    );
}

#[test]
fn cli_parses_catalog_sync() {
    let cli = Cli::try_parse_from(["trusty-mpm", "catalog", "sync", "--force"]).unwrap();
    match cli.command.unwrap() {
        Command::Catalog {
            action: CatalogAction::Sync { force },
        } => assert!(force),
        other => panic!("expected catalog sync, got {other:?}"),
    }
}

#[test]
fn cli_parses_catalog_ls() {
    let cli = Cli::try_parse_from(["trusty-mpm", "catalog", "ls"]).unwrap();
    match cli.command.unwrap() {
        Command::Catalog {
            action: CatalogAction::Ls { json },
        } => assert!(!json),
        other => panic!("expected catalog ls, got {other:?}"),
    }
}

#[test]
fn cli_parses_catalog_status() {
    let cli = Cli::try_parse_from(["trusty-mpm", "catalog", "status", "--json"]).unwrap();
    match cli.command.unwrap() {
        Command::Catalog {
            action: CatalogAction::Status { json },
        } => assert!(json),
        other => panic!("expected catalog status, got {other:?}"),
    }
}

#[test]
fn cli_parses_catalog_apply() {
    let cli =
        Cli::try_parse_from(["trusty-mpm", "catalog", "apply", "--force", "--prune"]).unwrap();
    match cli.command.unwrap() {
        Command::Catalog {
            action: CatalogAction::Apply { force, prune },
        } => {
            assert!(force);
            assert!(prune);
        }
        other => panic!("expected catalog apply, got {other:?}"),
    }
}

#[test]
fn cli_parses_catalog_apply_defaults() {
    // Without flags, both `force` and `prune` default to false (no surprise
    // network refetch, no surprise removals).
    let cli = Cli::try_parse_from(["trusty-mpm", "catalog", "apply"]).unwrap();
    match cli.command.unwrap() {
        Command::Catalog {
            action: CatalogAction::Apply { force, prune },
        } => {
            assert!(!force);
            assert!(!prune);
        }
        other => panic!("expected catalog apply, got {other:?}"),
    }
}

#[test]
fn cli_parses_ticket() {
    // Why: the minimal form `tm ticket <issue#>` must parse with the `gh`
    // backend as the default and an empty notes list (#1237).
    use crate::commands::ticket::system::TicketSystemKind;
    let cli = Cli::try_parse_from(["trusty-mpm", "ticket", "1232"]).unwrap();
    match cli.command.unwrap() {
        Command::Ticket {
            issue,
            system,
            notes,
            runtime,
        } => {
            assert_eq!(issue, "1232");
            assert_eq!(system, TicketSystemKind::Gh);
            assert!(notes.is_empty());
            assert_eq!(runtime, trusty_mpm::runtime::RuntimeKind::ClaudeCode);
        }
        other => panic!("expected ticket, got {other:?}"),
    }
}

#[test]
fn cli_parses_ticket_with_hash_and_system() {
    // Why: the leading `#` is allowed and the `[system]` positional selects the
    // backend (#1237).
    use crate::commands::ticket::system::TicketSystemKind;
    let cli = Cli::try_parse_from(["trusty-mpm", "ticket", "#1232", "jira"]).unwrap();
    match cli.command.unwrap() {
        Command::Ticket { issue, system, .. } => {
            assert_eq!(issue, "#1232");
            assert_eq!(system, TicketSystemKind::Jira);
        }
        other => panic!("expected ticket, got {other:?}"),
    }
}

#[test]
fn cli_parses_ticket_with_notes() {
    // Why: `--note/-m` is repeatable and each value is posted as an issue comment
    // for the audit trail (#1237).
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "ticket",
        "42",
        "-m",
        "starting work",
        "--note",
        "second note",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Ticket { issue, notes, .. } => {
            assert_eq!(issue, "42");
            assert_eq!(notes, vec!["starting work", "second note"]);
        }
        other => panic!("expected ticket, got {other:?}"),
    }
}

#[test]
fn cli_rejects_ticket_unknown_system() {
    // Why: an unknown `[system]` value must be rejected at parse time with a
    // "possible values" hint, not silently forwarded (#1237).
    let err = Cli::try_parse_from(["trusty-mpm", "ticket", "1", "bogus"]);
    assert!(err.is_err(), "expected unknown system to be rejected");
}

#[test]
fn cli_parses_issue_seed_labels() {
    // Why: `tm issue seed-labels [--dry-run]` must parse with the gh default
    // and surface the dry-run flag (#1246).
    use crate::cli::IssueCmd;
    let cli = Cli::try_parse_from(["trusty-mpm", "issue", "seed-labels", "--dry-run"]).unwrap();
    match cli.command.unwrap() {
        Command::Issue { cmd, .. } => match cmd {
            IssueCmd::SeedLabels { dry_run, config } => {
                assert!(dry_run);
                assert!(config.is_none());
            }
            other => panic!("expected seed-labels, got {other:?}"),
        },
        other => panic!("expected issue, got {other:?}"),
    }
}

#[test]
fn cli_parses_issue_transition() {
    // Why: `tm issue transition <issue#> <to-state> [--note]` must parse the
    // numeric issue, the target state, and the optional note (#1246).
    use crate::cli::IssueCmd;
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "issue",
        "transition",
        "1232",
        "approved",
        "--note",
        "approved by reviewer",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Issue { cmd, .. } => match cmd {
            IssueCmd::Transition {
                issue,
                to_state,
                note,
                ..
            } => {
                assert_eq!(issue, 1232);
                assert_eq!(to_state, "approved");
                assert_eq!(note.as_deref(), Some("approved by reviewer"));
            }
            other => panic!("expected transition, got {other:?}"),
        },
        other => panic!("expected issue, got {other:?}"),
    }
}

#[test]
fn cli_parses_issue_current_and_states_and_repair() {
    // Why: the read/introspection/recovery verbs must all parse (#1246).
    use crate::cli::IssueCmd;
    let current = Cli::try_parse_from(["trusty-mpm", "issue", "current", "7"]).unwrap();
    assert!(matches!(
        current.command.unwrap(),
        Command::Issue {
            cmd: IssueCmd::Current { issue: 7, .. },
            ..
        }
    ));
    let states = Cli::try_parse_from(["trusty-mpm", "issue", "states"]).unwrap();
    assert!(matches!(
        states.command.unwrap(),
        Command::Issue {
            cmd: IssueCmd::States { .. },
            ..
        }
    ));
    let repair = Cli::try_parse_from(["trusty-mpm", "issue", "repair", "9"]).unwrap();
    assert!(matches!(
        repair.command.unwrap(),
        Command::Issue {
            cmd: IssueCmd::Repair { issue: 9, .. },
            ..
        }
    ));
}

#[test]
fn gui_not_found_error_has_install_hint() {
    // Why: when `trusty-mpm-gui` is not installed, `tm gui` must fail with an
    // actionable message telling the user how to install it (gui decoupling,
    // publish-prep). A bare "No such file" from the OS is not acceptable.
    // What: feeds a synthetic `NotFound` spawn error into the result mapper and
    // asserts the error string carries the `cargo install trusty-mpm-gui` hint.
    let not_found = std::io::Error::new(std::io::ErrorKind::NotFound, "no such file");
    let err = crate::gui_status_to_result(Err(not_found))
        .expect_err("NotFound spawn error must map to an Err");
    let msg = err.to_string();
    assert!(
        msg.contains("cargo install trusty-mpm-gui"),
        "expected install hint, got: {msg}"
    );
    assert!(
        msg.contains("not installed"),
        "expected 'not installed' phrasing, got: {msg}"
    );
}

#[test]
fn gui_binary_resolution_falls_back_to_bare_name() {
    // Why: when no `trusty-mpm-gui` sibling exists next to the running binary,
    // the resolver must fall back to the bare name so the OS resolves it on PATH
    // (Single-Install convention). The test binary's dir has no such sibling.
    // What: asserts the resolved path's file name is exactly `trusty-mpm-gui`.
    let resolved = crate::resolve_gui_binary();
    assert_eq!(
        resolved.file_name().and_then(|n| n.to_str()),
        Some("trusty-mpm-gui"),
        "resolver must yield a trusty-mpm-gui path, got: {resolved:?}"
    );
}

#[test]
fn cli_parses_issue_seed_config_force() {
    // Why: `tm issue seed-config --force` must parse the overwrite flag (#1246).
    use crate::cli::IssueCmd;
    let cli = Cli::try_parse_from(["trusty-mpm", "issue", "seed-config", "--force"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Issue {
            cmd: IssueCmd::SeedConfig { force: true },
            ..
        }
    ));
}

#[test]
fn cli_parses_watch_poll_minimal() {
    // Why: the minimal `tm watch poll <project>` must parse with safety defaults
    // (dry-run off but execute also off → dry-run behaviour) and claude-code.
    use crate::cli::WatchCmd;
    let cli = Cli::try_parse_from(["trusty-mpm", "watch", "poll", "owner/repo"]).unwrap();
    match cli.command.unwrap() {
        Command::Watch {
            cmd: WatchCmd::Poll { args },
        } => {
            assert_eq!(args.project, "owner/repo");
            assert!(args.label.is_none());
            assert!(!args.dry_run);
            assert!(!args.execute, "execute must default off (safe)");
            assert!(args.interval_secs.is_none());
            assert!(args.state.is_none());
            assert_eq!(args.runtime, trusty_mpm::runtime::RuntimeKind::ClaudeCode);
        }
        other => panic!("expected watch poll, got {other:?}"),
    }
}

#[test]
fn cli_parses_watch_poll_with_flags() {
    // Why: `--label`, `--state`, and `--execute` must all parse on poll.
    use crate::cli::WatchCmd;
    use crate::commands::watch::github::IssueState;
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "watch",
        "poll",
        "acme/widget",
        "--label",
        "ship-it",
        "--state",
        "all",
        "--execute",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Watch {
            cmd: WatchCmd::Poll { args },
        } => {
            assert_eq!(args.project, "acme/widget");
            assert_eq!(args.label.as_deref(), Some("ship-it"));
            assert_eq!(args.state, Some(IssueState::All));
            assert!(args.execute);
        }
        other => panic!("expected watch poll, got {other:?}"),
    }
}

#[test]
fn cli_parses_watch_listen_with_interval() {
    // Why: `tm watch listen <project> --interval-secs N --dry-run` must parse the
    // listen-specific interval and the explicit safe flag.
    use crate::cli::WatchCmd;
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "watch",
        "listen",
        "owner/repo",
        "--interval-secs",
        "30",
        "--dry-run",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Watch {
            cmd: WatchCmd::Listen { args },
        } => {
            assert_eq!(args.project, "owner/repo");
            assert_eq!(args.interval_secs, Some(30));
            assert!(args.dry_run);
        }
        other => panic!("expected watch listen, got {other:?}"),
    }
}

// WI-10: `tm login` must parse to Command::Login.
#[test]
fn cli_parses_login_standalone() {
    // Why: `tm login` is the one-time keychain auth command (WI-10). It must
    // parse cleanly to the Login variant with no required arguments.
    // What: assert that `tm login` maps to Command::Login.
    // Test: direct parse round-trip.
    let cli = Cli::try_parse_from(["trusty-mpm", "login"]).unwrap();
    assert!(matches!(cli.command.unwrap(), Command::Login { .. }));
}

// ── Image-banner color tests ──────────────────────────────────────────────────

// Issue #1858: `shade_image` used to probe the process-global
// `colored::control` override internally, so these tests had to serialize on
// COLOR_LOCK and mutate/restore that global to exercise the color-on and
// color-off paths — and the sibling test in `two_panel.rs` that did the same
// without the lock was the actual flaky test. `shade_image` now takes
// `use_color` as an explicit parameter, so every test below passes it
// directly; no global mutation or lock is needed anywhere in this file.

#[test]
fn image_clip_has_correct_dimensions() {
    // Why: auto-sizing must produce rows that match the art's actual line count
    // and all rows must have the same display width (the art's max width).
    // What: call shade_image on the embedded default and check row count + col
    // consistency.
    // Test: direct call to shade_image with DEFAULT_BANNER_ART.
    use crate::formatters::banner::{shade_image, source::DEFAULT_BANNER_ART};
    let (lines, cols) = shade_image(DEFAULT_BANNER_ART, false);
    let raw_count = DEFAULT_BANNER_ART.lines().count();
    assert_eq!(
        lines.len(),
        raw_count,
        "shade_image row count must match art line count"
    );
    assert!(cols > 0, "auto-sized cols must be > 0");
    assert!(cols >= 20, "compact-splash art is at least 20 columns wide");
}

#[test]
fn art_char_shading_emits_truecolor() {
    // Why: shade_image must emit truecolor escapes when the caller asks for
    // color (#1839 Fix 3), independent of any process-global state.
    // What: call shade_image with `use_color = true` and verify at least one
    // line contains a truecolor ANSI escape (`\x1B[38;2;`).
    // Test: pure function call, no shared state to race.
    use crate::formatters::banner::{shade_image, source::DEFAULT_BANNER_ART};
    let (lines, _) = shade_image(DEFAULT_BANNER_ART, true);
    let any_colored = lines.iter().any(|l| l.contains("\x1B[38;2;"));
    assert!(
        any_colored,
        "shaded art must emit truecolor escapes when color is enabled"
    );
}

#[test]
fn art_shading_no_ansi_when_color_disabled() {
    // Why: shade_image must suppress ANSI escapes when color is disabled so that
    // banner output piped to a file or CI log is clean plain text (#1839 Fix 3).
    // What: call shade_image with `use_color = false` and assert no line
    // contains an ANSI escape byte.
    // Test: pure function call, no shared state to race.
    use crate::formatters::banner::{shade_image, source::DEFAULT_BANNER_ART};
    let (lines, _) = shade_image(DEFAULT_BANNER_ART, false);
    for line in &lines {
        assert!(
            !line.contains('\x1B'),
            "shade_image must not emit ANSI escapes when color is disabled: {line:?}"
        );
    }
}

#[test]
fn art_shading_spaces_are_uncolored() {
    // Why: spaces in the art should be transparent (no color escape), so
    // the terminal background shows through rather than applying a tint.
    // What: verify that space chars in shaded image lines have no escape prefix.
    // Test: check that strip_ansi still finds spaces in the output.
    use crate::formatters::banner::{
        shade_image, source::DEFAULT_BANNER_ART, two_panel::strip_ansi,
    };
    let (lines, _) = shade_image(DEFAULT_BANNER_ART, true);
    let has_space = lines.iter().any(|l| strip_ansi(l).contains(' '));
    assert!(has_space, "shaded art must contain some uncolored spaces");
}

#[test]
fn narrow_fallback_reconnect_box_includes_reconnecting_text() {
    // Why: the single-box narrow fallback (< MIN_WIDTH_TWO_PANEL) must include
    // "Reconnecting..." when reconnecting=true — matching the wide layout's
    // reconnect indicator. This verifies the fix from commit 54690868 is
    // preserved under the new single-box design.
    // What: render via `render_two_panel_banner` with a narrow width and
    // reconnecting=true; assert the label appears.
    // Test: pure string assertion via the public compositor.
    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: "my-project".to_string(),
        workspace: "/tmp/my-project".to_string(),
        user: String::new(),
        reconnecting: true,
        session_name: "tmpm-my-project".to_string(),
        daemon: DaemonInfo::default(),
        recent_commits: vec![],
        memory_status: "(not detected)".to_string(),
        search_status: "(not detected)".to_string(),
        review_status: "(not detected)".to_string(),
    };
    // 80-col: narrow stacked box.
    let out = render_two_panel_banner(&data, 80, true).expect("narrow box");
    let bare = strip_ansi(&out);
    assert!(
        bare.contains("Reconnecting..."),
        "narrow reconnect box must contain 'Reconnecting...' label"
    );
    // Also verify the outer box is intact.
    let first = bare.lines().next().unwrap_or("");
    assert!(first.starts_with('╭'), "must have outer box top border");
    colored::control::unset_override();
}

#[test]
fn narrow_fallback_normal_box_does_not_include_reconnecting_text() {
    // Why: normal launch (reconnecting=false) narrow box must NOT show
    // "Reconnecting..." — the operator should see the launch context only.
    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: "my-project".to_string(),
        workspace: "/tmp/my-project".to_string(),
        user: String::new(),
        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 out = render_two_panel_banner(&data, 80, false).expect("narrow box");
    let bare = strip_ansi(&out);
    assert!(
        !bare.contains("Reconnecting..."),
        "normal launch narrow box must not contain 'Reconnecting...' label"
    );
    colored::control::unset_override();
}

#[test]
fn cli_parses_banner() {
    // Why: `tm banner` must parse and default `--reconnecting` to false.
    // What: parse "banner" and assert the variant and flag are correct.
    // Test: direct clap parse.
    use crate::cli::{Cli, Command};
    use clap::Parser;
    let cli = Cli::try_parse_from(["tm", "banner"]).expect("banner must parse");
    assert!(
        matches!(
            cli.command,
            Some(Command::Banner {
                reconnecting: false
            })
        ),
        "expected Banner {{ reconnecting: false }}"
    );
}

#[test]
fn cli_parses_banner_reconnecting() {
    // Why: `tm banner --reconnecting` must set the flag to true.
    // What: parse "banner --reconnecting" and assert the reconnecting flag.
    // Test: direct clap parse.
    use crate::cli::{Cli, Command};
    use clap::Parser;
    let cli = Cli::try_parse_from(["tm", "banner", "--reconnecting"])
        .expect("banner --reconnecting must parse");
    assert!(
        matches!(cli.command, Some(Command::Banner { reconnecting: true })),
        "expected Banner {{ reconnecting: true }}"
    );
}

#[test]
fn banner_preview_no_clear_escape() {
    // Why: the `tm banner` preview must NOT begin with the full-screen clear
    // sequence — that would wipe the user's scrollback.
    // What: capture whether the print_banner_preview output starts with the
    // clear escape. Since it writes to stdout, we verify indirectly via the
    // single-box compositor which is used for the preview 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: "p".to_string(),
        workspace: "/tmp/p".to_string(),
        user: String::new(),
        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 out = render_two_panel_banner(&data, 120, false).expect("banner");
    // The compositor never emits a screen-clear — that is added by the print
    // wrappers only, and only for the launch (not preview) path.
    assert!(
        !out.starts_with("\x1B[2J"),
        "compositor output must not start with screen-clear escape"
    );
    // Version appears in the title bar.
    let bare = strip_ansi(&out);
    assert!(
        bare.contains(env!("CARGO_PKG_VERSION")),
        "compositor output must contain version in title bar"
    );
    colored::control::unset_override();
}

#[test]
fn banner_preview_does_not_panic() {
    // Why: `print_banner_preview` probes env/files that may or may not be present;
    // it must never panic in a clean environment.
    // What: call print_banner_preview with both reconnecting states; assert no panic.
    // Test: if the function returns, the assertion is trivially met.
    // Note: output goes to stdout; suppress by redirecting in the test environment.
    crate::formatters::banner::print_banner_preview(false);
    crate::formatters::banner::print_banner_preview(true);
}

#[test]
fn health_catalog_stale_message_contains_action() {
    // Why: operators should see an actionable command when the catalog is stale
    // or never synced — "updates available" without a fix is unhelpful (#1839 Fix 4).
    // What: asserts against the production constants from misc.rs so any change to
    // the actual output string is caught here rather than silently diverging.
    // Test: if `CATALOG_STALE_MSG` or `CATALOG_UNKNOWN_MSG` in misc.rs no longer
    // contains "tm catalog sync", this test fails and flags the regression.
    assert!(
        CATALOG_STALE_MSG.contains("tm catalog sync"),
        "CATALOG_STALE_MSG must name the fix command: {CATALOG_STALE_MSG:?}"
    );
    assert!(
        CATALOG_UNKNOWN_MSG.contains("tm catalog sync"),
        "CATALOG_UNKNOWN_MSG must name the fix command: {CATALOG_UNKNOWN_MSG:?}"
    );
}

#[test]
fn non_git_dir_fallback_prints_help_hint() {
    // Why: `tm` run from a non-git directory should exit cleanly with a help hint
    // rather than an error exit code (#1839 Fix 2).
    // What: asserts against `NON_GIT_FALLBACK_HINT` from misc.rs — the constant
    // that `fallback_protected` in guided.rs actually passes to `eprintln!`. If
    // the hint string is changed to drop "--help", this test catches it immediately.
    // Test: if `NON_GIT_FALLBACK_HINT` no longer mentions "--help", this fails.
    assert!(
        NON_GIT_FALLBACK_HINT.contains("--help"),
        "NON_GIT_FALLBACK_HINT must reference --help for discoverability: \
         {NON_GIT_FALLBACK_HINT:?}"
    );
}

/// Why (#4837): `tm memory import` is the zero-inference bulk-load path;
/// its required `--palace` and the default (write-enabled) mode must parse.
#[test]
fn cli_parses_memory_import() {
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "memory",
        "import",
        "/tmp/mem",
        "--palace",
        "trusty-tools",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Memory {
            action:
                MemoryAction::Import {
                    dir,
                    palace,
                    dry_run,
                    json,
                    allow_secret_like,
                    memory_url,
                },
        } => {
            assert_eq!(dir, std::path::PathBuf::from("/tmp/mem"));
            assert_eq!(palace, "trusty-tools");
            assert!(!dry_run, "writes are the default mode");
            assert!(!json);
            assert!(!allow_secret_like);
            assert!(memory_url.is_none(), "URL defaults to daemon discovery");
        }
        other => panic!("expected Memory/Import, got {other:?}"),
    }
}

/// Why (#4837): `--dry-run` is the safety flag an operator reaches for first,
/// and `--json` is the machine-readable report a caller verifies with — both
/// must round-trip, together with the explicit `--memory-url` override.
#[test]
fn cli_parses_memory_import_dry_run_json() {
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "memory",
        "import",
        "/tmp/mem",
        "--palace",
        "p",
        "--dry-run",
        "--json",
        "--allow-secret-like",
        "--memory-url",
        "http://127.0.0.1:7070",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Memory {
            action:
                MemoryAction::Import {
                    dry_run,
                    json,
                    allow_secret_like,
                    memory_url,
                    ..
                },
        } => {
            assert!(dry_run);
            assert!(json);
            assert!(allow_secret_like);
            assert_eq!(memory_url.as_deref(), Some("http://127.0.0.1:7070"));
        }
        other => panic!("expected Memory/Import, got {other:?}"),
    }
}

#[test]
fn cli_parses_shell_init() {
    // The dialect is a closed set: a typo must be refused at parse time rather
    // than reaching the emitter and printing a snippet for the wrong shell.
    for (arg, want) in [
        ("zsh", ShellArg::Zsh),
        ("bash", ShellArg::Bash),
        ("fish", ShellArg::Fish),
    ] {
        let cli = Cli::try_parse_from(["trusty-mpm", "shell-init", arg]).unwrap();
        match cli.command.unwrap() {
            Command::ShellInit { shell } => assert_eq!(shell, want),
            other => panic!("expected ShellInit, got {other:?}"),
        }
    }
    assert!(Cli::try_parse_from(["trusty-mpm", "shell-init", "ksh"]).is_err());
    assert!(Cli::try_parse_from(["trusty-mpm", "shell-init"]).is_err());
}