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