a4-cli 0.9.1

CLI tool for generating TypeScript SDKs from Arete stream specifications
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
//! # a4-cli
//!
//! Command-line tool for building, deploying, and managing Arete
//! stream stacks.
//!
//! ## Installation
//!
//! ```bash
//! cargo install a4-cli
//! ```
//!
//! ## Commands
//!
//! - `a4 init` - Initialize configuration
//! - `a4 up [stack]` - Deploy a stack (push + build + deploy)
//! - `a4 stack list` - List all stacks
//! - `a4 stack show` - Show stack details
//! - `a4 sdk create` - Generate TypeScript/Rust/Python SDK
//! - `a4 install` - Generate TypeScript/Rust/Python SDK from a hosted stack
//!
//! See `a4 --help` for the full command reference.

use clap::{Args, CommandFactory, Parser, Subcommand};
use clap_complete::{generate, Shell};
use colored::Colorize;
use std::io;
use std::process;

mod api_client;
mod commands;
mod config;
mod telemetry;
mod templates;
mod ui;

#[derive(Parser)]
#[command(name = "a4")]
#[command(about = "Arete CLI - Build, deploy, and manage stream stacks", long_about = None)]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,

    /// Path to arete.toml configuration file
    #[arg(short, long, global = true, default_value = "arete.toml")]
    config: String,

    /// Output as JSON (machine-readable format)
    #[arg(long, global = true)]
    json: bool,

    /// Enable verbose output
    #[arg(long, global = true)]
    verbose: bool,

    /// API URL to use (overrides ARETE_API_URL env var)
    #[arg(long, global = true, env = "ARETE_API_URL")]
    api_url: Option<String>,

    /// Generate shell completions
    #[arg(long, value_name = "SHELL")]
    completions: Option<Shell>,
}

#[derive(Subcommand)]
enum Commands {
    /// Create a new Arete project from a template
    Create {
        /// Project name (creates directory)
        name: Option<String>,

        /// Template: react-ore, rust-ore, typescript-ore, python-ore
        #[arg(short, long)]
        template: Option<String>,

        /// Use cached templates only (no network)
        #[arg(long)]
        offline: bool,

        /// Force re-download templates even if cached
        #[arg(long)]
        force_refresh: bool,

        /// Skip installing dependencies
        #[arg(long)]
        skip_install: bool,
    },

    /// Initialize a new Arete project (auto-detects stack files)
    Init,

    /// Deploy a stack: push, build, and watch until completion
    Up {
        /// Name of specific stack to deploy (deploys all if not specified)
        stack_name: Option<String>,

        /// Deploy to a specific branch (creates {stack-name}-{branch}.stack.arete.run)
        #[arg(short, long)]
        branch: Option<String>,

        /// Create a preview deployment with auto-generated branch name
        #[arg(long, conflicts_with = "branch")]
        preview: bool,

        /// Show what would be deployed without actually deploying
        #[arg(long)]
        dry_run: bool,

        /// Plan only from local artifacts; requires --dry-run and skips server checks
        #[arg(long, requires = "dry_run")]
        local_only: bool,
    },

    /// Show overview of stacks, builds, and deployments
    Status,

    /// Discover installable stacks and programs through pinned descriptors
    Explore {
        /// `stack`, `program`, `programs`, or a legacy stack reference
        target: Option<String>,

        /// Resource reference, or an entity for legacy `explore <stack> <entity>`
        reference: Option<String>,

        /// Entity for explicit `explore stack <ref> <entity>` drill-down
        entity: Option<String>,
    },

    /// Push local stacks to remote (alias for 'stack push')
    Push {
        /// Name of specific stack to push (pushes all if not specified)
        stack_name: Option<String>,
    },

