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