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