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 `_meta` object for `fallow health --format json --explain`.
722#[must_use]
723#[expect(
724    clippy::too_many_lines,
725    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"
726)]
727pub fn health_meta() -> Value {
728    json!({
729        "docs": HEALTH_DOCS,
730        "field_definitions": {
731            "actions[]": ACTIONS_FIELD_DEFINITION,
732            "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
733        },
734        "metrics": {
735            "cyclomatic": {
736                "name": "Cyclomatic Complexity",
737                "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.",
738                "range": "[1, \u{221e})",
739                "interpretation": "lower is better; default threshold: 20"
740            },
741            "cognitive": {
742                "name": "Cognitive Complexity",
743                "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.",
744                "range": "[0, \u{221e})",
745                "interpretation": "lower is better; default threshold: 15"
746            },
747            "line_count": {
748                "name": "Function Line Count",
749                "description": "Number of lines in the function body.",
750                "range": "[1, \u{221e})",
751                "interpretation": "context-dependent; long functions may need splitting"
752            },
753            "lines": {
754                "name": "File Line Count",
755                "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.",
756                "range": "[1, \u{221e})",
757                "interpretation": "context-dependent; large files may benefit from splitting even if individual functions are small"
758            },
759            "maintainability_index": {
760                "name": "Maintainability Index",
761                "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.",
762                "range": "[0, 100]",
763                "interpretation": "higher is better; <40 poor, 40\u{2013}70 moderate, >70 good"
764            },
765            "complexity_density": {
766                "name": "Complexity Density",
767                "description": "Total cyclomatic complexity divided by lines of code. Measures how densely complex the code is per line.",
768                "range": "[0, \u{221e})",
769                "interpretation": "lower is better; >1.0 indicates very dense complexity"
770            },
771            "dead_code_ratio": {
772                "name": "Dead Code Ratio",
773                "description": "Fraction of value exports (excluding type-only exports like interfaces and type aliases) with zero references across the project.",
774                "range": "[0, 1]",
775                "interpretation": "lower is better; 0 = all exports are used"
776            },
777            "fan_in": {
778                "name": "Fan-in (Importers)",
779                "description": "Number of files that import this file. High fan-in means high blast radius \u{2014} changes to this file affect many dependents.",
780                "range": "[0, \u{221e})",
781                "interpretation": "context-dependent; high fan-in files need careful review before changes"
782            },
783            "fan_out": {
784                "name": "Fan-out (Imports)",
785                "description": "Number of files this file directly imports. High fan-out indicates high coupling and change propagation risk.",
786                "range": "[0, \u{221e})",
787                "interpretation": "lower is better; MI penalty caps at ~40 imports"
788            },
789            "score": {
790                "name": "Hotspot Score",
791                "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.",
792                "range": "[0, 100]",
793                "interpretation": "higher = riskier; prioritize refactoring high-score files"
794            },
795            "weighted_commits": {
796                "name": "Weighted Commits",
797                "description": "Recency-weighted commit count using exponential decay with 90-day half-life. Recent commits contribute more than older ones.",
798                "range": "[0, \u{221e})",
799                "interpretation": "higher = more recent churn activity"
800            },
801            "trend": {
802                "name": "Churn Trend",
803                "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.",
804                "values": ["accelerating", "stable", "cooling"],
805                "interpretation": "accelerating files need attention; cooling files are stabilizing"
806            },
807            "priority": {
808                "name": "Refactoring Priority",
809                "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.",
810                "range": "[0, 100]",
811                "interpretation": "higher = more urgent to refactor"
812            },
813            "efficiency": {
814                "name": "Efficiency Score",
815                "description": "priority / effort_numeric (Low=1, Medium=2, High=3). Surfaces quick wins: high-priority, low-effort targets rank first. Default sort order.",
816                "range": "[0, 100] \u{2014} effective max depends on effort: Low=100, Medium=50, High\u{2248}33",
817                "interpretation": "higher = better quick-win value; targets are sorted by efficiency descending"
818            },
819            "effort": {
820                "name": "Effort Estimate",
821                "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.",
822                "values": ["low", "medium", "high"],
823                "interpretation": "low = quick win, high = needs planning and coordination"
824            },
825            "confidence": {
826                "name": "Confidence Level",
827                "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).",
828                "values": ["high", "medium", "low"],
829                "interpretation": "high = act on it, medium = verify context, low = treat as a signal, not a directive"
830            },
831            "health_score": {
832                "name": "Health Score",
833                "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.",
834                "range": "[0, 100]",
835                "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)"
836            },
837            "crap_max": {
838                "name": "Untested Complexity Risk (CRAP)",
839                "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.",
840                "range": "[1, \u{221e})",
841                "interpretation": "lower is better; >=30 is high-risk (CC >= 5 without test path)"
842            },
843            "bus_factor": {
844                "name": "Bus Factor",
845                "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.",
846                "range": "[1, \u{221e})",
847                "interpretation": "lower is higher knowledge-loss risk; 1 means a single contributor covers most of the recent history"
848            },
849            "contributor_count": {
850                "name": "Contributor Count",
851                "description": "Number of distinct authors who touched this file in the analysis window after bot-pattern filtering.",
852                "range": "[0, \u{221e})",
853                "interpretation": "higher generally indicates broader knowledge spread; pair with bus_factor for context"
854            },
855            "share": {
856                "name": "Contributor Share",
857                "description": "Recency-weighted share of total weighted commits attributed to a single contributor. Rounded to three decimals.",
858                "range": "[0, 1]",
859                "interpretation": "share close to 1.0 indicates dominance and pairs with low bus_factor"
860            },
861            "stale_days": {
862                "name": "Stale Days",
863                "description": "Days since this contributor last touched the file. Computed at analysis time.",
864                "range": "[0, \u{221e})",
865                "interpretation": "high stale_days on the top contributor often correlates with ownership drift"
866            },
867            "drift": {
868                "name": "Ownership Drift",
869                "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%.",
870                "values": [true, false],
871                "interpretation": "true means the original author is no longer maintaining; route reviews to the current top contributor"
872            },
873            "unowned": {
874                "name": "Unowned (Tristate)",
875                "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).",
876                "values": [true, false, null],
877                "interpretation": "true on a hotspot is a review-bottleneck risk; null means the signal is unavailable, not absent"
878            },
879            "runtime_coverage_verdict": {
880                "name": "Runtime Coverage Verdict",
881                "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).",
882                "values": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
883                "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."
884            },
885            "runtime_coverage_state": {
886                "name": "Runtime Coverage State",
887                "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.",
888                "values": ["called", "never-called", "coverage-unavailable", "unknown"],
889                "interpretation": "`never-called` in combination with static `unused` is the highest-confidence delete signal"
890            },
891            "runtime_coverage_confidence": {
892                "name": "Runtime Coverage Confidence",
893                "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.",
894                "values": ["high", "medium", "low", "unknown"],
895                "interpretation": "high = act on it; medium = verify context; low = treat as a signal only"
896            },
897            "production_invocations": {
898                "name": "Production Invocations",
899                "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.",
900                "range": "[0, \u{221e})",
901                "interpretation": "0 + tracked = cold path; 0 + untracked = unknown; high + never-called cannot occur by definition"
902            },
903            "percent_dead_in_production": {
904                "name": "Percent Dead in Production",
905                "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.",
906                "range": "[0, 100]",
907                "interpretation": "lower is better; values above ~10% on a long-running service indicate a large cleanup opportunity"
908            }
909        }
910    })
911}
912
913/// Build the `_meta` object for `fallow dupes --format json --explain`.
914#[must_use]
915pub fn dupes_meta() -> Value {
916    json!({
917        "docs": DUPES_DOCS,
918        "field_definitions": {
919            "actions[]": ACTIONS_FIELD_DEFINITION,
920            "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
921        },
922        "metrics": {
923            "duplication_percentage": {
924                "name": "Duplication Percentage",
925                "description": "Fraction of total source tokens that appear in at least one clone group. Computed over the full analyzed file set.",
926                "range": "[0, 100]",
927                "interpretation": "lower is better"
928            },
929            "token_count": {
930                "name": "Token Count",
931                "description": "Number of normalized source tokens in the clone group. Tokens are language-aware (keywords, identifiers, operators, punctuation). Higher token count = larger duplicate.",
932                "range": "[1, \u{221e})",
933                "interpretation": "larger clones have higher refactoring value"
934            },
935            "line_count": {
936                "name": "Line Count",
937                "description": "Number of source lines spanned by the clone instance. Approximation of clone size for human readability.",
938                "range": "[1, \u{221e})",
939                "interpretation": "larger clones are more impactful to deduplicate"
940            },
941            "clone_groups": {
942                "name": "Clone Groups",
943                "description": "A set of code fragments with identical or near-identical normalized token sequences. Each group has 2+ instances across different locations.",
944                "interpretation": "each group is a single refactoring opportunity"
945            },
946            "clone_groups_below_min_occurrences": {
947                "name": "Clone Groups Below minOccurrences",
948                "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`.",
949                "range": "[0, \u{221e})",
950                "interpretation": "high values suggest noisy pair-only duplication; lower `minOccurrences` to inspect"
951            },
952            "clone_families": {
953                "name": "Clone Families",
954                "description": "Groups of clone groups that share the same set of files. Indicates systematic duplication patterns (e.g., mirrored directory structures).",
955                "interpretation": "families suggest extract-module refactoring opportunities"
956            }
957        }
958    })
959}
960
961/// Build the `_meta` object for `fallow coverage setup --json --explain`.
962#[must_use]
963pub fn coverage_setup_meta() -> Value {
964    json!({
965        "docs_url": COVERAGE_SETUP_DOCS,
966        "field_definitions": {
967            "schema_version": "Coverage setup JSON contract version. Stays at \"1\" for additive opt-in fields such as _meta.",
968            "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.",
969            "package_manager": "Detected package manager used for install and run commands, or null when no package manager signal was found.",
970            "runtime_targets": "Union of runtime targets across emitted members.",
971            "members[]": "Per-runtime-workspace setup recipes. Pure aggregator roots and build-only libraries are omitted.",
972            "members[].name": "Workspace package name from package.json, or the root directory name when package.json has no name.",
973            "members[].path": "Workspace path relative to the command root. The root package is represented as \".\".",
974            "members[].framework_detected": "Runtime framework detected for that member.",
975            "members[].package_manager": "Package manager detected for that member, or inherited from the workspace root when no member-specific signal exists.",
976            "members[].runtime_targets": "Runtime targets produced by that member.",
977            "members[].files_to_edit": "Files in that member that should receive runtime beacon setup code.",
978            "members[].snippets": "Copy-paste setup snippets for that member, with paths relative to the command root.",
979            "members[].dockerfile_snippet": "Environment snippet for file-system capture in that member's containerized Node runtime, or null when not applicable.",
980            "members[].warnings": "Actionable setup caveats discovered for that member.",
981            "config_written": "Always null for --json because JSON setup is side-effect-free and never writes configuration.",
982            "files_to_edit": "Compatibility copy of the primary member's files, with workspace prefixes when the primary member is not the root.",
983            "snippets": "Compatibility copy of the primary member's snippets, with workspace prefixes when the primary member is not the root.",
984            "dockerfile_snippet": "Environment snippet for file-system capture in containerized Node runtimes, or null when not applicable.",
985            "commands": "Package-manager commands needed to install the runtime beacon and sidecar packages.",
986            "next_steps": "Ordered setup workflow after applying the emitted snippets.",
987            "warnings": "Actionable setup caveats discovered while building the recipe."
988        },
989        "enums": {
990            "framework_detected": ["nextjs", "nestjs", "nuxt", "sveltekit", "astro", "remix", "vite", "plain_node", "unknown"],
991            "runtime_targets": ["node", "browser"],
992            "package_manager": ["npm", "pnpm", "yarn", "bun", null]
993        },
994        "warnings": {
995            "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.",
996            "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.",
997            "Package manager was not detected": "No packageManager field or known lockfile was found. Commands fall back to npm.",
998            "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."
999        }
1000    })
1001}
1002
1003/// Build the `_meta` object for `fallow coverage analyze --format json --explain`.
1004#[must_use]
1005pub fn coverage_analyze_meta() -> Value {
1006    json!({
1007        "docs_url": COVERAGE_ANALYZE_DOCS,
1008        "field_definitions": {
1009            "schema_version": "Standalone coverage analyze envelope version. \"1\" for the current shape.",
1010            "version": "fallow CLI version that produced this output.",
1011            "elapsed_ms": "Wall-clock milliseconds spent producing the report.",
1012            "runtime_coverage": "Same RuntimeCoverageReport block emitted by `fallow health --runtime-coverage`.",
1013            "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.",
1014            "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.",
1015            "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.",
1016            "runtime_coverage.findings[].evidence.static_status": "used = the function is reachable in the AST module graph; unused = it is dead by static analysis.",
1017            "runtime_coverage.findings[].evidence.test_coverage": "covered = the local test suite hits the function; not_covered otherwise.",
1018            "runtime_coverage.findings[].evidence.v8_tracking": "tracked = V8 observed the function during the capture window; untracked otherwise.",
1019            "runtime_coverage.findings[].actions[].type": "Suggested follow-up identifier. delete-cold-code is emitted on safe_to_delete; review-runtime on review_required.",
1020            "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.",
1021            "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.",
1022            "runtime_coverage.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally."
1023        },
1024        "enums": {
1025            "data_source": ["local", "cloud"],
1026            "report_verdict": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
1027            "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
1028            "static_status": ["used", "unused"],
1029            "test_coverage": ["covered", "not_covered"],
1030            "v8_tracking": ["tracked", "untracked"],
1031            "action_type": ["delete-cold-code", "review-runtime"]
1032        },
1033        "warnings": {
1034            "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
1035            "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."
1036        }
1037    })
1038}
1039
1040#[cfg(test)]
1041mod tests {
1042    use super::*;
1043
1044    // ── rule_by_id ───────────────────────────────────────────────────
1045
1046    #[test]
1047    fn rule_by_id_finds_check_rule() {
1048        let rule = rule_by_id("fallow/unused-file").unwrap();
1049        assert_eq!(rule.name, "Unused Files");
1050    }
1051
1052    #[test]
1053    fn rule_by_id_finds_health_rule() {
1054        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1055        assert_eq!(rule.name, "High Cyclomatic Complexity");
1056    }
1057
1058    #[test]
1059    fn rule_by_id_finds_dupes_rule() {
1060        let rule = rule_by_id("fallow/code-duplication").unwrap();
1061        assert_eq!(rule.name, "Code Duplication");
1062    }
1063
1064    #[test]
1065    fn rule_by_id_returns_none_for_unknown() {
1066        assert!(rule_by_id("fallow/nonexistent").is_none());
1067        assert!(rule_by_id("").is_none());
1068    }
1069
1070    // ── rule_docs_url ────────────────────────────────────────────────
1071
1072    #[test]
1073    fn rule_docs_url_format() {
1074        let rule = rule_by_id("fallow/unused-export").unwrap();
1075        let url = rule_docs_url(rule);
1076        assert!(url.starts_with("https://docs.fallow.tools/"));
1077        assert!(url.contains("unused-exports"));
1078    }
1079
1080    // ── CHECK_RULES completeness ─────────────────────────────────────
1081
1082    #[test]
1083    fn check_rules_all_have_fallow_prefix() {
1084        for rule in CHECK_RULES {
1085            assert!(
1086                rule.id.starts_with("fallow/"),
1087                "rule {} should start with fallow/",
1088                rule.id
1089            );
1090        }
1091    }
1092
1093    #[test]
1094    fn check_rules_all_have_docs_path() {
1095        for rule in CHECK_RULES {
1096            assert!(
1097                !rule.docs_path.is_empty(),
1098                "rule {} should have a docs_path",
1099                rule.id
1100            );
1101        }
1102    }
1103
1104    #[test]
1105    fn check_rules_no_duplicate_ids() {
1106        let mut seen = rustc_hash::FxHashSet::default();
1107        for rule in CHECK_RULES.iter().chain(HEALTH_RULES).chain(DUPES_RULES) {
1108            assert!(seen.insert(rule.id), "duplicate rule id: {}", rule.id);
1109        }
1110    }
1111
1112    // ── check_meta ───────────────────────────────────────────────────
1113
1114    #[test]
1115    fn check_meta_has_docs_and_rules() {
1116        let meta = check_meta();
1117        assert!(meta.get("docs").is_some());
1118        assert!(meta.get("rules").is_some());
1119        let rules = meta["rules"].as_object().unwrap();
1120        // Verify all 13 rule categories are present (stripped fallow/ prefix)
1121        assert_eq!(rules.len(), CHECK_RULES.len());
1122        assert!(rules.contains_key("unused-file"));
1123        assert!(rules.contains_key("unused-export"));
1124        assert!(rules.contains_key("unused-type"));
1125        assert!(rules.contains_key("unused-dependency"));
1126        assert!(rules.contains_key("unused-dev-dependency"));
1127        assert!(rules.contains_key("unused-optional-dependency"));
1128        assert!(rules.contains_key("unused-enum-member"));
1129        assert!(rules.contains_key("unused-class-member"));
1130        assert!(rules.contains_key("unresolved-import"));
1131        assert!(rules.contains_key("unlisted-dependency"));
1132        assert!(rules.contains_key("duplicate-export"));
1133        assert!(rules.contains_key("type-only-dependency"));
1134        assert!(rules.contains_key("circular-dependency"));
1135    }
1136
1137    #[test]
1138    fn check_meta_documents_per_finding_auto_fixable() {
1139        let meta = check_meta();
1140        let defs = meta["field_definitions"].as_object().unwrap();
1141        let note = defs["actions[].auto_fixable"].as_str().unwrap();
1142        assert!(
1143            note.contains("PER FINDING"),
1144            "auto_fixable note must call out per-finding evaluation"
1145        );
1146        assert!(
1147            note.contains("remove-catalog-entry"),
1148            "auto_fixable note must cite remove-catalog-entry per-instance flip"
1149        );
1150        assert!(
1151            note.contains("used_in_workspaces"),
1152            "auto_fixable note must cite the dependency-action per-instance flip"
1153        );
1154        assert!(
1155            note.contains("ignoreExports"),
1156            "auto_fixable note must cite the duplicate-exports config-fixable flip"
1157        );
1158        assert!(defs.contains_key("actions[]"));
1159    }
1160
1161    #[test]
1162    fn health_and_dupes_meta_share_actions_field_definitions() {
1163        for meta in [health_meta(), dupes_meta()] {
1164            let defs = meta["field_definitions"].as_object().unwrap();
1165            assert_eq!(
1166                defs["actions[]"].as_str().unwrap(),
1167                ACTIONS_FIELD_DEFINITION,
1168            );
1169            assert_eq!(
1170                defs["actions[].auto_fixable"].as_str().unwrap(),
1171                ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION,
1172            );
1173        }
1174    }
1175
1176    #[test]
1177    fn check_meta_rule_has_required_fields() {
1178        let meta = check_meta();
1179        let rules = meta["rules"].as_object().unwrap();
1180        for (key, value) in rules {
1181            assert!(value.get("name").is_some(), "rule {key} missing 'name'");
1182            assert!(
1183                value.get("description").is_some(),
1184                "rule {key} missing 'description'"
1185            );
1186            assert!(value.get("docs").is_some(), "rule {key} missing 'docs'");
1187        }
1188    }
1189
1190    // ── health_meta ──────────────────────────────────────────────────
1191
1192    #[test]
1193    fn health_meta_has_metrics() {
1194        let meta = health_meta();
1195        assert!(meta.get("docs").is_some());
1196        let metrics = meta["metrics"].as_object().unwrap();
1197        assert!(metrics.contains_key("cyclomatic"));
1198        assert!(metrics.contains_key("cognitive"));
1199        assert!(metrics.contains_key("maintainability_index"));
1200        assert!(metrics.contains_key("complexity_density"));
1201        assert!(metrics.contains_key("fan_in"));
1202        assert!(metrics.contains_key("fan_out"));
1203    }
1204
1205    // ── dupes_meta ───────────────────────────────────────────────────
1206
1207    #[test]
1208    fn dupes_meta_has_metrics() {
1209        let meta = dupes_meta();
1210        assert!(meta.get("docs").is_some());
1211        let metrics = meta["metrics"].as_object().unwrap();
1212        assert!(metrics.contains_key("duplication_percentage"));
1213        assert!(metrics.contains_key("token_count"));
1214        assert!(metrics.contains_key("clone_groups"));
1215        assert!(metrics.contains_key("clone_families"));
1216    }
1217
1218    // ── coverage_setup_meta ─────────────────────────────────────────
1219
1220    #[test]
1221    fn coverage_setup_meta_has_docs_fields_enums_and_warnings() {
1222        let meta = coverage_setup_meta();
1223        assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
1224        assert!(
1225            meta["field_definitions"]
1226                .as_object()
1227                .unwrap()
1228                .contains_key("members[]")
1229        );
1230        assert!(
1231            meta["field_definitions"]
1232                .as_object()
1233                .unwrap()
1234                .contains_key("config_written")
1235        );
1236        assert!(
1237            meta["field_definitions"]
1238                .as_object()
1239                .unwrap()
1240                .contains_key("members[].package_manager")
1241        );
1242        assert!(
1243            meta["field_definitions"]
1244                .as_object()
1245                .unwrap()
1246                .contains_key("members[].warnings")
1247        );
1248        assert!(
1249            meta["enums"]
1250                .as_object()
1251                .unwrap()
1252                .contains_key("framework_detected")
1253        );
1254        assert!(
1255            meta["warnings"]
1256                .as_object()
1257                .unwrap()
1258                .contains_key("No runtime workspace members were detected")
1259        );
1260        assert!(
1261            meta["warnings"]
1262                .as_object()
1263                .unwrap()
1264                .contains_key("Package manager was not detected")
1265        );
1266    }
1267
1268    // ── coverage_analyze_meta ────────────────────────────────────────
1269
1270    #[test]
1271    fn coverage_analyze_meta_documents_data_source_and_action_vocabulary() {
1272        let meta = coverage_analyze_meta();
1273        assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
1274        let fields = meta["field_definitions"].as_object().unwrap();
1275        assert!(fields.contains_key("runtime_coverage.summary.data_source"));
1276        assert!(fields.contains_key("runtime_coverage.summary.last_received_at"));
1277        assert!(fields.contains_key("runtime_coverage.findings[].evidence.test_coverage"));
1278        assert!(fields.contains_key("runtime_coverage.findings[].actions[].type"));
1279        let enums = meta["enums"].as_object().unwrap();
1280        assert_eq!(enums["data_source"], json!(["local", "cloud"]));
1281        assert_eq!(enums["test_coverage"], json!(["covered", "not_covered"]));
1282        assert_eq!(enums["v8_tracking"], json!(["tracked", "untracked"]));
1283        assert_eq!(
1284            enums["action_type"],
1285            json!(["delete-cold-code", "review-runtime"])
1286        );
1287        let warnings = meta["warnings"].as_object().unwrap();
1288        assert!(warnings.contains_key("cloud_functions_unmatched"));
1289    }
1290
1291    // ── HEALTH_RULES completeness ──────────────────────────────────
1292
1293    #[test]
1294    fn health_rules_all_have_fallow_prefix() {
1295        for rule in HEALTH_RULES {
1296            assert!(
1297                rule.id.starts_with("fallow/"),
1298                "health rule {} should start with fallow/",
1299                rule.id
1300            );
1301        }
1302    }
1303
1304    #[test]
1305    fn health_rules_all_have_docs_path() {
1306        for rule in HEALTH_RULES {
1307            assert!(
1308                !rule.docs_path.is_empty(),
1309                "health rule {} should have a docs_path",
1310                rule.id
1311            );
1312        }
1313    }
1314
1315    #[test]
1316    fn health_rules_all_have_non_empty_fields() {
1317        for rule in HEALTH_RULES {
1318            assert!(
1319                !rule.name.is_empty(),
1320                "health rule {} missing name",
1321                rule.id
1322            );
1323            assert!(
1324                !rule.short.is_empty(),
1325                "health rule {} missing short description",
1326                rule.id
1327            );
1328            assert!(
1329                !rule.full.is_empty(),
1330                "health rule {} missing full description",
1331                rule.id
1332            );
1333        }
1334    }
1335
1336    // ── DUPES_RULES completeness ───────────────────────────────────
1337
1338    #[test]
1339    fn dupes_rules_all_have_fallow_prefix() {
1340        for rule in DUPES_RULES {
1341            assert!(
1342                rule.id.starts_with("fallow/"),
1343                "dupes rule {} should start with fallow/",
1344                rule.id
1345            );
1346        }
1347    }
1348
1349    #[test]
1350    fn dupes_rules_all_have_docs_path() {
1351        for rule in DUPES_RULES {
1352            assert!(
1353                !rule.docs_path.is_empty(),
1354                "dupes rule {} should have a docs_path",
1355                rule.id
1356            );
1357        }
1358    }
1359
1360    #[test]
1361    fn dupes_rules_all_have_non_empty_fields() {
1362        for rule in DUPES_RULES {
1363            assert!(!rule.name.is_empty(), "dupes rule {} missing name", rule.id);
1364            assert!(
1365                !rule.short.is_empty(),
1366                "dupes rule {} missing short description",
1367                rule.id
1368            );
1369            assert!(
1370                !rule.full.is_empty(),
1371                "dupes rule {} missing full description",
1372                rule.id
1373            );
1374        }
1375    }
1376
1377    // ── CHECK_RULES field completeness ─────────────────────────────
1378
1379    #[test]
1380    fn check_rules_all_have_non_empty_fields() {
1381        for rule in CHECK_RULES {
1382            assert!(!rule.name.is_empty(), "check rule {} missing name", rule.id);
1383            assert!(
1384                !rule.short.is_empty(),
1385                "check rule {} missing short description",
1386                rule.id
1387            );
1388            assert!(
1389                !rule.full.is_empty(),
1390                "check rule {} missing full description",
1391                rule.id
1392            );
1393        }
1394    }
1395
1396    // ── rule_docs_url with health/dupes rules ──────────────────────
1397
1398    #[test]
1399    fn rule_docs_url_health_rule() {
1400        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1401        let url = rule_docs_url(rule);
1402        assert!(url.starts_with("https://docs.fallow.tools/"));
1403        assert!(url.contains("health"));
1404    }
1405
1406    #[test]
1407    fn rule_docs_url_dupes_rule() {
1408        let rule = rule_by_id("fallow/code-duplication").unwrap();
1409        let url = rule_docs_url(rule);
1410        assert!(url.starts_with("https://docs.fallow.tools/"));
1411        assert!(url.contains("duplication"));
1412    }
1413
1414    // ── health_meta metric structure ───────────────────────────────
1415
1416    #[test]
1417    fn health_meta_all_metrics_have_name_and_description() {
1418        let meta = health_meta();
1419        let metrics = meta["metrics"].as_object().unwrap();
1420        for (key, value) in metrics {
1421            assert!(
1422                value.get("name").is_some(),
1423                "health metric {key} missing 'name'"
1424            );
1425            assert!(
1426                value.get("description").is_some(),
1427                "health metric {key} missing 'description'"
1428            );
1429            assert!(
1430                value.get("interpretation").is_some(),
1431                "health metric {key} missing 'interpretation'"
1432            );
1433        }
1434    }
1435
1436    #[test]
1437    fn health_meta_has_all_expected_metrics() {
1438        let meta = health_meta();
1439        let metrics = meta["metrics"].as_object().unwrap();
1440        let expected = [
1441            "cyclomatic",
1442            "cognitive",
1443            "line_count",
1444            "lines",
1445            "maintainability_index",
1446            "complexity_density",
1447            "dead_code_ratio",
1448            "fan_in",
1449            "fan_out",
1450            "score",
1451            "weighted_commits",
1452            "trend",
1453            "priority",
1454            "efficiency",
1455            "effort",
1456            "confidence",
1457            "bus_factor",
1458            "contributor_count",
1459            "share",
1460            "stale_days",
1461            "drift",
1462            "unowned",
1463            "runtime_coverage_verdict",
1464            "runtime_coverage_state",
1465            "runtime_coverage_confidence",
1466            "production_invocations",
1467            "percent_dead_in_production",
1468        ];
1469        for key in &expected {
1470            assert!(
1471                metrics.contains_key(*key),
1472                "health_meta missing expected metric: {key}"
1473            );
1474        }
1475    }
1476
1477    // ── dupes_meta metric structure ────────────────────────────────
1478
1479    #[test]
1480    fn dupes_meta_all_metrics_have_name_and_description() {
1481        let meta = dupes_meta();
1482        let metrics = meta["metrics"].as_object().unwrap();
1483        for (key, value) in metrics {
1484            assert!(
1485                value.get("name").is_some(),
1486                "dupes metric {key} missing 'name'"
1487            );
1488            assert!(
1489                value.get("description").is_some(),
1490                "dupes metric {key} missing 'description'"
1491            );
1492        }
1493    }
1494
1495    #[test]
1496    fn dupes_meta_has_line_count() {
1497        let meta = dupes_meta();
1498        let metrics = meta["metrics"].as_object().unwrap();
1499        assert!(metrics.contains_key("line_count"));
1500    }
1501
1502    // ── docs URLs ─────────────────────────────────────────────────
1503
1504    #[test]
1505    fn check_docs_url_valid() {
1506        assert!(CHECK_DOCS.starts_with("https://"));
1507        assert!(CHECK_DOCS.contains("dead-code"));
1508    }
1509
1510    #[test]
1511    fn health_docs_url_valid() {
1512        assert!(HEALTH_DOCS.starts_with("https://"));
1513        assert!(HEALTH_DOCS.contains("health"));
1514    }
1515
1516    #[test]
1517    fn dupes_docs_url_valid() {
1518        assert!(DUPES_DOCS.starts_with("https://"));
1519        assert!(DUPES_DOCS.contains("dupes"));
1520    }
1521
1522    // ── check_meta docs URL matches constant ──────────────────────
1523
1524    #[test]
1525    fn check_meta_docs_url_matches_constant() {
1526        let meta = check_meta();
1527        assert_eq!(meta["docs"].as_str().unwrap(), CHECK_DOCS);
1528    }
1529
1530    #[test]
1531    fn health_meta_docs_url_matches_constant() {
1532        let meta = health_meta();
1533        assert_eq!(meta["docs"].as_str().unwrap(), HEALTH_DOCS);
1534    }
1535
1536    #[test]
1537    fn dupes_meta_docs_url_matches_constant() {
1538        let meta = dupes_meta();
1539        assert_eq!(meta["docs"].as_str().unwrap(), DUPES_DOCS);
1540    }
1541
1542    // ── rule_by_id finds all check rules ──────────────────────────
1543
1544    #[test]
1545    fn rule_by_id_finds_all_check_rules() {
1546        for rule in CHECK_RULES {
1547            assert!(
1548                rule_by_id(rule.id).is_some(),
1549                "rule_by_id should find check rule {}",
1550                rule.id
1551            );
1552        }
1553    }
1554
1555    #[test]
1556    fn rule_by_id_finds_all_health_rules() {
1557        for rule in HEALTH_RULES {
1558            assert!(
1559                rule_by_id(rule.id).is_some(),
1560                "rule_by_id should find health rule {}",
1561                rule.id
1562            );
1563        }
1564    }
1565
1566    #[test]
1567    fn rule_by_id_finds_all_dupes_rules() {
1568        for rule in DUPES_RULES {
1569            assert!(
1570                rule_by_id(rule.id).is_some(),
1571                "rule_by_id should find dupes rule {}",
1572                rule.id
1573            );
1574        }
1575    }
1576
1577    // ── Rule count verification ───────────────────────────────────
1578
1579    #[test]
1580    fn check_rules_count() {
1581        assert_eq!(CHECK_RULES.len(), 23);
1582    }
1583
1584    #[test]
1585    fn health_rules_count() {
1586        assert_eq!(HEALTH_RULES.len(), 12);
1587    }
1588
1589    #[test]
1590    fn dupes_rules_count() {
1591        assert_eq!(DUPES_RULES.len(), 1);
1592    }
1593
1594    /// Every registered rule must declare a category. The PR/MR sticky
1595    /// renderer reads this via `category_for_rule`; without an entry the
1596    /// rule silently falls into the "Dead code" default and reviewers may
1597    /// see it grouped under an unexpected section. Catching this here is
1598    /// the same pattern as `check_rules_count` for the rule count itself.
1599    #[test]
1600    fn every_rule_declares_a_category() {
1601        let allowed = [
1602            "Dead code",
1603            "Dependencies",
1604            "Duplication",
1605            "Health",
1606            "Architecture",
1607            "Suppressions",
1608        ];
1609        for rule in CHECK_RULES.iter().chain(HEALTH_RULES).chain(DUPES_RULES) {
1610            assert!(
1611                !rule.category.is_empty(),
1612                "rule {} has empty category",
1613                rule.id
1614            );
1615            assert!(
1616                allowed.contains(&rule.category),
1617                "rule {} has unrecognised category {:?}; add to allowlist or pick from {:?}",
1618                rule.id,
1619                rule.category,
1620                allowed
1621            );
1622        }
1623    }
1624}