Skip to main content

fallow_cli/
explain.rs

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