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_families": {
863 "name": "Clone Families",
864 "description": "Groups of clone groups that share the same set of files. Indicates systematic duplication patterns (e.g., mirrored directory structures).",
865 "interpretation": "families suggest extract-module refactoring opportunities"
866 }
867 }
868 })
869}
870
871#[must_use]
873pub fn coverage_setup_meta() -> Value {
874 json!({
875 "docs_url": COVERAGE_SETUP_DOCS,
876 "field_definitions": {
877 "schema_version": "Coverage setup JSON contract version. Stays at \"1\" for additive opt-in fields such as _meta.",
878 "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.",
879 "package_manager": "Detected package manager used for install and run commands, or null when no package manager signal was found.",
880 "runtime_targets": "Union of runtime targets across emitted members.",
881 "members[]": "Per-runtime-workspace setup recipes. Pure aggregator roots and build-only libraries are omitted.",
882 "members[].name": "Workspace package name from package.json, or the root directory name when package.json has no name.",
883 "members[].path": "Workspace path relative to the command root. The root package is represented as \".\".",
884 "members[].framework_detected": "Runtime framework detected for that member.",
885 "members[].package_manager": "Package manager detected for that member, or inherited from the workspace root when no member-specific signal exists.",
886 "members[].runtime_targets": "Runtime targets produced by that member.",
887 "members[].files_to_edit": "Files in that member that should receive runtime beacon setup code.",
888 "members[].snippets": "Copy-paste setup snippets for that member, with paths relative to the command root.",
889 "members[].dockerfile_snippet": "Environment snippet for file-system capture in that member's containerized Node runtime, or null when not applicable.",
890 "members[].warnings": "Actionable setup caveats discovered for that member.",
891 "config_written": "Always null for --json because JSON setup is side-effect-free and never writes configuration.",
892 "files_to_edit": "Compatibility copy of the primary member's files, with workspace prefixes when the primary member is not the root.",
893 "snippets": "Compatibility copy of the primary member's snippets, with workspace prefixes when the primary member is not the root.",
894 "dockerfile_snippet": "Environment snippet for file-system capture in containerized Node runtimes, or null when not applicable.",
895 "commands": "Package-manager commands needed to install the runtime beacon and sidecar packages.",
896 "next_steps": "Ordered setup workflow after applying the emitted snippets.",
897 "warnings": "Actionable setup caveats discovered while building the recipe."
898 },
899 "enums": {
900 "framework_detected": ["nextjs", "nestjs", "nuxt", "sveltekit", "astro", "remix", "vite", "plain_node", "unknown"],
901 "runtime_targets": ["node", "browser"],
902 "package_manager": ["npm", "pnpm", "yarn", "bun", null]
903 },
904 "warnings": {
905 "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.",
906 "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.",
907 "Package manager was not detected": "No packageManager field or known lockfile was found. Commands fall back to npm.",
908 "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."
909 }
910 })
911}
912
913#[must_use]
915pub fn coverage_analyze_meta() -> Value {
916 json!({
917 "docs_url": COVERAGE_ANALYZE_DOCS,
918 "field_definitions": {
919 "schema_version": "Standalone coverage analyze envelope version. \"1\" for the current shape.",
920 "version": "fallow CLI version that produced this output.",
921 "elapsed_ms": "Wall-clock milliseconds spent producing the report.",
922 "runtime_coverage": "Same RuntimeCoverageReport block emitted by `fallow health --runtime-coverage`.",
923 "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.",
924 "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.",
925 "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.",
926 "runtime_coverage.findings[].evidence.static_status": "used = the function is reachable in the AST module graph; unused = it is dead by static analysis.",
927 "runtime_coverage.findings[].evidence.test_coverage": "covered = the local test suite hits the function; not_covered otherwise.",
928 "runtime_coverage.findings[].evidence.v8_tracking": "tracked = V8 observed the function during the capture window; untracked otherwise.",
929 "runtime_coverage.findings[].actions[].type": "Suggested follow-up identifier. delete-cold-code is emitted on safe_to_delete; review-runtime on review_required.",
930 "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.",
931 "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.",
932 "runtime_coverage.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally."
933 },
934 "enums": {
935 "data_source": ["local", "cloud"],
936 "report_verdict": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
937 "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
938 "static_status": ["used", "unused"],
939 "test_coverage": ["covered", "not_covered"],
940 "v8_tracking": ["tracked", "untracked"],
941 "action_type": ["delete-cold-code", "review-runtime"]
942 },
943 "warnings": {
944 "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
945 "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."
946 }
947 })
948}
949
950#[cfg(test)]
951mod tests {
952 use super::*;
953
954 #[test]
957 fn rule_by_id_finds_check_rule() {
958 let rule = rule_by_id("fallow/unused-file").unwrap();
959 assert_eq!(rule.name, "Unused Files");
960 }
961
962 #[test]
963 fn rule_by_id_finds_health_rule() {
964 let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
965 assert_eq!(rule.name, "High Cyclomatic Complexity");
966 }
967
968 #[test]
969 fn rule_by_id_finds_dupes_rule() {
970 let rule = rule_by_id("fallow/code-duplication").unwrap();
971 assert_eq!(rule.name, "Code Duplication");
972 }
973
974 #[test]
975 fn rule_by_id_returns_none_for_unknown() {
976 assert!(rule_by_id("fallow/nonexistent").is_none());
977 assert!(rule_by_id("").is_none());
978 }
979
980 #[test]
983 fn rule_docs_url_format() {
984 let rule = rule_by_id("fallow/unused-export").unwrap();
985 let url = rule_docs_url(rule);
986 assert!(url.starts_with("https://docs.fallow.tools/"));
987 assert!(url.contains("unused-exports"));
988 }
989
990 #[test]
993 fn check_rules_all_have_fallow_prefix() {
994 for rule in CHECK_RULES {
995 assert!(
996 rule.id.starts_with("fallow/"),
997 "rule {} should start with fallow/",
998 rule.id
999 );
1000 }
1001 }
1002
1003 #[test]
1004 fn check_rules_all_have_docs_path() {
1005 for rule in CHECK_RULES {
1006 assert!(
1007 !rule.docs_path.is_empty(),
1008 "rule {} should have a docs_path",
1009 rule.id
1010 );
1011 }
1012 }
1013
1014 #[test]
1015 fn check_rules_no_duplicate_ids() {
1016 let mut seen = rustc_hash::FxHashSet::default();
1017 for rule in CHECK_RULES.iter().chain(HEALTH_RULES).chain(DUPES_RULES) {
1018 assert!(seen.insert(rule.id), "duplicate rule id: {}", rule.id);
1019 }
1020 }
1021
1022 #[test]
1025 fn check_meta_has_docs_and_rules() {
1026 let meta = check_meta();
1027 assert!(meta.get("docs").is_some());
1028 assert!(meta.get("rules").is_some());
1029 let rules = meta["rules"].as_object().unwrap();
1030 assert_eq!(rules.len(), CHECK_RULES.len());
1032 assert!(rules.contains_key("unused-file"));
1033 assert!(rules.contains_key("unused-export"));
1034 assert!(rules.contains_key("unused-type"));
1035 assert!(rules.contains_key("unused-dependency"));
1036 assert!(rules.contains_key("unused-dev-dependency"));
1037 assert!(rules.contains_key("unused-optional-dependency"));
1038 assert!(rules.contains_key("unused-enum-member"));
1039 assert!(rules.contains_key("unused-class-member"));
1040 assert!(rules.contains_key("unresolved-import"));
1041 assert!(rules.contains_key("unlisted-dependency"));
1042 assert!(rules.contains_key("duplicate-export"));
1043 assert!(rules.contains_key("type-only-dependency"));
1044 assert!(rules.contains_key("circular-dependency"));
1045 }
1046
1047 #[test]
1048 fn check_meta_rule_has_required_fields() {
1049 let meta = check_meta();
1050 let rules = meta["rules"].as_object().unwrap();
1051 for (key, value) in rules {
1052 assert!(value.get("name").is_some(), "rule {key} missing 'name'");
1053 assert!(
1054 value.get("description").is_some(),
1055 "rule {key} missing 'description'"
1056 );
1057 assert!(value.get("docs").is_some(), "rule {key} missing 'docs'");
1058 }
1059 }
1060
1061 #[test]
1064 fn health_meta_has_metrics() {
1065 let meta = health_meta();
1066 assert!(meta.get("docs").is_some());
1067 let metrics = meta["metrics"].as_object().unwrap();
1068 assert!(metrics.contains_key("cyclomatic"));
1069 assert!(metrics.contains_key("cognitive"));
1070 assert!(metrics.contains_key("maintainability_index"));
1071 assert!(metrics.contains_key("complexity_density"));
1072 assert!(metrics.contains_key("fan_in"));
1073 assert!(metrics.contains_key("fan_out"));
1074 }
1075
1076 #[test]
1079 fn dupes_meta_has_metrics() {
1080 let meta = dupes_meta();
1081 assert!(meta.get("docs").is_some());
1082 let metrics = meta["metrics"].as_object().unwrap();
1083 assert!(metrics.contains_key("duplication_percentage"));
1084 assert!(metrics.contains_key("token_count"));
1085 assert!(metrics.contains_key("clone_groups"));
1086 assert!(metrics.contains_key("clone_families"));
1087 }
1088
1089 #[test]
1092 fn coverage_setup_meta_has_docs_fields_enums_and_warnings() {
1093 let meta = coverage_setup_meta();
1094 assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
1095 assert!(
1096 meta["field_definitions"]
1097 .as_object()
1098 .unwrap()
1099 .contains_key("members[]")
1100 );
1101 assert!(
1102 meta["field_definitions"]
1103 .as_object()
1104 .unwrap()
1105 .contains_key("config_written")
1106 );
1107 assert!(
1108 meta["field_definitions"]
1109 .as_object()
1110 .unwrap()
1111 .contains_key("members[].package_manager")
1112 );
1113 assert!(
1114 meta["field_definitions"]
1115 .as_object()
1116 .unwrap()
1117 .contains_key("members[].warnings")
1118 );
1119 assert!(
1120 meta["enums"]
1121 .as_object()
1122 .unwrap()
1123 .contains_key("framework_detected")
1124 );
1125 assert!(
1126 meta["warnings"]
1127 .as_object()
1128 .unwrap()
1129 .contains_key("No runtime workspace members were detected")
1130 );
1131 assert!(
1132 meta["warnings"]
1133 .as_object()
1134 .unwrap()
1135 .contains_key("Package manager was not detected")
1136 );
1137 }
1138
1139 #[test]
1142 fn coverage_analyze_meta_documents_data_source_and_action_vocabulary() {
1143 let meta = coverage_analyze_meta();
1144 assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
1145 let fields = meta["field_definitions"].as_object().unwrap();
1146 assert!(fields.contains_key("runtime_coverage.summary.data_source"));
1147 assert!(fields.contains_key("runtime_coverage.summary.last_received_at"));
1148 assert!(fields.contains_key("runtime_coverage.findings[].evidence.test_coverage"));
1149 assert!(fields.contains_key("runtime_coverage.findings[].actions[].type"));
1150 let enums = meta["enums"].as_object().unwrap();
1151 assert_eq!(enums["data_source"], json!(["local", "cloud"]));
1152 assert_eq!(enums["test_coverage"], json!(["covered", "not_covered"]));
1153 assert_eq!(enums["v8_tracking"], json!(["tracked", "untracked"]));
1154 assert_eq!(
1155 enums["action_type"],
1156 json!(["delete-cold-code", "review-runtime"])
1157 );
1158 let warnings = meta["warnings"].as_object().unwrap();
1159 assert!(warnings.contains_key("cloud_functions_unmatched"));
1160 }
1161
1162 #[test]
1165 fn health_rules_all_have_fallow_prefix() {
1166 for rule in HEALTH_RULES {
1167 assert!(
1168 rule.id.starts_with("fallow/"),
1169 "health rule {} should start with fallow/",
1170 rule.id
1171 );
1172 }
1173 }
1174
1175 #[test]
1176 fn health_rules_all_have_docs_path() {
1177 for rule in HEALTH_RULES {
1178 assert!(
1179 !rule.docs_path.is_empty(),
1180 "health rule {} should have a docs_path",
1181 rule.id
1182 );
1183 }
1184 }
1185
1186 #[test]
1187 fn health_rules_all_have_non_empty_fields() {
1188 for rule in HEALTH_RULES {
1189 assert!(
1190 !rule.name.is_empty(),
1191 "health rule {} missing name",
1192 rule.id
1193 );
1194 assert!(
1195 !rule.short.is_empty(),
1196 "health rule {} missing short description",
1197 rule.id
1198 );
1199 assert!(
1200 !rule.full.is_empty(),
1201 "health rule {} missing full description",
1202 rule.id
1203 );
1204 }
1205 }
1206
1207 #[test]
1210 fn dupes_rules_all_have_fallow_prefix() {
1211 for rule in DUPES_RULES {
1212 assert!(
1213 rule.id.starts_with("fallow/"),
1214 "dupes rule {} should start with fallow/",
1215 rule.id
1216 );
1217 }
1218 }
1219
1220 #[test]
1221 fn dupes_rules_all_have_docs_path() {
1222 for rule in DUPES_RULES {
1223 assert!(
1224 !rule.docs_path.is_empty(),
1225 "dupes rule {} should have a docs_path",
1226 rule.id
1227 );
1228 }
1229 }
1230
1231 #[test]
1232 fn dupes_rules_all_have_non_empty_fields() {
1233 for rule in DUPES_RULES {
1234 assert!(!rule.name.is_empty(), "dupes rule {} missing name", rule.id);
1235 assert!(
1236 !rule.short.is_empty(),
1237 "dupes rule {} missing short description",
1238 rule.id
1239 );
1240 assert!(
1241 !rule.full.is_empty(),
1242 "dupes rule {} missing full description",
1243 rule.id
1244 );
1245 }
1246 }
1247
1248 #[test]
1251 fn check_rules_all_have_non_empty_fields() {
1252 for rule in CHECK_RULES {
1253 assert!(!rule.name.is_empty(), "check rule {} missing name", rule.id);
1254 assert!(
1255 !rule.short.is_empty(),
1256 "check rule {} missing short description",
1257 rule.id
1258 );
1259 assert!(
1260 !rule.full.is_empty(),
1261 "check rule {} missing full description",
1262 rule.id
1263 );
1264 }
1265 }
1266
1267 #[test]
1270 fn rule_docs_url_health_rule() {
1271 let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1272 let url = rule_docs_url(rule);
1273 assert!(url.starts_with("https://docs.fallow.tools/"));
1274 assert!(url.contains("health"));
1275 }
1276
1277 #[test]
1278 fn rule_docs_url_dupes_rule() {
1279 let rule = rule_by_id("fallow/code-duplication").unwrap();
1280 let url = rule_docs_url(rule);
1281 assert!(url.starts_with("https://docs.fallow.tools/"));
1282 assert!(url.contains("duplication"));
1283 }
1284
1285 #[test]
1288 fn health_meta_all_metrics_have_name_and_description() {
1289 let meta = health_meta();
1290 let metrics = meta["metrics"].as_object().unwrap();
1291 for (key, value) in metrics {
1292 assert!(
1293 value.get("name").is_some(),
1294 "health metric {key} missing 'name'"
1295 );
1296 assert!(
1297 value.get("description").is_some(),
1298 "health metric {key} missing 'description'"
1299 );
1300 assert!(
1301 value.get("interpretation").is_some(),
1302 "health metric {key} missing 'interpretation'"
1303 );
1304 }
1305 }
1306
1307 #[test]
1308 fn health_meta_has_all_expected_metrics() {
1309 let meta = health_meta();
1310 let metrics = meta["metrics"].as_object().unwrap();
1311 let expected = [
1312 "cyclomatic",
1313 "cognitive",
1314 "line_count",
1315 "lines",
1316 "maintainability_index",
1317 "complexity_density",
1318 "dead_code_ratio",
1319 "fan_in",
1320 "fan_out",
1321 "score",
1322 "weighted_commits",
1323 "trend",
1324 "priority",
1325 "efficiency",
1326 "effort",
1327 "confidence",
1328 "bus_factor",
1329 "contributor_count",
1330 "share",
1331 "stale_days",
1332 "drift",
1333 "unowned",
1334 "runtime_coverage_verdict",
1335 "runtime_coverage_state",
1336 "runtime_coverage_confidence",
1337 "production_invocations",
1338 "percent_dead_in_production",
1339 ];
1340 for key in &expected {
1341 assert!(
1342 metrics.contains_key(*key),
1343 "health_meta missing expected metric: {key}"
1344 );
1345 }
1346 }
1347
1348 #[test]
1351 fn dupes_meta_all_metrics_have_name_and_description() {
1352 let meta = dupes_meta();
1353 let metrics = meta["metrics"].as_object().unwrap();
1354 for (key, value) in metrics {
1355 assert!(
1356 value.get("name").is_some(),
1357 "dupes metric {key} missing 'name'"
1358 );
1359 assert!(
1360 value.get("description").is_some(),
1361 "dupes metric {key} missing 'description'"
1362 );
1363 }
1364 }
1365
1366 #[test]
1367 fn dupes_meta_has_line_count() {
1368 let meta = dupes_meta();
1369 let metrics = meta["metrics"].as_object().unwrap();
1370 assert!(metrics.contains_key("line_count"));
1371 }
1372
1373 #[test]
1376 fn check_docs_url_valid() {
1377 assert!(CHECK_DOCS.starts_with("https://"));
1378 assert!(CHECK_DOCS.contains("dead-code"));
1379 }
1380
1381 #[test]
1382 fn health_docs_url_valid() {
1383 assert!(HEALTH_DOCS.starts_with("https://"));
1384 assert!(HEALTH_DOCS.contains("health"));
1385 }
1386
1387 #[test]
1388 fn dupes_docs_url_valid() {
1389 assert!(DUPES_DOCS.starts_with("https://"));
1390 assert!(DUPES_DOCS.contains("dupes"));
1391 }
1392
1393 #[test]
1396 fn check_meta_docs_url_matches_constant() {
1397 let meta = check_meta();
1398 assert_eq!(meta["docs"].as_str().unwrap(), CHECK_DOCS);
1399 }
1400
1401 #[test]
1402 fn health_meta_docs_url_matches_constant() {
1403 let meta = health_meta();
1404 assert_eq!(meta["docs"].as_str().unwrap(), HEALTH_DOCS);
1405 }
1406
1407 #[test]
1408 fn dupes_meta_docs_url_matches_constant() {
1409 let meta = dupes_meta();
1410 assert_eq!(meta["docs"].as_str().unwrap(), DUPES_DOCS);
1411 }
1412
1413 #[test]
1416 fn rule_by_id_finds_all_check_rules() {
1417 for rule in CHECK_RULES {
1418 assert!(
1419 rule_by_id(rule.id).is_some(),
1420 "rule_by_id should find check rule {}",
1421 rule.id
1422 );
1423 }
1424 }
1425
1426 #[test]
1427 fn rule_by_id_finds_all_health_rules() {
1428 for rule in HEALTH_RULES {
1429 assert!(
1430 rule_by_id(rule.id).is_some(),
1431 "rule_by_id should find health rule {}",
1432 rule.id
1433 );
1434 }
1435 }
1436
1437 #[test]
1438 fn rule_by_id_finds_all_dupes_rules() {
1439 for rule in DUPES_RULES {
1440 assert!(
1441 rule_by_id(rule.id).is_some(),
1442 "rule_by_id should find dupes rule {}",
1443 rule.id
1444 );
1445 }
1446 }
1447
1448 #[test]
1451 fn check_rules_count() {
1452 assert_eq!(CHECK_RULES.len(), 19);
1453 }
1454
1455 #[test]
1456 fn health_rules_count() {
1457 assert_eq!(HEALTH_RULES.len(), 12);
1458 }
1459
1460 #[test]
1461 fn dupes_rules_count() {
1462 assert_eq!(DUPES_RULES.len(), 1);
1463 }
1464
1465 #[test]
1471 fn every_rule_declares_a_category() {
1472 let allowed = [
1473 "Dead code",
1474 "Dependencies",
1475 "Duplication",
1476 "Health",
1477 "Architecture",
1478 "Suppressions",
1479 ];
1480 for rule in CHECK_RULES.iter().chain(HEALTH_RULES).chain(DUPES_RULES) {
1481 assert!(
1482 !rule.category.is_empty(),
1483 "rule {} has empty category",
1484 rule.id
1485 );
1486 assert!(
1487 allowed.contains(&rule.category),
1488 "rule {} has unrecognised category {:?}; add to allowlist or pick from {:?}",
1489 rule.id,
1490 rule.category,
1491 allowed
1492 );
1493 }
1494 }
1495}