ccswarm 0.9.0

AI Agent Workflow DevOps toolchain complementing Claude Code Agent Teams
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
//! CLI module for ccswarm with clippy exceptions for complex conditional patterns

#![allow(clippy::collapsible_else_if)]
#![allow(clippy::get_first)]

mod command_registry;
mod commands;

mod error_help;
mod output;
mod progress;
mod quickstart_simple;

pub(crate) mod handlers;

use output::{OutputFormatter, create_formatter};
pub use progress::{ProcessTracker, ProgressStyle, ProgressTracker, StatusLine};

use anyhow::{Context, Result, anyhow};
use clap::{Parser, Subcommand};
use colored::Colorize;
use std::io::Write;
use std::path::{Path, PathBuf};
use tracing::{info, warn};

use crate::agent::{Priority, Task, TaskType};
use crate::config::CcswarmConfig;

/// ccswarm - Claude Code integrated multi-agent system
#[derive(Parser)]
#[command(name = "ccswarm")]
#[command(about = "Claude Code multi-agent orchestration system")]
#[command(
    long_about = "ccswarm — turn tasks into PR-ready diffs with quality gates.\n\n\
    One task in, one quality-gated change out: plan → implement → review → fix,\n\
    reproducibly. Provider-agnostic (Claude Code, Codex, GitHub Copilot CLI).\n\n\
    Primary flow:\n  \
      ccswarm                                  # interactive task entry\n  \
      ccswarm pipeline --task \"...\"            # single-shot run\n  \
      ccswarm queue add \"...\"; ccswarm queue drain  # batch\n\n\
    Inspection:\n  \
      ccswarm doctor           Environment and provider CLI checks\n  \
      ccswarm runs list        Past pipeline runs\n  \
      ccswarm tail             Follow the current run's event stream\n  \
      ccswarm cost <run-id>    Duration + token breakdown"
)]
#[command(version = env!("CARGO_PKG_VERSION"))]
pub struct Cli {
    /// Configuration file path
    #[arg(short, long, default_value = "ccswarm.json")]
    pub config: PathBuf,

    /// Repository path
    #[arg(short, long, default_value = ".")]
    pub repo: PathBuf,

    /// Verbose output
    #[arg(short, long)]
    pub verbose: bool,

    /// JSON output format
    #[arg(long)]
    pub json: bool,

    /// Automatically fix errors when possible
    #[arg(long, global = true)]
    pub fix: bool,

    /// Default provider for stages that don't pin one in flow YAML
    /// (claude | codex | copilot). Overrides CCSWARM_PROVIDER.
    #[arg(long, global = true)]
    pub provider: Option<String>,

