sc-lint 0.8.3

Top-level CLI composition root for the sc-lint tool family.
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
use crate::scheduler::FailurePolicy;
use crate::test_selectors::TestRequest;
use serde_json::Value;
use serde_json::json;
use std::path::Path;

use crate::Cli;
use crate::CliError;
use crate::Command;
use crate::DocsGuide;
use crate::config::LoadedConfig;
use crate::consts;
use crate::contract::ServiceName;
use crate::dispatch;
use crate::installer;
use crate::profile_plan::PlatformScope;
use crate::python_adapter;
use crate::workflow;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DispatchTelemetry {
    tool: &'static str,
    finding_count: usize,
}

impl DispatchTelemetry {
    pub(crate) const fn new(tool: &'static str, finding_count: usize) -> Self {
        Self {
            tool,
            finding_count,
        }
    }

    pub const fn tool(&self) -> &'static str {
        self.tool
    }

    pub const fn finding_count(&self) -> usize {
        self.finding_count
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct CommandSuccess {
    pub data: Value,
    pub dispatch: Option<DispatchTelemetry>,
}

impl CommandSuccess {
    pub fn direct(data: Value) -> Self {
        Self {
            data,
            dispatch: None,
        }
    }

    pub fn with_dispatch(data: Value, dispatch: DispatchTelemetry) -> Self {
        Self {
            data,
            dispatch: Some(dispatch),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CommandId {
    Ci,
    CheckNative,
    CheckXwin,
    ClippyNative,
    ClippyXwin,
    CompatibilityCheck,
    Docs,
    Init,
    ConsumerTest,
    Setup,
    Upgrade,
    LintCi,
    ConsumerLintCi,
    LintFast,
    LintFull,
    LintFunctionLength,
    LintIdentityLiterals,
    LintLineCounts,
    LintScBoundary,
    LintScPortability,
    LintScRuntime,
    Version,
    ViewFindings,
    ViewGraph,
}

/// Parsed consumer-integration flags remain a single validated request rather
/// than three unrelated booleans at the execution boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ConsumerInitRequest {
    pub(crate) just: bool,
    pub(crate) check: bool,
    pub(crate) dry_run: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DocsRequest {
    pub(crate) guide: Option<DocsGuide>,
    pub(crate) path: bool,
}

/// Command-specific payloads stay coupled to the command variant that owns
/// them. This prevents an unrelated command context from carrying an
/// impossible `None` payload that would only fail during dispatch.
#[derive(Debug, Clone, PartialEq, Eq)]
enum CommandRequest {
    Setup {
        dry_run: bool,
    },
    Upgrade {
        check: bool,
        dry_run: bool,
    },
    Init(ConsumerInitRequest),
    Docs(DocsRequest),
    /// Consumer test selector, forwarded arguments or `--list`, and `--fail-fast`.
    ConsumerTest {
        request: TestRequest,
        fail_fast: bool,
    },
    /// Consumer lint selector (step or named profile), platform scope and `--fail-fast`.
    ConsumerLint {
        selector: Option<String>,
        scope: PlatformScope,
        fail_fast: bool,
    },
    /// `--rule-filter` value forwarded unchanged to an analyzer backend.
    RuleFilter(String),
}

impl CommandId {
    pub fn from_cli_command(command: &Command) -> Self {
        match command {
            Command::Lint {
                target, consumer, ..
            } => match target {
                crate::LintTarget::ScBoundary => Self::LintScBoundary,
                crate::LintTarget::ScPortability => Self::LintScPortability,
                crate::LintTarget::ScRuntime => Self::LintScRuntime,
                crate::LintTarget::FunctionLength => Self::LintFunctionLength,
                crate::LintTarget::LineCounts => Self::LintLineCounts,
                crate::LintTarget::IdentityLiterals => Self::LintIdentityLiterals,
                crate::LintTarget::Fast => Self::LintFast,
                crate::LintTarget::Full => Self::LintFull,
                crate::LintTarget::Ci if *consumer => Self::ConsumerLintCi,
                crate::LintTarget::Ci => Self::LintCi,
            },
            Command::View { target } => match target {
                crate::ViewTarget::Graph => Self::ViewGraph,
                crate::ViewTarget::Findings => Self::ViewFindings,
            },
            Command::Check { target } => match target {
                crate::CheckTarget::Native => Self::CheckNative,
                crate::CheckTarget::Xwin => Self::CheckXwin,
            },
            Command::Clippy { target } => match target {
                crate::ClippyTarget::Native => Self::ClippyNative,
                crate::ClippyTarget::Xwin => Self::ClippyXwin,
            },
            Command::Compatibility { command } => match command {
                crate::CompatibilityCommand::Check { .. } => Self::CompatibilityCheck,
            },
            Command::Docs { .. } => Self::Docs,
            Command::Setup { .. } => Self::Setup,
            Command::Upgrade { .. } => Self::Upgrade,
            Command::Init { .. } => Self::Init,
            Command::Test { .. } => Self::ConsumerTest,
            Command::Version => Self::Version,
            Command::Ci => Self::Ci,
        }
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Ci => "ci",
            Self::CheckNative => "check.native",
            Self::CheckXwin => "check.xwin",
            Self::ClippyNative => "clippy.native",
            Self::ClippyXwin => "clippy.xwin",
            Self::CompatibilityCheck => "compatibility.check",
            Self::Docs => "docs",
            Self::Init => "init",
            Self::ConsumerTest => "test",
            Self::Setup => "setup",
            Self::Upgrade => "upgrade",
            Self::LintCi => "lint.ci",
            Self::ConsumerLintCi => "lint.ci.consumer",
            Self::LintFast => "lint.fast",
            Self::LintFull => "lint.full",
            Self::LintIdentityLiterals => "lint.identity-literals",
            Self::LintFunctionLength => "lint.function-length",
            Self::LintLineCounts => "lint.line-counts",
            Self::LintScBoundary => consts::CMD_BOUNDARY,
            Self::LintScPortability => consts::CMD_PORTABILITY,
            Self::LintScRuntime => consts::CMD_RUNTIME,
            Self::Version => "version",
            Self::ViewFindings => "view.findings",
            Self::ViewGraph => "view.graph",
        }
    }

    pub const fn service_name(self) -> &'static str {
        match self {
            Self::LintScBoundary => "sc-boundary",
            Self::LintScPortability => "sc-portability",
            Self::LintScRuntime => "sc-runtime",
            Self::Ci
            | Self::CheckNative
            | Self::CheckXwin
            | Self::ClippyNative
            | Self::ClippyXwin
            | Self::CompatibilityCheck
            | Self::Docs
            | Self::Init
            | Self::ConsumerTest
            | Self::Setup
            | Self::Upgrade
            | Self::LintCi
            | Self::ConsumerLintCi
            | Self::LintFast
            | Self::LintFull
            | Self::LintFunctionLength
            | Self::LintIdentityLiterals
            | Self::LintLineCounts
            | Self::Version
            | Self::ViewFindings
            | Self::ViewGraph => consts::SERVICE_NAME,
        }
    }

    pub const fn summary(self) -> &'static str {
        match self {
            Self::Ci => "top-level ci orchestration path",
            Self::CheckNative | Self::CheckXwin => "preflight execution path",
            Self::ClippyNative | Self::ClippyXwin => "clippy execution path",
            Self::CompatibilityCheck => "installed sc-lint compatibility preflight",
            Self::Docs => "offline documentation discovery",
            Self::Init => "consumer integration generation",
            Self::ConsumerTest => "consumer test profile orchestration",
            Self::Setup => "managed sc-lint installation and repair",
            Self::Upgrade => "managed sc-lint upgrade inspection and activation",
            Self::LintCi | Self::LintFast | Self::LintFull => "lint profile orchestration path",
            Self::ConsumerLintCi => "consumer lint profile orchestration",
            Self::LintIdentityLiterals => "python-backed identity literal lint path",
            Self::LintFunctionLength => "python-backed function-length lint path",
            Self::LintLineCounts => "python-backed line-count lint path",
            Self::LintScBoundary => "boundary analyzer command path",
            Self::LintScPortability => "portability analyzer command path",
            Self::LintScRuntime => "runtime analyzer command path",
            Self::Version => "sc-lint version information",
            Self::ViewFindings => "python-backed findings view path",
            Self::ViewGraph => "reserved view contract surface",
        }
    }

    pub const fn requires_repo_root(self) -> bool {
        !matches!(
            self,
            Self::Version
                | Self::CompatibilityCheck
                | Self::Docs
                | Self::Setup
                | Self::Upgrade
                | Self::Init
                | Self::ConsumerTest
                | Self::ConsumerLintCi
        )
    }

    pub const fn dispatch_tool(self) -> Option<&'static str> {
        match self {
            Self::LintScBoundary => Some(consts::TOOL_BOUNDARY),
            Self::LintScPortability => Some(consts::TOOL_PORTABILITY),
            Self::LintScRuntime => Some(consts::TOOL_RUNTIME),
            _ => match self.python_tool() {
                Some(tool) => Some(tool.tool_name()),
                None => None,
            },
        }
    }

    /// Python-backed tool behind this command, if any.
    pub const fn python_tool(self) -> Option<python_adapter::PythonTool> {
        match self {
            Self::LintFunctionLength => Some(python_adapter::PythonTool::FunctionLength),
            Self::LintLineCounts => Some(python_adapter::PythonTool::LineCounts),
            Self::LintIdentityLiterals => Some(python_adapter::PythonTool::IdentityLiterals),
            Self::ViewFindings => Some(python_adapter::PythonTool::ViewFindings),
            _ => None,
        }
    }

    pub fn adapter_kind(self) -> Option<&'static str> {
        self.python_tool().map(|_| python_adapter::adapter_kind())
    }

    pub fn adapter_config_scope(self) -> Option<&'static str> {
        self.python_tool()
            .map(python_adapter::PythonTool::config_scope)
    }

    pub fn adapter_script(self) -> Option<&'static str> {
        self.python_tool()
            .map(python_adapter::PythonTool::script_relative_path)
    }

    pub const fn is_xwin_preflight(self) -> bool {
        matches!(self, Self::CheckXwin | Self::ClippyXwin)
    }

    pub(crate) const fn is_analyzer_lint(self) -> bool {
        matches!(
            self,
            Self::LintScBoundary | Self::LintScPortability | Self::LintScRuntime
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandContext {
    command_id: CommandId,
    service_name: ServiceName,
    summary: &'static str,
    requires_repo_root: bool,
    compatibility_binary: Option<std::path::PathBuf>,
    backend_search_path: Option<std::ffi::OsString>,
    request: Option<CommandRequest>,
}

impl CommandContext {
    /// Constructs a command context from parsed CLI arguments.
    ///
    /// This constructor is fallible: it returns a usage error when `--version`
    /// is combined with a subcommand or when neither a subcommand nor
    /// `--version` was provided.
    #[expect(
        clippy::result_large_err,
        reason = "Context construction preserves the shared top-level CliError contract before command dispatch starts."
    )]
    pub fn from_cli(cli: &Cli) -> Result<Self, CliError> {
        Self::from_cli_with_backend_search_path(cli, std::env::var_os("PATH"))
    }

    /// Constructs a command context with an explicit backend search path.
    /// Production captures PATH in `from_cli`; tests inject a controlled path.
    #[expect(
        clippy::result_large_err,
        reason = "Context construction preserves the shared top-level CliError contract before command dispatch starts."
    )]
    pub(crate) fn from_cli_with_backend_search_path(
        cli: &Cli,
        backend_search_path: Option<std::ffi::OsString>,
    ) -> Result<Self, CliError> {
        let (command_id, compatibility_binary, request) = match (&cli.command, cli.version) {
            (Some(command), false) => {
                validate_command_flags(cli, command)?;
                let compatibility_binary = match command {
                    Command::Compatibility {
                        command: crate::CompatibilityCommand::Check { binary },
                    } => binary.clone(),
                    _ => None,
                };
                let request = command_request(command);
                (
                    CommandId::from_cli_command(command),
                    compatibility_binary,
                    request,
                )
            }
            (None, true) => (CommandId::Version, None, None),
            (Some(_), true) => {
                return Err(CliError::usage(
                        "`--version` cannot be combined with a subcommand",
                    )
                    .with_suggested_action(
                        "Use either `sc-lint --version` or a subcommand such as `sc-lint version`.",
                    ));
            }
            (None, false) => {
                return Err(
                    CliError::usage("a command is required").with_suggested_action(
                        "Run `sc-lint --help` to inspect the supported command surface.",
                    ),
                );
            }
        };
        let service_name = ServiceName::new(command_id.service_name());

        Ok(Self {
            command_id,
            service_name,
            summary: command_id.summary(),
            requires_repo_root: command_id.requires_repo_root(),
            compatibility_binary,
            backend_search_path,
            request,
        })
    }

    pub(crate) fn backend_search_path(&self) -> Option<&std::ffi::OsStr> {
        self.backend_search_path.as_deref()
    }

    pub fn command_id(&self) -> &str {
        self.command_id.as_str()
    }

    pub fn service_name(&self) -> &str {
        self.service_name.as_str()
    }

    pub(crate) const fn id(&self) -> CommandId {
        self.command_id
    }

    pub const fn summary(&self) -> &'static str {
        self.summary
    }

    pub(crate) const fn requires_repo_root(&self) -> bool {
        self.requires_repo_root
    }

    pub(crate) const fn requires_compatibility_config(&self) -> bool {
        matches!(
            self.command_id,
            CommandId::CompatibilityCheck
                | CommandId::Setup
                | CommandId::Upgrade
                | CommandId::ConsumerLintCi
                | CommandId::ConsumerTest
        )
    }

    pub(crate) fn compatibility_binary(&self) -> Option<&Path> {
        self.compatibility_binary.as_deref()
    }

    pub(crate) const fn setup_dry_run(&self) -> bool {
        matches!(self.request, Some(CommandRequest::Setup { dry_run: true }))
    }

    pub(crate) const fn upgrade_check(&self) -> bool {
        matches!(
            self.request,
            Some(CommandRequest::Upgrade { check: true, .. })
        )
    }

    pub(crate) const fn upgrade_dry_run(&self) -> bool {
        matches!(
            self.request,
            Some(CommandRequest::Upgrade { dry_run: true, .. })
        )
    }

    pub(crate) fn consumer_init_request(&self) -> ConsumerInitRequest {
        match self.request {
            Some(CommandRequest::Init(request)) => request,
            _ => unreachable!("consumer initialization request is tied to the init command"),
        }
    }

    /// Selector for `lint --consumer`: `None` and `all` run every configured step.
    pub(crate) fn consumer_selector(&self) -> Option<&str> {
        match &self.request {
            Some(CommandRequest::ConsumerLint { selector, .. }) => selector.as_deref(),
            _ => None,
        }
    }

    /// The `sc-lint test` request.
    pub(crate) fn test_request(&self) -> &TestRequest {
        match &self.request {
            Some(CommandRequest::ConsumerTest { request, .. }) => request,
            _ => unreachable!("the consumer test request is tied to the test command"),
        }
    }

    /// `FailFast` iff `--fail-fast` was given to a consumer command.
    pub(crate) fn failure_policy(&self) -> FailurePolicy {
        match &self.request {
            Some(
                CommandRequest::ConsumerTest {
                    fail_fast: true, ..
                }
                | CommandRequest::ConsumerLint {
                    fail_fast: true, ..
                },
            ) => FailurePolicy::FailFast,
            _ => FailurePolicy::KeepGoing,
        }
    }

    /// Platform scope for `lint --consumer`; the default is the host scope.
    pub(crate) fn platform_scope(&self) -> PlatformScope {
        match &self.request {
            Some(CommandRequest::ConsumerLint { scope, .. }) => *scope,
            _ => PlatformScope::Host,
        }
    }

    /// `--rule-filter` value for `lint sc-boundary|sc-portability|sc-runtime`.
    pub(crate) fn rule_filter(&self) -> Option<&str> {
        match &self.request {
            Some(CommandRequest::RuleFilter(filter)) => Some(filter),
            _ => None,
        }
    }

    pub(crate) fn docs_request(&self) -> DocsRequest {
        match self.request {
            Some(CommandRequest::Docs(request)) => request,
            _ => unreachable!("documentation request is tied to the docs command"),
        }
    }

    /// Standalone consumer probes must never initialize repository logging.
    pub const fn skips_logging(&self) -> bool {
        matches!(
            self.command_id,
            CommandId::Version
                | CommandId::CompatibilityCheck
                | CommandId::Setup
                | CommandId::Upgrade
                | CommandId::Init
                | CommandId::Docs
                | CommandId::ConsumerLintCi
                | CommandId::ConsumerTest
        )
    }

    pub fn dispatch_tool(&self) -> Option<&'static str> {
        self.command_id.dispatch_tool()
    }

    pub fn adapter_kind(&self) -> Option<&'static str> {
        self.command_id.adapter_kind()
    }

    pub fn adapter_config_scope(&self) -> Option<&'static str> {
        self.command_id.adapter_config_scope()
    }

    pub fn adapter_script(&self) -> Option<&'static str> {
        self.command_id.adapter_script()
    }

    pub const fn is_xwin_preflight(&self) -> bool {
        self.command_id.is_xwin_preflight()
    }
}

