1#![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;
34pub mod audit_keys;
38mod audit_moved;
39pub mod audit_output;
40pub mod audit_run;
41pub mod combined_output;
42pub 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;
65pub mod markdown_output;
68pub mod mutation;
69mod next_steps;
70pub mod output_contracts;
71pub mod ownership;
72mod release_signature;
73pub mod released_skills;
74pub mod review_deltas;
75pub mod routing;
76pub mod run;
77pub mod runtime;
78mod runtime_json;
79mod runtime_output;
80pub mod sarif_output;
81pub mod schemas;
84pub mod security_output;
85pub mod similar_code;
87mod threshold_override_output;
88mod type_aware;
89pub use analysis_context::{ProgrammaticAnalysisContext, resolve_programmatic_analysis_context};
90pub use audit_output::{
91 AuditAttribution, AuditCodeClimateOutputInput, AuditJsonHeaderInput, AuditJsonOutputInput,
92 AuditSarifOutputInput, AuditSummary, AuditVerdict, attach_audit_diff_risk_attribution,
93 attach_audit_duplication_demotion_attribution, attach_audit_styling_attribution,
94 attach_audit_wire_attribution, audit_run_notices, build_audit_codeclimate,
95 build_audit_codeclimate_issues, build_audit_header_json, build_audit_header_map,
96 build_audit_sarif, build_diff_risk_codeclimate, build_review_brief_header,
97 serialize_audit_json,
98};
99pub use combined_output::{
100 CombinedCheckJsonSection, CombinedJsonOutputInput, serialize_combined_dupes_json,
101 serialize_combined_health_json, serialize_combined_json,
102};
103pub use compact_output::{
104 build_compact_lines, build_diff_risk_compact_lines, build_duplication_compact_lines,
105 build_grouped_compact_lines, build_health_compact_lines,
106};
107pub use coverage::{
108 CoverageInputError, CoverageInputSource, CoverageInputs, resolve_coverage_inputs,
109};
110pub use dead_code_codeclimate::build_codeclimate;
111pub use dead_code_sarif::build_sarif;
112pub use doctor::{DoctorOptions, run_doctor, run_doctor_with_cache_dir};
113pub use dupes_output::{
114 AttributedCloneGroup, AttributedCloneGroupFinding, AttributedInstance, CloneDemotionReason,
115 CloneFamilyFinding, CloneGroupFinding, CloneRegionFinding, CloneRegionGrade, CloneRegionSpan,
116 CombinedDupesSection, DupesReportPayload, DuplicationGroup, DuplicationGrouping,
117 build_duplication_codeclimate, set_duplication_audit_attribution,
118};
119pub use editor::{
120 ChangedFilesError, EditorAnalysisOutput, EditorAnalysisResults, EditorAnalysisSession,
121 EditorCloneFamily, EditorCloneFingerprintSet, EditorCloneGroup, EditorCloneInstance,
122 EditorDeadCodeAnalysisOutput, EditorDuplicationReport, EditorDuplicationStats,
123 EditorInlineComplexityExceeded, EditorInlineComplexityFinding, EditorMirroredDirectory,
124 EditorProjectAnalysisOutput, EditorRefactoringKind, EditorRefactoringSuggestion,
125 EditorSessionParseCounts, collect_inline_complexity, editor_duplicates, editor_extract,
126 editor_results, editor_security, editor_suppress, filter_inline_complexity_by_change_scope,
127 filter_inline_complexity_by_changed_files, resolve_git_toplevel,
128 try_get_changed_files_with_toplevel,
129};
130pub use explain::{
131 AUDIT_RULES, CHECK_RULES, DUPES_RULES, FLAGS_RULES, HEALTH_RULES, MUTATION_RULES, RuleDef,
132 RuleGuide, SECURITY_RULES, all_rules, bare_rule_id, coverage_analyze_meta, coverage_setup_meta,
133 explain_issue_type, rule_by_id, rule_by_token, rule_command, rule_config_key, rule_docs_url,
134 rule_guide, rule_has_guide, rule_rationale, rule_severity_key, security_meta,
135 serialize_explain_programmatic_json, unknown_explain_error,
136};
137pub use explain_examples::{ExampleAnchor, ExampleFile, RuleExample, rule_example, rule_examples};
138pub use fallow_config::levenshtein::closest_match;
139pub use fallow_config::{
140 AuditGate, AuditWorsened, HealthConfig, ProductionAnalysis, ProductionEnv, TypeAwareRequire,
141};
142pub use fallow_engine::change_scope::{
145 ChangeScope, ChangeScopeOwner, ChangeScopeRequest, first_package_baselines,
146 package_baseline_statuses,
147};
148pub use fallow_engine::discover::SOURCE_EXTENSIONS;
150#[cfg(any(test, feature = "testing"))]
153pub use fallow_engine::git_fixture;
154pub use fallow_engine::package_baselines::{PackageBaselineError, PackageChangeScope};
156pub use fallow_engine::post_edit;
159pub use fallow_engine::source_edits;
160pub use fallow_engine::thread_pool::{WORKER_STACK_SIZE, register_thread_stack};
167pub use fallow_engine::validate::validate_root;
170pub use fallow_engine::warm_parse;
176pub use fallow_output::PackageBaselineStatus;
178pub use fallow_output::serialize_similar_code_json_output;
179pub use fallow_types::trace::{
180 CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace, ReExportChain,
181 TracedCloneGroup, TracedExport, TracedReExport,
182};
183pub use fallow_types::trace_usage::{
184 DependencyUsage, DependencyUsageQuery, SitePageRequest, UsageQueryError,
185};
186pub use grouped_output::{
187 ResultGroup, UNOWNED_GROUP_LABEL, build_duplication_grouping_with, group_analysis_results_with,
188 health_signal_header_part, largest_clone_group_owner_with,
189};
190pub use health_codeclimate::build_health_codeclimate;
191pub use health_groups_markdown::build_health_groups_markdown;
192pub use json_output::{
193 CheckJsonExtraOutputs, CheckJsonOutputInput, CheckJsonPayloadInput, DuplicationJsonOutputInput,
194 GroupedCheckJsonOutputInput, GroupedDuplicationJsonOutputInput, serialize_check_json,
195 serialize_check_json_payload, serialize_duplication_json, serialize_grouped_check_json,
196 serialize_grouped_duplication_json,
197};
198pub use list_output::{
199 ListJsonEnvelope, ListJsonOutputInput, build_list_json_output, serialize_list_json_output,
200};
201pub use list_runtime::{
202 BoundaryData, ListBoundariesOptions, ListBoundariesProgrammaticOutput, LogicalGroupInfo,
203 ProjectInfoOptions, ProjectInfoProgrammaticOutput, RuleInfo, ZoneInfo, boundary_data_to_output,
204 compute_boundary_data, run_list_boundaries, run_project_info,
205 serialize_list_boundaries_programmatic_json, serialize_project_info_programmatic_json,
206};
207pub use markdown_output::{
208 ComplexityListing, build_diff_risk_markdown, build_duplication_markdown,
209 build_grouped_markdown, build_health_markdown, build_markdown, build_walkthrough_markdown,
210};
211pub use mutation::{
212 MutationProgress, MutationProgressSink, MutationReplayOptions, MutationRunOptions,
213 MutationRunScope, apply_mutation_verdicts, validate_mutation_verdicts,
214};
215pub use output_contracts::{
216 AuditOutput, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
217 BoundariesListing, CombinedOutput, FallowOutput, ImpactOutput, ListBoundariesOutput,
218 ListEntryPointOutput, ListOutput, ListPluginOutput, ReviewBriefWireOutput, SecurityGate,
219 SecurityOutput, SecurityOutputConfig, SecuritySummaryOutput, SimilarCodeCandidateSnapshot,
220 SimilarCodeOutput, TraceOutput, WorkspacesOutput,
221};
222pub use runtime::TYPE_AWARE_CONFIG_UNSUPPORTED;
223pub use runtime::{
224 AUDIT_CONFIG_BASELINE_UNSUPPORTED, ArchitectureOutput, ArchitectureProgrammaticOutput,
225 AuditProgrammaticKeySnapshot, AuditProgrammaticOutput, BoundaryViolationsOutput,
226 BoundaryViolationsProgrammaticOutput, CircularDependenciesOutput,
227 CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput, DeadCodeOutput,
228 DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput, DuplicationOutput,
229 DuplicationProgrammaticOutput, EngineHealthRunner, FeatureFlagsOutput,
230 FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
231 ProgrammaticHealthAnalysis, ProgrammaticHealthNextStepFacts, ProgrammaticHealthRun,
232 ProgrammaticHealthRunner, TraceClassMemberOutput, TraceCloneBenchmarkResult, TraceCloneOutput,
233 TraceCloneProgrammaticOutput, TraceDependencyOutput, TraceDependencyProgrammaticOutput,
234 TraceErrorOutput, TraceErrorProgrammaticOutput, TraceExportOutput,
235 TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
236 TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
237 benchmark_trace_clone_compact_json, benchmark_trace_graph_family_compact_json,
238 inspect_similar_code, load_health_config, parse_similar_code_candidate_snapshot, plan_mutation,
239 replay_mutation, review_similar_code, run_architecture, run_audit, run_boundary_violations,
240 run_circular_dependencies, run_combined, run_complexity_with_runner, run_dead_code,
241 run_dead_code_with_baseline, run_decision_surface, run_duplication, run_feature_flags,
242 run_health, run_health_with_runner, run_mutation, run_mutation_with_progress, run_similar_code,
243 run_trace_clone, run_trace_dependency, run_trace_error, run_trace_export, run_trace_file,
244 run_trace_import_path, select_similar_code_candidate_snapshot, serialize_health_report_json,
245};
246pub use runtime_json::{
247 serialize_architecture_programmatic_json, serialize_audit_programmatic_json,
248 serialize_boundary_violations_programmatic_json,
249 serialize_circular_dependencies_programmatic_json, serialize_combined_programmatic_json,
250 serialize_dead_code_programmatic_json, serialize_decision_surface_programmatic_json,
251 serialize_duplication_programmatic_json, serialize_feature_flags_programmatic_json,
252 serialize_health_programmatic_json, serialize_trace_clone_programmatic_json,
253 serialize_trace_dependency_programmatic_json, serialize_trace_error_programmatic_json,
254 serialize_trace_export_programmatic_json, serialize_trace_file_programmatic_json,
255 serialize_trace_import_path_programmatic_json,
256};
257pub use sarif_output::{
258 annotate_sarif_results, build_duplication_sarif, build_grouped_duplication_sarif,
259 build_health_sarif,
260};
261pub use security_output::SecurityGateMode;
262pub use type_aware::{
263 DEFAULT_BACKEND_FAMILY as DEFAULT_TYPE_AWARE_BACKEND_FAMILY, SemanticCouplingOutcome,
264 SemanticDeadCodeOutcome, SemanticInspectOutcome, TypeAwareError, TypeAwareFileChanges,
265 TypeAwareOutcome, TypeAwareSession, TypeAwareStatus, discard_unverified_semantic_candidates,
266 inspect_symbol as inspect_type_aware_symbol, merge_type_aware_meta,
267 refine_configured_dead_code_results as refine_type_aware_results_with_config,
268 shutdown_type_aware_sidecars, status as type_aware_status,
269 symbol_impact as run_type_aware_symbol_impact, symbol_impact as type_aware_symbol_impact,
270 terminate_active_type_aware_sidecars, trace_symbol as run_type_aware_symbol_trace,
271 trace_symbol as trace_type_aware_symbol, type_coupling as analyze_type_coupling,
272};
273
274pub use type_aware::setup_store as type_aware_setup;
277
278pub const COMMON_ANALYSIS_OPTION_FLAGS: &[&str] = &[
285 "root",
286 "config",
287 "no-cache",
288 "threads",
289 "changed-since",
290 "diff-file",
291 "production",
292 "workspace",
293 "changed-workspaces",
294 "explain",
295 "allow-remote-extends",
296];
297
298#[derive(Debug, Clone, Serialize)]
300pub struct ProgrammaticError {
301 pub message: String,
303 pub exit_code: u8,
305 pub code: Option<String>,
307 pub help: Option<String>,
309 pub context: Option<String>,
311}
312
313impl ProgrammaticError {
314 #[must_use]
317 pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
318 Self {
319 message: message.into(),
320 exit_code,
321 code: None,
322 help: None,
323 context: None,
324 }
325 }
326
327 #[must_use]
329 pub fn with_help(mut self, help: impl Into<String>) -> Self {
330 self.help = Some(help.into());
331 self
332 }
333
334 #[must_use]
337 pub fn with_code(mut self, code: impl Into<String>) -> Self {
338 self.code = Some(code.into());
339 self
340 }
341
342 #[must_use]
345 pub fn with_context(mut self, context: impl Into<String>) -> Self {
346 self.context = Some(context.into());
347 self
348 }
349}
350
351impl std::fmt::Display for ProgrammaticError {
352 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
353 write!(f, "{}", self.message)
354 }
355}
356
357impl std::error::Error for ProgrammaticError {}
358
359#[derive(Debug, Clone, Default)]
361pub struct AnalysisOptions {
362 pub root: Option<PathBuf>,
365 pub config_path: Option<PathBuf>,
367 pub allow_remote_extends: bool,
369 pub no_cache: bool,
371 pub threads: Option<usize>,
373 pub diff_file: Option<PathBuf>,
385 pub ambient_diff_file: Option<PathBuf>,
393 pub production: bool,
396 pub production_override: Option<bool>,
399 pub changed_since: Option<String>,
404 pub ambient_changed_since: Option<String>,
412 pub no_package_baselines: bool,
416 pub workspace: Option<Vec<String>>,
418 pub changed_workspaces: Option<String>,
420 pub explain: bool,
422 pub type_aware: TypeAwareOptions,
425 pub cancellation: Option<Arc<AtomicBool>>,
455 pub host: Option<run::HostInputs>,
461}
462
463#[derive(Debug, Clone, Default, PartialEq, Eq)]
465pub struct TypeAwareOptions {
466 pub enabled: Option<bool>,
473 pub projects: Vec<PathBuf>,
476 pub require: fallow_config::TypeAwareRequire,
478}
479
480impl TypeAwareOptions {
481 #[must_use]
483 pub const fn requested(&self) -> bool {
484 matches!(self.enabled, Some(true))
485 }
486}
487
488#[derive(Debug, Clone, Default, PartialEq, Eq)]
493pub struct DeadCodeFilters {
494 pub shared_state: bool,
496 pub unused_files: bool,
498 pub unused_exports: bool,
500 pub unused_deps: bool,
502 pub unused_types: bool,
504 pub private_type_leaks: bool,
506 pub deprecated_exports_in_use: bool,
508 pub unused_enum_members: bool,
510 pub unused_class_members: bool,
512 pub unused_namespace_members: bool,
514 pub unused_protected_class_members: bool,
516 pub namespace_escapes: bool,
519 pub test_only_exports: bool,
521 pub unused_store_members: bool,
523 pub unprovided_injects: bool,
525 pub unrendered_components: bool,
527 pub unused_component_props: bool,
529 pub absent_component_props: bool,
531 pub constant_parameters: bool,
533 pub unused_component_emits: bool,
535 pub unused_component_inputs: bool,
537 pub unused_component_outputs: bool,
539 pub unused_svelte_events: bool,
541 pub unused_effect_layers: bool,
543 pub unused_tagged_errors: bool,
545 pub unproduced_catch_tags: bool,
547 pub unused_server_actions: bool,
549 pub unused_load_data_keys: bool,
551 pub unresolved_imports: bool,
553 pub unlisted_deps: bool,
555 pub unlisted_binaries: bool,
557 pub duplicate_exports: bool,
559 pub duplicate_export_aliases: bool,
561 pub circular_deps: bool,
563 pub re_export_cycles: bool,
565 pub package_cycles: bool,
567 pub boundary_violations: bool,
569 pub policy_violations: bool,
571 pub stale_suppressions: bool,
573 pub unused_catalog_entries: bool,
575 pub empty_catalog_groups: bool,
577 pub unresolved_catalog_references: bool,
579 pub unused_dependency_overrides: bool,
581 pub misconfigured_dependency_overrides: bool,
583}
584
585impl DeadCodeFilters {
586 pub(crate) fn reports_dependency_findings(&self) -> bool {
590 !self.any_active() || self.unused_deps || self.unlisted_deps
591 }
592
593 fn any_active(&self) -> bool {
594 self.shared_state
595 || self.unused_files
596 || self.unused_exports
597 || self.unused_deps
598 || self.unused_types
599 || self.private_type_leaks
600 || self.deprecated_exports_in_use
601 || self.unused_enum_members
602 || self.unused_class_members
603 || self.unused_namespace_members
604 || self.unused_protected_class_members
605 || self.namespace_escapes
606 || self.test_only_exports
607 || self.unused_store_members
608 || self.unprovided_injects
609 || self.unrendered_components
610 || self.unused_component_props
611 || self.absent_component_props
612 || self.constant_parameters
613 || self.unused_component_emits
614 || self.unused_component_inputs
615 || self.unused_component_outputs
616 || self.unused_svelte_events
617 || self.unused_effect_layers
618 || self.unused_tagged_errors
619 || self.unproduced_catch_tags
620 || self.unused_server_actions
621 || self.unused_load_data_keys
622 || self.unresolved_imports
623 || self.unlisted_deps
624 || self.unlisted_binaries
625 || self.duplicate_exports
626 || self.duplicate_export_aliases
627 || self.circular_deps
628 || self.re_export_cycles
629 || self.package_cycles
630 || self.boundary_violations
631 || self.policy_violations
632 || self.stale_suppressions
633 || self.unused_catalog_entries
634 || self.empty_catalog_groups
635 || self.unresolved_catalog_references
636 || self.unused_dependency_overrides
637 || self.misconfigured_dependency_overrides
638 }
639
640 pub fn enable_registry_selector(&mut self, selector: &str) -> bool {
646 let Some(flag) = fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS
647 .iter()
648 .find_map(|&(name, flag)| (name == selector).then_some(flag))
649 else {
650 return false;
651 };
652 self.enable_cli_filter_flag(flag);
653 true
654 }
655
656 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
658 fallow_engine::requested_rule_off::explicit_filter_flags(|flag| {
659 let mut enabled = self.clone();
660 enabled.enable_cli_filter_flag(flag);
661 enabled == *self
662 })
663 }
664
665 fn enable_cli_filter_flag(&mut self, flag: &str) {
666 match flag {
667 "--unused-files" => self.unused_files = true,
668 "--unused-exports" => self.unused_exports = true,
669 "--unused-types" => self.unused_types = true,
670 "--private-type-leaks" => self.private_type_leaks = true,
671 "--deprecated-exports-in-use" => self.deprecated_exports_in_use = true,
672 "--unused-deps" => self.unused_deps = true,
673 "--unused-enum-members" => self.unused_enum_members = true,
674 "--unused-class-members" => self.unused_class_members = true,
675 "--unused-namespace-members" => self.unused_namespace_members = true,
676 "--unused-protected-class-members" => self.unused_protected_class_members = true,
677 "--namespace-escapes" => self.namespace_escapes = true,
678 "--test-only-exports" => self.test_only_exports = true,
679 "--unused-store-members" => self.unused_store_members = true,
680 "--unprovided-injects" => self.unprovided_injects = true,
681 "--unrendered-components" => self.unrendered_components = true,
682 "--unused-component-props" => self.unused_component_props = true,
683 "--absent-component-props" => self.absent_component_props = true,
684 "--constant-parameters" => self.constant_parameters = true,
685 "--unused-component-emits" => self.unused_component_emits = true,
686 "--unused-component-inputs" => self.unused_component_inputs = true,
687 "--unused-component-outputs" => self.unused_component_outputs = true,
688 "--unused-svelte-events" => self.unused_svelte_events = true,
689 "--unused-effect-layers" => self.unused_effect_layers = true,
690 "--unused-tagged-errors" => self.unused_tagged_errors = true,
691 "--unproduced-catch-tags" => self.unproduced_catch_tags = true,
692 "--unused-server-actions" => self.unused_server_actions = true,
693 "--unused-load-data-keys" => self.unused_load_data_keys = true,
694 "--unresolved-imports" => self.unresolved_imports = true,
695 "--unlisted-deps" => self.unlisted_deps = true,
696 "--unlisted-binaries" => self.unlisted_binaries = true,
697 "--duplicate-exports" => self.duplicate_exports = true,
698 "--duplicate-export-aliases" => self.duplicate_export_aliases = true,
699 "--circular-deps" => self.circular_deps = true,
700 "--re-export-cycles" => self.re_export_cycles = true,
701 "--package-cycles" => self.package_cycles = true,
702 "--boundary-violations" => self.boundary_violations = true,
703 "--policy-violations" => self.policy_violations = true,
704 "--stale-suppressions" => self.stale_suppressions = true,
705 "--unused-catalog-entries" => self.unused_catalog_entries = true,
706 "--empty-catalog-groups" => self.empty_catalog_groups = true,
707 "--unresolved-catalog-references" => self.unresolved_catalog_references = true,
708 "--unused-dependency-overrides" => self.unused_dependency_overrides = true,
709 "--misconfigured-dependency-overrides" => {
710 self.misconfigured_dependency_overrides = true;
711 }
712 _ => unreachable!("registry emitted unsupported dead-code filter flag: {flag}"),
713 }
714 }
715}
716
717#[derive(Debug, Clone, Default)]
719pub struct DeadCodeOptions {
720 pub analysis: AnalysisOptions,
722 pub filters: DeadCodeFilters,
724 pub files: Vec<PathBuf>,
726 pub include_entry_exports: bool,
728 pub show_cascade: bool,
730 pub finding_ids: Vec<String>,
735}
736
737#[derive(Debug, Clone, Default)]
743pub struct ArchitectureOptions {
744 pub shared_state: bool,
746 pub analysis: AnalysisOptions,
748 pub files: Vec<PathBuf>,
750 pub cycles: bool,
753 pub boundaries: bool,
755 pub policy: bool,
757}
758
759impl ArchitectureOptions {
760 #[must_use]
762 pub fn dead_code_filters(&self) -> DeadCodeFilters {
763 let all = !(self.cycles || self.boundaries || self.policy || self.shared_state);
764 DeadCodeFilters {
765 shared_state: self.shared_state,
766 circular_deps: self.cycles || all,
767 re_export_cycles: self.cycles || all,
768 package_cycles: self.cycles || all,
769 boundary_violations: self.boundaries || all,
770 policy_violations: self.policy || all,
771 ..DeadCodeFilters::default()
772 }
773 }
774
775 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
778 fallow_engine::requested_rule_off::architecture_requested_flags(
779 self.cycles,
780 self.boundaries,
781 self.policy,
782 )
783 }
784
785 #[must_use]
787 pub fn dead_code_options(&self) -> DeadCodeOptions {
788 DeadCodeOptions {
789 analysis: self.analysis.clone(),
790 filters: self.dead_code_filters(),
791 files: self.files.clone(),
792 include_entry_exports: false,
793 show_cascade: false,
794 finding_ids: Vec::new(),
795 }
796 }
797}
798
799#[derive(Debug, Clone, Default)]
801pub struct AuditOptions {
802 pub analysis: AnalysisOptions,
804 pub base: Option<String>,
807 pub production: bool,
809 pub production_dead_code: Option<bool>,
811 pub production_health: Option<bool>,
813 pub production_dupes: Option<bool>,
816 pub dead_code: Option<bool>,
820 pub health: Option<bool>,
823 pub duplication: Option<bool>,
826 pub css: Option<bool>,
829 pub css_deep: Option<bool>,
832 pub gate: Option<fallow_config::AuditGate>,
835 pub worsened: Option<fallow_config::AuditWorsened>,
838 pub max_crap: Option<f64>,
840 pub coverage: Option<PathBuf>,
842 pub coverage_root: Option<PathBuf>,
844 pub include_entry_exports: bool,
846 pub show_cascade: bool,
848 pub runtime_coverage: Option<PathBuf>,
850 pub min_invocations_hot: u64,
852}
853
854#[derive(Debug, Clone)]
856pub struct CombinedOptions {
857 pub analysis: AnalysisOptions,
859 pub production_dead_code: Option<bool>,
863 pub production_health: Option<bool>,
865 pub production_dupes: Option<bool>,
868 pub dead_code: bool,
870 pub duplication: bool,
872 pub health: bool,
874 pub include_entry_exports: bool,
876 pub show_cascade: bool,
878 pub duplication_options: DuplicationOptions,
880 pub health_options: ComplexityOptions,
882}
883
884impl Default for CombinedOptions {
885 fn default() -> Self {
886 Self {
887 analysis: AnalysisOptions::default(),
888 production_dead_code: None,
889 production_health: None,
890 production_dupes: None,
891 dead_code: true,
892 duplication: true,
893 health: true,
894 include_entry_exports: false,
895 show_cascade: false,
896 duplication_options: DuplicationOptions::default(),
897 health_options: ComplexityOptions::default(),
898 }
899 }
900}
901
902#[derive(Debug, Clone, Default)]
904pub struct DecisionSurfaceOptions {
905 pub analysis: AnalysisOptions,
907 pub base: Option<String>,
910 pub max_decisions: Option<usize>,
912}
913
914#[derive(Debug, Clone, Default)]
916pub struct FeatureFlagsOptions {
917 pub analysis: AnalysisOptions,
919 pub top: Option<usize>,
922 pub retirement: Option<FeatureFlagsRetirementOptions>,
924}
925
926#[derive(Debug, Clone, Default)]
929pub struct FeatureFlagsRetirementOptions {
930 pub flag_age: fallow_types::flag_retirement::FlagAgeMode,
932 pub flag_state: Option<std::path::PathBuf>,
934 pub reasons: Vec<fallow_types::flag_retirement::RetirementReason>,
936 pub sort: fallow_engine::flag_retirement::RetirementSort,
938 pub min_age_days: Option<u64>,
940 pub max_flag_age: Option<u64>,
942}
943
944#[derive(Debug, Clone, Copy, Default)]
946pub enum DuplicationMode {
947 Strict,
950 #[default]
952 Mild,
953 Weak,
955 Semantic,
958}
959
960#[derive(Debug, Clone, Default)]
962pub struct DuplicationOptions {
963 pub analysis: AnalysisOptions,
965 pub mode: Option<DuplicationMode>,
967 pub near: Option<bool>,
970 pub min_tokens: Option<usize>,
972 pub min_lines: Option<usize>,
974 pub min_occurrences: Option<usize>,
977 pub threshold: Option<f64>,
980 pub skip_local: Option<bool>,
983 pub ignore_symlinks: Option<bool>,
986 pub cross_language: Option<bool>,
988 pub ignore_imports: Option<bool>,
991 pub top: Option<usize>,
993 pub include_fragments: Option<bool>,
997}
998
999#[derive(Debug, Clone, Default)]
1001pub struct SimilarCodeOptions {
1002 pub analysis: AnalysisOptions,
1004 pub threshold: Option<f64>,
1006 pub min_lines: Option<usize>,
1009 pub top: Option<usize>,
1011 pub files: Vec<PathBuf>,
1015 #[doc(hidden)]
1020 pub adapter_provider_path: Option<PathBuf>,
1021}
1022
1023#[derive(Debug, Clone)]
1025pub struct SimilarCodeInspectOptions {
1026 pub analysis: AnalysisOptions,
1029 pub snapshot: fallow_output::SimilarCodeCandidateSnapshot,
1031}
1032
1033#[derive(Debug, Clone, Default)]
1035pub struct TraceExportOptions {
1036 pub analysis: AnalysisOptions,
1038 pub file: String,
1040 pub export_name: String,
1042}
1043
1044#[derive(Debug, Clone, Default)]
1046pub struct TraceFileOptions {
1047 pub analysis: AnalysisOptions,
1049 pub file: String,
1051}
1052
1053#[derive(Debug, Clone, Default)]
1055pub struct TraceImportPathOptions {
1056 pub analysis: AnalysisOptions,
1058 pub from: String,
1060 pub to: String,
1062 pub eager_only: bool,
1065}
1066
1067#[derive(Debug, Clone, Default)]
1069pub struct TraceErrorOptions {
1070 pub analysis: AnalysisOptions,
1072 pub trace: String,
1074 pub source: String,
1076}
1077
1078#[derive(Debug, Clone, Default)]
1080pub struct TraceDependencyOptions {
1081 pub analysis: AnalysisOptions,
1083 pub package_name: String,
1085 pub usage: Option<DependencyUsageQuery>,
1088}
1089
1090#[derive(Debug, Clone, PartialEq, Eq)]
1092pub enum TraceCloneTarget {
1093 Location {
1095 file: String,
1097 line: usize,
1099 },
1100 Fingerprint(String),
1102}
1103
1104#[derive(Debug, Clone)]
1106pub struct TraceCloneOptions {
1107 pub duplication: DuplicationOptions,
1109 pub target: TraceCloneTarget,
1111}
1112
1113#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1115pub enum ComplexitySort {
1116 #[default]
1118 Cyclomatic,
1119 Cognitive,
1121 Lines,
1123 Severity,
1125}
1126
1127#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1129pub enum OwnershipEmailMode {
1130 Raw,
1132 #[default]
1134 Handle,
1135 Anonymized,
1137 Hash,
1139}
1140
1141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1143pub enum TargetEffort {
1144 Low,
1146 Medium,
1148 High,
1150}
1151
1152#[derive(Debug, Clone, Default)]
1154pub struct ComplexityOptions {
1155 pub analysis: AnalysisOptions,
1157 pub max_cyclomatic: Option<u16>,
1159 pub max_cognitive: Option<u16>,
1161 pub max_crap: Option<f64>,
1163 pub max_file_lines: Option<u32>,
1166 pub top: Option<usize>,
1168 pub sort: ComplexitySort,
1170 pub complexity_breakdown: bool,
1172 pub complexity: bool,
1174 pub file_scores: bool,
1176 pub coverage_gaps: bool,
1178 pub config_activates_coverage_gaps: bool,
1183 pub hotspots: bool,
1185 pub ownership: bool,
1187 pub ownership_emails: Option<OwnershipEmailMode>,
1189 pub targets: bool,
1191 pub css: bool,
1193 pub css_deep: bool,
1195 pub effort: Option<TargetEffort>,
1198 pub score: bool,
1200 pub since: Option<String>,
1202 pub min_commits: Option<u32>,
1204 pub coverage: Option<PathBuf>,
1206 pub coverage_root: Option<PathBuf>,
1208 pub coverage_relocated: bool,
1213}
1214
1215#[derive(Debug, Clone, Copy, Default, PartialEq)]
1217pub struct ComplexityThresholdOverrides {
1218 pub max_cyclomatic: Option<u16>,
1220 pub max_cognitive: Option<u16>,
1222 pub max_crap: Option<f64>,
1224 pub max_file_lines: Option<u32>,
1226}
1227
1228#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1230pub struct ComplexityCoverageInputs<'a> {
1231 pub coverage: Option<&'a Path>,
1233 pub coverage_root: Option<&'a Path>,
1235 pub coverage_relocated: bool,
1238}
1239
1240#[derive(Debug, Clone)]
1242pub struct HealthSectionOptions {
1243 pub output: fallow_types::output_format::OutputFormat,
1245 pub complexity: bool,
1247 pub file_scores: bool,
1249 pub coverage_gaps: bool,
1251 pub hotspots: bool,
1253 pub targets: bool,
1255 pub css: bool,
1257 pub score: bool,
1259 pub score_gate: bool,
1261 pub snapshot_requested: bool,
1263 pub trend: bool,
1265}
1266
1267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1269pub struct DerivedHealthSections {
1270 pub any_section: bool,
1272 pub complexity: bool,
1274 pub file_scores: bool,
1276 pub coverage_gaps: bool,
1278 pub hotspots: bool,
1280 pub targets: bool,
1282 pub css: bool,
1284 pub score: bool,
1286 pub force_full: bool,
1288 pub score_only_output: bool,
1290}
1291
1292#[derive(Debug, Clone)]
1294pub struct ComplexitySectionOptions {
1295 pub complexity: bool,
1297 pub file_scores: bool,
1299 pub coverage_gaps: bool,
1301 pub hotspots: bool,
1303 pub ownership: bool,
1305 pub targets: bool,
1307 pub css: bool,
1309 pub score: bool,
1311}
1312
1313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1315pub struct DerivedComplexityOptions {
1316 pub any_section: bool,
1318 pub complexity: bool,
1320 pub file_scores: bool,
1322 pub coverage_gaps: bool,
1324 pub hotspots: bool,
1326 pub ownership: bool,
1328 pub targets: bool,
1330 pub force_full: bool,
1332 pub score_only_output: bool,
1334 pub score: bool,
1336}
1337
1338#[derive(Debug, Clone, PartialEq)]
1340pub struct ComplexityRunOptions<'a> {
1341 pub thresholds: ComplexityThresholdOverrides,
1343 pub top: Option<usize>,
1345 pub sort: ComplexitySort,
1347 pub complexity_breakdown: bool,
1349 pub sections: DerivedComplexityOptions,
1351 pub ownership_emails: Option<OwnershipEmailMode>,
1353 pub effort: Option<TargetEffort>,
1355 pub css: bool,
1357 pub css_deep: bool,
1359 pub since: Option<&'a str>,
1361 pub min_commits: Option<u32>,
1363 pub coverage_inputs: ComplexityCoverageInputs<'a>,
1365}
1366
1367pub fn configure_global_analysis_pool(threads: usize) -> bool {
1376 fallow_engine::thread_pool::worker_pool_builder(threads)
1377 .build_global()
1378 .is_ok()
1379}
1380
1381#[must_use]
1383pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
1384 let score = options.score
1385 || options.score_gate
1386 || options.trend
1387 || matches!(
1388 options.output,
1389 fallow_types::output_format::OutputFormat::Badge
1390 );
1391 let any_section = options.complexity
1392 || options.file_scores
1393 || options.coverage_gaps
1394 || options.hotspots
1395 || options.targets
1396 || score;
1397 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
1398 let force_full = options.snapshot_requested || effective_score;
1399
1400 DerivedHealthSections {
1401 any_section,
1402 complexity: if any_section {
1403 options.complexity
1404 } else {
1405 true
1406 },
1407 file_scores: if any_section {
1408 options.file_scores
1409 } else {
1410 true
1411 } || force_full,
1412 coverage_gaps: if any_section {
1413 options.coverage_gaps
1414 } else {
1415 false
1416 },
1417 hotspots: if any_section { options.hotspots } else { true }
1418 || options.snapshot_requested
1419 || options.trend,
1420 targets: if any_section { options.targets } else { true },
1421 css: options.css,
1422 score: effective_score,
1423 force_full,
1424 score_only_output: is_health_score_only_output(options, score),
1425 }
1426}
1427
1428#[must_use]
1430pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
1431 let requested_hotspots = options.hotspots || options.ownership;
1432 let sections = derive_health_sections(&HealthSectionOptions {
1433 output: fallow_types::output_format::OutputFormat::Human,
1434 complexity: options.complexity,
1435 file_scores: options.file_scores,
1436 coverage_gaps: options.coverage_gaps,
1437 hotspots: requested_hotspots,
1438 targets: options.targets,
1439 css: options.css,
1440 score: options.score,
1441 score_gate: false,
1442 snapshot_requested: false,
1443 trend: false,
1444 });
1445
1446 DerivedComplexityOptions {
1447 any_section: sections.any_section,
1448 complexity: sections.complexity,
1449 file_scores: sections.file_scores,
1450 coverage_gaps: sections.coverage_gaps,
1451 hotspots: sections.hotspots,
1452 ownership: options.ownership && sections.hotspots,
1453 targets: sections.targets,
1454 force_full: sections.force_full,
1455 score_only_output: sections.score_only_output,
1456 score: sections.score,
1457 }
1458}
1459
1460#[must_use]
1462pub fn derive_complexity_options(options: &ComplexityOptions) -> DerivedComplexityOptions {
1463 derive_complexity_sections(&complexity_section_options(options))
1464}
1465
1466#[must_use]
1468pub fn derive_complexity_run_options(options: &ComplexityOptions) -> ComplexityRunOptions<'_> {
1469 ComplexityRunOptions {
1470 thresholds: ComplexityThresholdOverrides {
1471 max_cyclomatic: options.max_cyclomatic,
1472 max_cognitive: options.max_cognitive,
1473 max_crap: options.max_crap,
1474 max_file_lines: options.max_file_lines,
1475 },
1476 top: options.top,
1477 sort: options.sort,
1478 complexity_breakdown: options.complexity_breakdown,
1479 sections: derive_complexity_options(options),
1480 ownership_emails: options.ownership_emails,
1481 effort: options.effort,
1482 css: options.css,
1483 css_deep: options.css_deep,
1484 since: options.since.as_deref(),
1485 min_commits: options.min_commits,
1486 coverage_inputs: ComplexityCoverageInputs {
1487 coverage: options.coverage.as_deref(),
1488 coverage_root: options.coverage_root.as_deref(),
1489 coverage_relocated: options.coverage_relocated,
1490 },
1491 }
1492}
1493
1494pub fn validate_complexity_options(options: &ComplexityOptions) -> Result<(), ProgrammaticError> {
1517 if let Some(path) = &options.coverage {
1518 let resolved = fallow_engine::health::scoring::resolve_relative_to_root(
1519 path,
1520 options.analysis.root.as_deref(),
1521 );
1522 if !resolved.exists() {
1523 return Err(ProgrammaticError::new(
1524 format!("coverage path does not exist: {}", resolved.display()),
1525 2,
1526 )
1527 .with_code("FALLOW_INVALID_COVERAGE_PATH")
1528 .with_context("health.coverage"));
1529 }
1530 }
1531 if let Err(message) =
1532 fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
1533 {
1534 return Err(ProgrammaticError::new(message, 2)
1535 .with_code("FALLOW_INVALID_COVERAGE_ROOT")
1536 .with_context("health.coverage_root"));
1537 }
1538
1539 Ok(())
1540}
1541
1542fn complexity_section_options(options: &ComplexityOptions) -> ComplexitySectionOptions {
1543 let ownership = options.ownership || options.ownership_emails.is_some();
1544 let requested_targets = options.targets || options.effort.is_some();
1545 ComplexitySectionOptions {
1546 complexity: options.complexity,
1547 file_scores: options.file_scores,
1548 coverage_gaps: options.coverage_gaps,
1549 hotspots: options.hotspots,
1550 ownership,
1551 targets: requested_targets,
1552 css: options.css,
1553 score: options.score,
1554 }
1555}
1556
1557fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
1558 score
1559 && !options.complexity
1560 && !options.file_scores
1561 && !options.coverage_gaps
1562 && !options.hotspots
1563 && !options.targets
1564 && !options.trend
1565}
1566
1567const fn thresholds_to_engine(
1568 thresholds: ComplexityThresholdOverrides,
1569) -> fallow_engine::health::HealthThresholdOverrides {
1570 fallow_engine::health::HealthThresholdOverrides {
1571 max_cyclomatic: thresholds.max_cyclomatic,
1572 max_cognitive: thresholds.max_cognitive,
1573 max_crap: thresholds.max_crap,
1574 max_file_lines: thresholds.max_file_lines,
1575 }
1576}
1577
1578const fn complexity_sort_to_engine(sort: ComplexitySort) -> fallow_engine::health::HealthSort {
1579 match sort {
1580 ComplexitySort::Severity => fallow_engine::health::HealthSort::Severity,
1581 ComplexitySort::Cyclomatic => fallow_engine::health::HealthSort::Cyclomatic,
1582 ComplexitySort::Cognitive => fallow_engine::health::HealthSort::Cognitive,
1583 ComplexitySort::Lines => fallow_engine::health::HealthSort::Lines,
1584 }
1585}
1586
1587const fn coverage_inputs_to_engine(
1588 coverage_inputs: ComplexityCoverageInputs<'_>,
1589) -> fallow_engine::health::HealthCoverageInputs<'_> {
1590 fallow_engine::health::HealthCoverageInputs {
1591 coverage: coverage_inputs.coverage,
1592 coverage_root: coverage_inputs.coverage_root,
1593 coverage_relocated: coverage_inputs.coverage_relocated,
1594 }
1595}
1596
1597const fn ownership_email_mode_to_config(mode: OwnershipEmailMode) -> EmailMode {
1598 match mode {
1599 OwnershipEmailMode::Raw => EmailMode::Raw,
1600 OwnershipEmailMode::Handle => EmailMode::Handle,
1601 OwnershipEmailMode::Anonymized => EmailMode::Anonymized,
1602 OwnershipEmailMode::Hash => EmailMode::Hash,
1603 }
1604}
1605
1606const fn target_effort_to_output(effort: TargetEffort) -> EffortEstimate {
1607 match effort {
1608 TargetEffort::Low => EffortEstimate::Low,
1609 TargetEffort::Medium => EffortEstimate::Medium,
1610 TargetEffort::High => EffortEstimate::High,
1611 }
1612}
1613
1614#[cfg(test)]
1615mod tests {
1616 use super::*;
1617
1618 #[test]
1619 fn duplication_defaults_match_cli_contract() {
1620 let options = DuplicationOptions::default();
1621 assert!(options.mode.is_none());
1622 assert!(options.min_tokens.is_none());
1623 assert!(options.min_lines.is_none());
1624 assert!(options.min_occurrences.is_none());
1625 }
1626
1627 #[test]
1628 fn programmatic_error_builder_keeps_optional_fields() {
1629 let error = ProgrammaticError::new("boom", 2)
1630 .with_code("FALLOW_TEST")
1631 .with_help("Try again")
1632 .with_context("analysis.root");
1633
1634 assert_eq!(error.message, "boom");
1635 assert_eq!(error.exit_code, 2);
1636 assert_eq!(error.code.as_deref(), Some("FALLOW_TEST"));
1637 assert_eq!(error.help.as_deref(), Some("Try again"));
1638 assert_eq!(error.context.as_deref(), Some("analysis.root"));
1639 }
1640
1641 #[test]
1642 fn dead_code_filters_accept_shared_registry_selectors() {
1643 for (selector, _) in fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS.iter() {
1644 let mut filters = DeadCodeFilters::default();
1645 assert!(
1646 filters.enable_registry_selector(selector),
1647 "{selector} should be accepted"
1648 );
1649 }
1650
1651 let mut filters = DeadCodeFilters::default();
1652 assert!(filters.enable_registry_selector("unused-files"));
1653 assert!(filters.unused_files);
1654 assert!(filters.enable_registry_selector("boundary-violations"));
1655 assert!(filters.boundary_violations);
1656 assert!(!filters.enable_registry_selector("not-a-real-selector"));
1657 }
1658
1659 #[test]
1660 fn default_complexity_options_match_programmatic_health_defaults() {
1661 let derived = derive_complexity_options(&ComplexityOptions::default());
1662
1663 assert!(!derived.any_section);
1664 assert!(derived.complexity);
1665 assert!(derived.file_scores);
1666 assert!(!derived.coverage_gaps);
1667 assert!(derived.hotspots);
1668 assert!(!derived.ownership);
1669 assert!(derived.targets);
1670 assert!(derived.force_full);
1671 assert!(!derived.score_only_output);
1672 assert!(derived.score);
1673 }
1674
1675 #[test]
1676 fn score_only_complexity_options_request_score_only_output() {
1677 let derived = derive_complexity_options(&ComplexityOptions {
1678 score: true,
1679 ..ComplexityOptions::default()
1680 });
1681
1682 assert!(derived.any_section);
1683 assert!(!derived.complexity);
1684 assert!(derived.file_scores);
1685 assert!(!derived.hotspots);
1686 assert!(!derived.targets);
1687 assert!(derived.force_full);
1688 assert!(derived.score_only_output);
1689 assert!(derived.score);
1690 }
1691
1692 #[test]
1693 fn ownership_implies_hotspots_when_requested() {
1694 let derived = derive_complexity_options(&ComplexityOptions {
1695 ownership: true,
1696 ..ComplexityOptions::default()
1697 });
1698
1699 assert!(derived.any_section);
1700 assert!(derived.hotspots);
1701 assert!(derived.ownership);
1702 assert!(!derived.targets);
1703 }
1704
1705 #[test]
1706 fn complexity_run_options_normalize_public_api_options() {
1707 let options = ComplexityOptions {
1708 max_cyclomatic: Some(42),
1709 max_cognitive: Some(21),
1710 max_crap: Some(18.5),
1711 top: Some(7),
1712 sort: ComplexitySort::Severity,
1713 complexity_breakdown: true,
1714 ownership_emails: Some(OwnershipEmailMode::Hash),
1715 effort: Some(TargetEffort::High),
1716 coverage: Some(PathBuf::from("coverage/coverage-final.json")),
1717 coverage_root: Some(PathBuf::from("/ci/workspace")),
1718 since: Some("30d".to_string()),
1719 min_commits: Some(4),
1720 ..ComplexityOptions::default()
1721 };
1722
1723 let run = derive_complexity_run_options(&options);
1724
1725 assert_eq!(run.thresholds.max_cyclomatic, Some(42));
1726 assert_eq!(run.thresholds.max_cognitive, Some(21));
1727 assert_eq!(run.thresholds.max_crap, Some(18.5));
1728 assert_eq!(run.top, Some(7));
1729 assert!(matches!(run.sort, ComplexitySort::Severity));
1730 assert!(run.complexity_breakdown);
1731 assert!(run.sections.hotspots);
1732 assert!(run.sections.ownership);
1733 assert!(run.sections.targets);
1734 assert!(matches!(
1735 run.ownership_emails,
1736 Some(OwnershipEmailMode::Hash)
1737 ));
1738 assert!(matches!(run.effort, Some(TargetEffort::High)));
1739 assert_eq!(run.since, Some("30d"));
1740 assert_eq!(run.min_commits, Some(4));
1741 assert_eq!(run.coverage_inputs.coverage, options.coverage.as_deref());
1742 assert_eq!(
1743 run.coverage_inputs.coverage_root,
1744 options.coverage_root.as_deref()
1745 );
1746 }
1747
1748 #[test]
1749 fn complexity_options_validation_accepts_existing_coverage_path_and_absolute_root() {
1750 let dir = tempfile::tempdir().expect("tempdir");
1751 let coverage = dir.path().join("coverage-final.json");
1752 std::fs::write(&coverage, "{}").expect("coverage fixture");
1753
1754 let result = validate_complexity_options(&ComplexityOptions {
1755 coverage: Some(coverage),
1756 coverage_root: Some(PathBuf::from("/ci/workspace")),
1757 ..ComplexityOptions::default()
1758 });
1759
1760 assert!(result.is_ok());
1761 }
1762
1763 #[test]
1764 fn complexity_options_validation_keeps_missing_coverage_error_contract() {
1765 let err = validate_complexity_options(&ComplexityOptions {
1766 coverage: Some(PathBuf::from("/missing/coverage-final.json")),
1767 ..ComplexityOptions::default()
1768 })
1769 .expect_err("missing coverage path should fail");
1770
1771 assert_eq!(err.exit_code, 2);
1772 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1773 assert_eq!(err.context.as_deref(), Some("health.coverage"));
1774 }
1775
1776 #[test]
1777 fn complexity_options_validation_keeps_relative_coverage_root_error_contract() {
1778 let err = validate_complexity_options(&ComplexityOptions {
1779 coverage_root: Some(PathBuf::from("coverage")),
1780 ..ComplexityOptions::default()
1781 })
1782 .expect_err("relative coverage root should fail");
1783
1784 assert_eq!(err.exit_code, 2);
1785 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_ROOT"));
1786 assert_eq!(err.context.as_deref(), Some("health.coverage_root"));
1787 }
1788
1789 #[test]
1793 fn complexity_options_validation_resolves_relative_coverage_against_root() {
1794 let dir = tempfile::tempdir().expect("tempdir");
1795 std::fs::create_dir_all(dir.path().join("artifacts")).expect("artifacts dir");
1796 std::fs::write(dir.path().join("artifacts/coverage-final.json"), "{}")
1797 .expect("coverage fixture");
1798 let relative = PathBuf::from("artifacts/coverage-final.json");
1799 assert!(
1800 !relative.exists(),
1801 "the fixture must not also exist under the test cwd"
1802 );
1803
1804 let result = validate_complexity_options(&ComplexityOptions {
1805 analysis: AnalysisOptions {
1806 root: Some(dir.path().to_path_buf()),
1807 ..AnalysisOptions::default()
1808 },
1809 coverage: Some(relative.clone()),
1810 ..ComplexityOptions::default()
1811 });
1812 assert!(result.is_ok(), "{result:?}");
1813
1814 let err = validate_complexity_options(&ComplexityOptions {
1815 analysis: AnalysisOptions {
1816 root: Some(dir.path().join("elsewhere")),
1817 ..AnalysisOptions::default()
1818 },
1819 coverage: Some(relative),
1820 ..ComplexityOptions::default()
1821 })
1822 .expect_err("the path does not exist under the other root");
1823 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1824 assert!(
1825 err.message.contains("elsewhere"),
1826 "the message names the resolved path: {}",
1827 err.message
1828 );
1829 }
1830
1831 #[test]
1832 fn default_health_sections_match_full_health_output() {
1833 let derived = derive_health_sections(&HealthSectionOptions {
1834 output: fallow_types::output_format::OutputFormat::Human,
1835 complexity: false,
1836 file_scores: false,
1837 coverage_gaps: false,
1838 hotspots: false,
1839 targets: false,
1840 css: false,
1841 score: false,
1842 score_gate: false,
1843 snapshot_requested: false,
1844 trend: false,
1845 });
1846
1847 assert!(!derived.any_section);
1848 assert!(derived.complexity);
1849 assert!(derived.file_scores);
1850 assert!(!derived.coverage_gaps);
1851 assert!(derived.hotspots);
1852 assert!(derived.targets);
1853 assert!(derived.score);
1854 assert!(derived.force_full);
1855 assert!(!derived.score_only_output);
1856 }
1857
1858 #[test]
1859 fn health_score_gate_requests_score_only_output() {
1860 let derived = derive_health_sections(&HealthSectionOptions {
1861 output: fallow_types::output_format::OutputFormat::Human,
1862 complexity: false,
1863 file_scores: false,
1864 coverage_gaps: false,
1865 hotspots: false,
1866 targets: false,
1867 css: false,
1868 score: false,
1869 score_gate: true,
1870 snapshot_requested: false,
1871 trend: false,
1872 });
1873
1874 assert!(derived.any_section);
1875 assert!(!derived.complexity);
1876 assert!(derived.file_scores);
1877 assert!(!derived.hotspots);
1878 assert!(!derived.targets);
1879 assert!(derived.score);
1880 assert!(derived.force_full);
1881 assert!(derived.score_only_output);
1882 }
1883
1884 #[test]
1885 fn health_snapshot_keeps_full_hidden_inputs_without_section_request() {
1886 let derived = derive_health_sections(&HealthSectionOptions {
1887 output: fallow_types::output_format::OutputFormat::Human,
1888 complexity: false,
1889 file_scores: false,
1890 coverage_gaps: false,
1891 hotspots: false,
1892 targets: false,
1893 css: true,
1894 score: false,
1895 score_gate: false,
1896 snapshot_requested: true,
1897 trend: false,
1898 });
1899
1900 assert!(!derived.any_section);
1901 assert!(derived.css);
1902 assert!(derived.file_scores);
1903 assert!(derived.hotspots);
1904 assert!(derived.score);
1905 assert!(derived.force_full);
1906 }
1907}
1908
1909mod shared_state_explain;