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.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally."
860        },
861        "enums": {
862            "data_source": ["local", "cloud"],
863            "report_verdict": ["clean", "hot-path-changes-needed", "cold-code-detected", "license-expired-grace", "unknown"],
864            "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
865            "static_status": ["used", "unused"],
866            "test_coverage": ["covered", "not_covered"],
867            "v8_tracking": ["tracked", "untracked"],
868            "action_type": ["delete-cold-code", "review-runtime"]
869        },
870        "warnings": {
871            "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
872            "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."
873        }
874    })
875}
876
877#[cfg(test)]
878mod tests {
879    use super::*;
880
881    // ── rule_by_id ───────────────────────────────────────────────────
882
883    #[test]
884    fn rule_by_id_finds_check_rule() {
885        let rule = rule_by_id("fallow/unused-file").unwrap();
886        assert_eq!(rule.name, "Unused Files");
887    }
888
889    #[test]
890    fn rule_by_id_finds_health_rule() {
891        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
892        assert_eq!(rule.name, "High Cyclomatic Complexity");
893    }
894
895    #[test]
896    fn rule_by_id_finds_dupes_rule() {
897        let rule = rule_by_id("fallow/code-duplication").unwrap();
898        assert_eq!(rule.name, "Code Duplication");
899    }
900
901    #[test]
902    fn rule_by_id_returns_none_for_unknown() {
903        assert!(rule_by_id("fallow/nonexistent").is_none());
904        assert!(rule_by_id("").is_none());
905    }
906
907    // ── rule_docs_url ────────────────────────────────────────────────
908
909    #[test]
910    fn rule_docs_url_format() {
911        let rule = rule_by_id("fallow/unused-export").unwrap();
912        let url = rule_docs_url(rule);
913        assert!(url.starts_with("https://docs.fallow.tools/"));
914        assert!(url.contains("unused-exports"));
915    }
916
917    // ── CHECK_RULES completeness ─────────────────────────────────────
918
919    #[test]
920    fn check_rules_all_have_fallow_prefix() {
921        for rule in CHECK_RULES {
922            assert!(
923                rule.id.starts_with("fallow/"),
924                "rule {} should start with fallow/",
925                rule.id
926            );
927        }
928    }
929
930    #[test]
931    fn check_rules_all_have_docs_path() {
932        for rule in CHECK_RULES {
933            assert!(
934                !rule.docs_path.is_empty(),
935                "rule {} should have a docs_path",
936                rule.id
937            );
938        }
939    }
940
941    #[test]
942    fn check_rules_no_duplicate_ids() {
943        let mut seen = rustc_hash::FxHashSet::default();
944        for rule in CHECK_RULES.iter().chain(HEALTH_RULES).chain(DUPES_RULES) {
945            assert!(seen.insert(rule.id), "duplicate rule id: {}", rule.id);
946        }
947    }
948
949    // ── check_meta ───────────────────────────────────────────────────
950
951    #[test]
952    fn check_meta_has_docs_and_rules() {
953        let meta = check_meta();
954        assert!(meta.get("docs").is_some());
955        assert!(meta.get("rules").is_some());
956        let rules = meta["rules"].as_object().unwrap();
957        // Verify all 13 rule categories are present (stripped fallow/ prefix)
958        assert_eq!(rules.len(), CHECK_RULES.len());
959        assert!(rules.contains_key("unused-file"));
960        assert!(rules.contains_key("unused-export"));
961        assert!(rules.contains_key("unused-type"));
962        assert!(rules.contains_key("unused-dependency"));
963        assert!(rules.contains_key("unused-dev-dependency"));
964        assert!(rules.contains_key("unused-optional-dependency"));
965        assert!(rules.contains_key("unused-enum-member"));
966        assert!(rules.contains_key("unused-class-member"));
967        assert!(rules.contains_key("unresolved-import"));
968        assert!(rules.contains_key("unlisted-dependency"));
969        assert!(rules.contains_key("duplicate-export"));
970        assert!(rules.contains_key("type-only-dependency"));
971        assert!(rules.contains_key("circular-dependency"));
972    }
973
974    #[test]
975    fn check_meta_rule_has_required_fields() {
976        let meta = check_meta();
977        let rules = meta["rules"].as_object().unwrap();
978        for (key, value) in rules {
979            assert!(value.get("name").is_some(), "rule {key} missing 'name'");
980            assert!(
981                value.get("description").is_some(),
982                "rule {key} missing 'description'"
983            );
984            assert!(value.get("docs").is_some(), "rule {key} missing 'docs'");
985        }
986    }
987
988    // ── health_meta ──────────────────────────────────────────────────
989
990    #[test]
991    fn health_meta_has_metrics() {
992        let meta = health_meta();
993        assert!(meta.get("docs").is_some());
994        let metrics = meta["metrics"].as_object().unwrap();
995        assert!(metrics.contains_key("cyclomatic"));
996        assert!(metrics.contains_key("cognitive"));
997        assert!(metrics.contains_key("maintainability_index"));
998        assert!(metrics.contains_key("complexity_density"));
999        assert!(metrics.contains_key("fan_in"));
1000        assert!(metrics.contains_key("fan_out"));
1001    }
1002
1003    // ── dupes_meta ───────────────────────────────────────────────────
1004
1005    #[test]
1006    fn dupes_meta_has_metrics() {
1007        let meta = dupes_meta();
1008        assert!(meta.get("docs").is_some());
1009        let metrics = meta["metrics"].as_object().unwrap();
1010        assert!(metrics.contains_key("duplication_percentage"));
1011        assert!(metrics.contains_key("token_count"));
1012        assert!(metrics.contains_key("clone_groups"));
1013        assert!(metrics.contains_key("clone_families"));
1014    }
1015
1016    // ── coverage_setup_meta ─────────────────────────────────────────
1017
1018    #[test]
1019    fn coverage_setup_meta_has_docs_fields_enums_and_warnings() {
1020        let meta = coverage_setup_meta();
1021        assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
1022        assert!(
1023            meta["field_definitions"]
1024                .as_object()
1025                .unwrap()
1026                .contains_key("members[]")
1027        );
1028        assert!(
1029            meta["field_definitions"]
1030                .as_object()
1031                .unwrap()
1032                .contains_key("config_written")
1033        );
1034        assert!(
1035            meta["field_definitions"]
1036                .as_object()
1037                .unwrap()
1038                .contains_key("members[].package_manager")
1039        );
1040        assert!(
1041            meta["field_definitions"]
1042                .as_object()
1043                .unwrap()
1044                .contains_key("members[].warnings")
1045        );
1046        assert!(
1047            meta["enums"]
1048                .as_object()
1049                .unwrap()
1050                .contains_key("framework_detected")
1051        );
1052        assert!(
1053            meta["warnings"]
1054                .as_object()
1055                .unwrap()
1056                .contains_key("No runtime workspace members were detected")
1057        );
1058        assert!(
1059            meta["warnings"]
1060                .as_object()
1061                .unwrap()
1062                .contains_key("Package manager was not detected")
1063        );
1064    }
1065
1066    // ── coverage_analyze_meta ────────────────────────────────────────
1067
1068    #[test]
1069    fn coverage_analyze_meta_documents_data_source_and_action_vocabulary() {
1070        let meta = coverage_analyze_meta();
1071        assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
1072        let fields = meta["field_definitions"].as_object().unwrap();
1073        assert!(fields.contains_key("runtime_coverage.summary.data_source"));
1074        assert!(fields.contains_key("runtime_coverage.summary.last_received_at"));
1075        assert!(fields.contains_key("runtime_coverage.findings[].evidence.test_coverage"));
1076        assert!(fields.contains_key("runtime_coverage.findings[].actions[].type"));
1077        let enums = meta["enums"].as_object().unwrap();
1078        assert_eq!(enums["data_source"], json!(["local", "cloud"]));
1079        assert_eq!(enums["test_coverage"], json!(["covered", "not_covered"]));
1080        assert_eq!(enums["v8_tracking"], json!(["tracked", "untracked"]));
1081        assert_eq!(
1082            enums["action_type"],
1083            json!(["delete-cold-code", "review-runtime"])
1084        );
1085        let warnings = meta["warnings"].as_object().unwrap();
1086        assert!(warnings.contains_key("cloud_functions_unmatched"));
1087    }
1088
1089    // ── HEALTH_RULES completeness ──────────────────────────────────
1090
1091    #[test]
1092    fn health_rules_all_have_fallow_prefix() {
1093        for rule in HEALTH_RULES {
1094            assert!(
1095                rule.id.starts_with("fallow/"),
1096                "health rule {} should start with fallow/",
1097                rule.id
1098            );
1099        }
1100    }
1101
1102    #[test]
1103    fn health_rules_all_have_docs_path() {
1104        for rule in HEALTH_RULES {
1105            assert!(
1106                !rule.docs_path.is_empty(),
1107                "health rule {} should have a docs_path",
1108                rule.id
1109            );
1110        }
1111    }
1112
1113    #[test]
1114    fn health_rules_all_have_non_empty_fields() {
1115        for rule in HEALTH_RULES {
1116            assert!(
1117                !rule.name.is_empty(),
1118                "health rule {} missing name",
1119                rule.id
1120            );
1121            assert!(
1122                !rule.short.is_empty(),
1123                "health rule {} missing short description",
1124                rule.id
1125            );
1126            assert!(
1127                !rule.full.is_empty(),
1128                "health rule {} missing full description",
1129                rule.id
1130            );
1131        }
1132    }
1133
1134    // ── DUPES_RULES completeness ───────────────────────────────────
1135
1136    #[test]
1137    fn dupes_rules_all_have_fallow_prefix() {
1138        for rule in DUPES_RULES {
1139            assert!(
1140                rule.id.starts_with("fallow/"),
1141                "dupes rule {} should start with fallow/",
1142                rule.id
1143            );
1144        }
1145    }
1146
1147    #[test]
1148    fn dupes_rules_all_have_docs_path() {
1149        for rule in DUPES_RULES {
1150            assert!(
1151                !rule.docs_path.is_empty(),
1152                "dupes rule {} should have a docs_path",
1153                rule.id
1154            );
1155        }
1156    }
1157
1158    #[test]
1159    fn dupes_rules_all_have_non_empty_fields() {
1160        for rule in DUPES_RULES {
1161            assert!(!rule.name.is_empty(), "dupes rule {} missing name", rule.id);
1162            assert!(
1163                !rule.short.is_empty(),
1164                "dupes rule {} missing short description",
1165                rule.id
1166            );
1167            assert!(
1168                !rule.full.is_empty(),
1169                "dupes rule {} missing full description",
1170                rule.id
1171            );
1172        }
1173    }
1174
1175    // ── CHECK_RULES field completeness ─────────────────────────────
1176
1177    #[test]
1178    fn check_rules_all_have_non_empty_fields() {
1179        for rule in CHECK_RULES {
1180            assert!(!rule.name.is_empty(), "check rule {} missing name", rule.id);
1181            assert!(
1182                !rule.short.is_empty(),
1183                "check rule {} missing short description",
1184                rule.id
1185            );
1186            assert!(
1187                !rule.full.is_empty(),
1188                "check rule {} missing full description",
1189                rule.id
1190            );
1191        }
1192    }
1193
1194    // ── rule_docs_url with health/dupes rules ──────────────────────
1195
1196    #[test]
1197    fn rule_docs_url_health_rule() {
1198        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1199        let url = rule_docs_url(rule);
1200        assert!(url.starts_with("https://docs.fallow.tools/"));
1201        assert!(url.contains("health"));
1202    }
1203
1204    #[test]
1205    fn rule_docs_url_dupes_rule() {
1206        let rule = rule_by_id("fallow/code-duplication").unwrap();
1207        let url = rule_docs_url(rule);
1208        assert!(url.starts_with("https://docs.fallow.tools/"));
1209        assert!(url.contains("duplication"));
1210    }
1211
1212    // ── health_meta metric structure ───────────────────────────────
1213
1214    #[test]
1215    fn health_meta_all_metrics_have_name_and_description() {
1216        let meta = health_meta();
1217        let metrics = meta["metrics"].as_object().unwrap();
1218        for (key, value) in metrics {
1219            assert!(
1220                value.get("name").is_some(),
1221                "health metric {key} missing 'name'"
1222            );
1223            assert!(
1224                value.get("description").is_some(),
1225                "health metric {key} missing 'description'"
1226            );
1227            assert!(
1228                value.get("interpretation").is_some(),
1229                "health metric {key} missing 'interpretation'"
1230            );
1231        }
1232    }
1233
1234    #[test]
1235    fn health_meta_has_all_expected_metrics() {
1236        let meta = health_meta();
1237        let metrics = meta["metrics"].as_object().unwrap();
1238        let expected = [
1239            "cyclomatic",
1240            "cognitive",
1241            "line_count",
1242            "lines",
1243            "maintainability_index",
1244            "complexity_density",
1245            "dead_code_ratio",
1246            "fan_in",
1247            "fan_out",
1248            "score",
1249            "weighted_commits",
1250            "trend",
1251            "priority",
1252            "efficiency",
1253            "effort",
1254            "confidence",
1255            "bus_factor",
1256            "contributor_count",
1257            "share",
1258            "stale_days",
1259            "drift",
1260            "unowned",
1261            "runtime_coverage_verdict",
1262            "runtime_coverage_state",
1263            "runtime_coverage_confidence",
1264            "production_invocations",
1265            "percent_dead_in_production",
1266        ];
1267        for key in &expected {
1268            assert!(
1269                metrics.contains_key(*key),
1270                "health_meta missing expected metric: {key}"
1271            );
1272        }
1273    }
1274
1275    // ── dupes_meta metric structure ────────────────────────────────
1276
1277    #[test]
1278    fn dupes_meta_all_metrics_have_name_and_description() {
1279        let meta = dupes_meta();
1280        let metrics = meta["metrics"].as_object().unwrap();
1281        for (key, value) in metrics {
1282            assert!(
1283                value.get("name").is_some(),
1284                "dupes metric {key} missing 'name'"
1285            );
1286            assert!(
1287                value.get("description").is_some(),
1288                "dupes metric {key} missing 'description'"
1289            );
1290        }
1291    }
1292
1293    #[test]
1294    fn dupes_meta_has_line_count() {
1295        let meta = dupes_meta();
1296        let metrics = meta["metrics"].as_object().unwrap();
1297        assert!(metrics.contains_key("line_count"));
1298    }
1299
1300    // ── docs URLs ─────────────────────────────────────────────────
1301
1302    #[test]
1303    fn check_docs_url_valid() {
1304        assert!(CHECK_DOCS.starts_with("https://"));
1305        assert!(CHECK_DOCS.contains("dead-code"));
1306    }
1307
1308    #[test]
1309    fn health_docs_url_valid() {
1310        assert!(HEALTH_DOCS.starts_with("https://"));
1311        assert!(HEALTH_DOCS.contains("health"));
1312    }
1313
1314    #[test]
1315    fn dupes_docs_url_valid() {
1316        assert!(DUPES_DOCS.starts_with("https://"));
1317        assert!(DUPES_DOCS.contains("dupes"));
1318    }
1319
1320    // ── check_meta docs URL matches constant ──────────────────────
1321
1322    #[test]
1323    fn check_meta_docs_url_matches_constant() {
1324        let meta = check_meta();
1325        assert_eq!(meta["docs"].as_str().unwrap(), CHECK_DOCS);
1326    }
1327
1328    #[test]
1329    fn health_meta_docs_url_matches_constant() {
1330        let meta = health_meta();
1331        assert_eq!(meta["docs"].as_str().unwrap(), HEALTH_DOCS);
1332    }
1333
1334    #[test]
1335    fn dupes_meta_docs_url_matches_constant() {
1336        let meta = dupes_meta();
1337        assert_eq!(meta["docs"].as_str().unwrap(), DUPES_DOCS);
1338    }
1339
1340    // ── rule_by_id finds all check rules ──────────────────────────
1341
1342    #[test]
1343    fn rule_by_id_finds_all_check_rules() {
1344        for rule in CHECK_RULES {
1345            assert!(
1346                rule_by_id(rule.id).is_some(),
1347                "rule_by_id should find check rule {}",
1348                rule.id
1349            );
1350        }
1351    }
1352
1353    #[test]
1354    fn rule_by_id_finds_all_health_rules() {
1355        for rule in HEALTH_RULES {
1356            assert!(
1357                rule_by_id(rule.id).is_some(),
1358                "rule_by_id should find health rule {}",
1359                rule.id
1360            );
1361        }
1362    }
1363
1364    #[test]
1365    fn rule_by_id_finds_all_dupes_rules() {
1366        for rule in DUPES_RULES {
1367            assert!(
1368                rule_by_id(rule.id).is_some(),
1369                "rule_by_id should find dupes rule {}",
1370                rule.id
1371            );
1372        }
1373    }
1374
1375    // ── Rule count verification ───────────────────────────────────
1376
1377    #[test]
1378    fn check_rules_count() {
1379        assert_eq!(CHECK_RULES.len(), 17);
1380    }
1381
1382    #[test]
1383    fn health_rules_count() {
1384        assert_eq!(HEALTH_RULES.len(), 12);
1385    }
1386
1387    #[test]
1388    fn dupes_rules_count() {
1389        assert_eq!(DUPES_RULES.len(), 1);
1390    }
1391}