    /// Log format: text (default), ndjson
    #[arg(long, default_value = "text")]
    pub log_format: String,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Initialize a new ccswarm project
    #[command(
        long_about = "Initialize a new ccswarm project in the current directory.\n\n\
        Creates ccswarm.json configuration and sets up agent worktrees.\n\n\
        Examples:\n  \
          ccswarm init --name MyApp\n  \
          ccswarm init --name MyApp --agents frontend,backend,qa"
    )]
    Init {
        /// Project name
        #[arg(short, long)]
        name: String,

        /// Repository URL
        #[arg(short, long)]
        repo_url: Option<String>,

        /// Agent configurations to create
        #[arg(long, value_delimiter = ',')]
        agents: Vec<String>,
    },

    /// Task management commands
    #[command(
        long_about = "Create, list, execute, merge, retry, and delete tasks.\n\n\
        Tasks are the primary unit of work in ccswarm. Each task is analyzed by the\n\
        Master Claude orchestrator and delegated to the appropriate specialist agent.\n\n\
        Examples:\n  \
          ccswarm task execute \"Fix login bug\"\n  \
          ccswarm task list --branches\n  \
          ccswarm task merge <id>"
    )]
    Task {
        #[command(subcommand)]
        action: TaskAction,
    },

    /// List agents and their configurations
    Agents {
        /// Show inactive agents
        #[arg(long)]
        all: bool,
    },

    /// Generate .claude/agents/*.md from facets or validate existing definitions
    #[command(name = "agent-gen")]
    AgentGen {
        #[command(subcommand)]
        action: AgentGenAction,
    },

    /// Manage Git worktrees
    Worktree {
        #[command(subcommand)]
        action: WorktreeAction,
    },

    /// Show logs
    Logs {
        /// Follow logs
        #[arg(short, long)]
        follow: bool,

        /// Specific agent
        #[arg(short, long)]
        agent: Option<String>,

        /// Number of lines to show
        #[arg(short, long, default_value = "100")]
        lines: usize,
    },

    /// Generate configuration template
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },

    /// Interactive task creation and execution with AI-assisted clarification
    Interactive {
        /// Interaction mode: assistant, persona, quiet, passthrough
        #[arg(short, long, default_value = "assistant")]
        mode: String,

        /// Flow to use for execution (e.g., "default")
        #[arg(short, long)]
        flow: Option<String>,
    },

    /// Execute a task through a flow pipeline
    #[command(
        long_about = "Execute a task through a flow-based workflow pipeline.\n\n\
        Flows define multi-step agent workflows (stages). The pipeline runner\n\
        executes each stage sequentially, passing context between steps.\n\n\
        Examples:\n  \
          ccswarm pipeline --task \"Fix README typo\" --flow default\n  \
          ccswarm pipeline --task \"Add tests\" --output-format json --verbose"
    )]
    Pipeline {
        /// Task description to execute
        #[arg(short, long)]
        task: String,

        /// Flow to use (default: "default")
        #[arg(short, long, default_value = "default")]
        flow: String,

        /// Output format: text, json, markdown
        #[arg(short, long, default_value = "text")]
        output_format: String,

        /// Timeout in seconds
        #[arg(long, default_value = "600")]
        timeout: u64,

        /// Verbose output with execution details
        #[arg(short, long)]
        verbose: bool,

        /// Write output to file
        #[arg(short = 'O', long)]
        output_file: Option<PathBuf>,

        /// Continue from a previous run (reuse Claude Code session)
        #[arg(long, name = "continue")]
        continue_from: Option<String>,

        /// Execute in isolated git worktree
        #[arg(long)]
        isolate: bool,

        /// Budget limit in USD per stage
        #[arg(long)]
        budget: Option<f64>,

        /// Cumulative input+output token cap across the whole run.
        /// Aborts the flow after the stage that crosses the threshold.
        /// Provider-agnostic (works for claude and codex).
        #[arg(long)]
        run_budget_tokens: Option<u64>,

        /// Model override for all stages
        #[arg(long, name = "model")]
        model_override: Option<String>,

        /// Auto-commit changes after successful execution
        #[arg(long)]
        auto_commit: bool,

        /// Create GitHub PR after successful execution (requires gh cli)
        #[arg(long)]
        create_pr: bool,

        /// Print the composed prompt for each stage and exit without spawning the
        /// provider CLI. Useful for reviewing what ccswarm would send before paying
        /// for the round-trip.
        #[arg(long)]
        dry_run: bool,
    },

    /// Check system health and diagnose issues
    #[command(long_about = "Diagnose and fix common ccswarm issues.\n\n\
        Checks Git setup, Claude Code CLI availability, API key configuration,\n\
        worktree health, and configuration file validity.\n\n\
        Examples:\n  \
          ccswarm doctor\n  \
          ccswarm doctor --fix\n  \
          ccswarm doctor --check-api")]
    Doctor {
        /// Run fixes for common issues
        #[arg(short, long)]
        fix: bool,

        /// Diagnose specific error code
        #[arg(long)]
        error: Option<String>,

        /// Check API connectivity
        #[arg(long)]
        check_api: bool,
    },

    /// Quick start with one command - streamlined setup and initialization
    Quickstart {
        /// Project name (default: infers from directory)
        #[arg(short, long)]
        name: Option<String>,

        /// Skip interactive prompts and use defaults
        #[arg(long)]
        no_prompt: bool,

        /// Enable all agents (frontend, backend, devops, qa)
        #[arg(long)]
        all_agents: bool,

        /// Run initial tests after setup
        #[arg(long)]
        with_tests: bool,
    },

    /// Manage workflow flows (list, eject, inspect)
    #[command(
        name = "flow",
        long_about = "Manage workflow flows for agent task execution.\n\n\
        Flows are YAML-defined workflow templates that specify stages (steps),\n\
        personas, policies, and output contracts.\n\n\
        Examples:\n  \
          ccswarm flow list\n  \
          ccswarm flow eject default\n  \
          ccswarm flow inspect default"
    )]
    Flow {
        #[command(subcommand)]
        action: FlowAction,
    },

    /// Manage external flow packages (repertoire)
    #[command(
        long_about = "Manage external flow packages from Git repositories.\n\n\
        Repertoire packages are collections of workflow flows that can be installed\n\
        from any Git repository and used alongside builtin flows.\n\n\
        Examples:\n  \
          ccswarm repertoire add https://github.com/user/my-flows\n  \
          ccswarm repertoire list\n  \
          ccswarm repertoire remove my-flows"
    )]
    Repertoire {
        #[command(subcommand)]
        action: RepertoireAction,
    },

    /// Experimental / research commands (sangha, extend, evolution, search)
    #[command(long_about = "Experimental features grouped under `lab`:\n  \
          ccswarm lab sangha propose ...      Collective voting on proposals\n  \
          ccswarm lab extend propose ...      Agent self-extension tracking\n  \
          ccswarm lab evolution report        Agent performance analytics\n  \
          ccswarm lab search docs \"...\"       Ripgrep over docs/ and source\n\n\
        These sit below the primary flow (task / pipeline / queue / runs). They exist for \
        research and may change without notice.")]
    Lab {
        #[command(subcommand)]
        action: LabAction,
    },

    /// Test harness to execute predefined scenarios and verify outcomes
    #[command(
        long_about = "Run harness scenarios to validate workflows end-to-end.\n\n\
        Scenarios are YAML files under .ccswarm/harness/ describing task, flow, and assertions.\n\n\
        Examples:\n  \
          ccswarm harness run\n  \
          ccswarm harness run --scenario .ccswarm/harness/add-login.yaml --report report.json --format json\n  \
          ccswarm harness list\n  \
          ccswarm harness plan\n  \
          ccswarm harness diff --baseline baseline.json\n  \
          ccswarm harness approve --report report.json --baseline baseline.json"
    )]
    Harness {
        #[command(subcommand)]
        action: HarnessAction,
    },

    /// Human-in-the-loop approval workflow
    #[command(long_about = "Approve or reject gated operations.\n\n\
        Examples:\n  \
          ccswarm approve plan --id run-abc123\n  \
          ccswarm approve deploy --id task-456 --reject --reason \"needs more tests\"\n  \
          ccswarm approve list --status pending")]
    Approve {
        #[command(subcommand)]
        action: ApproveAction,
    },

    /// Session management - list, inspect, and manage pipeline sessions
    #[command(
        long_about = "Browse and manage pipeline sessions stored in .ccswarm/runs/.\n\n\
        Sessions are created automatically when running pipelines. Each session\n\
        records events as NDJSON and produces a summary on completion.\n\n\
        Examples:\n  \
          ccswarm session list\n  \
          ccswarm session list --all\n  \
          ccswarm session view <session-id>"
    )]
    Session {
        #[command(subcommand)]
        action: SessionAction,
    },

    /// View past pipeline runs recorded in .ccswarm/runs/
    #[command(
        long_about = "Browse pipeline run history stored in .ccswarm/runs/.\n\n\
        Each run directory contains events.ndjson and summary.json produced\n\
        by the pipeline runner.\n\n\
        Examples:\n  \
          ccswarm run list\n  \
          ccswarm run view <run-id>"
    )]
    Run {
        #[command(subcommand)]
        action: RunAction,
    },

    /// List all registered facets (personas, policies, knowledge)
    #[command(
        long_about = "Show built-in and project-local facets available to flows.\n\n\
        Examples:\n  \
          ccswarm facets\n  \
          ccswarm facets personas\n  \
          ccswarm facets policies --detailed"
    )]
    Facets {
        /// Facet type filter: personas | policies | knowledge | all (default)
        #[arg(default_value = "all")]
        kind: String,

        /// Show description/role inline
        #[arg(short, long)]
        detailed: bool,
    },

    /// Queue tasks and drain them through the pipeline in batch
    #[command(
        long_about = "Accumulate tasks in .ccswarm/queue.yaml, then process them all.\n\n\
        Examples:\n  \
          ccswarm queue add \"Add login form\"\n  \
          ccswarm queue add --from-issue 42\n  \
          ccswarm queue list\n  \
          ccswarm queue drain --timeout 600"
    )]
    Queue {
        #[command(subcommand)]
        action: QueueAction,
    },

    /// Fully autonomous mode — no y/n prompts, auto-commit, auto-PR
    #[command(
        long_about = "Self-driving loop: pull tasks → pipeline → auto-fix → auto-commit → auto-PR → repeat.\n\n\
        All interactive prompts are suppressed. Use `--watch` to keep polling the queue \
        for new tasks; otherwise stops when the queue drains.\n\n\
        Safety: aborts on exceeded iteration count, first hard failure if --stop-on-error, \
        or exceeded wall-clock budget.\n\n\
        Examples:\n  \
          ccswarm auto                          # drain queue once, auto-everything\n  \
          ccswarm auto --task \"Add X\"           # single task, no queue needed\n  \
          ccswarm auto --watch --poll-secs 30   # daemon-like: keep running\n  \
          ccswarm auto --max-iterations 5 --stop-on-error"
    )]
    Auto {
        /// Single task to execute (bypass the queue)
        #[arg(short, long)]
        task: Option<String>,

        /// Flow to use (default: "default")
        #[arg(short, long, default_value = "default")]
        flow: String,

        /// Keep polling the queue for new tasks even after it empties
        #[arg(long)]
        watch: bool,

        /// Poll interval in seconds when --watch is set
        #[arg(long, default_value_t = 30)]
        poll_secs: u64,

        /// Maximum tasks to process in one invocation (0 = unlimited)
        #[arg(long, default_value_t = 0)]
        max_iterations: usize,

        /// Wall-clock budget in seconds for the whole session (0 = unlimited)
        #[arg(long, default_value_t = 0)]
        wall_budget_secs: u64,

        /// Abort the loop on the first task that fails
        #[arg(long)]
        stop_on_error: bool,

        /// Per-task timeout in seconds
        #[arg(long, default_value_t = 600)]
        timeout: u64,

        /// Create a GitHub PR after each successful task (requires gh cli)
        #[arg(long)]
        create_pr: bool,

        /// Pause before each commit until `ccswarm approve commit --id <run-id>`
        #[arg(long)]
        require_approval: bool,

        /// Seconds to wait for a commit approval before failing the task
        #[arg(long, default_value_t = 600)]
        approval_timeout: u64,
    },

    /// Revert-advisory for a past run (shows git commits since run started)
    #[command(
        long_about = "Inspect a past run and show the git commits that may need reverting.\n\n\
        This command is intentionally advisory: it never rewrites history on its own.\n\
        Copy the suggested `git revert` commands and run them yourself."
    )]
    Undo {
        /// Run ID (default: most recent)
        run_id: Option<String>,
    },

    /// Replay a past run: re-execute the recorded task through the pipeline
    #[command(
        long_about = "Extract the task from a past run's summary.json and re-run it.\n\n\
        Examples:\n  \
          ccswarm replay <run-id>\n  \
          ccswarm replay <run-id> --flow review-fix"
    )]
    Replay {
        /// Run ID (default: most recent)
        run_id: Option<String>,

        /// Override the flow used for replay (default: same flow as original)
        #[arg(short, long)]
        flow: Option<String>,

        /// Timeout in seconds
        #[arg(long, default_value = "600")]
        timeout: u64,
    },

    /// Show token / duration breakdown for a past run
    #[command(
        long_about = "Aggregate per-stage and per-agent metrics from events.ndjson.\n\n\
        Examples:\n  \
          ccswarm cost\n  \
          ccswarm cost <run-id>"
    )]
    Cost {
        /// Run ID (default: most recent)
        run_id: Option<String>,
    },

    /// Tail a pipeline run's event stream (live when still running)
    #[command(
        long_about = "Follow the NDJSON event log for a run with pretty formatting.\n\n\
        Examples:\n  \
          ccswarm tail\n  \
          ccswarm tail <run-id>\n  \
          ccswarm tail <run-id> --no-follow"
    )]
    Tail {
        /// Run ID (default: most recent run in .ccswarm/runs/)
        run_id: Option<String>,

        /// Do not follow new events; print existing log and exit
        #[arg(long)]
        no_follow: bool,
    },

    /// Create a new project and run pipeline in one command
    #[command(
        long_about = "Scaffold a new project: create directory, git init, run pipeline.\n\n\
        Examples:\n  \
          ccswarm scaffold --dir /tmp/myapp --task \"Create a todo app\"\n  \
          ccswarm scaffold --dir ./myapp --task \"Build a REST API\" --flow quick"
    )]
    Scaffold {
        /// Directory to create
        #[arg(short, long)]
        dir: PathBuf,

        /// Task description
        #[arg(short, long)]
        task: String,

        /// Flow to use (default: "default")
        #[arg(short, long, default_value = "default")]
        flow: String,

        /// Timeout in seconds
        #[arg(long, default_value = "600")]
        timeout: u64,
    },
}

