zoi-cli 1.24.2

Advanced Package Manager & Environment Orchestrator
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
use crate::cmd;
use crate::pkg::lock;
use crate::utils;
use clap::{
    ColorChoice, CommandFactory, FromArgMatches, Parser, Subcommand, ValueHint, builder::styling,
};
use clap_complete::Shell;
use clap_complete::generate;
use colored::Colorize;
use std::io::{self};
use std::path::PathBuf;

// Development, Special, Public or Production
const BRANCH: &str = "Production";
const STATUS: &str = "Release";
const NUMBER: &str = "1.24.2";
const PKG_SOURCE_HELP: &str = "Package identifier (e.g. @repo/name, #git@repo/name, path, or URL)";

/// Zoi - The Advanced Package Manager & Environment Orchestrator.
///
/// Part of the Zillowe Development Suite (ZDS), Zoi is designed to streamline
/// your development workflow by managing tools and project environments.
#[derive(Parser)]
#[command(name = "zoi", author, about, long_about = None, disable_version_flag = true,
    trailing_var_arg = true,
    color = ColorChoice::Auto,
    arg_required_else_help = true,
)]
pub struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    #[arg(
        short = 'v',
        long = "version",
        help = "Print detailed version information"
    )]
    version_flag: bool,

    #[arg(
        short = 'y',
        long,
        help = "Automatically answer yes to all prompts",
        global = true
    )]
    yes: bool,

    #[arg(
        long = "root",
        help = "Operate on a different root directory",
        global = true,
        value_hint = ValueHint::DirPath
    )]
    pub root: Option<std::path::PathBuf>,

    #[arg(
        long = "offline",
        help = "Do not attempt to connect to the network",
        global = true
    )]
    pub offline: bool,

    #[arg(
        long = "pkg-dir",
        help = "Additional directory to search for .zpa archives",
        global = true,
        value_hint = ValueHint::DirPath
    )]
    pub pkg_dirs: Vec<std::path::PathBuf>,
}

#[derive(clap::ValueEnum, Clone, Debug, Copy, PartialEq, Eq)]
pub enum SetupScope {
    User,
    System,
}

#[derive(clap::ValueEnum, Clone, Debug, Copy)]
pub enum InstallScope {
    User,
    System,
    Project,
}

#[derive(Subcommand)]
enum Commands {
    /// Generates shell completion scripts
    #[command(hide = true)]
    GenerateCompletions {
        /// The shell to generate completions for
        #[arg(value_enum)]
        shell: Shell,
    },

    /// Dynamic shell completions (internal use)
    #[command(hide = true)]
    Complete {
        /// The shell to complete for
        #[arg(value_enum)]
        shell: Shell,
        /// Current word index (1-based)
        index: usize,
        /// All words in the command line
        words: Vec<String>,
    },

    /// Generates man pages for zoi
    #[command(hide = true)]
    GenerateManual,

