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::collections::BTreeMap;
8use std::process::ExitCode;
9
10use colored::Colorize;
11use fallow_config::OutputFormat;
12use fallow_types::envelope::{Meta, MetaRule};
13use serde_json::{Value, json};
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/// Docs URL for the security command.
33pub const SECURITY_DOCS: &str = "https://docs.fallow.tools/cli/security";
34
35/// `_meta` description for the per-finding `actions[]` array shared across
36/// `check`, `health`, and `dupes` JSON output.
37const 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.";
38
39/// `_meta` description for the per-action `auto_fixable` bool. Calls out the
40/// per-finding (not per-action-type) evaluation rule and the currently active
41/// per-instance flips so agents know to branch on the field value of EACH
42/// finding's action, not on the action `type` alone.
43const 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`.";
44
45/// Rule definition for SARIF `fullDescription` and JSON `_meta`.
46pub struct RuleDef {
47    pub id: &'static str,
48    /// Coarse category label used by the sticky PR/MR comment renderer to
49    /// group findings into collapsible sections (Dead code, Dependencies,
50    /// Duplication, Health, Architecture, Suppressions). One source of
51    /// truth so the CodeClimate / SARIF / review-envelope path and the
52    /// renderer never drift; a unit test below asserts every RuleDef has
53    /// a non-empty category.
54    pub category: &'static str,
55    pub name: &'static str,
56    pub short: &'static str,
57    pub full: &'static str,
58    pub docs_path: &'static str,
59}
60
61pub const CHECK_RULES: &[RuleDef] = &[
62    RuleDef {
63        id: "fallow/unused-file",
64        category: "Dead code",
65        name: "Unused Files",
66        short: "File is not reachable from any entry point",
67        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.",
68        docs_path: "explanations/dead-code#unused-files",
69    },
70    RuleDef {
71        id: "fallow/unused-export",
72        category: "Dead code",
73        name: "Unused Exports",
74        short: "Export is never imported",
75        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.",
76        docs_path: "explanations/dead-code#unused-exports",
77    },
78    RuleDef {
79        id: "fallow/unused-type",
80        category: "Dead code",
81        name: "Unused Type Exports",
82        short: "Type export is never imported",
83        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.",
84        docs_path: "explanations/dead-code#unused-types",
85    },
86    RuleDef {
87        id: "fallow/private-type-leak",
88        category: "Dead code",
89        name: "Private Type Leaks",
90        short: "Exported signature references a private type",
91        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.",
92        docs_path: "explanations/dead-code#private-type-leaks",
93    },
94    RuleDef {
95        id: "fallow/unused-dependency",
96        category: "Dependencies",
97        name: "Unused Dependencies",
98        short: "Dependency listed but never imported",
99        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.",
100        docs_path: "explanations/dead-code#unused-dependencies",
101    },
102    RuleDef {
103        id: "fallow/unused-dev-dependency",
104        category: "Dependencies",
105        name: "Unused Dev Dependencies",
106        short: "Dev dependency listed but never imported",
107        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.",
108        docs_path: "explanations/dead-code#unused-devdependencies",
109    },
110    RuleDef {
111        id: "fallow/unused-optional-dependency",
112        category: "Dependencies",
113        name: "Unused Optional Dependencies",
114        short: "Optional dependency listed but never imported",
115        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.",
116        docs_path: "explanations/dead-code#unused-optionaldependencies",
117    },
118    RuleDef {
119        id: "fallow/type-only-dependency",
120        category: "Dependencies",
121        name: "Type-only Dependencies",
122        short: "Production dependency only used via type-only imports",
123        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.",
124        docs_path: "explanations/dead-code#type-only-dependencies",
125    },
126    RuleDef {
127        id: "fallow/test-only-dependency",
128        category: "Dependencies",
129        name: "Test-only Dependencies",
130        short: "Production dependency only imported by test files",
131        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.",
132        docs_path: "explanations/dead-code#test-only-dependencies",
133    },
134    RuleDef {
135        id: "fallow/unused-enum-member",
136        category: "Dead code",
137        name: "Unused Enum Members",
138        short: "Enum member is never referenced",
139        full: "Enum members that are never referenced in the codebase. Uses scope-aware binding analysis to track all references including computed access patterns.",
140        docs_path: "explanations/dead-code#unused-enum-members",
141    },
142    RuleDef {
143        id: "fallow/unused-class-member",
144        category: "Dead code",
145        name: "Unused Class Members",
146        short: "Class member is never referenced",
147        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.",
148        docs_path: "explanations/dead-code#unused-class-members",
149    },
150    RuleDef {
151        id: "fallow/unresolved-import",
152        category: "Dead code",
153        name: "Unresolved Imports",
154        short: "Import could not be resolved",
155        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.",
156        docs_path: "explanations/dead-code#unresolved-imports",
157    },
158    RuleDef {
159        id: "fallow/unlisted-dependency",
160        category: "Dependencies",
161        name: "Unlisted Dependencies",
162        short: "Dependency used but not in package.json",
163        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.",
164        docs_path: "explanations/dead-code#unlisted-dependencies",
165    },
166    RuleDef {
167        id: "fallow/duplicate-export",
168        category: "Dead code",
169        name: "Duplicate Exports",
170        short: "Export name appears in multiple modules",
171        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.",
172        docs_path: "explanations/dead-code#duplicate-exports",
173    },
174    RuleDef {
175        id: "fallow/circular-dependency",
176        category: "Architecture",
177        name: "Circular Dependencies",
178        short: "Circular dependency chain detected",
179        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.",
180        docs_path: "explanations/dead-code#circular-dependencies",
181    },
182    RuleDef {
183        id: "fallow/re-export-cycle",
184        category: "Architecture",
185        name: "Re-Export Cycles",
186        short: "Two or more barrel files re-export from each other in a loop",
187        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`.",
188        docs_path: "explanations/dead-code#re-export-cycles",
189    },
190    RuleDef {
191        id: "fallow/boundary-violation",
192        category: "Architecture",
193        name: "Boundary Violations",
194        short: "Import crosses a configured architecture boundary",
195        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.",
196        docs_path: "explanations/dead-code#boundary-violations",
197    },
198    RuleDef {
199        id: "fallow/boundary-coverage",
200        category: "Architecture",
201        name: "Boundary Coverage",
202        short: "Source file matches no configured architecture boundary zone",
203        full: "A reachable source file is not assigned to any configured boundary zone while boundaries.coverage.requireAllFiles is enabled. Add the file to a zone pattern, move it under an existing zone, or allow-list generated and intentionally unzoned paths with boundaries.coverage.allowUnmatched.",
204        docs_path: "explanations/dead-code#boundary-violations",
205    },
206    RuleDef {
207        id: "fallow/boundary-call-violation",
208        category: "Architecture",
209        name: "Boundary Call Violation",
210        short: "Zoned file calls a callee its zone forbids",
211        full: "A file classified into a boundary zone calls a callee matching one of the zone's boundaries.calls.forbidden patterns. The check is syntactic: it matches the written callee path and the import-resolved canonical path, and it only applies to files classified into a zone. Move the call behind an allowed abstraction, or adjust the zone's forbidden patterns if the rule was wrong.",
212        docs_path: "explanations/dead-code#boundary-violations",
213    },
214    RuleDef {
215        id: "fallow/policy-violation",
216        category: "Policy",
217        name: "Policy Violation",
218        short: "Banned call or import matched a rule-pack rule",
219        full: "A call site or import matched a banned-call or banned-import rule from a configured rule pack (the rulePacks config key). Packs are pure declarative data; the check is syntactic and does not follow aliased or re-bound callees, and import matching uses the raw specifier. Replace the banned usage per the rule's message, scope the rule with files/exclude globs, or adjust its severity.",
220        docs_path: "explanations/dead-code#policy-violations",
221    },
222    RuleDef {
223        id: "fallow/stale-suppression",
224        category: "Suppressions",
225        name: "Stale Suppressions",
226        short: "Suppression comment or tag no longer matches any issue",
227        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.",
228        docs_path: "explanations/dead-code#stale-suppressions",
229    },
230    RuleDef {
231        id: "fallow/unused-catalog-entry",
232        category: "Dependencies",
233        name: "Unused pnpm catalog entry",
234        short: "Catalog entry in pnpm-workspace.yaml not referenced by any workspace package",
235        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).",
236        docs_path: "explanations/dead-code#unused-catalog-entries",
237    },
238    RuleDef {
239        id: "fallow/empty-catalog-group",
240        category: "Dependencies",
241        name: "Empty pnpm catalog group",
242        short: "Named catalog group in pnpm-workspace.yaml has no entries",
243        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.",
244        docs_path: "explanations/dead-code#empty-catalog-groups",
245    },
246    RuleDef {
247        id: "fallow/unresolved-catalog-reference",
248        category: "Dependencies",
249        name: "Unresolved pnpm catalog reference",
250        short: "package.json references a catalog that does not declare the package",
251        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).",
252        docs_path: "explanations/dead-code#unresolved-catalog-references",
253    },
254    RuleDef {
255        id: "fallow/unused-dependency-override",
256        category: "Dependencies",
257        name: "Unused pnpm dependency override",
258        short: "pnpm.overrides entry targets a package not declared or resolved",
259        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.",
260        docs_path: "explanations/dead-code#unused-dependency-overrides",
261    },
262    RuleDef {
263        id: "fallow/misconfigured-dependency-override",
264        category: "Dependencies",
265        name: "Misconfigured pnpm dependency override",
266        short: "pnpm.overrides entry has an unparsable key or value",
267        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.",
268        docs_path: "explanations/dead-code#misconfigured-dependency-overrides",
269    },
270];
271
272/// Look up a rule definition by its SARIF rule ID across all rule sets.
273#[must_use]
274pub fn rule_by_id(id: &str) -> Option<&'static RuleDef> {
275    CHECK_RULES
276        .iter()
277        .chain(HEALTH_RULES.iter())
278        .chain(DUPES_RULES.iter())
279        .chain(FLAGS_RULES.iter())
280        .chain(SECURITY_RULES.iter())
281        .find(|r| r.id == id)
282}
283
284/// Build the docs URL for a rule.
285#[must_use]
286pub fn rule_docs_url(rule: &RuleDef) -> String {
287    format!("{DOCS_BASE}/{}", rule.docs_path)
288}
289
290/// Extra educational content for the standalone `fallow explain <issue-type>`
291/// command. Kept separate from [`RuleDef`] so SARIF and `_meta` payloads remain
292/// compact while terminal users and agents can ask for worked examples on
293/// demand.
294pub struct RuleGuide {
295    pub example: &'static str,
296    pub how_to_fix: &'static str,
297}
298
299/// Look up an issue type from a user-facing token.
300///
301/// Accepts canonical SARIF ids (`fallow/unused-export`), issue tokens
302/// (`unused-export`), and common CLI filter spellings (`unused-exports`).
303#[must_use]
304pub fn rule_by_token(token: &str) -> Option<&'static RuleDef> {
305    let trimmed = token.trim();
306    if trimmed.is_empty() {
307        return None;
308    }
309    if let Some(rule) = rule_by_id(trimmed) {
310        return Some(rule);
311    }
312    let normalized = trimmed
313        .strip_prefix("fallow/")
314        .unwrap_or(trimmed)
315        .trim_start_matches("--")
316        .replace('_', "-")
317        .split_whitespace()
318        .collect::<Vec<_>>()
319        .join("-");
320    let alias = match normalized.as_str() {
321        "unused-files" => Some("fallow/unused-file"),
322        "unused-exports" => Some("fallow/unused-export"),
323        "unused-types" => Some("fallow/unused-type"),
324        "private-type-leaks" => Some("fallow/private-type-leak"),
325        "unused-deps" | "unused-dependencies" => Some("fallow/unused-dependency"),
326        "unused-dev-deps" | "unused-dev-dependencies" => Some("fallow/unused-dev-dependency"),
327        "unused-optional-deps" | "unused-optional-dependencies" => {
328            Some("fallow/unused-optional-dependency")
329        }
330        "type-only-deps" | "type-only-dependencies" => Some("fallow/type-only-dependency"),
331        "test-only-deps" | "test-only-dependencies" => Some("fallow/test-only-dependency"),
332        "unused-enum-members" => Some("fallow/unused-enum-member"),
333        "unused-class-members" => Some("fallow/unused-class-member"),
334        "unresolved-imports" => Some("fallow/unresolved-import"),
335        "unlisted-deps" | "unlisted-dependencies" => Some("fallow/unlisted-dependency"),
336        "duplicate-exports" => Some("fallow/duplicate-export"),
337        "circular-deps" | "circular-dependencies" => Some("fallow/circular-dependency"),
338        "boundary-violations" => Some("fallow/boundary-violation"),
339        "boundary-coverage" | "boundary-coverage-violations" => Some("fallow/boundary-coverage"),
340        "boundary-calls" | "boundary-call-violations" => Some("fallow/boundary-call-violation"),
341        "policy-violation" | "policy-violations" => Some("fallow/policy-violation"),
342        "stale-suppressions" => Some("fallow/stale-suppression"),
343        "unused-catalog-entries" | "unused-catalog-entry" | "catalog" => {
344            Some("fallow/unused-catalog-entry")
345        }
346        "empty-catalog-groups" | "empty-catalog-group" | "empty-catalog" => {
347            Some("fallow/empty-catalog-group")
348        }
349        "unresolved-catalog-references" | "unresolved-catalog-reference" | "unresolved-catalog" => {
350            Some("fallow/unresolved-catalog-reference")
351        }
352        "unused-dependency-overrides"
353        | "unused-dependency-override"
354        | "unused-override"
355        | "unused-overrides" => Some("fallow/unused-dependency-override"),
356        "misconfigured-dependency-overrides"
357        | "misconfigured-dependency-override"
358        | "misconfigured-override"
359        | "misconfigured-overrides" => Some("fallow/misconfigured-dependency-override"),
360        "complexity" | "high-complexity" => Some("fallow/high-complexity"),
361        "cyclomatic" | "high-cyclomatic" | "high-cyclomatic-complexity" => {
362            Some("fallow/high-cyclomatic-complexity")
363        }
364        "cognitive" | "high-cognitive" | "high-cognitive-complexity" => {
365            Some("fallow/high-cognitive-complexity")
366        }
367        "crap" | "high-crap" | "high-crap-score" => Some("fallow/high-crap-score"),
368        "duplication" | "dupes" | "code-duplication" => Some("fallow/code-duplication"),
369        "feature-flag" | "feature-flags" | "flags" => Some("fallow/feature-flag"),
370        "security"
371        | "security-candidate"
372        | "security-candidates"
373        | "tainted-sink"
374        | "tainted-sinks"
375        | "security-sink"
376        | "security-sinks" => Some("security/tainted-sink"),
377        "client-server-leak"
378        | "client-server-leaks"
379        | "security-client-server-leak"
380        | "security-client-server-leaks" => Some("security/client-server-leak"),
381        "hardcoded-secret" | "hardcoded-secrets" | "hard-coded-secret" | "hard-coded-secrets" => {
382            Some("security/hardcoded-secret")
383        }
384        _ => None,
385    };
386    if let Some(id) = alias
387        && let Some(rule) = rule_by_id(id)
388    {
389        return Some(rule);
390    }
391    let security_token = normalized.strip_prefix("security-").unwrap_or(&normalized);
392    let security_id = format!("security/{security_token}");
393    if let Some(rule) = rule_by_id(&security_id) {
394        return Some(rule);
395    }
396    let singular = normalized
397        .strip_suffix('s')
398        .filter(|_| normalized != "unused-class")
399        .unwrap_or(&normalized);
400    let singular_security_token = singular.strip_prefix("security-").unwrap_or(singular);
401    let singular_security_id = format!("security/{singular_security_token}");
402    if let Some(rule) = rule_by_id(&singular_security_id) {
403        return Some(rule);
404    }
405    let id = format!("fallow/{singular}");
406    rule_by_id(&id).or_else(|| {
407        CHECK_RULES
408            .iter()
409            .chain(HEALTH_RULES.iter())
410            .chain(DUPES_RULES.iter())
411            .chain(FLAGS_RULES.iter())
412            .chain(SECURITY_RULES.iter())
413            .find(|rule| {
414                rule.docs_path.ends_with(&normalized)
415                    || rule.docs_path.ends_with(singular)
416                    || rule.name.eq_ignore_ascii_case(trimmed)
417            })
418    })
419}
420
421/// Return worked-example and fix guidance for a rule.
422#[must_use]
423pub fn rule_guide(rule: &RuleDef) -> RuleGuide {
424    source_dead_code_rule_guide(rule.id)
425        .or_else(|| member_import_rule_guide(rule.id))
426        .or_else(|| architecture_rule_guide(rule.id))
427        .or_else(|| catalog_rule_guide(rule.id))
428        .or_else(|| health_runtime_rule_guide(rule.id))
429        .or_else(|| duplication_rule_guide(rule.id))
430        .or_else(|| security_rule_guide(rule.id))
431        .unwrap_or_else(fallback_rule_guide)
432}
433
434fn source_dead_code_rule_guide(id: &str) -> Option<RuleGuide> {
435    Some(match id {
436        "fallow/unused-file" => RuleGuide {
437            example: "src/old-widget.ts is not imported by any entry point, route, script, or config file.",
438            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.",
439        },
440        "fallow/unused-export" => RuleGuide {
441            example: "export const formatPrice = ... exists in src/money.ts, but no module imports formatPrice.",
442            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.",
443        },
444        "fallow/unused-type" => RuleGuide {
445            example: "export interface LegacyProps is exported, but no module imports the type.",
446            how_to_fix: "Remove the type export, inline it, or keep it behind an explicit API entry point when consumers rely on it.",
447        },
448        "fallow/private-type-leak" => RuleGuide {
449            example: "export function makeUser(): InternalUser exposes InternalUser even though InternalUser is not exported.",
450            how_to_fix: "Export the referenced type, change the public signature to an exported type, or keep the helper private.",
451        },
452        "fallow/unused-dependency"
453        | "fallow/unused-dev-dependency"
454        | "fallow/unused-optional-dependency" => RuleGuide {
455            example: "package.json lists left-pad, but no source, script, config, or plugin-recognized file imports it.",
456            how_to_fix: "Remove the dependency after checking runtime/plugin usage. If another workspace uses it, move the dependency to that workspace.",
457        },
458        "fallow/type-only-dependency" => RuleGuide {
459            example: "zod is in dependencies but only appears in import type declarations.",
460            how_to_fix: "Move the package to devDependencies unless runtime code imports it as a value.",
461        },
462        "fallow/test-only-dependency" => RuleGuide {
463            example: "vitest is listed in dependencies, but only test files import it.",
464            how_to_fix: "Move the package to devDependencies unless production code imports it at runtime.",
465        },
466        _ => return None,
467    })
468}
469
470fn member_import_rule_guide(id: &str) -> Option<RuleGuide> {
471    Some(match id {
472        "fallow/unused-enum-member" => RuleGuide {
473            example: "Status.Legacy remains in an exported enum, but no code reads that member.",
474            how_to_fix: "Remove the member after checking serialized/API compatibility, or suppress it with a reason when external data still uses it.",
475        },
476        "fallow/unused-class-member" => RuleGuide {
477            example: "class Parser has a public parseLegacy method that is never called in the project.",
478            how_to_fix: "Remove or privatize the member. For reflection/framework lifecycle hooks, configure or suppress the intentional entry point.",
479        },
480        "fallow/unresolved-import" => RuleGuide {
481            example: "src/app.ts imports ./routes/admin, but no matching file exists after extension and index resolution.",
482            how_to_fix: "Fix the specifier, restore the missing file, install the package, or align tsconfig path aliases with the runtime resolver.",
483        },
484        "fallow/unlisted-dependency" => RuleGuide {
485            example: "src/api.ts imports undici, but the nearest package.json does not list undici.",
486            how_to_fix: "Add the package to dependencies/devDependencies in the workspace that imports it instead of relying on hoisting or transitive deps.",
487        },
488        "fallow/duplicate-export" => RuleGuide {
489            example: "Button is exported from both src/ui/button.ts and src/components/button.ts.",
490            how_to_fix: "Rename or consolidate the exports so consumers have one intentional import target.",
491        },
492        _ => return None,
493    })
494}
495
496fn architecture_rule_guide(id: &str) -> Option<RuleGuide> {
497    Some(match id {
498        "fallow/circular-dependency" => RuleGuide {
499            example: "src/a.ts imports src/b.ts, and src/b.ts imports src/a.ts.",
500            how_to_fix: "Extract shared code to a third module, invert the dependency, or split initialization-time side effects from type-only contracts.",
501        },
502        "fallow/boundary-violation" => RuleGuide {
503            example: "features/billing imports app/admin even though the configured boundary only allows imports from shared and entities.",
504            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.",
505        },
506        "fallow/boundary-coverage" => RuleGuide {
507            example: "src/generated/client.ts is reachable but does not match any boundaries.zones[].patterns entry.",
508            how_to_fix: "Add the file to the intended zone pattern, move it under a zoned directory, or add a generated-file glob to boundaries.coverage.allowUnmatched.",
509        },
510        "fallow/boundary-call-violation" => RuleGuide {
511            example: "src/domain/policy.ts calls execSync from node:child_process while boundaries.calls.forbidden bans child_process.* from the domain zone.",
512            how_to_fix: "Move the call into a zone that may perform the effect, route it through an allowed abstraction, or narrow the forbidden pattern if the rule was wrong. To suppress, use the boundary family token: `// fallow-ignore-next-line boundary-violation` governs import, coverage, and call findings alike (the rule-id-shaped `boundary-call-violation` is accepted as an alias).",
513        },
514        "fallow/policy-violation" => RuleGuide {
515            example: "src/app.ts imports moment while a rule pack bans the moment specifier with the message 'Use date-fns.'",
516            how_to_fix: "Replace the banned call or import with the alternative named in the rule's message. To waive a single line, use `// fallow-ignore-next-line policy-violation`; note the token covers every rule-pack rule on that line, and the file-level form covers the whole file.",
517        },
518        "fallow/stale-suppression" => RuleGuide {
519            example: "// fallow-ignore-next-line unused-export remains above an export that is now used.",
520            how_to_fix: "Remove the suppression. If a different issue is still intentional, replace it with a current, specific suppression.",
521        },
522        _ => return None,
523    })
524}
525
526fn catalog_rule_guide(id: &str) -> Option<RuleGuide> {
527    Some(match id {
528        "fallow/unused-catalog-entry" => RuleGuide {
529            example: "pnpm-workspace.yaml declares `catalog: { is-even: ^1.0.0 }`, but no workspace package.json declares `\"is-even\": \"catalog:\"`.",
530            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.",
531        },
532        "fallow/empty-catalog-group" => RuleGuide {
533            example: "pnpm-workspace.yaml declares `catalogs: { react17: {} }` after the last react17 entry was removed.",
534            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.",
535        },
536        "fallow/unresolved-catalog-reference" => RuleGuide {
537            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.",
538            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.",
539        },
540        "fallow/unused-dependency-override" => RuleGuide {
541            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.",
542            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.",
543        },
544        "fallow/misconfigured-dependency-override" => RuleGuide {
545            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.",
546            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.",
547        },
548        _ => return None,
549    })
550}
551
552fn health_runtime_rule_guide(id: &str) -> Option<RuleGuide> {
553    Some(match id {
554        "fallow/high-cyclomatic-complexity"
555        | "fallow/high-cognitive-complexity"
556        | "fallow/high-complexity" => RuleGuide {
557            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.",
558            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`.",
559        },
560        "fallow/high-crap-score" => RuleGuide {
561            example: "A complex function has little or no matching Istanbul coverage, so its CRAP score crosses the configured gate.",
562            how_to_fix: "Add focused tests for the risky branches first, then simplify the function if the score remains high.",
563        },
564        "fallow/refactoring-target" => RuleGuide {
565            example: "A file combines high complexity density, churn, fan-in, and dead-code signals.",
566            how_to_fix: "Start with the listed evidence: remove dead exports, extract complex functions, then reduce fan-out or cycles in small steps.",
567        },
568        "fallow/untested-file" | "fallow/untested-export" => RuleGuide {
569            example: "Production-reachable code has no dependency path from discovered test entry points.",
570            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.",
571        },
572        "fallow/runtime-safe-to-delete"
573        | "fallow/runtime-review-required"
574        | "fallow/runtime-low-traffic"
575        | "fallow/runtime-coverage-unavailable"
576        | "fallow/runtime-coverage" => RuleGuide {
577            example: "Runtime coverage shows a function was never called, barely called, or could not be matched during the capture window.",
578            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.",
579        },
580        _ => return None,
581    })
582}
583
584fn duplication_rule_guide(id: &str) -> Option<RuleGuide> {
585    Some(match id {
586        "fallow/code-duplication" => RuleGuide {
587            example: "Two files contain the same normalized token sequence across a multi-line block.",
588            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.",
589        },
590        _ => return None,
591    })
592}
593
594fn security_rule_guide(id: &str) -> Option<RuleGuide> {
595    Some(match id {
596        "security/tainted-sink" => RuleGuide {
597            example: "A non-literal request field reaches a catalogue sink such as security/sql-injection or security/dangerous-html. The finding is a candidate, not proof of exploitability.",
598            how_to_fix: "Trace the source, sink, sanitization, and runtime context. Fix confirmed issues with parameterization, escaping, validation, or safer APIs, and suppress only reviewed false positives with context.",
599        },
600        "security/client-server-leak" => RuleGuide {
601            example: "A module marked `use client` imports code that reads a non-public `process.env` or `import.meta.env` value through a static path.",
602            how_to_fix: "Keep non-public env reads on the server side, move the value behind an API boundary, or rename only intentionally public values to the framework's public prefix.",
603        },
604        "security/hardcoded-secret" => RuleGuide {
605            example: "A provider-prefixed token-shaped literal is assigned to a secret-shaped variable, and the hardcoded-secret category is explicitly included.",
606            how_to_fix: "Rotate real credentials, move them to a secret manager or environment variable, and keep test-only literals clearly fake so they do not resemble provider tokens.",
607        },
608        id if id.starts_with("security/") => RuleGuide {
609            example: "A `fallow security` candidate uses this catalogue category as its SARIF rule id, for example security/sql-injection for a matched SQL sink.",
610            how_to_fix: "Review the candidate trace before acting. Confirm attacker control, missing sanitization, and reachable runtime context, then fix with the category-appropriate safer API or add a reviewed suppression.",
611        },
612        _ => return None,
613    })
614}
615
616fn fallback_rule_guide() -> RuleGuide {
617    RuleGuide {
618        example: "Run the relevant command with --format json --quiet --explain to inspect this rule in context.",
619        how_to_fix: "Use the issue action hints, source location, and docs URL to decide whether to remove, move, configure, or suppress the finding.",
620    }
621}
622
623/// Run the standalone explain subcommand.
624#[must_use]
625pub fn run_explain(issue_type: &str, output: OutputFormat) -> ExitCode {
626    let Some(rule) = rule_by_token(issue_type) else {
627        let message = if looks_security_explain_token(issue_type) {
628            format!(
629                "unknown issue type '{issue_type}'. Try values like tainted-sink, client-server-leak, hardcoded-secret, sql-injection, or security/sql-injection"
630            )
631        } else {
632            format!(
633                "unknown issue type '{issue_type}'. Try values like unused files, unused-export, high complexity, or code duplication"
634            )
635        };
636        return crate::error::emit_error(&message, 2, output);
637    };
638    let guide = rule_guide(rule);
639    match output {
640        OutputFormat::Json => {
641            let envelope = crate::output_envelope::ExplainOutput {
642                id: rule.id.to_string(),
643                name: rule.name.to_string(),
644                summary: rule.short.to_string(),
645                rationale: rule.full.to_string(),
646                example: guide.example.to_string(),
647                how_to_fix: guide.how_to_fix.to_string(),
648                docs: rule_docs_url(rule),
649            };
650            match crate::output_envelope::serialize_root_output(
651                crate::output_envelope::FallowOutput::Explain(envelope),
652            ) {
653                Ok(value) => crate::report::emit_json(&value, "explain"),
654                Err(e) => {
655                    crate::error::emit_error(&format!("JSON serialization error: {e}"), 2, output)
656                }
657            }
658        }
659        OutputFormat::Human => print_explain_human(rule, &guide),
660        OutputFormat::Compact => print_explain_compact(rule),
661        OutputFormat::Markdown => print_explain_markdown(rule, &guide),
662        OutputFormat::Sarif
663        | OutputFormat::CodeClimate
664        | OutputFormat::PrCommentGithub
665        | OutputFormat::PrCommentGitlab
666        | OutputFormat::ReviewGithub
667        | OutputFormat::ReviewGitlab
668        | OutputFormat::Badge => crate::error::emit_error(
669            "explain supports human, compact, markdown, and json output",
670            2,
671            output,
672        ),
673    }
674}
675
676fn looks_security_explain_token(issue_type: &str) -> bool {
677    let normalized = issue_type.trim().to_ascii_lowercase().replace('_', "-");
678    normalized.contains("security")
679        || normalized.contains("secret")
680        || normalized.contains("sink")
681        || normalized.contains("cwe")
682        || normalized.contains("client-server")
683        || normalized.contains("injection")
684}
685
686fn print_explain_human(rule: &RuleDef, guide: &RuleGuide) -> ExitCode {
687    println!("{}", rule.name.bold());
688    println!("{}", rule.id.dimmed());
689    println!();
690    println!("{}", rule.short);
691    println!();
692    println!("{}", "Why it matters".bold());
693    println!("{}", rule.full);
694    println!();
695    println!("{}", "Example".bold());
696    println!("{}", guide.example);
697    println!();
698    println!("{}", "How to fix".bold());
699    println!("{}", guide.how_to_fix);
700    println!();
701    println!("{} {}", "Docs:".dimmed(), rule_docs_url(rule).dimmed());
702    ExitCode::SUCCESS
703}
704
705fn print_explain_compact(rule: &RuleDef) -> ExitCode {
706    println!("explain:{}:{}:{}", rule.id, rule.short, rule_docs_url(rule));
707    ExitCode::SUCCESS
708}
709
710fn print_explain_markdown(rule: &RuleDef, guide: &RuleGuide) -> ExitCode {
711    println!("# {}", rule.name);
712    println!();
713    println!("`{}`", rule.id);
714    println!();
715    println!("{}", rule.short);
716    println!();
717    println!("## Why it matters");
718    println!();
719    println!("{}", rule.full);
720    println!();
721    println!("## Example");
722    println!();
723    println!("{}", guide.example);
724    println!();
725    println!("## How to fix");
726    println!();
727    println!("{}", guide.how_to_fix);
728    println!();
729    println!("[Docs]({})", rule_docs_url(rule));
730    ExitCode::SUCCESS
731}
732
733pub const HEALTH_RULES: &[RuleDef] = &[
734    RuleDef {
735        id: "fallow/high-cyclomatic-complexity",
736        category: "Health",
737        name: "High Cyclomatic Complexity",
738        short: "Function has high cyclomatic complexity",
739        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`.",
740        docs_path: "explanations/health#cyclomatic-complexity",
741    },
742    RuleDef {
743        id: "fallow/high-cognitive-complexity",
744        category: "Health",
745        name: "High Cognitive Complexity",
746        short: "Function has high cognitive complexity",
747        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`.",
748        docs_path: "explanations/health#cognitive-complexity",
749    },
750    RuleDef {
751        id: "fallow/high-complexity",
752        category: "Health",
753        name: "High Complexity (Both)",
754        short: "Function exceeds both complexity thresholds",
755        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`.",
756        docs_path: "explanations/health#complexity-metrics",
757    },
758    RuleDef {
759        id: "fallow/high-crap-score",
760        category: "Health",
761        name: "High CRAP Score",
762        short: "Function has a high CRAP score (complexity combined with low coverage)",
763        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.",
764        docs_path: "explanations/health#crap-score",
765    },
766    RuleDef {
767        id: "fallow/refactoring-target",
768        category: "Health",
769        name: "Refactoring Target",
770        short: "File identified as a high-priority refactoring candidate",
771        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.",
772        docs_path: "explanations/health#refactoring-targets",
773    },
774    RuleDef {
775        id: "fallow/untested-file",
776        category: "Health",
777        name: "Untested File",
778        short: "Runtime-reachable file has no test dependency path",
779        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.",
780        docs_path: "explanations/health#coverage-gaps",
781    },
782    RuleDef {
783        id: "fallow/untested-export",
784        category: "Health",
785        name: "Untested Export",
786        short: "Runtime-reachable export has no test dependency path",
787        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.",
788        docs_path: "explanations/health#coverage-gaps",
789    },
790    RuleDef {
791        id: "fallow/runtime-safe-to-delete",
792        category: "Health",
793        name: "Production Safe To Delete",
794        short: "Statically unused AND never invoked in production with V8 tracking",
795        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.",
796        docs_path: "explanations/health#runtime-coverage",
797    },
798    RuleDef {
799        id: "fallow/runtime-review-required",
800        category: "Health",
801        name: "Production Review Required",
802        short: "Statically used but never invoked in production",
803        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.",
804        docs_path: "explanations/health#runtime-coverage",
805    },
806    RuleDef {
807        id: "fallow/runtime-low-traffic",
808        category: "Health",
809        name: "Production Low Traffic",
810        short: "Function was invoked below the low-traffic threshold",
811        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.",
812        docs_path: "explanations/health#runtime-coverage",
813    },
814    RuleDef {
815        id: "fallow/runtime-coverage-unavailable",
816        category: "Health",
817        name: "Runtime Coverage Unavailable",
818        short: "Runtime coverage could not be resolved for this function",
819        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.",
820        docs_path: "explanations/health#runtime-coverage",
821    },
822    RuleDef {
823        id: "fallow/runtime-coverage",
824        category: "Health",
825        name: "Runtime Coverage",
826        short: "Runtime coverage finding",
827        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.",
828        docs_path: "explanations/health#runtime-coverage",
829    },
830    RuleDef {
831        id: "fallow/coverage-intelligence-risky-change",
832        category: "Health",
833        name: "Coverage Intelligence Risky Change",
834        short: "Changed hot path combines high CRAP and low test coverage",
835        full: "Coverage intelligence combined change scope, runtime hot-path evidence, low test coverage, and high CRAP into a risky-change finding. Add focused tests or split the change before merging.",
836        docs_path: "explanations/health#coverage-intelligence",
837    },
838    RuleDef {
839        id: "fallow/coverage-intelligence-delete",
840        category: "Health",
841        name: "Coverage Intelligence Delete",
842        short: "Static and runtime evidence indicate code can be deleted",
843        full: "Coverage intelligence combined static unused status, runtime cold evidence, and lack of test reachability into a high-confidence delete recommendation.",
844        docs_path: "explanations/health#coverage-intelligence",
845    },
846    RuleDef {
847        id: "fallow/coverage-intelligence-review",
848        category: "Health",
849        name: "Coverage Intelligence Review",
850        short: "Cold reachable uncovered code needs owner review",
851        full: "Coverage intelligence found code that is statically reachable but cold in runtime evidence, uncovered by tests, and ownership-risky. Route it to an owner before changing or deleting it.",
852        docs_path: "explanations/health#coverage-intelligence",
853    },
854    RuleDef {
855        id: "fallow/coverage-intelligence-refactor",
856        category: "Health",
857        name: "Coverage Intelligence Refactor",
858        short: "Hot covered code has high CRAP and should be refactored carefully",
859        full: "Coverage intelligence found hot production code that is covered by tests but still has high CRAP. Refactor carefully while preserving behavior.",
860        docs_path: "explanations/health#coverage-intelligence",
861    },
862];
863
864pub const DUPES_RULES: &[RuleDef] = &[RuleDef {
865    id: "fallow/code-duplication",
866    category: "Duplication",
867    name: "Code Duplication",
868    short: "Duplicated code block",
869    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.",
870    docs_path: "explanations/duplication#clone-groups",
871}];
872
873pub const FLAGS_RULES: &[RuleDef] = &[RuleDef {
874    id: "fallow/feature-flag",
875    category: "Flags",
876    name: "Feature Flags",
877    short: "Detected feature flag pattern",
878    full: "A feature flag pattern detected by `fallow flags`: environment-variable checks, flag SDK calls (LaunchDarkly, Unleash, and similar), or config-object lookups. Long-lived flags accumulate dead branches; review old flags for retirement and pair with dead-code analysis to find branches that can no longer execute.",
879    docs_path: "cli/flags",
880}];
881
882macro_rules! security_catalogue_rule {
883    ($id:literal, $name:literal, $cwe:literal) => {
884        RuleDef {
885            id: concat!("security/", $id),
886            category: "Security",
887            name: $name,
888            short: concat!("Catalogue security candidate for CWE-", $cwe),
889            full: concat!(
890                $name,
891                " is a data-driven `fallow security` tainted-sink catalogue category with CWE-",
892                $cwe,
893                " metadata. fallow reports it as an unverified candidate when a captured sink shape matches this category. Use it to understand or filter `security/",
894                $id,
895                "` findings, then inspect the trace, source, sink, sanitization, and application context before treating it as exploitable."
896            ),
897            docs_path: "cli/security",
898        }
899    };
900}
901
902pub const SECURITY_RULES: &[RuleDef] = &[
903    RuleDef {
904        id: "security/tainted-sink",
905        category: "Security",
906        name: "Tainted Sink Candidates",
907        short: "Syntactic security sink candidates require verification",
908        full: "The `tainted-sink` family covers data-driven `fallow security` catalogue categories. These findings are unverified candidates, not confirmed vulnerabilities. fallow can connect known source signals to captured sink shapes and add CWE metadata, but it does not prove attacker control, missing sanitization, exploitability, or business impact.",
909        docs_path: "cli/security",
910    },
911    RuleDef {
912        id: "security/client-server-leak",
913        category: "Security",
914        name: "Client-server Secret Leak Candidates",
915        short: "Client-bound code reaches a non-public env read",
916        full: "`client-server-leak` reports a candidate when a `use client` module can transitively reach a static non-public `process.env` or `import.meta.env` read. Public-by-convention env prefixes are treated as public. The finding is advisory and still needs bundle, framework, and runtime verification before treating it as a real exposure.",
917        docs_path: "cli/security",
918    },
919    RuleDef {
920        id: "security/hardcoded-secret",
921        category: "Security",
922        name: "Hardcoded Secret Candidates",
923        short: "Provider-prefixed or contextual secret literals require verification",
924        full: "`hardcoded-secret` reports opt-in candidates for provider-prefixed or contextual secret-shaped literals. The category is include-required and only runs when listed in `security.categories.include`. It avoids raw entropy alone, but every result still requires review, secret rotation decisions, and context before acting.",
925        docs_path: "cli/security",
926    },
927    security_catalogue_rule!("dangerous-html", "Dangerous HTML sink", "79"),
928    security_catalogue_rule!(
929        "template-escape-bypass",
930        "Template escape bypass sink",
931        "79"
932    ),
933    security_catalogue_rule!("command-injection", "OS command injection sink", "78"),
934    security_catalogue_rule!("code-injection", "Code injection sink", "94"),
935    security_catalogue_rule!("dynamic-regex", "Dynamic regular expression sink", "1333"),
936    security_catalogue_rule!("redos-regex", "ReDoS regex sink", "1333"),
937    security_catalogue_rule!(
938        "resource-amplification",
939        "Resource amplification sink",
940        "400"
941    ),
942    security_catalogue_rule!("dynamic-module-load", "Dynamic module load sink", "95"),
943    security_catalogue_rule!("sql-injection", "SQL injection sink", "89"),
944    security_catalogue_rule!("ssrf", "Server-side request forgery sink", "918"),
945    security_catalogue_rule!(
946        "secret-to-network",
947        "Secret reaches a network request",
948        "201"
949    ),
950    security_catalogue_rule!("path-traversal", "Path traversal sink", "22"),
951    security_catalogue_rule!(
952        "header-injection",
953        "HTTP response header injection sink",
954        "113"
955    ),
956    security_catalogue_rule!("open-redirect", "Open redirect sink", "601"),
957    security_catalogue_rule!(
958        "postmessage-wildcard-origin",
959        "Wildcard postMessage target origin",
960        "346"
961    ),
962    security_catalogue_rule!("tls-validation-disabled", "TLS validation disabled", "295"),
963    security_catalogue_rule!("cleartext-transport", "Cleartext transport URL", "319"),
964    security_catalogue_rule!(
965        "electron-unsafe-webpreferences",
966        "Unsafe Electron BrowserWindow preferences",
967        "1188"
968    ),
969    security_catalogue_rule!(
970        "world-writable-permission",
971        "World-writable chmod mode",
972        "732"
973    ),
974    security_catalogue_rule!(
975        "insecure-temp-file",
976        "Predictable temporary file path",
977        "377"
978    ),
979    security_catalogue_rule!(
980        "mysql-multiple-statements",
981        "MySQL multiple statements enabled",
982        "89"
983    ),
984    security_catalogue_rule!("permissive-cors", "Permissive CORS policy", "942"),
985    security_catalogue_rule!("insecure-cookie", "Insecure cookie options", "614"),
986    security_catalogue_rule!("mass-assignment", "Mass assignment sink", "915"),
987    security_catalogue_rule!("weak-crypto", "Runtime-selectable crypto algorithm", "327"),
988    security_catalogue_rule!("insecure-randomness", "Insecure randomness sink", "338"),
989    security_catalogue_rule!("jwt-alg-none", "JWT alg none", "347"),
990    security_catalogue_rule!(
991        "jwt-verify-missing-algorithms",
992        "JWT verify missing algorithms allowlist",
993        "347"
994    ),
995    security_catalogue_rule!("deprecated-cipher", "Deprecated cipher constructor", "327"),
996    security_catalogue_rule!(
997        "unsafe-buffer-alloc",
998        "Unsafe Buffer allocation sink",
999        "1188"
1000    ),
1001    security_catalogue_rule!(
1002        "unsafe-deserialization",
1003        "Unsafe deserialization sink",
1004        "502"
1005    ),
1006    security_catalogue_rule!(
1007        "angular-trusted-html",
1008        "Angular bypassSecurityTrust sink",
1009        "79"
1010    ),
1011    security_catalogue_rule!("nextjs-open-redirect", "Next.js open redirect sink", "601"),
1012    security_catalogue_rule!("dom-document-write", "DOM document.write sink", "79"),
1013    security_catalogue_rule!("jquery-html", "jQuery .html() sink", "79"),
1014    security_catalogue_rule!(
1015        "route-send-file",
1016        "Route file-send path traversal sink",
1017        "22"
1018    ),
1019    security_catalogue_rule!("webview-injection", "WebView injected-script sink", "94"),
1020    security_catalogue_rule!("prototype-pollution", "Prototype pollution sink", "1321"),
1021    security_catalogue_rule!("zip-slip", "Archive path-traversal (zip-slip) sink", "22"),
1022    security_catalogue_rule!("nosql-injection", "NoSQL injection sink", "943"),
1023    security_catalogue_rule!("ssti", "Server-side template injection sink", "1336"),
1024    security_catalogue_rule!("xxe", "XML external entity (XXE) sink", "611"),
1025    security_catalogue_rule!("secret-pii-log", "Secret or PII logged", "532"),
1026    security_catalogue_rule!("xpath-injection", "XPath injection sink", "643"),
1027];
1028
1029/// Build the `_meta` object for `fallow dead-code --format json --explain`.
1030#[must_use]
1031pub fn check_meta() -> Value {
1032    let rules: Value = CHECK_RULES
1033        .iter()
1034        .map(|r| {
1035            (
1036                r.id.replace("fallow/", ""),
1037                json!({
1038                    "name": r.name,
1039                    "description": r.full,
1040                    "docs": rule_docs_url(r)
1041                }),
1042            )
1043        })
1044        .collect::<serde_json::Map<String, Value>>()
1045        .into();
1046
1047    json!({
1048        "docs": CHECK_DOCS,
1049        "rules": rules,
1050        "field_definitions": {
1051            "actions[]": ACTIONS_FIELD_DEFINITION,
1052            "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
1053        }
1054    })
1055}
1056
1057/// Build the sectioned `_meta` object for bare `fallow --format json --explain`.
1058#[must_use]
1059pub fn combined_meta(include_check: bool, include_dupes: bool, include_health: bool) -> Value {
1060    let mut sections = serde_json::Map::new();
1061    if include_check {
1062        sections.insert("check".to_string(), check_meta());
1063    }
1064    if include_dupes {
1065        sections.insert("dupes".to_string(), dupes_meta());
1066    }
1067    if include_health {
1068        sections.insert("health".to_string(), health_meta());
1069    }
1070    Value::Object(sections)
1071}
1072
1073/// Build the `_meta` object for `fallow health --format json --explain`.
1074#[must_use]
1075pub fn health_meta() -> Value {
1076    json!({
1077        "docs": HEALTH_DOCS,
1078        "field_definitions": {
1079            "actions[]": ACTIONS_FIELD_DEFINITION,
1080            "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
1081        },
1082        "metrics": health_metrics()
1083    })
1084}
1085
1086fn health_metrics() -> Value {
1087    let mut metrics = serde_json::Map::new();
1088    for section in [
1089        health_size_complexity_metrics(),
1090        health_quality_metrics(),
1091        health_coupling_metrics(),
1092        health_churn_metrics(),
1093        health_refactoring_rank_metrics(),
1094        health_refactoring_confidence_metrics(),
1095        health_risk_metrics(),
1096        health_contributor_metrics(),
1097        health_ownership_metrics(),
1098        health_runtime_verdict_metrics(),
1099        health_runtime_observation_metrics(),
1100        health_runtime_production_metrics(),
1101    ] {
1102        let Value::Object(section) = section else {
1103            continue;
1104        };
1105        metrics.extend(section);
1106    }
1107    Value::Object(metrics)
1108}
1109
1110fn health_size_complexity_metrics() -> Value {
1111    json!({
1112            "cyclomatic": {
1113                "name": "Cyclomatic Complexity",
1114                "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.",
1115                "range": "[1, \u{221e})",
1116                "interpretation": "lower is better; default threshold: 20"
1117            },
1118            "cognitive": {
1119                "name": "Cognitive Complexity",
1120                "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.",
1121                "range": "[0, \u{221e})",
1122                "interpretation": "lower is better; default threshold: 15"
1123            },
1124            "line_count": {
1125                "name": "Function Line Count",
1126                "description": "Number of lines in the function body.",
1127                "range": "[1, \u{221e})",
1128                "interpretation": "context-dependent; long functions may need splitting"
1129            },
1130            "lines": {
1131                "name": "File Line Count",
1132                "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.",
1133                "range": "[1, \u{221e})",
1134                "interpretation": "context-dependent; large files may benefit from splitting even if individual functions are small"
1135            }
1136    })
1137}
1138
1139fn health_quality_metrics() -> Value {
1140    json!({
1141            "maintainability_index": {
1142                "name": "Maintainability Index",
1143                "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.",
1144                "range": "[0, 100]",
1145                "interpretation": "higher is better; <40 poor, 40\u{2013}70 moderate, >70 good"
1146            },
1147            "complexity_density": {
1148                "name": "Complexity Density",
1149                "description": "Total cyclomatic complexity divided by lines of code. Measures how densely complex the code is per line.",
1150                "range": "[0, \u{221e})",
1151                "interpretation": "lower is better; >1.0 indicates very dense complexity"
1152            },
1153            "dead_code_ratio": {
1154                "name": "Dead Code Ratio",
1155                "description": "Fraction of value exports (excluding type-only exports like interfaces and type aliases) with zero references across the project.",
1156                "range": "[0, 1]",
1157                "interpretation": "lower is better; 0 = all exports are used"
1158            }
1159    })
1160}
1161
1162fn health_coupling_metrics() -> Value {
1163    json!({
1164            "fan_in": {
1165                "name": "Fan-in (Importers)",
1166                "description": "Number of files that import this file. High fan-in means high blast radius \u{2014} changes to this file affect many dependents.",
1167                "range": "[0, \u{221e})",
1168                "interpretation": "context-dependent; high fan-in files need careful review before changes"
1169            },
1170            "fan_out": {
1171                "name": "Fan-out (Imports)",
1172                "description": "Number of files this file directly imports. High fan-out indicates high coupling and change propagation risk.",
1173                "range": "[0, \u{221e})",
1174                "interpretation": "lower is better; MI penalty caps at ~40 imports"
1175            },
1176    })
1177}
1178
1179fn health_churn_metrics() -> Value {
1180    json!({
1181            "score": {
1182                "name": "Hotspot Score",
1183                "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.",
1184                "range": "[0, 100]",
1185                "interpretation": "higher = riskier; prioritize refactoring high-score files"
1186            },
1187            "weighted_commits": {
1188                "name": "Weighted Commits",
1189                "description": "Recency-weighted commit count using exponential decay with 90-day half-life. Recent commits contribute more than older ones.",
1190                "range": "[0, \u{221e})",
1191                "interpretation": "higher = more recent churn activity"
1192            },
1193            "trend": {
1194                "name": "Churn Trend",
1195                "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.",
1196                "values": ["accelerating", "stable", "cooling"],
1197                "interpretation": "accelerating files need attention; cooling files are stabilizing"
1198            }
1199    })
1200}
1201
1202fn health_refactoring_rank_metrics() -> Value {
1203    json!({
1204            "priority": {
1205                "name": "Refactoring Priority",
1206                "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.",
1207                "range": "[0, 100]",
1208                "interpretation": "higher = more urgent to refactor"
1209            },
1210            "efficiency": {
1211                "name": "Efficiency Score",
1212                "description": "priority / effort_numeric (Low=1, Medium=2, High=3). Surfaces quick wins: high-priority, low-effort targets rank first. Default sort order.",
1213                "range": "[0, 100] \u{2014} effective max depends on effort: Low=100, Medium=50, High\u{2248}33",
1214                "interpretation": "higher = better quick-win value; targets are sorted by efficiency descending"
1215            },
1216            "effort": {
1217                "name": "Effort Estimate",
1218                "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.",
1219                "values": ["low", "medium", "high"],
1220                "interpretation": "low = quick win, high = needs planning and coordination"
1221            },
1222    })
1223}
1224
1225fn health_refactoring_confidence_metrics() -> Value {
1226    json!({
1227            "confidence": {
1228                "name": "Confidence Level",
1229                "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).",
1230                "values": ["high", "medium", "low"],
1231                "interpretation": "high = act on it, medium = verify context, low = treat as a signal, not a directive"
1232            },
1233            "health_score": {
1234                "name": "Health Score",
1235                "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.",
1236                "range": "[0, 100]",
1237                "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)"
1238            }
1239    })
1240}
1241
1242fn health_risk_metrics() -> Value {
1243    json!({
1244            "crap_max": {
1245                "name": "Untested Complexity Risk (CRAP)",
1246                "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.",
1247                "range": "[1, \u{221e})",
1248                "interpretation": "lower is better; >=30 is high-risk (CC >= 5 without test path)"
1249            },
1250    })
1251}
1252
1253fn health_contributor_metrics() -> Value {
1254    json!({
1255            "bus_factor": {
1256                "name": "Bus Factor",
1257                "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.",
1258                "range": "[1, \u{221e})",
1259                "interpretation": "lower is higher knowledge-loss risk; 1 means a single contributor covers most of the recent history"
1260            },
1261            "contributor_count": {
1262                "name": "Contributor Count",
1263                "description": "Number of distinct authors who touched this file in the analysis window after bot-pattern filtering.",
1264                "range": "[0, \u{221e})",
1265                "interpretation": "higher generally indicates broader knowledge spread; pair with bus_factor for context"
1266            },
1267            "share": {
1268                "name": "Contributor Share",
1269                "description": "Recency-weighted share of total weighted commits attributed to a single contributor. Rounded to three decimals.",
1270                "range": "[0, 1]",
1271                "interpretation": "share close to 1.0 indicates dominance and pairs with low bus_factor"
1272            },
1273    })
1274}
1275
1276fn health_ownership_metrics() -> Value {
1277    json!({
1278            "stale_days": {
1279                "name": "Stale Days",
1280                "description": "Days since this contributor last touched the file. Computed at analysis time.",
1281                "range": "[0, \u{221e})",
1282                "interpretation": "high stale_days on the top contributor often correlates with ownership drift"
1283            },
1284            "drift": {
1285                "name": "Ownership Drift",
1286                "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%.",
1287                "values": [true, false],
1288                "interpretation": "true means the original author is no longer maintaining; route reviews to the current top contributor"
1289            },
1290            "unowned": {
1291                "name": "Unowned (Tristate)",
1292                "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).",
1293                "values": [true, false, null],
1294                "interpretation": "true on a hotspot is a review-bottleneck risk; null means the signal is unavailable, not absent"
1295            }
1296    })
1297}
1298
1299fn health_runtime_verdict_metrics() -> Value {
1300    json!({
1301            "runtime_coverage_verdict": {
1302                "name": "Runtime Coverage Verdict",
1303                "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).",
1304                "values": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
1305                "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."
1306            },
1307    })
1308}
1309
1310fn health_runtime_observation_metrics() -> Value {
1311    json!({
1312            "runtime_coverage_state": {
1313                "name": "Runtime Coverage State",
1314                "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.",
1315                "values": ["called", "never-called", "coverage-unavailable", "unknown"],
1316                "interpretation": "`never-called` in combination with static `unused` is the highest-confidence delete signal"
1317            },
1318            "runtime_coverage_confidence": {
1319                "name": "Runtime Coverage Confidence",
1320                "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.",
1321                "values": ["high", "medium", "low", "unknown"],
1322                "interpretation": "high = act on it; medium = verify context; low = treat as a signal only"
1323            }
1324    })
1325}
1326
1327fn health_runtime_production_metrics() -> Value {
1328    json!({
1329            "production_invocations": {
1330                "name": "Production Invocations",
1331                "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.",
1332                "range": "[0, \u{221e})",
1333                "interpretation": "0 + tracked = cold path; 0 + untracked = unknown; high + never-called cannot occur by definition"
1334            },
1335            "percent_dead_in_production": {
1336                "name": "Percent Dead in Production",
1337                "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.",
1338                "range": "[0, 100]",
1339                "interpretation": "lower is better; values above ~10% on a long-running service indicate a large cleanup opportunity"
1340            }
1341    })
1342}
1343
1344/// Build the `_meta` object for `fallow dupes --format json --explain`.
1345#[must_use]
1346pub fn dupes_meta() -> Value {
1347    json!({
1348        "docs": DUPES_DOCS,
1349        "field_definitions": {
1350            "actions[]": ACTIONS_FIELD_DEFINITION,
1351            "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
1352        },
1353        "metrics": {
1354            "duplication_percentage": {
1355                "name": "Duplication Percentage",
1356                "description": "Fraction of total source tokens that appear in at least one clone group. Computed over the full analyzed file set.",
1357                "range": "[0, 100]",
1358                "interpretation": "lower is better"
1359            },
1360            "token_count": {
1361                "name": "Token Count",
1362                "description": "Number of normalized source tokens in the clone group. Tokens are language-aware (keywords, identifiers, operators, punctuation). Higher token count = larger duplicate.",
1363                "range": "[1, \u{221e})",
1364                "interpretation": "larger clones have higher refactoring value"
1365            },
1366            "line_count": {
1367                "name": "Line Count",
1368                "description": "Number of source lines spanned by the clone instance. Approximation of clone size for human readability.",
1369                "range": "[1, \u{221e})",
1370                "interpretation": "larger clones are more impactful to deduplicate"
1371            },
1372            "clone_groups": {
1373                "name": "Clone Groups",
1374                "description": "A set of code fragments with identical or near-identical normalized token sequences. Each group has 2+ instances across different locations.",
1375                "interpretation": "each group is a single refactoring opportunity"
1376            },
1377            "clone_groups_below_min_occurrences": {
1378                "name": "Clone Groups Below minOccurrences",
1379                "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`.",
1380                "range": "[0, \u{221e})",
1381                "interpretation": "high values suggest noisy pair-only duplication; lower `minOccurrences` to inspect"
1382            },
1383            "clone_families": {
1384                "name": "Clone Families",
1385                "description": "Groups of clone groups that share the same set of files. Indicates systematic duplication patterns (e.g., mirrored directory structures).",
1386                "interpretation": "families suggest extract-module refactoring opportunities"
1387            }
1388        }
1389    })
1390}
1391
1392/// Build the `_meta` object for `fallow security --format json --explain`.
1393#[must_use]
1394pub fn security_meta() -> Meta {
1395    let rules = SECURITY_RULES
1396        .iter()
1397        .map(|rule| {
1398            (
1399                rule.id.to_string(),
1400                MetaRule {
1401                    name: Some(rule.name.to_string()),
1402                    description: Some(rule.full.to_string()),
1403                    docs: Some(rule_docs_url(rule)),
1404                },
1405            )
1406        })
1407        .collect();
1408
1409    Meta {
1410        docs: Some(SECURITY_DOCS.to_string()),
1411        telemetry: None,
1412        field_definitions: BTreeMap::from([
1413            (
1414                "version".to_string(),
1415                "fallow CLI version that produced this output.".to_string(),
1416            ),
1417            (
1418                "elapsed_ms".to_string(),
1419                "Wall-clock milliseconds spent producing the security report.".to_string(),
1420            ),
1421            (
1422                "config".to_string(),
1423                "Privacy-safe config context relevant to security candidate generation."
1424                    .to_string(),
1425            ),
1426            (
1427                "config.rules.*.configured".to_string(),
1428                "Severity from resolved config before the security command forced default-off rules on."
1429                    .to_string(),
1430            ),
1431            (
1432                "config.rules.*.effective".to_string(),
1433                "Severity used for this security command run.".to_string(),
1434            ),
1435            (
1436                "config.categories_include".to_string(),
1437                "Configured security category include list. null means unset, [] means explicitly empty."
1438                    .to_string(),
1439            ),
1440            (
1441                "config.categories_exclude".to_string(),
1442                "Configured security category exclude list. null means unset, [] means explicitly empty."
1443                    .to_string(),
1444            ),
1445            (
1446                "security_findings[]".to_string(),
1447                "Unverified security candidates for downstream human or agent verification."
1448                    .to_string(),
1449            ),
1450            (
1451                "summary.security_findings".to_string(),
1452                "Number of security candidates after all filters, gates, and scopes.".to_string(),
1453            ),
1454            (
1455                "summary.by_severity".to_string(),
1456                "Fixed high, medium, and low severity counts for summary JSON.".to_string(),
1457            ),
1458            (
1459                "summary.by_category".to_string(),
1460                "Candidate counts by catalogue category, or by kind for uncategorized findings."
1461                    .to_string(),
1462            ),
1463            (
1464                "summary.by_reachability".to_string(),
1465                "Fixed reachability and source-backed ranking-signal counts for summary JSON."
1466                    .to_string(),
1467            ),
1468            (
1469                "summary.by_runtime_state".to_string(),
1470                "Fixed production-runtime coverage state counts for summary JSON.".to_string(),
1471            ),
1472            (
1473                "unresolved_edge_files".to_string(),
1474                "Number of client files whose import cone contains dynamic edges the graph could not follow."
1475                    .to_string(),
1476            ),
1477            (
1478                "unresolved_callee_sites".to_string(),
1479                "Number of sink-shaped nodes whose callee could not be flattened to a static path."
1480                    .to_string(),
1481            ),
1482        ]),
1483        metrics: BTreeMap::new(),
1484        rules,
1485    }
1486}
1487
1488/// Build the `_meta` object for `fallow coverage setup --json --explain`.
1489#[must_use]
1490pub fn coverage_setup_meta() -> Value {
1491    json!({
1492        "docs_url": COVERAGE_SETUP_DOCS,
1493        "field_definitions": {
1494            "schema_version": "Coverage setup JSON contract version. Stays at \"1\" for additive opt-in fields such as _meta.",
1495            "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.",
1496            "package_manager": "Detected package manager used for install and run commands, or null when no package manager signal was found.",
1497            "runtime_targets": "Union of runtime targets across emitted members.",
1498            "members[]": "Per-runtime-workspace setup recipes. Pure aggregator roots and build-only libraries are omitted.",
1499            "members[].name": "Workspace package name from package.json, or the root directory name when package.json has no name.",
1500            "members[].path": "Workspace path relative to the command root. The root package is represented as \".\".",
1501            "members[].framework_detected": "Runtime framework detected for that member.",
1502            "members[].package_manager": "Package manager detected for that member, or inherited from the workspace root when no member-specific signal exists.",
1503            "members[].runtime_targets": "Runtime targets produced by that member.",
1504            "members[].files_to_edit": "Files in that member that should receive runtime beacon setup code.",
1505            "members[].snippets": "Copy-paste setup snippets for that member, with paths relative to the command root.",
1506            "members[].dockerfile_snippet": "Environment snippet for file-system capture in that member's containerized Node runtime, or null when not applicable.",
1507            "members[].warnings": "Actionable setup caveats discovered for that member.",
1508            "config_written": "Always null for --json because JSON setup is side-effect-free and never writes configuration.",
1509            "files_to_edit": "Compatibility copy of the primary member's files, with workspace prefixes when the primary member is not the root.",
1510            "snippets": "Compatibility copy of the primary member's snippets, with workspace prefixes when the primary member is not the root.",
1511            "dockerfile_snippet": "Environment snippet for file-system capture in containerized Node runtimes, or null when not applicable.",
1512            "commands": "Package-manager commands needed to install the runtime beacon and sidecar packages.",
1513            "next_steps": "Ordered setup workflow after applying the emitted snippets.",
1514            "warnings": "Actionable setup caveats discovered while building the recipe."
1515        },
1516        "enums": {
1517            "framework_detected": ["nextjs", "nestjs", "nuxt", "sveltekit", "astro", "remix", "vite", "plain_node", "unknown"],
1518            "runtime_targets": ["node", "browser"],
1519            "package_manager": ["npm", "pnpm", "yarn", "bun", null]
1520        },
1521        "warnings": {
1522            "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.",
1523            "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.",
1524            "Package manager was not detected": "No packageManager field or known lockfile was found. Commands fall back to npm.",
1525            "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."
1526        }
1527    })
1528}
1529
1530/// Build the `_meta` object for `fallow coverage analyze --format json --explain`.
1531#[must_use]
1532pub fn coverage_analyze_meta() -> Value {
1533    json!({
1534        "docs_url": COVERAGE_ANALYZE_DOCS,
1535        "field_definitions": {
1536            "schema_version": "Standalone coverage analyze envelope version. \"1\" for the current shape.",
1537            "version": "fallow CLI version that produced this output.",
1538            "elapsed_ms": "Wall-clock milliseconds spent producing the report.",
1539            "runtime_coverage": "Same RuntimeCoverageReport block emitted by `fallow health --runtime-coverage`.",
1540            "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.",
1541            "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.",
1542            "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.",
1543            "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.",
1544            "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.",
1545            "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.",
1546            "runtime_coverage.findings[].evidence.static_status": "used = the function is reachable in the AST module graph; unused = it is dead by static analysis.",
1547            "runtime_coverage.findings[].evidence.test_coverage": "covered = the local test suite hits the function; not_covered otherwise.",
1548            "runtime_coverage.findings[].evidence.v8_tracking": "tracked = V8 observed the function during the capture window; untracked otherwise.",
1549            "runtime_coverage.findings[].actions[].type": "Suggested follow-up identifier. delete-cold-code is emitted on safe_to_delete; review-runtime on review_required.",
1550            "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.",
1551            "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.",
1552            "runtime_coverage.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally."
1553        },
1554        "enums": {
1555            "data_source": ["local", "cloud"],
1556            "report_verdict": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
1557            "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
1558            "static_status": ["used", "unused"],
1559            "test_coverage": ["covered", "not_covered"],
1560            "v8_tracking": ["tracked", "untracked"],
1561            "action_type": ["delete-cold-code", "review-runtime"]
1562        },
1563        "warnings": {
1564            "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
1565            "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."
1566        }
1567    })
1568}
1569
1570#[cfg(test)]
1571mod tests {
1572    use super::*;
1573
1574    #[test]
1575    fn rule_by_id_finds_check_rule() {
1576        let rule = rule_by_id("fallow/unused-file").unwrap();
1577        assert_eq!(rule.name, "Unused Files");
1578    }
1579
1580    #[test]
1581    fn rule_by_id_finds_health_rule() {
1582        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1583        assert_eq!(rule.name, "High Cyclomatic Complexity");
1584    }
1585
1586    #[test]
1587    fn rule_by_id_finds_dupes_rule() {
1588        let rule = rule_by_id("fallow/code-duplication").unwrap();
1589        assert_eq!(rule.name, "Code Duplication");
1590    }
1591
1592    #[test]
1593    fn rule_by_id_finds_security_rule() {
1594        let rule = rule_by_id("security/tainted-sink").unwrap();
1595        assert_eq!(rule.name, "Tainted Sink Candidates");
1596    }
1597
1598    #[test]
1599    fn rule_by_id_returns_none_for_unknown() {
1600        assert!(rule_by_id("fallow/nonexistent").is_none());
1601        assert!(rule_by_id("").is_none());
1602    }
1603
1604    #[test]
1605    fn rule_docs_url_format() {
1606        let rule = rule_by_id("fallow/unused-export").unwrap();
1607        let url = rule_docs_url(rule);
1608        assert!(url.starts_with("https://docs.fallow.tools/"));
1609        assert!(url.contains("unused-exports"));
1610    }
1611
1612    #[test]
1613    fn check_rules_all_have_fallow_prefix() {
1614        for rule in CHECK_RULES {
1615            assert!(
1616                rule.id.starts_with("fallow/"),
1617                "rule {} should start with fallow/",
1618                rule.id
1619            );
1620        }
1621    }
1622
1623    #[test]
1624    fn check_rules_all_have_docs_path() {
1625        for rule in CHECK_RULES {
1626            assert!(
1627                !rule.docs_path.is_empty(),
1628                "rule {} should have a docs_path",
1629                rule.id
1630            );
1631        }
1632    }
1633
1634    #[test]
1635    fn check_rules_no_duplicate_ids() {
1636        let mut seen = rustc_hash::FxHashSet::default();
1637        for rule in CHECK_RULES
1638            .iter()
1639            .chain(HEALTH_RULES)
1640            .chain(DUPES_RULES)
1641            .chain(FLAGS_RULES)
1642            .chain(SECURITY_RULES)
1643        {
1644            assert!(seen.insert(rule.id), "duplicate rule id: {}", rule.id);
1645        }
1646    }
1647
1648    #[test]
1649    fn check_meta_has_docs_and_rules() {
1650        let meta = check_meta();
1651        assert!(meta.get("docs").is_some());
1652        assert!(meta.get("rules").is_some());
1653        let rules = meta["rules"].as_object().unwrap();
1654        assert_eq!(rules.len(), CHECK_RULES.len());
1655        assert!(rules.contains_key("unused-file"));
1656        assert!(rules.contains_key("unused-export"));
1657        assert!(rules.contains_key("unused-type"));
1658        assert!(rules.contains_key("unused-dependency"));
1659        assert!(rules.contains_key("unused-dev-dependency"));
1660        assert!(rules.contains_key("unused-optional-dependency"));
1661        assert!(rules.contains_key("unused-enum-member"));
1662        assert!(rules.contains_key("unused-class-member"));
1663        assert!(rules.contains_key("unresolved-import"));
1664        assert!(rules.contains_key("unlisted-dependency"));
1665        assert!(rules.contains_key("duplicate-export"));
1666        assert!(rules.contains_key("type-only-dependency"));
1667        assert!(rules.contains_key("circular-dependency"));
1668    }
1669
1670    #[test]
1671    fn check_meta_documents_per_finding_auto_fixable() {
1672        let meta = check_meta();
1673        let defs = meta["field_definitions"].as_object().unwrap();
1674        let note = defs["actions[].auto_fixable"].as_str().unwrap();
1675        assert!(
1676            note.contains("PER FINDING"),
1677            "auto_fixable note must call out per-finding evaluation"
1678        );
1679        assert!(
1680            note.contains("remove-catalog-entry"),
1681            "auto_fixable note must cite remove-catalog-entry per-instance flip"
1682        );
1683        assert!(
1684            note.contains("used_in_workspaces"),
1685            "auto_fixable note must cite the dependency-action per-instance flip"
1686        );
1687        assert!(
1688            note.contains("ignoreExports"),
1689            "auto_fixable note must cite the duplicate-exports config-fixable flip"
1690        );
1691        assert!(defs.contains_key("actions[]"));
1692    }
1693
1694    #[test]
1695    fn health_and_dupes_meta_share_actions_field_definitions() {
1696        for meta in [health_meta(), dupes_meta()] {
1697            let defs = meta["field_definitions"].as_object().unwrap();
1698            assert_eq!(
1699                defs["actions[]"].as_str().unwrap(),
1700                ACTIONS_FIELD_DEFINITION,
1701            );
1702            assert_eq!(
1703                defs["actions[].auto_fixable"].as_str().unwrap(),
1704                ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION,
1705            );
1706        }
1707    }
1708
1709    #[test]
1710    fn check_meta_rule_has_required_fields() {
1711        let meta = check_meta();
1712        let rules = meta["rules"].as_object().unwrap();
1713        for (key, value) in rules {
1714            assert!(value.get("name").is_some(), "rule {key} missing 'name'");
1715            assert!(
1716                value.get("description").is_some(),
1717                "rule {key} missing 'description'"
1718            );
1719            assert!(value.get("docs").is_some(), "rule {key} missing 'docs'");
1720        }
1721    }
1722
1723    #[test]
1724    fn health_meta_has_metrics() {
1725        let meta = health_meta();
1726        assert!(meta.get("docs").is_some());
1727        let metrics = meta["metrics"].as_object().unwrap();
1728        assert!(metrics.contains_key("cyclomatic"));
1729        assert!(metrics.contains_key("cognitive"));
1730        assert!(metrics.contains_key("maintainability_index"));
1731        assert!(metrics.contains_key("complexity_density"));
1732        assert!(metrics.contains_key("fan_in"));
1733        assert!(metrics.contains_key("fan_out"));
1734    }
1735
1736    #[test]
1737    fn dupes_meta_has_metrics() {
1738        let meta = dupes_meta();
1739        assert!(meta.get("docs").is_some());
1740        let metrics = meta["metrics"].as_object().unwrap();
1741        assert!(metrics.contains_key("duplication_percentage"));
1742        assert!(metrics.contains_key("token_count"));
1743        assert!(metrics.contains_key("clone_groups"));
1744        assert!(metrics.contains_key("clone_families"));
1745    }
1746
1747    #[test]
1748    fn coverage_setup_meta_has_docs_fields_enums_and_warnings() {
1749        let meta = coverage_setup_meta();
1750        assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
1751        assert!(
1752            meta["field_definitions"]
1753                .as_object()
1754                .unwrap()
1755                .contains_key("members[]")
1756        );
1757        assert!(
1758            meta["field_definitions"]
1759                .as_object()
1760                .unwrap()
1761                .contains_key("config_written")
1762        );
1763        assert!(
1764            meta["field_definitions"]
1765                .as_object()
1766                .unwrap()
1767                .contains_key("members[].package_manager")
1768        );
1769        assert!(
1770            meta["field_definitions"]
1771                .as_object()
1772                .unwrap()
1773                .contains_key("members[].warnings")
1774        );
1775        assert!(
1776            meta["enums"]
1777                .as_object()
1778                .unwrap()
1779                .contains_key("framework_detected")
1780        );
1781        assert!(
1782            meta["warnings"]
1783                .as_object()
1784                .unwrap()
1785                .contains_key("No runtime workspace members were detected")
1786        );
1787        assert!(
1788            meta["warnings"]
1789                .as_object()
1790                .unwrap()
1791                .contains_key("Package manager was not detected")
1792        );
1793    }
1794
1795    #[test]
1796    fn coverage_analyze_meta_documents_data_source_and_action_vocabulary() {
1797        let meta = coverage_analyze_meta();
1798        assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
1799        let fields = meta["field_definitions"].as_object().unwrap();
1800        assert!(fields.contains_key("runtime_coverage.summary.data_source"));
1801        assert!(fields.contains_key("runtime_coverage.summary.last_received_at"));
1802        assert!(fields.contains_key("runtime_coverage.findings[].evidence.test_coverage"));
1803        assert!(fields.contains_key("runtime_coverage.findings[].actions[].type"));
1804        let enums = meta["enums"].as_object().unwrap();
1805        assert_eq!(enums["data_source"], json!(["local", "cloud"]));
1806        assert_eq!(enums["test_coverage"], json!(["covered", "not_covered"]));
1807        assert_eq!(enums["v8_tracking"], json!(["tracked", "untracked"]));
1808        assert_eq!(
1809            enums["action_type"],
1810            json!(["delete-cold-code", "review-runtime"])
1811        );
1812        let warnings = meta["warnings"].as_object().unwrap();
1813        assert!(warnings.contains_key("cloud_functions_unmatched"));
1814    }
1815
1816    #[test]
1817    fn health_rules_all_have_fallow_prefix() {
1818        for rule in HEALTH_RULES {
1819            assert!(
1820                rule.id.starts_with("fallow/"),
1821                "health rule {} should start with fallow/",
1822                rule.id
1823            );
1824        }
1825    }
1826
1827    #[test]
1828    fn health_rules_all_have_docs_path() {
1829        for rule in HEALTH_RULES {
1830            assert!(
1831                !rule.docs_path.is_empty(),
1832                "health rule {} should have a docs_path",
1833                rule.id
1834            );
1835        }
1836    }
1837
1838    #[test]
1839    fn health_rules_all_have_non_empty_fields() {
1840        for rule in HEALTH_RULES {
1841            assert!(
1842                !rule.name.is_empty(),
1843                "health rule {} missing name",
1844                rule.id
1845            );
1846            assert!(
1847                !rule.short.is_empty(),
1848                "health rule {} missing short description",
1849                rule.id
1850            );
1851            assert!(
1852                !rule.full.is_empty(),
1853                "health rule {} missing full description",
1854                rule.id
1855            );
1856        }
1857    }
1858
1859    #[test]
1860    fn dupes_rules_all_have_fallow_prefix() {
1861        for rule in DUPES_RULES {
1862            assert!(
1863                rule.id.starts_with("fallow/"),
1864                "dupes rule {} should start with fallow/",
1865                rule.id
1866            );
1867        }
1868    }
1869
1870    #[test]
1871    fn dupes_rules_all_have_docs_path() {
1872        for rule in DUPES_RULES {
1873            assert!(
1874                !rule.docs_path.is_empty(),
1875                "dupes rule {} should have a docs_path",
1876                rule.id
1877            );
1878        }
1879    }
1880
1881    #[test]
1882    fn dupes_rules_all_have_non_empty_fields() {
1883        for rule in DUPES_RULES {
1884            assert!(!rule.name.is_empty(), "dupes rule {} missing name", rule.id);
1885            assert!(
1886                !rule.short.is_empty(),
1887                "dupes rule {} missing short description",
1888                rule.id
1889            );
1890            assert!(
1891                !rule.full.is_empty(),
1892                "dupes rule {} missing full description",
1893                rule.id
1894            );
1895        }
1896    }
1897
1898    #[test]
1899    fn security_rules_all_have_security_prefix() {
1900        for rule in SECURITY_RULES {
1901            assert!(
1902                rule.id.starts_with("security/"),
1903                "security rule {} should start with security/",
1904                rule.id
1905            );
1906        }
1907    }
1908
1909    #[test]
1910    fn security_rules_all_have_docs_path() {
1911        for rule in SECURITY_RULES {
1912            assert_eq!(
1913                rule.docs_path, "cli/security",
1914                "security rule {} should point at security docs",
1915                rule.id
1916            );
1917        }
1918    }
1919
1920    #[test]
1921    fn security_rules_all_have_non_empty_fields() {
1922        for rule in SECURITY_RULES {
1923            assert!(
1924                !rule.name.is_empty(),
1925                "security rule {} missing name",
1926                rule.id
1927            );
1928            assert!(
1929                !rule.short.is_empty(),
1930                "security rule {} missing short description",
1931                rule.id
1932            );
1933            assert!(
1934                !rule.full.is_empty(),
1935                "security rule {} missing full description",
1936                rule.id
1937            );
1938        }
1939    }
1940
1941    #[test]
1942    fn check_rules_all_have_non_empty_fields() {
1943        for rule in CHECK_RULES {
1944            assert!(!rule.name.is_empty(), "check rule {} missing name", rule.id);
1945            assert!(
1946                !rule.short.is_empty(),
1947                "check rule {} missing short description",
1948                rule.id
1949            );
1950            assert!(
1951                !rule.full.is_empty(),
1952                "check rule {} missing full description",
1953                rule.id
1954            );
1955        }
1956    }
1957
1958    #[test]
1959    fn rule_docs_url_health_rule() {
1960        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1961        let url = rule_docs_url(rule);
1962        assert!(url.starts_with("https://docs.fallow.tools/"));
1963        assert!(url.contains("health"));
1964    }
1965
1966    #[test]
1967    fn rule_docs_url_dupes_rule() {
1968        let rule = rule_by_id("fallow/code-duplication").unwrap();
1969        let url = rule_docs_url(rule);
1970        assert!(url.starts_with("https://docs.fallow.tools/"));
1971        assert!(url.contains("duplication"));
1972    }
1973
1974    #[test]
1975    fn rule_docs_url_security_rule() {
1976        let rule = rule_by_id("security/sql-injection").unwrap();
1977        let url = rule_docs_url(rule);
1978        assert_eq!(url, "https://docs.fallow.tools/cli/security");
1979    }
1980
1981    #[test]
1982    fn health_meta_all_metrics_have_name_and_description() {
1983        let meta = health_meta();
1984        let metrics = meta["metrics"].as_object().unwrap();
1985        for (key, value) in metrics {
1986            assert!(
1987                value.get("name").is_some(),
1988                "health metric {key} missing 'name'"
1989            );
1990            assert!(
1991                value.get("description").is_some(),
1992                "health metric {key} missing 'description'"
1993            );
1994            assert!(
1995                value.get("interpretation").is_some(),
1996                "health metric {key} missing 'interpretation'"
1997            );
1998        }
1999    }
2000
2001    #[test]
2002    fn health_meta_has_all_expected_metrics() {
2003        let meta = health_meta();
2004        let metrics = meta["metrics"].as_object().unwrap();
2005        let expected = [
2006            "cyclomatic",
2007            "cognitive",
2008            "line_count",
2009            "lines",
2010            "maintainability_index",
2011            "complexity_density",
2012            "dead_code_ratio",
2013            "fan_in",
2014            "fan_out",
2015            "score",
2016            "weighted_commits",
2017            "trend",
2018            "priority",
2019            "efficiency",
2020            "effort",
2021            "confidence",
2022            "bus_factor",
2023            "contributor_count",
2024            "share",
2025            "stale_days",
2026            "drift",
2027            "unowned",
2028            "runtime_coverage_verdict",
2029            "runtime_coverage_state",
2030            "runtime_coverage_confidence",
2031            "production_invocations",
2032            "percent_dead_in_production",
2033        ];
2034        for key in &expected {
2035            assert!(
2036                metrics.contains_key(*key),
2037                "health_meta missing expected metric: {key}"
2038            );
2039        }
2040    }
2041
2042    #[test]
2043    fn dupes_meta_all_metrics_have_name_and_description() {
2044        let meta = dupes_meta();
2045        let metrics = meta["metrics"].as_object().unwrap();
2046        for (key, value) in metrics {
2047            assert!(
2048                value.get("name").is_some(),
2049                "dupes metric {key} missing 'name'"
2050            );
2051            assert!(
2052                value.get("description").is_some(),
2053                "dupes metric {key} missing 'description'"
2054            );
2055        }
2056    }
2057
2058    #[test]
2059    fn dupes_meta_has_line_count() {
2060        let meta = dupes_meta();
2061        let metrics = meta["metrics"].as_object().unwrap();
2062        assert!(metrics.contains_key("line_count"));
2063    }
2064
2065    #[test]
2066    fn check_docs_url_valid() {
2067        assert!(CHECK_DOCS.starts_with("https://"));
2068        assert!(CHECK_DOCS.contains("dead-code"));
2069    }
2070
2071    #[test]
2072    fn health_docs_url_valid() {
2073        assert!(HEALTH_DOCS.starts_with("https://"));
2074        assert!(HEALTH_DOCS.contains("health"));
2075    }
2076
2077    #[test]
2078    fn dupes_docs_url_valid() {
2079        assert!(DUPES_DOCS.starts_with("https://"));
2080        assert!(DUPES_DOCS.contains("dupes"));
2081    }
2082
2083    #[test]
2084    fn check_meta_docs_url_matches_constant() {
2085        let meta = check_meta();
2086        assert_eq!(meta["docs"].as_str().unwrap(), CHECK_DOCS);
2087    }
2088
2089    #[test]
2090    fn health_meta_docs_url_matches_constant() {
2091        let meta = health_meta();
2092        assert_eq!(meta["docs"].as_str().unwrap(), HEALTH_DOCS);
2093    }
2094
2095    #[test]
2096    fn dupes_meta_docs_url_matches_constant() {
2097        let meta = dupes_meta();
2098        assert_eq!(meta["docs"].as_str().unwrap(), DUPES_DOCS);
2099    }
2100
2101    #[test]
2102    fn rule_by_id_finds_all_check_rules() {
2103        for rule in CHECK_RULES {
2104            assert!(
2105                rule_by_id(rule.id).is_some(),
2106                "rule_by_id should find check rule {}",
2107                rule.id
2108            );
2109        }
2110    }
2111
2112    #[test]
2113    fn rule_by_id_finds_all_health_rules() {
2114        for rule in HEALTH_RULES {
2115            assert!(
2116                rule_by_id(rule.id).is_some(),
2117                "rule_by_id should find health rule {}",
2118                rule.id
2119            );
2120        }
2121    }
2122
2123    #[test]
2124    fn rule_by_id_finds_all_dupes_rules() {
2125        for rule in DUPES_RULES {
2126            assert!(
2127                rule_by_id(rule.id).is_some(),
2128                "rule_by_id should find dupes rule {}",
2129                rule.id
2130            );
2131        }
2132    }
2133
2134    #[test]
2135    fn rule_by_id_finds_all_security_rules() {
2136        for rule in SECURITY_RULES {
2137            assert!(
2138                rule_by_id(rule.id).is_some(),
2139                "rule_by_id should find security rule {}",
2140                rule.id
2141            );
2142        }
2143    }
2144
2145    #[test]
2146    fn check_rules_count() {
2147        assert_eq!(CHECK_RULES.len(), 26);
2148    }
2149
2150    #[test]
2151    fn health_rules_count() {
2152        assert_eq!(HEALTH_RULES.len(), 16);
2153    }
2154
2155    #[test]
2156    fn dupes_rules_count() {
2157        assert_eq!(DUPES_RULES.len(), 1);
2158    }
2159
2160    #[test]
2161    fn flags_rules_count() {
2162        assert_eq!(FLAGS_RULES.len(), 1);
2163    }
2164
2165    #[test]
2166    fn security_rules_count() {
2167        assert_eq!(
2168            SECURITY_RULES.len(),
2169            matcher_entries_from_security_catalogue().len() + 3
2170        );
2171    }
2172
2173    #[test]
2174    fn security_rules_cover_every_catalogue_matcher() {
2175        let mut rule_ids = rustc_hash::FxHashSet::default();
2176        for rule in SECURITY_RULES {
2177            rule_ids.insert(rule.id);
2178        }
2179
2180        for matcher in matcher_entries_from_security_catalogue() {
2181            let rule_id = format!("security/{}", matcher.id);
2182            assert!(
2183                rule_ids.contains(rule_id.as_str()),
2184                "security matcher {} has no explain rule",
2185                matcher.id
2186            );
2187        }
2188    }
2189
2190    #[test]
2191    fn security_catalogue_rules_match_catalogue_title_and_cwe() {
2192        for matcher in matcher_entries_from_security_catalogue() {
2193            let rule_id = format!("security/{}", matcher.id);
2194            let rule = rule_by_id(&rule_id)
2195                .unwrap_or_else(|| panic!("security matcher {} has no explain rule", matcher.id));
2196            let cwe = format!("CWE-{}", matcher.cwe);
2197            assert_eq!(
2198                rule.name, matcher.title,
2199                "security matcher {} has stale explain title",
2200                matcher.id
2201            );
2202            assert!(
2203                rule.short.contains(&cwe),
2204                "security matcher {} explain summary does not mention {cwe}",
2205                matcher.id
2206            );
2207            assert!(
2208                rule.full.contains(&cwe),
2209                "security matcher {} explain rationale does not mention {cwe}",
2210                matcher.id
2211            );
2212        }
2213    }
2214
2215    /// Every registered rule must declare a category. The PR/MR sticky
2216    /// renderer reads this via `category_for_rule`; without an entry the
2217    /// rule silently falls into the "Dead code" default and reviewers may
2218    /// see it grouped under an unexpected section. Catching this here is
2219    /// the same pattern as `check_rules_count` for the rule count itself.
2220    #[test]
2221    fn every_rule_declares_a_category() {
2222        let allowed = [
2223            "Dead code",
2224            "Dependencies",
2225            "Duplication",
2226            "Health",
2227            "Architecture",
2228            "Suppressions",
2229            "Security",
2230            "Policy",
2231            "Flags",
2232        ];
2233        for rule in CHECK_RULES
2234            .iter()
2235            .chain(HEALTH_RULES)
2236            .chain(DUPES_RULES)
2237            .chain(FLAGS_RULES)
2238            .chain(SECURITY_RULES)
2239        {
2240            assert!(
2241                !rule.category.is_empty(),
2242                "rule {} has empty category",
2243                rule.id
2244            );
2245            assert!(
2246                allowed.contains(&rule.category),
2247                "rule {} has unrecognised category {:?}; add to allowlist or pick from {:?}",
2248                rule.id,
2249                rule.category,
2250                allowed
2251            );
2252        }
2253    }
2254
2255    #[derive(Debug)]
2256    struct MatcherEntry {
2257        id: &'static str,
2258        title: &'static str,
2259        cwe: &'static str,
2260    }
2261
2262    fn matcher_entries_from_security_catalogue() -> Vec<MatcherEntry> {
2263        let toml = include_str!("../../core/data/security_matchers.toml");
2264        let mut entries = Vec::new();
2265        let mut in_matcher = false;
2266        let mut id = None;
2267        let mut title = None;
2268        let mut cwe = None;
2269
2270        for line in toml.lines() {
2271            let trimmed = line.trim();
2272            if trimmed == "[[matcher]]" {
2273                if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2274                    entries.push(MatcherEntry { id, title, cwe });
2275                }
2276                in_matcher = true;
2277                continue;
2278            }
2279            if trimmed.starts_with("[[") {
2280                if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2281                    entries.push(MatcherEntry { id, title, cwe });
2282                }
2283                in_matcher = false;
2284                continue;
2285            }
2286            if !in_matcher {
2287                continue;
2288            }
2289            if let Some(value) = trimmed
2290                .strip_prefix("id = \"")
2291                .and_then(|value| value.strip_suffix('"'))
2292            {
2293                id = Some(value);
2294            } else if let Some(value) = trimmed
2295                .strip_prefix("title = \"")
2296                .and_then(|value| value.strip_suffix('"'))
2297            {
2298                title = Some(value);
2299            } else if let Some(value) = trimmed.strip_prefix("cwe = ") {
2300                cwe = Some(value);
2301            }
2302        }
2303
2304        if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2305            entries.push(MatcherEntry { id, title, cwe });
2306        }
2307
2308        let mut seen = rustc_hash::FxHashSet::default();
2309        entries
2310            .into_iter()
2311            .filter(|entry| seen.insert(entry.id))
2312            .collect()
2313    }
2314}