@blundergoat/gruff-ts 0.5.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 +82 -0
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +49 -50
  4. package/SECURITY.md +18 -31
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -10
  8. package/docs/agent-hook.md +32 -35
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +160 -89
  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 -172
  15. package/docs/rules.md +126 -98
  16. package/package.json +10 -8
  17. package/src/analyser.ts +817 -323
  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 +62 -68
  22. package/src/blocks.ts +512 -336
  23. package/src/changed-regions.ts +380 -79
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +445 -436
  26. package/src/cli-program.ts +915 -172
  27. package/src/cli.ts +9 -3
  28. package/src/comment-rules.ts +236 -418
  29. package/src/comment-scanner.ts +339 -47
  30. package/src/complexity-metrics.ts +111 -35
  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 +751 -223
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +182 -54
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +493 -140
  40. package/src/doc-rules.ts +602 -126
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +134 -109
  43. package/src/findings.ts +47 -27
  44. package/src/fixture-purpose-rules.ts +194 -50
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +328 -121
  47. package/src/hook-contract.ts +681 -255
  48. package/src/init-config.ts +163 -118
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -468
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +32 -127
  54. package/src/parsed-script.ts +868 -314
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +86 -74
  57. package/src/project-config-rules.ts +324 -140
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +102 -38
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +821 -203
  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 +249 -55
  66. package/src/security-flow-rules.ts +791 -115
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +460 -387
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +378 -104
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +343 -253
  73. package/src/text-scans.ts +62 -11
  74. package/src/types.ts +220 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -163
  77. package/src/test-fixtures.ts +0 -671
@@ -8,16 +8,22 @@ import type { SourceFile } from "./discovery.ts";
8
8
  import { makeFinding } from "./findings.ts";
9
9
  import type { Config, Finding, Pillar, Severity } from "./types.ts";
10
10
 
11
- // Splits only at top-level commas, then strips parameter-property modifiers and `...rest`.
12
- // Destructured parameters remain intentionally invisible to per-parameter rules.
13
- export function parameterNames(params: string): Array<{ name: string; raw: string }> {
11
+ /**
12
+ * Extracts named entries from parameter-list text for per-parameter rules, omitting destructured or unrecognized entries.
13
+ * Each entry has name, raw text without supported modifiers or rest dots, and isParameterProperty set when a modifier was removed.
14
+ *
15
+ * @param params - raw parameter-list text inside a signature's parentheses
16
+ * @returns matching parameter entries with stripped raw text and parameter-property flags, or an empty array on empty input
17
+ */
18
+ export function parameterNames(params: string): Array<{ name: string; raw: string; isParameterProperty: boolean }> {
14
19
  return splitTopLevelParameters(params)
15
20
  .map((parameter) => parameter.trim())
16
21
  .filter(Boolean)
17
22
  .map((raw) => {
18
- const stripped = raw.replace(/^(?:(?:public|private|protected|readonly|override)\s+)*/, "").replace(/^\.\.\./, "");
23
+ const modifiers = raw.match(/^(?:(?:public|private|protected|readonly|override)\s+)*/)?.[0] ?? "";
24
+ const stripped = raw.slice(modifiers.length).replace(/^\.\.\./, "");
19
25
  const name = stripped.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\s*(?=[?:=]|$)/)?.[1] ?? "";
20
- return { name, raw: stripped };
26
+ return { name, raw: stripped, isParameterProperty: modifiers !== "" };
21
27
  })
22
28
  .filter((parameter) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(parameter.name));
23
29
  }
@@ -33,9 +39,13 @@ interface ParameterSplitState {
33
39
  isEscaped: boolean;
34
40
  }
35
41
 
