git-paw 0.7.0

Parallel AI Worktrees — orchestrate multiple AI coding CLI sessions across git worktrees
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
//! CLI argument parsing.
//!
//! Defines the command-line interface using `clap` v4 with derive macros.
//! All subcommands, flags, and options are declared here.

use clap::{Parser, Subcommand, ValueEnum};
use std::path::PathBuf;

/// Spec format selector for the `--specs-format` flag.
///
/// Three formats are supported:
/// - `openspec` — `openspec/changes/<name>/` directory layout.
/// - `markdown` — single-file Markdown specs with YAML frontmatter.
/// - `speckit` — GitHub Spec Kit `.specify/specs/<feature>/` layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[clap(rename_all = "lowercase")]
pub enum SpecsFormat {
    /// `OpenSpec` format (directory of `<change>/tasks.md`).
    Openspec,
    /// Markdown format (one `.md` file per spec with frontmatter).
    Markdown,
    /// Spec Kit format (`.specify/specs/<feature>/`).
    Speckit,
}

impl SpecsFormat {
    /// Returns the backend-dispatch string for this format.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Openspec => "openspec",
            Self::Markdown => "markdown",
            Self::Speckit => "speckit",
        }
    }
}

/// Parallel AI Worktrees — orchestrate multiple AI coding CLI sessions
/// across git worktrees from a single terminal using tmux.
#[derive(Debug, Parser)]
#[command(
    name = "git-paw",
    version,
    about = "Parallel AI Worktrees — orchestrate multiple AI coding CLI sessions across git worktrees",
    long_about = "git-paw orchestrates multiple AI coding CLI sessions (Claude, Codex, Gemini, etc.) \
                  across git worktrees from a single terminal using tmux. Each branch gets its own \
                  worktree and AI session, running in parallel.",
    after_help = "\x1b[1mQuick Start:\x1b[0m\n\n  \
                  # Launch interactive session (picks CLI and branches)\n  \
                  git paw\n\n  \
                  # Use Claude on specific branches\n  \
                  git paw start --cli claude --branches feat/auth,feat/api\n\n  \
                  # Check session status\n  \
                  git paw status\n\n  \
                  # Pause session (detaches client, stops broker, keeps CLIs alive)\n  \
                  git paw pause\n\n  \
                  # Stop session (kills CLIs, preserves worktrees for later)\n  \
                  git paw stop\n\n  \
                  # Remove everything\n  \
                  git paw purge"
)]
pub struct Cli {
    /// Subcommand to run. Defaults to `start` if omitted.
    #[command(subcommand)]
    pub command: Option<Command>,
}

