1use std::process::ExitCode;
8
9use colored::Colorize;
10use fallow_config::OutputFormat;
11use serde_json::{Value, json};
12
13const 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
32const 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.";
37
38const 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`.";
43
44pub struct RuleDef {
48 pub id: &'static str,
49 pub category: &'static str,
56 pub name: &'static str,
57 pub short: &'static str,
58 pub full: &'static str,
59 pub docs_path: &'static str,
60}
61
62pub const CHECK_RULES: &[RuleDef] = &[
63 RuleDef {
64 id: "fallow/unused-file",
65 category: "Dead code",
66 name: "Unused Files",
67 short: "File is not reachable from any entry point",
68 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.",
69 docs_path: "explanations/dead-code#unused-files",
70 },
71 RuleDef {
72 id: "fallow/unused-export",
73 category: "Dead code",
74 name: "Unused Exports",
75 short: "Export is never imported",
76 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.",
77 docs_path: "explanations/dead-code#unused-exports",
78 },
79 RuleDef {
80 id: "fallow/unused-type",
81 category: "Dead code",
82 name: "Unused Type Exports",
83 short: "Type export is never imported",
84 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.",
85 docs_path: "explanations/dead-code#unused-types",
86 },
87 RuleDef {
88 id: "fallow/private-type-leak",
89 category: "Dead code",
90 name: "Private Type Leaks",
91 short: "Exported signature references a private type",
92 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.",
93 docs_path: "explanations/dead-code#private-type-leaks",
94 },
95 RuleDef {
96 id: "fallow/unused-dependency",
97 category: "Dependencies",
98 name: "Unused Dependencies",
99 short: "Dependency listed but never imported",
100 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.",
101 docs_path: "explanations/dead-code#unused-dependencies",
102 },
103 RuleDef {
104 id: "fallow/unused-dev-dependency",
105 category: "Dependencies",
106 name: "Unused Dev Dependencies",
107 short: "Dev dependency listed but never imported",
108 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.",
109 docs_path: "explanations/dead-code#unused-devdependencies",
110 },
111 RuleDef {
112 id: "fallow/unused-optional-dependency",
113 category: "Dependencies",
114 name: "Unused Optional Dependencies",
115 short: "Optional dependency listed but never imported",
116 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.",
117 docs_path: "explanations/dead-code#unused-optionaldependencies",
118 },
119 RuleDef {
120 id: "fallow/type-only-dependency",
121 category: "Dependencies",
122 name: "Type-only Dependencies",
123 short: "Production dependency only used via type-only imports",
124 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.",
125 docs_path: "explanations/dead-code#type-only-dependencies",
126 },
127 RuleDef {
128 id: "fallow/test-only-dependency",
129 category: "Dependencies",
130 name: "Test-only Dependencies",
131 short: "Production dependency only imported by test files",
132 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.",
133 docs_path: "explanations/dead-code#test-only-dependencies",
134 },
135 RuleDef {
136 id: "fallow/unused-enum-member",
137 category: "Dead code",
138 name: "Unused Enum Members",
139 short: "Enum member is never referenced",
140 full: "Enum members that are never referenced in the codebase. Uses scope-aware binding analysis to track all references including computed access patterns.",
141 docs_path: "explanations/dead-code#unused-enum-members",
142 },
143 RuleDef {
144 id: "fallow/unused-class-member",
145 category: "Dead code",
146 name: "Unused Class Members",
147 short: "Class member is never referenced",
148 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.",
149 docs_path: "explanations/dead-code#unused-class-members",
150 },
151 RuleDef {
152 id: "fallow/unresolved-import",
153 category: "Dead code",
154 name: "Unresolved Imports",
155 short: "Import could not be resolved",
156 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.",
157 docs_path: "explanations/dead-code#unresolved-imports",
158 },
159 RuleDef {
160 id: "fallow/unlisted-dependency",
161 category: "Dependencies",
162 name: "Unlisted Dependencies",
163 short: "Dependency used but not in package.json",
164 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.",
165 docs_path: "explanations/dead-code#unlisted-dependencies",
166 },
167 RuleDef {
168 id: "fallow/duplicate-export",
169 category: "Dead code",
170 name: "Duplicate Exports",
171 short: "Export name appears in multiple modules",
172 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.",
173 docs_path: "explanations/dead-code#duplicate-exports",
174 },
175 RuleDef {
176 id: "fallow/circular-dependency",
177 category: "Architecture",
178 name: "Circular Dependencies",
179 short: "Circular dependency chain detected",
180 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.",
181 docs_path: "explanations/dead-code#circular-dependencies",
182 },
183 RuleDef {
184 id: "fallow/boundary-violation",
185 category: "Architecture",
186 name: "Boundary Violations",
187 short: "Import crosses a configured architecture boundary",
188 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.",
189 docs_path: "explanations/dead-code#boundary-violations",
190 },
191 RuleDef {
192 id: "fallow/stale-suppression",
193 category: "Suppressions",
194 name: "Stale Suppressions",
195 short: "Suppression comment or tag no longer matches any issue",
196 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.",
197 docs_path: "explanations/dead-code#stale-suppressions",
198 },
199 RuleDef {
200 id: "fallow/unused-catalog-entry",
201 category: "Dependencies",
202 name: "Unused pnpm catalog entry",
203 short: "Catalog entry in pnpm-workspace.yaml not referenced by any workspace package",
204 full: "An entry in the `catalog:` or `catalogs:` section of pnpm-workspace.yaml that no workspace package.json references via the `catalog:` protocol. Catalog entries are leftover dependency metadata once a package is removed from every consumer; delete the entry to keep the catalog truthful. See also: fallow/unresolved-catalog-reference (the inverse: consumer references a catalog that does not declare the package).",
205 docs_path: "explanations/dead-code#unused-catalog-entries",
206 },
207 RuleDef {
208 id: "fallow/empty-catalog-group",
209 category: "Dependencies",
210 name: "Empty pnpm catalog group",
211 short: "Named catalog group in pnpm-workspace.yaml has no entries",
212 full: "A named group under `catalogs:` in pnpm-workspace.yaml has no package entries. Empty named groups are leftover catalog structure after the last entry is removed. The top-level `catalog:` map is intentionally ignored because some projects keep it as a stable hook.",
213 docs_path: "explanations/dead-code#empty-catalog-groups",
214 },
215 RuleDef {
216 id: "fallow/unresolved-catalog-reference",
217 category: "Dependencies",
218 name: "Unresolved pnpm catalog reference",
219 short: "package.json references a catalog that does not declare the package",
220 full: "A workspace package.json declares a dependency with the `catalog:` or `catalog:<name>` protocol, but the catalog has no entry for that package. `pnpm install` will fail with ERR_PNPM_CATALOG_ENTRY_NOT_FOUND_FOR_CATALOG_PROTOCOL. To fix: add the package to the named catalog, switch the reference to a different catalog that does declare it, or remove the reference and pin a hardcoded version. Scope: the detector scans `dependencies`, `devDependencies`, `peerDependencies`, and `optionalDependencies` in every workspace `package.json`. See also: fallow/unused-catalog-entry (the inverse: catalog entries no consumer references).",
221 docs_path: "explanations/dead-code#unresolved-catalog-references",
222 },
223 RuleDef {
224 id: "fallow/unused-dependency-override",
225 category: "Dependencies",
226 name: "Unused pnpm dependency override",
227 short: "pnpm.overrides entry targets a package not declared or resolved",
228 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.",
229 docs_path: "explanations/dead-code#unused-dependency-overrides",
230 },
231 RuleDef {
232 id: "fallow/misconfigured-dependency-override",
233 category: "Dependencies",
234 name: "Misconfigured pnpm dependency override",
235 short: "pnpm.overrides entry has an unparsable key or value",
236 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.",
237 docs_path: "explanations/dead-code#misconfigured-dependency-overrides",
238 },
239];
240
241#[must_use]
243pub fn rule_by_id(id: &str) -> Option<&'static RuleDef> {
244 CHECK_RULES
245 .iter()
246 .chain(HEALTH_RULES.iter())
247 .chain(DUPES_RULES.iter())
248 .find(|r| r.id == id)
249}
250
251#[must_use]
253pub fn rule_docs_url(rule: &RuleDef) -> String {
254 format!("{DOCS_BASE}/{}", rule.docs_path)
255}
256
257pub struct RuleGuide {
262 pub example: &'static str,
263 pub how_to_fix: &'static str,
264}
265
266#[must_use]
271pub fn rule_by_token(token: &str) -> Option<&'static RuleDef> {
272 let trimmed = token.trim();
273 if trimmed.is_empty() {
274 return None;
275 }
276 if let Some(rule) = rule_by_id(trimmed) {
277 return Some(rule);
278 }
279 let normalized = trimmed
280 .strip_prefix("fallow/")
281 .unwrap_or(trimmed)
282 .trim_start_matches("--")
283 .replace('_', "-");
284 let alias = match normalized.as_str() {
285 "unused-files" => Some("fallow/unused-file"),
286 "unused-exports" => Some("fallow/unused-export"),
287 "unused-types" => Some("fallow/unused-type"),
288 "private-type-leaks" => Some("fallow/private-type-leak"),
289 "unused-deps" | "unused-dependencies" => Some("fallow/unused-dependency"),
290 "unused-dev-deps" | "unused-dev-dependencies" => Some("fallow/unused-dev-dependency"),
291 "unused-optional-deps" | "unused-optional-dependencies" => {
292 Some("fallow/unused-optional-dependency")
293 }
294 "type-only-deps" | "type-only-dependencies" => Some("fallow/type-only-dependency"),
295 "test-only-deps" | "test-only-dependencies" => Some("fallow/test-only-dependency"),
296 "unused-enum-members" => Some("fallow/unused-enum-member"),
297 "unused-class-members" => Some("fallow/unused-class-member"),
298 "unresolved-imports" => Some("fallow/unresolved-import"),
299 "unlisted-deps" | "unlisted-dependencies" => Some("fallow/unlisted-dependency"),
300 "duplicate-exports" => Some("fallow/duplicate-export"),
301 "circular-deps" | "circular-dependencies" => Some("fallow/circular-dependency"),
302 "boundary-violations" => Some("fallow/boundary-violation"),
303 "stale-suppressions" => Some("fallow/stale-suppression"),
304 "unused-catalog-entries" | "unused-catalog-entry" | "catalog" => {
305 Some("fallow/unused-catalog-entry")
306 }
307 "empty-catalog-groups" | "empty-catalog-group" | "empty-catalog" => {
308 Some("fallow/empty-catalog-group")
309 }
310 "unresolved-catalog-references" | "unresolved-catalog-reference" | "unresolved-catalog" => {
311 Some("fallow/unresolved-catalog-reference")
312 }
313 "unused-dependency-overrides"
314 | "unused-dependency-override"
315 | "unused-override"
316 | "unused-overrides" => Some("fallow/unused-dependency-override"),
317 "misconfigured-dependency-overrides"
318 | "misconfigured-dependency-override"
319 | "misconfigured-override"
320 | "misconfigured-overrides" => Some("fallow/misconfigured-dependency-override"),
321 "complexity" | "high-complexity" => Some("fallow/high-complexity"),
322 "cyclomatic" | "high-cyclomatic" | "high-cyclomatic-complexity" => {
323 Some("fallow/high-cyclomatic-complexity")
324 }
325 "cognitive" | "high-cognitive" | "high-cognitive-complexity" => {
326 Some("fallow/high-cognitive-complexity")
327 }
328 "crap" | "high-crap" | "high-crap-score" => Some("fallow/high-crap-score"),
329 "duplication" | "dupes" | "code-duplication" => Some("fallow/code-duplication"),
330 _ => None,
331 };
332 if let Some(id) = alias
333 && let Some(rule) = rule_by_id(id)
334 {
335 return Some(rule);
336 }
337 let singular = normalized
338 .strip_suffix('s')
339 .filter(|_| normalized != "unused-class")
340 .unwrap_or(&normalized);
341 let id = format!("fallow/{singular}");
342 rule_by_id(&id).or_else(|| {
343 CHECK_RULES
344 .iter()
345 .chain(HEALTH_RULES.iter())
346 .chain(DUPES_RULES.iter())
347 .find(|rule| {
348 rule.docs_path.ends_with(&normalized)
349 || rule.docs_path.ends_with(singular)
350 || rule.name.eq_ignore_ascii_case(trimmed)
351 })
352 })
353}
354
355#[must_use]
357pub fn rule_guide(rule: &RuleDef) -> RuleGuide {
358 match rule.id {
359 "fallow/unused-file" => RuleGuide {
360 example: "src/old-widget.ts is not imported by any entry point, route, script, or config file.",
361 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.",
362 },
363 "fallow/unused-export" => RuleGuide {
364 example: "export const formatPrice = ... exists in src/money.ts, but no module imports formatPrice.",
365 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.",
366 },
367 "fallow/unused-type" => RuleGuide {
368 example: "export interface LegacyProps is exported, but no module imports the type.",
369 how_to_fix: "Remove the type export, inline it, or keep it behind an explicit API entry point when consumers rely on it.",
370 },
371 "fallow/private-type-leak" => RuleGuide {
372 example: "export function makeUser(): InternalUser exposes InternalUser even though InternalUser is not exported.",
373 how_to_fix: "Export the referenced type, change the public signature to an exported type, or keep the helper private.",
374 },
375 "fallow/unused-dependency"
376 | "fallow/unused-dev-dependency"
377 | "fallow/unused-optional-dependency" => RuleGuide {
378 example: "package.json lists left-pad, but no source, script, config, or plugin-recognized file imports it.",
379 how_to_fix: "Remove the dependency after checking runtime/plugin usage. If another workspace uses it, move the dependency to that workspace.",
380 },
381 "fallow/type-only-dependency" => RuleGuide {
382 example: "zod is in dependencies but only appears in import type declarations.",
383 how_to_fix: "Move the package to devDependencies unless runtime code imports it as a value.",
384 },
385 "fallow/test-only-dependency" => RuleGuide {
386 example: "vitest is listed in dependencies, but only test files import it.",
387 how_to_fix: "Move the package to devDependencies unless production code imports it at runtime.",
388 },
389 "fallow/unused-enum-member" => RuleGuide {
390 example: "Status.Legacy remains in an exported enum, but no code reads that member.",
391 how_to_fix: "Remove the member after checking serialized/API compatibility, or suppress it with a reason when external data still uses it.",
392 },
393 "fallow/unused-class-member" => RuleGuide {
394 example: "class Parser has a public parseLegacy method that is never called in the project.",
395 how_to_fix: "Remove or privatize the member. For reflection/framework lifecycle hooks, configure or suppress the intentional entry point.",
396 },
397 "fallow/unresolved-import" => RuleGuide {
398 example: "src/app.ts imports ./routes/admin, but no matching file exists after extension and index resolution.",
399 how_to_fix: "Fix the specifier, restore the missing file, install the package, or align tsconfig path aliases with the runtime resolver.",
400 },
401 "fallow/unlisted-dependency" => RuleGuide {
402 example: "src/api.ts imports undici, but the nearest package.json does not list undici.",
403 how_to_fix: "Add the package to dependencies/devDependencies in the workspace that imports it instead of relying on hoisting or transitive deps.",
404 },
405 "fallow/duplicate-export" => RuleGuide {
406 example: "Button is exported from both src/ui/button.ts and src/components/button.ts.",
407 how_to_fix: "Rename or consolidate the exports so consumers have one intentional import target.",
408 },
409 "fallow/circular-dependency" => RuleGuide {
410 example: "src/a.ts imports src/b.ts, and src/b.ts imports src/a.ts.",
411 how_to_fix: "Extract shared code to a third module, invert the dependency, or split initialization-time side effects from type-only contracts.",
412 },
413 "fallow/boundary-violation" => RuleGuide {
414 example: "features/billing imports app/admin even though the configured boundary only allows imports from shared and entities.",
415 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.",
416 },
417 "fallow/stale-suppression" => RuleGuide {
418 example: "// fallow-ignore-next-line unused-export remains above an export that is now used.",
419 how_to_fix: "Remove the suppression. If a different issue is still intentional, replace it with a current, specific suppression.",
420 },
421 "fallow/unused-catalog-entry" => RuleGuide {
422 example: "pnpm-workspace.yaml declares `catalog: { is-even: ^1.0.0 }`, but no workspace package.json declares `\"is-even\": \"catalog:\"`.",
423 how_to_fix: "Delete the entry from pnpm-workspace.yaml. If any consumer uses a hardcoded version (surfaced in `hardcoded_consumers`), switch that consumer to `catalog:` first to keep versions aligned.",
424 },
425 "fallow/empty-catalog-group" => RuleGuide {
426 example: "pnpm-workspace.yaml declares `catalogs: { react17: {} }` after the last react17 entry was removed.",
427 how_to_fix: "Delete the empty named group header from pnpm-workspace.yaml. Comments between the deleted header and the next sibling can stay in place for manual review.",
428 },
429 "fallow/unresolved-catalog-reference" => RuleGuide {
430 example: "packages/app/package.json declares `\"old-react\": \"catalog:react17\"`, but `catalogs.react17` in pnpm-workspace.yaml does not declare `old-react`. `pnpm install` will fail.",
431 how_to_fix: "If `available_in_catalogs` is non-empty, change the reference to one of those catalogs (e.g. `catalog:react18`). Otherwise add the package to the named catalog in pnpm-workspace.yaml, or remove the catalog reference and pin a hardcoded version. For staged migrations where the catalog edit lands separately, add the (package, catalog, consumer) triple to `ignoreCatalogReferences` in your fallow config.",
432 },
433 "fallow/unused-dependency-override" => RuleGuide {
434 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.",
435 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.",
436 },
437 "fallow/misconfigured-dependency-override" => RuleGuide {
438 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.",
439 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.",
440 },
441 "fallow/high-cyclomatic-complexity"
442 | "fallow/high-cognitive-complexity"
443 | "fallow/high-complexity" => RuleGuide {
444 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.",
445 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`.",
446 },
447 "fallow/high-crap-score" => RuleGuide {
448 example: "A complex function has little or no matching Istanbul coverage, so its CRAP score crosses the configured gate.",
449 how_to_fix: "Add focused tests for the risky branches first, then simplify the function if the score remains high.",
450 },
451 "fallow/refactoring-target" => RuleGuide {
452 example: "A file combines high complexity density, churn, fan-in, and dead-code signals.",
453 how_to_fix: "Start with the listed evidence: remove dead exports, extract complex functions, then reduce fan-out or cycles in small steps.",
454 },
455 "fallow/untested-file" | "fallow/untested-export" => RuleGuide {
456 example: "Production-reachable code has no dependency path from discovered test entry points.",
457 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.",
458 },
459 "fallow/runtime-safe-to-delete"
460 | "fallow/runtime-review-required"
461 | "fallow/runtime-low-traffic"
462 | "fallow/runtime-coverage-unavailable"
463 | "fallow/runtime-coverage" => RuleGuide {
464 example: "Runtime coverage shows a function was never called, barely called, or could not be matched during the capture window.",
465 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.",
466 },
467 "fallow/code-duplication" => RuleGuide {
468 example: "Two files contain the same normalized token sequence across a multi-line block.",
469 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.",
470 },
471 _ => RuleGuide {
472 example: "Run the relevant command with --format json --quiet --explain to inspect this rule in context.",
473 how_to_fix: "Use the issue action hints, source location, and docs URL to decide whether to remove, move, configure, or suppress the finding.",
474 },
475 }
476}
477
478#[must_use]
480pub fn run_explain(issue_type: &str, output: OutputFormat) -> ExitCode {
481 let Some(rule) = rule_by_token(issue_type) else {
482 return crate::error::emit_error(
483 &format!(
484 "unknown issue type '{issue_type}'. Try values like unused-export, unused-dependency, high-complexity, or code-duplication"
485 ),
486 2,
487 output,
488 );
489 };
490 let guide = rule_guide(rule);
491 match output {
492 OutputFormat::Json => {
493 let envelope = crate::output_envelope::ExplainOutput {
494 id: rule.id.to_string(),
495 name: rule.name.to_string(),
496 summary: rule.short.to_string(),
497 rationale: rule.full.to_string(),
498 example: guide.example.to_string(),
499 how_to_fix: guide.how_to_fix.to_string(),
500 docs: rule_docs_url(rule),
501 };
502 match serde_json::to_value(&envelope) {
503 Ok(value) => crate::report::emit_json(&value, "explain"),
504 Err(e) => {
505 crate::error::emit_error(&format!("JSON serialization error: {e}"), 2, output)
506 }
507 }
508 }
509 OutputFormat::Human => print_explain_human(rule, &guide),
510 OutputFormat::Compact => print_explain_compact(rule),
511 OutputFormat::Markdown => print_explain_markdown(rule, &guide),
512 OutputFormat::Sarif
513 | OutputFormat::CodeClimate
514 | OutputFormat::PrCommentGithub
515 | OutputFormat::PrCommentGitlab
516 | OutputFormat::ReviewGithub
517 | OutputFormat::ReviewGitlab
518 | OutputFormat::Badge => crate::error::emit_error(
519 "explain supports human, compact, markdown, and json output",
520 2,
521 output,
522 ),
523 }
524}
525
526fn print_explain_human(rule: &RuleDef, guide: &RuleGuide) -> ExitCode {
527 println!("{}", rule.name.bold());
528 println!("{}", rule.id.dimmed());
529 println!();
530 println!("{}", rule.short);
531 println!();
532 println!("{}", "Why it matters".bold());
533 println!("{}", rule.full);
534 println!();
535 println!("{}", "Example".bold());
536 println!("{}", guide.example);
537 println!();
538 println!("{}", "How to fix".bold());
539 println!("{}", guide.how_to_fix);
540 println!();
541 println!("{} {}", "Docs:".dimmed(), rule_docs_url(rule).dimmed());
542 ExitCode::SUCCESS
543}
544
545fn print_explain_compact(rule: &RuleDef) -> ExitCode {
546 println!("explain:{}:{}:{}", rule.id, rule.short, rule_docs_url(rule));
547 ExitCode::SUCCESS
548}
549
550fn print_explain_markdown(rule: &RuleDef, guide: &RuleGuide) -> ExitCode {
551 println!("# {}", rule.name);
552 println!();
553 println!("`{}`", rule.id);
554 println!();
555 println!("{}", rule.short);
556 println!();
557 println!("## Why it matters");
558 println!();
559 println!("{}", rule.full);
560 println!();
561 println!("## Example");
562 println!();
563 println!("{}", guide.example);
564 println!();
565 println!("## How to fix");
566 println!();
567 println!("{}", guide.how_to_fix);
568 println!();
569 println!("[Docs]({})", rule_docs_url(rule));
570 ExitCode::SUCCESS
571}
572
573pub const HEALTH_RULES: &[RuleDef] = &[
576 RuleDef {
577 id: "fallow/high-cyclomatic-complexity",
578 category: "Health",
579 name: "High Cyclomatic Complexity",
580 short: "Function has high cyclomatic complexity",
581 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`.",
582 docs_path: "explanations/health#cyclomatic-complexity",
583 },
584 RuleDef {
585 id: "fallow/high-cognitive-complexity",
586 category: "Health",
587 name: "High Cognitive Complexity",
588 short: "Function has high cognitive complexity",
589 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`.",
590 docs_path: "explanations/health#cognitive-complexity",
591 },
592 RuleDef {
593 id: "fallow/high-complexity",
594 category: "Health",
595 name: "High Complexity (Both)",
596 short: "Function exceeds both complexity thresholds",
597 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`.",
598 docs_path: "explanations/health#complexity-metrics",
599 },
600 RuleDef {
601 id: "fallow/high-crap-score",
602 category: "Health",
603 name: "High CRAP Score",
604 short: "Function has a high CRAP score (complexity combined with low coverage)",
605 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.",
606 docs_path: "explanations/health#crap-score",
607 },
608 RuleDef {
609 id: "fallow/refactoring-target",
610 category: "Health",
611 name: "Refactoring Target",
612 short: "File identified as a high-priority refactoring candidate",
613 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.",
614 docs_path: "explanations/health#refactoring-targets",
615 },
616 RuleDef {
617 id: "fallow/untested-file",
618 category: "Health",
619 name: "Untested File",
620 short: "Runtime-reachable file has no test dependency path",
621 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.",
622 docs_path: "explanations/health#coverage-gaps",
623 },
624 RuleDef {
625 id: "fallow/untested-export",
626 category: "Health",
627 name: "Untested Export",
628 short: "Runtime-reachable export has no test dependency path",
629 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.",
630 docs_path: "explanations/health#coverage-gaps",
631 },
632 RuleDef {
633 id: "fallow/runtime-safe-to-delete",
634 category: "Health",
635 name: "Production Safe To Delete",
636 short: "Statically unused AND never invoked in production with V8 tracking",
637 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.",
638 docs_path: "explanations/health#runtime-coverage",
639 },
640 RuleDef {
641 id: "fallow/runtime-review-required",
642 category: "Health",
643 name: "Production Review Required",
644 short: "Statically used but never invoked in production",
645 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.",
646 docs_path: "explanations/health#runtime-coverage",
647 },
648 RuleDef {
649 id: "fallow/runtime-low-traffic",
650 category: "Health",
651 name: "Production Low Traffic",
652 short: "Function was invoked below the low-traffic threshold",
653 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.",
654 docs_path: "explanations/health#runtime-coverage",
655 },
656 RuleDef {
657 id: "fallow/runtime-coverage-unavailable",
658 category: "Health",
659 name: "Runtime Coverage Unavailable",
660 short: "Runtime coverage could not be resolved for this function",
661 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.",
662 docs_path: "explanations/health#runtime-coverage",
663 },
664 RuleDef {
665 id: "fallow/runtime-coverage",
666 category: "Health",
667 name: "Runtime Coverage",
668 short: "Runtime coverage finding",
669 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.",
670 docs_path: "explanations/health#runtime-coverage",
671 },
672];
673
674pub const DUPES_RULES: &[RuleDef] = &[RuleDef {
675 id: "fallow/code-duplication",
676 category: "Duplication",
677 name: "Code Duplication",
678 short: "Duplicated code block",
679 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.",
680 docs_path: "explanations/duplication#clone-groups",
681}];
682
683#[must_use]
687pub fn check_meta() -> Value {
688 let rules: Value = CHECK_RULES
689 .iter()
690 .map(|r| {
691 (
692 r.id.replace("fallow/", ""),
693 json!({
694 "name": r.name,
695 "description": r.full,
696 "docs": rule_docs_url(r)
697 }),
698 )
699 })
700 .collect::<serde_json::Map<String, Value>>()
701 .into();
702
703 json!({
704 "docs": CHECK_DOCS,
705 "rules": rules,
706 "field_definitions": {
707 "actions[]": ACTIONS_FIELD_DEFINITION,
708 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
709 }
710 })
711}
712
713#[must_use]
715#[expect(
716 clippy::too_many_lines,
717 reason = "flat metric table: every entry is 3-4 short lines of metadata and keeping them in one map is clearer than splitting into per-metric helpers"
718)]
719pub fn health_meta() -> Value {
720 json!({
721 "docs": HEALTH_DOCS,
722 "field_definitions": {
723 "actions[]": ACTIONS_FIELD_DEFINITION,
724 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
725 },
726 "metrics": {
727 "cyclomatic": {
728 "name": "Cyclomatic Complexity",
729 "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.",
730 "range": "[1, \u{221e})",
731 "interpretation": "lower is better; default threshold: 20"
732 },
733 "cognitive": {
734 "name": "Cognitive Complexity",
735 "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.",
736 "range": "[0, \u{221e})",
737 "interpretation": "lower is better; default threshold: 15"
738 },
739 "line_count": {
740 "name": "Function Line Count",
741 "description": "Number of lines in the function body.",
742 "range": "[1, \u{221e})",
743 "interpretation": "context-dependent; long functions may need splitting"
744 },
745 "lines": {
746 "name": "File Line Count",
747 "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.",
748 "range": "[1, \u{221e})",
749 "interpretation": "context-dependent; large files may benefit from splitting even if individual functions are small"
750 },
751 "maintainability_index": {
752 "name": "Maintainability Index",
753 "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.",
754 "range": "[0, 100]",
755 "interpretation": "higher is better; <40 poor, 40\u{2013}70 moderate, >70 good"
756 },
757 "complexity_density": {
758 "name": "Complexity Density",
759 "description": "Total cyclomatic complexity divided by lines of code. Measures how densely complex the code is per line.",
760 "range": "[0, \u{221e})",
761 "interpretation": "lower is better; >1.0 indicates very dense complexity"
762 },
763 "dead_code_ratio": {
764 "name": "Dead Code Ratio",
765 "description": "Fraction of value exports (excluding type-only exports like interfaces and type aliases) with zero references across the project.",
766 "range": "[0, 1]",
767 "interpretation": "lower is better; 0 = all exports are used"
768 },
769 "fan_in": {
770 "name": "Fan-in (Importers)",
771 "description": "Number of files that import this file. High fan-in means high blast radius \u{2014} changes to this file affect many dependents.",
772 "range": "[0, \u{221e})",
773 "interpretation": "context-dependent; high fan-in files need careful review before changes"
774 },
775 "fan_out": {
776 "name": "Fan-out (Imports)",
777 "description": "Number of files this file directly imports. High fan-out indicates high coupling and change propagation risk.",
778 "range": "[0, \u{221e})",
779 "interpretation": "lower is better; MI penalty caps at ~40 imports"
780 },
781 "score": {
782 "name": "Hotspot Score",
783 "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.",
784 "range": "[0, 100]",
785 "interpretation": "higher = riskier; prioritize refactoring high-score files"
786 },
787 "weighted_commits": {
788 "name": "Weighted Commits",
789 "description": "Recency-weighted commit count using exponential decay with 90-day half-life. Recent commits contribute more than older ones.",
790 "range": "[0, \u{221e})",
791 "interpretation": "higher = more recent churn activity"
792 },
793 "trend": {
794 "name": "Churn Trend",
795 "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.",
796 "values": ["accelerating", "stable", "cooling"],
797 "interpretation": "accelerating files need attention; cooling files are stabilizing"
798 },
799 "priority": {
800 "name": "Refactoring Priority",
801 "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.",
802 "range": "[0, 100]",
803 "interpretation": "higher = more urgent to refactor"
804 },
805 "efficiency": {
806 "name": "Efficiency Score",
807 "description": "priority / effort_numeric (Low=1, Medium=2, High=3). Surfaces quick wins: high-priority, low-effort targets rank first. Default sort order.",
808 "range": "[0, 100] \u{2014} effective max depends on effort: Low=100, Medium=50, High\u{2248}33",
809 "interpretation": "higher = better quick-win value; targets are sorted by efficiency descending"
810 },
811 "effort": {
812 "name": "Effort Estimate",
813 "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.",
814 "values": ["low", "medium", "high"],
815 "interpretation": "low = quick win, high = needs planning and coordination"
816 },
817 "confidence": {
818 "name": "Confidence Level",
819 "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).",
820 "values": ["high", "medium", "low"],
821 "interpretation": "high = act on it, medium = verify context, low = treat as a signal, not a directive"
822 },
823 "health_score": {
824 "name": "Health Score",
825 "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.",
826 "range": "[0, 100]",
827 "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)"
828 },
829 "crap_max": {
830 "name": "Untested Complexity Risk (CRAP)",
831 "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.",
832 "range": "[1, \u{221e})",
833 "interpretation": "lower is better; >=30 is high-risk (CC >= 5 without test path)"
834 },
835 "bus_factor": {
836 "name": "Bus Factor",
837 "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.",
838 "range": "[1, \u{221e})",
839 "interpretation": "lower is higher knowledge-loss risk; 1 means a single contributor covers most of the recent history"
840 },
841 "contributor_count": {
842 "name": "Contributor Count",
843 "description": "Number of distinct authors who touched this file in the analysis window after bot-pattern filtering.",
844 "range": "[0, \u{221e})",
845 "interpretation": "higher generally indicates broader knowledge spread; pair with bus_factor for context"
846 },
847 "share": {
848 "name": "Contributor Share",
849 "description": "Recency-weighted share of total weighted commits attributed to a single contributor. Rounded to three decimals.",
850 "range": "[0, 1]",
851 "interpretation": "share close to 1.0 indicates dominance and pairs with low bus_factor"
852 },
853 "stale_days": {
854 "name": "Stale Days",
855 "description": "Days since this contributor last touched the file. Computed at analysis time.",
856 "range": "[0, \u{221e})",
857 "interpretation": "high stale_days on the top contributor often correlates with ownership drift"
858 },
859 "drift": {
860 "name": "Ownership Drift",
861 "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%.",
862 "values": [true, false],
863 "interpretation": "true means the original author is no longer maintaining; route reviews to the current top contributor"
864 },
865 "unowned": {
866 "name": "Unowned (Tristate)",
867 "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).",
868 "values": [true, false, null],
869 "interpretation": "true on a hotspot is a review-bottleneck risk; null means the signal is unavailable, not absent"
870 },
871 "runtime_coverage_verdict": {
872 "name": "Runtime Coverage Verdict",
873 "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).",
874 "values": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
875 "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."
876 },
877 "runtime_coverage_state": {
878 "name": "Runtime Coverage State",
879 "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.",
880 "values": ["called", "never-called", "coverage-unavailable", "unknown"],
881 "interpretation": "`never-called` in combination with static `unused` is the highest-confidence delete signal"
882 },
883 "runtime_coverage_confidence": {
884 "name": "Runtime Coverage Confidence",
885 "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.",
886 "values": ["high", "medium", "low", "unknown"],
887 "interpretation": "high = act on it; medium = verify context; low = treat as a signal only"
888 },
889 "production_invocations": {
890 "name": "Production Invocations",
891 "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.",
892 "range": "[0, \u{221e})",
893 "interpretation": "0 + tracked = cold path; 0 + untracked = unknown; high + never-called cannot occur by definition"
894 },
895 "percent_dead_in_production": {
896 "name": "Percent Dead in Production",
897 "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.",
898 "range": "[0, 100]",
899 "interpretation": "lower is better; values above ~10% on a long-running service indicate a large cleanup opportunity"
900 }
901 }
902 })
903}
904
905#[must_use]
907pub fn dupes_meta() -> Value {
908 json!({
909 "docs": DUPES_DOCS,
910 "field_definitions": {
911 "actions[]": ACTIONS_FIELD_DEFINITION,
912 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
913 },
914 "metrics": {
915 "duplication_percentage": {
916 "name": "Duplication Percentage",
917 "description": "Fraction of total source tokens that appear in at least one clone group. Computed over the full analyzed file set.",
918 "range": "[0, 100]",
919 "interpretation": "lower is better"
920 },
921 "token_count": {
922 "name": "Token Count",
923 "description": "Number of normalized source tokens in the clone group. Tokens are language-aware (keywords, identifiers, operators, punctuation). Higher token count = larger duplicate.",
924 "range": "[1, \u{221e})",
925 "interpretation": "larger clones have higher refactoring value"
926 },
927 "line_count": {
928 "name": "Line Count",
929 "description": "Number of source lines spanned by the clone instance. Approximation of clone size for human readability.",
930 "range": "[1, \u{221e})",
931 "interpretation": "larger clones are more impactful to deduplicate"
932 },
933 "clone_groups": {
934 "name": "Clone Groups",
935 "description": "A set of code fragments with identical or near-identical normalized token sequences. Each group has 2+ instances across different locations.",
936 "interpretation": "each group is a single refactoring opportunity"
937 },
938 "clone_groups_below_min_occurrences": {
939 "name": "Clone Groups Below minOccurrences",
940 "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`.",
941 "range": "[0, \u{221e})",
942 "interpretation": "high values suggest noisy pair-only duplication; lower `minOccurrences` to inspect"
943 },
944 "clone_families": {
945 "name": "Clone Families",
946 "description": "Groups of clone groups that share the same set of files. Indicates systematic duplication patterns (e.g., mirrored directory structures).",
947 "interpretation": "families suggest extract-module refactoring opportunities"
948 }
949 }
950 })
951}
952
953#[must_use]
955pub fn coverage_setup_meta() -> Value {
956 json!({
957 "docs_url": COVERAGE_SETUP_DOCS,
958 "field_definitions": {
959 "schema_version": "Coverage setup JSON contract version. Stays at \"1\" for additive opt-in fields such as _meta.",
960 "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.",
961 "package_manager": "Detected package manager used for install and run commands, or null when no package manager signal was found.",
962 "runtime_targets": "Union of runtime targets across emitted members.",
963 "members[]": "Per-runtime-workspace setup recipes. Pure aggregator roots and build-only libraries are omitted.",
964 "members[].name": "Workspace package name from package.json, or the root directory name when package.json has no name.",
965 "members[].path": "Workspace path relative to the command root. The root package is represented as \".\".",
966 "members[].framework_detected": "Runtime framework detected for that member.",
967 "members[].package_manager": "Package manager detected for that member, or inherited from the workspace root when no member-specific signal exists.",
968 "members[].runtime_targets": "Runtime targets produced by that member.",
969 "members[].files_to_edit": "Files in that member that should receive runtime beacon setup code.",
970 "members[].snippets": "Copy-paste setup snippets for that member, with paths relative to the command root.",
971 "members[].dockerfile_snippet": "Environment snippet for file-system capture in that member's containerized Node runtime, or null when not applicable.",
972 "members[].warnings": "Actionable setup caveats discovered for that member.",
973 "config_written": "Always null for --json because JSON setup is side-effect-free and never writes configuration.",
974 "files_to_edit": "Compatibility copy of the primary member's files, with workspace prefixes when the primary member is not the root.",
975 "snippets": "Compatibility copy of the primary member's snippets, with workspace prefixes when the primary member is not the root.",
976 "dockerfile_snippet": "Environment snippet for file-system capture in containerized Node runtimes, or null when not applicable.",
977 "commands": "Package-manager commands needed to install the runtime beacon and sidecar packages.",
978 "next_steps": "Ordered setup workflow after applying the emitted snippets.",
979 "warnings": "Actionable setup caveats discovered while building the recipe."
980 },
981 "enums": {
982 "framework_detected": ["nextjs", "nestjs", "nuxt", "sveltekit", "astro", "remix", "vite", "plain_node", "unknown"],
983 "runtime_targets": ["node", "browser"],
984 "package_manager": ["npm", "pnpm", "yarn", "bun", null]
985 },
986 "warnings": {
987 "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.",
988 "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.",
989 "Package manager was not detected": "No packageManager field or known lockfile was found. Commands fall back to npm.",
990 "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."
991 }
992 })
993}
994
995#[must_use]
997pub fn coverage_analyze_meta() -> Value {
998 json!({
999 "docs_url": COVERAGE_ANALYZE_DOCS,
1000 "field_definitions": {
1001 "schema_version": "Standalone coverage analyze envelope version. \"1\" for the current shape.",
1002 "version": "fallow CLI version that produced this output.",
1003 "elapsed_ms": "Wall-clock milliseconds spent producing the report.",
1004 "runtime_coverage": "Same RuntimeCoverageReport block emitted by `fallow health --runtime-coverage`.",
1005 "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.",
1006 "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.",
1007 "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.",
1008 "runtime_coverage.findings[].evidence.static_status": "used = the function is reachable in the AST module graph; unused = it is dead by static analysis.",
1009 "runtime_coverage.findings[].evidence.test_coverage": "covered = the local test suite hits the function; not_covered otherwise.",
1010 "runtime_coverage.findings[].evidence.v8_tracking": "tracked = V8 observed the function during the capture window; untracked otherwise.",
1011 "runtime_coverage.findings[].actions[].type": "Suggested follow-up identifier. delete-cold-code is emitted on safe_to_delete; review-runtime on review_required.",
1012 "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.",
1013 "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.",
1014 "runtime_coverage.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally."
1015 },
1016 "enums": {
1017 "data_source": ["local", "cloud"],
1018 "report_verdict": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
1019 "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
1020 "static_status": ["used", "unused"],
1021 "test_coverage": ["covered", "not_covered"],
1022 "v8_tracking": ["tracked", "untracked"],
1023 "action_type": ["delete-cold-code", "review-runtime"]
1024 },
1025 "warnings": {
1026 "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
1027 "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."
1028 }
1029 })
1030}
1031
1032#[cfg(test)]
1033mod tests {
1034 use super::*;
1035
1036 #[test]
1039 fn rule_by_id_finds_check_rule() {
1040 let rule = rule_by_id("fallow/unused-file").unwrap();
1041 assert_eq!(rule.name, "Unused Files");
1042 }
1043
1044 #[test]
1045 fn rule_by_id_finds_health_rule() {
1046 let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1047 assert_eq!(rule.name, "High Cyclomatic Complexity");
1048 }
1049
1050 #[test]
1051 fn rule_by_id_finds_dupes_rule() {
1052 let rule = rule_by_id("fallow/code-duplication").unwrap();
1053 assert_eq!(rule.name, "Code Duplication");
1054 }
1055
1056 #[test]
1057 fn rule_by_id_returns_none_for_unknown() {
1058 assert!(rule_by_id("fallow/nonexistent").is_none());
1059 assert!(rule_by_id("").is_none());
1060 }
1061
1062 #[test]
1065 fn rule_docs_url_format() {
1066 let rule = rule_by_id("fallow/unused-export").unwrap();
1067 let url = rule_docs_url(rule);
1068 assert!(url.starts_with("https://docs.fallow.tools/"));
1069 assert!(url.contains("unused-exports"));
1070 }
1071
1072 #[test]
1075 fn check_rules_all_have_fallow_prefix() {
1076 for rule in CHECK_RULES {
1077 assert!(
1078 rule.id.starts_with("fallow/"),
1079 "rule {} should start with fallow/",
1080 rule.id
1081 );
1082 }
1083 }
1084
1085 #[test]
1086 fn check_rules_all_have_docs_path() {
1087 for rule in CHECK_RULES {
1088 assert!(
1089 !rule.docs_path.is_empty(),
1090 "rule {} should have a docs_path",
1091 rule.id
1092 );
1093 }
1094 }
1095
1096 #[test]
1097 fn check_rules_no_duplicate_ids() {
1098 let mut seen = rustc_hash::FxHashSet::default();
1099 for rule in CHECK_RULES.iter().chain(HEALTH_RULES).chain(DUPES_RULES) {
1100 assert!(seen.insert(rule.id), "duplicate rule id: {}", rule.id);
1101 }
1102 }
1103
1104 #[test]
1107 fn check_meta_has_docs_and_rules() {
1108 let meta = check_meta();
1109 assert!(meta.get("docs").is_some());
1110 assert!(meta.get("rules").is_some());
1111 let rules = meta["rules"].as_object().unwrap();
1112 assert_eq!(rules.len(), CHECK_RULES.len());
1114 assert!(rules.contains_key("unused-file"));
1115 assert!(rules.contains_key("unused-export"));
1116 assert!(rules.contains_key("unused-type"));
1117 assert!(rules.contains_key("unused-dependency"));
1118 assert!(rules.contains_key("unused-dev-dependency"));
1119 assert!(rules.contains_key("unused-optional-dependency"));
1120 assert!(rules.contains_key("unused-enum-member"));
1121 assert!(rules.contains_key("unused-class-member"));
1122 assert!(rules.contains_key("unresolved-import"));
1123 assert!(rules.contains_key("unlisted-dependency"));
1124 assert!(rules.contains_key("duplicate-export"));
1125 assert!(rules.contains_key("type-only-dependency"));
1126 assert!(rules.contains_key("circular-dependency"));
1127 }
1128
1129 #[test]
1130 fn check_meta_documents_per_finding_auto_fixable() {
1131 let meta = check_meta();
1132 let defs = meta["field_definitions"].as_object().unwrap();
1133 let note = defs["actions[].auto_fixable"].as_str().unwrap();
1134 assert!(
1135 note.contains("PER FINDING"),
1136 "auto_fixable note must call out per-finding evaluation"
1137 );
1138 assert!(
1139 note.contains("remove-catalog-entry"),
1140 "auto_fixable note must cite remove-catalog-entry per-instance flip"
1141 );
1142 assert!(
1143 note.contains("used_in_workspaces"),
1144 "auto_fixable note must cite the dependency-action per-instance flip"
1145 );
1146 assert!(
1147 note.contains("ignoreExports"),
1148 "auto_fixable note must cite the duplicate-exports config-fixable flip"
1149 );
1150 assert!(defs.contains_key("actions[]"));
1151 }
1152
1153 #[test]
1154 fn health_and_dupes_meta_share_actions_field_definitions() {
1155 for meta in [health_meta(), dupes_meta()] {
1156 let defs = meta["field_definitions"].as_object().unwrap();
1157 assert_eq!(
1158 defs["actions[]"].as_str().unwrap(),
1159 ACTIONS_FIELD_DEFINITION,
1160 );
1161 assert_eq!(
1162 defs["actions[].auto_fixable"].as_str().unwrap(),
1163 ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION,
1164 );
1165 }
1166 }
1167
1168 #[test]
1169 fn check_meta_rule_has_required_fields() {
1170 let meta = check_meta();
1171 let rules = meta["rules"].as_object().unwrap();
1172 for (key, value) in rules {
1173 assert!(value.get("name").is_some(), "rule {key} missing 'name'");
1174 assert!(
1175 value.get("description").is_some(),
1176 "rule {key} missing 'description'"
1177 );
1178 assert!(value.get("docs").is_some(), "rule {key} missing 'docs'");
1179 }
1180 }
1181
1182 #[test]
1185 fn health_meta_has_metrics() {
1186 let meta = health_meta();
1187 assert!(meta.get("docs").is_some());
1188 let metrics = meta["metrics"].as_object().unwrap();
1189 assert!(metrics.contains_key("cyclomatic"));
1190 assert!(metrics.contains_key("cognitive"));
1191 assert!(metrics.contains_key("maintainability_index"));
1192 assert!(metrics.contains_key("complexity_density"));
1193 assert!(metrics.contains_key("fan_in"));
1194 assert!(metrics.contains_key("fan_out"));
1195 }
1196
1197 #[test]
1200 fn dupes_meta_has_metrics() {
1201 let meta = dupes_meta();
1202 assert!(meta.get("docs").is_some());
1203 let metrics = meta["metrics"].as_object().unwrap();
1204 assert!(metrics.contains_key("duplication_percentage"));
1205 assert!(metrics.contains_key("token_count"));
1206 assert!(metrics.contains_key("clone_groups"));
1207 assert!(metrics.contains_key("clone_families"));
1208 }
1209
1210 #[test]
1213 fn coverage_setup_meta_has_docs_fields_enums_and_warnings() {
1214 let meta = coverage_setup_meta();
1215 assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
1216 assert!(
1217 meta["field_definitions"]
1218 .as_object()
1219 .unwrap()
1220 .contains_key("members[]")
1221 );
1222 assert!(
1223 meta["field_definitions"]
1224 .as_object()
1225 .unwrap()
1226 .contains_key("config_written")
1227 );
1228 assert!(
1229 meta["field_definitions"]
1230 .as_object()
1231 .unwrap()
1232 .contains_key("members[].package_manager")
1233 );
1234 assert!(
1235 meta["field_definitions"]
1236 .as_object()
1237 .unwrap()
1238 .contains_key("members[].warnings")
1239 );
1240 assert!(
1241 meta["enums"]
1242 .as_object()
1243 .unwrap()
1244 .contains_key("framework_detected")
1245 );
1246 assert!(
1247 meta["warnings"]
1248 .as_object()
1249 .unwrap()
1250 .contains_key("No runtime workspace members were detected")
1251 );
1252 assert!(
1253 meta["warnings"]
1254 .as_object()
1255 .unwrap()
1256 .contains_key("Package manager was not detected")
1257 );
1258 }
1259
1260 #[test]
1263 fn coverage_analyze_meta_documents_data_source_and_action_vocabulary() {
1264 let meta = coverage_analyze_meta();
1265 assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
1266 let fields = meta["field_definitions"].as_object().unwrap();
1267 assert!(fields.contains_key("runtime_coverage.summary.data_source"));
1268 assert!(fields.contains_key("runtime_coverage.summary.last_received_at"));
1269 assert!(fields.contains_key("runtime_coverage.findings[].evidence.test_coverage"));
1270 assert!(fields.contains_key("runtime_coverage.findings[].actions[].type"));
1271 let enums = meta["enums"].as_object().unwrap();
1272 assert_eq!(enums["data_source"], json!(["local", "cloud"]));
1273 assert_eq!(enums["test_coverage"], json!(["covered", "not_covered"]));
1274 assert_eq!(enums["v8_tracking"], json!(["tracked", "untracked"]));
1275 assert_eq!(
1276 enums["action_type"],
1277 json!(["delete-cold-code", "review-runtime"])
1278 );
1279 let warnings = meta["warnings"].as_object().unwrap();
1280 assert!(warnings.contains_key("cloud_functions_unmatched"));
1281 }
1282
1283 #[test]
1286 fn health_rules_all_have_fallow_prefix() {
1287 for rule in HEALTH_RULES {
1288 assert!(
1289 rule.id.starts_with("fallow/"),
1290 "health rule {} should start with fallow/",
1291 rule.id
1292 );
1293 }
1294 }
1295
1296 #[test]
1297 fn health_rules_all_have_docs_path() {
1298 for rule in HEALTH_RULES {
1299 assert!(
1300 !rule.docs_path.is_empty(),
1301 "health rule {} should have a docs_path",
1302 rule.id
1303 );
1304 }
1305 }
1306
1307 #[test]
1308 fn health_rules_all_have_non_empty_fields() {
1309 for rule in HEALTH_RULES {
1310 assert!(
1311 !rule.name.is_empty(),
1312 "health rule {} missing name",
1313 rule.id
1314 );
1315 assert!(
1316 !rule.short.is_empty(),
1317 "health rule {} missing short description",
1318 rule.id
1319 );
1320 assert!(
1321 !rule.full.is_empty(),
1322 "health rule {} missing full description",
1323 rule.id
1324 );
1325 }
1326 }
1327
1328 #[test]
1331 fn dupes_rules_all_have_fallow_prefix() {
1332 for rule in DUPES_RULES {
1333 assert!(
1334 rule.id.starts_with("fallow/"),
1335 "dupes rule {} should start with fallow/",
1336 rule.id
1337 );
1338 }
1339 }
1340
1341 #[test]
1342 fn dupes_rules_all_have_docs_path() {
1343 for rule in DUPES_RULES {
1344 assert!(
1345 !rule.docs_path.is_empty(),
1346 "dupes rule {} should have a docs_path",
1347 rule.id
1348 );
1349 }
1350 }
1351
1352 #[test]
1353 fn dupes_rules_all_have_non_empty_fields() {
1354 for rule in DUPES_RULES {
1355 assert!(!rule.name.is_empty(), "dupes rule {} missing name", rule.id);
1356 assert!(
1357 !rule.short.is_empty(),
1358 "dupes rule {} missing short description",
1359 rule.id
1360 );
1361 assert!(
1362 !rule.full.is_empty(),
1363 "dupes rule {} missing full description",
1364 rule.id
1365 );
1366 }
1367 }
1368
1369 #[test]
1372 fn check_rules_all_have_non_empty_fields() {
1373 for rule in CHECK_RULES {
1374 assert!(!rule.name.is_empty(), "check rule {} missing name", rule.id);
1375 assert!(
1376 !rule.short.is_empty(),
1377 "check rule {} missing short description",
1378 rule.id
1379 );
1380 assert!(
1381 !rule.full.is_empty(),
1382 "check rule {} missing full description",
1383 rule.id
1384 );
1385 }
1386 }
1387
1388 #[test]
1391 fn rule_docs_url_health_rule() {
1392 let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1393 let url = rule_docs_url(rule);
1394 assert!(url.starts_with("https://docs.fallow.tools/"));
1395 assert!(url.contains("health"));
1396 }
1397
1398 #[test]
1399 fn rule_docs_url_dupes_rule() {
1400 let rule = rule_by_id("fallow/code-duplication").unwrap();
1401 let url = rule_docs_url(rule);
1402 assert!(url.starts_with("https://docs.fallow.tools/"));
1403 assert!(url.contains("duplication"));
1404 }
1405
1406 #[test]
1409 fn health_meta_all_metrics_have_name_and_description() {
1410 let meta = health_meta();
1411 let metrics = meta["metrics"].as_object().unwrap();
1412 for (key, value) in metrics {
1413 assert!(
1414 value.get("name").is_some(),
1415 "health metric {key} missing 'name'"
1416 );
1417 assert!(
1418 value.get("description").is_some(),
1419 "health metric {key} missing 'description'"
1420 );
1421 assert!(
1422 value.get("interpretation").is_some(),
1423 "health metric {key} missing 'interpretation'"
1424 );
1425 }
1426 }
1427
1428 #[test]
1429 fn health_meta_has_all_expected_metrics() {
1430 let meta = health_meta();
1431 let metrics = meta["metrics"].as_object().unwrap();
1432 let expected = [
1433 "cyclomatic",
1434 "cognitive",
1435 "line_count",
1436 "lines",
1437 "maintainability_index",
1438 "complexity_density",
1439 "dead_code_ratio",
1440 "fan_in",
1441 "fan_out",
1442 "score",
1443 "weighted_commits",
1444 "trend",
1445 "priority",
1446 "efficiency",
1447 "effort",
1448 "confidence",
1449 "bus_factor",
1450 "contributor_count",
1451 "share",
1452 "stale_days",
1453 "drift",
1454 "unowned",
1455 "runtime_coverage_verdict",
1456 "runtime_coverage_state",
1457 "runtime_coverage_confidence",
1458 "production_invocations",
1459 "percent_dead_in_production",
1460 ];
1461 for key in &expected {
1462 assert!(
1463 metrics.contains_key(*key),
1464 "health_meta missing expected metric: {key}"
1465 );
1466 }
1467 }
1468
1469 #[test]
1472 fn dupes_meta_all_metrics_have_name_and_description() {
1473 let meta = dupes_meta();
1474 let metrics = meta["metrics"].as_object().unwrap();
1475 for (key, value) in metrics {
1476 assert!(
1477 value.get("name").is_some(),
1478 "dupes metric {key} missing 'name'"
1479 );
1480 assert!(
1481 value.get("description").is_some(),
1482 "dupes metric {key} missing 'description'"
1483 );
1484 }
1485 }
1486
1487 #[test]
1488 fn dupes_meta_has_line_count() {
1489 let meta = dupes_meta();
1490 let metrics = meta["metrics"].as_object().unwrap();
1491 assert!(metrics.contains_key("line_count"));
1492 }
1493
1494 #[test]
1497 fn check_docs_url_valid() {
1498 assert!(CHECK_DOCS.starts_with("https://"));
1499 assert!(CHECK_DOCS.contains("dead-code"));
1500 }
1501
1502 #[test]
1503 fn health_docs_url_valid() {
1504 assert!(HEALTH_DOCS.starts_with("https://"));
1505 assert!(HEALTH_DOCS.contains("health"));
1506 }
1507
1508 #[test]
1509 fn dupes_docs_url_valid() {
1510 assert!(DUPES_DOCS.starts_with("https://"));
1511 assert!(DUPES_DOCS.contains("dupes"));
1512 }
1513
1514 #[test]
1517 fn check_meta_docs_url_matches_constant() {
1518 let meta = check_meta();
1519 assert_eq!(meta["docs"].as_str().unwrap(), CHECK_DOCS);
1520 }
1521
1522 #[test]
1523 fn health_meta_docs_url_matches_constant() {
1524 let meta = health_meta();
1525 assert_eq!(meta["docs"].as_str().unwrap(), HEALTH_DOCS);
1526 }
1527
1528 #[test]
1529 fn dupes_meta_docs_url_matches_constant() {
1530 let meta = dupes_meta();
1531 assert_eq!(meta["docs"].as_str().unwrap(), DUPES_DOCS);
1532 }
1533
1534 #[test]
1537 fn rule_by_id_finds_all_check_rules() {
1538 for rule in CHECK_RULES {
1539 assert!(
1540 rule_by_id(rule.id).is_some(),
1541 "rule_by_id should find check rule {}",
1542 rule.id
1543 );
1544 }
1545 }
1546
1547 #[test]
1548 fn rule_by_id_finds_all_health_rules() {
1549 for rule in HEALTH_RULES {
1550 assert!(
1551 rule_by_id(rule.id).is_some(),
1552 "rule_by_id should find health rule {}",
1553 rule.id
1554 );
1555 }
1556 }
1557
1558 #[test]
1559 fn rule_by_id_finds_all_dupes_rules() {
1560 for rule in DUPES_RULES {
1561 assert!(
1562 rule_by_id(rule.id).is_some(),
1563 "rule_by_id should find dupes rule {}",
1564 rule.id
1565 );
1566 }
1567 }
1568
1569 #[test]
1572 fn check_rules_count() {
1573 assert_eq!(CHECK_RULES.len(), 22);
1574 }
1575
1576 #[test]
1577 fn health_rules_count() {
1578 assert_eq!(HEALTH_RULES.len(), 12);
1579 }
1580
1581 #[test]
1582 fn dupes_rules_count() {
1583 assert_eq!(DUPES_RULES.len(), 1);
1584 }
1585
1586 #[test]
1592 fn every_rule_declares_a_category() {
1593 let allowed = [
1594 "Dead code",
1595 "Dependencies",
1596 "Duplication",
1597 "Health",
1598 "Architecture",
1599 "Suppressions",
1600 ];
1601 for rule in CHECK_RULES.iter().chain(HEALTH_RULES).chain(DUPES_RULES) {
1602 assert!(
1603 !rule.category.is_empty(),
1604 "rule {} has empty category",
1605 rule.id
1606 );
1607 assert!(
1608 allowed.contains(&rule.category),
1609 "rule {} has unrecognised category {:?}; add to allowlist or pick from {:?}",
1610 rule.id,
1611 rule.category,
1612 allowed
1613 );
1614 }
1615 }
1616}