/// Rejects flag combinations clap cannot express: `init` with `--config` or
/// `--root`, `--consumer` off `lint ci`, and `--rule-filter` off the analyzers.
#[expect(
    clippy::result_large_err,
    reason = "Context construction preserves the shared top-level CliError contract before command dispatch starts."
)]
fn validate_command_flags(cli: &Cli, command: &Command) -> Result<(), CliError> {
    if matches!(command, Command::Init { .. }) && (cli.config.is_some() || cli.root.is_some()) {
        return Err(CliError::usage(
            "`sc-lint init --just` does not accept `--config` or `--root`",
        )
        .with_suggested_action(
            "Run it from the consumer repository root; it always manages `sc-lint.toml` there.",
        ));
    }
    if matches!(command, Command::Lint { consumer: true, target, .. } if !matches!(target, crate::LintTarget::Ci))
    {
        return Err(CliError::usage(
                "`--consumer` is only supported by `sc-lint lint ci`",
            )
            .with_suggested_action(
                "Use `sc-lint lint --consumer --config sc-lint.toml ci` for a consumer repository.",
            ));
    }
    if matches!(command, Command::Lint { rule_filter: Some(_), target, .. } if !matches!(target, crate::LintTarget::ScBoundary | crate::LintTarget::ScPortability | crate::LintTarget::ScRuntime))
    {
        return Err(CliError::usage(
            "`--rule-filter` applies only to sc-boundary, sc-portability and sc-runtime",
        ));
    }
    Ok(())
}

