Skip to main content

fallow_cli/
explain.rs

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