@blundergoat/gruff-ts 0.2.0 → 0.3.1

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 (48) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +81 -13
  3. package/docs/README.md +2 -0
  4. package/docs/agent-hook.md +80 -0
  5. package/docs/ci-integration.md +16 -0
  6. package/docs/configuration.md +21 -5
  7. package/docs/output-formats.md +10 -0
  8. package/docs/philosophy.md +21 -0
  9. package/docs/releasing.md +5 -5
  10. package/docs/rules.md +26 -18
  11. package/package.json +5 -5
  12. package/scripts/bump-version.sh +1 -1
  13. package/src/analyser.ts +48 -37
  14. package/src/blocks.ts +23 -70
  15. package/src/changed-regions.ts +390 -0
  16. package/src/check-ignore.ts +49 -0
  17. package/src/class-rules.ts +80 -33
  18. package/src/cli-program.ts +106 -12
  19. package/src/comment-rules.ts +5 -1
  20. package/src/config-parse.ts +458 -0
  21. package/src/config-preservation.ts +1 -1
  22. package/src/config.ts +215 -460
  23. package/src/constants.ts +1 -1
  24. package/src/context-doc-rules.ts +2 -4
  25. package/src/dashboard.ts +7 -4
  26. package/src/discovery.ts +88 -32
  27. package/src/findings-helpers.ts +41 -5
  28. package/src/findings.ts +10 -0
  29. package/src/fixture-purpose-rules.ts +7 -9
  30. package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
  31. package/src/init-config.ts +3 -0
  32. package/src/line-rules.ts +7 -5
  33. package/src/naming-pushers.ts +35 -6
  34. package/src/profiles.ts +231 -0
  35. package/src/project-config-rules.ts +5 -5
  36. package/src/project-rules.ts +6 -117
  37. package/src/report-html.ts +1 -1
  38. package/src/report-renderers.ts +98 -7
  39. package/src/rule-list.ts +23 -2
  40. package/src/rules.ts +11 -12
  41. package/src/safety-rules.ts +16 -6
  42. package/src/scoring.ts +43 -5
  43. package/src/security-flow-rules.ts +533 -0
  44. package/src/sensitive-data-rules.ts +138 -2
  45. package/src/static-analysis-redundant-rules.ts +411 -0
  46. package/src/test-block-rules.ts +115 -53
  47. package/src/test-fixtures.ts +50 -9
  48. package/src/types.ts +79 -2
package/src/rules.ts CHANGED
@@ -3,12 +3,9 @@ import type { RuleDescriptor } from "./types.ts";
3
3
 
4
4
  const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
