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 usage matched a rule-pack rule",
227 full: "A call site, import, or catalogue-derived effect matched a rule from a configured rule pack (the rulePacks config key). Packs are pure declarative data; the check is syntactic, call and effect matching use written plus import-resolved canonical callees, and import matching uses the raw specifier. Replace the banned usage per the rule's message, scope the rule with files/exclude globs, or adjust its severity.",
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 catalog entry",
242 short: "Catalog entry not referenced by any workspace package",
243 full: "An entry in a package manager catalog (`pnpm-workspace.yaml` `catalog:` / `catalogs:` or Bun root `package.json` `workspaces.catalog` / `workspaces.catalogs`) that no workspace package.json references via the `catalog:` protocol. Catalog entries are leftover dependency metadata once a package is removed from every consumer; delete the entry to keep the catalog truthful. See also: fallow/unresolved-catalog-reference (the inverse: consumer references a catalog that does not declare the package).",
244 docs_path: "explanations/dead-code#unused-catalog-entries",
245 },
246 RuleDef {
247 id: "fallow/empty-catalog-group",
248 category: "Dependencies",
249 name: "Empty catalog group",
250 short: "Named catalog group has no entries",
251 full: "A named group under `catalogs:` in `pnpm-workspace.yaml` or Bun root `package.json` has no package entries. Empty named groups are leftover catalog structure after the last entry is removed. The default `catalog` map is intentionally ignored because some projects keep it as a stable hook.",
252 docs_path: "explanations/dead-code#empty-catalog-groups",
253 },
254 RuleDef {
255 id: "fallow/unresolved-catalog-reference",
256 category: "Dependencies",
257 name: "Unresolved 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. The package manager install will fail until the catalog is fixed. To fix: add the package to the named catalog, switch the reference to a different catalog that does declare it, or remove the reference and pin a hardcoded version. Scope: the detector scans `dependencies`, `devDependencies`, `peerDependencies`, and `optionalDependencies` in every workspace `package.json`, using `pnpm-workspace.yaml` catalogs when present and Bun root `package.json` catalogs otherwise. See also: fallow/unused-catalog-entry (the inverse: catalog entries no consumer references).",
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, Svelte, or React component prop is referenced nowhere in its own component",
323 full: "A declared component prop referenced nowhere inside its own component, in these framework shapes: a Vue `<script setup>` defineProps prop, a Svelte 5 `$props()` prop, or a React/Preact prop destructured from a component's first parameter and read nowhere in its body. Framework type checkers check caller-side prop correctness, not this in-component dead-input direction. Conservative: Vue abstains on `$attrs` fallthrough, whole-object props use, defineExpose, defineModel, and imported prop-type aliases; Svelte abstains on rest, computed, nested, and whole-object `$props()` shapes; React abstains on rest spread (`{...rest}`), props forwarded by spread, props passed wholesale to a hook, `forwardRef` / imported-interface props, and exported public-API component props. Default warn; suppress or remove the prop.",
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, import, or effectful usage with the alternative named in the rule's message. To waive one rule, use `// fallow-ignore-next-line policy-violation:<pack>/<rule-id>` or the file-level form. Use bare `policy-violation` only when you intend to suppress every rule-pack finding at that scope.",
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: "The catalog source declares `catalog: { is-even: ^1.0.0 }`, but no workspace package.json declares `\"is-even\": \"catalog:\"`.",
768 how_to_fix: "Delete the entry from the catalog source file. If any consumer uses a hardcoded version (surfaced in `hardcoded_consumers`), switch that consumer to `catalog:` first to keep versions aligned.",
769 },
770 "fallow/empty-catalog-group" => RuleGuide {
771 example: "The catalog source declares `catalogs: { react17: {} }` after the last react17 entry was removed.",
772 how_to_fix: "Delete the empty named group from the catalog source file. Comments between the deleted header and the next sibling can stay in place for manual review.",
773 },
774 "fallow/unresolved-catalog-reference" => RuleGuide {
775 example: "packages/app/package.json declares `\"old-react\": \"catalog:react17\"`, but `catalogs.react17` in the catalog source does not declare `old-react`. The package manager install will fail.",
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 the catalog source, or remove the catalog reference and pin a hardcoded version. For staged migrations where the catalog edit lands separately, add the (package, catalog, consumer) triple to `ignoreCatalogReferences` in your fallow config.",
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 security_catalogue_rule!(
1266 "llm-call-injection",
1267 "Untrusted input reaches an LLM call",
1268 "1427"
1269 ),
1270];
1271
1272#[must_use]
1274pub fn check_meta() -> Value {
1275 let rules: Value = CHECK_RULES
1276 .iter()
1277 .map(|r| {
1278 (
1279 r.id.replace("fallow/", ""),
1280 json!({
1281 "name": r.name,
1282 "description": r.full,
1283 "docs": rule_docs_url(r)
1284 }),
1285 )
1286 })
1287 .collect::<serde_json::Map<String, Value>>()
1288 .into();
1289
1290 json!({
1291 "docs": CHECK_DOCS,
1292 "rules": rules,
1293 "field_definitions": {
1294 "actions[]": ACTIONS_FIELD_DEFINITION,
1295 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
1296 }
1297 })
1298}
1299
1300#[must_use]
1302pub fn combined_meta(include_check: bool, include_dupes: bool, include_health: bool) -> Value {
1303 let mut sections = serde_json::Map::new();
1304 if include_check {
1305 sections.insert("check".to_string(), check_meta());
1306 }
1307 if include_dupes {
1308 sections.insert("dupes".to_string(), dupes_meta());
1309 }
1310 if include_health {
1311 sections.insert("health".to_string(), health_meta());
1312 }
1313 Value::Object(sections)
1314}
1315
1316#[must_use]
1318pub fn health_meta() -> Value {
1319 json!({
1320 "docs": HEALTH_DOCS,
1321 "field_definitions": {
1322 "actions[]": ACTIONS_FIELD_DEFINITION,
1323 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
1324 },
1325 "metrics": health_metrics()
1326 })
1327}
1328
1329fn health_metrics() -> Value {
1330 let mut metrics = serde_json::Map::new();
1331 for section in [
1332 health_size_complexity_metrics(),
1333 health_quality_metrics(),
1334 health_coupling_metrics(),
1335 health_render_fan_in_metrics(),
1336 health_churn_metrics(),
1337 health_refactoring_rank_metrics(),
1338 health_refactoring_confidence_metrics(),
1339 health_risk_metrics(),
1340 health_contributor_metrics(),
1341 health_ownership_metrics(),
1342 health_runtime_verdict_metrics(),
1343 health_runtime_observation_metrics(),
1344 health_runtime_production_metrics(),
1345 ] {
1346 let Value::Object(section) = section else {
1347 continue;
1348 };
1349 metrics.extend(section);
1350 }
1351 Value::Object(metrics)
1352}
1353
1354fn health_size_complexity_metrics() -> Value {
1355 json!({
1356 "cyclomatic": {
1357 "name": "Cyclomatic Complexity",
1358 "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.",
1359 "range": "[1, \u{221e})",
1360 "interpretation": "lower is better; default threshold: 20"
1361 },
1362 "cognitive": {
1363 "name": "Cognitive Complexity",
1364 "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.",
1365 "range": "[0, \u{221e})",
1366 "interpretation": "lower is better; default threshold: 15"
1367 },
1368 "line_count": {
1369 "name": "Function Line Count",
1370 "description": "Number of lines in the function body.",
1371 "range": "[1, \u{221e})",
1372 "interpretation": "context-dependent; long functions may need splitting"
1373 },
1374 "lines": {
1375 "name": "File Line Count",
1376 "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.",
1377 "range": "[1, \u{221e})",
1378 "interpretation": "context-dependent; large files may benefit from splitting even if individual functions are small"
1379 }
1380 })
1381}
1382
1383fn health_quality_metrics() -> Value {
1384 json!({
1385 "maintainability_index": {
1386 "name": "Maintainability Index",
1387 "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.",
1388 "range": "[0, 100]",
1389 "interpretation": "higher is better; <40 poor, 40\u{2013}70 moderate, >70 good"
1390 },
1391 "complexity_density": {
1392 "name": "Complexity Density",
1393 "description": "Total cyclomatic complexity divided by lines of code. Measures how densely complex the code is per line.",
1394 "range": "[0, \u{221e})",
1395 "interpretation": "lower is better; >1.0 indicates very dense complexity"
1396 },
1397 "dead_code_ratio": {
1398 "name": "Dead Code Ratio",
1399 "description": "Fraction of value exports (excluding type-only exports like interfaces and type aliases) with zero references across the project.",
1400 "range": "[0, 1]",
1401 "interpretation": "lower is better; 0 = all exports are used"
1402 }
1403 })
1404}
1405
1406fn health_coupling_metrics() -> Value {
1407 json!({
1408 "fan_in": {
1409 "name": "Fan-in (Importers)",
1410 "description": "Number of files that import this file. High fan-in means high blast radius \u{2014} changes to this file affect many dependents.",
1411 "range": "[0, \u{221e})",
1412 "interpretation": "context-dependent; high fan-in files need careful review before changes"
1413 },
1414 "fan_out": {
1415 "name": "Fan-out (Imports)",
1416 "description": "Number of files this file directly imports. High fan-out indicates high coupling and change propagation risk.",
1417 "range": "[0, \u{221e})",
1418 "interpretation": "lower is better; MI penalty caps at ~40 imports"
1419 },
1420 })
1421}
1422
1423fn health_render_fan_in_metrics() -> Value {
1424 json!({
1425 "max_render_fan_in": {
1426 "name": "Render Fan-in (Blast Radius)",
1427 "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.",
1428 "range": "[0, \u{221e})",
1429 "interpretation": "context-dependent; a high distinct-parents component edit-ripples to many render locations. Descriptive only, never a gate or finding"
1430 }
1431 })
1432}
1433
1434fn health_churn_metrics() -> Value {
1435 json!({
1436 "score": {
1437 "name": "Hotspot Score",
1438 "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.",
1439 "range": "[0, 100]",
1440 "interpretation": "higher = riskier; prioritize refactoring high-score files"
1441 },
1442 "weighted_commits": {
1443 "name": "Weighted Commits",
1444 "description": "Recency-weighted commit count using exponential decay with 90-day half-life. Recent commits contribute more than older ones.",
1445 "range": "[0, \u{221e})",
1446 "interpretation": "higher = more recent churn activity"
1447 },
1448 "trend": {
1449 "name": "Churn Trend",
1450 "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.",
1451 "values": ["accelerating", "stable", "cooling"],
1452 "interpretation": "accelerating files need attention; cooling files are stabilizing"
1453 }
1454 })
1455}
1456
1457fn health_refactoring_rank_metrics() -> Value {
1458 json!({
1459 "priority": {
1460 "name": "Refactoring Priority",
1461 "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.",
1462 "range": "[0, 100]",
1463 "interpretation": "higher = more urgent to refactor"
1464 },
1465 "efficiency": {
1466 "name": "Efficiency Score",
1467 "description": "priority / effort_numeric (Low=1, Medium=2, High=3). Surfaces quick wins: high-priority, low-effort targets rank first. Default sort order.",
1468 "range": "[0, 100] \u{2014} effective max depends on effort: Low=100, Medium=50, High\u{2248}33",
1469 "interpretation": "higher = better quick-win value; targets are sorted by efficiency descending"
1470 },
1471 "effort": {
1472 "name": "Effort Estimate",
1473 "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.",
1474 "values": ["low", "medium", "high"],
1475 "interpretation": "low = quick win, high = needs planning and coordination"
1476 },
1477 })
1478}
1479
1480fn health_refactoring_confidence_metrics() -> Value {
1481 json!({
1482 "confidence": {
1483 "name": "Confidence Level",
1484 "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).",
1485 "values": ["high", "medium", "low"],
1486 "interpretation": "high = act on it, medium = verify context, low = treat as a signal, not a directive"
1487 },
1488 "health_score": {
1489 "name": "Health Score",
1490 "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.",
1491 "range": "[0, 100]",
1492 "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)"
1493 }
1494 })
1495}
1496
1497fn health_risk_metrics() -> Value {
1498 json!({
1499 "crap_max": {
1500 "name": "Untested Complexity Risk (CRAP)",
1501 "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.",
1502 "range": "[1, \u{221e})",
1503 "interpretation": "lower is better; >=30 is high-risk (CC >= 5 without test path)"
1504 },
1505 })
1506}
1507
1508fn health_contributor_metrics() -> Value {
1509 json!({
1510 "bus_factor": {
1511 "name": "Bus Factor",
1512 "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.",
1513 "range": "[1, \u{221e})",
1514 "interpretation": "lower is higher knowledge-loss risk; 1 means a single contributor covers most of the recent history"
1515 },
1516 "contributor_count": {
1517 "name": "Contributor Count",
1518 "description": "Number of distinct authors who touched this file in the analysis window after bot-pattern filtering.",
1519 "range": "[0, \u{221e})",
1520 "interpretation": "higher generally indicates broader knowledge spread; pair with bus_factor for context"
1521 },
1522 "share": {
1523 "name": "Contributor Share",
1524 "description": "Recency-weighted share of total weighted commits attributed to a single contributor. Rounded to three decimals.",
1525 "range": "[0, 1]",
1526 "interpretation": "share close to 1.0 indicates dominance and pairs with low bus_factor"
1527 },
1528 })
1529}
1530
1531fn health_ownership_metrics() -> Value {
1532 json!({
1533 "stale_days": {
1534 "name": "Stale Days",
1535 "description": "Days since this contributor last touched the file. Computed at analysis time.",
1536 "range": "[0, \u{221e})",
1537 "interpretation": "high stale_days on the top contributor often correlates with ownership drift"
1538 },
1539 "drift": {
1540 "name": "Ownership Drift",
1541 "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%.",
1542 "values": [true, false],
1543 "interpretation": "true means the original author is no longer maintaining; route reviews to the current top contributor"
1544 },
1545 "unowned": {
1546 "name": "Unowned (Tristate)",
1547 "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).",
1548 "values": [true, false, null],
1549 "interpretation": "true on a hotspot is a review-bottleneck risk; null means the signal is unavailable, not absent"
1550 }
1551 })
1552}
1553
1554fn health_runtime_verdict_metrics() -> Value {
1555 json!({
1556 "runtime_coverage_verdict": {
1557 "name": "Runtime Coverage Verdict",
1558 "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).",
1559 "values": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
1560 "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."
1561 },
1562 })
1563}
1564
1565fn health_runtime_observation_metrics() -> Value {
1566 json!({
1567 "runtime_coverage_state": {
1568 "name": "Runtime Coverage State",
1569 "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.",
1570 "values": ["called", "never-called", "coverage-unavailable", "unknown"],
1571 "interpretation": "`never-called` in combination with static `unused` is the highest-confidence delete signal"
1572 },
1573 "runtime_coverage_confidence": {
1574 "name": "Runtime Coverage Confidence",
1575 "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.",
1576 "values": ["high", "medium", "low", "unknown"],
1577 "interpretation": "high = act on it; medium = verify context; low = treat as a signal only"
1578 }
1579 })
1580}
1581
1582fn health_runtime_production_metrics() -> Value {
1583 json!({
1584 "production_invocations": {
1585 "name": "Production Invocations",
1586 "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.",
1587 "range": "[0, \u{221e})",
1588 "interpretation": "0 + tracked = cold path; 0 + untracked = unknown; high + never-called cannot occur by definition"
1589 },
1590 "percent_dead_in_production": {
1591 "name": "Percent Dead in Production",
1592 "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.",
1593 "range": "[0, 100]",
1594 "interpretation": "lower is better; values above ~10% on a long-running service indicate a large cleanup opportunity"
1595 }
1596 })
1597}
1598
1599#[must_use]
1601pub fn dupes_meta() -> Value {
1602 json!({
1603 "docs": DUPES_DOCS,
1604 "field_definitions": {
1605 "actions[]": ACTIONS_FIELD_DEFINITION,
1606 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
1607 },
1608 "metrics": {
1609 "duplication_percentage": {
1610 "name": "Duplication Percentage",
1611 "description": "Fraction of total source tokens that appear in at least one clone group. Computed over the full analyzed file set.",
1612 "range": "[0, 100]",
1613 "interpretation": "lower is better"
1614 },
1615 "token_count": {
1616 "name": "Token Count",
1617 "description": "Number of normalized source tokens in the clone group. Tokens are language-aware (keywords, identifiers, operators, punctuation). Higher token count = larger duplicate.",
1618 "range": "[1, \u{221e})",
1619 "interpretation": "larger clones have higher refactoring value"
1620 },
1621 "line_count": {
1622 "name": "Line Count",
1623 "description": "Number of source lines spanned by the clone instance. Approximation of clone size for human readability.",
1624 "range": "[1, \u{221e})",
1625 "interpretation": "larger clones are more impactful to deduplicate"
1626 },
1627 "clone_groups": {
1628 "name": "Clone Groups",
1629 "description": "A set of code fragments with identical or near-identical normalized token sequences. Each group has 2+ instances across different locations.",
1630 "interpretation": "each group is a single refactoring opportunity"
1631 },
1632 "clone_groups_below_min_occurrences": {
1633 "name": "Clone Groups Below minOccurrences",
1634 "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`.",
1635 "range": "[0, \u{221e})",
1636 "interpretation": "high values suggest noisy pair-only duplication; lower `minOccurrences` to inspect"
1637 },
1638 "clone_families": {
1639 "name": "Clone Families",
1640 "description": "Groups of clone groups that share the same set of files. Indicates systematic duplication patterns (e.g., mirrored directory structures).",
1641 "interpretation": "families suggest extract-module refactoring opportunities"
1642 }
1643 }
1644 })
1645}
1646
1647#[must_use]
1649pub fn security_meta() -> Meta {
1650 let rules = SECURITY_RULES
1651 .iter()
1652 .map(|rule| {
1653 (
1654 rule.id.to_string(),
1655 MetaRule {
1656 name: Some(rule.name.to_string()),
1657 description: Some(rule.full.to_string()),
1658 docs: Some(rule_docs_url(rule)),
1659 },
1660 )
1661 })
1662 .collect();
1663
1664 Meta {
1665 docs: Some(SECURITY_DOCS.to_string()),
1666 telemetry: None,
1667 field_definitions: BTreeMap::from([
1668 (
1669 "version".to_string(),
1670 "fallow CLI version that produced this output.".to_string(),
1671 ),
1672 (
1673 "elapsed_ms".to_string(),
1674 "Wall-clock milliseconds spent producing the security report.".to_string(),
1675 ),
1676 (
1677 "config".to_string(),
1678 "Privacy-safe config context relevant to security candidate generation."
1679 .to_string(),
1680 ),
1681 (
1682 "config.rules.*.configured".to_string(),
1683 "Severity from resolved config before the security command forced default-off rules on."
1684 .to_string(),
1685 ),
1686 (
1687 "config.rules.*.effective".to_string(),
1688 "Severity used for this security command run.".to_string(),
1689 ),
1690 (
1691 "config.categories_include".to_string(),
1692 "Configured security category include list. null means unset, [] means explicitly empty."
1693 .to_string(),
1694 ),
1695 (
1696 "config.categories_exclude".to_string(),
1697 "Configured security category exclude list. null means unset, [] means explicitly empty."
1698 .to_string(),
1699 ),
1700 (
1701 "security_findings[]".to_string(),
1702 "Unverified security candidates for downstream human or agent verification."
1703 .to_string(),
1704 ),
1705 (
1706 "summary.security_findings".to_string(),
1707 "Number of security candidates after all filters, gates, and scopes.".to_string(),
1708 ),
1709 (
1710 "summary.by_severity".to_string(),
1711 "Fixed high, medium, and low severity counts for summary JSON.".to_string(),
1712 ),
1713 (
1714 "summary.by_category".to_string(),
1715 "Candidate counts by catalogue category, or by kind for uncategorized findings."
1716 .to_string(),
1717 ),
1718 (
1719 "summary.by_reachability".to_string(),
1720 "Fixed reachability and source-backed ranking-signal counts for summary JSON."
1721 .to_string(),
1722 ),
1723 (
1724 "summary.by_runtime_state".to_string(),
1725 "Fixed production-runtime coverage state counts for summary JSON.".to_string(),
1726 ),
1727 (
1728 "unresolved_edge_files".to_string(),
1729 "Number of client files whose import cone contains dynamic edges the graph could not follow."
1730 .to_string(),
1731 ),
1732 (
1733 "unresolved_callee_sites".to_string(),
1734 "Number of sink-shaped nodes whose callee could not be flattened to a static path."
1735 .to_string(),
1736 ),
1737 ]),
1738 metrics: BTreeMap::new(),
1739 rules,
1740 }
1741}
1742
1743#[must_use]
1745pub fn coverage_setup_meta() -> Value {
1746 json!({
1747 "docs_url": COVERAGE_SETUP_DOCS,
1748 "field_definitions": {
1749 "schema_version": "Coverage setup JSON contract version. Stays at \"1\" for additive opt-in fields such as _meta.",
1750 "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.",
1751 "package_manager": "Detected package manager used for install and run commands, or null when no package manager signal was found.",
1752 "runtime_targets": "Union of runtime targets across emitted members.",
1753 "members[]": "Per-runtime-workspace setup recipes. Pure aggregator roots and build-only libraries are omitted.",
1754 "members[].name": "Workspace package name from package.json, or the root directory name when package.json has no name.",
1755 "members[].path": "Workspace path relative to the command root. The root package is represented as \".\".",
1756 "members[].framework_detected": "Runtime framework detected for that member.",
1757 "members[].package_manager": "Package manager detected for that member, or inherited from the workspace root when no member-specific signal exists.",
1758 "members[].runtime_targets": "Runtime targets produced by that member.",
1759 "members[].files_to_edit": "Files in that member that should receive runtime beacon setup code.",
1760 "members[].snippets": "Copy-paste setup snippets for that member, with paths relative to the command root.",
1761 "members[].dockerfile_snippet": "Environment snippet for file-system capture in that member's containerized Node runtime, or null when not applicable.",
1762 "members[].warnings": "Actionable setup caveats discovered for that member.",
1763 "config_written": "Always null for --json because JSON setup is side-effect-free and never writes configuration.",
1764 "files_to_edit": "Compatibility copy of the primary member's files, with workspace prefixes when the primary member is not the root.",
1765 "snippets": "Compatibility copy of the primary member's snippets, with workspace prefixes when the primary member is not the root.",
1766 "dockerfile_snippet": "Environment snippet for file-system capture in containerized Node runtimes, or null when not applicable.",
1767 "commands": "Package-manager commands needed to install the runtime beacon and sidecar packages.",
1768 "next_steps": "Ordered setup workflow after applying the emitted snippets.",
1769 "warnings": "Actionable setup caveats discovered while building the recipe."
1770 },
1771 "enums": {
1772 "framework_detected": ["nextjs", "nestjs", "nuxt", "sveltekit", "astro", "remix", "vite", "plain_node", "unknown"],
1773 "runtime_targets": ["node", "browser"],
1774 "package_manager": ["npm", "pnpm", "yarn", "bun", null]
1775 },
1776 "warnings": {
1777 "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.",
1778 "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.",
1779 "Package manager was not detected": "No packageManager field or known lockfile was found. Commands fall back to npm.",
1780 "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."
1781 }
1782 })
1783}
1784
1785#[must_use]
1787pub fn coverage_analyze_meta() -> Value {
1788 json!({
1789 "docs_url": COVERAGE_ANALYZE_DOCS,
1790 "field_definitions": {
1791 "schema_version": "Standalone coverage analyze envelope version. \"1\" for the current shape.",
1792 "version": "fallow CLI version that produced this output.",
1793 "elapsed_ms": "Wall-clock milliseconds spent producing the report.",
1794 "runtime_coverage": "Same RuntimeCoverageReport block emitted by `fallow health --runtime-coverage`.",
1795 "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.",
1796 "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.",
1797 "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.",
1798 "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.",
1799 "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.",
1800 "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.",
1801 "runtime_coverage.findings[].evidence.static_status": "used = the function is reachable in the AST module graph; unused = it is dead by static analysis.",
1802 "runtime_coverage.findings[].evidence.test_coverage": "covered = the local test suite hits the function; not_covered otherwise.",
1803 "runtime_coverage.findings[].evidence.v8_tracking": "tracked = V8 observed the function during the capture window; untracked otherwise.",
1804 "runtime_coverage.findings[].actions[].type": "Suggested follow-up identifier. delete-cold-code is emitted on safe_to_delete; review-runtime on review_required.",
1805 "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.",
1806 "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.",
1807 "runtime_coverage.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally."
1808 },
1809 "enums": {
1810 "data_source": ["local", "cloud"],
1811 "report_verdict": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
1812 "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
1813 "static_status": ["used", "unused"],
1814 "test_coverage": ["covered", "not_covered"],
1815 "v8_tracking": ["tracked", "untracked"],
1816 "action_type": ["delete-cold-code", "review-runtime"]
1817 },
1818 "warnings": {
1819 "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
1820 "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."
1821 }
1822 })
1823}
1824
1825#[cfg(test)]
1826mod tests {
1827 use super::*;
1828
1829 #[test]
1830 fn rule_by_id_finds_check_rule() {
1831 let rule = rule_by_id("fallow/unused-file").unwrap();
1832 assert_eq!(rule.name, "Unused Files");
1833 }
1834
1835 #[test]
1836 fn rule_by_id_finds_health_rule() {
1837 let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1838 assert_eq!(rule.name, "High Cyclomatic Complexity");
1839 }
1840
1841 #[test]
1842 fn rule_by_id_finds_dupes_rule() {
1843 let rule = rule_by_id("fallow/code-duplication").unwrap();
1844 assert_eq!(rule.name, "Code Duplication");
1845 }
1846
1847 #[test]
1848 fn rule_by_id_finds_security_rule() {
1849 let rule = rule_by_id("security/tainted-sink").unwrap();
1850 assert_eq!(rule.name, "Tainted Sink Candidates");
1851 }
1852
1853 #[test]
1854 fn rule_by_id_returns_none_for_unknown() {
1855 assert!(rule_by_id("fallow/nonexistent").is_none());
1856 assert!(rule_by_id("").is_none());
1857 }
1858
1859 #[test]
1860 fn rule_docs_url_format() {
1861 let rule = rule_by_id("fallow/unused-export").unwrap();
1862 let url = rule_docs_url(rule);
1863 assert!(url.starts_with("https://docs.fallow.tools/"));
1864 assert!(url.contains("unused-exports"));
1865 }
1866
1867 #[test]
1868 fn check_rules_all_have_fallow_prefix() {
1869 for rule in CHECK_RULES {
1870 assert!(
1871 rule.id.starts_with("fallow/"),
1872 "rule {} should start with fallow/",
1873 rule.id
1874 );
1875 }
1876 }
1877
1878 #[test]
1879 fn check_rules_all_have_docs_path() {
1880 for rule in CHECK_RULES {
1881 assert!(
1882 !rule.docs_path.is_empty(),
1883 "rule {} should have a docs_path",
1884 rule.id
1885 );
1886 }
1887 }
1888
1889 #[test]
1890 fn check_rules_no_duplicate_ids() {
1891 let mut seen = rustc_hash::FxHashSet::default();
1892 for rule in CHECK_RULES
1893 .iter()
1894 .chain(HEALTH_RULES)
1895 .chain(DUPES_RULES)
1896 .chain(FLAGS_RULES)
1897 .chain(SECURITY_RULES)
1898 {
1899 assert!(seen.insert(rule.id), "duplicate rule id: {}", rule.id);
1900 }
1901 }
1902
1903 #[test]
1904 fn check_meta_has_docs_and_rules() {
1905 let meta = check_meta();
1906 assert!(meta.get("docs").is_some());
1907 assert!(meta.get("rules").is_some());
1908 let rules = meta["rules"].as_object().unwrap();
1909 assert_eq!(rules.len(), CHECK_RULES.len());
1910 assert!(rules.contains_key("unused-file"));
1911 assert!(rules.contains_key("unused-export"));
1912 assert!(rules.contains_key("unused-type"));
1913 assert!(rules.contains_key("unused-dependency"));
1914 assert!(rules.contains_key("unused-dev-dependency"));
1915 assert!(rules.contains_key("unused-optional-dependency"));
1916 assert!(rules.contains_key("unused-enum-member"));
1917 assert!(rules.contains_key("unused-class-member"));
1918 assert!(rules.contains_key("unresolved-import"));
1919 assert!(rules.contains_key("unlisted-dependency"));
1920 assert!(rules.contains_key("duplicate-export"));
1921 assert!(rules.contains_key("type-only-dependency"));
1922 assert!(rules.contains_key("circular-dependency"));
1923 }
1924
1925 #[test]
1926 fn check_meta_documents_per_finding_auto_fixable() {
1927 let meta = check_meta();
1928 let defs = meta["field_definitions"].as_object().unwrap();
1929 let note = defs["actions[].auto_fixable"].as_str().unwrap();
1930 assert!(
1931 note.contains("PER FINDING"),
1932 "auto_fixable note must call out per-finding evaluation"
1933 );
1934 assert!(
1935 note.contains("remove-catalog-entry"),
1936 "auto_fixable note must cite remove-catalog-entry per-instance flip"
1937 );
1938 assert!(
1939 note.contains("used_in_workspaces"),
1940 "auto_fixable note must cite the dependency-action per-instance flip"
1941 );
1942 assert!(
1943 note.contains("ignoreExports"),
1944 "auto_fixable note must cite the duplicate-exports config-fixable flip"
1945 );
1946 assert!(defs.contains_key("actions[]"));
1947 }
1948
1949 #[test]
1950 fn health_and_dupes_meta_share_actions_field_definitions() {
1951 for meta in [health_meta(), dupes_meta()] {
1952 let defs = meta["field_definitions"].as_object().unwrap();
1953 assert_eq!(
1954 defs["actions[]"].as_str().unwrap(),
1955 ACTIONS_FIELD_DEFINITION,
1956 );
1957 assert_eq!(
1958 defs["actions[].auto_fixable"].as_str().unwrap(),
1959 ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION,
1960 );
1961 }
1962 }
1963
1964 #[test]
1965 fn check_meta_rule_has_required_fields() {
1966 let meta = check_meta();
1967 let rules = meta["rules"].as_object().unwrap();
1968 for (key, value) in rules {
1969 assert!(value.get("name").is_some(), "rule {key} missing 'name'");
1970 assert!(
1971 value.get("description").is_some(),
1972 "rule {key} missing 'description'"
1973 );
1974 assert!(value.get("docs").is_some(), "rule {key} missing 'docs'");
1975 }
1976 }
1977
1978 #[test]
1979 fn health_meta_has_metrics() {
1980 let meta = health_meta();
1981 assert!(meta.get("docs").is_some());
1982 let metrics = meta["metrics"].as_object().unwrap();
1983 assert!(metrics.contains_key("cyclomatic"));
1984 assert!(metrics.contains_key("cognitive"));
1985 assert!(metrics.contains_key("maintainability_index"));
1986 assert!(metrics.contains_key("complexity_density"));
1987 assert!(metrics.contains_key("fan_in"));
1988 assert!(metrics.contains_key("fan_out"));
1989 }
1990
1991 #[test]
1992 fn dupes_meta_has_metrics() {
1993 let meta = dupes_meta();
1994 assert!(meta.get("docs").is_some());
1995 let metrics = meta["metrics"].as_object().unwrap();
1996 assert!(metrics.contains_key("duplication_percentage"));
1997 assert!(metrics.contains_key("token_count"));
1998 assert!(metrics.contains_key("clone_groups"));
1999 assert!(metrics.contains_key("clone_families"));
2000 }
2001
2002 #[test]
2003 fn coverage_setup_meta_has_docs_fields_enums_and_warnings() {
2004 let meta = coverage_setup_meta();
2005 assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
2006 assert!(
2007 meta["field_definitions"]
2008 .as_object()
2009 .unwrap()
2010 .contains_key("members[]")
2011 );
2012 assert!(
2013 meta["field_definitions"]
2014 .as_object()
2015 .unwrap()
2016 .contains_key("config_written")
2017 );
2018 assert!(
2019 meta["field_definitions"]
2020 .as_object()
2021 .unwrap()
2022 .contains_key("members[].package_manager")
2023 );
2024 assert!(
2025 meta["field_definitions"]
2026 .as_object()
2027 .unwrap()
2028 .contains_key("members[].warnings")
2029 );
2030 assert!(
2031 meta["enums"]
2032 .as_object()
2033 .unwrap()
2034 .contains_key("framework_detected")
2035 );
2036 assert!(
2037 meta["warnings"]
2038 .as_object()
2039 .unwrap()
2040 .contains_key("No runtime workspace members were detected")
2041 );
2042 assert!(
2043 meta["warnings"]
2044 .as_object()
2045 .unwrap()
2046 .contains_key("Package manager was not detected")
2047 );
2048 }
2049
2050 #[test]
2051 fn coverage_analyze_meta_documents_data_source_and_action_vocabulary() {
2052 let meta = coverage_analyze_meta();
2053 assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
2054 let fields = meta["field_definitions"].as_object().unwrap();
2055 assert!(fields.contains_key("runtime_coverage.summary.data_source"));
2056 assert!(fields.contains_key("runtime_coverage.summary.last_received_at"));
2057 assert!(fields.contains_key("runtime_coverage.findings[].evidence.test_coverage"));
2058 assert!(fields.contains_key("runtime_coverage.findings[].actions[].type"));
2059 let enums = meta["enums"].as_object().unwrap();
2060 assert_eq!(enums["data_source"], json!(["local", "cloud"]));
2061 assert_eq!(enums["test_coverage"], json!(["covered", "not_covered"]));
2062 assert_eq!(enums["v8_tracking"], json!(["tracked", "untracked"]));
2063 assert_eq!(
2064 enums["action_type"],
2065 json!(["delete-cold-code", "review-runtime"])
2066 );
2067 let warnings = meta["warnings"].as_object().unwrap();
2068 assert!(warnings.contains_key("cloud_functions_unmatched"));
2069 }
2070
2071 #[test]
2072 fn health_rules_all_have_fallow_prefix() {
2073 for rule in HEALTH_RULES {
2074 assert!(
2075 rule.id.starts_with("fallow/"),
2076 "health rule {} should start with fallow/",
2077 rule.id
2078 );
2079 }
2080 }
2081
2082 #[test]
2083 fn health_rules_all_have_docs_path() {
2084 for rule in HEALTH_RULES {
2085 assert!(
2086 !rule.docs_path.is_empty(),
2087 "health rule {} should have a docs_path",
2088 rule.id
2089 );
2090 }
2091 }
2092
2093 #[test]
2094 fn health_rules_all_have_non_empty_fields() {
2095 for rule in HEALTH_RULES {
2096 assert!(
2097 !rule.name.is_empty(),
2098 "health rule {} missing name",
2099 rule.id
2100 );
2101 assert!(
2102 !rule.short.is_empty(),
2103 "health rule {} missing short description",
2104 rule.id
2105 );
2106 assert!(
2107 !rule.full.is_empty(),
2108 "health rule {} missing full description",
2109 rule.id
2110 );
2111 }
2112 }
2113
2114 #[test]
2115 fn dupes_rules_all_have_fallow_prefix() {
2116 for rule in DUPES_RULES {
2117 assert!(
2118 rule.id.starts_with("fallow/"),
2119 "dupes rule {} should start with fallow/",
2120 rule.id
2121 );
2122 }
2123 }
2124
2125 #[test]
2126 fn dupes_rules_all_have_docs_path() {
2127 for rule in DUPES_RULES {
2128 assert!(
2129 !rule.docs_path.is_empty(),
2130 "dupes rule {} should have a docs_path",
2131 rule.id
2132 );
2133 }
2134 }
2135
2136 #[test]
2137 fn dupes_rules_all_have_non_empty_fields() {
2138 for rule in DUPES_RULES {
2139 assert!(!rule.name.is_empty(), "dupes rule {} missing name", rule.id);
2140 assert!(
2141 !rule.short.is_empty(),
2142 "dupes rule {} missing short description",
2143 rule.id
2144 );
2145 assert!(
2146 !rule.full.is_empty(),
2147 "dupes rule {} missing full description",
2148 rule.id
2149 );
2150 }
2151 }
2152
2153 #[test]
2154 fn security_rules_all_have_security_prefix() {
2155 for rule in SECURITY_RULES {
2156 assert!(
2157 rule.id.starts_with("security/"),
2158 "security rule {} should start with security/",
2159 rule.id
2160 );
2161 }
2162 }
2163
2164 #[test]
2165 fn security_rules_all_have_docs_path() {
2166 for rule in SECURITY_RULES {
2167 assert_eq!(
2168 rule.docs_path, "cli/security",
2169 "security rule {} should point at security docs",
2170 rule.id
2171 );
2172 }
2173 }
2174
2175 #[test]
2176 fn security_rules_all_have_non_empty_fields() {
2177 for rule in SECURITY_RULES {
2178 assert!(
2179 !rule.name.is_empty(),
2180 "security rule {} missing name",
2181 rule.id
2182 );
2183 assert!(
2184 !rule.short.is_empty(),
2185 "security rule {} missing short description",
2186 rule.id
2187 );
2188 assert!(
2189 !rule.full.is_empty(),
2190 "security rule {} missing full description",
2191 rule.id
2192 );
2193 }
2194 }
2195
2196 #[test]
2197 fn check_rules_all_have_non_empty_fields() {
2198 for rule in CHECK_RULES {
2199 assert!(!rule.name.is_empty(), "check rule {} missing name", rule.id);
2200 assert!(
2201 !rule.short.is_empty(),
2202 "check rule {} missing short description",
2203 rule.id
2204 );
2205 assert!(
2206 !rule.full.is_empty(),
2207 "check rule {} missing full description",
2208 rule.id
2209 );
2210 }
2211 }
2212
2213 #[test]
2214 fn rule_docs_url_health_rule() {
2215 let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
2216 let url = rule_docs_url(rule);
2217 assert!(url.starts_with("https://docs.fallow.tools/"));
2218 assert!(url.contains("health"));
2219 }
2220
2221 #[test]
2222 fn rule_docs_url_dupes_rule() {
2223 let rule = rule_by_id("fallow/code-duplication").unwrap();
2224 let url = rule_docs_url(rule);
2225 assert!(url.starts_with("https://docs.fallow.tools/"));
2226 assert!(url.contains("duplication"));
2227 }
2228
2229 #[test]
2230 fn rule_docs_url_security_rule() {
2231 let rule = rule_by_id("security/sql-injection").unwrap();
2232 let url = rule_docs_url(rule);
2233 assert_eq!(url, "https://docs.fallow.tools/cli/security");
2234 }
2235
2236 #[test]
2237 fn health_meta_all_metrics_have_name_and_description() {
2238 let meta = health_meta();
2239 let metrics = meta["metrics"].as_object().unwrap();
2240 for (key, value) in metrics {
2241 assert!(
2242 value.get("name").is_some(),
2243 "health metric {key} missing 'name'"
2244 );
2245 assert!(
2246 value.get("description").is_some(),
2247 "health metric {key} missing 'description'"
2248 );
2249 assert!(
2250 value.get("interpretation").is_some(),
2251 "health metric {key} missing 'interpretation'"
2252 );
2253 }
2254 }
2255
2256 #[test]
2257 fn health_meta_has_all_expected_metrics() {
2258 let meta = health_meta();
2259 let metrics = meta["metrics"].as_object().unwrap();
2260 let expected = [
2261 "cyclomatic",
2262 "cognitive",
2263 "line_count",
2264 "lines",
2265 "maintainability_index",
2266 "complexity_density",
2267 "dead_code_ratio",
2268 "fan_in",
2269 "fan_out",
2270 "score",
2271 "weighted_commits",
2272 "trend",
2273 "priority",
2274 "efficiency",
2275 "effort",
2276 "confidence",
2277 "bus_factor",
2278 "contributor_count",
2279 "share",
2280 "stale_days",
2281 "drift",
2282 "unowned",
2283 "runtime_coverage_verdict",
2284 "runtime_coverage_state",
2285 "runtime_coverage_confidence",
2286 "production_invocations",
2287 "percent_dead_in_production",
2288 ];
2289 for key in &expected {
2290 assert!(
2291 metrics.contains_key(*key),
2292 "health_meta missing expected metric: {key}"
2293 );
2294 }
2295 }
2296
2297 #[test]
2298 fn dupes_meta_all_metrics_have_name_and_description() {
2299 let meta = dupes_meta();
2300 let metrics = meta["metrics"].as_object().unwrap();
2301 for (key, value) in metrics {
2302 assert!(
2303 value.get("name").is_some(),
2304 "dupes metric {key} missing 'name'"
2305 );
2306 assert!(
2307 value.get("description").is_some(),
2308 "dupes metric {key} missing 'description'"
2309 );
2310 }
2311 }
2312
2313 #[test]
2314 fn dupes_meta_has_line_count() {
2315 let meta = dupes_meta();
2316 let metrics = meta["metrics"].as_object().unwrap();
2317 assert!(metrics.contains_key("line_count"));
2318 }
2319
2320 #[test]
2321 fn check_docs_url_valid() {
2322 assert!(CHECK_DOCS.starts_with("https://"));
2323 assert!(CHECK_DOCS.contains("dead-code"));
2324 }
2325
2326 #[test]
2327 fn health_docs_url_valid() {
2328 assert!(HEALTH_DOCS.starts_with("https://"));
2329 assert!(HEALTH_DOCS.contains("health"));
2330 }
2331
2332 #[test]
2333 fn dupes_docs_url_valid() {
2334 assert!(DUPES_DOCS.starts_with("https://"));
2335 assert!(DUPES_DOCS.contains("dupes"));
2336 }
2337
2338 #[test]
2339 fn check_meta_docs_url_matches_constant() {
2340 let meta = check_meta();
2341 assert_eq!(meta["docs"].as_str().unwrap(), CHECK_DOCS);
2342 }
2343
2344 #[test]
2345 fn health_meta_docs_url_matches_constant() {
2346 let meta = health_meta();
2347 assert_eq!(meta["docs"].as_str().unwrap(), HEALTH_DOCS);
2348 }
2349
2350 #[test]
2351 fn dupes_meta_docs_url_matches_constant() {
2352 let meta = dupes_meta();
2353 assert_eq!(meta["docs"].as_str().unwrap(), DUPES_DOCS);
2354 }
2355
2356 #[test]
2357 fn rule_by_id_finds_all_check_rules() {
2358 for rule in CHECK_RULES {
2359 assert!(
2360 rule_by_id(rule.id).is_some(),
2361 "rule_by_id should find check rule {}",
2362 rule.id
2363 );
2364 }
2365 }
2366
2367 #[test]
2368 fn rule_by_id_finds_all_health_rules() {
2369 for rule in HEALTH_RULES {
2370 assert!(
2371 rule_by_id(rule.id).is_some(),
2372 "rule_by_id should find health rule {}",
2373 rule.id
2374 );
2375 }
2376 }
2377
2378 #[test]
2379 fn rule_by_id_finds_all_dupes_rules() {
2380 for rule in DUPES_RULES {
2381 assert!(
2382 rule_by_id(rule.id).is_some(),
2383 "rule_by_id should find dupes rule {}",
2384 rule.id
2385 );
2386 }
2387 }
2388
2389 #[test]
2390 fn rule_by_id_finds_all_security_rules() {
2391 for rule in SECURITY_RULES {
2392 assert!(
2393 rule_by_id(rule.id).is_some(),
2394 "rule_by_id should find security rule {}",
2395 rule.id
2396 );
2397 }
2398 }
2399
2400 #[test]
2401 fn check_rules_count() {
2402 assert_eq!(CHECK_RULES.len(), 44);
2403 }
2404
2405 #[test]
2406 fn health_rules_count() {
2407 assert_eq!(HEALTH_RULES.len(), 16);
2408 }
2409
2410 #[test]
2411 fn dupes_rules_count() {
2412 assert_eq!(DUPES_RULES.len(), 1);
2413 }
2414
2415 #[test]
2416 fn flags_rules_count() {
2417 assert_eq!(FLAGS_RULES.len(), 1);
2418 }
2419
2420 #[test]
2421 fn security_rules_count() {
2422 assert_eq!(
2423 SECURITY_RULES.len(),
2424 matcher_entries_from_security_catalogue().len() + 3
2425 );
2426 }
2427
2428 #[test]
2429 fn security_rules_cover_every_catalogue_matcher() {
2430 let mut rule_ids = rustc_hash::FxHashSet::default();
2431 for rule in SECURITY_RULES {
2432 rule_ids.insert(rule.id);
2433 }
2434
2435 for matcher in matcher_entries_from_security_catalogue() {
2436 let rule_id = format!("security/{}", matcher.id);
2437 assert!(
2438 rule_ids.contains(rule_id.as_str()),
2439 "security matcher {} has no explain rule",
2440 matcher.id
2441 );
2442 }
2443 }
2444
2445 #[test]
2446 fn security_catalogue_rules_match_catalogue_title_and_cwe() {
2447 for matcher in matcher_entries_from_security_catalogue() {
2448 let rule_id = format!("security/{}", matcher.id);
2449 let rule = rule_by_id(&rule_id)
2450 .unwrap_or_else(|| panic!("security matcher {} has no explain rule", matcher.id));
2451 let cwe = format!("CWE-{}", matcher.cwe);
2452 assert_eq!(
2453 rule.name, matcher.title,
2454 "security matcher {} has stale explain title",
2455 matcher.id
2456 );
2457 assert!(
2458 rule.short.contains(&cwe),
2459 "security matcher {} explain summary does not mention {cwe}",
2460 matcher.id
2461 );
2462 assert!(
2463 rule.full.contains(&cwe),
2464 "security matcher {} explain rationale does not mention {cwe}",
2465 matcher.id
2466 );
2467 }
2468 }
2469
2470 #[test]
2476 fn every_rule_declares_a_category() {
2477 let allowed = [
2478 "Dead code",
2479 "Dependencies",
2480 "Duplication",
2481 "Health",
2482 "Architecture",
2483 "Suppressions",
2484 "Security",
2485 "Policy",
2486 "Flags",
2487 ];
2488 for rule in CHECK_RULES
2489 .iter()
2490 .chain(HEALTH_RULES)
2491 .chain(DUPES_RULES)
2492 .chain(FLAGS_RULES)
2493 .chain(SECURITY_RULES)
2494 {
2495 assert!(
2496 !rule.category.is_empty(),
2497 "rule {} has empty category",
2498 rule.id
2499 );
2500 assert!(
2501 allowed.contains(&rule.category),
2502 "rule {} has unrecognised category {:?}; add to allowlist or pick from {:?}",
2503 rule.id,
2504 rule.category,
2505 allowed
2506 );
2507 }
2508 }
2509
2510 #[derive(Debug)]
2511 struct MatcherEntry {
2512 id: &'static str,
2513 title: &'static str,
2514 cwe: &'static str,
2515 }
2516
2517 fn matcher_entries_from_security_catalogue() -> Vec<MatcherEntry> {
2518 let toml = include_str!("../../core/data/security_matchers.toml");
2519 let mut entries = Vec::new();
2520 let mut in_matcher = false;
2521 let mut id = None;
2522 let mut title = None;
2523 let mut cwe = None;
2524
2525 for line in toml.lines() {
2526 let trimmed = line.trim();
2527 if trimmed == "[[matcher]]" {
2528 if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2529 entries.push(MatcherEntry { id, title, cwe });
2530 }
2531 in_matcher = true;
2532 continue;
2533 }
2534 if trimmed.starts_with("[[") {
2535 if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2536 entries.push(MatcherEntry { id, title, cwe });
2537 }
2538 in_matcher = false;
2539 continue;
2540 }
2541 if !in_matcher {
2542 continue;
2543 }
2544 if let Some(value) = trimmed
2545 .strip_prefix("id = \"")
2546 .and_then(|value| value.strip_suffix('"'))
2547 {
2548 id = Some(value);
2549 } else if let Some(value) = trimmed
2550 .strip_prefix("title = \"")
2551 .and_then(|value| value.strip_suffix('"'))
2552 {
2553 title = Some(value);
2554 } else if let Some(value) = trimmed.strip_prefix("cwe = ") {
2555 cwe = Some(value);
2556 }
2557 }
2558
2559 if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2560 entries.push(MatcherEntry { id, title, cwe });
2561 }
2562
2563 let mut seen = rustc_hash::FxHashSet::default();
2564 entries
2565 .into_iter()
2566 .filter(|entry| seen.insert(entry.id))
2567 .collect()
2568 }
2569}