Skip to main content

fallow_cli/
explain.rs

1//! Metric and rule definitions for explainable CLI output.
2//!
3//! Provides structured metadata that describes what each metric, threshold,
4//! and rule means — consumed by the `_meta` object in JSON output and by
5//! SARIF `fullDescription` / `helpUri` fields.
6
7use std::process::ExitCode;
8
9use colored::Colorize;
10use fallow_config::OutputFormat;
11use serde_json::{Value, json};
12
13// ── Docs base URL ────────────────────────────────────────────────
14
15const DOCS_BASE: &str = "https://docs.fallow.tools";
16
17/// Docs URL for the dead-code (check) command.
18pub const CHECK_DOCS: &str = "https://docs.fallow.tools/cli/dead-code";
19
20/// Docs URL for the health command.
21pub const HEALTH_DOCS: &str = "https://docs.fallow.tools/cli/health";
22
23/// Docs URL for the dupes command.
24pub const DUPES_DOCS: &str = "https://docs.fallow.tools/cli/dupes";
25
26/// Docs URL for the runtime coverage setup command's agent-readable JSON.
27pub const COVERAGE_SETUP_DOCS: &str = "https://docs.fallow.tools/cli/coverage#agent-readable-json";
28
29/// Docs URL for `fallow coverage analyze --format json --explain`.
30pub const COVERAGE_ANALYZE_DOCS: &str = "https://docs.fallow.tools/cli/coverage#analyze";
31
32// ── Check rules ─────────────────────────────────────────────────
33
34/// Rule definition for SARIF `fullDescription` and JSON `_meta`.
35pub struct RuleDef {
36    pub id: &'static str,
37    pub name: &'static str,
38    pub short: &'static str,
39    pub full: &'static str,
40    pub docs_path: &'static str,
41}
42
43pub const CHECK_RULES: &[RuleDef] = &[
44    RuleDef {
45        id: "fallow/unused-file",
46        name: "Unused Files",
47        short: "File is not reachable from any entry point",
48        full: "Source files that are not imported by any other module and are not entry points (scripts, tests, configs). These files can safely be deleted. Detection uses graph reachability from configured entry points.",
49        docs_path: "explanations/dead-code#unused-files",
50    },
51    RuleDef {
52        id: "fallow/unused-export",
53        name: "Unused Exports",
54        short: "Export is never imported",
55        full: "Named exports that are never imported by any other module in the project. Includes both direct exports and re-exports through barrel files. The export may still be used locally within the same file.",
56        docs_path: "explanations/dead-code#unused-exports",
57    },
58    RuleDef {
59        id: "fallow/unused-type",
60        name: "Unused Type Exports",
61        short: "Type export is never imported",
62        full: "Type-only exports (interfaces, type aliases, enums used only as types) that are never imported. These do not generate runtime code but add maintenance burden.",
63        docs_path: "explanations/dead-code#unused-types",
64    },
65    RuleDef {
66        id: "fallow/private-type-leak",
67        name: "Private Type Leaks",
68        short: "Exported signature references a private type",
69        full: "Exported values or types whose public TypeScript signature references a same-file type declaration that is not exported. Consumers cannot name that private type directly, so the backing type should be exported or removed from the public signature.",
70        docs_path: "explanations/dead-code#private-type-leaks",
71    },
72    RuleDef {
73        id: "fallow/unused-dependency",
74        name: "Unused Dependencies",
75        short: "Dependency listed but never imported",
76        full: "Packages listed in dependencies that are never imported or required by any source file. Framework plugins and CLI tools may be false positives — use the ignore_dependencies config to suppress.",
77        docs_path: "explanations/dead-code#unused-dependencies",
78    },
79    RuleDef {
80        id: "fallow/unused-dev-dependency",
81        name: "Unused Dev Dependencies",
82        short: "Dev dependency listed but never imported",
83        full: "Packages listed in devDependencies that are never imported by test files, config files, or scripts. Build tools and jest presets that are referenced only in config may appear as false positives.",
84        docs_path: "explanations/dead-code#unused-devdependencies",
85    },
86    RuleDef {
87        id: "fallow/unused-optional-dependency",
88        name: "Unused Optional Dependencies",
89        short: "Optional dependency listed but never imported",
90        full: "Packages listed in optionalDependencies that are never imported. Optional dependencies are typically platform-specific — verify they are not needed on any supported platform before removing.",
91        docs_path: "explanations/dead-code#unused-optionaldependencies",
92    },
93    RuleDef {
94        id: "fallow/type-only-dependency",
95        name: "Type-only Dependencies",
96        short: "Production dependency only used via type-only imports",
97        full: "Production dependencies that are only imported via `import type` statements. These can be moved to devDependencies since they generate no runtime code and are stripped during compilation.",
98        docs_path: "explanations/dead-code#type-only-dependencies",
99    },
100    RuleDef {
101        id: "fallow/test-only-dependency",
102        name: "Test-only Dependencies",
103        short: "Production dependency only imported by test files",
104        full: "Production dependencies that are only imported from test files. These can usually move to devDependencies because production entry points do not require them at runtime.",
105        docs_path: "explanations/dead-code#test-only-dependencies",
106    },
107    RuleDef {
108        id: "fallow/unused-enum-member",
109        name: "Unused Enum Members",
110        short: "Enum member is never referenced",
111        full: "Enum members that are never referenced in the codebase. Uses scope-aware binding analysis to track all references including computed access patterns.",
112        docs_path: "explanations/dead-code#unused-enum-members",
113    },
114    RuleDef {
115        id: "fallow/unused-class-member",
116        name: "Unused Class Members",
117        short: "Class member is never referenced",
118        full: "Class methods and properties that are never referenced outside the class. Private members are checked within the class scope; public members are checked project-wide.",
119        docs_path: "explanations/dead-code#unused-class-members",
120    },
121    RuleDef {
122        id: "fallow/unresolved-import",
123        name: "Unresolved Imports",
124        short: "Import could not be resolved",
125        full: "Import specifiers that could not be resolved to a file on disk. Common causes: deleted files, typos in paths, missing path aliases in tsconfig, or uninstalled packages.",
126        docs_path: "explanations/dead-code#unresolved-imports",
127    },
128    RuleDef {
129        id: "fallow/unlisted-dependency",
130        name: "Unlisted Dependencies",
131        short: "Dependency used but not in package.json",
132        full: "Packages that are imported in source code but not listed in package.json. These work by accident (hoisted from another workspace package or transitive dep) and will break in strict package managers.",
133        docs_path: "explanations/dead-code#unlisted-dependencies",
134    },
135    RuleDef {
136        id: "fallow/duplicate-export",
137        name: "Duplicate Exports",
138        short: "Export name appears in multiple modules",
139        full: "The same export name is defined in multiple modules. Consumers may import from the wrong module, leading to subtle bugs. Consider renaming or consolidating.",
140        docs_path: "explanations/dead-code#duplicate-exports",
141    },
142    RuleDef {
143        id: "fallow/circular-dependency",
144        name: "Circular Dependencies",
145        short: "Circular dependency chain detected",
146        full: "A cycle in the module import graph. Circular dependencies cause undefined behavior with CommonJS (partial modules) and initialization ordering issues with ESM. Break cycles by extracting shared code.",
147        docs_path: "explanations/dead-code#circular-dependencies",
148    },
149    RuleDef {
150        id: "fallow/boundary-violation",
151        name: "Boundary Violations",
152        short: "Import crosses a configured architecture boundary",
153        full: "A module imports from a zone that its configured boundary rules do not allow. Boundary checks help keep layered architecture, feature slices, and package ownership rules enforceable.",
154        docs_path: "explanations/dead-code#boundary-violations",
155    },
156    RuleDef {
157        id: "fallow/stale-suppression",
158        name: "Stale Suppressions",
159        short: "Suppression comment or tag no longer matches any issue",
160        full: "A fallow-ignore-next-line, fallow-ignore-file, or @expected-unused suppression that no longer matches any active issue. The underlying problem was fixed but the suppression was left behind. Remove it to keep the codebase clean.",
161        docs_path: "explanations/dead-code#stale-suppressions",
162    },
163];
164
165/// Look up a rule definition by its SARIF rule ID across all rule sets.
166#[must_use]
167pub fn rule_by_id(id: &str) -> Option<&'static RuleDef> {
168    CHECK_RULES
169        .iter()
170        .chain(HEALTH_RULES.iter())
171        .chain(DUPES_RULES.iter())
172        .find(|r| r.id == id)
173}
174
175/// Build the docs URL for a rule.
176#[must_use]
177pub fn rule_docs_url(rule: &RuleDef) -> String {
178    format!("{DOCS_BASE}/{}", rule.docs_path)
179}
180
181/// Extra educational content for the standalone `fallow explain <issue-type>`
182/// command. Kept separate from [`RuleDef`] so SARIF and `_meta` payloads remain
183/// compact while terminal users and agents can ask for worked examples on
184/// demand.
185pub struct RuleGuide {
186    pub example: &'static str,
187    pub how_to_fix: &'static str,
188}
189
190/// Look up an issue type from a user-facing token.
191///
192/// Accepts canonical SARIF ids (`fallow/unused-export`), issue tokens
193/// (`unused-export`), and common CLI filter spellings (`unused-exports`).
194#[must_use]
195pub fn rule_by_token(token: &str) -> Option<&'static RuleDef> {
196    let trimmed = token.trim();
197    if trimmed.is_empty() {
198        return None;
199    }
200    if let Some(rule) = rule_by_id(trimmed) {
201        return Some(rule);
202    }
203    let normalized = trimmed
204        .strip_prefix("fallow/")
205        .unwrap_or(trimmed)
206        .trim_start_matches("--")
207        .replace('_', "-");
208    let alias = match normalized.as_str() {
209        "unused-files" => Some("fallow/unused-file"),
210        "unused-exports" => Some("fallow/unused-export"),
211        "unused-types" => Some("fallow/unused-type"),
212        "private-type-leaks" => Some("fallow/private-type-leak"),
213        "unused-deps" | "unused-dependencies" => Some("fallow/unused-dependency"),
214        "unused-dev-deps" | "unused-dev-dependencies" => Some("fallow/unused-dev-dependency"),
215        "unused-optional-deps" | "unused-optional-dependencies" => {
216            Some("fallow/unused-optional-dependency")
217        }
218        "type-only-deps" | "type-only-dependencies" => Some("fallow/type-only-dependency"),
219        "test-only-deps" | "test-only-dependencies" => Some("fallow/test-only-dependency"),
220        "unused-enum-members" => Some("fallow/unused-enum-member"),
221        "unused-class-members" => Some("fallow/unused-class-member"),
222        "unresolved-imports" => Some("fallow/unresolved-import"),
223        "unlisted-deps" | "unlisted-dependencies" => Some("fallow/unlisted-dependency"),
224        "duplicate-exports" => Some("fallow/duplicate-export"),
225        "circular-deps" | "circular-dependencies" => Some("fallow/circular-dependency"),
226        "boundary-violations" => Some("fallow/boundary-violation"),
227        "stale-suppressions" => Some("fallow/stale-suppression"),
228        "complexity" | "high-complexity" => Some("fallow/high-complexity"),
229        "cyclomatic" | "high-cyclomatic" | "high-cyclomatic-complexity" => {
230            Some("fallow/high-cyclomatic-complexity")
231        }
232        "cognitive" | "high-cognitive" | "high-cognitive-complexity" => {
233            Some("fallow/high-cognitive-complexity")
234        }
235        "crap" | "high-crap" | "high-crap-score" => Some("fallow/high-crap-score"),
236        "duplication" | "dupes" | "code-duplication" => Some("fallow/code-duplication"),
237        _ => None,
238    };
239    if let Some(id) = alias
240        && let Some(rule) = rule_by_id(id)
241    {
242        return Some(rule);
243    }
244    let singular = normalized
245        .strip_suffix('s')
246        .filter(|_| normalized != "unused-class")
247        .unwrap_or(&normalized);
248    let id = format!("fallow/{singular}");
249    rule_by_id(&id).or_else(|| {
250        CHECK_RULES
251            .iter()
252            .chain(HEALTH_RULES.iter())
253            .chain(DUPES_RULES.iter())
254            .find(|rule| {
255                rule.docs_path.ends_with(&normalized)
256                    || rule.docs_path.ends_with(singular)
257                    || rule.name.eq_ignore_ascii_case(trimmed)
258            })
259    })
260}
261
262/// Return worked-example and fix guidance for a rule.
263#[must_use]
264pub fn rule_guide(rule: &RuleDef) -> RuleGuide {
265    match rule.id {
266        "fallow/unused-file" => RuleGuide {
267            example: "src/old-widget.ts is not imported by any entry point, route, script, or config file.",
268            how_to_fix: "Delete the file if it is genuinely dead. If a framework loads it implicitly, add the right plugin/config pattern or mark it in alwaysUsed.",
269        },
270        "fallow/unused-export" => RuleGuide {
271            example: "export const formatPrice = ... exists in src/money.ts, but no module imports formatPrice.",
272            how_to_fix: "Remove the export or make it file-local. If it is public API, import it from an entry point or add an intentional suppression with context.",
273        },
274        "fallow/unused-type" => RuleGuide {
275            example: "export interface LegacyProps is exported, but no module imports the type.",
276            how_to_fix: "Remove the type export, inline it, or keep it behind an explicit API entry point when consumers rely on it.",
277        },
278        "fallow/private-type-leak" => RuleGuide {
279            example: "export function makeUser(): InternalUser exposes InternalUser even though InternalUser is not exported.",
280            how_to_fix: "Export the referenced type, change the public signature to an exported type, or keep the helper private.",
281        },
282        "fallow/unused-dependency"
283        | "fallow/unused-dev-dependency"
284        | "fallow/unused-optional-dependency" => RuleGuide {
285            example: "package.json lists left-pad, but no source, script, config, or plugin-recognized file imports it.",
286            how_to_fix: "Remove the dependency after checking runtime/plugin usage. If another workspace uses it, move the dependency to that workspace.",
287        },
288        "fallow/type-only-dependency" => RuleGuide {
289            example: "zod is in dependencies but only appears in import type declarations.",
290            how_to_fix: "Move the package to devDependencies unless runtime code imports it as a value.",
291        },
292        "fallow/test-only-dependency" => RuleGuide {
293            example: "vitest is listed in dependencies, but only test files import it.",
294            how_to_fix: "Move the package to devDependencies unless production code imports it at runtime.",
295        },
296        "fallow/unused-enum-member" => RuleGuide {
297            example: "Status.Legacy remains in an exported enum, but no code reads that member.",
298            how_to_fix: "Remove the member after checking serialized/API compatibility, or suppress it with a reason when external data still uses it.",
299        },
300        "fallow/unused-class-member" => RuleGuide {
301            example: "class Parser has a public parseLegacy method that is never called in the project.",
302            how_to_fix: "Remove or privatize the member. For reflection/framework lifecycle hooks, configure or suppress the intentional entry point.",
303        },
304        "fallow/unresolved-import" => RuleGuide {
305            example: "src/app.ts imports ./routes/admin, but no matching file exists after extension and index resolution.",
306            how_to_fix: "Fix the specifier, restore the missing file, install the package, or align tsconfig path aliases with the runtime resolver.",
307        },
308        "fallow/unlisted-dependency" => RuleGuide {
309            example: "src/api.ts imports undici, but the nearest package.json does not list undici.",
310            how_to_fix: "Add the package to dependencies/devDependencies in the workspace that imports it instead of relying on hoisting or transitive deps.",
311        },
312        "fallow/duplicate-export" => RuleGuide {
313            example: "Button is exported from both src/ui/button.ts and src/components/button.ts.",
314            how_to_fix: "Rename or consolidate the exports so consumers have one intentional import target.",
315        },
316        "fallow/circular-dependency" => RuleGuide {
317            example: "src/a.ts imports src/b.ts, and src/b.ts imports src/a.ts.",
318            how_to_fix: "Extract shared code to a third module, invert the dependency, or split initialization-time side effects from type-only contracts.",
319        },
320        "fallow/boundary-violation" => RuleGuide {
321            example: "features/billing imports app/admin even though the configured boundary only allows imports from shared and entities.",
322            how_to_fix: "Move the shared contract to an allowed zone, invert the dependency, or update the boundary config only if the architecture rule was wrong.",
323        },
324        "fallow/stale-suppression" => RuleGuide {
325            example: "// fallow-ignore-next-line unused-export remains above an export that is now used.",
326            how_to_fix: "Remove the suppression. If a different issue is still intentional, replace it with a current, specific suppression.",
327        },
328        "fallow/high-cyclomatic-complexity"
329        | "fallow/high-cognitive-complexity"
330        | "fallow/high-complexity" => RuleGuide {
331            example: "A function contains several nested conditionals, loops, and early exits, exceeding the configured complexity threshold.",
332            how_to_fix: "Extract named helpers, split independent branches, flatten guard clauses, and add tests around the behavior before refactoring.",
333        },
334        "fallow/high-crap-score" => RuleGuide {
335            example: "A complex function has little or no matching Istanbul coverage, so its CRAP score crosses the configured gate.",
336            how_to_fix: "Add focused tests for the risky branches first, then simplify the function if the score remains high.",
337        },
338        "fallow/refactoring-target" => RuleGuide {
339            example: "A file combines high complexity density, churn, fan-in, and dead-code signals.",
340            how_to_fix: "Start with the listed evidence: remove dead exports, extract complex functions, then reduce fan-out or cycles in small steps.",
341        },
342        "fallow/untested-file" | "fallow/untested-export" => RuleGuide {
343            example: "Production-reachable code has no dependency path from discovered test entry points.",
344            how_to_fix: "Add or wire a test that imports the runtime path, or update entry-point/test discovery if the existing test is invisible to fallow.",
345        },
346        "fallow/runtime-safe-to-delete"
347        | "fallow/runtime-review-required"
348        | "fallow/runtime-low-traffic"
349        | "fallow/runtime-coverage-unavailable"
350        | "fallow/runtime-coverage" => RuleGuide {
351            example: "Runtime coverage shows a function was never called, barely called, or could not be matched during the capture window.",
352            how_to_fix: "Treat high-confidence cold static-dead code as delete candidates. For advisory or unavailable coverage, inspect seasonality, workers, source maps, and capture quality first.",
353        },
354        "fallow/code-duplication" => RuleGuide {
355            example: "Two files contain the same normalized token sequence across a multi-line block.",
356            how_to_fix: "Extract the shared logic when the duplicated behavior should evolve together. Leave it duplicated when the similarity is accidental and likely to diverge.",
357        },
358        _ => RuleGuide {
359            example: "Run the relevant command with --format json --quiet --explain to inspect this rule in context.",
360            how_to_fix: "Use the issue action hints, source location, and docs URL to decide whether to remove, move, configure, or suppress the finding.",
361        },
362    }
363}
364
365/// Run the standalone explain subcommand.
366#[must_use]
367pub fn run_explain(issue_type: &str, output: OutputFormat) -> ExitCode {
368    let Some(rule) = rule_by_token(issue_type) else {
369        return crate::error::emit_error(
370            &format!(
371                "unknown issue type '{issue_type}'. Try values like unused-export, unused-dependency, high-complexity, or code-duplication"
372            ),
373            2,
374            output,
375        );
376    };
377    let guide = rule_guide(rule);
378    match output {
379        OutputFormat::Json => crate::report::emit_json(
380            &json!({
381                "id": rule.id,
382                "name": rule.name,
383                "summary": rule.short,
384                "rationale": rule.full,
385                "example": guide.example,
386                "how_to_fix": guide.how_to_fix,
387                "docs": rule_docs_url(rule),
388            }),
389            "explain",
390        ),
391        OutputFormat::Human => print_explain_human(rule, &guide),
392        OutputFormat::Compact => print_explain_compact(rule),
393        OutputFormat::Markdown => print_explain_markdown(rule, &guide),
394        OutputFormat::Sarif | OutputFormat::CodeClimate | OutputFormat::Badge => {
395            crate::error::emit_error(
396                "explain supports human, compact, markdown, and json output",
397                2,
398                output,
399            )
400        }
401    }
402}
403
404fn print_explain_human(rule: &RuleDef, guide: &RuleGuide) -> ExitCode {
405    println!("{}", rule.name.bold());
406    println!("{}", rule.id.dimmed());
407    println!();
408    println!("{}", rule.short);
409    println!();
410    println!("{}", "Why it matters".bold());
411    println!("{}", rule.full);
412    println!();
413    println!("{}", "Example".bold());
414    println!("{}", guide.example);
415    println!();
416    println!("{}", "How to fix".bold());
417    println!("{}", guide.how_to_fix);
418    println!();
419    println!("{} {}", "Docs:".dimmed(), rule_docs_url(rule).dimmed());
420    ExitCode::SUCCESS
421}
422
423fn print_explain_compact(rule: &RuleDef) -> ExitCode {
424    println!("explain:{}:{}:{}", rule.id, rule.short, rule_docs_url(rule));
425    ExitCode::SUCCESS
426}
427
428fn print_explain_markdown(rule: &RuleDef, guide: &RuleGuide) -> ExitCode {
429    println!("# {}", rule.name);
430    println!();
431    println!("`{}`", rule.id);
432    println!();
433    println!("{}", rule.short);
434    println!();
435    println!("## Why it matters");
436    println!();
437    println!("{}", rule.full);
438    println!();
439    println!("## Example");
440    println!();
441    println!("{}", guide.example);
442    println!();
443    println!("## How to fix");
444    println!();
445    println!("{}", guide.how_to_fix);
446    println!();
447    println!("[Docs]({})", rule_docs_url(rule));
448    ExitCode::SUCCESS
449}
450
451// ── Health SARIF rules ──────────────────────────────────────────
452
453pub const HEALTH_RULES: &[RuleDef] = &[
454    RuleDef {
455        id: "fallow/high-cyclomatic-complexity",
456        name: "High Cyclomatic Complexity",
457        short: "Function has high cyclomatic complexity",
458        full: "McCabe cyclomatic complexity exceeds the configured threshold. Cyclomatic complexity counts the number of independent paths through a function (1 + decision points: if/else, switch cases, loops, ternary, logical operators). High values indicate functions that are hard to test exhaustively.",
459        docs_path: "explanations/health#cyclomatic-complexity",
460    },
461    RuleDef {
462        id: "fallow/high-cognitive-complexity",
463        name: "High Cognitive Complexity",
464        short: "Function has high cognitive complexity",
465        full: "SonarSource cognitive complexity exceeds the configured threshold. Unlike cyclomatic complexity, cognitive complexity penalizes nesting depth and non-linear control flow (breaks, continues, early returns). It measures how hard a function is to understand when reading sequentially.",
466        docs_path: "explanations/health#cognitive-complexity",
467    },
468    RuleDef {
469        id: "fallow/high-complexity",
470        name: "High Complexity (Both)",
471        short: "Function exceeds both complexity thresholds",
472        full: "Function exceeds both cyclomatic and cognitive complexity thresholds. This is the strongest signal that a function needs refactoring, it has many paths AND is hard to understand.",
473        docs_path: "explanations/health#complexity-metrics",
474    },
475    RuleDef {
476        id: "fallow/high-crap-score",
477        name: "High CRAP Score",
478        short: "Function has a high CRAP score (complexity combined with low coverage)",
479        full: "The function's CRAP (Change Risk Anti-Patterns) score meets or exceeds the configured threshold. CRAP combines cyclomatic complexity with test coverage using the Savoia and Evans (2007) formula: `CC^2 * (1 - coverage/100)^3 + CC`. High CRAP indicates changes to this function carry high risk because it is complex AND poorly tested. Pair with `--coverage` for accurate per-function scoring; without it fallow estimates coverage from the module graph.",
480        docs_path: "explanations/health#crap-score",
481    },
482    RuleDef {
483        id: "fallow/refactoring-target",
484        name: "Refactoring Target",
485        short: "File identified as a high-priority refactoring candidate",
486        full: "File identified as a refactoring candidate based on a weighted combination of complexity density, churn velocity, dead code ratio, fan-in (blast radius), and fan-out (coupling). Categories: urgent churn+complexity, break circular dependency, split high-impact file, remove dead code, extract complex functions, reduce coupling.",
487        docs_path: "explanations/health#refactoring-targets",
488    },
489    RuleDef {
490        id: "fallow/untested-file",
491        name: "Untested File",
492        short: "Runtime-reachable file has no test dependency path",
493        full: "A file is reachable from runtime entry points but not from any discovered test entry point. This indicates production code that no test imports, directly or transitively, according to the static module graph.",
494        docs_path: "explanations/health#coverage-gaps",
495    },
496    RuleDef {
497        id: "fallow/untested-export",
498        name: "Untested Export",
499        short: "Runtime-reachable export has no test dependency path",
500        full: "A value export is reachable from runtime entry points but no test-reachable module references it. This is a static test dependency gap rather than line coverage, and highlights exports exercised only through production entry paths.",
501        docs_path: "explanations/health#coverage-gaps",
502    },
503    RuleDef {
504        id: "fallow/runtime-safe-to-delete",
505        name: "Production Safe To Delete",
506        short: "Statically unused AND never invoked in production with V8 tracking",
507        full: "The function is both statically unreachable in the module graph and was never invoked during the observed runtime coverage window. This is the highest-confidence delete signal fallow emits.",
508        docs_path: "explanations/health#runtime-coverage",
509    },
510    RuleDef {
511        id: "fallow/runtime-review-required",
512        name: "Production Review Required",
513        short: "Statically used but never invoked in production",
514        full: "The function is reachable in the module graph (or exercised by tests / untracked call sites) but was not invoked during the observed runtime coverage window. Needs a human look — may be seasonal, error-path only, or legitimately unused.",
515        docs_path: "explanations/health#runtime-coverage",
516    },
517    RuleDef {
518        id: "fallow/runtime-low-traffic",
519        name: "Production Low Traffic",
520        short: "Function was invoked below the low-traffic threshold",
521        full: "The function was invoked in production but below the configured `--low-traffic-threshold` fraction of total trace count (spec default 0.1%). Effectively dead for the current period.",
522        docs_path: "explanations/health#runtime-coverage",
523    },
524    RuleDef {
525        id: "fallow/runtime-coverage-unavailable",
526        name: "Runtime Coverage Unavailable",
527        short: "Runtime coverage could not be resolved for this function",
528        full: "The function could not be matched to a V8-tracked coverage entry. Common causes: the function lives in a worker thread (separate V8 isolate), it is lazy-parsed and never reached the JIT tier, or its source map did not resolve to the expected source path. This is advisory, not a dead-code signal.",
529        docs_path: "explanations/health#runtime-coverage",
530    },
531    RuleDef {
532        id: "fallow/runtime-coverage",
533        name: "Runtime Coverage",
534        short: "Runtime coverage finding",
535        full: "Generic runtime-coverage finding for verdicts not covered by a more specific rule. Covers the forward-compat `unknown` sentinel; the CLI filters `active` entries out of `runtime_coverage.findings` so the surfaced list stays actionable.",
536        docs_path: "explanations/health#runtime-coverage",
537    },
538];
539
540pub const DUPES_RULES: &[RuleDef] = &[RuleDef {
541    id: "fallow/code-duplication",
542    name: "Code Duplication",
543    short: "Duplicated code block",
544    full: "A block of code that appears in multiple locations with identical or near-identical token sequences. Clone detection uses normalized token comparison — identifier names and literals are abstracted away in non-strict modes.",
545    docs_path: "explanations/duplication#clone-groups",
546}];
547
548// ── JSON _meta builders ─────────────────────────────────────────
549
550/// Build the `_meta` object for `fallow dead-code --format json --explain`.
551#[must_use]
552pub fn check_meta() -> Value {
553    let rules: Value = CHECK_RULES
554        .iter()
555        .map(|r| {
556            (
557                r.id.replace("fallow/", ""),
558                json!({
559                    "name": r.name,
560                    "description": r.full,
561                    "docs": rule_docs_url(r)
562                }),
563            )
564        })
565        .collect::<serde_json::Map<String, Value>>()
566        .into();
567
568    json!({
569        "docs": CHECK_DOCS,
570        "rules": rules
571    })
572}
573
574/// Build the `_meta` object for `fallow health --format json --explain`.
575#[must_use]
576#[expect(
577    clippy::too_many_lines,
578    reason = "flat metric table: every entry is 3-4 short lines of metadata and keeping them in one map is clearer than splitting into per-metric helpers"
579)]
580pub fn health_meta() -> Value {
581    json!({
582        "docs": HEALTH_DOCS,
583        "metrics": {
584            "cyclomatic": {
585                "name": "Cyclomatic Complexity",
586                "description": "McCabe cyclomatic complexity: 1 + number of decision points (if/else, switch cases, loops, ternary, logical operators). Measures the number of independent paths through a function.",
587                "range": "[1, \u{221e})",
588                "interpretation": "lower is better; default threshold: 20"
589            },
590            "cognitive": {
591                "name": "Cognitive Complexity",
592                "description": "SonarSource cognitive complexity: penalizes nesting depth and non-linear control flow (breaks, continues, early returns). Measures how hard a function is to understand when reading top-to-bottom.",
593                "range": "[0, \u{221e})",
594                "interpretation": "lower is better; default threshold: 15"
595            },
596            "line_count": {
597                "name": "Function Line Count",
598                "description": "Number of lines in the function body.",
599                "range": "[1, \u{221e})",
600                "interpretation": "context-dependent; long functions may need splitting"
601            },
602            "lines": {
603                "name": "File Line Count",
604                "description": "Total lines of code in the file (from line offsets). Provides scale context for other metrics: a file with 0.4 complexity density at 80 LOC is different from 0.4 density at 800 LOC.",
605                "range": "[1, \u{221e})",
606                "interpretation": "context-dependent; large files may benefit from splitting even if individual functions are small"
607            },
608            "maintainability_index": {
609                "name": "Maintainability Index",
610                "description": "Composite score: 100 - (complexity_density \u{00d7} 30 \u{00d7} dampening) - (dead_code_ratio \u{00d7} 20) - min(ln(fan_out+1) \u{00d7} 4, 15), where dampening = min(lines/50, 1.0). Clamped to [0, 100]. Higher is better.",
611                "range": "[0, 100]",
612                "interpretation": "higher is better; <40 poor, 40\u{2013}70 moderate, >70 good"
613            },
614            "complexity_density": {
615                "name": "Complexity Density",
616                "description": "Total cyclomatic complexity divided by lines of code. Measures how densely complex the code is per line.",
617                "range": "[0, \u{221e})",
618                "interpretation": "lower is better; >1.0 indicates very dense complexity"
619            },
620            "dead_code_ratio": {
621                "name": "Dead Code Ratio",
622                "description": "Fraction of value exports (excluding type-only exports like interfaces and type aliases) with zero references across the project.",
623                "range": "[0, 1]",
624                "interpretation": "lower is better; 0 = all exports are used"
625            },
626            "fan_in": {
627                "name": "Fan-in (Importers)",
628                "description": "Number of files that import this file. High fan-in means high blast radius \u{2014} changes to this file affect many dependents.",
629                "range": "[0, \u{221e})",
630                "interpretation": "context-dependent; high fan-in files need careful review before changes"
631            },
632            "fan_out": {
633                "name": "Fan-out (Imports)",
634                "description": "Number of files this file directly imports. High fan-out indicates high coupling and change propagation risk.",
635                "range": "[0, \u{221e})",
636                "interpretation": "lower is better; MI penalty caps at ~40 imports"
637            },
638            "score": {
639                "name": "Hotspot Score",
640                "description": "normalized_churn \u{00d7} normalized_complexity \u{00d7} 100, where normalization is against the project maximum. Identifies files that are both complex AND frequently changing.",
641                "range": "[0, 100]",
642                "interpretation": "higher = riskier; prioritize refactoring high-score files"
643            },
644            "weighted_commits": {
645                "name": "Weighted Commits",
646                "description": "Recency-weighted commit count using exponential decay with 90-day half-life. Recent commits contribute more than older ones.",
647                "range": "[0, \u{221e})",
648                "interpretation": "higher = more recent churn activity"
649            },
650            "trend": {
651                "name": "Churn Trend",
652                "description": "Compares recent vs older commit frequency within the analysis window. accelerating = recent > 1.5\u{00d7} older, cooling = recent < 0.67\u{00d7} older, stable = in between.",
653                "values": ["accelerating", "stable", "cooling"],
654                "interpretation": "accelerating files need attention; cooling files are stabilizing"
655            },
656            "priority": {
657                "name": "Refactoring Priority",
658                "description": "Weighted score: complexity density (30%), hotspot boost (25%), dead code ratio (20%), fan-in (15%), fan-out (10%). Fan-in and fan-out normalization uses adaptive percentile-based thresholds (p95 of the project distribution). Does not use the maintainability index to avoid double-counting.",
659                "range": "[0, 100]",
660                "interpretation": "higher = more urgent to refactor"
661            },
662            "efficiency": {
663                "name": "Efficiency Score",
664                "description": "priority / effort_numeric (Low=1, Medium=2, High=3). Surfaces quick wins: high-priority, low-effort targets rank first. Default sort order.",
665                "range": "[0, 100] \u{2014} effective max depends on effort: Low=100, Medium=50, High\u{2248}33",
666                "interpretation": "higher = better quick-win value; targets are sorted by efficiency descending"
667            },
668            "effort": {
669                "name": "Effort Estimate",
670                "description": "Heuristic effort estimate based on file size, function count, and fan-in. Thresholds adapt to the project\u{2019}s distribution (percentile-based). Low: small file, few functions, low fan-in. High: large file, high fan-in, or many functions with high density. Medium: everything else.",
671                "values": ["low", "medium", "high"],
672                "interpretation": "low = quick win, high = needs planning and coordination"
673            },
674            "confidence": {
675                "name": "Confidence Level",
676                "description": "Reliability of the recommendation based on data source. High: deterministic graph/AST analysis (dead code, circular deps, complexity). Medium: heuristic thresholds (fan-in/fan-out coupling). Low: depends on git history quality (churn-based recommendations).",
677                "values": ["high", "medium", "low"],
678                "interpretation": "high = act on it, medium = verify context, low = treat as a signal, not a directive"
679            },
680            "health_score": {
681                "name": "Health Score",
682                "description": "Project-level aggregate score computed from vital signs: dead code, complexity, maintainability, hotspots, unused dependencies, and circular dependencies. Penalties subtracted from 100. Missing metrics (from pipelines that didn't run) don't penalize. Use --score to compute the score; add --hotspots, or --targets with --score, when the score should include the churn-backed hotspot penalty.",
683                "range": "[0, 100]",
684                "interpretation": "higher is better; A (85\u{2013}100), B (70\u{2013}84), C (55\u{2013}69), D (40\u{2013}54), F (0\u{2013}39)"
685            },
686            "crap_max": {
687                "name": "Untested Complexity Risk (CRAP)",
688                "description": "Change Risk Anti-Patterns score (Savoia & Evans, 2007). Formula: CC\u{00b2} \u{00d7} (1 - cov/100)\u{00b3} + CC. Default model (static_estimated): estimates per-function coverage from export references \u{2014} directly test-referenced exports get 85%, indirectly test-reachable functions get 40%, untested files get 0%. Provide --coverage <path> with Istanbul-format coverage-final.json (from Jest, Vitest, c8, nyc) for exact per-function CRAP scores.",
689                "range": "[1, \u{221e})",
690                "interpretation": "lower is better; >=30 is high-risk (CC >= 5 without test path)"
691            },
692            "bus_factor": {
693                "name": "Bus Factor",
694                "description": "Avelino truck factor: the minimum number of distinct contributors who together account for at least 50% of recency-weighted commits to this file in the analysis window. Bot authors are excluded.",
695                "range": "[1, \u{221e})",
696                "interpretation": "lower is higher knowledge-loss risk; 1 means a single contributor covers most of the recent history"
697            },
698            "contributor_count": {
699                "name": "Contributor Count",
700                "description": "Number of distinct authors who touched this file in the analysis window after bot-pattern filtering.",
701                "range": "[0, \u{221e})",
702                "interpretation": "higher generally indicates broader knowledge spread; pair with bus_factor for context"
703            },
704            "share": {
705                "name": "Contributor Share",
706                "description": "Recency-weighted share of total weighted commits attributed to a single contributor. Rounded to three decimals.",
707                "range": "[0, 1]",
708                "interpretation": "share close to 1.0 indicates dominance and pairs with low bus_factor"
709            },
710            "stale_days": {
711                "name": "Stale Days",
712                "description": "Days since this contributor last touched the file. Computed at analysis time.",
713                "range": "[0, \u{221e})",
714                "interpretation": "high stale_days on the top contributor often correlates with ownership drift"
715            },
716            "drift": {
717                "name": "Ownership Drift",
718                "description": "True when the file's original author (earliest first commit in the window) differs from the current top contributor, the file is at least 30 days old, and the original author's recency-weighted share is below 10%.",
719                "values": [true, false],
720                "interpretation": "true means the original author is no longer maintaining; route reviews to the current top contributor"
721            },
722            "unowned": {
723                "name": "Unowned (Tristate)",
724                "description": "true = a CODEOWNERS file exists but no rule matches this file; false = a rule matches; null = no CODEOWNERS file was discovered for the repository (cannot determine).",
725                "values": [true, false, null],
726                "interpretation": "true on a hotspot is a review-bottleneck risk; null means the signal is unavailable, not absent"
727            },
728            "runtime_coverage_verdict": {
729                "name": "Runtime Coverage Verdict",
730                "description": "Overall verdict across all runtime-coverage findings. `clean` = nothing cold; `cold-code-detected` = one or more tracked functions had zero invocations; `hot-path-changes-needed` = a function modified in the current change set is on the hot path; `license-expired-grace` = analysis ran but the license is in its post-expiry grace window; `unknown` = verdict could not be computed (degenerate input).",
731                "values": ["clean", "hot-path-changes-needed", "cold-code-detected", "license-expired-grace", "unknown"],
732                "interpretation": "`cold-code-detected` is the primary actionable signal; `hot-path-changes-needed` elevates code-review attention for touched hot paths"
733            },
734            "runtime_coverage_state": {
735                "name": "Runtime Coverage State",
736                "description": "Per-function observation: `called` = V8 saw at least one invocation; `never-called` = V8 tracked the function but it never ran; `coverage-unavailable` = the function was not in the V8 tracking set (e.g., lazy-parsed, worker thread, dynamic code); `unknown` = forward-compat sentinel for newer sidecar states.",
737                "values": ["called", "never-called", "coverage-unavailable", "unknown"],
738                "interpretation": "`never-called` in combination with static `unused` is the highest-confidence delete signal"
739            },
740            "runtime_coverage_confidence": {
741                "name": "Runtime Coverage Confidence",
742                "description": "Confidence in a runtime-coverage finding. `high` = tracked by V8 with a statistically meaningful observation volume; `medium` = either low observation volume or indirect evidence; `low` = minimal data; `unknown` = insufficient information to classify.",
743                "values": ["high", "medium", "low", "unknown"],
744                "interpretation": "high = act on it; medium = verify context; low = treat as a signal only"
745            },
746            "production_invocations": {
747                "name": "Production Invocations",
748                "description": "Observed invocation count for the function over the collected coverage window. For `coverage-unavailable` findings this is `0` and semantically means `null` (not tracked). Absolute counts are not directly comparable across services without normalizing by trace_count.",
749                "range": "[0, \u{221e})",
750                "interpretation": "0 + tracked = cold path; 0 + untracked = unknown; high + never-called cannot occur by definition"
751            },
752            "percent_dead_in_production": {
753                "name": "Percent Dead in Production",
754                "description": "Fraction of tracked functions with zero observed invocations, multiplied by 100. Computed before any `--top` truncation so the summary total is stable regardless of display limits.",
755                "range": "[0, 100]",
756                "interpretation": "lower is better; values above ~10% on a long-running service indicate a large cleanup opportunity"
757            }
758        }
759    })
760}
761
762/// Build the `_meta` object for `fallow dupes --format json --explain`.
763#[must_use]
764pub fn dupes_meta() -> Value {
765    json!({
766        "docs": DUPES_DOCS,
767        "metrics": {
768            "duplication_percentage": {
769                "name": "Duplication Percentage",
770                "description": "Fraction of total source tokens that appear in at least one clone group. Computed over the full analyzed file set.",
771                "range": "[0, 100]",
772                "interpretation": "lower is better"
773            },
774            "token_count": {
775                "name": "Token Count",
776                "description": "Number of normalized source tokens in the clone group. Tokens are language-aware (keywords, identifiers, operators, punctuation). Higher token count = larger duplicate.",
777                "range": "[1, \u{221e})",
778                "interpretation": "larger clones have higher refactoring value"
779            },
780            "line_count": {
781                "name": "Line Count",
782                "description": "Number of source lines spanned by the clone instance. Approximation of clone size for human readability.",
783                "range": "[1, \u{221e})",
784                "interpretation": "larger clones are more impactful to deduplicate"
785            },
786            "clone_groups": {
787                "name": "Clone Groups",
788                "description": "A set of code fragments with identical or near-identical normalized token sequences. Each group has 2+ instances across different locations.",
789                "interpretation": "each group is a single refactoring opportunity"
790            },
791            "clone_families": {
792                "name": "Clone Families",
793                "description": "Groups of clone groups that share the same set of files. Indicates systematic duplication patterns (e.g., mirrored directory structures).",
794                "interpretation": "families suggest extract-module refactoring opportunities"
795            }
796        }
797    })
798}
799
800/// Build the `_meta` object for `fallow coverage setup --json --explain`.
801#[must_use]
802pub fn coverage_setup_meta() -> Value {
803    json!({
804        "docs_url": COVERAGE_SETUP_DOCS,
805        "field_definitions": {
806            "schema_version": "Coverage setup JSON contract version. Stays at \"1\" for additive opt-in fields such as _meta.",
807            "framework_detected": "Primary detected runtime framework for compatibility with single-app consumers. In workspaces this mirrors the first emitted runtime member; unknown means no runtime member was detected.",
808            "package_manager": "Detected package manager used for install and run commands, or null when no package manager signal was found.",
809            "runtime_targets": "Union of runtime targets across emitted members.",
810            "members[]": "Per-runtime-workspace setup recipes. Pure aggregator roots and build-only libraries are omitted.",
811            "members[].name": "Workspace package name from package.json, or the root directory name when package.json has no name.",
812            "members[].path": "Workspace path relative to the command root. The root package is represented as \".\".",
813            "members[].framework_detected": "Runtime framework detected for that member.",
814            "members[].package_manager": "Package manager detected for that member, or inherited from the workspace root when no member-specific signal exists.",
815            "members[].runtime_targets": "Runtime targets produced by that member.",
816            "members[].files_to_edit": "Files in that member that should receive runtime beacon setup code.",
817            "members[].snippets": "Copy-paste setup snippets for that member, with paths relative to the command root.",
818            "members[].dockerfile_snippet": "Environment snippet for file-system capture in that member's containerized Node runtime, or null when not applicable.",
819            "members[].warnings": "Actionable setup caveats discovered for that member.",
820            "config_written": "Always null for --json because JSON setup is side-effect-free and never writes configuration.",
821            "files_to_edit": "Compatibility copy of the primary member's files, with workspace prefixes when the primary member is not the root.",
822            "snippets": "Compatibility copy of the primary member's snippets, with workspace prefixes when the primary member is not the root.",
823            "dockerfile_snippet": "Environment snippet for file-system capture in containerized Node runtimes, or null when not applicable.",
824            "commands": "Package-manager commands needed to install the runtime beacon and sidecar packages.",
825            "next_steps": "Ordered setup workflow after applying the emitted snippets.",
826            "warnings": "Actionable setup caveats discovered while building the recipe."
827        },
828        "enums": {
829            "framework_detected": ["nextjs", "nestjs", "nuxt", "sveltekit", "astro", "remix", "vite", "plain_node", "unknown"],
830            "runtime_targets": ["node", "browser"],
831            "package_manager": ["npm", "pnpm", "yarn", "bun", null]
832        },
833        "warnings": {
834            "No runtime workspace members were detected": "The root appears to be a workspace, but no runtime-bearing package was found. The payload emits install commands only.",
835            "No local coverage artifact was detected yet": "Run the application with runtime coverage collection enabled, then re-run setup or health with the produced capture path.",
836            "Package manager was not detected": "No packageManager field or known lockfile was found. Commands fall back to npm.",
837            "Framework was not detected": "No known framework dependency or runtime script was found. Treat the recipe as a generic Node setup and adjust the entry path as needed."
838        }
839    })
840}
841
842/// Build the `_meta` object for `fallow coverage analyze --format json --explain`.
843#[must_use]
844pub fn coverage_analyze_meta() -> Value {
845    json!({
846        "docs_url": COVERAGE_ANALYZE_DOCS,
847        "field_definitions": {
848            "schema_version": "Standalone coverage analyze envelope version. \"1\" for the current shape.",
849            "version": "fallow CLI version that produced this output.",
850            "elapsed_ms": "Wall-clock milliseconds spent producing the report.",
851            "runtime_coverage": "Same RuntimeCoverageReport block emitted by `fallow health --runtime-coverage`.",
852            "runtime_coverage.summary.data_source": "Which evidence source produced the report. local = on-disk artifact via --runtime-coverage <path>; cloud = explicit pull via --cloud / --runtime-coverage-cloud / FALLOW_RUNTIME_COVERAGE_SOURCE=cloud.",
853            "runtime_coverage.summary.last_received_at": "ISO-8601 timestamp of the newest runtime payload included in the report. Null for local artifacts that do not carry receipt metadata.",
854            "runtime_coverage.summary.capture_quality": "Capture-window telemetry derived from the runtime evidence. lazy_parse_warning trips when more than 30% of tracked functions are V8-untracked, which usually indicates a short observation window.",
855            "runtime_coverage.findings[].evidence.static_status": "used = the function is reachable in the AST module graph; unused = it is dead by static analysis.",
856            "runtime_coverage.findings[].evidence.test_coverage": "covered = the local test suite hits the function; not_covered otherwise.",
857            "runtime_coverage.findings[].evidence.v8_tracking": "tracked = V8 observed the function during the capture window; untracked otherwise.",
858            "runtime_coverage.findings[].actions[].type": "Suggested follow-up identifier. delete-cold-code is emitted on safe_to_delete; review-runtime on review_required.",
859            "runtime_coverage.blast_radius[]": "First-class blast-radius entries with stable fallow:blast IDs, static caller count, traffic-weighted caller reach, optional cloud deploy touch count, and low/medium/high risk band.",
860            "runtime_coverage.importance[]": "First-class production-importance entries with stable fallow:importance IDs, invocations, cyclomatic complexity, owner count, 0-100 importance score, and templated reason.",
861            "runtime_coverage.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally."
862        },
863        "enums": {
864            "data_source": ["local", "cloud"],
865            "report_verdict": ["clean", "hot-path-changes-needed", "cold-code-detected", "license-expired-grace", "unknown"],
866            "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
867            "static_status": ["used", "unused"],
868            "test_coverage": ["covered", "not_covered"],
869            "v8_tracking": ["tracked", "untracked"],
870            "action_type": ["delete-cold-code", "review-runtime"]
871        },
872        "warnings": {
873            "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
874            "cloud_functions_unmatched": "One or more cloud-side functions could not be matched against the local AST/static index and were dropped from findings. Common causes: stale runtime data after a rename/move, file path mismatch between deploy and repo, or analysis run on the wrong commit."
875        }
876    })
877}
878
879#[cfg(test)]
880mod tests {
881    use super::*;
882
883    // ── rule_by_id ───────────────────────────────────────────────────
884
885    #[test]
886    fn rule_by_id_finds_check_rule() {
887        let rule = rule_by_id("fallow/unused-file").unwrap();
888        assert_eq!(rule.name, "Unused Files");
889    }
890
891    #[test]
892    fn rule_by_id_finds_health_rule() {
893        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
894        assert_eq!(rule.name, "High Cyclomatic Complexity");
895    }
896
897    #[test]
898    fn rule_by_id_finds_dupes_rule() {
899        let rule = rule_by_id("fallow/code-duplication").unwrap();
900        assert_eq!(rule.name, "Code Duplication");
901    }
902
903    #[test]
904    fn rule_by_id_returns_none_for_unknown() {
905        assert!(rule_by_id("fallow/nonexistent").is_none());
906        assert!(rule_by_id("").is_none());
907    }
908
909    // ── rule_docs_url ────────────────────────────────────────────────
910
911    #[test]
912    fn rule_docs_url_format() {
913        let rule = rule_by_id("fallow/unused-export").unwrap();
914        let url = rule_docs_url(rule);
915        assert!(url.starts_with("https://docs.fallow.tools/"));
916        assert!(url.contains("unused-exports"));
917    }
918
919    // ── CHECK_RULES completeness ─────────────────────────────────────
920
921    #[test]
922    fn check_rules_all_have_fallow_prefix() {
923        for rule in CHECK_RULES {
924            assert!(
925                rule.id.starts_with("fallow/"),
926                "rule {} should start with fallow/",
927                rule.id
928            );
929        }
930    }
931
932    #[test]
933    fn check_rules_all_have_docs_path() {
934        for rule in CHECK_RULES {
935            assert!(
936                !rule.docs_path.is_empty(),
937                "rule {} should have a docs_path",
938                rule.id
939            );
940        }
941    }
942
943    #[test]
944    fn check_rules_no_duplicate_ids() {
945        let mut seen = rustc_hash::FxHashSet::default();
946        for rule in CHECK_RULES.iter().chain(HEALTH_RULES).chain(DUPES_RULES) {
947            assert!(seen.insert(rule.id), "duplicate rule id: {}", rule.id);
948        }
949    }
950
951    // ── check_meta ───────────────────────────────────────────────────
952
953    #[test]
954    fn check_meta_has_docs_and_rules() {
955        let meta = check_meta();
956        assert!(meta.get("docs").is_some());
957        assert!(meta.get("rules").is_some());
958        let rules = meta["rules"].as_object().unwrap();
959        // Verify all 13 rule categories are present (stripped fallow/ prefix)
960        assert_eq!(rules.len(), CHECK_RULES.len());
961        assert!(rules.contains_key("unused-file"));
962        assert!(rules.contains_key("unused-export"));
963        assert!(rules.contains_key("unused-type"));
964        assert!(rules.contains_key("unused-dependency"));
965        assert!(rules.contains_key("unused-dev-dependency"));
966        assert!(rules.contains_key("unused-optional-dependency"));
967        assert!(rules.contains_key("unused-enum-member"));
968        assert!(rules.contains_key("unused-class-member"));
969        assert!(rules.contains_key("unresolved-import"));
970        assert!(rules.contains_key("unlisted-dependency"));
971        assert!(rules.contains_key("duplicate-export"));
972        assert!(rules.contains_key("type-only-dependency"));
973        assert!(rules.contains_key("circular-dependency"));
974    }
975
976    #[test]
977    fn check_meta_rule_has_required_fields() {
978        let meta = check_meta();
979        let rules = meta["rules"].as_object().unwrap();
980        for (key, value) in rules {
981            assert!(value.get("name").is_some(), "rule {key} missing 'name'");
982            assert!(
983                value.get("description").is_some(),
984                "rule {key} missing 'description'"
985            );
986            assert!(value.get("docs").is_some(), "rule {key} missing 'docs'");
987        }
988    }
989
990    // ── health_meta ──────────────────────────────────────────────────
991
992    #[test]
993    fn health_meta_has_metrics() {
994        let meta = health_meta();
995        assert!(meta.get("docs").is_some());
996        let metrics = meta["metrics"].as_object().unwrap();
997        assert!(metrics.contains_key("cyclomatic"));
998        assert!(metrics.contains_key("cognitive"));
999        assert!(metrics.contains_key("maintainability_index"));
1000        assert!(metrics.contains_key("complexity_density"));
1001        assert!(metrics.contains_key("fan_in"));
1002        assert!(metrics.contains_key("fan_out"));
1003    }
1004
1005    // ── dupes_meta ───────────────────────────────────────────────────
1006
1007    #[test]
1008    fn dupes_meta_has_metrics() {
1009        let meta = dupes_meta();
1010        assert!(meta.get("docs").is_some());
1011        let metrics = meta["metrics"].as_object().unwrap();
1012        assert!(metrics.contains_key("duplication_percentage"));
1013        assert!(metrics.contains_key("token_count"));
1014        assert!(metrics.contains_key("clone_groups"));
1015        assert!(metrics.contains_key("clone_families"));
1016    }
1017
1018    // ── coverage_setup_meta ─────────────────────────────────────────
1019
1020    #[test]
1021    fn coverage_setup_meta_has_docs_fields_enums_and_warnings() {
1022        let meta = coverage_setup_meta();
1023        assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
1024        assert!(
1025            meta["field_definitions"]
1026                .as_object()
1027                .unwrap()
1028                .contains_key("members[]")
1029        );
1030        assert!(
1031            meta["field_definitions"]
1032                .as_object()
1033                .unwrap()
1034                .contains_key("config_written")
1035        );
1036        assert!(
1037            meta["field_definitions"]
1038                .as_object()
1039                .unwrap()
1040                .contains_key("members[].package_manager")
1041        );
1042        assert!(
1043            meta["field_definitions"]
1044                .as_object()
1045                .unwrap()
1046                .contains_key("members[].warnings")
1047        );
1048        assert!(
1049            meta["enums"]
1050                .as_object()
1051                .unwrap()
1052                .contains_key("framework_detected")
1053        );
1054        assert!(
1055            meta["warnings"]
1056                .as_object()
1057                .unwrap()
1058                .contains_key("No runtime workspace members were detected")
1059        );
1060        assert!(
1061            meta["warnings"]
1062                .as_object()
1063                .unwrap()
1064                .contains_key("Package manager was not detected")
1065        );
1066    }
1067
1068    // ── coverage_analyze_meta ────────────────────────────────────────
1069
1070    #[test]
1071    fn coverage_analyze_meta_documents_data_source_and_action_vocabulary() {
1072        let meta = coverage_analyze_meta();
1073        assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
1074        let fields = meta["field_definitions"].as_object().unwrap();
1075        assert!(fields.contains_key("runtime_coverage.summary.data_source"));
1076        assert!(fields.contains_key("runtime_coverage.summary.last_received_at"));
1077        assert!(fields.contains_key("runtime_coverage.findings[].evidence.test_coverage"));
1078        assert!(fields.contains_key("runtime_coverage.findings[].actions[].type"));
1079        let enums = meta["enums"].as_object().unwrap();
1080        assert_eq!(enums["data_source"], json!(["local", "cloud"]));
1081        assert_eq!(enums["test_coverage"], json!(["covered", "not_covered"]));
1082        assert_eq!(enums["v8_tracking"], json!(["tracked", "untracked"]));
1083        assert_eq!(
1084            enums["action_type"],
1085            json!(["delete-cold-code", "review-runtime"])
1086        );
1087        let warnings = meta["warnings"].as_object().unwrap();
1088        assert!(warnings.contains_key("cloud_functions_unmatched"));
1089    }
1090
1091    // ── HEALTH_RULES completeness ──────────────────────────────────
1092
1093    #[test]
1094    fn health_rules_all_have_fallow_prefix() {
1095        for rule in HEALTH_RULES {
1096            assert!(
1097                rule.id.starts_with("fallow/"),
1098                "health rule {} should start with fallow/",
1099                rule.id
1100            );
1101        }
1102    }
1103
1104    #[test]
1105    fn health_rules_all_have_docs_path() {
1106        for rule in HEALTH_RULES {
1107            assert!(
1108                !rule.docs_path.is_empty(),
1109                "health rule {} should have a docs_path",
1110                rule.id
1111            );
1112        }
1113    }
1114
1115    #[test]
1116    fn health_rules_all_have_non_empty_fields() {
1117        for rule in HEALTH_RULES {
1118            assert!(
1119                !rule.name.is_empty(),
1120                "health rule {} missing name",
1121                rule.id
1122            );
1123            assert!(
1124                !rule.short.is_empty(),
1125                "health rule {} missing short description",
1126                rule.id
1127            );
1128            assert!(
1129                !rule.full.is_empty(),
1130                "health rule {} missing full description",
1131                rule.id
1132            );
1133        }
1134    }
1135
1136    // ── DUPES_RULES completeness ───────────────────────────────────
1137
1138    #[test]
1139    fn dupes_rules_all_have_fallow_prefix() {
1140        for rule in DUPES_RULES {
1141            assert!(
1142                rule.id.starts_with("fallow/"),
1143                "dupes rule {} should start with fallow/",
1144                rule.id
1145            );
1146        }
1147    }
1148
1149    #[test]
1150    fn dupes_rules_all_have_docs_path() {
1151        for rule in DUPES_RULES {
1152            assert!(
1153                !rule.docs_path.is_empty(),
1154                "dupes rule {} should have a docs_path",
1155                rule.id
1156            );
1157        }
1158    }
1159
1160    #[test]
1161    fn dupes_rules_all_have_non_empty_fields() {
1162        for rule in DUPES_RULES {
1163            assert!(!rule.name.is_empty(), "dupes rule {} missing name", rule.id);
1164            assert!(
1165                !rule.short.is_empty(),
1166                "dupes rule {} missing short description",
1167                rule.id
1168            );
1169            assert!(
1170                !rule.full.is_empty(),
1171                "dupes rule {} missing full description",
1172                rule.id
1173            );
1174        }
1175    }
1176
1177    // ── CHECK_RULES field completeness ─────────────────────────────
1178
1179    #[test]
1180    fn check_rules_all_have_non_empty_fields() {
1181        for rule in CHECK_RULES {
1182            assert!(!rule.name.is_empty(), "check rule {} missing name", rule.id);
1183            assert!(
1184                !rule.short.is_empty(),
1185                "check rule {} missing short description",
1186                rule.id
1187            );
1188            assert!(
1189                !rule.full.is_empty(),
1190                "check rule {} missing full description",
1191                rule.id
1192            );
1193        }
1194    }
1195
1196    // ── rule_docs_url with health/dupes rules ──────────────────────
1197
1198    #[test]
1199    fn rule_docs_url_health_rule() {
1200        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1201        let url = rule_docs_url(rule);
1202        assert!(url.starts_with("https://docs.fallow.tools/"));
1203        assert!(url.contains("health"));
1204    }
1205
1206    #[test]
1207    fn rule_docs_url_dupes_rule() {
1208        let rule = rule_by_id("fallow/code-duplication").unwrap();
1209        let url = rule_docs_url(rule);
1210        assert!(url.starts_with("https://docs.fallow.tools/"));
1211        assert!(url.contains("duplication"));
1212    }
1213
1214    // ── health_meta metric structure ───────────────────────────────
1215
1216    #[test]
1217    fn health_meta_all_metrics_have_name_and_description() {
1218        let meta = health_meta();
1219        let metrics = meta["metrics"].as_object().unwrap();
1220        for (key, value) in metrics {
1221            assert!(
1222                value.get("name").is_some(),
1223                "health metric {key} missing 'name'"
1224            );
1225            assert!(
1226                value.get("description").is_some(),
1227                "health metric {key} missing 'description'"
1228            );
1229            assert!(
1230                value.get("interpretation").is_some(),
1231                "health metric {key} missing 'interpretation'"
1232            );
1233        }
1234    }
1235
1236    #[test]
1237    fn health_meta_has_all_expected_metrics() {
1238        let meta = health_meta();
1239        let metrics = meta["metrics"].as_object().unwrap();
1240        let expected = [
1241            "cyclomatic",
1242            "cognitive",
1243            "line_count",
1244            "lines",
1245            "maintainability_index",
1246            "complexity_density",
1247            "dead_code_ratio",
1248            "fan_in",
1249            "fan_out",
1250            "score",
1251            "weighted_commits",
1252            "trend",
1253            "priority",
1254            "efficiency",
1255            "effort",
1256            "confidence",
1257            "bus_factor",
1258            "contributor_count",
1259            "share",
1260            "stale_days",
1261            "drift",
1262            "unowned",
1263            "runtime_coverage_verdict",
1264            "runtime_coverage_state",
1265            "runtime_coverage_confidence",
1266            "production_invocations",
1267            "percent_dead_in_production",
1268        ];
1269        for key in &expected {
1270            assert!(
1271                metrics.contains_key(*key),
1272                "health_meta missing expected metric: {key}"
1273            );
1274        }
1275    }
1276
1277    // ── dupes_meta metric structure ────────────────────────────────
1278
1279    #[test]
1280    fn dupes_meta_all_metrics_have_name_and_description() {
1281        let meta = dupes_meta();
1282        let metrics = meta["metrics"].as_object().unwrap();
1283        for (key, value) in metrics {
1284            assert!(
1285                value.get("name").is_some(),
1286                "dupes metric {key} missing 'name'"
1287            );
1288            assert!(
1289                value.get("description").is_some(),
1290                "dupes metric {key} missing 'description'"
1291            );
1292        }
1293    }
1294
1295    #[test]
1296    fn dupes_meta_has_line_count() {
1297        let meta = dupes_meta();
1298        let metrics = meta["metrics"].as_object().unwrap();
1299        assert!(metrics.contains_key("line_count"));
1300    }
1301
1302    // ── docs URLs ─────────────────────────────────────────────────
1303
1304    #[test]
1305    fn check_docs_url_valid() {
1306        assert!(CHECK_DOCS.starts_with("https://"));
1307        assert!(CHECK_DOCS.contains("dead-code"));
1308    }
1309
1310    #[test]
1311    fn health_docs_url_valid() {
1312        assert!(HEALTH_DOCS.starts_with("https://"));
1313        assert!(HEALTH_DOCS.contains("health"));
1314    }
1315
1316    #[test]
1317    fn dupes_docs_url_valid() {
1318        assert!(DUPES_DOCS.starts_with("https://"));
1319        assert!(DUPES_DOCS.contains("dupes"));
1320    }
1321
1322    // ── check_meta docs URL matches constant ──────────────────────
1323
1324    #[test]
1325    fn check_meta_docs_url_matches_constant() {
1326        let meta = check_meta();
1327        assert_eq!(meta["docs"].as_str().unwrap(), CHECK_DOCS);
1328    }
1329
1330    #[test]
1331    fn health_meta_docs_url_matches_constant() {
1332        let meta = health_meta();
1333        assert_eq!(meta["docs"].as_str().unwrap(), HEALTH_DOCS);
1334    }
1335
1336    #[test]
1337    fn dupes_meta_docs_url_matches_constant() {
1338        let meta = dupes_meta();
1339        assert_eq!(meta["docs"].as_str().unwrap(), DUPES_DOCS);
1340    }
1341
1342    // ── rule_by_id finds all check rules ──────────────────────────
1343
1344    #[test]
1345    fn rule_by_id_finds_all_check_rules() {
1346        for rule in CHECK_RULES {
1347            assert!(
1348                rule_by_id(rule.id).is_some(),
1349                "rule_by_id should find check rule {}",
1350                rule.id
1351            );
1352        }
1353    }
1354
1355    #[test]
1356    fn rule_by_id_finds_all_health_rules() {
1357        for rule in HEALTH_RULES {
1358            assert!(
1359                rule_by_id(rule.id).is_some(),
1360                "rule_by_id should find health rule {}",
1361                rule.id
1362            );
1363        }
1364    }
1365
1366    #[test]
1367    fn rule_by_id_finds_all_dupes_rules() {
1368        for rule in DUPES_RULES {
1369            assert!(
1370                rule_by_id(rule.id).is_some(),
1371                "rule_by_id should find dupes rule {}",
1372                rule.id
1373            );
1374        }
1375    }
1376
1377    // ── Rule count verification ───────────────────────────────────
1378
1379    #[test]
1380    fn check_rules_count() {
1381        assert_eq!(CHECK_RULES.len(), 17);
1382    }
1383
1384    #[test]
1385    fn health_rules_count() {
1386        assert_eq!(HEALTH_RULES.len(), 12);
1387    }
1388
1389    #[test]
1390    fn dupes_rules_count() {
1391        assert_eq!(DUPES_RULES.len(), 1);
1392    }
1393}