@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/scoring.ts CHANGED
@@ -1,36 +1,152 @@
1
- // Score, grade, and fail-on helpers derived from finding severities for reports and CLI exits.
1
+ // Computes the quality scores and grades a user sees in reports and score history.
2
+ //
3
+ // A scan scores the rules and files it evaluated. Correlated findings share a penalty when they describe the same declaration.
4
+ // CI uses the configured finding threshold to decide whether to pass or fail independently of the score.
2
5
  import { grade } from "./pillar-summary.ts";
3
- import type { AnalysisReport, FailThreshold, Finding, Pillar, Severity } from "./types.ts";
6
+ import { ruleDescriptors } from "./rules.ts";
7
+ import type { AnalysisReport, Confidence, FailThreshold, Finding, Pillar, Severity } from "./types.ts";
4
8
 
5
- // Builds the per-pillar and per-file score breakdown that ships in `gruff.analysis.v2`. The composite
6
- // score is the mean of pillar scores so adding a pillar shifts the headline number. `topOffenders` is
7
- // the full file list sorted worst-first; renderers cap it themselves (HTML/hotspot keep their 10-row
8
- // UX, summary honours `--top`). The field shape is part of the `gruff.analysis.v2` schema contract.
9
- function scoreReport(findings: Finding[]): AnalysisReport["score"] {
9
+ // Every pillar that has at least one rule behind it. The composite averages over this whole set,
10
+ // because averaging only finding-bearing pillars let a pillar vanish from the mean the moment its
11
+ // last finding was fixed - lowering the headline score for finishing a pillar.
12
+ const SCOREABLE_PILLARS: readonly Pillar[] = [...new Set(ruleDescriptors().map((descriptor) => descriptor.pillar))];
13
+
14
+ // Ratified cross-port scoring constants (`bounded-normalized-density-floored`, shared by all five gruff ports).
15
+ //
16
+ // `SCORE_FLOOR` caps how far one saturated pillar drags the composite; `DENSITY_SCALE` is the per-file density halfway between the floor and 100.
17
+ const SCORE_FLOOR = 50;
18
+ const DENSITY_SCALE = 0.1;
19
+
20
+ /**
21
+ * Computes a pillar or file score using the shared density curve, where scaling penalty and file count together preserves the score.
22
+ *
23
+ * @param weight - Summed penalty weight for the pillar or file.
24
+ * @param evaluatedFiles - Number of evaluated files used to normalize the penalty density.
25
+ * @returns Rounded score on the bounded density curve, or null when evaluatedFiles is nonpositive because there is no score to include.
26
+ */
27
+ function curveScore(weight: number, evaluatedFiles: number): number | null {
28
+ if (evaluatedFiles <= 0) {
29
+ return null;
30
+ }
31
+ const density = weight / evaluatedFiles;
32
+ return roundScore(SCORE_FLOOR + (100 - SCORE_FLOOR) / (1 + density / DENSITY_SCALE));
33
+ }
34
+
35
+ /**
36
+ * Rounds one score to the ratified two decimals, normalizing negative zero away because JSON
37
+ * projection keeps it in some ports and not others.
38
+ *
39
+ * @param rawScore - Unrounded numeric score to normalize.
40
+ * @returns Score rounded to two decimal places with negative zero normalized to 0.
41
+ */
42
+ function roundScore(rawScore: number): number {
43
+ const rounded = Math.round(rawScore * 100) / 100;
44
+ return rounded === 0 ? 0 : rounded;
45
+ }
46
+
47
+ /**
48
+ * Builds the overall grade, pillar scores, and highest-priority files for the user's report.
49
+ * Invariant: each evaluated or finding-bearing pillar appears once, and a clean pillar scores 100 with evaluated files.
50
+ *
51
+ * @param findings - Findings emitted by the scan to aggregate into pillar, cluster, rule, and file scores.
52
+ * @param evaluatedFiles - Count of evaluated files; zero or less yields null scores and grades because there is no measurement.
53
+ * @param evaluatedPillars - Pillars evaluated by the run so clean pillars still appear alongside finding-bearing ones.
54
+ * @returns Report score summary with composite score, grade, evaluated file count, pillars, clusters, rule attribution, and top offenders.
55
+ */
56
+ function scoreReport(findings: Finding[], evaluatedFiles: number, evaluatedPillars: Iterable<Pillar> = SCOREABLE_PILLARS): AnalysisReport["score"] {
10
57
  const byPillar = new Map<Pillar, Finding[]>();
11
58
  const byFile = new Map<string, Finding[]>();
12
59
  const penalties = scoringPenaltyMap(findings);
60
+ // Use each finding in both the pillar breakdown and the list of files a user can address.
13
61
  for (const finding of findings) {
14
62
  byPillar.set(finding.pillar, [...(byPillar.get(finding.pillar) ?? []), finding]);
15
63
  byFile.set(finding.filePath, [...(byFile.get(finding.filePath) ?? []), finding]);
16
64
  }
17
- const pillars = [...byPillar.entries()].map(([pillar, pillarFindings]) => {
18
- const penalty = pillarFindings.reduce((sum, finding) => sum + findingPenalty(penalties, finding), 0);
19
- return { pillar, score: Math.max(0, 100 - penalty), penalty, findings: pillarFindings.length };
65
+ const scoredPillars = [...new Set([...evaluatedPillars, ...byPillar.keys()])];
66
+ const pillars = scoredPillars.map((pillar) => {
67
+ // Evaluated pillars with no findings still appear as clean in the report.
68
+ const pillarFindings = byPillar.get(pillar) ?? [];
69
+ const penalty = roundScore(pillarFindings.reduce((sum, finding) => sum + findingPenalty(penalties, finding), 0));
70
+ const score = curveScore(penalty, evaluatedFiles);
71
+ return { pillar, applicable: true, score, grade: score === null ? null : grade(score), penalty, findings: pillarFindings.length };
20
72
  });
21
- const composite = pillars.length === 0 ? 100 : pillars.reduce((sum, pillar) => sum + pillar.score, 0) / pillars.length;
73
+ const applicableScores = pillars.flatMap((pillar) => (pillar.score === null ? [] : [pillar.score]));
74
+ // Without evaluated files, pillars and the composite have null scores and grades because the scan has no measurement.
75
+ const composite =
76
+ applicableScores.length === 0 ? null : roundScore(applicableScores.reduce((sum, score) => sum + score, 0) / applicableScores.length);
22
77
  const topOffenders = [...byFile.entries()]
23
- .map(([filePath, fileFindings]) => ({
24
- filePath,
25
- score: Math.max(0, 100 - fileFindings.reduce((sum, finding) => sum + findingPenalty(penalties, finding), 0)),
26
- findings: fileFindings.length,
78
+ .map(([filePath, fileFindings]) => {
79
+ // A file's density is its own weighted findings, so file and project scores share one curve.
80
+ const penalty = roundScore(fileFindings.reduce((sum, finding) => sum + findingPenalty(penalties, finding), 0));
81
+ return { filePath, score: evaluatedFiles <= 0 ? null : curveScore(penalty, 1), penalty, findings: fileFindings.length };
82
+ })
83
+ .sort((left, right) => (left.score ?? 100) - (right.score ?? 100));
84
+ return {
85
+ composite,
86
+ grade: composite === null ? null : grade(composite),
87
+ evaluatedFiles,
88
+ scoredPillars,
89
+ clusters: correlatedClusters(findings, penalties),
90
+ ruleAttribution: ruleAttribution(findings, penalties),
91
+ pillars,
92
+ topOffenders,
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Builds cluster rows for groups of at least two supplied correlated findings sharing a file and symbol in stable file and symbol order.
98
+ *
99
+ * @param findings - Findings to group by correlated complexity cluster key.
100
+ * @param penalties - Precomputed penalty map summed per group, falling back to normal finding weight for missing entries.
101
+ * @returns Cluster rows sorted by file and symbol with sorted rule IDs, counts, and rounded weights, or empty when no group qualifies.
102
+ */
103
+ function correlatedClusters(findings: Finding[], penalties: ReadonlyMap<Finding, number>): AnalysisReport["score"]["clusters"] {
104
+ const groups = new Map<string, Finding[]>();
105
+ for (const finding of findings) {
106
+ const key = complexityClusterKey(finding);
107
+ if (key) {
108
+ groups.set(key, [...(groups.get(key) ?? []), finding]);
109
+ }
110
+ }
111
+ return [...groups.values()]
112
+ // A lone correlated finding billed its own full weight, so it is not a cluster to report.
113
+ .filter((group) => group.length >= 2)
114
+ .map((group) => ({
115
+ file: group[0]!.filePath,
116
+ symbol: String(group[0]!.symbol),
117
+ ruleIds: group.map((finding) => finding.ruleId).sort(),
118
+ findings: group.length,
119
+ weight: roundScore(group.reduce((sum, finding) => sum + findingPenalty(penalties, finding), 0)),
27
120
  }))
28
- .sort((left, right) => left.score - right.score);
29
- return { composite, grade: grade(composite), pillars, topOffenders };
121
+ .sort((left, right) => left.file.localeCompare(right.file) || left.symbol.localeCompare(right.symbol));
122
+ }
123
+
124
+ /**
125
+ * Aggregates finding counts and rounded scoring penalties by native rule ID in stable rule ID order.
126
+ * The attribution contract keeps the native rule ID even when reporting groups concepts.
127
+ *
128
+ * @param findings - Findings to tally by rule ID; rules with no findings produce no row.
129
+ * @param penalties - Precomputed penalty map used per finding, falling back to normal finding weight when an entry is missing.
130
+ * @returns Attribution entries sorted by native rule ID with finding counts and rounded total weights.
131
+ */
132
+ function ruleAttribution(findings: Finding[], penalties: ReadonlyMap<Finding, number>): AnalysisReport["score"]["ruleAttribution"] {
133
+ const totals = new Map<string, { findings: number; weight: number }>();
134
+ for (const finding of findings) {
135
+ const entry = totals.get(finding.ruleId) ?? { findings: 0, weight: 0 };
136
+ totals.set(finding.ruleId, { findings: entry.findings + 1, weight: entry.weight + findingPenalty(penalties, finding) });
137
+ }
138
+ return [...totals.entries()]
139
+ .map(([ruleId, entry]) => ({ ruleId, findings: entry.findings, weight: roundScore(entry.weight) }))
140
+ .sort((left, right) => left.ruleId.localeCompare(right.ruleId));
30
141
  }
31
142
 
32
- // Severity tallies emitted in the report summary. The four-key shape (advisory/warning/error/total)
33
- // is part of the `gruff.analysis.v2` schema and consumers rely on `total` matching the array length.
143
+ /**
144
+ * Computes severity tallies emitted in native analysis state, where the four-key shape
145
+ * (advisory/warning/error/total) is nested under summary.findings by the v3 machine adapter.
146
+ *
147
+ * @param findings - Findings to count across advisory, warning, error, and total; total must match the findings array length.
148
+ * @returns Object containing advisory, warning, error, and total counts.
149
+ */
34
150
  function summarize(findings: Finding[]) {
35
151
  return {
36
152
  advisory: findings.filter((finding) => finding.severity === "advisory").length,
@@ -40,18 +156,45 @@ function summarize(findings: Finding[]) {
40
156
  };
41
157
  }
42
158
 
43
- // Process exit contract: 2 when diagnostics were emitted (parse/IO failures the user must know about),
44
- // 1 when any finding crosses `failOn`, 0 otherwise. CI scripts and the dashboard runner depend on
45
- // this three-value invariant; reshuffling the precedence is a stable-contract regression.
46
- function exitFor(report: AnalysisReport, failOn: FailThreshold): number {
47
- if (report.diagnostics.length > 0) {
159
+ /**
160
+ * Apply the three-value exit contract used by CI and the dashboard, with invalidating diagnostics taking precedence over findings.
161
+ * Diagnostics invalidate the run by default. An explicit false leaves the finding gate in effect.
162
+ *
163
+ * @param report - Analysis results whose diagnostics and findings determine the exit status.
164
+ * @param failOn - Minimum severity for a finding to fail the gate. The none setting disables the finding gate.
165
+ * @param minConfidence - Confidence floor a finding must also meet. The default low admits all finding confidence levels.
166
+ * @returns 2 for any run-invalidating diagnostic, otherwise 1 if any finding meets both floors, otherwise 0.
167
+ */
168
+ function exitFor(report: AnalysisReport, failOn: FailThreshold, minConfidence: Confidence = "low"): number {
169
+ if (report.diagnostics.some((diagnostic) => diagnostic.invalidatesRun !== false)) {
48
170
  return 2;
49
171
  }
50
- return report.findings.some((finding) => thresholdTriggered(failOn, finding.severity)) ? 1 : 0;
172
+ return report.findings.some((finding) => reachesGate(finding, failOn, minConfidence)) ? 1 : 0;
173
+ }
174
+
175
+ /**
176
+ * Checks whether a finding meets both the severity floor and the confidence floor; both must pass to reach the gate.
177
+ *
178
+ * @param finding - Finding whose severity and confidence are evaluated against the gate floors.
179
+ * @param failOn - Minimum severity threshold; setting it to none always returns false so findings cannot fail the run.
180
+ * @param minConfidence - Minimum confidence rank required alongside the severity floor.
181
+ * @returns True if finding satisfies both failOn and minConfidence, otherwise false.
182
+ */
183
+ function reachesGate(finding: Finding, failOn: FailThreshold, minConfidence: Confidence): boolean {
184
+ return thresholdTriggered(failOn, finding.severity) && CONFIDENCE_GATE_RANK[finding.confidence] >= CONFIDENCE_GATE_RANK[minConfidence];
51
185
  }
52
186
 
53
- // Severity ladder: "none" never triggers, "advisory" triggers on anything, "warning" needs at least
54
- // warning, "error" needs error. Order is intentional - `failOn=warning` must still trigger on errors.
187
+ // Confidence ladder for the gate; a finding at or above the requested rank can reach it.
188
+ const CONFIDENCE_GATE_RANK: Record<Confidence, number> = { low: 0, medium: 1, high: 2 };
189
+
190
+ /**
191
+ * Checks whether a finding's severity reaches the configured failure threshold, where warning is a floor
192
+ * that includes warnings and errors because higher severities qualify, and error includes only errors.
193
+ *
194
+ * @param thresholdValue - Configured failure threshold; none never triggers, and advisory includes every severity.
195
+ * @param severity - Finding severity to compare against thresholdValue.
196
+ * @returns True when severity meets or exceeds thresholdValue, otherwise false.
197
+ */
55
198
  function thresholdTriggered(thresholdValue: FailThreshold, severity: Severity): boolean {
56
199
  if (thresholdValue === "none") {
57
200
  return false;
@@ -65,22 +208,51 @@ function thresholdTriggered(thresholdValue: FailThreshold, severity: Severity):
65
208
  return severity === "error";
66
209
  }
67
210
 
68
- // Penalty weights tuned so a handful of errors visibly drag a pillar below a passing grade while
69
- // a long tail of advisories cannot single-handedly fail a healthy pillar. Adjusting these shifts
70
- // every historical score and the grade letters in `scores.jsonl`.
211
+ /**
212
+ * Returns the ratified family severity weight, identical in all five ports so changing it is a family decision.
213
+ *
214
+ * @param severity - Finding severity level to map to its base weight.
215
+ * @returns Numeric scoring weight: 12 for error, 4 for warning, or 1 for advisory.
216
+ */
71
217
  function severityPenalty(severity: Severity): number {
72
- return severity === "error" ? 8 : severity === "warning" ? 4 : 1.5;
218
+ return severity === "error" ? 12 : severity === "warning" ? 4 : 1;
73
219
  }
74
220
 
75
- const CORRELATED_COMPLEXITY_RULE_IDS = new Set(["complexity.cognitive", "complexity.cyclomatic", "size.function-length"]);
221
+ /**
222
+ * Maps finding confidence to its multiplier so scoring density charges uncertain findings less than high-confidence ones.
223
+ *
224
+ * @param confidence - Confidence level of a finding.
225
+ * @returns Multiplier for severity weight: 1 for high, 0.75 for medium, or 0.5 for low.
226
+ */
227
+ function confidenceWeight(confidence: Confidence): number {
228
+ return confidence === "high" ? 1 : confidence === "medium" ? 0.75 : 0.5;
229
+ }
76
230
 
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.
231
+ /**
232
+ * Computes one finding's ratified weight by multiplying its severity weight by its confidence weight.
233
+ * Invariant: the weight is never negative, and a low-confidence finding always weighs less than the same severity at high confidence.
234
+ *
235
+ * @param finding - Finding whose severity and confidence determine its weight.
236
+ * @returns Non-negative product of severityPenalty and confidenceWeight.
237
+ */
238
+ function findingWeight(finding: Finding): number {
239
+ return severityPenalty(finding.severity) * confidenceWeight(finding.confidence);
240
+ }
241
+
242
+ const CORRELATED_COMPLEXITY_RULE_IDS = new Set(["complexity.cyclomatic", "size.function-length"]);
243
+
244
+ /**
245
+ * Builds a scoring penalty map keyed by the input findings, where unclustered findings and singleton clusters keep their own weight.
246
+ * Invariant: findings in a complexity cluster share its highest weight equally so that one function incurs one combined penalty.
247
+ *
248
+ * @param findings - Findings to assign individual or cluster-shared scoring penalties.
249
+ * @returns Map from each finding to its effective scoring penalty.
250
+ */
79
251
  function scoringPenaltyMap(findings: Finding[]): Map<Finding, number> {
80
252
  const penalties = new Map<Finding, number>();
81
253
  const clusters = new Map<string, Finding[]>();
82
254
  for (const finding of findings) {
83
- penalties.set(finding, severityPenalty(finding.severity));
255
+ penalties.set(finding, findingWeight(finding));
84
256
  const key = complexityClusterKey(finding);
85
257
  if (key) {
86
258
  clusters.set(key, [...(clusters.get(key) ?? []), finding]);
@@ -90,32 +262,46 @@ function scoringPenaltyMap(findings: Finding[]): Map<Finding, number> {
90
262
  if (cluster.length < 2) {
91
263
  continue;
92
264
  }
93
- const sharedPenalty = Math.max(...cluster.map((finding) => severityPenalty(finding.severity))) / cluster.length;
265
+ const sharedPenalty = Math.max(...cluster.map(findingWeight)) / cluster.length;
94
266
  cluster.forEach((finding) => penalties.set(finding, sharedPenalty));
95
267
  }
96
268
  return penalties;
97
269
  }
98
270
 
99
- // Invariant: line+symbol grouping prevents unrelated functions in the same file from sharing score relief.
271
+ /**
272
+ * Derives a grouping key for related complexity findings on one declaration so the report can share their penalty.
273
+ * Invariant: findings without a symbol or a matching rule keep their own penalty and return no group key.
274
+ *
275
+ * @param finding - Finding to inspect for declaration identity and correlated complexity rule membership.
276
+ * @returns Composite file and declaration key when correlated, or undefined when the finding stays unclustered.
277
+ */
100
278
  function complexityClusterKey(finding: Finding): string | undefined {
101
- if (!finding.symbol || !finding.line || !CORRELATED_COMPLEXITY_RULE_IDS.has(finding.ruleId)) {
279
+ // Without a declaration to match, keep the finding visible as its own contribution to the score.
280
+ if (!finding.symbol || !CORRELATED_COMPLEXITY_RULE_IDS.has(finding.ruleId)) {
102
281
  return undefined;
103
282
  }
104
- return `${finding.filePath}\0${finding.symbol}\0${finding.line}`;
283
+ // Prefer the declaration identity when present so same-named functions can receive separate penalties.
284
+ return `${finding.filePath}\0${finding.baselineSubject ?? finding.symbol}`;
105
285
  }
106
286
 
107
- // Invariant: one finding uses one precomputed score penalty or the normal severity weight fallback.
287
+ /**
288
+ * Resolves a finding's effective penalty from precomputed penalties or falls back to its individual weight.
289
+ * Invariant: returns the finding's precomputed penalty, including zero, when present in the map.
290
+ *
291
+ * @param penalties - Precomputed penalty lookup keyed by finding instance.
292
+ * @param finding - Finding whose effective penalty is needed.
293
+ * @returns Precomputed penalty from penalties, or findingWeight when the map has no entry.
294
+ */
108
295
  function findingPenalty(penalties: ReadonlyMap<Finding, number>, finding: Finding): number {
109
- return penalties.get(finding) ?? severityPenalty(finding.severity);
296
+ return penalties.get(finding) ?? findingWeight(finding);
110
297
  }
111
298
 
112
- /*
113
- * Per-severity grade breakdown for the human summary block. The composite headline alone hides the
114
- * fact that an F can be driven entirely by advisories (goat-flow scan: F at 12.9 with 0 errors / 276
115
- * warnings / 1367 advisories). Mirrors the existing pillar formula `100 - count * severityPenalty`
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.
299
+ /**
300
+ * Shows how each severity scores in the human summary. Each bucket applies its severity penalty with a zero floor.
301
+ * The breakdown belongs to the summary and keeps the gruff.analysis.v3 report schema stable.
302
+ *
303
+ * @param findings - findings to count by their reported severity
304
+ * @returns - count, score and letter grade for each severity. A bucket with no findings scores 100.
119
305
  */
120
306
  function severityGradeBreakdown(findings: Finding[]): {
121
307
  error: { grade: string; score: number; count: number };
@@ -133,12 +319,29 @@ function severityGradeBreakdown(findings: Finding[]): {
133
319
  };
134
320
  }
135
321
 
136
- // Single severity bucket using the same `score = max(0, 100 - count * penalty)` formula as the
137
- // pillar reduce in `scoreReport`. Returns the bucket plus its grade letter so renderers don't have
138
- // to import `grade` separately.
322
+ /**
323
+ * Computes a linear severity-only bucket score and grade clamped at zero, without using the project density curve or confidence weights.
324
+ *
325
+ * @param severity - Severity level whose base penalty scales the bucket deduction.
326
+ * @param count - Number of findings recorded at the supplied severity.
327
+ * @returns Bucket containing the letter grade, clamped score, and finding count.
328
+ */
139
329
  function severityBucket(severity: Severity, count: number): { grade: string; score: number; count: number } {
140
330
  const score = Math.max(0, 100 - count * severityPenalty(severity));
141
331
  return { grade: grade(score), score, count };
142
332
  }
143
333
 
144
- export { scoreReport, summarize, exitFor, severityGradeBreakdown };
334
+ /**
335
+ * Formats one composite score line for text reports, using a shared message when either score or grade is null.
336
+ *
337
+ * @param composite - Numeric composite score, or null when nothing was evaluated.
338
+ * @param gradeLetter - Letter grade label for the composite score, or null when nothing was evaluated.
339
+ * @returns Formatted composite line, or the shared nothing-evaluated message if either input is null.
340
+ */
341
+ function compositeLine(composite: number | null, gradeLetter: string | null): string {
342
+ return composite === null || gradeLetter === null
343
+ ? "Composite: n/a (nothing evaluated)"
344
+ : `Composite: ${gradeLetter} (${composite.toFixed(2)} / 100)`;
345
+ }
346
+
347
+ export { compositeLine, scoreReport, summarize, exitFor, severityGradeBreakdown };