/// Available subcommands.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Launch a new session or reattach to an existing one
    #[command(
        about = "Launch a new session or reattach to an existing one",
        long_about = "Smart start: reattaches if a session is active, recovers if stopped/crashed, \
                      or launches a new interactive session.\n\n\
                      By default, every existing agent branch is rebased onto the repository's \
                      default branch (whatever `origin/HEAD` tracks — typically `main`) before \
                      its worktree is opened, so agents always start from current main. Pass \
                      `--no-rebase` to skip this step and reproduce the pre-v0.6 behaviour \
                      (useful when you have local pinned SHAs or are deliberately working off a \
                      stale baseline). If the rebase hits a conflict, the affected branch is \
                      left at its pre-rebase HEAD and `git paw start` exits with an error \
                      listing the conflicting files.\n\n\
                      Examples:\n  \
                      git paw start\n  \
                      git paw start --cli claude\n  \
                      git paw start --cli claude --branches feat/auth,feat/api\n  \
                      git paw start --from-all-specs\n  \
                      git paw start --from-all-specs --cli claude\n  \
                      git paw start --specs add-auth,fix-session\n  \
                      git paw start --specs   # opens spec picker (TTY required)\n  \
                      git paw start --dry-run\n  \
                      git paw start --preset backend\n  \
                      git paw start --supervisor   # auto-approve safe prompts via [supervisor.auto_approve]\n  \
                      git paw start --no-supervisor  # disable supervisor for this session (overrides config)\n  \
                      git paw start --no-rebase   # skip rebasing agent branches onto the default branch"
    )]
    Start {
        /// AI CLI to use (e.g., claude, codex, gemini). Skips CLI picker if provided.
        #[arg(long, help = "AI CLI to use (skips CLI picker)")]
        cli: Option<String>,

        /// Comma-separated branch names. Skips branch picker if provided.
        #[arg(
            long,
            value_delimiter = ',',
            help = "Comma-separated branches (skips branch picker)"
        )]
        branches: Option<Vec<String>>,

        /// Launch worktrees for every discovered spec across all configured formats.
        #[arg(
            long,
            alias = "from-specs",
            help = "Launch from every discovered spec across all configured formats"
        )]
        from_all_specs: bool,

        /// Narrow the session to named specs, or open the multi-select picker
        /// when given without values.
        ///
        /// `--specs add-auth,fix-session` runs only those specs. Bare `--specs`
        /// opens a multi-select picker; an interactive terminal is required
        /// (otherwise the command exits with an actionable error pointing at
        /// `--specs NAME[,NAME...]` and `--from-all-specs`).
        ///
        /// Mutually exclusive with `--from-all-specs`.
        #[arg(
            long,
            value_delimiter = ',',
            num_args = 0..,
            conflicts_with = "from_all_specs",
            help = "Comma-separated spec names; bare flag opens picker (TTY required)"
        )]
        specs: Option<Vec<String>>,

        /// Override the spec format used for `--from-all-specs` / `--specs` scanning.
        ///
        /// Accepted values: `openspec`, `markdown`, `speckit`. Overrides both
        /// the `[specs] type` setting in `.git-paw/config.toml` and the
        /// auto-detection of `.specify/` at the repo root.
        #[arg(
            long,
            value_enum,
            help = "Override spec format (openspec, markdown, speckit)"
        )]
        specs_format: Option<SpecsFormat>,

        /// Preview the session plan without executing.
        #[arg(long, help = "Preview the session plan without executing")]
        dry_run: bool,

        /// Use a named preset from config.
        #[arg(long, help = "Use a named preset from config")]
        preset: Option<String>,

        /// Enable supervisor mode for this session.
        #[arg(
            long,
            default_value_t = false,
            help = "Enable supervisor mode for this session"
        )]
        supervisor: bool,

        /// Disable supervisor mode for this session, overriding any config setting.
        #[arg(
            long,
            conflicts_with = "supervisor",
            default_value_t = false,
            help = "Disable supervisor for this session, overriding any [supervisor] enabled = true in config"
        )]
        no_supervisor: bool,

        /// Bypass uncommitted-spec validation warning.
        #[arg(long, help = "Bypass uncommitted-spec validation warning")]
        force: bool,

        /// Skip rebasing existing agent branches onto the default branch
        /// before opening their worktrees.
        ///
        /// By default, `git paw start` rebases every existing agent branch
        /// onto the repository's default branch (whatever `origin/HEAD`
        /// tracks, typically `main`) before opening or reopening its
        /// worktree, so agents always start from current `main`. Pass
        /// `--no-rebase` to skip the rebase step entirely and reproduce the
        /// pre-v0.6 behaviour. Newly created branches (no prior commits) are
        /// not rebased regardless of this flag.
        #[arg(
            long,
            default_value_t = false,
            help = "Skip rebasing existing agent branches onto the default branch before opening worktrees"
        )]
        no_rebase: bool,
    },

    /// Attach a new worktree + agent pane to a running session
    #[command(
        about = "Attach a new worktree + agent pane to a running session",
        long_about = "Hot-attaches a worktree and agent pane to an already-running session — \
                      no stop/purge/restart, the other agents keep working undisturbed. The \
                      agent grid re-tiles to the layout a start of that many agents would \
                      produce, the new branch is registered in the session, and the agent boots \
                      with the same broker boot block + initial prompt a start-time agent gets.\n\n\
                      Provide a branch name, or use --from-spec to derive the branch (and CLI) \
                      from a discovered spec. Adding past the 25-agent cap is rejected. When the \
                      session is paused, the new pane starts paused too and begins on the next \
                      `git paw resume`. The supervisor (if any) discovers the new agent on its \
                      next broker poll — no restart.\n\n\
                      Examples:\n  \
                      git paw add feat/new-thing\n  \
                      git paw add feat/api --cli codex\n  \
                      git paw add --from-spec add-export"
    )]
    Add {
        /// Branch to attach. Omit when using --from-spec (the branch is
        /// derived from the spec).
        #[arg(
            required_unless_present = "from_spec",
            help = "Branch to attach (omit when using --from-spec)"
        )]
        branch: Option<String>,

        /// AI CLI to launch in the new pane (defaults to the session's CLI).
        #[arg(
            long,
            help = "AI CLI for the new pane (defaults to the session's default CLI)"
        )]
        cli: Option<String>,

        /// Resolve the branch name and CLI from a discovered spec instead of a
        /// positional branch argument.
        #[arg(
            long,
            conflicts_with = "branch",
            help = "Derive branch + CLI from a spec (OpenSpec change, Markdown spec, or Spec Kit feature)"
        )]
        from_spec: Option<String>,
    },

    /// Detach a single agent from a running session
    #[command(
        about = "Detach a single agent from a running session",
        long_about = "Removes one agent from an active session: closes its tmux pane, re-tiles \
                      the grid for the smaller agent count, removes its worktree (reusing \
                      `git paw purge`'s per-worktree teardown), and drops it from the session. \
                      The other agents are left untouched.\n\n\
                      Safe by default: `remove` refuses to delete a worktree with uncommitted \
                      changes (it lists what would be lost) unless you pass --force. Pass \
                      --keep-worktree to detach the pane + session entry but leave the worktree \
                      and branch on disk (this skips the uncommitted-work check, since nothing \
                      is deleted). `remove supervisor` is refused — use `git paw stop` to end \
                      the whole session. The supervisor notices the departure on its next broker \
                      poll (the agent stops heartbeating) — no restart.\n\n\
                      Examples:\n  \
                      git paw remove feat/done-thing\n  \
                      git paw remove feat/wip --force\n  \
                      git paw remove feat/keep --keep-worktree"
    )]
    Remove {
        /// Branch of the agent to remove.
        #[arg(help = "Branch of the agent to remove")]
        branch: String,

        /// Detach the pane + session entry but leave the worktree and branch
        /// on disk (skips the uncommitted-work safety check).
        #[arg(
            long,
            help = "Leave the worktree + branch on disk; only detach the pane and session entry"
        )]
        keep_worktree: bool,

        /// Remove the worktree even when it has uncommitted changes.
        #[arg(
            long,
            help = "Remove even with uncommitted changes (bypass the safety check)"
        )]
        force: bool,
    },

    /// Pause the session (detaches client, stops broker, leaves CLIs running)
    #[command(
        about = "Pause the session (detaches client, stops broker, leaves CLIs running)",
        long_about = "Detaches the tmux client and stops the broker, but leaves all CLI \
                      processes running in the background. This preserves agent conversation \
                      state for instant resume via `git paw start`. RAM stays allocated \
                      (~300 MB per Claude pane).\n\n\
                      Use pause for short breaks (lunch, meetings, end-of-day). For longer \
                      breaks, use `git paw stop` to kill the CLIs and release RAM (worktrees \
                      preserved). A future `git paw hibernate` (v1.0.0) will snapshot state \
                      to disk.\n\n\
                      Example:\n  git paw pause"
    )]
    Pause,

    /// Stop the session (kills tmux, keeps worktrees and state)
    #[command(
        about = "Stop the session (kills tmux, keeps worktrees and state)",
        long_about = "Kills the tmux session and every CLI pane process, but preserves \
                      worktrees and session state on disk. CLI conversation context is lost. \
                      Run `git paw start` later to recover the session with fresh CLI \
                      processes.\n\n\
                      Three teardown verbs:\n  \
                      pause — soft stop (detach + broker stop; CLIs keep running, RAM held)\n  \
                      stop  — kills CLI processes; preserves worktrees on disk (this command)\n  \
                      purge — full reset; removes worktrees, branches, and state\n\n\
                      `stop` prompts for confirmation in interactive terminals. Use \
                      `--force` to skip the prompt (scripts) or pipe stdin from \
                      `/dev/null` for non-interactive contexts.\n\n\
                      Examples:\n  git paw stop\n  git paw stop --force"
    )]
    Stop {
        /// Skip confirmation prompt.
        #[arg(long, default_value_t = false, help = "Skip confirmation prompt")]
        force: bool,
    },

    /// Remove everything (tmux session, worktrees, and state)
    #[command(
        about = "Remove everything (tmux session, worktrees, and state)",
        long_about = "Nuclear option: kills the tmux session, removes all worktrees, and deletes \
                      session state. Requires confirmation unless --force is used.\n\n\
                      Use --stale to purge only sessions whose tmux session is gone (a stale \
                      receipt). Live sessions are left untouched, so --stale is safe in cleanup \
                      scripts. Pairing --stale with --force is a no-op (--force is redundant on \
                      a stale entry).\n\n\
                      Examples:\n  git paw purge\n  git paw purge --force\n  git paw purge --stale"
    )]
    Purge {
        /// Skip confirmation prompt.
        #[arg(long, help = "Skip confirmation prompt")]
        force: bool,
        /// Purge only stale sessions (receipt claims active but tmux is gone).
        #[arg(
            long,
            help = "Purge only stale sessions (receipt claims active but tmux is gone); \
                    live sessions untouched"
        )]
        stale: bool,
    },

    /// Show session state for the current repo
    #[command(
        about = "Show session state for the current repo",
        long_about = "Displays the current session status, branches, CLIs, and worktree paths \
                      for the repository in the current directory.\n\n\
                      Status is one of 🟢 active (tmux running), 🔵 paused, 🟡 stopped, or \
                      🔴 stale (the receipt claims active but the tmux session no longer \
                      exists — a crash or release-boundary carry-over). Run `git paw start` to \
                      self-heal a stale receipt, or `git paw purge --stale` to clear it.\n\n\
                      Pass --json for machine-readable output (the `status` field is one of \
                      active/paused/stopped/stale).\n\n\
                      Examples:\n  git paw status\n  git paw status --json"
    )]
    Status {
        /// Emit machine-readable JSON instead of the human-readable display.
        #[arg(long, help = "Emit machine-readable JSON")]
        json: bool,
    },

    /// List detected and custom AI CLIs
    #[command(
        about = "List detected and custom AI CLIs",
        long_about = "Shows all AI CLIs found on PATH (auto-detected) and any custom CLIs \
                      registered in your config.\n\n\
                      Example:\n  git paw list-clis"
    )]
    ListClis,

    /// Register a custom AI CLI
    #[command(
        about = "Register a custom AI CLI",
        long_about = "Adds a custom CLI to your global config (~/.config/git-paw/config.toml). \
                      The command can be an absolute path or a binary name on PATH.\n\n\
                      Examples:\n  \
                      git paw add-cli my-agent /usr/local/bin/my-agent\n  \
                      git paw add-cli my-agent my-agent --display-name \"My Agent\""
    )]
    AddCli {
        /// Name to register the CLI as.
        #[arg(help = "Name to register the CLI as")]
        name: String,

        /// Command or path to the CLI binary.
        #[arg(help = "Command or path to the CLI binary")]
        command: String,

        /// Optional display name for the CLI.
        #[arg(long, help = "Display name shown in prompts")]
        display_name: Option<String>,
    },

    /// Unregister a custom AI CLI
    #[command(
        about = "Unregister a custom AI CLI",
        long_about = "Removes a custom CLI from your global config. Only custom CLIs can be \
                      removed — auto-detected CLIs cannot.\n\n\
                      Example:\n  git paw remove-cli my-agent"
    )]
    RemoveCli {
        /// Name of the custom CLI to remove.
        #[arg(help = "Name of the custom CLI to remove")]
        name: String,
    },

    /// Initialize .git-paw/ directory and configuration
    #[command(
        about = "Initialize .git-paw/ directory and configuration",
        long_about = "Creates the .git-paw/ directory with a default config and sets up \
                      .gitignore for logs.\n\n\
                      Examples:\n  git paw init"
    )]
    Init,

    /// Internal: run the broker and dashboard in pane 0
    #[command(
        hide = true,
        name = "__dashboard",
        about = "Internal: run the broker and dashboard in pane 0",
        long_about = "Internal subcommand used by git-paw to run the broker and dashboard TUI \
                      in pane 0 of a tmux session. Not intended for direct invocation."
    )]
    Dashboard,

    /// View captured session logs
    #[command(
        about = "View captured session logs",
        long_about = "Reads session logs captured by pipe-pane. By default, strips ANSI codes \
                      for clean output. Use --color to view with colors via less -R.\n\n\
                      Examples:\n  \
                      git paw replay --list\n  \
                      git paw replay feat/add-auth\n  \
                      git paw replay feat/add-auth --color\n  \
                      git paw replay feat/add-auth --session paw-myproject"
    )]
    Replay {
        /// Branch name to replay (fuzzy-matched against log filenames).
        #[arg(required_unless_present = "list", help = "Branch to replay")]
        branch: Option<String>,

        /// List available log sessions and branches.
        #[arg(long, help = "List available log sessions and branches")]
        list: bool,

        /// Display with ANSI colors via less -R.
        #[arg(long, help = "Display with colors via less -R")]
        color: bool,

        /// Session name to replay from (defaults to most recent).
        #[arg(long, help = "Session to replay from (defaults to most recent)")]
        session: Option<String>,
    },

    /// Report manually-approved command patterns for a session
    #[command(
        about = "Report manually-approved command patterns for a session",
        long_about = "Lists the command patterns you manually approved during a session — the \
                      prompts the auto-approve preset did NOT match — sorted by how often each \
                      was approved. Each row carries a SUGGEST hint for where the pattern might \
                      be promoted: the project-local allowlist (project-specific scripts/paths) \
                      or the bundled dev-allowlist preset (general commands like `make <target>`). \
                      The suggestion is a hint, not a rule.\n\n\
                      Reads `.git-paw/sessions/<session>.manual-approvals.jsonl`. Defaults to the \
                      active session; pass --session to target another. Recording is controlled by \
                      `[supervisor] manual_approvals_log` (default on).\n\n\
                      Examples:\n  \
                      git paw approvals\n  \
                      git paw approvals --json\n  \
                      git paw approvals --session paw-myproject\n  \
                      git paw approvals --limit 5"
    )]
    Approvals {
        /// Session to read approvals from (defaults to the active session).
        #[arg(long, help = "Session to read from (defaults to the active session)")]
        session: Option<String>,

        /// Cap the output to the top N patterns by count.
        #[arg(long, help = "Show at most N patterns (top N by count)")]
        limit: Option<usize>,

        /// Emit machine-readable JSON instead of the text table.
        #[arg(long, help = "Emit machine-readable JSON")]
        json: bool,
    },

    /// Run a read-only Model Context Protocol (MCP) server over stdio
    #[command(
        about = "Run a read-only Model Context Protocol (MCP) server over stdio",
        long_about = "Starts a Model Context Protocol (MCP) server on stdin/stdout so any \
                      MCP-aware client (Claude Desktop, Cursor, ChatGPT Desktop, Windsurf, \
                      VS Code MCP) can query this repository's read-only state: agent \
                      coordination intents/conflicts, governance docs, specs and tasks, \
                      session status and learnings, agent skills, git context, source \
                      browsing (list_files, read_file, search_code over the local working \
                      tree), and the repository's own README and documentation.\n\n\
                      The server is client-spawned and one-shot: the MCP client owns the \
                      process lifecycle and the server exits when stdin is closed. It runs \
                      standalone — no tmux session, broker, or supervisor is required. When a \
                      data source is unavailable (no broker, no session, no governance config) \
                      tools return well-formed empty/null results rather than errors.\n\n\
                      Repository resolution: --repo wins; otherwise the nearest ancestor of the \
                      current directory containing .git is used (worktrees resolve to their own \
                      root). Claude Desktop spawns servers from its app-support directory, so it \
                      MUST pass --repo with an absolute path.\n\n\
                      Claude Desktop config (claude_desktop_config.json):\n\n  \
                      {\n    \
                        \"mcpServers\": {\n      \
                          \"git-paw\": {\n        \
                            \"command\": \"git\",\n        \
                            \"args\": [\"paw\", \"mcp\", \"--repo\", \"/absolute/path/to/your/repo\"]\n      \
                          }\n    \
                        }\n  \
                      }\n\n\
                      Examples:\n  \
                      git paw mcp\n  \
                      git paw mcp --repo /path/to/repo\n  \
                      git paw mcp --repo /path/to/repo --log-file /tmp/git-paw-mcp.log"
    )]
    Mcp {
        /// Repository to operate against, overriding current-directory
        /// discovery. Required for clients that spawn from a fixed directory
        /// (notably Claude Desktop).
        #[arg(
            long,
            value_name = "PATH",
            help = "Repository to serve (overrides current-directory discovery; required for Claude Desktop)"
        )]
        repo: Option<PathBuf>,

        /// Write tracing output to this file in addition to stderr (off by
        /// default). Stdout always stays reserved for the JSON-RPC stream.
        #[arg(
            long,
            value_name = "PATH",
            help = "Also write tracing output to this file (stderr is always used)"
        )]
        log_file: Option<PathBuf>,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    /// Helper: parse args as if running `git-paw <args>`.
    fn parse(args: &[&str]) -> Cli {
        let mut full = vec!["git-paw"];
        full.extend(args);
        Cli::try_parse_from(full).expect("failed to parse")
    }

    // -- Default subcommand --

    #[test]
    fn no_args_defaults_to_none_command() {
        let cli = parse(&[]);
        assert!(
            cli.command.is_none(),
            "no args should yield None (handled as Start in main)"
        );
    }

    // -- Start subcommand --

    #[test]
    fn start_with_no_flags() {
        let cli = parse(&["start"]);
        match cli.command.unwrap() {
            Command::Start {
                cli,
                branches,
                from_all_specs,
                specs,
                specs_format,
                dry_run,
                preset,
                supervisor,
                no_supervisor,
                force,
                no_rebase,
            } => {
                assert!(cli.is_none());
                assert!(branches.is_none());
                assert!(!from_all_specs);
                assert!(specs.is_none());
                assert!(specs_format.is_none());
                assert!(!dry_run);
                assert!(preset.is_none());
                assert!(!supervisor);
                assert!(!no_supervisor);
                assert!(!force);
                assert!(!no_rebase);
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_cli_flag() {
        let cli = parse(&["start", "--cli", "claude"]);
        match cli.command.unwrap() {
            Command::Start { cli, .. } => assert_eq!(cli.as_deref(), Some("claude")),
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_from_all_specs_sets_flag_and_leaves_specs_unset() {
        let cli = parse(&["start", "--from-all-specs"]);
        match cli.command.unwrap() {
            Command::Start {
                from_all_specs,
                specs,
                ..
            } => {
                assert!(from_all_specs);
                assert!(specs.is_none());
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_from_specs_alias_parses_identically_to_from_all_specs() {
        let alias_args = parse(&["start", "--from-specs"]);
        let canonical_args = parse(&["start", "--from-all-specs"]);
        match (alias_args.command.unwrap(), canonical_args.command.unwrap()) {
            (
                Command::Start {
                    from_all_specs: a_all,
                    specs: a_specs,
                    supervisor: a_sup,
                    ..
                },
                Command::Start {
                    from_all_specs: c_all,
                    specs: c_specs,
                    supervisor: c_sup,
                    ..
                },
            ) => {
                assert_eq!(a_all, c_all);
                assert_eq!(a_specs, c_specs);
                assert_eq!(a_sup, c_sup);
                assert!(a_all);
            }
            other => panic!("expected two Start variants, got {other:?}"),
        }
    }

    #[test]
    fn start_with_bare_specs_yields_empty_vec_picker_mode() {
        let cli = parse(&["start", "--specs"]);
        match cli.command.unwrap() {
            Command::Start {
                from_all_specs,
                specs,
                ..
            } => {
                assert!(!from_all_specs);
                assert_eq!(specs, Some(Vec::<String>::new()));
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_specs_single_name() {
        let cli = parse(&["start", "--specs", "add-auth"]);
        match cli.command.unwrap() {
            Command::Start { specs, .. } => {
                assert_eq!(specs, Some(vec!["add-auth".to_string()]));
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_specs_two_comma_separated_names() {
        let cli = parse(&["start", "--specs", "add-auth,fix-session"]);
        match cli.command.unwrap() {
            Command::Start { specs, .. } => {
                assert_eq!(
                    specs,
                    Some(vec!["add-auth".to_string(), "fix-session".to_string()])
                );
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_specs_three_comma_separated_names() {
        let cli = parse(&["start", "--specs", "add-auth,fix-session,add-logging"]);
        match cli.command.unwrap() {
            Command::Start { specs, .. } => {
                assert_eq!(
                    specs,
                    Some(vec![
                        "add-auth".to_string(),
                        "fix-session".to_string(),
                        "add-logging".to_string(),
                    ])
                );
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_from_all_specs_and_specs_is_rejected() {
        let result = Cli::try_parse_from([
            "git-paw",
            "start",
            "--from-all-specs",
            "--specs",
            "add-auth",
        ]);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("--from-all-specs"), "got: {err}");
        assert!(err.contains("--specs"), "got: {err}");
    }

    #[test]
    fn start_with_from_specs_alias_and_specs_is_rejected() {
        let result =
            Cli::try_parse_from(["git-paw", "start", "--from-specs", "--specs", "add-auth"]);
        assert!(result.is_err());
    }

    #[test]
    fn start_with_from_all_specs_and_supervisor_sets_both_flags() {
        let cli = parse(&["start", "--from-all-specs", "--supervisor"]);
        match cli.command.unwrap() {
            Command::Start {
                from_all_specs,
                specs,
                supervisor,
                ..
            } => {
                assert!(from_all_specs);
                assert!(supervisor);
                assert!(specs.is_none());
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_supervisor_only_leaves_spec_mode_unset() {
        let cli = parse(&["start", "--supervisor"]);
        match cli.command.unwrap() {
            Command::Start {
                from_all_specs,
                specs,
                supervisor,
                ..
            } => {
                assert!(!from_all_specs);
                assert!(specs.is_none());
                assert!(supervisor);
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_help_contains_from_all_specs_and_specs_but_not_alias() {
        let result = Cli::try_parse_from(["git-paw", "start", "--help"]);
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(
            help.contains("--from-all-specs"),
            "start --help should contain --from-all-specs; got: {help}"
        );
        assert!(
            help.contains("--specs"),
            "start --help should contain --specs; got: {help}"
        );
        assert!(
            !help.contains("--from-specs"),
            "start --help should NOT contain hidden alias --from-specs; got: {help}"
        );
    }

    #[test]
    fn start_with_branches_flag_comma_separated() {
        let cli = parse(&["start", "--branches", "feat/a,feat/b,fix/c"]);
        match cli.command.unwrap() {
            Command::Start { branches, .. } => {
                let b = branches.expect("branches should be set");
                assert_eq!(b, vec!["feat/a", "feat/b", "fix/c"]);
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_dry_run() {
        let cli = parse(&["start", "--dry-run"]);
        match cli.command.unwrap() {
            Command::Start { dry_run, .. } => assert!(dry_run),
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_preset() {
        let cli = parse(&["start", "--preset", "backend"]);
        match cli.command.unwrap() {
            Command::Start { preset, .. } => assert_eq!(preset.as_deref(), Some("backend")),
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_supervisor_flag() {
        let cli = parse(&["start", "--supervisor"]);
        match cli.command.unwrap() {
            Command::Start { supervisor, .. } => assert!(supervisor),
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_without_supervisor_defaults_false() {
        let cli = parse(&["start", "--cli", "claude"]);
        match cli.command.unwrap() {
            Command::Start { supervisor, .. } => assert!(!supervisor),
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_supervisor_and_other_flags() {
        let cli = parse(&[
            "start",
            "--supervisor",
            "--cli",
            "claude",
            "--branches",
            "feat/a,feat/b",
        ]);
        match cli.command.unwrap() {
            Command::Start {
                supervisor,
                cli,
                branches,
                ..
            } => {
                assert!(supervisor);
                assert_eq!(cli.as_deref(), Some("claude"));
                assert_eq!(branches.unwrap(), vec!["feat/a", "feat/b"]);
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    // -- --specs-format flag --

    #[test]
    fn start_with_specs_format_speckit() {
        let cli = parse(&["start", "--from-specs", "--specs-format", "speckit"]);
        match cli.command.unwrap() {
            Command::Start { specs_format, .. } => {
                assert_eq!(specs_format, Some(SpecsFormat::Speckit));
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_specs_format_openspec() {
        let cli = parse(&["start", "--from-specs", "--specs-format", "openspec"]);
        match cli.command.unwrap() {
            Command::Start { specs_format, .. } => {
                assert_eq!(specs_format, Some(SpecsFormat::Openspec));
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_specs_format_markdown() {
        let cli = parse(&["start", "--from-specs", "--specs-format", "markdown"]);
        match cli.command.unwrap() {
            Command::Start { specs_format, .. } => {
                assert_eq!(specs_format, Some(SpecsFormat::Markdown));
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_rejects_unknown_specs_format() {
        let result = Cli::try_parse_from([
            "git-paw",
            "start",
            "--from-specs",
            "--specs-format",
            "unknown-value",
        ]);
        assert!(result.is_err(), "unknown value should be rejected");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("openspec") && err.contains("markdown") && err.contains("speckit"),
            "error should list all three valid values, got: {err}"
        );
    }

    #[test]
    fn specs_format_as_str_matches_backend_names() {
        assert_eq!(SpecsFormat::Openspec.as_str(), "openspec");
        assert_eq!(SpecsFormat::Markdown.as_str(), "markdown");
        assert_eq!(SpecsFormat::Speckit.as_str(), "speckit");
    }

    #[test]
    fn start_help_shows_specs_format_flag() {
        let result = Cli::try_parse_from(["git-paw", "start", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(
            help.contains("--specs-format"),
            "start --help should contain --specs-format"
        );
    }

    #[test]
    fn start_help_shows_supervisor_flag() {
        let result = Cli::try_parse_from(["git-paw", "start", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(
            help.contains("--supervisor"),
            "start --help should contain --supervisor"
        );
    }

    // -- --no-supervisor flag --

    #[test]
    fn start_with_no_supervisor_flag() {
        let cli = parse(&["start", "--no-supervisor"]);
        match cli.command.unwrap() {
            Command::Start {
                supervisor,
                no_supervisor,
                ..
            } => {
                assert!(no_supervisor);
                assert!(!supervisor);
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_without_flags_leaves_no_supervisor_false() {
        let cli = parse(&["start"]);
        match cli.command.unwrap() {
            Command::Start {
                supervisor,
                no_supervisor,
                ..
            } => {
                assert!(!no_supervisor);
                assert!(!supervisor);
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_with_supervisor_and_no_supervisor_is_rejected() {
        let result = Cli::try_parse_from(["git-paw", "start", "--supervisor", "--no-supervisor"]);
        assert!(
            result.is_err(),
            "--supervisor + --no-supervisor must be rejected by clap"
        );
        let err = result.unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("--supervisor") && msg.contains("--no-supervisor"),
            "error should mention both flags, got: {msg}"
        );
    }

    #[test]
    fn start_with_no_supervisor_and_supervisor_reversed_is_also_rejected() {
        // clap's conflicts_with is bidirectional; order of flags shouldn't matter.
        let result = Cli::try_parse_from(["git-paw", "start", "--no-supervisor", "--supervisor"]);
        assert!(result.is_err());
    }

    #[test]
    fn start_no_supervisor_combines_with_other_flags() {
        let cli = parse(&[
            "start",
            "--no-supervisor",
            "--cli",
            "claude",
            "--branches",
            "feat/a,feat/b",
        ]);
        match cli.command.unwrap() {
            Command::Start {
                no_supervisor,
                cli,
                branches,
                ..
            } => {
                assert!(no_supervisor);
                assert_eq!(cli.as_deref(), Some("claude"));
                assert_eq!(branches.unwrap(), vec!["feat/a", "feat/b"]);
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_help_shows_no_supervisor_flag() {
        let result = Cli::try_parse_from(["git-paw", "start", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(
            help.contains("--no-supervisor"),
            "start --help should contain --no-supervisor, got: {help}"
        );
    }

    #[test]
    fn start_with_all_flags() {
        let cli = parse(&[
            "start",
            "--cli",
            "gemini",
            "--branches",
            "a,b",
            "--dry-run",
            "--preset",
            "dev",
        ]);
        match cli.command.unwrap() {
            Command::Start {
                cli,
                branches,
                dry_run,
                preset,
                ..
            } => {
                assert_eq!(cli.as_deref(), Some("gemini"));
                assert_eq!(branches.unwrap(), vec!["a", "b"]);
                assert!(dry_run);
                assert_eq!(preset.as_deref(), Some("dev"));
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    // -- Add subcommand --

    #[test]
    fn add_with_branch_only() {
        let cli = parse(&["add", "feat/new"]);
        match cli.command.unwrap() {
            Command::Add {
                branch,
                cli,
                from_spec,
            } => {
                assert_eq!(branch.as_deref(), Some("feat/new"));
                assert!(cli.is_none());
                assert!(from_spec.is_none());
            }
            other => panic!("expected Add, got {other:?}"),
        }
    }

    #[test]
    fn add_with_branch_and_cli() {
        let cli = parse(&["add", "feat/x", "--cli", "codex"]);
        match cli.command.unwrap() {
            Command::Add { branch, cli, .. } => {
                assert_eq!(branch.as_deref(), Some("feat/x"));
                assert_eq!(cli.as_deref(), Some("codex"));
            }
            other => panic!("expected Add, got {other:?}"),
        }
    }

    #[test]
    fn add_with_from_spec_only_needs_no_branch() {
        let cli = parse(&["add", "--from-spec", "add-export"]);
        match cli.command.unwrap() {
            Command::Add {
                branch, from_spec, ..
            } => {
                assert!(branch.is_none());
                assert_eq!(from_spec.as_deref(), Some("add-export"));
            }
            other => panic!("expected Add, got {other:?}"),
        }
    }

    #[test]
    fn add_with_no_branch_and_no_from_spec_is_rejected() {
        let result = Cli::try_parse_from(["git-paw", "add"]);
        assert!(
            result.is_err(),
            "add requires either a branch or --from-spec"
        );
    }

    #[test]
    fn add_with_branch_and_from_spec_is_rejected() {
        let result = Cli::try_parse_from(["git-paw", "add", "feat/x", "--from-spec", "change"]);
        assert!(
            result.is_err(),
            "branch and --from-spec are mutually exclusive"
        );
    }

    #[test]
    fn add_help_lists_flags_and_examples() {
        let result = Cli::try_parse_from(["git-paw", "add", "--help"]);
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(help.contains("--cli"), "got: {help}");
        assert!(help.contains("--from-spec"), "got: {help}");
        assert!(
            help.contains("git paw add feat/api --cli codex"),
            "add --help should include copy-pasteable examples; got: {help}"
        );
    }

    // -- Remove subcommand --

    #[test]
    fn remove_with_branch_only() {
        let cli = parse(&["remove", "feat/done"]);
        match cli.command.unwrap() {
            Command::Remove {
                branch,
                keep_worktree,
                force,
            } => {
                assert_eq!(branch, "feat/done");
                assert!(!keep_worktree);
                assert!(!force);
            }
            other => panic!("expected Remove, got {other:?}"),
        }
    }

    #[test]
    fn remove_with_keep_worktree_and_force() {
        let cli = parse(&["remove", "feat/x", "--keep-worktree", "--force"]);
        match cli.command.unwrap() {
            Command::Remove {
                keep_worktree,
                force,
                ..
            } => {
                assert!(keep_worktree);
                assert!(force);
            }
            other => panic!("expected Remove, got {other:?}"),
        }
    }

    #[test]
    fn remove_without_branch_is_rejected() {
        let result = Cli::try_parse_from(["git-paw", "remove"]);
        assert!(result.is_err(), "remove requires a branch");
    }

    #[test]
    fn remove_help_lists_flags_and_examples() {
        let result = Cli::try_parse_from(["git-paw", "remove", "--help"]);
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(help.contains("--keep-worktree"), "got: {help}");
        assert!(help.contains("--force"), "got: {help}");
        assert!(
            help.contains("git paw remove feat/wip --force"),
            "remove --help should include copy-pasteable examples; got: {help}"
        );
    }

    #[test]
    fn root_help_lists_add_and_remove() {
        let result = Cli::try_parse_from(["git-paw", "--help"]);
        let help = result.unwrap_err().to_string();
        assert!(
            help.contains("add"),
            "root help should list add; got: {help}"
        );
        assert!(
            help.contains("remove"),
            "root help should list remove; got: {help}"
        );
    }

    // -- Pause subcommand --

    #[test]
    fn pause_parses() {
        let cli = parse(&["pause"]);
        assert!(matches!(cli.command.unwrap(), Command::Pause));
    }

    #[test]
    fn pause_help_mentions_ram_tradeoff() {
        let result = Cli::try_parse_from(["git-paw", "pause", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(
            help.to_lowercase().contains("ram"),
            "pause --help should mention RAM tradeoff, got: {help}"
        );
        assert!(
            help.contains("stop"),
            "pause --help should cross-reference stop, got: {help}"
        );
    }

    #[test]
    fn pause_rejects_unknown_flags() {
        let result = Cli::try_parse_from(["git-paw", "pause", "--anything"]);
        assert!(result.is_err(), "pause should reject unknown flags");
    }

    #[test]
    fn root_help_lists_pause() {
        let result = Cli::try_parse_from(["git-paw", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(
            help.contains("pause"),
            "root --help should list pause subcommand, got: {help}"
        );
        // Quick-start block should also reference pause.
        assert!(
            help.contains("git paw pause"),
            "after_help quick-start should mention `git paw pause`"
        );
    }

    // -- Stop subcommand --

    #[test]
    fn stop_parses() {
        let cli = parse(&["stop"]);
        assert!(matches!(
            cli.command.unwrap(),
            Command::Stop { force: false }
        ));
    }

    #[test]
    fn stop_without_force() {
        let cli = parse(&["stop"]);
        match cli.command.unwrap() {
            Command::Stop { force } => assert!(!force),
            other => panic!("expected Stop, got {other:?}"),
        }
    }

    #[test]
    fn stop_with_force() {
        let cli = parse(&["stop", "--force"]);
        match cli.command.unwrap() {
            Command::Stop { force } => assert!(force),
            other => panic!("expected Stop, got {other:?}"),
        }
    }

    #[test]
    fn stop_help_mentions_pause_and_purge() {
        let result = Cli::try_parse_from(["git-paw", "stop", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(
            help.contains("pause"),
            "stop --help should reference pause, got: {help}"
        );
        assert!(
            help.contains("purge"),
            "stop --help should reference purge, got: {help}"
        );
        assert!(
            help.contains("--force"),
            "stop --help should list --force, got: {help}"
        );
    }

    // -- Purge subcommand --

    #[test]
    fn purge_without_force() {
        let cli = parse(&["purge"]);
        match cli.command.unwrap() {
            Command::Purge { force, stale } => {
                assert!(!force);
                assert!(!stale);
            }
            other => panic!("expected Purge, got {other:?}"),
        }
    }

    #[test]
    fn purge_with_force() {
        let cli = parse(&["purge", "--force"]);
        match cli.command.unwrap() {
            Command::Purge { force, stale } => {
                assert!(force);
                assert!(!stale);
            }
            other => panic!("expected Purge, got {other:?}"),
        }
    }

    #[test]
    fn purge_with_stale() {
        let cli = parse(&["purge", "--stale"]);
        match cli.command.unwrap() {
            Command::Purge { force, stale } => {
                assert!(!force);
                assert!(stale);
            }
            other => panic!("expected Purge, got {other:?}"),
        }
    }

    #[test]
    fn purge_with_stale_and_force() {
        let cli = parse(&["purge", "--stale", "--force"]);
        match cli.command.unwrap() {
            Command::Purge { force, stale } => {
                assert!(force);
                assert!(stale);
            }
            other => panic!("expected Purge, got {other:?}"),
        }
    }

    // -- Status subcommand --

    #[test]
    fn status_parses() {
        let cli = parse(&["status"]);
        match cli.command.unwrap() {
            Command::Status { json } => assert!(!json),
            other => panic!("expected Status, got {other:?}"),
        }
    }

    #[test]
    fn status_with_json() {
        let cli = parse(&["status", "--json"]);
        match cli.command.unwrap() {
            Command::Status { json } => assert!(json),
            other => panic!("expected Status, got {other:?}"),
        }
    }

    // -- List-CLIs subcommand --

    #[test]
    fn list_clis_parses() {
        let cli = parse(&["list-clis"]);
        assert!(matches!(cli.command.unwrap(), Command::ListClis));
    }

    // -- Add-CLI subcommand --

    #[test]
    fn add_cli_with_required_args() {
        let cli = parse(&["add-cli", "my-agent", "/usr/local/bin/my-agent"]);
        match cli.command.unwrap() {
            Command::AddCli {
                name,
                command,
                display_name,
            } => {
                assert_eq!(name, "my-agent");
                assert_eq!(command, "/usr/local/bin/my-agent");
                assert!(display_name.is_none());
            }
            other => panic!("expected AddCli, got {other:?}"),
        }
    }

    #[test]
    fn add_cli_with_display_name() {
        let cli = parse(&[
            "add-cli",
            "my-agent",
            "my-agent",
            "--display-name",
            "My Agent",
        ]);
        match cli.command.unwrap() {
            Command::AddCli {
                name,
                command,
                display_name,
            } => {
                assert_eq!(name, "my-agent");
                assert_eq!(command, "my-agent");
                assert_eq!(display_name.as_deref(), Some("My Agent"));
            }
            other => panic!("expected AddCli, got {other:?}"),
        }
    }

    // -- Remove-CLI subcommand --

    #[test]
    fn remove_cli_parses() {
        let cli = parse(&["remove-cli", "my-agent"]);
        match cli.command.unwrap() {
            Command::RemoveCli { name } => assert_eq!(name, "my-agent"),
            other => panic!("expected RemoveCli, got {other:?}"),
        }
    }

    // -- Help text quality --

    #[test]
    fn version_flag_is_accepted() {
        let result = Cli::try_parse_from(["git-paw", "--version"]);
        // clap returns Err(DisplayVersion) for --version, which is expected
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion);
    }

    #[test]
    fn help_flag_is_accepted() {
        let result = Cli::try_parse_from(["git-paw", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
    }

    // --- Gap #6: init_parses ---

    #[test]
    fn init_parses() {
        let cli = parse(&["init"]);
        assert!(matches!(cli.command.unwrap(), Command::Init));
    }

    // --- Gap #7: init_help_text ---

    #[test]
    fn init_help_text() {
        let result = Cli::try_parse_from(["git-paw", "init", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
    }

    #[test]
    fn unknown_subcommand_is_rejected() {
        let result = Cli::try_parse_from(["git-paw", "unknown-command"]);
        assert!(result.is_err());
    }

    #[test]
    fn add_cli_missing_required_args_is_rejected() {
        let result = Cli::try_parse_from(["git-paw", "add-cli"]);
        assert!(result.is_err());
    }

    // -- Replay subcommand --

    #[test]
    fn replay_with_branch() {
        let cli = parse(&["replay", "feat/add-auth"]);
        match cli.command.unwrap() {
            Command::Replay {
                branch,
                list,
                color,
                session,
            } => {
                assert_eq!(branch.as_deref(), Some("feat/add-auth"));
                assert!(!list);
                assert!(!color);
                assert!(session.is_none());
            }
            other => panic!("expected Replay, got {other:?}"),
        }
    }

    #[test]
    fn replay_with_list() {
        let cli = parse(&["replay", "--list"]);
        match cli.command.unwrap() {
            Command::Replay { branch, list, .. } => {
                assert!(list);
                assert!(branch.is_none());
            }
            other => panic!("expected Replay, got {other:?}"),
        }
    }

    #[test]
    fn replay_with_color() {
        let cli = parse(&["replay", "feat/add-auth", "--color"]);
        match cli.command.unwrap() {
            Command::Replay { color, .. } => assert!(color),
            other => panic!("expected Replay, got {other:?}"),
        }
    }

    #[test]
    fn replay_with_session() {
        let cli = parse(&["replay", "feat/add-auth", "--session", "paw-myproject"]);
        match cli.command.unwrap() {
            Command::Replay { session, .. } => {
                assert_eq!(session.as_deref(), Some("paw-myproject"));
            }
            other => panic!("expected Replay, got {other:?}"),
        }
    }

    #[test]
    fn replay_no_args_fails() {
        let result = Cli::try_parse_from(["git-paw", "replay"]);
        assert!(result.is_err());
    }

    #[test]
    fn replay_help_text() {
        let result = Cli::try_parse_from(["git-paw", "replay", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(help.contains("--list"));
        assert!(help.contains("--color"));
        assert!(help.contains("--session"));
    }

    #[test]
    fn help_shows_replay_subcommand() {
        let result = Cli::try_parse_from(["git-paw", "--help"]);
        let err = result.unwrap_err();
        let help = err.to_string();
        assert!(
            help.contains("replay"),
            "help should list the replay subcommand"
        );
    }

    // -- __dashboard subcommand --

    #[test]
    fn dashboard_parses() {
        let cli = parse(&["__dashboard"]);
        assert!(matches!(cli.command.unwrap(), Command::Dashboard));
    }

    // -- --no-rebase flag --

    #[test]
    fn start_with_no_rebase_flag_sets_no_rebase_true() {
        let cli = parse(&["start", "--no-rebase"]);
        match cli.command.unwrap() {
            Command::Start { no_rebase, .. } => assert!(no_rebase),
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_without_no_rebase_defaults_to_false() {
        let cli = parse(&["start"]);
        match cli.command.unwrap() {
            Command::Start { no_rebase, .. } => assert!(!no_rebase),
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_no_rebase_combines_with_supervisor() {
        let cli = parse(&["start", "--no-rebase", "--supervisor"]);
        match cli.command.unwrap() {
            Command::Start {
                no_rebase,
                supervisor,
                ..
            } => {
                assert!(no_rebase);
                assert!(supervisor);
            }
            other => panic!("expected Start, got {other:?}"),
        }
    }

    #[test]
    fn start_help_shows_no_rebase_flag() {
        let result = Cli::try_parse_from(["git-paw", "start", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(
            help.contains("--no-rebase"),
            "start --help should contain --no-rebase, got: {help}"
        );
    }

    // -- Approvals subcommand --

    #[test]
    fn approvals_parses_with_no_flags() {
        let cli = parse(&["approvals"]);
        match cli.command.unwrap() {
            Command::Approvals {
                session,
                limit,
                json,
            } => {
                assert!(session.is_none());
                assert!(limit.is_none());
                assert!(!json);
            }
            other => panic!("expected Approvals, got {other:?}"),
        }
    }

    #[test]
    fn approvals_with_session_limit_and_json() {
        let cli = parse(&[
            "approvals",
            "--session",
            "paw-other",
            "--limit",
            "5",
            "--json",
        ]);
        match cli.command.unwrap() {
            Command::Approvals {
                session,
                limit,
                json,
            } => {
                assert_eq!(session.as_deref(), Some("paw-other"));
                assert_eq!(limit, Some(5));
                assert!(json);
            }
            other => panic!("expected Approvals, got {other:?}"),
        }
    }

    #[test]
    fn approvals_rejects_non_numeric_limit() {
        let result = Cli::try_parse_from(["git-paw", "approvals", "--limit", "lots"]);
        assert!(result.is_err());
    }

    #[test]
    fn approvals_help_lists_flags_and_examples() {
        let result = Cli::try_parse_from(["git-paw", "approvals", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(help.contains("--session"), "got: {help}");
        assert!(help.contains("--limit"), "got: {help}");
        assert!(help.contains("--json"), "got: {help}");
        assert!(
            help.contains("git paw approvals --json"),
            "help should include examples, got: {help}"
        );
    }

    #[test]
    fn help_shows_approvals_subcommand() {
        let result = Cli::try_parse_from(["git-paw", "--help"]);
        let err = result.unwrap_err();
        let help = err.to_string();
        assert!(
            help.contains("approvals"),
            "root help should list approvals subcommand, got: {help}"
        );
    }

    // -- Mcp subcommand --

    #[test]
    fn mcp_parses_with_no_flags() {
        let cli = parse(&["mcp"]);
        match cli.command.unwrap() {
            Command::Mcp { repo, log_file } => {
                assert!(repo.is_none());
                assert!(log_file.is_none());
            }
            other => panic!("expected Mcp, got {other:?}"),
        }
    }

    #[test]
    fn mcp_parses_with_repo() {
        let cli = parse(&["mcp", "--repo", "/path/to/repo"]);
        match cli.command.unwrap() {
            Command::Mcp { repo, .. } => {
                assert_eq!(repo.as_deref(), Some(std::path::Path::new("/path/to/repo")));
            }
            other => panic!("expected Mcp, got {other:?}"),
        }
    }

    #[test]
    fn mcp_parses_with_repo_and_log_file() {
        let cli = parse(&["mcp", "--repo", "/r", "--log-file", "/tmp/mcp.log"]);
        match cli.command.unwrap() {
            Command::Mcp { repo, log_file } => {
                assert_eq!(repo.as_deref(), Some(std::path::Path::new("/r")));
                assert_eq!(
                    log_file.as_deref(),
                    Some(std::path::Path::new("/tmp/mcp.log"))
                );
            }
            other => panic!("expected Mcp, got {other:?}"),
        }
    }

    #[test]
    fn mcp_rejects_daemon_and_http_flags() {
        // v0.7.0 ships stdio only — no --port / --host / --daemon / start / stop / status.
        for bad in [
            vec!["mcp", "--port", "9119"],
            vec!["mcp", "--host", "127.0.0.1"],
            vec!["mcp", "--daemon"],
            vec!["mcp", "start"],
            vec!["mcp", "stop"],
            vec!["mcp", "status"],
        ] {
            let mut full = vec!["git-paw"];
            full.extend(bad.iter().copied());
            assert!(
                Cli::try_parse_from(&full).is_err(),
                "mcp should reject {bad:?} in v0.7.0"
            );
        }
    }

    #[test]
    fn mcp_help_describes_supported_flags_and_config_snippet() {
        let result = Cli::try_parse_from(["git-paw", "mcp", "--help"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::DisplayHelp);
        let help = err.to_string();
        assert!(
            help.contains("--repo"),
            "mcp --help should list --repo; got: {help}"
        );
        assert!(
            help.contains("--log-file"),
            "mcp --help should list --log-file; got: {help}"
        );
        assert!(
            help.contains("mcpServers"),
            "mcp --help should include a copy-pasteable Claude Desktop config snippet; got: {help}"
        );
        for forbidden in ["--port", "--host", "--daemon"] {
            assert!(
                !help.contains(forbidden),
                "mcp --help must not advertise {forbidden}; got: {help}"
            );
        }
    }

    #[test]
    fn help_shows_mcp_subcommand() {
        let result = Cli::try_parse_from(["git-paw", "--help"]);
        let err = result.unwrap_err();
        let help = err.to_string();
        assert!(
            help.contains("mcp"),
            "root help should list the mcp subcommand, got: {help}"
        );
    }

    #[test]
    fn dashboard_does_not_appear_in_help() {
        let result = Cli::try_parse_from(["git-paw", "--help"]);
        let err = result.unwrap_err();
        let help = err.to_string();
        assert!(
            !help.contains("__dashboard"),
            "hidden __dashboard subcommand should not appear in help output"
        );
    }
}