Skip to main content

fallow_cli/
explain.rs

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