@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
@@ -3,13 +3,182 @@
3
3
  // on it without forming a cycle.
4
4
  import { execFileSync } from "node:child_process";
5
5
  import { basename } from "node:path";
6
+ import { ruleSeverity } from "./config.ts";
6
7
  import type { SourceFile } from "./discovery.ts";
7
8
  import { makeFinding } from "./findings.ts";
8
- import type { Finding, Pillar, Severity } from "./types.ts";
9
+ import type { Config, Finding, Pillar, Severity } from "./types.ts";
9
10
 
10
- // Input bundle for `finding()` - the lowest-cost finding factory. Captures everything the caller
11
- // must supply for a line-anchored Finding; shared defaults (confidence "high", empty metadata)
12
- // are added inside the builder so callers don't repeat them at every rule site.
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 }> {
19
+ return splitTopLevelParameters(params)
20
+ .map((parameter) => parameter.trim())
21
+ .filter(Boolean)
22
+ .map((raw) => {
23
+ const modifiers = raw.match(/^(?:(?:public|private|protected|readonly|override)\s+)*/)?.[0] ?? "";
24
+ const stripped = raw.slice(modifiers.length).replace(/^\.\.\./, "");
25
+ const name = stripped.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\s*(?=[?:=]|$)/)?.[1] ?? "";
26
+ return { name, raw: stripped, isParameterProperty: modifiers !== "" };
27
+ })
28
+ .filter((parameter) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(parameter.name));
29
+ }
30
+
31
+ // Nesting and quote context for the parameter splitter. Kept as one mutable record so the
32
+ // per-character helpers stay small enough to read at a glance.
33
+ interface ParameterSplitState {
34
+ parenthesisDepth: number;
35
+ bracketDepth: number;
36
+ braceDepth: number;
37
+ angleDepth: number;
38
+ quote: string;
39
+ isEscaped: boolean;
40
+ }
41
+
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
+ */
49
+ function splitTopLevelParameters(params: string): string[] {
50
+ const parameters: string[] = [];
51
+ const state: ParameterSplitState = { parenthesisDepth: 0, bracketDepth: 0, braceDepth: 0, angleDepth: 0, quote: "", isEscaped: false };
52
+ let start = 0;
53
+ for (let index = 0; index < params.length; index += 1) {
54
+ const character = params[index] ?? "";
55
+ if (advanceParameterQuoteState(state, character)) {
56
+ continue;
57
+ }
58
+ if (character === "," && isTopLevelParameterPosition(state)) {
59
+ parameters.push(params.slice(start, index));
60
+ start = index + 1;
61
+ continue;
62
+ }
63
+ advanceParameterDepths(state, params, index, start);
64
+ }
65
+ parameters.push(params.slice(start));
66
+ return parameters;
67
+ }
68
+
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
+ */
76
+ function advanceParameterQuoteState(state: ParameterSplitState, character: string): boolean {
77
+ if (state.quote !== "") {
78
+ if (state.isEscaped) {
79
+ state.isEscaped = false;
80
+ } else if (character === "\\") {
81
+ state.isEscaped = true;
82
+ } else if (character === state.quote) {
83
+ state.quote = "";
84
+ }
85
+ return true;
86
+ }
87
+ if (character === '"' || character === "'" || character === "`") {
88
+ state.quote = character;
89
+ return true;
90
+ }
91
+ return false;
92
+ }
93
+
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
+ */
104
+ function advanceParameterDepths(state: ParameterSplitState, params: string, index: number, start: number): void {
105
+ const character = params[index] ?? "";
106
+ if (character === "(") state.parenthesisDepth += 1;
107
+ else if (character === ")") state.parenthesisDepth = Math.max(0, state.parenthesisDepth - 1);
108
+ else if (character === "[") state.bracketDepth += 1;
109
+ else if (character === "]") state.bracketDepth = Math.max(0, state.bracketDepth - 1);
110
+ else if (character === "{") state.braceDepth += 1;
111
+ else if (character === "}") state.braceDepth = Math.max(0, state.braceDepth - 1);
112
+ else if (character === "<" && opensTypeArgumentList(params, index, start)) state.angleDepth += 1;
113
+ else if (character === ">" && state.angleDepth > 0 && params[index - 1] !== "=") state.angleDepth -= 1;
114
+ }
115
+
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
+ */
122
+ function isTopLevelParameterPosition(state: ParameterSplitState): boolean {
123
+ return state.parenthesisDepth === 0 && state.bracketDepth === 0 && state.braceDepth === 0 && state.angleDepth === 0;
124
+ }
125
+
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
+ */
136
+ function opensTypeArgumentList(params: string, index: number, parameterStart: number): boolean {
137
+ const prefix = params.slice(parameterStart, index);
138
+ const previousCharacter = params[index - 1] ?? "";
139
+ const isTypeContext = prefix.includes(":") && !prefix.includes("=");
140
+ const followsTokenWithoutWhitespace = previousCharacter !== "" && !/\s/.test(previousCharacter);
141
+ const startsGenericArrowDefault = /=\s*$/.test(prefix);
142
+ if (!isTypeContext && !followsTokenWithoutWhitespace && !startsGenericArrowDefault) {
143
+ return false;
144
+ }
145
+ let depth = 1;
146
+ for (let cursor = index + 1; cursor < params.length; cursor += 1) {
147
+ const character = params[cursor] ?? "";
148
+ if (character === "<") depth += 1;
149
+ else if (character === ">" && params[cursor - 1] !== "=") {
150
+ depth -= 1;
151
+ if (depth === 0) {
152
+ const isFollowedByCallParameters = /^\s*\(/.test(params.slice(cursor + 1));
153
+ return isTypeContext || isFollowedByCallParameters;
154
+ }
155
+ }
156
+ }
157
+ return false;
158
+ }
159
+
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
167
+ */
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
+ }
175
+ const severity = ruleSeverity(config, finding.ruleId, finding.severity);
176
+ return severity === finding.severity ? finding : { ...finding, severity };
177
+ }
178
+
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.
13
182
  export interface LineFindingArgs {
14
183
  ruleId: string;
15
184
  message: string;
@@ -17,19 +186,31 @@ export interface LineFindingArgs {
17
186
  line: number;
18
187
  severity: Severity;
19
188
  pillar: Pillar;
189
+ // The rule's advice; omitted, the finding carries none and consumers fall back to the catalogue.
190
+ remediation?: string | undefined;
20
191
  }
21
192
 
22
- // Cheapest finding factory: line-anchored, no symbol, confidence "high". Produces the
23
- // (ruleId, filePath, line) tuple that every per-line emission relies on - this tuple is the
24
- // 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
+ */
25
200
  export function finding(args: LineFindingArgs): Finding {
26
- 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
+ });
27
205
  }