#[derive(Subcommand)]
pub enum RepertoireAction {
    /// Install a flow package from a Git repository
    Add {
        /// Git URL of the flow package
        url: String,
    },

    /// List installed flow packages
    List,

    /// Remove an installed flow package
    Remove {
        /// Package name to remove
        name: String,
    },
}

#[derive(Subcommand)]
pub enum LabAction {
    /// Collective voting on proposals
    Sangha {
        #[command(subcommand)]
        action: SanghaAction,
    },
    /// Agent self-extension tracking
    Extend {
        #[command(subcommand)]
        action: ExtendAction,
    },
    /// Agent performance analytics
    Evolution {
        #[command(subcommand)]
        action: EvolutionAction,
    },
    /// Ripgrep over docs/ and source
    Search {
        #[command(subcommand)]
        action: SearchAction,
    },
}

#[derive(Subcommand)]
pub enum SanghaAction {
    /// Create a proposal for collective voting
    Propose {
        #[arg(short, long)]
        title: String,
        #[arg(short, long)]
        description: String,
        /// feature | refactor | policy | tooling
        #[arg(long, default_value = "feature")]
        proposal_type: String,
    },
    /// Vote on a proposal
    Vote {
        /// Proposal ID
        id: String,
        /// Approve (omit to reject)
        #[arg(long)]
        approve: bool,
        #[arg(short, long)]
        reason: Option<String>,
    },
    /// List proposals
    List {
        /// Filter: open | accepted | rejected
        #[arg(short, long)]
        status: Option<String>,
    },
    /// Show proposal details and vote tally
    Status {
        /// Proposal ID
        id: String,
    },
}