5
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 },
7
- { ruleId: "complexity.npath", pillar: "complexity", severity: "warning", confidence: "medium", description: "Flags functions with high approximate NPath complexity.", remediation: "Break apart compound branch combinations. Or raise rules.complexity.npath.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 200 },
8
- { 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." },
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." },
9
7
  { ruleId: "design.circular-import", pillar: "design", severity: "warning", confidence: "medium", description: "Flags simple relative import cycles inside the discovered source set.", remediation: "Extract the shared contract or invert one dependency." },
10
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 },
11
- { ruleId: "design.god-function", pillar: "design", severity: "warning", confidence: "high", description: "Flags functions that are both long and complex.", remediation: "Split responsibilities into smaller functions." },
12
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"] },
13
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." },
14
11
  { 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." },
@@ -45,7 +42,7 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
45
42
  { 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." },
46
43
  { ruleId: "modernisation.var-declaration", pillar: "modernisation", severity: "advisory", confidence: "high", description: "Flags var declarations.", remediation: "Use let or const with the narrowest useful scope." },
47
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"] },
48
- { 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 with project-specific values.", allowlistKeys: ["booleanPrefixes"] },
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"] },
49
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." },
50
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"] },
51
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"] },
@@ -79,33 +76,35 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
79
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." },
80
77
  { 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." },
81
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." },
82
- { ruleId: "security.url-dependency", pillar: "security", severity: "warning", confidence: "medium", description: "Flags dependencies installed from URL or git specs.", remediation: "Prefer registry versions that can be locked and audited." },
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." },
83
81
  { 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." },
84
- { ruleId: "sensitive-data.api-key-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags vendor API key patterns.", remediation: "Remove the secret and load it from a secure runtime source." },
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." },
85
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." },
86
- { ruleId: "sensitive-data.database-url-password", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags database URLs that include passwords.", remediation: "Move credentials into a secret store or runtime environment." },
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
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
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
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.pii-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags PII-like identifier patterns.", remediation: "Remove personal data from source and fixtures." },
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." },
91
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." },
92
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 },
93
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 },
94
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 },
95
- { ruleId: "size.stylesheet-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags stylesheets longer than the configured threshold.", remediation: "Split unrelated component styles into smaller files. Or raise rules.size.stylesheet-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 1500 },
96
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
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." },
98
98
  { 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
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
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.missing-nearby-test", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags exported production files without nearby tests.", remediation: "Add a focused test beside the source or in a nearby test directory." },
102
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." },
103
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." },
104
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." },
105
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." },
106
- { ruleId: "test-quality.setup-bloat", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags tests with too much setup before the first assertion.", remediation: "Extract builders or reduce fixture setup. Or raise rules.test-quality.setup-bloat.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 12 },
107
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." },
108
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." },
107
+ { 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.", remediation: "Remove the redundant assertion, replace it with behavioral evidence, or document why runtime coverage matters." },
109
108
  { 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." },
110
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." },
111
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." },
@@ -12,7 +12,7 @@ import type { Finding } from "./types.ts";
12
12
  export function analyseTypeSafetyLine(file: SourceFile, line: string, codeLine: string, lineNumber: number, findings: Finding[]): void {
13
13
  pushTsDirectiveFinding(file, line, lineNumber, findings);
14
14
  pushNonNullAssertionFindings(file, codeLine, lineNumber, findings);
15
- pushDoubleCastFindings(file, codeLine, lineNumber, findings);
15
+ pushDoubleCastFindings(file, line, codeLine, lineNumber, findings);
16
16
  pushExportedAnyFinding(file, codeLine, lineNumber, findings);
17
17
  }
18
18
 
@@ -146,28 +146,38 @@ function pushNonNullAssertionFindings(file: SourceFile, codeLine: string, lineNu
146
146
  }
147
147
  }
148
148
 
149
- // `as unknown as Foo` and `as any as Foo` double-cast patterns. Both source and target types are
150
- // captured in stable metadata so reviewers can see what's being coerced. Reports `modernisation.double-cast`.
151
- function pushDoubleCastFindings(file: SourceFile, codeLine: string, lineNumber: number, findings: Finding[]): void {
149
+ // `as unknown as Foo` and `as any as Foo` double-cast patterns. Why: the rationale branch keeps
150
+ // boundary casts visible without scoring a documented TS2352/validator hop like an unexplained
151
+ // bypass because typed parser migrations often land later; invariant: never throws and emits stable metadata.
152
+ function pushDoubleCastFindings(file: SourceFile, rawLine: string, codeLine: string, lineNumber: number, findings: Finding[]): void {
152
153
  for (const match of codeLine.matchAll(/\bas\s+(unknown|any)\s+as\s+([^;,\n]+)/g)) {
153
154
  const sourceType = match[1] ?? "";
154
155
  const targetType = (match[2] ?? "").trim().replace(/[.)]+$/, "");
156
+ const hasRationale = hasDoubleCastTrustBoundaryRationale(rawLine);
155
157
  findings.push(
156
158
  makeFinding({
157
159
  ruleId: "modernisation.double-cast",
158
160
  message: `Double cast through \`${sourceType}\` bypasses structural type checks.`,
159
161
  filePath: file.displayPath,
160
162
  line: lineNumber,
161
- severity: "warning",
163
+ severity: hasRationale ? "advisory" : "warning",
162
164
  pillar: "modernisation",
163
165
  confidence: "medium",
164
166
  remediation: "Prefer a typed parser, type guard, or narrower assertion at the trust boundary.",
165
- metadata: { sourceType, targetType },
167
+ metadata: { sourceType, targetType, ...(hasRationale ? { rationale: "trust-boundary" } : {}) },
166
168
  }),
167
169
  );
168
170
  }
169
171
  }
170
172
 
173
+ // Accepts only inline comments that name the trust boundary or validation reason for the cast.
174
+ function hasDoubleCastTrustBoundaryRationale(rawLine: string): boolean {
175
+ return (
176
+ /(?:\/\/|\/\*)/.test(rawLine) &&
177
+ /\b(?:trust boundary|external input|wire format|parser boundary|TS2352|unknown hop|validated|narrowed|type guard|schema)\b/i.test(rawLine)
178
+ );
179
+ }
180
+
171
181
  /*
172
182
  * `any` in an exported declaration's public surface. Only one finding per line because a single
173
183
  * `export` with multiple any-typed fields is one design problem, not many. Reports the stable
package/src/scoring.ts CHANGED
@@ -9,19 +9,20 @@ import type { AnalysisReport, FailThreshold, Finding, Pillar, Severity } from ".
9
9
  function scoreReport(findings: Finding[]): AnalysisReport["score"] {
10
10
  const byPillar = new Map<Pillar, Finding[]>();
11
11
  const byFile = new Map<string, Finding[]>();
12
+ const penalties = scoringPenaltyMap(findings);
12
13
  for (const finding of findings) {
13
14
  byPillar.set(finding.pillar, [...(byPillar.get(finding.pillar) ?? []), finding]);
14
15
  byFile.set(finding.filePath, [...(byFile.get(finding.filePath) ?? []), finding]);
15
16
  }
16
17
  const pillars = [...byPillar.entries()].map(([pillar, pillarFindings]) => {
17
- const penalty = pillarFindings.reduce((sum, finding) => sum + severityPenalty(finding.severity), 0);
18
+ const penalty = pillarFindings.reduce((sum, finding) => sum + findingPenalty(penalties, finding), 0);
18
19
  return { pillar, score: Math.max(0, 100 - penalty), penalty, findings: pillarFindings.length };
19
20
  });
20
21
  const composite = pillars.length === 0 ? 100 : pillars.reduce((sum, pillar) => sum + pillar.score, 0) / pillars.length;
21
22
  const topOffenders = [...byFile.entries()]
22
23
  .map(([filePath, fileFindings]) => ({
23
24
  filePath,
24
- score: Math.max(0, 100 - fileFindings.reduce((sum, finding) => sum + severityPenalty(finding.severity), 0)),
25
+ score: Math.max(0, 100 - fileFindings.reduce((sum, finding) => sum + findingPenalty(penalties, finding), 0)),
25
26
  findings: fileFindings.length,
26
27
  }))
27
28
  .sort((left, right) => left.score - right.score);
@@ -71,13 +72,50 @@ function severityPenalty(severity: Severity): number {
71
72
  return severity === "error" ? 8 : severity === "warning" ? 4 : 1.5;
72
73
  }
73
74
 
75
+ const CORRELATED_COMPLEXITY_RULE_IDS = new Set(["complexity.cognitive", "complexity.cyclomatic", "size.function-length"]);
76
+
77
+ // Correlated complexity findings describe one hard-to-review function.
78
+ // Invariant: detailed reports keep every rule finding while grade math splits one max-severity penalty.
79
+ function scoringPenaltyMap(findings: Finding[]): Map<Finding, number> {
80
+ const penalties = new Map<Finding, number>();
81
+ const clusters = new Map<string, Finding[]>();
82
+ for (const finding of findings) {
83
+ penalties.set(finding, severityPenalty(finding.severity));
84
+ const key = complexityClusterKey(finding);
85
+ if (key) {
86
+ clusters.set(key, [...(clusters.get(key) ?? []), finding]);
87
+ }
88
+ }
89
+ for (const cluster of clusters.values()) {
90
+ if (cluster.length < 2) {
91
+ continue;
92
+ }
93
+ const sharedPenalty = Math.max(...cluster.map((finding) => severityPenalty(finding.severity))) / cluster.length;
94
+ cluster.forEach((finding) => penalties.set(finding, sharedPenalty));
95
+ }
96
+ return penalties;
97
+ }
98
+
99
+ // Invariant: line+symbol grouping prevents unrelated functions in the same file from sharing score relief.
100
+ function complexityClusterKey(finding: Finding): string | undefined {
101
+ if (!finding.symbol || !finding.line || !CORRELATED_COMPLEXITY_RULE_IDS.has(finding.ruleId)) {
102
+ return undefined;
103
+ }
104
+ return `${finding.filePath}\0${finding.symbol}\0${finding.line}`;
105
+ }
106
+
107
+ // Invariant: one finding uses one precomputed score penalty or the normal severity weight fallback.
108
+ function findingPenalty(penalties: ReadonlyMap<Finding, number>, finding: Finding): number {
109
+ return penalties.get(finding) ?? severityPenalty(finding.severity);
110
+ }
111
+
74
112
  /*
75
113
  * Per-severity grade breakdown for the human summary block. The composite headline alone hides the
76
114
  * fact that an F can be driven entirely by advisories (goat-flow scan: F at 12.9 with 0 errors / 276
77
115
  * warnings / 1367 advisories). Mirrors the existing pillar formula `100 - count * severityPenalty`
78
- * so the math stays consistent with how a single-rule pillar would score. The schema invariant
79
- * matters: the composite score and `gruff.analysis.v2` JSON shape stay byte-stable - only the
80
- * human renderers surface this breakdown.
116
+ * so the math stays consistent with how a single-rule pillar would score. The report-shape
117
+ * invariant matters: severity breakdowns and correlated complexity clustering must not add
118
+ * `gruff.analysis.v2` JSON fields, even when score values change.
81
119
  */
82
120
  function severityGradeBreakdown(findings: Finding[]): {
83
121
  error: { grade: string; score: number; count: number };