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