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