Skip to main content

sc_lint/
command.rs

1use crate::scheduler::FailurePolicy;
2use crate::test_selectors::TestRequest;
3use serde_json::Value;
4use serde_json::json;
5use std::path::Path;
6
7use crate::Cli;
8use crate::CliError;
9use crate::Command;
10use crate::DocsGuide;
11use crate::config::LoadedConfig;
12use crate::consts;
13use crate::contract::ServiceName;
14use crate::dispatch;
15use crate::installer;
16use crate::profile_plan::PlatformScope;
17use crate::python_adapter;
18use crate::workflow;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct DispatchTelemetry {
22    tool: &'static str,
23    finding_count: usize,
24}
25
26impl DispatchTelemetry {
27    pub(crate) const fn new(tool: &'static str, finding_count: usize) -> Self {
28        Self {
29            tool,
30            finding_count,
31        }
32    }
33
34    pub const fn tool(&self) -> &'static str {
35        self.tool
36    }
37
38    pub const fn finding_count(&self) -> usize {
39        self.finding_count
40    }
41}
42
43#[derive(Debug, Clone, PartialEq)]
44pub struct CommandSuccess {
45    pub data: Value,
46    pub dispatch: Option<DispatchTelemetry>,
47}
48
49impl CommandSuccess {
50    pub fn direct(data: Value) -> Self {
51        Self {
52            data,
53            dispatch: None,
54        }
55    }
56
57    pub fn with_dispatch(data: Value, dispatch: DispatchTelemetry) -> Self {
58        Self {
59            data,
60            dispatch: Some(dispatch),
61        }
62    }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub(crate) enum CommandId {
67    Ci,
68    CheckNative,
69    CheckXwin,
70    ClippyNative,
71    ClippyXwin,
72    CompatibilityCheck,
73    Docs,
74    Init,
75    ConsumerTest,
76    Setup,
77    Upgrade,
78    LintCi,
79    ConsumerLintCi,
80    LintFast,
81    LintFull,
82    LintFunctionLength,
83    LintIdentityLiterals,
84    LintLineCounts,
85    LintScBoundary,
86    LintScPortability,
87    LintScRuntime,
88    Version,
89    ViewFindings,
90    ViewGraph,
91}
92
93/// Parsed consumer-integration flags remain a single validated request rather
94/// than three unrelated booleans at the execution boundary.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub(crate) struct ConsumerInitRequest {
97    pub(crate) just: bool,
98    pub(crate) check: bool,
99    pub(crate) dry_run: bool,
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub(crate) struct DocsRequest {
104    pub(crate) guide: Option<DocsGuide>,
105    pub(crate) path: bool,
106}
107
108/// Command-specific payloads stay coupled to the command variant that owns
109/// them. This prevents an unrelated command context from carrying an
110/// impossible `None` payload that would only fail during dispatch.
111#[derive(Debug, Clone, PartialEq, Eq)]
112enum CommandRequest {
113    Setup {
114        dry_run: bool,
115    },
116    Upgrade {
117        check: bool,
118        dry_run: bool,
119    },
120    Init(ConsumerInitRequest),
121    Docs(DocsRequest),
122    /// Consumer test selector, forwarded arguments or `--list`, and `--fail-fast`.
123    ConsumerTest {
124        request: TestRequest,
125        fail_fast: bool,
126    },
127    /// Consumer lint selector (step or named profile), platform scope and `--fail-fast`.
128    ConsumerLint {
129        selector: Option<String>,
130        scope: PlatformScope,
131        fail_fast: bool,
132    },
133    /// `--rule-filter` value forwarded unchanged to an analyzer backend.
134    RuleFilter(String),
135}
136
137impl CommandId {
138    pub fn from_cli_command(command: &Command) -> Self {
139        match command {
140            Command::Lint {
141                target, consumer, ..
142            } => match target {
143                crate::LintTarget::ScBoundary => Self::LintScBoundary,
144                crate::LintTarget::ScPortability => Self::LintScPortability,
145                crate::LintTarget::ScRuntime => Self::LintScRuntime,
146                crate::LintTarget::FunctionLength => Self::LintFunctionLength,
147                crate::LintTarget::LineCounts => Self::LintLineCounts,
148                crate::LintTarget::IdentityLiterals => Self::LintIdentityLiterals,
149                crate::LintTarget::Fast => Self::LintFast,
150                crate::LintTarget::Full => Self::LintFull,
151                crate::LintTarget::Ci if *consumer => Self::ConsumerLintCi,
152                crate::LintTarget::Ci => Self::LintCi,
153            },
154            Command::View { target } => match target {
155                crate::ViewTarget::Graph => Self::ViewGraph,
156                crate::ViewTarget::Findings => Self::ViewFindings,
157            },
158            Command::Check { target } => match target {
159                crate::CheckTarget::Native => Self::CheckNative,
160                crate::CheckTarget::Xwin => Self::CheckXwin,
161            },
162            Command::Clippy { target } => match target {
163                crate::ClippyTarget::Native => Self::ClippyNative,
164                crate::ClippyTarget::Xwin => Self::ClippyXwin,
165            },
166            Command::Compatibility { command } => match command {
167                crate::CompatibilityCommand::Check { .. } => Self::CompatibilityCheck,
168            },
169            Command::Docs { .. } => Self::Docs,
170            Command::Setup { .. } => Self::Setup,
171            Command::Upgrade { .. } => Self::Upgrade,
172            Command::Init { .. } => Self::Init,
173            Command::Test { .. } => Self::ConsumerTest,
174            Command::Version => Self::Version,
175            Command::Ci => Self::Ci,
176        }
177    }
178
179    pub const fn as_str(self) -> &'static str {
180        match self {
181            Self::Ci => "ci",
182            Self::CheckNative => "check.native",
183            Self::CheckXwin => "check.xwin",
184            Self::ClippyNative => "clippy.native",
185            Self::ClippyXwin => "clippy.xwin",
186            Self::CompatibilityCheck => "compatibility.check",
187            Self::Docs => "docs",
188            Self::Init => "init",
189            Self::ConsumerTest => "test",
190            Self::Setup => "setup",
191            Self::Upgrade => "upgrade",
192            Self::LintCi => "lint.ci",
193            Self::ConsumerLintCi => "lint.ci.consumer",
194            Self::LintFast => "lint.fast",
195            Self::LintFull => "lint.full",
196            Self::LintIdentityLiterals => "lint.identity-literals",
197            Self::LintFunctionLength => "lint.function-length",
198            Self::LintLineCounts => "lint.line-counts",
199            Self::LintScBoundary => consts::CMD_BOUNDARY,
200            Self::LintScPortability => consts::CMD_PORTABILITY,
201            Self::LintScRuntime => consts::CMD_RUNTIME,
202            Self::Version => "version",
203            Self::ViewFindings => "view.findings",
204            Self::ViewGraph => "view.graph",
205        }
206    }
207
208    pub const fn service_name(self) -> &'static str {
209        match self {
210            Self::LintScBoundary => "sc-boundary",
211            Self::LintScPortability => "sc-portability",
212            Self::LintScRuntime => "sc-runtime",
213            Self::Ci
214            | Self::CheckNative
215            | Self::CheckXwin
216            | Self::ClippyNative
217            | Self::ClippyXwin
218            | Self::CompatibilityCheck
219            | Self::Docs
220            | Self::Init
221            | Self::ConsumerTest
222            | Self::Setup
223            | Self::Upgrade
224            | Self::LintCi
225            | Self::ConsumerLintCi
226            | Self::LintFast
227            | Self::LintFull
228            | Self::LintFunctionLength
229            | Self::LintIdentityLiterals
230            | Self::LintLineCounts
231            | Self::Version
232            | Self::ViewFindings
233            | Self::ViewGraph => consts::SERVICE_NAME,
234        }
235    }
236
237    pub const fn summary(self) -> &'static str {
238        match self {
239            Self::Ci => "top-level ci orchestration path",
240            Self::CheckNative | Self::CheckXwin => "preflight execution path",
241            Self::ClippyNative | Self::ClippyXwin => "clippy execution path",
242            Self::CompatibilityCheck => "installed sc-lint compatibility preflight",
243            Self::Docs => "offline documentation discovery",
244            Self::Init => "consumer integration generation",
245            Self::ConsumerTest => "consumer test profile orchestration",
246            Self::Setup => "managed sc-lint installation and repair",
247            Self::Upgrade => "managed sc-lint upgrade inspection and activation",
248            Self::LintCi | Self::LintFast | Self::LintFull => "lint profile orchestration path",
249            Self::ConsumerLintCi => "consumer lint profile orchestration",
250            Self::LintIdentityLiterals => "python-backed identity literal lint path",
251            Self::LintFunctionLength => "python-backed function-length lint path",
252            Self::LintLineCounts => "python-backed line-count lint path",
253            Self::LintScBoundary => "boundary analyzer command path",
254            Self::LintScPortability => "portability analyzer command path",
255            Self::LintScRuntime => "runtime analyzer command path",
256            Self::Version => "sc-lint version information",
257            Self::ViewFindings => "python-backed findings view path",
258            Self::ViewGraph => "reserved view contract surface",
259        }
260    }
261
262    pub const fn requires_repo_root(self) -> bool {
263        !matches!(
264            self,
265            Self::Version
266                | Self::CompatibilityCheck
267                | Self::Docs
268                | Self::Setup
269                | Self::Upgrade
270                | Self::Init
271                | Self::ConsumerTest
272                | Self::ConsumerLintCi
273        )
274    }
275
276    pub const fn dispatch_tool(self) -> Option<&'static str> {
277        match self {
278            Self::LintScBoundary => Some(consts::TOOL_BOUNDARY),
279            Self::LintScPortability => Some(consts::TOOL_PORTABILITY),
280            Self::LintScRuntime => Some(consts::TOOL_RUNTIME),
281            _ => match self.python_tool() {
282                Some(tool) => Some(tool.tool_name()),
283                None => None,
284            },
285        }
286    }
287
288    /// Python-backed tool behind this command, if any.
289    pub const fn python_tool(self) -> Option<python_adapter::PythonTool> {
290        match self {
291            Self::LintFunctionLength => Some(python_adapter::PythonTool::FunctionLength),
292            Self::LintLineCounts => Some(python_adapter::PythonTool::LineCounts),
293            Self::LintIdentityLiterals => Some(python_adapter::PythonTool::IdentityLiterals),
294            Self::ViewFindings => Some(python_adapter::PythonTool::ViewFindings),
295            _ => None,
296        }
297    }
298
299    pub fn adapter_kind(self) -> Option<&'static str> {
300        self.python_tool().map(|_| python_adapter::adapter_kind())
301    }
302
303    pub fn adapter_config_scope(self) -> Option<&'static str> {
304        self.python_tool()
305            .map(python_adapter::PythonTool::config_scope)
306    }
307
308    pub fn adapter_script(self) -> Option<&'static str> {
309        self.python_tool()
310            .map(python_adapter::PythonTool::script_relative_path)
311    }
312
313    pub const fn is_xwin_preflight(self) -> bool {
314        matches!(self, Self::CheckXwin | Self::ClippyXwin)
315    }
316
317    pub(crate) const fn is_analyzer_lint(self) -> bool {
318        matches!(
319            self,
320            Self::LintScBoundary | Self::LintScPortability | Self::LintScRuntime
321        )
322    }
323}
324
325#[derive(Debug, Clone, PartialEq, Eq)]
326pub struct CommandContext {
327    command_id: CommandId,
328    service_name: ServiceName,
329    summary: &'static str,
330    requires_repo_root: bool,
331    compatibility_binary: Option<std::path::PathBuf>,
332    backend_search_path: Option<std::ffi::OsString>,
333    request: Option<CommandRequest>,
334}
335
336impl CommandContext {
337    /// Constructs a command context from parsed CLI arguments.
338    ///
339    /// This constructor is fallible: it returns a usage error when `--version`
340    /// is combined with a subcommand or when neither a subcommand nor
341    /// `--version` was provided.
342    #[expect(
343        clippy::result_large_err,
344        reason = "Context construction preserves the shared top-level CliError contract before command dispatch starts."
345    )]
346    pub fn from_cli(cli: &Cli) -> Result<Self, CliError> {
347        Self::from_cli_with_backend_search_path(cli, std::env::var_os("PATH"))
348    }
349
350    /// Constructs a command context with an explicit backend search path.
351    /// Production captures PATH in `from_cli`; tests inject a controlled path.
352    #[expect(
353        clippy::result_large_err,
354        reason = "Context construction preserves the shared top-level CliError contract before command dispatch starts."
355    )]
356    pub(crate) fn from_cli_with_backend_search_path(
357        cli: &Cli,
358        backend_search_path: Option<std::ffi::OsString>,
359    ) -> Result<Self, CliError> {
360        let (command_id, compatibility_binary, request) = match (&cli.command, cli.version) {
361            (Some(command), false) => {
362                validate_command_flags(cli, command)?;
363                let compatibility_binary = match command {
364                    Command::Compatibility {
365                        command: crate::CompatibilityCommand::Check { binary },
366                    } => binary.clone(),
367                    _ => None,
368                };
369                let request = command_request(command);
370                (
371                    CommandId::from_cli_command(command),
372                    compatibility_binary,
373                    request,
374                )
375            }
376            (None, true) => (CommandId::Version, None, None),
377            (Some(_), true) => {
378                return Err(CliError::usage(
379                        "`--version` cannot be combined with a subcommand",
380                    )
381                    .with_suggested_action(
382                        "Use either `sc-lint --version` or a subcommand such as `sc-lint version`.",
383                    ));
384            }
385            (None, false) => {
386                return Err(
387                    CliError::usage("a command is required").with_suggested_action(
388                        "Run `sc-lint --help` to inspect the supported command surface.",
389                    ),
390                );
391            }
392        };
393        let service_name = ServiceName::new(command_id.service_name());
394
395        Ok(Self {
396            command_id,
397            service_name,
398            summary: command_id.summary(),
399            requires_repo_root: command_id.requires_repo_root(),
400            compatibility_binary,
401            backend_search_path,
402            request,
403        })
404    }
405
406    pub(crate) fn backend_search_path(&self) -> Option<&std::ffi::OsStr> {
407        self.backend_search_path.as_deref()
408    }
409
410    pub fn command_id(&self) -> &str {
411        self.command_id.as_str()
412    }
413
414    pub fn service_name(&self) -> &str {
415        self.service_name.as_str()
416    }
417
418    pub(crate) const fn id(&self) -> CommandId {
419        self.command_id
420    }
421
422    pub const fn summary(&self) -> &'static str {
423        self.summary
424    }
425
426    pub(crate) const fn requires_repo_root(&self) -> bool {
427        self.requires_repo_root
428    }
429
430    pub(crate) const fn requires_compatibility_config(&self) -> bool {
431        matches!(
432            self.command_id,
433            CommandId::CompatibilityCheck
434                | CommandId::Setup
435                | CommandId::Upgrade
436                | CommandId::ConsumerLintCi
437                | CommandId::ConsumerTest
438        )
439    }
440
441    pub(crate) fn compatibility_binary(&self) -> Option<&Path> {
442        self.compatibility_binary.as_deref()
443    }
444
445    pub(crate) const fn setup_dry_run(&self) -> bool {
446        matches!(self.request, Some(CommandRequest::Setup { dry_run: true }))
447    }
448
449    pub(crate) const fn upgrade_check(&self) -> bool {
450        matches!(
451            self.request,
452            Some(CommandRequest::Upgrade { check: true, .. })
453        )
454    }
455
456    pub(crate) const fn upgrade_dry_run(&self) -> bool {
457        matches!(
458            self.request,
459            Some(CommandRequest::Upgrade { dry_run: true, .. })
460        )
461    }
462
463    pub(crate) fn consumer_init_request(&self) -> ConsumerInitRequest {
464        match self.request {
465            Some(CommandRequest::Init(request)) => request,
466            _ => unreachable!("consumer initialization request is tied to the init command"),
467        }
468    }
469
470    /// Selector for `lint --consumer`: `None` and `all` run every configured step.
471    pub(crate) fn consumer_selector(&self) -> Option<&str> {
472        match &self.request {
473            Some(CommandRequest::ConsumerLint { selector, .. }) => selector.as_deref(),
474            _ => None,
475        }
476    }
477
478    /// The `sc-lint test` request.
479    pub(crate) fn test_request(&self) -> &TestRequest {
480        match &self.request {
481            Some(CommandRequest::ConsumerTest { request, .. }) => request,
482            _ => unreachable!("the consumer test request is tied to the test command"),
483        }
484    }
485
486    /// `FailFast` iff `--fail-fast` was given to a consumer command.
487    pub(crate) fn failure_policy(&self) -> FailurePolicy {
488        match &self.request {
489            Some(
490                CommandRequest::ConsumerTest {
491                    fail_fast: true, ..
492                }
493                | CommandRequest::ConsumerLint {
494                    fail_fast: true, ..
495                },
496            ) => FailurePolicy::FailFast,
497            _ => FailurePolicy::KeepGoing,
498        }
499    }
500
501    /// Platform scope for `lint --consumer`; the default is the host scope.
502    pub(crate) fn platform_scope(&self) -> PlatformScope {
503        match &self.request {
504            Some(CommandRequest::ConsumerLint { scope, .. }) => *scope,
505            _ => PlatformScope::Host,
506        }
507    }
508
509    /// `--rule-filter` value for `lint sc-boundary|sc-portability|sc-runtime`.
510    pub(crate) fn rule_filter(&self) -> Option<&str> {
511        match &self.request {
512            Some(CommandRequest::RuleFilter(filter)) => Some(filter),
513            _ => None,
514        }
515    }
516
517    pub(crate) fn docs_request(&self) -> DocsRequest {
518        match self.request {
519            Some(CommandRequest::Docs(request)) => request,
520            _ => unreachable!("documentation request is tied to the docs command"),
521        }
522    }
523
524    /// Standalone consumer probes must never initialize repository logging.
525    pub const fn skips_logging(&self) -> bool {
526        matches!(
527            self.command_id,
528            CommandId::Version
529                | CommandId::CompatibilityCheck
530                | CommandId::Setup
531                | CommandId::Upgrade
532                | CommandId::Init
533                | CommandId::Docs
534                | CommandId::ConsumerLintCi
535                | CommandId::ConsumerTest
536        )
537    }
538
539    pub fn dispatch_tool(&self) -> Option<&'static str> {
540        self.command_id.dispatch_tool()
541    }
542
543    pub fn adapter_kind(&self) -> Option<&'static str> {
544        self.command_id.adapter_kind()
545    }
546
547    pub fn adapter_config_scope(&self) -> Option<&'static str> {
548        self.command_id.adapter_config_scope()
549    }
550
551    pub fn adapter_script(&self) -> Option<&'static str> {
552        self.command_id.adapter_script()
553    }
554
555    pub const fn is_xwin_preflight(&self) -> bool {
556        self.command_id.is_xwin_preflight()
557    }
558}
559
560/// Rejects flag combinations clap cannot express: `init` with `--config` or
561/// `--root`, `--consumer` off `lint ci`, and `--rule-filter` off the analyzers.
562#[expect(
563    clippy::result_large_err,
564    reason = "Context construction preserves the shared top-level CliError contract before command dispatch starts."
565)]
566fn validate_command_flags(cli: &Cli, command: &Command) -> Result<(), CliError> {
567    if matches!(command, Command::Init { .. }) && (cli.config.is_some() || cli.root.is_some()) {
568        return Err(CliError::usage(
569            "`sc-lint init --just` does not accept `--config` or `--root`",
570        )
571        .with_suggested_action(
572            "Run it from the consumer repository root; it always manages `sc-lint.toml` there.",
573        ));
574    }
575    if matches!(command, Command::Lint { consumer: true, target, .. } if !matches!(target, crate::LintTarget::Ci))
576    {
577        return Err(CliError::usage(
578                "`--consumer` is only supported by `sc-lint lint ci`",
579            )
580            .with_suggested_action(
581                "Use `sc-lint lint --consumer --config sc-lint.toml ci` for a consumer repository.",
582            ));
583    }
584    if matches!(command, Command::Lint { rule_filter: Some(_), target, .. } if !matches!(target, crate::LintTarget::ScBoundary | crate::LintTarget::ScPortability | crate::LintTarget::ScRuntime))
585    {
586        return Err(CliError::usage(
587            "`--rule-filter` applies only to sc-boundary, sc-portability and sc-runtime",
588        ));
589    }
590    Ok(())
591}
592
593/// The per-command payload a dispatched command reads from its context.
594fn command_request(command: &Command) -> Option<CommandRequest> {
595    match command {
596        Command::Setup { dry_run } => Some(CommandRequest::Setup { dry_run: *dry_run }),
597        Command::Upgrade { check, dry_run } => Some(CommandRequest::Upgrade {
598            check: *check,
599            dry_run: *dry_run,
600        }),
601        Command::Init {
602            just,
603            check,
604            dry_run,
605        } => Some(CommandRequest::Init(ConsumerInitRequest {
606            just: *just,
607            check: *check,
608            dry_run: *dry_run,
609        })),
610        Command::Docs { guide, path } => Some(CommandRequest::Docs(DocsRequest {
611            guide: *guide,
612            path: *path,
613        })),
614        Command::Lint {
615            consumer: true,
616            profile,
617            platform_scope,
618            fail_fast,
619            ..
620        } => Some(CommandRequest::ConsumerLint {
621            selector: profile.clone(),
622            scope: platform_scope.map_or(PlatformScope::Host, PlatformScope::from),
623            fail_fast: *fail_fast,
624        }),
625        Command::Lint {
626            rule_filter: Some(filter),
627            ..
628        } => Some(CommandRequest::RuleFilter(filter.clone())),
629        Command::Test {
630            selector_and_args,
631            list,
632            fail_fast,
633        } => {
634            let (selector, args) = match selector_and_args.split_first() {
635                Some((selector, args)) => (Some(selector.clone()), args.to_vec()),
636                None => (None, Vec::new()),
637            };
638            Some(CommandRequest::ConsumerTest {
639                request: TestRequest::new(selector, args, *list),
640                fail_fast: *fail_fast,
641            })
642        }
643        _ => None,
644    }
645}
646
647#[expect(
648    clippy::result_large_err,
649    reason = "CliError is the stable top-level contract type for the bootstrap CLI execution seam."
650)]
651pub(crate) fn execute(
652    context: &CommandContext,
653    loaded_config: &LoadedConfig,
654) -> Result<CommandSuccess, CliError> {
655    match context.id() {
656        CommandId::Version => Ok(CommandSuccess::direct(version_payload())),
657        CommandId::CompatibilityCheck => Ok(CommandSuccess::direct(
658            loaded_config.evaluate_compatibility(context.compatibility_binary())?,
659        )),
660        CommandId::Docs => Ok(CommandSuccess::direct(crate::docs::run(
661            context.docs_request(),
662        )?)),
663        CommandId::Setup | CommandId::Upgrade => execute_installer_with_version_probe(
664            context,
665            loaded_config,
666            |binary| installer::probe_version(binary).ok(),
667            installer::managed_payload_complete,
668        ),
669        CommandId::Init => Ok(CommandSuccess::direct(crate::config::run_consumer_init(
670            context.consumer_init_request(),
671        )?)),
672        CommandId::ConsumerLintCi => workflow::run_consumer_lint_profile(
673            loaded_config,
674            context.consumer_selector(),
675            context.platform_scope(),
676            context.failure_policy(),
677        ),
678        CommandId::ConsumerTest => workflow::run_consumer_test_profile(
679            loaded_config,
680            context.test_request(),
681            context.failure_policy(),
682        ),
683        CommandId::LintScBoundary => dispatch::run_sc_boundary(context, loaded_config),
684        CommandId::LintScPortability => dispatch::run_sc_portability(context, loaded_config),
685        CommandId::LintScRuntime => dispatch::run_sc_runtime(context, loaded_config),
686        CommandId::LintFunctionLength => python_adapter::run_python_tool(
687            loaded_config,
688            python_adapter::PythonTool::FunctionLength,
689        ),
690        CommandId::LintLineCounts => {
691            python_adapter::run_python_tool(loaded_config, python_adapter::PythonTool::LineCounts)
692        }
693        CommandId::LintIdentityLiterals => python_adapter::run_python_tool(
694            loaded_config,
695            python_adapter::PythonTool::IdentityLiterals,
696        ),
697        CommandId::LintFast => {
698            workflow::run_lint_profile(loaded_config, crate::cli::LintProfile::Fast)
699        }
700        CommandId::LintFull => {
701            workflow::run_lint_profile(loaded_config, crate::cli::LintProfile::Full)
702        }
703        CommandId::LintCi => workflow::run_lint_profile(loaded_config, crate::cli::LintProfile::Ci),
704        CommandId::ViewGraph => reserved_command(
705            context,
706            "A later sprint will connect graph-oriented view surfaces once the contract is stable.",
707        ),
708        CommandId::ViewFindings => {
709            python_adapter::run_python_tool(loaded_config, python_adapter::PythonTool::ViewFindings)
710        }
711        CommandId::CheckNative => workflow::run_check(loaded_config, crate::CheckTarget::Native),
712        CommandId::CheckXwin => workflow::run_check(loaded_config, crate::CheckTarget::Xwin),
713        CommandId::ClippyNative => workflow::run_clippy(loaded_config, crate::ClippyTarget::Native),
714        CommandId::ClippyXwin => workflow::run_clippy(loaded_config, crate::ClippyTarget::Xwin),
715        CommandId::Ci => workflow::run_ci(loaded_config),
716    }
717}
718
719#[expect(
720    clippy::result_large_err,
721    reason = "Installer dispatch tests preserve the product's top-level CliError contract."
722)]
723fn execute_installer_with_version_probe(
724    context: &CommandContext,
725    loaded_config: &LoadedConfig,
726    version_probe: impl Fn(&std::path::Path) -> Option<semver::Version>,
727    payload_complete: impl Fn(&std::path::Path) -> bool,
728) -> Result<CommandSuccess, CliError> {
729    match context.id() {
730        CommandId::Setup => Ok(CommandSuccess::direct(installer::run_with_probes(
731            loaded_config,
732            false,
733            context.setup_dry_run(),
734            version_probe,
735            payload_complete,
736        )?)),
737        CommandId::Upgrade => Ok(CommandSuccess::direct(installer::run_with_probes(
738            loaded_config,
739            context.upgrade_check(),
740            context.upgrade_dry_run(),
741            version_probe,
742            payload_complete,
743        )?)),
744        _ => panic!("version-probe dispatch is only for installer commands"),
745    }
746}
747
748#[cfg(test)]
749#[expect(
750    clippy::result_large_err,
751    reason = "Installer dispatch tests preserve the product's top-level CliError contract."
752)]
753pub(crate) fn execute_installer_with_test_probes(
754    context: &CommandContext,
755    loaded_config: &LoadedConfig,
756    version_probe: impl Fn(&std::path::Path) -> Option<semver::Version>,
757    payload_complete: impl Fn(&std::path::Path) -> bool,
758) -> Result<CommandSuccess, CliError> {
759    execute_installer_with_version_probe(context, loaded_config, version_probe, payload_complete)
760}
761
762#[expect(
763    clippy::result_large_err,
764    reason = "Reserved bootstrap commands must return the same top-level CliError contract as real command paths."
765)]
766fn reserved_command(context: &CommandContext, follow_up: &str) -> Result<CommandSuccess, CliError> {
767    Err(CliError::capability(format!(
768        "{} is a reserved contract surface. {follow_up}",
769        context.command_id()
770    )))
771}
772
773pub(crate) fn version_payload() -> Value {
774    json!({
775        consts::FIELD_TOOL: consts::SERVICE_NAME,
776        consts::FIELD_VERSION: env!("CARGO_PKG_VERSION"),
777        "contract_schema": crate::config::VERSION_PROBE_SCHEMA,
778        "self_contained": dispatch::self_contained_layout(),
779        consts::FIELD_STATUS: "pass",
780    })
781}