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