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