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