#[derive(Subcommand)]
pub enum ExtendAction {
    /// Propose a capability extension
    Propose {
        #[arg(short, long)]
        title: String,
        #[arg(short, long)]
        description: String,
        /// Target agent: frontend | backend | devops | qa | all
        #[arg(short, long, default_value = "all")]
        agent: String,
        /// Also create a Sangha proposal for consensus approval
        #[arg(long)]
        auto_sangha: bool,
    },
    /// Generate an extension proposal from local workflow context
    AutoPropose {
        /// Target agent: frontend | backend | devops | qa | all
        #[arg(short, long, default_value = "all")]
        agent: String,
        /// Optional reason or observed gap to include in the proposal
        #[arg(short, long)]
        reason: Option<String>,
        /// Do not create a linked Sangha proposal
        #[arg(long = "no-auto-sangha", action = clap::ArgAction::SetFalse, default_value_t = true)]
        auto_sangha: bool,
    },
    /// List extensions
    List {
        /// Filter: proposed | approved | active | deprecated
        #[arg(short, long)]
        status: Option<String>,
    },
    /// Show extension details
    Status {
        /// Extension ID
        id: String,
    },
    /// Show recent extension history
    History {
        /// Max entries to show
        #[arg(default_value = "20")]
        limit: usize,
    },
}

#[derive(Subcommand)]
pub enum SearchAction {
    /// Search documentation files
    Docs {
        /// Search query
        query: String,
        #[arg(short, long, default_value = "10")]
        limit: usize,
    },
    /// Search source code
    Code {
        /// Search query
        query: String,
        /// File glob filter (e.g. "*.rs")
        #[arg(short, long)]
        glob: Option<String>,
        #[arg(short, long, default_value = "10")]
        limit: usize,
    },
}

#[derive(Subcommand)]
pub enum EvolutionAction {
    /// Show agent performance metrics from coordination/agent-status/
    Metrics {
        #[arg(short, long)]
        agent: Option<String>,
        /// text | json
        #[arg(short, long, default_value = "text")]
        format: String,
    },
    /// Analyze task success/failure patterns from coordination/task-queue/
    Patterns {
        #[arg(short, long)]
        agent: Option<String>,
        #[arg(short, long, default_value = "50")]
        limit: usize,
    },
    /// Generate evolution report
    Report {
        /// text | json | markdown
        #[arg(short, long, default_value = "text")]
        format: String,
    },
}

#[derive(Subcommand)]
pub enum ApproveAction {
    /// Approve or reject a plan gate
    Plan {
        #[arg(long)]
        id: String,
        #[arg(long)]
        reject: bool,
        #[arg(long)]
        reason: Option<String>,
    },
    /// Approve or reject a risky edit gate
    RiskyEdit {
        #[arg(long)]
        id: String,
        #[arg(long)]
        reject: bool,
        #[arg(long)]
        reason: Option<String>,
    },
    /// Approve or reject a deploy gate
    Deploy {
        #[arg(long)]
        id: String,
        #[arg(long)]
        reject: bool,
        #[arg(long)]
        reason: Option<String>,
    },
    /// Approve or reject a merge gate
    Merge {
        #[arg(long)]
        id: String,
        #[arg(long)]
        reject: bool,
        #[arg(long)]
        reason: Option<String>,
    },
    /// Approve or reject a pending commit gate (unattended runs)
    Commit {
        #[arg(long)]
        id: String,
        #[arg(long)]
        reject: bool,
        #[arg(long)]
        reason: Option<String>,
    },
    /// List approval requests
    List {
        #[arg(short, long)]
        status: Option<String>,
    },
}

#[derive(Subcommand)]
pub enum QueueAction {
    /// Append a task to the queue
    Add {
        /// Task description (ignored if --from-issue or --file is given).
        /// Pass `-` to read the task body from stdin.
        #[arg(default_value = "")]
        task: String,
        /// Load task body from a tracker issue
        #[arg(long, value_name = "ISSUE")]
        from_issue: Option<String>,
        /// Load task body from a file (convenient for long prompts)
        #[arg(long, value_name = "PATH")]
        file: Option<std::path::PathBuf>,
        /// Flow to run when this task is drained (default: "default")
        #[arg(short, long)]
        flow: Option<String>,
    },
    /// Show queued tasks
    List,
    /// Clear pending tasks from the queue
    Clear,
    /// Manually release a claimed task
    Release {
        /// Queue task ID to release
        id: String,
        /// Release reason recorded in the queue file
        #[arg(long)]
        reason: String,
    },
    /// Execute all queued tasks through the pipeline.
    /// `drain` runs unattended by default — all commit/PR prompts are suppressed so
    /// the queue fully empties without user input. Pass `--interactive` to restore
    /// the old per-task y/n prompts.
    Drain {
        /// Flow override; by default each task uses its per-task flow or "default"
        #[arg(short, long)]
        flow: Option<String>,
        /// Timeout per task in seconds
        #[arg(long, default_value = "600")]
        timeout: u64,
        /// Stop on the first failure (default: continue)
        #[arg(long)]
        fail_fast: bool,
        /// Restore per-task y/n prompts (default: off, unattended)
        #[arg(long)]
        interactive: bool,
        /// Also create a GitHub PR for each successful task (requires `gh` CLI)
        #[arg(long)]
        create_pr: bool,
        /// Run queue reconciliation and exit without dispatching new work
        #[arg(long)]
        reconcile_only: bool,
        /// Pause before each commit until `ccswarm approve commit --id <run-id>`
        #[arg(long)]
        require_approval: bool,
        /// Seconds to wait for a commit approval before failing the task
        #[arg(long, default_value_t = 600)]
        approval_timeout: u64,
    },
}