    /// Generate a TypeScript, Rust, or Python SDK from a hosted stack
    Install {
        /// Hosted stack identifier, or the reserved install target `program`
        target: String,

        /// Program install identifier when using `a4 install program <program>`
        install_name: Option<String>,

        /// Generate a TypeScript SDK
        #[arg(long, conflicts_with_all = ["rust", "python"])]
        ts: bool,

        /// Generate a Rust SDK
        #[arg(long, conflicts_with_all = ["ts", "python"])]
        rust: bool,

        /// Generate a Python SDK
        #[arg(long, conflicts_with_all = ["ts", "rust"])]
        python: bool,

        /// Output path (file for TypeScript, directory for Rust or Python)
        #[arg(short, long)]
        output: Option<String>,

        /// Package name for TypeScript imports, or the generated Python distribution
        #[arg(short, long)]
        package_name: Option<String>,

        /// Crate name for generated Rust crate
        #[arg(long)]
        crate_name: Option<String>,

        /// Generate Rust (mod.rs) or Python as a module instead of a standalone crate/package
        #[arg(long)]
        module: bool,

        /// WebSocket URL for the stack
        #[arg(long)]
        url: Option<String>,

        /// Local extensions artifact source (manifest file, entry file, or directory)
        #[arg(long)]
        extensions: Option<String>,
    },

    /// SDK generation commands
    #[command(subcommand)]
    Sdk(SdkCommands),

    /// Configuration management commands
    #[command(subcommand)]
    Config(ConfigCommands),

    /// Authentication commands
    #[command(subcommand)]
    Auth(AuthCommands),

    /// Stack management commands - manage your deployed stacks
    #[command(subcommand)]
    Stack(StackCommands),

    /// Build and validate portable live artifacts
    #[command(subcommand)]
    Live(LiveCommands),

    /// Build and validate portable program artifacts
    #[command(subcommand)]
    Program(ProgramCommands),

    /// Build commands (advanced) - low-level build management
    #[command(subcommand, hide = true)]
    Build(BuildCommands),

    /// Manage anonymous usage telemetry
    #[command(subcommand)]
    Telemetry(TelemetryCommands),

    /// Inspect and analyze Anchor/Shank IDL files
    Idl(commands::idl::IdlArgs),

    /// Stream live entity data from a deployed stack via WebSocket
    Stream(commands::stream::StreamArgs),
}

#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)] // Clap owns this short-lived command value.
enum SdkCommands {
    /// Create SDK from a stack
    Create(SdkCreateArgs),

    /// Regenerate SDKs for every configured stack
    Sync(SdkSyncArgs),

    /// List all available stacks from arete.toml
    List,
}

#[derive(Args)]
struct SdkCreateArgs {
    /// Name of the stack to generate SDK for
    #[arg(
        required_unless_present_any = ["idl", "program_spec", "manifest"],
        conflicts_with_all = ["idl", "program_spec", "manifest"]
    )]
    stack_name: Option<String>,

    /// Generate a TypeScript SDK
    #[arg(long, conflicts_with_all = ["rust", "python"])]
    ts: bool,

    /// Generate a Rust SDK
    #[arg(long, conflicts_with_all = ["ts", "python"])]
    rust: bool,

    /// Generate a Python SDK
    #[arg(long, conflicts_with_all = ["ts", "rust"])]
    python: bool,

    /// Output path (file for TypeScript, directory for Rust or Python)
    #[arg(short, long)]
    output: Option<String>,

    /// Package name for TypeScript imports, or the generated Python distribution
    #[arg(short, long)]
    package_name: Option<String>,

    /// Crate name for generated Rust crate
    #[arg(long)]
    crate_name: Option<String>,

    /// Generate Rust (mod.rs) or Python as a module instead of a standalone crate/package
    #[arg(long)]
    module: bool,

    /// WebSocket URL for the stack (overrides config)
    #[arg(long)]
    url: Option<String>,

    /// Local extensions artifact source (manifest file, entry file, or directory)
    #[arg(long)]
    extensions: Option<String>,

    /// Raw IDL file to generate a standalone program SDK from (TypeScript + --program-only only)
    #[arg(
        long,
        requires = "program_only",
        conflicts_with_all = ["stack_name", "program_spec", "manifest"]
    )]
    idl: Option<String>,

    /// Local ProgramSpec artifact to generate a standalone program SDK from
    #[arg(
        long,
        requires = "program_only",
        conflicts_with_all = ["stack_name", "idl", "manifest"]
    )]
    program_spec: Option<String>,

    /// Local StackManifest artifact; dependencies default to its directory
    #[arg(
        long,
        conflicts_with_all = ["stack_name", "idl", "program_spec", "program_only"]
    )]
    manifest: Option<String>,

    /// Approved recursive artifact search root; repeat for dependencies outside the manifest directory
    #[arg(long, requires = "manifest")]
    artifact_dir: Vec<String>,

    /// Existing aliased live SDK import (`alias=./path.js`); repeat for composed manifests
    #[arg(long, requires = "manifest")]
    live_module: Vec<String>,

    /// Existing independent program SDK import (`alias=./path.js`); repeat for composed manifests
    #[arg(long, requires = "manifest")]
    program_module: Vec<String>,

    /// Emit a standalone program-SDK module (pdas/accounts/instructions, no
    /// views or stack const). TypeScript only.
    #[arg(long, conflicts_with_all = ["rust", "python"])]
    program_only: bool,
}

