airs-cli 0.4.1

Native Rust CLI for Prisma AIRS (executable airs-cli-rs until 1.0), built on the scm-sdk crate
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
//! Command planning (all usage validation, before any tenant read) and dispatch.

pub mod doctor;
pub mod profile_cleanup;
pub mod profile_write;
pub mod profiles;
pub mod scan;
pub mod tenant;
pub mod tenant_import;
pub mod tenant_write;
pub mod topic_assign;
pub mod topic_eval;
pub mod topic_write;
pub mod topics;

use crate::cli::{Cli, ProfilesCommand, RuntimeCommand, TenantCommand, TopCommand, TopicsCommand};
use crate::debug::{DebugLog, DebugPolicy};
use crate::error::{
    self, CliError, InterruptContext, Operation, Phase, Plane, SdkContext, SecretSet,
};
use crate::output::{self, Format, Output};
use crate::pagination::{self, GetParams, ListParams};
use crate::tenant::{self as registry, Environment, TenantContext};
use std::time::Duration;

/// Per-invocation state shared by every command.
pub struct Invocation {
    pub output: Output,
    /// Shared by every SDK client; cancelled by SIGINT/SIGTERM.
    pub session: scm::Session,
    pub env: Environment,
    /// The validated `--tenant` value.
    pub tenant_flag: Option<String>,
    /// Secrets seen this invocation (shared with the OAuth provider, which adds every
    /// lease); server text carrying one is never printed.
    pub secrets: SecretSet,
    /// The `--debug` API log, when this run writes one (DESIGN §2.9); every client's
    /// transport records into it.
    pub debug: Option<DebugLog>,
    /// Which streams are terminals (the prompt and confirmation gates, §3.10).
    pub terminals: crate::input::Terminals,
    /// Whether a tenant write passed its commit point (an interruption then reports
    /// `the change was saved`, §3.9).
    pub committed: bool,
    /// What an interruption reports when no SDK call said otherwise and `committed` is
    /// not set: a multi-step write after its first step (`topics revert`), or the scans
    /// sent so far (`topics eval`) (DESIGN §13.2). `None` keeps the plan's context.
    pub interrupt: Option<InterruptContext>,
}

impl Invocation {
    pub fn new(output: Output, tenant_flag: Option<String>) -> Self {
        Self {
            output,
            session: scm::Session::new(),
            env: Environment::capture(),
            tenant_flag,
            secrets: SecretSet::default(),
            debug: None,
            terminals: crate::input::Terminals::detect(),
            committed: false,
            interrupt: None,
        }
    }

    /// Open the debug log (after planning, before the tenant is read) and print its
    /// notice. A failure is an operational error and no request is sent.
    pub fn open_debug_log(&mut self) -> Result<(), CliError> {
        let dir =
            crate::debug::directory(self.env.xdg_state_home.as_deref(), self.env.home.as_deref())?;
        let log = DebugLog::open(
            &dir,
            self.secrets.clone(),
            crate::render::style::stderr_color(),
        )?;
        self.output.status(&format!(
            "Debug: API log → {}",
            output::terminal_safe(&log.path().display().to_string())
        ));
        self.debug = Some(log);
        Ok(())
    }

    /// Load the selected tenant (store, selection, tenant file, TSG pin) and register
    /// its secrets for output scrubbing.
    pub fn load_tenant(&mut self) -> Result<TenantContext, CliError> {
        let context = registry::load_selected(&self.env, self.tenant_flag.as_deref())?;
        self.secrets.register_config(&context.config);
        Ok(context)
    }

    /// Prepare a management read (milestone 2): load the tenant, settle the output
    /// format (`format` is the explicit `--output`; otherwise the tenant's
    /// `defaultOutput`, else `pretty`), check the management credentials, build the
    /// clients and fetch the OAuth token under `options` (from [`walk_options`];
    /// `None`: the SDK's own token budget).
    pub async fn connect_management(
        &mut self,
        format: Option<Format>,
        options: Option<&scm::RequestOptions>,
    ) -> Result<(scm::airs::management::ManagementClient, Format), CliError> {
        let context = self.load_tenant()?;
        let format = output::resolve_tenant_default(format, context.config.default_output());
        crate::tenant::config::require_management(&context.config, Some(context.name()))?;
        let clients = crate::clients::ManagementClients::build(
            &context.config,
            &self.session,
            &self.secrets,
            self.debug.as_ref(),
        )?;
        let budget = if options.is_some() {
            crate::clients::WALK_BUDGET
        } else {
            crate::clients::TOKEN_BUDGET
        };
        clients.authenticate(options, budget).await?;
        Ok((clients.management, format))
    }