36
- // Parameter defaults and type expressions can contain their own commas. A small delimiter scanner
37
- // keeps those nested commas attached, because adding another TypeScript parse to this hot path
38
- // would cost more than the character walk saves.
42
+ /**
43
+ * Splits parameter-list text into original substrings at top-level commas, keeping quoted and nested commas within each parameter.
44
+ * Preserves whitespace and empty segments so `parameterNames` can filter them out.
45
+ *
46
+ * @param params - raw parameter-list text to split at top-level commas
47
+ * @returns original parameter substrings, or a single empty string on empty input
48
+ */
39
49
  function splitTopLevelParameters(params: string): string[] {
40
50
  const parameters: string[] = [];
41
51
  const state: ParameterSplitState = { parenthesisDepth: 0, bracketDepth: 0, braceDepth: 0, angleDepth: 0, quote: "", isEscaped: false };
@@ -56,8 +66,13 @@ function splitTopLevelParameters(params: string): string[] {
56
66
  return parameters;
57
67
  }
58
68
 
59
- // Consumes quote-context characters: inside a string nothing is structural, and a quote character
60
- // opens string context. Returns false for ordinary characters so the caller keeps scanning.
69
+ /**
70
+ * Updates quote and escape tracking in place so string contents are not treated as parameter structure.
71
+ *
72
+ * @param state - mutable splitter state whose `quote` and `isEscaped` fields are updated
73
+ * @param character - current character being scanned from the parameter list
74
+ * @returns true when `character` belongs to quoted text or opens a quote, or false when the caller should inspect it as a delimiter
75
+ */
61
76
  function advanceParameterQuoteState(state: ParameterSplitState, character: string): boolean {
62
77
  if (state.quote !== "") {
63
78
  if (state.isEscaped) {
@@ -76,8 +91,16 @@ function advanceParameterQuoteState(state: ParameterSplitState, character: strin
76
91
  return false;
77
92
  }
78
93
 
79
- // Tracks nesting for parentheses, brackets, braces, and guarded type-argument angles so commas
80
- // inside them stay attached to their parameter.
94
+ /**
95
+ * Updates nesting depths in place for the character at `index` so nested commas do not split parameters.
96
+ * Uses `start` as the current parameter's starting offset when recognizing type arguments.
97
+ *
98
+ * @param state - mutable splitter state whose parenthesis, bracket, brace, and angle depths are updated
99
+ * @param params - full parameter-list text being scanned
100
+ * @param index - zero-based character offset in `params` to inspect
101
+ * @param start - zero-based starting offset of the current parameter segment in `params`
102
+ * @returns Nothing. Mutates `state` nesting depths in place.
103
+ */
81
104
  function advanceParameterDepths(state: ParameterSplitState, params: string, index: number, start: number): void {
82
105
  const character = params[index] ?? "";
83
106
  if (character === "(") state.parenthesisDepth += 1;
@@ -90,14 +113,26 @@ function advanceParameterDepths(state: ParameterSplitState, params: string, inde
90
113
  else if (character === ">" && state.angleDepth > 0 && params[index - 1] !== "=") state.angleDepth -= 1;
91
114
  }
92
115
 
93
- // A comma splits parameters only outside every nesting kind.
116
+ /**
117
+ * Checks whether the splitter sits outside every nesting kind, because a comma splits parameters only at top level.
118
+ *
119
+ * @param state - current splitter nesting depths to inspect
120
+ * @returns true only when parenthesis, bracket, brace, and angle depths are all zero
121
+ */
94
122
  function isTopLevelParameterPosition(state: ParameterSplitState): boolean {
95
123
  return state.parenthesisDepth === 0 && state.bracketDepth === 0 && state.braceDepth === 0 && state.angleDepth === 0;
96
124
  }
97
125
 
98
- // Treat `<...>` as type arguments in annotations, or in generic call/arrow defaults whose closing
99
- // token is followed by `(`. Requiring that call boundary keeps comparison chains from swallowing
100
- // a later parameter while preserving commas inside `factory<T, U>(...)` and `<T, U>(...) => ...`.
126
+ /**
127
+ * Determines whether the `<` at `index` opens a type-argument list so its commas stay within the parameter.
128
+ * A colon without `=` marks type context; otherwise the matching `>` must precede optional space and `(`.
129
+ * Rejects unrecognized prefixes and unmatched brackets to avoid treating comparison operators as type delimiters.
130
+ *
131
+ * @param params - full parameter-list text being scanned
132
+ * @param index - zero-based offset of the `<` character in `params`
133
+ * @param parameterStart - zero-based starting offset of the current parameter segment bounding the prefix
134
+ * @returns true when the prefix and matching `>` indicate a type-argument list, or false otherwise
135
+ */
101
136
  function opensTypeArgumentList(params: string, index: number, parameterStart: number): boolean {
102
137
  const prefix = params.slice(parameterStart, index);
103
138
  const previousCharacter = params[index - 1] ?? "";
@@ -122,20 +157,28 @@ function opensTypeArgumentList(params: string, index: number, parameterStart: nu
122
157
  return false;
123
158
  }
124
159
 
125
- /*
126
- * Central severity-override pass: config `rules.<id>.severity` wins over the scanner's created
127
- * severity for every rule family in one place, so a user's policy applies even to scanners that
128
- * hardcode their descriptor literal; without an override the created severity stands.
129
- * Invariant: the fingerprint hashes (ruleId, filePath, line, symbol), so overrides never churn identity.
160
+ /**
161
+ * Applies rules.<id>.severity while preserving the finding's stable fingerprint.
162
+ * Lower-band notices and unbuilt build-output bin advisories keep their assigned severity so starter configs do not promote them.
163
+ *
164
+ * @param config - effective configuration supplying any override for this finding's rule
165
+ * @param finding - scanner result to check. Lower-band and unbuilt-output advisories keep their assigned severity.
166
+ * @returns - the original finding if its severity stands, or a copy carrying the configured severity
130
167
  */
131
168
  export function applyConfiguredSeverity(config: Config, finding: Finding): Finding {
169
+ // A lower-band size or complexity finding is advisory whatever severity the user configured (FAMILY-CONTRACT.md
170
+ // section 12, search `Size and complexity findings in two bands`). Unbuilt dist/build/lib bin targets keep advisory
171
+ // severity for the same reason: starter configs pin `design.package-bin-missing` to `warning`.
172
+ if (finding.metadata.limitBand === "lower" || finding.metadata.unbuiltOutput === true) {
173
+ return finding;
174
+ }
132
175
  const severity = ruleSeverity(config, finding.ruleId, finding.severity);
133
176
  return severity === finding.severity ? finding : { ...finding, severity };
134
177
  }
135
178
 
136
- // Input bundle for `finding()` - the lowest-cost finding factory. Captures everything the caller
137
- // must supply for a line-anchored Finding; shared defaults (confidence "high", empty metadata)
138
- // are added inside the builder so callers don't repeat them at every rule site.
179
+ // Input bundle for `finding()`, defining the stable contract for line-anchored findings.
180
+ //
181
+ // Defaults (`confidence: "high"`, empty `metadata`) are filled inside `finding()`, and analysis then stamps each rule's catalogue confidence.
139
182
  export interface LineFindingArgs {
140
183
  ruleId: string;
141
184
  message: string;
@@ -143,19 +186,31 @@ export interface LineFindingArgs {
143
186
  line: number;
144
187
  severity: Severity;
145
188
  pillar: Pillar;
189
+ // The rule's advice; omitted, the finding carries none and consumers fall back to the catalogue.
190
+ remediation?: string | undefined;
146
191
  }
147
192
 
148
- // Cheapest finding factory: line-anchored, no symbol, confidence "high". Produces the
149
- // (ruleId, filePath, line) tuple that every per-line emission relies on - this tuple is the
150
- // stable fingerprint that drives baseline matching and report determinism.
193
+ /**
194
+ * Builds a high-confidence, symbol-free finding for a per-line report entry.
195
+ * Uses `args.file.displayPath` and `args.line` for location and omits empty remediation text.
196
+ *
197
+ * @param args - rule, message, file, line, severity, pillar, and optional remediation fields
198
+ * @returns finding whose fingerprint hashes ruleId, filePath, line, and an empty symbol slot
199
+ */
151
200
  export function finding(args: LineFindingArgs): Finding {
152
- return makeFinding({ ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.line, severity: args.severity, pillar: args.pillar, confidence: "high" });
201
+ return makeFinding({
202
+ ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.line, severity: args.severity, pillar: args.pillar,
203
+ confidence: "high", ...(args.remediation ? { remediation: args.remediation } : {}),
204
+ });
153
205
  }
154
206
 
155
- // Diff-aware discovery: uses `execFileSync` (not `execSync`) so the `mode` value is passed as
156
- // an argv entry and a malicious value cannot inject shell metacharacters. Custom-mode values pass
157
- // through `--end-of-options` so a leading `-` cannot be reinterpreted as a `git diff` flag
158
- // (e.g., `--output=…`). Normalises path separators to `/` for clean display-path joins.
207
+ /**
208
+ * Collects slash-normalized Git paths for `staged`, `unstaged`, `working-tree`, or a revision compared with the working tree.
209
+ * Spawns Git without a shell and places revision arguments after `--end-of-options`; command failures propagate to the caller.
210
+ *
211
+ * @param mode - diff selection mode (`staged`, `unstaged`, `working-tree`, or a Git revision)
212
+ * @returns set of matching slash-normalized paths (including non-ignored untracked paths in working-tree mode), or an empty set when none match
213
+ */
159
214
  export function changedFiles(mode: string): Set<string> {
160
215
  if (mode === "staged") {
161
216
  return gitPathSet(["diff", "--name-only", "--cached"]);
@@ -169,28 +224,45 @@ export function changedFiles(mode: string): Set<string> {
169
224
  return gitPathSet(["diff", "--name-only", "--end-of-options", mode]);
170
225
  }
171
226
 
172
- // Spawns `git` through execFileSync with one fixed argv vector and returns the normalized path set
173
- // used by diff filtering; spawns no shell because callers choose argv arrays, never shell strings.
227
+ /**
228
+ * Spawns Git through `execFileSync` without a shell and normalizes output paths; Git failures propagate to the caller.
229
+ *
230
+ * @param args - Git subcommand and option arguments passed directly without shell interpolation
231
+ * @returns set of non-empty output paths with backslashes converted to slashes, or an empty set when Git emits no paths
232
+ */
174
233
  function gitPathSet(args: string[]): Set<string> {
175
234
  return new Set(execFileSync("git", args, { encoding: "utf8" }).split(/\r?\n/).filter(Boolean).map((line) => line.replaceAll("\\", "/")));
176
235
  }
177
236
 
178
- // Strips directory and trailing extension. Used by `naming.class-file-mismatch` so the exported
179
- // symbol name and the file stem normalise to the same shape - both sides must agree on this
180
- // canonical form for the deterministic comparison to be meaningful.
237
+ /**
238
+ * Strips directory segments and any trailing extension so `naming.class-file-mismatch` can normalize file stems.
239
+ * Both sides must agree on this canonical form for the deterministic comparison to be meaningful.
240
+ *
241
+ * @param path - source file path whose base stem is extracted
242
+ * @returns file name without parent directories or its final dot extension
243
+ */
181
244
  export function fileBaseName(path: string): string {
182
245
  return basename(path).replace(/\.[^.]+$/, "");
183
246
  }
184
247
 
185
- // Lowercase-and-strip-separators canonical form. Treats `FooBar`, `foo_bar`, and `foo-bar` as
186
- // the same key so naming rules can compare across case styles without baking the convention in.
248
+ /**
249
+ * Normalizes an identifier to a lowercase ASCII alphanumeric key so naming rules can compare across case styles.
250
+ * Treats `FooBar`, `foo_bar`, and `foo-bar` as the same key.
251
+ *
252
+ * @param identifier - source identifier to strip and lowercase
253
+ * @returns lowercase ASCII alphanumeric key, or an empty string when `identifier` contains no ASCII letters or digits
254
+ */
187
255
  export function normalizedIdentifier(identifier: string): string {
188
256
  return identifier.replace(/[^A-Za-z0-9]/g, "").toLowerCase();
189
257
  }
190
258
 
191
- // Inserts a space at every camelCase boundary, then splits on any non-alphanumeric run. Acronym
192
- // runs (`HTTPServer`) stay intact because the inserted boundary is `lower → Upper`, not
193
- // `Upper → Upper` - callers comparing word lists rely on this to keep tokens aligned.
259
+ /**
260
+ * Splits an identifier into lowercase ASCII word tokens for naming comparisons.
261
+ * Splits where an ASCII lowercase letter or digit precedes an uppercase letter and at non-alphanumeric runs, keeping uppercase runs together.
262
+ *
263
+ * @param identifier - source identifier to tokenize into lowercase words
264
+ * @returns lowercase word tokens (for example `HTTPServer` yields `["httpserver"]`), or an empty array when no ASCII letters or digits exist
265
+ */
194
266
  export function splitIdentifierWords(identifier: string): string[] {
195
267
  return identifier
196
268
  .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
@@ -199,81 +271,34 @@ export function splitIdentifierWords(identifier: string): string[] {
199
271
  .filter(Boolean);
200
272
  }
201
273
 
202
- // Counts newlines before the offset to get a 0-based line number. `Math.max(0, …)` guards against
203
- // negative input - callers occasionally pass `match.index` which is typed as optional.
274
+ /**
275
+ * Computes the zero-based line number at a character offset in source text.
276
+ * Negative offsets select the first line so they cannot index from the end, and offsets beyond the end select the final line.
277
+ *
278
+ * @param source - full text in which lines are counted by newline characters
279
+ * @param index - zero-based character offset clamped at zero
280
+ * @returns zero-based line number containing the clamped offset
281
+ */
204
282
  export function lineOffset(source: string, index: number): number {
205
283
  return source.slice(0, Math.max(0, index)).split("\n").length - 1;
206
284
  }
207
285
 
208
- // Detector for `waste.commented-out-code`: require a parseable disabled-code shape rather than a
209
- // bare keyword so prose such as "import cycle" or section headings don't look executable.
210
- export function isCommentedOutCode(line: string): boolean {
211
- const trimmed = line.trim();
212
- if (!trimmed.startsWith("//")) {
213
- return false;
214
- }
215
- const uncommented = trimmed.replace(/^\/\/+\s?/, "");
216
- if (isCommentSeparatorOrAnchor(uncommented)) {
217
- return false;
218
- }
219
- return isDisabledDeclaration(uncommented) || isDisabledControlFlow(uncommented) || isDisabledCall(uncommented);
220
- }
221
-
222
- // Skips prose examples, labels, search anchors, and section dividers that often begin with code words.
223
- function isCommentSeparatorOrAnchor(uncommented: string): boolean {
224
- const text = uncommented.trim();
225
- return (
226
- text === "" ||
227
- /^[-=*_#]{3,}$/.test(text) ||
228
- /^[A-Za-z_$][A-Za-z0-9_$]*\s*:\s*['"`[{]/.test(text) ||
229
- /\b(?:search|grep|anchor|example|for example|e\.g\.)\s*:/.test(text) ||
230
- /^(?!(?:if|for|while|switch)\b)[A-Za-z_$][A-Za-z0-9_$]*\s+\([^;{}]*[A-Za-z][^;{}]*\)$/.test(text) ||
231
- /^[A-Z][A-Za-z0-9_$]*(?:\s|\s*\([^)]*\)$)/.test(text)
232
- );
233
- }
234
-
235
- // Declarations must carry their syntactic partner (`=`, `{`, `from`, etc.) to count as disabled code.
236
- function isDisabledDeclaration(uncommented: string): boolean {
237
- return (
238
- /^(?:const|let|var)\s+[A-Za-z_$][A-Za-z0-9_$]*\s*=/.test(uncommented) ||
239
- /^(?:async\s+)?function\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\(/.test(uncommented) ||
240
- /^class\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s+extends\s+[A-Za-z_$][A-Za-z0-9_$]*)?\s*\{?/.test(uncommented) ||
241
- /^interface\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{?/.test(uncommented) ||
242
- /^type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*=/.test(uncommented) ||
243
- /^enum\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{?/.test(uncommented) ||
244
- /^import\s+(?:["'][^"']+["']|.+\s+from\s+["'][^"']+["'])/.test(uncommented) ||
245
- /^export\s+(?:\{|\*|(?:default\s+)?(?:const|let|var|function|class|interface|type|enum)\b)/.test(uncommented)
246
- );
247
- }
248
-
249
- // Control-flow comments need real syntax such as parentheses or an expression after `return`/`throw`.
250
- function isDisabledControlFlow(uncommented: string): boolean {
251
- return /^(?:if|for|while|switch)\s*\(/.test(uncommented) || /^(?:return|throw|await)\s+\S/.test(uncommented);
252
- }
253
-
254
- // Keep single-line disabled calls; heading/prose guards above filter labels such as `Rules (...)`.
255
- function isDisabledCall(uncommented: string): boolean {
256
- return /^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)?\s*\([^)]*\);?$/.test(uncommented);
257
- }
258
-
259
- // Lowercase membership test against the configured banned-names set. Drives the
260
- // `naming.identifier-quality` predicate so the rule stays a single Set lookup per identifier.
261
- export function isGenericName(name: string, bannedNames: Set<string>): boolean {
262
- return bannedNames.has(name.toLowerCase());
263
- }
264
-
265
- // Escapes the standard regex metacharacters so user-supplied strings (rule IDs, identifiers,
266
- // paths) can be embedded in dynamic patterns without altering their meaning. Hot path -
267
- // used by every rule that builds a per-source RegExp.
286
+ /**
287
+ * Escapes standard regex metacharacters so user-supplied strings (rule IDs, identifiers, paths) can be embedded in dynamic patterns literally.
288
+ *
289
+ * @param source - raw string to escape for safe inclusion in a `RegExp` pattern
290
+ * @returns string with regex metacharacters backslash-escaped
291
+ */
268
292
  export function escapeRegex(source: string): string {
269
293
  return source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
270
294
  }
271
295
 
272
- /*
273
- * Per-rule severity tally for the `summary` Top-N rules block. Walks the findings once and returns
274
- * a deterministic Map keyed by ruleId carrying total / error / warning / advisory counts. Lets the
275
- * renderer surface "412 (0 err / 0 warn / 412 adv)" rows without re-scanning findings per row. The
276
- * count shape mirrors the `summary` schema invariant - total must equal err + warn + adv.
296
+ /**
297
+ * Accumulates rule counts so that summary rows can be rendered without scanning the findings again.
298
+ * Each total must equal the sum of errors, warnings and advisories.
299
+ *
300
+ * @param findings - report results to group by rule and count by severity
301
+ * @returns a map of totals and severity counts keyed by rule ID, or an empty map when there are no findings
277
302
  */
278
303
  export function countRuleSeverities(findings: Finding[]): Map<string, { total: number; error: number; warning: number; advisory: number }> {
279
304
  const counts = new Map<string, { total: number; error: number; warning: number; advisory: number }>();
package/src/findings.ts CHANGED
@@ -1,17 +1,21 @@
1
- // Finding factory helpers that centralize fingerprint generation and optional-field omission.
1
+ // Finding construction keeps report fields, baseline fingerprints, and cross-edit identities consistent.
2
+ //
3
+ // Rules provide user-facing evidence through one shared input shape.
4
+ // This module omits absent fields and adds deterministic identifiers before any renderer or baseline sees the finding.
2
5
  import { createHash } from "node:crypto";
3
6
  import type { Confidence, Finding, Pillar, Severity } from "./types.ts";
4
7
 
5
- // Caller-supplied fields. makeFinding hashes (ruleId, filePath, line, symbol) into the fingerprint,
6
- // so any field added here that should affect baseline identity must also be folded into that hash.
8
+ // Describes the evidence one rule supplies before a complete user-facing finding is built.
9
+ //
10
+ // Optional locations and guidance stay absent when the rule cannot provide them.
11
+ // Stable contract: centralized identifiers make every report and baseline interpret the same occurrence consistently.
7
12
  interface FindingInput {
8
13
  ruleId: string;
9
14
  message: string;
10
15
  filePath: string;
11
16
  line?: number;
12
17
  endLine?: number;
13
- // One-based match column. Deliberately NOT part of the fingerprint hash (ADR-017): it only
14
- // discriminates same-line occurrences in report dedupe and enriches SARIF/JSON locations.
18
+ // The optional one-based column separates same-line occurrences in reports without changing the baseline fingerprint (ADR-017).
15
19
  column?: number;
16
20
  severity: Severity;
17
21
  pillar: Pillar;
@@ -21,39 +25,55 @@ interface FindingInput {
21
25
  metadata?: Record<string, unknown>;
22
26
  }
23
27
 
24
- // Builds the canonical Finding shape. The 16-hex fingerprint is the baseline identity used by
25
- // `gruff.baseline.v1`; changing the hashed fields or their join order is a baseline-breaking
26
- // schema change. Optional fields are omitted (not set to undefined) so finding equality stays stable.
27
- function makeFinding(input: FindingInput): Finding {
28
+ /**
29
+ * Builds a report finding with a stable baseline fingerprint and cross-edit identity, omitting absent optional fields.
30
+ *
31
+ * @param findingInput - Rule evidence supplying the rule id, message, file path, severity, pillar, confidence, and optional location or metadata.
32
+ * @returns The complete finding carrying deterministic `fingerprint` and `stableIdentity` hashes.
33
+ */
34
+ function makeFinding(findingInput: FindingInput): Finding {
35
+ // Missing line or symbol values occupy stable empty slots so that the fields keep their positions in the fingerprint input.
28
36
  const fingerprint = createHash("sha256")
29
- .update([input.ruleId, input.filePath, input.line ?? "", input.symbol ?? ""].join("\0"))
37
+ .update([findingInput.ruleId, findingInput.filePath, findingInput.line ?? "", findingInput.symbol ?? ""].join("\0"))
30
38
  .digest("hex")
31
39
  .slice(0, 16);
40
+ // Omits missing or zero coordinates and empty optional text so consumers can treat them as unavailable. Missing metadata becomes an empty object.
32
41
  return {
33
- ruleId: input.ruleId,
34
- message: input.message,
35
- filePath: input.filePath,
36
- ...(input.line ? { line: input.line } : {}),
37
- ...(input.endLine ? { endLine: input.endLine } : {}),
38
- ...(input.column ? { column: input.column } : {}),
39
- severity: input.severity,
40
- pillar: input.pillar,
42
+ ruleId: findingInput.ruleId,
43
+ message: findingInput.message,
44
+ filePath: findingInput.filePath,
45
+ ...(findingInput.line ? { line: findingInput.line } : {}),
46
+ ...(findingInput.endLine ? { endLine: findingInput.endLine } : {}),
47
+ ...(findingInput.column ? { column: findingInput.column } : {}),
48
+ severity: findingInput.severity,
49
+ pillar: findingInput.pillar,
41
50
  secondaryPillars: [],
42
51
  tier: "v0.1",
43
- confidence: input.confidence,
44
- ...(input.symbol ? { symbol: input.symbol } : {}),
45
- ...(input.remediation ? { remediation: input.remediation } : {}),
46
- metadata: input.metadata ?? {},
52
+ confidence: findingInput.confidence,
53
+ ...(findingInput.symbol ? { symbol: findingInput.symbol } : {}),
54
+ ...(findingInput.remediation ? { remediation: findingInput.remediation } : {}),
55
+ metadata: findingInput.metadata ?? {},
47
56
  fingerprint,
48
- stableIdentity: stableIdentityFor(input),
57
+ stableIdentity: stableIdentityFor(findingInput),
49
58
  };
50
59
  }
51
60
 
52
- // Stable, line-insensitive identity for external diff tooling; fingerprint remains line-sensitive.
53
- function stableIdentityFor(input: FindingInput): string {
54
- const symbolOrMessage = input.symbol && input.symbol.length > 0 ? input.symbol : input.message;
61
+ /**
62
+ * Builds the line-insensitive identity external diff tools use to track a finding across edits.
63
+ *
64
+ * @param findingInput - Rule evidence supplying the rule id, file path, symbol or message, and optional column to separate same-line occurrences.
65
+ * @returns A deterministic 16-character hex SHA-256 prefix that distinguishes same-line occurrences without storing secret-derived text.
66
+ */
67
+ function stableIdentityFor(findingInput: FindingInput): string {
68
+ // Empty or missing symbols cannot identify the user's code, so those findings fall back to their user-facing message.
69
+ const hasNamedSymbol = typeof findingInput.symbol === "string" && findingInput.symbol.length > 0;
70
+ const symbolOrMessage = hasNamedSymbol ? findingInput.symbol : findingInput.message;
71
+ // A named symbol already identifies the user's code; otherwise a known column keeps same-line occurrences separate.
72
+ const occurrenceIdentity = hasNamedSymbol || findingInput.column === undefined
73
+ ? symbolOrMessage
74
+ : `${symbolOrMessage}\0column:${findingInput.column}`;
55
75
  return createHash("sha256")
56
- .update([input.ruleId, input.filePath, symbolOrMessage].join("\0"))
76
+ .update([findingInput.ruleId, findingInput.filePath, occurrenceIdentity].join("\0"))
57
77
  .digest("hex")
58
78
  .slice(0, 16);
59
79
  }