#[derive(Args)]
struct SdkSyncArgs {
    /// Sync TypeScript SDKs only
    #[arg(long, conflicts_with_all = ["rust", "python"])]
    ts: bool,

    /// Sync Rust SDKs only
    #[arg(long, conflicts_with_all = ["ts", "python"])]
    rust: bool,

    /// Sync Python SDKs only
    #[arg(long, conflicts_with_all = ["ts", "rust"])]
    python: bool,

    /// Limit sync to one or more configured stack names
    #[arg(long = "stack", short = 's')]
    stacks: Vec<String>,
}

#[derive(Subcommand)]
enum ConfigCommands {
    /// Validate the configuration file
    Validate,
}

#[derive(Subcommand)]
enum AuthCommands {
    /// Login with your API key
    Login {
        /// API key (prompts if not provided)
        #[arg(short, long)]
        key: Option<String>,
    },

    /// Logout (remove stored credentials for current environment)
    Logout,

    /// Logout from all environments (remove all stored credentials)
    LogoutAll,

    /// Check authentication status (shows current environment and all stored credentials)
    Status,

    /// Verify authentication and show user info
    Whoami,

    /// Manage API keys for browser/client use
    #[command(subcommand)]
    Keys(KeysCommands),
}

#[derive(Subcommand)]
enum KeysCommands {
    /// List all your API keys
    List,

    /// Create a new publishable API key for browser/client use
    CreatePublishable {
        /// Name for the key (optional)
        #[arg(short, long)]
        name: Option<String>,

        /// Allowed origins (e.g., https://example.com or http://localhost:5173)
        /// Can specify multiple: --origin https://app.com --origin https://www.app.com
        #[arg(short, long, required = true, num_args = 1..)]
        origin: Vec<String>,

        /// Number of days until the key expires (default: 365)
        #[arg(short, long)]
        expiry_days: Option<i64>,
    },
}

#[derive(Subcommand)]
enum StackCommands {
    /// Compose ProgramSpecs and LiveSpecs into a portable StackManifest
    Compose {
        /// Client-facing stack name
        #[arg(long)]
        name: String,

        /// ProgramSpec artifact path; repeat for each program
        #[arg(long = "program")]
        programs: Vec<String>,

        /// Aliased LiveSpec artifact (`alias=path`); repeat to compose live packages
        #[arg(long = "live")]
        live_specs: Vec<String>,

        /// Approved recursive artifact search root; repeat for multiple roots
        #[arg(long = "artifact-dir")]
        artifact_dirs: Vec<String>,

        /// Selected client view (`alias=view_id`); repeat for an exact ordered allowlist
        #[arg(long = "selected-view")]
        selected_views: Vec<String>,

        /// StackManifest output path
        #[arg(short, long)]
        output: String,
    },

