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