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