28
206
 
29
- // Diff-aware discovery: uses `execFileSync` (not `execSync`) so the `mode` value is passed as
30
- // an argv entry and a malicious value cannot inject shell metacharacters. Custom-mode values pass
31
- // through `--end-of-options` so a leading `-` cannot be reinterpreted as a `git diff` flag
32
- // (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
+ */
33
214
  export function changedFiles(mode: string): Set<string> {
34
215
  if (mode === "staged") {
35
216
  return gitPathSet(["diff", "--name-only", "--cached"]);
@@ -43,28 +224,45 @@ export function changedFiles(mode: string): Set<string> {
43
224
  return gitPathSet(["diff", "--name-only", "--end-of-options", mode]);
44
225
  }
45
226
 
46
- // Spawns `git` through execFileSync with one fixed argv vector and returns the normalized path set
47
- // 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
+ */
48
233
  function gitPathSet(args: string[]): Set<string> {
49
234
  return new Set(execFileSync("git", args, { encoding: "utf8" }).split(/\r?\n/).filter(Boolean).map((line) => line.replaceAll("\\", "/")));
50
235
  }
51
236
 
52
- // Strips directory and trailing extension. Used by `naming.class-file-mismatch` so the exported
53
- // symbol name and the file stem normalise to the same shape - both sides must agree on this
54
- // 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
+ */
55
244
  export function fileBaseName(path: string): string {
56
245
  return basename(path).replace(/\.[^.]+$/, "");
57
246
  }
58
247
 
59
- // Lowercase-and-strip-separators canonical form. Treats `FooBar`, `foo_bar`, and `foo-bar` as
60
- // 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
+ */
61
255
  export function normalizedIdentifier(identifier: string): string {
62
256
  return identifier.replace(/[^A-Za-z0-9]/g, "").toLowerCase();
63
257
  }
64
258
 
65
- // Inserts a space at every camelCase boundary, then splits on any non-alphanumeric run. Acronym
66
- // runs (`HTTPServer`) stay intact because the inserted boundary is `lower → Upper`, not
67
- // `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
+ */
68
266
  export function splitIdentifierWords(identifier: string): string[] {
69
267
  return identifier
70
268
  .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
@@ -73,81 +271,34 @@ export function splitIdentifierWords(identifier: string): string[] {
73
271
  .filter(Boolean);
74
272
  }
75
273
 
76
- // Counts newlines before the offset to get a 0-based line number. `Math.max(0, …)` guards against
77
- // 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
+ */
78
282
  export function lineOffset(source: string, index: number): number {
79
283
  return source.slice(0, Math.max(0, index)).split("\n").length - 1;
80
284
  }
81
285
 
82
- // Detector for `waste.commented-out-code`: require a parseable disabled-code shape rather than a
83
- // bare keyword so prose such as "import cycle" or section headings don't look executable.
84
- export function isCommentedOutCode(line: string): boolean {
85
- const trimmed = line.trim();
86
- if (!trimmed.startsWith("//")) {
87
- return false;
88
- }
89
- const uncommented = trimmed.replace(/^\/\/+\s?/, "");
90
- if (isCommentSeparatorOrAnchor(uncommented)) {
91
- return false;
92
- }
93
- return isDisabledDeclaration(uncommented) || isDisabledControlFlow(uncommented) || isDisabledCall(uncommented);
94
- }
95
-
96
- // Skips prose examples, labels, search anchors, and section dividers that often begin with code words.
97
- function isCommentSeparatorOrAnchor(uncommented: string): boolean {
98
- const text = uncommented.trim();
99
- return (
100
- text === "" ||
101
- /^[-=*_#]{3,}$/.test(text) ||
102
- /^[A-Za-z_$][A-Za-z0-9_$]*\s*:\s*['"`[{]/.test(text) ||
103
- /\b(?:search|grep|anchor|example|for example|e\.g\.)\s*:/.test(text) ||
104
- /^(?!(?:if|for|while|switch)\b)[A-Za-z_$][A-Za-z0-9_$]*\s+\([^;{}]*[A-Za-z][^;{}]*\)$/.test(text) ||
105
- /^[A-Z][A-Za-z0-9_$]*(?:\s|\s*\([^)]*\)$)/.test(text)
106
- );
107
- }
108
-
109
- // Declarations must carry their syntactic partner (`=`, `{`, `from`, etc.) to count as disabled code.
110
- function isDisabledDeclaration(uncommented: string): boolean {
111
- return (
112
- /^(?:const|let|var)\s+[A-Za-z_$][A-Za-z0-9_$]*\s*=/.test(uncommented) ||
113
- /^(?:async\s+)?function\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\(/.test(uncommented) ||
114
- /^class\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s+extends\s+[A-Za-z_$][A-Za-z0-9_$]*)?\s*\{?/.test(uncommented) ||
115
- /^interface\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{?/.test(uncommented) ||
116
- /^type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*=/.test(uncommented) ||
117
- /^enum\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{?/.test(uncommented) ||
118
- /^import\s+(?:["'][^"']+["']|.+\s+from\s+["'][^"']+["'])/.test(uncommented) ||
119
- /^export\s+(?:\{|\*|(?:default\s+)?(?:const|let|var|function|class|interface|type|enum)\b)/.test(uncommented)
120
- );
121
- }
122
-
123
- // Control-flow comments need real syntax such as parentheses or an expression after `return`/`throw`.
124
- function isDisabledControlFlow(uncommented: string): boolean {
125
- return /^(?:if|for|while|switch)\s*\(/.test(uncommented) || /^(?:return|throw|await)\s+\S/.test(uncommented);
126
- }
127
-
128
- // Keep single-line disabled calls; heading/prose guards above filter labels such as `Rules (...)`.
129
- function isDisabledCall(uncommented: string): boolean {
130
- return /^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)?\s*\([^)]*\);?$/.test(uncommented);
131
- }
132
-
133
- // Lowercase membership test against the configured banned-names set. Drives the
134
- // `naming.identifier-quality` predicate so the rule stays a single Set lookup per identifier.
135
- export function isGenericName(name: string, bannedNames: Set<string>): boolean {
136
- return bannedNames.has(name.toLowerCase());
137
- }
138
-
139
- // Escapes the standard regex metacharacters so user-supplied strings (rule IDs, identifiers,
140
- // paths) can be embedded in dynamic patterns without altering their meaning. Hot path -
141
- // 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
+ */
142
292
  export function escapeRegex(source: string): string {
143
293
  return source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
144
294
  }
145
295
 
146
- /*
147
- * Per-rule severity tally for the `summary` Top-N rules block. Walks the findings once and returns
148
- * a deterministic Map keyed by ruleId carrying total / error / warning / advisory counts. Lets the
149
- * renderer surface "412 (0 err / 0 warn / 412 adv)" rows without re-scanning findings per row. The
150
- * 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
151
302
  */
152
303
  export function countRuleSeverities(findings: Finding[]): Map<string, { total: number; error: number; warning: number; advisory: number }> {
153
304
  const counts = new Map<string, { total: number; error: number; warning: number; advisory: number }>();
package/src/findings.ts CHANGED
@@ -1,15 +1,22 @@
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;
18
+ // The optional one-based column separates same-line occurrences in reports without changing the baseline fingerprint (ADR-017).
19
+ column?: number;
13
20
  severity: Severity;
14
21
  pillar: Pillar;
15
22
  confidence: Confidence;
@@ -18,38 +25,55 @@ interface FindingInput {
18
25
  metadata?: Record<string, unknown>;
19
26
  }
20
27
 
21
- // Builds the canonical Finding shape. The 16-hex fingerprint is the baseline identity used by
22
- // `gruff.baseline.v1`; changing the hashed fields or their join order is a baseline-breaking
23
- // schema change. Optional fields are omitted (not set to undefined) so finding equality stays stable.
24
- 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.
25
36
  const fingerprint = createHash("sha256")
26
- .update([input.ruleId, input.filePath, input.line ?? "", input.symbol ?? ""].join("\0"))
37
+ .update([findingInput.ruleId, findingInput.filePath, findingInput.line ?? "", findingInput.symbol ?? ""].join("\0"))
27
38
  .digest("hex")
28
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.
29
41
  return {
30
- ruleId: input.ruleId,
31
- message: input.message,
32
- filePath: input.filePath,
33
- ...(input.line ? { line: input.line } : {}),
34
- ...(input.endLine ? { endLine: input.endLine } : {}),
35
- severity: input.severity,
36
- 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,
37
50
  secondaryPillars: [],
38
51
  tier: "v0.1",
39
- confidence: input.confidence,
40
- ...(input.symbol ? { symbol: input.symbol } : {}),
41
- ...(input.remediation ? { remediation: input.remediation } : {}),
42
- metadata: input.metadata ?? {},
52
+ confidence: findingInput.confidence,
53
+ ...(findingInput.symbol ? { symbol: findingInput.symbol } : {}),
54
+ ...(findingInput.remediation ? { remediation: findingInput.remediation } : {}),
55
+ metadata: findingInput.metadata ?? {},
43
56
  fingerprint,
44
- stableIdentity: stableIdentityFor(input),
57
+ stableIdentity: stableIdentityFor(findingInput),
45
58
  };
46
59
  }
47
60
 
48
- // Stable, line-insensitive identity for external diff tooling; fingerprint remains line-sensitive.
49
- function stableIdentityFor(input: FindingInput): string {
50
- 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}`;
51
75
  return createHash("sha256")
52
- .update([input.ruleId, input.filePath, symbolOrMessage].join("\0"))
76
+ .update([findingInput.ruleId, findingInput.filePath, occurrenceIdentity].join("\0"))
53
77
  .digest("hex")
54
78
  .slice(0, 16);
55
79
  }