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