fledge 0.15.0

Dev-lifecycle CLI — scaffolding, tasks, lanes, plugins, and more.
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
use anyhow::Result;
use clap::{CommandFactory, Parser};
use clap_complete::Shell;
use console::style;
use std::path::PathBuf;

mod ai;
mod ask;
mod changelog;
mod config;
mod create_template;
mod doctor;
mod github;
mod init;
mod introspect;
mod lanes;
mod llm;
mod meta;
mod plugin;
mod prompts;
mod protocol;
mod publish;
mod release;
mod remote;
mod review;
mod run;
mod search;
mod spec;
mod spinner;
mod templates;
mod trust;
mod utils;
mod validate;
mod versioning;
mod watch;
mod work;

#[derive(Parser)]
#[command(
    name = "fledge",
    version,
    about = "Dev-lifecycle CLI — get your projects ready to fly."
)]
struct Cli {
    /// Run without prompts: treat every interactive confirmation as --yes,
    /// and bail with a clear error on prompts that have no default. Also
    /// settable via the FLEDGE_NON_INTERACTIVE env var.
    #[arg(long, global = true, visible_alias = "ni")]
    non_interactive: bool,

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

#[derive(clap::Subcommand)]
enum Commands {
    /// Manage AI provider and model selection
    Ai {
        #[command(subcommand)]
        action: AiSubcommand,
    },
    /// Ask a question about your codebase
    Ask {
        /// The question to ask
        question: Vec<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Include full spec + companions for these modules in the prompt
        /// (comma-separated, repeatable, use "all" for every spec)
        #[arg(long, value_name = "NAMES")]
        with_specs: Vec<String>,
        /// Omit the compact spec index from the prompt (saves tokens)
        #[arg(long)]
        no_spec_index: bool,
        /// LLM provider: claude (default) or ollama. Overrides
        /// FLEDGE_AI_PROVIDER and ai.provider in config.
        #[arg(long, value_name = "NAME", value_parser = ["claude", "ollama"])]
        provider: Option<String>,
        /// Model name. Overrides FLEDGE_AI_MODEL and
        /// ai.{claude,ollama}.model in config.
        #[arg(long, value_name = "MODEL")]
        model: Option<String>,
    },
    /// Generate a changelog from git tags and commits
    Changelog {
        /// Number of releases to show
        #[arg(short, long, default_value = "10")]
        limit: usize,
        /// Show a specific tag only
        #[arg(short, long)]
        tag: Option<String>,
        /// Show unreleased changes since the latest tag
        #[arg(long)]
        unreleased: bool,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Generate shell completions
    Completions {
        /// Shell to generate completions for (auto-detects if omitted with --install)
        #[arg(value_enum)]
        shell: Option<Shell>,
        /// Install completions to the standard location for your shell
        #[arg(long)]
        install: bool,
    },
    /// Manage global configuration
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// Diagnose project environment health
    Doctor {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Dump the full command tree (for agents and tooling)
    Introspect {
        /// Output as JSON (default: pretty tree)
        #[arg(long)]
        json: bool,
    },
    /// Manage and run composable workflow pipelines
    #[command(alias = "lane")]
    Lanes {
        #[command(subcommand)]
        action: LaneSubcommand,
    },
    /// Manage plugins (install, remove, list, search)
    #[command(alias = "plugin")]
    Plugins {
        #[command(subcommand)]
        action: PluginSubcommand,
        /// Output as JSON
        #[arg(long, global = true)]
        json: bool,
    },
    /// Cut a release — bump version, changelog, tag, and optionally push
    Release {
        /// Version bump: major, minor, patch, or explicit version (e.g. "1.0.0")
        bump: String,
        /// Show what would happen without making changes
        #[arg(long)]
        dry_run: bool,
        /// Skip creating a git tag
        #[arg(long)]
        no_tag: bool,
        /// Skip changelog generation
        #[arg(long)]
        no_changelog: bool,
        /// Push commit and tag to remote after release
        #[arg(long)]
        push: bool,
        /// Run a lane before releasing (e.g. "ci")
        #[arg(long)]
        pre_lane: Option<String>,
        /// Allow releasing with uncommitted changes
        #[arg(long)]
        allow_dirty: bool,
    },
    /// AI-powered code review of current changes
    Review {
        /// Base branch to diff against (default: auto-detect)
        #[arg(short, long)]
        base: Option<String>,
        /// Review only a specific file
        #[arg(short, long)]
        file: Option<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Model name for the active provider (overrides FLEDGE_AI_MODEL
        /// and ai.{claude,ollama}.model in config)
        #[arg(short, long)]
        model: Option<String>,
        /// Custom review focus prompt (appended to default instructions)
        #[arg(short, long)]
        prompt: Option<String>,
        /// Output format: summary (default), checklist, inline
        #[arg(long, default_value = "summary")]
        format: String,
        /// Include full spec + companions for these modules in the review
        /// context (comma-separated, repeatable). Appended to any
        /// auto-detected specs.
        #[arg(long, value_name = "NAMES")]
        with_specs: Vec<String>,
        /// Disable auto-detection of specs based on files in the diff
        #[arg(long)]
        no_auto_specs: bool,
        /// LLM provider: claude (default) or ollama. Overrides
        /// FLEDGE_AI_PROVIDER and ai.provider in config.
        #[arg(long, value_name = "NAME", value_parser = ["claude", "ollama"])]
        provider: Option<String>,
        /// Add another model to the review panel — runs in parallel against
        /// the same diff + spec context. Format: provider[:model], e.g.
        /// `ollama:gpt-oss:120b-cloud` or just `claude` to use the active
        /// claude config. Repeatable and comma-separated.
        #[arg(long, value_name = "REF")]
        with_model: Vec<String>,
        /// Drop the active config (--provider/--model or
        /// `fledge ai use`) from the panel. Only the explicit --with-model
        /// entries will run. Useful for "compare exactly these N models".
        #[arg(long)]
        no_active: bool,
    },
    /// Run a project task defined in fledge.toml
    Run {
        /// Task name to run (lists tasks if omitted)
        task: Option<String>,
        /// Create a starter fledge.toml
        #[arg(long)]
        init: bool,
        /// List available tasks
        #[arg(short, long)]
        list: bool,
        /// Override detected project language (e.g. rust, node, go, python, swift, ruby, java-gradle, java-maven)
        #[arg(long)]
        lang: Option<String>,
        /// Output results as JSON
        #[arg(long)]
        json: bool,
    },
    /// Manage specs (check, init, new)
    Spec {
        #[command(subcommand)]
        action: SpecSubcommand,
    },
    /// Manage templates (init, create, validate, list)
    #[command(alias = "template")]
    Templates {
        #[command(subcommand)]
        action: TemplatesSubcommand,
    },
    /// Watch for file changes and re-run a task or lane
    Watch {
        /// Task name to re-run on changes (use --lane for lanes)
        name: String,
        /// Watch and re-run a lane instead of a task
        #[arg(long)]
        lane: bool,
        /// Only watch a specific directory (default: current directory)
        #[arg(short, long)]
        path: Option<PathBuf>,
        /// Only trigger on specific file extensions (comma-separated, e.g. "rs,toml")
        #[arg(short, long)]
        ext: Option<String>,
        /// Debounce interval in milliseconds
        #[arg(short, long, default_value = "500")]
        debounce: u64,
        /// Clear terminal before each run
        #[arg(long)]
        clear: bool,
    },
    /// Feature branch and PR workflow
    Work {
        #[command(subcommand)]
        action: WorkSubcommand,
    },
    #[command(external_subcommand)]
    External(Vec<String>),
}

#[derive(clap::Subcommand)]
enum TemplatesSubcommand {
    /// Create a new project from a template
    Init {
        /// Project name
        name: String,
        /// Template to use (skip interactive selection)
        #[arg(short, long)]
        template: Option<String>,
        /// Parent directory for the project
        #[arg(short, long, default_value = ".")]
        output: PathBuf,
        /// Author name (bypasses prompt; overrides config)
        #[arg(long)]
        author: Option<String>,
        /// GitHub organization (bypasses prompt; overrides config)
        #[arg(long)]
        org: Option<String>,
        /// Skip git init and initial commit
        #[arg(long)]
        no_git: bool,
        /// Skip dependency installation (post-create hooks)
        #[arg(long)]
        no_install: bool,
        /// Force re-clone of cached remote templates
        #[arg(long)]
        refresh: bool,
        /// Show what would be created without writing anything
        #[arg(long)]
        dry_run: bool,
        /// Skip all confirmation prompts (accept defaults)
        #[arg(short, long)]
        yes: bool,
    },
    /// Scaffold a new fledge template
    Create {
        /// Template name
        name: String,
        /// Parent directory for the template
        #[arg(short, long, default_value = ".")]
        output: PathBuf,
        /// Template description (bypasses prompt)
        #[arg(short, long)]
        description: Option<String>,
        /// Comma-separated file patterns to render through Tera (bypasses prompt)
        #[arg(long)]
        render_patterns: Option<String>,
        /// Include post-create hooks scaffold (bypasses prompt)
        #[arg(long, num_args = 0..=1, default_missing_value = "true")]
        hooks: Option<bool>,
        /// Include custom prompts scaffold (bypasses prompt)
        #[arg(long, num_args = 0..=1, default_missing_value = "true")]
        prompts: Option<bool>,
        /// Skip all interactive prompts (accept defaults)
        #[arg(short, long)]
        yes: bool,
    },
    /// Validate a template or directory of templates
    Validate {
        /// Path to a template or directory of templates
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Treat warnings as errors
        #[arg(long)]
        strict: bool,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// List available templates
    List,
}

#[derive(clap::Subcommand)]
enum SpecSubcommand {
    /// Validate specs against source code
    Check {
        /// Treat warnings as errors
        #[arg(long)]
        strict: bool,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Initialize spec-sync configuration
    Init,
    /// List all specs in the project
    #[command(alias = "ls")]
    List {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Scaffold a new spec module
    New {
        /// Module name
        name: String,
    },
    /// Show a single spec's frontmatter, sections, and companions
    Show {
        /// Module name
        name: String,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
}

#[derive(clap::Subcommand)]
enum WorkSubcommand {
    /// Start a new work branch
    Start {
        /// Branch name (will be sanitized for git)
        name: String,
        /// Branch type: feat, fix, chore, docs, hotfix, refactor (default: feat)
        #[arg(short = 't', long = "branch-type", value_name = "TYPE")]
        branch_type: Option<String>,
        /// Link to GitHub issue (prefixes branch name with issue number)
        #[arg(short, long, value_name = "NUMBER")]
        issue: Option<u64>,
        /// Override branch prefix entirely (e.g. "user/leif")
        #[arg(long)]
        prefix: Option<String>,
        /// Base branch to branch from (default: main)
        #[arg(long)]
        base: Option<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Create a pull request from the current branch
    Pr {
        /// PR title (auto-generated from branch name if omitted)
        #[arg(short, long)]
        title: Option<String>,
        /// PR body (auto-generated from commits if omitted)
        #[arg(short, long)]
        body: Option<String>,
        /// Create as a draft PR
        #[arg(long)]
        draft: bool,
        /// Target base branch for the PR
        #[arg(long)]
        base: Option<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Skip the preview/confirmation prompt
        #[arg(short = 'y', long)]
        yes: bool,
        /// Generate the PR body via the configured AI provider (uses commit log + diff as context)
        #[arg(long)]
        ai: bool,
        /// Override AI provider for --ai (claude or ollama)
        #[arg(long, value_parser = ["claude", "ollama"])]
        provider: Option<String>,
        /// Override AI model for --ai
        #[arg(long)]
        model: Option<String>,
    },
    /// Show current branch and PR status
    Status {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
}

#[derive(clap::Subcommand)]
enum AiSubcommand {
    /// Show the active AI provider, model, and host
    Status {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// List available models for the active (or specified) provider
    Models {
        /// Provider: claude or ollama (default: active provider)
        #[arg(long, value_name = "NAME", value_parser = ["claude", "ollama"])]
        provider: Option<String>,
        /// Filter models by substring (case-insensitive)
        #[arg(long, value_name = "QUERY")]
        search: Option<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Select the active provider (and optionally model); interactive if args
    /// are omitted
    #[command(name = "use")]
    Use {
        /// Provider: claude or ollama
        #[arg(value_parser = ["claude", "ollama"])]
        provider: Option<String>,
        /// Model name (e.g. qwen3-coder:480b-cloud)
        model: Option<String>,
    },
}

#[derive(clap::Subcommand)]
enum ConfigAction {
    /// Get a config value
    Get {
        /// Config key (e.g. defaults.github_org)
        key: String,
    },
    /// Set a config value
    Set {
        /// Config key (e.g. defaults.github_org)
        key: String,
        /// Value to set
        value: String,
    },
    /// Remove a config value
    Unset {
        /// Config key (e.g. defaults.github_org)
        key: String,
    },
    /// Add a value to a list config key (templates.paths, templates.repos)
    Add {
        /// Config key (templates.paths or templates.repos)
        key: String,
        /// Value to add
        value: String,
    },
    /// Remove a value from a list config key (templates.paths, templates.repos)
    Remove {
        /// Config key (templates.paths or templates.repos)
        key: String,
        /// Value to remove
        value: String,
    },
    /// Show all config values
    List,
    /// Show config file path
    Path,
    /// Initialize config with a preset (e.g. corvidlabs)
    Init {
        /// Preset name (available: corvidlabs)
        #[arg(long)]
        preset: Option<String>,
    },
}

#[derive(clap::Subcommand)]
enum LaneSubcommand {
    /// Run a lane by name
    Run {
        /// Lane name
        name: String,
        /// Show execution plan without running
        #[arg(long)]
        dry_run: bool,
        /// Output results as JSON
        #[arg(long)]
        json: bool,
    },
    /// List available lanes
    List {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Add default lanes to fledge.toml
    Init,
    /// Search GitHub for community lanes
    Search {
        /// Keyword to filter results
        query: Option<String>,
        /// Filter by author/owner
        #[arg(short, long)]
        author: Option<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Import lanes from a GitHub repo (owner/repo)
    Import {
        /// GitHub repo (owner/repo) or full URL, optionally with @ref
        source: String,
        /// Skip all confirmation prompts
        #[arg(short, long)]
        yes: bool,
    },
    /// Publish lanes to GitHub
    Publish {
        /// Path to the directory containing fledge.toml with lanes
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Publish under a GitHub organization
        #[arg(long)]
        org: Option<String>,
        /// Create as a private repository
        #[arg(long)]
        private: bool,
        /// Override the repository description
        #[arg(long)]
        description: Option<String>,
        /// Skip all confirmation prompts
        #[arg(short, long)]
        yes: bool,
    },
    /// Scaffold a new lane repo
    Create {
        /// Lane repo name
        name: String,
        /// Parent directory
        #[arg(short, long, default_value = ".")]
        output: PathBuf,
        /// Description (bypasses prompt)
        #[arg(short, long)]
        description: Option<String>,
        /// Skip all interactive prompts
        #[arg(short, long)]
        yes: bool,
    },
    /// Validate lane definitions in fledge.toml
    Validate {
        /// Path to a directory containing fledge.toml
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Treat warnings as errors
        #[arg(long)]
        strict: bool,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    #[command(external_subcommand)]
    External(Vec<String>),
}

#[derive(clap::Subcommand)]
enum PluginSubcommand {
    /// Install a plugin from GitHub
    Install {
        /// GitHub repo (owner/repo[@ref]) or full URL — use @tag to pin a version. Omit when using --defaults.
        source: Option<String>,
        /// Reinstall if already present
        #[arg(long)]
        force: bool,
        /// Skip all confirmation prompts (accept defaults)
        #[arg(short, long)]
        yes: bool,
        /// Install fledge's curated set of default plugins (github, deps, metrics, templates-remote, doctor)
        #[arg(long, conflicts_with = "source")]
        defaults: bool,
    },
    /// Remove an installed plugin
    Remove {
        /// Plugin name
        name: String,
    },
    /// Update installed plugins (git pull + rebuild)
    Update {
        /// Plugin name (omit to update all)
        name: Option<String>,
    },
    /// List installed plugins
    List,
    /// Audit installed plugins — show trust tiers, capabilities, and hooks
    Audit,
    /// Search for plugins on GitHub
    Search {
        /// Search query
        query: Option<String>,
        /// Filter by author/owner
        #[arg(short, long)]
        author: Option<String>,
        /// Maximum results
        #[arg(short, long, default_value = "20")]
        limit: usize,
    },
    /// Run a plugin command
    Run {
        /// Plugin command name
        name: String,
        /// Arguments to pass to the plugin
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Publish a plugin to GitHub
    Publish {
        /// Path to the plugin directory
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Publish under a GitHub organization
        #[arg(long)]
        org: Option<String>,
        /// Create as a private repository
        #[arg(long)]
        private: bool,
        /// Override the repository description
        #[arg(long)]
        description: Option<String>,
        /// Skip all confirmation prompts
        #[arg(short, long)]
        yes: bool,
    },
    /// Scaffold a new plugin
    Create {
        /// Plugin name
        name: String,
        /// Parent directory
        #[arg(short, long, default_value = ".")]
        output: PathBuf,
        /// Description (bypasses prompt)
        #[arg(short, long)]
        description: Option<String>,
        /// Skip all interactive prompts
        #[arg(short, long)]
        yes: bool,
    },
    /// Validate a plugin manifest
    Validate {
        /// Path to a directory containing plugin.toml
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Treat warnings as errors
        #[arg(long)]
        strict: bool,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
}

fn main() {
    if let Err(e) = run() {
        eprintln!("{} {:#}", style("error:").red().bold(), e);
        std::process::exit(1);
    }
}

fn run() -> Result<()> {
    // Env var is honored regardless of how the CLI is invoked, so agent shells
    // can set FLEDGE_NON_INTERACTIVE=1 once and forget about it.
    utils::init_non_interactive_from_env();
    let cli = Cli::parse();
    if cli.non_interactive {
        utils::set_non_interactive(true);
    }

    match cli.command {
        Commands::Templates { action } => {
            handle_templates(action)?;
        }
        Commands::Config { action } => {
            handle_config(action)?;
        }
        Commands::Spec { action } => {
            let action = match action {
                SpecSubcommand::Check { strict, json } => spec::SpecAction::Check { strict, json },
                SpecSubcommand::Init => spec::SpecAction::Init,
                SpecSubcommand::List { json } => spec::SpecAction::List { json },
                SpecSubcommand::New { name } => spec::SpecAction::New { name },
                SpecSubcommand::Show { name, json } => spec::SpecAction::Show { name, json },
            };
            spec::run(action)?;
        }
        Commands::Work { action } => {
            let action = match action {
                WorkSubcommand::Start {
                    name,
                    branch_type,
                    issue,
                    prefix,
                    base,
                    json,
                } => work::WorkAction::Start {
                    name,
                    branch_type,
                    issue,
                    prefix,
                    base,
                    json,
                },
                WorkSubcommand::Pr {
                    title,
                    body,
                    draft,
                    base,
                    json,
                    yes,
                    ai,
                    provider,
                    model,
                } => work::WorkAction::Pr {
                    title,
                    body,
                    draft,
                    base,
                    json,
                    yes,
                    ai,
                    provider,
                    model,
                },
                WorkSubcommand::Status { json } => work::WorkAction::Status { json },
            };
            work::run(action)?;
        }
        Commands::Run {
            task,
            init,
            list,
            lang,
            json,
        } => {
            run::run(run::RunOptions {
                task,
                init,
                list,
                lang,
                json,
            })?;
        }
        Commands::Watch {
            name,
            lane,
            path,
            ext,
            debounce,
            clear,
        } => {
            let extensions = ext.map(|e| watch::parse_extensions(&e)).unwrap_or_default();
            watch::run(watch::WatchOptions {
                name,
                lane,
                path,
                extensions,
                debounce_ms: debounce,
                clear,
            })?;
        }
        Commands::Review {
            base,
            file,
            json,
            model,
            prompt,
            format,
            with_specs,
            no_auto_specs,
            provider,
            with_model,
            no_active,
        } => {
            let format: review::ReviewFormat =
                format.parse().map_err(|e: String| anyhow::anyhow!(e))?;
            review::run(review::ReviewOptions {
                base,
                file,
                json,
                model,
                prompt,
                format,
                with_specs,
                no_auto_specs,
                provider,
                with_model,
                no_active,
            })?;
        }
        Commands::Lanes { action } => {
            let action = match action {
                LaneSubcommand::Run {
                    name,
                    dry_run,
                    json,
                } => lanes::LaneAction::Run {
                    name,
                    dry_run,
                    json,
                },
                LaneSubcommand::List { json } => lanes::LaneAction::List { json },
                LaneSubcommand::Init => lanes::LaneAction::Init,
                LaneSubcommand::Search {
                    query,
                    author,
                    json,
                } => lanes::LaneAction::Search {
                    query,
                    author,
                    json,
                },
                LaneSubcommand::Import { source, yes } => lanes::LaneAction::Import { source, yes },
                LaneSubcommand::Publish {
                    path,
                    org,
                    private,
                    description,
                    yes,
                } => lanes::LaneAction::Publish {
                    path,
                    org,
                    private,
                    description,
                    yes,
                },
                LaneSubcommand::Create {
                    name,
                    output,
                    description,
                    yes,
                } => lanes::LaneAction::Create {
                    name,
                    output,
                    description,
                    yes,
                },
                LaneSubcommand::Validate { path, strict, json } => {
                    lanes::LaneAction::Validate { path, strict, json }
                }
                LaneSubcommand::External(args) => {
                    let name = args.first().cloned().unwrap_or_default();
                    let dry_run = args.iter().any(|a| a == "--dry-run");
                    let json = args.iter().any(|a| a == "--json");
                    lanes::LaneAction::Run {
                        name,
                        dry_run,
                        json,
                    }
                }
            };
            lanes::run(action)?;
        }
        Commands::Changelog {
            limit,
            tag,
            unreleased,
            json,
        } => {
            changelog::run(changelog::ChangelogOptions {
                limit,
                tag,
                unreleased,
                json,
            })?;
        }
        Commands::Doctor { json } => {
            doctor::run(doctor::DoctorOptions { json })?;
        }
        Commands::Introspect { json } => {
            let cmd = <Cli as clap::CommandFactory>::command();
            introspect::run(introspect::IntrospectOptions { json }, cmd)?;
        }
        Commands::Plugins { action, json } => {
            let action = match action {
                PluginSubcommand::Install {
                    source,
                    force,
                    yes,
                    defaults,
                } => plugin::PluginAction::Install {
                    source,
                    force: force || yes,
                    defaults,
                },
                PluginSubcommand::Remove { name } => plugin::PluginAction::Remove { name },
                PluginSubcommand::Update { name } => plugin::PluginAction::Update { name },
                PluginSubcommand::List => plugin::PluginAction::List,
                PluginSubcommand::Audit => plugin::PluginAction::Audit,
                PluginSubcommand::Search {
                    query,
                    author,
                    limit,
                } => plugin::PluginAction::Search {
                    query,
                    author,
                    limit,
                },
                PluginSubcommand::Run { name, args } => plugin::PluginAction::Run { name, args },
                PluginSubcommand::Publish {
                    path,
                    org,
                    private,
                    description,
                    yes,
                } => plugin::PluginAction::Publish {
                    path,
                    org,
                    private,
                    description,
                    yes,
                },
                PluginSubcommand::Create {
                    name,
                    output,
                    description,
                    yes,
                } => plugin::PluginAction::Create {
                    name,
                    output,
                    description,
                    yes,
                },
                PluginSubcommand::Validate { path, strict, json } => {
                    plugin::PluginAction::Validate { path, strict, json }
                }
            };
            plugin::run(plugin::PluginOptions { action, json })?;
        }
        Commands::Release {
            bump,
            dry_run,
            no_tag,
            no_changelog,
            push,
            pre_lane,
            allow_dirty,
        } => {
            release::run(release::ReleaseOptions {
                bump,
                dry_run,
                no_tag,
                no_changelog,
                push,
                pre_lane,
                allow_dirty,
            })?;
        }
        Commands::Ai { action } => {
            let action = match action {
                AiSubcommand::Status { json } => ai::AiAction::Status { json },
                AiSubcommand::Models {
                    provider,
                    search,
                    json,
                } => ai::AiAction::Models {
                    provider,
                    search,
                    json,
                },
                AiSubcommand::Use { provider, model } => ai::AiAction::Use { provider, model },
            };
            ai::run(action)?;
        }
        Commands::Ask {
            question,
            json,
            with_specs,
            no_spec_index,
            provider,
            model,
        } => {
            if question.is_empty() {
                anyhow::bail!("Please provide a question. Usage: fledge ask <question>");
            }
            ask::run(ask::AskOptions {
                question: question.join(" "),
                json,
                with_specs,
                no_spec_index,
                provider,
                model,
            })?;
        }
        Commands::Completions { shell, install } => {
            if install {
                install_completions(shell)?;
            } else {
                let shell = shell.ok_or_else(|| {
                    anyhow::anyhow!(
                        "Shell argument is required when not using --install. Usage: fledge completions <bash|zsh|fish>"
                    )
                })?;
                clap_complete::generate(
                    shell,
                    &mut Cli::command(),
                    "fledge",
                    &mut std::io::stdout(),
                );
            }
        }
        Commands::External(args) => {
            let cmd_name = args.first().ok_or_else(|| {
                anyhow::anyhow!(
                    "no subcommand provided\n\n  tip: use {} for help",
                    style("fledge help").cyan()
                )
            })?;
            let cmd_args: Vec<String> = args[1..].to_vec();
            if plugin::resolve_plugin_command(cmd_name).is_some() {
                plugin::run(plugin::PluginOptions {
                    action: plugin::PluginAction::Run {
                        name: cmd_name.clone(),
                        args: cmd_args,
                    },
                    json: false,
                })?;
            } else {
                anyhow::bail!(
                    "unrecognized subcommand '{}'\n\n  tip: use {} for help",
                    cmd_name,
                    style("fledge help").cyan()
                );
            }
        }
    }

    Ok(())
}

fn handle_templates(action: TemplatesSubcommand) -> Result<()> {
    match action {
        TemplatesSubcommand::Init {
            name,
            template,
            output,
            author,
            org,
            no_git,
            no_install,
            refresh,
            dry_run,
            yes,
        } => {
            init::run(init::InitOptions {
                name,
                template,
                output,
                author,
                org,
                no_git,
                no_install,
                refresh,
                dry_run,
                yes,
            })?;
        }
        TemplatesSubcommand::Create {
            name,
            output,
            description,
            render_patterns,
            hooks,
            prompts,
            yes,
        } => {
            create_template::run(create_template::CreateTemplateOptions {
                name,
                output,
                description,
                render_patterns,
                hooks,
                prompts,
                yes,
            })?;
        }
        TemplatesSubcommand::Validate { path, strict, json } => {
            validate::run(validate::ValidateOptions { path, strict, json })?;
        }
        TemplatesSubcommand::List => {
            list_templates()?;
        }
    }
    Ok(())
}

fn handle_config(action: ConfigAction) -> Result<()> {
    match action {
        ConfigAction::Get { key } => {
            let config = config::Config::load()?;
            if !config::Config::is_valid_key(&key) {
                anyhow::bail!(
                    "Unknown config key '{}'. Valid keys: defaults.author, defaults.github_org, defaults.license, github.token, templates.paths, templates.repos",
                    key
                );
            }
            match config.get(&key) {
                Some(value) if !value.is_empty() => println!("{}", value),
                _ => println!("{} {} is not set", style("*").cyan().bold(), key),
            }
        }
        ConfigAction::Set { key, value } => {
            let mut config = config::Config::load()?;
            config.set(&key, &value)?;
            config.save()?;
            println!(
                "{} Set {} = {}",
                style("").green().bold(),
                style(&key).cyan(),
                style(&value).green()
            );
        }
        ConfigAction::Unset { key } => {
            let mut config = config::Config::load()?;
            config.unset(&key)?;
            config.save()?;
            println!(
                "{} Unset {}",
                style("").green().bold(),
                style(&key).cyan()
            );
        }
        ConfigAction::Add { key, value } => {
            let mut config = config::Config::load()?;
            config.add_to_list(&key, &value)?;
            config.save()?;
            println!(
                "{} Added {} to {}",
                style("").green().bold(),
                style(&value).green(),
                style(&key).cyan()
            );
        }
        ConfigAction::Remove { key, value } => {
            let mut config = config::Config::load()?;
            let removed = config.remove_from_list(&key, &value)?;
            if removed {
                config.save()?;
                println!(
                    "{} Removed {} from {}",
                    style("").green().bold(),
                    style(&value).green(),
                    style(&key).cyan()
                );
            } else {
                println!(
                    "{} {} not found in {}",
                    style("*").cyan().bold(),
                    style(&value).dim(),
                    style(&key).cyan()
                );
            }
        }
        ConfigAction::List => {
            let config = config::Config::load()?;
            let path = config::Config::config_path();
            println!(
                "{} Config: {}\n",
                style("*").cyan().bold(),
                style(path.display()).dim()
            );
            print_config_entry("defaults.author", &config.defaults.author);
            print_config_entry("defaults.github_org", &config.defaults.github_org);
            print_config_entry("defaults.license", &config.defaults.license);
            print_config_entry(
                "github.token",
                &config.github.token.as_ref().map(|_| "***".to_string()),
            );
            if config.templates.paths.is_empty() {
                println!(
                    "  {:<24} {}",
                    style("templates.paths").cyan(),
                    style("(none)").dim()
                );
            } else {
                for (i, p) in config.templates.paths.iter().enumerate() {
                    if i == 0 {
                        println!("  {:<24} {}", style("templates.paths").cyan(), p);
                    } else {
                        println!("  {:<24} {}", "", p);
                    }
                }
            }
            if config.templates.repos.is_empty() {
                println!(
                    "  {:<24} {}",
                    style("templates.repos").cyan(),
                    style("(none)").dim()
                );
            } else {
                for (i, r) in config.templates.repos.iter().enumerate() {
                    if i == 0 {
                        println!("  {:<24} {}", style("templates.repos").cyan(), r);
                    } else {
                        println!("  {:<24} {}", "", r);
                    }
                }
            }
        }
        ConfigAction::Path => {
            println!("{}", config::Config::config_path().display());
        }
        ConfigAction::Init { preset } => {
            config::init_config(preset.as_deref())?;
        }
    }
    Ok(())
}

fn print_config_entry(key: &str, value: &Option<impl std::fmt::Display>) {
    match value {
        Some(v) => println!("  {:<24} {}", style(key).cyan(), v),
        None => println!("  {:<24} {}", style(key).cyan(), style("(not set)").dim()),
    }
}

fn install_completions(shell: Option<Shell>) -> Result<()> {
    let shell = shell.unwrap_or_else(|| {
        let shell_env = std::env::var("SHELL").unwrap_or_default();
        if shell_env.ends_with("zsh") {
            Shell::Zsh
        } else if shell_env.ends_with("fish") {
            Shell::Fish
        } else {
            Shell::Bash
        }
    });

    let home =
        dirs::home_dir().ok_or_else(|| anyhow::anyhow!("cannot determine home directory"))?;

    let dest = match shell {
        Shell::Bash => {
            let dir = home.join(".local/share/bash-completion/completions");
            std::fs::create_dir_all(&dir)?;
            dir.join("fledge")
        }
        Shell::Zsh => {
            let dir = home.join(".zfunc");
            std::fs::create_dir_all(&dir)?;
            dir.join("_fledge")
        }
        Shell::Fish => {
            let dir = home.join(".config/fish/completions");
            std::fs::create_dir_all(&dir)?;
            dir.join("fledge.fish")
        }
        _ => anyhow::bail!(
            "auto-install not supported for {:?} — use `fledge completions <shell>` to generate manually",
            shell
        ),
    };

    let mut buf = Vec::new();
    clap_complete::generate(shell, &mut Cli::command(), "fledge", &mut buf);
    std::fs::write(&dest, buf)?;

    println!(
        "{} Installed {} completions to {}",
        style("").green().bold(),
        style(format!("{shell:?}")).cyan(),
        style(dest.display()).dim()
    );

    if matches!(shell, Shell::Zsh) {
        println!(
            "\n  {}",
            style("Add to your .zshrc if not already present:").dim()
        );
        println!("    fpath=(~/.zfunc $fpath)");
        println!("    autoload -Uz compinit && compinit");
    }

    Ok(())
}

fn list_templates() -> Result<()> {
    let config = config::Config::load()?;
    let extra_paths = config.extra_template_paths();
    let token = config.github_token();
    let available = templates::discover_templates_with_repos(
        &extra_paths,
        config.template_repos(),
        token.as_deref(),
    )?;

    if available.is_empty() {
        anyhow::bail!("No templates found. Configure template sources via `fledge config add templates.repos <owner/repo>`, add templates to the templates/ directory, or set templates.paths via `fledge config add templates.paths <path>`.");
    }

    println!("{}", style("Available templates:").bold());
    for t in &available {
        println!(
            "  {:<14} {}",
            style(&t.name).green(),
            style(&t.description).dim()
        );
    }

    Ok(())
}