    /// Load the tenant, check the management credentials and build the clients, without
    /// any request (a confirmation may follow before the token is fetched, §13.2).
    pub fn management_clients(&mut self) -> Result<crate::clients::ManagementClients, CliError> {
        let context = self.load_tenant()?;
        crate::tenant::config::require_management(&context.config, Some(context.name()))?;
        Ok(crate::clients::ManagementClients::build(
            &context.config,
            &self.session,
            &self.secrets,
            self.debug.as_ref(),
        )?)
    }

    /// Map an SDK error from a management API call made under `budget`.
    pub fn management_error(&self, error: &scm::Error, budget: Duration) -> CliError {
        error::from_sdk(
            error,
            &SdkContext {
                plane: Plane::Management,
                phase: Phase::Api,
                operation: Operation::Read,
                timeout: budget,
                secrets: &self.secrets,
            },
        )
    }
}

/// An interruption before any write of a runtime write command was sent reads
/// `nothing was changed` (§13.2), not the read commands' `no data was written`.
pub fn nothing_changed(error: CliError) -> CliError {
    match error {
        CliError::Interrupted(InterruptContext::NoDataWritten) => {
            CliError::Interrupted(InterruptContext::NothingChanged)
        }
        other => other,
    }
}

/// An M4 confirmation (§13.2): `? <message> (y/N) ` on stderr; `y` or `yes` confirm. A
/// signal that already arrived stops the command first (nothing was changed); one at
/// the prompt ends the process with `Cancelled; nothing was changed.`.
pub fn confirm(invocation: &mut Invocation, message: &str) -> Result<bool, CliError> {
    if let Some(signals) = invocation.output.signals() {
        signals.set_runtime_prompt();
    }
    if invocation.output.pending_signal().is_some() {
        return Err(CliError::Interrupted(InterruptContext::NothingChanged));
    }
    let stdin = std::io::stdin();
    let mut input = stdin.lock();
    Ok(crate::input::Prompter::new(&mut input, &mut invocation.output, true).confirm(message))
}

/// The deprecated-alias warning (TS text, DESIGN §13.1).
pub const FORMAT_DEPRECATED: &str =
    "⚠ --format is deprecated and will be removed in v4 — use --output";

/// The hidden `--format` value of the command, when it has one and it was given.
fn format_alias(cli: &Cli) -> Option<&str> {
    match &cli.command {
        Some(TopCommand::Runtime(crate::cli::RuntimeGroup {
            command:
                Some(RuntimeCommand::Topics(crate::cli::TopicsGroup {
                    command: Some(command),
                })),
        })) => match command {
            TopicsCommand::Create(args) => args.format.as_deref(),
            TopicsCommand::Apply(args) => args.format.as_deref(),
            TopicsCommand::Revert(args) => args.format.as_deref(),
            TopicsCommand::Eval(args) => args.format.as_deref(),
            _ => None,
        },
        _ => None,
    }
}

/// Whether the command line uses the deprecated `--format` alias.
pub fn uses_format_alias(cli: &Cli) -> bool {
    format_alias(cli).is_some()
}

/// Whether the command line runs one of the M4 runtime write commands (§13).
fn is_runtime_write(cli: &Cli) -> bool {
    match &cli.command {
        Some(TopCommand::Runtime(crate::cli::RuntimeGroup {
            command:
                Some(RuntimeCommand::Topics(crate::cli::TopicsGroup {
                    command: Some(command),
                })),
        })) => !matches!(command, TopicsCommand::List(_) | TopicsCommand::Get(_)),
        Some(TopCommand::Runtime(crate::cli::RuntimeGroup {
            command:
                Some(RuntimeCommand::Profiles(crate::cli::ProfilesGroup {
                    command: Some(command),
                })),
        })) => matches!(
            command,
            ProfilesCommand::Create(_)
                | ProfilesCommand::Update(_)
                | ProfilesCommand::Delete(_)
                | ProfilesCommand::Cleanup(_)
        ),
        _ => false,
    }
}

/// The format of an M4 command that renders data (§13.1, D94): `--format` is validated
/// like `--output`; an explicit `--output` wins, else `--format`, else `pretty`. The
/// tenant's `defaultOutput` is never consulted.
fn runtime_write_format(cli: &Cli) -> Result<Format, CliError> {
    let alias = output::validate_explicit(format_alias(cli))?;
    let explicit = output::validate_explicit(cli.global.output.as_deref())?;
    Ok(explicit.or(alias).unwrap_or(Format::Pretty))
}

