Skip to main content

fallow_cli/
explain.rs

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