    /// Prints concise version and build information
    #[command(
        alias = "v",
        long_about = "Displays the version number, build status, branch, and commit hash. This is the same output provided by the -v and --version flags."
    )]
    Version,

    /// Shows detailed application information and credits
    #[command(
        long_about = "Displays the full application name, description, author, license, and homepage information."
    )]
    About,

    /// Displays detected operating system and architecture information
    #[command(
        long_about = "Detects and displays key system details, including the OS, CPU architecture, Linux distribution (if applicable), and available package managers."
    )]
    Info,

    /// Downloads a package archive or source bundle
    #[command(
        alias = "dl",
        long_about = "Downloads the binary archive (.zpa) or source bundle (.zsa) for a package to the local cache or a specified directory."
    )]
    Download {
        /// Package identifier (e.g. @repo/name, path, or URL)
        #[arg(value_name = "PACKAGE", required = true, help = PKG_SOURCE_HELP)]
        package: String,

        /// Download the binary archive (.zpa) [default]
        #[arg(long, group = "type")]
        archive: bool,

        /// Download the source bundle (.zsa)
        #[arg(long, group = "type")]
        source: bool,

        /// Directory to output the downloaded file to
        #[arg(short, long)]
        output_dir: Option<PathBuf>,
    },

    /// Downloads or updates the package database from the remote repository
    #[command(
        alias = "sy",
        long_about = "Clones the official package database from GitLab to your local machine (~/.zoi/pkgs/db). If the database already exists, it verifies the remote URL and pulls the latest changes."
    )]
    Sync {
        #[command(subcommand)]
        command: Option<SyncCommands>,

        /// Show the full git output
        #[arg(short, long)]
        verbose: bool,

        /// Fallback to other mirrors if the default one fails
        #[arg(long)]
        fallback: bool,

        /// Do not check for installed package managers
        #[arg(long = "no-pm")]
        no_package_managers: bool,

        /// Force re-sync by removing existing databases and re-cloning from scratch
        #[arg(long)]
        force: bool,

        /// Sync registries to the project's local .zoi/pkgs/db/ using revisions from zoi.lua
        #[arg(long)]
        local: bool,

        /// When used with --local, sync using revisions from zoi.lock instead of zoi.lua
        #[arg(long)]
        frozen: bool,

        /// The scope to sync the registries to
        #[arg(long, value_enum, conflicts_with = "local")]
        scope: Option<SetupScope>,
    },

    /// Migration helpers for converting external manifests to Zoi package files
    Migrate(cmd::migrate::MigrateCommand),

    /// Lists installed or all available packages
    #[command(alias = "ls")]
    List {
        /// List all packages from the database, not just installed ones
        #[arg(short, long)]
        all: bool,
        /// List only installed packages that have updates available
        #[arg(short, long)]
        outdated: bool,
        /// Filter by registry handle (e.g. 'zoidberg')
        #[arg(long)]
        registry: Option<String>,
        /// Filter by repository (e.g. 'main', 'extra')
        #[arg(long)]
        repo: Option<String>,
        /// Filter by package type (package, app, collection, extension)
        #[arg(short = 't', long = "type")]
        package_type: Option<String>,
        /// List packages not found in any configured registry
        #[arg(short = 'm', long)]
        foreign: bool,
        /// List only package names (internal use for completions)
        #[arg(long, hide = true)]
        names: bool,
        /// List packages with descriptions for completion
        #[arg(long, hide = true)]
        completion: bool,
    },

    /// Shows detailed information about a package
    Show {
        #[arg(value_name = "ALL_PACKAGES", help = PKG_SOURCE_HELP)]
        package_name: String,
        /// Display the raw, unformatted package file
        #[arg(long)]
        raw: bool,
        /// Use PURL (Package URL) specification for resolving package
        #[arg(long)]
        purl: bool,
    },

    /// Pin a package to a specific version
    Pin {
        #[arg(value_name = "INST_PACKAGES", help = PKG_SOURCE_HELP)]
        package: String,
        /// The version to pin the package to
        version: String,
    },

    /// Find which package provides a specific command or file
    Provides {
        /// The command or file path to search for
        term: String,
    },

    /// Visualize the dependency tree of a package
    Tree {
        #[arg(value_name = "ALL_PACKAGES", required = true, help = PKG_SOURCE_HELP)]
        packages: Vec<String>,
    },

    /// Unpin a package, allowing it to be updated
    Unpin {
        #[arg(value_name = "INST_PACKAGES", help = PKG_SOURCE_HELP)]
        package: String,
    },

    /// Modify the installation reason of a package
    #[command(
        alias = "m",
        long_about = "Changes whether a package is considered explicitly installed or a dependency. Explicit packages are not removed by 'autoremove', while dependencies are if no other package requires them.",
        group(clap::ArgGroup::new("mode").required(true).args(["as_dependency", "as_explicit"]))
    )]
    Mark {
        #[arg(value_name = "INST_PACKAGES", required = true, help = PKG_SOURCE_HELP)]
        packages: Vec<String>,

        /// Mark packages as dependencies
        #[arg(long, aliases = ["asdeps"])]
        as_dependency: bool,

        /// Mark packages as explicitly installed
        #[arg(long, aliases = ["asexpl"], conflicts_with = "as_dependency")]
        as_explicit: bool,
    },

    /// Updates one or more packages to their latest versions
    #[command(
        alias = "up",
        arg_required_else_help = true,
        group(clap::ArgGroup::new("target").required(true).args(["package_names", "all"]))
    )]
    Update {
        #[arg(value_name = "INST_PACKAGES", help = PKG_SOURCE_HELP)]
        package_names: Vec<String>,

        /// Update all installed packages
        #[arg(long, conflicts_with = "package_names")]
        all: bool,

        /// Do not actually perform the update, just show what would be done
        #[arg(long)]
        dry_run: bool,
        /// Explain why each selected update is included or skipped
        #[arg(long)]
        explain: bool,
        /// Emit machine-readable update plan JSON
        #[arg(long)]
        plan_json: bool,
        /// Interactively choose which upgradable packages to update (with --all)
        #[arg(long, requires = "all")]
        interactive: bool,
    },

    /// Installs one or more packages from a name, local file, URL, or git repository
    #[command(aliases = ["i", "in", "add"])]
    Install {
        #[arg(value_name = "ALL_SOURCES", help = PKG_SOURCE_HELP)]
        sources: Vec<String>,
        /// Install from a git repository (e.g. 'Zillowe/Hello', 'gl:Zillowe/Hello')
        #[arg(long, value_name = "REPO", conflicts_with = "sources")]
        repo: Option<String>,
        /// Force re-installation even if the package is already installed
        #[arg(long)]
        force: bool,
        /// Accept all optional dependencies
        #[arg(long)]
        all_optional: bool,
        /// The scope to install the package to
        #[arg(long, value_enum, conflicts_with_all = &["local", "global"])]
        scope: Option<InstallScope>,
        /// Install packages to the current project (alias for --scope=project)
        #[arg(long, conflicts_with = "global")]
        local: bool,
        /// Install packages globally for the current user (alias for --scope=user)
        #[arg(long)]
        global: bool,
        /// Save the package to the project's zoi.yaml
        #[arg(long)]
        save: bool,
        /// The type of package to build if building from source (e.g. 'source', 'pre-compiled').
        #[arg(long)]
        r#type: Option<String>,
        /// Do not actually perform the installation, just show what would be done
        #[arg(long)]
        dry_run: bool,

        /// Force building from source even if a pre-compiled archive is available in the registry
        #[arg(long, short = 'b')]
        build: bool,

        /// Enforce zoi.lock exactly (project install only, no lockfile updates)
        #[arg(long)]
        frozen: bool,

        /// Explain dependency selection and install decisions
        #[arg(long)]
        explain: bool,

        /// Emit machine-readable install plan JSON
        #[arg(long)]
        plan_json: bool,

        /// Retry failed downloads this many times (minimum 1)
        #[arg(long, default_value_t = 3)]
        retry: u32,

        /// Show additional install details (package origins, preflight info)
        #[arg(long, short)]
        verbose: bool,

        /// Use PURL (Package URL) specification for resolving packages
        #[arg(long)]
        purl: bool,
    },

    /// Add a tool to the current project or global configuration and install it
    #[command(alias = "u")]
    Use {
        /// Package(s) to use (e.g. node@20)
        #[arg(value_name = "ALL_PACKAGES", required = true, help = PKG_SOURCE_HELP)]
        packages: Vec<String>,

        /// Add to global configuration instead of project
        #[arg(short, long)]
        global: bool,
    },

    /// Uninstalls one or more packages previously installed by Zoi
    #[command(
        aliases = ["un", "rm", "remove"],
        long_about = "Removes one or more packages' files from the Zoi store and deletes their symlinks from the bin directory. This command will fail if a package was not installed by Zoi."
    )]
    Uninstall {
        #[arg(value_name = "INST_PACKAGES", required = true, help = PKG_SOURCE_HELP)]
        packages: Vec<String>,
        /// The scope to uninstall the package from
        #[arg(long, value_enum, conflicts_with_all = &["local", "global"])]
        scope: Option<InstallScope>,
        /// Uninstall packages from the current project (alias for --scope=project)
        #[arg(long, conflicts_with = "global")]
        local: bool,
        /// Uninstall packages globally for the current user (alias for --scope=user)
        #[arg(long)]
        global: bool,
        /// Remove the package from the project's zoi.yaml
        #[arg(long)]
        save: bool,
        /// Recursively remove dependencies that are no longer needed
        #[arg(short, long)]
        recursive: bool,

        /// Do not actually uninstall, just show what would be done
        #[arg(long)]
        dry_run: bool,

        /// Explain uninstall decisions (dependency impact and safety blocks)
        #[arg(long)]
        explain: bool,

        /// Emit machine-readable uninstall plan JSON
        #[arg(long)]
        plan_json: bool,
    },

    /// Execute a command defined in a local zoi.yaml file
    #[command(
        long_about = "Execute a command from zoi.yaml. If no command is specified, it will launch an interactive prompt to choose one."
    )]
    Run {
        /// The alias of the command to execute
        cmd_alias: Option<String>,
        /// Arguments to pass to the command
        args: Vec<String>,
    },

    /// Manage and set up project environments from a local zoi.yaml file
    #[command(
        long_about = "Checks for required packages and runs setup commands for a defined environment. If no environment is specified, it launches an interactive prompt."
    )]
    Env {
        /// The alias of the environment to set up
        env_alias: Option<String>,

        /// Export environment variables for the current shell
        #[arg(long, value_enum, hide = true)]
        export_shell: Option<Shell>,
    },

    /// Enter a development shell for the current project
    #[command(
        alias = "develop",
        long_about = "Loads the project configuration from zoi.yaml, ensures all required packages are installed locally, sets up environment variables (PATH, LD_LIBRARY_PATH, etc.), and drops you into a subshell."
    )]
    Dev {
        /// Command to run in the dev shell instead of an interactive shell
        #[arg(short, long)]
        run: Option<String>,
        /// Temporary clone a repository and enter its development shell
        #[arg(long)]
        repo: Option<String>,
    },

    /// Upgrades the Zoi binary to the latest version
    #[command(
        alias = "ug",
        long_about = "Upgrades Zoi to the latest version. By default, it attempts a delta upgrade (bsdiff) to minimize download size. If the delta upgrade is unavailable or fails, it automatically falls back to a full download."
    )]
    Upgrade {
        /// Force a full download instead of a delta upgrade
        #[arg(long)]
        force: bool,

        /// Upgrade to a specific git tag
        #[arg(long)]
        tag: Option<String>,

        /// Upgrade to the latest release of a specific branch (e.g. Prod, Pub)
        #[arg(long)]
        branch: Option<String>,
    },

    /// Removes packages that were installed as dependencies but are no longer needed
    Autoremove {
        /// Do not actually remove packages, just show what would be done
        #[arg(long)]
        dry_run: bool,
    },

    /// Explains why a package is installed
    Why {
        #[arg(value_name = "INST_PACKAGES", help = PKG_SOURCE_HELP)]
        package_name: String,
    },

    /// Find which package owns a file
    #[command(alias = "owns")]
    Owner {
        /// Path to the file
        #[arg(value_hint = ValueHint::FilePath)]
        path: std::path::PathBuf,
    },

    /// List all files owned by a package
    Files {
        #[arg(value_name = "INST_PACKAGES", help = PKG_SOURCE_HELP)]
        package: String,
    },

    /// Shows the history of package operations
    History {
        /// Verify audit log chain integrity instead of printing history entries
        #[arg(long, conflicts_with = "export")]
        verify: bool,
        /// Export audit history to a file (default format: JSON array with chain fields)
        #[arg(long, value_hint = ValueHint::FilePath, conflicts_with = "verify")]
        export: Option<std::path::PathBuf>,
        /// Export in newline-delimited JSON (ndjson) instead of a JSON array
        #[arg(long, requires = "export")]
        ndjson: bool,
    },

    /// Searches for packages by name or description
    #[command(
        alias = "s",
        long_about = "Searches for a case-insensitive term in the name, description, and tags of all available packages in the database. Filter by repo, type, or tags."
    )]
    Search {
        /// The term to search for (e.g. 'editor', 'cli')
        search_term: String,
        /// Filter by registry handle (e.g. 'zoidberg')
        #[arg(long)]
        registry: Option<String>,
        /// Filter by repository (e.g. 'main', 'extra')
        #[arg(long)]
        repo: Option<String>,
        /// Filter by package type (package, app, collection, extension)
        #[arg(long = "type")]
        package_type: Option<String>,
        /// Filter by tags (any match). Multiple via comma or repeated -t
        #[arg(short = 't', long = "tag", value_delimiter = ',', num_args = 1..)]
        tags: Option<Vec<String>>,
        /// Sort results by field (name, repo, type)
        #[arg(long, default_value = "name")]
        sort: String,
        /// Search for files provided by packages instead of package names
        #[arg(short, long)]
        files: bool,
        /// Open results in an interactive TUI
        #[arg(short = 'i', long)]
        interactive: bool,
    },

    /// Manage background services for installed packages
    #[command(alias = "svc")]
    Service(cmd::service::ServiceCommand),

    /// Set up shell completions or enter an ephemeral environment with specific packages
    #[command(
        long_about = "If a shell is provided, it installs completion scripts. If 'hook' is provided, it outputs shell-specific hook scripts for auto-activation. If packages are provided via --package/-p, it enters a temporary subshell with those packages available in PATH.",
        arg_required_else_help = true,
        group(clap::ArgGroup::new("shell_action").required(true).args(["shell", "hook", "packages"]).multiple(true))
    )]
    Shell {
        /// The shell to set up completions for
        #[arg(value_enum)]
        shell: Option<Shell>,
        /// Generate a shell hook for automatic environment activation
        #[arg(long)]
        hook: bool,
        /// The scope to apply the setup to (user or system-wide)
        #[arg(long, value_enum, default_value = "user")]
        scope: SetupScope,
        /// Packages to include in the ephemeral environment
        #[arg(short, long = "package", value_name = "ALL_PACKAGES")]
        packages: Vec<String>,
        /// Command to run in the ephemeral environment instead of an interactive shell
        #[arg(short, long)]
        run: Option<String>,
        /// Show additional details (resolution, installation progress, etc.)
        #[arg(long, short)]
        verbose: bool,
    },

    /// Execute a package binary directly with its dependencies resolved
    #[command(
        alias = "x",
        long_about = "Resolves a package and its dependencies, installs them if needed, then runs the requested binary directly. By default runs the first binary the package provides. Uses bwrap for sandboxed packages."
    )]
    Exec {
        #[arg(value_name = "ALL_SOURCES", help = PKG_SOURCE_HELP)]
        source: String,

        /// Specific binary to run (required if package provides multiple binaries)
        #[arg(long)]
        bin: Option<String>,

        /// Show additional execution details
        #[arg(long, short)]
        verbose: bool,

        /// Arguments to pass to the executed binary
        #[arg(value_name = "ARGS")]
        args: Vec<String>,
    },

    /// Clears the cache of downloaded package binaries
    Clean {
        /// Do not actually clear the cache, just show what would be done
        #[arg(long)]
        dry_run: bool,
    },

    /// Clones the git repository of a package
    Clone {
        /// The package identifier (e.g. @repo/name, path, or URL)
        #[arg(value_name = "ALL_PACKAGES", required = true, help = PKG_SOURCE_HELP)]
        package: String,
        /// The location to clone the repository to
        #[arg(value_name = "LOCATION")]
        location: Option<String>,
    },

    /// Manage Zoi's local cache
    Cache {
        #[command(subcommand)]
        command: CacheCommands,
    },

    /// Inspect recorded transactions
    #[command(alias = "tx")]
    Transaction {
        #[command(subcommand)]
        command: TransactionCommands,
    },

    /// Manage and author Zoi registries
    #[command(alias = "reg")]
    Registry(cmd::registry::RegistryCommand),

    /// Manage declarative user environments (ZoiOS only)
    Home(cmd::home::HomeCommand),

    /// Manage the underlying ZoiOS system (ZoiOS only)
    System(cmd::system::SystemCommand),

    /// Manage package repositories
    #[command(
        aliases = ["repositories"],
        long_about = "Manages the list of package repositories used by Zoi.\n\nCommands:\n- add (alias: a): Add an official repo by name or clone from a git URL.\n- remove|rm: Remove a repo from active list (repo rm <name>).\n- list|ls: Show active repositories by default; use 'list all' to show all available repositories.\n- git: Manage cloned git repositories (git ls, git rm <repo-name>)."
    )]
    Repo(cmd::repo::RepoCommand),

    /// Manage telemetry settings (opt-in analytics)
    #[command(
        long_about = "Manage opt-in anonymous telemetry used to understand package popularity. Default is disabled."
    )]
    Telemetry {
        #[arg(value_enum)]
        action: TelemetryAction,
    },

    /// Create an application using a package template
    Create {
        #[arg(value_name = "ALL_SOURCES", help = PKG_SOURCE_HELP)]
        source: String,
        /// The application name to substitute into template commands
        app_name: Option<String>,
    },

    /// Downgrade a package to a specific version from local cache or store
    #[command(
        alias = "dg",
        long_about = "Interactively choose and install an older version of a package from the local store or archive cache. This is useful if a recent update has introduced bugs or compatibility issues."
    )]
    Downgrade {
        #[arg(value_name = "INST_PACKAGES", help = PKG_SOURCE_HELP)]
        package: String,
    },

    /// Manage Zoi extensions
    #[command(alias = "ext")]
    Extension(ExtensionCommand),

    /// Rollback a package to the previously installed version
    Rollback {
        #[arg(value_name = "INST_PACKAGES", required_unless_present = "last_transaction", help = PKG_SOURCE_HELP)]
        package: Option<String>,

        /// Rollback the last transaction
        #[arg(long, conflicts_with = "package")]
        last_transaction: bool,
    },

    /// Shows a package's manual
    Man {
        #[arg(value_name = "ALL_PACKAGES", help = PKG_SOURCE_HELP)]
        package_name: String,
        /// Always look at the upstream manual even if it's downloaded
        #[arg(long)]
        upstream: bool,
        /// Print the manual to the terminal raw
        #[arg(long)]
        raw: bool,
        /// Do not use the TUI, use the system pager instead
        #[arg(long)]
        no_tui: bool,
    },

    /// Build, create, and manage Zoi packages
    #[command(alias = "pkg")]
    Package(cmd::package::PackageCommand),

    /// Manage PGP keys for package signature verification
    Pgp(cmd::pgp::PgpCommand),

    /// Helper commands for various tasks
    Helper(cmd::helper::HelperCommand),

    /// Checks for common issues and provides actionable suggestions
    Doctor,

    /// Audit installed or all packages for security vulnerabilities
    Audit {
        /// Show all vulnerabilities from the database, not just for installed packages
        #[arg(short, long)]
        all: bool,
        /// Filter by registry handle
        #[arg(long)]
        registry: Option<String>,
        /// Filter by repository
        #[arg(long)]
        repo: Option<String>,
    },

    #[command(external_subcommand)]
    External(Vec<String>),
}