/// The per-command payload a dispatched command reads from its context.
fn command_request(command: &Command) -> Option<CommandRequest> {
    match command {
        Command::Setup { dry_run } => Some(CommandRequest::Setup { dry_run: *dry_run }),
        Command::Upgrade { check, dry_run } => Some(CommandRequest::Upgrade {
            check: *check,
            dry_run: *dry_run,
        }),
        Command::Init {
            just,
            check,
            dry_run,
        } => Some(CommandRequest::Init(ConsumerInitRequest {
            just: *just,
            check: *check,
            dry_run: *dry_run,
        })),
        Command::Docs { guide, path } => Some(CommandRequest::Docs(DocsRequest {
            guide: *guide,
            path: *path,
        })),
        Command::Lint {
            consumer: true,
            profile,
            platform_scope,
            fail_fast,
            ..
        } => Some(CommandRequest::ConsumerLint {
            selector: profile.clone(),
            scope: platform_scope.map_or(PlatformScope::Host, PlatformScope::from),
            fail_fast: *fail_fast,
        }),
        Command::Lint {
            rule_filter: Some(filter),
            ..
        } => Some(CommandRequest::RuleFilter(filter.clone())),
        Command::Test {
            selector_and_args,
            list,
            fail_fast,
        } => {
            let (selector, args) = match selector_and_args.split_first() {
                Some((selector, args)) => (Some(selector.clone()), args.to_vec()),
                None => (None, Vec::new()),
            };
            Some(CommandRequest::ConsumerTest {
                request: TestRequest::new(selector, args, *list),
                fail_fast: *fail_fast,
            })
        }
        _ => None,
    }
}

