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