Skip to main content

fallow_api/
lib.rs

1//! Programmatic API contract types for fallow.
2//!
3//! Runtime execution for dead-code, duplication and health lives here. The
4//! default health runner, `EngineHealthRunner`, runs the engine pipeline.
5//! Tests and hosts can inject a different runner. This crate owns the
6//! CLI-independent option, error, and output contracts so NAPI, future Rust
7//! embedders, and the engine facade can share them without depending on the
8//! CLI crate.
9#![warn(missing_docs)]
10#![cfg_attr(
11    test,
12    allow(
13        clippy::expect_used,
14        reason = "tests use expect to keep fixture setup concise"
15    )
16)]
17
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20use std::sync::atomic::AtomicBool;
21
22use fallow_config::EmailMode;
23use fallow_output::EffortEstimate;
24use serde::Serialize;
25
26mod analysis_context;
27mod audit_complexity;
28/// Stable per-finding keys and audit ledgers that compare head results against
29/// a base snapshot, plus helpers that annotate output JSON with
30/// introduced-vs-pre-existing attribution.
31pub mod audit_keys;
32pub mod audit_output;
33pub mod audit_run;
34pub mod combined_output;
35/// One-line-per-finding compact text builders for dead-code, grouped, health,
36/// and duplication output.
37pub mod compact_output;
38pub mod coverage;
39pub mod dead_code_codeclimate;
40pub mod dead_code_sarif;
41pub mod decision_surface;
42pub mod dependency_deltas;
43pub mod diff_risk;
44pub mod doctor;
45pub mod dupes_output;
46pub mod editor;
47pub mod explain;
48pub mod grouped_output;
49pub mod health_codeclimate;
50mod health_groups_markdown;
51pub mod json_output;
52pub mod list_output;
53mod list_runtime;
54/// Markdown report builders for dead-code, grouped, duplication, health, and
55/// walkthrough output.
56pub mod markdown_output;
57pub mod mutation;
58mod next_steps;
59pub mod output_contracts;
60pub mod ownership;
61pub mod review_deltas;
62pub mod routing;
63pub mod runtime;
64mod runtime_json;
65mod runtime_output;
66pub mod sarif_output;
67/// JSON Schema documents and zero-config rule defaults re-exported from
68/// `fallow-config` for embedders such as the MCP resource surface.
69pub mod schemas;
70pub mod security_output;
71/// Local-only advisory similar-code discovery and provider status.
72pub mod similar_code;
73mod type_aware;
74pub use analysis_context::{ProgrammaticAnalysisContext, resolve_programmatic_analysis_context};
75pub use audit_output::{
76    AuditAttribution, AuditCodeClimateOutputInput, AuditJsonHeaderInput, AuditJsonOutputInput,
77    AuditSarifOutputInput, AuditSummary, AuditVerdict, attach_audit_diff_risk_attribution,
78    attach_audit_duplication_demotion_attribution, attach_audit_styling_attribution,
79    attach_audit_wire_attribution, build_audit_codeclimate, build_audit_codeclimate_issues,
80    build_audit_header_json, build_audit_header_map, build_audit_sarif,
81    build_diff_risk_codeclimate, build_review_brief_header, serialize_audit_json,
82};
83pub use combined_output::{
84    CombinedCheckJsonSection, CombinedJsonOutputInput, serialize_combined_dupes_json,
85    serialize_combined_health_json, serialize_combined_json,
86};
87pub use compact_output::{
88    build_compact_lines, build_diff_risk_compact_lines, build_duplication_compact_lines,
89    build_grouped_compact_lines, build_health_compact_lines,
90};
91pub use coverage::{
92    CoverageInputError, CoverageInputSource, CoverageInputs, resolve_coverage_inputs,
93};
94pub use dead_code_codeclimate::build_codeclimate;
95pub use dead_code_sarif::build_sarif;
96pub use doctor::{DoctorOptions, run_doctor, run_doctor_with_cache_dir};
97pub use dupes_output::{
98    AttributedCloneGroup, AttributedCloneGroupFinding, AttributedInstance, CloneDemotionReason,
99    CloneFamilyFinding, CloneGroupFinding, CombinedDupesSection, DupesReportPayload,
100    DuplicationGroup, DuplicationGrouping, build_duplication_codeclimate,
101};
102pub use editor::{
103    ChangedFilesError, EditorAnalysisOutput, EditorAnalysisResults, EditorAnalysisSession,
104    EditorCloneFamily, EditorCloneFingerprintSet, EditorCloneGroup, EditorCloneInstance,
105    EditorDeadCodeAnalysisOutput, EditorDuplicationReport, EditorDuplicationStats,
106    EditorInlineComplexityExceeded, EditorInlineComplexityFinding, EditorMirroredDirectory,
107    EditorProjectAnalysisOutput, EditorRefactoringKind, EditorRefactoringSuggestion,
108    EditorSessionParseCounts, collect_inline_complexity, editor_duplicates, editor_extract,
109    editor_results, editor_security, editor_suppress, filter_inline_complexity_by_change_scope,
110    filter_inline_complexity_by_changed_files, resolve_git_toplevel,
111    try_get_changed_files_with_toplevel,
112};
113pub use explain::{
114    AUDIT_RULES, CHECK_RULES, DUPES_RULES, FLAGS_RULES, HEALTH_RULES, RuleDef, RuleGuide,
115    SECURITY_RULES, all_rules, bare_rule_id, coverage_analyze_meta, coverage_setup_meta,
116    explain_issue_type, rule_by_id, rule_by_token, rule_command, rule_docs_url, rule_guide,
117    rule_severity_key, security_meta, serialize_explain_programmatic_json, unknown_explain_error,
118};
119pub use fallow_config::levenshtein::closest_match;
120pub use fallow_config::{AuditGate, AuditWorsened, HealthConfig, TypeAwareRequire};
121/// Engine-owned change scope of one run: a global changed-file set or the
122/// per-workspace Git baselines of `workspaces.changedSince`.
123pub use fallow_engine::change_scope::{
124    ChangeScope, ChangeScopeOwner, ChangeScopeRequest, first_package_baselines,
125    package_baseline_statuses,
126};
127/// Engine-owned per-workspace Git baseline state used by analysis surfaces.
128pub use fallow_engine::package_baselines::{PackageBaselineError, PackageChangeScope};
129/// Stack size for threads that run analysis, and the registration that lets a
130/// bounded parse stay on such a thread.
131///
132/// A process that runs analysis outside
133/// [`ProgrammaticAnalysisContext::install`], such as the LSP server, gives its
134/// own threads this stack size and registers it at thread start.
135pub use fallow_engine::thread_pool::{WORKER_STACK_SIZE, register_thread_stack};
136/// Parsed modules that a long-lived process keeps across analysis calls.
137///
138/// A process that runs many calls on the same project, such as the MCP
139/// server, installs a store once. Each later analysis session then takes the
140/// modules of an unchanged file list from memory and does no parse work.
141pub use fallow_engine::warm_parse;
142/// Shared JSON and editor notification row for an applied package Git ref.
143pub use fallow_output::PackageBaselineStatus;
144pub use fallow_output::serialize_similar_code_json_output;
145pub use fallow_types::trace::{
146    CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace, ReExportChain,
147    TracedCloneGroup, TracedExport, TracedReExport,
148};
149pub use fallow_types::trace_usage::{
150    DependencyUsage, DependencyUsageQuery, SitePageRequest, UsageQueryError,
151};
152pub use grouped_output::{
153    ResultGroup, UNOWNED_GROUP_LABEL, build_duplication_grouping_with, group_analysis_results_with,
154    health_signal_header_part, largest_clone_group_owner_with,
155};
156pub use health_codeclimate::build_health_codeclimate;
157pub use health_groups_markdown::build_health_groups_markdown;
158pub use json_output::{
159    CheckJsonExtraOutputs, CheckJsonOutputInput, CheckJsonPayloadInput, DuplicationJsonOutputInput,
160    GroupedCheckJsonOutputInput, GroupedDuplicationJsonOutputInput, serialize_check_json,
161    serialize_check_json_payload, serialize_duplication_json, serialize_grouped_check_json,
162    serialize_grouped_duplication_json,
163};
164pub use list_output::{
165    ListJsonEnvelope, ListJsonOutputInput, build_list_json_output, serialize_list_json_output,
166};
167pub use list_runtime::{
168    BoundaryData, ListBoundariesOptions, ListBoundariesProgrammaticOutput, LogicalGroupInfo,
169    ProjectInfoOptions, ProjectInfoProgrammaticOutput, RuleInfo, ZoneInfo, boundary_data_to_output,
170    compute_boundary_data, run_list_boundaries, run_project_info,
171    serialize_list_boundaries_programmatic_json, serialize_project_info_programmatic_json,
172};
173pub use markdown_output::{
174    ComplexityListing, build_diff_risk_markdown, build_duplication_markdown,
175    build_grouped_markdown, build_health_markdown, build_markdown, build_walkthrough_markdown,
176};
177pub use mutation::{
178    MutationProgress, MutationProgressSink, MutationRunOptions, MutationRunScope,
179    apply_mutation_verdicts, validate_mutation_verdicts,
180};
181pub use output_contracts::{
182    AuditOutput, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
183    BoundariesListing, CombinedOutput, FallowOutput, ImpactOutput, ListBoundariesOutput,
184    ListEntryPointOutput, ListOutput, ListPluginOutput, ReviewBriefWireOutput, SecurityGate,
185    SecurityOutput, SecurityOutputConfig, SecuritySummaryOutput, SimilarCodeCandidateSnapshot,
186    SimilarCodeOutput, TraceOutput, WorkspacesOutput,
187};
188pub use runtime::TYPE_AWARE_CONFIG_UNSUPPORTED;
189pub use runtime::{
190    AUDIT_CONFIG_BASELINE_UNSUPPORTED, ArchitectureOutput, ArchitectureProgrammaticOutput,
191    AuditProgrammaticKeySnapshot, AuditProgrammaticOutput, BoundaryViolationsOutput,
192    BoundaryViolationsProgrammaticOutput, CircularDependenciesOutput,
193    CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput, DeadCodeOutput,
194    DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput, DuplicationOutput,
195    DuplicationProgrammaticOutput, EngineHealthRunner, FeatureFlagsOutput,
196    FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
197    ProgrammaticHealthAnalysis, ProgrammaticHealthNextStepFacts, ProgrammaticHealthRun,
198    ProgrammaticHealthRunner, TraceClassMemberOutput, TraceCloneBenchmarkResult, TraceCloneOutput,
199    TraceCloneProgrammaticOutput, TraceDependencyOutput, TraceDependencyProgrammaticOutput,
200    TraceErrorOutput, TraceErrorProgrammaticOutput, TraceExportOutput,
201    TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
202    TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
203    benchmark_trace_clone_compact_json, benchmark_trace_graph_family_compact_json,
204    inspect_similar_code, load_health_config, parse_similar_code_candidate_snapshot, plan_mutation,
205    review_similar_code, run_architecture, run_audit, run_boundary_violations,
206    run_circular_dependencies, run_combined, run_complexity_with_runner, run_dead_code,
207    run_dead_code_with_baseline, run_decision_surface, run_duplication, run_feature_flags,
208    run_health, run_health_with_runner, run_mutation, run_mutation_with_progress, run_similar_code,
209    run_trace_clone, run_trace_dependency, run_trace_error, run_trace_export, run_trace_file,
210    run_trace_import_path, select_similar_code_candidate_snapshot, serialize_health_report_json,
211};
212pub use runtime_json::{
213    serialize_architecture_programmatic_json, serialize_audit_programmatic_json,
214    serialize_boundary_violations_programmatic_json,
215    serialize_circular_dependencies_programmatic_json, serialize_combined_programmatic_json,
216    serialize_dead_code_programmatic_json, serialize_decision_surface_programmatic_json,
217    serialize_duplication_programmatic_json, serialize_feature_flags_programmatic_json,
218    serialize_health_programmatic_json, serialize_trace_clone_programmatic_json,
219    serialize_trace_dependency_programmatic_json, serialize_trace_error_programmatic_json,
220    serialize_trace_export_programmatic_json, serialize_trace_file_programmatic_json,
221    serialize_trace_import_path_programmatic_json,
222};
223pub use sarif_output::{
224    annotate_sarif_results, build_duplication_sarif, build_grouped_duplication_sarif,
225    build_health_sarif,
226};
227pub use security_output::SecurityGateMode;
228pub use type_aware::{
229    DEFAULT_BACKEND_FAMILY as DEFAULT_TYPE_AWARE_BACKEND_FAMILY, SemanticCouplingOutcome,
230    SemanticDeadCodeOutcome, SemanticInspectOutcome, TypeAwareError, TypeAwareFileChanges,
231    TypeAwareOutcome, TypeAwareSession, TypeAwareStatus, discard_unverified_semantic_candidates,
232    inspect_symbol as inspect_type_aware_symbol, merge_type_aware_meta,
233    refine_configured_dead_code_results as refine_type_aware_results_with_config,
234    shutdown_type_aware_sidecars, status as type_aware_status,
235    symbol_impact as run_type_aware_symbol_impact, symbol_impact as type_aware_symbol_impact,
236    terminate_active_type_aware_sidecars, trace_symbol as run_type_aware_symbol_trace,
237    trace_symbol as trace_type_aware_symbol, type_coupling as analyze_type_coupling,
238};
239
240/// Long names of the analysis-affecting global CLI flags that
241/// [`AnalysisOptions`] mirrors for embedders.
242///
243/// A contract test in the CLI crate asserts this list stays in sync with the
244/// clap globals, so drift between the CLI surface and the programmatic
245/// options is caught at test time.
246pub const COMMON_ANALYSIS_OPTION_FLAGS: &[&str] = &[
247    "root",
248    "config",
249    "no-cache",
250    "threads",
251    "changed-since",
252    "diff-file",
253    "production",
254    "workspace",
255    "changed-workspaces",
256    "explain",
257    "allow-remote-extends",
258];
259
260/// Structured error surface for the programmatic API.
261#[derive(Debug, Clone, Serialize)]
262pub struct ProgrammaticError {
263    /// Human-readable description; also the `Display` output.
264    pub message: String,
265    /// Process exit code the CLI maps this failure to.
266    pub exit_code: u8,
267    /// Stable machine-readable code such as `FALLOW_INVALID_COVERAGE_PATH`.
268    pub code: Option<String>,
269    /// Optional remediation hint for the caller.
270    pub help: Option<String>,
271    /// Dotted path of the offending input, such as `health.coverage`.
272    pub context: Option<String>,
273}
274
275impl ProgrammaticError {
276    /// Create an error from the required message and exit code, with all
277    /// optional fields left empty.
278    #[must_use]
279    pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
280        Self {
281            message: message.into(),
282            exit_code,
283            code: None,
284            help: None,
285            context: None,
286        }
287    }
288
289    /// Attach a remediation hint shown to the caller alongside the message.
290    #[must_use]
291    pub fn with_help(mut self, help: impl Into<String>) -> Self {
292        self.help = Some(help.into());
293        self
294    }
295
296    /// Attach a stable machine-readable code such as
297    /// `FALLOW_INVALID_COVERAGE_PATH`.
298    #[must_use]
299    pub fn with_code(mut self, code: impl Into<String>) -> Self {
300        self.code = Some(code.into());
301        self
302    }
303
304    /// Attach the dotted path of the offending input, such as
305    /// `health.coverage`.
306    #[must_use]
307    pub fn with_context(mut self, context: impl Into<String>) -> Self {
308        self.context = Some(context.into());
309        self
310    }
311}
312
313impl std::fmt::Display for ProgrammaticError {
314    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
315        write!(f, "{}", self.message)
316    }
317}
318
319impl std::error::Error for ProgrammaticError {}
320
321/// Shared options for all one-shot analyses.
322#[derive(Debug, Clone, Default)]
323pub struct AnalysisOptions {
324    /// Project root to analyze. `None` resolves to the current working
325    /// directory.
326    pub root: Option<PathBuf>,
327    /// Explicit config file path. `None` uses config discovery from the root.
328    pub config_path: Option<PathBuf>,
329    /// Permit `https://` config inheritance for this analysis call.
330    pub allow_remote_extends: bool,
331    /// Bypass the on-disk analysis cache for this call.
332    pub no_cache: bool,
333    /// Worker thread count. `None` picks the default; `Some(0)` is rejected.
334    pub threads: Option<usize>,
335    /// Explicit unified diff file that scopes changed-code analysis.
336    ///
337    /// Relative file paths resolve against the analysis root. Patch headers
338    /// are placed relative to that root or its Git repository toplevel.
339    /// A readable patch with foreign or ambiguous paths leaves the analysis
340    /// at full scope and records a `not-applied` diff-filter request outcome.
341    /// Empty and deletion-only patches apply an empty scope.
342    ///
343    /// A file that cannot be read fails the call with
344    /// `FALLOW_INVALID_DIFF_FILE`: the caller named it and can fix it.
345    /// An explicit file never falls back to `ambient_diff_file`.
346    pub diff_file: Option<PathBuf>,
347    /// Unified diff file inherited from the environment (`FALLOW_DIFF_FILE`)
348    /// rather than named by the caller. Read only when `diff_file` is unset.
349    ///
350    /// A file that cannot be read or placed does not fail the call. The
351    /// analysis runs at full scope and `request_outcomes["diff-filter"]` states
352    /// the reason, exactly as the CLI does for the same variable: a caller
353    /// cannot fix a CI environment it inherited (issue #2799).
354    pub ambient_diff_file: Option<PathBuf>,
355    /// Legacy convenience override. `true` forces production mode; `false`
356    /// defers to config unless `production_override` is set.
357    pub production: bool,
358    /// Explicit production override from an embedder option. `None` means
359    /// use the project config for the current analysis.
360    pub production_override: Option<bool>,
361    /// Git base reference that scopes analysis to files changed since it.
362    ///
363    /// A ref that does not resolve fails the call with
364    /// `FALLOW_CHANGED_FILES_FAILED`: the caller named it and can fix it.
365    pub changed_since: Option<String>,
366    /// Git base reference inherited from the environment
367    /// (`FALLOW_CHANGED_SINCE`) rather than named by the caller. Read only when
368    /// `changed_since` is unset.
369    ///
370    /// A ref that does not resolve does not fail the call. The analysis runs at
371    /// full scope and `request_outcomes["changed-since"]` states the reason,
372    /// exactly as the CLI does for `--changed-since`.
373    pub ambient_changed_since: Option<String>,
374    /// Ignore the per-package refs of `workspaces.changedSince` for this call,
375    /// as `--no-package-baselines` does on the CLI. Every workspace package is
376    /// then analyzed in full scope.
377    pub no_package_baselines: bool,
378    /// Restrict analysis to the named workspace packages.
379    pub workspace: Option<Vec<String>>,
380    /// Restrict analysis to workspaces changed since the given git reference.
381    pub changed_workspaces: Option<String>,
382    /// Include rule and metric explanations (`_meta`) in machine output.
383    pub explain: bool,
384    /// Optional project-wide TypeScript semantic analysis. Disabled by default
385    /// and never changes compiler or typed-lint ownership.
386    pub type_aware: TypeAwareOptions,
387    /// Caller-owned cooperative cancellation for this analysis.
388    ///
389    /// Setting the flag asks the analysis to stop at its next stage boundary
390    /// and return a `FALLOW_CANCELLED` error. `None`, the default, is an
391    /// analysis that always runs to completion.
392    ///
393    /// The field is on the shared options struct, but the entry points do not
394    /// all honor it, so read the one being called before relying on it:
395    ///
396    /// - Cancelled at the entry, on both sides of the per-file parse loop, and
397    ///   at each pipeline stage boundary: [`run_dead_code`],
398    ///   [`run_circular_dependencies`], [`run_boundary_violations`],
399    ///   [`run_architecture`],
400    ///   [`run_combined`], [`run_duplication`], [`run_feature_flags`], and the
401    ///   four trace routes.
402    /// - Cancelled only at the boundaries around config load and file
403    ///   discovery, because they are the whole run: [`run_project_info`] and
404    ///   [`run_list_boundaries`].
405    /// - Cancelled only at the entry, then run to completion:
406    ///   [`run_health`], which hands off to a runner that builds its own
407    ///   session below these options.
408    /// - Not cancellable at all: [`run_decision_surface`] and
409    ///   [`run_similar_code`].
410    ///
411    /// The stop is cooperative everywhere it exists, so it has no upper bound:
412    /// it is only as prompt as the longest stage holding no check, and
413    /// duplication detection and the dead-code detectors are each seconds of
414    /// uninterruptible work on a large repository. A caller that needs a
415    /// bounded stop has to run Fallow as a child process and kill it.
416    pub cancellation: Option<Arc<AtomicBool>>,
417}
418
419/// Typed options for Fallow's optional TypeScript semantic companion.
420#[derive(Debug, Clone, Default, PartialEq, Eq)]
421pub struct TypeAwareOptions {
422    /// `Some(true)` turns on TypeScript semantic refinement for this call, as
423    /// `--type-aware` does. `Some(false)` keeps the call syntactic, as
424    /// `--no-type-aware` does, also when `FALLOW_TYPE_AWARE` or the config
425    /// turns it on. `None` follows `FALLOW_TYPE_AWARE` and the config. The
426    /// typed runners cannot run type-aware analysis from those layers, so they
427    /// return [`TYPE_AWARE_CONFIG_UNSUPPORTED`] when a layer turns it on.
428    pub enabled: Option<bool>,
429    /// Explicit TypeScript project paths handed to the semantic sidecar.
430    /// Empty defers to project discovery.
431    pub projects: Vec<PathBuf>,
432    /// How strictly semantic completion is required before results are kept.
433    pub require: fallow_config::TypeAwareRequire,
434}
435
436impl TypeAwareOptions {
437    /// The caller requested type-aware analysis for this call.
438    #[must_use]
439    pub const fn requested(&self) -> bool {
440        matches!(self.enabled, Some(true))
441    }
442}
443
444/// Issue-type filters for the dead-code analysis.
445///
446/// Each flag opts one issue type into the report. When no flag is enabled the
447/// analysis reports every issue type.
448#[derive(Debug, Clone, Default, PartialEq, Eq)]
449pub struct DeadCodeFilters {
450    /// Files never reached from any entry point.
451    pub unused_files: bool,
452    /// Exported symbols never imported elsewhere.
453    pub unused_exports: bool,
454    /// Declared dependencies never imported.
455    pub unused_deps: bool,
456    /// Exported types never referenced.
457    pub unused_types: bool,
458    /// Exported APIs that expose non-exported types.
459    pub private_type_leaks: bool,
460    /// Exports marked `@deprecated` that are still in use.
461    pub deprecated_exports_in_use: bool,
462    /// Enum members never read.
463    pub unused_enum_members: bool,
464    /// Class members never used outside their declaration.
465    pub unused_class_members: bool,
466    /// Members of an exported TypeScript namespace that no code reads.
467    pub unused_namespace_members: bool,
468    /// Store members (for example Pinia) never used outside the store.
469    pub unused_store_members: bool,
470    /// `inject` calls with no matching `provide`.
471    pub unprovided_injects: bool,
472    /// Components never rendered by any template or JSX.
473    pub unrendered_components: bool,
474    /// Declared component props never used.
475    pub unused_component_props: bool,
476    /// Review optional props omitted by known reachable callers.
477    pub absent_component_props: bool,
478    /// Declared component emits never used.
479    pub unused_component_emits: bool,
480    /// Declared component inputs never bound.
481    pub unused_component_inputs: bool,
482    /// Declared component outputs never listened to.
483    pub unused_component_outputs: bool,
484    /// Svelte component events never listened to.
485    pub unused_svelte_events: bool,
486    /// Effect layers composed only into unused layers.
487    pub unused_effect_layers: bool,
488    /// Effect tagged errors that no code produces.
489    pub unused_tagged_errors: bool,
490    /// `catchTag` handlers for a tag that no code produces.
491    pub unproduced_catch_tags: bool,
492    /// Server actions never invoked.
493    pub unused_server_actions: bool,
494    /// `load` data keys never read by the consuming page.
495    pub unused_load_data_keys: bool,
496    /// Imports that do not resolve to a file or package.
497    pub unresolved_imports: bool,
498    /// Imported packages missing from the dependency manifest.
499    pub unlisted_deps: bool,
500    /// Binaries that no installed or listed package provides.
501    pub unlisted_binaries: bool,
502    /// The same symbol exported more than once.
503    pub duplicate_exports: bool,
504    /// One binding that one module exports under two or more names.
505    pub duplicate_export_aliases: bool,
506    /// Circular import chains.
507    pub circular_deps: bool,
508    /// Cycles formed through re-export chains.
509    pub re_export_cycles: bool,
510    /// Dependency cycles between workspace packages.
511    pub package_cycles: bool,
512    /// Imports that cross configured architecture boundaries.
513    pub boundary_violations: bool,
514    /// Violations of configured dependency policy rules.
515    pub policy_violations: bool,
516    /// Suppression comments that no longer match a finding.
517    pub stale_suppressions: bool,
518    /// Catalog entries never referenced by a workspace package.
519    pub unused_catalog_entries: bool,
520    /// Catalog groups that contain no entries.
521    pub empty_catalog_groups: bool,
522    /// `catalog:` references without a matching catalog entry.
523    pub unresolved_catalog_references: bool,
524    /// Dependency overrides that never affect a resolved package.
525    pub unused_dependency_overrides: bool,
526    /// Dependency overrides that cannot apply as written.
527    pub misconfigured_dependency_overrides: bool,
528}
529
530impl DeadCodeFilters {
531    /// Whether the report keeps dependency findings: no filter is active, or
532    /// `unused_deps` or `unlisted_deps` is one of the active filters. The CLI
533    /// applies the same rule to its `--unused-deps` and `--unlisted-deps`.
534    pub(crate) fn reports_dependency_findings(&self) -> bool {
535        !self.any_active() || self.unused_deps || self.unlisted_deps
536    }
537
538    fn any_active(&self) -> bool {
539        self.unused_files
540            || self.unused_exports
541            || self.unused_deps
542            || self.unused_types
543            || self.private_type_leaks
544            || self.deprecated_exports_in_use
545            || self.unused_enum_members
546            || self.unused_class_members
547            || self.unused_namespace_members
548            || self.unused_store_members
549            || self.unprovided_injects
550            || self.unrendered_components
551            || self.unused_component_props
552            || self.absent_component_props
553            || self.unused_component_emits
554            || self.unused_component_inputs
555            || self.unused_component_outputs
556            || self.unused_svelte_events
557            || self.unused_effect_layers
558            || self.unused_tagged_errors
559            || self.unproduced_catch_tags
560            || self.unused_server_actions
561            || self.unused_load_data_keys
562            || self.unresolved_imports
563            || self.unlisted_deps
564            || self.unlisted_binaries
565            || self.duplicate_exports
566            || self.duplicate_export_aliases
567            || self.circular_deps
568            || self.re_export_cycles
569            || self.package_cycles
570            || self.boundary_violations
571            || self.policy_violations
572            || self.stale_suppressions
573            || self.unused_catalog_entries
574            || self.empty_catalog_groups
575            || self.unresolved_catalog_references
576            || self.unused_dependency_overrides
577            || self.misconfigured_dependency_overrides
578    }
579
580    /// Enable the issue filter addressed by a shared registry selector.
581    ///
582    /// Returns `false` when the selector is not registered for dead-code
583    /// filtering. Callers that expose user input should surface their own
584    /// validation error with the accepted registry values.
585    pub fn enable_registry_selector(&mut self, selector: &str) -> bool {
586        let Some(flag) = fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS
587            .iter()
588            .find_map(|&(name, flag)| (name == selector).then_some(flag))
589        else {
590            return false;
591        };
592        self.enable_cli_filter_flag(flag);
593        true
594    }
595
596    /// The canonical CLI selector of each active filter.
597    pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
598        fallow_engine::requested_rule_off::explicit_filter_flags(|flag| {
599            let mut enabled = self.clone();
600            enabled.enable_cli_filter_flag(flag);
601            enabled == *self
602        })
603    }
604
605    fn enable_cli_filter_flag(&mut self, flag: &str) {
606        match flag {
607            "--unused-files" => self.unused_files = true,
608            "--unused-exports" => self.unused_exports = true,
609            "--unused-types" => self.unused_types = true,
610            "--private-type-leaks" => self.private_type_leaks = true,
611            "--deprecated-exports-in-use" => self.deprecated_exports_in_use = true,
612            "--unused-deps" => self.unused_deps = true,
613            "--unused-enum-members" => self.unused_enum_members = true,
614            "--unused-class-members" => self.unused_class_members = true,
615            "--unused-namespace-members" => self.unused_namespace_members = true,
616            "--unused-store-members" => self.unused_store_members = true,
617            "--unprovided-injects" => self.unprovided_injects = true,
618            "--unrendered-components" => self.unrendered_components = true,
619            "--unused-component-props" => self.unused_component_props = true,
620            "--absent-component-props" => self.absent_component_props = true,
621            "--unused-component-emits" => self.unused_component_emits = true,
622            "--unused-component-inputs" => self.unused_component_inputs = true,
623            "--unused-component-outputs" => self.unused_component_outputs = true,
624            "--unused-svelte-events" => self.unused_svelte_events = true,
625            "--unused-effect-layers" => self.unused_effect_layers = true,
626            "--unused-tagged-errors" => self.unused_tagged_errors = true,
627            "--unproduced-catch-tags" => self.unproduced_catch_tags = true,
628            "--unused-server-actions" => self.unused_server_actions = true,
629            "--unused-load-data-keys" => self.unused_load_data_keys = true,
630            "--unresolved-imports" => self.unresolved_imports = true,
631            "--unlisted-deps" => self.unlisted_deps = true,
632            "--unlisted-binaries" => self.unlisted_binaries = true,
633            "--duplicate-exports" => self.duplicate_exports = true,
634            "--duplicate-export-aliases" => self.duplicate_export_aliases = true,
635            "--circular-deps" => self.circular_deps = true,
636            "--re-export-cycles" => self.re_export_cycles = true,
637            "--package-cycles" => self.package_cycles = true,
638            "--boundary-violations" => self.boundary_violations = true,
639            "--policy-violations" => self.policy_violations = true,
640            "--stale-suppressions" => self.stale_suppressions = true,
641            "--unused-catalog-entries" => self.unused_catalog_entries = true,
642            "--empty-catalog-groups" => self.empty_catalog_groups = true,
643            "--unresolved-catalog-references" => self.unresolved_catalog_references = true,
644            "--unused-dependency-overrides" => self.unused_dependency_overrides = true,
645            "--misconfigured-dependency-overrides" => {
646                self.misconfigured_dependency_overrides = true;
647            }
648            _ => unreachable!("registry emitted unsupported dead-code filter flag: {flag}"),
649        }
650    }
651}
652
653/// Options for dead-code-oriented analyses.
654#[derive(Debug, Clone, Default)]
655pub struct DeadCodeOptions {
656    /// Shared analysis options.
657    pub analysis: AnalysisOptions,
658    /// Issue-type selection; everything is reported when no filter is set.
659    pub filters: DeadCodeFilters,
660    /// Restrict findings to these files when non-empty.
661    pub files: Vec<PathBuf>,
662    /// Also report unused exports declared in entry-point files.
663    pub include_entry_exports: bool,
664    /// Keep the export and member findings of unused files (`--show-cascade`).
665    pub show_cascade: bool,
666    /// Report only the findings with these `finding_id` values. The filter
667    /// runs last, after the baseline, and the output then carries
668    /// `finding_id_query`. Empty reports every finding. Only
669    /// [`run_dead_code`] and [`run_dead_code_with_baseline`] accept it.
670    pub finding_ids: Vec<String>,
671}
672
673/// Options for the analysis of `fallow architecture`: import cycles, boundary
674/// violations and rule-pack policy violations.
675///
676/// No selector reports every architecture issue type. Each selector keeps one
677/// kind, as `--cycles`, `--boundaries` and `--policy` do on the CLI.
678#[derive(Debug, Clone, Default)]
679pub struct ArchitectureOptions {
680    /// Shared analysis options.
681    pub analysis: AnalysisOptions,
682    /// Restrict findings to these files when non-empty.
683    pub files: Vec<PathBuf>,
684    /// Import cycles: circular dependencies, re-export cycles and workspace
685    /// package cycles.
686    pub cycles: bool,
687    /// Boundary violations, boundary coverage and forbidden calls.
688    pub boundaries: bool,
689    /// Rule-pack policy violations.
690    pub policy: bool,
691}
692
693impl ArchitectureOptions {
694    /// The dead-code issue-type filters that the selectors stand for.
695    #[must_use]
696    pub fn dead_code_filters(&self) -> DeadCodeFilters {
697        let all = !(self.cycles || self.boundaries || self.policy);
698        DeadCodeFilters {
699            circular_deps: self.cycles || all,
700            re_export_cycles: self.cycles || all,
701            package_cycles: self.cycles || all,
702            boundary_violations: self.boundaries || all,
703            policy_violations: self.policy || all,
704            ..DeadCodeFilters::default()
705        }
706    }
707
708    /// The canonical CLI selector of each selector that the caller set. No
709    /// selector asks for no specific check, so the list is empty.
710    pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
711        fallow_engine::requested_rule_off::architecture_requested_flags(
712            self.cycles,
713            self.boundaries,
714            self.policy,
715        )
716    }
717
718    /// The dead-code options that run this analysis.
719    #[must_use]
720    pub fn dead_code_options(&self) -> DeadCodeOptions {
721        DeadCodeOptions {
722            analysis: self.analysis.clone(),
723            filters: self.dead_code_filters(),
724            files: self.files.clone(),
725            include_entry_exports: false,
726            show_cascade: false,
727            finding_ids: Vec::new(),
728        }
729    }
730}
731
732/// Options for changed-code audit analysis.
733#[derive(Debug, Clone, Default)]
734pub struct AuditOptions {
735    /// Shared analysis options.
736    pub analysis: AnalysisOptions,
737    /// Git base reference for the changed-code comparison. `None` lets the
738    /// audit detect a base itself.
739    pub base: Option<String>,
740    /// Force production mode for every audit domain.
741    pub production: bool,
742    /// Production override for the dead-code domain; `None` defers to config.
743    pub production_dead_code: Option<bool>,
744    /// Production override for the health domain; `None` defers to config.
745    pub production_health: Option<bool>,
746    /// Production override for the duplication domain; `None` defers to
747    /// config.
748    pub production_dupes: Option<bool>,
749    /// Run the dead-code domain; `None` defers to `audit.deadCode` in config,
750    /// which defaults to on. When off, the verdict comes from the domains that
751    /// run.
752    pub dead_code: Option<bool>,
753    /// Run the health domain; `None` defers to `audit.health` in config,
754    /// which defaults to on.
755    pub health: Option<bool>,
756    /// Run the duplication domain; `None` defers to `audit.dupes` in config,
757    /// which defaults to on.
758    pub duplication: Option<bool>,
759    /// `Some(false)` skips CSS / styling analysis, as `--no-css` does. `None`
760    /// and `Some(true)` defer to `audit.css` in config, which defaults to on.
761    pub css: Option<bool>,
762    /// Enable deep cross-file CSS analysis; `None` defers to `audit.cssDeep`
763    /// in config, which defaults to on. It runs only when CSS analysis runs.
764    pub css_deep: Option<bool>,
765    /// Gate mode deciding which findings fail the audit; `None` defers to
766    /// `audit.gate` in config, which defaults to `new-only`.
767    pub gate: Option<fallow_config::AuditGate>,
768    /// How a worsened complexity finding affects the verdict; `None` defers
769    /// to `audit.worsened` in config, which defaults to `warn`.
770    pub worsened: Option<fallow_config::AuditWorsened>,
771    /// Fail the gate when a changed function exceeds this CRAP score.
772    pub max_crap: Option<f64>,
773    /// Test coverage report path for coverage-aware findings.
774    pub coverage: Option<PathBuf>,
775    /// Absolute path prefix the coverage report recorded its files under.
776    pub coverage_root: Option<PathBuf>,
777    /// Also report unused exports declared in entry-point files.
778    pub include_entry_exports: bool,
779    /// Keep the export and member findings of unused files (`--show-cascade`).
780    pub show_cascade: bool,
781    /// Runtime coverage capture merged into the audit.
782    pub runtime_coverage: Option<PathBuf>,
783    /// Minimum recorded invocations for a code path to count as hot.
784    pub min_invocations_hot: u64,
785}
786
787/// Options for bare combined analysis through the programmatic API.
788#[derive(Debug, Clone)]
789pub struct CombinedOptions {
790    /// Shared analysis options.
791    pub analysis: AnalysisOptions,
792    /// Run the dead-code domain.
793    pub dead_code: bool,
794    /// Run the duplication domain.
795    pub duplication: bool,
796    /// Run the health domain.
797    pub health: bool,
798    /// Also report unused exports declared in entry-point files.
799    pub include_entry_exports: bool,
800    /// Keep the export and member findings of unused files (`--show-cascade`).
801    pub show_cascade: bool,
802    /// Options for the duplication domain.
803    pub duplication_options: DuplicationOptions,
804    /// Options for the health domain.
805    pub health_options: ComplexityOptions,
806}
807
808impl Default for CombinedOptions {
809    fn default() -> Self {
810        Self {
811            analysis: AnalysisOptions::default(),
812            dead_code: true,
813            duplication: true,
814            health: true,
815            include_entry_exports: false,
816            show_cascade: false,
817            duplication_options: DuplicationOptions::default(),
818            health_options: ComplexityOptions::default(),
819        }
820    }
821}
822
823/// Options for changed-code decision-surface analysis.
824#[derive(Debug, Clone, Default)]
825pub struct DecisionSurfaceOptions {
826    /// Shared analysis options.
827    pub analysis: AnalysisOptions,
828    /// Git base reference for the changed-code comparison. `None` lets the
829    /// analysis detect a base itself.
830    pub base: Option<String>,
831    /// Cap on the number of decisions surfaced.
832    pub max_decisions: Option<usize>,
833}
834
835/// Options for feature-flag analysis.
836#[derive(Debug, Clone, Default)]
837pub struct FeatureFlagsOptions {
838    /// Shared analysis options.
839    pub analysis: AnalysisOptions,
840    /// Cap on the number of reported flags. With `retirement`, it also caps
841    /// the retirement rows.
842    pub top: Option<usize>,
843    /// Retirement report options. `None` leaves the `retirement` block out.
844    pub retirement: Option<FeatureFlagsRetirementOptions>,
845}
846
847/// Options of the flag retirement report, the `--retirement` mode of
848/// `fallow flags`.
849#[derive(Debug, Clone, Default)]
850pub struct FeatureFlagsRetirementOptions {
851    /// How to measure flag age.
852    pub flag_age: fallow_types::flag_retirement::FlagAgeMode,
853    /// Vendor flag export to read, like `--flag-state`.
854    pub flag_state: Option<std::path::PathBuf>,
855    /// Keep only rows with one of these reasons. Empty keeps all rows.
856    pub reasons: Vec<fallow_types::flag_retirement::RetirementReason>,
857    /// Row order.
858    pub sort: fallow_engine::flag_retirement::RetirementSort,
859    /// Keep only rows at least this many days old.
860    pub min_age_days: Option<u64>,
861    /// Report the flags older than this many days in `max_flag_age`.
862    pub max_flag_age: Option<u64>,
863}
864
865/// Programmatic duplication mode selection.
866#[derive(Debug, Clone, Copy, Default)]
867pub enum DuplicationMode {
868    /// Preserve all tokens, including identifier names and literal values
869    /// (Type-1 clones only).
870    Strict,
871    /// Default mode, equivalent to strict for AST-based tokenization.
872    #[default]
873    Mild,
874    /// Blind string literal values while preserving structure.
875    Weak,
876    /// Blind all identifiers and literal values for structural (Type-2)
877    /// detection.
878    Semantic,
879}
880
881/// Options for duplication analysis.
882#[derive(Debug, Clone, Default)]
883pub struct DuplicationOptions {
884    /// Shared analysis options.
885    pub analysis: AnalysisOptions,
886    /// Detection mode; `None` defers to the project config.
887    pub mode: Option<DuplicationMode>,
888    /// Detect function-scoped near-miss clones in addition to exact clones.
889    /// `None` defers to the project config.
890    pub near: Option<bool>,
891    /// Minimum number of tokens for a clone.
892    pub min_tokens: Option<usize>,
893    /// Minimum number of lines for a clone.
894    pub min_lines: Option<usize>,
895    /// Minimum number of occurrences before a clone group is reported.
896    /// Values below 2 are silently treated as 2 by the engine-facing adapter.
897    pub min_occurrences: Option<usize>,
898    /// Maximum allowed duplication percentage before the gate fails; 0 means
899    /// no limit. `None` defers to the project config.
900    pub threshold: Option<f64>,
901    /// Only report cross-directory duplicates. `None` defers to the project
902    /// config.
903    pub skip_local: Option<bool>,
904    /// Omit clone instances whose path is a symlink or lies under a symlinked
905    /// directory. `None` defers to the project config.
906    pub ignore_symlinks: Option<bool>,
907    /// Match clones across languages. `None` defers to the project config.
908    pub cross_language: Option<bool>,
909    /// Exclude module wiring from clone detection. `None` defers to the project
910    /// config.
911    pub ignore_imports: Option<bool>,
912    /// Cap on the number of reported clone groups.
913    pub top: Option<usize>,
914    /// Emit the verbatim source text on each clone instance. `None` keeps the
915    /// text, matching `fallow dupes` without `--no-fragments`; `Some(false)`
916    /// yields a location-only payload.
917    pub include_fragments: Option<bool>,
918}
919
920/// Options for local advisory similar-code discovery.
921#[derive(Debug, Clone, Default)]
922pub struct SimilarCodeOptions {
923    /// Shared project, config, cache, diff, and workspace options.
924    pub analysis: AnalysisOptions,
925    /// Model-specific cosine floor. `None` uses `similarCode.threshold`.
926    pub threshold: Option<f64>,
927    /// Minimum source lines per function. `None` uses
928    /// `similarCode.minLines`.
929    pub min_lines: Option<usize>,
930    /// Cap on displayed candidates after the full bounded comparison.
931    pub top: Option<usize>,
932    /// Restrict work and reported pairs to those where at least one side matches
933    /// one of these project-relative files. Deterministic background context is
934    /// retained only within the bounded scoped comparison budget.
935    pub files: Vec<PathBuf>,
936    /// Exact companion binary resolved and signature-verified by an official
937    /// distribution adapter such as the Node loader. `None` uses trusted
938    /// sibling discovery. Project config, PATH commands, and remote providers
939    /// must never populate this field.
940    #[doc(hidden)]
941    pub adapter_provider_path: Option<PathBuf>,
942}
943
944/// Options for one similar-code candidate inspection packet.
945#[derive(Debug, Clone)]
946pub struct SimilarCodeInspectOptions {
947    /// Shared project and configuration options used only for source validation
948    /// and deterministic enrichment. Inspect never reruns provider retrieval.
949    pub analysis: AnalysisOptions,
950    /// Bounded candidate handoff selected from the original discovery output.
951    pub snapshot: fallow_output::SimilarCodeCandidateSnapshot,
952}
953
954/// Options for export trace analysis.
955#[derive(Debug, Clone, Default)]
956pub struct TraceExportOptions {
957    /// Shared analysis options.
958    pub analysis: AnalysisOptions,
959    /// Path of the module that declares the export.
960    pub file: String,
961    /// Name of the export to trace.
962    pub export_name: String,
963}
964
965/// Options for file trace analysis.
966#[derive(Debug, Clone, Default)]
967pub struct TraceFileOptions {
968    /// Shared analysis options.
969    pub analysis: AnalysisOptions,
970    /// Path of the file to trace.
971    pub file: String,
972}
973
974/// Options for shortest-import-path trace analysis.
975#[derive(Debug, Clone, Default)]
976pub struct TraceImportPathOptions {
977    /// Shared analysis options.
978    pub analysis: AnalysisOptions,
979    /// Path of the module the walk starts from.
980    pub from: String,
981    /// Path of the module the walk is looking for.
982    pub to: String,
983    /// Follow only static imports that carry a runtime value, so the route
984    /// explains why `to` loads before `from` runs.
985    pub eager_only: bool,
986}
987
988/// Options for stack-trace frame resolution.
989#[derive(Debug, Clone, Default)]
990pub struct TraceErrorOptions {
991    /// Shared analysis options.
992    pub analysis: AnalysisOptions,
993    /// The runtime stack trace, verbatim.
994    pub trace: String,
995    /// Where the trace came from, reported back as the payload's `source`.
996    pub source: String,
997}
998
999/// Options for dependency trace analysis.
1000#[derive(Debug, Clone, Default)]
1001pub struct TraceDependencyOptions {
1002    /// Shared analysis options.
1003    pub analysis: AnalysisOptions,
1004    /// Package whose importers are traced.
1005    pub package_name: String,
1006    /// The per-specifier usage to report. `None` keeps the output equal to
1007    /// `fallow dead-code --trace-dependency`, with no `usage` object.
1008    pub usage: Option<DependencyUsageQuery>,
1009}
1010
1011/// Duplicate-code trace target.
1012#[derive(Debug, Clone, PartialEq, Eq)]
1013pub enum TraceCloneTarget {
1014    /// Select the clone group covering this file and line.
1015    Location {
1016        /// Path of the file containing the clone instance.
1017        file: String,
1018        /// One-based line inside the clone instance.
1019        line: usize,
1020    },
1021    /// Select the clone group by its fingerprint.
1022    Fingerprint(String),
1023}
1024
1025/// Options for duplicate-code trace analysis.
1026#[derive(Debug, Clone)]
1027pub struct TraceCloneOptions {
1028    /// Duplication options controlling detection before the trace.
1029    pub duplication: DuplicationOptions,
1030    /// Clone group to trace.
1031    pub target: TraceCloneTarget,
1032}
1033
1034/// Sort criteria for complexity findings.
1035#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1036pub enum ComplexitySort {
1037    /// Sort by cyclomatic complexity (default).
1038    #[default]
1039    Cyclomatic,
1040    /// Sort by cognitive complexity.
1041    Cognitive,
1042    /// Sort by function length in lines.
1043    Lines,
1044    /// Sort by finding severity.
1045    Severity,
1046}
1047
1048/// Privacy mode for ownership-aware hotspot output.
1049#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1050pub enum OwnershipEmailMode {
1051    /// Show the raw email address as it appears in git history.
1052    Raw,
1053    /// Show only the local part before the `@` (default).
1054    #[default]
1055    Handle,
1056    /// Show a stable non-cryptographic pseudonym derived from the raw email.
1057    Anonymized,
1058    /// Legacy spelling retained for embedders that already pass `hash`.
1059    Hash,
1060}
1061
1062/// Effort filter for refactoring targets.
1063#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1064pub enum TargetEffort {
1065    /// Low estimated refactoring effort.
1066    Low,
1067    /// Medium estimated refactoring effort.
1068    Medium,
1069    /// High estimated refactoring effort.
1070    High,
1071}
1072
1073/// Options for complexity / health analysis.
1074#[derive(Debug, Clone, Default)]
1075pub struct ComplexityOptions {
1076    /// Shared analysis options.
1077    pub analysis: AnalysisOptions,
1078    /// Override for the cyclomatic complexity threshold.
1079    pub max_cyclomatic: Option<u16>,
1080    /// Override for the cognitive complexity threshold.
1081    pub max_cognitive: Option<u16>,
1082    /// Override for the CRAP score threshold.
1083    pub max_crap: Option<f64>,
1084    /// Override for the file-length threshold in physical lines. `0` turns
1085    /// the check off.
1086    pub max_file_lines: Option<u32>,
1087    /// Cap on the number of reported findings.
1088    pub top: Option<usize>,
1089    /// Sort order for complexity findings.
1090    pub sort: ComplexitySort,
1091    /// Include the per-metric complexity breakdown with each finding.
1092    pub complexity_breakdown: bool,
1093    /// Request the complexity findings section.
1094    pub complexity: bool,
1095    /// Request the per-file score section.
1096    pub file_scores: bool,
1097    /// Request the coverage-gap section.
1098    pub coverage_gaps: bool,
1099    /// Request the churn hotspot section.
1100    pub hotspots: bool,
1101    /// Include ownership data with hotspots; implies the hotspot section.
1102    pub ownership: bool,
1103    /// Email privacy mode for ownership output; implies ownership when set.
1104    pub ownership_emails: Option<OwnershipEmailMode>,
1105    /// Request the refactoring targets section.
1106    pub targets: bool,
1107    /// Include CSS / styling health.
1108    pub css: bool,
1109    /// Enable deep cross-file CSS analysis.
1110    pub css_deep: bool,
1111    /// Filter refactoring targets by estimated effort; implies the targets
1112    /// section when set.
1113    pub effort: Option<TargetEffort>,
1114    /// Request the overall health score.
1115    pub score: bool,
1116    /// Git time window (for example `30d`) for churn-based sections.
1117    pub since: Option<String>,
1118    /// Minimum commit count for a file to count as a hotspot.
1119    pub min_commits: Option<u32>,
1120    /// Test coverage report path for coverage-aware sections.
1121    pub coverage: Option<PathBuf>,
1122    /// Absolute path prefix the coverage report recorded its files under.
1123    pub coverage_root: Option<PathBuf>,
1124    /// The coverage map was recorded against a different checkout of this
1125    /// project, so function line numbers may have drifted arbitrarily.
1126    /// Set internally by the audit base-worktree pass; leave `false` for
1127    /// same-checkout coverage.
1128    pub coverage_relocated: bool,
1129}
1130
1131/// Health threshold overrides accepted by the programmatic API.
1132#[derive(Debug, Clone, Copy, Default, PartialEq)]
1133pub struct ComplexityThresholdOverrides {
1134    /// Override for the cyclomatic complexity threshold.
1135    pub max_cyclomatic: Option<u16>,
1136    /// Override for the cognitive complexity threshold.
1137    pub max_cognitive: Option<u16>,
1138    /// Override for the CRAP score threshold.
1139    pub max_crap: Option<f64>,
1140    /// Override for the file-length threshold in physical lines.
1141    pub max_file_lines: Option<u32>,
1142}
1143
1144/// Coverage inputs accepted by the programmatic API.
1145#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1146pub struct ComplexityCoverageInputs<'a> {
1147    /// Test coverage report path.
1148    pub coverage: Option<&'a Path>,
1149    /// Absolute path prefix the coverage report recorded its files under.
1150    pub coverage_root: Option<&'a Path>,
1151    /// The coverage map was recorded against a different checkout of this
1152    /// project; tolerate arbitrary line drift for unambiguous name matches.
1153    pub coverage_relocated: bool,
1154}
1155
1156/// Input for deriving effective health sections from API-owned flags.
1157#[derive(Debug, Clone)]
1158pub struct HealthSectionOptions {
1159    /// Requested output format; `Badge` implies the score section.
1160    pub output: fallow_types::output_format::OutputFormat,
1161    /// The complexity findings section was requested.
1162    pub complexity: bool,
1163    /// The per-file score section was requested.
1164    pub file_scores: bool,
1165    /// The coverage-gap section was requested.
1166    pub coverage_gaps: bool,
1167    /// The churn hotspot section was requested.
1168    pub hotspots: bool,
1169    /// The refactoring targets section was requested.
1170    pub targets: bool,
1171    /// CSS / styling health was requested.
1172    pub css: bool,
1173    /// The overall health score was requested.
1174    pub score: bool,
1175    /// A score gate is active; implies the score section.
1176    pub score_gate: bool,
1177    /// A snapshot write was requested; forces full hidden inputs.
1178    pub snapshot_requested: bool,
1179    /// Trend output was requested; implies score and hotspot inputs.
1180    pub trend: bool,
1181}
1182
1183/// Derived section selection for health runs.
1184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1185pub struct DerivedHealthSections {
1186    /// At least one section was explicitly requested.
1187    pub any_section: bool,
1188    /// Emit the complexity findings section.
1189    pub complexity: bool,
1190    /// Compute the per-file score section.
1191    pub file_scores: bool,
1192    /// Emit the coverage-gap section.
1193    pub coverage_gaps: bool,
1194    /// Compute the churn hotspot section.
1195    pub hotspots: bool,
1196    /// Emit the refactoring targets section.
1197    pub targets: bool,
1198    /// Include CSS / styling health.
1199    pub css: bool,
1200    /// Compute the overall health score.
1201    pub score: bool,
1202    /// Compute full inputs even for sections that are not emitted.
1203    pub force_full: bool,
1204    /// Only the score should be printed.
1205    pub score_only_output: bool,
1206}
1207
1208/// Input for deriving effective programmatic complexity sections.
1209#[derive(Debug, Clone)]
1210pub struct ComplexitySectionOptions {
1211    /// The complexity findings section was requested.
1212    pub complexity: bool,
1213    /// The per-file score section was requested.
1214    pub file_scores: bool,
1215    /// The coverage-gap section was requested.
1216    pub coverage_gaps: bool,
1217    /// The churn hotspot section was requested.
1218    pub hotspots: bool,
1219    /// Ownership data was requested; implies the hotspot section.
1220    pub ownership: bool,
1221    /// The refactoring targets section was requested.
1222    pub targets: bool,
1223    /// CSS / styling health was requested.
1224    pub css: bool,
1225    /// The overall health score was requested.
1226    pub score: bool,
1227}
1228
1229/// Derived section selection for programmatic health / complexity runs.
1230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1231pub struct DerivedComplexityOptions {
1232    /// At least one section was explicitly requested.
1233    pub any_section: bool,
1234    /// Emit the complexity findings section.
1235    pub complexity: bool,
1236    /// Compute the per-file score section.
1237    pub file_scores: bool,
1238    /// Emit the coverage-gap section.
1239    pub coverage_gaps: bool,
1240    /// Compute the churn hotspot section.
1241    pub hotspots: bool,
1242    /// Include ownership data with hotspots.
1243    pub ownership: bool,
1244    /// Emit the refactoring targets section.
1245    pub targets: bool,
1246    /// Compute full inputs even for sections that are not emitted.
1247    pub force_full: bool,
1248    /// Only the score should be printed.
1249    pub score_only_output: bool,
1250    /// Compute the overall health score.
1251    pub score: bool,
1252}
1253
1254/// Normalized programmatic complexity / health inputs owned by `fallow-api`.
1255#[derive(Debug, Clone, PartialEq)]
1256pub struct ComplexityRunOptions<'a> {
1257    /// Complexity threshold overrides.
1258    pub thresholds: ComplexityThresholdOverrides,
1259    /// Cap on the number of reported findings.
1260    pub top: Option<usize>,
1261    /// Sort order for complexity findings.
1262    pub sort: ComplexitySort,
1263    /// Include the per-metric complexity breakdown with each finding.
1264    pub complexity_breakdown: bool,
1265    /// Derived effective section selection.
1266    pub sections: DerivedComplexityOptions,
1267    /// Email privacy mode for ownership output.
1268    pub ownership_emails: Option<OwnershipEmailMode>,
1269    /// Filter refactoring targets by estimated effort.
1270    pub effort: Option<TargetEffort>,
1271    /// Include CSS / styling health.
1272    pub css: bool,
1273    /// Enable deep cross-file CSS analysis.
1274    pub css_deep: bool,
1275    /// Git time window (for example `30d`) for churn-based sections.
1276    pub since: Option<&'a str>,
1277    /// Minimum commit count for a file to count as a hotspot.
1278    pub min_commits: Option<u32>,
1279    /// Test coverage inputs.
1280    pub coverage_inputs: ComplexityCoverageInputs<'a>,
1281}
1282
1283/// Build the process-global Rayon pool with the [`WORKER_STACK_SIZE`] stack
1284/// and `threads` workers. Zero threads selects the Rayon default count, which
1285/// honors `RAYON_NUM_THREADS`.
1286///
1287/// A process that runs analysis outside
1288/// [`ProgrammaticAnalysisContext::install`] calls this once at startup, before
1289/// any parallel work. Returns `false` when the global pool already exists or
1290/// when a worker thread cannot start. Rayon then keeps its default pool.
1291pub fn configure_global_analysis_pool(threads: usize) -> bool {
1292    fallow_engine::thread_pool::worker_pool_builder(threads)
1293        .build_global()
1294        .is_ok()
1295}
1296
1297/// Derive effective health section flags for API consumers.
1298#[must_use]
1299pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
1300    let score = options.score
1301        || options.score_gate
1302        || options.trend
1303        || matches!(
1304            options.output,
1305            fallow_types::output_format::OutputFormat::Badge
1306        );
1307    let any_section = options.complexity
1308        || options.file_scores
1309        || options.coverage_gaps
1310        || options.hotspots
1311        || options.targets
1312        || score;
1313    let effective_score = if any_section { score } else { true } || options.snapshot_requested;
1314    let force_full = options.snapshot_requested || effective_score;
1315
1316    DerivedHealthSections {
1317        any_section,
1318        complexity: if any_section {
1319            options.complexity
1320        } else {
1321            true
1322        },
1323        file_scores: if any_section {
1324            options.file_scores
1325        } else {
1326            true
1327        } || force_full,
1328        coverage_gaps: if any_section {
1329            options.coverage_gaps
1330        } else {
1331            false
1332        },
1333        hotspots: if any_section { options.hotspots } else { true }
1334            || options.snapshot_requested
1335            || options.trend,
1336        targets: if any_section { options.targets } else { true },
1337        css: options.css,
1338        score: effective_score,
1339        force_full,
1340        score_only_output: is_health_score_only_output(options, score),
1341    }
1342}
1343
1344/// Derive effective programmatic health / complexity section flags.
1345#[must_use]
1346pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
1347    let requested_hotspots = options.hotspots || options.ownership;
1348    let sections = derive_health_sections(&HealthSectionOptions {
1349        output: fallow_types::output_format::OutputFormat::Human,
1350        complexity: options.complexity,
1351        file_scores: options.file_scores,
1352        coverage_gaps: options.coverage_gaps,
1353        hotspots: requested_hotspots,
1354        targets: options.targets,
1355        css: options.css,
1356        score: options.score,
1357        score_gate: false,
1358        snapshot_requested: false,
1359        trend: false,
1360    });
1361
1362    DerivedComplexityOptions {
1363        any_section: sections.any_section,
1364        complexity: sections.complexity,
1365        file_scores: sections.file_scores,
1366        coverage_gaps: sections.coverage_gaps,
1367        hotspots: sections.hotspots,
1368        ownership: options.ownership && sections.hotspots,
1369        targets: sections.targets,
1370        force_full: sections.force_full,
1371        score_only_output: sections.score_only_output,
1372        score: sections.score,
1373    }
1374}
1375
1376/// Derive effective programmatic health / complexity section flags.
1377#[must_use]
1378pub fn derive_complexity_options(options: &ComplexityOptions) -> DerivedComplexityOptions {
1379    derive_complexity_sections(&complexity_section_options(options))
1380}
1381
1382/// Normalize public API complexity options into engine-owned run contracts.
1383#[must_use]
1384pub fn derive_complexity_run_options(options: &ComplexityOptions) -> ComplexityRunOptions<'_> {
1385    ComplexityRunOptions {
1386        thresholds: ComplexityThresholdOverrides {
1387            max_cyclomatic: options.max_cyclomatic,
1388            max_cognitive: options.max_cognitive,
1389            max_crap: options.max_crap,
1390            max_file_lines: options.max_file_lines,
1391        },
1392        top: options.top,
1393        sort: options.sort,
1394        complexity_breakdown: options.complexity_breakdown,
1395        sections: derive_complexity_options(options),
1396        ownership_emails: options.ownership_emails,
1397        effort: options.effort,
1398        css: options.css,
1399        css_deep: options.css_deep,
1400        since: options.since.as_deref(),
1401        min_commits: options.min_commits,
1402        coverage_inputs: ComplexityCoverageInputs {
1403            coverage: options.coverage.as_deref(),
1404            coverage_root: options.coverage_root.as_deref(),
1405            coverage_relocated: options.coverage_relocated,
1406        },
1407    }
1408}
1409
1410/// Validate programmatic complexity / health inputs before invoking a concrete
1411/// runner.
1412///
1413/// These option contracts belong to the API boundary because NAPI and future
1414/// Rust embedders construct the same [`ComplexityOptions`] type.
1415///
1416/// A relative coverage path resolves against `analysis.root` (the cwd when
1417/// unset), exactly as the engine resolves it at read time, so a
1418/// project-relative `health.coverage` validates against the project and not
1419/// against the embedder's working directory.
1420///
1421/// The options carry no record of which layer supplied `coverage`, so the
1422/// path error's `context` is always `health.coverage`, whichever of the tool
1423/// parameter, `FALLOW_COVERAGE`, or the config field won
1424/// ([`crate::coverage::resolve_coverage_inputs`] resolves that order). The
1425/// sibling root error names its layer because
1426/// [`crate::coverage::CoverageInputError`] carries it.
1427///
1428/// # Errors
1429///
1430/// Returns a structured programmatic error when a coverage path does not exist
1431/// or when `coverage_root` is not an absolute prefix from the coverage data.
1432pub fn validate_complexity_options(options: &ComplexityOptions) -> Result<(), ProgrammaticError> {
1433    if let Some(path) = &options.coverage {
1434        let resolved = fallow_engine::health::scoring::resolve_relative_to_root(
1435            path,
1436            options.analysis.root.as_deref(),
1437        );
1438        if !resolved.exists() {
1439            return Err(ProgrammaticError::new(
1440                format!("coverage path does not exist: {}", resolved.display()),
1441                2,
1442            )
1443            .with_code("FALLOW_INVALID_COVERAGE_PATH")
1444            .with_context("health.coverage"));
1445        }
1446    }
1447    if let Err(message) =
1448        fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
1449    {
1450        return Err(ProgrammaticError::new(message, 2)
1451            .with_code("FALLOW_INVALID_COVERAGE_ROOT")
1452            .with_context("health.coverage_root"));
1453    }
1454
1455    Ok(())
1456}
1457
1458fn complexity_section_options(options: &ComplexityOptions) -> ComplexitySectionOptions {
1459    let ownership = options.ownership || options.ownership_emails.is_some();
1460    let requested_targets = options.targets || options.effort.is_some();
1461    ComplexitySectionOptions {
1462        complexity: options.complexity,
1463        file_scores: options.file_scores,
1464        coverage_gaps: options.coverage_gaps,
1465        hotspots: options.hotspots,
1466        ownership,
1467        targets: requested_targets,
1468        css: options.css,
1469        score: options.score,
1470    }
1471}
1472
1473fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
1474    score
1475        && !options.complexity
1476        && !options.file_scores
1477        && !options.coverage_gaps
1478        && !options.hotspots
1479        && !options.targets
1480        && !options.trend
1481}
1482
1483const fn thresholds_to_engine(
1484    thresholds: ComplexityThresholdOverrides,
1485) -> fallow_engine::health::HealthThresholdOverrides {
1486    fallow_engine::health::HealthThresholdOverrides {
1487        max_cyclomatic: thresholds.max_cyclomatic,
1488        max_cognitive: thresholds.max_cognitive,
1489        max_crap: thresholds.max_crap,
1490        max_file_lines: thresholds.max_file_lines,
1491    }
1492}
1493
1494const fn complexity_sort_to_engine(sort: ComplexitySort) -> fallow_engine::health::HealthSort {
1495    match sort {
1496        ComplexitySort::Severity => fallow_engine::health::HealthSort::Severity,
1497        ComplexitySort::Cyclomatic => fallow_engine::health::HealthSort::Cyclomatic,
1498        ComplexitySort::Cognitive => fallow_engine::health::HealthSort::Cognitive,
1499        ComplexitySort::Lines => fallow_engine::health::HealthSort::Lines,
1500    }
1501}
1502
1503const fn coverage_inputs_to_engine(
1504    coverage_inputs: ComplexityCoverageInputs<'_>,
1505) -> fallow_engine::health::HealthCoverageInputs<'_> {
1506    fallow_engine::health::HealthCoverageInputs {
1507        coverage: coverage_inputs.coverage,
1508        coverage_root: coverage_inputs.coverage_root,
1509        coverage_relocated: coverage_inputs.coverage_relocated,
1510    }
1511}
1512
1513const fn ownership_email_mode_to_config(mode: OwnershipEmailMode) -> EmailMode {
1514    match mode {
1515        OwnershipEmailMode::Raw => EmailMode::Raw,
1516        OwnershipEmailMode::Handle => EmailMode::Handle,
1517        OwnershipEmailMode::Anonymized => EmailMode::Anonymized,
1518        OwnershipEmailMode::Hash => EmailMode::Hash,
1519    }
1520}
1521
1522const fn target_effort_to_output(effort: TargetEffort) -> EffortEstimate {
1523    match effort {
1524        TargetEffort::Low => EffortEstimate::Low,
1525        TargetEffort::Medium => EffortEstimate::Medium,
1526        TargetEffort::High => EffortEstimate::High,
1527    }
1528}
1529
1530#[cfg(test)]
1531mod tests {
1532    use super::*;
1533
1534    #[test]
1535    fn duplication_defaults_match_cli_contract() {
1536        let options = DuplicationOptions::default();
1537        assert!(options.mode.is_none());
1538        assert!(options.min_tokens.is_none());
1539        assert!(options.min_lines.is_none());
1540        assert!(options.min_occurrences.is_none());
1541    }
1542
1543    #[test]
1544    fn programmatic_error_builder_keeps_optional_fields() {
1545        let error = ProgrammaticError::new("boom", 2)
1546            .with_code("FALLOW_TEST")
1547            .with_help("Try again")
1548            .with_context("analysis.root");
1549
1550        assert_eq!(error.message, "boom");
1551        assert_eq!(error.exit_code, 2);
1552        assert_eq!(error.code.as_deref(), Some("FALLOW_TEST"));
1553        assert_eq!(error.help.as_deref(), Some("Try again"));
1554        assert_eq!(error.context.as_deref(), Some("analysis.root"));
1555    }
1556
1557    #[test]
1558    fn dead_code_filters_accept_shared_registry_selectors() {
1559        for (selector, _) in fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS.iter() {
1560            let mut filters = DeadCodeFilters::default();
1561            assert!(
1562                filters.enable_registry_selector(selector),
1563                "{selector} should be accepted"
1564            );
1565        }
1566
1567        let mut filters = DeadCodeFilters::default();
1568        assert!(filters.enable_registry_selector("unused-files"));
1569        assert!(filters.unused_files);
1570        assert!(filters.enable_registry_selector("boundary-violations"));
1571        assert!(filters.boundary_violations);
1572        assert!(!filters.enable_registry_selector("not-a-real-selector"));
1573    }
1574
1575    #[test]
1576    fn default_complexity_options_match_programmatic_health_defaults() {
1577        let derived = derive_complexity_options(&ComplexityOptions::default());
1578
1579        assert!(!derived.any_section);
1580        assert!(derived.complexity);
1581        assert!(derived.file_scores);
1582        assert!(!derived.coverage_gaps);
1583        assert!(derived.hotspots);
1584        assert!(!derived.ownership);
1585        assert!(derived.targets);
1586        assert!(derived.force_full);
1587        assert!(!derived.score_only_output);
1588        assert!(derived.score);
1589    }
1590
1591    #[test]
1592    fn score_only_complexity_options_request_score_only_output() {
1593        let derived = derive_complexity_options(&ComplexityOptions {
1594            score: true,
1595            ..ComplexityOptions::default()
1596        });
1597
1598        assert!(derived.any_section);
1599        assert!(!derived.complexity);
1600        assert!(derived.file_scores);
1601        assert!(!derived.hotspots);
1602        assert!(!derived.targets);
1603        assert!(derived.force_full);
1604        assert!(derived.score_only_output);
1605        assert!(derived.score);
1606    }
1607
1608    #[test]
1609    fn ownership_implies_hotspots_when_requested() {
1610        let derived = derive_complexity_options(&ComplexityOptions {
1611            ownership: true,
1612            ..ComplexityOptions::default()
1613        });
1614
1615        assert!(derived.any_section);
1616        assert!(derived.hotspots);
1617        assert!(derived.ownership);
1618        assert!(!derived.targets);
1619    }
1620
1621    #[test]
1622    fn complexity_run_options_normalize_public_api_options() {
1623        let options = ComplexityOptions {
1624            max_cyclomatic: Some(42),
1625            max_cognitive: Some(21),
1626            max_crap: Some(18.5),
1627            top: Some(7),
1628            sort: ComplexitySort::Severity,
1629            complexity_breakdown: true,
1630            ownership_emails: Some(OwnershipEmailMode::Hash),
1631            effort: Some(TargetEffort::High),
1632            coverage: Some(PathBuf::from("coverage/coverage-final.json")),
1633            coverage_root: Some(PathBuf::from("/ci/workspace")),
1634            since: Some("30d".to_string()),
1635            min_commits: Some(4),
1636            ..ComplexityOptions::default()
1637        };
1638
1639        let run = derive_complexity_run_options(&options);
1640
1641        assert_eq!(run.thresholds.max_cyclomatic, Some(42));
1642        assert_eq!(run.thresholds.max_cognitive, Some(21));
1643        assert_eq!(run.thresholds.max_crap, Some(18.5));
1644        assert_eq!(run.top, Some(7));
1645        assert!(matches!(run.sort, ComplexitySort::Severity));
1646        assert!(run.complexity_breakdown);
1647        assert!(run.sections.hotspots);
1648        assert!(run.sections.ownership);
1649        assert!(run.sections.targets);
1650        assert!(matches!(
1651            run.ownership_emails,
1652            Some(OwnershipEmailMode::Hash)
1653        ));
1654        assert!(matches!(run.effort, Some(TargetEffort::High)));
1655        assert_eq!(run.since, Some("30d"));
1656        assert_eq!(run.min_commits, Some(4));
1657        assert_eq!(run.coverage_inputs.coverage, options.coverage.as_deref());
1658        assert_eq!(
1659            run.coverage_inputs.coverage_root,
1660            options.coverage_root.as_deref()
1661        );
1662    }
1663
1664    #[test]
1665    fn complexity_options_validation_accepts_existing_coverage_path_and_absolute_root() {
1666        let dir = tempfile::tempdir().expect("tempdir");
1667        let coverage = dir.path().join("coverage-final.json");
1668        std::fs::write(&coverage, "{}").expect("coverage fixture");
1669
1670        let result = validate_complexity_options(&ComplexityOptions {
1671            coverage: Some(coverage),
1672            coverage_root: Some(PathBuf::from("/ci/workspace")),
1673            ..ComplexityOptions::default()
1674        });
1675
1676        assert!(result.is_ok());
1677    }
1678
1679    #[test]
1680    fn complexity_options_validation_keeps_missing_coverage_error_contract() {
1681        let err = validate_complexity_options(&ComplexityOptions {
1682            coverage: Some(PathBuf::from("/missing/coverage-final.json")),
1683            ..ComplexityOptions::default()
1684        })
1685        .expect_err("missing coverage path should fail");
1686
1687        assert_eq!(err.exit_code, 2);
1688        assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1689        assert_eq!(err.context.as_deref(), Some("health.coverage"));
1690    }
1691
1692    #[test]
1693    fn complexity_options_validation_keeps_relative_coverage_root_error_contract() {
1694        let err = validate_complexity_options(&ComplexityOptions {
1695            coverage_root: Some(PathBuf::from("coverage")),
1696            ..ComplexityOptions::default()
1697        })
1698        .expect_err("relative coverage root should fail");
1699
1700        assert_eq!(err.exit_code, 2);
1701        assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_ROOT"));
1702        assert_eq!(err.context.as_deref(), Some("health.coverage_root"));
1703    }
1704
1705    /// #2368: a project-relative coverage path (the documented form of
1706    /// `health.coverage`) must be checked under the analysis root, not under
1707    /// the embedder's working directory.
1708    #[test]
1709    fn complexity_options_validation_resolves_relative_coverage_against_root() {
1710        let dir = tempfile::tempdir().expect("tempdir");
1711        std::fs::create_dir_all(dir.path().join("artifacts")).expect("artifacts dir");
1712        std::fs::write(dir.path().join("artifacts/coverage-final.json"), "{}")
1713            .expect("coverage fixture");
1714        let relative = PathBuf::from("artifacts/coverage-final.json");
1715        assert!(
1716            !relative.exists(),
1717            "the fixture must not also exist under the test cwd"
1718        );
1719
1720        let result = validate_complexity_options(&ComplexityOptions {
1721            analysis: AnalysisOptions {
1722                root: Some(dir.path().to_path_buf()),
1723                ..AnalysisOptions::default()
1724            },
1725            coverage: Some(relative.clone()),
1726            ..ComplexityOptions::default()
1727        });
1728        assert!(result.is_ok(), "{result:?}");
1729
1730        let err = validate_complexity_options(&ComplexityOptions {
1731            analysis: AnalysisOptions {
1732                root: Some(dir.path().join("elsewhere")),
1733                ..AnalysisOptions::default()
1734            },
1735            coverage: Some(relative),
1736            ..ComplexityOptions::default()
1737        })
1738        .expect_err("the path does not exist under the other root");
1739        assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1740        assert!(
1741            err.message.contains("elsewhere"),
1742            "the message names the resolved path: {}",
1743            err.message
1744        );
1745    }
1746
1747    #[test]
1748    fn default_health_sections_match_full_health_output() {
1749        let derived = derive_health_sections(&HealthSectionOptions {
1750            output: fallow_types::output_format::OutputFormat::Human,
1751            complexity: false,
1752            file_scores: false,
1753            coverage_gaps: false,
1754            hotspots: false,
1755            targets: false,
1756            css: false,
1757            score: false,
1758            score_gate: false,
1759            snapshot_requested: false,
1760            trend: false,
1761        });
1762
1763        assert!(!derived.any_section);
1764        assert!(derived.complexity);
1765        assert!(derived.file_scores);
1766        assert!(!derived.coverage_gaps);
1767        assert!(derived.hotspots);
1768        assert!(derived.targets);
1769        assert!(derived.score);
1770        assert!(derived.force_full);
1771        assert!(!derived.score_only_output);
1772    }
1773
1774    #[test]
1775    fn health_score_gate_requests_score_only_output() {
1776        let derived = derive_health_sections(&HealthSectionOptions {
1777            output: fallow_types::output_format::OutputFormat::Human,
1778            complexity: false,
1779            file_scores: false,
1780            coverage_gaps: false,
1781            hotspots: false,
1782            targets: false,
1783            css: false,
1784            score: false,
1785            score_gate: true,
1786            snapshot_requested: false,
1787            trend: false,
1788        });
1789
1790        assert!(derived.any_section);
1791        assert!(!derived.complexity);
1792        assert!(derived.file_scores);
1793        assert!(!derived.hotspots);
1794        assert!(!derived.targets);
1795        assert!(derived.score);
1796        assert!(derived.force_full);
1797        assert!(derived.score_only_output);
1798    }
1799
1800    #[test]
1801    fn health_snapshot_keeps_full_hidden_inputs_without_section_request() {
1802        let derived = derive_health_sections(&HealthSectionOptions {
1803            output: fallow_types::output_format::OutputFormat::Human,
1804            complexity: false,
1805            file_scores: false,
1806            coverage_gaps: false,
1807            hotspots: false,
1808            targets: false,
1809            css: true,
1810            score: false,
1811            score_gate: false,
1812            snapshot_requested: true,
1813            trend: false,
1814        });
1815
1816        assert!(!derived.any_section);
1817        assert!(derived.css);
1818        assert!(derived.file_scores);
1819        assert!(derived.hotspots);
1820        assert!(derived.score);
1821        assert!(derived.force_full);
1822    }
1823}