/// One shared deadline for a whole walk, including its token request (DESIGN §5).
pub fn walk_options() -> Result<scm::RequestOptions, CliError> {
    scm::RequestOptions::with_timeout(crate::clients::WALK_BUDGET).map_err(|_| {
        CliError::operational("AISEC_SDK_ERROR:The request options could not be configured")
    })
}

/// A fully validated invocation.
pub enum Plan {
    /// A command group without a subcommand: its help on stderr, exit 2.
    GroupHelp(&'static [&'static str]),
    TenantList(Format),
    TenantPath(Option<String>),
    TenantRead(Option<String>, Format),
    TenantGet {
        name: String,
        key: &'static str,
        format: Format,
    },
    Doctor(Format),
    Scan(scan::ScanInput, Format),
    ProfilesList(ListParams, Option<Format>),
    ProfilesGet(GetParams, Option<Format>),
    TopicsList(ListParams, Option<Format>),
    TopicsGet(GetParams, Option<Format>),
    /// `tenant create|set|unset|switch|delete` (§3.11).
    TenantWrite(tenant_write::WritePlan),
    /// `tenant import` (§3.12).
    TenantImport(tenant_import::ImportPlan),
    /// `runtime topics create` (§13.5).
    TopicsCreate(topic_write::CreatePlan),
    /// `runtime topics update` (§13.6).
    TopicsUpdate(topic_write::UpdatePlan),
    /// `runtime topics delete` (§13.7).
    TopicsDelete(topic_write::DeletePlan),
    /// `runtime topics apply` (§13.8).
    TopicsApply(topic_assign::ApplyPlan),
    /// `runtime topics revert` (§13.9).
    TopicsRevert(topic_assign::RevertPlan),
    /// `runtime topics eval` (§13.10).
    TopicsEval(topic_eval::EvalPlan),
    /// `runtime topics sample` (§13.11).
    TopicsSample(topic_eval::SamplePlan),
    /// `runtime profiles create` (§13.12).
    ProfilesCreate(Box<profile_write::CreatePlan>),
    /// `runtime profiles update` (§13.13).
    ProfilesUpdate(Box<profile_write::UpdatePlan>),
    /// `runtime profiles delete` (§13.14).
    ProfilesDelete(profile_write::DeletePlan),
    /// `runtime profiles cleanup` (§13.15).
    ProfilesCleanup(profile_cleanup::CleanupPlan),
}

impl Plan {
    /// What an interrupted run reports when no SDK call said otherwise. Exhaustive on
    /// purpose: a new command (a write, M4) must decide what an interruption means.
    pub fn interrupt_context(&self) -> InterruptContext {
        match self {
            Self::Scan(..) => InterruptContext::ScanOutcomeUnknown,
            // `the change was saved` once the commit point passed (lib::execute).
            Self::TenantWrite(_) | Self::TenantImport(_) => {
                InterruptContext::NoConfigurationChanged
            }
            // `the change was saved` once a write completed (lib::execute, §13.2).
            Self::TopicsCreate(_)
            | Self::TopicsUpdate(_)
            | Self::TopicsDelete(_)
            | Self::ProfilesCreate(_)
            | Self::ProfilesUpdate(_)
            | Self::ProfilesDelete(_)
            | Self::TopicsApply(_)
            | Self::TopicsRevert(_) => InterruptContext::NothingChanged,
            // Replaced by the deletions so far once the deletion loop starts (§13.15).
            Self::ProfilesCleanup(_) => InterruptContext::NothingChanged,
            // Replaced by the scans sent so far once the CSV is read (§13.10).
            Self::TopicsEval(_) => InterruptContext::ScanNotSubmitted,
            // `the change was saved` once the file is written.
            Self::TopicsSample(_) => InterruptContext::NoDataWritten,
            Self::GroupHelp(_)
            | Self::TenantList(_)
            | Self::TenantPath(_)
            | Self::TenantRead(..)
            | Self::TenantGet { .. }
            | Self::Doctor(_)
            | Self::ProfilesList(..)
            | Self::ProfilesGet(..)
            | Self::TopicsList(..)
            | Self::TopicsGet(..) => InterruptContext::NoDataWritten,
        }
    }

