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