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 review_deltas;
74pub mod routing;
75pub mod run;
76pub mod runtime;
77mod runtime_json;
78mod runtime_output;
79pub mod sarif_output;
80pub mod schemas;
83pub mod security_output;
84pub mod similar_code;
86mod threshold_override_output;
87mod type_aware;
88pub use analysis_context::{ProgrammaticAnalysisContext, resolve_programmatic_analysis_context};
89pub use audit_output::{
90 AuditAttribution, AuditCodeClimateOutputInput, AuditJsonHeaderInput, AuditJsonOutputInput,
91 AuditSarifOutputInput, AuditSummary, AuditVerdict, attach_audit_diff_risk_attribution,
92 attach_audit_duplication_demotion_attribution, attach_audit_styling_attribution,
93 attach_audit_wire_attribution, audit_run_notices, build_audit_codeclimate,
94 build_audit_codeclimate_issues, build_audit_header_json, build_audit_header_map,
95 build_audit_sarif, build_diff_risk_codeclimate, build_review_brief_header,
96 serialize_audit_json,
97};
98pub use combined_output::{
99 CombinedCheckJsonSection, CombinedJsonOutputInput, serialize_combined_dupes_json,
100 serialize_combined_health_json, serialize_combined_json,
101};
102pub use compact_output::{
103 build_compact_lines, build_diff_risk_compact_lines, build_duplication_compact_lines,
104 build_grouped_compact_lines, build_health_compact_lines,
105};
106pub use coverage::{
107 CoverageInputError, CoverageInputSource, CoverageInputs, resolve_coverage_inputs,
108};
109pub use dead_code_codeclimate::build_codeclimate;
110pub use dead_code_sarif::build_sarif;
111pub use doctor::{DoctorOptions, run_doctor, run_doctor_with_cache_dir};
112pub use dupes_output::{
113 AttributedCloneGroup, AttributedCloneGroupFinding, AttributedInstance, CloneDemotionReason,
114 CloneFamilyFinding, CloneGroupFinding, CloneRegionFinding, CloneRegionGrade, CloneRegionSpan,
115 CombinedDupesSection, DupesReportPayload, DuplicationGroup, DuplicationGrouping,
116 build_duplication_codeclimate, set_duplication_audit_attribution,
117};
118pub use editor::{
119 ChangedFilesError, EditorAnalysisOutput, EditorAnalysisResults, EditorAnalysisSession,
120 EditorCloneFamily, EditorCloneFingerprintSet, EditorCloneGroup, EditorCloneInstance,
121 EditorDeadCodeAnalysisOutput, EditorDuplicationReport, EditorDuplicationStats,
122 EditorInlineComplexityExceeded, EditorInlineComplexityFinding, EditorMirroredDirectory,
123 EditorProjectAnalysisOutput, EditorRefactoringKind, EditorRefactoringSuggestion,
124 EditorSessionParseCounts, collect_inline_complexity, editor_duplicates, editor_extract,
125 editor_results, editor_security, editor_suppress, filter_inline_complexity_by_change_scope,
126 filter_inline_complexity_by_changed_files, resolve_git_toplevel,
127 try_get_changed_files_with_toplevel,
128};
129pub use explain::{
130 AUDIT_RULES, CHECK_RULES, DUPES_RULES, FLAGS_RULES, HEALTH_RULES, MUTATION_RULES, RuleDef,
131 RuleGuide, SECURITY_RULES, all_rules, bare_rule_id, coverage_analyze_meta, coverage_setup_meta,
132 explain_issue_type, rule_by_id, rule_by_token, rule_command, rule_config_key, rule_docs_url,
133 rule_guide, rule_has_guide, rule_rationale, rule_severity_key, security_meta,
134 serialize_explain_programmatic_json, unknown_explain_error,
135};
136pub use explain_examples::{ExampleAnchor, ExampleFile, RuleExample, rule_example, rule_examples};
137pub use fallow_config::levenshtein::closest_match;
138pub use fallow_config::{
139 AuditGate, AuditWorsened, HealthConfig, ProductionAnalysis, ProductionEnv, TypeAwareRequire,
140};
141pub use fallow_engine::change_scope::{
144 ChangeScope, ChangeScopeOwner, ChangeScopeRequest, first_package_baselines,
145 package_baseline_statuses,
146};
147#[cfg(any(test, feature = "testing"))]
150pub use fallow_engine::git_fixture;
151pub use fallow_engine::package_baselines::{PackageBaselineError, PackageChangeScope};
153pub use fallow_engine::post_edit;
156pub use fallow_engine::source_edits;
157pub use fallow_engine::thread_pool::{WORKER_STACK_SIZE, register_thread_stack};
164pub use fallow_engine::warm_parse;
170pub use fallow_output::PackageBaselineStatus;
172pub use fallow_output::serialize_similar_code_json_output;
173pub use fallow_types::trace::{
174 CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace, ReExportChain,
175 TracedCloneGroup, TracedExport, TracedReExport,
176};
177pub use fallow_types::trace_usage::{
178 DependencyUsage, DependencyUsageQuery, SitePageRequest, UsageQueryError,
179};
180pub use grouped_output::{
181 ResultGroup, UNOWNED_GROUP_LABEL, build_duplication_grouping_with, group_analysis_results_with,
182 health_signal_header_part, largest_clone_group_owner_with,
183};
184pub use health_codeclimate::build_health_codeclimate;
185pub use health_groups_markdown::build_health_groups_markdown;
186pub use json_output::{
187 CheckJsonExtraOutputs, CheckJsonOutputInput, CheckJsonPayloadInput, DuplicationJsonOutputInput,
188 GroupedCheckJsonOutputInput, GroupedDuplicationJsonOutputInput, serialize_check_json,
189 serialize_check_json_payload, serialize_duplication_json, serialize_grouped_check_json,
190 serialize_grouped_duplication_json,
191};
192pub use list_output::{
193 ListJsonEnvelope, ListJsonOutputInput, build_list_json_output, serialize_list_json_output,
194};
195pub use list_runtime::{
196 BoundaryData, ListBoundariesOptions, ListBoundariesProgrammaticOutput, LogicalGroupInfo,
197 ProjectInfoOptions, ProjectInfoProgrammaticOutput, RuleInfo, ZoneInfo, boundary_data_to_output,
198 compute_boundary_data, run_list_boundaries, run_project_info,
199 serialize_list_boundaries_programmatic_json, serialize_project_info_programmatic_json,
200};
201pub use markdown_output::{
202 ComplexityListing, build_diff_risk_markdown, build_duplication_markdown,
203 build_grouped_markdown, build_health_markdown, build_markdown, build_walkthrough_markdown,
204};
205pub use mutation::{
206 MutationProgress, MutationProgressSink, MutationReplayOptions, MutationRunOptions,
207 MutationRunScope, apply_mutation_verdicts, validate_mutation_verdicts,
208};
209pub use output_contracts::{
210 AuditOutput, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
211 BoundariesListing, CombinedOutput, FallowOutput, ImpactOutput, ListBoundariesOutput,
212 ListEntryPointOutput, ListOutput, ListPluginOutput, ReviewBriefWireOutput, SecurityGate,
213 SecurityOutput, SecurityOutputConfig, SecuritySummaryOutput, SimilarCodeCandidateSnapshot,
214 SimilarCodeOutput, TraceOutput, WorkspacesOutput,
215};
216pub use runtime::TYPE_AWARE_CONFIG_UNSUPPORTED;
217pub use runtime::{
218 AUDIT_CONFIG_BASELINE_UNSUPPORTED, ArchitectureOutput, ArchitectureProgrammaticOutput,
219 AuditProgrammaticKeySnapshot, AuditProgrammaticOutput, BoundaryViolationsOutput,
220 BoundaryViolationsProgrammaticOutput, CircularDependenciesOutput,
221 CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput, DeadCodeOutput,
222 DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput, DuplicationOutput,
223 DuplicationProgrammaticOutput, EngineHealthRunner, FeatureFlagsOutput,
224 FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
225 ProgrammaticHealthAnalysis, ProgrammaticHealthNextStepFacts, ProgrammaticHealthRun,
226 ProgrammaticHealthRunner, TraceClassMemberOutput, TraceCloneBenchmarkResult, TraceCloneOutput,
227 TraceCloneProgrammaticOutput, TraceDependencyOutput, TraceDependencyProgrammaticOutput,
228 TraceErrorOutput, TraceErrorProgrammaticOutput, TraceExportOutput,
229 TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
230 TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
231 benchmark_trace_clone_compact_json, benchmark_trace_graph_family_compact_json,
232 inspect_similar_code, load_health_config, parse_similar_code_candidate_snapshot, plan_mutation,
233 replay_mutation, review_similar_code, run_architecture, run_audit, run_boundary_violations,
234 run_circular_dependencies, run_combined, run_complexity_with_runner, run_dead_code,
235 run_dead_code_with_baseline, run_decision_surface, run_duplication, run_feature_flags,
236 run_health, run_health_with_runner, run_mutation, run_mutation_with_progress, run_similar_code,
237 run_trace_clone, run_trace_dependency, run_trace_error, run_trace_export, run_trace_file,
238 run_trace_import_path, select_similar_code_candidate_snapshot, serialize_health_report_json,
239};
240pub use runtime_json::{
241 serialize_architecture_programmatic_json, serialize_audit_programmatic_json,
242 serialize_boundary_violations_programmatic_json,
243 serialize_circular_dependencies_programmatic_json, serialize_combined_programmatic_json,
244 serialize_dead_code_programmatic_json, serialize_decision_surface_programmatic_json,
245 serialize_duplication_programmatic_json, serialize_feature_flags_programmatic_json,
246 serialize_health_programmatic_json, serialize_trace_clone_programmatic_json,
247 serialize_trace_dependency_programmatic_json, serialize_trace_error_programmatic_json,
248 serialize_trace_export_programmatic_json, serialize_trace_file_programmatic_json,
249 serialize_trace_import_path_programmatic_json,
250};
251pub use sarif_output::{
252 annotate_sarif_results, build_duplication_sarif, build_grouped_duplication_sarif,
253 build_health_sarif,
254};
255pub use security_output::SecurityGateMode;
256pub use type_aware::{
257 DEFAULT_BACKEND_FAMILY as DEFAULT_TYPE_AWARE_BACKEND_FAMILY, SemanticCouplingOutcome,
258 SemanticDeadCodeOutcome, SemanticInspectOutcome, TypeAwareError, TypeAwareFileChanges,
259 TypeAwareOutcome, TypeAwareSession, TypeAwareStatus, discard_unverified_semantic_candidates,
260 inspect_symbol as inspect_type_aware_symbol, merge_type_aware_meta,
261 refine_configured_dead_code_results as refine_type_aware_results_with_config,
262 shutdown_type_aware_sidecars, status as type_aware_status,
263 symbol_impact as run_type_aware_symbol_impact, symbol_impact as type_aware_symbol_impact,
264 terminate_active_type_aware_sidecars, trace_symbol as run_type_aware_symbol_trace,
265 trace_symbol as trace_type_aware_symbol, type_coupling as analyze_type_coupling,
266};
267
268pub use type_aware::setup_store as type_aware_setup;
271
272pub const COMMON_ANALYSIS_OPTION_FLAGS: &[&str] = &[
279 "root",
280 "config",
281 "no-cache",
282 "threads",
283 "changed-since",
284 "diff-file",
285 "production",
286 "workspace",
287 "changed-workspaces",
288 "explain",
289 "allow-remote-extends",
290];
291
292#[derive(Debug, Clone, Serialize)]
294pub struct ProgrammaticError {
295 pub message: String,
297 pub exit_code: u8,
299 pub code: Option<String>,
301 pub help: Option<String>,
303 pub context: Option<String>,
305}
306
307impl ProgrammaticError {
308 #[must_use]
311 pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
312 Self {
313 message: message.into(),
314 exit_code,
315 code: None,
316 help: None,
317 context: None,
318 }
319 }
320
321 #[must_use]
323 pub fn with_help(mut self, help: impl Into<String>) -> Self {
324 self.help = Some(help.into());
325 self
326 }
327
328 #[must_use]
331 pub fn with_code(mut self, code: impl Into<String>) -> Self {
332 self.code = Some(code.into());
333 self
334 }
335
336 #[must_use]
339 pub fn with_context(mut self, context: impl Into<String>) -> Self {
340 self.context = Some(context.into());
341 self
342 }
343}
344
345impl std::fmt::Display for ProgrammaticError {
346 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347 write!(f, "{}", self.message)
348 }
349}
350
351impl std::error::Error for ProgrammaticError {}
352
353#[derive(Debug, Clone, Default)]
355pub struct AnalysisOptions {
356 pub root: Option<PathBuf>,
359 pub config_path: Option<PathBuf>,
361 pub allow_remote_extends: bool,
363 pub no_cache: bool,
365 pub threads: Option<usize>,
367 pub diff_file: Option<PathBuf>,
379 pub ambient_diff_file: Option<PathBuf>,
387 pub production: bool,
390 pub production_override: Option<bool>,
393 pub changed_since: Option<String>,
398 pub ambient_changed_since: Option<String>,
406 pub no_package_baselines: bool,
410 pub workspace: Option<Vec<String>>,
412 pub changed_workspaces: Option<String>,
414 pub explain: bool,
416 pub type_aware: TypeAwareOptions,
419 pub cancellation: Option<Arc<AtomicBool>>,
449 pub host: Option<run::HostInputs>,
455}
456
457#[derive(Debug, Clone, Default, PartialEq, Eq)]
459pub struct TypeAwareOptions {
460 pub enabled: Option<bool>,
467 pub projects: Vec<PathBuf>,
470 pub require: fallow_config::TypeAwareRequire,
472}
473
474impl TypeAwareOptions {
475 #[must_use]
477 pub const fn requested(&self) -> bool {
478 matches!(self.enabled, Some(true))
479 }
480}
481
482#[derive(Debug, Clone, Default, PartialEq, Eq)]
487pub struct DeadCodeFilters {
488 pub shared_state: bool,
490 pub unused_files: bool,
492 pub unused_exports: bool,
494 pub unused_deps: bool,
496 pub unused_types: bool,
498 pub private_type_leaks: bool,
500 pub deprecated_exports_in_use: bool,
502 pub unused_enum_members: bool,
504 pub unused_class_members: bool,
506 pub unused_namespace_members: bool,
508 pub unused_protected_class_members: bool,
510 pub namespace_escapes: bool,
513 pub unused_store_members: bool,
515 pub unprovided_injects: bool,
517 pub unrendered_components: bool,
519 pub unused_component_props: bool,
521 pub absent_component_props: bool,
523 pub constant_parameters: bool,
525 pub unused_component_emits: bool,
527 pub unused_component_inputs: bool,
529 pub unused_component_outputs: bool,
531 pub unused_svelte_events: bool,
533 pub unused_effect_layers: bool,
535 pub unused_tagged_errors: bool,
537 pub unproduced_catch_tags: bool,
539 pub unused_server_actions: bool,
541 pub unused_load_data_keys: bool,
543 pub unresolved_imports: bool,
545 pub unlisted_deps: bool,
547 pub unlisted_binaries: bool,
549 pub duplicate_exports: bool,
551 pub duplicate_export_aliases: bool,
553 pub circular_deps: bool,
555 pub re_export_cycles: bool,
557 pub package_cycles: bool,
559 pub boundary_violations: bool,
561 pub policy_violations: bool,
563 pub stale_suppressions: bool,
565 pub unused_catalog_entries: bool,
567 pub empty_catalog_groups: bool,
569 pub unresolved_catalog_references: bool,
571 pub unused_dependency_overrides: bool,
573 pub misconfigured_dependency_overrides: bool,
575}
576
577impl DeadCodeFilters {
578 pub(crate) fn reports_dependency_findings(&self) -> bool {
582 !self.any_active() || self.unused_deps || self.unlisted_deps
583 }
584
585 fn any_active(&self) -> bool {
586 self.shared_state
587 || self.unused_files
588 || self.unused_exports
589 || self.unused_deps
590 || self.unused_types
591 || self.private_type_leaks
592 || self.deprecated_exports_in_use
593 || self.unused_enum_members
594 || self.unused_class_members
595 || self.unused_namespace_members
596 || self.unused_protected_class_members
597 || self.namespace_escapes
598 || self.unused_store_members
599 || self.unprovided_injects
600 || self.unrendered_components
601 || self.unused_component_props
602 || self.absent_component_props
603 || self.constant_parameters
604 || self.unused_component_emits
605 || self.unused_component_inputs
606 || self.unused_component_outputs
607 || self.unused_svelte_events
608 || self.unused_effect_layers
609 || self.unused_tagged_errors
610 || self.unproduced_catch_tags
611 || self.unused_server_actions
612 || self.unused_load_data_keys
613 || self.unresolved_imports
614 || self.unlisted_deps
615 || self.unlisted_binaries
616 || self.duplicate_exports
617 || self.duplicate_export_aliases
618 || self.circular_deps
619 || self.re_export_cycles
620 || self.package_cycles
621 || self.boundary_violations
622 || self.policy_violations
623 || self.stale_suppressions
624 || self.unused_catalog_entries
625 || self.empty_catalog_groups
626 || self.unresolved_catalog_references
627 || self.unused_dependency_overrides
628 || self.misconfigured_dependency_overrides
629 }
630
631 pub fn enable_registry_selector(&mut self, selector: &str) -> bool {
637 let Some(flag) = fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS
638 .iter()
639 .find_map(|&(name, flag)| (name == selector).then_some(flag))
640 else {
641 return false;
642 };
643 self.enable_cli_filter_flag(flag);
644 true
645 }
646
647 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
649 fallow_engine::requested_rule_off::explicit_filter_flags(|flag| {
650 let mut enabled = self.clone();
651 enabled.enable_cli_filter_flag(flag);
652 enabled == *self
653 })
654 }
655
656 fn enable_cli_filter_flag(&mut self, flag: &str) {
657 match flag {
658 "--unused-files" => self.unused_files = true,
659 "--unused-exports" => self.unused_exports = true,
660 "--unused-types" => self.unused_types = true,
661 "--private-type-leaks" => self.private_type_leaks = true,
662 "--deprecated-exports-in-use" => self.deprecated_exports_in_use = true,
663 "--unused-deps" => self.unused_deps = true,
664 "--unused-enum-members" => self.unused_enum_members = true,
665 "--unused-class-members" => self.unused_class_members = true,
666 "--unused-namespace-members" => self.unused_namespace_members = true,
667 "--unused-protected-class-members" => self.unused_protected_class_members = true,
668 "--namespace-escapes" => self.namespace_escapes = true,
669 "--unused-store-members" => self.unused_store_members = true,
670 "--unprovided-injects" => self.unprovided_injects = true,
671 "--unrendered-components" => self.unrendered_components = true,
672 "--unused-component-props" => self.unused_component_props = true,
673 "--absent-component-props" => self.absent_component_props = true,
674 "--constant-parameters" => self.constant_parameters = true,
675 "--unused-component-emits" => self.unused_component_emits = true,
676 "--unused-component-inputs" => self.unused_component_inputs = true,
677 "--unused-component-outputs" => self.unused_component_outputs = true,
678 "--unused-svelte-events" => self.unused_svelte_events = true,
679 "--unused-effect-layers" => self.unused_effect_layers = true,
680 "--unused-tagged-errors" => self.unused_tagged_errors = true,
681 "--unproduced-catch-tags" => self.unproduced_catch_tags = true,
682 "--unused-server-actions" => self.unused_server_actions = true,
683 "--unused-load-data-keys" => self.unused_load_data_keys = true,
684 "--unresolved-imports" => self.unresolved_imports = true,
685 "--unlisted-deps" => self.unlisted_deps = true,
686 "--unlisted-binaries" => self.unlisted_binaries = true,
687 "--duplicate-exports" => self.duplicate_exports = true,
688 "--duplicate-export-aliases" => self.duplicate_export_aliases = true,
689 "--circular-deps" => self.circular_deps = true,
690 "--re-export-cycles" => self.re_export_cycles = true,
691 "--package-cycles" => self.package_cycles = true,
692 "--boundary-violations" => self.boundary_violations = true,
693 "--policy-violations" => self.policy_violations = true,
694 "--stale-suppressions" => self.stale_suppressions = true,
695 "--unused-catalog-entries" => self.unused_catalog_entries = true,
696 "--empty-catalog-groups" => self.empty_catalog_groups = true,
697 "--unresolved-catalog-references" => self.unresolved_catalog_references = true,
698 "--unused-dependency-overrides" => self.unused_dependency_overrides = true,
699 "--misconfigured-dependency-overrides" => {
700 self.misconfigured_dependency_overrides = true;
701 }
702 _ => unreachable!("registry emitted unsupported dead-code filter flag: {flag}"),
703 }
704 }
705}
706
707#[derive(Debug, Clone, Default)]
709pub struct DeadCodeOptions {
710 pub analysis: AnalysisOptions,
712 pub filters: DeadCodeFilters,
714 pub files: Vec<PathBuf>,
716 pub include_entry_exports: bool,
718 pub show_cascade: bool,
720 pub finding_ids: Vec<String>,
725}
726
727#[derive(Debug, Clone, Default)]
733pub struct ArchitectureOptions {
734 pub shared_state: bool,
736 pub analysis: AnalysisOptions,
738 pub files: Vec<PathBuf>,
740 pub cycles: bool,
743 pub boundaries: bool,
745 pub policy: bool,
747}
748
749impl ArchitectureOptions {
750 #[must_use]
752 pub fn dead_code_filters(&self) -> DeadCodeFilters {
753 let all = !(self.cycles || self.boundaries || self.policy || self.shared_state);
754 DeadCodeFilters {
755 shared_state: self.shared_state,
756 circular_deps: self.cycles || all,
757 re_export_cycles: self.cycles || all,
758 package_cycles: self.cycles || all,
759 boundary_violations: self.boundaries || all,
760 policy_violations: self.policy || all,
761 ..DeadCodeFilters::default()
762 }
763 }
764
765 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
768 fallow_engine::requested_rule_off::architecture_requested_flags(
769 self.cycles,
770 self.boundaries,
771 self.policy,
772 )
773 }
774
775 #[must_use]
777 pub fn dead_code_options(&self) -> DeadCodeOptions {
778 DeadCodeOptions {
779 analysis: self.analysis.clone(),
780 filters: self.dead_code_filters(),
781 files: self.files.clone(),
782 include_entry_exports: false,
783 show_cascade: false,
784 finding_ids: Vec::new(),
785 }
786 }
787}
788
789#[derive(Debug, Clone, Default)]
791pub struct AuditOptions {
792 pub analysis: AnalysisOptions,
794 pub base: Option<String>,
797 pub production: bool,
799 pub production_dead_code: Option<bool>,
801 pub production_health: Option<bool>,
803 pub production_dupes: Option<bool>,
806 pub dead_code: Option<bool>,
810 pub health: Option<bool>,
813 pub duplication: Option<bool>,
816 pub css: Option<bool>,
819 pub css_deep: Option<bool>,
822 pub gate: Option<fallow_config::AuditGate>,
825 pub worsened: Option<fallow_config::AuditWorsened>,
828 pub max_crap: Option<f64>,
830 pub coverage: Option<PathBuf>,
832 pub coverage_root: Option<PathBuf>,
834 pub include_entry_exports: bool,
836 pub show_cascade: bool,
838 pub runtime_coverage: Option<PathBuf>,
840 pub min_invocations_hot: u64,
842}
843
844#[derive(Debug, Clone)]
846pub struct CombinedOptions {
847 pub analysis: AnalysisOptions,
849 pub production_dead_code: Option<bool>,
853 pub production_health: Option<bool>,
855 pub production_dupes: Option<bool>,
858 pub dead_code: bool,
860 pub duplication: bool,
862 pub health: bool,
864 pub include_entry_exports: bool,
866 pub show_cascade: bool,
868 pub duplication_options: DuplicationOptions,
870 pub health_options: ComplexityOptions,
872}
873
874impl Default for CombinedOptions {
875 fn default() -> Self {
876 Self {
877 analysis: AnalysisOptions::default(),
878 production_dead_code: None,
879 production_health: None,
880 production_dupes: None,
881 dead_code: true,
882 duplication: true,
883 health: true,
884 include_entry_exports: false,
885 show_cascade: false,
886 duplication_options: DuplicationOptions::default(),
887 health_options: ComplexityOptions::default(),
888 }
889 }
890}
891
892#[derive(Debug, Clone, Default)]
894pub struct DecisionSurfaceOptions {
895 pub analysis: AnalysisOptions,
897 pub base: Option<String>,
900 pub max_decisions: Option<usize>,
902}
903
904#[derive(Debug, Clone, Default)]
906pub struct FeatureFlagsOptions {
907 pub analysis: AnalysisOptions,
909 pub top: Option<usize>,
912 pub retirement: Option<FeatureFlagsRetirementOptions>,
914}
915
916#[derive(Debug, Clone, Default)]
919pub struct FeatureFlagsRetirementOptions {
920 pub flag_age: fallow_types::flag_retirement::FlagAgeMode,
922 pub flag_state: Option<std::path::PathBuf>,
924 pub reasons: Vec<fallow_types::flag_retirement::RetirementReason>,
926 pub sort: fallow_engine::flag_retirement::RetirementSort,
928 pub min_age_days: Option<u64>,
930 pub max_flag_age: Option<u64>,
932}
933
934#[derive(Debug, Clone, Copy, Default)]
936pub enum DuplicationMode {
937 Strict,
940 #[default]
942 Mild,
943 Weak,
945 Semantic,
948}
949
950#[derive(Debug, Clone, Default)]
952pub struct DuplicationOptions {
953 pub analysis: AnalysisOptions,
955 pub mode: Option<DuplicationMode>,
957 pub near: Option<bool>,
960 pub min_tokens: Option<usize>,
962 pub min_lines: Option<usize>,
964 pub min_occurrences: Option<usize>,
967 pub threshold: Option<f64>,
970 pub skip_local: Option<bool>,
973 pub ignore_symlinks: Option<bool>,
976 pub cross_language: Option<bool>,
978 pub ignore_imports: Option<bool>,
981 pub top: Option<usize>,
983 pub include_fragments: Option<bool>,
987}
988
989#[derive(Debug, Clone, Default)]
991pub struct SimilarCodeOptions {
992 pub analysis: AnalysisOptions,
994 pub threshold: Option<f64>,
996 pub min_lines: Option<usize>,
999 pub top: Option<usize>,
1001 pub files: Vec<PathBuf>,
1005 #[doc(hidden)]
1010 pub adapter_provider_path: Option<PathBuf>,
1011}
1012
1013#[derive(Debug, Clone)]
1015pub struct SimilarCodeInspectOptions {
1016 pub analysis: AnalysisOptions,
1019 pub snapshot: fallow_output::SimilarCodeCandidateSnapshot,
1021}
1022
1023#[derive(Debug, Clone, Default)]
1025pub struct TraceExportOptions {
1026 pub analysis: AnalysisOptions,
1028 pub file: String,
1030 pub export_name: String,
1032}
1033
1034#[derive(Debug, Clone, Default)]
1036pub struct TraceFileOptions {
1037 pub analysis: AnalysisOptions,
1039 pub file: String,
1041}
1042
1043#[derive(Debug, Clone, Default)]
1045pub struct TraceImportPathOptions {
1046 pub analysis: AnalysisOptions,
1048 pub from: String,
1050 pub to: String,
1052 pub eager_only: bool,
1055}
1056
1057#[derive(Debug, Clone, Default)]
1059pub struct TraceErrorOptions {
1060 pub analysis: AnalysisOptions,
1062 pub trace: String,
1064 pub source: String,
1066}
1067
1068#[derive(Debug, Clone, Default)]
1070pub struct TraceDependencyOptions {
1071 pub analysis: AnalysisOptions,
1073 pub package_name: String,
1075 pub usage: Option<DependencyUsageQuery>,
1078}
1079
1080#[derive(Debug, Clone, PartialEq, Eq)]
1082pub enum TraceCloneTarget {
1083 Location {
1085 file: String,
1087 line: usize,
1089 },
1090 Fingerprint(String),
1092}
1093
1094#[derive(Debug, Clone)]
1096pub struct TraceCloneOptions {
1097 pub duplication: DuplicationOptions,
1099 pub target: TraceCloneTarget,
1101}
1102
1103#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1105pub enum ComplexitySort {
1106 #[default]
1108 Cyclomatic,
1109 Cognitive,
1111 Lines,
1113 Severity,
1115}
1116
1117#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1119pub enum OwnershipEmailMode {
1120 Raw,
1122 #[default]
1124 Handle,
1125 Anonymized,
1127 Hash,
1129}
1130
1131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1133pub enum TargetEffort {
1134 Low,
1136 Medium,
1138 High,
1140}
1141
1142#[derive(Debug, Clone, Default)]
1144pub struct ComplexityOptions {
1145 pub analysis: AnalysisOptions,
1147 pub max_cyclomatic: Option<u16>,
1149 pub max_cognitive: Option<u16>,
1151 pub max_crap: Option<f64>,
1153 pub max_file_lines: Option<u32>,
1156 pub top: Option<usize>,
1158 pub sort: ComplexitySort,
1160 pub complexity_breakdown: bool,
1162 pub complexity: bool,
1164 pub file_scores: bool,
1166 pub coverage_gaps: bool,
1168 pub config_activates_coverage_gaps: bool,
1173 pub hotspots: bool,
1175 pub ownership: bool,
1177 pub ownership_emails: Option<OwnershipEmailMode>,
1179 pub targets: bool,
1181 pub css: bool,
1183 pub css_deep: bool,
1185 pub effort: Option<TargetEffort>,
1188 pub score: bool,
1190 pub since: Option<String>,
1192 pub min_commits: Option<u32>,
1194 pub coverage: Option<PathBuf>,
1196 pub coverage_root: Option<PathBuf>,
1198 pub coverage_relocated: bool,
1203}
1204
1205#[derive(Debug, Clone, Copy, Default, PartialEq)]
1207pub struct ComplexityThresholdOverrides {
1208 pub max_cyclomatic: Option<u16>,
1210 pub max_cognitive: Option<u16>,
1212 pub max_crap: Option<f64>,
1214 pub max_file_lines: Option<u32>,
1216}
1217
1218#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1220pub struct ComplexityCoverageInputs<'a> {
1221 pub coverage: Option<&'a Path>,
1223 pub coverage_root: Option<&'a Path>,
1225 pub coverage_relocated: bool,
1228}
1229
1230#[derive(Debug, Clone)]
1232pub struct HealthSectionOptions {
1233 pub output: fallow_types::output_format::OutputFormat,
1235 pub complexity: bool,
1237 pub file_scores: bool,
1239 pub coverage_gaps: bool,
1241 pub hotspots: bool,
1243 pub targets: bool,
1245 pub css: bool,
1247 pub score: bool,
1249 pub score_gate: bool,
1251 pub snapshot_requested: bool,
1253 pub trend: bool,
1255}
1256
1257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1259pub struct DerivedHealthSections {
1260 pub any_section: bool,
1262 pub complexity: bool,
1264 pub file_scores: bool,
1266 pub coverage_gaps: bool,
1268 pub hotspots: bool,
1270 pub targets: bool,
1272 pub css: bool,
1274 pub score: bool,
1276 pub force_full: bool,
1278 pub score_only_output: bool,
1280}
1281
1282#[derive(Debug, Clone)]
1284pub struct ComplexitySectionOptions {
1285 pub complexity: bool,
1287 pub file_scores: bool,
1289 pub coverage_gaps: bool,
1291 pub hotspots: bool,
1293 pub ownership: bool,
1295 pub targets: bool,
1297 pub css: bool,
1299 pub score: bool,
1301}
1302
1303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1305pub struct DerivedComplexityOptions {
1306 pub any_section: bool,
1308 pub complexity: bool,
1310 pub file_scores: bool,
1312 pub coverage_gaps: bool,
1314 pub hotspots: bool,
1316 pub ownership: bool,
1318 pub targets: bool,
1320 pub force_full: bool,
1322 pub score_only_output: bool,
1324 pub score: bool,
1326}
1327
1328#[derive(Debug, Clone, PartialEq)]
1330pub struct ComplexityRunOptions<'a> {
1331 pub thresholds: ComplexityThresholdOverrides,
1333 pub top: Option<usize>,
1335 pub sort: ComplexitySort,
1337 pub complexity_breakdown: bool,
1339 pub sections: DerivedComplexityOptions,
1341 pub ownership_emails: Option<OwnershipEmailMode>,
1343 pub effort: Option<TargetEffort>,
1345 pub css: bool,
1347 pub css_deep: bool,
1349 pub since: Option<&'a str>,
1351 pub min_commits: Option<u32>,
1353 pub coverage_inputs: ComplexityCoverageInputs<'a>,
1355}
1356
1357pub fn configure_global_analysis_pool(threads: usize) -> bool {
1366 fallow_engine::thread_pool::worker_pool_builder(threads)
1367 .build_global()
1368 .is_ok()
1369}
1370
1371#[must_use]
1373pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
1374 let score = options.score
1375 || options.score_gate
1376 || options.trend
1377 || matches!(
1378 options.output,
1379 fallow_types::output_format::OutputFormat::Badge
1380 );
1381 let any_section = options.complexity
1382 || options.file_scores
1383 || options.coverage_gaps
1384 || options.hotspots
1385 || options.targets
1386 || score;
1387 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
1388 let force_full = options.snapshot_requested || effective_score;
1389
1390 DerivedHealthSections {
1391 any_section,
1392 complexity: if any_section {
1393 options.complexity
1394 } else {
1395 true
1396 },
1397 file_scores: if any_section {
1398 options.file_scores
1399 } else {
1400 true
1401 } || force_full,
1402 coverage_gaps: if any_section {
1403 options.coverage_gaps
1404 } else {
1405 false
1406 },
1407 hotspots: if any_section { options.hotspots } else { true }
1408 || options.snapshot_requested
1409 || options.trend,
1410 targets: if any_section { options.targets } else { true },
1411 css: options.css,
1412 score: effective_score,
1413 force_full,
1414 score_only_output: is_health_score_only_output(options, score),
1415 }
1416}
1417
1418#[must_use]
1420pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
1421 let requested_hotspots = options.hotspots || options.ownership;
1422 let sections = derive_health_sections(&HealthSectionOptions {
1423 output: fallow_types::output_format::OutputFormat::Human,
1424 complexity: options.complexity,
1425 file_scores: options.file_scores,
1426 coverage_gaps: options.coverage_gaps,
1427 hotspots: requested_hotspots,
1428 targets: options.targets,
1429 css: options.css,
1430 score: options.score,
1431 score_gate: false,
1432 snapshot_requested: false,
1433 trend: false,
1434 });
1435
1436 DerivedComplexityOptions {
1437 any_section: sections.any_section,
1438 complexity: sections.complexity,
1439 file_scores: sections.file_scores,
1440 coverage_gaps: sections.coverage_gaps,
1441 hotspots: sections.hotspots,
1442 ownership: options.ownership && sections.hotspots,
1443 targets: sections.targets,
1444 force_full: sections.force_full,
1445 score_only_output: sections.score_only_output,
1446 score: sections.score,
1447 }
1448}
1449
1450#[must_use]
1452pub fn derive_complexity_options(options: &ComplexityOptions) -> DerivedComplexityOptions {
1453 derive_complexity_sections(&complexity_section_options(options))
1454}
1455
1456#[must_use]
1458pub fn derive_complexity_run_options(options: &ComplexityOptions) -> ComplexityRunOptions<'_> {
1459 ComplexityRunOptions {
1460 thresholds: ComplexityThresholdOverrides {
1461 max_cyclomatic: options.max_cyclomatic,
1462 max_cognitive: options.max_cognitive,
1463 max_crap: options.max_crap,
1464 max_file_lines: options.max_file_lines,
1465 },
1466 top: options.top,
1467 sort: options.sort,
1468 complexity_breakdown: options.complexity_breakdown,
1469 sections: derive_complexity_options(options),
1470 ownership_emails: options.ownership_emails,
1471 effort: options.effort,
1472 css: options.css,
1473 css_deep: options.css_deep,
1474 since: options.since.as_deref(),
1475 min_commits: options.min_commits,
1476 coverage_inputs: ComplexityCoverageInputs {
1477 coverage: options.coverage.as_deref(),
1478 coverage_root: options.coverage_root.as_deref(),
1479 coverage_relocated: options.coverage_relocated,
1480 },
1481 }
1482}
1483
1484pub fn validate_complexity_options(options: &ComplexityOptions) -> Result<(), ProgrammaticError> {
1507 if let Some(path) = &options.coverage {
1508 let resolved = fallow_engine::health::scoring::resolve_relative_to_root(
1509 path,
1510 options.analysis.root.as_deref(),
1511 );
1512 if !resolved.exists() {
1513 return Err(ProgrammaticError::new(
1514 format!("coverage path does not exist: {}", resolved.display()),
1515 2,
1516 )
1517 .with_code("FALLOW_INVALID_COVERAGE_PATH")
1518 .with_context("health.coverage"));
1519 }
1520 }
1521 if let Err(message) =
1522 fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
1523 {
1524 return Err(ProgrammaticError::new(message, 2)
1525 .with_code("FALLOW_INVALID_COVERAGE_ROOT")
1526 .with_context("health.coverage_root"));
1527 }
1528
1529 Ok(())
1530}
1531
1532fn complexity_section_options(options: &ComplexityOptions) -> ComplexitySectionOptions {
1533 let ownership = options.ownership || options.ownership_emails.is_some();
1534 let requested_targets = options.targets || options.effort.is_some();
1535 ComplexitySectionOptions {
1536 complexity: options.complexity,
1537 file_scores: options.file_scores,
1538 coverage_gaps: options.coverage_gaps,
1539 hotspots: options.hotspots,
1540 ownership,
1541 targets: requested_targets,
1542 css: options.css,
1543 score: options.score,
1544 }
1545}
1546
1547fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
1548 score
1549 && !options.complexity
1550 && !options.file_scores
1551 && !options.coverage_gaps
1552 && !options.hotspots
1553 && !options.targets
1554 && !options.trend
1555}
1556
1557const fn thresholds_to_engine(
1558 thresholds: ComplexityThresholdOverrides,
1559) -> fallow_engine::health::HealthThresholdOverrides {
1560 fallow_engine::health::HealthThresholdOverrides {
1561 max_cyclomatic: thresholds.max_cyclomatic,
1562 max_cognitive: thresholds.max_cognitive,
1563 max_crap: thresholds.max_crap,
1564 max_file_lines: thresholds.max_file_lines,
1565 }
1566}
1567
1568const fn complexity_sort_to_engine(sort: ComplexitySort) -> fallow_engine::health::HealthSort {
1569 match sort {
1570 ComplexitySort::Severity => fallow_engine::health::HealthSort::Severity,
1571 ComplexitySort::Cyclomatic => fallow_engine::health::HealthSort::Cyclomatic,
1572 ComplexitySort::Cognitive => fallow_engine::health::HealthSort::Cognitive,
1573 ComplexitySort::Lines => fallow_engine::health::HealthSort::Lines,
1574 }
1575}
1576
1577const fn coverage_inputs_to_engine(
1578 coverage_inputs: ComplexityCoverageInputs<'_>,
1579) -> fallow_engine::health::HealthCoverageInputs<'_> {
1580 fallow_engine::health::HealthCoverageInputs {
1581 coverage: coverage_inputs.coverage,
1582 coverage_root: coverage_inputs.coverage_root,
1583 coverage_relocated: coverage_inputs.coverage_relocated,
1584 }
1585}
1586
1587const fn ownership_email_mode_to_config(mode: OwnershipEmailMode) -> EmailMode {
1588 match mode {
1589 OwnershipEmailMode::Raw => EmailMode::Raw,
1590 OwnershipEmailMode::Handle => EmailMode::Handle,
1591 OwnershipEmailMode::Anonymized => EmailMode::Anonymized,
1592 OwnershipEmailMode::Hash => EmailMode::Hash,
1593 }
1594}
1595
1596const fn target_effort_to_output(effort: TargetEffort) -> EffortEstimate {
1597 match effort {
1598 TargetEffort::Low => EffortEstimate::Low,
1599 TargetEffort::Medium => EffortEstimate::Medium,
1600 TargetEffort::High => EffortEstimate::High,
1601 }
1602}
1603
1604#[cfg(test)]
1605mod tests {
1606 use super::*;
1607
1608 #[test]
1609 fn duplication_defaults_match_cli_contract() {
1610 let options = DuplicationOptions::default();
1611 assert!(options.mode.is_none());
1612 assert!(options.min_tokens.is_none());
1613 assert!(options.min_lines.is_none());
1614 assert!(options.min_occurrences.is_none());
1615 }
1616
1617 #[test]
1618 fn programmatic_error_builder_keeps_optional_fields() {
1619 let error = ProgrammaticError::new("boom", 2)
1620 .with_code("FALLOW_TEST")
1621 .with_help("Try again")
1622 .with_context("analysis.root");
1623
1624 assert_eq!(error.message, "boom");
1625 assert_eq!(error.exit_code, 2);
1626 assert_eq!(error.code.as_deref(), Some("FALLOW_TEST"));
1627 assert_eq!(error.help.as_deref(), Some("Try again"));
1628 assert_eq!(error.context.as_deref(), Some("analysis.root"));
1629 }
1630
1631 #[test]
1632 fn dead_code_filters_accept_shared_registry_selectors() {
1633 for (selector, _) in fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS.iter() {
1634 let mut filters = DeadCodeFilters::default();
1635 assert!(
1636 filters.enable_registry_selector(selector),
1637 "{selector} should be accepted"
1638 );
1639 }
1640
1641 let mut filters = DeadCodeFilters::default();
1642 assert!(filters.enable_registry_selector("unused-files"));
1643 assert!(filters.unused_files);
1644 assert!(filters.enable_registry_selector("boundary-violations"));
1645 assert!(filters.boundary_violations);
1646 assert!(!filters.enable_registry_selector("not-a-real-selector"));
1647 }
1648
1649 #[test]
1650 fn default_complexity_options_match_programmatic_health_defaults() {
1651 let derived = derive_complexity_options(&ComplexityOptions::default());
1652
1653 assert!(!derived.any_section);
1654 assert!(derived.complexity);
1655 assert!(derived.file_scores);
1656 assert!(!derived.coverage_gaps);
1657 assert!(derived.hotspots);
1658 assert!(!derived.ownership);
1659 assert!(derived.targets);
1660 assert!(derived.force_full);
1661 assert!(!derived.score_only_output);
1662 assert!(derived.score);
1663 }
1664
1665 #[test]
1666 fn score_only_complexity_options_request_score_only_output() {
1667 let derived = derive_complexity_options(&ComplexityOptions {
1668 score: true,
1669 ..ComplexityOptions::default()
1670 });
1671
1672 assert!(derived.any_section);
1673 assert!(!derived.complexity);
1674 assert!(derived.file_scores);
1675 assert!(!derived.hotspots);
1676 assert!(!derived.targets);
1677 assert!(derived.force_full);
1678 assert!(derived.score_only_output);
1679 assert!(derived.score);
1680 }
1681
1682 #[test]
1683 fn ownership_implies_hotspots_when_requested() {
1684 let derived = derive_complexity_options(&ComplexityOptions {
1685 ownership: true,
1686 ..ComplexityOptions::default()
1687 });
1688
1689 assert!(derived.any_section);
1690 assert!(derived.hotspots);
1691 assert!(derived.ownership);
1692 assert!(!derived.targets);
1693 }
1694
1695 #[test]
1696 fn complexity_run_options_normalize_public_api_options() {
1697 let options = ComplexityOptions {
1698 max_cyclomatic: Some(42),
1699 max_cognitive: Some(21),
1700 max_crap: Some(18.5),
1701 top: Some(7),
1702 sort: ComplexitySort::Severity,
1703 complexity_breakdown: true,
1704 ownership_emails: Some(OwnershipEmailMode::Hash),
1705 effort: Some(TargetEffort::High),
1706 coverage: Some(PathBuf::from("coverage/coverage-final.json")),
1707 coverage_root: Some(PathBuf::from("/ci/workspace")),
1708 since: Some("30d".to_string()),
1709 min_commits: Some(4),
1710 ..ComplexityOptions::default()
1711 };
1712
1713 let run = derive_complexity_run_options(&options);
1714
1715 assert_eq!(run.thresholds.max_cyclomatic, Some(42));
1716 assert_eq!(run.thresholds.max_cognitive, Some(21));
1717 assert_eq!(run.thresholds.max_crap, Some(18.5));
1718 assert_eq!(run.top, Some(7));
1719 assert!(matches!(run.sort, ComplexitySort::Severity));
1720 assert!(run.complexity_breakdown);
1721 assert!(run.sections.hotspots);
1722 assert!(run.sections.ownership);
1723 assert!(run.sections.targets);
1724 assert!(matches!(
1725 run.ownership_emails,
1726 Some(OwnershipEmailMode::Hash)
1727 ));
1728 assert!(matches!(run.effort, Some(TargetEffort::High)));
1729 assert_eq!(run.since, Some("30d"));
1730 assert_eq!(run.min_commits, Some(4));
1731 assert_eq!(run.coverage_inputs.coverage, options.coverage.as_deref());
1732 assert_eq!(
1733 run.coverage_inputs.coverage_root,
1734 options.coverage_root.as_deref()
1735 );
1736 }
1737
1738 #[test]
1739 fn complexity_options_validation_accepts_existing_coverage_path_and_absolute_root() {
1740 let dir = tempfile::tempdir().expect("tempdir");
1741 let coverage = dir.path().join("coverage-final.json");
1742 std::fs::write(&coverage, "{}").expect("coverage fixture");
1743
1744 let result = validate_complexity_options(&ComplexityOptions {
1745 coverage: Some(coverage),
1746 coverage_root: Some(PathBuf::from("/ci/workspace")),
1747 ..ComplexityOptions::default()
1748 });
1749
1750 assert!(result.is_ok());
1751 }
1752
1753 #[test]
1754 fn complexity_options_validation_keeps_missing_coverage_error_contract() {
1755 let err = validate_complexity_options(&ComplexityOptions {
1756 coverage: Some(PathBuf::from("/missing/coverage-final.json")),
1757 ..ComplexityOptions::default()
1758 })
1759 .expect_err("missing coverage path should fail");
1760
1761 assert_eq!(err.exit_code, 2);
1762 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1763 assert_eq!(err.context.as_deref(), Some("health.coverage"));
1764 }
1765
1766 #[test]
1767 fn complexity_options_validation_keeps_relative_coverage_root_error_contract() {
1768 let err = validate_complexity_options(&ComplexityOptions {
1769 coverage_root: Some(PathBuf::from("coverage")),
1770 ..ComplexityOptions::default()
1771 })
1772 .expect_err("relative coverage root should fail");
1773
1774 assert_eq!(err.exit_code, 2);
1775 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_ROOT"));
1776 assert_eq!(err.context.as_deref(), Some("health.coverage_root"));
1777 }
1778
1779 #[test]
1783 fn complexity_options_validation_resolves_relative_coverage_against_root() {
1784 let dir = tempfile::tempdir().expect("tempdir");
1785 std::fs::create_dir_all(dir.path().join("artifacts")).expect("artifacts dir");
1786 std::fs::write(dir.path().join("artifacts/coverage-final.json"), "{}")
1787 .expect("coverage fixture");
1788 let relative = PathBuf::from("artifacts/coverage-final.json");
1789 assert!(
1790 !relative.exists(),
1791 "the fixture must not also exist under the test cwd"
1792 );
1793
1794 let result = validate_complexity_options(&ComplexityOptions {
1795 analysis: AnalysisOptions {
1796 root: Some(dir.path().to_path_buf()),
1797 ..AnalysisOptions::default()
1798 },
1799 coverage: Some(relative.clone()),
1800 ..ComplexityOptions::default()
1801 });
1802 assert!(result.is_ok(), "{result:?}");
1803
1804 let err = validate_complexity_options(&ComplexityOptions {
1805 analysis: AnalysisOptions {
1806 root: Some(dir.path().join("elsewhere")),
1807 ..AnalysisOptions::default()
1808 },
1809 coverage: Some(relative),
1810 ..ComplexityOptions::default()
1811 })
1812 .expect_err("the path does not exist under the other root");
1813 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1814 assert!(
1815 err.message.contains("elsewhere"),
1816 "the message names the resolved path: {}",
1817 err.message
1818 );
1819 }
1820
1821 #[test]
1822 fn default_health_sections_match_full_health_output() {
1823 let derived = derive_health_sections(&HealthSectionOptions {
1824 output: fallow_types::output_format::OutputFormat::Human,
1825 complexity: false,
1826 file_scores: false,
1827 coverage_gaps: false,
1828 hotspots: false,
1829 targets: false,
1830 css: false,
1831 score: false,
1832 score_gate: false,
1833 snapshot_requested: false,
1834 trend: false,
1835 });
1836
1837 assert!(!derived.any_section);
1838 assert!(derived.complexity);
1839 assert!(derived.file_scores);
1840 assert!(!derived.coverage_gaps);
1841 assert!(derived.hotspots);
1842 assert!(derived.targets);
1843 assert!(derived.score);
1844 assert!(derived.force_full);
1845 assert!(!derived.score_only_output);
1846 }
1847
1848 #[test]
1849 fn health_score_gate_requests_score_only_output() {
1850 let derived = derive_health_sections(&HealthSectionOptions {
1851 output: fallow_types::output_format::OutputFormat::Human,
1852 complexity: false,
1853 file_scores: false,
1854 coverage_gaps: false,
1855 hotspots: false,
1856 targets: false,
1857 css: false,
1858 score: false,
1859 score_gate: true,
1860 snapshot_requested: false,
1861 trend: false,
1862 });
1863
1864 assert!(derived.any_section);
1865 assert!(!derived.complexity);
1866 assert!(derived.file_scores);
1867 assert!(!derived.hotspots);
1868 assert!(!derived.targets);
1869 assert!(derived.score);
1870 assert!(derived.force_full);
1871 assert!(derived.score_only_output);
1872 }
1873
1874 #[test]
1875 fn health_snapshot_keeps_full_hidden_inputs_without_section_request() {
1876 let derived = derive_health_sections(&HealthSectionOptions {
1877 output: fallow_types::output_format::OutputFormat::Human,
1878 complexity: false,
1879 file_scores: false,
1880 coverage_gaps: false,
1881 hotspots: false,
1882 targets: false,
1883 css: true,
1884 score: false,
1885 score_gate: false,
1886 snapshot_requested: true,
1887 trend: false,
1888 });
1889
1890 assert!(!derived.any_section);
1891 assert!(derived.css);
1892 assert!(derived.file_scores);
1893 assert!(derived.hotspots);
1894 assert!(derived.score);
1895 assert!(derived.force_full);
1896 }
1897}
1898
1899mod shared_state_explain;