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