@blundergoat/gruff-ts 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
package/src/rules.ts CHANGED
@@ -1,126 +1,94 @@
1
- // Rule descriptor catalogue that defines the public rule metadata emitted by list-rules and reports.
2
- import type { RuleDescriptor } from "./types.ts";
1
+ // Canonical catalogue of all active gruff-ts rules, severities, confidences, thresholds, and remediation guidance.
2
+ //
3
+ // Single source of truth consumed by `list-rules`, `gruff-ts init`, profile expansion, config validation, and report renderers.
4
+ // Order and IDs stay deterministic so CLI listings, baselines, and documentation checks never drift.
5
+ import type { Confidence, RuleDescriptor } from "./types.ts";
3
6
 
4
7
  const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
5
- { ruleId: "complexity.cognitive", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with high combined branch and nesting complexity.", remediation: "Split nested decisions into smaller named functions. Or raise rules.complexity.cognitive.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 },
6
- { ruleId: "complexity.cyclomatic", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with many independent branch paths.", remediation: "Reduce branching or move policy tables out of imperative code. Or raise rules.complexity.cyclomatic.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 }, { ruleId: "dead-code.unused-private-method", pillar: "dead-code", severity: "advisory", confidence: "low", description: "Flags private methods without an apparent same-file call site.", remediation: "Remove the method or add a direct call site." },
7
- { ruleId: "design.circular-import", pillar: "design", severity: "warning", confidence: "medium", description: "Flags strongly connected relative import components that include the scan surface.", remediation: "Extract the shared contract or invert one dependency." },
8
- { ruleId: "design.deep-relative-import", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags relative imports that climb too many parent directories.", remediation: "Move the shared module closer or add a local boundary. Or raise rules.design.deep-relative-import.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 2 },
9
- { ruleId: "design.large-module-concentration", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags a production module that dominates project source lines.", remediation: "Split unrelated responsibilities once stable seams are visible. Or raise rules.design.large-module-concentration.threshold or tune minFiles, minLines under rules.design.large-module-concentration.options.", threshold: 55, optionKeys: ["minFiles", "minLines"] },
10
- { ruleId: "design.package-bin-missing", pillar: "design", severity: "warning", confidence: "high", description: "Flags package bin entries that point at missing files.", remediation: "Update the bin path or add the executable file." },
8
+ { ruleId: "complexity.cyclomatic", pillar: "complexity", severity: "warning", confidence: "high", isEnabledByDefault: false, description: "Counts a base path plus if, loop, catch, ternary, &&, and || nodes, and each switch with a non-default case once; default, ??, optional chains, and non-null assertions add zero.", remediation: "Simplify the execution path: return early, merge branches that lead to the same result, and drop flags that steer later branches. Moving branches into helpers leaves the path as hard to follow.", threshold: 15 }, { ruleId: "dead-code.unused-private-method", pillar: "dead-code", severity: "advisory", confidence: "low", description: "Flags private methods without an apparent same-file call site.", remediation: "Remove the method or add a direct call site.", falsePositiveShapes: [{ shape: "A private method reached only through non-literal dispatch - bracket access such as `this[\"handleRetry\"]()`, a string-keyed handler table, or a decorator/framework lifecycle hook - because the string form is blanked by the comment/string mask before counting, so neither the `name(` counter nor the `this.name` counter ever sees it.", mitigation: "Add a direct `this.handleRetry(...)` call site (or a typed dispatch map holding `this.handleRetry` rather than the string name), or set `rules.dead-code.unused-private-method.enabled: false`." }, { shape: "A private method exercised only from a sibling test file through an `(instance as any).method()` cast, since `analyseDeadCode` is invoked per file from the analyser and has no cross-file view of usage.", mitigation: "Drop `private` if the method is genuinely part of the surface under test, or set `rules.dead-code.unused-private-method.enabled: false`." }] },
9
+ { ruleId: "design.circular-import", pillar: "design", severity: "warning", confidence: "medium", description: "Flags strongly connected relative import components that include the scan surface.", remediation: "Extract the shared contract or invert one dependency.", falsePositiveShapes: [{ shape: "A cycle completed only by an inline type-only specifier such as `import { type Config } from \"./b.ts\"`: `isTypeOnlyImportStatement` matches only the statement-level `import type` / `export type` form, so the inline `{ type ... }` form is recorded as a runtime edge and joins the SCC even though it is erased at compile time.", mitigation: "Rewrite the specifier as a statement-level `import type { Config } from \"./b.ts\"`, which `circularImportTargets` then excludes from the graph; failing that, set `rules.design.circular-import.enabled: false`." }, { shape: "A barrel/index re-export facade: `resolveRelativeImport` tries barrel candidates, so a module importing from its own directory's `index.ts` while that barrel re-exports the module forms an SCC that bundlers and Node resolve without incident.", mitigation: "Import the concrete module path instead of the barrel from inside the barrel's own directory, or set `rules.design.circular-import.enabled: false`." }] },
10
+ { ruleId: "design.large-module-concentration", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags a production module that dominates project source lines.", remediation: "Split unrelated responsibilities into smaller modules once stable seams are visible.", threshold: 55, optionKeys: ["minFiles", "minLines"], falsePositiveShapes: [{ shape: "A single-purpose data module - a generated catalogue, a lookup table, or one long constant literal - legitimately holds most production lines while containing no mixed responsibilities to split.", mitigation: "Raise `rules.design.large-module-concentration.threshold` above the observed share, or raise `rules.design.large-module-concentration.options.minLines` so data modules of that size stop qualifying." }, { shape: "A project just over the file-count floor (four production sources by default) where one entrypoint naturally dominates simply because there are so few peers to dilute the share.", mitigation: "Raise `rules.design.large-module-concentration.options.minFiles` so the rule waits until the project is large enough for the share to mean something." }] },
11
+ { ruleId: "design.package-bin-missing", pillar: "design", severity: "warning", confidence: "high", description: "Flags package bin entries that point at missing files; unbuilt dist, build, or lib targets with a build script report as advisory.", remediation: "Update the bin path, run the package build script, or add the executable file." },
11
12
  { ruleId: "design.package-bin-not-executable", pillar: "design", severity: "warning", confidence: "high", description: "Flags package bin targets that are not executable.", remediation: "Make the bin target executable and keep its shebang valid." },
12
- { ruleId: "docs.fixture-purpose-missing", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags large or scanner-relevant fixtures without a nearby purpose comment.", remediation: "Explain what scanner path, regression, or fixture behavior the source covers." },
13
- { ruleId: "docs.magic-threshold-without-rationale", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags threshold-like numeric values without a nearby rationale comment.", remediation: "Explain the threshold, limit, budget, or default near the value." },
14
- { ruleId: "docs.missing-error-behavior-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags commented functions whose error behavior is not described.", remediation: "Document thrown errors, diagnostics, exits, reports, or recovery behavior." },
15
- { ruleId: "docs.missing-exported-function-doc", pillar: "documentation", severity: "warning", confidence: "medium", description: "Flags exported functions without a leading maintainer comment.", remediation: "Add a JSDoc or line comment explaining the exported API's contract, since public surface has a higher cost of omission." },
16
- { ruleId: "docs.missing-file-overview", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags source files without a top-of-file purpose comment.", remediation: "Add a brief file overview before imports or declarations." },
17
- { ruleId: "docs.missing-internal-function-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags internal helper functions without a leading maintainer comment.", remediation: "Add a short comment explaining the helper's role; internal helpers are advisory, exported surface fires the warning variant." },
18
- { ruleId: "docs.missing-interface-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags interfaces without a leading maintainer comment.", remediation: "Add a short JSDoc or line comment explaining the interface contract." },
19
- { ruleId: "docs.missing-invariant-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags commented declarations that own schema, fingerprint, baseline, or determinism contracts without saying so.", remediation: "Document the invariant, contract, schema, fingerprint, or deterministic behavior." },
20
- { ruleId: "docs.missing-param-tag", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags documented exports with parameters missing @param tags.", remediation: "Document every current parameter in the JSDoc." },
21
- { ruleId: "docs.missing-public-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags exported class, type, and enum APIs without a nearby doc comment.", remediation: "Add a short comment explaining the public API contract." },
22
- { ruleId: "docs.missing-return-tag", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags documented non-void exports without @returns.", remediation: "Document the returned value or remove stale JSDoc." },
23
- { ruleId: "docs.missing-side-effect-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags commented functions that perform observable side effects without naming them.", remediation: "Name the filesystem, process, environment, network, or persistence side effect." },
24
- { ruleId: "docs.missing-why-for-complex-code", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags comments on complex functions that do not explain why the shape exists.", remediation: "Explain the tradeoff, compatibility reason, or invariant behind the complex control flow." },
25
- { ruleId: "docs.stale-comment", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags comments that reference missing files, unknown rules, stale CLI flags, or the wrong declaration.", remediation: "Update the comment or add historical context explaining why it remains useful." },
26
- { ruleId: "docs.stale-param-tag", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags @param tags for parameters no longer in the signature.", remediation: "Remove stale tags or update the function signature." },
27
- { ruleId: "docs.suppression-without-rationale", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags lint, formatter, coverage, or tool suppressions without a maintainer rationale.", remediation: "Explain why the suppression is intentional, a false positive, or tracked elsewhere." },
28
- { ruleId: "docs.todo-without-tracking", pillar: "documentation", severity: "advisory", confidence: "high", description: "Flags TODO, FIXME, HACK, and XXX comments without tracking context.", remediation: "Attach a tracking URL, issue id, owner, date, ADR, or .goat-flow task reference." },
29
- { ruleId: "docs.useless-docblock", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags comments or docblocks that only restate the symbol name.", remediation: "Replace the comment with useful contract or behavior detail." },
13
+ { ruleId: "docs.fixture-purpose-missing", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags large or scanner-relevant fixtures without a nearby purpose comment.", remediation: "Add a comment on or directly above the fixture (or above the test declaration) explaining what scanner path, regression, or fixture behavior it covers.", falsePositiveShapes: [{ shape: "A long inline fixture whose intent is already stated in the enclosing test(\"...\") title rather than in a comment, so hasFixturePurposeComment finds nothing at either accepted position.", mitigation: "Move one sentence of that intent into a comment directly above the test declaration (or on the fixture), or set rules.docs.fixture-purpose-missing.enabled to false." }, { shape: "A 12+ line template literal in a test file that is expected/golden output rather than an input fixture, where a rationale comment adds nothing.", mitigation: "Add a short comment naming the scanner path it pins, or set rules.docs.fixture-purpose-missing.enabled to false." }] },
14
+ { ruleId: "docs.missing-error-behavior-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags commented functions that throw without an @throws tag.", remediation: "Add an @throws tag that names each error the function throws and when.", falsePositiveShapes: [{ shape: "A `throw` inside a nested callback or local helper defined in the commented function is attributed to the outer function by the body scan, even when the outer function itself never throws.", mitigation: "Add an @throws tag to the outer comment that says the nested function throws, not the call, or move the throwing helper out of the function, or set rules.docs.missing-error-behavior-doc.enabled to false." }] },
15
+ { ruleId: "docs.missing-exported-function-doc", pillar: "documentation", severity: "warning", confidence: "medium", description: "Flags exported functions without a leading maintainer comment; with `everyCallable` on either JSDoc tag rule, also public methods of exported classes.", remediation: "Add a JSDoc or line comment explaining the exported API's contract, since public surface has a higher cost of omission.", falsePositiveShapes: [{ shape: "A trivially self-evident exported wrapper or re-export shim (export function toJson(x: X): string { return JSON.stringify(x); }) where any honest comment restates the name.", mitigation: "Write a line comment that states the contract rather than the name, or set rules.docs.missing-exported-function-doc.enabled to false." }] },
16
+ { ruleId: "docs.missing-file-overview", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags source files without a top-of-file purpose comment.", remediation: "Add a brief file overview before imports or declarations.", falsePositiveShapes: [{ shape: "A file that opens with a directive prologue such as \"use client\"; or \"use strict\"; — only #! is skipped by hasFileOverviewComment, so the overview comment on the next line is never seen.", mitigation: "Move the overview comment above the directive, or set rules.docs.missing-file-overview.enabled to false." }, { shape: "A barrel or index file that only re-exports and genuinely has no purpose beyond its name, where the module's purpose is documented above its main export lower in the file.", mitigation: "Add a one-line comment above the first import, or set rules.docs.missing-file-overview.enabled to false." }] },
17
+ { ruleId: "docs.missing-internal-function-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags internal helper functions without a leading maintainer comment.", remediation: "Add a short comment explaining the helper's role; internal helpers are advisory, exported surface fires the warning variant.", falsePositiveShapes: [{ shape: "Small single-expression private helpers extracted purely to name a sub-step, where the name already is the documentation and every added comment restates it.", mitigation: "Set rules.docs.missing-internal-function-doc.enabled to false if the project documents only its exported surface; otherwise add a comment stating the helper's role rather than its name." }] },
18
+ { ruleId: "docs.missing-interface-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags interfaces without a leading maintainer comment.", remediation: "Add a short JSDoc or line comment explaining the interface contract.", falsePositiveShapes: [{ shape: "A small file-local interface that exists only as one function's argument bundle or an internal row shape, which interfaceDeclarations still matches because the export keyword is optional in its regex.", mitigation: "Add a one-line // comment above it (a line comment satisfies hasLeadingCommentBeforeLine), or set rules.docs.missing-interface-doc.enabled to false." }, { shape: "Interfaces in ambient or generated declaration surfaces where each member is already self-describing and per-interface prose is churn.", mitigation: "Exclude the generated path from the scan, or set rules.docs.missing-interface-doc.enabled to false." }] },
19
+ { ruleId: "docs.missing-invariant-doc", isEnabledByDefault: false, pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags commented declarations that own schema, fingerprint, baseline, or determinism contracts without saying so.", remediation: "Document the invariant, contract, schema, fingerprint, or deterministic behavior.", falsePositiveShapes: [{ shape: "Any helper that calls .sort( for purely local ordering — the signal regex matches the bare word sort, so a one-line comparator wrapper with no ordering contract to publish is flagged.", mitigation: "Say \"stable\" or \"deterministic\" in the comment if the ordering does matter, otherwise set rules.docs.missing-invariant-doc.enabled to false." }, { shape: "Any function that merely mentions the type name Finding (pervasive in analyser-shaped code) or a local variable named baseline, which trips the contract vocabulary without owning a contract.", mitigation: "Add one of invariant/contract/schema/fingerprint to the comment where a contract really exists, or set rules.docs.missing-invariant-doc.enabled to false." }] },
20
+ { ruleId: "docs.missing-param-tag", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags non-test documented exports with parameters missing @param tags; with `everyCallable`, requires `/** ... */` JSDoc with described @param tags across all non-test callables including slash- and block-commented helpers, while skipping test files.", remediation: "Document every current parameter in a `/** ... */` JSDoc block.", optionKeys: ["everyCallable"], falsePositiveShapes: [{ shape: "A docblock deliberately written as a one-paragraph prose summary with no tags at all — the rule then fires once per declaration, naming every parameter the prose may already describe.", mitigation: "Either add an @param line per parameter or set rules.docs.missing-param-tag.enabled to false for projects that document behaviour in prose." }, { shape: "Destructured or options-object parameters, where the docblock documents the individual option keys rather than the binding pattern the parser reports as the parameter name.", mitigation: "Add a single @param tag named after the whole options parameter alongside the per-key lines, or set rules.docs.missing-param-tag.enabled to false." }] },
21
+ { ruleId: "docs.missing-public-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags exported class, type, and enum APIs without a nearby doc comment.", remediation: "Add a short comment explaining the public API contract.", falsePositiveShapes: [{ shape: "An exported class, type, or enum documented with an ordinary // line comment — hasDocCommentBeforeLine accepts only /** openers and * continuation lines, so a perfectly good line comment does not count (unlike docs.missing-interface-doc, which accepts either).", mitigation: "Convert the comment to a /** ... */ block, or set rules.docs.missing-public-doc.enabled to false." }, { shape: "Self-evident exported type aliases produced by the exportedDeclarations regex, such as export type Foo = Bar re-export shims that restate an already-documented type.", mitigation: "Add a one-line /** ... */ naming the reason for the alias, or set rules.docs.missing-public-doc.enabled to false." }] },
22
+ { ruleId: "docs.missing-return-tag", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags non-test documented callables without a described @returns tag, including void callables; with `everyCallable`, requires `/** ... */` JSDoc across all non-test callables including slash- and block-commented helpers, while skipping test files.", remediation: "Document the return value or void return behavior in a `/** ... */` JSDoc `@returns` tag.", optionKeys: ["everyCallable"], falsePositiveShapes: [{ shape: "A docblock whose prose already explains the return behavior in a sentence rather than a tag — the rule checks for an explicit @return or @returns tag inside a `/** ... */` JSDoc block.", mitigation: "Convert that sentence into an @returns tag in a JSDoc block, or set rules.docs.missing-return-tag.enabled to false." }] },
23
+ { ruleId: "docs.missing-side-effect-doc", isEnabledByDefault: false, pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags commented functions that perform observable side effects without naming them.", remediation: "Name the filesystem, process, environment, network, or persistence side effect.", falsePositiveShapes: [{ shape: "A pure function whose name merely starts with write — the name arm of hasSideEffectSignal is /^(?:write|recordHistory|startDashboard)\\b/, so a string builder such as writeRow that touches nothing external is flagged.", mitigation: "Rename to a non-write verb (formatRow, renderRow), or set rules.docs.missing-side-effect-doc.enabled to false." }, { shape: "A function that genuinely has the side effect and documents it using different words (\"emits\", \"saves\", \"outputs\"), none of which appear in hasSideEffectMarker's nine-word vocabulary.", mitigation: "Reword the comment to use one of writes/reads/persists/mutates/starts/spawns/network/filesystem/environment." }] },
24
+ { ruleId: "docs.missing-why-for-complex-code", pillar: "documentation", severity: "advisory", confidence: "low", description: "Flags comments on complex functions that do not explain why the shape exists.", remediation: "Explain the tradeoff, compatibility reason, or invariant behind the complex control flow.", falsePositiveShapes: [{ shape: "A long but flat dispatch — a big switch or a table-driven mapper — that crosses the cyclomatic gate purely by branch count while having no design tradeoff to explain.", mitigation: "Raise rules.complexity.cyclomatic.threshold (this rule reuses that key), or set rules.docs.missing-why-for-complex-code.enabled to false." }, { shape: "A comment that does explain the why in words outside both of hasComplexWhyMarker's vocabularies (\"historical\", \"workaround\", \"the spec requires\"): it accepts causal words anywhere, and constraint or contrast words such as must, never, only or instead only in a comment that says more than the function's own name.", mitigation: "Include one of because/why/intentional/tradeoff/compat/avoid/preserve, a phrase like \"due to\" or \"required by\", or a stated constraint (must, never, always, only, otherwise, instead, unless, since, cannot, to avoid, to keep, needs to) in a comment that says more than the name." }] },
25
+ { ruleId: "docs.stale-param-tag", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags @param tags for parameters or destructured keys no longer in the signature; with `everyCallable` on `docs.missing-param-tag`, covers all non-test documented callables.", remediation: "Remove stale tags or update the function signature.", falsePositiveShapes: [{ shape: "An outer function whose docblock documents the parameters of the inner function it returns (curried factories, higher-order builders) — those tag names are absent from the outer signature.", mitigation: "Move those tags into the returned function's own docblock, or set rules.docs.stale-param-tag.enabled to false." }, { shape: "A docblock attached above an overload signature set where the tag names follow the implementation signature's names rather than the overload's.", mitigation: "Align the tag names with the signature the parser reports, or set rules.docs.stale-param-tag.enabled to false." }] },
26
+ { ruleId: "docs.suppression-without-rationale", pillar: "documentation", severity: "advisory", confidence: "low", description: "Flags lint, formatter, coverage, or tool suppressions without a maintainer rationale.", remediation: "Explain why the suppression is intentional, a false positive, or tracked elsewhere.", falsePositiveShapes: [{ shape: "A suppression whose rationale is written in plain prose that misses the accepted vocabulary — \"upstream types are wrong here\" contains no because/intentional/false positive/tracked in/reason:/ticket/URL.", mitigation: "Prefix the explanation with \"reason:\" or start it with \"because\", both of which hasSuppressionRationale accepts." }, { shape: "A prettier-ignore above a hand-aligned table, matrix, or ASCII diagram, where the formatting intent is self-evident from the very lines below it.", mitigation: "Add \"because the alignment is load-bearing\" to the directive line, or set rules.docs.suppression-without-rationale.enabled to false." }] },
27
+ { ruleId: "docs.todo-without-tracking", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags comments introduced by a TODO, FIXME, HACK, or XXX marker without tracking context; prose that only mentions a marker word stays quiet.", remediation: "Attach a tracking URL, issue id, owner, date, ADR, or .goat-flow task reference.", falsePositiveShapes: [{ shape: "A `TODO` names an owner in its marker or includes a numeric tracking reference in a form that `hasTodoTracking` misses.", mitigation: "Write the existing owner as `owner: <name>` or the numeric reference as `#<number>` in the comment." }, { shape: "A `TODO` sits immediately above a test whose title references the issue. The rule looks for tracking tokens in the comment text alone.", mitigation: "Copy the existing issue reference from the test title into the `TODO` as `#<number>` or an issue URL." }] },
30
28
  { ruleId: "modernisation.date-now-candidate", pillar: "modernisation", severity: "advisory", confidence: "high", description: "Flags verbose current-time expressions that can use Date.now().", remediation: "Use Date.now() for current epoch milliseconds." },
31
- { ruleId: "modernisation.double-cast", pillar: "modernisation", severity: "warning", confidence: "medium", description: "Flags casts through unknown or any into another type.", remediation: "Use a parser, type guard, or narrower assertion." },
32
- { ruleId: "modernisation.loose-equality", pillar: "modernisation", severity: "advisory", confidence: "medium", description: "Flags loose equality comparisons that may coerce values.", remediation: "Use === or !== unless intentionally checking nullish values." },
33
- { ruleId: "modernisation.non-null-assertion", pillar: "modernisation", severity: "warning", confidence: "medium", description: "Flags non-null assertions that bypass null checks.", remediation: "Narrow the value or handle null and undefined explicitly." },
34
- { ruleId: "modernisation.nullish-coalescing-candidate", pillar: "modernisation", severity: "advisory", confidence: "medium", description: "Flags || fallbacks that may erase valid falsy values.", remediation: "Use ?? when only null or undefined should fall back." },
35
- { ruleId: "modernisation.object-spread-candidate", pillar: "modernisation", severity: "advisory", confidence: "medium", description: "Flags Object.assign({}, ...) cloning that can use object spread.", remediation: "Use object spread when shallow-cloning plain objects." },
36
- { ruleId: "modernisation.optional-chaining-candidate", pillar: "modernisation", severity: "advisory", confidence: "medium", description: "Flags repeated guard-and-property access patterns.", remediation: "Use optional chaining for clearer null-safe access." },
37
- { ruleId: "modernisation.public-property", pillar: "modernisation", severity: "advisory", confidence: "high", description: "Flags public class properties that expose representation.", remediation: "Prefer readonly properties or accessors when invariants matter." },
38
- { ruleId: "modernisation.readonly-property-candidate", pillar: "modernisation", severity: "advisory", confidence: "medium", description: "Flags class properties that appear readonly-worthy.", remediation: "Mark the property readonly when mutation is not part of the contract." },
39
- { ruleId: "modernisation.ts-comment-without-rationale", pillar: "modernisation", severity: "warning", confidence: "medium", description: "Flags TypeScript suppression comments without a rationale.", remediation: "Add a short reason or remove the suppression." },
29
+ { ruleId: "modernisation.double-cast", pillar: "modernisation", severity: "warning", confidence: "medium", description: "Flags casts through unknown or any into another type.", remediation: "Use a parser, type guard, or narrower assertion.", falsePositiveShapes: [{ shape: "A deliberate, documented trust-boundary cast (parsing an external payload) still emits a finding; hasDoubleCastTrustBoundaryRationale only lowers severity to advisory when the same line carries a comment naming a trust boundary, validator, or TS2352.", mitigation: "Add an inline comment on the cast line naming the boundary (e.g. `// wire format, validated`) to keep it advisory, or set `rules.modernisation.double-cast.enabled` to false." }, { shape: "Test doubles that widen a partial literal into a full interface (`{} as unknown as Client`) fire exactly like production casts because there is no test-path gate.", mitigation: "Build the double through a typed factory or a `satisfies`-checked fixture, or disable `rules.modernisation.double-cast.enabled` for the run." }] },
30
+ { ruleId: "modernisation.non-null-assertion", pillar: "modernisation", severity: "warning", confidence: "medium", description: "Flags non-null assertions that bypass null checks.", remediation: "Narrow the value or handle null and undefined explicitly.", falsePositiveShapes: [{ shape: "An assertion that is provably safe from a guard earlier in the same function (`if (!user) return; … user!.id`): the check is per-line regex matching with no flow analysis, so the preceding narrowing is invisible to it.", mitigation: "Bind the narrowed value to a local (`const found = user; …`) so the `!` disappears, or set `rules.modernisation.non-null-assertion.enabled` to false." }, { shape: "A single chained expression such as `a!.b!.c` emits one finding per `!`, so one design decision is counted several times in the report.", mitigation: "Narrow once into a local before the chain, which collapses the repeated assertions into a single guarded access." }] },
31
+ { ruleId: "modernisation.readonly-property-candidate", pillar: "modernisation", severity: "advisory", confidence: "medium", description: "Flags private class fields their class assigns only in its own constructor.", remediation: "Mark the property readonly when mutation is not part of the contract.", falsePositiveShapes: [{ shape: "A private field changed only through a path the syntax walk does not name, such as `Reflect.set(this, ...)`, `Object.defineProperty(this, ...)` or an untyped alias written outside the class: marking it readonly still compiles, but the field does change after construction.", mitigation: "Leave the field mutable and set `rules.modernisation.readonly-property-candidate.enabled` to false for classes that hold mutable state by design." }] },
32
+ { ruleId: "modernisation.ts-comment-without-rationale", pillar: "modernisation", severity: "warning", confidence: "medium", description: "Flags TypeScript suppression comments without a rationale.", remediation: "Add a short reason on the directive line or in the `//` comment lines directly above it, or remove the suppression.", falsePositiveShapes: [{ shape: "A terse but adequate reason of one or two words (`// @ts-expect-error legacy shim`) fails the three-word bar in hasDirectiveRationale and is reported as unexplained.", mitigation: "Expand to three or more words, or include a tracking token such as an issue id or URL, both of which the heuristic accepts." }] },
40
33
  { ruleId: "modernisation.tsconfig-exact-optional-disabled", pillar: "modernisation", severity: "warning", confidence: "high", description: "Flags tsconfig files without exactOptionalPropertyTypes enabled.", remediation: "Enable exactOptionalPropertyTypes unless migration is blocked." },
41
34
  { ruleId: "modernisation.tsconfig-index-safety-disabled", pillar: "modernisation", severity: "warning", confidence: "high", description: "Flags tsconfig files without noUncheckedIndexedAccess enabled.", remediation: "Enable noUncheckedIndexedAccess unless migration is blocked." },
42
35
  { ruleId: "modernisation.tsconfig-strict-disabled", pillar: "modernisation", severity: "warning", confidence: "high", description: "Flags tsconfig files without strict mode enabled.", remediation: "Enable strict unless migration is blocked." },
43
36
  { ruleId: "modernisation.var-declaration", pillar: "modernisation", severity: "advisory", confidence: "high", description: "Flags var declarations.", remediation: "Use let or const with the narrowest useful scope." },
44
- { ruleId: "naming.acronym-case", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags mixed casings of a known acronym in one file.", remediation: "Use one casing for each acronym throughout the file. Or extend allowlists.knownAcronyms with project-specific values.", allowlistKeys: ["knownAcronyms"] },
45
- { ruleId: "naming.boolean-prefix", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean names without intent-revealing prefixes on declarations, function parameters (typed `: boolean` or with `= true|false` default), and interface/type-literal fields.", remediation: "Use prefixes such as is, has, can, should, or will. Or extend allowlists.booleanPrefixes / allowlists.acceptedBooleanNames for project-specific contract names.", allowlistKeys: ["booleanPrefixes", "acceptedBooleanNames"] },
46
- { ruleId: "naming.class-file-mismatch", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags exported classes whose name differs from the file name.", remediation: "Rename the class or file so the primary export is easy to locate." },
47
- { ruleId: "naming.generic-function", pillar: "naming", severity: "advisory", confidence: "high", description: "Flags generic function names that hide intent.", remediation: "Name the domain action instead of a generic operation. Or remove the name from allowlists.bannedGenericNames if your project does not consider it generic.", allowlistKeys: ["bannedGenericNames"] },
48
- { ruleId: "naming.generic-parameter", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags placeholder parameter names in multi-parameter, long, exported, or complex functions.", remediation: "Use a name that describes the parameter's role. Or tune minCyclomatic, minLineCount, minParameters under rules.naming.generic-parameter.options.", optionKeys: ["minCyclomatic", "minLineCount", "minParameters"] },
49
- { ruleId: "naming.hungarian-notation", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags identifiers named after storage type prefixes.", remediation: "Name the domain concept instead of the storage type. Or remove the prefix from allowlists.hungarianPrefixes if your project does not consider it Hungarian-style.", allowlistKeys: ["hungarianPrefixes"] },
50
- { ruleId: "naming.identifier-quality", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags placeholder or numbered identifiers on declarations, function parameters, and destructured locals.", remediation: "Use names that explain domain role or intent. Or remove the name from allowlists.placeholderNames if your project considers it valid.", allowlistKeys: ["placeholderNames"] },
51
- { ruleId: "naming.inconsistent-casing", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags the same canonical identifier appearing in two different surface forms (for example CONSTANT_CASE and camelCase) in one file.", remediation: "Choose one form and use it consistently within the file." },
52
- { ruleId: "naming.negative-boolean", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean identifiers framed as a negation on declarations, parameters, and interface fields.", remediation: "Invert the framing so callers do not read a double negation. Or extend allowlists.negativeBooleanAllowed with project-specific values.", allowlistKeys: ["negativeBooleanAllowed"] },
53
- { ruleId: "naming.short-variable", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags very short variable names outside common loop counters; covers declarations, function parameters, and destructured locals.", remediation: "Use a name that describes the domain role. Or extend allowlists.acceptedAbbreviations with project-specific values.", allowlistKeys: ["acceptedAbbreviations"] },
54
- { ruleId: "security.async-foreach", pillar: "security", severity: "warning", confidence: "medium", description: "Flags async callbacks passed to forEach.", remediation: "Use for...of with await, Promise.all, or an explicit queue." },
37
+ { ruleId: "naming.class-file-mismatch", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags a sole public class whose name differs from the file name.", remediation: "Rename the class or file, or add the exact fileBase:ClassName pair to allowlists.acceptedClassFilePairs.", allowlistKeys: ["acceptedClassFilePairs"], falsePositiveShapes: [{ shape: "A conventional entry file - `export default class UserService {}` in `index.ts`, or a role-named `handler.ts` holding one domain class - is flagged, because only the literal name \"default\" is exempted, not a named default export in a convention-named file.", mitigation: "Add the exact lowercase pair (for example `index:UserService`) to allowlists.acceptedClassFilePairs." }, { shape: "When the shared parse is unavailable the detector falls back to the legacy directly-exported inventory, which can undercount a module's other public declarations and make a class look like the sole public export of a multi-export feature module.", mitigation: "Add the fileBase:ClassName pair to allowlists.acceptedClassFilePairs, or export the class from a file named after it so the normalised-name check passes." }] },
38
+ { ruleId: "naming.identifier-quality", pillar: "naming", severity: "advisory", confidence: "low", description: "Flags placeholder or numbered identifiers on declarations, function parameters, and destructured locals.", remediation: "Use names that explain domain role or intent. Or remove the name from allowlists.placeholderNames if your project considers it valid.", allowlistKeys: ["placeholderNames"], falsePositiveShapes: [{ shape: "A thin generic wrapper where the placeholder word IS the correct name: `const data = await response.json()` in a fetch helper, or `item` as the element of a genuinely type-parameterised list utility.", mitigation: "Remove that word from allowlists.placeholderNames (the key replaces the built-in list of foo/bar/baz/tmp/temp/thing/stuff/data/value/item), or rename to the domain noun." }, { shape: "Numbered operands whose digit carries real meaning - `value1` and `value2` in a pair comparison, `item2` in a two-column mapping - are reported as \"numbered\" because the stem matches, independent of context.", mitigation: "Rename to role names (`left`/`right`), or set rules.naming.identifier-quality.enabled to false; NUMBERED_PLACEHOLDER_STEMS is a built-in constant and is not exposed as a config key." }] },
39
+ { ruleId: "naming.short-variable", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags very short variable names outside common loop counters; covers declarations, function parameters, and destructured locals.", remediation: "Use a name that describes the domain role. Or extend allowlists.acceptedAbbreviations with project-specific values.", allowlistKeys: ["acceptedAbbreviations"], falsePositiveShapes: [{ shape: "Two-character domain abbreviations outside the default set - `el`, `fn`, `ok`, `ts`, `dx` - are flagged wherever they are declared or destructured, even when the surrounding code makes their meaning obvious.", mitigation: "Add them to allowlists.acceptedAbbreviations (the key replaces the built-in list of age/app/db/fs/id/io/key/log/max/min/now/raw/rx/tx/ui/url, so restate the defaults you still want)." }, { shape: "A for-of binding whose body exceeds the hard-coded ten-line span still fires, so `for (const f of files) { ... }` over a 12-line body is reported although the binding's lifetime is still just that loop.", mitigation: "Rename the binding to the element's domain noun, or add the letter to allowlists.acceptedAbbreviations; the ten-line span is a constant in `function pushShortVariableAt` and has no config key." }] },
40
+ { ruleId: "security.async-foreach", pillar: "security", severity: "warning", confidence: "medium", description: "Flags async callbacks passed to forEach.", remediation: "Use for...of with await, Promise.all, or an explicit queue.", falsePositiveShapes: [{ shape: "A project-defined forEach-like method may await callbacks even though its call text matches the built-in array shape.", mitigation: "Use an explicit awaited loop or queue, or review the custom iterator contract before accepting the warning." }] },
55
41
  { ruleId: "security.disabled-tls-verification", pillar: "security", severity: "error", confidence: "high", description: "Flags code that disables TLS certificate verification.", remediation: "Remove the override and fix certificate trust at the source." },
56
42
  { ruleId: "security.document-write", pillar: "security", severity: "warning", confidence: "high", description: "Flags document.write usage.", remediation: "Use safe DOM APIs and encode untrusted content." },
57
- { ruleId: "security.dynamic-regexp", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input used to construct regular expressions.", remediation: "Use a fixed pattern, escape user input, or enforce strict length and character limits." },
43
+ { ruleId: "security.dynamic-regexp", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input used to construct regular expressions.", remediation: "Use a fixed pattern, escape user input, or enforce strict length and character limits.", falsePositiveShapes: [{ shape: "`new RegExp(process.env.SOME_PATTERN)` in build, config, or tooling code, where the environment variable is operator-supplied rather than attacker-supplied — `process.env.*` is unconditionally one of the four external-input tokens.", mitigation: "Move the pattern to a literal constant in source, or disable the rule with `rules.security.dynamic-regexp.enabled: false`." }, { shape: "`new RegExp(escapeRegExp(req.query.q))` — the source token still sits inside the same call segment, so the already-escaped input is reported by the same-line matcher, which has no notion of a sanitiser.", mitigation: "Bound the input with an explicit length and character check as the descriptor's remediation says, or set `rules.security.dynamic-regexp.enabled: false` if your codebase routes all patterns through a shared escaper." }] },
58
44
  { ruleId: "security.eval-call", pillar: "security", severity: "error", confidence: "high", description: "Flags eval() dynamic code execution.", remediation: "Replace eval with explicit parsing or a safe dispatch table." },
59
- { ruleId: "security.floating-promise", pillar: "security", severity: "warning", confidence: "medium", description: "Flags promise-like calls without await, return, or void.", remediation: "Await it, return it, or mark intentional fire-and-forget with void." },
60
- { ruleId: "security.github-actions-broad-permissions", pillar: "security", severity: "warning", confidence: "medium", description: "Flags GitHub Actions workflows that grant broad write permissions.", remediation: "Reduce workflow permissions to read-only by default and grant write scopes only to trusted jobs." },
61
- { ruleId: "security.github-actions-pull-request-target", pillar: "security", severity: "warning", confidence: "medium", description: "Flags pull_request_target workflows paired with risky execution or trust context.", remediation: "Use pull_request for untrusted code or isolate checkout, secrets, and write permissions behind trust checks." },
62
- { ruleId: "security.github-actions-remote-shell", pillar: "security", severity: "warning", confidence: "medium", description: "Flags workflow run steps that pipe remote downloads to a shell.", remediation: "Vendor the installer, pin an audited action, or verify downloaded content before execution." },
63
- { ruleId: "security.github-actions-secrets-in-pr", pillar: "security", severity: "warning", confidence: "medium", description: "Flags pull request workflows that reference GitHub secrets.", remediation: "Avoid exposing secrets to pull request workflows unless the code path is trusted and tightly gated." },
64
- { ruleId: "security.github-actions-unpinned-action", pillar: "security", severity: "warning", confidence: "medium", description: "Flags third-party GitHub Actions that are not pinned to a full commit SHA.", remediation: "Pin third-party actions to a reviewed 40-character commit SHA and update them deliberately." },
65
- { ruleId: "security.inner-html", pillar: "security", severity: "warning", confidence: "high", description: "Flags innerHTML assignment.", remediation: "Use safe DOM APIs or sanitize trusted HTML centrally." },
66
- { ruleId: "security.insecure-random", pillar: "security", severity: "warning", confidence: "high", description: "Flags Math.random usage in source.", remediation: "Use crypto-backed randomness for security-sensitive values." },
67
- { ruleId: "security.javascript-url", pillar: "security", severity: "error", confidence: "high", description: "Flags javascript: URL literals that execute script.", remediation: "Use safe routes or event handlers instead of executable URL strings." },
45
+ { ruleId: "security.github-actions-pull-request-target", pillar: "security", severity: "warning", confidence: "medium", description: "Flags pull_request_target workflows paired with risky execution or trust context.", remediation: "Use pull_request for untrusted code or isolate checkout, secrets, and write permissions behind trust checks.", falsePositiveShapes: [{ shape: "A safe `pull_request_target` job (label-only, no checkout of PR head) sharing a workflow file with an unrelated job that has a `run:` step or a `secrets.` reference — pullRequestTargetRiskContext scans the whole file and is not scoped to the triggering job.", mitigation: "Split the pull_request_target job into its own workflow file so the risk signals no longer share a file, or set `rules.security.github-actions-pull-request-target.enabled: false`." }, { shape: "A guard line that names the event in order to exclude it, such as `if: github.event_name != 'pull_request_target'`, satisfies hasPullRequestTargetEvent because that predicate is a bare /\\bpull_request_target\\b/ token test on any non-comment line.", mitigation: "Express the guard without naming the event (for example by allowlisting the events you do want), or set `rules.security.github-actions-pull-request-target.enabled: false`." }] },
46
+ { ruleId: "security.github-actions-remote-shell", pillar: "security", severity: "warning", confidence: "medium", description: "Flags workflow run steps that pipe remote downloads to a shell.", remediation: "Vendor the installer, pin an audited action, or verify downloaded content before execution.", falsePositiveShapes: [{ shape: "Documentation or echoed text inside a `run:` block scalar that merely quotes the pattern (`echo \"install with: curl https://example.com/i.sh | sh\"`) is flagged, because runCommands joins the block's raw lines and isRemoteShellCommand does no shell quoting analysis.", mitigation: "Move the sample text into a YAML comment line, which function isCommentOrBlank skips, or set `rules.security.github-actions-remote-shell.enabled: false`." }, { shape: "A pinned official installer from a vendor you already trust (rustup, uv, nvm) is treated identically to an arbitrary URL — the regex has no host allowlist.", mitigation: "Replace the pipe with a pinned setup action or a vendored, checksum-verified installer as the remediation says, or set `rules.security.github-actions-remote-shell.enabled: false`." }] },
47
+ { ruleId: "security.github-actions-secrets-in-pr", pillar: "security", severity: "warning", confidence: "medium", description: "Flags pull_request_target workflows that reference repository secrets other than GITHUB_TOKEN.", remediation: "Avoid exposing secrets to pull request workflows unless the code path is trusted and tightly gated.", falsePositiveShapes: [{ shape: "A secret reference may be protected by a trusted-actor gate or an event condition outside the bounded comparison grammar, or have unsupported YAML ownership; the source scan cannot prove those boundaries.", mitigation: "Use an own job or step event guard the rule can prove unreachable for pull_request_target, or review the unsupported boundary before excluding the workflow." }] },
48
+ { ruleId: "security.github-actions-unpinned-action", pillar: "security", severity: "warning", confidence: "medium", description: "Flags third-party GitHub Actions that are not pinned to a full commit SHA.", remediation: "Pin third-party actions to a reviewed 40-character commit SHA and update them deliberately.", falsePositiveShapes: [{ shape: "First-party actions maintained by your own organisation (`myorg/ci-actions@v1`) are classified as third-party, because function thirdPartyActionUse exempts only the two literal owners `actions` and `github` and has no configurable owner allowlist.", mitigation: "Reference the action by local path (`uses: ./.github/actions/…`), which the detector exempts, or set `rules.security.github-actions-unpinned-action.enabled: false`." }] },
49
+ { ruleId: "security.inner-html", pillar: "security", severity: "warning", confidence: "high", isEnabledByDefault: false, description: "Flags innerHTML assignment unless the value is a plain string or a template without substitutions.", remediation: "Use safe DOM APIs or sanitize trusted HTML centrally." },
50
+ { ruleId: "security.javascript-url", pillar: "security", severity: "error", confidence: "high", description: "Flags javascript: URL literals that execute script; a literal compared with ==, ===, != or !== stays quiet.", remediation: "Use safe routes or event handlers instead of executable URL strings." },
68
51
  { ruleId: "security.new-function", pillar: "security", severity: "error", confidence: "high", description: "Flags Function constructor dynamic code execution.", remediation: "Replace dynamic construction with explicit functions or dispatch." },
69
- { ruleId: "security.open-redirect-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to redirect or navigation sinks.", remediation: "Redirect only to relative paths or destinations from an allowlist." },
70
- { ruleId: "security.path-traversal-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to filesystem path sinks.", remediation: "Validate paths against an allowlist and resolve them under a safe root." },
71
- { ruleId: "security.process-exec", pillar: "security", severity: "warning", confidence: "high", description: "Flags child-process execution calls and annotates emitted findings with command-source and shell-mode hints.", remediation: "Review the command source and shell mode; prefer fixed command vectors with shell disabled." },
72
- { ruleId: "security.proto-access", pillar: "security", severity: "warning", confidence: "medium", description: "Flags direct __proto__ access that can enable prototype pollution.", remediation: "Use Object.getPrototypeOf, Object.create(null), or validated keys." },
73
- { ruleId: "security.remote-install-script", pillar: "security", severity: "error", confidence: "medium", description: "Flags package scripts that pipe remote content to a shell.", remediation: "Vendor, pin, or remove remote shell execution." },
74
- { ruleId: "security.risky-lifecycle-script", pillar: "security", severity: "warning", confidence: "medium", description: "Flags install-time and side-effectful publish lifecycle scripts while allowing validation-only publish gates.", remediation: "Review whether lifecycle execution is required; keep install/publish side effects behind explicit commands when possible." },
75
- { ruleId: "security.sql-concatenation", pillar: "security", severity: "warning", confidence: "high", description: "Flags SQL text composed with runtime interpolation or concatenation in query, execute, raw, or prepare calls.", remediation: "Use parameterized values, and keep dynamic identifiers constrained to trusted constants or explicit review." },
76
- { ruleId: "security.ssrf-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to network request sinks.", remediation: "Validate destinations against an allowlist and block internal hosts." },
52
+ // Off by default (ADR-021): right on 1 of 5 judged findings, too few to delete on. Remove the flag once a larger sample
53
+ // measures it right at least half the time.
54
+ { ruleId: "security.open-redirect-candidate", isEnabledByDefault: false, pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to redirect or navigation sinks.", remediation: "Redirect only to relative paths or destinations from an allowlist.", falsePositiveShapes: [{ shape: "A redirect built from deploy-time operator configuration, e.g. `res.redirect(`${process.env.APP_BASE_URL}/login`)`, because `process.env.*` is one of the SOURCE_TOKENS and is treated as external input even though only the operator sets it.", mitigation: "Read the env value into a module-level constant outside any function and use that constant at the sink — taint is not inherited across function boundaries (`function isFunctionLike` marks scope edges) — or set `rules.security.open-redirect-candidate.enabled: false`." }, { shape: "A redirect target already narrowed by a project validator, e.g. `res.redirect(resolveSafeTarget(req.query.next))`, because only regex-escape helpers are recognised as sanitizers by `function isSafeWrapperExpression`; every other wrapper call keeps the taint.", mitigation: "Branch on the validated key and pass a fixed string literal to the redirect call, or set `rules.security.open-redirect-candidate.enabled: false`." }] },
55
+ { ruleId: "security.path-traversal-candidate", pillar: "security", severity: "warning", confidence: "medium", isEnabledByDefault: false, description: "Flags external input sent to filesystem path sinks.", remediation: "Validate paths against an allowlist and resolve them under a safe root.", falsePositiveShapes: [{ shape: "CLI tooling that intentionally opens an operator-supplied path, e.g. `readFileSync(process.argv[2])` or a path built from `process.env.CONFIG_DIR`, since `process.argv` and `process.env.*` are external-input tokens even though the person running the command owns the path.", mitigation: "Hoist the env/argv read to a module-level constant used inside the function (taint does not cross function boundaries), or set `rules.security.path-traversal-candidate.enabled: false` for CLI-only packages." }, { shape: "A non-filesystem method whose bare name collides with the sink list — the AST matcher is `/(?:^|\\.)(?:…|stat|rm|mkdir|readdir|…)$/` on callee text — so `cache.stat(req.params.id)` or a storage abstraction's `store.rm(...)` is treated as a filesystem sink.", mitigation: "Rename the colliding method away from the fs-API vocabulary, or set `rules.security.path-traversal-candidate.enabled: false`." }] },
56
+ { ruleId: "security.remote-install-script", pillar: "security", severity: "error", confidence: "medium", description: "Flags package scripts that pipe remote content to a shell.", remediation: "Vendor, pin, or remove remote shell execution.", falsePositiveShapes: [{ shape: "A developer-only bootstrap script that never runs during install — `function analysePackageScripts` iterates every key in `scripts`, so `\"setup:tools\": \"curl -fsSL https://example.com/install.sh | sh\"` is reported at error severity exactly like a `postinstall` hook.", mitigation: "Vendor or pin the installer as a registry dependency, or set `rules.security.remote-install-script.enabled: false` if the bootstrap is a reviewed, out-of-band developer step." }] },
57
+ { ruleId: "security.sql-concatenation", pillar: "security", severity: "warning", confidence: "low", description: "Flags SQL text composed with runtime interpolation or concatenation in query, execute, raw, or prepare calls.", remediation: "Use parameterized values, and keep dynamic identifiers constrained to trusted constants or explicit review.", falsePositiveShapes: [{ shape: "The matcher flags a `query`, `execute`, `raw`, or `prepare` call when the call opening, the opening of its first-argument template literal, and a `SELECT`, `INSERT`, `UPDATE`, or `DELETE` before the `${` all appear on the same line, even when the interpolation inserts a SQL fragment returned by a helper or a cast fragment selected from two dialect-specific constants.", mitigation: "Write complete SQL literals for the dialect variants and select the statement before calling `query()`." }, { shape: "The matcher flags a `query`, `execute`, `raw`, or `prepare` call when the call opening, the opening of its first-argument template literal, and a `SELECT`, `INSERT`, `UPDATE`, or `DELETE` before the `${` all appear on the same line, even when the interpolation inserts a quoted model table name or a `FROM` clause built by quoting an identifier.", mitigation: "Build the complete statement with a SQL builder, use its identifier API for the model table name or the dialect’s dummy table when present, and pass the rendered SQL directly to `query()`." }] },
58
+ { ruleId: "security.ssrf-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to network request sinks.", remediation: "Validate destinations against an allowlist and block internal hosts.", falsePositiveShapes: [{ shape: "Validation on an earlier line or inside a helper can be outside the same-line candidate evidence.", mitigation: "Keep the destination allow-list visible at the sink or review the warning with its surrounding validation." }] },
77
59
  { ruleId: "security.string-timer", pillar: "security", severity: "warning", confidence: "high", description: "Flags string callbacks passed to timers.", remediation: "Pass a function callback instead of source text." },
78
- { ruleId: "security.throw-non-error", pillar: "security", severity: "warning", confidence: "medium", description: "Flags thrown non-Error values.", remediation: "Throw an Error subclass with a clear message." },
79
- { ruleId: "security.unsafe-deserialization", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input reaching unsafe deserialization or dynamic code-loading sinks.", remediation: "Use schema-bound parsers or validate and decode data without executing code." },
80
- { ruleId: "security.url-dependency", pillar: "security", severity: "warning", confidence: "medium", description: "Flags dependencies installed from URL, git, or local file specs.", remediation: "Prefer registry versions that can be locked and audited." },
60
+ { ruleId: "security.throw-non-error", pillar: "security", severity: "warning", confidence: "medium", description: "Flags thrown non-Error values.", remediation: "Throw an Error subclass with a clear message.", falsePositiveShapes: [{ shape: "Deliberate structured control-flow payloads that a framework contract expects, e.g. `throw { status: 404, body }` in an HTTP handler, which match the object-literal branch even though the shape is intentional.", mitigation: "Throw an Error subclass that carries the payload as properties (`throw new HttpError(404, body)` is exempt because the expression starts with an identifier), or set `rules.security.throw-non-error.enabled: false`." }] },
61
+ { ruleId: "security.unsafe-deserialization", pillar: "security", severity: "warning", confidence: "medium", isEnabledByDefault: false, description: "Flags external input reaching unsafe deserialization or dynamic code-loading sinks.", remediation: "Use schema-bound parsers or validate and decode data without executing code.", falsePositiveShapes: [{ shape: "A CLI loading its own YAML config with `yaml.load(readFileSync(process.argv[2]))`, where the operator supplies the file but `function isUnsafeYamlLoad` still treats the load as unsafe because no schema is pinned.", mitigation: "Pass `{ schema: JSON_SCHEMA }` (or FAILSAFE_SCHEMA/CORE_SCHEMA) as the second argument — `function hasSafeYamlSchema` then clears the finding." }, { shape: "A project's own codec method named `unserialize` that only decodes data structures — the matcher is `/(?:^|\\.)unserialize$/` on callee text and does not check what the method does.", mitigation: "Rename the method (e.g. to `decode`), or set `rules.security.unsafe-deserialization.enabled: false`." }] },
62
+ { ruleId: "security.url-dependency", pillar: "security", severity: "warning", confidence: "medium", description: "Flags dependencies installed from URL, git, or local file specs.", remediation: "Prefer registry versions that can be locked and audited.", falsePositiveShapes: [{ shape: "Intentional monorepo-local links such as `\"@acme/shared\": \"file:../shared\"` in devDependencies, which are unpublishable by design yet match the `file:` branch.", mitigation: "Use the package manager's workspace protocol if the toolchain supports it, or set `rules.security.url-dependency.enabled: false` for the internal package." }, { shape: "A git spec already pinned to an immutable commit, e.g. `\"github:org/repo#a1b2c3d\"`, which the regex accepts through its optional `(?:#.+)?` tail and reports the same as an unpinned branch reference.", mitigation: "Publish the fork to a registry so the version can be locked and audited, or set `rules.security.url-dependency.enabled: false`." }] },
81
63
  { ruleId: "security.weak-crypto", pillar: "security", severity: "warning", confidence: "high", description: "Flags weak crypto primitives such as md5, sha1, or createCipher.", remediation: "Use modern algorithms and authenticated encryption." },
82
- { ruleId: "security.xxe-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external XML reaching parsers configured to expand entities.", remediation: "Disable external entity expansion and use hardened XML parser options." },
83
- { ruleId: "sensitive-data.api-key-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags vendor API key patterns including GitHub, GitLab, npm, Google API, Slack, Discord, and Stripe/OpenAI-style keys.", remediation: "Remove the secret and load it from a secure runtime source." },
84
- { ruleId: "sensitive-data.aws-access-key", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags AWS access key looking values.", remediation: "Remove the key and rotate it immediately." },
85
- { ruleId: "sensitive-data.database-url-password", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags database and HTTP(S) URLs that include passwords or embedded credentials.", remediation: "Move credentials into a secret store or runtime environment." },
86
- { ruleId: "sensitive-data.gcp-service-account-key", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags GCP service-account key files (type service_account alongside a private key).", remediation: "Remove the service-account key from source and rotate it; load credentials from a secure runtime source." },
87
- { ruleId: "sensitive-data.hardcoded-env-value", pillar: "sensitive-data", severity: "error", confidence: "medium", description: "Flags environment-style secret values committed in text.", remediation: "Load secret-like values from secure runtime configuration. Or raise rules.sensitive-data.hardcoded-env-value.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 16 },
88
- { ruleId: "sensitive-data.high-entropy-string", pillar: "sensitive-data", severity: "error", confidence: "medium", description: "Flags high-entropy string literals that may be secrets.", remediation: "Remove the value and load it from a secure runtime source. Or raise rules.sensitive-data.high-entropy-string.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 32 },
89
- { ruleId: "sensitive-data.jwt-token", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags JWT-looking token literals.", remediation: "Remove the token and rotate the credential if real." },
90
- { ruleId: "sensitive-data.phi-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags PHI identifiers such as Medicare (MBI) and medical record numbers.", remediation: "Remove protected health information from source and fixtures." },
91
- { ruleId: "sensitive-data.pii-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags PII-like identifier patterns including SSN-shaped values and Luhn-valid payment cards.", remediation: "Remove personal data from source and fixtures." },
92
- { ruleId: "sensitive-data.private-key", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags private key block markers.", remediation: "Remove the key material and rotate affected credentials." },
93
- { ruleId: "size.file-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags files longer than the configured threshold.", remediation: "Split unrelated responsibilities into smaller files. Or raise rules.size.file-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 750 },
94
- { ruleId: "size.function-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags functions longer than the configured threshold.", remediation: "Extract named helpers or split workflows. Or raise rules.size.function-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 200 },
95
- { ruleId: "size.parameter-count", pillar: "size", severity: "warning", confidence: "high", description: "Flags functions with too many parameters.", remediation: "Group related options or reduce the function's responsibility. Or raise rules.size.parameter-count.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 7 },
96
- { ruleId: "test-quality.conditional-logic", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests with conditional logic.", remediation: "Split branch-specific expectations into separate tests." },
97
- { ruleId: "test-quality.exception-type-only", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only assert exception type.", remediation: "Assert message, code, or observable behavior as well." },
64
+ { ruleId: "security.xxe-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external XML reaching parsers configured to expand entities.", remediation: "Disable external entity expansion and use hardened XML parser options.", falsePositiveShapes: [{ shape: "An explicitly hardened xmldom parser: `function hasUnsafeXmlParserOption` matches the bare key `\\bresolveEntity\\s*:` with no constraint on its value, so `resolveEntity: () => null` or `resolveEntity: false` — the fix — is read as entity-expansion evidence.", mitigation: "Drop the explicit `resolveEntity` key and rely on the parser's non-expanding default, or set `rules.security.xxe-candidate.enabled: false`." }, { shape: "A pipeline that deliberately expands entities over first-party XML the project itself ships, which still matches because `processEntities: true`/`noent: true` is the only evidence the detector needs once an external-input token is in scope.", mitigation: "Pre-expand the trusted document at build time and parse with entity expansion off, or set `rules.security.xxe-candidate.enabled: false`." }] },
65
+ { ruleId: "sensitive-data.api-key-pattern", pillar: "sensitive-data", severity: "warning", confidence: "high", description: "Flags vendor API key patterns including GitHub, GitLab, npm, Google API, Slack, Discord, and Stripe/OpenAI-style keys.", remediation: "Remove the secret and load it from a secure runtime source." },
66
+ { ruleId: "sensitive-data.aws-access-key", pillar: "sensitive-data", severity: "warning", confidence: "high", isEnabledByDefault: false, description: "Flags AWS access key looking values (AKIA long-term and ASIA session identifiers).", remediation: "Remove the key and rotate it immediately." },
67
+ { ruleId: "sensitive-data.database-url-password", pillar: "sensitive-data", severity: "warning", confidence: "high", isEnabledByDefault: false, description: "Flags database and HTTP(S) URLs that include passwords or embedded credentials.", remediation: "Move credentials into a secret store or runtime environment." },
68
+ { ruleId: "sensitive-data.gcp-service-account-key", pillar: "sensitive-data", severity: "warning", confidence: "high", description: "Flags GCP service-account key files (type service_account alongside a private key).", remediation: "Remove the service-account key from source and rotate it; load credentials from a secure runtime source." },
69
+ // Off by default (ADR-021): wrong on its only judged finding, too few to delete on. Remove the flag once a larger sample
70
+ // measures it right at least half the time.
71
+ { ruleId: "sensitive-data.jwt-token", isEnabledByDefault: false, pillar: "sensitive-data", severity: "warning", confidence: "high", description: "Flags JWT-looking token literals.", remediation: "Remove the token and rotate the credential if real." },
72
+ { ruleId: "sensitive-data.phi-pattern", pillar: "sensitive-data", severity: "warning", confidence: "high", description: "Flags PHI identifiers such as Medicare (MBI) and medical record numbers.", remediation: "Remove protected health information from source and fixtures." },
73
+ { ruleId: "sensitive-data.pii-pattern", pillar: "sensitive-data", severity: "warning", confidence: "high", description: "Flags PII-like identifier patterns including SSN-shaped values and Luhn-valid payment cards.", remediation: "Remove personal data from source and fixtures." },
74
+ { ruleId: "sensitive-data.private-key", pillar: "sensitive-data", severity: "warning", confidence: "high", description: "Flags private key block markers.", remediation: "Remove the key material and rotate affected credentials." },
75
+ { ruleId: "size.file-length", pillar: "size", severity: "error", confidence: "high", description: "Flags JavaScript and TypeScript files whose substantive nonblank, non-comment line count exceeds the configured threshold.", remediation: "Split this file by responsibility, one responsibility per file.", threshold: 1000 },
76
+ { ruleId: "size.function-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags functions longer than the configured threshold.", remediation: "Split this function at its steps, one step per function.", threshold: 200 },
77
+ { ruleId: "size.parameter-count", pillar: "size", severity: "warning", confidence: "medium", description: "Flags functions with too many parameters.", remediation: "Group the parameters that travel together into one object, or split the function by caller.", threshold: 7, falsePositiveShapes: [{ shape: "The rule counts each parameter in a fixed-arity interpolation helper that declares bound values and text fragments in order, sometimes alongside view state.", mitigation: "Group the alternating fragments and values into a labeled tuple parameter that preserves their order, keeping view state separate where present." }] },
78
+ { ruleId: "test-quality.duplicate-test-body", pillar: "test-quality", severity: "advisory", confidence: "low", isEnabledByDefault: true, description: "Flags groups of at least three tests in one lexical container with matching multi-statement bodies after eligible literal normalization.", remediation: "Review the group as a consolidation candidate; use the test runner's table form with a descriptive label per row when it keeps each case clear.", falsePositiveShapes: [{ shape: "Separately named behavioral examples can intentionally share syntax while their input values communicate different requirements; syntax alone cannot decide whether a table makes those requirements easier to review.", mitigation: "Keep the separate examples when their names or structure carry useful intent, and leave rules.test-quality.duplicate-test-body.enabled false or suppress the reviewed group." }] },
98
79
  { ruleId: "test-quality.global-state-mutation", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tests mutating process or global runtime state.", remediation: "Isolate state changes and restore them around the test." },
99
- { ruleId: "test-quality.loop-in-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags loops inside test bodies.", remediation: "Use table tests or separate named cases." },
100
- { ruleId: "test-quality.magic-number-assertion", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags assertions against unexplained numeric literals.", remediation: "Name expected values or assert domain-specific outcomes." },
101
- { ruleId: "test-quality.mock-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only verify mock interaction.", remediation: "Assert observable behavior in addition to collaboration." },
102
- { ruleId: "test-quality.no-assertions", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tests without apparent assertions.", remediation: "Add assertions for observable behavior." },
103
- { ruleId: "test-quality.no-throw-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only assert code does not throw.", remediation: "Assert the observable result or state change." },
104
- { ruleId: "test-quality.only-skip", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags focused or skipped test markers.", remediation: "Remove .only and either enable or delete skipped tests." },
105
- { ruleId: "test-quality.sleep-in-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags sleeps in tests.", remediation: "Synchronize on behavior instead of wall-clock time." },
106
- { ruleId: "test-quality.snapshot-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that rely only on snapshots.", remediation: "Add targeted assertions for important behavior." },
80
+ { ruleId: "test-quality.loop-in-test", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags test-body loops whose assertions do not identify the failing iteration.", remediation: "Add a per-case message to looped assertions, or use a fixture table or separate named cases.", falsePositiveShapes: [{ shape: "A loop that only builds fixture data but calls a helper whose name ends in `Check` (or touches `.resolves`/`.rejects`), which `hasAssertion` in src/blocks.ts treats as an assertion — the loop is reported although no expectation runs per iteration.", mitigation: "Rename the helper away from the `Check` suffix, hoist the data-building loop out of the test body, or set `rules.test-quality.loop-in-test.enabled` to false." }] },
107
81
  { ruleId: "test-quality.static-analysis-redundant-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that primarily assert code shape rather than behavior, with review guidance for importability sentinels.", remediation: "Remove redundant assertions, replace them with behavioral evidence, or document why runtime module-load coverage matters." },
108
82
  { ruleId: "test-quality.trivial-assertion", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tautological assertions.", remediation: "Assert a real result from the system under test." },
109
- { ruleId: "test-quality.unused-mock", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags mocks created but not used.", remediation: "Remove unused mocks or wire them into the behavior under test." },
110
- { ruleId: "waste.any-type", pillar: "maintainability", severity: "warning", confidence: "high", description: "Flags any type usage.", remediation: "Use unknown with validation or a precise type." },
111
- { ruleId: "waste.broad-runtime-version", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags broad runtime dependency version ranges.", remediation: "Use bounded semver ranges and lockfiles." },
112
- { ruleId: "waste.commented-out-code", pillar: "maintainability", severity: "advisory", confidence: "high", description: "Flags comments that appear to contain disabled code.", remediation: "Delete dead code or restore it behind a real feature path." },
113
- { ruleId: "waste.console-log", pillar: "maintainability", severity: "advisory", confidence: "high", description: "Flags console log/debug calls in source.", remediation: "Remove debug logging or route through structured logging." },
114
- { ruleId: "waste.empty-function", pillar: "maintainability", severity: "advisory", confidence: "high", description: "Flags functions with no executable body.", remediation: "Delete the function or add the missing implementation." },
115
- { ruleId: "waste.exported-any", pillar: "maintainability", severity: "warning", confidence: "medium", description: "Flags exported APIs exposing any.", remediation: "Use a named interface, unknown with validation, or precise generics." },
116
- { ruleId: "waste.redundant-boolean-cast", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags redundant boolean casts in condition expressions.", remediation: "Use the condition value directly or name the boolean conversion." },
117
- { ruleId: "waste.redundant-variable", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags variables returned immediately after assignment.", remediation: "Return the expression directly." },
118
- { ruleId: "waste.swallowed-catch", pillar: "maintainability", severity: "warning", confidence: "medium", description: "Flags empty catch blocks.", remediation: "Handle, report, rethrow, or document intentional ignore paths." },
83
+ { ruleId: "test-quality.unused-mock", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags mocks created but not used.", remediation: "Remove unused mocks or wire them into the behavior under test.", falsePositiveShapes: [{ shape: "A `sinon.stub(target, \"method\")` whose whole purpose is the install side effect — it patches the method on the target object, so the test exercises the target and asserts observable output without ever naming the returned stub again, and the single-occurrence count reports it as unused.", mitigation: "Assert through the stub (e.g. `sinon.assert.calledWith(stubName, ...)`) so the binding is referenced, or set `rules.test-quality.unused-mock.enabled` to false for suites that install stubs this way." }] },
84
+ { ruleId: "waste.any-type", pillar: "maintainability", severity: "warning", confidence: "medium", description: "Flags any type usage.", remediation: "Use unknown with validation or a precise type.", falsePositiveShapes: [{ shape: "The line matcher flags `: any` in a test callback or stub that passes through or ignores a value, or in an `any[]` accumulator that is only appended to and returned.", mitigation: "Use a generic input and return type for the identity callback, `unknown` for ignored or forwarded inputs, `void` for the empty stub’s return, and `unknown[]` for the opaque accumulator and its returned tuple slot." }, { shape: "The line matcher flags an `as any` cast on a callback in a short generic factory whose signature specifies its input and output types.", mitigation: "Give the internal callback type the factory’s input and output type parameters so the factory can assign the callback directly." }] },
85
+ { ruleId: "waste.broad-runtime-version", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags broad runtime dependency version ranges.", remediation: "Use bounded semver ranges and lockfiles.", falsePositiveShapes: [{ shape: "A deliberately bounded multi-range spec such as `\"^18.0.0 || ^20.0.0\"`, flagged only because `isBroadRuntimeVersion` treats the presence of `||` as broad even though every alternative in the union is upper-bounded.", mitigation: "Collapse the union to one bounded range if you can support only one major, or set `rules.waste.broad-runtime-version.enabled` to false when dual-major support is a deliberate policy." }, { shape: "A plugin or adapter package that must float with its host, declaring an intentionally open `>=` spec (e.g. `\"typescript\": \">=5\"`), which matches the `/^>=\\s*\\d/` branch because it has no `<` upper bound.", mitigation: "Add an upper bound (`\">=5 <7\"`) so the range is auditable, or disable via `rules.waste.broad-runtime-version.enabled`." }] },
86
+ { ruleId: "waste.exported-any", pillar: "maintainability", severity: "warning", confidence: "medium", description: "Flags exported APIs exposing any.", remediation: "Use a named interface, unknown with validation, or precise generics.", falsePositiveShapes: [{ shape: "A one-line exported arrow function whose `any` lives in the body rather than the signature — e.g. `export const trim = (v: string): string => (v as any).trim();` — flags as a public-contract `any` because the check is line-scoped and matches `\\bany\\b` anywhere on the export line.", mitigation: "Move the body onto its own line so the internal cast leaves the declaration line, or set `rules.waste.exported-any.enabled` to false." }, { shape: "A deliberately variadic exported utility type or signature such as `export type AnyFn = (...args: any[]) => unknown;`, where `any[]` is the only way to accept arbitrary argument tuples.", mitigation: "Replace `any[]` with `unknown[]` (call sites narrow at use), or disable via `rules.waste.exported-any.enabled`." }] },
87
+ { ruleId: "waste.swallowed-catch", isEnabledByDefault: false, pillar: "maintainability", severity: "warning", confidence: "medium", description: "Flags empty catch blocks.", remediation: "Handle, report, rethrow, or document intentional ignore paths.", falsePositiveShapes: [{ shape: "An intentionally empty catch whose comment is a single word other than an intent marker, such as `/* expected */`, which the shape check in `hasIntentionalCatchRationale` reads as a label rather than a reason.", mitigation: "Say why in two or more words, cite a tracking reference, or set `rules.waste.swallowed-catch.enabled` to false." }, { shape: "A class method named `catch`, such as a promise-like wrapper's `catch(onRejected) {}`, is read as an empty catch block.", mitigation: "Keep the rule off, or rename the method." }, { shape: "An empty catch whose reason is written in a comment above the try or before the catch keyword, rather than inside the catch body.", mitigation: "Move the reason into the catch body, or keep the rule off." }] },
119
88
  { ruleId: "waste.useless-catch", pillar: "maintainability", severity: "advisory", confidence: "high", description: "Flags catch blocks that only rethrow the caught value.", remediation: "Remove the catch block or add meaningful handling." },
120
- { ruleId: "waste.useless-return", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags terminal bare return statements in void functions.", remediation: "Remove the final return statement." },
89
+ { ruleId: "waste.useless-return", pillar: "maintainability", severity: "advisory", confidence: "medium", isEnabledByDefault: false, description: "Flags terminal bare return statements in void functions.", remediation: "Remove the final return statement.", falsePositiveShapes: [{ shape: "A genuine early-exit guard that happens to be the textually last statement — the upward walk in `terminalBareReturnLines` skips over `}` lines, so a `return;` inside a trailing `if (…) { … }` block is attributed to the whole function even though it is conditional and load-bearing.", mitigation: "Write the guard on one line (`if (done) return;`) so the walk does not land on a bare `return;`, or set `rules.waste.useless-return.enabled` to false." }] },
121
90
  { ruleId: "waste.unreachable-code", pillar: "maintainability", severity: "warning", confidence: "high", description: "Flags statements after terminating statements.", remediation: "Delete unreachable code or restructure the control flow." },
122
- { ruleId: "waste.unused-import", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags named imports with no apparent usage.", remediation: "Remove unused imports." },
123
- { ruleId: "waste.unused-parameter", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags parameters with no apparent usage.", remediation: "Remove the parameter or prefix it with _ if intentional." },
91
+ { ruleId: "waste.unused-import", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags named imports with no apparent usage.", remediation: "Remove unused imports.", falsePositiveShapes: [{ shape: "An import used exactly once, inside a template-literal interpolation that itself contains braces — e.g. `` `${format({ level: Level.Warn })}` `` — because the rescue regex `\\$\\{[^}]*\\bNAME\\b[^}]*\\}` cannot cross the inner `}`, so the masked count stays at 1 and the binding looks unused.", mitigation: "Bind the value to a local before the template (`const level = Level.Warn;`) so the reference appears in plain code, or set `rules.waste.unused-import.enabled` to false." }] },
124
92
  ];
125
93
 
126
94
  /**
@@ -131,3 +99,31 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
131
99
  export function ruleDescriptors(): RuleDescriptor[] {
132
100
  return [...RULE_DESCRIPTORS].sort((left, right) => left.ruleId.localeCompare(right.ruleId));
133
101
  }
102
+
103
+ // Each rule's published confidence, built once, because analysis asks per finding.
104
+ const RULE_CONFIDENCE: ReadonlyMap<string, Confidence> = new Map(RULE_DESCRIPTORS.map((descriptor) => [descriptor.ruleId, descriptor.confidence]));
105
+
106
+ /**
107
+ * Return the confidence the rule catalogue publishes for a rule, the single value list-rules, the hook gate and the score must share.
108
+ *
109
+ * @param ruleId - rule id as a finding carries it
110
+ * @returns the descriptor's confidence, or undefined for an id the catalogue does not list
111
+ */
112
+ export function catalogueConfidence(ruleId: string): Confidence | undefined {
113
+ return RULE_CONFIDENCE.get(ruleId);
114
+ }
115
+
116
+ // Rule ids whose descriptor turns them off unless a config enables them; built once, because analysis asks per finding.
117
+ const DEFAULT_DISABLED_RULE_IDS: ReadonlySet<string> = new Set(
118
+ RULE_DESCRIPTORS.filter((descriptor) => descriptor.isEnabledByDefault === false).map((descriptor) => descriptor.ruleId),
119
+ );
120
+
121
+ /**
122
+ * Reports the registry default published by list-rules, SARIF and init.
123
+ *
124
+ * @param ruleId - Any rule id; an id the registry does not hold reports true, the default every descriptor starts from.
125
+ * @returns False when the registry explicitly disables the rule by default, and true otherwise.
126
+ */
127
+ export function ruleDefaultEnabled(ruleId: string): boolean {
128
+ return !DEFAULT_DISABLED_RULE_IDS.has(ruleId);
129
+ }