    /// List all stacks with their deployment status
    List,

    /// Push local stacks with their stack file to remote
    Push {
        /// Name of specific stack to push (pushes all if not specified)
        stack_name: Option<String>,
    },

    /// Show detailed stack information including deployment status and versions
    Show {
        /// Name of the stack
        stack_name: String,

        /// Show specific version details
        #[arg(short, long)]
        version: Option<i32>,
    },

    /// Show version history for a stack
    Versions {
        /// Name of the stack
        stack_name: String,

        /// Maximum number of versions to show
        #[arg(short, long, default_value = "20")]
        limit: i64,
    },

    /// Delete a stack from remote
    Delete {
        /// Name of the stack to delete
        stack_name: String,

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

    /// Rollback to a previous deployment
    Rollback {
        /// Name of the stack to rollback
        stack_name: String,

        /// Rollback to specific version number (uses previous successful if not specified)
        #[arg(long)]
        to: Option<i32>,

        /// Rollback to specific build ID
        #[arg(long)]
        build: Option<i32>,

        /// Branch deployment to rollback (default: production)
        #[arg(long, default_value = "production")]
        branch: String,

        /// Force full rebuild instead of using existing image
        #[arg(long)]
        rebuild: bool,

        /// Don't watch the rollback progress
        #[arg(long)]
        no_wait: bool,
    },

    /// Stop a deployment
    Stop {
        /// Name of the stack to stop
        stack_name: String,

        /// Branch deployment to stop (default: production)
        #[arg(long)]
        branch: Option<String>,

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

#[derive(Subcommand)]
enum LiveCommands {
    /// Normalize a supported legacy stack into LiveSpec and ProgramSpec artifacts
    Build {
        /// Legacy .stack.json input
        input: String,

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

        /// Directory for ProgramSpec outputs
        #[arg(long)]
        program_dir: Option<String>,
    },
}

#[derive(Subcommand)]
enum ProgramCommands {
    /// Normalize an IDL into a portable ProgramSpec artifact
    Build {
        /// IDL JSON input
        input: String,

        /// ProgramSpec output path
        #[arg(short, long)]
        output: String,

        /// Program ID when the IDL does not declare one
        #[arg(long)]
        program_id: Option<String>,
    },
}

#[derive(Subcommand)]
enum TelemetryCommands {
    /// Show current telemetry status
    Status,

    /// Enable telemetry collection
    Enable,

    /// Disable telemetry collection
    Disable,
}

/// Build commands - advanced low-level build management
/// These are power-user commands; most users should use `a4 up` instead.
#[derive(Subcommand)]
enum BuildCommands {
    /// Create a new build from a stack (watches progress by default)
    Create {
        /// Name of the stack to build
        stack_name: String,

        /// Use specific version (default: latest)
        #[arg(short, long)]
        version: Option<i32>,

        /// Use local stack file directly instead of stack version
        #[arg(long)]
        ast_file: Option<String>,

        /// Don't wait for build to complete (return immediately)
        #[arg(long)]
        no_wait: bool,
    },

    /// List builds
    List {
        /// Maximum number of builds to show
        #[arg(short, long, default_value = "20")]
        limit: i64,

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

    /// Get detailed build status
    Status {
        /// Build ID
        build_id: i32,

        /// Watch build progress until completion
        #[arg(short, long)]
        watch: bool,

        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
}

fn main() {
    let cli = Cli::parse();

    // Set ARETE_API_URL env var if --api-url flag is provided
    // This ensures all ApiClient instances use the correct URL
    if let Some(ref api_url) = cli.api_url {
        std::env::set_var("ARETE_API_URL", api_url);
    }

    if let Some(shell) = cli.completions {
        let mut cmd = Cli::command();
        generate(shell, &mut cmd, "a4", &mut io::stdout());
        return;
    }

    telemetry::show_consent_banner_if_needed();

    let cmd_name = cli.command.as_ref().map(command_name).unwrap_or("help");
    let start = std::time::Instant::now();
    let result = run(cli);

    telemetry::record_command(
        cmd_name,
        result.is_ok(),
        result
            .as_ref()
            .err()
            .and_then(telemetry::extract_error_code)
            .as_deref(),
        start.elapsed(),
        None,
    );

    telemetry::flush();

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

fn command_name(cmd: &Commands) -> &'static str {
    match cmd {
        Commands::Create { .. } => "create",
        Commands::Init => "init",
        Commands::Up { .. } => "up",
        Commands::Status => "status",
        Commands::Explore { .. } => "explore",
        Commands::Push { .. } => "push",
        Commands::Install { .. } => "install",
        Commands::Sdk(_) => "sdk",
        Commands::Config(_) => "config",
        Commands::Auth(_) => "auth",
        Commands::Stack(_) => "stack",
        Commands::Live(_) => "live",
        Commands::Program(_) => "program",
        Commands::Build(_) => "build",
        Commands::Telemetry(_) => "telemetry",
        Commands::Idl(_) => "idl",
        Commands::Stream(_) => "stream",
    }
}

fn run(cli: Cli) -> anyhow::Result<()> {
    let Some(command) = cli.command else {
        Cli::command().print_help()?;
        return Ok(());
    };

    match command {
        Commands::Create {
            name,
            template,
            offline,
            force_refresh,
            skip_install,
        } => commands::create::create(name, template, offline, force_refresh, skip_install),
        Commands::Init => commands::config::init(&cli.config),
        Commands::Up {
            stack_name,
            branch,
            preview,
            dry_run,
            local_only,
        } => commands::up::up(
            &cli.config,
            stack_name.as_deref(),
            branch,
            preview,
            dry_run,
            local_only,
            cli.json,
        ),
        Commands::Status => commands::status::status(cli.json),
        Commands::Explore {
            target,
            reference,
            entity,
        } => match (target.as_deref(), reference.as_deref(), entity.as_deref()) {
            (None, None, None) => commands::explore::list(cli.json),
            (Some("programs"), None, None) => commands::explore::list_programs(cli.json),
            (Some("program"), Some(reference), None) => {
                commands::explore::show_program(reference, cli.json)
            }
            (Some("stack"), Some(reference), entity) => {
                commands::explore::show_stack(reference, entity, cli.json)
            }
            (Some("program"), None, None) => Err(anyhow::anyhow!(
                "Program reference required. Usage: a4 explore program <ref>"
            )),
            (Some("stack"), None, None) => Err(anyhow::anyhow!(
                "Stack reference required. Usage: a4 explore stack <ref>"
            )),
            (Some(stack), entity, None) => {
                commands::explore::show_stack(stack, entity, cli.json)
            }
            _ => Err(anyhow::anyhow!(
                "Invalid explore arguments. Use `a4 explore`, `a4 explore programs`, `a4 explore stack <ref>`, or `a4 explore program <ref>`."
            )),
        },
        Commands::Push { stack_name } => commands::stack::push(&cli.config, stack_name.as_deref()),
        Commands::Install {
            target,
            install_name,
            ts,
            rust,
            python,
            output,
            package_name,
            crate_name,
            module,
            url,
            extensions,
        } => commands::sdk::install_command(
            &target,
            install_name.as_deref(),
            ts,
            rust,
            python,
            output,
            package_name,
            crate_name,
            module,
            url,
            extensions,
        ),
        Commands::Sdk(sdk_cmd) => match sdk_cmd {
            SdkCommands::Create(create_args) => commands::sdk::create(
                &cli.config,
                create_args.stack_name.as_deref(),
                create_args.ts,
                create_args.rust,
                create_args.python,
                create_args.output,
                create_args.package_name,
                create_args.crate_name,
                create_args.module,
                create_args.url,
                create_args.extensions,
                create_args.idl,
                create_args.program_spec,
                create_args.manifest,
                create_args.artifact_dir,
                create_args.live_module,
                create_args.program_module,
                create_args.program_only,
            ),
            SdkCommands::Sync(sync_args) => commands::sdk::sync(
                &cli.config,
                sync_args.ts,
                sync_args.rust,
                sync_args.python,
                sync_args.stacks,
            ),
            SdkCommands::List => commands::sdk::list(&cli.config),
        },
        Commands::Config(config_cmd) => match config_cmd {
            ConfigCommands::Validate => commands::config::validate(&cli.config),
        },
        Commands::Auth(auth_cmd) => match auth_cmd {
            AuthCommands::Login { key } => commands::auth::login(key),
            AuthCommands::Logout => commands::auth::logout(),
            AuthCommands::LogoutAll => commands::auth::logout_all(),
            AuthCommands::Status => commands::auth::status(),
            AuthCommands::Whoami => commands::auth::whoami(),
            AuthCommands::Keys(keys_cmd) => match keys_cmd {
                KeysCommands::List => commands::auth::list_keys(),
                KeysCommands::CreatePublishable {
                    name,
                    origin,
                    expiry_days,
                } => commands::auth::create_publishable_key(name, origin, expiry_days),
            },
        },
        Commands::Stack(stack_cmd) => match stack_cmd {
            StackCommands::Compose {
                name,
                programs,
                live_specs,
                artifact_dirs,
                selected_views,
                output,
            } => commands::public_artifacts::compose_stack(
                &name,
                &programs,
                &live_specs,
                &artifact_dirs,
                &selected_views,
                &output,
            ),
            StackCommands::List => commands::stack::list(cli.json),
            StackCommands::Push { stack_name } => {
                commands::stack::push(&cli.config, stack_name.as_deref())
            }
            StackCommands::Show {
                stack_name,
                version,
            } => commands::stack::show(&stack_name, version, cli.json),
            StackCommands::Versions { stack_name, limit } => {
                commands::stack::versions(&stack_name, limit, cli.json)
            }
            StackCommands::Delete { stack_name, force } => {
                commands::stack::delete(&stack_name, force)
            }
            StackCommands::Rollback {
                stack_name,
                to,
                build,
                branch,
                rebuild,
                no_wait,
            } => commands::stack::rollback(&stack_name, to, build, &branch, rebuild, !no_wait),
            StackCommands::Stop {
                stack_name,
                branch,
                force,
            } => commands::stack::stop(&stack_name, branch.as_deref(), force),
        },
        Commands::Live(live_cmd) => match live_cmd {
            LiveCommands::Build {
                input,
                output,
                program_dir,
            } => commands::public_artifacts::build_live(&input, output, program_dir),
        },
        Commands::Program(program_cmd) => match program_cmd {
            ProgramCommands::Build {
                input,
                output,
                program_id,
            } => commands::public_artifacts::build_program(&input, &output, program_id.as_deref()),
        },
        Commands::Build(build_cmd) => match build_cmd {
            BuildCommands::Create {
                stack_name,
                version,
                ast_file,
                no_wait,
            } => commands::build::create(
                &cli.config,
                &stack_name,
                version,
                ast_file.as_deref(),
                !no_wait,
            ),
            BuildCommands::List { limit, status } => {
                commands::build::list(limit, status.as_deref(), cli.json)
            }
            BuildCommands::Status {
                build_id,
                watch,
                json,
            } => commands::build::status(build_id, watch, json || cli.json),
        },
        Commands::Idl(args) => commands::idl::run(args),
        Commands::Stream(args) => commands::stream::run(args, &cli.config),
        Commands::Telemetry(telemetry_cmd) => match telemetry_cmd {
            TelemetryCommands::Status => commands::telemetry::status(),
            TelemetryCommands::Enable => commands::telemetry::enable(),
            TelemetryCommands::Disable => commands::telemetry::disable(),
        },
    }
}

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

    #[test]
    fn local_only_is_restricted_to_dry_run() {
        assert!(
            Cli::try_parse_from(["a4", "up", "stack.stack-manifest.json", "--local-only"]).is_err()
        );

        let cli = Cli::try_parse_from([
            "a4",
            "up",
            "stack.stack-manifest.json",
            "--dry-run",
            "--local-only",
        ])
        .expect("local-only dry run should parse");
        match cli.command {
            Some(Commands::Up {
                dry_run,
                local_only,
                ..
            }) => {
                assert!(dry_run);
                assert!(local_only);
            }
            _ => panic!("expected up command"),
        }
    }

    #[test]
    fn global_json_is_available_to_manifest_native_up() {
        let cli = Cli::try_parse_from([
            "a4",
            "--json",
            "up",
            "stack.stack-manifest.json",
            "--dry-run",
        ])
        .expect("manifest-native JSON dry run should parse");
        assert!(cli.json);
        assert!(matches!(
            cli.command,
            Some(Commands::Up {
                dry_run: true,
                local_only: false,
                ..
            })
        ));
    }

    #[test]
    fn parse_install_stack_shorthand() {
        let cli = Cli::try_parse_from(["a4", "install", "ore"]).expect("cli should parse");

        match cli.command {
            Some(Commands::Install {
                target,
                install_name,
                ..
            }) => {
                assert_eq!(target, "ore");
                assert_eq!(install_name, None);
            }
            _ => panic!("expected install command"),
        }
    }

    #[test]
    fn parse_install_program_target() {
        let cli = Cli::try_parse_from(["a4", "install", "program", "spl-token", "--ts"])
            .expect("cli should parse");

        match cli.command {
            Some(Commands::Install {
                target,
                install_name,
                ts,
                ..
            }) => {
                assert_eq!(target, "program");
                assert_eq!(install_name.as_deref(), Some("spl-token"));
                assert!(ts);
            }
            _ => panic!("expected install command"),
        }
    }

    #[test]
    fn parse_explicit_stack_explore() {
        let cli = Cli::try_parse_from(["a4", "explore", "stack", "ore", "Position", "--json"])
            .expect("cli should parse");
        match cli.command {
            Some(Commands::Explore {
                target,
                reference,
                entity,
            }) => {
                assert_eq!(target.as_deref(), Some("stack"));
                assert_eq!(reference.as_deref(), Some("ore"));
                assert_eq!(entity.as_deref(), Some("Position"));
                assert!(cli.json);
            }
            _ => panic!("expected explore command"),
        }
    }

    #[test]
    fn parse_program_list_and_program_explore() {
        for (args, expected_reference) in [
            (vec!["a4", "explore", "programs"], None),
            (
                vec!["a4", "explore", "program", "spl-token"],
                Some("spl-token"),
            ),
        ] {
            let cli = Cli::try_parse_from(args).expect("cli should parse");
            match cli.command {
                Some(Commands::Explore {
                    target,
                    reference,
                    entity,
                }) => {
                    assert_eq!(
                        target.as_deref(),
                        Some(if expected_reference.is_some() {
                            "program"
                        } else {
                            "programs"
                        })
                    );
                    assert_eq!(reference.as_deref(), expected_reference);
                    assert!(entity.is_none());
                }
                _ => panic!("expected explore command"),
            }
        }
    }

    #[test]
    fn parse_legacy_stack_entity_explore() {
        let cli = Cli::try_parse_from(["a4", "explore", "ore", "Position"])
            .expect("legacy CLI should parse");
        match cli.command {
            Some(Commands::Explore {
                target,
                reference,
                entity,
            }) => {
                assert_eq!(target.as_deref(), Some("ore"));
                assert_eq!(reference.as_deref(), Some("Position"));
                assert!(entity.is_none());
            }
            _ => panic!("expected explore command"),
        }
    }
}