#[derive(clap::Parser, Debug)]
pub struct ExtensionCommand {
    #[command(subcommand)]
    pub command: ExtensionCommands,
}

#[derive(clap::Subcommand, Debug)]
pub enum ExtensionCommands {
    /// Add an extension
    Add {
        /// The name of the extension to add
        #[arg(required = true)]
        name: String,
    },
    /// Remove an extension
    Remove {
        /// The name of the extension to remove
        #[arg(required = true)]
        name: String,
    },
}

#[derive(clap::Subcommand, Clone)]
pub enum SyncCommands {
    /// Add a new registry
    Add {
        /// URL of the registry to add
        url: String,
    },
    /// Remove a configured registry by its handle
    Remove {
        /// Handle of the registry to remove
        handle: String,
    },
    /// List configured registries
    #[command(alias = "ls")]
    List,
    /// Set the default registry URL
    Set {
        /// URL or keyword (default, github, gitlab, codeberg)
        url: String,
    },
}

#[derive(clap::Subcommand)]
pub enum CacheCommands {
    /// Add package archive(s) to the local cache
    Add {
        /// Path to the .zpa archive(s)
        #[arg(required = true)]
        files: Vec<std::path::PathBuf>,
    },
    /// Clear the local cache
    #[command(alias = "clean")]
    Clear {
        /// Do not actually clear the cache, just show what would be done
        #[arg(long)]
        dry_run: bool,
    },
    /// List all archives currently in the cache
    #[command(alias = "ls")]
    List,
    /// Manage cache mirrors used for archive downloads
    Mirror {
        #[command(subcommand)]
        command: CacheMirrorCommands,
    },
}