#[expect(
    clippy::result_large_err,
    reason = "CliError is the stable top-level contract type for the bootstrap CLI execution seam."
)]
pub(crate) fn execute(
    context: &CommandContext,
    loaded_config: &LoadedConfig,
) -> Result<CommandSuccess, CliError> {
    match context.id() {
        CommandId::Version => Ok(CommandSuccess::direct(version_payload())),
        CommandId::CompatibilityCheck => Ok(CommandSuccess::direct(
            loaded_config.evaluate_compatibility(context.compatibility_binary())?,
        )),
        CommandId::Docs => Ok(CommandSuccess::direct(crate::docs::run(
            context.docs_request(),
        )?)),
        CommandId::Setup | CommandId::Upgrade => execute_installer_with_version_probe(
            context,
            loaded_config,
            |binary| installer::probe_version(binary).ok(),
            installer::managed_payload_complete,
        ),
        CommandId::Init => Ok(CommandSuccess::direct(crate::config::run_consumer_init(
            context.consumer_init_request(),
        )?)),
        CommandId::ConsumerLintCi => workflow::run_consumer_lint_profile(
            loaded_config,
            context.consumer_selector(),
            context.platform_scope(),
            context.failure_policy(),
        ),
        CommandId::ConsumerTest => workflow::run_consumer_test_profile(
            loaded_config,
            context.test_request(),
            context.failure_policy(),
        ),
        CommandId::LintScBoundary => dispatch::run_sc_boundary(context, loaded_config),
        CommandId::LintScPortability => dispatch::run_sc_portability(context, loaded_config),
        CommandId::LintScRuntime => dispatch::run_sc_runtime(context, loaded_config),
        CommandId::LintFunctionLength => python_adapter::run_python_tool(
            loaded_config,
            python_adapter::PythonTool::FunctionLength,
        ),
        CommandId::LintLineCounts => {
            python_adapter::run_python_tool(loaded_config, python_adapter::PythonTool::LineCounts)
        }
        CommandId::LintIdentityLiterals => python_adapter::run_python_tool(
            loaded_config,
            python_adapter::PythonTool::IdentityLiterals,
        ),
        CommandId::LintFast => {
            workflow::run_lint_profile(loaded_config, crate::cli::LintProfile::Fast)
        }
        CommandId::LintFull => {
            workflow::run_lint_profile(loaded_config, crate::cli::LintProfile::Full)
        }
        CommandId::LintCi => workflow::run_lint_profile(loaded_config, crate::cli::LintProfile::Ci),
        CommandId::ViewGraph => reserved_command(
            context,
            "A later sprint will connect graph-oriented view surfaces once the contract is stable.",
        ),
        CommandId::ViewFindings => {
            python_adapter::run_python_tool(loaded_config, python_adapter::PythonTool::ViewFindings)
        }
        CommandId::CheckNative => workflow::run_check(loaded_config, crate::CheckTarget::Native),
        CommandId::CheckXwin => workflow::run_check(loaded_config, crate::CheckTarget::Xwin),
        CommandId::ClippyNative => workflow::run_clippy(loaded_config, crate::ClippyTarget::Native),
        CommandId::ClippyXwin => workflow::run_clippy(loaded_config, crate::ClippyTarget::Xwin),
        CommandId::Ci => workflow::run_ci(loaded_config),
    }
}

