Skip to main content

fallow_api/
explain.rs

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