    /// Whether `--debug` opens a log for this command (DESIGN §2.9, D63): only the
    /// commands that can send requests. Exhaustive on purpose: a new command decides.
    pub fn debug_policy(&self) -> DebugPolicy {
        match self {
            Self::Doctor(_)
            | Self::Scan(..)
            | Self::ProfilesList(..)
            | Self::ProfilesGet(..)
            | Self::TopicsList(..)
            | Self::TopicsGet(..)
            | Self::TopicsCreate(_)
            | Self::TopicsUpdate(_)
            | Self::TopicsDelete(_)
            | Self::ProfilesCreate(_)
            | Self::ProfilesUpdate(_)
            | Self::ProfilesDelete(_)
            | Self::TopicsApply(_)
            | Self::TopicsRevert(_)
            | Self::TopicsEval(_)
            | Self::ProfilesCleanup(_) => DebugPolicy::Log,
            Self::TopicsSample(_)
            | Self::GroupHelp(_)
            | Self::TenantList(_)
            | Self::TenantPath(_)
            | Self::TenantRead(..)
            | Self::TenantGet { .. }
            | Self::TenantWrite(_)
            | Self::TenantImport(_) => DebugPolicy::None,
        }
    }
}

/// Validate every flag and value. Never reads the registry or the network. Every
/// command validates `--output` (DESIGN §2.4); management reads settle a missing one
/// from the tenant later.
pub fn plan(cli: &Cli) -> Result<Plan, CliError> {
    let explicit = cli.global.output.as_deref();
    // `tenant import` renders its report: `--output` is resolved first, then any
    // `--tenant` is refused, then its own checks run (§3.11, §3.12).
    if let Some(TopCommand::Tenant(crate::cli::TenantGroup {
        command: Some(TenantCommand::Import(args)),
    })) = &cli.command
    {
        let format = output::resolve(explicit)?;
        if cli.global.tenant.is_some() {
            return Err(CliError::usage(
                "--tenant cannot be used with 'tenant import'; name the tenant as an argument",
            ));
        }
        return Ok(Plan::TenantImport(tenant_import::plan(args, format)?));
    }
    // The write commands name their tenant positionally: `--output` is validated first,
    // then any `--tenant` is refused, then the command's own checks run (§3.11).
    if let Some(TopCommand::Tenant(crate::cli::TenantGroup {
        command: Some(command),
    })) = &cli.command
        && let Some(subcommand) = tenant_write::write_command_name(command)
    {
        output::validate_explicit(explicit)?;
        if cli.global.tenant.is_some() {
            return Err(CliError::usage(format!(
                "--tenant cannot be used with 'tenant {subcommand}'; name the tenant as an argument"
            )));
        }
        return Ok(Plan::TenantWrite(tenant_write::plan(command)?));
    }
    // The M4 commands check `--format` and `--output` before `--tenant` (§13.2).
    if is_runtime_write(cli) {
        runtime_write_format(cli)?;
    }
    registry::validate_tenant_flag(cli.global.tenant.as_deref())?;
    let Some(command) = &cli.command else {
        return Ok(Plan::GroupHelp(&[]));
    };
    Ok(match command {
        TopCommand::Tenant(group) => match &group.command {
            None => Plan::GroupHelp(&["tenant"]),
            Some(
                TenantCommand::Create(_)
                | TenantCommand::Set(_)
                | TenantCommand::Unset { .. }
                | TenantCommand::Switch { .. }
                | TenantCommand::Delete { .. }
                | TenantCommand::Import(_),
            ) => unreachable!("write commands are planned above"),
            Some(TenantCommand::List) => Plan::TenantList(output::resolve(explicit)?),
            // The path is printed in every format; an invalid name is still rejected.
            Some(TenantCommand::Path { name }) => {
                output::validate_explicit(explicit)?;
                Plan::TenantPath(name.clone())
            }
            Some(TenantCommand::Read { name }) => {
                Plan::TenantRead(name.clone(), output::resolve(explicit)?)
            }
            Some(TenantCommand::Get { name, key }) => {
                // The key is validated before the format (D34 order).
                let key = crate::tenant::config::schema_key(key).ok_or_else(|| {
                    CliError::usage(format!(
                        "Unknown configuration key. Supported keys: {}",
                        crate::tenant::config::KEYS.join(", ")
                    ))
                })?;
                Plan::TenantGet {
                    name: name.clone(),
                    key,
                    format: output::resolve(explicit)?,
                }
            }
        },
        TopCommand::Doctor => Plan::Doctor(output::resolve(explicit)?),
        TopCommand::Runtime(group) => match &group.command {
            None => Plan::GroupHelp(&["runtime"]),
            Some(RuntimeCommand::Scan(args)) => {
                let format = output::resolve(explicit)?;
                Plan::Scan(scan::validate_input(args)?, format)
            }
            Some(RuntimeCommand::Profiles(profiles)) => match &profiles.command {
                None => Plan::GroupHelp(&["runtime", "profiles"]),
                Some(ProfilesCommand::List(args)) => {
                    let format = output::validate_explicit(explicit)?;
                    Plan::ProfilesList(
                        pagination::parse_list(&args.paging, args.all_versions)?,
                        format,
                    )
                }
                Some(ProfilesCommand::Get(args)) => {
                    let format = output::validate_explicit(explicit)?;
                    Plan::ProfilesGet(pagination::parse_get(&args.lookup)?, format)
                }
                Some(ProfilesCommand::Create(args)) => {
                    let format = runtime_write_format(cli)?;
                    Plan::ProfilesCreate(Box::new(profile_write::plan_create(args, format)?))
                }
                Some(ProfilesCommand::Update(args)) => {
                    let format = runtime_write_format(cli)?;
                    Plan::ProfilesUpdate(Box::new(profile_write::plan_update(args, format)?))
                }
                Some(ProfilesCommand::Delete(args)) => {
                    output::validate_explicit(explicit)?;
                    Plan::ProfilesDelete(profile_write::plan_delete(
                        args,
                        crate::input::Terminals::detect().interactive(),
                    )?)
                }
                Some(ProfilesCommand::Cleanup(args)) => {
                    let format = runtime_write_format(cli)?;
                    Plan::ProfilesCleanup(profile_cleanup::plan_cleanup(
                        args,
                        format,
                        crate::input::Terminals::detect().interactive(),
                    )?)
                }
            },
            Some(RuntimeCommand::Topics(topics)) => match &topics.command {
                None => Plan::GroupHelp(&["runtime", "topics"]),
                Some(TopicsCommand::List(args)) => {
                    let format = output::validate_explicit(explicit)?;
                    Plan::TopicsList(
                        pagination::parse_list(&args.paging, args.all_versions)?,
                        format,
                    )
                }
                Some(TopicsCommand::Get(args)) => {
                    let format = output::validate_explicit(explicit)?;
                    Plan::TopicsGet(pagination::parse_get(&args.lookup)?, format)
                }
                Some(TopicsCommand::Create(args)) => {
                    let format = runtime_write_format(cli)?;
                    Plan::TopicsCreate(topic_write::plan_create(args, format)?)
                }
                Some(TopicsCommand::Update(args)) => {
                    let format = runtime_write_format(cli)?;
                    Plan::TopicsUpdate(topic_write::plan_update(args, format)?)
                }
                Some(TopicsCommand::Delete(args)) => {
                    output::validate_explicit(explicit)?;
                    Plan::TopicsDelete(topic_write::plan_delete(
                        args,
                        crate::input::Terminals::detect().interactive(),
                    )?)
                }
                Some(TopicsCommand::Apply(args)) => {
                    let format = runtime_write_format(cli)?;
                    Plan::TopicsApply(topic_assign::plan_apply(args, format)?)
                }
                Some(TopicsCommand::Revert(args)) => {
                    let format = runtime_write_format(cli)?;
                    Plan::TopicsRevert(topic_assign::plan_revert(
                        args,
                        format,
                        crate::input::Terminals::detect().interactive(),
                    )?)
                }
                Some(TopicsCommand::Eval(args)) => {
                    let format = runtime_write_format(cli)?;
                    Plan::TopicsEval(topic_eval::plan_eval(args, format)?)
                }
                Some(TopicsCommand::Sample(args)) => {
                    output::validate_explicit(explicit)?;
                    Plan::TopicsSample(topic_eval::plan_sample(args))
                }
            },
        },
    })
}