#[expect(
    clippy::result_large_err,
    reason = "Installer dispatch tests preserve the product's top-level CliError contract."
)]
fn execute_installer_with_version_probe(
    context: &CommandContext,
    loaded_config: &LoadedConfig,
    version_probe: impl Fn(&std::path::Path) -> Option<semver::Version>,
    payload_complete: impl Fn(&std::path::Path) -> bool,
) -> Result<CommandSuccess, CliError> {
    match context.id() {
        CommandId::Setup => Ok(CommandSuccess::direct(installer::run_with_probes(
            loaded_config,
            false,
            context.setup_dry_run(),
            version_probe,
            payload_complete,
        )?)),
        CommandId::Upgrade => Ok(CommandSuccess::direct(installer::run_with_probes(
            loaded_config,
            context.upgrade_check(),
            context.upgrade_dry_run(),
            version_probe,
            payload_complete,
        )?)),
        _ => panic!("version-probe dispatch is only for installer commands"),
    }
}

#[cfg(test)]
#[expect(
    clippy::result_large_err,
    reason = "Installer dispatch tests preserve the product's top-level CliError contract."
)]
pub(crate) fn execute_installer_with_test_probes(
    context: &CommandContext,
    loaded_config: &LoadedConfig,
    version_probe: impl Fn(&std::path::Path) -> Option<semver::Version>,
    payload_complete: impl Fn(&std::path::Path) -> bool,
) -> Result<CommandSuccess, CliError> {
    execute_installer_with_version_probe(context, loaded_config, version_probe, payload_complete)
}

#[expect(
    clippy::result_large_err,
    reason = "Reserved bootstrap commands must return the same top-level CliError contract as real command paths."
)]
fn reserved_command(context: &CommandContext, follow_up: &str) -> Result<CommandSuccess, CliError> {
    Err(CliError::capability(format!(
        "{} is a reserved contract surface. {follow_up}",
        context.command_id()
    )))
}

pub(crate) fn version_payload() -> Value {
    json!({
        consts::FIELD_TOOL: consts::SERVICE_NAME,
        consts::FIELD_VERSION: env!("CARGO_PKG_VERSION"),
        "contract_schema": crate::config::VERSION_PROBE_SCHEMA,
        "self_contained": dispatch::self_contained_layout(),
        consts::FIELD_STATUS: "pass",
    })
}