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};
147pub use fallow_engine::discover::SOURCE_EXTENSIONS;
149#[cfg(any(test, feature = "testing"))]
152pub use fallow_engine::git_fixture;
153pub use fallow_engine::package_baselines::{PackageBaselineError, PackageChangeScope};
155pub use fallow_engine::post_edit;
158pub use fallow_engine::source_edits;
159pub use fallow_engine::thread_pool::{WORKER_STACK_SIZE, register_thread_stack};
166pub use fallow_engine::warm_parse;
172pub use fallow_output::PackageBaselineStatus;
174pub use fallow_output::serialize_similar_code_json_output;
175pub use fallow_types::trace::{
176 CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace, ReExportChain,
177 TracedCloneGroup, TracedExport, TracedReExport,
178};
179pub use fallow_types::trace_usage::{
180 DependencyUsage, DependencyUsageQuery, SitePageRequest, UsageQueryError,
181};
182pub use grouped_output::{
183 ResultGroup, UNOWNED_GROUP_LABEL, build_duplication_grouping_with, group_analysis_results_with,
184 health_signal_header_part, largest_clone_group_owner_with,
185};
186pub use health_codeclimate::build_health_codeclimate;
187pub use health_groups_markdown::build_health_groups_markdown;
188pub use json_output::{
189 CheckJsonExtraOutputs, CheckJsonOutputInput, CheckJsonPayloadInput, DuplicationJsonOutputInput,
190 GroupedCheckJsonOutputInput, GroupedDuplicationJsonOutputInput, serialize_check_json,
191 serialize_check_json_payload, serialize_duplication_json, serialize_grouped_check_json,
192 serialize_grouped_duplication_json,
193};
194pub use list_output::{
195 ListJsonEnvelope, ListJsonOutputInput, build_list_json_output, serialize_list_json_output,
196};
197pub use list_runtime::{
198 BoundaryData, ListBoundariesOptions, ListBoundariesProgrammaticOutput, LogicalGroupInfo,
199 ProjectInfoOptions, ProjectInfoProgrammaticOutput, RuleInfo, ZoneInfo, boundary_data_to_output,
200 compute_boundary_data, run_list_boundaries, run_project_info,
201 serialize_list_boundaries_programmatic_json, serialize_project_info_programmatic_json,
202};
203pub use markdown_output::{
204 ComplexityListing, build_diff_risk_markdown, build_duplication_markdown,
205 build_grouped_markdown, build_health_markdown, build_markdown, build_walkthrough_markdown,
206};
207pub use mutation::{
208 MutationProgress, MutationProgressSink, MutationReplayOptions, MutationRunOptions,
209 MutationRunScope, apply_mutation_verdicts, validate_mutation_verdicts,
210};
211pub use output_contracts::{
212 AuditOutput, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
213 BoundariesListing, CombinedOutput, FallowOutput, ImpactOutput, ListBoundariesOutput,
214 ListEntryPointOutput, ListOutput, ListPluginOutput, ReviewBriefWireOutput, SecurityGate,
215 SecurityOutput, SecurityOutputConfig, SecuritySummaryOutput, SimilarCodeCandidateSnapshot,
216 SimilarCodeOutput, TraceOutput, WorkspacesOutput,
217};
218pub use runtime::TYPE_AWARE_CONFIG_UNSUPPORTED;
219pub use runtime::{
220 AUDIT_CONFIG_BASELINE_UNSUPPORTED, ArchitectureOutput, ArchitectureProgrammaticOutput,
221 AuditProgrammaticKeySnapshot, AuditProgrammaticOutput, BoundaryViolationsOutput,
222 BoundaryViolationsProgrammaticOutput, CircularDependenciesOutput,
223 CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput, DeadCodeOutput,
224 DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput, DuplicationOutput,
225 DuplicationProgrammaticOutput, EngineHealthRunner, FeatureFlagsOutput,
226 FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
227 ProgrammaticHealthAnalysis, ProgrammaticHealthNextStepFacts, ProgrammaticHealthRun,
228 ProgrammaticHealthRunner, TraceClassMemberOutput, TraceCloneBenchmarkResult, TraceCloneOutput,
229 TraceCloneProgrammaticOutput, TraceDependencyOutput, TraceDependencyProgrammaticOutput,
230 TraceErrorOutput, TraceErrorProgrammaticOutput, TraceExportOutput,
231 TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
232 TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
233 benchmark_trace_clone_compact_json, benchmark_trace_graph_family_compact_json,
234 inspect_similar_code, load_health_config, parse_similar_code_candidate_snapshot, plan_mutation,
235 replay_mutation, review_similar_code, run_architecture, run_audit, run_boundary_violations,
236 run_circular_dependencies, run_combined, run_complexity_with_runner, run_dead_code,
237 run_dead_code_with_baseline, run_decision_surface, run_duplication, run_feature_flags,
238 run_health, run_health_with_runner, run_mutation, run_mutation_with_progress, run_similar_code,
239 run_trace_clone, run_trace_dependency, run_trace_error, run_trace_export, run_trace_file,
240 run_trace_import_path, select_similar_code_candidate_snapshot, serialize_health_report_json,
241};
242pub use runtime_json::{
243 serialize_architecture_programmatic_json, serialize_audit_programmatic_json,
244 serialize_boundary_violations_programmatic_json,
245 serialize_circular_dependencies_programmatic_json, serialize_combined_programmatic_json,
246 serialize_dead_code_programmatic_json, serialize_decision_surface_programmatic_json,
247 serialize_duplication_programmatic_json, serialize_feature_flags_programmatic_json,
248 serialize_health_programmatic_json, serialize_trace_clone_programmatic_json,
249 serialize_trace_dependency_programmatic_json, serialize_trace_error_programmatic_json,
250 serialize_trace_export_programmatic_json, serialize_trace_file_programmatic_json,
251 serialize_trace_import_path_programmatic_json,
252};
253pub use sarif_output::{
254 annotate_sarif_results, build_duplication_sarif, build_grouped_duplication_sarif,
255 build_health_sarif,
256};
257pub use security_output::SecurityGateMode;
258pub use type_aware::{
259 DEFAULT_BACKEND_FAMILY as DEFAULT_TYPE_AWARE_BACKEND_FAMILY, SemanticCouplingOutcome,
260 SemanticDeadCodeOutcome, SemanticInspectOutcome, TypeAwareError, TypeAwareFileChanges,
261 TypeAwareOutcome, TypeAwareSession, TypeAwareStatus, discard_unverified_semantic_candidates,
262 inspect_symbol as inspect_type_aware_symbol, merge_type_aware_meta,
263 refine_configured_dead_code_results as refine_type_aware_results_with_config,
264 shutdown_type_aware_sidecars, status as type_aware_status,
265 symbol_impact as run_type_aware_symbol_impact, symbol_impact as type_aware_symbol_impact,
266 terminate_active_type_aware_sidecars, trace_symbol as run_type_aware_symbol_trace,
267 trace_symbol as trace_type_aware_symbol, type_coupling as analyze_type_coupling,
268};
269
270pub use type_aware::setup_store as type_aware_setup;
273
274pub const COMMON_ANALYSIS_OPTION_FLAGS: &[&str] = &[
281 "root",
282 "config",
283 "no-cache",
284 "threads",
285 "changed-since",
286 "diff-file",
287 "production",
288 "workspace",
289 "changed-workspaces",
290 "explain",
291 "allow-remote-extends",
292];
293
294#[derive(Debug, Clone, Serialize)]
296pub struct ProgrammaticError {
297 pub message: String,
299 pub exit_code: u8,
301 pub code: Option<String>,
303 pub help: Option<String>,
305 pub context: Option<String>,
307}
308
309impl ProgrammaticError {
310 #[must_use]
313 pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
314 Self {
315 message: message.into(),
316 exit_code,
317 code: None,
318 help: None,
319 context: None,
320 }
321 }
322
323 #[must_use]
325 pub fn with_help(mut self, help: impl Into<String>) -> Self {
326 self.help = Some(help.into());
327 self
328 }
329
330 #[must_use]
333 pub fn with_code(mut self, code: impl Into<String>) -> Self {
334 self.code = Some(code.into());
335 self
336 }
337
338 #[must_use]
341 pub fn with_context(mut self, context: impl Into<String>) -> Self {
342 self.context = Some(context.into());
343 self
344 }
345}
346
347impl std::fmt::Display for ProgrammaticError {
348 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
349 write!(f, "{}", self.message)
350 }
351}
352
353impl std::error::Error for ProgrammaticError {}
354
355#[derive(Debug, Clone, Default)]
357pub struct AnalysisOptions {
358 pub root: Option<PathBuf>,
361 pub config_path: Option<PathBuf>,
363 pub allow_remote_extends: bool,
365 pub no_cache: bool,
367 pub threads: Option<usize>,
369 pub diff_file: Option<PathBuf>,
381 pub ambient_diff_file: Option<PathBuf>,
389 pub production: bool,
392 pub production_override: Option<bool>,
395 pub changed_since: Option<String>,
400 pub ambient_changed_since: Option<String>,
408 pub no_package_baselines: bool,
412 pub workspace: Option<Vec<String>>,
414 pub changed_workspaces: Option<String>,
416 pub explain: bool,
418 pub type_aware: TypeAwareOptions,
421 pub cancellation: Option<Arc<AtomicBool>>,
451 pub host: Option<run::HostInputs>,
457}
458
459#[derive(Debug, Clone, Default, PartialEq, Eq)]
461pub struct TypeAwareOptions {
462 pub enabled: Option<bool>,
469 pub projects: Vec<PathBuf>,
472 pub require: fallow_config::TypeAwareRequire,
474}
475
476impl TypeAwareOptions {
477 #[must_use]
479 pub const fn requested(&self) -> bool {
480 matches!(self.enabled, Some(true))
481 }
482}
483
484#[derive(Debug, Clone, Default, PartialEq, Eq)]
489pub struct DeadCodeFilters {
490 pub shared_state: bool,
492 pub unused_files: bool,
494 pub unused_exports: bool,
496 pub unused_deps: bool,
498 pub unused_types: bool,
500 pub private_type_leaks: bool,
502 pub deprecated_exports_in_use: bool,
504 pub unused_enum_members: bool,
506 pub unused_class_members: bool,
508 pub unused_namespace_members: bool,
510 pub unused_protected_class_members: bool,
512 pub namespace_escapes: bool,
515 pub unused_store_members: bool,
517 pub unprovided_injects: bool,
519 pub unrendered_components: bool,
521 pub unused_component_props: bool,
523 pub absent_component_props: bool,
525 pub constant_parameters: bool,
527 pub unused_component_emits: bool,
529 pub unused_component_inputs: bool,
531 pub unused_component_outputs: bool,
533 pub unused_svelte_events: bool,
535 pub unused_effect_layers: bool,
537 pub unused_tagged_errors: bool,
539 pub unproduced_catch_tags: bool,
541 pub unused_server_actions: bool,
543 pub unused_load_data_keys: bool,
545 pub unresolved_imports: bool,
547 pub unlisted_deps: bool,
549 pub unlisted_binaries: bool,
551 pub duplicate_exports: bool,
553 pub duplicate_export_aliases: bool,
555 pub circular_deps: bool,
557 pub re_export_cycles: bool,
559 pub package_cycles: bool,
561 pub boundary_violations: bool,
563 pub policy_violations: bool,
565 pub stale_suppressions: bool,
567 pub unused_catalog_entries: bool,
569 pub empty_catalog_groups: bool,
571 pub unresolved_catalog_references: bool,
573 pub unused_dependency_overrides: bool,
575 pub misconfigured_dependency_overrides: bool,
577}
578
579impl DeadCodeFilters {
580 pub(crate) fn reports_dependency_findings(&self) -> bool {
584 !self.any_active() || self.unused_deps || self.unlisted_deps
585 }
586
587 fn any_active(&self) -> bool {
588 self.shared_state
589 || self.unused_files
590 || self.unused_exports
591 || self.unused_deps
592 || self.unused_types
593 || self.private_type_leaks
594 || self.deprecated_exports_in_use
595 || self.unused_enum_members
596 || self.unused_class_members
597 || self.unused_namespace_members
598 || self.unused_protected_class_members
599 || self.namespace_escapes
600 || self.unused_store_members
601 || self.unprovided_injects
602 || self.unrendered_components
603 || self.unused_component_props
604 || self.absent_component_props
605 || self.constant_parameters
606 || self.unused_component_emits
607 || self.unused_component_inputs
608 || self.unused_component_outputs
609 || self.unused_svelte_events
610 || self.unused_effect_layers
611 || self.unused_tagged_errors
612 || self.unproduced_catch_tags
613 || self.unused_server_actions
614 || self.unused_load_data_keys
615 || self.unresolved_imports
616 || self.unlisted_deps
617 || self.unlisted_binaries
618 || self.duplicate_exports
619 || self.duplicate_export_aliases
620 || self.circular_deps
621 || self.re_export_cycles
622 || self.package_cycles
623 || self.boundary_violations
624 || self.policy_violations
625 || self.stale_suppressions
626 || self.unused_catalog_entries
627 || self.empty_catalog_groups
628 || self.unresolved_catalog_references
629 || self.unused_dependency_overrides
630 || self.misconfigured_dependency_overrides
631 }
632
633 pub fn enable_registry_selector(&mut self, selector: &str) -> bool {
639 let Some(flag) = fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS
640 .iter()
641 .find_map(|&(name, flag)| (name == selector).then_some(flag))
642 else {
643 return false;
644 };
645 self.enable_cli_filter_flag(flag);
646 true
647 }
648
649 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
651 fallow_engine::requested_rule_off::explicit_filter_flags(|flag| {
652 let mut enabled = self.clone();
653 enabled.enable_cli_filter_flag(flag);
654 enabled == *self
655 })
656 }
657
658 fn enable_cli_filter_flag(&mut self, flag: &str) {
659 match flag {
660 "--unused-files" => self.unused_files = true,
661 "--unused-exports" => self.unused_exports = true,
662 "--unused-types" => self.unused_types = true,
663 "--private-type-leaks" => self.private_type_leaks = true,
664 "--deprecated-exports-in-use" => self.deprecated_exports_in_use = true,
665 "--unused-deps" => self.unused_deps = true,
666 "--unused-enum-members" => self.unused_enum_members = true,
667 "--unused-class-members" => self.unused_class_members = true,
668 "--unused-namespace-members" => self.unused_namespace_members = true,
669 "--unused-protected-class-members" => self.unused_protected_class_members = true,
670 "--namespace-escapes" => self.namespace_escapes = true,
671 "--unused-store-members" => self.unused_store_members = true,
672 "--unprovided-injects" => self.unprovided_injects = true,
673 "--unrendered-components" => self.unrendered_components = true,
674 "--unused-component-props" => self.unused_component_props = true,
675 "--absent-component-props" => self.absent_component_props = true,
676 "--constant-parameters" => self.constant_parameters = true,
677 "--unused-component-emits" => self.unused_component_emits = true,
678 "--unused-component-inputs" => self.unused_component_inputs = true,
679 "--unused-component-outputs" => self.unused_component_outputs = true,
680 "--unused-svelte-events" => self.unused_svelte_events = true,
681 "--unused-effect-layers" => self.unused_effect_layers = true,
682 "--unused-tagged-errors" => self.unused_tagged_errors = true,
683 "--unproduced-catch-tags" => self.unproduced_catch_tags = true,
684 "--unused-server-actions" => self.unused_server_actions = true,
685 "--unused-load-data-keys" => self.unused_load_data_keys = true,
686 "--unresolved-imports" => self.unresolved_imports = true,
687 "--unlisted-deps" => self.unlisted_deps = true,
688 "--unlisted-binaries" => self.unlisted_binaries = true,
689 "--duplicate-exports" => self.duplicate_exports = true,
690 "--duplicate-export-aliases" => self.duplicate_export_aliases = true,
691 "--circular-deps" => self.circular_deps = true,
692 "--re-export-cycles" => self.re_export_cycles = true,
693 "--package-cycles" => self.package_cycles = true,
694 "--boundary-violations" => self.boundary_violations = true,
695 "--policy-violations" => self.policy_violations = true,
696 "--stale-suppressions" => self.stale_suppressions = true,
697 "--unused-catalog-entries" => self.unused_catalog_entries = true,
698 "--empty-catalog-groups" => self.empty_catalog_groups = true,
699 "--unresolved-catalog-references" => self.unresolved_catalog_references = true,
700 "--unused-dependency-overrides" => self.unused_dependency_overrides = true,
701 "--misconfigured-dependency-overrides" => {
702 self.misconfigured_dependency_overrides = true;
703 }
704 _ => unreachable!("registry emitted unsupported dead-code filter flag: {flag}"),
705 }
706 }
707}
708
709#[derive(Debug, Clone, Default)]
711pub struct DeadCodeOptions {
712 pub analysis: AnalysisOptions,
714 pub filters: DeadCodeFilters,
716 pub files: Vec<PathBuf>,
718 pub include_entry_exports: bool,
720 pub show_cascade: bool,
722 pub finding_ids: Vec<String>,
727}
728
729#[derive(Debug, Clone, Default)]
735pub struct ArchitectureOptions {
736 pub shared_state: bool,
738 pub analysis: AnalysisOptions,
740 pub files: Vec<PathBuf>,
742 pub cycles: bool,
745 pub boundaries: bool,
747 pub policy: bool,
749}
750
751impl ArchitectureOptions {
752 #[must_use]
754 pub fn dead_code_filters(&self) -> DeadCodeFilters {
755 let all = !(self.cycles || self.boundaries || self.policy || self.shared_state);
756 DeadCodeFilters {
757 shared_state: self.shared_state,
758 circular_deps: self.cycles || all,
759 re_export_cycles: self.cycles || all,
760 package_cycles: self.cycles || all,
761 boundary_violations: self.boundaries || all,
762 policy_violations: self.policy || all,
763 ..DeadCodeFilters::default()
764 }
765 }
766
767 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
770 fallow_engine::requested_rule_off::architecture_requested_flags(
771 self.cycles,
772 self.boundaries,
773 self.policy,
774 )
775 }
776
777 #[must_use]
779 pub fn dead_code_options(&self) -> DeadCodeOptions {
780 DeadCodeOptions {
781 analysis: self.analysis.clone(),
782 filters: self.dead_code_filters(),
783 files: self.files.clone(),
784 include_entry_exports: false,
785 show_cascade: false,
786 finding_ids: Vec::new(),
787 }
788 }
789}
790
791#[derive(Debug, Clone, Default)]
793pub struct AuditOptions {
794 pub analysis: AnalysisOptions,
796 pub base: Option<String>,
799 pub production: bool,
801 pub production_dead_code: Option<bool>,
803 pub production_health: Option<bool>,
805 pub production_dupes: Option<bool>,
808 pub dead_code: Option<bool>,
812 pub health: Option<bool>,
815 pub duplication: Option<bool>,
818 pub css: Option<bool>,
821 pub css_deep: Option<bool>,
824 pub gate: Option<fallow_config::AuditGate>,
827 pub worsened: Option<fallow_config::AuditWorsened>,
830 pub max_crap: Option<f64>,
832 pub coverage: Option<PathBuf>,
834 pub coverage_root: Option<PathBuf>,
836 pub include_entry_exports: bool,
838 pub show_cascade: bool,
840 pub runtime_coverage: Option<PathBuf>,
842 pub min_invocations_hot: u64,
844}
845
846#[derive(Debug, Clone)]
848pub struct CombinedOptions {
849 pub analysis: AnalysisOptions,
851 pub production_dead_code: Option<bool>,
855 pub production_health: Option<bool>,
857 pub production_dupes: Option<bool>,
860 pub dead_code: bool,
862 pub duplication: bool,
864 pub health: bool,
866 pub include_entry_exports: bool,
868 pub show_cascade: bool,
870 pub duplication_options: DuplicationOptions,
872 pub health_options: ComplexityOptions,
874}
875
876impl Default for CombinedOptions {
877 fn default() -> Self {
878 Self {
879 analysis: AnalysisOptions::default(),
880 production_dead_code: None,
881 production_health: None,
882 production_dupes: None,
883 dead_code: true,
884 duplication: true,
885 health: true,
886 include_entry_exports: false,
887 show_cascade: false,
888 duplication_options: DuplicationOptions::default(),
889 health_options: ComplexityOptions::default(),
890 }
891 }
892}
893
894#[derive(Debug, Clone, Default)]
896pub struct DecisionSurfaceOptions {
897 pub analysis: AnalysisOptions,
899 pub base: Option<String>,
902 pub max_decisions: Option<usize>,
904}
905
906#[derive(Debug, Clone, Default)]
908pub struct FeatureFlagsOptions {
909 pub analysis: AnalysisOptions,
911 pub top: Option<usize>,
914 pub retirement: Option<FeatureFlagsRetirementOptions>,
916}
917
918#[derive(Debug, Clone, Default)]
921pub struct FeatureFlagsRetirementOptions {
922 pub flag_age: fallow_types::flag_retirement::FlagAgeMode,
924 pub flag_state: Option<std::path::PathBuf>,
926 pub reasons: Vec<fallow_types::flag_retirement::RetirementReason>,
928 pub sort: fallow_engine::flag_retirement::RetirementSort,
930 pub min_age_days: Option<u64>,
932 pub max_flag_age: Option<u64>,
934}
935
936#[derive(Debug, Clone, Copy, Default)]
938pub enum DuplicationMode {
939 Strict,
942 #[default]
944 Mild,
945 Weak,
947 Semantic,
950}
951
952#[derive(Debug, Clone, Default)]
954pub struct DuplicationOptions {
955 pub analysis: AnalysisOptions,
957 pub mode: Option<DuplicationMode>,
959 pub near: Option<bool>,
962 pub min_tokens: Option<usize>,
964 pub min_lines: Option<usize>,
966 pub min_occurrences: Option<usize>,
969 pub threshold: Option<f64>,
972 pub skip_local: Option<bool>,
975 pub ignore_symlinks: Option<bool>,
978 pub cross_language: Option<bool>,
980 pub ignore_imports: Option<bool>,
983 pub top: Option<usize>,
985 pub include_fragments: Option<bool>,
989}
990
991#[derive(Debug, Clone, Default)]
993pub struct SimilarCodeOptions {
994 pub analysis: AnalysisOptions,
996 pub threshold: Option<f64>,
998 pub min_lines: Option<usize>,
1001 pub top: Option<usize>,
1003 pub files: Vec<PathBuf>,
1007 #[doc(hidden)]
1012 pub adapter_provider_path: Option<PathBuf>,
1013}
1014
1015#[derive(Debug, Clone)]
1017pub struct SimilarCodeInspectOptions {
1018 pub analysis: AnalysisOptions,
1021 pub snapshot: fallow_output::SimilarCodeCandidateSnapshot,
1023}
1024
1025#[derive(Debug, Clone, Default)]
1027pub struct TraceExportOptions {
1028 pub analysis: AnalysisOptions,
1030 pub file: String,
1032 pub export_name: String,
1034}
1035
1036#[derive(Debug, Clone, Default)]
1038pub struct TraceFileOptions {
1039 pub analysis: AnalysisOptions,
1041 pub file: String,
1043}
1044
1045#[derive(Debug, Clone, Default)]
1047pub struct TraceImportPathOptions {
1048 pub analysis: AnalysisOptions,
1050 pub from: String,
1052 pub to: String,
1054 pub eager_only: bool,
1057}
1058
1059#[derive(Debug, Clone, Default)]
1061pub struct TraceErrorOptions {
1062 pub analysis: AnalysisOptions,
1064 pub trace: String,
1066 pub source: String,
1068}
1069
1070#[derive(Debug, Clone, Default)]
1072pub struct TraceDependencyOptions {
1073 pub analysis: AnalysisOptions,
1075 pub package_name: String,
1077 pub usage: Option<DependencyUsageQuery>,
1080}
1081
1082#[derive(Debug, Clone, PartialEq, Eq)]
1084pub enum TraceCloneTarget {
1085 Location {
1087 file: String,
1089 line: usize,
1091 },
1092 Fingerprint(String),
1094}
1095
1096#[derive(Debug, Clone)]
1098pub struct TraceCloneOptions {
1099 pub duplication: DuplicationOptions,
1101 pub target: TraceCloneTarget,
1103}
1104
1105#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1107pub enum ComplexitySort {
1108 #[default]
1110 Cyclomatic,
1111 Cognitive,
1113 Lines,
1115 Severity,
1117}
1118
1119#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1121pub enum OwnershipEmailMode {
1122 Raw,
1124 #[default]
1126 Handle,
1127 Anonymized,
1129 Hash,
1131}
1132
1133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1135pub enum TargetEffort {
1136 Low,
1138 Medium,
1140 High,
1142}
1143
1144#[derive(Debug, Clone, Default)]
1146pub struct ComplexityOptions {
1147 pub analysis: AnalysisOptions,
1149 pub max_cyclomatic: Option<u16>,
1151 pub max_cognitive: Option<u16>,
1153 pub max_crap: Option<f64>,
1155 pub max_file_lines: Option<u32>,
1158 pub top: Option<usize>,
1160 pub sort: ComplexitySort,
1162 pub complexity_breakdown: bool,
1164 pub complexity: bool,
1166 pub file_scores: bool,
1168 pub coverage_gaps: bool,
1170 pub config_activates_coverage_gaps: bool,
1175 pub hotspots: bool,
1177 pub ownership: bool,
1179 pub ownership_emails: Option<OwnershipEmailMode>,
1181 pub targets: bool,
1183 pub css: bool,
1185 pub css_deep: bool,
1187 pub effort: Option<TargetEffort>,
1190 pub score: bool,
1192 pub since: Option<String>,
1194 pub min_commits: Option<u32>,
1196 pub coverage: Option<PathBuf>,
1198 pub coverage_root: Option<PathBuf>,
1200 pub coverage_relocated: bool,
1205}
1206
1207#[derive(Debug, Clone, Copy, Default, PartialEq)]
1209pub struct ComplexityThresholdOverrides {
1210 pub max_cyclomatic: Option<u16>,
1212 pub max_cognitive: Option<u16>,
1214 pub max_crap: Option<f64>,
1216 pub max_file_lines: Option<u32>,
1218}
1219
1220#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1222pub struct ComplexityCoverageInputs<'a> {
1223 pub coverage: Option<&'a Path>,
1225 pub coverage_root: Option<&'a Path>,
1227 pub coverage_relocated: bool,
1230}
1231
1232#[derive(Debug, Clone)]
1234pub struct HealthSectionOptions {
1235 pub output: fallow_types::output_format::OutputFormat,
1237 pub complexity: bool,
1239 pub file_scores: bool,
1241 pub coverage_gaps: bool,
1243 pub hotspots: bool,
1245 pub targets: bool,
1247 pub css: bool,
1249 pub score: bool,
1251 pub score_gate: bool,
1253 pub snapshot_requested: bool,
1255 pub trend: bool,
1257}
1258
1259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1261pub struct DerivedHealthSections {
1262 pub any_section: bool,
1264 pub complexity: bool,
1266 pub file_scores: bool,
1268 pub coverage_gaps: bool,
1270 pub hotspots: bool,
1272 pub targets: bool,
1274 pub css: bool,
1276 pub score: bool,
1278 pub force_full: bool,
1280 pub score_only_output: bool,
1282}
1283
1284#[derive(Debug, Clone)]
1286pub struct ComplexitySectionOptions {
1287 pub complexity: bool,
1289 pub file_scores: bool,
1291 pub coverage_gaps: bool,
1293 pub hotspots: bool,
1295 pub ownership: bool,
1297 pub targets: bool,
1299 pub css: bool,
1301 pub score: bool,
1303}
1304
1305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1307pub struct DerivedComplexityOptions {
1308 pub any_section: bool,
1310 pub complexity: bool,
1312 pub file_scores: bool,
1314 pub coverage_gaps: bool,
1316 pub hotspots: bool,
1318 pub ownership: bool,
1320 pub targets: bool,
1322 pub force_full: bool,
1324 pub score_only_output: bool,
1326 pub score: bool,
1328}
1329
1330#[derive(Debug, Clone, PartialEq)]
1332pub struct ComplexityRunOptions<'a> {
1333 pub thresholds: ComplexityThresholdOverrides,
1335 pub top: Option<usize>,
1337 pub sort: ComplexitySort,
1339 pub complexity_breakdown: bool,
1341 pub sections: DerivedComplexityOptions,
1343 pub ownership_emails: Option<OwnershipEmailMode>,
1345 pub effort: Option<TargetEffort>,
1347 pub css: bool,
1349 pub css_deep: bool,
1351 pub since: Option<&'a str>,
1353 pub min_commits: Option<u32>,
1355 pub coverage_inputs: ComplexityCoverageInputs<'a>,
1357}
1358
1359pub fn configure_global_analysis_pool(threads: usize) -> bool {
1368 fallow_engine::thread_pool::worker_pool_builder(threads)
1369 .build_global()
1370 .is_ok()
1371}
1372
1373#[must_use]
1375pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
1376 let score = options.score
1377 || options.score_gate
1378 || options.trend
1379 || matches!(
1380 options.output,
1381 fallow_types::output_format::OutputFormat::Badge
1382 );
1383 let any_section = options.complexity
1384 || options.file_scores
1385 || options.coverage_gaps
1386 || options.hotspots
1387 || options.targets
1388 || score;
1389 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
1390 let force_full = options.snapshot_requested || effective_score;
1391
1392 DerivedHealthSections {
1393 any_section,
1394 complexity: if any_section {
1395 options.complexity
1396 } else {
1397 true
1398 },
1399 file_scores: if any_section {
1400 options.file_scores
1401 } else {
1402 true
1403 } || force_full,
1404 coverage_gaps: if any_section {
1405 options.coverage_gaps
1406 } else {
1407 false
1408 },
1409 hotspots: if any_section { options.hotspots } else { true }
1410 || options.snapshot_requested
1411 || options.trend,
1412 targets: if any_section { options.targets } else { true },
1413 css: options.css,
1414 score: effective_score,
1415 force_full,
1416 score_only_output: is_health_score_only_output(options, score),
1417 }
1418}
1419
1420#[must_use]
1422pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
1423 let requested_hotspots = options.hotspots || options.ownership;
1424 let sections = derive_health_sections(&HealthSectionOptions {
1425 output: fallow_types::output_format::OutputFormat::Human,
1426 complexity: options.complexity,
1427 file_scores: options.file_scores,
1428 coverage_gaps: options.coverage_gaps,
1429 hotspots: requested_hotspots,
1430 targets: options.targets,
1431 css: options.css,
1432 score: options.score,
1433 score_gate: false,
1434 snapshot_requested: false,
1435 trend: false,
1436 });
1437
1438 DerivedComplexityOptions {
1439 any_section: sections.any_section,
1440 complexity: sections.complexity,
1441 file_scores: sections.file_scores,
1442 coverage_gaps: sections.coverage_gaps,
1443 hotspots: sections.hotspots,
1444 ownership: options.ownership && sections.hotspots,
1445 targets: sections.targets,
1446 force_full: sections.force_full,
1447 score_only_output: sections.score_only_output,
1448 score: sections.score,
1449 }
1450}
1451
1452#[must_use]
1454pub fn derive_complexity_options(options: &ComplexityOptions) -> DerivedComplexityOptions {
1455 derive_complexity_sections(&complexity_section_options(options))
1456}
1457
1458#[must_use]
1460pub fn derive_complexity_run_options(options: &ComplexityOptions) -> ComplexityRunOptions<'_> {
1461 ComplexityRunOptions {
1462 thresholds: ComplexityThresholdOverrides {
1463 max_cyclomatic: options.max_cyclomatic,
1464 max_cognitive: options.max_cognitive,
1465 max_crap: options.max_crap,
1466 max_file_lines: options.max_file_lines,
1467 },
1468 top: options.top,
1469 sort: options.sort,
1470 complexity_breakdown: options.complexity_breakdown,
1471 sections: derive_complexity_options(options),
1472 ownership_emails: options.ownership_emails,
1473 effort: options.effort,
1474 css: options.css,
1475 css_deep: options.css_deep,
1476 since: options.since.as_deref(),
1477 min_commits: options.min_commits,
1478 coverage_inputs: ComplexityCoverageInputs {
1479 coverage: options.coverage.as_deref(),
1480 coverage_root: options.coverage_root.as_deref(),
1481 coverage_relocated: options.coverage_relocated,
1482 },
1483 }
1484}
1485
1486pub fn validate_complexity_options(options: &ComplexityOptions) -> Result<(), ProgrammaticError> {
1509 if let Some(path) = &options.coverage {
1510 let resolved = fallow_engine::health::scoring::resolve_relative_to_root(
1511 path,
1512 options.analysis.root.as_deref(),
1513 );
1514 if !resolved.exists() {
1515 return Err(ProgrammaticError::new(
1516 format!("coverage path does not exist: {}", resolved.display()),
1517 2,
1518 )
1519 .with_code("FALLOW_INVALID_COVERAGE_PATH")
1520 .with_context("health.coverage"));
1521 }
1522 }
1523 if let Err(message) =
1524 fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
1525 {
1526 return Err(ProgrammaticError::new(message, 2)
1527 .with_code("FALLOW_INVALID_COVERAGE_ROOT")
1528 .with_context("health.coverage_root"));
1529 }
1530
1531 Ok(())
1532}
1533
1534fn complexity_section_options(options: &ComplexityOptions) -> ComplexitySectionOptions {
1535 let ownership = options.ownership || options.ownership_emails.is_some();
1536 let requested_targets = options.targets || options.effort.is_some();
1537 ComplexitySectionOptions {
1538 complexity: options.complexity,
1539 file_scores: options.file_scores,
1540 coverage_gaps: options.coverage_gaps,
1541 hotspots: options.hotspots,
1542 ownership,
1543 targets: requested_targets,
1544 css: options.css,
1545 score: options.score,
1546 }
1547}
1548
1549fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
1550 score
1551 && !options.complexity
1552 && !options.file_scores
1553 && !options.coverage_gaps
1554 && !options.hotspots
1555 && !options.targets
1556 && !options.trend
1557}
1558
1559const fn thresholds_to_engine(
1560 thresholds: ComplexityThresholdOverrides,
1561) -> fallow_engine::health::HealthThresholdOverrides {
1562 fallow_engine::health::HealthThresholdOverrides {
1563 max_cyclomatic: thresholds.max_cyclomatic,
1564 max_cognitive: thresholds.max_cognitive,
1565 max_crap: thresholds.max_crap,
1566 max_file_lines: thresholds.max_file_lines,
1567 }
1568}
1569
1570const fn complexity_sort_to_engine(sort: ComplexitySort) -> fallow_engine::health::HealthSort {
1571 match sort {
1572 ComplexitySort::Severity => fallow_engine::health::HealthSort::Severity,
1573 ComplexitySort::Cyclomatic => fallow_engine::health::HealthSort::Cyclomatic,
1574 ComplexitySort::Cognitive => fallow_engine::health::HealthSort::Cognitive,
1575 ComplexitySort::Lines => fallow_engine::health::HealthSort::Lines,
1576 }
1577}
1578
1579const fn coverage_inputs_to_engine(
1580 coverage_inputs: ComplexityCoverageInputs<'_>,
1581) -> fallow_engine::health::HealthCoverageInputs<'_> {
1582 fallow_engine::health::HealthCoverageInputs {
1583 coverage: coverage_inputs.coverage,
1584 coverage_root: coverage_inputs.coverage_root,
1585 coverage_relocated: coverage_inputs.coverage_relocated,
1586 }
1587}
1588
1589const fn ownership_email_mode_to_config(mode: OwnershipEmailMode) -> EmailMode {
1590 match mode {
1591 OwnershipEmailMode::Raw => EmailMode::Raw,
1592 OwnershipEmailMode::Handle => EmailMode::Handle,
1593 OwnershipEmailMode::Anonymized => EmailMode::Anonymized,
1594 OwnershipEmailMode::Hash => EmailMode::Hash,
1595 }
1596}
1597
1598const fn target_effort_to_output(effort: TargetEffort) -> EffortEstimate {
1599 match effort {
1600 TargetEffort::Low => EffortEstimate::Low,
1601 TargetEffort::Medium => EffortEstimate::Medium,
1602 TargetEffort::High => EffortEstimate::High,
1603 }
1604}
1605
1606#[cfg(test)]
1607mod tests {
1608 use super::*;
1609
1610 #[test]
1611 fn duplication_defaults_match_cli_contract() {
1612 let options = DuplicationOptions::default();
1613 assert!(options.mode.is_none());
1614 assert!(options.min_tokens.is_none());
1615 assert!(options.min_lines.is_none());
1616 assert!(options.min_occurrences.is_none());
1617 }
1618
1619 #[test]
1620 fn programmatic_error_builder_keeps_optional_fields() {
1621 let error = ProgrammaticError::new("boom", 2)
1622 .with_code("FALLOW_TEST")
1623 .with_help("Try again")
1624 .with_context("analysis.root");
1625
1626 assert_eq!(error.message, "boom");
1627 assert_eq!(error.exit_code, 2);
1628 assert_eq!(error.code.as_deref(), Some("FALLOW_TEST"));
1629 assert_eq!(error.help.as_deref(), Some("Try again"));
1630 assert_eq!(error.context.as_deref(), Some("analysis.root"));
1631 }
1632
1633 #[test]
1634 fn dead_code_filters_accept_shared_registry_selectors() {
1635 for (selector, _) in fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS.iter() {
1636 let mut filters = DeadCodeFilters::default();
1637 assert!(
1638 filters.enable_registry_selector(selector),
1639 "{selector} should be accepted"
1640 );
1641 }
1642
1643 let mut filters = DeadCodeFilters::default();
1644 assert!(filters.enable_registry_selector("unused-files"));
1645 assert!(filters.unused_files);
1646 assert!(filters.enable_registry_selector("boundary-violations"));
1647 assert!(filters.boundary_violations);
1648 assert!(!filters.enable_registry_selector("not-a-real-selector"));
1649 }
1650
1651 #[test]
1652 fn default_complexity_options_match_programmatic_health_defaults() {
1653 let derived = derive_complexity_options(&ComplexityOptions::default());
1654
1655 assert!(!derived.any_section);
1656 assert!(derived.complexity);
1657 assert!(derived.file_scores);
1658 assert!(!derived.coverage_gaps);
1659 assert!(derived.hotspots);
1660 assert!(!derived.ownership);
1661 assert!(derived.targets);
1662 assert!(derived.force_full);
1663 assert!(!derived.score_only_output);
1664 assert!(derived.score);
1665 }
1666
1667 #[test]
1668 fn score_only_complexity_options_request_score_only_output() {
1669 let derived = derive_complexity_options(&ComplexityOptions {
1670 score: true,
1671 ..ComplexityOptions::default()
1672 });
1673
1674 assert!(derived.any_section);
1675 assert!(!derived.complexity);
1676 assert!(derived.file_scores);
1677 assert!(!derived.hotspots);
1678 assert!(!derived.targets);
1679 assert!(derived.force_full);
1680 assert!(derived.score_only_output);
1681 assert!(derived.score);
1682 }
1683
1684 #[test]
1685 fn ownership_implies_hotspots_when_requested() {
1686 let derived = derive_complexity_options(&ComplexityOptions {
1687 ownership: true,
1688 ..ComplexityOptions::default()
1689 });
1690
1691 assert!(derived.any_section);
1692 assert!(derived.hotspots);
1693 assert!(derived.ownership);
1694 assert!(!derived.targets);
1695 }
1696
1697 #[test]
1698 fn complexity_run_options_normalize_public_api_options() {
1699 let options = ComplexityOptions {
1700 max_cyclomatic: Some(42),
1701 max_cognitive: Some(21),
1702 max_crap: Some(18.5),
1703 top: Some(7),
1704 sort: ComplexitySort::Severity,
1705 complexity_breakdown: true,
1706 ownership_emails: Some(OwnershipEmailMode::Hash),
1707 effort: Some(TargetEffort::High),
1708 coverage: Some(PathBuf::from("coverage/coverage-final.json")),
1709 coverage_root: Some(PathBuf::from("/ci/workspace")),
1710 since: Some("30d".to_string()),
1711 min_commits: Some(4),
1712 ..ComplexityOptions::default()
1713 };
1714
1715 let run = derive_complexity_run_options(&options);
1716
1717 assert_eq!(run.thresholds.max_cyclomatic, Some(42));
1718 assert_eq!(run.thresholds.max_cognitive, Some(21));
1719 assert_eq!(run.thresholds.max_crap, Some(18.5));
1720 assert_eq!(run.top, Some(7));
1721 assert!(matches!(run.sort, ComplexitySort::Severity));
1722 assert!(run.complexity_breakdown);
1723 assert!(run.sections.hotspots);
1724 assert!(run.sections.ownership);
1725 assert!(run.sections.targets);
1726 assert!(matches!(
1727 run.ownership_emails,
1728 Some(OwnershipEmailMode::Hash)
1729 ));
1730 assert!(matches!(run.effort, Some(TargetEffort::High)));
1731 assert_eq!(run.since, Some("30d"));
1732 assert_eq!(run.min_commits, Some(4));
1733 assert_eq!(run.coverage_inputs.coverage, options.coverage.as_deref());
1734 assert_eq!(
1735 run.coverage_inputs.coverage_root,
1736 options.coverage_root.as_deref()
1737 );
1738 }
1739
1740 #[test]
1741 fn complexity_options_validation_accepts_existing_coverage_path_and_absolute_root() {
1742 let dir = tempfile::tempdir().expect("tempdir");
1743 let coverage = dir.path().join("coverage-final.json");
1744 std::fs::write(&coverage, "{}").expect("coverage fixture");
1745
1746 let result = validate_complexity_options(&ComplexityOptions {
1747 coverage: Some(coverage),
1748 coverage_root: Some(PathBuf::from("/ci/workspace")),
1749 ..ComplexityOptions::default()
1750 });
1751
1752 assert!(result.is_ok());
1753 }
1754
1755 #[test]
1756 fn complexity_options_validation_keeps_missing_coverage_error_contract() {
1757 let err = validate_complexity_options(&ComplexityOptions {
1758 coverage: Some(PathBuf::from("/missing/coverage-final.json")),
1759 ..ComplexityOptions::default()
1760 })
1761 .expect_err("missing coverage path should fail");
1762
1763 assert_eq!(err.exit_code, 2);
1764 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1765 assert_eq!(err.context.as_deref(), Some("health.coverage"));
1766 }
1767
1768 #[test]
1769 fn complexity_options_validation_keeps_relative_coverage_root_error_contract() {
1770 let err = validate_complexity_options(&ComplexityOptions {
1771 coverage_root: Some(PathBuf::from("coverage")),
1772 ..ComplexityOptions::default()
1773 })
1774 .expect_err("relative coverage root should fail");
1775
1776 assert_eq!(err.exit_code, 2);
1777 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_ROOT"));
1778 assert_eq!(err.context.as_deref(), Some("health.coverage_root"));
1779 }
1780
1781 #[test]
1785 fn complexity_options_validation_resolves_relative_coverage_against_root() {
1786 let dir = tempfile::tempdir().expect("tempdir");
1787 std::fs::create_dir_all(dir.path().join("artifacts")).expect("artifacts dir");
1788 std::fs::write(dir.path().join("artifacts/coverage-final.json"), "{}")
1789 .expect("coverage fixture");
1790 let relative = PathBuf::from("artifacts/coverage-final.json");
1791 assert!(
1792 !relative.exists(),
1793 "the fixture must not also exist under the test cwd"
1794 );
1795
1796 let result = validate_complexity_options(&ComplexityOptions {
1797 analysis: AnalysisOptions {
1798 root: Some(dir.path().to_path_buf()),
1799 ..AnalysisOptions::default()
1800 },
1801 coverage: Some(relative.clone()),
1802 ..ComplexityOptions::default()
1803 });
1804 assert!(result.is_ok(), "{result:?}");
1805
1806 let err = validate_complexity_options(&ComplexityOptions {
1807 analysis: AnalysisOptions {
1808 root: Some(dir.path().join("elsewhere")),
1809 ..AnalysisOptions::default()
1810 },
1811 coverage: Some(relative),
1812 ..ComplexityOptions::default()
1813 })
1814 .expect_err("the path does not exist under the other root");
1815 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1816 assert!(
1817 err.message.contains("elsewhere"),
1818 "the message names the resolved path: {}",
1819 err.message
1820 );
1821 }
1822
1823 #[test]
1824 fn default_health_sections_match_full_health_output() {
1825 let derived = derive_health_sections(&HealthSectionOptions {
1826 output: fallow_types::output_format::OutputFormat::Human,
1827 complexity: false,
1828 file_scores: false,
1829 coverage_gaps: false,
1830 hotspots: false,
1831 targets: false,
1832 css: false,
1833 score: false,
1834 score_gate: false,
1835 snapshot_requested: false,
1836 trend: false,
1837 });
1838
1839 assert!(!derived.any_section);
1840 assert!(derived.complexity);
1841 assert!(derived.file_scores);
1842 assert!(!derived.coverage_gaps);
1843 assert!(derived.hotspots);
1844 assert!(derived.targets);
1845 assert!(derived.score);
1846 assert!(derived.force_full);
1847 assert!(!derived.score_only_output);
1848 }
1849
1850 #[test]
1851 fn health_score_gate_requests_score_only_output() {
1852 let derived = derive_health_sections(&HealthSectionOptions {
1853 output: fallow_types::output_format::OutputFormat::Human,
1854 complexity: false,
1855 file_scores: false,
1856 coverage_gaps: false,
1857 hotspots: false,
1858 targets: false,
1859 css: false,
1860 score: false,
1861 score_gate: true,
1862 snapshot_requested: false,
1863 trend: false,
1864 });
1865
1866 assert!(derived.any_section);
1867 assert!(!derived.complexity);
1868 assert!(derived.file_scores);
1869 assert!(!derived.hotspots);
1870 assert!(!derived.targets);
1871 assert!(derived.score);
1872 assert!(derived.force_full);
1873 assert!(derived.score_only_output);
1874 }
1875
1876 #[test]
1877 fn health_snapshot_keeps_full_hidden_inputs_without_section_request() {
1878 let derived = derive_health_sections(&HealthSectionOptions {
1879 output: fallow_types::output_format::OutputFormat::Human,
1880 complexity: false,
1881 file_scores: false,
1882 coverage_gaps: false,
1883 hotspots: false,
1884 targets: false,
1885 css: true,
1886 score: false,
1887 score_gate: false,
1888 snapshot_requested: true,
1889 trend: false,
1890 });
1891
1892 assert!(!derived.any_section);
1893 assert!(derived.css);
1894 assert!(derived.file_scores);
1895 assert!(derived.hotspots);
1896 assert!(derived.score);
1897 assert!(derived.force_full);
1898 }
1899}
1900
1901mod shared_state_explain;