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, MutationReplayOptions, MutationRunOptions,
186    MutationRunScope, 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    replay_mutation, 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    /// Request advisory shared-state observations and an explicit finding selection.
458    pub shared_state: bool,
459    /// Files never reached from any entry point.
460    pub unused_files: bool,
461    /// Exported symbols never imported elsewhere.
462    pub unused_exports: bool,
463    /// Declared dependencies never imported.
464    pub unused_deps: bool,
465    /// Exported types never referenced.
466    pub unused_types: bool,
467    /// Exported APIs that expose non-exported types.
468    pub private_type_leaks: bool,
469    /// Exports marked `@deprecated` that are still in use.
470    pub deprecated_exports_in_use: bool,
471    /// Enum members never read.
472    pub unused_enum_members: bool,
473    /// Class members never used outside their declaration.
474    pub unused_class_members: bool,
475    /// Members of an exported TypeScript namespace that no code reads.
476    pub unused_namespace_members: bool,
477    /// Store members (for example Pinia) never used outside the store.
478    pub unused_store_members: bool,
479    /// `inject` calls with no matching `provide`.
480    pub unprovided_injects: bool,
481    /// Components never rendered by any template or JSX.
482    pub unrendered_components: bool,
483    /// Declared component props never used.
484    pub unused_component_props: bool,
485    /// Review optional props omitted by known reachable callers.
486    pub absent_component_props: bool,
487    /// Review parameters that each visible call passes in one way.
488    pub constant_parameters: bool,
489    /// Declared component emits never used.
490    pub unused_component_emits: bool,
491    /// Declared component inputs never bound.
492    pub unused_component_inputs: bool,
493    /// Declared component outputs never listened to.
494    pub unused_component_outputs: bool,
495    /// Svelte component events never listened to.
496    pub unused_svelte_events: bool,
497    /// Effect layers composed only into unused layers.
498    pub unused_effect_layers: bool,
499    /// Effect tagged errors that no code produces.
500    pub unused_tagged_errors: bool,
501    /// `catchTag` handlers for a tag that no code produces.
502    pub unproduced_catch_tags: bool,
503    /// Server actions never invoked.
504    pub unused_server_actions: bool,
505    /// `load` data keys never read by the consuming page.
506    pub unused_load_data_keys: bool,
507    /// Imports that do not resolve to a file or package.
508    pub unresolved_imports: bool,
509    /// Imported packages missing from the dependency manifest.
510    pub unlisted_deps: bool,
511    /// Binaries that no installed or listed package provides.
512    pub unlisted_binaries: bool,
513    /// The same symbol exported more than once.
514    pub duplicate_exports: bool,
515    /// One binding that one module exports under two or more names.
516    pub duplicate_export_aliases: bool,
517    /// Circular import chains.
518    pub circular_deps: bool,
519    /// Cycles formed through re-export chains.
520    pub re_export_cycles: bool,
521    /// Dependency cycles between workspace packages.
522    pub package_cycles: bool,
523    /// Imports that cross configured architecture boundaries.
524    pub boundary_violations: bool,
525    /// Violations of configured dependency policy rules.
526    pub policy_violations: bool,
527    /// Suppression comments that no longer match a finding.
528    pub stale_suppressions: bool,
529    /// Catalog entries never referenced by a workspace package.
530    pub unused_catalog_entries: bool,
531    /// Catalog groups that contain no entries.
532    pub empty_catalog_groups: bool,
533    /// `catalog:` references without a matching catalog entry.
534    pub unresolved_catalog_references: bool,
535    /// Dependency overrides that never affect a resolved package.
536    pub unused_dependency_overrides: bool,
537    /// Dependency overrides that cannot apply as written.
538    pub misconfigured_dependency_overrides: bool,
539}
540
541impl DeadCodeFilters {
542    /// Whether the report keeps dependency findings: no filter is active, or
543    /// `unused_deps` or `unlisted_deps` is one of the active filters. The CLI
544    /// applies the same rule to its `--unused-deps` and `--unlisted-deps`.
545    pub(crate) fn reports_dependency_findings(&self) -> bool {
546        !self.any_active() || self.unused_deps || self.unlisted_deps
547    }
548
549    fn any_active(&self) -> bool {
550        self.shared_state
551            || self.unused_files
552            || self.unused_exports
553            || self.unused_deps
554            || self.unused_types
555            || self.private_type_leaks
556            || self.deprecated_exports_in_use
557            || self.unused_enum_members
558            || self.unused_class_members
559            || self.unused_namespace_members
560            || self.unused_store_members
561            || self.unprovided_injects
562            || self.unrendered_components
563            || self.unused_component_props
564            || self.absent_component_props
565            || self.constant_parameters
566            || self.unused_component_emits
567            || self.unused_component_inputs
568            || self.unused_component_outputs
569            || self.unused_svelte_events
570            || self.unused_effect_layers
571            || self.unused_tagged_errors
572            || self.unproduced_catch_tags
573            || self.unused_server_actions
574            || self.unused_load_data_keys
575            || self.unresolved_imports
576            || self.unlisted_deps
577            || self.unlisted_binaries
578            || self.duplicate_exports
579            || self.duplicate_export_aliases
580            || self.circular_deps
581            || self.re_export_cycles
582            || self.package_cycles
583            || self.boundary_violations
584            || self.policy_violations
585            || self.stale_suppressions
586            || self.unused_catalog_entries
587            || self.empty_catalog_groups
588            || self.unresolved_catalog_references
589            || self.unused_dependency_overrides
590            || self.misconfigured_dependency_overrides
591    }
592
593    /// Enable the issue filter addressed by a shared registry selector.
594    ///
595    /// Returns `false` when the selector is not registered for dead-code
596    /// filtering. Callers that expose user input should surface their own
597    /// validation error with the accepted registry values.
598    pub fn enable_registry_selector(&mut self, selector: &str) -> bool {
599        let Some(flag) = fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS
600            .iter()
601            .find_map(|&(name, flag)| (name == selector).then_some(flag))
602        else {
603            return false;
604        };
605        self.enable_cli_filter_flag(flag);
606        true
607    }
608
609    /// The canonical CLI selector of each active filter.
610    pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
611        fallow_engine::requested_rule_off::explicit_filter_flags(|flag| {
612            let mut enabled = self.clone();
613            enabled.enable_cli_filter_flag(flag);
614            enabled == *self
615        })
616    }
617
618    fn enable_cli_filter_flag(&mut self, flag: &str) {
619        match flag {
620            "--unused-files" => self.unused_files = true,
621            "--unused-exports" => self.unused_exports = true,
622            "--unused-types" => self.unused_types = true,
623            "--private-type-leaks" => self.private_type_leaks = true,
624            "--deprecated-exports-in-use" => self.deprecated_exports_in_use = true,
625            "--unused-deps" => self.unused_deps = true,
626            "--unused-enum-members" => self.unused_enum_members = true,
627            "--unused-class-members" => self.unused_class_members = true,
628            "--unused-namespace-members" => self.unused_namespace_members = true,
629            "--unused-store-members" => self.unused_store_members = true,
630            "--unprovided-injects" => self.unprovided_injects = true,
631            "--unrendered-components" => self.unrendered_components = true,
632            "--unused-component-props" => self.unused_component_props = true,
633            "--absent-component-props" => self.absent_component_props = true,
634            "--constant-parameters" => self.constant_parameters = true,
635            "--unused-component-emits" => self.unused_component_emits = true,
636            "--unused-component-inputs" => self.unused_component_inputs = true,
637            "--unused-component-outputs" => self.unused_component_outputs = true,
638            "--unused-svelte-events" => self.unused_svelte_events = true,
639            "--unused-effect-layers" => self.unused_effect_layers = true,
640            "--unused-tagged-errors" => self.unused_tagged_errors = true,
641            "--unproduced-catch-tags" => self.unproduced_catch_tags = true,
642            "--unused-server-actions" => self.unused_server_actions = true,
643            "--unused-load-data-keys" => self.unused_load_data_keys = true,
644            "--unresolved-imports" => self.unresolved_imports = true,
645            "--unlisted-deps" => self.unlisted_deps = true,
646            "--unlisted-binaries" => self.unlisted_binaries = true,
647            "--duplicate-exports" => self.duplicate_exports = true,
648            "--duplicate-export-aliases" => self.duplicate_export_aliases = true,
649            "--circular-deps" => self.circular_deps = true,
650            "--re-export-cycles" => self.re_export_cycles = true,
651            "--package-cycles" => self.package_cycles = true,
652            "--boundary-violations" => self.boundary_violations = true,
653            "--policy-violations" => self.policy_violations = true,
654            "--stale-suppressions" => self.stale_suppressions = true,
655            "--unused-catalog-entries" => self.unused_catalog_entries = true,
656            "--empty-catalog-groups" => self.empty_catalog_groups = true,
657            "--unresolved-catalog-references" => self.unresolved_catalog_references = true,
658            "--unused-dependency-overrides" => self.unused_dependency_overrides = true,
659            "--misconfigured-dependency-overrides" => {
660                self.misconfigured_dependency_overrides = true;
661            }
662            _ => unreachable!("registry emitted unsupported dead-code filter flag: {flag}"),
663        }
664    }
665}
666
667/// Options for dead-code-oriented analyses.
668#[derive(Debug, Clone, Default)]
669pub struct DeadCodeOptions {
670    /// Shared analysis options.
671    pub analysis: AnalysisOptions,
672    /// Issue-type selection; everything is reported when no filter is set.
673    pub filters: DeadCodeFilters,
674    /// Restrict findings to these files when non-empty.
675    pub files: Vec<PathBuf>,
676    /// Also report unused exports declared in entry-point files.
677    pub include_entry_exports: bool,
678    /// Keep the export and member findings of unused files (`--show-cascade`).
679    pub show_cascade: bool,
680    /// Report only the findings with these `finding_id` values. The filter
681    /// runs last, after the baseline, and the output then carries
682    /// `finding_id_query`. Empty reports every finding. Only
683    /// [`run_dead_code`] and [`run_dead_code_with_baseline`] accept it.
684    pub finding_ids: Vec<String>,
685}
686
687/// Options for the analysis of `fallow architecture`: import cycles, boundary
688/// violations and rule-pack policy violations.
689///
690/// No selector reports every architecture issue type. Each selector keeps one
691/// kind, as `--cycles`, `--boundaries` and `--policy` do on the CLI.
692#[derive(Debug, Clone, Default)]
693pub struct ArchitectureOptions {
694    /// Include the optional advisory shared-state inventory.
695    pub shared_state: bool,
696    /// Shared analysis options.
697    pub analysis: AnalysisOptions,
698    /// Restrict findings to these files when non-empty.
699    pub files: Vec<PathBuf>,
700    /// Import cycles: circular dependencies, re-export cycles and workspace
701    /// package cycles.
702    pub cycles: bool,
703    /// Boundary violations, boundary coverage and forbidden calls.
704    pub boundaries: bool,
705    /// Rule-pack policy violations.
706    pub policy: bool,
707}
708
709impl ArchitectureOptions {
710    /// The dead-code issue-type filters that the selectors stand for.
711    #[must_use]
712    pub fn dead_code_filters(&self) -> DeadCodeFilters {
713        let all = !(self.cycles || self.boundaries || self.policy || self.shared_state);
714        DeadCodeFilters {
715            shared_state: self.shared_state,
716            circular_deps: self.cycles || all,
717            re_export_cycles: self.cycles || all,
718            package_cycles: self.cycles || all,
719            boundary_violations: self.boundaries || all,
720            policy_violations: self.policy || all,
721            ..DeadCodeFilters::default()
722        }
723    }
724
725    /// The canonical CLI selector of each selector that the caller set. No
726    /// selector asks for no specific check, so the list is empty.
727    pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
728        fallow_engine::requested_rule_off::architecture_requested_flags(
729            self.cycles,
730            self.boundaries,
731            self.policy,
732        )
733    }
734
735    /// The dead-code options that run this analysis.
736    #[must_use]
737    pub fn dead_code_options(&self) -> DeadCodeOptions {
738        DeadCodeOptions {
739            analysis: self.analysis.clone(),
740            filters: self.dead_code_filters(),
741            files: self.files.clone(),
742            include_entry_exports: false,
743            show_cascade: false,
744            finding_ids: Vec::new(),
745        }
746    }
747}
748
749/// Options for changed-code audit analysis.
750#[derive(Debug, Clone, Default)]
751pub struct AuditOptions {
752    /// Shared analysis options.
753    pub analysis: AnalysisOptions,
754    /// Git base reference for the changed-code comparison. `None` lets the
755    /// audit detect a base itself.
756    pub base: Option<String>,
757    /// Force production mode for every audit domain.
758    pub production: bool,
759    /// Production override for the dead-code domain; `None` defers to config.
760    pub production_dead_code: Option<bool>,
761    /// Production override for the health domain; `None` defers to config.
762    pub production_health: Option<bool>,
763    /// Production override for the duplication domain; `None` defers to
764    /// config.
765    pub production_dupes: Option<bool>,
766    /// Run the dead-code domain; `None` defers to `audit.deadCode` in config,
767    /// which defaults to on. When off, the verdict comes from the domains that
768    /// run.
769    pub dead_code: Option<bool>,
770    /// Run the health domain; `None` defers to `audit.health` in config,
771    /// which defaults to on.
772    pub health: Option<bool>,
773    /// Run the duplication domain; `None` defers to `audit.dupes` in config,
774    /// which defaults to on.
775    pub duplication: Option<bool>,
776    /// `Some(false)` skips CSS / styling analysis, as `--no-css` does. `None`
777    /// and `Some(true)` defer to `audit.css` in config, which defaults to on.
778    pub css: Option<bool>,
779    /// Enable deep cross-file CSS analysis; `None` defers to `audit.cssDeep`
780    /// in config, which defaults to on. It runs only when CSS analysis runs.
781    pub css_deep: Option<bool>,
782    /// Gate mode deciding which findings fail the audit; `None` defers to
783    /// `audit.gate` in config, which defaults to `new-only`.
784    pub gate: Option<fallow_config::AuditGate>,
785    /// How a worsened complexity finding affects the verdict; `None` defers
786    /// to `audit.worsened` in config, which defaults to `warn`.
787    pub worsened: Option<fallow_config::AuditWorsened>,
788    /// Fail the gate when a changed function exceeds this CRAP score.
789    pub max_crap: Option<f64>,
790    /// Test coverage report path for coverage-aware findings.
791    pub coverage: Option<PathBuf>,
792    /// Absolute path prefix the coverage report recorded its files under.
793    pub coverage_root: Option<PathBuf>,
794    /// Also report unused exports declared in entry-point files.
795    pub include_entry_exports: bool,
796    /// Keep the export and member findings of unused files (`--show-cascade`).
797    pub show_cascade: bool,
798    /// Runtime coverage capture merged into the audit.
799    pub runtime_coverage: Option<PathBuf>,
800    /// Minimum recorded invocations for a code path to count as hot.
801    pub min_invocations_hot: u64,
802}
803
804/// Options for bare combined analysis through the programmatic API.
805#[derive(Debug, Clone)]
806pub struct CombinedOptions {
807    /// Shared analysis options.
808    pub analysis: AnalysisOptions,
809    /// Run the dead-code domain.
810    pub dead_code: bool,
811    /// Run the duplication domain.
812    pub duplication: bool,
813    /// Run the health domain.
814    pub health: bool,
815    /// Also report unused exports declared in entry-point files.
816    pub include_entry_exports: bool,
817    /// Keep the export and member findings of unused files (`--show-cascade`).
818    pub show_cascade: bool,
819    /// Options for the duplication domain.
820    pub duplication_options: DuplicationOptions,
821    /// Options for the health domain.
822    pub health_options: ComplexityOptions,
823}
824
825impl Default for CombinedOptions {
826    fn default() -> Self {
827        Self {
828            analysis: AnalysisOptions::default(),
829            dead_code: true,
830            duplication: true,
831            health: true,
832            include_entry_exports: false,
833            show_cascade: false,
834            duplication_options: DuplicationOptions::default(),
835            health_options: ComplexityOptions::default(),
836        }
837    }
838}
839
840/// Options for changed-code decision-surface analysis.
841#[derive(Debug, Clone, Default)]
842pub struct DecisionSurfaceOptions {
843    /// Shared analysis options.
844    pub analysis: AnalysisOptions,
845    /// Git base reference for the changed-code comparison. `None` lets the
846    /// analysis detect a base itself.
847    pub base: Option<String>,
848    /// Cap on the number of decisions surfaced.
849    pub max_decisions: Option<usize>,
850}
851
852/// Options for feature-flag analysis.
853#[derive(Debug, Clone, Default)]
854pub struct FeatureFlagsOptions {
855    /// Shared analysis options.
856    pub analysis: AnalysisOptions,
857    /// Cap on the number of reported flags. With `retirement`, it also caps
858    /// the retirement rows.
859    pub top: Option<usize>,
860    /// Retirement report options. `None` leaves the `retirement` block out.
861    pub retirement: Option<FeatureFlagsRetirementOptions>,
862}
863
864/// Options of the flag retirement report, the `--retirement` mode of
865/// `fallow flags`.
866#[derive(Debug, Clone, Default)]
867pub struct FeatureFlagsRetirementOptions {
868    /// How to measure flag age.
869    pub flag_age: fallow_types::flag_retirement::FlagAgeMode,
870    /// Vendor flag export to read, like `--flag-state`.
871    pub flag_state: Option<std::path::PathBuf>,
872    /// Keep only rows with one of these reasons. Empty keeps all rows.
873    pub reasons: Vec<fallow_types::flag_retirement::RetirementReason>,
874    /// Row order.
875    pub sort: fallow_engine::flag_retirement::RetirementSort,
876    /// Keep only rows at least this many days old.
877    pub min_age_days: Option<u64>,
878    /// Report the flags older than this many days in `max_flag_age`.
879    pub max_flag_age: Option<u64>,
880}
881
882/// Programmatic duplication mode selection.
883#[derive(Debug, Clone, Copy, Default)]
884pub enum DuplicationMode {
885    /// Preserve all tokens, including identifier names and literal values
886    /// (Type-1 clones only).
887    Strict,
888    /// Default mode, equivalent to strict for AST-based tokenization.
889    #[default]
890    Mild,
891    /// Blind string literal values while preserving structure.
892    Weak,
893    /// Blind all identifiers and literal values for structural (Type-2)
894    /// detection.
895    Semantic,
896}
897
898/// Options for duplication analysis.
899#[derive(Debug, Clone, Default)]
900pub struct DuplicationOptions {
901    /// Shared analysis options.
902    pub analysis: AnalysisOptions,
903    /// Detection mode; `None` defers to the project config.
904    pub mode: Option<DuplicationMode>,
905    /// Detect function-scoped near-miss clones in addition to exact clones.
906    /// `None` defers to the project config.
907    pub near: Option<bool>,
908    /// Minimum number of tokens for a clone.
909    pub min_tokens: Option<usize>,
910    /// Minimum number of lines for a clone.
911    pub min_lines: Option<usize>,
912    /// Minimum number of occurrences before a clone group is reported.
913    /// Values below 2 are silently treated as 2 by the engine-facing adapter.
914    pub min_occurrences: Option<usize>,
915    /// Maximum allowed duplication percentage before the gate fails; 0 means
916    /// no limit. `None` defers to the project config.
917    pub threshold: Option<f64>,
918    /// Only report cross-directory duplicates. `None` defers to the project
919    /// config.
920    pub skip_local: Option<bool>,
921    /// Omit clone instances whose path is a symlink or lies under a symlinked
922    /// directory. `None` defers to the project config.
923    pub ignore_symlinks: Option<bool>,
924    /// Match clones across languages. `None` defers to the project config.
925    pub cross_language: Option<bool>,
926    /// Exclude module wiring from clone detection. `None` defers to the project
927    /// config.
928    pub ignore_imports: Option<bool>,
929    /// Cap on the number of reported clone groups.
930    pub top: Option<usize>,
931    /// Emit the verbatim source text on each clone instance. `None` keeps the
932    /// text, matching `fallow dupes` without `--no-fragments`; `Some(false)`
933    /// yields a location-only payload.
934    pub include_fragments: Option<bool>,
935}
936
937/// Options for local advisory similar-code discovery.
938#[derive(Debug, Clone, Default)]
939pub struct SimilarCodeOptions {
940    /// Shared project, config, cache, diff, and workspace options.
941    pub analysis: AnalysisOptions,
942    /// Model-specific cosine floor. `None` uses `similarCode.threshold`.
943    pub threshold: Option<f64>,
944    /// Minimum source lines per function. `None` uses
945    /// `similarCode.minLines`.
946    pub min_lines: Option<usize>,
947    /// Cap on displayed candidates after the full bounded comparison.
948    pub top: Option<usize>,
949    /// Restrict work and reported pairs to those where at least one side matches
950    /// one of these project-relative files. Deterministic background context is
951    /// retained only within the bounded scoped comparison budget.
952    pub files: Vec<PathBuf>,
953    /// Exact companion binary resolved and signature-verified by an official
954    /// distribution adapter such as the Node loader. `None` uses trusted
955    /// sibling discovery. Project config, PATH commands, and remote providers
956    /// must never populate this field.
957    #[doc(hidden)]
958    pub adapter_provider_path: Option<PathBuf>,
959}
960
961/// Options for one similar-code candidate inspection packet.
962#[derive(Debug, Clone)]
963pub struct SimilarCodeInspectOptions {
964    /// Shared project and configuration options used only for source validation
965    /// and deterministic enrichment. Inspect never reruns provider retrieval.
966    pub analysis: AnalysisOptions,
967    /// Bounded candidate handoff selected from the original discovery output.
968    pub snapshot: fallow_output::SimilarCodeCandidateSnapshot,
969}
970
971/// Options for export trace analysis.
972#[derive(Debug, Clone, Default)]
973pub struct TraceExportOptions {
974    /// Shared analysis options.
975    pub analysis: AnalysisOptions,
976    /// Path of the module that declares the export.
977    pub file: String,
978    /// Name of the export to trace.
979    pub export_name: String,
980}
981
982/// Options for file trace analysis.
983#[derive(Debug, Clone, Default)]
984pub struct TraceFileOptions {
985    /// Shared analysis options.
986    pub analysis: AnalysisOptions,
987    /// Path of the file to trace.
988    pub file: String,
989}
990
991/// Options for shortest-import-path trace analysis.
992#[derive(Debug, Clone, Default)]
993pub struct TraceImportPathOptions {
994    /// Shared analysis options.
995    pub analysis: AnalysisOptions,
996    /// Path of the module the walk starts from.
997    pub from: String,
998    /// Path of the module the walk is looking for.
999    pub to: String,
1000    /// Follow only static imports that carry a runtime value, so the route
1001    /// explains why `to` loads before `from` runs.
1002    pub eager_only: bool,
1003}
1004
1005/// Options for stack-trace frame resolution.
1006#[derive(Debug, Clone, Default)]
1007pub struct TraceErrorOptions {
1008    /// Shared analysis options.
1009    pub analysis: AnalysisOptions,
1010    /// The runtime stack trace, verbatim.
1011    pub trace: String,
1012    /// Where the trace came from, reported back as the payload's `source`.
1013    pub source: String,
1014}
1015
1016/// Options for dependency trace analysis.
1017#[derive(Debug, Clone, Default)]
1018pub struct TraceDependencyOptions {
1019    /// Shared analysis options.
1020    pub analysis: AnalysisOptions,
1021    /// Package whose importers are traced.
1022    pub package_name: String,
1023    /// The per-specifier usage to report. `None` keeps the output equal to
1024    /// `fallow dead-code --trace-dependency`, with no `usage` object.
1025    pub usage: Option<DependencyUsageQuery>,
1026}
1027
1028/// Duplicate-code trace target.
1029#[derive(Debug, Clone, PartialEq, Eq)]
1030pub enum TraceCloneTarget {
1031    /// Select the clone group covering this file and line.
1032    Location {
1033        /// Path of the file containing the clone instance.
1034        file: String,
1035        /// One-based line inside the clone instance.
1036        line: usize,
1037    },
1038    /// Select the clone group by its fingerprint.
1039    Fingerprint(String),
1040}
1041
1042/// Options for duplicate-code trace analysis.
1043#[derive(Debug, Clone)]
1044pub struct TraceCloneOptions {
1045    /// Duplication options controlling detection before the trace.
1046    pub duplication: DuplicationOptions,
1047    /// Clone group to trace.
1048    pub target: TraceCloneTarget,
1049}
1050
1051/// Sort criteria for complexity findings.
1052#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1053pub enum ComplexitySort {
1054    /// Sort by cyclomatic complexity (default).
1055    #[default]
1056    Cyclomatic,
1057    /// Sort by cognitive complexity.
1058    Cognitive,
1059    /// Sort by function length in lines.
1060    Lines,
1061    /// Sort by finding severity.
1062    Severity,
1063}
1064
1065/// Privacy mode for ownership-aware hotspot output.
1066#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1067pub enum OwnershipEmailMode {
1068    /// Show the raw email address as it appears in git history.
1069    Raw,
1070    /// Show only the local part before the `@` (default).
1071    #[default]
1072    Handle,
1073    /// Show a stable non-cryptographic pseudonym derived from the raw email.
1074    Anonymized,
1075    /// Legacy spelling retained for embedders that already pass `hash`.
1076    Hash,
1077}
1078
1079/// Effort filter for refactoring targets.
1080#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1081pub enum TargetEffort {
1082    /// Low estimated refactoring effort.
1083    Low,
1084    /// Medium estimated refactoring effort.
1085    Medium,
1086    /// High estimated refactoring effort.
1087    High,
1088}
1089
1090/// Options for complexity / health analysis.
1091#[derive(Debug, Clone, Default)]
1092pub struct ComplexityOptions {
1093    /// Shared analysis options.
1094    pub analysis: AnalysisOptions,
1095    /// Override for the cyclomatic complexity threshold.
1096    pub max_cyclomatic: Option<u16>,
1097    /// Override for the cognitive complexity threshold.
1098    pub max_cognitive: Option<u16>,
1099    /// Override for the CRAP score threshold.
1100    pub max_crap: Option<f64>,
1101    /// Override for the file-length threshold in physical lines. `0` turns
1102    /// the check off.
1103    pub max_file_lines: Option<u32>,
1104    /// Cap on the number of reported findings.
1105    pub top: Option<usize>,
1106    /// Sort order for complexity findings.
1107    pub sort: ComplexitySort,
1108    /// Include the per-metric complexity breakdown with each finding.
1109    pub complexity_breakdown: bool,
1110    /// Request the complexity findings section.
1111    pub complexity: bool,
1112    /// Request the per-file score section.
1113    pub file_scores: bool,
1114    /// Request the coverage-gap section.
1115    pub coverage_gaps: bool,
1116    /// Request the churn hotspot section.
1117    pub hotspots: bool,
1118    /// Include ownership data with hotspots; implies the hotspot section.
1119    pub ownership: bool,
1120    /// Email privacy mode for ownership output; implies ownership when set.
1121    pub ownership_emails: Option<OwnershipEmailMode>,
1122    /// Request the refactoring targets section.
1123    pub targets: bool,
1124    /// Include CSS / styling health.
1125    pub css: bool,
1126    /// Enable deep cross-file CSS analysis.
1127    pub css_deep: bool,
1128    /// Filter refactoring targets by estimated effort; implies the targets
1129    /// section when set.
1130    pub effort: Option<TargetEffort>,
1131    /// Request the overall health score.
1132    pub score: bool,
1133    /// Git time window (for example `30d`) for churn-based sections.
1134    pub since: Option<String>,
1135    /// Minimum commit count for a file to count as a hotspot.
1136    pub min_commits: Option<u32>,
1137    /// Test coverage report path for coverage-aware sections.
1138    pub coverage: Option<PathBuf>,
1139    /// Absolute path prefix the coverage report recorded its files under.
1140    pub coverage_root: Option<PathBuf>,
1141    /// The coverage map was recorded against a different checkout of this
1142    /// project, so function line numbers may have drifted arbitrarily.
1143    /// Set internally by the audit base-worktree pass; leave `false` for
1144    /// same-checkout coverage.
1145    pub coverage_relocated: bool,
1146}
1147
1148/// Health threshold overrides accepted by the programmatic API.
1149#[derive(Debug, Clone, Copy, Default, PartialEq)]
1150pub struct ComplexityThresholdOverrides {
1151    /// Override for the cyclomatic complexity threshold.
1152    pub max_cyclomatic: Option<u16>,
1153    /// Override for the cognitive complexity threshold.
1154    pub max_cognitive: Option<u16>,
1155    /// Override for the CRAP score threshold.
1156    pub max_crap: Option<f64>,
1157    /// Override for the file-length threshold in physical lines.
1158    pub max_file_lines: Option<u32>,
1159}
1160
1161/// Coverage inputs accepted by the programmatic API.
1162#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1163pub struct ComplexityCoverageInputs<'a> {
1164    /// Test coverage report path.
1165    pub coverage: Option<&'a Path>,
1166    /// Absolute path prefix the coverage report recorded its files under.
1167    pub coverage_root: Option<&'a Path>,
1168    /// The coverage map was recorded against a different checkout of this
1169    /// project; tolerate arbitrary line drift for unambiguous name matches.
1170    pub coverage_relocated: bool,
1171}
1172
1173/// Input for deriving effective health sections from API-owned flags.
1174#[derive(Debug, Clone)]
1175pub struct HealthSectionOptions {
1176    /// Requested output format; `Badge` implies the score section.
1177    pub output: fallow_types::output_format::OutputFormat,
1178    /// The complexity findings section was requested.
1179    pub complexity: bool,
1180    /// The per-file score section was requested.
1181    pub file_scores: bool,
1182    /// The coverage-gap section was requested.
1183    pub coverage_gaps: bool,
1184    /// The churn hotspot section was requested.
1185    pub hotspots: bool,
1186    /// The refactoring targets section was requested.
1187    pub targets: bool,
1188    /// CSS / styling health was requested.
1189    pub css: bool,
1190    /// The overall health score was requested.
1191    pub score: bool,
1192    /// A score gate is active; implies the score section.
1193    pub score_gate: bool,
1194    /// A snapshot write was requested; forces full hidden inputs.
1195    pub snapshot_requested: bool,
1196    /// Trend output was requested; implies score and hotspot inputs.
1197    pub trend: bool,
1198}
1199
1200/// Derived section selection for health runs.
1201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1202pub struct DerivedHealthSections {
1203    /// At least one section was explicitly requested.
1204    pub any_section: bool,
1205    /// Emit the complexity findings section.
1206    pub complexity: bool,
1207    /// Compute the per-file score section.
1208    pub file_scores: bool,
1209    /// Emit the coverage-gap section.
1210    pub coverage_gaps: bool,
1211    /// Compute the churn hotspot section.
1212    pub hotspots: bool,
1213    /// Emit the refactoring targets section.
1214    pub targets: bool,
1215    /// Include CSS / styling health.
1216    pub css: bool,
1217    /// Compute the overall health score.
1218    pub score: bool,
1219    /// Compute full inputs even for sections that are not emitted.
1220    pub force_full: bool,
1221    /// Only the score should be printed.
1222    pub score_only_output: bool,
1223}
1224
1225/// Input for deriving effective programmatic complexity sections.
1226#[derive(Debug, Clone)]
1227pub struct ComplexitySectionOptions {
1228    /// The complexity findings section was requested.
1229    pub complexity: bool,
1230    /// The per-file score section was requested.
1231    pub file_scores: bool,
1232    /// The coverage-gap section was requested.
1233    pub coverage_gaps: bool,
1234    /// The churn hotspot section was requested.
1235    pub hotspots: bool,
1236    /// Ownership data was requested; implies the hotspot section.
1237    pub ownership: bool,
1238    /// The refactoring targets section was requested.
1239    pub targets: bool,
1240    /// CSS / styling health was requested.
1241    pub css: bool,
1242    /// The overall health score was requested.
1243    pub score: bool,
1244}
1245
1246/// Derived section selection for programmatic health / complexity runs.
1247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1248pub struct DerivedComplexityOptions {
1249    /// At least one section was explicitly requested.
1250    pub any_section: bool,
1251    /// Emit the complexity findings section.
1252    pub complexity: bool,
1253    /// Compute the per-file score section.
1254    pub file_scores: bool,
1255    /// Emit the coverage-gap section.
1256    pub coverage_gaps: bool,
1257    /// Compute the churn hotspot section.
1258    pub hotspots: bool,
1259    /// Include ownership data with hotspots.
1260    pub ownership: bool,
1261    /// Emit the refactoring targets section.
1262    pub targets: bool,
1263    /// Compute full inputs even for sections that are not emitted.
1264    pub force_full: bool,
1265    /// Only the score should be printed.
1266    pub score_only_output: bool,
1267    /// Compute the overall health score.
1268    pub score: bool,
1269}
1270
1271/// Normalized programmatic complexity / health inputs owned by `fallow-api`.
1272#[derive(Debug, Clone, PartialEq)]
1273pub struct ComplexityRunOptions<'a> {
1274    /// Complexity threshold overrides.
1275    pub thresholds: ComplexityThresholdOverrides,
1276    /// Cap on the number of reported findings.
1277    pub top: Option<usize>,
1278    /// Sort order for complexity findings.
1279    pub sort: ComplexitySort,
1280    /// Include the per-metric complexity breakdown with each finding.
1281    pub complexity_breakdown: bool,
1282    /// Derived effective section selection.
1283    pub sections: DerivedComplexityOptions,
1284    /// Email privacy mode for ownership output.
1285    pub ownership_emails: Option<OwnershipEmailMode>,
1286    /// Filter refactoring targets by estimated effort.
1287    pub effort: Option<TargetEffort>,
1288    /// Include CSS / styling health.
1289    pub css: bool,
1290    /// Enable deep cross-file CSS analysis.
1291    pub css_deep: bool,
1292    /// Git time window (for example `30d`) for churn-based sections.
1293    pub since: Option<&'a str>,
1294    /// Minimum commit count for a file to count as a hotspot.
1295    pub min_commits: Option<u32>,
1296    /// Test coverage inputs.
1297    pub coverage_inputs: ComplexityCoverageInputs<'a>,
1298}
1299
1300/// Build the process-global Rayon pool with the [`WORKER_STACK_SIZE`] stack
1301/// and `threads` workers. Zero threads selects the Rayon default count, which
1302/// honors `RAYON_NUM_THREADS`.
1303///
1304/// A process that runs analysis outside
1305/// [`ProgrammaticAnalysisContext::install`] calls this once at startup, before
1306/// any parallel work. Returns `false` when the global pool already exists or
1307/// when a worker thread cannot start. Rayon then keeps its default pool.
1308pub fn configure_global_analysis_pool(threads: usize) -> bool {
1309    fallow_engine::thread_pool::worker_pool_builder(threads)
1310        .build_global()
1311        .is_ok()
1312}
1313
1314/// Derive effective health section flags for API consumers.
1315#[must_use]
1316pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
1317    let score = options.score
1318        || options.score_gate
1319        || options.trend
1320        || matches!(
1321            options.output,
1322            fallow_types::output_format::OutputFormat::Badge
1323        );
1324    let any_section = options.complexity
1325        || options.file_scores
1326        || options.coverage_gaps
1327        || options.hotspots
1328        || options.targets
1329        || score;
1330    let effective_score = if any_section { score } else { true } || options.snapshot_requested;
1331    let force_full = options.snapshot_requested || effective_score;
1332
1333    DerivedHealthSections {
1334        any_section,
1335        complexity: if any_section {
1336            options.complexity
1337        } else {
1338            true
1339        },
1340        file_scores: if any_section {
1341            options.file_scores
1342        } else {
1343            true
1344        } || force_full,
1345        coverage_gaps: if any_section {
1346            options.coverage_gaps
1347        } else {
1348            false
1349        },
1350        hotspots: if any_section { options.hotspots } else { true }
1351            || options.snapshot_requested
1352            || options.trend,
1353        targets: if any_section { options.targets } else { true },
1354        css: options.css,
1355        score: effective_score,
1356        force_full,
1357        score_only_output: is_health_score_only_output(options, score),
1358    }
1359}
1360
1361/// Derive effective programmatic health / complexity section flags.
1362#[must_use]
1363pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
1364    let requested_hotspots = options.hotspots || options.ownership;
1365    let sections = derive_health_sections(&HealthSectionOptions {
1366        output: fallow_types::output_format::OutputFormat::Human,
1367        complexity: options.complexity,
1368        file_scores: options.file_scores,
1369        coverage_gaps: options.coverage_gaps,
1370        hotspots: requested_hotspots,
1371        targets: options.targets,
1372        css: options.css,
1373        score: options.score,
1374        score_gate: false,
1375        snapshot_requested: false,
1376        trend: false,
1377    });
1378
1379    DerivedComplexityOptions {
1380        any_section: sections.any_section,
1381        complexity: sections.complexity,
1382        file_scores: sections.file_scores,
1383        coverage_gaps: sections.coverage_gaps,
1384        hotspots: sections.hotspots,
1385        ownership: options.ownership && sections.hotspots,
1386        targets: sections.targets,
1387        force_full: sections.force_full,
1388        score_only_output: sections.score_only_output,
1389        score: sections.score,
1390    }
1391}
1392
1393/// Derive effective programmatic health / complexity section flags.
1394#[must_use]
1395pub fn derive_complexity_options(options: &ComplexityOptions) -> DerivedComplexityOptions {
1396    derive_complexity_sections(&complexity_section_options(options))
1397}
1398
1399/// Normalize public API complexity options into engine-owned run contracts.
1400#[must_use]
1401pub fn derive_complexity_run_options(options: &ComplexityOptions) -> ComplexityRunOptions<'_> {
1402    ComplexityRunOptions {
1403        thresholds: ComplexityThresholdOverrides {
1404            max_cyclomatic: options.max_cyclomatic,
1405            max_cognitive: options.max_cognitive,
1406            max_crap: options.max_crap,
1407            max_file_lines: options.max_file_lines,
1408        },
1409        top: options.top,
1410        sort: options.sort,
1411        complexity_breakdown: options.complexity_breakdown,
1412        sections: derive_complexity_options(options),
1413        ownership_emails: options.ownership_emails,
1414        effort: options.effort,
1415        css: options.css,
1416        css_deep: options.css_deep,
1417        since: options.since.as_deref(),
1418        min_commits: options.min_commits,
1419        coverage_inputs: ComplexityCoverageInputs {
1420            coverage: options.coverage.as_deref(),
1421            coverage_root: options.coverage_root.as_deref(),
1422            coverage_relocated: options.coverage_relocated,
1423        },
1424    }
1425}
1426
1427/// Validate programmatic complexity / health inputs before invoking a concrete
1428/// runner.
1429///
1430/// These option contracts belong to the API boundary because NAPI and future
1431/// Rust embedders construct the same [`ComplexityOptions`] type.
1432///
1433/// A relative coverage path resolves against `analysis.root` (the cwd when
1434/// unset), exactly as the engine resolves it at read time, so a
1435/// project-relative `health.coverage` validates against the project and not
1436/// against the embedder's working directory.
1437///
1438/// The options carry no record of which layer supplied `coverage`, so the
1439/// path error's `context` is always `health.coverage`, whichever of the tool
1440/// parameter, `FALLOW_COVERAGE`, or the config field won
1441/// ([`crate::coverage::resolve_coverage_inputs`] resolves that order). The
1442/// sibling root error names its layer because
1443/// [`crate::coverage::CoverageInputError`] carries it.
1444///
1445/// # Errors
1446///
1447/// Returns a structured programmatic error when a coverage path does not exist
1448/// or when `coverage_root` is not an absolute prefix from the coverage data.
1449pub fn validate_complexity_options(options: &ComplexityOptions) -> Result<(), ProgrammaticError> {
1450    if let Some(path) = &options.coverage {
1451        let resolved = fallow_engine::health::scoring::resolve_relative_to_root(
1452            path,
1453            options.analysis.root.as_deref(),
1454        );
1455        if !resolved.exists() {
1456            return Err(ProgrammaticError::new(
1457                format!("coverage path does not exist: {}", resolved.display()),
1458                2,
1459            )
1460            .with_code("FALLOW_INVALID_COVERAGE_PATH")
1461            .with_context("health.coverage"));
1462        }
1463    }
1464    if let Err(message) =
1465        fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
1466    {
1467        return Err(ProgrammaticError::new(message, 2)
1468            .with_code("FALLOW_INVALID_COVERAGE_ROOT")
1469            .with_context("health.coverage_root"));
1470    }
1471
1472    Ok(())
1473}
1474
1475fn complexity_section_options(options: &ComplexityOptions) -> ComplexitySectionOptions {
1476    let ownership = options.ownership || options.ownership_emails.is_some();
1477    let requested_targets = options.targets || options.effort.is_some();
1478    ComplexitySectionOptions {
1479        complexity: options.complexity,
1480        file_scores: options.file_scores,
1481        coverage_gaps: options.coverage_gaps,
1482        hotspots: options.hotspots,
1483        ownership,
1484        targets: requested_targets,
1485        css: options.css,
1486        score: options.score,
1487    }
1488}
1489
1490fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
1491    score
1492        && !options.complexity
1493        && !options.file_scores
1494        && !options.coverage_gaps
1495        && !options.hotspots
1496        && !options.targets
1497        && !options.trend
1498}
1499
1500const fn thresholds_to_engine(
1501    thresholds: ComplexityThresholdOverrides,
1502) -> fallow_engine::health::HealthThresholdOverrides {
1503    fallow_engine::health::HealthThresholdOverrides {
1504        max_cyclomatic: thresholds.max_cyclomatic,
1505        max_cognitive: thresholds.max_cognitive,
1506        max_crap: thresholds.max_crap,
1507        max_file_lines: thresholds.max_file_lines,
1508    }
1509}
1510
1511const fn complexity_sort_to_engine(sort: ComplexitySort) -> fallow_engine::health::HealthSort {
1512    match sort {
1513        ComplexitySort::Severity => fallow_engine::health::HealthSort::Severity,
1514        ComplexitySort::Cyclomatic => fallow_engine::health::HealthSort::Cyclomatic,
1515        ComplexitySort::Cognitive => fallow_engine::health::HealthSort::Cognitive,
1516        ComplexitySort::Lines => fallow_engine::health::HealthSort::Lines,
1517    }
1518}
1519
1520const fn coverage_inputs_to_engine(
1521    coverage_inputs: ComplexityCoverageInputs<'_>,
1522) -> fallow_engine::health::HealthCoverageInputs<'_> {
1523    fallow_engine::health::HealthCoverageInputs {
1524        coverage: coverage_inputs.coverage,
1525        coverage_root: coverage_inputs.coverage_root,
1526        coverage_relocated: coverage_inputs.coverage_relocated,
1527    }
1528}
1529
1530const fn ownership_email_mode_to_config(mode: OwnershipEmailMode) -> EmailMode {
1531    match mode {
1532        OwnershipEmailMode::Raw => EmailMode::Raw,
1533        OwnershipEmailMode::Handle => EmailMode::Handle,
1534        OwnershipEmailMode::Anonymized => EmailMode::Anonymized,
1535        OwnershipEmailMode::Hash => EmailMode::Hash,
1536    }
1537}
1538
1539const fn target_effort_to_output(effort: TargetEffort) -> EffortEstimate {
1540    match effort {
1541        TargetEffort::Low => EffortEstimate::Low,
1542        TargetEffort::Medium => EffortEstimate::Medium,
1543        TargetEffort::High => EffortEstimate::High,
1544    }
1545}
1546
1547#[cfg(test)]
1548mod tests {
1549    use super::*;
1550
1551    #[test]
1552    fn duplication_defaults_match_cli_contract() {
1553        let options = DuplicationOptions::default();
1554        assert!(options.mode.is_none());
1555        assert!(options.min_tokens.is_none());
1556        assert!(options.min_lines.is_none());
1557        assert!(options.min_occurrences.is_none());
1558    }
1559
1560    #[test]
1561    fn programmatic_error_builder_keeps_optional_fields() {
1562        let error = ProgrammaticError::new("boom", 2)
1563            .with_code("FALLOW_TEST")
1564            .with_help("Try again")
1565            .with_context("analysis.root");
1566
1567        assert_eq!(error.message, "boom");
1568        assert_eq!(error.exit_code, 2);
1569        assert_eq!(error.code.as_deref(), Some("FALLOW_TEST"));
1570        assert_eq!(error.help.as_deref(), Some("Try again"));
1571        assert_eq!(error.context.as_deref(), Some("analysis.root"));
1572    }
1573
1574    #[test]
1575    fn dead_code_filters_accept_shared_registry_selectors() {
1576        for (selector, _) in fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS.iter() {
1577            let mut filters = DeadCodeFilters::default();
1578            assert!(
1579                filters.enable_registry_selector(selector),
1580                "{selector} should be accepted"
1581            );
1582        }
1583
1584        let mut filters = DeadCodeFilters::default();
1585        assert!(filters.enable_registry_selector("unused-files"));
1586        assert!(filters.unused_files);
1587        assert!(filters.enable_registry_selector("boundary-violations"));
1588        assert!(filters.boundary_violations);
1589        assert!(!filters.enable_registry_selector("not-a-real-selector"));
1590    }
1591
1592    #[test]
1593    fn default_complexity_options_match_programmatic_health_defaults() {
1594        let derived = derive_complexity_options(&ComplexityOptions::default());
1595
1596        assert!(!derived.any_section);
1597        assert!(derived.complexity);
1598        assert!(derived.file_scores);
1599        assert!(!derived.coverage_gaps);
1600        assert!(derived.hotspots);
1601        assert!(!derived.ownership);
1602        assert!(derived.targets);
1603        assert!(derived.force_full);
1604        assert!(!derived.score_only_output);
1605        assert!(derived.score);
1606    }
1607
1608    #[test]
1609    fn score_only_complexity_options_request_score_only_output() {
1610        let derived = derive_complexity_options(&ComplexityOptions {
1611            score: true,
1612            ..ComplexityOptions::default()
1613        });
1614
1615        assert!(derived.any_section);
1616        assert!(!derived.complexity);
1617        assert!(derived.file_scores);
1618        assert!(!derived.hotspots);
1619        assert!(!derived.targets);
1620        assert!(derived.force_full);
1621        assert!(derived.score_only_output);
1622        assert!(derived.score);
1623    }
1624
1625    #[test]
1626    fn ownership_implies_hotspots_when_requested() {
1627        let derived = derive_complexity_options(&ComplexityOptions {
1628            ownership: true,
1629            ..ComplexityOptions::default()
1630        });
1631
1632        assert!(derived.any_section);
1633        assert!(derived.hotspots);
1634        assert!(derived.ownership);
1635        assert!(!derived.targets);
1636    }
1637
1638    #[test]
1639    fn complexity_run_options_normalize_public_api_options() {
1640        let options = ComplexityOptions {
1641            max_cyclomatic: Some(42),
1642            max_cognitive: Some(21),
1643            max_crap: Some(18.5),
1644            top: Some(7),
1645            sort: ComplexitySort::Severity,
1646            complexity_breakdown: true,
1647            ownership_emails: Some(OwnershipEmailMode::Hash),
1648            effort: Some(TargetEffort::High),
1649            coverage: Some(PathBuf::from("coverage/coverage-final.json")),
1650            coverage_root: Some(PathBuf::from("/ci/workspace")),
1651            since: Some("30d".to_string()),
1652            min_commits: Some(4),
1653            ..ComplexityOptions::default()
1654        };
1655
1656        let run = derive_complexity_run_options(&options);
1657
1658        assert_eq!(run.thresholds.max_cyclomatic, Some(42));
1659        assert_eq!(run.thresholds.max_cognitive, Some(21));
1660        assert_eq!(run.thresholds.max_crap, Some(18.5));
1661        assert_eq!(run.top, Some(7));
1662        assert!(matches!(run.sort, ComplexitySort::Severity));
1663        assert!(run.complexity_breakdown);
1664        assert!(run.sections.hotspots);
1665        assert!(run.sections.ownership);
1666        assert!(run.sections.targets);
1667        assert!(matches!(
1668            run.ownership_emails,
1669            Some(OwnershipEmailMode::Hash)
1670        ));
1671        assert!(matches!(run.effort, Some(TargetEffort::High)));
1672        assert_eq!(run.since, Some("30d"));
1673        assert_eq!(run.min_commits, Some(4));
1674        assert_eq!(run.coverage_inputs.coverage, options.coverage.as_deref());
1675        assert_eq!(
1676            run.coverage_inputs.coverage_root,
1677            options.coverage_root.as_deref()
1678        );
1679    }
1680
1681    #[test]
1682    fn complexity_options_validation_accepts_existing_coverage_path_and_absolute_root() {
1683        let dir = tempfile::tempdir().expect("tempdir");
1684        let coverage = dir.path().join("coverage-final.json");
1685        std::fs::write(&coverage, "{}").expect("coverage fixture");
1686
1687        let result = validate_complexity_options(&ComplexityOptions {
1688            coverage: Some(coverage),
1689            coverage_root: Some(PathBuf::from("/ci/workspace")),
1690            ..ComplexityOptions::default()
1691        });
1692
1693        assert!(result.is_ok());
1694    }
1695
1696    #[test]
1697    fn complexity_options_validation_keeps_missing_coverage_error_contract() {
1698        let err = validate_complexity_options(&ComplexityOptions {
1699            coverage: Some(PathBuf::from("/missing/coverage-final.json")),
1700            ..ComplexityOptions::default()
1701        })
1702        .expect_err("missing coverage path should fail");
1703
1704        assert_eq!(err.exit_code, 2);
1705        assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1706        assert_eq!(err.context.as_deref(), Some("health.coverage"));
1707    }
1708
1709    #[test]
1710    fn complexity_options_validation_keeps_relative_coverage_root_error_contract() {
1711        let err = validate_complexity_options(&ComplexityOptions {
1712            coverage_root: Some(PathBuf::from("coverage")),
1713            ..ComplexityOptions::default()
1714        })
1715        .expect_err("relative coverage root should fail");
1716
1717        assert_eq!(err.exit_code, 2);
1718        assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_ROOT"));
1719        assert_eq!(err.context.as_deref(), Some("health.coverage_root"));
1720    }
1721
1722    /// #2368: a project-relative coverage path (the documented form of
1723    /// `health.coverage`) must be checked under the analysis root, not under
1724    /// the embedder's working directory.
1725    #[test]
1726    fn complexity_options_validation_resolves_relative_coverage_against_root() {
1727        let dir = tempfile::tempdir().expect("tempdir");
1728        std::fs::create_dir_all(dir.path().join("artifacts")).expect("artifacts dir");
1729        std::fs::write(dir.path().join("artifacts/coverage-final.json"), "{}")
1730            .expect("coverage fixture");
1731        let relative = PathBuf::from("artifacts/coverage-final.json");
1732        assert!(
1733            !relative.exists(),
1734            "the fixture must not also exist under the test cwd"
1735        );
1736
1737        let result = validate_complexity_options(&ComplexityOptions {
1738            analysis: AnalysisOptions {
1739                root: Some(dir.path().to_path_buf()),
1740                ..AnalysisOptions::default()
1741            },
1742            coverage: Some(relative.clone()),
1743            ..ComplexityOptions::default()
1744        });
1745        assert!(result.is_ok(), "{result:?}");
1746
1747        let err = validate_complexity_options(&ComplexityOptions {
1748            analysis: AnalysisOptions {
1749                root: Some(dir.path().join("elsewhere")),
1750                ..AnalysisOptions::default()
1751            },
1752            coverage: Some(relative),
1753            ..ComplexityOptions::default()
1754        })
1755        .expect_err("the path does not exist under the other root");
1756        assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1757        assert!(
1758            err.message.contains("elsewhere"),
1759            "the message names the resolved path: {}",
1760            err.message
1761        );
1762    }
1763
1764    #[test]
1765    fn default_health_sections_match_full_health_output() {
1766        let derived = derive_health_sections(&HealthSectionOptions {
1767            output: fallow_types::output_format::OutputFormat::Human,
1768            complexity: false,
1769            file_scores: false,
1770            coverage_gaps: false,
1771            hotspots: false,
1772            targets: false,
1773            css: false,
1774            score: false,
1775            score_gate: false,
1776            snapshot_requested: false,
1777            trend: false,
1778        });
1779
1780        assert!(!derived.any_section);
1781        assert!(derived.complexity);
1782        assert!(derived.file_scores);
1783        assert!(!derived.coverage_gaps);
1784        assert!(derived.hotspots);
1785        assert!(derived.targets);
1786        assert!(derived.score);
1787        assert!(derived.force_full);
1788        assert!(!derived.score_only_output);
1789    }
1790
1791    #[test]
1792    fn health_score_gate_requests_score_only_output() {
1793        let derived = derive_health_sections(&HealthSectionOptions {
1794            output: fallow_types::output_format::OutputFormat::Human,
1795            complexity: false,
1796            file_scores: false,
1797            coverage_gaps: false,
1798            hotspots: false,
1799            targets: false,
1800            css: false,
1801            score: false,
1802            score_gate: true,
1803            snapshot_requested: false,
1804            trend: false,
1805        });
1806
1807        assert!(derived.any_section);
1808        assert!(!derived.complexity);
1809        assert!(derived.file_scores);
1810        assert!(!derived.hotspots);
1811        assert!(!derived.targets);
1812        assert!(derived.score);
1813        assert!(derived.force_full);
1814        assert!(derived.score_only_output);
1815    }
1816
1817    #[test]
1818    fn health_snapshot_keeps_full_hidden_inputs_without_section_request() {
1819        let derived = derive_health_sections(&HealthSectionOptions {
1820            output: fallow_types::output_format::OutputFormat::Human,
1821            complexity: false,
1822            file_scores: false,
1823            coverage_gaps: false,
1824            hotspots: false,
1825            targets: false,
1826            css: true,
1827            score: false,
1828            score_gate: false,
1829            snapshot_requested: true,
1830            trend: false,
1831        });
1832
1833        assert!(!derived.any_section);
1834        assert!(derived.css);
1835        assert!(derived.file_scores);
1836        assert!(derived.hotspots);
1837        assert!(derived.score);
1838        assert!(derived.force_full);
1839    }
1840}
1841
1842mod shared_state_explain;