Skip to main content

fallow_api/
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 serde_json::Value;
8
9const DOCS_BASE: &str = "https://docs.fallow.tools";
10
11/// Rule definition for SARIF `fullDescription` and JSON `_meta`.
12pub struct RuleDef {
13    /// Canonical rule id, such as `fallow/unused-export` or
14    /// `security/sql-injection`; used as the SARIF rule id.
15    pub id: &'static str,
16    /// Coarse category label used by the sticky PR/MR comment renderer to
17    /// group findings into collapsible sections (Dead code, Dependencies,
18    /// Duplication, Health, Architecture, Suppressions). One source of
19    /// truth so the CodeClimate / SARIF / review-envelope path and the
20    /// renderer never drift; a unit test below asserts every RuleDef has
21    /// a non-empty category.
22    pub category: &'static str,
23    /// Human-readable rule title.
24    pub name: &'static str,
25    /// One-line description used as the SARIF `shortDescription`.
26    pub short: &'static str,
27    /// Paragraph-length description used as the SARIF `fullDescription`.
28    pub full: &'static str,
29    /// Path under the docs site base URL for the rule's `helpUri`.
30    pub docs_path: &'static str,
31}
32
33/// Rule definitions for every dead-code family finding.
34pub const CHECK_RULES: &[RuleDef] = &[
35    RuleDef {
36        id: "fallow/unused-file",
37        category: "Dead code",
38        name: "Unused Files",
39        short: "File is not reachable from any entry point",
40        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.",
41        docs_path: "explanations/dead-code#unused-files",
42    },
43    RuleDef {
44        id: "fallow/unused-export",
45        category: "Dead code",
46        name: "Unused Exports",
47        short: "Export is never imported",
48        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.",
49        docs_path: "explanations/dead-code#unused-exports",
50    },
51    RuleDef {
52        id: "fallow/unused-type",
53        category: "Dead code",
54        name: "Unused Type Exports",
55        short: "Type export is never imported",
56        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.",
57        docs_path: "explanations/dead-code#unused-types",
58    },
59    RuleDef {
60        id: "fallow/private-type-leak",
61        category: "Dead code",
62        name: "Private Type Leaks",
63        short: "Exported signature references a private type",
64        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.",
65        docs_path: "explanations/dead-code#private-type-leaks",
66    },
67    RuleDef {
68        id: "fallow/unused-dependency",
69        category: "Dependencies",
70        name: "Unused Dependencies",
71        short: "Dependency listed but never imported",
72        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.",
73        docs_path: "explanations/dead-code#unused-dependencies",
74    },
75    RuleDef {
76        id: "fallow/unused-dev-dependency",
77        category: "Dependencies",
78        name: "Unused Dev Dependencies",
79        short: "Dev dependency listed but never imported",
80        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.",
81        docs_path: "explanations/dead-code#unused-devdependencies",
82    },
83    RuleDef {
84        id: "fallow/unused-optional-dependency",
85        category: "Dependencies",
86        name: "Unused Optional Dependencies",
87        short: "Optional dependency listed but never imported",
88        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.",
89        docs_path: "explanations/dead-code#unused-optionaldependencies",
90    },
91    RuleDef {
92        id: "fallow/type-only-dependency",
93        category: "Dependencies",
94        name: "Type-only Dependencies",
95        short: "Production dependency only used via type-only imports",
96        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.",
97        docs_path: "explanations/dead-code#type-only-dependencies",
98    },
99    RuleDef {
100        id: "fallow/test-only-dependency",
101        category: "Dependencies",
102        name: "Test-only Dependencies",
103        short: "Production dependency only imported by test files",
104        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.",
105        docs_path: "explanations/dead-code#test-only-dependencies",
106    },
107    RuleDef {
108        id: "fallow/dev-dependency-in-production",
109        category: "Dependencies",
110        name: "Dev Dependencies Used in Production",
111        short: "devDependency imported by production code with a runtime import",
112        full: "A package in `devDependencies` that is imported by production (non-test, non-config) source code via a runtime/value import. It should be promoted to `dependencies`: a production-only install (`pnpm install --prod`) omits devDependencies, so the import would break at runtime. This is the promote-side mirror of `test-only-dependency` and `type-only-dependency`. A dev dependency imported from production code only via `import type` is NOT flagged (types are erased at build time), and a package also listed in `dependencies`, `peerDependencies`, or `optionalDependencies` is left alone because another manifest section provides it at runtime.",
113        docs_path: "explanations/dead-code#dev-dependencies-in-production",
114    },
115    RuleDef {
116        id: "fallow/unused-enum-member",
117        category: "Dead code",
118        name: "Unused Enum Members",
119        short: "Enum member is never referenced",
120        full: "Enum members that are never referenced in the codebase. Uses scope-aware binding analysis to track all references including computed access patterns.",
121        docs_path: "explanations/dead-code#unused-enum-members",
122    },
123    RuleDef {
124        id: "fallow/unused-class-member",
125        category: "Dead code",
126        name: "Unused Class Members",
127        short: "Class member is never referenced",
128        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.",
129        docs_path: "explanations/dead-code#unused-class-members",
130    },
131    RuleDef {
132        id: "fallow/unused-store-member",
133        category: "Dead code",
134        name: "Unused Store Members",
135        short: "Store member is never accessed by any consumer",
136        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.",
137        docs_path: "explanations/dead-code#unused-store-members",
138    },
139    RuleDef {
140        id: "fallow/unresolved-import",
141        category: "Dead code",
142        name: "Unresolved Imports",
143        short: "Import could not be resolved",
144        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.",
145        docs_path: "explanations/dead-code#unresolved-imports",
146    },
147    RuleDef {
148        id: "fallow/unlisted-dependency",
149        category: "Dependencies",
150        name: "Unlisted Dependencies",
151        short: "Dependency used but not in package.json",
152        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.",
153        docs_path: "explanations/dead-code#unlisted-dependencies",
154    },
155    RuleDef {
156        id: "fallow/duplicate-export",
157        category: "Dead code",
158        name: "Duplicate Exports",
159        short: "Export name appears in multiple modules",
160        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.",
161        docs_path: "explanations/dead-code#duplicate-exports",
162    },
163    RuleDef {
164        id: "fallow/circular-dependency",
165        category: "Architecture",
166        name: "Circular Dependencies",
167        short: "Circular dependency chain detected",
168        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.",
169        docs_path: "explanations/dead-code#circular-dependencies",
170    },
171    RuleDef {
172        id: "fallow/re-export-cycle",
173        category: "Architecture",
174        name: "Re-Export Cycles",
175        short: "Two or more barrel files re-export from each other in a loop",
176        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`.",
177        docs_path: "explanations/dead-code#re-export-cycles",
178    },
179    RuleDef {
180        id: "fallow/boundary-violation",
181        category: "Architecture",
182        name: "Boundary Violations",
183        short: "Import crosses a configured architecture boundary",
184        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.",
185        docs_path: "explanations/dead-code#boundary-violations",
186    },
187    RuleDef {
188        id: "fallow/boundary-coverage",
189        category: "Architecture",
190        name: "Boundary Coverage",
191        short: "Source file matches no configured architecture boundary zone",
192        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.",
193        docs_path: "explanations/dead-code#boundary-violations",
194    },
195    RuleDef {
196        id: "fallow/boundary-call-violation",
197        category: "Architecture",
198        name: "Boundary Call Violation",
199        short: "Zoned file calls a callee its zone forbids",
200        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.",
201        docs_path: "explanations/dead-code#boundary-violations",
202    },
203    RuleDef {
204        id: "fallow/policy-violation",
205        category: "Policy",
206        name: "Policy Violation",
207        short: "Banned usage matched a rule-pack rule",
208        full: "A call site, import, or catalogue-derived effect matched a rule from a configured rule pack (the rulePacks config key). Packs are pure declarative data; the check is syntactic, call and effect matching use written plus import-resolved canonical 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.",
209        docs_path: "explanations/dead-code#policy-violations",
210    },
211    RuleDef {
212        id: "fallow/stale-suppression",
213        category: "Suppressions",
214        name: "Stale Suppressions",
215        short: "Suppression comment or tag no longer matches any issue",
216        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.",
217        docs_path: "explanations/dead-code#stale-suppressions",
218    },
219    RuleDef {
220        id: "fallow/missing-suppression-reason",
221        category: "Suppressions",
222        name: "Missing Suppression Reason",
223        short: "Suppression comment omits a required reason",
224        full: "A fallow-ignore-next-line or fallow-ignore-file suppression omits the explanatory reason required by the requireSuppressionReason rule. Add a short reason after the suppression token, or remove the suppression if the issue is no longer intentional.",
225        docs_path: "explanations/dead-code#stale-suppressions",
226    },
227    RuleDef {
228        id: "fallow/unused-catalog-entry",
229        category: "Dependencies",
230        name: "Unused catalog entry",
231        short: "Catalog entry not referenced by any workspace package",
232        full: "An entry in a package manager catalog (`pnpm-workspace.yaml` `catalog:` / `catalogs:` or Bun root `package.json` `workspaces.catalog` / `workspaces.catalogs`) 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).",
233        docs_path: "explanations/dead-code#unused-catalog-entries",
234    },
235    RuleDef {
236        id: "fallow/empty-catalog-group",
237        category: "Dependencies",
238        name: "Empty catalog group",
239        short: "Named catalog group has no entries",
240        full: "A named group under `catalogs:` in `pnpm-workspace.yaml` or Bun root `package.json` has no package entries. Empty named groups are leftover catalog structure after the last entry is removed. The default `catalog` map is intentionally ignored because some projects keep it as a stable hook.",
241        docs_path: "explanations/dead-code#empty-catalog-groups",
242    },
243    RuleDef {
244        id: "fallow/unresolved-catalog-reference",
245        category: "Dependencies",
246        name: "Unresolved catalog reference",
247        short: "package.json references a catalog that does not declare the package",
248        full: "A workspace package.json declares a dependency with the `catalog:` or `catalog:<name>` protocol, but the catalog has no entry for that package. The package manager install will fail until the catalog is fixed. 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`, using `pnpm-workspace.yaml` catalogs when present and Bun root `package.json` catalogs otherwise. See also: fallow/unused-catalog-entry (the inverse: catalog entries no consumer references).",
249        docs_path: "explanations/dead-code#unresolved-catalog-references",
250    },
251    RuleDef {
252        id: "fallow/unused-dependency-override",
253        category: "Dependencies",
254        name: "Unused dependency override",
255        short: "Package-manager override target is not declared or resolved",
256        full: "An entry in `pnpm-workspace.yaml`'s `overrides:` section, `package.json#pnpm.overrides`, npm or Bun's top-level `package.json#overrides`, or Bun's `package.json#resolutions` whose target package is not declared by any workspace package and is not present in the active readable lockfile (`pnpm-lock.yaml`, `package-lock.json`, `npm-shrinkwrap.json`, or `bun.lock`). Override entries linger after their target package leaves the resolved dependency tree. pnpm and npm projects without a readable lockfile fall back to workspace package manifests and keep a `hint` so transitive CVE pins can be reviewed before removal. Bun projects with only binary `bun.lockb` fail closed: fallow reports a workspace diagnostic and emits no unused-override finding until a readable `bun.lock` exists. To fix: delete the entry, refresh the active lockfile if it is stale, or add the entry to `ignoreDependencyOverrides` when the override is intentionally retained. See also: fallow/misconfigured-dependency-override.",
257        docs_path: "explanations/dead-code#unused-dependency-overrides",
258    },
259    RuleDef {
260        id: "fallow/misconfigured-dependency-override",
261        category: "Dependencies",
262        name: "Misconfigured dependency override",
263        short: "Package-manager override has an unparsable key or value",
264        full: "An entry in `pnpm-workspace.yaml#overrides`, `package.json#pnpm.overrides`, npm or Bun's top-level `package.json#overrides`, or Bun's `package.json#resolutions` whose key or value cannot be interpreted in that source's override grammar. Common shapes include an empty key, an empty value, a malformed version selector (`@types/react@<<18`), or an unbalanced parent matcher (`react>`). The active package manager may reject or ignore the entry. To fix: correct the key or value according to that package manager's grammar, or remove the entry. See also: fallow/unused-dependency-override.",
265        docs_path: "explanations/dead-code#misconfigured-dependency-overrides",
266    },
267    RuleDef {
268        id: "fallow/invalid-client-export",
269        category: "Policy",
270        name: "Invalid client export",
271        short: "\"use client\" file exports a server-only / route-config name",
272        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`.",
273        docs_path: "explanations/dead-code#invalid-client-exports",
274    },
275    RuleDef {
276        id: "fallow/mixed-client-server-barrel",
277        category: "Policy",
278        name: "Mixed client/server barrel",
279        short: "Barrel re-exports both a \"use client\" module and a server-only module",
280        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`.",
281        docs_path: "explanations/dead-code#mixed-client-server-barrels",
282    },
283    RuleDef {
284        id: "fallow/misplaced-directive",
285        category: "Policy",
286        name: "Misplaced directive",
287        short: "\"use client\" / \"use server\" directive is not in the leading position and is ignored",
288        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`.",
289        docs_path: "explanations/dead-code#misplaced-directives",
290    },
291    RuleDef {
292        id: "fallow/unprovided-inject",
293        category: "Dead code",
294        name: "Unprovided injects",
295        short: "inject() / getContext() reads a key that no provide() / setContext() supplies",
296        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.",
297        docs_path: "explanations/dead-code#unprovided-injects",
298    },
299    RuleDef {
300        id: "fallow/unrendered-component",
301        category: "Dead code",
302        name: "Unrendered components",
303        short: "A Vue / Svelte component is reachable through a barrel but rendered nowhere",
304        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.",
305        docs_path: "explanations/dead-code#unrendered-components",
306    },
307    RuleDef {
308        id: "fallow/unused-component-prop",
309        category: "Dead code",
310        name: "Unused component props",
311        short: "A Vue, Svelte, or React component prop is referenced nowhere in its own component",
312        full: "A declared component prop referenced nowhere inside its own component, in these framework shapes: a Vue `<script setup>` defineProps prop, a Svelte 5 `$props()` prop, or a React/Preact prop destructured from a component's first parameter and read nowhere in its body. Framework type checkers 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; Svelte abstains on rest, computed, nested, and whole-object `$props()` shapes; 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.",
313        docs_path: "explanations/dead-code#unused-component-props",
314    },
315    RuleDef {
316        id: "fallow/unused-component-emit",
317        category: "Dead code",
318        name: "Unused component emits",
319        short: "A Vue <script setup> defineEmits event is emitted nowhere in its own component",
320        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.",
321        docs_path: "explanations/dead-code#unused-component-emits",
322    },
323    RuleDef {
324        id: "fallow/unused-component-input",
325        category: "Dead code",
326        name: "Unused component inputs",
327        short: "An Angular @Input() / signal input() / model() input is read nowhere in its own component",
328        full: "An Angular `@Input()` / signal `input()` / `model()` declared input that is read nowhere in its own component (neither the inline / external template nor the class body). The Angular compiler never flags a declared-but-unread `@Input`, and there is no `@angular-eslint` rule for it. Conservative: usage detection over-credits by design (a template sentinel ref, any class-body member access by that name, or a bare identifier read counts as used), and the whole component abstains on an unresolved `extends` heritage clause (a base class in another file may read the input). A `model()` is recorded as an input only. Default warn; suppress or remove the input. The check runs only when the project declares `@angular/core`.",
329        docs_path: "explanations/dead-code#unused-component-inputs",
330    },
331    RuleDef {
332        id: "fallow/unused-component-output",
333        category: "Dead code",
334        name: "Unused component outputs",
335        short: "An Angular @Output() / signal output() output is emitted nowhere in its own component",
336        full: "An Angular `@Output()` / signal `output()` declared output that is emitted nowhere in its own component (no `this.<output>.emit(...)`). The Angular compiler never flags a declared-but-unemitted `@Output`, and there is no `@angular-eslint` rule for it. Conservative: usage detection over-credits by design (a `this.<output>.emit` call site, or any value read of `this.<output>` that might forward it, counts as used), and the whole component abstains on an unresolved `extends` heritage clause. A `model()`-derived implicit output is never flagged. Default warn; suppress or remove the output. The check runs only when the project declares `@angular/core`.",
337        docs_path: "explanations/dead-code#unused-component-outputs",
338    },
339    RuleDef {
340        id: "fallow/unused-svelte-event",
341        category: "Dead code",
342        name: "Unused Svelte events",
343        short: "A Svelte component dispatches a createEventDispatcher event whose name is listened to nowhere in the project",
344        full: "A Svelte component that dispatches a custom event via `createEventDispatcher` (`const dispatch = createEventDispatcher(); dispatch('save')`) whose event name is listened to NOWHERE in the analyzed project. This is the cross-file dead-OUTPUT direction: the component fires an event nothing handles. No native tool covers the listener side: eslint-plugin-svelte and svelte-check are single-file / type-only. fallow builds a project-wide listened-event set from every component-tag `on:<name>` binding (event forwarding, an `on:<name>` with no handler, counts as a listen), then flags a dispatched event whose name is in no listened set. Conservative (zero false positives): the whole component abstains on a dynamic `dispatch(<nonLiteral>)` (the event name is unknowable) or a `dispatch` reference forwarded as a value; a DOM `on:click` on a lowercase element is NOT a custom event and is ignored; and any listener on any component anywhere credits the name (the liberal over-credit, false-negative-safe direction). Default warn; remove the dispatched event or wire a listener. The check runs only when the project declares `svelte`.",
345        docs_path: "explanations/dead-code#unused-svelte-events",
346    },
347    RuleDef {
348        id: "fallow/unused-server-action",
349        category: "Dead code",
350        name: "Unused server actions",
351        short: "A Next.js Server Action exported from a \"use server\" file is referenced by no code in the project",
352        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`.",
353        docs_path: "explanations/dead-code#unused-server-actions",
354    },
355    RuleDef {
356        id: "fallow/unused-load-data-key",
357        category: "Dead code",
358        name: "Unused load data keys",
359        short: "A SvelteKit load() return-object key is read by no consumer",
360        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`.",
361        docs_path: "explanations/dead-code#unused-load-data-keys",
362    },
363    RuleDef {
364        id: "fallow/prop-drilling",
365        category: "Dead code",
366        name: "Prop drilling",
367        short: "A React/Preact prop is forwarded unchanged through 3+ pass-through components to a distant consumer",
368        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`.",
369        docs_path: "explanations/dead-code#prop-drilling",
370    },
371    RuleDef {
372        id: "fallow/thin-wrapper",
373        category: "Dead code",
374        name: "Thin wrapper",
375        short: "A React/Preact component whose whole body is a single spread-forwarded child render (a candidate for inlining)",
376        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`.",
377        docs_path: "explanations/dead-code#thin-wrapper",
378    },
379    RuleDef {
380        id: "fallow/duplicate-prop-shape",
381        category: "Dead code",
382        name: "Duplicate prop shape",
383        short: "Three or more React/Preact components across two or more files declare an identical prop-name set (a missing shared Props type)",
384        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`.",
385        docs_path: "explanations/dead-code#duplicate-prop-shape",
386    },
387    RuleDef {
388        id: "fallow/route-collision",
389        category: "Policy",
390        name: "Route collision",
391        short: "Two or more Next.js App Router route files resolve to the same URL",
392        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`.",
393        docs_path: "explanations/dead-code#route-collisions",
394    },
395    RuleDef {
396        id: "fallow/dynamic-segment-name-conflict",
397        category: "Policy",
398        name: "Dynamic segment name conflict",
399        short: "Sibling Next.js dynamic route segments use different slug names at the same position",
400        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`.",
401        docs_path: "explanations/dead-code#dynamic-segment-name-conflicts",
402    },
403];
404
405/// Look up a rule definition by its SARIF rule ID across all rule sets.
406#[must_use]
407pub fn rule_by_id(id: &str) -> Option<&'static RuleDef> {
408    CHECK_RULES
409        .iter()
410        .chain(HEALTH_RULES.iter())
411        .chain(DUPES_RULES.iter())
412        .chain(FLAGS_RULES.iter())
413        .chain(SECURITY_RULES.iter())
414        .find(|r| r.id == id)
415}
416
417/// Build the docs URL for a rule.
418#[must_use]
419pub fn rule_docs_url(rule: &RuleDef) -> String {
420    let docs_path = rule_result_meta(rule).map_or(rule.docs_path, |meta| meta.meta_docs_path);
421    format!("{DOCS_BASE}/{docs_path}")
422}
423
424fn rule_result_meta(rule: &RuleDef) -> Option<&'static fallow_types::issue_meta::IssueResultMeta> {
425    let code = rule.id.strip_prefix("fallow/")?;
426    fallow_types::issue_meta::issue_result_meta_by_code(code)
427}
428
429fn rule_explain_name(rule: &RuleDef) -> &'static str {
430    rule_result_meta(rule).map_or(rule.name, |meta| meta.meta_name)
431}
432
433fn rule_explain_summary(rule: &RuleDef) -> &'static str {
434    rule_result_meta(rule).map_or(rule.short, |meta| meta.sarif_description)
435}
436
437/// Extra educational content for the standalone `fallow explain <issue-type>`
438/// command. Kept separate from [`RuleDef`] so SARIF and `_meta` payloads remain
439/// compact while terminal users and agents can ask for worked examples on
440/// demand.
441pub struct RuleGuide {
442    /// Worked code example illustrating the issue.
443    pub example: &'static str,
444    /// Step-by-step remediation guidance.
445    pub how_to_fix: &'static str,
446}
447
448/// Look up an issue type from a user-facing token.
449///
450/// Accepts canonical SARIF ids (`fallow/unused-export`), issue tokens
451/// (`unused-export`), and common CLI filter spellings (`unused-exports`).
452#[must_use]
453pub fn rule_by_token(token: &str) -> Option<&'static RuleDef> {
454    let trimmed = token.trim();
455    if trimmed.is_empty() {
456        return None;
457    }
458    if let Some(rule) = rule_by_id(trimmed) {
459        return Some(rule);
460    }
461    let normalized = trimmed
462        .strip_prefix("fallow/")
463        .unwrap_or(trimmed)
464        .trim_start_matches("--")
465        .replace('_', "-")
466        .split_whitespace()
467        .collect::<Vec<_>>()
468        .join("-");
469    if let Some(rule) = dead_code_registry_rule(&normalized) {
470        return Some(rule);
471    }
472    let alias = health_alias_id(&normalized).or_else(|| security_alias_id(&normalized));
473    if let Some(id) = alias
474        && let Some(rule) = rule_by_id(id)
475    {
476        return Some(rule);
477    }
478    let security_token = normalized.strip_prefix("security-").unwrap_or(&normalized);
479    let security_id = format!("security/{security_token}");
480    if let Some(rule) = rule_by_id(&security_id) {
481        return Some(rule);
482    }
483    let singular = normalized
484        .strip_suffix('s')
485        .filter(|_| normalized != "unused-class")
486        .unwrap_or(&normalized);
487    let singular_security_token = singular.strip_prefix("security-").unwrap_or(singular);
488    let singular_security_id = format!("security/{singular_security_token}");
489    if let Some(rule) = rule_by_id(&singular_security_id) {
490        return Some(rule);
491    }
492    let id = format!("fallow/{singular}");
493    rule_by_id(&id).or_else(|| {
494        CHECK_RULES
495            .iter()
496            .chain(HEALTH_RULES.iter())
497            .chain(DUPES_RULES.iter())
498            .chain(FLAGS_RULES.iter())
499            .chain(SECURITY_RULES.iter())
500            .find(|rule| {
501                rule.docs_path.ends_with(&normalized)
502                    || rule.docs_path.ends_with(singular)
503                    || rule_result_meta(rule).is_some_and(|meta| {
504                        meta.meta_docs_path.ends_with(&normalized)
505                            || meta.meta_docs_path.ends_with(singular)
506                            || meta.meta_name.eq_ignore_ascii_case(trimmed)
507                    })
508                    || rule.name.eq_ignore_ascii_case(trimmed)
509            })
510    })
511}
512
513fn dead_code_registry_rule(normalized: &str) -> Option<&'static RuleDef> {
514    let meta = fallow_types::issue_meta::issue_meta_for_contract_token(normalized)?;
515    CHECK_RULES
516        .iter()
517        .find(|rule| rule.id.strip_prefix("fallow/") == Some(meta.code))
518}
519
520fn health_alias_id(normalized: &str) -> Option<&'static str> {
521    match normalized {
522        "complexity" | "high-complexity" => Some("fallow/high-complexity"),
523        "cyclomatic" | "high-cyclomatic" | "high-cyclomatic-complexity" => {
524            Some("fallow/high-cyclomatic-complexity")
525        }
526        "cognitive" | "high-cognitive" | "high-cognitive-complexity" => {
527            Some("fallow/high-cognitive-complexity")
528        }
529        "crap" | "high-crap" | "high-crap-score" => Some("fallow/high-crap-score"),
530        "duplication" | "dupes" | "code-duplication" => Some("fallow/code-duplication"),
531        "feature-flag" | "feature-flags" | "flags" => Some("fallow/feature-flag"),
532        _ => None,
533    }
534}
535
536fn security_alias_id(normalized: &str) -> Option<&'static str> {
537    match normalized {
538        "security"
539        | "security-candidate"
540        | "security-candidates"
541        | "tainted-sink"
542        | "tainted-sinks"
543        | "security-sink"
544        | "security-sinks" => Some("security/tainted-sink"),
545        "client-server-leak"
546        | "client-server-leaks"
547        | "security-client-server-leak"
548        | "security-client-server-leaks" => Some("security/client-server-leak"),
549        "hardcoded-secret" | "hardcoded-secrets" | "hard-coded-secret" | "hard-coded-secrets" => {
550            Some("security/hardcoded-secret")
551        }
552        _ => None,
553    }
554}
555
556/// Return worked-example and fix guidance for a rule.
557#[must_use]
558pub fn rule_guide(rule: &RuleDef) -> RuleGuide {
559    source_dead_code_rule_guide(rule.id)
560        .or_else(|| member_import_rule_guide(rule.id))
561        .or_else(|| architecture_rule_guide(rule.id))
562        .or_else(|| catalog_rule_guide(rule.id))
563        .or_else(|| health_runtime_rule_guide(rule.id))
564        .or_else(|| duplication_rule_guide(rule.id))
565        .or_else(|| security_rule_guide(rule.id))
566        .unwrap_or_else(fallback_rule_guide)
567}
568
569fn source_dead_code_rule_guide(id: &str) -> Option<RuleGuide> {
570    Some(match id {
571        "fallow/unused-file" => RuleGuide {
572            example: "src/old-widget.ts is not imported by any entry point, route, script, or config file.",
573            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.",
574        },
575        "fallow/unused-export" => RuleGuide {
576            example: "export const formatPrice = ... exists in src/money.ts, but no module imports formatPrice.",
577            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.",
578        },
579        "fallow/unused-type" => RuleGuide {
580            example: "export interface LegacyProps is exported, but no module imports the type.",
581            how_to_fix: "Remove the type export, inline it, or keep it behind an explicit API entry point when consumers rely on it.",
582        },
583        "fallow/private-type-leak" => RuleGuide {
584            example: "export function makeUser(): InternalUser exposes InternalUser even though InternalUser is not exported.",
585            how_to_fix: "Export the referenced type, change the public signature to an exported type, or keep the helper private.",
586        },
587        "fallow/unused-dependency"
588        | "fallow/unused-dev-dependency"
589        | "fallow/unused-optional-dependency" => RuleGuide {
590            example: "package.json lists left-pad, but no source, script, config, or plugin-recognized file imports it.",
591            how_to_fix: "Remove the dependency after checking runtime/plugin usage. If another workspace uses it, move the dependency to that workspace.",
592        },
593        "fallow/type-only-dependency" => RuleGuide {
594            example: "zod is in dependencies but only appears in import type declarations.",
595            how_to_fix: "Move the package to devDependencies unless runtime code imports it as a value.",
596        },
597        "fallow/test-only-dependency" => RuleGuide {
598            example: "vitest is listed in dependencies, but only test files import it.",
599            how_to_fix: "Move the package to devDependencies unless production code imports it at runtime.",
600        },
601        "fallow/dev-dependency-in-production" => RuleGuide {
602            example: "yaml is in devDependencies, but src/config.ts imports { parse } from 'yaml' and runs it at runtime.",
603            how_to_fix: "Move the package to dependencies so a production-only install keeps it. Leave it in devDependencies if the only production imports are `import type` or another manifest section (dependencies / peer / optional) already provides it.",
604        },
605        _ => return None,
606    })
607}
608
609fn member_import_rule_guide(id: &str) -> Option<RuleGuide> {
610    Some(match id {
611        "fallow/unused-enum-member" => RuleGuide {
612            example: "Status.Legacy remains in an exported enum, but no code reads that member.",
613            how_to_fix: "Remove the member after checking serialized/API compatibility, or suppress it with a reason when external data still uses it.",
614        },
615        "fallow/unused-class-member" => RuleGuide {
616            example: "class Parser has a public parseLegacy method that is never called in the project.",
617            how_to_fix: "Remove or privatize the member. For reflection/framework lifecycle hooks, configure or suppress the intentional entry point.",
618        },
619        "fallow/unused-store-member" => RuleGuide {
620            example: "useCartStore declares a discountTotal getter that no component, composable, or other store ever reads.",
621            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.",
622        },
623        "fallow/unprovided-inject" => RuleGuide {
624            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.",
625            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.",
626        },
627        "fallow/unrendered-component" => RuleGuide {
628            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.",
629            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.",
630        },
631        "fallow/unused-component-prop" => RuleGuide {
632            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).",
633            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.",
634        },
635        "fallow/unused-component-emit" => RuleGuide {
636            example: "Widget.vue declares defineEmits<{ close: [] }>() but `emit('close')` is called nowhere in the component's script.",
637            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.",
638        },
639        "fallow/unused-component-input" => RuleGuide {
640            example: "user-card.component.ts declares @Input() size: string (or size = input<string>()) but `size` is read nowhere in the template or the class body.",
641            how_to_fix: "Remove the unused input, or read it in the template or class body. If the input is part of a deliberately-stable public component API, suppress the line with // fallow-ignore-next-line unused-component-input.",
642        },
643        "fallow/unused-component-output" => RuleGuide {
644            example: "user-card.component.ts declares @Output() close = new EventEmitter<void>() (or close = output<void>()) but `this.close.emit(...)` is called nowhere in the class.",
645            how_to_fix: "Remove the unused output, or emit it from the class. If the output is part of a deliberately-stable public component API, suppress the line with // fallow-ignore-next-line unused-component-output.",
646        },
647        "fallow/unused-svelte-event" => RuleGuide {
648            example: "Child.svelte calls const dispatch = createEventDispatcher(); dispatch('dead'), but no parent listens for it (no <Child on:dead> anywhere in the project).",
649            how_to_fix: "Remove the dispatched event, or listen for it on the component (<Child on:dead={...}> or forward it via <Child on:dead>). If the event is dispatched reflectively (a dynamic name) or is part of a deliberately-stable public component API, suppress the line with // fallow-ignore-next-line unused-svelte-event.",
650        },
651        "fallow/unused-server-action" => RuleGuide {
652            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}>.",
653            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.",
654        },
655        "fallow/unused-load-data-key" => RuleGuide {
656            example: "src/routes/blog/+page.ts returns { posts, draftCount } but +page.svelte only reads data.posts and no component reads page.data.draftCount.",
657            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.",
658        },
659        "fallow/prop-drilling" => RuleGuide {
660            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.",
661            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.",
662        },
663        "fallow/thin-wrapper" => RuleGuide {
664            example: "const ButtonWrapper = (props) => <Button {...props}/>; the wrapper has no own markup, hooks, or logic, so it only re-points at Button.",
665            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.",
666        },
667        "fallow/duplicate-prop-shape" => RuleGuide {
668            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.",
669            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.",
670        },
671        "fallow/unresolved-import" => RuleGuide {
672            example: "src/app.ts imports ./routes/admin, but no matching file exists after extension and index resolution.",
673            how_to_fix: "Fix the specifier, restore the missing file, install the package, or align tsconfig path aliases with the runtime resolver.",
674        },
675        "fallow/unlisted-dependency" => RuleGuide {
676            example: "src/api.ts imports undici, but the nearest package.json does not list undici.",
677            how_to_fix: "Add the package to dependencies/devDependencies in the workspace that imports it instead of relying on hoisting or transitive deps.",
678        },
679        "fallow/duplicate-export" => RuleGuide {
680            example: "Button is exported from both src/ui/button.ts and src/components/button.ts.",
681            how_to_fix: "Rename or consolidate the exports so consumers have one intentional import target.",
682        },
683        _ => return None,
684    })
685}
686
687fn architecture_rule_guide(id: &str) -> Option<RuleGuide> {
688    Some(match id {
689        "fallow/circular-dependency" => RuleGuide {
690            example: "src/a.ts imports src/b.ts, and src/b.ts imports src/a.ts.",
691            how_to_fix: "Extract shared code to a third module, invert the dependency, or split initialization-time side effects from type-only contracts.",
692        },
693        "fallow/boundary-violation" => RuleGuide {
694            example: "features/billing imports app/admin even though the configured boundary only allows imports from shared and entities.",
695            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.",
696        },
697        "fallow/boundary-coverage" => RuleGuide {
698            example: "src/generated/client.ts is reachable but does not match any boundaries.zones[].patterns entry.",
699            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.",
700        },
701        "fallow/boundary-call-violation" => RuleGuide {
702            example: "src/domain/policy.ts calls execSync from node:child_process while boundaries.calls.forbidden bans child_process.* from the domain zone.",
703            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).",
704        },
705        "fallow/policy-violation" => RuleGuide {
706            example: "src/app.ts imports moment while a rule pack bans the moment specifier with the message 'Use date-fns.'",
707            how_to_fix: "Replace the banned call, import, or effectful usage 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.",
708        },
709        "fallow/stale-suppression" => RuleGuide {
710            example: "// fallow-ignore-next-line unused-export remains above an export that is now used.",
711            how_to_fix: "Remove the suppression. If a different issue is still intentional, replace it with a current, specific suppression.",
712        },
713        "fallow/missing-suppression-reason" => RuleGuide {
714            example: "// fallow-ignore-next-line unused-export appears without the required explanatory reason.",
715            how_to_fix: "Add a concise reason after the suppression token, or remove the suppression if the issue is no longer intentional.",
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: "The catalog source declares `catalog: { is-even: ^1.0.0 }`, but no workspace package.json declares `\"is-even\": \"catalog:\"`.",
725            how_to_fix: "Delete the entry from the catalog source file. 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: "The catalog source declares `catalogs: { react17: {} }` after the last react17 entry was removed.",
729            how_to_fix: "Delete the empty named group from the catalog source file. 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 the catalog source does not declare `old-react`. The package manager 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 the catalog source, 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: "The root package.json declares `overrides: { axios: ^1.6.0 }`, but no workspace package.json declares `axios` and the active lockfile does not resolve it.",
737            how_to_fix: "Delete the entry from its reported declaration source. If the finding is caused by a stale or missing readable lockfile, refresh the active lockfile 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: "The root package.json declares `overrides: { \"axios\": \"\" }`. An empty override value is invalid and the active package manager will reject or ignore it.",
741            how_to_fix: "Fix the key or value to match the active package manager's grammar. For pnpm this includes bare or scoped package names, version selectors, parent matchers, and the supported `-`, `$ref`, and `npm:alias` values. For npm or Bun, preserve the supported nested object shape. Remove experimental entries that should not remain.",
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-family findings on markup: Angular .html templates and inline `@Component({ template: ... })` literals, Vue SFC `<template>` blocks, Svelte markup, and Astro markup, plus each top-level Svelte `{#snippet name(...)}` block as its own `<snippet:NAME>` unit. `<component>` rollup findings 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, flatten nested control flow and move branch selection out of the markup: Angular `@if`/`@for`/`@switch`/`@defer` and legacy `*ngIf`/`*ngFor` into computed signals on the component class, Vue `v-if`/`v-else-if`/`v-for` into computed properties, Svelte `{#if}`/`{:else if}`/`{#each}`/`{#await}`/`{#key}` into derived state, Astro control flow into props resolved in the frontmatter. In Svelte, moving a repeated or deeply nested block into a top-level `{#snippet}` gives it its own `<snippet:NAME>` unit with nesting rebased to zero, so the in-file extraction moves the score; splitting a large template into child components lowers the score in every dialect. 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. Synthetic template-family units (the `<template>` units on Angular, Vue, Svelte and Astro markup, and Svelte `<snippet:NAME>` units) are not scored on this dimension: a template carries no direct coverage of its own, so fallow gates templates on the cyclomatic and cognitive dimensions instead.",
757            how_to_fix: "Add focused tests for the risky branches first, then simplify the function if the score remains high. Template findings never carry this rule, so a `maxCrap` override scoped to a template unit buys nothing and can be removed.",
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/// Build the typed standalone explain output for a user-facing issue token.
819///
820/// # Errors
821///
822/// Returns a structured programmatic error when the token does not map to a
823/// registered rule.
824pub fn explain_issue_type(
825    issue_type: &str,
826) -> Result<fallow_output::ExplainOutput, crate::ProgrammaticError> {
827    let Some(rule) = rule_by_token(issue_type) else {
828        return Err(unknown_explain_error(issue_type));
829    };
830    let guide = rule_guide(rule);
831    Ok(fallow_output::ExplainOutput {
832        id: rule.id.to_string(),
833        name: rule_explain_name(rule).to_string(),
834        summary: rule_explain_summary(rule).to_string(),
835        rationale: rule.full.to_string(),
836        example: guide.example.to_string(),
837        how_to_fix: guide.how_to_fix.to_string(),
838        docs: rule_docs_url(rule),
839    })
840}
841
842/// Serialize standalone explain output using the programmatic API contract.
843///
844/// # Errors
845///
846/// Returns a structured programmatic error for unknown rule tokens or JSON
847/// serialization failures.
848pub fn serialize_explain_programmatic_json(
849    issue_type: &str,
850    mode: fallow_output::RootEnvelopeMode,
851    analysis_run_id: Option<&str>,
852) -> Result<serde_json::Value, crate::ProgrammaticError> {
853    let output = explain_issue_type(issue_type)?;
854    fallow_output::serialize_explain_json_output(output, mode, analysis_run_id).map_err(|error| {
855        crate::ProgrammaticError::new(format!("JSON serialization error: {error}"), 2)
856            .with_code("json_serialization")
857    })
858}
859
860/// Structured error for an unrecognized `fallow explain` issue type, with
861/// suggestions matched to whether the token looks security-related.
862#[must_use]
863pub fn unknown_explain_error(issue_type: &str) -> crate::ProgrammaticError {
864    let message = if looks_security_explain_token(issue_type) {
865        format!(
866            "unknown issue type '{issue_type}'. Try values like tainted-sink, client-server-leak, hardcoded-secret, sql-injection, or security/sql-injection"
867        )
868    } else {
869        format!(
870            "unknown issue type '{issue_type}'. Try values like unused files, unused-export, high complexity, or code duplication"
871        )
872    };
873    crate::ProgrammaticError::new(message, 2).with_code("unknown_issue_type")
874}
875
876fn looks_security_explain_token(issue_type: &str) -> bool {
877    let normalized = issue_type.trim().to_ascii_lowercase().replace('_', "-");
878    normalized.contains("security")
879        || normalized.contains("secret")
880        || normalized.contains("sink")
881        || normalized.contains("cwe")
882        || normalized.contains("client-server")
883        || normalized.contains("injection")
884}
885
886/// Rule definitions for complexity and health findings.
887pub const HEALTH_RULES: &[RuleDef] = &[
888    RuleDef {
889        id: "fallow/high-cyclomatic-complexity",
890        category: "Health",
891        name: "High Cyclomatic Complexity",
892        short: "Function has high cyclomatic complexity",
893        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 across every supported template dialect (Angular .html templates and inline `@Component({ template: ... })` literals, Vue SFC `<template>` blocks, Svelte markup, Astro markup), counting each dialect's control-flow blocks (Angular `@if`/`@else if`/`@for`/`@case`/`@defer (when ...)` and legacy `*ngIf`/`*ngFor`; Vue `v-if`/`v-else-if`/`v-for`; Svelte `{#if}`/`{:else if}`/`{#each}`/`{#await}`/`{#key}`; the Astro equivalents) plus ternary and logical operators inside bound attributes and interpolations; on each top-level Svelte `{#snippet name(...)}` block, emitted as its own `<snippet:NAME>` unit; 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`.",
894        docs_path: "explanations/health#cyclomatic-complexity",
895    },
896    RuleDef {
897        id: "fallow/high-cognitive-complexity",
898        category: "Health",
899        name: "High Cognitive Complexity",
900        short: "Function has high cognitive complexity",
901        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 across every supported template dialect (Angular .html templates and inline `@Component({ template: ... })` literals, Vue SFC `<template>` blocks, Svelte markup, Astro markup), where nesting penalties accumulate on stacked control-flow blocks: Angular `@if`/`@for`/`@switch`, Vue `v-if`/`v-for`, Svelte `{#if}`/`{#each}`/`{#await}`; on each top-level Svelte `{#snippet name(...)}` block, emitted as its own `<snippet:NAME>` unit with nesting rebased to zero so in-file snippet extraction lowers the parent template's score; 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`.",
902        docs_path: "explanations/health#cognitive-complexity",
903    },
904    RuleDef {
905        id: "fallow/high-complexity",
906        category: "Health",
907        name: "High Complexity (Both)",
908        short: "Function exceeds both complexity thresholds",
909        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 in every supported template dialect (Angular .html templates and inline `@Component({ template: ... })` literals, Vue SFC `<template>` blocks, Svelte markup, Astro markup) 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`.",
910        docs_path: "explanations/health#complexity-metrics",
911    },
912    RuleDef {
913        id: "fallow/high-crap-score",
914        category: "Health",
915        name: "High CRAP Score",
916        short: "Function has a high CRAP score (complexity combined with low coverage)",
917        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. This rule fires on functions only: synthetic template-family units (`<template>`, Svelte `<snippet:NAME>`) are excluded from the CRAP dimension, because a template is exercised only through its component and carries no coverage the formula could measure. Templates gate on the cyclomatic and cognitive dimensions instead.",
918        docs_path: "explanations/health#crap-score",
919    },
920    RuleDef {
921        id: "fallow/refactoring-target",
922        category: "Health",
923        name: "Refactoring Target",
924        short: "File identified as a high-priority refactoring candidate",
925        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.",
926        docs_path: "explanations/health#refactoring-targets",
927    },
928    RuleDef {
929        id: "fallow/css-token-drift",
930        category: "Health",
931        name: "CSS Token Drift",
932        short: "CSS or CSS-in-JS hardcoded styling value bypasses the design token system",
933        full: "A styling value appears to bypass the project's design token system, for example a Tailwind arbitrary value in markup. The finding is advisory by default and does not affect the audit verdict unless rules.css-token-drift is set to error. Verify the value and replace it with an existing scale token when appropriate.",
934        docs_path: "explanations/health#css-token-drift",
935    },
936    RuleDef {
937        id: "fallow/css-duplicate-block",
938        category: "Health",
939        name: "CSS Duplicate Block",
940        short: "CSS or CSS-in-JS declaration block is duplicated across rules",
941        full: "A style rule declaration block is repeated across selectors, suggesting copy-pasted styling that can often be consolidated. The finding is advisory by default and does not affect the audit verdict unless rules.css-duplicate-block is set to error.",
942        docs_path: "explanations/health#css-duplicate-block",
943    },
944    RuleDef {
945        id: "fallow/css-selector-complexity",
946        category: "Health",
947        name: "CSS Selector Complexity",
948        short: "CSS selector, nesting, or important usage is structurally complex",
949        full: "A CSS or CSS-in-JS rule crosses the structural floor for selector specificity, selector complexity, nesting depth, or important usage. The finding is advisory by default and does not affect the audit verdict unless rules.css-selector-complexity is set to error.",
950        docs_path: "explanations/health#css-selector-complexity",
951    },
952    RuleDef {
953        id: "fallow/css-dead-surface",
954        category: "Health",
955        name: "CSS Dead Surface",
956        short: "CSS or CSS-in-JS surface appears unused",
957        full: "A styling surface appears unused in the analyzed project, such as a scoped SFC class with no component-local use. The finding is advisory by default and does not affect the audit verdict unless rules.css-dead-surface is set to error. Verify dynamic consumers before deleting.",
958        docs_path: "explanations/health#css-dead-surface",
959    },
960    RuleDef {
961        id: "fallow/css-broken-reference",
962        category: "Health",
963        name: "CSS Broken Reference",
964        short: "CSS or CSS-in-JS reference resolves to no stylesheet definition",
965        full: "A styling reference appears unresolved, such as a class token or keyframes name that has no stylesheet definition in the analyzed project. The finding is advisory by default and does not affect the audit verdict unless rules.css-broken-reference is set to error. Verify external or CSS-in-JS definitions before fixing.",
966        docs_path: "explanations/health#css-broken-reference",
967    },
968    RuleDef {
969        id: "fallow/untested-file",
970        category: "Health",
971        name: "Untested File",
972        short: "Runtime-reachable file has no test dependency path",
973        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.",
974        docs_path: "explanations/health#coverage-gaps",
975    },
976    RuleDef {
977        id: "fallow/untested-export",
978        category: "Health",
979        name: "Untested Export",
980        short: "Runtime-reachable export has no test dependency path",
981        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.",
982        docs_path: "explanations/health#coverage-gaps",
983    },
984    RuleDef {
985        id: "fallow/runtime-safe-to-delete",
986        category: "Health",
987        name: "Production Safe To Delete",
988        short: "Statically unused AND never invoked in production with V8 tracking",
989        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.",
990        docs_path: "explanations/health#runtime-coverage",
991    },
992    RuleDef {
993        id: "fallow/runtime-review-required",
994        category: "Health",
995        name: "Production Review Required",
996        short: "Statically used but never invoked in production",
997        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.",
998        docs_path: "explanations/health#runtime-coverage",
999    },
1000    RuleDef {
1001        id: "fallow/runtime-low-traffic",
1002        category: "Health",
1003        name: "Production Low Traffic",
1004        short: "Function was invoked below the low-traffic threshold",
1005        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.",
1006        docs_path: "explanations/health#runtime-coverage",
1007    },
1008    RuleDef {
1009        id: "fallow/runtime-coverage-unavailable",
1010        category: "Health",
1011        name: "Runtime Coverage Unavailable",
1012        short: "Runtime coverage could not be resolved for this function",
1013        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.",
1014        docs_path: "explanations/health#runtime-coverage",
1015    },
1016    RuleDef {
1017        id: "fallow/runtime-coverage",
1018        category: "Health",
1019        name: "Runtime Coverage",
1020        short: "Runtime coverage finding",
1021        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.",
1022        docs_path: "explanations/health#runtime-coverage",
1023    },
1024    RuleDef {
1025        id: "fallow/coverage-intelligence-risky-change",
1026        category: "Health",
1027        name: "Coverage Intelligence Risky Change",
1028        short: "Changed hot path combines high CRAP and low test coverage",
1029        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.",
1030        docs_path: "explanations/health#coverage-intelligence",
1031    },
1032    RuleDef {
1033        id: "fallow/coverage-intelligence-delete",
1034        category: "Health",
1035        name: "Coverage Intelligence Delete",
1036        short: "Static and runtime evidence indicate code can be deleted",
1037        full: "Coverage intelligence combined static unused status, runtime cold evidence, and lack of test reachability into a high-confidence delete recommendation.",
1038        docs_path: "explanations/health#coverage-intelligence",
1039    },
1040    RuleDef {
1041        id: "fallow/coverage-intelligence-review",
1042        category: "Health",
1043        name: "Coverage Intelligence Review",
1044        short: "Cold reachable uncovered code needs owner review",
1045        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.",
1046        docs_path: "explanations/health#coverage-intelligence",
1047    },
1048    RuleDef {
1049        id: "fallow/coverage-intelligence-refactor",
1050        category: "Health",
1051        name: "Coverage Intelligence Refactor",
1052        short: "Hot covered code has high CRAP and should be refactored carefully",
1053        full: "Coverage intelligence found hot production code that is covered by tests but still has high CRAP. Refactor carefully while preserving behavior.",
1054        docs_path: "explanations/health#coverage-intelligence",
1055    },
1056];
1057
1058/// Rule definitions for duplication findings.
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
1068/// Rule definitions for feature-flag findings.
1069pub const FLAGS_RULES: &[RuleDef] = &[RuleDef {
1070    id: "fallow/feature-flag",
1071    category: "Flags",
1072    name: "Feature Flags",
1073    short: "Detected feature flag pattern",
1074    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.",
1075    docs_path: "cli/flags",
1076}];
1077
1078macro_rules! security_catalogue_rule {
1079    ($id:literal, $name:literal, $cwe:literal) => {
1080        RuleDef {
1081            id: concat!("security/", $id),
1082            category: "Security",
1083            name: $name,
1084            short: concat!("Catalogue security candidate for CWE-", $cwe),
1085            full: concat!(
1086                $name,
1087                " is a data-driven `fallow security` tainted-sink catalogue category with CWE-",
1088                $cwe,
1089                " metadata. fallow reports it as an unverified candidate when a captured sink shape matches this category. Use it to understand or filter `security/",
1090                $id,
1091                "` findings, then inspect the trace, source, sink, sanitization, and application context before treating it as exploitable."
1092            ),
1093            docs_path: "cli/security",
1094        }
1095    };
1096}
1097
1098/// Rule definitions for security candidate findings, including the
1099/// data-driven tainted-sink catalogue categories.
1100pub const SECURITY_RULES: &[RuleDef] = &[
1101    RuleDef {
1102        id: "security/tainted-sink",
1103        category: "Security",
1104        name: "Tainted Sink Candidates",
1105        short: "Syntactic security sink candidates require verification",
1106        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.",
1107        docs_path: "cli/security",
1108    },
1109    RuleDef {
1110        id: "security/client-server-leak",
1111        category: "Security",
1112        name: "Client-server Secret Leak Candidates",
1113        short: "Client-bound code reaches a non-public env read",
1114        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.",
1115        docs_path: "cli/security",
1116    },
1117    RuleDef {
1118        id: "security/hardcoded-secret",
1119        category: "Security",
1120        name: "Hardcoded Secret Candidates",
1121        short: "Provider-prefixed or contextual secret literals require verification",
1122        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.",
1123        docs_path: "cli/security",
1124    },
1125    security_catalogue_rule!("dangerous-html", "Dangerous HTML sink", "79"),
1126    security_catalogue_rule!(
1127        "template-escape-bypass",
1128        "Template escape bypass sink",
1129        "79"
1130    ),
1131    security_catalogue_rule!("command-injection", "OS command injection sink", "78"),
1132    security_catalogue_rule!("code-injection", "Code injection sink", "94"),
1133    security_catalogue_rule!("dynamic-regex", "Dynamic regular expression sink", "1333"),
1134    security_catalogue_rule!("redos-regex", "ReDoS regex sink", "1333"),
1135    security_catalogue_rule!(
1136        "resource-amplification",
1137        "Resource amplification sink",
1138        "400"
1139    ),
1140    security_catalogue_rule!("dynamic-module-load", "Dynamic module load sink", "95"),
1141    security_catalogue_rule!("sql-injection", "SQL injection sink", "89"),
1142    security_catalogue_rule!("ssrf", "Server-side request forgery sink", "918"),
1143    security_catalogue_rule!(
1144        "secret-to-network",
1145        "Secret reaches a network request",
1146        "201"
1147    ),
1148    security_catalogue_rule!("path-traversal", "Path traversal sink", "22"),
1149    security_catalogue_rule!(
1150        "header-injection",
1151        "HTTP response header injection sink",
1152        "113"
1153    ),
1154    security_catalogue_rule!("open-redirect", "Open redirect sink", "601"),
1155    security_catalogue_rule!(
1156        "postmessage-wildcard-origin",
1157        "Wildcard postMessage target origin",
1158        "346"
1159    ),
1160    security_catalogue_rule!("tls-validation-disabled", "TLS validation disabled", "295"),
1161    security_catalogue_rule!("cleartext-transport", "Cleartext transport URL", "319"),
1162    security_catalogue_rule!(
1163        "electron-unsafe-webpreferences",
1164        "Unsafe Electron BrowserWindow preferences",
1165        "1188"
1166    ),
1167    security_catalogue_rule!(
1168        "world-writable-permission",
1169        "World-writable chmod mode",
1170        "732"
1171    ),
1172    security_catalogue_rule!(
1173        "insecure-temp-file",
1174        "Predictable temporary file path",
1175        "377"
1176    ),
1177    security_catalogue_rule!(
1178        "mysql-multiple-statements",
1179        "MySQL multiple statements enabled",
1180        "89"
1181    ),
1182    security_catalogue_rule!("permissive-cors", "Permissive CORS policy", "942"),
1183    security_catalogue_rule!("insecure-cookie", "Insecure cookie options", "614"),
1184    security_catalogue_rule!("mass-assignment", "Mass assignment sink", "915"),
1185    security_catalogue_rule!("weak-crypto", "Runtime-selectable crypto algorithm", "327"),
1186    security_catalogue_rule!("insecure-randomness", "Insecure randomness sink", "338"),
1187    security_catalogue_rule!("jwt-alg-none", "JWT alg none", "347"),
1188    security_catalogue_rule!(
1189        "jwt-verify-missing-algorithms",
1190        "JWT verify missing algorithms allowlist",
1191        "347"
1192    ),
1193    security_catalogue_rule!("deprecated-cipher", "Deprecated cipher constructor", "327"),
1194    security_catalogue_rule!(
1195        "unsafe-buffer-alloc",
1196        "Unsafe Buffer allocation sink",
1197        "1188"
1198    ),
1199    security_catalogue_rule!(
1200        "unsafe-deserialization",
1201        "Unsafe deserialization sink",
1202        "502"
1203    ),
1204    security_catalogue_rule!(
1205        "angular-trusted-html",
1206        "Angular bypassSecurityTrust sink",
1207        "79"
1208    ),
1209    security_catalogue_rule!("nextjs-open-redirect", "Next.js open redirect sink", "601"),
1210    security_catalogue_rule!("dom-document-write", "DOM document.write sink", "79"),
1211    security_catalogue_rule!("jquery-html", "jQuery .html() sink", "79"),
1212    security_catalogue_rule!(
1213        "route-send-file",
1214        "Route file-send path traversal sink",
1215        "22"
1216    ),
1217    security_catalogue_rule!("webview-injection", "WebView injected-script sink", "94"),
1218    security_catalogue_rule!("prototype-pollution", "Prototype pollution sink", "1321"),
1219    security_catalogue_rule!("zip-slip", "Archive path-traversal (zip-slip) sink", "22"),
1220    security_catalogue_rule!("nosql-injection", "NoSQL injection sink", "943"),
1221    security_catalogue_rule!("ssti", "Server-side template injection sink", "1336"),
1222    security_catalogue_rule!("xxe", "XML external entity (XXE) sink", "611"),
1223    security_catalogue_rule!("secret-pii-log", "Secret or PII logged", "532"),
1224    security_catalogue_rule!("xpath-injection", "XPath injection sink", "643"),
1225    security_catalogue_rule!(
1226        "llm-call-injection",
1227        "Untrusted input reaches an LLM call",
1228        "1427"
1229    ),
1230];
1231
1232/// Build the `_meta` object for `fallow security --format json --explain`.
1233#[must_use]
1234pub fn security_meta() -> fallow_types::envelope::Meta {
1235    fallow_output::security_meta(SECURITY_RULES.iter().map(|rule| {
1236        fallow_output::SecurityRuleMeta {
1237            id: rule.id,
1238            name: rule.name,
1239            description: rule.full,
1240            docs_path: rule.docs_path,
1241        }
1242    }))
1243}
1244
1245/// Build the `_meta` object for `fallow coverage setup --json --explain`.
1246#[must_use]
1247pub fn coverage_setup_meta() -> Value {
1248    fallow_output::coverage_setup_meta()
1249}
1250
1251/// Build the `_meta` object for `fallow coverage analyze --format json --explain`.
1252#[must_use]
1253pub fn coverage_analyze_meta() -> Value {
1254    fallow_output::coverage_analyze_meta()
1255}
1256
1257#[cfg(test)]
1258#[allow(
1259    clippy::unwrap_used,
1260    reason = "registry tests intentionally index fixture JSON"
1261)]
1262mod tests {
1263    use super::*;
1264    use serde_json::json;
1265
1266    fn meta_value(meta: fallow_types::envelope::Meta) -> Value {
1267        serde_json::to_value(meta).expect("metadata should serialize")
1268    }
1269
1270    fn check_meta() -> Value {
1271        meta_value(fallow_output::check_meta())
1272    }
1273
1274    fn health_meta() -> Value {
1275        meta_value(fallow_output::health_meta())
1276    }
1277
1278    fn dupes_meta() -> Value {
1279        meta_value(fallow_output::dupes_meta())
1280    }
1281
1282    #[test]
1283    fn rule_by_id_finds_check_rule() {
1284        let rule = rule_by_id("fallow/unused-file").unwrap();
1285        assert_eq!(rule.name, "Unused Files");
1286    }
1287
1288    #[test]
1289    fn rule_by_id_finds_health_rule() {
1290        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1291        assert_eq!(rule.name, "High Cyclomatic Complexity");
1292    }
1293
1294    #[test]
1295    fn rule_by_id_finds_dupes_rule() {
1296        let rule = rule_by_id("fallow/code-duplication").unwrap();
1297        assert_eq!(rule.name, "Code Duplication");
1298    }
1299
1300    #[test]
1301    fn rule_by_id_finds_security_rule() {
1302        let rule = rule_by_id("security/tainted-sink").unwrap();
1303        assert_eq!(rule.name, "Tainted Sink Candidates");
1304    }
1305
1306    #[test]
1307    fn rule_by_id_returns_none_for_unknown() {
1308        assert!(rule_by_id("fallow/nonexistent").is_none());
1309        assert!(rule_by_id("").is_none());
1310    }
1311
1312    #[test]
1313    fn rule_docs_url_format() {
1314        let rule = rule_by_id("fallow/unused-export").unwrap();
1315        let url = rule_docs_url(rule);
1316        assert!(url.starts_with("https://docs.fallow.tools/"));
1317        assert!(url.contains("unused-exports"));
1318    }
1319
1320    #[test]
1321    fn explain_output_prefers_issue_result_registry_contract_fields() {
1322        let output = explain_issue_type("unused-type").unwrap();
1323        let meta = fallow_types::issue_meta::issue_result_meta_by_code("unused-type").unwrap();
1324        assert_eq!(output.name, meta.meta_name);
1325        assert_eq!(output.summary, meta.sarif_description);
1326        assert_eq!(
1327            output.docs,
1328            format!("https://docs.fallow.tools/{}", meta.meta_docs_path)
1329        );
1330    }
1331
1332    #[test]
1333    fn dependency_override_explanations_cover_supported_package_managers() {
1334        let unused = explain_issue_type("unused-dependency-override").unwrap();
1335        assert_eq!(unused.name, "Unused dependency override");
1336        assert!(unused.summary.contains("Package-manager override"));
1337        assert!(unused.rationale.contains("npm"));
1338        assert!(unused.rationale.contains("Bun"));
1339
1340        let misconfigured = explain_issue_type("misconfigured-dependency-override").unwrap();
1341        assert_eq!(misconfigured.name, "Misconfigured dependency override");
1342        assert!(misconfigured.summary.contains("Package-manager override"));
1343        assert!(misconfigured.rationale.contains("npm"));
1344        assert!(misconfigured.rationale.contains("Bun"));
1345    }
1346
1347    #[test]
1348    fn result_sarif_rule_ids_have_explain_metadata() {
1349        for contract in fallow_output::issue_output_contracts() {
1350            for rule_id in contract.sarif_rule_ids {
1351                assert!(
1352                    rule_by_id(&rule_id).is_some(),
1353                    "result metadata code {} has SARIF rule id {rule_id} without RuleDef",
1354                    contract.code
1355                );
1356            }
1357        }
1358    }
1359
1360    #[test]
1361    fn registry_dead_code_tokens_resolve_to_explain_rules() {
1362        for meta in fallow_types::issue_meta::ISSUE_KIND_META {
1363            let Some(expected) = CHECK_RULES
1364                .iter()
1365                .find(|rule| rule.id.strip_prefix("fallow/") == Some(meta.code))
1366            else {
1367                continue;
1368            };
1369            assert_registry_token(expected, meta.code);
1370            for token in meta.aliases {
1371                assert_registry_token(expected, token);
1372            }
1373            if let Some(token) = meta.config_key {
1374                assert_registry_token(expected, token);
1375            }
1376            if let Some(token) = meta.mcp_issue_type {
1377                assert_registry_token(expected, token);
1378            }
1379            if let Some(token) = meta.filter_flag {
1380                assert_registry_token(expected, token);
1381            }
1382            if let Some(token) = meta.suppress_token {
1383                assert_registry_token(expected, token);
1384            }
1385        }
1386    }
1387
1388    fn assert_registry_token(expected: &RuleDef, token: &str) {
1389        if !registry_token_is_unique(token) {
1390            return;
1391        }
1392        let actual = rule_by_token(token)
1393            .unwrap_or_else(|| panic!("registry token {token} did not resolve to an explain rule"));
1394        assert_eq!(
1395            actual.id, expected.id,
1396            "registry token {token} resolved to the wrong explain rule"
1397        );
1398    }
1399
1400    fn registry_token_is_unique(token: &str) -> bool {
1401        fallow_types::issue_meta::ISSUE_KIND_META
1402            .iter()
1403            .filter(|meta| {
1404                CHECK_RULES
1405                    .iter()
1406                    .any(|rule| rule.id.strip_prefix("fallow/") == Some(meta.code))
1407                    && fallow_types::issue_meta::issue_meta_matches_contract_token(meta, token)
1408            })
1409            .count()
1410            == 1
1411    }
1412
1413    #[test]
1414    fn check_rules_all_have_fallow_prefix() {
1415        for rule in CHECK_RULES {
1416            assert!(
1417                rule.id.starts_with("fallow/"),
1418                "rule {} should start with fallow/",
1419                rule.id
1420            );
1421        }
1422    }
1423
1424    #[test]
1425    fn check_rules_all_have_docs_path() {
1426        for rule in CHECK_RULES {
1427            assert!(
1428                !rule.docs_path.is_empty(),
1429                "rule {} should have a docs_path",
1430                rule.id
1431            );
1432        }
1433    }
1434
1435    #[test]
1436    fn check_rules_no_duplicate_ids() {
1437        let mut seen = rustc_hash::FxHashSet::default();
1438        for rule in CHECK_RULES
1439            .iter()
1440            .chain(HEALTH_RULES)
1441            .chain(DUPES_RULES)
1442            .chain(FLAGS_RULES)
1443            .chain(SECURITY_RULES)
1444        {
1445            assert!(seen.insert(rule.id), "duplicate rule id: {}", rule.id);
1446        }
1447    }
1448
1449    #[test]
1450    fn check_meta_has_docs_and_rules() {
1451        let meta = check_meta();
1452        assert!(meta.get("docs").is_some());
1453        assert!(meta.get("rules").is_some());
1454        let rules = meta["rules"].as_object().unwrap();
1455        assert_eq!(rules.len(), CHECK_RULES.len());
1456        assert!(rules.contains_key("unused-file"));
1457        assert!(rules.contains_key("unused-export"));
1458        assert!(rules.contains_key("unused-type"));
1459        assert!(rules.contains_key("unused-dependency"));
1460        assert!(rules.contains_key("unused-dev-dependency"));
1461        assert!(rules.contains_key("unused-optional-dependency"));
1462        assert!(rules.contains_key("unused-enum-member"));
1463        assert!(rules.contains_key("unused-class-member"));
1464        assert!(rules.contains_key("unresolved-import"));
1465        assert!(rules.contains_key("unlisted-dependency"));
1466        assert!(rules.contains_key("duplicate-export"));
1467        assert!(rules.contains_key("type-only-dependency"));
1468        assert!(rules.contains_key("circular-dependency"));
1469    }
1470
1471    #[test]
1472    fn check_meta_documents_per_finding_auto_fixable() {
1473        let meta = check_meta();
1474        let defs = meta["field_definitions"].as_object().unwrap();
1475        let note = defs["actions[].auto_fixable"].as_str().unwrap();
1476        assert!(
1477            note.contains("PER FINDING"),
1478            "auto_fixable note must call out per-finding evaluation"
1479        );
1480        assert!(
1481            note.contains("remove-catalog-entry"),
1482            "auto_fixable note must cite remove-catalog-entry per-instance flip"
1483        );
1484        assert!(
1485            note.contains("used_in_workspaces"),
1486            "auto_fixable note must cite the dependency-action per-instance flip"
1487        );
1488        assert!(
1489            note.contains("ignoreExports"),
1490            "auto_fixable note must cite the duplicate-exports config-fixable flip"
1491        );
1492        assert!(defs.contains_key("actions[]"));
1493    }
1494
1495    #[test]
1496    fn health_and_dupes_meta_share_actions_field_definitions() {
1497        for meta in [health_meta(), dupes_meta()] {
1498            let defs = meta["field_definitions"].as_object().unwrap();
1499            assert_eq!(
1500                defs["actions[]"].as_str().unwrap(),
1501                fallow_output::ACTIONS_FIELD_DEFINITION,
1502            );
1503            assert_eq!(
1504                defs["actions[].auto_fixable"].as_str().unwrap(),
1505                fallow_output::ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION,
1506            );
1507        }
1508    }
1509
1510    #[test]
1511    fn check_meta_rule_has_required_fields() {
1512        let meta = check_meta();
1513        let rules = meta["rules"].as_object().unwrap();
1514        for (key, value) in rules {
1515            assert!(value.get("name").is_some(), "rule {key} missing 'name'");
1516            assert!(
1517                value.get("description").is_some(),
1518                "rule {key} missing 'description'"
1519            );
1520            assert!(value.get("docs").is_some(), "rule {key} missing 'docs'");
1521        }
1522    }
1523
1524    #[test]
1525    fn health_meta_has_metrics() {
1526        let meta = health_meta();
1527        assert!(meta.get("docs").is_some());
1528        let metrics = meta["metrics"].as_object().unwrap();
1529        assert!(metrics.contains_key("cyclomatic"));
1530        assert!(metrics.contains_key("cognitive"));
1531        assert!(metrics.contains_key("maintainability_index"));
1532        assert!(metrics.contains_key("complexity_density"));
1533        assert!(metrics.contains_key("fan_in"));
1534        assert!(metrics.contains_key("fan_out"));
1535    }
1536
1537    #[test]
1538    fn dupes_meta_has_metrics() {
1539        let meta = dupes_meta();
1540        assert!(meta.get("docs").is_some());
1541        let metrics = meta["metrics"].as_object().unwrap();
1542        assert!(metrics.contains_key("duplication_percentage"));
1543        assert!(metrics.contains_key("token_count"));
1544        assert!(metrics.contains_key("clone_groups"));
1545        assert!(metrics.contains_key("clone_families"));
1546    }
1547
1548    #[test]
1549    fn coverage_setup_meta_has_docs_fields_enums_and_warnings() {
1550        let meta = coverage_setup_meta();
1551        assert_eq!(meta["docs_url"], fallow_output::COVERAGE_SETUP_DOCS);
1552        assert!(
1553            meta["field_definitions"]
1554                .as_object()
1555                .unwrap()
1556                .contains_key("members[]")
1557        );
1558        assert!(
1559            meta["field_definitions"]
1560                .as_object()
1561                .unwrap()
1562                .contains_key("config_written")
1563        );
1564        assert!(
1565            meta["field_definitions"]
1566                .as_object()
1567                .unwrap()
1568                .contains_key("members[].package_manager")
1569        );
1570        assert!(
1571            meta["field_definitions"]
1572                .as_object()
1573                .unwrap()
1574                .contains_key("members[].warnings")
1575        );
1576        assert!(
1577            meta["enums"]
1578                .as_object()
1579                .unwrap()
1580                .contains_key("framework_detected")
1581        );
1582        assert!(
1583            meta["warnings"]
1584                .as_object()
1585                .unwrap()
1586                .contains_key("No runtime workspace members were detected")
1587        );
1588        assert!(
1589            meta["warnings"]
1590                .as_object()
1591                .unwrap()
1592                .contains_key("Package manager was not detected")
1593        );
1594    }
1595
1596    #[test]
1597    fn coverage_analyze_meta_documents_data_source_and_action_vocabulary() {
1598        let meta = coverage_analyze_meta();
1599        assert_eq!(meta["docs_url"], fallow_output::COVERAGE_ANALYZE_DOCS);
1600        let fields = meta["field_definitions"].as_object().unwrap();
1601        assert!(fields.contains_key("runtime_coverage.summary.data_source"));
1602        assert!(fields.contains_key("runtime_coverage.summary.last_received_at"));
1603        assert!(fields.contains_key("runtime_coverage.findings[].evidence.test_coverage"));
1604        assert!(fields.contains_key("runtime_coverage.findings[].actions[].type"));
1605        let enums = meta["enums"].as_object().unwrap();
1606        assert_eq!(enums["data_source"], json!(["local", "cloud"]));
1607        assert_eq!(enums["test_coverage"], json!(["covered", "not_covered"]));
1608        assert_eq!(enums["v8_tracking"], json!(["tracked", "untracked"]));
1609        assert_eq!(
1610            enums["action_type"],
1611            json!(["delete-cold-code", "review-runtime"])
1612        );
1613        let warnings = meta["warnings"].as_object().unwrap();
1614        assert!(warnings.contains_key("cloud_functions_unmatched"));
1615    }
1616
1617    #[test]
1618    fn health_rules_all_have_fallow_prefix() {
1619        for rule in HEALTH_RULES {
1620            assert!(
1621                rule.id.starts_with("fallow/"),
1622                "health rule {} should start with fallow/",
1623                rule.id
1624            );
1625        }
1626    }
1627
1628    #[test]
1629    fn health_rules_all_have_docs_path() {
1630        for rule in HEALTH_RULES {
1631            assert!(
1632                !rule.docs_path.is_empty(),
1633                "health rule {} should have a docs_path",
1634                rule.id
1635            );
1636        }
1637    }
1638
1639    #[test]
1640    fn health_rules_all_have_non_empty_fields() {
1641        for rule in HEALTH_RULES {
1642            assert!(
1643                !rule.name.is_empty(),
1644                "health rule {} missing name",
1645                rule.id
1646            );
1647            assert!(
1648                !rule.short.is_empty(),
1649                "health rule {} missing short description",
1650                rule.id
1651            );
1652            assert!(
1653                !rule.full.is_empty(),
1654                "health rule {} missing full description",
1655                rule.id
1656            );
1657        }
1658    }
1659
1660    #[test]
1661    fn dupes_rules_all_have_fallow_prefix() {
1662        for rule in DUPES_RULES {
1663            assert!(
1664                rule.id.starts_with("fallow/"),
1665                "dupes rule {} should start with fallow/",
1666                rule.id
1667            );
1668        }
1669    }
1670
1671    #[test]
1672    fn dupes_rules_all_have_docs_path() {
1673        for rule in DUPES_RULES {
1674            assert!(
1675                !rule.docs_path.is_empty(),
1676                "dupes rule {} should have a docs_path",
1677                rule.id
1678            );
1679        }
1680    }
1681
1682    #[test]
1683    fn dupes_rules_all_have_non_empty_fields() {
1684        for rule in DUPES_RULES {
1685            assert!(!rule.name.is_empty(), "dupes rule {} missing name", rule.id);
1686            assert!(
1687                !rule.short.is_empty(),
1688                "dupes rule {} missing short description",
1689                rule.id
1690            );
1691            assert!(
1692                !rule.full.is_empty(),
1693                "dupes rule {} missing full description",
1694                rule.id
1695            );
1696        }
1697    }
1698
1699    #[test]
1700    fn security_rules_all_have_security_prefix() {
1701        for rule in SECURITY_RULES {
1702            assert!(
1703                rule.id.starts_with("security/"),
1704                "security rule {} should start with security/",
1705                rule.id
1706            );
1707        }
1708    }
1709
1710    #[test]
1711    fn security_rules_all_have_docs_path() {
1712        for rule in SECURITY_RULES {
1713            assert_eq!(
1714                rule.docs_path, "cli/security",
1715                "security rule {} should point at security docs",
1716                rule.id
1717            );
1718        }
1719    }
1720
1721    #[test]
1722    fn security_rules_all_have_non_empty_fields() {
1723        for rule in SECURITY_RULES {
1724            assert!(
1725                !rule.name.is_empty(),
1726                "security rule {} missing name",
1727                rule.id
1728            );
1729            assert!(
1730                !rule.short.is_empty(),
1731                "security rule {} missing short description",
1732                rule.id
1733            );
1734            assert!(
1735                !rule.full.is_empty(),
1736                "security rule {} missing full description",
1737                rule.id
1738            );
1739        }
1740    }
1741
1742    #[test]
1743    fn check_rules_all_have_non_empty_fields() {
1744        for rule in CHECK_RULES {
1745            assert!(!rule.name.is_empty(), "check rule {} missing name", rule.id);
1746            assert!(
1747                !rule.short.is_empty(),
1748                "check rule {} missing short description",
1749                rule.id
1750            );
1751            assert!(
1752                !rule.full.is_empty(),
1753                "check rule {} missing full description",
1754                rule.id
1755            );
1756        }
1757    }
1758
1759    #[test]
1760    fn rule_docs_url_health_rule() {
1761        let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1762        let url = rule_docs_url(rule);
1763        assert!(url.starts_with("https://docs.fallow.tools/"));
1764        assert!(url.contains("health"));
1765    }
1766
1767    #[test]
1768    fn rule_docs_url_dupes_rule() {
1769        let rule = rule_by_id("fallow/code-duplication").unwrap();
1770        let url = rule_docs_url(rule);
1771        assert!(url.starts_with("https://docs.fallow.tools/"));
1772        assert!(url.contains("duplication"));
1773    }
1774
1775    #[test]
1776    fn rule_docs_url_security_rule() {
1777        let rule = rule_by_id("security/sql-injection").unwrap();
1778        let url = rule_docs_url(rule);
1779        assert_eq!(url, "https://docs.fallow.tools/cli/security");
1780    }
1781
1782    #[test]
1783    fn health_meta_all_metrics_have_name_and_description() {
1784        let meta = health_meta();
1785        let metrics = meta["metrics"].as_object().unwrap();
1786        for (key, value) in metrics {
1787            assert!(
1788                value.get("name").is_some(),
1789                "health metric {key} missing 'name'"
1790            );
1791            assert!(
1792                value.get("description").is_some(),
1793                "health metric {key} missing 'description'"
1794            );
1795            assert!(
1796                value.get("interpretation").is_some(),
1797                "health metric {key} missing 'interpretation'"
1798            );
1799        }
1800    }
1801
1802    #[test]
1803    fn health_meta_has_all_expected_metrics() {
1804        let meta = health_meta();
1805        let metrics = meta["metrics"].as_object().unwrap();
1806        let expected = [
1807            "cyclomatic",
1808            "cognitive",
1809            "line_count",
1810            "lines",
1811            "maintainability_index",
1812            "complexity_density",
1813            "dead_code_ratio",
1814            "fan_in",
1815            "fan_out",
1816            "score",
1817            "weighted_commits",
1818            "trend",
1819            "priority",
1820            "efficiency",
1821            "effort",
1822            "confidence",
1823            "bus_factor",
1824            "contributor_count",
1825            "share",
1826            "stale_days",
1827            "drift",
1828            "unowned",
1829            "runtime_coverage_verdict",
1830            "runtime_coverage_state",
1831            "runtime_coverage_confidence",
1832            "production_invocations",
1833            "percent_dead_in_production",
1834        ];
1835        for key in &expected {
1836            assert!(
1837                metrics.contains_key(*key),
1838                "health_meta missing expected metric: {key}"
1839            );
1840        }
1841    }
1842
1843    #[test]
1844    fn dupes_meta_all_metrics_have_name_and_description() {
1845        let meta = dupes_meta();
1846        let metrics = meta["metrics"].as_object().unwrap();
1847        for (key, value) in metrics {
1848            assert!(
1849                value.get("name").is_some(),
1850                "dupes metric {key} missing 'name'"
1851            );
1852            assert!(
1853                value.get("description").is_some(),
1854                "dupes metric {key} missing 'description'"
1855            );
1856        }
1857    }
1858
1859    #[test]
1860    fn dupes_meta_has_line_count() {
1861        let meta = dupes_meta();
1862        let metrics = meta["metrics"].as_object().unwrap();
1863        assert!(metrics.contains_key("line_count"));
1864    }
1865
1866    #[test]
1867    fn check_docs_url_valid() {
1868        assert!(fallow_output::CHECK_DOCS.starts_with("https://"));
1869        assert!(fallow_output::CHECK_DOCS.contains("dead-code"));
1870    }
1871
1872    #[test]
1873    fn health_docs_url_valid() {
1874        assert!(fallow_output::HEALTH_DOCS.starts_with("https://"));
1875        assert!(fallow_output::HEALTH_DOCS.contains("health"));
1876    }
1877
1878    #[test]
1879    fn dupes_docs_url_valid() {
1880        assert!(fallow_output::DUPES_DOCS.starts_with("https://"));
1881        assert!(fallow_output::DUPES_DOCS.contains("dupes"));
1882    }
1883
1884    #[test]
1885    fn check_meta_docs_url_matches_constant() {
1886        let meta = check_meta();
1887        assert_eq!(meta["docs"].as_str().unwrap(), fallow_output::CHECK_DOCS);
1888    }
1889
1890    #[test]
1891    fn health_meta_docs_url_matches_constant() {
1892        let meta = health_meta();
1893        assert_eq!(meta["docs"].as_str().unwrap(), fallow_output::HEALTH_DOCS);
1894    }
1895
1896    #[test]
1897    fn dupes_meta_docs_url_matches_constant() {
1898        let meta = dupes_meta();
1899        assert_eq!(meta["docs"].as_str().unwrap(), fallow_output::DUPES_DOCS);
1900    }
1901
1902    #[test]
1903    fn rule_by_id_finds_all_check_rules() {
1904        for rule in CHECK_RULES {
1905            assert!(
1906                rule_by_id(rule.id).is_some(),
1907                "rule_by_id should find check rule {}",
1908                rule.id
1909            );
1910        }
1911    }
1912
1913    #[test]
1914    fn rule_by_id_finds_all_health_rules() {
1915        for rule in HEALTH_RULES {
1916            assert!(
1917                rule_by_id(rule.id).is_some(),
1918                "rule_by_id should find health rule {}",
1919                rule.id
1920            );
1921        }
1922    }
1923
1924    #[test]
1925    fn rule_by_id_finds_all_dupes_rules() {
1926        for rule in DUPES_RULES {
1927            assert!(
1928                rule_by_id(rule.id).is_some(),
1929                "rule_by_id should find dupes rule {}",
1930                rule.id
1931            );
1932        }
1933    }
1934
1935    #[test]
1936    fn rule_by_id_finds_all_security_rules() {
1937        for rule in SECURITY_RULES {
1938            assert!(
1939                rule_by_id(rule.id).is_some(),
1940                "rule_by_id should find security rule {}",
1941                rule.id
1942            );
1943        }
1944    }
1945
1946    #[test]
1947    fn check_rules_count() {
1948        assert_eq!(CHECK_RULES.len(), 46);
1949    }
1950
1951    #[test]
1952    fn health_rules_count() {
1953        assert_eq!(HEALTH_RULES.len(), 21);
1954    }
1955
1956    #[test]
1957    fn dupes_rules_count() {
1958        assert_eq!(DUPES_RULES.len(), 1);
1959    }
1960
1961    #[test]
1962    fn flags_rules_count() {
1963        assert_eq!(FLAGS_RULES.len(), 1);
1964    }
1965
1966    #[test]
1967    fn security_rules_count() {
1968        assert_eq!(
1969            SECURITY_RULES.len(),
1970            matcher_entries_from_security_catalogue().len() + 3
1971        );
1972    }
1973
1974    #[test]
1975    fn security_rules_cover_every_catalogue_matcher() {
1976        let mut rule_ids = rustc_hash::FxHashSet::default();
1977        for rule in SECURITY_RULES {
1978            rule_ids.insert(rule.id);
1979        }
1980
1981        for matcher in matcher_entries_from_security_catalogue() {
1982            let rule_id = format!("security/{}", matcher.id);
1983            assert!(
1984                rule_ids.contains(rule_id.as_str()),
1985                "security matcher {} has no explain rule",
1986                matcher.id
1987            );
1988        }
1989    }
1990
1991    #[test]
1992    fn security_catalogue_rules_match_catalogue_title_and_cwe() {
1993        for matcher in matcher_entries_from_security_catalogue() {
1994            let rule_id = format!("security/{}", matcher.id);
1995            let rule = rule_by_id(&rule_id)
1996                .unwrap_or_else(|| panic!("security matcher {} has no explain rule", matcher.id));
1997            let cwe = format!("CWE-{}", matcher.cwe);
1998            assert_eq!(
1999                rule.name, matcher.title,
2000                "security matcher {} has stale explain title",
2001                matcher.id
2002            );
2003            assert!(
2004                rule.short.contains(&cwe),
2005                "security matcher {} explain summary does not mention {cwe}",
2006                matcher.id
2007            );
2008            assert!(
2009                rule.full.contains(&cwe),
2010                "security matcher {} explain rationale does not mention {cwe}",
2011                matcher.id
2012            );
2013        }
2014    }
2015
2016    /// Every registered rule must declare a category. The PR/MR sticky
2017    /// renderer reads this via `category_for_rule`; without an entry the
2018    /// rule silently falls into the "Dead code" default and reviewers may
2019    /// see it grouped under an unexpected section. Catching this here is
2020    /// the same pattern as `check_rules_count` for the rule count itself.
2021    #[test]
2022    fn every_rule_declares_a_category() {
2023        let allowed = [
2024            "Dead code",
2025            "Dependencies",
2026            "Duplication",
2027            "Health",
2028            "Architecture",
2029            "Suppressions",
2030            "Security",
2031            "Policy",
2032            "Flags",
2033        ];
2034        for rule in CHECK_RULES
2035            .iter()
2036            .chain(HEALTH_RULES)
2037            .chain(DUPES_RULES)
2038            .chain(FLAGS_RULES)
2039            .chain(SECURITY_RULES)
2040        {
2041            assert!(
2042                !rule.category.is_empty(),
2043                "rule {} has empty category",
2044                rule.id
2045            );
2046            assert!(
2047                allowed.contains(&rule.category),
2048                "rule {} has unrecognised category {:?}; add to allowlist or pick from {:?}",
2049                rule.id,
2050                rule.category,
2051                allowed
2052            );
2053        }
2054    }
2055
2056    #[derive(Debug)]
2057    struct MatcherEntry {
2058        id: &'static str,
2059        title: &'static str,
2060        cwe: &'static str,
2061    }
2062
2063    fn matcher_entries_from_security_catalogue() -> Vec<MatcherEntry> {
2064        let toml = include_str!("../../security/data/security_matchers.toml");
2065        let mut entries = Vec::new();
2066        let mut in_matcher = false;
2067        let mut id = None;
2068        let mut title = None;
2069        let mut cwe = None;
2070
2071        for line in toml.lines() {
2072            let trimmed = line.trim();
2073            if trimmed == "[[matcher]]" {
2074                if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2075                    entries.push(MatcherEntry { id, title, cwe });
2076                }
2077                in_matcher = true;
2078                continue;
2079            }
2080            if trimmed.starts_with("[[") {
2081                if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2082                    entries.push(MatcherEntry { id, title, cwe });
2083                }
2084                in_matcher = false;
2085                continue;
2086            }
2087            if !in_matcher {
2088                continue;
2089            }
2090            if let Some(value) = trimmed
2091                .strip_prefix("id = \"")
2092                .and_then(|value| value.strip_suffix('"'))
2093            {
2094                id = Some(value);
2095            } else if let Some(value) = trimmed
2096                .strip_prefix("title = \"")
2097                .and_then(|value| value.strip_suffix('"'))
2098            {
2099                title = Some(value);
2100            } else if let Some(value) = trimmed.strip_prefix("cwe = ") {
2101                cwe = Some(value);
2102            }
2103        }
2104
2105        if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2106            entries.push(MatcherEntry { id, title, cwe });
2107        }
2108
2109        let mut seen = rustc_hash::FxHashSet::default();
2110        entries
2111            .into_iter()
2112            .filter(|entry| seen.insert(entry.id))
2113            .collect()
2114    }
2115}