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