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