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