/// Run a validated plan (everything except `GroupHelp`, which `lib` renders).
pub async fn dispatch(invocation: &mut Invocation, plan: Plan) -> Result<(), CliError> {
    match plan {
        Plan::GroupHelp(_) => Ok(()),
        Plan::TenantList(format) => tenant::list(invocation, format),
        Plan::TenantPath(name) => tenant::path(invocation, name.as_deref()),
        Plan::TenantRead(name, format) => tenant::read(invocation, name.as_deref(), format),
        Plan::TenantGet { name, key, format } => tenant::get(invocation, &name, key, format),
        Plan::Doctor(format) => doctor::run(invocation, format).await,
        Plan::Scan(input, format) => scan::run(invocation, &input, format).await,
        Plan::ProfilesList(params, format) => profiles::list(invocation, &params, format).await,
        Plan::ProfilesGet(params, format) => profiles::get(invocation, &params, format).await,
        Plan::TopicsList(params, format) => topics::list(invocation, &params, format).await,
        Plan::TopicsGet(params, format) => topics::get(invocation, &params, format).await,
        Plan::TenantWrite(write) => tenant_write::run(invocation, write),
        Plan::TenantImport(import) => tenant_import::run(invocation, import),
        Plan::TopicsCreate(plan) => topic_write::create(invocation, &plan).await,
        Plan::TopicsUpdate(plan) => topic_write::update(invocation, &plan).await,
        Plan::TopicsDelete(plan) => topic_write::delete(invocation, &plan).await,
        Plan::TopicsApply(plan) => topic_assign::apply(invocation, &plan).await,
        Plan::TopicsRevert(plan) => topic_assign::revert(invocation, &plan).await,
        Plan::TopicsEval(plan) => topic_eval::eval(invocation, &plan).await,
        Plan::TopicsSample(plan) => topic_eval::sample(invocation, &plan),
        Plan::ProfilesCreate(plan) => profile_write::create(invocation, &plan).await,
        Plan::ProfilesUpdate(plan) => profile_write::update(invocation, &plan).await,
        Plan::ProfilesDelete(plan) => profile_write::delete(invocation, &plan).await,
        Plan::ProfilesCleanup(plan) => profile_cleanup::cleanup(invocation, &plan).await,
    }
}

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

    fn plan_of(args: &[&str]) -> Result<Plan, CliError> {
        let matches = crate::cli::command().try_get_matches_from(args).unwrap();
        plan(&Cli::from_arg_matches(&matches).unwrap())
    }

    fn usage(args: &[&str]) -> String {
        match plan_of(args) {
            Err(CliError::Usage(message)) => message,
            Err(other) => panic!("expected usage error, got {other:?}"),
            Ok(_) => panic!("expected usage error"),
        }
    }

    #[test]
    fn usage_errors_need_no_tenant() {
        assert_eq!(
            usage(&[
                "airs-cli-rs",
                "runtime",
                "profiles",
                "list",
                "--output",
                "xml"
            ]),
            "Invalid output format 'xml'. Expected: pretty, table, json"
        );
        assert_eq!(
            usage(&["airs-cli-rs", "doctor", "--output", "yaml"]),
            "Invalid output format 'yaml'. Expected: pretty, table, json"
        );
        assert_eq!(
            usage(&["airs-cli-rs", "tenant", "path", "--output", "csv"]),
            "Invalid output format 'csv'. Expected: pretty, table, json"
        );
        assert_eq!(
            usage(&["airs-cli-rs", "runtime", "topics", "list", "--limit", "0"]),
            "--limit must be a positive integer"
        );
        assert_eq!(
            usage(&[
                "airs-cli-rs",
                "runtime",
                "profiles",
                "get",
                "x",
                "--revision",
                "abc"
            ]),
            "--revision must be a non-negative integer"
        );
        assert!(
            usage(&["airs-cli-rs", "tenant", "get", "dev", "nope"]).starts_with(
                "Unknown configuration key. Supported keys: airsApiKey, airsApiToken,"
            )
        );
        assert!(
            usage(&["airs-cli-rs", "--tenant", "-x", "doctor"]).starts_with("Tenant name must be")
        );
        assert_eq!(
            usage(&["airs-cli-rs", "runtime", "scan", "--profile", "p", ""]),
            "AISEC_USER_REQUEST_PAYLOAD_ERROR:At least one of prompt, response, codePrompt, codeResponse, or toolEvent must be provided"
        );
    }

    #[test]
    fn unknown_key_wins_over_output_and_path_ignores_a_valid_output() {
        assert!(
            usage(&[
                "airs-cli-rs",
                "tenant",
                "get",
                "dev",
                "nope",
                "--output",
                "xml"
            ])
            .starts_with("Unknown configuration key")
        );
        assert!(matches!(
            plan_of(&["airs-cli-rs", "tenant", "path", "--output", "table"]),
            Ok(Plan::TenantPath(None))
        ));
    }

    #[test]
    fn write_commands_validate_output_then_refuse_tenant() {
        assert_eq!(
            usage(&[
                "airs-cli-rs",
                "--tenant",
                "-x",
                "tenant",
                "switch",
                "dev",
                "--output",
                "xml"
            ]),
            "Invalid output format 'xml'. Expected: pretty, table, json"
        );
        for (sub, args) in [
            ("create", &["create", "dev"][..]),
            ("set", &["set", "dev", "defaultOutput", "json"]),
            ("unset", &["unset", "dev", "defaultOutput"]),
            ("switch", &["switch", "dev"]),
            ("delete", &["rm", "dev"]),
        ] {
            let mut full = vec!["airs-cli-rs", "--tenant", "-x", "tenant"];
            full.extend_from_slice(args);
            assert_eq!(
                usage(&full),
                format!(
                    "--tenant cannot be used with 'tenant {sub}'; name the tenant as an argument"
                )
            );
        }
        assert_eq!(
            usage(&["airs-cli-rs", "--tenant", "dev", "tenant", "create", "_bad"]),
            "--tenant cannot be used with 'tenant create'; name the tenant as an argument",
            "before the name check"
        );
        assert_eq!(
            usage(&[
                "airs-cli-rs",
                "tenant",
                "create",
                "_bad",
                "--output",
                "table"
            ]),
            "Tenant name must be 1–64 letters, digits, hyphens or underscores and start with a letter/digit"
        );
        assert!(matches!(
            plan_of(&["airs-cli-rs", "tenant", "switch", "dev", "--output", "json"]),
            Ok(Plan::TenantWrite(tenant_write::WritePlan::Switch { .. }))
        ));
        assert_eq!(
            plan_of(&["airs-cli-rs", "tenant", "switch", "dev"])
                .ok()
                .unwrap()
                .interrupt_context(),
            InterruptContext::NoConfigurationChanged
        );
    }

    #[test]
    fn runtime_writes_check_formats_before_the_tenant_flag_and_ignore_the_default() {
        let create = [
            "airs-cli-rs",
            "--tenant",
            "-bad",
            "runtime",
            "topics",
            "create",
            "--name",
            "n",
            "--description",
            "d",
            "--examples",
            "a",
            "b",
        ];
        let mut with_output = create.to_vec();
        with_output.extend(["--output", "xml"]);
        assert_eq!(
            usage(&with_output),
            "Invalid output format 'xml'. Expected: pretty, table, json"
        );
        let mut with_format = create.to_vec();
        with_format.extend(["--format", "csv"]);
        assert_eq!(
            usage(&with_format),
            "Invalid output format 'csv'. Expected: pretty, table, json"
        );
        assert!(usage(&create).starts_with("Tenant name must be"));
        let plain = &create[3..];
        let mut args = vec!["airs-cli-rs"];
        args.extend_from_slice(plain);
        args.extend(["--format", "json", "--output", "table"]);
        assert!(matches!(
            plan_of(&args),
            Ok(Plan::TopicsCreate(topic_write::CreatePlan {
                format: Format::Table,
                ..
            }))
        ));
        let mut args = vec!["airs-cli-rs"];
        args.extend_from_slice(plain);
        let plan = plan_of(&args).ok().unwrap();
        assert!(matches!(
            &plan,
            Plan::TopicsCreate(topic_write::CreatePlan {
                format: Format::Pretty,
                ..
            })
        ));
        assert_eq!(plan.interrupt_context(), InterruptContext::NothingChanged);
        assert_eq!(plan.debug_policy(), DebugPolicy::Log);
        assert_eq!(
            usage(&[
                "airs-cli-rs",
                "runtime",
                "profiles",
                "delete",
                "p",
                "--force",
                "--updated-by",
                "a@b",
                "--output",
                "yaml"
            ]),
            "Invalid output format 'yaml'. Expected: pretty, table, json"
        );
    }

    #[test]
    fn topic_assign_and_eval_plans_check_formats_first() {
        let apply = [
            "airs-cli-rs",
            "--tenant",
            "-bad",
            "runtime",
            "topics",
            "apply",
            "--profile",
            "p",
            "--name",
            "n",
            "--intent",
            "deny",
            "--format",
            "xml",
        ];
        assert_eq!(
            usage(&apply),
            "Invalid output format 'xml'. Expected: pretty, table, json"
        );
        assert!(usage(&apply[..12]).starts_with("Tenant name must be"));
        let mut eval = vec![
            "airs-cli-rs",
            "runtime",
            "topics",
            "eval",
            "--profile",
            "p",
            "--prompts",
            "x.csv",
            "--format",
            "json",
        ];
        let plan = plan_of(&eval).ok().unwrap();
        assert!(matches!(
            &plan,
            Plan::TopicsEval(topic_eval::EvalPlan {
                format: Format::Json,
                concurrency: 5,
                rate: None,
                ..
            })
        ));
        assert_eq!(plan.interrupt_context(), InterruptContext::ScanNotSubmitted);
        eval.extend(["--output", "table"]);
        assert!(matches!(
            plan_of(&eval),
            Ok(Plan::TopicsEval(topic_eval::EvalPlan {
                format: Format::Table,
                ..
            }))
        ));
        let sample = plan_of(&[
            "airs-cli-rs",
            "runtime",
            "topics",
            "sample",
            "--output",
            "json",
        ]);
        assert!(matches!(
            &sample,
            Ok(Plan::TopicsSample(topic_eval::SamplePlan {
                output_file: None
            }))
        ));
        assert_eq!(
            sample.ok().unwrap().interrupt_context(),
            InterruptContext::NoDataWritten
        );
    }

    #[test]
    fn groups_without_subcommands_render_help() {
        for (args, path) in [
            (&["airs-cli-rs"][..], &[][..]),
            (&["airs-cli-rs", "--quiet"], &[]),
            (&["airs-cli-rs", "runtime"], &["runtime"]),
            (
                &["airs-cli-rs", "runtime", "topics"],
                &["runtime", "topics"],
            ),
            (&["airs-cli-rs", "tenant"], &["tenant"]),
        ] {
            match plan_of(args) {
                Ok(Plan::GroupHelp(found)) => assert_eq!(found, path),
                _ => panic!("expected group help for {args:?}"),
            }
        }
    }

    #[test]
    fn debug_policy_logs_only_commands_that_send_requests() {
        let policy = |args: &[&str]| plan_of(args).ok().unwrap().debug_policy();
        for args in [
            &["airs-cli-rs", "doctor"][..],
            &["airs-cli-rs", "runtime", "scan", "--profile", "p", "hi"],
            &["airs-cli-rs", "runtime", "profiles", "list"],
            &["airs-cli-rs", "runtime", "profiles", "get", "x"],
            &["airs-cli-rs", "runtime", "topics", "ls"],
            &["airs-cli-rs", "runtime", "topics", "get", "x"],
            &[
                "airs-cli-rs",
                "runtime",
                "topics",
                "apply",
                "--profile",
                "p",
                "--name",
                "n",
            ],
            &[
                "airs-cli-rs",
                "runtime",
                "topics",
                "revert",
                "--profile",
                "p",
                "--name",
                "n",
                "--force",
            ],
            &[
                "airs-cli-rs",
                "runtime",
                "topics",
                "eval",
                "--profile",
                "p",
                "--prompts",
                "p.csv",
            ],
        ] {
            assert_eq!(policy(args), DebugPolicy::Log, "{args:?}");
        }
        for args in [
            &["airs-cli-rs", "tenant", "list"][..],
            &["airs-cli-rs", "tenant", "switch", "dev"],
            &["airs-cli-rs", "tenant", "delete", "dev"],
            &["airs-cli-rs", "tenant", "create", "dev"],
            &["airs-cli-rs", "tenant", "path"],
            &["airs-cli-rs", "tenant", "read"],
            &["airs-cli-rs", "tenant", "get", "dev", "mgmtTsgId"],
            &["airs-cli-rs", "runtime"],
            &["airs-cli-rs", "runtime", "topics", "sample"],
        ] {
            assert_eq!(policy(args), DebugPolicy::None, "{args:?}");
        }
    }

    #[test]
    fn valid_plans() {
        assert!(matches!(
            plan_of(&[
                "airs-cli-rs",
                "runtime",
                "profiles",
                "ls",
                "--output",
                "json",
                "--all"
            ]),
            Ok(Plan::ProfilesList(
                ListParams { all: true, .. },
                Some(Format::Json)
            ))
        ));
        assert!(matches!(
            plan_of(&["airs-cli-rs", "tenant", "get", "dev", "mgmtTsgId"]),
            Ok(Plan::TenantGet {
                key: "mgmtTsgId",
                format: Format::Pretty,
                ..
            })
        ));
        assert!(matches!(
            plan_of(&["airs-cli-rs", "--output", "json", "doctor"]),
            Ok(Plan::Doctor(Format::Json))
        ));
        assert!(matches!(
            plan_of(&["airs-cli-rs", "tenant", "list"]),
            Ok(Plan::TenantList(Format::Pretty))
        ));
        assert!(matches!(
            plan_of(&["airs-cli-rs", "runtime", "topics", "get", "x"]),
            Ok(Plan::TopicsGet(_, None))
        ));
        assert!(matches!(
            plan_of(&[
                "airs-cli-rs",
                "runtime",
                "scan",
                "--profile",
                "p",
                "hi",
                "--output",
                "table"
            ]),
            Ok(Plan::Scan(_, Format::Table))
        ));
    }
}