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(SECURITY_RULES.iter())
280 .find(|r| r.id == id)
281}
282
283#[must_use]
285pub fn rule_docs_url(rule: &RuleDef) -> String {
286 format!("{DOCS_BASE}/{}", rule.docs_path)
287}
288
289pub struct RuleGuide {
294 pub example: &'static str,
295 pub how_to_fix: &'static str,
296}
297
298#[must_use]
303pub fn rule_by_token(token: &str) -> Option<&'static RuleDef> {
304 let trimmed = token.trim();
305 if trimmed.is_empty() {
306 return None;
307 }
308 if let Some(rule) = rule_by_id(trimmed) {
309 return Some(rule);
310 }
311 let normalized = trimmed
312 .strip_prefix("fallow/")
313 .unwrap_or(trimmed)
314 .trim_start_matches("--")
315 .replace('_', "-")
316 .split_whitespace()
317 .collect::<Vec<_>>()
318 .join("-");
319 let alias = match normalized.as_str() {
320 "unused-files" => Some("fallow/unused-file"),
321 "unused-exports" => Some("fallow/unused-export"),
322 "unused-types" => Some("fallow/unused-type"),
323 "private-type-leaks" => Some("fallow/private-type-leak"),
324 "unused-deps" | "unused-dependencies" => Some("fallow/unused-dependency"),
325 "unused-dev-deps" | "unused-dev-dependencies" => Some("fallow/unused-dev-dependency"),
326 "unused-optional-deps" | "unused-optional-dependencies" => {
327 Some("fallow/unused-optional-dependency")
328 }
329 "type-only-deps" | "type-only-dependencies" => Some("fallow/type-only-dependency"),
330 "test-only-deps" | "test-only-dependencies" => Some("fallow/test-only-dependency"),
331 "unused-enum-members" => Some("fallow/unused-enum-member"),
332 "unused-class-members" => Some("fallow/unused-class-member"),
333 "unresolved-imports" => Some("fallow/unresolved-import"),
334 "unlisted-deps" | "unlisted-dependencies" => Some("fallow/unlisted-dependency"),
335 "duplicate-exports" => Some("fallow/duplicate-export"),
336 "circular-deps" | "circular-dependencies" => Some("fallow/circular-dependency"),
337 "boundary-violations" => Some("fallow/boundary-violation"),
338 "boundary-coverage" | "boundary-coverage-violations" => Some("fallow/boundary-coverage"),
339 "boundary-calls" | "boundary-call-violations" => Some("fallow/boundary-call-violation"),
340 "policy-violation" | "policy-violations" => Some("fallow/policy-violation"),
341 "stale-suppressions" => Some("fallow/stale-suppression"),
342 "unused-catalog-entries" | "unused-catalog-entry" | "catalog" => {
343 Some("fallow/unused-catalog-entry")
344 }
345 "empty-catalog-groups" | "empty-catalog-group" | "empty-catalog" => {
346 Some("fallow/empty-catalog-group")
347 }
348 "unresolved-catalog-references" | "unresolved-catalog-reference" | "unresolved-catalog" => {
349 Some("fallow/unresolved-catalog-reference")
350 }
351 "unused-dependency-overrides"
352 | "unused-dependency-override"
353 | "unused-override"
354 | "unused-overrides" => Some("fallow/unused-dependency-override"),
355 "misconfigured-dependency-overrides"
356 | "misconfigured-dependency-override"
357 | "misconfigured-override"
358 | "misconfigured-overrides" => Some("fallow/misconfigured-dependency-override"),
359 "complexity" | "high-complexity" => Some("fallow/high-complexity"),
360 "cyclomatic" | "high-cyclomatic" | "high-cyclomatic-complexity" => {
361 Some("fallow/high-cyclomatic-complexity")
362 }
363 "cognitive" | "high-cognitive" | "high-cognitive-complexity" => {
364 Some("fallow/high-cognitive-complexity")
365 }
366 "crap" | "high-crap" | "high-crap-score" => Some("fallow/high-crap-score"),
367 "duplication" | "dupes" | "code-duplication" => Some("fallow/code-duplication"),
368 "security"
369 | "security-candidate"
370 | "security-candidates"
371 | "tainted-sink"
372 | "tainted-sinks"
373 | "security-sink"
374 | "security-sinks" => Some("security/tainted-sink"),
375 "client-server-leak"
376 | "client-server-leaks"
377 | "security-client-server-leak"
378 | "security-client-server-leaks" => Some("security/client-server-leak"),
379 "hardcoded-secret" | "hardcoded-secrets" | "hard-coded-secret" | "hard-coded-secrets" => {
380 Some("security/hardcoded-secret")
381 }
382 _ => None,
383 };
384 if let Some(id) = alias
385 && let Some(rule) = rule_by_id(id)
386 {
387 return Some(rule);
388 }
389 let security_token = normalized.strip_prefix("security-").unwrap_or(&normalized);
390 let security_id = format!("security/{security_token}");
391 if let Some(rule) = rule_by_id(&security_id) {
392 return Some(rule);
393 }
394 let singular = normalized
395 .strip_suffix('s')
396 .filter(|_| normalized != "unused-class")
397 .unwrap_or(&normalized);
398 let singular_security_token = singular.strip_prefix("security-").unwrap_or(singular);
399 let singular_security_id = format!("security/{singular_security_token}");
400 if let Some(rule) = rule_by_id(&singular_security_id) {
401 return Some(rule);
402 }
403 let id = format!("fallow/{singular}");
404 rule_by_id(&id).or_else(|| {
405 CHECK_RULES
406 .iter()
407 .chain(HEALTH_RULES.iter())
408 .chain(DUPES_RULES.iter())
409 .chain(SECURITY_RULES.iter())
410 .find(|rule| {
411 rule.docs_path.ends_with(&normalized)
412 || rule.docs_path.ends_with(singular)
413 || rule.name.eq_ignore_ascii_case(trimmed)
414 })
415 })
416}
417
418#[must_use]
420pub fn rule_guide(rule: &RuleDef) -> RuleGuide {
421 match rule.id {
422 "fallow/unused-file" => RuleGuide {
423 example: "src/old-widget.ts is not imported by any entry point, route, script, or config file.",
424 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.",
425 },
426 "fallow/unused-export" => RuleGuide {
427 example: "export const formatPrice = ... exists in src/money.ts, but no module imports formatPrice.",
428 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.",
429 },
430 "fallow/unused-type" => RuleGuide {
431 example: "export interface LegacyProps is exported, but no module imports the type.",
432 how_to_fix: "Remove the type export, inline it, or keep it behind an explicit API entry point when consumers rely on it.",
433 },
434 "fallow/private-type-leak" => RuleGuide {
435 example: "export function makeUser(): InternalUser exposes InternalUser even though InternalUser is not exported.",
436 how_to_fix: "Export the referenced type, change the public signature to an exported type, or keep the helper private.",
437 },
438 "fallow/unused-dependency"
439 | "fallow/unused-dev-dependency"
440 | "fallow/unused-optional-dependency" => RuleGuide {
441 example: "package.json lists left-pad, but no source, script, config, or plugin-recognized file imports it.",
442 how_to_fix: "Remove the dependency after checking runtime/plugin usage. If another workspace uses it, move the dependency to that workspace.",
443 },
444 "fallow/type-only-dependency" => RuleGuide {
445 example: "zod is in dependencies but only appears in import type declarations.",
446 how_to_fix: "Move the package to devDependencies unless runtime code imports it as a value.",
447 },
448 "fallow/test-only-dependency" => RuleGuide {
449 example: "vitest is listed in dependencies, but only test files import it.",
450 how_to_fix: "Move the package to devDependencies unless production code imports it at runtime.",
451 },
452 "fallow/unused-enum-member" => RuleGuide {
453 example: "Status.Legacy remains in an exported enum, but no code reads that member.",
454 how_to_fix: "Remove the member after checking serialized/API compatibility, or suppress it with a reason when external data still uses it.",
455 },
456 "fallow/unused-class-member" => RuleGuide {
457 example: "class Parser has a public parseLegacy method that is never called in the project.",
458 how_to_fix: "Remove or privatize the member. For reflection/framework lifecycle hooks, configure or suppress the intentional entry point.",
459 },
460 "fallow/unresolved-import" => RuleGuide {
461 example: "src/app.ts imports ./routes/admin, but no matching file exists after extension and index resolution.",
462 how_to_fix: "Fix the specifier, restore the missing file, install the package, or align tsconfig path aliases with the runtime resolver.",
463 },
464 "fallow/unlisted-dependency" => RuleGuide {
465 example: "src/api.ts imports undici, but the nearest package.json does not list undici.",
466 how_to_fix: "Add the package to dependencies/devDependencies in the workspace that imports it instead of relying on hoisting or transitive deps.",
467 },
468 "fallow/duplicate-export" => RuleGuide {
469 example: "Button is exported from both src/ui/button.ts and src/components/button.ts.",
470 how_to_fix: "Rename or consolidate the exports so consumers have one intentional import target.",
471 },
472 "fallow/circular-dependency" => RuleGuide {
473 example: "src/a.ts imports src/b.ts, and src/b.ts imports src/a.ts.",
474 how_to_fix: "Extract shared code to a third module, invert the dependency, or split initialization-time side effects from type-only contracts.",
475 },
476 "fallow/boundary-violation" => RuleGuide {
477 example: "features/billing imports app/admin even though the configured boundary only allows imports from shared and entities.",
478 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.",
479 },
480 "fallow/boundary-coverage" => RuleGuide {
481 example: "src/generated/client.ts is reachable but does not match any boundaries.zones[].patterns entry.",
482 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.",
483 },
484 "fallow/boundary-call-violation" => RuleGuide {
485 example: "src/domain/policy.ts calls execSync from node:child_process while boundaries.calls.forbidden bans child_process.* from the domain zone.",
486 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).",
487 },
488 "fallow/policy-violation" => RuleGuide {
489 example: "src/app.ts imports moment while a rule pack bans the moment specifier with the message 'Use date-fns.'",
490 how_to_fix: "Replace the banned call or import with the alternative named in the rule's message. To waive a single line, use `// fallow-ignore-next-line policy-violation`; note the token covers every rule-pack rule on that line, and the file-level form covers the whole file.",
491 },
492 "fallow/stale-suppression" => RuleGuide {
493 example: "// fallow-ignore-next-line unused-export remains above an export that is now used.",
494 how_to_fix: "Remove the suppression. If a different issue is still intentional, replace it with a current, specific suppression.",
495 },
496 "fallow/unused-catalog-entry" => RuleGuide {
497 example: "pnpm-workspace.yaml declares `catalog: { is-even: ^1.0.0 }`, but no workspace package.json declares `\"is-even\": \"catalog:\"`.",
498 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.",
499 },
500 "fallow/empty-catalog-group" => RuleGuide {
501 example: "pnpm-workspace.yaml declares `catalogs: { react17: {} }` after the last react17 entry was removed.",
502 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.",
503 },
504 "fallow/unresolved-catalog-reference" => RuleGuide {
505 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.",
506 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.",
507 },
508 "fallow/unused-dependency-override" => RuleGuide {
509 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.",
510 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.",
511 },
512 "fallow/misconfigured-dependency-override" => RuleGuide {
513 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.",
514 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.",
515 },
516 "fallow/high-cyclomatic-complexity"
517 | "fallow/high-cognitive-complexity"
518 | "fallow/high-complexity" => RuleGuide {
519 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.",
520 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`.",
521 },
522 "fallow/high-crap-score" => RuleGuide {
523 example: "A complex function has little or no matching Istanbul coverage, so its CRAP score crosses the configured gate.",
524 how_to_fix: "Add focused tests for the risky branches first, then simplify the function if the score remains high.",
525 },
526 "fallow/refactoring-target" => RuleGuide {
527 example: "A file combines high complexity density, churn, fan-in, and dead-code signals.",
528 how_to_fix: "Start with the listed evidence: remove dead exports, extract complex functions, then reduce fan-out or cycles in small steps.",
529 },
530 "fallow/untested-file" | "fallow/untested-export" => RuleGuide {
531 example: "Production-reachable code has no dependency path from discovered test entry points.",
532 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.",
533 },
534 "fallow/runtime-safe-to-delete"
535 | "fallow/runtime-review-required"
536 | "fallow/runtime-low-traffic"
537 | "fallow/runtime-coverage-unavailable"
538 | "fallow/runtime-coverage" => RuleGuide {
539 example: "Runtime coverage shows a function was never called, barely called, or could not be matched during the capture window.",
540 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.",
541 },
542 "fallow/code-duplication" => RuleGuide {
543 example: "Two files contain the same normalized token sequence across a multi-line block.",
544 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.",
545 },
546 "security/tainted-sink" => RuleGuide {
547 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.",
548 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.",
549 },
550 "security/client-server-leak" => RuleGuide {
551 example: "A module marked `use client` imports code that reads a non-public `process.env` or `import.meta.env` value through a static path.",
552 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.",
553 },
554 "security/hardcoded-secret" => RuleGuide {
555 example: "A provider-prefixed token-shaped literal is assigned to a secret-shaped variable, and the hardcoded-secret category is explicitly included.",
556 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.",
557 },
558 id if id.starts_with("security/") => RuleGuide {
559 example: "A `fallow security` candidate uses this catalogue category as its SARIF rule id, for example security/sql-injection for a matched SQL sink.",
560 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.",
561 },
562 _ => RuleGuide {
563 example: "Run the relevant command with --format json --quiet --explain to inspect this rule in context.",
564 how_to_fix: "Use the issue action hints, source location, and docs URL to decide whether to remove, move, configure, or suppress the finding.",
565 },
566 }
567}
568
569#[must_use]
571pub fn run_explain(issue_type: &str, output: OutputFormat) -> ExitCode {
572 let Some(rule) = rule_by_token(issue_type) else {
573 let message = if looks_security_explain_token(issue_type) {
574 format!(
575 "unknown issue type '{issue_type}'. Try values like tainted-sink, client-server-leak, hardcoded-secret, sql-injection, or security/sql-injection"
576 )
577 } else {
578 format!(
579 "unknown issue type '{issue_type}'. Try values like unused files, unused-export, high complexity, or code duplication"
580 )
581 };
582 return crate::error::emit_error(&message, 2, output);
583 };
584 let guide = rule_guide(rule);
585 match output {
586 OutputFormat::Json => {
587 let envelope = crate::output_envelope::ExplainOutput {
588 id: rule.id.to_string(),
589 name: rule.name.to_string(),
590 summary: rule.short.to_string(),
591 rationale: rule.full.to_string(),
592 example: guide.example.to_string(),
593 how_to_fix: guide.how_to_fix.to_string(),
594 docs: rule_docs_url(rule),
595 };
596 match crate::output_envelope::serialize_root_output(
597 crate::output_envelope::FallowOutput::Explain(envelope),
598 ) {
599 Ok(value) => crate::report::emit_json(&value, "explain"),
600 Err(e) => {
601 crate::error::emit_error(&format!("JSON serialization error: {e}"), 2, output)
602 }
603 }
604 }
605 OutputFormat::Human => print_explain_human(rule, &guide),
606 OutputFormat::Compact => print_explain_compact(rule),
607 OutputFormat::Markdown => print_explain_markdown(rule, &guide),
608 OutputFormat::Sarif
609 | OutputFormat::CodeClimate
610 | OutputFormat::PrCommentGithub
611 | OutputFormat::PrCommentGitlab
612 | OutputFormat::ReviewGithub
613 | OutputFormat::ReviewGitlab
614 | OutputFormat::Badge => crate::error::emit_error(
615 "explain supports human, compact, markdown, and json output",
616 2,
617 output,
618 ),
619 }
620}
621
622fn looks_security_explain_token(issue_type: &str) -> bool {
623 let normalized = issue_type.trim().to_ascii_lowercase().replace('_', "-");
624 normalized.contains("security")
625 || normalized.contains("secret")
626 || normalized.contains("sink")
627 || normalized.contains("cwe")
628 || normalized.contains("client-server")
629 || normalized.contains("injection")
630}
631
632fn print_explain_human(rule: &RuleDef, guide: &RuleGuide) -> ExitCode {
633 println!("{}", rule.name.bold());
634 println!("{}", rule.id.dimmed());
635 println!();
636 println!("{}", rule.short);
637 println!();
638 println!("{}", "Why it matters".bold());
639 println!("{}", rule.full);
640 println!();
641 println!("{}", "Example".bold());
642 println!("{}", guide.example);
643 println!();
644 println!("{}", "How to fix".bold());
645 println!("{}", guide.how_to_fix);
646 println!();
647 println!("{} {}", "Docs:".dimmed(), rule_docs_url(rule).dimmed());
648 ExitCode::SUCCESS
649}
650
651fn print_explain_compact(rule: &RuleDef) -> ExitCode {
652 println!("explain:{}:{}:{}", rule.id, rule.short, rule_docs_url(rule));
653 ExitCode::SUCCESS
654}
655
656fn print_explain_markdown(rule: &RuleDef, guide: &RuleGuide) -> ExitCode {
657 println!("# {}", rule.name);
658 println!();
659 println!("`{}`", rule.id);
660 println!();
661 println!("{}", rule.short);
662 println!();
663 println!("## Why it matters");
664 println!();
665 println!("{}", rule.full);
666 println!();
667 println!("## Example");
668 println!();
669 println!("{}", guide.example);
670 println!();
671 println!("## How to fix");
672 println!();
673 println!("{}", guide.how_to_fix);
674 println!();
675 println!("[Docs]({})", rule_docs_url(rule));
676 ExitCode::SUCCESS
677}
678
679pub const HEALTH_RULES: &[RuleDef] = &[
680 RuleDef {
681 id: "fallow/high-cyclomatic-complexity",
682 category: "Health",
683 name: "High Cyclomatic Complexity",
684 short: "Function has high cyclomatic complexity",
685 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`.",
686 docs_path: "explanations/health#cyclomatic-complexity",
687 },
688 RuleDef {
689 id: "fallow/high-cognitive-complexity",
690 category: "Health",
691 name: "High Cognitive Complexity",
692 short: "Function has high cognitive complexity",
693 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`.",
694 docs_path: "explanations/health#cognitive-complexity",
695 },
696 RuleDef {
697 id: "fallow/high-complexity",
698 category: "Health",
699 name: "High Complexity (Both)",
700 short: "Function exceeds both complexity thresholds",
701 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`.",
702 docs_path: "explanations/health#complexity-metrics",
703 },
704 RuleDef {
705 id: "fallow/high-crap-score",
706 category: "Health",
707 name: "High CRAP Score",
708 short: "Function has a high CRAP score (complexity combined with low coverage)",
709 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.",
710 docs_path: "explanations/health#crap-score",
711 },
712 RuleDef {
713 id: "fallow/refactoring-target",
714 category: "Health",
715 name: "Refactoring Target",
716 short: "File identified as a high-priority refactoring candidate",
717 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.",
718 docs_path: "explanations/health#refactoring-targets",
719 },
720 RuleDef {
721 id: "fallow/untested-file",
722 category: "Health",
723 name: "Untested File",
724 short: "Runtime-reachable file has no test dependency path",
725 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.",
726 docs_path: "explanations/health#coverage-gaps",
727 },
728 RuleDef {
729 id: "fallow/untested-export",
730 category: "Health",
731 name: "Untested Export",
732 short: "Runtime-reachable export has no test dependency path",
733 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.",
734 docs_path: "explanations/health#coverage-gaps",
735 },
736 RuleDef {
737 id: "fallow/runtime-safe-to-delete",
738 category: "Health",
739 name: "Production Safe To Delete",
740 short: "Statically unused AND never invoked in production with V8 tracking",
741 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.",
742 docs_path: "explanations/health#runtime-coverage",
743 },
744 RuleDef {
745 id: "fallow/runtime-review-required",
746 category: "Health",
747 name: "Production Review Required",
748 short: "Statically used but never invoked in production",
749 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.",
750 docs_path: "explanations/health#runtime-coverage",
751 },
752 RuleDef {
753 id: "fallow/runtime-low-traffic",
754 category: "Health",
755 name: "Production Low Traffic",
756 short: "Function was invoked below the low-traffic threshold",
757 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.",
758 docs_path: "explanations/health#runtime-coverage",
759 },
760 RuleDef {
761 id: "fallow/runtime-coverage-unavailable",
762 category: "Health",
763 name: "Runtime Coverage Unavailable",
764 short: "Runtime coverage could not be resolved for this function",
765 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.",
766 docs_path: "explanations/health#runtime-coverage",
767 },
768 RuleDef {
769 id: "fallow/runtime-coverage",
770 category: "Health",
771 name: "Runtime Coverage",
772 short: "Runtime coverage finding",
773 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.",
774 docs_path: "explanations/health#runtime-coverage",
775 },
776 RuleDef {
777 id: "fallow/coverage-intelligence-risky-change",
778 category: "Health",
779 name: "Coverage Intelligence Risky Change",
780 short: "Changed hot path combines high CRAP and low test coverage",
781 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.",
782 docs_path: "explanations/health#coverage-intelligence",
783 },
784 RuleDef {
785 id: "fallow/coverage-intelligence-delete",
786 category: "Health",
787 name: "Coverage Intelligence Delete",
788 short: "Static and runtime evidence indicate code can be deleted",
789 full: "Coverage intelligence combined static unused status, runtime cold evidence, and lack of test reachability into a high-confidence delete recommendation.",
790 docs_path: "explanations/health#coverage-intelligence",
791 },
792 RuleDef {
793 id: "fallow/coverage-intelligence-review",
794 category: "Health",
795 name: "Coverage Intelligence Review",
796 short: "Cold reachable uncovered code needs owner review",
797 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.",
798 docs_path: "explanations/health#coverage-intelligence",
799 },
800 RuleDef {
801 id: "fallow/coverage-intelligence-refactor",
802 category: "Health",
803 name: "Coverage Intelligence Refactor",
804 short: "Hot covered code has high CRAP and should be refactored carefully",
805 full: "Coverage intelligence found hot production code that is covered by tests but still has high CRAP. Refactor carefully while preserving behavior.",
806 docs_path: "explanations/health#coverage-intelligence",
807 },
808];
809
810pub const DUPES_RULES: &[RuleDef] = &[RuleDef {
811 id: "fallow/code-duplication",
812 category: "Duplication",
813 name: "Code Duplication",
814 short: "Duplicated code block",
815 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.",
816 docs_path: "explanations/duplication#clone-groups",
817}];
818
819macro_rules! security_catalogue_rule {
820 ($id:literal, $name:literal, $cwe:literal) => {
821 RuleDef {
822 id: concat!("security/", $id),
823 category: "Security",
824 name: $name,
825 short: concat!("Catalogue security candidate for CWE-", $cwe),
826 full: concat!(
827 $name,
828 " is a data-driven `fallow security` tainted-sink catalogue category with CWE-",
829 $cwe,
830 " metadata. fallow reports it as an unverified candidate when a captured sink shape matches this category. Use it to understand or filter `security/",
831 $id,
832 "` findings, then inspect the trace, source, sink, sanitization, and application context before treating it as exploitable."
833 ),
834 docs_path: "cli/security",
835 }
836 };
837}
838
839pub const SECURITY_RULES: &[RuleDef] = &[
840 RuleDef {
841 id: "security/tainted-sink",
842 category: "Security",
843 name: "Tainted Sink Candidates",
844 short: "Syntactic security sink candidates require verification",
845 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.",
846 docs_path: "cli/security",
847 },
848 RuleDef {
849 id: "security/client-server-leak",
850 category: "Security",
851 name: "Client-server Secret Leak Candidates",
852 short: "Client-bound code reaches a non-public env read",
853 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.",
854 docs_path: "cli/security",
855 },
856 RuleDef {
857 id: "security/hardcoded-secret",
858 category: "Security",
859 name: "Hardcoded Secret Candidates",
860 short: "Provider-prefixed or contextual secret literals require verification",
861 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.",
862 docs_path: "cli/security",
863 },
864 security_catalogue_rule!("dangerous-html", "Dangerous HTML sink", "79"),
865 security_catalogue_rule!(
866 "template-escape-bypass",
867 "Template escape bypass sink",
868 "79"
869 ),
870 security_catalogue_rule!("command-injection", "OS command injection sink", "78"),
871 security_catalogue_rule!("code-injection", "Code injection sink", "94"),
872 security_catalogue_rule!("dynamic-regex", "Dynamic regular expression sink", "1333"),
873 security_catalogue_rule!("redos-regex", "ReDoS regex sink", "1333"),
874 security_catalogue_rule!(
875 "resource-amplification",
876 "Resource amplification sink",
877 "400"
878 ),
879 security_catalogue_rule!("dynamic-module-load", "Dynamic module load sink", "95"),
880 security_catalogue_rule!("sql-injection", "SQL injection sink", "89"),
881 security_catalogue_rule!("ssrf", "Server-side request forgery sink", "918"),
882 security_catalogue_rule!(
883 "secret-to-network",
884 "Secret reaches a network request",
885 "201"
886 ),
887 security_catalogue_rule!("path-traversal", "Path traversal sink", "22"),
888 security_catalogue_rule!(
889 "header-injection",
890 "HTTP response header injection sink",
891 "113"
892 ),
893 security_catalogue_rule!("open-redirect", "Open redirect sink", "601"),
894 security_catalogue_rule!(
895 "postmessage-wildcard-origin",
896 "Wildcard postMessage target origin",
897 "346"
898 ),
899 security_catalogue_rule!("tls-validation-disabled", "TLS validation disabled", "295"),
900 security_catalogue_rule!("cleartext-transport", "Cleartext transport URL", "319"),
901 security_catalogue_rule!(
902 "electron-unsafe-webpreferences",
903 "Unsafe Electron BrowserWindow preferences",
904 "1188"
905 ),
906 security_catalogue_rule!(
907 "world-writable-permission",
908 "World-writable chmod mode",
909 "732"
910 ),
911 security_catalogue_rule!(
912 "insecure-temp-file",
913 "Predictable temporary file path",
914 "377"
915 ),
916 security_catalogue_rule!(
917 "mysql-multiple-statements",
918 "MySQL multiple statements enabled",
919 "89"
920 ),
921 security_catalogue_rule!("permissive-cors", "Permissive CORS policy", "942"),
922 security_catalogue_rule!("insecure-cookie", "Insecure cookie options", "614"),
923 security_catalogue_rule!("mass-assignment", "Mass assignment sink", "915"),
924 security_catalogue_rule!("weak-crypto", "Runtime-selectable crypto algorithm", "327"),
925 security_catalogue_rule!("insecure-randomness", "Insecure randomness sink", "338"),
926 security_catalogue_rule!("jwt-alg-none", "JWT alg none", "347"),
927 security_catalogue_rule!(
928 "jwt-verify-missing-algorithms",
929 "JWT verify missing algorithms allowlist",
930 "347"
931 ),
932 security_catalogue_rule!("deprecated-cipher", "Deprecated cipher constructor", "327"),
933 security_catalogue_rule!(
934 "unsafe-buffer-alloc",
935 "Unsafe Buffer allocation sink",
936 "1188"
937 ),
938 security_catalogue_rule!(
939 "unsafe-deserialization",
940 "Unsafe deserialization sink",
941 "502"
942 ),
943 security_catalogue_rule!(
944 "angular-trusted-html",
945 "Angular bypassSecurityTrust sink",
946 "79"
947 ),
948 security_catalogue_rule!("nextjs-open-redirect", "Next.js open redirect sink", "601"),
949 security_catalogue_rule!("dom-document-write", "DOM document.write sink", "79"),
950 security_catalogue_rule!("jquery-html", "jQuery .html() sink", "79"),
951 security_catalogue_rule!(
952 "route-send-file",
953 "Route file-send path traversal sink",
954 "22"
955 ),
956 security_catalogue_rule!("webview-injection", "WebView injected-script sink", "94"),
957 security_catalogue_rule!("prototype-pollution", "Prototype pollution sink", "1321"),
958 security_catalogue_rule!("zip-slip", "Archive path-traversal (zip-slip) sink", "22"),
959 security_catalogue_rule!("nosql-injection", "NoSQL injection sink", "943"),
960 security_catalogue_rule!("ssti", "Server-side template injection sink", "1336"),
961 security_catalogue_rule!("xxe", "XML external entity (XXE) sink", "611"),
962 security_catalogue_rule!("secret-pii-log", "Secret or PII logged", "532"),
963 security_catalogue_rule!("xpath-injection", "XPath injection sink", "643"),
964];
965
966#[must_use]
968pub fn check_meta() -> Value {
969 let rules: Value = CHECK_RULES
970 .iter()
971 .map(|r| {
972 (
973 r.id.replace("fallow/", ""),
974 json!({
975 "name": r.name,
976 "description": r.full,
977 "docs": rule_docs_url(r)
978 }),
979 )
980 })
981 .collect::<serde_json::Map<String, Value>>()
982 .into();
983
984 json!({
985 "docs": CHECK_DOCS,
986 "rules": rules,
987 "field_definitions": {
988 "actions[]": ACTIONS_FIELD_DEFINITION,
989 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
990 }
991 })
992}
993
994#[must_use]
996pub fn combined_meta(include_check: bool, include_dupes: bool, include_health: bool) -> Value {
997 let mut sections = serde_json::Map::new();
998 if include_check {
999 sections.insert("check".to_string(), check_meta());
1000 }
1001 if include_dupes {
1002 sections.insert("dupes".to_string(), dupes_meta());
1003 }
1004 if include_health {
1005 sections.insert("health".to_string(), health_meta());
1006 }
1007 Value::Object(sections)
1008}
1009
1010#[must_use]
1012#[expect(
1013 clippy::too_many_lines,
1014 reason = "flat metric table: every entry is 3-4 short lines of metadata and keeping them in one map is clearer than splitting into per-metric helpers"
1015)]
1016pub fn health_meta() -> Value {
1017 json!({
1018 "docs": HEALTH_DOCS,
1019 "field_definitions": {
1020 "actions[]": ACTIONS_FIELD_DEFINITION,
1021 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
1022 },
1023 "metrics": {
1024 "cyclomatic": {
1025 "name": "Cyclomatic Complexity",
1026 "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.",
1027 "range": "[1, \u{221e})",
1028 "interpretation": "lower is better; default threshold: 20"
1029 },
1030 "cognitive": {
1031 "name": "Cognitive Complexity",
1032 "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.",
1033 "range": "[0, \u{221e})",
1034 "interpretation": "lower is better; default threshold: 15"
1035 },
1036 "line_count": {
1037 "name": "Function Line Count",
1038 "description": "Number of lines in the function body.",
1039 "range": "[1, \u{221e})",
1040 "interpretation": "context-dependent; long functions may need splitting"
1041 },
1042 "lines": {
1043 "name": "File Line Count",
1044 "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.",
1045 "range": "[1, \u{221e})",
1046 "interpretation": "context-dependent; large files may benefit from splitting even if individual functions are small"
1047 },
1048 "maintainability_index": {
1049 "name": "Maintainability Index",
1050 "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.",
1051 "range": "[0, 100]",
1052 "interpretation": "higher is better; <40 poor, 40\u{2013}70 moderate, >70 good"
1053 },
1054 "complexity_density": {
1055 "name": "Complexity Density",
1056 "description": "Total cyclomatic complexity divided by lines of code. Measures how densely complex the code is per line.",
1057 "range": "[0, \u{221e})",
1058 "interpretation": "lower is better; >1.0 indicates very dense complexity"
1059 },
1060 "dead_code_ratio": {
1061 "name": "Dead Code Ratio",
1062 "description": "Fraction of value exports (excluding type-only exports like interfaces and type aliases) with zero references across the project.",
1063 "range": "[0, 1]",
1064 "interpretation": "lower is better; 0 = all exports are used"
1065 },
1066 "fan_in": {
1067 "name": "Fan-in (Importers)",
1068 "description": "Number of files that import this file. High fan-in means high blast radius \u{2014} changes to this file affect many dependents.",
1069 "range": "[0, \u{221e})",
1070 "interpretation": "context-dependent; high fan-in files need careful review before changes"
1071 },
1072 "fan_out": {
1073 "name": "Fan-out (Imports)",
1074 "description": "Number of files this file directly imports. High fan-out indicates high coupling and change propagation risk.",
1075 "range": "[0, \u{221e})",
1076 "interpretation": "lower is better; MI penalty caps at ~40 imports"
1077 },
1078 "score": {
1079 "name": "Hotspot Score",
1080 "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.",
1081 "range": "[0, 100]",
1082 "interpretation": "higher = riskier; prioritize refactoring high-score files"
1083 },
1084 "weighted_commits": {
1085 "name": "Weighted Commits",
1086 "description": "Recency-weighted commit count using exponential decay with 90-day half-life. Recent commits contribute more than older ones.",
1087 "range": "[0, \u{221e})",
1088 "interpretation": "higher = more recent churn activity"
1089 },
1090 "trend": {
1091 "name": "Churn Trend",
1092 "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.",
1093 "values": ["accelerating", "stable", "cooling"],
1094 "interpretation": "accelerating files need attention; cooling files are stabilizing"
1095 },
1096 "priority": {
1097 "name": "Refactoring Priority",
1098 "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.",
1099 "range": "[0, 100]",
1100 "interpretation": "higher = more urgent to refactor"
1101 },
1102 "efficiency": {
1103 "name": "Efficiency Score",
1104 "description": "priority / effort_numeric (Low=1, Medium=2, High=3). Surfaces quick wins: high-priority, low-effort targets rank first. Default sort order.",
1105 "range": "[0, 100] \u{2014} effective max depends on effort: Low=100, Medium=50, High\u{2248}33",
1106 "interpretation": "higher = better quick-win value; targets are sorted by efficiency descending"
1107 },
1108 "effort": {
1109 "name": "Effort Estimate",
1110 "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.",
1111 "values": ["low", "medium", "high"],
1112 "interpretation": "low = quick win, high = needs planning and coordination"
1113 },
1114 "confidence": {
1115 "name": "Confidence Level",
1116 "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).",
1117 "values": ["high", "medium", "low"],
1118 "interpretation": "high = act on it, medium = verify context, low = treat as a signal, not a directive"
1119 },
1120 "health_score": {
1121 "name": "Health Score",
1122 "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.",
1123 "range": "[0, 100]",
1124 "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)"
1125 },
1126 "crap_max": {
1127 "name": "Untested Complexity Risk (CRAP)",
1128 "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.",
1129 "range": "[1, \u{221e})",
1130 "interpretation": "lower is better; >=30 is high-risk (CC >= 5 without test path)"
1131 },
1132 "bus_factor": {
1133 "name": "Bus Factor",
1134 "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.",
1135 "range": "[1, \u{221e})",
1136 "interpretation": "lower is higher knowledge-loss risk; 1 means a single contributor covers most of the recent history"
1137 },
1138 "contributor_count": {
1139 "name": "Contributor Count",
1140 "description": "Number of distinct authors who touched this file in the analysis window after bot-pattern filtering.",
1141 "range": "[0, \u{221e})",
1142 "interpretation": "higher generally indicates broader knowledge spread; pair with bus_factor for context"
1143 },
1144 "share": {
1145 "name": "Contributor Share",
1146 "description": "Recency-weighted share of total weighted commits attributed to a single contributor. Rounded to three decimals.",
1147 "range": "[0, 1]",
1148 "interpretation": "share close to 1.0 indicates dominance and pairs with low bus_factor"
1149 },
1150 "stale_days": {
1151 "name": "Stale Days",
1152 "description": "Days since this contributor last touched the file. Computed at analysis time.",
1153 "range": "[0, \u{221e})",
1154 "interpretation": "high stale_days on the top contributor often correlates with ownership drift"
1155 },
1156 "drift": {
1157 "name": "Ownership Drift",
1158 "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%.",
1159 "values": [true, false],
1160 "interpretation": "true means the original author is no longer maintaining; route reviews to the current top contributor"
1161 },
1162 "unowned": {
1163 "name": "Unowned (Tristate)",
1164 "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).",
1165 "values": [true, false, null],
1166 "interpretation": "true on a hotspot is a review-bottleneck risk; null means the signal is unavailable, not absent"
1167 },
1168 "runtime_coverage_verdict": {
1169 "name": "Runtime Coverage Verdict",
1170 "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).",
1171 "values": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
1172 "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."
1173 },
1174 "runtime_coverage_state": {
1175 "name": "Runtime Coverage State",
1176 "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.",
1177 "values": ["called", "never-called", "coverage-unavailable", "unknown"],
1178 "interpretation": "`never-called` in combination with static `unused` is the highest-confidence delete signal"
1179 },
1180 "runtime_coverage_confidence": {
1181 "name": "Runtime Coverage Confidence",
1182 "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.",
1183 "values": ["high", "medium", "low", "unknown"],
1184 "interpretation": "high = act on it; medium = verify context; low = treat as a signal only"
1185 },
1186 "production_invocations": {
1187 "name": "Production Invocations",
1188 "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.",
1189 "range": "[0, \u{221e})",
1190 "interpretation": "0 + tracked = cold path; 0 + untracked = unknown; high + never-called cannot occur by definition"
1191 },
1192 "percent_dead_in_production": {
1193 "name": "Percent Dead in Production",
1194 "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.",
1195 "range": "[0, 100]",
1196 "interpretation": "lower is better; values above ~10% on a long-running service indicate a large cleanup opportunity"
1197 }
1198 }
1199 })
1200}
1201
1202#[must_use]
1204pub fn dupes_meta() -> Value {
1205 json!({
1206 "docs": DUPES_DOCS,
1207 "field_definitions": {
1208 "actions[]": ACTIONS_FIELD_DEFINITION,
1209 "actions[].auto_fixable": ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION
1210 },
1211 "metrics": {
1212 "duplication_percentage": {
1213 "name": "Duplication Percentage",
1214 "description": "Fraction of total source tokens that appear in at least one clone group. Computed over the full analyzed file set.",
1215 "range": "[0, 100]",
1216 "interpretation": "lower is better"
1217 },
1218 "token_count": {
1219 "name": "Token Count",
1220 "description": "Number of normalized source tokens in the clone group. Tokens are language-aware (keywords, identifiers, operators, punctuation). Higher token count = larger duplicate.",
1221 "range": "[1, \u{221e})",
1222 "interpretation": "larger clones have higher refactoring value"
1223 },
1224 "line_count": {
1225 "name": "Line Count",
1226 "description": "Number of source lines spanned by the clone instance. Approximation of clone size for human readability.",
1227 "range": "[1, \u{221e})",
1228 "interpretation": "larger clones are more impactful to deduplicate"
1229 },
1230 "clone_groups": {
1231 "name": "Clone Groups",
1232 "description": "A set of code fragments with identical or near-identical normalized token sequences. Each group has 2+ instances across different locations.",
1233 "interpretation": "each group is a single refactoring opportunity"
1234 },
1235 "clone_groups_below_min_occurrences": {
1236 "name": "Clone Groups Below minOccurrences",
1237 "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`.",
1238 "range": "[0, \u{221e})",
1239 "interpretation": "high values suggest noisy pair-only duplication; lower `minOccurrences` to inspect"
1240 },
1241 "clone_families": {
1242 "name": "Clone Families",
1243 "description": "Groups of clone groups that share the same set of files. Indicates systematic duplication patterns (e.g., mirrored directory structures).",
1244 "interpretation": "families suggest extract-module refactoring opportunities"
1245 }
1246 }
1247 })
1248}
1249
1250#[must_use]
1252pub fn security_meta() -> Meta {
1253 let rules = SECURITY_RULES
1254 .iter()
1255 .map(|rule| {
1256 (
1257 rule.id.to_string(),
1258 MetaRule {
1259 name: Some(rule.name.to_string()),
1260 description: Some(rule.full.to_string()),
1261 docs: Some(rule_docs_url(rule)),
1262 },
1263 )
1264 })
1265 .collect();
1266
1267 Meta {
1268 docs: Some(SECURITY_DOCS.to_string()),
1269 telemetry: None,
1270 field_definitions: BTreeMap::from([
1271 (
1272 "version".to_string(),
1273 "fallow CLI version that produced this output.".to_string(),
1274 ),
1275 (
1276 "elapsed_ms".to_string(),
1277 "Wall-clock milliseconds spent producing the security report.".to_string(),
1278 ),
1279 (
1280 "config".to_string(),
1281 "Privacy-safe config context relevant to security candidate generation."
1282 .to_string(),
1283 ),
1284 (
1285 "config.rules.*.configured".to_string(),
1286 "Severity from resolved config before the security command forced default-off rules on."
1287 .to_string(),
1288 ),
1289 (
1290 "config.rules.*.effective".to_string(),
1291 "Severity used for this security command run.".to_string(),
1292 ),
1293 (
1294 "config.categories_include".to_string(),
1295 "Configured security category include list. null means unset, [] means explicitly empty."
1296 .to_string(),
1297 ),
1298 (
1299 "config.categories_exclude".to_string(),
1300 "Configured security category exclude list. null means unset, [] means explicitly empty."
1301 .to_string(),
1302 ),
1303 (
1304 "security_findings[]".to_string(),
1305 "Unverified security candidates for downstream human or agent verification."
1306 .to_string(),
1307 ),
1308 (
1309 "summary.security_findings".to_string(),
1310 "Number of security candidates after all filters, gates, and scopes.".to_string(),
1311 ),
1312 (
1313 "summary.by_severity".to_string(),
1314 "Fixed high, medium, and low severity counts for summary JSON.".to_string(),
1315 ),
1316 (
1317 "summary.by_category".to_string(),
1318 "Candidate counts by catalogue category, or by kind for uncategorized findings."
1319 .to_string(),
1320 ),
1321 (
1322 "summary.by_reachability".to_string(),
1323 "Fixed reachability and source-backed ranking-signal counts for summary JSON."
1324 .to_string(),
1325 ),
1326 (
1327 "summary.by_runtime_state".to_string(),
1328 "Fixed production-runtime coverage state counts for summary JSON.".to_string(),
1329 ),
1330 (
1331 "unresolved_edge_files".to_string(),
1332 "Number of client files whose import cone contains dynamic edges the graph could not follow."
1333 .to_string(),
1334 ),
1335 (
1336 "unresolved_callee_sites".to_string(),
1337 "Number of sink-shaped nodes whose callee could not be flattened to a static path."
1338 .to_string(),
1339 ),
1340 ]),
1341 metrics: BTreeMap::new(),
1342 rules,
1343 }
1344}
1345
1346#[must_use]
1348pub fn coverage_setup_meta() -> Value {
1349 json!({
1350 "docs_url": COVERAGE_SETUP_DOCS,
1351 "field_definitions": {
1352 "schema_version": "Coverage setup JSON contract version. Stays at \"1\" for additive opt-in fields such as _meta.",
1353 "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.",
1354 "package_manager": "Detected package manager used for install and run commands, or null when no package manager signal was found.",
1355 "runtime_targets": "Union of runtime targets across emitted members.",
1356 "members[]": "Per-runtime-workspace setup recipes. Pure aggregator roots and build-only libraries are omitted.",
1357 "members[].name": "Workspace package name from package.json, or the root directory name when package.json has no name.",
1358 "members[].path": "Workspace path relative to the command root. The root package is represented as \".\".",
1359 "members[].framework_detected": "Runtime framework detected for that member.",
1360 "members[].package_manager": "Package manager detected for that member, or inherited from the workspace root when no member-specific signal exists.",
1361 "members[].runtime_targets": "Runtime targets produced by that member.",
1362 "members[].files_to_edit": "Files in that member that should receive runtime beacon setup code.",
1363 "members[].snippets": "Copy-paste setup snippets for that member, with paths relative to the command root.",
1364 "members[].dockerfile_snippet": "Environment snippet for file-system capture in that member's containerized Node runtime, or null when not applicable.",
1365 "members[].warnings": "Actionable setup caveats discovered for that member.",
1366 "config_written": "Always null for --json because JSON setup is side-effect-free and never writes configuration.",
1367 "files_to_edit": "Compatibility copy of the primary member's files, with workspace prefixes when the primary member is not the root.",
1368 "snippets": "Compatibility copy of the primary member's snippets, with workspace prefixes when the primary member is not the root.",
1369 "dockerfile_snippet": "Environment snippet for file-system capture in containerized Node runtimes, or null when not applicable.",
1370 "commands": "Package-manager commands needed to install the runtime beacon and sidecar packages.",
1371 "next_steps": "Ordered setup workflow after applying the emitted snippets.",
1372 "warnings": "Actionable setup caveats discovered while building the recipe."
1373 },
1374 "enums": {
1375 "framework_detected": ["nextjs", "nestjs", "nuxt", "sveltekit", "astro", "remix", "vite", "plain_node", "unknown"],
1376 "runtime_targets": ["node", "browser"],
1377 "package_manager": ["npm", "pnpm", "yarn", "bun", null]
1378 },
1379 "warnings": {
1380 "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.",
1381 "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.",
1382 "Package manager was not detected": "No packageManager field or known lockfile was found. Commands fall back to npm.",
1383 "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."
1384 }
1385 })
1386}
1387
1388#[must_use]
1390pub fn coverage_analyze_meta() -> Value {
1391 json!({
1392 "docs_url": COVERAGE_ANALYZE_DOCS,
1393 "field_definitions": {
1394 "schema_version": "Standalone coverage analyze envelope version. \"1\" for the current shape.",
1395 "version": "fallow CLI version that produced this output.",
1396 "elapsed_ms": "Wall-clock milliseconds spent producing the report.",
1397 "runtime_coverage": "Same RuntimeCoverageReport block emitted by `fallow health --runtime-coverage`.",
1398 "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.",
1399 "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.",
1400 "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.",
1401 "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.",
1402 "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.",
1403 "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.",
1404 "runtime_coverage.findings[].evidence.static_status": "used = the function is reachable in the AST module graph; unused = it is dead by static analysis.",
1405 "runtime_coverage.findings[].evidence.test_coverage": "covered = the local test suite hits the function; not_covered otherwise.",
1406 "runtime_coverage.findings[].evidence.v8_tracking": "tracked = V8 observed the function during the capture window; untracked otherwise.",
1407 "runtime_coverage.findings[].actions[].type": "Suggested follow-up identifier. delete-cold-code is emitted on safe_to_delete; review-runtime on review_required.",
1408 "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.",
1409 "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.",
1410 "runtime_coverage.warnings[].code": "Stable warning identifier. cloud_functions_unmatched flags entries dropped because no AST/static counterpart was found locally."
1411 },
1412 "enums": {
1413 "data_source": ["local", "cloud"],
1414 "report_verdict": ["clean", "hot-path-touched", "cold-code-detected", "license-expired-grace", "unknown"],
1415 "finding_verdict": ["safe_to_delete", "review_required", "coverage_unavailable", "low_traffic", "active", "unknown"],
1416 "static_status": ["used", "unused"],
1417 "test_coverage": ["covered", "not_covered"],
1418 "v8_tracking": ["tracked", "untracked"],
1419 "action_type": ["delete-cold-code", "review-runtime"]
1420 },
1421 "warnings": {
1422 "no_runtime_data": "Cloud returned an empty runtime window. Either the period is too narrow or no traces have been ingested yet.",
1423 "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."
1424 }
1425 })
1426}
1427
1428#[cfg(test)]
1429mod tests {
1430 use super::*;
1431
1432 #[test]
1433 fn rule_by_id_finds_check_rule() {
1434 let rule = rule_by_id("fallow/unused-file").unwrap();
1435 assert_eq!(rule.name, "Unused Files");
1436 }
1437
1438 #[test]
1439 fn rule_by_id_finds_health_rule() {
1440 let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1441 assert_eq!(rule.name, "High Cyclomatic Complexity");
1442 }
1443
1444 #[test]
1445 fn rule_by_id_finds_dupes_rule() {
1446 let rule = rule_by_id("fallow/code-duplication").unwrap();
1447 assert_eq!(rule.name, "Code Duplication");
1448 }
1449
1450 #[test]
1451 fn rule_by_id_finds_security_rule() {
1452 let rule = rule_by_id("security/tainted-sink").unwrap();
1453 assert_eq!(rule.name, "Tainted Sink Candidates");
1454 }
1455
1456 #[test]
1457 fn rule_by_id_returns_none_for_unknown() {
1458 assert!(rule_by_id("fallow/nonexistent").is_none());
1459 assert!(rule_by_id("").is_none());
1460 }
1461
1462 #[test]
1463 fn rule_docs_url_format() {
1464 let rule = rule_by_id("fallow/unused-export").unwrap();
1465 let url = rule_docs_url(rule);
1466 assert!(url.starts_with("https://docs.fallow.tools/"));
1467 assert!(url.contains("unused-exports"));
1468 }
1469
1470 #[test]
1471 fn check_rules_all_have_fallow_prefix() {
1472 for rule in CHECK_RULES {
1473 assert!(
1474 rule.id.starts_with("fallow/"),
1475 "rule {} should start with fallow/",
1476 rule.id
1477 );
1478 }
1479 }
1480
1481 #[test]
1482 fn check_rules_all_have_docs_path() {
1483 for rule in CHECK_RULES {
1484 assert!(
1485 !rule.docs_path.is_empty(),
1486 "rule {} should have a docs_path",
1487 rule.id
1488 );
1489 }
1490 }
1491
1492 #[test]
1493 fn check_rules_no_duplicate_ids() {
1494 let mut seen = rustc_hash::FxHashSet::default();
1495 for rule in CHECK_RULES
1496 .iter()
1497 .chain(HEALTH_RULES)
1498 .chain(DUPES_RULES)
1499 .chain(SECURITY_RULES)
1500 {
1501 assert!(seen.insert(rule.id), "duplicate rule id: {}", rule.id);
1502 }
1503 }
1504
1505 #[test]
1506 fn check_meta_has_docs_and_rules() {
1507 let meta = check_meta();
1508 assert!(meta.get("docs").is_some());
1509 assert!(meta.get("rules").is_some());
1510 let rules = meta["rules"].as_object().unwrap();
1511 assert_eq!(rules.len(), CHECK_RULES.len());
1512 assert!(rules.contains_key("unused-file"));
1513 assert!(rules.contains_key("unused-export"));
1514 assert!(rules.contains_key("unused-type"));
1515 assert!(rules.contains_key("unused-dependency"));
1516 assert!(rules.contains_key("unused-dev-dependency"));
1517 assert!(rules.contains_key("unused-optional-dependency"));
1518 assert!(rules.contains_key("unused-enum-member"));
1519 assert!(rules.contains_key("unused-class-member"));
1520 assert!(rules.contains_key("unresolved-import"));
1521 assert!(rules.contains_key("unlisted-dependency"));
1522 assert!(rules.contains_key("duplicate-export"));
1523 assert!(rules.contains_key("type-only-dependency"));
1524 assert!(rules.contains_key("circular-dependency"));
1525 }
1526
1527 #[test]
1528 fn check_meta_documents_per_finding_auto_fixable() {
1529 let meta = check_meta();
1530 let defs = meta["field_definitions"].as_object().unwrap();
1531 let note = defs["actions[].auto_fixable"].as_str().unwrap();
1532 assert!(
1533 note.contains("PER FINDING"),
1534 "auto_fixable note must call out per-finding evaluation"
1535 );
1536 assert!(
1537 note.contains("remove-catalog-entry"),
1538 "auto_fixable note must cite remove-catalog-entry per-instance flip"
1539 );
1540 assert!(
1541 note.contains("used_in_workspaces"),
1542 "auto_fixable note must cite the dependency-action per-instance flip"
1543 );
1544 assert!(
1545 note.contains("ignoreExports"),
1546 "auto_fixable note must cite the duplicate-exports config-fixable flip"
1547 );
1548 assert!(defs.contains_key("actions[]"));
1549 }
1550
1551 #[test]
1552 fn health_and_dupes_meta_share_actions_field_definitions() {
1553 for meta in [health_meta(), dupes_meta()] {
1554 let defs = meta["field_definitions"].as_object().unwrap();
1555 assert_eq!(
1556 defs["actions[]"].as_str().unwrap(),
1557 ACTIONS_FIELD_DEFINITION,
1558 );
1559 assert_eq!(
1560 defs["actions[].auto_fixable"].as_str().unwrap(),
1561 ACTIONS_AUTO_FIXABLE_FIELD_DEFINITION,
1562 );
1563 }
1564 }
1565
1566 #[test]
1567 fn check_meta_rule_has_required_fields() {
1568 let meta = check_meta();
1569 let rules = meta["rules"].as_object().unwrap();
1570 for (key, value) in rules {
1571 assert!(value.get("name").is_some(), "rule {key} missing 'name'");
1572 assert!(
1573 value.get("description").is_some(),
1574 "rule {key} missing 'description'"
1575 );
1576 assert!(value.get("docs").is_some(), "rule {key} missing 'docs'");
1577 }
1578 }
1579
1580 #[test]
1581 fn health_meta_has_metrics() {
1582 let meta = health_meta();
1583 assert!(meta.get("docs").is_some());
1584 let metrics = meta["metrics"].as_object().unwrap();
1585 assert!(metrics.contains_key("cyclomatic"));
1586 assert!(metrics.contains_key("cognitive"));
1587 assert!(metrics.contains_key("maintainability_index"));
1588 assert!(metrics.contains_key("complexity_density"));
1589 assert!(metrics.contains_key("fan_in"));
1590 assert!(metrics.contains_key("fan_out"));
1591 }
1592
1593 #[test]
1594 fn dupes_meta_has_metrics() {
1595 let meta = dupes_meta();
1596 assert!(meta.get("docs").is_some());
1597 let metrics = meta["metrics"].as_object().unwrap();
1598 assert!(metrics.contains_key("duplication_percentage"));
1599 assert!(metrics.contains_key("token_count"));
1600 assert!(metrics.contains_key("clone_groups"));
1601 assert!(metrics.contains_key("clone_families"));
1602 }
1603
1604 #[test]
1605 fn coverage_setup_meta_has_docs_fields_enums_and_warnings() {
1606 let meta = coverage_setup_meta();
1607 assert_eq!(meta["docs_url"], COVERAGE_SETUP_DOCS);
1608 assert!(
1609 meta["field_definitions"]
1610 .as_object()
1611 .unwrap()
1612 .contains_key("members[]")
1613 );
1614 assert!(
1615 meta["field_definitions"]
1616 .as_object()
1617 .unwrap()
1618 .contains_key("config_written")
1619 );
1620 assert!(
1621 meta["field_definitions"]
1622 .as_object()
1623 .unwrap()
1624 .contains_key("members[].package_manager")
1625 );
1626 assert!(
1627 meta["field_definitions"]
1628 .as_object()
1629 .unwrap()
1630 .contains_key("members[].warnings")
1631 );
1632 assert!(
1633 meta["enums"]
1634 .as_object()
1635 .unwrap()
1636 .contains_key("framework_detected")
1637 );
1638 assert!(
1639 meta["warnings"]
1640 .as_object()
1641 .unwrap()
1642 .contains_key("No runtime workspace members were detected")
1643 );
1644 assert!(
1645 meta["warnings"]
1646 .as_object()
1647 .unwrap()
1648 .contains_key("Package manager was not detected")
1649 );
1650 }
1651
1652 #[test]
1653 fn coverage_analyze_meta_documents_data_source_and_action_vocabulary() {
1654 let meta = coverage_analyze_meta();
1655 assert_eq!(meta["docs_url"], COVERAGE_ANALYZE_DOCS);
1656 let fields = meta["field_definitions"].as_object().unwrap();
1657 assert!(fields.contains_key("runtime_coverage.summary.data_source"));
1658 assert!(fields.contains_key("runtime_coverage.summary.last_received_at"));
1659 assert!(fields.contains_key("runtime_coverage.findings[].evidence.test_coverage"));
1660 assert!(fields.contains_key("runtime_coverage.findings[].actions[].type"));
1661 let enums = meta["enums"].as_object().unwrap();
1662 assert_eq!(enums["data_source"], json!(["local", "cloud"]));
1663 assert_eq!(enums["test_coverage"], json!(["covered", "not_covered"]));
1664 assert_eq!(enums["v8_tracking"], json!(["tracked", "untracked"]));
1665 assert_eq!(
1666 enums["action_type"],
1667 json!(["delete-cold-code", "review-runtime"])
1668 );
1669 let warnings = meta["warnings"].as_object().unwrap();
1670 assert!(warnings.contains_key("cloud_functions_unmatched"));
1671 }
1672
1673 #[test]
1674 fn health_rules_all_have_fallow_prefix() {
1675 for rule in HEALTH_RULES {
1676 assert!(
1677 rule.id.starts_with("fallow/"),
1678 "health rule {} should start with fallow/",
1679 rule.id
1680 );
1681 }
1682 }
1683
1684 #[test]
1685 fn health_rules_all_have_docs_path() {
1686 for rule in HEALTH_RULES {
1687 assert!(
1688 !rule.docs_path.is_empty(),
1689 "health rule {} should have a docs_path",
1690 rule.id
1691 );
1692 }
1693 }
1694
1695 #[test]
1696 fn health_rules_all_have_non_empty_fields() {
1697 for rule in HEALTH_RULES {
1698 assert!(
1699 !rule.name.is_empty(),
1700 "health rule {} missing name",
1701 rule.id
1702 );
1703 assert!(
1704 !rule.short.is_empty(),
1705 "health rule {} missing short description",
1706 rule.id
1707 );
1708 assert!(
1709 !rule.full.is_empty(),
1710 "health rule {} missing full description",
1711 rule.id
1712 );
1713 }
1714 }
1715
1716 #[test]
1717 fn dupes_rules_all_have_fallow_prefix() {
1718 for rule in DUPES_RULES {
1719 assert!(
1720 rule.id.starts_with("fallow/"),
1721 "dupes rule {} should start with fallow/",
1722 rule.id
1723 );
1724 }
1725 }
1726
1727 #[test]
1728 fn dupes_rules_all_have_docs_path() {
1729 for rule in DUPES_RULES {
1730 assert!(
1731 !rule.docs_path.is_empty(),
1732 "dupes rule {} should have a docs_path",
1733 rule.id
1734 );
1735 }
1736 }
1737
1738 #[test]
1739 fn dupes_rules_all_have_non_empty_fields() {
1740 for rule in DUPES_RULES {
1741 assert!(!rule.name.is_empty(), "dupes rule {} missing name", rule.id);
1742 assert!(
1743 !rule.short.is_empty(),
1744 "dupes rule {} missing short description",
1745 rule.id
1746 );
1747 assert!(
1748 !rule.full.is_empty(),
1749 "dupes rule {} missing full description",
1750 rule.id
1751 );
1752 }
1753 }
1754
1755 #[test]
1756 fn security_rules_all_have_security_prefix() {
1757 for rule in SECURITY_RULES {
1758 assert!(
1759 rule.id.starts_with("security/"),
1760 "security rule {} should start with security/",
1761 rule.id
1762 );
1763 }
1764 }
1765
1766 #[test]
1767 fn security_rules_all_have_docs_path() {
1768 for rule in SECURITY_RULES {
1769 assert_eq!(
1770 rule.docs_path, "cli/security",
1771 "security rule {} should point at security docs",
1772 rule.id
1773 );
1774 }
1775 }
1776
1777 #[test]
1778 fn security_rules_all_have_non_empty_fields() {
1779 for rule in SECURITY_RULES {
1780 assert!(
1781 !rule.name.is_empty(),
1782 "security rule {} missing name",
1783 rule.id
1784 );
1785 assert!(
1786 !rule.short.is_empty(),
1787 "security rule {} missing short description",
1788 rule.id
1789 );
1790 assert!(
1791 !rule.full.is_empty(),
1792 "security rule {} missing full description",
1793 rule.id
1794 );
1795 }
1796 }
1797
1798 #[test]
1799 fn check_rules_all_have_non_empty_fields() {
1800 for rule in CHECK_RULES {
1801 assert!(!rule.name.is_empty(), "check rule {} missing name", rule.id);
1802 assert!(
1803 !rule.short.is_empty(),
1804 "check rule {} missing short description",
1805 rule.id
1806 );
1807 assert!(
1808 !rule.full.is_empty(),
1809 "check rule {} missing full description",
1810 rule.id
1811 );
1812 }
1813 }
1814
1815 #[test]
1816 fn rule_docs_url_health_rule() {
1817 let rule = rule_by_id("fallow/high-cyclomatic-complexity").unwrap();
1818 let url = rule_docs_url(rule);
1819 assert!(url.starts_with("https://docs.fallow.tools/"));
1820 assert!(url.contains("health"));
1821 }
1822
1823 #[test]
1824 fn rule_docs_url_dupes_rule() {
1825 let rule = rule_by_id("fallow/code-duplication").unwrap();
1826 let url = rule_docs_url(rule);
1827 assert!(url.starts_with("https://docs.fallow.tools/"));
1828 assert!(url.contains("duplication"));
1829 }
1830
1831 #[test]
1832 fn rule_docs_url_security_rule() {
1833 let rule = rule_by_id("security/sql-injection").unwrap();
1834 let url = rule_docs_url(rule);
1835 assert_eq!(url, "https://docs.fallow.tools/cli/security");
1836 }
1837
1838 #[test]
1839 fn health_meta_all_metrics_have_name_and_description() {
1840 let meta = health_meta();
1841 let metrics = meta["metrics"].as_object().unwrap();
1842 for (key, value) in metrics {
1843 assert!(
1844 value.get("name").is_some(),
1845 "health metric {key} missing 'name'"
1846 );
1847 assert!(
1848 value.get("description").is_some(),
1849 "health metric {key} missing 'description'"
1850 );
1851 assert!(
1852 value.get("interpretation").is_some(),
1853 "health metric {key} missing 'interpretation'"
1854 );
1855 }
1856 }
1857
1858 #[test]
1859 fn health_meta_has_all_expected_metrics() {
1860 let meta = health_meta();
1861 let metrics = meta["metrics"].as_object().unwrap();
1862 let expected = [
1863 "cyclomatic",
1864 "cognitive",
1865 "line_count",
1866 "lines",
1867 "maintainability_index",
1868 "complexity_density",
1869 "dead_code_ratio",
1870 "fan_in",
1871 "fan_out",
1872 "score",
1873 "weighted_commits",
1874 "trend",
1875 "priority",
1876 "efficiency",
1877 "effort",
1878 "confidence",
1879 "bus_factor",
1880 "contributor_count",
1881 "share",
1882 "stale_days",
1883 "drift",
1884 "unowned",
1885 "runtime_coverage_verdict",
1886 "runtime_coverage_state",
1887 "runtime_coverage_confidence",
1888 "production_invocations",
1889 "percent_dead_in_production",
1890 ];
1891 for key in &expected {
1892 assert!(
1893 metrics.contains_key(*key),
1894 "health_meta missing expected metric: {key}"
1895 );
1896 }
1897 }
1898
1899 #[test]
1900 fn dupes_meta_all_metrics_have_name_and_description() {
1901 let meta = dupes_meta();
1902 let metrics = meta["metrics"].as_object().unwrap();
1903 for (key, value) in metrics {
1904 assert!(
1905 value.get("name").is_some(),
1906 "dupes metric {key} missing 'name'"
1907 );
1908 assert!(
1909 value.get("description").is_some(),
1910 "dupes metric {key} missing 'description'"
1911 );
1912 }
1913 }
1914
1915 #[test]
1916 fn dupes_meta_has_line_count() {
1917 let meta = dupes_meta();
1918 let metrics = meta["metrics"].as_object().unwrap();
1919 assert!(metrics.contains_key("line_count"));
1920 }
1921
1922 #[test]
1923 fn check_docs_url_valid() {
1924 assert!(CHECK_DOCS.starts_with("https://"));
1925 assert!(CHECK_DOCS.contains("dead-code"));
1926 }
1927
1928 #[test]
1929 fn health_docs_url_valid() {
1930 assert!(HEALTH_DOCS.starts_with("https://"));
1931 assert!(HEALTH_DOCS.contains("health"));
1932 }
1933
1934 #[test]
1935 fn dupes_docs_url_valid() {
1936 assert!(DUPES_DOCS.starts_with("https://"));
1937 assert!(DUPES_DOCS.contains("dupes"));
1938 }
1939
1940 #[test]
1941 fn check_meta_docs_url_matches_constant() {
1942 let meta = check_meta();
1943 assert_eq!(meta["docs"].as_str().unwrap(), CHECK_DOCS);
1944 }
1945
1946 #[test]
1947 fn health_meta_docs_url_matches_constant() {
1948 let meta = health_meta();
1949 assert_eq!(meta["docs"].as_str().unwrap(), HEALTH_DOCS);
1950 }
1951
1952 #[test]
1953 fn dupes_meta_docs_url_matches_constant() {
1954 let meta = dupes_meta();
1955 assert_eq!(meta["docs"].as_str().unwrap(), DUPES_DOCS);
1956 }
1957
1958 #[test]
1959 fn rule_by_id_finds_all_check_rules() {
1960 for rule in CHECK_RULES {
1961 assert!(
1962 rule_by_id(rule.id).is_some(),
1963 "rule_by_id should find check rule {}",
1964 rule.id
1965 );
1966 }
1967 }
1968
1969 #[test]
1970 fn rule_by_id_finds_all_health_rules() {
1971 for rule in HEALTH_RULES {
1972 assert!(
1973 rule_by_id(rule.id).is_some(),
1974 "rule_by_id should find health rule {}",
1975 rule.id
1976 );
1977 }
1978 }
1979
1980 #[test]
1981 fn rule_by_id_finds_all_dupes_rules() {
1982 for rule in DUPES_RULES {
1983 assert!(
1984 rule_by_id(rule.id).is_some(),
1985 "rule_by_id should find dupes rule {}",
1986 rule.id
1987 );
1988 }
1989 }
1990
1991 #[test]
1992 fn rule_by_id_finds_all_security_rules() {
1993 for rule in SECURITY_RULES {
1994 assert!(
1995 rule_by_id(rule.id).is_some(),
1996 "rule_by_id should find security rule {}",
1997 rule.id
1998 );
1999 }
2000 }
2001
2002 #[test]
2003 fn check_rules_count() {
2004 assert_eq!(CHECK_RULES.len(), 26);
2005 }
2006
2007 #[test]
2008 fn health_rules_count() {
2009 assert_eq!(HEALTH_RULES.len(), 16);
2010 }
2011
2012 #[test]
2013 fn dupes_rules_count() {
2014 assert_eq!(DUPES_RULES.len(), 1);
2015 }
2016
2017 #[test]
2018 fn security_rules_count() {
2019 assert_eq!(
2020 SECURITY_RULES.len(),
2021 matcher_entries_from_security_catalogue().len() + 3
2022 );
2023 }
2024
2025 #[test]
2026 fn security_rules_cover_every_catalogue_matcher() {
2027 let mut rule_ids = rustc_hash::FxHashSet::default();
2028 for rule in SECURITY_RULES {
2029 rule_ids.insert(rule.id);
2030 }
2031
2032 for matcher in matcher_entries_from_security_catalogue() {
2033 let rule_id = format!("security/{}", matcher.id);
2034 assert!(
2035 rule_ids.contains(rule_id.as_str()),
2036 "security matcher {} has no explain rule",
2037 matcher.id
2038 );
2039 }
2040 }
2041
2042 #[test]
2043 fn security_catalogue_rules_match_catalogue_title_and_cwe() {
2044 for matcher in matcher_entries_from_security_catalogue() {
2045 let rule_id = format!("security/{}", matcher.id);
2046 let rule = rule_by_id(&rule_id)
2047 .unwrap_or_else(|| panic!("security matcher {} has no explain rule", matcher.id));
2048 let cwe = format!("CWE-{}", matcher.cwe);
2049 assert_eq!(
2050 rule.name, matcher.title,
2051 "security matcher {} has stale explain title",
2052 matcher.id
2053 );
2054 assert!(
2055 rule.short.contains(&cwe),
2056 "security matcher {} explain summary does not mention {cwe}",
2057 matcher.id
2058 );
2059 assert!(
2060 rule.full.contains(&cwe),
2061 "security matcher {} explain rationale does not mention {cwe}",
2062 matcher.id
2063 );
2064 }
2065 }
2066
2067 #[test]
2073 fn every_rule_declares_a_category() {
2074 let allowed = [
2075 "Dead code",
2076 "Dependencies",
2077 "Duplication",
2078 "Health",
2079 "Architecture",
2080 "Suppressions",
2081 "Security",
2082 "Policy",
2083 ];
2084 for rule in CHECK_RULES
2085 .iter()
2086 .chain(HEALTH_RULES)
2087 .chain(DUPES_RULES)
2088 .chain(SECURITY_RULES)
2089 {
2090 assert!(
2091 !rule.category.is_empty(),
2092 "rule {} has empty category",
2093 rule.id
2094 );
2095 assert!(
2096 allowed.contains(&rule.category),
2097 "rule {} has unrecognised category {:?}; add to allowlist or pick from {:?}",
2098 rule.id,
2099 rule.category,
2100 allowed
2101 );
2102 }
2103 }
2104
2105 #[derive(Debug)]
2106 struct MatcherEntry {
2107 id: &'static str,
2108 title: &'static str,
2109 cwe: &'static str,
2110 }
2111
2112 fn matcher_entries_from_security_catalogue() -> Vec<MatcherEntry> {
2113 let toml = include_str!("../../core/data/security_matchers.toml");
2114 let mut entries = Vec::new();
2115 let mut in_matcher = false;
2116 let mut id = None;
2117 let mut title = None;
2118 let mut cwe = None;
2119
2120 for line in toml.lines() {
2121 let trimmed = line.trim();
2122 if trimmed == "[[matcher]]" {
2123 if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2124 entries.push(MatcherEntry { id, title, cwe });
2125 }
2126 in_matcher = true;
2127 continue;
2128 }
2129 if trimmed.starts_with("[[") {
2130 if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2131 entries.push(MatcherEntry { id, title, cwe });
2132 }
2133 in_matcher = false;
2134 continue;
2135 }
2136 if !in_matcher {
2137 continue;
2138 }
2139 if let Some(value) = trimmed
2140 .strip_prefix("id = \"")
2141 .and_then(|value| value.strip_suffix('"'))
2142 {
2143 id = Some(value);
2144 } else if let Some(value) = trimmed
2145 .strip_prefix("title = \"")
2146 .and_then(|value| value.strip_suffix('"'))
2147 {
2148 title = Some(value);
2149 } else if let Some(value) = trimmed.strip_prefix("cwe = ") {
2150 cwe = Some(value);
2151 }
2152 }
2153
2154 if let (Some(id), Some(title), Some(cwe)) = (id.take(), title.take(), cwe.take()) {
2155 entries.push(MatcherEntry { id, title, cwe });
2156 }
2157
2158 let mut seen = rustc_hash::FxHashSet::default();
2159 entries
2160 .into_iter()
2161 .filter(|entry| seen.insert(entry.id))
2162 .collect()
2163 }
2164}