1use std::collections::BTreeMap;
8use std::process::ExitCode;
9
10use colored::Colorize;
11use fallow_config::OutputFormat;
12use fallow_types::envelope::{Meta, MetaRule};
13use serde_json::{Value, json};
14
15const 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 const SECURITY_DOCS: &str = "https://docs.fallow.tools/cli/security";
34
35const ACTIONS_FIELD_DEFINITION: &str = "Per-finding fix and suppression suggestions. Each entry carries a `type` discriminant (kebab-case) plus a per-action `auto_fixable` bool. Consumers dispatch on `type` to choose the remediation and filter on `auto_fixable` of each individual entry.";
38
39const ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION: &str = "Evaluated PER FINDING, not per action type. The same `type` may carry `auto_fixable: true` on one finding and `auto_fixable: false` on another when per-instance guards in the `fallow fix` applier discriminate. Filter on this bool of each individual action, not on `type` alone. Current per-instance flips: (1) `remove-catalog-entry` is `true` only when the finding's `hardcoded_consumers` array is empty (else fallow fix skips the entry to avoid breaking `pnpm install`); (2) the primary dependency action flips between `remove-dependency` (`auto_fixable: true`) and `move-dependency` (`auto_fixable: false`) based on `used_in_workspaces`; (3) `add-to-config` for `ignoreExports` is `true` when fallow fix can safely apply the action, which means EITHER a fallow config file already exists OR no config exists and the working directory is NOT inside a monorepo subpackage (the applier then creates `.fallowrc.json` using `fallow init`'s framework-aware scaffolding and layers the new rules on top); `false` inside a monorepo subpackage with no workspace-root config because the applier refuses to fragment per-package configs; (4) `update-catalog-reference` is always `false` today (catalog-switching applier not yet wired). All `suppress-line` and `suppress-file` actions are uniformly `false`.";
44
45pub struct RuleDef {
47 pub id: &'static str,
48 pub category: &'static str,
55 pub name: &'static str,
56 pub short: &'static str,
57 pub full: &'static str,
58 pub docs_path: &'static str,
59}
60
61pub const CHECK_RULES: &[RuleDef] = &[
62 RuleDef {
63 id: "fallow/unused-file",
64 category: "Dead code",
65 name: "Unused Files",
66 short: "File is not reachable from any entry point",
67 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.",
68 docs_path: "explanations/dead-code#unused-files",
69 },
70 RuleDef {
71 id: "fallow/unused-export",
72 category: "Dead code",
73 name: "Unused Exports",
74 short: "Export is never imported",
75 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.",
76 docs_path: "explanations/dead-code#unused-exports",
77 },
78 RuleDef {
79 id: "fallow/unused-type",
80 category: "Dead code",
81 name: "Unused Type Exports",
82 short: "Type export is never imported",
83 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.",
84 docs_path: "explanations/dead-code#unused-types",
85 },
86 RuleDef {
87 id: "fallow/private-type-leak",
88 category: "Dead code",
89 name: "Private Type Leaks",
90 short: "Exported signature references a private type",
91 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.",
92 docs_path: "explanations/dead-code#private-type-leaks",
93 },
94 RuleDef {
95 id: "fallow/unused-dependency",
96 category: "Dependencies",
97 name: "Unused Dependencies",
98 short: "Dependency listed but never imported",
99 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.",
100 docs_path: "explanations/dead-code#unused-dependencies",
101 },
102 RuleDef {
103 id: "fallow/unused-dev-dependency",
104 category: "Dependencies",
105 name: "Unused Dev Dependencies",
106 short: "Dev dependency listed but never imported",
107 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.",
108 docs_path: "explanations/dead-code#unused-devdependencies",
109 },
110 RuleDef {
111 id: "fallow/unused-optional-dependency",
112 category: "Dependencies",
113 name: "Unused Optional Dependencies",
114 short: "Optional dependency listed but never imported",
115 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.",
116 docs_path: "explanations/dead-code#unused-optionaldependencies",
117 },
118 RuleDef {
119 id: "fallow/type-only-dependency",
120 category: "Dependencies",
121 name: "Type-only Dependencies",
122 short: "Production dependency only used via type-only imports",
123 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.",
124 docs_path: "explanations/dead-code#type-only-dependencies",
125 },
126 RuleDef {
127 id: "fallow/test-only-dependency",
128 category: "Dependencies",
129 name: "Test-only Dependencies",
130 short: "Production dependency only imported by test files",
131 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.",
132 docs_path: "explanations/dead-code#test-only-dependencies",
133 },
134 RuleDef {
135 id: "fallow/unused-enum-member",
136 category: "Dead code",
137 name: "Unused Enum Members",
138 short: "Enum member is never referenced",
139 full: "Enum members that are never referenced in the codebase. Uses scope-aware binding analysis to track all references including computed access patterns.",
140 docs_path: "explanations/dead-code#unused-enum-members",
141 },
142 RuleDef {
143 id: "fallow/unused-class-member",
144 category: "Dead code",
145 name: "Unused Class Members",
146 short: "Class member is never referenced",
147 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.",
148 docs_path: "explanations/dead-code#unused-class-members",
149 },
150 RuleDef {
151 id: "fallow/unresolved-import",
152 category: "Dead code",
153 name: "Unresolved Imports",
154 short: "Import could not be resolved",
155 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.",
156 docs_path: "explanations/dead-code#unresolved-imports",
157 },
158 RuleDef {
159 id: "fallow/unlisted-dependency",
160 category: "Dependencies",
161 name: "Unlisted Dependencies",
162 short: "Dependency used but not in package.json",
163 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.",
164 docs_path: "explanations/dead-code#unlisted-dependencies",
165 },
166 RuleDef {
167 id: "fallow/duplicate-export",
168 category: "Dead code",
169 name: "Duplicate Exports",
170 short: "Export name appears in multiple modules",
171 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.",
172 docs_path: "explanations/dead-code#duplicate-exports",
173 },
174 RuleDef {
175 id: "fallow/circular-dependency",
176 category: "Architecture",
177 name: "Circular Dependencies",
178 short: "Circular dependency chain detected",
179 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.",
180 docs_path: "explanations/dead-code#circular-dependencies",
181 },
182 RuleDef {
183 id: "fallow/re-export-cycle",
184 category: "Architecture",
185 name: "Re-Export Cycles",
186 short: "Two or more barrel files re-export from each other in a loop",
187 full: "A barrel file re-exports from another barrel that ultimately re-exports back. When this happens, imports from any file in the loop may silently come up empty, because the re-export chain has no terminating module to resolve names against. To fix this: open any one file in the loop and remove the `export * from` (or `export { ... } from`) statement that points back into the cycle. Any single removal will break the cycle and restore working re-exports. A self-loop (a single barrel re-exporting from itself, often a rename leftover) is reported under the same rule with kind `self-loop`.",
188 docs_path: "explanations/dead-code#re-export-cycles",
189 },
190 RuleDef {
191 id: "fallow/boundary-violation",
192 category: "Architecture",
193 name: "Boundary Violations",
194 short: "Import crosses a configured architecture boundary",
195 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.",
196 docs_path: "explanations/dead-code#boundary-violations",
197 },
198 RuleDef {
199 id: "fallow/boundary-coverage",
200 category: "Architecture",
201 name: "Boundary Coverage",
202 short: "Source file matches no configured architecture boundary zone",
203 full: "A reachable source file is not assigned to any configured boundary zone while boundaries.coverage.requireAllFiles is enabled. Add the file to a zone pattern, move it under an existing zone, or allow-list generated and intentionally unzoned paths with boundaries.coverage.allowUnmatched.",
204 docs_path: "explanations/dead-code#boundary-violations",
205 },
206 RuleDef {
207 id: "fallow/boundary-call-violation",
208 category: "Architecture",
209 name: "Boundary Call Violation",
210 short: "Zoned file calls a callee its zone forbids",
211 full: "A file classified into a boundary zone calls a callee matching one of the zone's boundaries.calls.forbidden patterns. The check is syntactic: it matches the written callee path and the import-resolved canonical path, and it only applies to files classified into a zone. Move the call behind an allowed abstraction, or adjust the zone's forbidden patterns if the rule was wrong.",
212 docs_path: "explanations/dead-code#boundary-violations",
213 },
214 RuleDef {
215 id: "fallow/policy-violation",
216 category: "Policy",
217 name: "Policy Violation",
218 short: "Banned call or import matched a rule-pack rule",
219 full: "A call site or import matched a banned-call or banned-import rule from a configured rule pack (the rulePacks config key). Packs are pure declarative data; the check is syntactic and does not follow aliased or re-bound callees, and import matching uses the raw specifier. Replace the banned usage per the rule's message, scope the rule with files/exclude globs, or adjust its severity.",
220 docs_path: "explanations/dead-code#policy-violations",
221 },
222 RuleDef {
223 id: "fallow/stale-suppression",
224 category: "Suppressions",
225 name: "Stale Suppressions",
226 short: "Suppression comment or tag no longer matches any issue",
227 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.",
228 docs_path: "explanations/dead-code#stale-suppressions",
229 },
230 RuleDef {
231 id: "fallow/unused-catalog-entry",
232 category: "Dependencies",
233 name: "Unused pnpm catalog entry",
234 short: "Catalog entry in pnpm-workspace.yaml not referenced by any workspace package",
235 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).",
236 docs_path: "explanations/dead-code#unused-catalog-entries",
237 },
238 RuleDef {
239 id: "fallow/empty-catalog-group",
240 category: "Dependencies",
241 name: "Empty pnpm catalog group",
242 short: "Named catalog group in pnpm-workspace.yaml has no entries",
243 full: "A named group under `catalogs:` in pnpm-workspace.yaml has no package entries. Empty named groups are leftover catalog structure after the last entry is removed. The top-level `catalog:` map is intentionally ignored because some projects keep it as a stable hook.",
244 docs_path: "explanations/dead-code#empty-catalog-groups",
245 },
246 RuleDef {
247 id: "fallow/unresolved-catalog-reference",
248 category: "Dependencies",
249 name: "Unresolved pnpm catalog reference",
250 short: "package.json references a catalog that does not declare the package",
251 full: "A workspace package.json declares a dependency with the `catalog:` or `catalog:<name>` protocol, but the catalog has no entry for that package. `pnpm install` will fail with ERR_PNPM_CATALOG_ENTRY_NOT_FOUND_FOR_CATALOG_PROTOCOL. To fix: add the package to the named catalog, switch the reference to a different catalog that does declare it, or remove the reference and pin a hardcoded version. Scope: the detector scans `dependencies`, `devDependencies`, `peerDependencies`, and `optionalDependencies` in every workspace `package.json`. See also: fallow/unused-catalog-entry (the inverse: catalog entries no consumer references).",
252 docs_path: "explanations/dead-code#unresolved-catalog-references",
253 },
254 RuleDef {
255 id: "fallow/unused-dependency-override",
256 category: "Dependencies",
257 name: "Unused pnpm dependency override",
258 short: "pnpm.overrides entry targets a package not declared or resolved",
259 full: "An entry in `pnpm-workspace.yaml`'s `overrides:` section, or the root `package.json`'s `pnpm.overrides` block, whose target package is not declared by any workspace package and is not present in `pnpm-lock.yaml`. Override entries linger after their target package leaves the resolved dependency tree. For projects without a readable lockfile, fallow falls back to workspace package.json manifests and keeps a `hint` so transitive CVE pins can be reviewed before removal. To fix: delete the entry, refresh `pnpm-lock.yaml` if it is stale, or add the entry to `ignoreDependencyOverrides` when the override is intentionally retained. See also: fallow/misconfigured-dependency-override.",
260 docs_path: "explanations/dead-code#unused-dependency-overrides",
261 },
262 RuleDef {
263 id: "fallow/misconfigured-dependency-override",
264 category: "Dependencies",
265 name: "Misconfigured pnpm dependency override",
266 short: "pnpm.overrides entry has an unparsable key or value",
267 full: "An entry in `pnpm-workspace.yaml`'s `overrides:` or `package.json`'s `pnpm.overrides` whose key or value does not parse as a valid pnpm override spec. Common shapes: empty key, empty value, malformed version selector on the target (`@types/react@<<18`), unbalanced parent matcher (`react>`), or unsupported `npm:alias@` syntax in the version (only the `-`, `$ref`, and `npm:alias` pnpm idioms are allowed). pnpm rejects the workspace at install time with a parser error. To fix: correct the key/value shape, or remove the entry. See also: fallow/unused-dependency-override.",
268 docs_path: "explanations/dead-code#misconfigured-dependency-overrides",
269 },
270];
271
272#[must_use]
274pub fn rule_by_id(id: &str) -> Option<&'static RuleDef> {
275 CHECK_RULES
276 .iter()
277 .chain(HEALTH_RULES.iter())
278 .chain(DUPES_RULES.iter())
279 .chain(FLAGS_RULES.iter())
280 .chain(SECURITY_RULES.iter())
281 .find(|r| r.id == id)
282}
283
284#[must_use]
286pub fn rule_docs_url(rule: &RuleDef) -> String {
287 format!("{DOCS_BASE}/{}", rule.docs_path)
288}
289
290pub struct RuleGuide {
295 pub example: &'static str,
296 pub how_to_fix: &'static str,
297}
298
299#[must_use]
304pub fn rule_by_token(token: &str) -> Option<&'static RuleDef> {
305 let trimmed = token.trim();
306 if trimmed.is_empty() {
307 return None;
308 }
309 if let Some(rule) = rule_by_id(trimmed) {
310 return Some(rule);
311 }
312 let normalized = trimmed
313 .strip_prefix("fallow/")
314 .unwrap_or(trimmed)
315 .trim_start_matches("--")
316 .replace('_', "-")
317 .split_whitespace()
318 .collect::<Vec<_>>()
319 .join("-");
320 let alias = dead_code_alias_id(&normalized)
321 .or_else(|| catalog_alias_id(&normalized))
322 .or_else(|| health_alias_id(&normalized))
323 .or_else(|| security_alias_id(&normalized));
324 if let Some(id) = alias
325 && let Some(rule) = rule_by_id(id)
326 {
327 return Some(rule);
328 }
329 let security_token = normalized.strip_prefix("security-").unwrap_or(&normalized);
330 let security_id = format!("security/{security_token}");
331 if let Some(rule) = rule_by_id(&security_id) {
332 return Some(rule);
333 }
334 let singular = normalized
335 .strip_suffix('s')
336 .filter(|_| normalized != "unused-class")
337 .unwrap_or(&normalized);
338 let singular_security_token = singular.strip_prefix("security-").unwrap_or(singular);
339 let singular_security_id = format!("security/{singular_security_token}");
340 if let Some(rule) = rule_by_id(&singular_security_id) {
341 return Some(rule);
342 }
343 let id = format!("fallow/{singular}");
344 rule_by_id(&id).or_else(|| {
345 CHECK_RULES
346 .iter()
347 .chain(HEALTH_RULES.iter())
348 .chain(DUPES_RULES.iter())
349 .chain(FLAGS_RULES.iter())
350 .chain(SECURITY_RULES.iter())
351 .find(|rule| {
352 rule.docs_path.ends_with(&normalized)
353 || rule.docs_path.ends_with(singular)
354 || rule.name.eq_ignore_ascii_case(trimmed)
355 })
356 })
357}
358
359fn dead_code_alias_id(normalized: &str) -> Option<&'static str> {
360 match normalized {
361 "unused-files" => Some("fallow/unused-file"),
362 "unused-exports" => Some("fallow/unused-export"),
363 "unused-types" => Some("fallow/unused-type"),
364 "private-type-leaks" => Some("fallow/private-type-leak"),
365 "unused-deps" | "unused-dependencies" => Some("fallow/unused-dependency"),
366 "unused-dev-deps" | "unused-dev-dependencies" => Some("fallow/unused-dev-dependency"),
367 "unused-optional-deps" | "unused-optional-dependencies" => {
368 Some("fallow/unused-optional-dependency")
369 }
370 "type-only-deps" | "type-only-dependencies" => Some("fallow/type-only-dependency"),
371 "test-only-deps" | "test-only-dependencies" => Some("fallow/test-only-dependency"),
372 "unused-enum-members" => Some("fallow/unused-enum-member"),
373 "unused-class-members" => Some("fallow/unused-class-member"),
374 "unresolved-imports" => Some("fallow/unresolved-import"),
375 "unlisted-deps" | "unlisted-dependencies" => Some("fallow/unlisted-dependency"),
376 "duplicate-exports" => Some("fallow/duplicate-export"),
377 "circular-deps" | "circular-dependencies" => Some("fallow/circular-dependency"),
378 "boundary-violations" => Some("fallow/boundary-violation"),
379 "boundary-coverage" | "boundary-coverage-violations" => Some("fallow/boundary-coverage"),
380 "boundary-calls" | "boundary-call-violations" => Some("fallow/boundary-call-violation"),
381 "policy-violation" | "policy-violations" => Some("fallow/policy-violation"),
382 "stale-suppressions" => Some("fallow/stale-suppression"),
383 _ => None,
384 }
385}
386
387fn catalog_alias_id(normalized: &str) -> Option<&'static str> {
388 match normalized {
389 "unused-catalog-entries" | "unused-catalog-entry" | "catalog" => {
390 Some("fallow/unused-catalog-entry")
391 }
392 "empty-catalog-groups" | "empty-catalog-group" | "empty-catalog" => {
393 Some("fallow/empty-catalog-group")
394 }
395 "unresolved-catalog-references" | "unresolved-catalog-reference" | "unresolved-catalog" => {
396 Some("fallow/unresolved-catalog-reference")
397 }
398 "unused-dependency-overrides"
399 | "unused-dependency-override"
400 | "unused-override"
401 | "unused-overrides" => Some("fallow/unused-dependency-override"),
402 "misconfigured-dependency-overrides"
403 | "misconfigured-dependency-override"
404 | "misconfigured-override"
405 | "misconfigured-overrides" => Some("fallow/misconfigured-dependency-override"),
406 _ => None,
407 }
408}
409
410fn health_alias_id(normalized: &str) -> Option<&'static str> {
411 match normalized {
412 "complexity" | "high-complexity" => Some("fallow/high-complexity"),
413 "cyclomatic" | "high-cyclomatic" | "high-cyclomatic-complexity" => {
414 Some("fallow/high-cyclomatic-complexity")
415 }
416 "cognitive" | "high-cognitive" | "high-cognitive-complexity" => {
417 Some("fallow/high-cognitive-complexity")
418 }
419 "crap" | "high-crap" | "high-crap-score" => Some("fallow/high-crap-score"),
420 "duplication" | "dupes" | "code-duplication" => Some("fallow/code-duplication"),
421 "feature-flag" | "feature-flags" | "flags" => Some("fallow/feature-flag"),
422 _ => None,
423 }
424}
425
426fn security_alias_id(normalized: &str) -> Option<&'static str> {
427 match normalized {
428 "security"
429 | "security-candidate"
430 | "security-candidates"
431 | "tainted-sink"
432 | "tainted-sinks"
433 | "security-sink"
434 | "security-sinks" => Some("security/tainted-sink"),
435 "client-server-leak"
436 | "client-server-leaks"
437 | "security-client-server-leak"
438 | "security-client-server-leaks" => Some("security/client-server-leak"),
439 "hardcoded-secret" | "hardcoded-secrets" | "hard-coded-secret" | "hard-coded-secrets" => {
440 Some("security/hardcoded-secret")
441 }
442 _ => None,
443 }
444}
445
446#[must_use]
448pub fn rule_guide(rule: &RuleDef) -> RuleGuide {
449 source_dead_code_rule_guide(rule.id)
450 .or_else(|| member_import_rule_guide(rule.id))
451 .or_else(|| architecture_rule_guide(rule.id))
452 .or_else(|| catalog_rule_guide(rule.id))
453 .or_else(|| health_runtime_rule_guide(rule.id))
454 .or_else(|| duplication_rule_guide(rule.id))
455 .or_else(|| security_rule_guide(rule.id))
456 .unwrap_or_else(fallback_rule_guide)
457}
458
459fn source_dead_code_rule_guide(id: &str) -> Option<RuleGuide> {
460 Some(match id {
461 "fallow/unused-file" => RuleGuide {
462 example: "src/old-widget.ts is not imported by any entry point, route, script, or config file.",
463 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.",
464 },
465 "fallow/unused-export" => RuleGuide {
466 example: "export const formatPrice = ... exists in src/money.ts, but no module imports formatPrice.",
467 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.",
468 },
469 "fallow/unused-type" => RuleGuide {
470 example: "export interface LegacyProps is exported, but no module imports the type.",
471 how_to_fix: "Remove the type export, inline it, or keep it behind an explicit API entry point when consumers rely on it.",
472 },
473 "fallow/private-type-leak" => RuleGuide {
474 example: "export function makeUser(): InternalUser exposes InternalUser even though InternalUser is not exported.",
475 how_to_fix: "Export the referenced type, change the public signature to an exported type, or keep the helper private.",
476 },
477 "fallow/unused-dependency"
478 | "fallow/unused-dev-dependency"
479 | "fallow/unused-optional-dependency" => RuleGuide {
480 example: "package.json lists left-pad, but no source, script, config, or plugin-recognized file imports it.",
481 how_to_fix: "Remove the dependency after checking runtime/plugin usage. If another workspace uses it, move the dependency to that workspace.",
482 },
483 "fallow/type-only-dependency" => RuleGuide {
484 example: "zod is in dependencies but only appears in import type declarations.",
485 how_to_fix: "Move the package to devDependencies unless runtime code imports it as a value.",
486 },
487 "fallow/test-only-dependency" => RuleGuide {
488 example: "vitest is listed in dependencies, but only test files import it.",
489 how_to_fix: "Move the package to devDependencies unless production code imports it at runtime.",
490 },
491 _ => return None,
492 })
493}
494
495fn member_import_rule_guide(id: &str) -> Option<RuleGuide> {
496 Some(match id {
497 "fallow/unused-enum-member" => RuleGuide {
498 example: "Status.Legacy remains in an exported enum, but no code reads that member.",
499 how_to_fix: "Remove the member after checking serialized/API compatibility, or suppress it with a reason when external data still uses it.",
500 },
501 "fallow/unused-class-member" => RuleGuide {
502 example: "class Parser has a public parseLegacy method that is never called in the project.",
503 how_to_fix: "Remove or privatize the member. For reflection/framework lifecycle hooks, configure or suppress the intentional entry point.",
504 },
505 "fallow/unresolved-import" => RuleGuide {
506 example: "src/app.ts imports ./routes/admin, but no matching file exists after extension and index resolution.",
507 how_to_fix: "Fix the specifier, restore the missing file, install the package, or align tsconfig path aliases with the runtime resolver.",
508 },
509 "fallow/unlisted-dependency" => RuleGuide {
510 example: "src/api.ts imports undici, but the nearest package.json does not list undici.",
511 how_to_fix: "Add the package to dependencies/devDependencies in the workspace that imports it instead of relying on hoisting or transitive deps.",
512 },
513 "fallow/duplicate-export" => RuleGuide {
514 example: "Button is exported from both src/ui/button.ts and src/components/button.ts.",
515 how_to_fix: "Rename or consolidate the exports so consumers have one intentional import target.",
516 },
517 _ => return None,
518 })
519}
520
521fn architecture_rule_guide(id: &str) -> Option<RuleGuide> {
522 Some(match id {
523 "fallow/circular-dependency" => RuleGuide {
524 example: "src/a.ts imports src/b.ts, and src/b.ts imports src/a.ts.",
525 how_to_fix: "Extract shared code to a third module, invert the dependency, or split initialization-time side effects from type-only contracts.",
526 },
527 "fallow/boundary-violation" => RuleGuide {
528 example: "features/billing imports app/admin even though the configured boundary only allows imports from shared and entities.",
529 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.",
530 },
531 "fallow/boundary-coverage" => RuleGuide {
532 example: "src/generated/client.ts is reachable but does not match any boundaries.zones[].patterns entry.",
533 how_to_fix: "Add the file to the intended zone pattern, move it under a zoned directory, or add a generated-file glob to boundaries.coverage.allowUnmatched.",
534 },
535 "fallow/boundary-call-violation" => RuleGuide {
536 example: "src/domain/policy.ts calls execSync from node:child_process while boundaries.calls.forbidden bans child_process.* from the domain zone.",
537 how_to_fix: "Move the call into a zone that may perform the effect, route it through an allowed abstraction, or narrow the forbidden pattern if the rule was wrong. To suppress, use the boundary family token: `// fallow-ignore-next-line boundary-violation` governs import, coverage, and call findings alike (the rule-id-shaped `boundary-call-violation` is accepted as an alias).",
538 },
539 "fallow/policy-violation" => RuleGuide {
540 example: "src/app.ts imports moment while a rule pack bans the moment specifier with the message 'Use date-fns.'",
541 how_to_fix: "Replace the banned call or import with the alternative named in the rule's message. To waive one rule, use `// fallow-ignore-next-line policy-violation:<pack>/<rule-id>` or the file-level form. Use bare `policy-violation` only when you intend to suppress every rule-pack finding at that scope.",
542 },
543 "fallow/stale-suppression" => RuleGuide {
544 example: "// fallow-ignore-next-line unused-export remains above an export that is now used.",
545 how_to_fix: "Remove the suppression. If a different issue is still intentional, replace it with a current, specific suppression.",
546 },
547 _ => return None,
548 })
549}
550
551fn catalog_rule_guide(id: &str) -> Option<RuleGuide> {
552 Some(match id {
553 "fallow/unused-catalog-entry" => RuleGuide {
554 example: "pnpm-workspace.yaml declares `catalog: { is-even: ^1.0.0 }`, but no workspace package.json declares `\"is-even\": \"catalog:\"`.",
555 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.",
556 },
557 "fallow/empty-catalog-group" => RuleGuide {
558 example: "pnpm-workspace.yaml declares `catalogs: { react17: {} }` after the last react17 entry was removed.",
559 how_to_fix: "Delete the empty named group header from pnpm-workspace.yaml. Comments between the deleted header and the next sibling can stay in place for manual review.",
560 },
561 "fallow/unresolved-catalog-reference" => RuleGuide {
562 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.",
563 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.",
564 },
565 "fallow/unused-dependency-override" => RuleGuide {
566 example: "pnpm-workspace.yaml declares `overrides: { axios: ^1.6.0 }`, but no workspace package.json declares `axios` and `pnpm-lock.yaml` does not resolve it.",
567 how_to_fix: "Delete the entry from `pnpm-workspace.yaml` or `package.json#pnpm.overrides`. If the finding is caused by a stale or missing lockfile, refresh `pnpm-lock.yaml` and rerun fallow. If the override is intentionally retained, add it to `ignoreDependencyOverrides` in your fallow config.",
568 },
569 "fallow/misconfigured-dependency-override" => RuleGuide {
570 example: "pnpm-workspace.yaml declares `overrides: { \"@types/react@<<18\": \"18.0.0\" }`. The doubled `<<` is not a valid pnpm version selector and pnpm will reject the workspace at install time.",
571 how_to_fix: "Fix the key/value to match pnpm's override grammar: bare names (`axios`), scoped names (`@types/react`), targets with version selectors (`@types/react@<18`), parent matchers (`react>react-dom`), and parent chains with selectors on either side. Allowed value idioms: bare version range, `-` (delete), `$ref`, and `npm:alias`. If the entry was experimental, remove it.",
572 },
573 _ => return None,
574 })
575}
576
577fn health_runtime_rule_guide(id: &str) -> Option<RuleGuide> {
578 Some(match id {
579 "fallow/high-cyclomatic-complexity"
580 | "fallow/high-cognitive-complexity"
581 | "fallow/high-complexity" => RuleGuide {
582 example: "A function contains several nested conditionals, loops, and early exits, exceeding the configured complexity threshold. fallow also flags synthetic `<template>` findings on Angular .html templates and inline `@Component({ template: ... })` literals, and `<component>` rollup findings that combine the worst class method with its template.",
583 how_to_fix: "For function findings, extract named helpers, split independent branches, flatten guard clauses, and add tests around the behavior before refactoring. For `<template>` findings, split the template into child components, hoist data into the component class as computed signals, or replace nested `@if`/`@for` with a flatter structure. For `<component>` rollup findings, attack the larger half first; the per-half breakdown lives in `component_rollup`.",
584 },
585 "fallow/high-crap-score" => RuleGuide {
586 example: "A complex function has little or no matching Istanbul coverage, so its CRAP score crosses the configured gate.",
587 how_to_fix: "Add focused tests for the risky branches first, then simplify the function if the score remains high.",
588 },
589 "fallow/refactoring-target" => RuleGuide {
590 example: "A file combines high complexity density, churn, fan-in, and dead-code signals.",
591 how_to_fix: "Start with the listed evidence: remove dead exports, extract complex functions, then reduce fan-out or cycles in small steps.",
592 },
593 "fallow/untested-file" | "fallow/untested-export" => RuleGuide {
594 example: "Production-reachable code has no dependency path from discovered test entry points.",
595 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.",
596 },
597 "fallow/runtime-safe-to-delete"
598 | "fallow/runtime-review-required"
599 | "fallow/runtime-low-traffic"
600 | "fallow/runtime-coverage-unavailable"
601 | "fallow/runtime-coverage" => RuleGuide {
602 example: "Runtime coverage shows a function was never called, barely called, or could not be matched during the capture window.",
603 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.",
604 },
605 _ => return None,
606 })
607}
608
609fn duplication_rule_guide(id: &str) -> Option<RuleGuide> {
610 Some(match id {
611 "fallow/code-duplication" => RuleGuide {
612 example: "Two files contain the same normalized token sequence across a multi-line block.",
613 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.",
614 },
615 _ => return None,
616 })
617}
618
619fn security_rule_guide(id: &str) -> Option<RuleGuide> {
620 Some(match id {
621 "security/tainted-sink" => RuleGuide {
622 example: "A non-literal request field reaches a catalogue sink such as security/sql-injection or security/dangerous-html. The finding is a candidate, not proof of exploitability.",
623 how_to_fix: "Trace the source, sink, sanitization, and runtime context. Fix confirmed issues with parameterization, escaping, validation, or safer APIs, and suppress only reviewed false positives with context.",
624 },
625 "security/client-server-leak" => RuleGuide {
626 example: "A module marked `use client` imports code that reads a non-public `process.env` or `import.meta.env` value through a static path.",
627 how_to_fix: "Keep non-public env reads on the server side, move the value behind an API boundary, or rename only intentionally public values to the framework's public prefix.",
628 },
629 "security/hardcoded-secret" => RuleGuide {
630 example: "A provider-prefixed token-shaped literal is assigned to a secret-shaped variable, and the hardcoded-secret category is explicitly included.",
631 how_to_fix: "Rotate real credentials, move them to a secret manager or environment variable, and keep test-only literals clearly fake so they do not resemble provider tokens.",
632 },
633 id if id.starts_with("security/") => RuleGuide {
634 example: "A `fallow security` candidate uses this catalogue category as its SARIF rule id, for example security/sql-injection for a matched SQL sink.",
635 how_to_fix: "Review the candidate trace before acting. Confirm attacker control, missing sanitization, and reachable runtime context, then fix with the category-appropriate safer API or add a reviewed suppression.",
636 },
637 _ => return None,
638 })
639}
640
641fn fallback_rule_guide() -> RuleGuide {
642 RuleGuide {
643 example: "Run the relevant command with --format json --quiet --explain to inspect this rule in context.",
644 how_to_fix: "Use the issue action hints, source location, and docs URL to decide whether to remove, move, configure, or suppress the finding.",
645 }
646}
647
648#[must_use]
650pub fn run_explain(issue_type: &str, output: OutputFormat) -> ExitCode {
651 let Some(rule) = rule_by_token(issue_type) else {
652 let message = if looks_security_explain_token(issue_type) {
653 format!(
654 "unknown issue type '{issue_type}'. Try values like tainted-sink, client-server-leak, hardcoded-secret, sql-injection, or security/sql-injection"
655 )
656 } else {
657 format!(
658 "unknown issue type '{issue_type}'. Try values like unused files, unused-export, high complexity, or code duplication"
659 )
660 };
661 return crate::error::emit_error(&message, 2, output);
662 };
663 let guide = rule_guide(rule);
664 match output {
665 OutputFormat::Json => {
666 let envelope = crate::output_envelope::ExplainOutput {
667 id: rule.id.to_string(),
668 name: rule.name.to_string(),
669 summary: rule.short.to_string(),
670 rationale: rule.full.to_string(),
671 example: guide.example.to_string(),
672 how_to_fix: guide.how_to_fix.to_string(),
673 docs: rule_docs_url(rule),
674 };
675 match crate::output_envelope::serialize_root_output(
676 crate::output_envelope::FallowOutput::Explain(envelope),
677 ) {
678 Ok(value) => crate::report::emit_json(&value, "explain"),
679 Err(e) => {
680 crate::error::emit_error(&format!("JSON serialization error: {e}"), 2, output)
681 }
682 }
683 }
684 OutputFormat::Human => print_explain_human(rule, &guide),
685 OutputFormat::Compact => print_explain_compact(rule),
686 OutputFormat::Markdown => print_explain_markdown(rule, &guide),
687 OutputFormat::Sarif
688 | OutputFormat::CodeClimate
689 | OutputFormat::PrCommentGithub
690 | OutputFormat::PrCommentGitlab
691 | OutputFormat::ReviewGithub
692 | OutputFormat::ReviewGitlab
693 | OutputFormat::Badge => crate::error::emit_error(
694 "explain supports human, compact, markdown, and json output",
695 2,
696 output,
697 ),
698 }
699}
700
701fn looks_security_explain_token(issue_type: &str) -> bool {
702 let normalized = issue_type.trim().to_ascii_lowercase().replace('_', "-");
703 normalized.contains("security")
704 || normalized.contains("secret")
705 || normalized.contains("sink")
706 || normalized.contains("cwe")
707 || normalized.contains("client-server")
708 || normalized.contains("injection")
709}
710
711fn print_explain_human(rule: &RuleDef, guide: &RuleGuide) -> ExitCode {
712 println!("{}", rule.name.bold());
713 println!("{}", rule.id.dimmed());
714 println!();
715 println!("{}", rule.short);
716 println!();
717 println!("{}", "Why it matters".bold());
718 println!("{}", rule.full);
719 println!();
720 println!("{}", "Example".bold());
721 println!("{}", guide.example);
722 println!();
723 println!("{}", "How to fix".bold());
724 println!("{}", guide.how_to_fix);
725 println!();
726 println!("{} {}", "Docs:".dimmed(), rule_docs_url(rule).dimmed());
727 ExitCode::SUCCESS
728}
729
730fn print_explain_compact(rule: &RuleDef) -> ExitCode {
731 println!("explain:{}:{}:{}", rule.id, rule.short, rule_docs_url(rule));
732 ExitCode::SUCCESS
733}
734
735fn print_explain_markdown(rule: &RuleDef, guide: &RuleGuide) -> ExitCode {
736 println!("# {}", rule.name);
737 println!();
738 println!("`{}`", rule.id);
739 println!();
740 println!("{}", rule.short);
741 println!();
742 println!("## Why it matters");
743 println!();
744 println!("{}", rule.full);
745 println!();
746 println!("## Example");
747 println!();
748 println!("{}", guide.example);
749 println!();
750 println!("## How to fix");
751 println!();
752 println!("{}", guide.how_to_fix);
753 println!();
754 println!("[Docs]({})", rule_docs_url(rule));
755 ExitCode::SUCCESS
756}
757
758pub const HEALTH_RULES: &[RuleDef] = &[
759 RuleDef {
760 id: "fallow/high-cyclomatic-complexity",
761 category: "Health",
762 name: "High Cyclomatic Complexity",
763 short: "Function has high cyclomatic complexity",
764 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. fallow also emits this rule on synthetic `<template>` findings (Angular .html templates and inline `@Component({ template: ... })` literals), counting template control-flow blocks (`@if`, `@else if`, `@for`, `@case`, `@defer (when ...)`, legacy `*ngIf`/`*ngFor`) plus ternary and logical operators inside bound attributes and `{{ }}` interpolations; and on synthetic `<component>` rollup findings whose `cyclomatic` is the worst class method's score plus the template's. Ranking and `--targets` use the rollup total; JSON exposes the per-half breakdown under `component_rollup`.",
765 docs_path: "explanations/health#cyclomatic-complexity",
766 },
767 RuleDef {
768 id: "fallow/high-cognitive-complexity",
769 category: "Health",
770 name: "High Cognitive Complexity",
771 short: "Function has high cognitive complexity",
772 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. fallow also emits this rule on synthetic `<template>` findings (Angular .html templates and inline `@Component({ template: ... })` literals), where nesting penalties accumulate on stacked `@if`/`@for`/`@switch` blocks; and on synthetic `<component>` rollup findings whose `cognitive` is the worst class method's score plus the template's. Ranking and `--targets` use the rollup total; JSON exposes the per-half breakdown under `component_rollup`.",
773 docs_path: "explanations/health#cognitive-complexity",
774 },
775 RuleDef {
776 id: "fallow/high-complexity",
777 category: "Health",
778 name: "High Complexity (Both)",
779 short: "Function exceeds both complexity thresholds",
780 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. The same rule fires on synthetic `<template>` findings (Angular .html templates and inline `@Component({ template: ... })` literals) when both metrics exceed their thresholds, and on synthetic `<component>` rollup findings whose totals are the worst class method's score plus the template's. Ranking and `--targets` use the rollup totals; JSON exposes the per-half breakdown under `component_rollup`.",
781 docs_path: "explanations/health#complexity-metrics",
782 },
783 RuleDef {
784 id: "fallow/high-crap-score",
785 category: "Health",
786 name: "High CRAP Score",
787 short: "Function has a high CRAP score (complexity combined with low coverage)",
788 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.",
789 docs_path: "explanations/health#crap-score",
790 },
791 RuleDef {
792 id: "fallow/refactoring-target",
793 category: "Health",
794 name: "Refactoring Target",
795 short: "File identified as a high-priority refactoring candidate",
796 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.",
797 docs_path: "explanations/health#refactoring-targets",
798 },
799 RuleDef {
800 id: "fallow/untested-file",
801 category: "Health",
802 name: "Untested File",
803 short: "Runtime-reachable file has no test dependency path",
804 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.",
805 docs_path: "explanations/health#coverage-gaps",
806 },
807 RuleDef {
808 id: "fallow/untested-export",
809 category: "Health",
810 name: "Untested Export",
811 short: "Runtime-reachable export has no test dependency path",
812 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.",
813 docs_path: "explanations/health#coverage-gaps",
814 },
815 RuleDef {
816 id: "fallow/runtime-safe-to-delete",
817 category: "Health",
818 name: "Production Safe To Delete",
819 short: "Statically unused AND never invoked in production with V8 tracking",
820 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.",
821 docs_path: "explanations/health#runtime-coverage",
822 },
823 RuleDef {
824 id: "fallow/runtime-review-required",
825 category: "Health",
826 name: "Production Review Required",
827 short: "Statically used but never invoked in production",
828 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.",
829 docs_path: "explanations/health#runtime-coverage",
830 },
831 RuleDef {
832 id: "fallow/runtime-low-traffic",
833 category: "Health",
834 name: "Production Low Traffic",
835 short: "Function was invoked below the low-traffic threshold",
836 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.",
837 docs_path: "explanations/health#runtime-coverage",
838 },
839 RuleDef {
840 id: "fallow/runtime-coverage-unavailable",
841 category: "Health",
842 name: "Runtime Coverage Unavailable",
843 short: "Runtime coverage could not be resolved for this function",
844 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.",
845 docs_path: "explanations/health#runtime-coverage",
846 },
847 RuleDef {
848 id: "fallow/runtime-coverage",
849 category: "Health",
850 name: "Runtime Coverage",
851 short: "Runtime coverage finding",
852 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.",
853 docs_path: "explanations/health#runtime-coverage",
854 },
855 RuleDef {
856 id: "fallow/coverage-intelligence-risky-change",
857 category: "Health",
858 name: "Coverage Intelligence Risky Change",
859 short: "Changed hot path combines high CRAP and low test coverage",
860 full: "Coverage intelligence combined change scope, runtime hot-path evidence, low test coverage, and high CRAP into a risky-change finding. Add focused tests or split the change before merging.",
861 docs_path: "explanations/health#coverage-intelligence",
862 },
863 RuleDef {
864 id: "fallow/coverage-intelligence-delete",
865 category: "Health",
866 name: "Coverage Intelligence Delete",
867 short: "Static and runtime evidence indicate code can be deleted",
868 full: "Coverage intelligence combined static unused status, runtime cold evidence, and lack of test reachability into a high-confidence delete recommendation.",
869 docs_path: "explanations/health#coverage-intelligence",
870 },
871 RuleDef {
872 id: "fallow/coverage-intelligence-review",
873 category: "Health",
874 name: "Coverage Intelligence Review",
875 short: "Cold reachable uncovered code needs owner review",
876 full: "Coverage intelligence found code that is statically reachable but cold in runtime evidence, uncovered by tests, and ownership-risky. Route it to an owner before changing or deleting it.",
877 docs_path: "explanations/health#coverage-intelligence",
878 },
879 RuleDef {
880 id: "fallow/coverage-intelligence-refactor",
881 category: "Health",
882 name: "Coverage Intelligence Refactor",
883 short: "Hot covered code has high CRAP and should be refactored carefully",
884 full: "Coverage intelligence found hot production code that is covered by tests but still has high CRAP. Refactor carefully while preserving behavior.",
885 docs_path: "explanations/health#coverage-intelligence",
886 },
887];
888
889pub const DUPES_RULES: &[RuleDef] = &[RuleDef {
890 id: "fallow/code-duplication",
891 category: "Duplication",
892 name: "Code Duplication",
893 short: "Duplicated code block",
894 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.",
895 docs_path: "explanations/duplication#clone-groups",
896}];
897
898pub const FLAGS_RULES: &[RuleDef] = &[RuleDef {
899 id: "fallow/feature-flag",
900 category: "Flags",
901 name: "Feature Flags",
902 short: "Detected feature flag pattern",
903 full: "A feature flag pattern detected by `fallow flags`: environment-variable checks, flag SDK calls (LaunchDarkly, Unleash, and similar), or config-object lookups. Long-lived flags accumulate dead branches; review old flags for retirement and pair with dead-code analysis to find branches that can no longer execute.",
904 docs_path: "cli/flags",
905}];
906
907macro_rules! security_catalogue_rule {
908 ($id:literal, $name:literal, $cwe:literal) => {
909 RuleDef {
910 id: concat!("security/", $id),
911 category: "Security",
912 name: $name,
913 short: concat!("Catalogue security candidate for CWE-", $cwe),
914 full: concat!(
915 $name,
916 " is a data-driven `fallow security` tainted-sink catalogue category with CWE-",
917 $cwe,
918 " metadata. fallow reports it as an unverified candidate when a captured sink shape matches this category. Use it to understand or filter `security/",
919 $id,
920 "` findings, then inspect the trace, source, sink, sanitization, and application context before treating it as exploitable."
921 ),
922 docs_path: "cli/security",
923 }
924 };
925}
926
927pub const SECURITY_RULES: &[RuleDef] = &[
928 RuleDef {
929 id: "security/tainted-sink",
930 category: "Security",
931 name: "Tainted Sink Candidates",
932 short: "Syntactic security sink candidates require verification",
933 full: "The `tainted-sink` family covers data-driven `fallow security` catalogue categories. These findings are unverified candidates, not confirmed vulnerabilities. fallow can connect known source signals to captured sink shapes and add CWE metadata, but it does not prove attacker control, missing sanitization, exploitability, or business impact.",
934 docs_path: "cli/security",
935 },
936 RuleDef {
937 id: "security/client-server-leak",
938 category: "Security",
939 name: "Client-server Secret Leak Candidates",
940 short: "Client-bound code reaches a non-public env read",
941 full: "`client-server-leak` reports a candidate when a `use client` module can transitively reach a static non-public `process.env` or `import.meta.env` read. Public-by-convention env prefixes are treated as public. The finding is advisory and still needs bundle, framework, and runtime verification before treating it as a real exposure.",
942 docs_path: "cli/security",
943 },
944 RuleDef {
945 id: "security/hardcoded-secret",
946 category: "Security",
947 name: "Hardcoded Secret Candidates",
948 short: "Provider-prefixed or contextual secret literals require verification",
949 full: "`hardcoded-secret` reports opt-in candidates for provider-prefixed or contextual secret-shaped literals. The category is include-required and only runs when listed in `security.categories.include`. It avoids raw entropy alone, but every result still requires review, secret rotation decisions, and context before acting.",
950 docs_path: "cli/security",
951 },
952 security_catalogue_rule!("dangerous-html", "Dangerous HTML sink", "79"),
953 security_catalogue_rule!(
954 "template-escape-bypass",
955 "Template escape bypass sink",
956 "79"
957 ),
958 security_catalogue_rule!("command-injection", "OS command injection sink", "78"),
959 security_catalogue_rule!("code-injection", "Code injection sink", "94"),
960 security_catalogue_rule!("dynamic-regex", "Dynamic regular expression sink", "1333"),
961 security_catalogue_rule!("redos-regex", "ReDoS regex sink", "1333"),
962 security_catalogue_rule!(
963 "resource-amplification",
964 "Resource amplification sink",
965 "400"
966 ),
967 security_catalogue_rule!("dynamic-module-load", "Dynamic module load sink", "95"),
968 security_catalogue_rule!("sql-injection", "SQL injection sink", "89"),
969 security_catalogue_rule!("ssrf", "Server-side request forgery sink", "918"),
970 security_catalogue_rule!(
971 "secret-to-network",
972 "Secret reaches a network request",
973 "201"
974 ),
975 security_catalogue_rule!("path-traversal", "Path traversal sink", "22"),
976 security_catalogue_rule!(
977 "header-injection",
978 "HTTP response header injection sink",
979 "113"
980 ),
981 security_catalogue_rule!("open-redirect", "Open redirect sink", "601"),
982 security_catalogue_rule!(
983 "postmessage-wildcard-origin",
984 "Wildcard postMessage target origin",
985 "346"
986 ),
987 security_catalogue_rule!("tls-validation-disabled", "TLS validation disabled", "295"),
988 security_catalogue_rule!("cleartext-transport", "Cleartext transport URL", "319"),
989 security_catalogue_rule!(
990 "electron-unsafe-webpreferences",
991 "Unsafe Electron BrowserWindow preferences",
992 "1188"
993 ),
994 security_catalogue_rule!(
995 "world-writable-permission",
996 "World-writable chmod mode",
997 "732"
998 ),
999 security_catalogue_rule!(
1000 "insecure-temp-file",
1001 "Predictable temporary file path",
1002 "377"
1003 ),
1004 security_catalogue_rule!(
1005 "mysql-multiple-statements",
1006 "MySQL multiple statements enabled",
1007 "89"
1008 ),
1009 security_catalogue_rule!("permissive-cors", "Permissive CORS policy", "942"),
1010 security_catalogue_rule!("insecure-cookie", "Insecure cookie options", "614"),
1011 security_catalogue_rule!("mass-assignment", "Mass assignment sink", "915"),
1012 security_catalogue_rule!("weak-crypto", "Runtime-selectable crypto algorithm", "327"),
1013 security_catalogue_rule!("insecure-randomness", "Insecure randomness sink", "338"),
1014 security_catalogue_rule!("jwt-alg-none", "JWT alg none", "347"),
1015 security_catalogue_rule!(
1016 "jwt-verify-missing-algorithms",
1017 "JWT verify missing algorithms allowlist",
1018 "347"
1019 ),
1020 security_catalogue_rule!("deprecated-cipher", "Deprecated cipher constructor", "327"),
1021 security_catalogue_rule!(
1022 "unsafe-buffer-alloc",
1023 "Unsafe Buffer allocation sink",
1024 "1188"
1025 ),
1026 security_catalogue_rule!(
1027 "unsafe-deserialization",
1028 "Unsafe deserialization sink",
1029 "502"
1030 ),
1031 security_catalogue_rule!(
1032 "angular-trusted-html",
1033 "Angular bypassSecurityTrust sink",
1034 "79"
1035 ),
1036 security_catalogue_rule!("nextjs-open-redirect", "Next.js open redirect sink", "601"),
1037 security_catalogue_rule!("dom-document-write", "DOM document.write sink", "79"),
1038 security_catalogue_rule!("jquery-html", "jQuery .html() sink", "79"),
1039 security_catalogue_rule!(
1040 "route-send-file",
1041 "Route file-send path traversal sink",
1042 "22"
1043 ),
1044 security_catalogue_rule!("webview-injection", "WebView injected-script sink", "94"),
1045 security_catalogue_rule!("prototype-pollution", "Prototype pollution sink", "1321"),
1046 security_catalogue_rule!("zip-slip", "Archive path-traversal (zip-slip) sink", "22"),
1047 security_catalogue_rule!("nosql-injection", "NoSQL injection sink", "943"),
1048 security_catalogue_rule!("ssti", "Server-side template injection sink", "1336"),
1049 security_catalogue_rule!("xxe", "XML external entity (XXE) sink", "611"),
1050 security_catalogue_rule!("secret-pii-log", "Secret or PII logged", "532"),
1051 security_catalogue_rule!("xpath-injection", "XPath injection sink", "643"),
1052];
1053
1054#[must_use]
1056pub fn check_meta() -> Value {
1057 let rules: Value = CHECK_RULES
1058 .iter()
1059 .map(|r| {
1060 (
1061 r.id.replace("fallow/", ""),
1062 json!({
1063 "name": r.name,
1064 "description": r.full,
1065 "docs": rule_docs_url(r)
1066 }),
1067 )
1068 })
1069 .collect::<serde_json::Map<String, Value>>()
1070 .into();
1071
1072 json!({
1073 "docs": CHECK_DOCS,
1074 "rules": rules,
1075 "field_definitions": {
1076 "actions[]": ACTIONS_FIELD_DEFINITION,
1077 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
1078 }
1079 })
1080}
1081
1082#[must_use]
1084pub fn combined_meta(include_check: bool, include_dupes: bool, include_health: bool) -> Value {
1085 let mut sections = serde_json::Map::new();
1086 if include_check {
1087 sections.insert("check".to_string(), check_meta());
1088 }
1089 if include_dupes {
1090 sections.insert("dupes".to_string(), dupes_meta());
1091 }
1092 if include_health {
1093 sections.insert("health".to_string(), health_meta());
1094 }
1095 Value::Object(sections)
1096}
1097
1098#[must_use]
1100pub fn health_meta() -> Value {
1101 json!({
1102 "docs": HEALTH_DOCS,
1103 "field_definitions": {
1104 "actions[]": ACTIONS_FIELD_DEFINITION,
1105 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
1106 },
1107 "metrics": health_metrics()
1108 })
1109}
1110
1111fn health_metrics() -> Value {
1112 let mut metrics = serde_json::Map::new();
1113 for section in [
1114 health_size_complexity_metrics(),
1115 health_quality_metrics(),
1116 health_coupling_metrics(),
1117 health_churn_metrics(),
1118 health_refactoring_rank_metrics(),
1119 health_refactoring_confidence_metrics(),
1120 health_risk_metrics(),
1121 health_contributor_metrics(),
1122 health_ownership_metrics(),
1123 health_runtime_verdict_metrics(),
1124 health_runtime_observation_metrics(),
1125 health_runtime_production_metrics(),
1126 ] {
1127 let Value::Object(section) = section else {
1128 continue;
1129 };
1130 metrics.extend(section);
1131 }
1132 Value::Object(metrics)
1133}
1134
1135fn health_size_complexity_metrics() -> Value {
1136 json!({
1137 "cyclomatic": {
1138 "name": "Cyclomatic Complexity",
1139 "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.",
1140 "range": "[1, \u{221e})",
1141 "interpretation": "lower is better; default threshold: 20"
1142 },
1143 "cognitive": {
1144 "name": "Cognitive Complexity",
1145 "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.",
1146 "range": "[0, \u{221e})",
1147 "interpretation": "lower is better; default threshold: 15"
1148 },
1149 "line_count": {
1150 "name": "Function Line Count",
1151 "description": "Number of lines in the function body.",
1152 "range": "[1, \u{221e})",
1153 "interpretation": "context-dependent; long functions may need splitting"
1154 },
1155 "lines": {
1156 "name": "File Line Count",
1157 "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.",
1158 "range": "[1, \u{221e})",
1159 "interpretation": "context-dependent; large files may benefit from splitting even if individual functions are small"
1160 }
1161 })
1162}
1163
1164fn health_quality_metrics() -> Value {
1165 json!({
1166 "maintainability_index": {
1167 "name": "Maintainability Index",
1168 "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.",
1169 "range": "[0, 100]",
1170 "interpretation": "higher is better; <40 poor, 40\u{2013}70 moderate, >70 good"
1171 },
1172 "complexity_density": {
1173 "name": "Complexity Density",
1174 "description": "Total cyclomatic complexity divided by lines of code. Measures how densely complex the code is per line.",
1175 "range": "[0, \u{221e})",
1176 "interpretation": "lower is better; >1.0 indicates very dense complexity"
1177 },
1178 "dead_code_ratio": {
1179 "name": "Dead Code Ratio",
1180 "description": "Fraction of value exports (excluding type-only exports like interfaces and type aliases) with zero references across the project.",
1181 "range": "[0, 1]",
1182 "interpretation": "lower is better; 0 = all exports are used"
1183 }
1184 })
1185}
1186
1187fn health_coupling_metrics() -> Value {
1188 json!({
1189 "fan_in": {
1190 "name": "Fan-in (Importers)",
1191 "description": "Number of files that import this file. High fan-in means high blast radius \u{2014} changes to this file affect many dependents.",
1192 "range": "[0, \u{221e})",
1193 "interpretation": "context-dependent; high fan-in files need careful review before changes"
1194 },
1195 "fan_out": {
1196 "name": "Fan-out (Imports)",
1197 "description": "Number of files this file directly imports. High fan-out indicates high coupling and change propagation risk.",
1198 "range": "[0, \u{221e})",
1199 "interpretation": "lower is better; MI penalty caps at ~40 imports"
1200 },
1201 })
1202}
1203
1204fn health_churn_metrics() -> Value {
1205 json!({
1206 "score": {
1207 "name": "Hotspot Score",
1208 "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.",
1209 "range": "[0, 100]",
1210 "interpretation": "higher = riskier; prioritize refactoring high-score files"
1211 },
1212 "weighted_commits": {
1213 "name": "Weighted Commits",
1214 "description": "Recency-weighted commit count using exponential decay with 90-day half-life. Recent commits contribute more than older ones.",
1215 "range": "[0, \u{221e})",
1216 "interpretation": "higher = more recent churn activity"
1217 },
1218 "trend": {
1219 "name": "Churn Trend",
1220 "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.",
1221 "values": ["accelerating", "stable", "cooling"],
1222 "interpretation": "accelerating files need attention; cooling files are stabilizing"
1223 }
1224 })
1225}
1226
1227fn health_refactoring_rank_metrics() -> Value {
1228 json!({
1229 "priority": {
1230 "name": "Refactoring Priority",
1231 "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.",
1232 "range": "[0, 100]",
1233 "interpretation": "higher = more urgent to refactor"
1234 },
1235 "efficiency": {
1236 "name": "Efficiency Score",
1237 "description": "priority / effort_numeric (Low=1, Medium=2, High=3). Surfaces quick wins: high-priority, low-effort targets rank first. Default sort order.",
1238 "range": "[0, 100] \u{2014} effective max depends on effort: Low=100, Medium=50, High\u{2248}33",
1239 "interpretation": "higher = better quick-win value; targets are sorted by efficiency descending"
1240 },
1241 "effort": {
1242 "name": "Effort Estimate",
1243 "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.",
1244 "values": ["low", "medium", "high"],
1245 "interpretation": "low = quick win, high = needs planning and coordination"
1246 },
1247 })
1248}
1249
1250fn health_refactoring_confidence_metrics() -> Value {
1251 json!({
1252 "confidence": {
1253 "name": "Confidence Level",
1254 "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).",
1255 "values": ["high", "medium", "low"],
1256 "interpretation": "high = act on it, medium = verify context, low = treat as a signal, not a directive"
1257 },
1258 "health_score": {
1259 "name": "Health Score",
1260 "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.",
1261 "range": "[0, 100]",
1262 "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)"
1263 }
1264 })
1265}
1266
1267fn health_risk_metrics() -> Value {
1268 json!({
1269 "crap_max": {
1270 "name": "Untested Complexity Risk (CRAP)",
1271 "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.",
1272 "range": "[1, \u{221e})",
1273 "interpretation": "lower is better; >=30 is high-risk (CC >= 5 without test path)"
1274 },
1275 })
1276}
1277
1278fn health_contributor_metrics() -> Value {
1279 json!({
1280 "bus_factor": {
1281 "name": "Bus Factor",
1282 "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.",
1283 "range": "[1, \u{221e})",
1284 "interpretation": "lower is higher knowledge-loss risk; 1 means a single contributor covers most of the recent history"
1285 },
1286 "contributor_count": {
1287 "name": "Contributor Count",
1288 "description": "Number of distinct authors who touched this file in the analysis window after bot-pattern filtering.",
1289 "range": "[0, \u{221e})",
1290 "interpretation": "higher generally indicates broader knowledge spread; pair with bus_factor for context"
1291 },
1292 "share": {
1293 "name": "Contributor Share",
1294 "description": "Recency-weighted share of total weighted commits attributed to a single contributor. Rounded to three decimals.",
1295 "range": "[0, 1]",
1296 "interpretation": "share close to 1.0 indicates dominance and pairs with low bus_factor"
1297 },
1298 })
1299}
1300
1301fn health_ownership_metrics() -> Value {
1302 json!({
1303 "stale_days": {
1304 "name": "Stale Days",
1305 "description": "Days since this contributor last touched the file. Computed at analysis time.",
1306 "range": "[0, \u{221e})",
1307 "interpretation": "high stale_days on the top contributor often correlates with ownership drift"
1308 },
1309 "drift": {
1310 "name": "Ownership Drift",
1311 "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%.",
1312 "values": [true, false],
1313 "interpretation": "true means the original author is no longer maintaining; route reviews to the current top contributor"
1314 },
1315 "unowned": {
1316 "name": "Unowned (Tristate)",
1317 "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).",
1318 "values": [true, false, null],
1319 "interpretation": "true on a hotspot is a review-bottleneck risk; null means the signal is unavailable, not absent"
1320 }
1321 })
1322}
1323
1324fn health_runtime_verdict_metrics() -> Value {
1325 json!({
1326 "runtime_coverage_verdict": {
1327 "name": "Runtime Coverage Verdict",
1328 "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).",
1329 "values": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
1330 "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."
1331 },
1332 })
1333}
1334
1335fn health_runtime_observation_metrics() -> Value {
1336 json!({
1337 "runtime_coverage_state": {
1338 "name": "Runtime Coverage State",
1339 "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.",
1340 "values": ["called", "never-called", "coverage-unavailable", "unknown"],
1341 "interpretation": "`never-called` in combination with static `unused` is the highest-confidence delete signal"
1342 },
1343 "runtime_coverage_confidence": {
1344 "name": "Runtime Coverage Confidence",
1345 "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.",
1346 "values": ["high", "medium", "low", "unknown"],
1347 "interpretation": "high = act on it; medium = verify context; low = treat as a signal only"
1348 }
1349 })
1350}
1351
1352fn health_runtime_production_metrics() -> Value {
1353 json!({
1354 "production_invocations": {
1355 "name": "Production Invocations",
1356 "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.",
1357 "range": "[0, \u{221e})",
1358 "interpretation": "0 + tracked = cold path; 0 + untracked = unknown; high + never-called cannot occur by definition"
1359 },
1360 "percent_dead_in_production": {
1361 "name": "Percent Dead in Production",
1362 "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.",
1363 "range": "[0, 100]",
1364 "interpretation": "lower is better; values above ~10% on a long-running service indicate a large cleanup opportunity"
1365 }
1366 })
1367}
1368
1369#[must_use]
1371pub fn dupes_meta() -> Value {
1372 json!({
1373 "docs": DUPES_DOCS,
1374 "field_definitions": {
1375 "actions[]": ACTIONS_FIELD_DEFINITION,
1376 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
1377 },
1378 "metrics": {
1379 "duplication_percentage": {
1380 "name": "Duplication Percentage",
1381 "description": "Fraction of total source tokens that appear in at least one clone group. Computed over the full analyzed file set.",
1382 "range": "[0, 100]",
1383 "interpretation": "lower is better"
1384 },
1385 "token_count": {
1386 "name": "Token Count",
1387 "description": "Number of normalized source tokens in the clone group. Tokens are language-aware (keywords, identifiers, operators, punctuation). Higher token count = larger duplicate.",
1388 "range": "[1, \u{221e})",
1389 "interpretation": "larger clones have higher refactoring value"
1390 },
1391 "line_count": {
1392 "name": "Line Count",
1393 "description": "Number of source lines spanned by the clone instance. Approximation of clone size for human readability.",
1394 "range": "[1, \u{221e})",
1395 "interpretation": "larger clones are more impactful to deduplicate"
1396 },
1397 "clone_groups": {
1398 "name": "Clone Groups",
1399 "description": "A set of code fragments with identical or near-identical normalized token sequences. Each group has 2+ instances across different locations.",
1400 "interpretation": "each group is a single refactoring opportunity"
1401 },
1402 "clone_groups_below_min_occurrences": {
1403 "name": "Clone Groups Below minOccurrences",
1404 "description": "Number of clone groups detected but hidden by the `duplicates.minOccurrences` filter. Always 0 (or absent) when the filter is at its default of 2. Pre-filter group count = `clone_groups + clone_groups_below_min_occurrences`.",
1405 "range": "[0, \u{221e})",
1406 "interpretation": "high values suggest noisy pair-only duplication; lower `minOccurrences` to inspect"
1407 },
1408 "clone_families": {
1409 "name": "Clone Families",
1410 "description": "Groups of clone groups that share the same set of files. Indicates systematic duplication patterns (e.g., mirrored directory structures).",
1411 "interpretation": "families suggest extract-module refactoring opportunities"
1412 }
1413 }
1414 })
1415}
1416
1417#[must_use]
1419pub fn security_meta() -> Meta {
1420 let rules = SECURITY_RULES
1421 .iter()
1422 .map(|rule| {
1423 (
1424 rule.id.to_string(),
1425 MetaRule {
1426 name: Some(rule.name.to_string()),
1427 description: Some(rule.full.to_string()),
1428 docs: Some(rule_docs_url(rule)),
1429 },
1430 )
1431 })
1432 .collect();
1433
1434 Meta {
1435 docs: Some(SECURITY_DOCS.to_string()),
1436 telemetry: None,
1437 field_definitions: BTreeMap::from([
1438 (
1439 "version".to_string(),
1440 "fallow CLI version that produced this output.".to_string(),
1441 ),
1442 (
1443 "elapsed_ms".to_string(),
1444 "Wall-clock milliseconds spent producing the security report.".to_string(),
1445 ),
1446 (
1447 "config".to_string(),
1448 "Privacy-safe config context relevant to security candidate generation."
1449 .to_string(),
1450 ),
1451 (
1452 "config.rules.*.configured".to_string(),
1453 "Severity from resolved config before the security command forced default-off rules on."
1454 .to_string(),
1455 ),
1456 (
1457 "config.rules.*.effective".to_string(),
1458 "Severity used for this security command run.".to_string(),
1459 ),
1460 (
1461 "config.categories_include".to_string(),
1462 "Configured security category include list. null means unset, [] means explicitly empty."
1463 .to_string(),
1464 ),
1465 (
1466 "config.categories_exclude".to_string(),
1467 "Configured security category exclude list. null means unset, [] means explicitly empty."
1468 .to_string(),
1469 ),
1470 (
1471 "security_findings[]".to_string(),
1472 "Unverified security candidates for downstream human or agent verification."
1473 .to_string(),
1474 ),
1475 (
1476 "summary.security_findings".to_string(),
1477 "Number of security candidates after all filters, gates, and scopes.".to_string(),
1478 ),
1479 (
1480 "summary.by_severity".to_string(),
1481 "Fixed high, medium, and low severity counts for summary JSON.".to_string(),
1482 ),
1483 (
1484 "summary.by_category".to_string(),
1485 "Candidate counts by catalogue category, or by kind for uncategorized findings."
1486 .to_string(),
1487 ),
1488 (
1489 "summary.by_reachability".to_string(),
1490 "Fixed reachability and source-backed ranking-signal counts for summary JSON."
1491 .to_string(),
1492 ),
1493 (
1494 "summary.by_runtime_state".to_string(),
1495 "Fixed production-runtime coverage state counts for summary JSON.".to_string(),
1496 ),
1497 (
1498 "unresolved_edge_files".to_string(),
1499 "Number of client files whose import cone contains dynamic edges the graph could not follow."
1500 .to_string(),
1501 ),
1502 (
1503 "unresolved_callee_sites".to_string(),
1504 "Number of sink-shaped nodes whose callee could not be flattened to a static path."
1505 .to_string(),
1506 ),
1507 ]),
1508 metrics: BTreeMap::new(),
1509 rules,
1510 }
1511}
1512
1513#[must_use]
1515pub fn coverage_setup_meta() -> Value {
1516 json!({
1517 "docs_url": COVERAGE_SETUP_DOCS,
1518 "field_definitions": {
1519 "schema_version": "Coverage setup JSON contract version. Stays at \"1\" for additive opt-in fields such as _meta.",
1520 "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.",
1521 "package_manager": "Detected package manager used for install and run commands, or null when no package manager signal was found.",
1522 "runtime_targets": "Union of runtime targets across emitted members.",
1523 "members[]": "Per-runtime-workspace setup recipes. Pure aggregator roots and build-only libraries are omitted.",
1524 "members[].name": "Workspace package name from package.json, or the root directory name when package.json has no name.",
1525 "members[].path": "Workspace path relative to the command root. The root package is represented as \".\".",
1526 "members[].framework_detected": "Runtime framework detected for that member.",
1527 "members[].package_manager": "Package manager detected for that member, or inherited from the workspace root when no member-specific signal exists.",
1528 "members[].runtime_targets": "Runtime targets produced by that member.",
1529 "members[].files_to_edit": "Files in that member that should receive runtime beacon setup code.",
1530 "members[].snippets": "Copy-paste setup snippets for that member, with paths relative to the command root.",
1531 "members[].dockerfile_snippet": "Environment snippet for file-system capture in that member's containerized Node runtime, or null when not applicable.",
1532 "members[].warnings": "Actionable setup caveats discovered for that member.",
1533 "config_written": "Always null for --json because JSON setup is side-effect-free and never writes configuration.",
1534 "files_to_edit": "Compatibility copy of the primary member's files, with workspace prefixes when the primary member is not the root.",
1535 "snippets": "Compatibility copy of the primary member's snippets, with workspace prefixes when the primary member is not the root.",
1536 "dockerfile_snippet": "Environment snippet for file-system capture in containerized Node runtimes, or null when not applicable.",
1537 "commands": "Package-manager commands needed to install the runtime beacon and sidecar packages.",
1538 "next_steps": "Ordered setup workflow after applying the emitted snippets.",
1539 "warnings": "Actionable setup caveats discovered while building the recipe."
1540 },
1541 "enums": {
1542 "framework_detected": ["nextjs", "nestjs", "nuxt", "sveltekit", "astro", "remix", "vite", "plain_node", "unknown"],
1543 "runtime_targets": ["node", "browser"],
1544 "package_manager": ["npm", "pnpm", "yarn", "bun", null]
1545 },
1546 "warnings": {
1547 "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.",
1548 "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.",
1549 "Package manager was not detected": "No packageManager field or known lockfile was found. Commands fall back to npm.",
1550 "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."
1551 }
1552 })
1553}
1554
1555#[must_use]
1557pub fn coverage_analyze_meta() -> Value {
1558 json!({
1559 "docs_url": COVERAGE_ANALYZE_DOCS,
1560 "field_definitions": {
1561 "schema_version": "Standalone coverage analyze envelope version. \"1\" for the current shape.",
1562 "version": "fallow CLI version that produced this output.",
1563 "elapsed_ms": "Wall-clock milliseconds spent producing the report.",
1564 "runtime_coverage": "Same RuntimeCoverageReport block emitted by `fallow health --runtime-coverage`.",
1565 "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.",
1566 "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.",
1567 "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.",
1568 "runtime_coverage.findings[].id": "Per-finding SUPPRESSION key (fallow:prod:<hash>). Hashes file + function + the current line, so it changes when the function moves. Use it to suppress one finding at its current location.",
1569 "runtime_coverage.findings[].stable_id": "Cross-surface JOIN key (fallow:fn:<hash>) from fallow_cov_protocol::function_identity_id, hashing file + name + start_line. The same function shares ONE value across findings, hot paths, blast-radius, and importance entries (the per-finding id uses a per-surface salt and differs), and across V8/Istanbul/oxc producers (columns are excluded from the hash). Like id, it changes when the function's file, name, or start line changes: it is a cross-surface/cross-producer join key, NOT a line-move-immune one. Omitted from the JSON entirely (not emitted as null) when the producing surface or an un-migrated cloud supplied no FunctionIdentity. New baselines key on this when present to align with the cross-surface join key; the grace-window reader accepts the legacy id too.",
1570 "runtime_coverage._matching": "Function-identity fallback order when joining runtime evidence to local static analysis: (1) exact stable_id match (fallow:fn:<hash>) when both sides carry one; (2) exact (path, name, start_line); (3) fuzzy nearest candidate within a line tolerance. Baseline suppression accepts BOTH the stable_id and the legacy fallow:prod: id during the grace window, so baselines written before this version keep suppressing.",
1571 "runtime_coverage.findings[].evidence.static_status": "used = the function is reachable in the AST module graph; unused = it is dead by static analysis.",
1572 "runtime_coverage.findings[].evidence.test_coverage": "covered = the local test suite hits the function; not_covered otherwise.",
1573 "runtime_coverage.findings[].evidence.v8_tracking": "tracked = V8 observed the function during the capture window; untracked otherwise.",
1574 "runtime_coverage.findings[].actions[].type": "Suggested follow-up identifier. delete-cold-code is emitted on safe_to_delete; review-runtime on review_required.",
1575 "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.",
1576 "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.",
1577 "runtime_coverage.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally."
1578 },
1579 "enums": {
1580 "data_source": ["local", "cloud"],
1581 "report_verdict": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
1582 "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
1583 "static_status": ["used", "unused"],
1584 "test_coverage": ["covered", "not_covered"],
1585 "v8_tracking": ["tracked", "untracked"],
1586 "action_type": ["delete-cold-code", "review-runtime"]
1587 },
1588 "warnings": {
1589 "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
1590 "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."
1591 }
1592 })
1593}
1594
1595#[cfg(test)]
1596mod tests {
1597 use super::*;
1598
1599 #[test]
1600 fn rule_by_id_finds_check_rule() {
1601 let rule = rule_by_id("fallow/unused-file").unwrap();
1602 assert_eq!(rule.name, "Unused Files");
1603 }
1604
1605 #[test]
1606 fn rule_by_id_finds_health_rule() {
1607 let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1608 assert_eq!(rule.name, "High Cyclomatic Complexity");
1609 }
1610
1611 #[test]
1612 fn rule_by_id_finds_dupes_rule() {
1613 let rule = rule_by_id("fallow/code-duplication").unwrap();
1614 assert_eq!(rule.name, "Code Duplication");
1615 }
1616
1617 #[test]
1618 fn rule_by_id_finds_security_rule() {
1619 let rule = rule_by_id("security/tainted-sink").unwrap();
1620 assert_eq!(rule.name, "Tainted Sink Candidates");
1621 }
1622
1623 #[test]
1624 fn rule_by_id_returns_none_for_unknown() {
1625 assert!(rule_by_id("fallow/nonexistent").is_none());
1626 assert!(rule_by_id("").is_none());
1627 }
1628
1629 #[test]
1630 fn rule_docs_url_format() {
1631 let rule = rule_by_id("fallow/unused-export").unwrap();
1632 let url = rule_docs_url(rule);
1633 assert!(url.starts_with("https://docs.fallow.tools/"));
1634 assert!(url.contains("unused-exports"));
1635 }
1636
1637 #[test]
1638 fn check_rules_all_have_fallow_prefix() {
1639 for rule in CHECK_RULES {
1640 assert!(
1641 rule.id.starts_with("fallow/"),
1642 "rule {} should start with fallow/",
1643 rule.id
1644 );
1645 }
1646 }
1647
1648 #[test]
1649 fn check_rules_all_have_docs_path() {
1650 for rule in CHECK_RULES {
1651 assert!(
1652 !rule.docs_path.is_empty(),
1653 "rule {} should have a docs_path",
1654 rule.id
1655 );
1656 }
1657 }
1658
1659 #[test]
1660 fn check_rules_no_duplicate_ids() {
1661 let mut seen = rustc_hash::FxHashSet::default();
1662 for rule in CHECK_RULES
1663 .iter()
1664 .chain(HEALTH_RULES)
1665 .chain(DUPES_RULES)
1666 .chain(FLAGS_RULES)
1667 .chain(SECURITY_RULES)
1668 {
1669 assert!(seen.insert(rule.id), "duplicate rule id: {}", rule.id);
1670 }
1671 }
1672
1673 #[test]
1674 fn check_meta_has_docs_and_rules() {
1675 let meta = check_meta();
1676 assert!(meta.get("docs").is_some());
1677 assert!(meta.get("rules").is_some());
1678 let rules = meta["rules"].as_object().unwrap();
1679 assert_eq!(rules.len(), CHECK_RULES.len());
1680 assert!(rules.contains_key("unused-file"));
1681 assert!(rules.contains_key("unused-export"));
1682 assert!(rules.contains_key("unused-type"));
1683 assert!(rules.contains_key("unused-dependency"));
1684 assert!(rules.contains_key("unused-dev-dependency"));
1685 assert!(rules.contains_key("unused-optional-dependency"));
1686 assert!(rules.contains_key("unused-enum-member"));
1687 assert!(rules.contains_key("unused-class-member"));
1688 assert!(rules.contains_key("unresolved-import"));
1689 assert!(rules.contains_key("unlisted-dependency"));
1690 assert!(rules.contains_key("duplicate-export"));
1691 assert!(rules.contains_key("type-only-dependency"));
1692 assert!(rules.contains_key("circular-dependency"));
1693 }
1694
1695 #[test]
1696 fn check_meta_documents_per_finding_auto_fixable() {
1697 let meta = check_meta();
1698 let defs = meta["field_definitions"].as_object().unwrap();
1699 let note = defs["actions[].auto_fixable"].as_str().unwrap();
1700 assert!(
1701 note.contains("PER FINDING"),
1702 "auto_fixable note must call out per-finding evaluation"
1703 );
1704 assert!(
1705 note.contains("remove-catalog-entry"),
1706 "auto_fixable note must cite remove-catalog-entry per-instance flip"
1707 );
1708 assert!(
1709 note.contains("used_in_workspaces"),
1710 "auto_fixable note must cite the dependency-action per-instance flip"
1711 );
1712 assert!(
1713 note.contains("ignoreExports"),
1714 "auto_fixable note must cite the duplicate-exports config-fixable flip"
1715 );
1716 assert!(defs.contains_key("actions[]"));
1717 }
1718
1719 #[test]
1720 fn health_and_dupes_meta_share_actions_field_definitions() {
1721 for meta in [health_meta(), dupes_meta()] {
1722 let defs = meta["field_definitions"].as_object().unwrap();
1723 assert_eq!(
1724 defs["actions[]"].as_str().unwrap(),
1725 ACTIONS_FIELD_DEFINITION,
1726 );
1727 assert_eq!(
1728 defs["actions[].auto_fixable"].as_str().unwrap(),
1729 ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION,
1730 );
1731 }
1732 }
1733
1734 #[test]
1735 fn check_meta_rule_has_required_fields() {
1736 let meta = check_meta();
1737 let rules = meta["rules"].as_object().unwrap();
1738 for (key, value) in rules {
1739 assert!(value.get("name").is_some(), "rule {key} missing 'name'");
1740 assert!(
1741 value.get("description").is_some(),
1742 "rule {key} missing 'description'"
1743 );
1744 assert!(value.get("docs").is_some(), "rule {key} missing 'docs'");
1745 }
1746 }
1747
1748 #[test]
1749 fn health_meta_has_metrics() {
1750 let meta = health_meta();
1751 assert!(meta.get("docs").is_some());
1752 let metrics = meta["metrics"].as_object().unwrap();
1753 assert!(metrics.contains_key("cyclomatic"));
1754 assert!(metrics.contains_key("cognitive"));
1755 assert!(metrics.contains_key("maintainability_index"));
1756 assert!(metrics.contains_key("complexity_density"));
1757 assert!(metrics.contains_key("fan_in"));
1758 assert!(metrics.contains_key("fan_out"));
1759 }
1760
1761 #[test]
1762 fn dupes_meta_has_metrics() {
1763 let meta = dupes_meta();
1764 assert!(meta.get("docs").is_some());
1765 let metrics = meta["metrics"].as_object().unwrap();
1766 assert!(metrics.contains_key("duplication_percentage"));
1767 assert!(metrics.contains_key("token_count"));
1768 assert!(metrics.contains_key("clone_groups"));
1769 assert!(metrics.contains_key("clone_families"));
1770 }
1771
1772 #[test]
1773 fn coverage_setup_meta_has_docs_fields_enums_and_warnings() {
1774 let meta = coverage_setup_meta();
1775 assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
1776 assert!(
1777 meta["field_definitions"]
1778 .as_object()
1779 .unwrap()
1780 .contains_key("members[]")
1781 );
1782 assert!(
1783 meta["field_definitions"]
1784 .as_object()
1785 .unwrap()
1786 .contains_key("config_written")
1787 );
1788 assert!(
1789 meta["field_definitions"]
1790 .as_object()
1791 .unwrap()
1792 .contains_key("members[].package_manager")
1793 );
1794 assert!(
1795 meta["field_definitions"]
1796 .as_object()
1797 .unwrap()
1798 .contains_key("members[].warnings")
1799 );
1800 assert!(
1801 meta["enums"]
1802 .as_object()
1803 .unwrap()
1804 .contains_key("framework_detected")
1805 );
1806 assert!(
1807 meta["warnings"]
1808 .as_object()
1809 .unwrap()
1810 .contains_key("No runtime workspace members were detected")
1811 );
1812 assert!(
1813 meta["warnings"]
1814 .as_object()
1815 .unwrap()
1816 .contains_key("Package manager was not detected")
1817 );
1818 }
1819
1820 #[test]
1821 fn coverage_analyze_meta_documents_data_source_and_action_vocabulary() {
1822 let meta = coverage_analyze_meta();
1823 assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
1824 let fields = meta["field_definitions"].as_object().unwrap();
1825 assert!(fields.contains_key("runtime_coverage.summary.data_source"));
1826 assert!(fields.contains_key("runtime_coverage.summary.last_received_at"));
1827 assert!(fields.contains_key("runtime_coverage.findings[].evidence.test_coverage"));
1828 assert!(fields.contains_key("runtime_coverage.findings[].actions[].type"));
1829 let enums = meta["enums"].as_object().unwrap();
1830 assert_eq!(enums["data_source"], json!(["local", "cloud"]));
1831 assert_eq!(enums["test_coverage"], json!(["covered", "not_covered"]));
1832 assert_eq!(enums["v8_tracking"], json!(["tracked", "untracked"]));
1833 assert_eq!(
1834 enums["action_type"],
1835 json!(["delete-cold-code", "review-runtime"])
1836 );
1837 let warnings = meta["warnings"].as_object().unwrap();
1838 assert!(warnings.contains_key("cloud_functions_unmatched"));
1839 }
1840
1841 #[test]
1842 fn health_rules_all_have_fallow_prefix() {
1843 for rule in HEALTH_RULES {
1844 assert!(
1845 rule.id.starts_with("fallow/"),
1846 "health rule {} should start with fallow/",
1847 rule.id
1848 );
1849 }
1850 }
1851
1852 #[test]
1853 fn health_rules_all_have_docs_path() {
1854 for rule in HEALTH_RULES {
1855 assert!(
1856 !rule.docs_path.is_empty(),
1857 "health rule {} should have a docs_path",
1858 rule.id
1859 );
1860 }
1861 }
1862
1863 #[test]
1864 fn health_rules_all_have_non_empty_fields() {
1865 for rule in HEALTH_RULES {
1866 assert!(
1867 !rule.name.is_empty(),
1868 "health rule {} missing name",
1869 rule.id
1870 );
1871 assert!(
1872 !rule.short.is_empty(),
1873 "health rule {} missing short description",
1874 rule.id
1875 );
1876 assert!(
1877 !rule.full.is_empty(),
1878 "health rule {} missing full description",
1879 rule.id
1880 );
1881 }
1882 }
1883
1884 #[test]
1885 fn dupes_rules_all_have_fallow_prefix() {
1886 for rule in DUPES_RULES {
1887 assert!(
1888 rule.id.starts_with("fallow/"),
1889 "dupes rule {} should start with fallow/",
1890 rule.id
1891 );
1892 }
1893 }
1894
1895 #[test]
1896 fn dupes_rules_all_have_docs_path() {
1897 for rule in DUPES_RULES {
1898 assert!(
1899 !rule.docs_path.is_empty(),
1900 "dupes rule {} should have a docs_path",
1901 rule.id
1902 );
1903 }
1904 }
1905
1906 #[test]
1907 fn dupes_rules_all_have_non_empty_fields() {
1908 for rule in DUPES_RULES {
1909 assert!(!rule.name.is_empty(), "dupes rule {} missing name", rule.id);
1910 assert!(
1911 !rule.short.is_empty(),
1912 "dupes rule {} missing short description",
1913 rule.id
1914 );
1915 assert!(
1916 !rule.full.is_empty(),
1917 "dupes rule {} missing full description",
1918 rule.id
1919 );
1920 }
1921 }
1922
1923 #[test]
1924 fn security_rules_all_have_security_prefix() {
1925 for rule in SECURITY_RULES {
1926 assert!(
1927 rule.id.starts_with("security/"),
1928 "security rule {} should start with security/",
1929 rule.id
1930 );
1931 }
1932 }
1933
1934 #[test]
1935 fn security_rules_all_have_docs_path() {
1936 for rule in SECURITY_RULES {
1937 assert_eq!(
1938 rule.docs_path, "cli/security",
1939 "security rule {} should point at security docs",
1940 rule.id
1941 );
1942 }
1943 }
1944
1945 #[test]
1946 fn security_rules_all_have_non_empty_fields() {
1947 for rule in SECURITY_RULES {
1948 assert!(
1949 !rule.name.is_empty(),
1950 "security rule {} missing name",
1951 rule.id
1952 );
1953 assert!(
1954 !rule.short.is_empty(),
1955 "security rule {} missing short description",
1956 rule.id
1957 );
1958 assert!(
1959 !rule.full.is_empty(),
1960 "security rule {} missing full description",
1961 rule.id
1962 );
1963 }
1964 }
1965
1966 #[test]
1967 fn check_rules_all_have_non_empty_fields() {
1968 for rule in CHECK_RULES {
1969 assert!(!rule.name.is_empty(), "check rule {} missing name", rule.id);
1970 assert!(
1971 !rule.short.is_empty(),
1972 "check rule {} missing short description",
1973 rule.id
1974 );
1975 assert!(
1976 !rule.full.is_empty(),
1977 "check rule {} missing full description",
1978 rule.id
1979 );
1980 }
1981 }
1982
1983 #[test]
1984 fn rule_docs_url_health_rule() {
1985 let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1986 let url = rule_docs_url(rule);
1987 assert!(url.starts_with("https://docs.fallow.tools/"));
1988 assert!(url.contains("health"));
1989 }
1990
1991 #[test]
1992 fn rule_docs_url_dupes_rule() {
1993 let rule = rule_by_id("fallow/code-duplication").unwrap();
1994 let url = rule_docs_url(rule);
1995 assert!(url.starts_with("https://docs.fallow.tools/"));
1996 assert!(url.contains("duplication"));
1997 }
1998
1999 #[test]
2000 fn rule_docs_url_security_rule() {
2001 let rule = rule_by_id("security/sql-injection").unwrap();
2002 let url = rule_docs_url(rule);
2003 assert_eq!(url, "https://docs.fallow.tools/cli/security");
2004 }
2005
2006 #[test]
2007 fn health_meta_all_metrics_have_name_and_description() {
2008 let meta = health_meta();
2009 let metrics = meta["metrics"].as_object().unwrap();
2010 for (key, value) in metrics {
2011 assert!(
2012 value.get("name").is_some(),
2013 "health metric {key} missing 'name'"
2014 );
2015 assert!(
2016 value.get("description").is_some(),
2017 "health metric {key} missing 'description'"
2018 );
2019 assert!(
2020 value.get("interpretation").is_some(),
2021 "health metric {key} missing 'interpretation'"
2022 );
2023 }
2024 }
2025
2026 #[test]
2027 fn health_meta_has_all_expected_metrics() {
2028 let meta = health_meta();
2029 let metrics = meta["metrics"].as_object().unwrap();
2030 let expected = [
2031 "cyclomatic",
2032 "cognitive",
2033 "line_count",
2034 "lines",
2035 "maintainability_index",
2036 "complexity_density",
2037 "dead_code_ratio",
2038 "fan_in",
2039 "fan_out",
2040 "score",
2041 "weighted_commits",
2042 "trend",
2043 "priority",
2044 "efficiency",
2045 "effort",
2046 "confidence",
2047 "bus_factor",
2048 "contributor_count",
2049 "share",
2050 "stale_days",
2051 "drift",
2052 "unowned",
2053 "runtime_coverage_verdict",
2054 "runtime_coverage_state",
2055 "runtime_coverage_confidence",
2056 "production_invocations",
2057 "percent_dead_in_production",
2058 ];
2059 for key in &expected {
2060 assert!(
2061 metrics.contains_key(*key),
2062 "health_meta missing expected metric: {key}"
2063 );
2064 }
2065 }
2066
2067 #[test]
2068 fn dupes_meta_all_metrics_have_name_and_description() {
2069 let meta = dupes_meta();
2070 let metrics = meta["metrics"].as_object().unwrap();
2071 for (key, value) in metrics {
2072 assert!(
2073 value.get("name").is_some(),
2074 "dupes metric {key} missing 'name'"
2075 );
2076 assert!(
2077 value.get("description").is_some(),
2078 "dupes metric {key} missing 'description'"
2079 );
2080 }
2081 }
2082
2083 #[test]
2084 fn dupes_meta_has_line_count() {
2085 let meta = dupes_meta();
2086 let metrics = meta["metrics"].as_object().unwrap();
2087 assert!(metrics.contains_key("line_count"));
2088 }
2089
2090 #[test]
2091 fn check_docs_url_valid() {
2092 assert!(CHECK_DOCS.starts_with("https://"));
2093 assert!(CHECK_DOCS.contains("dead-code"));
2094 }
2095
2096 #[test]
2097 fn health_docs_url_valid() {
2098 assert!(HEALTH_DOCS.starts_with("https://"));
2099 assert!(HEALTH_DOCS.contains("health"));
2100 }
2101
2102 #[test]
2103 fn dupes_docs_url_valid() {
2104 assert!(DUPES_DOCS.starts_with("https://"));
2105 assert!(DUPES_DOCS.contains("dupes"));
2106 }
2107
2108 #[test]
2109 fn check_meta_docs_url_matches_constant() {
2110 let meta = check_meta();
2111 assert_eq!(meta["docs"].as_str().unwrap(), CHECK_DOCS);
2112 }
2113
2114 #[test]
2115 fn health_meta_docs_url_matches_constant() {
2116 let meta = health_meta();
2117 assert_eq!(meta["docs"].as_str().unwrap(), HEALTH_DOCS);
2118 }
2119
2120 #[test]
2121 fn dupes_meta_docs_url_matches_constant() {
2122 let meta = dupes_meta();
2123 assert_eq!(meta["docs"].as_str().unwrap(), DUPES_DOCS);
2124 }
2125
2126 #[test]
2127 fn rule_by_id_finds_all_check_rules() {
2128 for rule in CHECK_RULES {
2129 assert!(
2130 rule_by_id(rule.id).is_some(),
2131 "rule_by_id should find check rule {}",
2132 rule.id
2133 );
2134 }
2135 }
2136
2137 #[test]
2138 fn rule_by_id_finds_all_health_rules() {
2139 for rule in HEALTH_RULES {
2140 assert!(
2141 rule_by_id(rule.id).is_some(),
2142 "rule_by_id should find health rule {}",
2143 rule.id
2144 );
2145 }
2146 }
2147
2148 #[test]
2149 fn rule_by_id_finds_all_dupes_rules() {
2150 for rule in DUPES_RULES {
2151 assert!(
2152 rule_by_id(rule.id).is_some(),
2153 "rule_by_id should find dupes rule {}",
2154 rule.id
2155 );
2156 }
2157 }
2158
2159 #[test]
2160 fn rule_by_id_finds_all_security_rules() {
2161 for rule in SECURITY_RULES {
2162 assert!(
2163 rule_by_id(rule.id).is_some(),
2164 "rule_by_id should find security rule {}",
2165 rule.id
2166 );
2167 }
2168 }
2169
2170 #[test]
2171 fn check_rules_count() {
2172 assert_eq!(CHECK_RULES.len(), 26);
2173 }
2174
2175 #[test]
2176 fn health_rules_count() {
2177 assert_eq!(HEALTH_RULES.len(), 16);
2178 }
2179
2180 #[test]
2181 fn dupes_rules_count() {
2182 assert_eq!(DUPES_RULES.len(), 1);
2183 }
2184
2185 #[test]
2186 fn flags_rules_count() {
2187 assert_eq!(FLAGS_RULES.len(), 1);
2188 }
2189
2190 #[test]
2191 fn security_rules_count() {
2192 assert_eq!(
2193 SECURITY_RULES.len(),
2194 matcher_entries_from_security_catalogue().len() + 3
2195 );
2196 }
2197
2198 #[test]
2199 fn security_rules_cover_every_catalogue_matcher() {
2200 let mut rule_ids = rustc_hash::FxHashSet::default();
2201 for rule in SECURITY_RULES {
2202 rule_ids.insert(rule.id);
2203 }
2204
2205 for matcher in matcher_entries_from_security_catalogue() {
2206 let rule_id = format!("security/{}", matcher.id);
2207 assert!(
2208 rule_ids.contains(rule_id.as_str()),
2209 "security matcher {} has no explain rule",
2210 matcher.id
2211 );
2212 }
2213 }
2214
2215 #[test]
2216 fn security_catalogue_rules_match_catalogue_title_and_cwe() {
2217 for matcher in matcher_entries_from_security_catalogue() {
2218 let rule_id = format!("security/{}", matcher.id);
2219 let rule = rule_by_id(&rule_id)
2220 .unwrap_or_else(|| panic!("security matcher {} has no explain rule", matcher.id));
2221 let cwe = format!("CWE-{}", matcher.cwe);
2222 assert_eq!(
2223 rule.name, matcher.title,
2224 "security matcher {} has stale explain title",
2225 matcher.id
2226 );
2227 assert!(
2228 rule.short.contains(&cwe),
2229 "security matcher {} explain summary does not mention {cwe}",
2230 matcher.id
2231 );
2232 assert!(
2233 rule.full.contains(&cwe),
2234 "security matcher {} explain rationale does not mention {cwe}",
2235 matcher.id
2236 );
2237 }
2238 }
2239
2240 #[test]
2246 fn every_rule_declares_a_category() {
2247 let allowed = [
2248 "Dead code",
2249 "Dependencies",
2250 "Duplication",
2251 "Health",
2252 "Architecture",
2253 "Suppressions",
2254 "Security",
2255 "Policy",
2256 "Flags",
2257 ];
2258 for rule in CHECK_RULES
2259 .iter()
2260 .chain(HEALTH_RULES)
2261 .chain(DUPES_RULES)
2262 .chain(FLAGS_RULES)
2263 .chain(SECURITY_RULES)
2264 {
2265 assert!(
2266 !rule.category.is_empty(),
2267 "rule {} has empty category",
2268 rule.id
2269 );
2270 assert!(
2271 allowed.contains(&rule.category),
2272 "rule {} has unrecognised category {:?}; add to allowlist or pick from {:?}",
2273 rule.id,
2274 rule.category,
2275 allowed
2276 );
2277 }
2278 }
2279
2280 #[derive(Debug)]
2281 struct MatcherEntry {
2282 id: &'static str,
2283 title: &'static str,
2284 cwe: &'static str,
2285 }
2286
2287 fn matcher_entries_from_security_catalogue() -> Vec<MatcherEntry> {
2288 let toml = include_str!("../../core/data/security_matchers.toml");
2289 let mut entries = Vec::new();
2290 let mut in_matcher = false;
2291 let mut id = None;
2292 let mut title = None;
2293 let mut cwe = None;
2294
2295 for line in toml.lines() {
2296 let trimmed = line.trim();
2297 if trimmed == "[[matcher]]" {
2298 if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2299 entries.push(MatcherEntry { id, title, cwe });
2300 }
2301 in_matcher = true;
2302 continue;
2303 }
2304 if trimmed.starts_with("[[") {
2305 if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2306 entries.push(MatcherEntry { id, title, cwe });
2307 }
2308 in_matcher = false;
2309 continue;
2310 }
2311 if !in_matcher {
2312 continue;
2313 }
2314 if let Some(value) = trimmed
2315 .strip_prefix("id = \"")
2316 .and_then(|value| value.strip_suffix('"'))
2317 {
2318 id = Some(value);
2319 } else if let Some(value) = trimmed
2320 .strip_prefix("title = \"")
2321 .and_then(|value| value.strip_suffix('"'))
2322 {
2323 title = Some(value);
2324 } else if let Some(value) = trimmed.strip_prefix("cwe = ") {
2325 cwe = Some(value);
2326 }
2327 }
2328
2329 if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2330 entries.push(MatcherEntry { id, title, cwe });
2331 }
2332
2333 let mut seen = rustc_hash::FxHashSet::default();
2334 entries
2335 .into_iter()
2336 .filter(|entry| seen.insert(entry.id))
2337 .collect()
2338 }
2339}