#[derive(clap::Subcommand)]
pub enum CacheMirrorCommands {
    /// Add a cache mirror base URL
    Add {
        /// Mirror base URL
        url: String,
    },
    /// Remove a cache mirror base URL
    Remove {
        /// Mirror base URL
        url: String,
    },
    /// List configured cache mirrors
    #[command(alias = "ls")]
    List,
}

#[derive(clap::Subcommand)]
pub enum TransactionCommands {
    /// List known transaction logs
    #[command(alias = "ls")]
    List,
    /// Show details for a transaction
    Show {
        /// Transaction ID
        id: String,
    },
    /// List modified files for a transaction
    Files {
        /// Transaction ID
        id: String,
    },
}

#[derive(clap::ValueEnum, Clone)]
enum TelemetryAction {
    Status,
    Enable,
    Disable,
}

pub fn run() -> anyhow::Result<()> {
    let styles = styling::Styles::styled()
        .header(styling::AnsiColor::Yellow.on_default() | styling::Effects::BOLD)
        .usage(styling::AnsiColor::Green.on_default() | styling::Effects::BOLD)
        .literal(styling::AnsiColor::Green.on_default())
        .placeholder(styling::AnsiColor::Cyan.on_default());

    let commit: &str = option_env!("ZOI_COMMIT_HASH").unwrap_or("dev");
    let cmd = Cli::command().styles(styles.clone());
    let matches = cmd.clone().get_matches();
    let cli = match Cli::from_arg_matches(&matches) {
        Ok(cli) => cli,
        Err(err) => {
            err.print()?;
            return Err(anyhow::anyhow!("Failed to parse arguments"));
        }
    };

    if let Some(root) = cli.root {
        crate::pkg::sysroot::set_sysroot(root);
    }

    let config = crate::pkg::config::read_config().unwrap_or_default();

    let is_offline = cli.offline || config.offline_mode;
    crate::pkg::offline::set_offline(is_offline);

    let mut all_pkg_dirs = cli.pkg_dirs;
    for dir in config.pkg_dirs {
        let path = std::path::PathBuf::from(dir);
        if !all_pkg_dirs.contains(&path) {
            all_pkg_dirs.push(path);
        }
    }
    crate::pkg::pkgdir::set_pkg_dirs(all_pkg_dirs);

    utils::check_path();

    if let Err(e) = crate::pkg::pgp::ensure_builtin_keys() {
        eprintln!(
            "{}: Failed to ensure builtin PGP keys: {}",
            "Warning".yellow(),
            e
        );
    }

    let plugin_manager = crate::pkg::plugin::PluginManager::new()?;
    if let Err(e) = plugin_manager.load_all(cli.yes) {
        eprintln!("{}: Failed to load plugins: {}", "Warning".yellow(), e);
    }

    if cli.version_flag {
        cmd::version::run(BRANCH, STATUS, NUMBER, commit);
        return Ok(());
    }

    if let Some(command) = cli.command {
        let needs_lock = matches!(
            command,
            Commands::Install { .. }
                | Commands::Uninstall { .. }
                | Commands::Update { .. }
                | Commands::Autoremove { .. }
                | Commands::Rollback { .. }
                | Commands::Package(_)
        );

        let _lock_guard = if needs_lock {
            Some(lock::acquire_lock()?)
        } else {
            None
        };

        let result = match command {
            Commands::GenerateCompletions { shell } => {
                let mut cmd = Cli::command();
                let bin_name = cmd.get_name().to_string();
                generate(shell, &mut cmd, bin_name, &mut io::stdout());
                Ok(())
            }
            Commands::Complete {
                shell,
                index,
                words,
            } => cmd::complete::run(shell, index, words),
            Commands::GenerateManual => cmd::gen_man::run().map_err(Into::into),
            Commands::Version => {
                cmd::version::run(BRANCH, STATUS, NUMBER, commit);
                Ok(())
            }
            Commands::About => {
                cmd::about::run(BRANCH, STATUS, NUMBER, commit);
                Ok(())
            }
            Commands::Info => cmd::info::run(BRANCH, STATUS, NUMBER, commit),
            Commands::Sync {
                command,
                verbose,
                fallback,
                no_package_managers,
                force,
                local,
                frozen,
                scope,
            } => {
                if let Some(cmd) = command {
                    match cmd {
                        SyncCommands::Add { url } => cmd::sync::add_registry(&url),
                        SyncCommands::Remove { handle } => cmd::sync::remove_registry(&handle),
                        SyncCommands::List => cmd::sync::list_registries(),
                        SyncCommands::Set { url } => cmd::sync::set_registry(&url),
                    }
                } else if local {
                    plugin_manager.trigger_hook("on_pre_sync", None)?;
                    let res = cmd::sync::run_local(verbose, fallback, force, frozen);
                    plugin_manager.trigger_hook_nonfatal("on_post_sync", None);
                    res
                } else {
                    plugin_manager.trigger_hook("on_pre_sync", None)?;
                    let res = cmd::sync::run(verbose, fallback, no_package_managers, force, scope);
                    plugin_manager.trigger_hook_nonfatal("on_post_sync", None);
                    res
                }
            }
            Commands::Migrate(args) => cmd::migrate::run(args),
            Commands::List {
                all,
                outdated,
                registry,
                repo,
                package_type,
                foreign,
                names,
                completion,
            } => cmd::list::run(
                all,
                outdated,
                registry,
                repo,
                package_type,
                foreign,
                names,
                completion,
            ),
            Commands::Show {
                package_name,
                raw,
                purl,
            } => cmd::show::run(&package_name, raw, purl),
            Commands::Pin { package, version } => cmd::pin::run(&package, &version),
            Commands::Provides { term } => cmd::provides::run(&term),
            Commands::Tree { packages } => cmd::tree::run(&packages),
            Commands::Unpin { package } => cmd::unpin::run(&package),
            Commands::Mark {
                packages,
                as_dependency,
                as_explicit,
            } => cmd::mark::run(&packages, as_dependency, as_explicit),
            Commands::Update {
                package_names,
                all,
                dry_run,
                explain,
                plan_json,
                interactive,
            } => cmd::update::run(
                all,
                &package_names,
                cli.yes,
                dry_run,
                explain,
                plan_json,
                interactive,
            )
            .map_err(|e| cmd::ux::with_failure_hint("update", e)),
            Commands::Install {
                sources,
                repo,
                force,
                all_optional,
                scope,
                local,
                global,
                save,
                r#type,
                dry_run,
                build,
                frozen,
                explain,
                plan_json,
                retry,
                verbose,
                purl,
            } => cmd::install::run(
                &sources,
                repo,
                force,
                all_optional,
                cli.yes,
                scope,
                local,
                global,
                save,
                r#type,
                dry_run,
                Some(&plugin_manager),
                build,
                frozen,
                explain,
                plan_json,
                retry,
                verbose,
                purl,
                None,
            )
            .map_err(|e| cmd::ux::with_failure_hint("install", e)),
            Commands::Use { packages, global } => cmd::use_cmd::run(packages, global),
            Commands::Uninstall {
                packages,
                scope,
                local,
                global,
                save,
                recursive,
                dry_run,
                explain,
                plan_json,
            } => cmd::uninstall::run(
                &packages,
                scope,
                local,
                global,
                save,
                cli.yes,
                recursive,
                Some(&plugin_manager),
                explain,
                plan_json,
                dry_run,
            )
            .map_err(|e| cmd::ux::with_failure_hint("uninstall", e)),
            Commands::Run { cmd_alias, args } => cmd::run::run(cmd_alias, args),
            Commands::Env {
                env_alias,
                export_shell,
            } => cmd::env::run(env_alias, export_shell),
            Commands::Dev { run, repo } => cmd::dev::run(run, repo),
            Commands::Upgrade { force, tag, branch } => {
                match cmd::upgrade::run(BRANCH, STATUS, NUMBER, force, tag, branch) {
                    Ok(()) => {
                        println!(
                            "\n{}",
                            "Zoi upgraded successfully! Please restart your shell for changes to take effect."
                                .green()
                        );
                        println!(
                            "\n{}: https://github.com/zillowe/zoi/blob/main/CHANGELOG.md",
                            "Changelog".cyan().bold()
                        );
                        println!(
                            "\n{}: To update shell completions, run 'zoi shell <your-shell>'.",
                            "Hint".cyan().bold()
                        );
                    }
                    Err(e) if e.to_string() == "already_on_latest" => {}
                    Err(e) if e.to_string() == "managed_by_package_manager" => {}
                    Err(e) => return Err(e),
                }
                Ok(())
            }
            Commands::Autoremove { dry_run } => cmd::autoremove::run(cli.yes, dry_run),
            Commands::Why { package_name } => cmd::why::run(&package_name),
            Commands::Owner { path } => cmd::owner::run(&path),
            Commands::Files { package } => cmd::files::run(&package),
            Commands::History {
                verify,
                export,
                ndjson,
            } => cmd::history::run(verify, export, ndjson),
            Commands::Search {
                search_term,
                registry,
                repo,
                package_type,
                tags,
                sort,
                files,
                interactive,
            } => cmd::search::run(
                search_term,
                registry,
                repo,
                package_type,
                tags,
                sort,
                files,
                interactive,
            ),
            Commands::Service(args) => cmd::service::run(args),
            Commands::Shell {
                shell,
                hook,
                scope,
                packages,
                run,
                verbose,
            } => {
                let target_shell = shell
                    .or_else(crate::pkg::utils::get_current_shell)
                    .unwrap_or(Shell::Bash);
                if hook {
                    cmd::shell::print_hook(target_shell)
                } else if !packages.is_empty() {
                    cmd::shell::enter_ephemeral_shell(
                        &packages,
                        run,
                        verbose,
                        Some(&plugin_manager),
                    )
                } else {
                    cmd::shell::run(target_shell, scope)
                }
            }
            Commands::Exec {
                source,
                bin,
                verbose,
                args,
            } => cmd::exec::run(source, bin, args, verbose),
            Commands::Download {
                package,
                archive: _,
                source,
                output_dir,
            } => {
                let download_type = if source {
                    cmd::download::DownloadType::Source
                } else {
                    cmd::download::DownloadType::Archive
                };
                cmd::download::run(package, download_type, output_dir)
            }
            Commands::Clean { dry_run } => cmd::clean::run(dry_run),
            Commands::Clone { package, location } => cmd::clone::run(&package, location, cli.yes),
            Commands::Cache { command } => match command {
                CacheCommands::Add { files } => cmd::cache::add(&files),
                CacheCommands::Clear { dry_run } => cmd::cache::clear(dry_run),
                CacheCommands::List => cmd::cache::list(),
                CacheCommands::Mirror { command } => match command {
                    CacheMirrorCommands::Add { url } => cmd::cache::add_mirror(&url),
                    CacheMirrorCommands::Remove { url } => cmd::cache::remove_mirror(&url),
                    CacheMirrorCommands::List => cmd::cache::list_mirrors(),
                },
            },
            Commands::Transaction { command } => match command {
                TransactionCommands::List => cmd::transaction::list(),
                TransactionCommands::Show { id } => cmd::transaction::show(&id),
                TransactionCommands::Files { id } => cmd::transaction::files(&id),
            },
            Commands::Repo(args) => cmd::repo::run(args),
            Commands::Registry(args) => cmd::registry::run(args),
            Commands::Home(args) => cmd::home::run(args),
            Commands::System(args) => cmd::system::run(args, cli.yes),
            Commands::Telemetry { action } => {
                use cmd::telemetry::{TelemetryCommand, run};
                let cmd = match action {
                    TelemetryAction::Status => TelemetryCommand::Status,
                    TelemetryAction::Enable => TelemetryCommand::Enable,
                    TelemetryAction::Disable => TelemetryCommand::Disable,
                };
                run(cmd)
            }
            Commands::Create { source, app_name } => cmd::create::run(
                cmd::create::CreateCommand { source, app_name },
                cli.yes,
                Some(&plugin_manager),
            ),
            Commands::Downgrade { package } => {
                cmd::downgrade::run(&package, cli.yes, Some(&plugin_manager))
            }
            Commands::Extension(args) => cmd::extension::run(args, cli.yes, Some(&plugin_manager)),
            Commands::Rollback {
                package,
                last_transaction,
            } => {
                if last_transaction {
                    cmd::rollback::run_transaction_rollback(cli.yes, Some(&plugin_manager))
                } else if let Some(pkg) = package {
                    cmd::rollback::run(&pkg, cli.yes, Some(&plugin_manager))
                } else {
                    Ok(())
                }
            }
            Commands::Man {
                package_name,
                upstream,
                raw,
                no_tui,
            } => cmd::man::run(&package_name, upstream, raw, no_tui),
            Commands::Package(args) => cmd::package::run(args),
            Commands::Pgp(args) => cmd::pgp::run(args),
            Commands::Helper(args) => cmd::helper::run(args),
            Commands::Doctor => cmd::doctor::run(),
            Commands::Audit {
                all,
                registry,
                repo,
            } => cmd::audit::run(all, registry, repo),
            Commands::External(args) => {
                let (cmd_name, cmd_args) = if args.is_empty() {
                    return Err(anyhow::anyhow!("No command specified"));
                } else {
                    (&args[0], args[1..].to_vec())
                };

                match plugin_manager.run_command(cmd_name, cmd_args) {
                    Ok(true) => Ok(()),
                    Ok(false) => {
                        let mut shadow_cmd = Cli::command().styles(styles);
                        shadow_cmd = shadow_cmd.allow_external_subcommands(false);

                        let err = shadow_cmd
                            .clone()
                            .try_get_matches_from(std::env::args())
                            .err()
                            .unwrap_or_else(|| {
                                shadow_cmd.error(
                                    clap::error::ErrorKind::InvalidSubcommand,
                                    format!("unrecognized subcommand '{}'", cmd_name),
                                )
                            });

                        let plugin_cmds = plugin_manager.list_commands()?;
                        if !plugin_cmds.is_empty() {
                            eprintln!("{}:", "Available Plugin Commands".cyan().bold());
                            for (pcmd, pdesc) in plugin_cmds {
                                if pdesc.is_empty() {
                                    eprintln!("  {}", pcmd);
                                } else {
                                    eprintln!("  {:<12} {}", pcmd, pdesc.dimmed());
                                }
                            }
                            eprintln!();
                        }

                        err.exit();
                    }
                    Err(e) => Err(e),
                }
            }
        };

        if let Err(e) = result {
            eprintln!("Error: {}", e);
            std::process::exit(1);
        }
    }
    Ok(())
}