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;
56mod explain_guides;
57mod explain_rationale;
58pub mod grouped_output;
59pub mod health_codeclimate;
60mod health_groups_markdown;
61pub mod json_output;
62pub mod list_output;
63mod list_runtime;
64pub mod markdown_output;
67pub mod mutation;
68mod next_steps;
69pub mod output_contracts;
70pub mod ownership;
71mod release_signature;
72pub mod review_deltas;
73pub mod routing;
74pub mod run;
75pub mod runtime;
76mod runtime_json;
77mod runtime_output;
78pub mod sarif_output;
79pub mod schemas;
82pub mod security_output;
83pub mod similar_code;
85mod type_aware;
86pub use analysis_context::{ProgrammaticAnalysisContext, resolve_programmatic_analysis_context};
87pub use audit_output::{
88 AuditAttribution, AuditCodeClimateOutputInput, AuditJsonHeaderInput, AuditJsonOutputInput,
89 AuditSarifOutputInput, AuditSummary, AuditVerdict, attach_audit_diff_risk_attribution,
90 attach_audit_duplication_demotion_attribution, attach_audit_styling_attribution,
91 attach_audit_wire_attribution, audit_run_notices, build_audit_codeclimate,
92 build_audit_codeclimate_issues, build_audit_header_json, build_audit_header_map,
93 build_audit_sarif, build_diff_risk_codeclimate, build_review_brief_header,
94 serialize_audit_json,
95};
96pub use combined_output::{
97 CombinedCheckJsonSection, CombinedJsonOutputInput, serialize_combined_dupes_json,
98 serialize_combined_health_json, serialize_combined_json,
99};
100pub use compact_output::{
101 build_compact_lines, build_diff_risk_compact_lines, build_duplication_compact_lines,
102 build_grouped_compact_lines, build_health_compact_lines,
103};
104pub use coverage::{
105 CoverageInputError, CoverageInputSource, CoverageInputs, resolve_coverage_inputs,
106};
107pub use dead_code_codeclimate::build_codeclimate;
108pub use dead_code_sarif::build_sarif;
109pub use doctor::{DoctorOptions, run_doctor, run_doctor_with_cache_dir};
110pub use dupes_output::{
111 AttributedCloneGroup, AttributedCloneGroupFinding, AttributedInstance, CloneDemotionReason,
112 CloneFamilyFinding, CloneGroupFinding, CombinedDupesSection, DupesReportPayload,
113 DuplicationGroup, DuplicationGrouping, build_duplication_codeclimate,
114 set_duplication_audit_attribution,
115};
116pub use editor::{
117 ChangedFilesError, EditorAnalysisOutput, EditorAnalysisResults, EditorAnalysisSession,
118 EditorCloneFamily, EditorCloneFingerprintSet, EditorCloneGroup, EditorCloneInstance,
119 EditorDeadCodeAnalysisOutput, EditorDuplicationReport, EditorDuplicationStats,
120 EditorInlineComplexityExceeded, EditorInlineComplexityFinding, EditorMirroredDirectory,
121 EditorProjectAnalysisOutput, EditorRefactoringKind, EditorRefactoringSuggestion,
122 EditorSessionParseCounts, collect_inline_complexity, editor_duplicates, editor_extract,
123 editor_results, editor_security, editor_suppress, filter_inline_complexity_by_change_scope,
124 filter_inline_complexity_by_changed_files, resolve_git_toplevel,
125 try_get_changed_files_with_toplevel,
126};
127pub use explain::{
128 AUDIT_RULES, CHECK_RULES, DUPES_RULES, FLAGS_RULES, HEALTH_RULES, MUTATION_RULES, RuleDef,
129 RuleGuide, SECURITY_RULES, all_rules, bare_rule_id, coverage_analyze_meta, coverage_setup_meta,
130 explain_issue_type, rule_by_id, rule_by_token, rule_command, rule_config_key, rule_docs_url,
131 rule_guide, rule_has_guide, rule_rationale, rule_severity_key, security_meta,
132 serialize_explain_programmatic_json, unknown_explain_error,
133};
134pub use fallow_config::levenshtein::closest_match;
135pub use fallow_config::{
136 AuditGate, AuditWorsened, HealthConfig, ProductionAnalysis, ProductionEnv, TypeAwareRequire,
137};
138pub use fallow_engine::change_scope::{
141 ChangeScope, ChangeScopeOwner, ChangeScopeRequest, first_package_baselines,
142 package_baseline_statuses,
143};
144pub use fallow_engine::package_baselines::{PackageBaselineError, PackageChangeScope};
146pub use fallow_engine::thread_pool::{WORKER_STACK_SIZE, register_thread_stack};
153pub use fallow_engine::warm_parse;
159pub use fallow_output::PackageBaselineStatus;
161pub use fallow_output::serialize_similar_code_json_output;
162pub use fallow_types::trace::{
163 CloneTrace, DependencyTrace, ExportReference, ExportTrace, FileTrace, ReExportChain,
164 TracedCloneGroup, TracedExport, TracedReExport,
165};
166pub use fallow_types::trace_usage::{
167 DependencyUsage, DependencyUsageQuery, SitePageRequest, UsageQueryError,
168};
169pub use grouped_output::{
170 ResultGroup, UNOWNED_GROUP_LABEL, build_duplication_grouping_with, group_analysis_results_with,
171 health_signal_header_part, largest_clone_group_owner_with,
172};
173pub use health_codeclimate::build_health_codeclimate;
174pub use health_groups_markdown::build_health_groups_markdown;
175pub use json_output::{
176 CheckJsonExtraOutputs, CheckJsonOutputInput, CheckJsonPayloadInput, DuplicationJsonOutputInput,
177 GroupedCheckJsonOutputInput, GroupedDuplicationJsonOutputInput, serialize_check_json,
178 serialize_check_json_payload, serialize_duplication_json, serialize_grouped_check_json,
179 serialize_grouped_duplication_json,
180};
181pub use list_output::{
182 ListJsonEnvelope, ListJsonOutputInput, build_list_json_output, serialize_list_json_output,
183};
184pub use list_runtime::{
185 BoundaryData, ListBoundariesOptions, ListBoundariesProgrammaticOutput, LogicalGroupInfo,
186 ProjectInfoOptions, ProjectInfoProgrammaticOutput, RuleInfo, ZoneInfo, boundary_data_to_output,
187 compute_boundary_data, run_list_boundaries, run_project_info,
188 serialize_list_boundaries_programmatic_json, serialize_project_info_programmatic_json,
189};
190pub use markdown_output::{
191 ComplexityListing, build_diff_risk_markdown, build_duplication_markdown,
192 build_grouped_markdown, build_health_markdown, build_markdown, build_walkthrough_markdown,
193};
194pub use mutation::{
195 MutationProgress, MutationProgressSink, MutationReplayOptions, MutationRunOptions,
196 MutationRunScope, apply_mutation_verdicts, validate_mutation_verdicts,
197};
198pub use output_contracts::{
199 AuditOutput, BoundariesListLogicalGroup, BoundariesListRule, BoundariesListZone,
200 BoundariesListing, CombinedOutput, FallowOutput, ImpactOutput, ListBoundariesOutput,
201 ListEntryPointOutput, ListOutput, ListPluginOutput, ReviewBriefWireOutput, SecurityGate,
202 SecurityOutput, SecurityOutputConfig, SecuritySummaryOutput, SimilarCodeCandidateSnapshot,
203 SimilarCodeOutput, TraceOutput, WorkspacesOutput,
204};
205pub use runtime::TYPE_AWARE_CONFIG_UNSUPPORTED;
206pub use runtime::{
207 AUDIT_CONFIG_BASELINE_UNSUPPORTED, ArchitectureOutput, ArchitectureProgrammaticOutput,
208 AuditProgrammaticKeySnapshot, AuditProgrammaticOutput, BoundaryViolationsOutput,
209 BoundaryViolationsProgrammaticOutput, CircularDependenciesOutput,
210 CircularDependenciesProgrammaticOutput, CombinedProgrammaticOutput, DeadCodeOutput,
211 DeadCodeProgrammaticOutput, DecisionSurfaceProgrammaticOutput, DuplicationOutput,
212 DuplicationProgrammaticOutput, EngineHealthRunner, FeatureFlagsOutput,
213 FeatureFlagsProgrammaticOutput, HealthJsonReportInput, HealthProgrammaticOutput,
214 ProgrammaticHealthAnalysis, ProgrammaticHealthNextStepFacts, ProgrammaticHealthRun,
215 ProgrammaticHealthRunner, TraceClassMemberOutput, TraceCloneBenchmarkResult, TraceCloneOutput,
216 TraceCloneProgrammaticOutput, TraceDependencyOutput, TraceDependencyProgrammaticOutput,
217 TraceErrorOutput, TraceErrorProgrammaticOutput, TraceExportOutput,
218 TraceExportProgrammaticOutput, TraceExportTargetOutput, TraceFileOutput,
219 TraceFileProgrammaticOutput, TraceImportPathOutput, TraceImportPathProgrammaticOutput,
220 benchmark_trace_clone_compact_json, benchmark_trace_graph_family_compact_json,
221 inspect_similar_code, load_health_config, parse_similar_code_candidate_snapshot, plan_mutation,
222 replay_mutation, review_similar_code, run_architecture, run_audit, run_boundary_violations,
223 run_circular_dependencies, run_combined, run_complexity_with_runner, run_dead_code,
224 run_dead_code_with_baseline, run_decision_surface, run_duplication, run_feature_flags,
225 run_health, run_health_with_runner, run_mutation, run_mutation_with_progress, run_similar_code,
226 run_trace_clone, run_trace_dependency, run_trace_error, run_trace_export, run_trace_file,
227 run_trace_import_path, select_similar_code_candidate_snapshot, serialize_health_report_json,
228};
229pub use runtime_json::{
230 serialize_architecture_programmatic_json, serialize_audit_programmatic_json,
231 serialize_boundary_violations_programmatic_json,
232 serialize_circular_dependencies_programmatic_json, serialize_combined_programmatic_json,
233 serialize_dead_code_programmatic_json, serialize_decision_surface_programmatic_json,
234 serialize_duplication_programmatic_json, serialize_feature_flags_programmatic_json,
235 serialize_health_programmatic_json, serialize_trace_clone_programmatic_json,
236 serialize_trace_dependency_programmatic_json, serialize_trace_error_programmatic_json,
237 serialize_trace_export_programmatic_json, serialize_trace_file_programmatic_json,
238 serialize_trace_import_path_programmatic_json,
239};
240pub use sarif_output::{
241 annotate_sarif_results, build_duplication_sarif, build_grouped_duplication_sarif,
242 build_health_sarif,
243};
244pub use security_output::SecurityGateMode;
245pub use type_aware::{
246 DEFAULT_BACKEND_FAMILY as DEFAULT_TYPE_AWARE_BACKEND_FAMILY, SemanticCouplingOutcome,
247 SemanticDeadCodeOutcome, SemanticInspectOutcome, TypeAwareError, TypeAwareFileChanges,
248 TypeAwareOutcome, TypeAwareSession, TypeAwareStatus, discard_unverified_semantic_candidates,
249 inspect_symbol as inspect_type_aware_symbol, merge_type_aware_meta,
250 refine_configured_dead_code_results as refine_type_aware_results_with_config,
251 shutdown_type_aware_sidecars, status as type_aware_status,
252 symbol_impact as run_type_aware_symbol_impact, symbol_impact as type_aware_symbol_impact,
253 terminate_active_type_aware_sidecars, trace_symbol as run_type_aware_symbol_trace,
254 trace_symbol as trace_type_aware_symbol, type_coupling as analyze_type_coupling,
255};
256
257pub use type_aware::setup_store as type_aware_setup;
260
261pub const COMMON_ANALYSIS_OPTION_FLAGS: &[&str] = &[
268 "root",
269 "config",
270 "no-cache",
271 "threads",
272 "changed-since",
273 "diff-file",
274 "production",
275 "workspace",
276 "changed-workspaces",
277 "explain",
278 "allow-remote-extends",
279];
280
281#[derive(Debug, Clone, Serialize)]
283pub struct ProgrammaticError {
284 pub message: String,
286 pub exit_code: u8,
288 pub code: Option<String>,
290 pub help: Option<String>,
292 pub context: Option<String>,
294}
295
296impl ProgrammaticError {
297 #[must_use]
300 pub fn new(message: impl Into<String>, exit_code: u8) -> Self {
301 Self {
302 message: message.into(),
303 exit_code,
304 code: None,
305 help: None,
306 context: None,
307 }
308 }
309
310 #[must_use]
312 pub fn with_help(mut self, help: impl Into<String>) -> Self {
313 self.help = Some(help.into());
314 self
315 }
316
317 #[must_use]
320 pub fn with_code(mut self, code: impl Into<String>) -> Self {
321 self.code = Some(code.into());
322 self
323 }
324
325 #[must_use]
328 pub fn with_context(mut self, context: impl Into<String>) -> Self {
329 self.context = Some(context.into());
330 self
331 }
332}
333
334impl std::fmt::Display for ProgrammaticError {
335 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
336 write!(f, "{}", self.message)
337 }
338}
339
340impl std::error::Error for ProgrammaticError {}
341
342#[derive(Debug, Clone, Default)]
344pub struct AnalysisOptions {
345 pub root: Option<PathBuf>,
348 pub config_path: Option<PathBuf>,
350 pub allow_remote_extends: bool,
352 pub no_cache: bool,
354 pub threads: Option<usize>,
356 pub diff_file: Option<PathBuf>,
368 pub ambient_diff_file: Option<PathBuf>,
376 pub production: bool,
379 pub production_override: Option<bool>,
382 pub changed_since: Option<String>,
387 pub ambient_changed_since: Option<String>,
395 pub no_package_baselines: bool,
399 pub workspace: Option<Vec<String>>,
401 pub changed_workspaces: Option<String>,
403 pub explain: bool,
405 pub type_aware: TypeAwareOptions,
408 pub cancellation: Option<Arc<AtomicBool>>,
438 pub host: Option<run::HostInputs>,
444}
445
446#[derive(Debug, Clone, Default, PartialEq, Eq)]
448pub struct TypeAwareOptions {
449 pub enabled: Option<bool>,
456 pub projects: Vec<PathBuf>,
459 pub require: fallow_config::TypeAwareRequire,
461}
462
463impl TypeAwareOptions {
464 #[must_use]
466 pub const fn requested(&self) -> bool {
467 matches!(self.enabled, Some(true))
468 }
469}
470
471#[derive(Debug, Clone, Default, PartialEq, Eq)]
476pub struct DeadCodeFilters {
477 pub shared_state: bool,
479 pub unused_files: bool,
481 pub unused_exports: bool,
483 pub unused_deps: bool,
485 pub unused_types: bool,
487 pub private_type_leaks: bool,
489 pub deprecated_exports_in_use: bool,
491 pub unused_enum_members: bool,
493 pub unused_class_members: bool,
495 pub unused_namespace_members: bool,
497 pub unused_protected_class_members: bool,
499 pub unused_store_members: bool,
501 pub unprovided_injects: bool,
503 pub unrendered_components: bool,
505 pub unused_component_props: bool,
507 pub absent_component_props: bool,
509 pub constant_parameters: bool,
511 pub unused_component_emits: bool,
513 pub unused_component_inputs: bool,
515 pub unused_component_outputs: bool,
517 pub unused_svelte_events: bool,
519 pub unused_effect_layers: bool,
521 pub unused_tagged_errors: bool,
523 pub unproduced_catch_tags: bool,
525 pub unused_server_actions: bool,
527 pub unused_load_data_keys: bool,
529 pub unresolved_imports: bool,
531 pub unlisted_deps: bool,
533 pub unlisted_binaries: bool,
535 pub duplicate_exports: bool,
537 pub duplicate_export_aliases: bool,
539 pub circular_deps: bool,
541 pub re_export_cycles: bool,
543 pub package_cycles: bool,
545 pub boundary_violations: bool,
547 pub policy_violations: bool,
549 pub stale_suppressions: bool,
551 pub unused_catalog_entries: bool,
553 pub empty_catalog_groups: bool,
555 pub unresolved_catalog_references: bool,
557 pub unused_dependency_overrides: bool,
559 pub misconfigured_dependency_overrides: bool,
561}
562
563impl DeadCodeFilters {
564 pub(crate) fn reports_dependency_findings(&self) -> bool {
568 !self.any_active() || self.unused_deps || self.unlisted_deps
569 }
570
571 fn any_active(&self) -> bool {
572 self.shared_state
573 || self.unused_files
574 || self.unused_exports
575 || self.unused_deps
576 || self.unused_types
577 || self.private_type_leaks
578 || self.deprecated_exports_in_use
579 || self.unused_enum_members
580 || self.unused_class_members
581 || self.unused_namespace_members
582 || self.unused_protected_class_members
583 || self.unused_store_members
584 || self.unprovided_injects
585 || self.unrendered_components
586 || self.unused_component_props
587 || self.absent_component_props
588 || self.constant_parameters
589 || self.unused_component_emits
590 || self.unused_component_inputs
591 || self.unused_component_outputs
592 || self.unused_svelte_events
593 || self.unused_effect_layers
594 || self.unused_tagged_errors
595 || self.unproduced_catch_tags
596 || self.unused_server_actions
597 || self.unused_load_data_keys
598 || self.unresolved_imports
599 || self.unlisted_deps
600 || self.unlisted_binaries
601 || self.duplicate_exports
602 || self.duplicate_export_aliases
603 || self.circular_deps
604 || self.re_export_cycles
605 || self.package_cycles
606 || self.boundary_violations
607 || self.policy_violations
608 || self.stale_suppressions
609 || self.unused_catalog_entries
610 || self.empty_catalog_groups
611 || self.unresolved_catalog_references
612 || self.unused_dependency_overrides
613 || self.misconfigured_dependency_overrides
614 }
615
616 pub fn enable_registry_selector(&mut self, selector: &str) -> bool {
622 let Some(flag) = fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS
623 .iter()
624 .find_map(|&(name, flag)| (name == selector).then_some(flag))
625 else {
626 return false;
627 };
628 self.enable_cli_filter_flag(flag);
629 true
630 }
631
632 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
634 fallow_engine::requested_rule_off::explicit_filter_flags(|flag| {
635 let mut enabled = self.clone();
636 enabled.enable_cli_filter_flag(flag);
637 enabled == *self
638 })
639 }
640
641 fn enable_cli_filter_flag(&mut self, flag: &str) {
642 match flag {
643 "--unused-files" => self.unused_files = true,
644 "--unused-exports" => self.unused_exports = true,
645 "--unused-types" => self.unused_types = true,
646 "--private-type-leaks" => self.private_type_leaks = true,
647 "--deprecated-exports-in-use" => self.deprecated_exports_in_use = true,
648 "--unused-deps" => self.unused_deps = true,
649 "--unused-enum-members" => self.unused_enum_members = true,
650 "--unused-class-members" => self.unused_class_members = true,
651 "--unused-namespace-members" => self.unused_namespace_members = true,
652 "--unused-protected-class-members" => self.unused_protected_class_members = true,
653 "--unused-store-members" => self.unused_store_members = true,
654 "--unprovided-injects" => self.unprovided_injects = true,
655 "--unrendered-components" => self.unrendered_components = true,
656 "--unused-component-props" => self.unused_component_props = true,
657 "--absent-component-props" => self.absent_component_props = true,
658 "--constant-parameters" => self.constant_parameters = true,
659 "--unused-component-emits" => self.unused_component_emits = true,
660 "--unused-component-inputs" => self.unused_component_inputs = true,
661 "--unused-component-outputs" => self.unused_component_outputs = true,
662 "--unused-svelte-events" => self.unused_svelte_events = true,
663 "--unused-effect-layers" => self.unused_effect_layers = true,
664 "--unused-tagged-errors" => self.unused_tagged_errors = true,
665 "--unproduced-catch-tags" => self.unproduced_catch_tags = true,
666 "--unused-server-actions" => self.unused_server_actions = true,
667 "--unused-load-data-keys" => self.unused_load_data_keys = true,
668 "--unresolved-imports" => self.unresolved_imports = true,
669 "--unlisted-deps" => self.unlisted_deps = true,
670 "--unlisted-binaries" => self.unlisted_binaries = true,
671 "--duplicate-exports" => self.duplicate_exports = true,
672 "--duplicate-export-aliases" => self.duplicate_export_aliases = true,
673 "--circular-deps" => self.circular_deps = true,
674 "--re-export-cycles" => self.re_export_cycles = true,
675 "--package-cycles" => self.package_cycles = true,
676 "--boundary-violations" => self.boundary_violations = true,
677 "--policy-violations" => self.policy_violations = true,
678 "--stale-suppressions" => self.stale_suppressions = true,
679 "--unused-catalog-entries" => self.unused_catalog_entries = true,
680 "--empty-catalog-groups" => self.empty_catalog_groups = true,
681 "--unresolved-catalog-references" => self.unresolved_catalog_references = true,
682 "--unused-dependency-overrides" => self.unused_dependency_overrides = true,
683 "--misconfigured-dependency-overrides" => {
684 self.misconfigured_dependency_overrides = true;
685 }
686 _ => unreachable!("registry emitted unsupported dead-code filter flag: {flag}"),
687 }
688 }
689}
690
691#[derive(Debug, Clone, Default)]
693pub struct DeadCodeOptions {
694 pub analysis: AnalysisOptions,
696 pub filters: DeadCodeFilters,
698 pub files: Vec<PathBuf>,
700 pub include_entry_exports: bool,
702 pub show_cascade: bool,
704 pub finding_ids: Vec<String>,
709}
710
711#[derive(Debug, Clone, Default)]
717pub struct ArchitectureOptions {
718 pub shared_state: bool,
720 pub analysis: AnalysisOptions,
722 pub files: Vec<PathBuf>,
724 pub cycles: bool,
727 pub boundaries: bool,
729 pub policy: bool,
731}
732
733impl ArchitectureOptions {
734 #[must_use]
736 pub fn dead_code_filters(&self) -> DeadCodeFilters {
737 let all = !(self.cycles || self.boundaries || self.policy || self.shared_state);
738 DeadCodeFilters {
739 shared_state: self.shared_state,
740 circular_deps: self.cycles || all,
741 re_export_cycles: self.cycles || all,
742 package_cycles: self.cycles || all,
743 boundary_violations: self.boundaries || all,
744 policy_violations: self.policy || all,
745 ..DeadCodeFilters::default()
746 }
747 }
748
749 pub(crate) fn requested_flags(&self) -> Vec<&'static str> {
752 fallow_engine::requested_rule_off::architecture_requested_flags(
753 self.cycles,
754 self.boundaries,
755 self.policy,
756 )
757 }
758
759 #[must_use]
761 pub fn dead_code_options(&self) -> DeadCodeOptions {
762 DeadCodeOptions {
763 analysis: self.analysis.clone(),
764 filters: self.dead_code_filters(),
765 files: self.files.clone(),
766 include_entry_exports: false,
767 show_cascade: false,
768 finding_ids: Vec::new(),
769 }
770 }
771}
772
773#[derive(Debug, Clone, Default)]
775pub struct AuditOptions {
776 pub analysis: AnalysisOptions,
778 pub base: Option<String>,
781 pub production: bool,
783 pub production_dead_code: Option<bool>,
785 pub production_health: Option<bool>,
787 pub production_dupes: Option<bool>,
790 pub dead_code: Option<bool>,
794 pub health: Option<bool>,
797 pub duplication: Option<bool>,
800 pub css: Option<bool>,
803 pub css_deep: Option<bool>,
806 pub gate: Option<fallow_config::AuditGate>,
809 pub worsened: Option<fallow_config::AuditWorsened>,
812 pub max_crap: Option<f64>,
814 pub coverage: Option<PathBuf>,
816 pub coverage_root: Option<PathBuf>,
818 pub include_entry_exports: bool,
820 pub show_cascade: bool,
822 pub runtime_coverage: Option<PathBuf>,
824 pub min_invocations_hot: u64,
826}
827
828#[derive(Debug, Clone)]
830pub struct CombinedOptions {
831 pub analysis: AnalysisOptions,
833 pub production_dead_code: Option<bool>,
837 pub production_health: Option<bool>,
839 pub production_dupes: Option<bool>,
842 pub dead_code: bool,
844 pub duplication: bool,
846 pub health: bool,
848 pub include_entry_exports: bool,
850 pub show_cascade: bool,
852 pub duplication_options: DuplicationOptions,
854 pub health_options: ComplexityOptions,
856}
857
858impl Default for CombinedOptions {
859 fn default() -> Self {
860 Self {
861 analysis: AnalysisOptions::default(),
862 production_dead_code: None,
863 production_health: None,
864 production_dupes: None,
865 dead_code: true,
866 duplication: true,
867 health: true,
868 include_entry_exports: false,
869 show_cascade: false,
870 duplication_options: DuplicationOptions::default(),
871 health_options: ComplexityOptions::default(),
872 }
873 }
874}
875
876#[derive(Debug, Clone, Default)]
878pub struct DecisionSurfaceOptions {
879 pub analysis: AnalysisOptions,
881 pub base: Option<String>,
884 pub max_decisions: Option<usize>,
886}
887
888#[derive(Debug, Clone, Default)]
890pub struct FeatureFlagsOptions {
891 pub analysis: AnalysisOptions,
893 pub top: Option<usize>,
896 pub retirement: Option<FeatureFlagsRetirementOptions>,
898}
899
900#[derive(Debug, Clone, Default)]
903pub struct FeatureFlagsRetirementOptions {
904 pub flag_age: fallow_types::flag_retirement::FlagAgeMode,
906 pub flag_state: Option<std::path::PathBuf>,
908 pub reasons: Vec<fallow_types::flag_retirement::RetirementReason>,
910 pub sort: fallow_engine::flag_retirement::RetirementSort,
912 pub min_age_days: Option<u64>,
914 pub max_flag_age: Option<u64>,
916}
917
918#[derive(Debug, Clone, Copy, Default)]
920pub enum DuplicationMode {
921 Strict,
924 #[default]
926 Mild,
927 Weak,
929 Semantic,
932}
933
934#[derive(Debug, Clone, Default)]
936pub struct DuplicationOptions {
937 pub analysis: AnalysisOptions,
939 pub mode: Option<DuplicationMode>,
941 pub near: Option<bool>,
944 pub min_tokens: Option<usize>,
946 pub min_lines: Option<usize>,
948 pub min_occurrences: Option<usize>,
951 pub threshold: Option<f64>,
954 pub skip_local: Option<bool>,
957 pub ignore_symlinks: Option<bool>,
960 pub cross_language: Option<bool>,
962 pub ignore_imports: Option<bool>,
965 pub top: Option<usize>,
967 pub include_fragments: Option<bool>,
971}
972
973#[derive(Debug, Clone, Default)]
975pub struct SimilarCodeOptions {
976 pub analysis: AnalysisOptions,
978 pub threshold: Option<f64>,
980 pub min_lines: Option<usize>,
983 pub top: Option<usize>,
985 pub files: Vec<PathBuf>,
989 #[doc(hidden)]
994 pub adapter_provider_path: Option<PathBuf>,
995}
996
997#[derive(Debug, Clone)]
999pub struct SimilarCodeInspectOptions {
1000 pub analysis: AnalysisOptions,
1003 pub snapshot: fallow_output::SimilarCodeCandidateSnapshot,
1005}
1006
1007#[derive(Debug, Clone, Default)]
1009pub struct TraceExportOptions {
1010 pub analysis: AnalysisOptions,
1012 pub file: String,
1014 pub export_name: String,
1016}
1017
1018#[derive(Debug, Clone, Default)]
1020pub struct TraceFileOptions {
1021 pub analysis: AnalysisOptions,
1023 pub file: String,
1025}
1026
1027#[derive(Debug, Clone, Default)]
1029pub struct TraceImportPathOptions {
1030 pub analysis: AnalysisOptions,
1032 pub from: String,
1034 pub to: String,
1036 pub eager_only: bool,
1039}
1040
1041#[derive(Debug, Clone, Default)]
1043pub struct TraceErrorOptions {
1044 pub analysis: AnalysisOptions,
1046 pub trace: String,
1048 pub source: String,
1050}
1051
1052#[derive(Debug, Clone, Default)]
1054pub struct TraceDependencyOptions {
1055 pub analysis: AnalysisOptions,
1057 pub package_name: String,
1059 pub usage: Option<DependencyUsageQuery>,
1062}
1063
1064#[derive(Debug, Clone, PartialEq, Eq)]
1066pub enum TraceCloneTarget {
1067 Location {
1069 file: String,
1071 line: usize,
1073 },
1074 Fingerprint(String),
1076}
1077
1078#[derive(Debug, Clone)]
1080pub struct TraceCloneOptions {
1081 pub duplication: DuplicationOptions,
1083 pub target: TraceCloneTarget,
1085}
1086
1087#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1089pub enum ComplexitySort {
1090 #[default]
1092 Cyclomatic,
1093 Cognitive,
1095 Lines,
1097 Severity,
1099}
1100
1101#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1103pub enum OwnershipEmailMode {
1104 Raw,
1106 #[default]
1108 Handle,
1109 Anonymized,
1111 Hash,
1113}
1114
1115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1117pub enum TargetEffort {
1118 Low,
1120 Medium,
1122 High,
1124}
1125
1126#[derive(Debug, Clone, Default)]
1128pub struct ComplexityOptions {
1129 pub analysis: AnalysisOptions,
1131 pub max_cyclomatic: Option<u16>,
1133 pub max_cognitive: Option<u16>,
1135 pub max_crap: Option<f64>,
1137 pub max_file_lines: Option<u32>,
1140 pub top: Option<usize>,
1142 pub sort: ComplexitySort,
1144 pub complexity_breakdown: bool,
1146 pub complexity: bool,
1148 pub file_scores: bool,
1150 pub coverage_gaps: bool,
1152 pub config_activates_coverage_gaps: bool,
1157 pub hotspots: bool,
1159 pub ownership: bool,
1161 pub ownership_emails: Option<OwnershipEmailMode>,
1163 pub targets: bool,
1165 pub css: bool,
1167 pub css_deep: bool,
1169 pub effort: Option<TargetEffort>,
1172 pub score: bool,
1174 pub since: Option<String>,
1176 pub min_commits: Option<u32>,
1178 pub coverage: Option<PathBuf>,
1180 pub coverage_root: Option<PathBuf>,
1182 pub coverage_relocated: bool,
1187}
1188
1189#[derive(Debug, Clone, Copy, Default, PartialEq)]
1191pub struct ComplexityThresholdOverrides {
1192 pub max_cyclomatic: Option<u16>,
1194 pub max_cognitive: Option<u16>,
1196 pub max_crap: Option<f64>,
1198 pub max_file_lines: Option<u32>,
1200}
1201
1202#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1204pub struct ComplexityCoverageInputs<'a> {
1205 pub coverage: Option<&'a Path>,
1207 pub coverage_root: Option<&'a Path>,
1209 pub coverage_relocated: bool,
1212}
1213
1214#[derive(Debug, Clone)]
1216pub struct HealthSectionOptions {
1217 pub output: fallow_types::output_format::OutputFormat,
1219 pub complexity: bool,
1221 pub file_scores: bool,
1223 pub coverage_gaps: bool,
1225 pub hotspots: bool,
1227 pub targets: bool,
1229 pub css: bool,
1231 pub score: bool,
1233 pub score_gate: bool,
1235 pub snapshot_requested: bool,
1237 pub trend: bool,
1239}
1240
1241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1243pub struct DerivedHealthSections {
1244 pub any_section: bool,
1246 pub complexity: bool,
1248 pub file_scores: bool,
1250 pub coverage_gaps: bool,
1252 pub hotspots: bool,
1254 pub targets: bool,
1256 pub css: bool,
1258 pub score: bool,
1260 pub force_full: bool,
1262 pub score_only_output: bool,
1264}
1265
1266#[derive(Debug, Clone)]
1268pub struct ComplexitySectionOptions {
1269 pub complexity: bool,
1271 pub file_scores: bool,
1273 pub coverage_gaps: bool,
1275 pub hotspots: bool,
1277 pub ownership: bool,
1279 pub targets: bool,
1281 pub css: bool,
1283 pub score: bool,
1285}
1286
1287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1289pub struct DerivedComplexityOptions {
1290 pub any_section: bool,
1292 pub complexity: bool,
1294 pub file_scores: bool,
1296 pub coverage_gaps: bool,
1298 pub hotspots: bool,
1300 pub ownership: bool,
1302 pub targets: bool,
1304 pub force_full: bool,
1306 pub score_only_output: bool,
1308 pub score: bool,
1310}
1311
1312#[derive(Debug, Clone, PartialEq)]
1314pub struct ComplexityRunOptions<'a> {
1315 pub thresholds: ComplexityThresholdOverrides,
1317 pub top: Option<usize>,
1319 pub sort: ComplexitySort,
1321 pub complexity_breakdown: bool,
1323 pub sections: DerivedComplexityOptions,
1325 pub ownership_emails: Option<OwnershipEmailMode>,
1327 pub effort: Option<TargetEffort>,
1329 pub css: bool,
1331 pub css_deep: bool,
1333 pub since: Option<&'a str>,
1335 pub min_commits: Option<u32>,
1337 pub coverage_inputs: ComplexityCoverageInputs<'a>,
1339}
1340
1341pub fn configure_global_analysis_pool(threads: usize) -> bool {
1350 fallow_engine::thread_pool::worker_pool_builder(threads)
1351 .build_global()
1352 .is_ok()
1353}
1354
1355#[must_use]
1357pub fn derive_health_sections(options: &HealthSectionOptions) -> DerivedHealthSections {
1358 let score = options.score
1359 || options.score_gate
1360 || options.trend
1361 || matches!(
1362 options.output,
1363 fallow_types::output_format::OutputFormat::Badge
1364 );
1365 let any_section = options.complexity
1366 || options.file_scores
1367 || options.coverage_gaps
1368 || options.hotspots
1369 || options.targets
1370 || score;
1371 let effective_score = if any_section { score } else { true } || options.snapshot_requested;
1372 let force_full = options.snapshot_requested || effective_score;
1373
1374 DerivedHealthSections {
1375 any_section,
1376 complexity: if any_section {
1377 options.complexity
1378 } else {
1379 true
1380 },
1381 file_scores: if any_section {
1382 options.file_scores
1383 } else {
1384 true
1385 } || force_full,
1386 coverage_gaps: if any_section {
1387 options.coverage_gaps
1388 } else {
1389 false
1390 },
1391 hotspots: if any_section { options.hotspots } else { true }
1392 || options.snapshot_requested
1393 || options.trend,
1394 targets: if any_section { options.targets } else { true },
1395 css: options.css,
1396 score: effective_score,
1397 force_full,
1398 score_only_output: is_health_score_only_output(options, score),
1399 }
1400}
1401
1402#[must_use]
1404pub fn derive_complexity_sections(options: &ComplexitySectionOptions) -> DerivedComplexityOptions {
1405 let requested_hotspots = options.hotspots || options.ownership;
1406 let sections = derive_health_sections(&HealthSectionOptions {
1407 output: fallow_types::output_format::OutputFormat::Human,
1408 complexity: options.complexity,
1409 file_scores: options.file_scores,
1410 coverage_gaps: options.coverage_gaps,
1411 hotspots: requested_hotspots,
1412 targets: options.targets,
1413 css: options.css,
1414 score: options.score,
1415 score_gate: false,
1416 snapshot_requested: false,
1417 trend: false,
1418 });
1419
1420 DerivedComplexityOptions {
1421 any_section: sections.any_section,
1422 complexity: sections.complexity,
1423 file_scores: sections.file_scores,
1424 coverage_gaps: sections.coverage_gaps,
1425 hotspots: sections.hotspots,
1426 ownership: options.ownership && sections.hotspots,
1427 targets: sections.targets,
1428 force_full: sections.force_full,
1429 score_only_output: sections.score_only_output,
1430 score: sections.score,
1431 }
1432}
1433
1434#[must_use]
1436pub fn derive_complexity_options(options: &ComplexityOptions) -> DerivedComplexityOptions {
1437 derive_complexity_sections(&complexity_section_options(options))
1438}
1439
1440#[must_use]
1442pub fn derive_complexity_run_options(options: &ComplexityOptions) -> ComplexityRunOptions<'_> {
1443 ComplexityRunOptions {
1444 thresholds: ComplexityThresholdOverrides {
1445 max_cyclomatic: options.max_cyclomatic,
1446 max_cognitive: options.max_cognitive,
1447 max_crap: options.max_crap,
1448 max_file_lines: options.max_file_lines,
1449 },
1450 top: options.top,
1451 sort: options.sort,
1452 complexity_breakdown: options.complexity_breakdown,
1453 sections: derive_complexity_options(options),
1454 ownership_emails: options.ownership_emails,
1455 effort: options.effort,
1456 css: options.css,
1457 css_deep: options.css_deep,
1458 since: options.since.as_deref(),
1459 min_commits: options.min_commits,
1460 coverage_inputs: ComplexityCoverageInputs {
1461 coverage: options.coverage.as_deref(),
1462 coverage_root: options.coverage_root.as_deref(),
1463 coverage_relocated: options.coverage_relocated,
1464 },
1465 }
1466}
1467
1468pub fn validate_complexity_options(options: &ComplexityOptions) -> Result<(), ProgrammaticError> {
1491 if let Some(path) = &options.coverage {
1492 let resolved = fallow_engine::health::scoring::resolve_relative_to_root(
1493 path,
1494 options.analysis.root.as_deref(),
1495 );
1496 if !resolved.exists() {
1497 return Err(ProgrammaticError::new(
1498 format!("coverage path does not exist: {}", resolved.display()),
1499 2,
1500 )
1501 .with_code("FALLOW_INVALID_COVERAGE_PATH")
1502 .with_context("health.coverage"));
1503 }
1504 }
1505 if let Err(message) =
1506 fallow_engine::health::validate_coverage_root_absolute(options.coverage_root.as_deref())
1507 {
1508 return Err(ProgrammaticError::new(message, 2)
1509 .with_code("FALLOW_INVALID_COVERAGE_ROOT")
1510 .with_context("health.coverage_root"));
1511 }
1512
1513 Ok(())
1514}
1515
1516fn complexity_section_options(options: &ComplexityOptions) -> ComplexitySectionOptions {
1517 let ownership = options.ownership || options.ownership_emails.is_some();
1518 let requested_targets = options.targets || options.effort.is_some();
1519 ComplexitySectionOptions {
1520 complexity: options.complexity,
1521 file_scores: options.file_scores,
1522 coverage_gaps: options.coverage_gaps,
1523 hotspots: options.hotspots,
1524 ownership,
1525 targets: requested_targets,
1526 css: options.css,
1527 score: options.score,
1528 }
1529}
1530
1531fn is_health_score_only_output(options: &HealthSectionOptions, score: bool) -> bool {
1532 score
1533 && !options.complexity
1534 && !options.file_scores
1535 && !options.coverage_gaps
1536 && !options.hotspots
1537 && !options.targets
1538 && !options.trend
1539}
1540
1541const fn thresholds_to_engine(
1542 thresholds: ComplexityThresholdOverrides,
1543) -> fallow_engine::health::HealthThresholdOverrides {
1544 fallow_engine::health::HealthThresholdOverrides {
1545 max_cyclomatic: thresholds.max_cyclomatic,
1546 max_cognitive: thresholds.max_cognitive,
1547 max_crap: thresholds.max_crap,
1548 max_file_lines: thresholds.max_file_lines,
1549 }
1550}
1551
1552const fn complexity_sort_to_engine(sort: ComplexitySort) -> fallow_engine::health::HealthSort {
1553 match sort {
1554 ComplexitySort::Severity => fallow_engine::health::HealthSort::Severity,
1555 ComplexitySort::Cyclomatic => fallow_engine::health::HealthSort::Cyclomatic,
1556 ComplexitySort::Cognitive => fallow_engine::health::HealthSort::Cognitive,
1557 ComplexitySort::Lines => fallow_engine::health::HealthSort::Lines,
1558 }
1559}
1560
1561const fn coverage_inputs_to_engine(
1562 coverage_inputs: ComplexityCoverageInputs<'_>,
1563) -> fallow_engine::health::HealthCoverageInputs<'_> {
1564 fallow_engine::health::HealthCoverageInputs {
1565 coverage: coverage_inputs.coverage,
1566 coverage_root: coverage_inputs.coverage_root,
1567 coverage_relocated: coverage_inputs.coverage_relocated,
1568 }
1569}
1570
1571const fn ownership_email_mode_to_config(mode: OwnershipEmailMode) -> EmailMode {
1572 match mode {
1573 OwnershipEmailMode::Raw => EmailMode::Raw,
1574 OwnershipEmailMode::Handle => EmailMode::Handle,
1575 OwnershipEmailMode::Anonymized => EmailMode::Anonymized,
1576 OwnershipEmailMode::Hash => EmailMode::Hash,
1577 }
1578}
1579
1580const fn target_effort_to_output(effort: TargetEffort) -> EffortEstimate {
1581 match effort {
1582 TargetEffort::Low => EffortEstimate::Low,
1583 TargetEffort::Medium => EffortEstimate::Medium,
1584 TargetEffort::High => EffortEstimate::High,
1585 }
1586}
1587
1588#[cfg(test)]
1589mod tests {
1590 use super::*;
1591
1592 #[test]
1593 fn duplication_defaults_match_cli_contract() {
1594 let options = DuplicationOptions::default();
1595 assert!(options.mode.is_none());
1596 assert!(options.min_tokens.is_none());
1597 assert!(options.min_lines.is_none());
1598 assert!(options.min_occurrences.is_none());
1599 }
1600
1601 #[test]
1602 fn programmatic_error_builder_keeps_optional_fields() {
1603 let error = ProgrammaticError::new("boom", 2)
1604 .with_code("FALLOW_TEST")
1605 .with_help("Try again")
1606 .with_context("analysis.root");
1607
1608 assert_eq!(error.message, "boom");
1609 assert_eq!(error.exit_code, 2);
1610 assert_eq!(error.code.as_deref(), Some("FALLOW_TEST"));
1611 assert_eq!(error.help.as_deref(), Some("Try again"));
1612 assert_eq!(error.context.as_deref(), Some("analysis.root"));
1613 }
1614
1615 #[test]
1616 fn dead_code_filters_accept_shared_registry_selectors() {
1617 for (selector, _) in fallow_types::issue_meta::MCP_ISSUE_TYPE_FLAGS.iter() {
1618 let mut filters = DeadCodeFilters::default();
1619 assert!(
1620 filters.enable_registry_selector(selector),
1621 "{selector} should be accepted"
1622 );
1623 }
1624
1625 let mut filters = DeadCodeFilters::default();
1626 assert!(filters.enable_registry_selector("unused-files"));
1627 assert!(filters.unused_files);
1628 assert!(filters.enable_registry_selector("boundary-violations"));
1629 assert!(filters.boundary_violations);
1630 assert!(!filters.enable_registry_selector("not-a-real-selector"));
1631 }
1632
1633 #[test]
1634 fn default_complexity_options_match_programmatic_health_defaults() {
1635 let derived = derive_complexity_options(&ComplexityOptions::default());
1636
1637 assert!(!derived.any_section);
1638 assert!(derived.complexity);
1639 assert!(derived.file_scores);
1640 assert!(!derived.coverage_gaps);
1641 assert!(derived.hotspots);
1642 assert!(!derived.ownership);
1643 assert!(derived.targets);
1644 assert!(derived.force_full);
1645 assert!(!derived.score_only_output);
1646 assert!(derived.score);
1647 }
1648
1649 #[test]
1650 fn score_only_complexity_options_request_score_only_output() {
1651 let derived = derive_complexity_options(&ComplexityOptions {
1652 score: true,
1653 ..ComplexityOptions::default()
1654 });
1655
1656 assert!(derived.any_section);
1657 assert!(!derived.complexity);
1658 assert!(derived.file_scores);
1659 assert!(!derived.hotspots);
1660 assert!(!derived.targets);
1661 assert!(derived.force_full);
1662 assert!(derived.score_only_output);
1663 assert!(derived.score);
1664 }
1665
1666 #[test]
1667 fn ownership_implies_hotspots_when_requested() {
1668 let derived = derive_complexity_options(&ComplexityOptions {
1669 ownership: true,
1670 ..ComplexityOptions::default()
1671 });
1672
1673 assert!(derived.any_section);
1674 assert!(derived.hotspots);
1675 assert!(derived.ownership);
1676 assert!(!derived.targets);
1677 }
1678
1679 #[test]
1680 fn complexity_run_options_normalize_public_api_options() {
1681 let options = ComplexityOptions {
1682 max_cyclomatic: Some(42),
1683 max_cognitive: Some(21),
1684 max_crap: Some(18.5),
1685 top: Some(7),
1686 sort: ComplexitySort::Severity,
1687 complexity_breakdown: true,
1688 ownership_emails: Some(OwnershipEmailMode::Hash),
1689 effort: Some(TargetEffort::High),
1690 coverage: Some(PathBuf::from("coverage/coverage-final.json")),
1691 coverage_root: Some(PathBuf::from("/ci/workspace")),
1692 since: Some("30d".to_string()),
1693 min_commits: Some(4),
1694 ..ComplexityOptions::default()
1695 };
1696
1697 let run = derive_complexity_run_options(&options);
1698
1699 assert_eq!(run.thresholds.max_cyclomatic, Some(42));
1700 assert_eq!(run.thresholds.max_cognitive, Some(21));
1701 assert_eq!(run.thresholds.max_crap, Some(18.5));
1702 assert_eq!(run.top, Some(7));
1703 assert!(matches!(run.sort, ComplexitySort::Severity));
1704 assert!(run.complexity_breakdown);
1705 assert!(run.sections.hotspots);
1706 assert!(run.sections.ownership);
1707 assert!(run.sections.targets);
1708 assert!(matches!(
1709 run.ownership_emails,
1710 Some(OwnershipEmailMode::Hash)
1711 ));
1712 assert!(matches!(run.effort, Some(TargetEffort::High)));
1713 assert_eq!(run.since, Some("30d"));
1714 assert_eq!(run.min_commits, Some(4));
1715 assert_eq!(run.coverage_inputs.coverage, options.coverage.as_deref());
1716 assert_eq!(
1717 run.coverage_inputs.coverage_root,
1718 options.coverage_root.as_deref()
1719 );
1720 }
1721
1722 #[test]
1723 fn complexity_options_validation_accepts_existing_coverage_path_and_absolute_root() {
1724 let dir = tempfile::tempdir().expect("tempdir");
1725 let coverage = dir.path().join("coverage-final.json");
1726 std::fs::write(&coverage, "{}").expect("coverage fixture");
1727
1728 let result = validate_complexity_options(&ComplexityOptions {
1729 coverage: Some(coverage),
1730 coverage_root: Some(PathBuf::from("/ci/workspace")),
1731 ..ComplexityOptions::default()
1732 });
1733
1734 assert!(result.is_ok());
1735 }
1736
1737 #[test]
1738 fn complexity_options_validation_keeps_missing_coverage_error_contract() {
1739 let err = validate_complexity_options(&ComplexityOptions {
1740 coverage: Some(PathBuf::from("/missing/coverage-final.json")),
1741 ..ComplexityOptions::default()
1742 })
1743 .expect_err("missing coverage path should fail");
1744
1745 assert_eq!(err.exit_code, 2);
1746 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1747 assert_eq!(err.context.as_deref(), Some("health.coverage"));
1748 }
1749
1750 #[test]
1751 fn complexity_options_validation_keeps_relative_coverage_root_error_contract() {
1752 let err = validate_complexity_options(&ComplexityOptions {
1753 coverage_root: Some(PathBuf::from("coverage")),
1754 ..ComplexityOptions::default()
1755 })
1756 .expect_err("relative coverage root should fail");
1757
1758 assert_eq!(err.exit_code, 2);
1759 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_ROOT"));
1760 assert_eq!(err.context.as_deref(), Some("health.coverage_root"));
1761 }
1762
1763 #[test]
1767 fn complexity_options_validation_resolves_relative_coverage_against_root() {
1768 let dir = tempfile::tempdir().expect("tempdir");
1769 std::fs::create_dir_all(dir.path().join("artifacts")).expect("artifacts dir");
1770 std::fs::write(dir.path().join("artifacts/coverage-final.json"), "{}")
1771 .expect("coverage fixture");
1772 let relative = PathBuf::from("artifacts/coverage-final.json");
1773 assert!(
1774 !relative.exists(),
1775 "the fixture must not also exist under the test cwd"
1776 );
1777
1778 let result = validate_complexity_options(&ComplexityOptions {
1779 analysis: AnalysisOptions {
1780 root: Some(dir.path().to_path_buf()),
1781 ..AnalysisOptions::default()
1782 },
1783 coverage: Some(relative.clone()),
1784 ..ComplexityOptions::default()
1785 });
1786 assert!(result.is_ok(), "{result:?}");
1787
1788 let err = validate_complexity_options(&ComplexityOptions {
1789 analysis: AnalysisOptions {
1790 root: Some(dir.path().join("elsewhere")),
1791 ..AnalysisOptions::default()
1792 },
1793 coverage: Some(relative),
1794 ..ComplexityOptions::default()
1795 })
1796 .expect_err("the path does not exist under the other root");
1797 assert_eq!(err.code.as_deref(), Some("FALLOW_INVALID_COVERAGE_PATH"));
1798 assert!(
1799 err.message.contains("elsewhere"),
1800 "the message names the resolved path: {}",
1801 err.message
1802 );
1803 }
1804
1805 #[test]
1806 fn default_health_sections_match_full_health_output() {
1807 let derived = derive_health_sections(&HealthSectionOptions {
1808 output: fallow_types::output_format::OutputFormat::Human,
1809 complexity: false,
1810 file_scores: false,
1811 coverage_gaps: false,
1812 hotspots: false,
1813 targets: false,
1814 css: false,
1815 score: false,
1816 score_gate: false,
1817 snapshot_requested: false,
1818 trend: false,
1819 });
1820
1821 assert!(!derived.any_section);
1822 assert!(derived.complexity);
1823 assert!(derived.file_scores);
1824 assert!(!derived.coverage_gaps);
1825 assert!(derived.hotspots);
1826 assert!(derived.targets);
1827 assert!(derived.score);
1828 assert!(derived.force_full);
1829 assert!(!derived.score_only_output);
1830 }
1831
1832 #[test]
1833 fn health_score_gate_requests_score_only_output() {
1834 let derived = derive_health_sections(&HealthSectionOptions {
1835 output: fallow_types::output_format::OutputFormat::Human,
1836 complexity: false,
1837 file_scores: false,
1838 coverage_gaps: false,
1839 hotspots: false,
1840 targets: false,
1841 css: false,
1842 score: false,
1843 score_gate: true,
1844 snapshot_requested: false,
1845 trend: false,
1846 });
1847
1848 assert!(derived.any_section);
1849 assert!(!derived.complexity);
1850 assert!(derived.file_scores);
1851 assert!(!derived.hotspots);
1852 assert!(!derived.targets);
1853 assert!(derived.score);
1854 assert!(derived.force_full);
1855 assert!(derived.score_only_output);
1856 }
1857
1858 #[test]
1859 fn health_snapshot_keeps_full_hidden_inputs_without_section_request() {
1860 let derived = derive_health_sections(&HealthSectionOptions {
1861 output: fallow_types::output_format::OutputFormat::Human,
1862 complexity: false,
1863 file_scores: false,
1864 coverage_gaps: false,
1865 hotspots: false,
1866 targets: false,
1867 css: true,
1868 score: false,
1869 score_gate: false,
1870 snapshot_requested: true,
1871 trend: false,
1872 });
1873
1874 assert!(!derived.any_section);
1875 assert!(derived.css);
1876 assert!(derived.file_scores);
1877 assert!(derived.hotspots);
1878 assert!(derived.score);
1879 assert!(derived.force_full);
1880 }
1881}
1882
1883mod shared_state_explain;