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