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