#[derive(Subcommand)]
pub enum RunAction {
    /// List past pipeline runs (sorted by date, newest first)
    List,
    /// View details and events for a specific run
    View {
        /// Run ID to inspect
        id: String,
    },
    /// Compare the timeline of two runs
    Diff {
        /// Baseline run ID
        a: String,
        /// Candidate run ID
        b: String,
    },
}

#[derive(Subcommand)]
pub enum AgentGenAction {
    /// Generate a .claude/agents/*.md file from facets
    Generate {
        /// Agent name (used as filename)
        name: String,
        /// Persona facet to use (e.g. "coder", "reviewer")
        #[arg(short, long)]
        persona: Option<String>,
        /// Policy facet to use (e.g. "coding", "security")
        #[arg(long)]
        policy: Option<String>,
        /// Short description for the agent
        #[arg(short, long)]
        description: Option<String>,
        /// Model to use (default: sonnet)
        #[arg(short, long, default_value = "sonnet")]
        model: String,
        /// Output directory (default: .claude/agents/)
        #[arg(short, long)]
        output: Option<PathBuf>,
    },
    /// Validate existing .claude/agents/*.md files
    Validate {
        /// Specific file to validate (default: all in .claude/agents/)
        path: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
pub enum HarnessAction {
    /// Run scenarios from a file or directory (defaults to .ccswarm/harness/)
    Run {
        /// Scenario YAML file
        #[arg(short, long)]
        scenario: Option<PathBuf>,
        /// Directory containing scenarios
        #[arg(short, long)]
        dir: Option<PathBuf>,
        /// Write report to file
        #[arg(short, long)]
        report: Option<PathBuf>,
        /// Report format (json|text|markdown)
        #[arg(short, long, default_value = "json")]
        format: String,
        /// Parallel jobs (0 or omitted = auto)
        #[arg(short = 'j', long, default_value_t = 0)]
        jobs: usize,
    },

    /// List discovered scenarios under .ccswarm/harness/
    List,

    /// Show expanded execution plan without running
    Plan {
        /// Scenario YAML file
        #[arg(short, long)]
        scenario: Option<PathBuf>,
        /// Directory containing scenarios
        #[arg(short, long)]
        dir: Option<PathBuf>,
    },

    /// Compare current results against a baseline report
    Diff {
        /// Baseline JSON file (created by harness run --report)
        #[arg(long)]
        baseline: PathBuf,
        /// Scenario YAML file (optional; if omitted, use .ccswarm/harness/)
        #[arg(short, long)]
        scenario: Option<PathBuf>,
        /// Directory containing scenarios (optional)
        #[arg(short, long)]
        dir: Option<PathBuf>,
        /// Output format (json|text|markdown)
        #[arg(short, long, default_value = "json")]
        format: String,
    },

    /// Approve current results as new baseline
    Approve {
        /// Source report JSON (current run)
        #[arg(long)]
        report: PathBuf,
        /// Destination baseline JSON
        #[arg(long)]
        baseline: PathBuf,
        /// Overwrite without prompt
        #[arg(long)]
        force: bool,
    },

    /// Create a sample harness scenario file
    Init {
        /// Output file path (default: .ccswarm/harness/sample.yaml)
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Scenario name to embed
        #[arg(short, long, default_value = "sample-task")]
        name: String,
    },
}

#[derive(Subcommand)]
pub enum FlowAction {
    /// List all available flows (builtin and custom)
    List,

    /// Eject a builtin flow to a local YAML file for customization
    Eject {
        /// Name of the flow to eject
        name: String,

        /// Output directory (default: .ccswarm/flows/)
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// Inspect a flow's structure and stages
    Inspect {
        /// Name of the flow to inspect
        name: String,
    },

    /// Check a flow YAML file for structural validity
    Check {
        /// Name of builtin/custom flow, or path to a YAML file
        target: String,
    },

    /// Scaffold a new flow YAML file
    New {
        /// Name of the new flow (used as filename)
        name: String,

        /// Template: "minimal" (1 stage) or "faceted" (plan+implement+review)
        #[arg(short, long, default_value = "minimal")]
        template: String,

        /// Output directory (default: .ccswarm/flows/)
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// Render composed prompts for each stage in a flow
    Render {
        /// Name of builtin/custom flow, or path to a YAML file
        target: String,

        /// Render only the stage with this ID
        #[arg(short, long)]
        stage: Option<String>,
    },

    /// Suggest an appropriate builtin flow for a given task description
    Suggest {
        /// Task description to classify
        task: String,
    },
}

#[derive(Subcommand)]
pub enum WorktreeAction {
    /// List all worktrees
    List,

    /// Create a new worktree
    Create {
        /// Worktree path
        path: PathBuf,

        /// Branch name
        branch: String,

        /// Create new branch
        #[arg(short, long)]
        new_branch: bool,
    },

    /// Remove a worktree
    Remove {
        /// Worktree path
        path: PathBuf,

        /// Force removal
        #[arg(short, long)]
        force: bool,
    },

    /// Prune stale worktrees
    Prune,

    /// Clean all ccswarm worktrees and branches
    Clean {
        /// Force cleanup without confirmation
        #[arg(short, long)]
        force: bool,
    },
}

#[derive(Subcommand)]
pub enum TaskAction {
    /// Add a new task to the queue
    Add {
        /// Task description (or template ID if using template)
        description: String,

        /// Task priority
        #[arg(short, long, default_value = "medium")]
        priority: String,

        /// Task type
        #[arg(short, long, default_value = "development")]
        task_type: String,

        /// Additional details
        #[arg(long)]
        details: Option<String>,

        /// Estimated duration in seconds
        #[arg(long)]
        duration: Option<u32>,

        /// Auto-assign to best agent
        #[arg(long)]
        auto_assign: bool,

        /// Use a template for task creation
        #[arg(long)]
        template: Option<String>,

        /// Template variable values (key=value)
        #[arg(long, value_delimiter = ',')]
        template_vars: Vec<String>,

        /// Interactive template variable input
        #[arg(long)]
        interactive: bool,
    },

    /// List all tasks
    List {
        /// Show all tasks including completed
        #[arg(short, long)]
        all: bool,

        /// Filter by status (pending, in_progress, completed, failed)
        #[arg(short, long)]
        status: Option<String>,

        /// Filter by agent
        #[arg(long)]
        agent: Option<String>,

        /// Show detailed information
        #[arg(short, long)]
        detailed: bool,

        /// Show worktree branch information for each task
        #[arg(long)]
        branches: bool,
    },

    /// Show task status
    Status {
        /// Task ID
        task_id: String,

        /// Show execution history
        #[arg(long)]
        history: bool,

        /// Show orchestration details
        #[arg(long)]
        orchestration: bool,
    },

    /// Cancel a task
    Cancel {
        /// Task ID
        task_id: String,

        /// Force cancellation even if in progress
        #[arg(short, long)]
        force: bool,

        /// Reason for cancellation
        #[arg(short, long)]
        reason: Option<String>,
    },

    /// Show task execution history
    History {
        /// Number of recent tasks to show
        #[arg(short, long, default_value = "20")]
        limit: usize,

        /// Filter by agent
        #[arg(short, long)]
        agent: Option<String>,

        /// Show only failed tasks
        #[arg(long)]
        failed_only: bool,
    },

    /// Execute a task immediately (bypass queue)
    Execute {
        /// Task ID or new task description
        task: String,

        /// Force execution on specific agent
        #[arg(short, long)]
        agent: Option<String>,

        /// Use orchestrator for complex execution
        #[arg(long)]
        orchestrate: bool,
    },

    /// Show task queue statistics
    Stats {
        /// Show detailed breakdown
        #[arg(short, long)]
        detailed: bool,

        /// Show performance metrics
        #[arg(long)]
        performance: bool,
    },

    /// Merge a completed task's worktree branch into main
    Merge {
        /// Task ID to merge
        task_id: String,

        /// Delete the worktree branch after merge
        #[arg(long, default_value = "true")]
        cleanup: bool,

        /// Skip confirmation prompt
        #[arg(short, long)]
        yes: bool,
    },

    /// Retry a failed task
    Retry {
        /// Task ID to retry
        task_id: String,

        /// Force retry even if task is not in failed state
        #[arg(short, long)]
        force: bool,
    },

    /// Delete a task and its associated worktree
    Delete {
        /// Task ID to delete
        task_id: String,

        /// Force deletion even if task is in progress
        #[arg(short, long)]
        force: bool,
    },
}

#[derive(Subcommand)]
pub enum ConfigAction {
    /// Generate default configuration
    Generate {
        /// Output file
        #[arg(short, long, default_value = "ccswarm.json")]
        output: PathBuf,

        /// Project template
        #[arg(short, long, default_value = "full-stack")]
        template: String,
    },

    /// Validate configuration
    Validate {
        /// Configuration file
        #[arg(short, long, default_value = "ccswarm.json")]
        file: PathBuf,
    },

    /// Show configuration details
    Show {
        /// Configuration file
        #[arg(short, long, default_value = "ccswarm.json")]
        file: PathBuf,
        /// Show a single agent configuration
        #[arg(short, long)]
        agent: Option<String>,
        /// Print raw JSON (ignored for JSON output)
        #[arg(long)]
        raw: bool,
    },
}

#[derive(Subcommand)]
pub enum SessionAction {
    /// List all sessions (pipeline runs) with metadata extracted from event logs
    List {
        /// Show all sessions including those without summary
        #[arg(short, long)]
        all: bool,
    },

    /// View details and events for a specific session
    View {
        /// Session/run ID to inspect
        id: String,
    },

    /// Create a new agent session
    Create {
        /// Agent type (frontend, backend, devops, qa)
        #[arg(short, long)]
        agent: String,

        /// Workspace path
        #[arg(short, long)]
        workspace: Option<String>,

        /// Background mode
        #[arg(short, long)]
        background: bool,
    },

    /// Pause a running session
    Pause {
        /// Session ID
        session_id: String,
    },

    /// Resume a paused session
    Resume {
        /// Session ID
        session_id: String,
    },

    /// Attach to a session
    Attach {
        /// Session ID
        session_id: String,
    },

    /// Detach from a session
    Detach {
        /// Session ID
        session_id: String,
    },

    /// Kill a session
    Kill {
        /// Session ID
        session_id: String,

        /// Force kill
        #[arg(short, long)]
        force: bool,
    },
}

#[derive(Subcommand)]
pub enum DelegateAction {
    /// Delegate a task to specific agent
    Task {
        /// Task description
        description: String,

        /// Target agent type (frontend, backend, devops, qa)
        #[arg(short, long)]
        agent: String,

        /// Task priority
        #[arg(short, long, default_value = "medium")]
        priority: String,

        /// Task type
        #[arg(short, long, default_value = "development")]
        task_type: String,

        /// Additional details
        #[arg(long)]
        details: Option<String>,

        /// Force delegation even if agent doesn't match
        #[arg(long)]
        force: bool,
    },

    /// Analyze task and suggest optimal agent
    Analyze {
        /// Task description
        description: String,

        /// Show delegation reasoning
        #[arg(short, long)]
        verbose: bool,

        /// Delegation strategy to use
        #[arg(short, long, default_value = "hybrid")]
        strategy: String,
    },

    /// Show delegation statistics
    Stats {
        /// Show detailed breakdown
        #[arg(short, long)]
        detailed: bool,

        /// Time period to analyze (hours)
        #[arg(long, default_value = "24")]
        period: u32,
    },

    /// Interactive delegation mode
    Interactive,

    /// Show configuration
    Show {
        /// Configuration file
        #[arg(short, long, default_value = "ccswarm.json")]
        file: PathBuf,
    },
}

#[derive(Subcommand)]
pub enum QualityAction {
    /// Run all quality checks through agents
    Check {
        /// Skip specific check types
        #[arg(long, value_delimiter = ',')]
        skip: Vec<String>,

        /// Run only specific check types
        #[arg(long, value_delimiter = ',')]
        only: Vec<String>,

        /// Fail fast on first error
        #[arg(long)]
        fail_fast: bool,
    },

    /// Run format checks (DevOps agent)
    Format {
        /// Automatically fix formatting issues
        #[arg(long)]
        fix: bool,
    },

    /// Run linting checks (DevOps agent)  
    Lint {
        /// Automatically fix linting issues where possible
        #[arg(long)]
        fix: bool,
    },

    /// Run test suite (QA agent)
    Test {
        /// Test filter pattern
        #[arg(short, long)]
        pattern: Option<String>,

        /// Run only unit tests
        #[arg(long)]
        unit: bool,

        /// Run only integration tests
        #[arg(long)]
        integration: bool,

        /// Run only security tests
        #[arg(long)]
        security: bool,
    },

    /// Run build verification (DevOps agent)
    Build {
        /// Build in release mode
        #[arg(long)]
        release: bool,

        /// Build all targets
        #[arg(long)]
        all_targets: bool,
    },

    /// Run security analysis (Backend agent)
    Security {
        /// Run vulnerability scan
        #[arg(long)]
        audit: bool,

        /// Check dependencies
        #[arg(long)]
        deps: bool,
    },

    /// Show quality gate status
    Status {
        /// Show detailed status for each check
        #[arg(short, long)]
        detailed: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum TemplateAction {
    /// List available templates
    List {
        /// Show all templates including disabled ones
        #[arg(short, long)]
        all: bool,

        /// Filter by category
        #[arg(short, long)]
        category: Option<String>,

        /// Filter by tags
        #[arg(short, long, value_delimiter = ',')]
        tags: Vec<String>,

        /// Search term for name or description
        #[arg(short, long)]
        search: Option<String>,

        /// Sort by popularity
        #[arg(long)]
        popular: bool,

        /// Sort by success rate
        #[arg(long)]
        quality: bool,

        /// Show detailed information
        #[arg(short, long)]
        detailed: bool,
    },

    /// Show template details
    Show {
        /// Template ID or name
        template: String,

        /// Show template source code
        #[arg(long)]
        source: bool,

        /// Show usage statistics
        #[arg(long)]
        stats: bool,
    },

    /// Create a new template
    Create {
        /// Template ID
        #[arg(short, long)]
        id: String,

        /// Template name
        #[arg(short, long)]
        name: String,

        /// Template description
        #[arg(short, long)]
        description: String,

        /// Template category
        #[arg(short, long)]
        category: String,

        /// Open editor to define template details
        #[arg(long)]
        editor: bool,

        /// Use existing template as base
        #[arg(long)]
        from: Option<String>,
    },

    /// Edit an existing template
    Edit {
        /// Template ID or name
        template: String,

        /// Open in external editor
        #[arg(long)]
        editor: bool,
    },

    /// Delete a template
    Delete {
        /// Template ID or name
        template: String,

        /// Force deletion without confirmation
        #[arg(short, long)]
        force: bool,
    },

    /// Apply a template to create a task
    Apply {
        /// Template ID or name
        template: String,

        /// Variable values (key=value)
        #[arg(short, long, value_delimiter = ',')]
        vars: Vec<String>,

        /// Interactive mode to prompt for variables
        #[arg(short, long)]
        interactive: bool,

        /// Preview the generated task without creating it
        #[arg(long)]
        preview: bool,

        /// Auto-assign to best agent
        #[arg(long)]
        auto_assign: bool,
    },

    /// Validate a template
    Validate {
        /// Template ID or name
        template: String,

        /// Show detailed validation report
        #[arg(short, long)]
        detailed: bool,

        /// Treat warnings as errors
        #[arg(long)]
        strict: bool,
    },

    /// Clone a template
    Clone {
        /// Source template ID or name
        source: String,

        /// New template ID
        #[arg(short, long)]
        id: String,

        /// New template name (optional)
        #[arg(short, long)]
        name: Option<String>,
    },

    /// Import templates from file
    Import {
        /// JSON file containing templates
        file: String,

        /// Overwrite existing templates
        #[arg(long)]
        force: bool,
    },

    /// Export templates to file
    Export {
        /// Output file path
        #[arg(short, long)]
        output: String,

        /// Export specific templates only
        #[arg(short, long, value_delimiter = ',')]
        templates: Vec<String>,

        /// Include usage statistics
        #[arg(long)]
        stats: bool,
    },

    /// Install predefined templates
    Install {
        /// Install all predefined templates
        #[arg(long)]
        all: bool,

        /// Install specific template categories
        #[arg(short, long, value_delimiter = ',')]
        categories: Vec<String>,

        /// Force reinstall existing templates
        #[arg(long)]
        force: bool,
    },

    /// Show template usage statistics
    Stats {
        /// Show global statistics
        #[arg(short, long)]
        global: bool,

        /// Show statistics for specific template
        #[arg(short, long)]
        template: Option<String>,
    },

    /// Search templates
    Search {
        /// Search query
        query: String,

        /// Limit number of results
        #[arg(short, long, default_value = "10")]
        limit: usize,

        /// Minimum quality score (0.0-1.0)
        #[arg(long)]
        min_quality: Option<f64>,
    },
}

pub struct CliRunner {
    config: CcswarmConfig,
    repo_path: PathBuf,
    json_output: bool,
    formatter: OutputFormatter,
    /// `--provider` flag: default provider for stages that don't pin one in
    /// flow YAML. Overrides the CCSWARM_PROVIDER env var.
    default_provider: Option<crate::providers::ProviderKind>,
}

impl CliRunner {
    /// Create new CLI runner
    pub async fn new(cli: &Cli) -> Result<Self> {
        // Load configuration
        let config = if cli.config.exists() {
            CcswarmConfig::from_file(cli.config.clone())
                .await
                .context("Failed to load configuration")?
        } else {
            if !cli.json {
                warn!("Configuration file not found, using defaults");
            }
            create_default_config(&cli.repo)?
        };

        let formatter = create_formatter(cli.json);

        // Fail fast on an unknown provider name rather than silently running
        // everything on the claude default.
        let default_provider = match cli.provider.as_deref() {
            Some(name) => Some(crate::providers::ProviderKind::parse(name).ok_or_else(|| {
                anyhow::anyhow!(
                    "unknown provider '{}' (expected: claude | codex | copilot)",
                    name
                )
            })?),
            None => None,
        };

        Ok(Self {
            config,
            repo_path: cli.repo.clone(),
            json_output: cli.json,
            formatter,
            default_provider,
        })
    }

    /// Run the CLI command
    pub async fn run(&self, command: &Commands) -> Result<()> {
        // Use the command registry for centralized command handling
        let registry = self::command_registry::get_command_registry();
        registry.execute(self, command).await
    }

    /// Handle scaffold command
    pub async fn handle_scaffold(
        &self,
        dir: &std::path::Path,
        task: &str,
        flow: &str,
        timeout: u64,
    ) -> Result<()> {
        handlers::scaffold::handle_scaffold(dir, task, flow, timeout, self.default_provider).await
    }

    /// Handle agent-gen subcommands
    pub async fn handle_agent_gen(&self, action: &AgentGenAction) -> Result<()> {
        match action {
            AgentGenAction::Generate {
                name,
                persona,
                policy,
                description,
                model,
                output,
            } => {
                let output_dir = output
                    .clone()
                    .unwrap_or_else(|| self.repo_path.join(".claude/agents"));
                let path = handlers::agent_gen::generate_agent_definition(
                    name,
                    persona.as_deref(),
                    policy.as_deref(),
                    description.as_deref(),
                    model,
                    &output_dir,
                )
                .await?;
                println!("Generated agent definition: {}", path.display());
                Ok(())
            }
            AgentGenAction::Validate { path } => {
                let agents_dir = self.repo_path.join(".claude/agents");
                let paths: Vec<PathBuf> = if let Some(p) = path {
                    vec![p.clone()]
                } else {
                    let mut entries = Vec::new();
                    let mut dir = tokio::fs::read_dir(&agents_dir).await?;
                    while let Some(entry) = dir.next_entry().await? {
                        let p = entry.path();
                        if p.extension().is_some_and(|ext| ext == "md") {
                            entries.push(p);
                        }
                    }
                    entries
                };

                let mut all_valid = true;
                for p in &paths {
                    let issues = handlers::agent_gen::validate_agent_definition(p).await?;
                    if issues.is_empty() {
                        println!("  {} OK", p.display());
                    } else {
                        all_valid = false;
                        println!("  {} {} issue(s):", p.display(), issues.len());
                        for issue in &issues {
                            println!("    - {}", issue);
                        }
                    }
                }
                if all_valid {
                    println!("All agent definitions are valid.");
                }
                Ok(())
            }
        }
    }
}

fn create_default_config(repo_path: &Path) -> Result<CcswarmConfig> {
    let mut agents = std::collections::HashMap::new();

    // Add common agent configurations
    agents.insert(
        "frontend".to_string(),
        crate::config::AgentConfig {
            specialization: "react_typescript".to_string(),
            worktree: "../worktrees/frontend-agent".to_string(),
            branch: "feature/frontend-ui".to_string(),
            claude_config: crate::config::ClaudeConfig::for_agent("frontend"),
            claude_md_template: "frontend_specialist".to_string(),
        },
    );

    agents.insert(
        "backend".to_string(),
        crate::config::AgentConfig {
            specialization: "node_microservices".to_string(),
            worktree: "../worktrees/backend-agent".to_string(),
            branch: "feature/backend-api".to_string(),
            claude_config: crate::config::ClaudeConfig::for_agent("backend"),
            claude_md_template: "backend_specialist".to_string(),
        },
    );

    agents.insert(
        "devops".to_string(),
        crate::config::AgentConfig {
            specialization: "aws_kubernetes".to_string(),
            worktree: "../worktrees/devops-agent".to_string(),
            branch: "feature/infrastructure".to_string(),
            claude_config: crate::config::ClaudeConfig::for_agent("devops"),
            claude_md_template: "devops_specialist".to_string(),
        },
    );

    Ok(CcswarmConfig {
        project: crate::config::ProjectConfig {
            name: "New ccswarm Project".to_string(),
            repository: crate::config::RepositoryConfig {
                url: repo_path.to_string_lossy().to_string(),
                main_branch: "main".to_string(),
                ..Default::default()
            },
            master_claude: crate::config::MasterClaudeConfig {
                role: "technical_lead".to_string(),
                quality_threshold: 0.90,
                think_mode: crate::config::ThinkMode::UltraThink,
                permission_level: "supervised".to_string(),
                claude_config: crate::config::ClaudeConfig::for_master(),
                enable_proactive_mode: true, // Enabled by default
                proactive_frequency: 30,     // 30 second interval
                high_frequency: 15,          // High frequency 15 second interval
            },
        },
        agents,
        coordination: crate::config::CoordinationConfig {
            communication_method: "json_files".to_string(),
            sync_interval: 30,
            quality_gate_frequency: "on_commit".to_string(),
            master_review_trigger: "all_tasks_complete".to_string(),
        },
    })
}

fn create_minimal_config(repo_path: &Path) -> Result<CcswarmConfig> {
    let mut config = create_default_config(repo_path)?;
    config.agents.clear();
    config.project.name = "Minimal ccswarm Project".to_string();
    Ok(config)
}

fn create_frontend_only_config(repo_path: &Path) -> Result<CcswarmConfig> {
    let mut config = create_minimal_config(repo_path)?;
    config.project.name = "Frontend ccswarm Project".to_string();

    config.agents.insert(
        "frontend".to_string(),
        crate::config::AgentConfig {
            specialization: "react_typescript".to_string(),
            worktree: "../worktrees/frontend-agent".to_string(),
            branch: "feature/frontend".to_string(),
            claude_config: crate::config::ClaudeConfig::for_agent("frontend"),
            claude_md_template: "frontend_specialist".to_string(),
        },
    );

    Ok(config)
}