@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
@@ -2,7 +2,7 @@
2
2
  // pass - template-literal fixtures, generated array fixtures, and high-setup test blocks - then
3
3
  // reports `docs.fixture-purpose-missing` for each candidate without a nearby explanation comment.
4
4
  import { type FunctionBlock, setupLineCount } from "./blocks.ts";
5
- import { type CommentRecord } from "./comment-scanner.ts";
5
+ import { combinedContextLineComment, type CommentRecord } from "./comment-scanner.ts";
6
6
  import { type SourceFile } from "./discovery.ts";
7
7
  import { makeFinding } from "./findings.ts";
8
8
  import { isFixtureLikePath, isTestPath } from "./project-rules.ts";
@@ -36,8 +36,13 @@ export interface FixturePurposeInput {
36
36
  findings: Finding[];
37
37
  }
38
38
 
39
- // Test/fixture paths only - gated up front so production source never reports fixture-purpose
40
- // findings. Reports the stable `docs.fixture-purpose-missing` finding for each candidate.
39
+ /**
40
+ * Appends `docs.fixture-purpose-missing` findings to `input.findings` for undocumented candidates in the parsed file context.
41
+ * Files whose paths are neither tests nor fixture-like are ignored.
42
+ *
43
+ * @param input - File metadata, raw and code-only source text, lines, comments, function blocks, and target findings array.
44
+ * @returns Nothing. Mutates `input.findings` by pushing any missing-purpose findings.
45
+ */
41
46
  export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
42
47
  const { file, source, codeSource, lines, comments, blocks, findings } = input;
43
48
  if (!isTestPath(file.displayPath) && !isFixtureLikePath(file.displayPath)) {
@@ -50,14 +55,14 @@ export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
50
55
  findings.push(
51
56
  makeFinding({
52
57
  ruleId: "docs.fixture-purpose-missing",
53
- message: `Large fixture source near \`${candidate.symbol}\` is missing a purpose comment.`,
58
+ message: fixturePurposeMessage(candidate),
54
59
  filePath: file.displayPath,
55
60
  line: candidate.line,
56
61
  severity: "advisory",
57
62
  pillar: "documentation",
58
63
  confidence: "medium",
59
64
  symbol: candidate.symbol,
60
- remediation: "Add a nearby comment explaining what scanner path, regression, or fixture behavior this source covers.",
65
+ remediation: fixturePurposeRemediation(candidate),
61
66
  metadata: {
62
67
  targetKind: candidate.targetKind,
63
68
  fixtureLines: candidate.lineCount,
@@ -67,8 +72,43 @@ export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
67
72
  }
68
73
  }
69
74
 
70
- // Three candidate kinds collected in one pass: template-literal fixtures, generated array fixtures,
71
- // and test setup blocks. `occupiedLines` tracks the first two so the third doesn't double-report.
75
+ /**
76
+ * Builds the `docs.fixture-purpose-missing` diagnostic message for a candidate.
77
+ * The message must name the test for `test-setup` candidates or locate other fixtures by the nearby call or declaration name.
78
+ *
79
+ * @param candidate - Fixture-purpose candidate providing `targetKind` and `symbol`.
80
+ * @returns Formatted finding message describing the missing purpose comment.
81
+ */
82
+ function fixturePurposeMessage(candidate: FixturePurposeCandidate): string {
83
+ if (candidate.targetKind === "test-setup") {
84
+ return `Test \`${candidate.symbol}\` builds a large fixture setup without a purpose comment above the test.`;
85
+ }
86
+ return `Large fixture source near \`${candidate.symbol}\` is missing a purpose comment.`;
87
+ }
88
+
89
+ /**
90
+ * Builds the remediation guidance for a candidate's `targetKind`.
91
+ * The recommended placement must be accepted by `hasFixturePurposeComment` so the fix can clear the finding.
92
+ *
93
+ * @param candidate - Fixture-purpose candidate whose `targetKind` selects test-setup or fixture placement guidance.
94
+ * @returns Actionable remediation instruction explaining where to place the purpose comment.
95
+ */
96
+ function fixturePurposeRemediation(candidate: FixturePurposeCandidate): string {
97
+ if (candidate.targetKind === "test-setup") {
98
+ return "Add a comment directly above the test declaration explaining what scanner path, regression, or fixture behavior this setup covers.";
99
+ }
100
+ return "Add a comment on or directly above the fixture explaining what scanner path, regression, or fixture behavior this source covers.";
101
+ }
102
+
103
+ /**
104
+ * Finds unique fixture-purpose candidates within `source`'s line range across templates, generated arrays, and test setups.
105
+ * Template and generated-array locations suppress overlapping test blocks.
106
+ *
107
+ * @param source - Full file text used to extract template literal contents and line bounds.
108
+ * @param codeSource - Comment-stripped source text scanned for line-level fixture triggers.
109
+ * @param blocks - Parsed function blocks evaluated for large test-setup blocks.
110
+ * @returns Deduplicated candidates within `source` line bounds, or an empty array when none qualify.
111
+ */
72
112
  function fixturePurposeCandidates(source: string, codeSource: string, blocks: FunctionBlock[]): FixturePurposeCandidate[] {
73
113
  if (!hasFixturePurposeCandidateSignal(codeSource, blocks)) {
74
114
  return [];
@@ -101,13 +141,27 @@ function fixturePurposeCandidates(source: string, codeSource: string, blocks: Fu
101
141
  return candidates.filter((candidate) => candidate.line <= lines.length);
102
142
  }
103
143
 
104
- // Whole-file preflight for the only shapes that can become fixture-purpose findings.
144
+ /**
145
+ * Checks whether a file has a recognized fixture trigger or any test block so candidate extraction can proceed.
146
+ * Returning `false` skips fixture-purpose candidate extraction for the whole file.
147
+ *
148
+ * @param codeSource - Comment-stripped source text checked for fixture helper calls or fixture variable declarations.
149
+ * @param blocks - Parsed function blocks checked for at least one test block.
150
+ * @returns `true` if the file contains a test block or fixture trigger signal, otherwise `false`.
151
+ */
105
152
  function hasFixturePurposeCandidateSignal(codeSource: string, blocks: FunctionBlock[]): boolean {
106
153
  return blocks.some((block) => block.isTest) || /\b(?:analyseFixture|analyseProject|writeFileSync|Array\.from)\s*\(/.test(codeSource) || /\b(?:const|let|var)\s+[A-Za-z_$][A-Za-z0-9_$]*(?:Fixture|FIXTURE)[A-Za-z0-9_$]*\b[^=\n]*=/.test(codeSource);
107
154
  }
108
155
 
109
- // Composite key prevents two fixture candidates landing at the same line/symbol/kind tuple - a
110
- // real case when one declaration triggers both a template-literal match and a generated-array match.
156
+ /**
157
+ * Adds `candidate` to `candidates` only if its line, symbol, and `targetKind` tuple is absent from `seen`.
158
+ * Mutates `seen` and `candidates` together so existing tuples leave both unchanged while different kinds remain distinct.
159
+ *
160
+ * @param candidates - Target candidate list appended to when the tuple key is new.
161
+ * @param seen - Deduplication key set tracking `line`, `symbol`, and `targetKind` entries already added.
162
+ * @param candidate - Candidate entry to record if not yet seen.
163
+ * @returns Nothing. Mutates `seen` and `candidates` when `candidate` is unique.
164
+ */
111
165
  function pushUniqueFixturePurposeCandidate(candidates: FixturePurposeCandidate[], seen: Set<string>, candidate: FixturePurposeCandidate): void {
112
166
  const key = `${candidate.line}\0${candidate.symbol}\0${candidate.targetKind}`;
113
167
  if (seen.has(key)) {
@@ -117,8 +171,16 @@ function pushUniqueFixturePurposeCandidate(candidates: FixturePurposeCandidate[]
117
171
  candidates.push(candidate);
118
172
  }
119
173
 
120
- // Two-stage gate: detect the call-site trigger (`analyseFixture`, `analyseProject`, etc.), then
121
- // extract the adjacent template literal and confirm it is large enough to need documentation.
174
+ /**
175
+ * Builds a template-fixture candidate when `codeLine` has a recognized trigger and large template text.
176
+ * Reads the template literal from `source` at one-based `lineNumber` and rejects missing, empty, or small templates.
177
+ *
178
+ * @param source - Full file text containing the template literal body.
179
+ * @param lineOffsets - Precomputed UTF-16 starting offsets for each line in `source`.
180
+ * @param codeLine - Comment-stripped text of the current line checked for a fixture trigger.
181
+ * @param lineNumber - One-based line number of `codeLine`.
182
+ * @returns A `FixturePurposeCandidate` when triggered and over `FIXTURE_PURPOSE_MIN_LINES`, or `undefined`.
183
+ */
122
184
  function fixtureTemplateCandidate(source: string, lineOffsets: number[], codeLine: string, lineNumber: number): FixturePurposeCandidate | undefined {
123
185
  const trigger = fixtureTemplateTrigger(codeLine);
124
186
  if (!trigger) {
@@ -136,8 +198,13 @@ function fixtureTemplateCandidate(source: string, lineOffsets: number[], codeLin
136
198
  };
137
199
  }
138
200
 
139
- // Four trigger forms in priority order: `analyseFixture(`, `analyseProject(`, `writeFileSync(`,
140
- // or a `*Fixture` / `*FIXTURE` constant declaration. The `targetKind` differentiates them in metadata.
201
+ /**
202
+ * Identifies the fixture-trigger symbol and `targetKind` on `codeLine` for candidate metadata.
203
+ * Checks `analyseFixture`, `analyseProject`, and `writeFileSync` in that order, then falls back to `fixtureConstantName`.
204
+ *
205
+ * @param codeLine - Comment-stripped source line inspected for fixture calls or declarations.
206
+ * @returns Trigger `{ symbol, targetKind }` metadata, or `undefined` when no trigger matches.
207
+ */
141
208
  function fixtureTemplateTrigger(codeLine: string): { symbol: string; targetKind: string } | undefined {
142
209
  if (/\banalyseFixture\s*\(/.test(codeLine)) {
143
210
  return { symbol: "analyseFixture", targetKind: "inline-source" };
@@ -152,14 +219,26 @@ function fixtureTemplateTrigger(codeLine: string): { symbol: string; targetKind:
152
219
  return fixtureName ? { symbol: fixtureName, targetKind: "fixture-constant" } : undefined;
153
220
  }
154
221
 
155
- // Identifier names matching `*Fixture` or `*FIXTURE` are treated as opt-in markers - projects
156
- // signal "this is fixture data" with that suffix, so it's the natural trigger for the rule.
222
+ /**
223
+ * Extracts a variable declaration name matching `*Fixture` or `*FIXTURE` from `codeLine`.
224
+ * Projects signal fixture data with those opt-in markers, so matching declarations act as a natural trigger for the rule.
225
+ *
226
+ * @param codeLine - Comment-stripped source line checked for a `const`, `let`, or `var` fixture declaration.
227
+ * @returns Declared identifier name if it matches the fixture marker pattern, otherwise `undefined`.
228
+ */
157
229
  function fixtureConstantName(codeLine: string): string | undefined {
158
230
  return codeLine.match(/\b(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*(?:Fixture|FIXTURE)[A-Za-z0-9_$]*)\b[^=\n]*=/)?.[1];
159
231
  }
160
232
 
161
- // `Array.from({ length: N })` style generated fixtures. Requires both a `*Fixture` constant name
162
- // and N > FIXTURE_PURPOSE_MIN_LINES so trivial test arrays don't trip the rule.
233
+ /**
234
+ * Builds a `generated-fixture` candidate when a marked declaration and qualifying `Array.from` length digits share a line.
235
+ * Reads length digits from `codeLine` or `rawLine`, using `rawLine` for the name only when `codeLine` has a declaration keyword.
236
+ *
237
+ * @param rawLine - Original source line used as fallback for fixture name and length extraction.
238
+ * @param codeLine - Comment-stripped line checked first for the declaration and `Array.from` length.
239
+ * @param lineNumber - One-based line number recorded as the candidate's anchor line.
240
+ * @returns A `FixturePurposeCandidate` when both name and length exceeding `FIXTURE_PURPOSE_MIN_LINES` match, else `undefined`.
241
+ */
163
242
  function generatedFixtureCandidate(rawLine: string, codeLine: string, lineNumber: number): FixturePurposeCandidate | undefined {
164
243
  const fixtureName = fixtureConstantName(codeLine) ?? (/\b(?:const|let|var)\b/.test(codeLine) ? fixtureConstantName(rawLine) : undefined);
165
244
  const generatedLength = Number((codeLine.match(/\bArray\.from\s*\(\s*\{\s*length\s*:\s*(\d+)/) ?? rawLine.match(/\bArray\.from\s*\(\s*\{\s*length\s*:\s*(\d+)/))?.[1] ?? 0);
@@ -174,8 +253,14 @@ function generatedFixtureCandidate(rawLine: string, codeLine: string, lineNumber
174
253
  };
175
254
  }
176
255
 
177
- // Test blocks with high setup-line counts AND a fixture-shape signal. Excludes blocks whose setup
178
- // already produced a template-literal or generated-array candidate at the same line.
256
+ /**
257
+ * Collects `test-setup` candidates for test blocks whose setup exceeds `FIXTURE_PURPOSE_MIN_LINES` with a fixture-shape signal.
258
+ * Any prior template or generated-array candidate line inside a block suppresses that block to avoid duplicate reporting.
259
+ *
260
+ * @param blocks - Parsed function blocks to inspect for qualifying test blocks.
261
+ * @param occupiedLines - Line numbers already claimed by template or generated-array fixture candidates.
262
+ * @returns List of `test-setup` candidates for unsuppressed qualifying test blocks.
263
+ */
179
264
  function fixtureTestBlockCandidates(blocks: FunctionBlock[], occupiedLines: Set<number>): FixturePurposeCandidate[] {
180
265
  const candidates: FixturePurposeCandidate[] = [];
181
266
  for (const block of blocks) {
@@ -196,8 +281,14 @@ function fixtureTestBlockCandidates(blocks: FunctionBlock[], occupiedLines: Set<
196
281
  return candidates;
197
282
  }
198
283
 
199
- // Returns true if any occupied line falls inside the block's line range. Prevents test blocks
200
- // from double-reporting on a fixture that was already detected as a template literal.
284
+ /**
285
+ * Checks whether any anchor line in `occupiedLines` falls within `block`'s line range.
286
+ * The setup scan skips matching blocks to avoid reporting the same fixture twice.
287
+ *
288
+ * @param block - Function block providing `startLine` and `lineCount` bounds.
289
+ * @param occupiedLines - Set of one-based candidate anchor line numbers.
290
+ * @returns `true` if any occupied line falls between `block.startLine` and its inclusive end line, otherwise `false`.
291
+ */
201
292
  function fixtureLineInsideBlock(block: FunctionBlock, occupiedLines: Set<number>): boolean {
202
293
  const endLine = block.startLine + block.lineCount - 1;
203
294
  for (const line of occupiedLines) {
@@ -208,15 +299,24 @@ function fixtureLineInsideBlock(block: FunctionBlock, occupiedLines: Set<number>
208
299
  return false;
209
300
  }
210
301
 
211
- // Either the canonical fixture-generation calls (analyseFixture / writeFileSync / mkdtempSync /
212
- // Array.from) or an identifier containing "fixture". The narrow allowlist is deliberate - broader
213
- // matchers would catch ordinary production code that happens to construct test data.
302
+ /**
303
+ * Checks whether a test body calls `analyseFixture`, `writeFileSync`, `mkdtempSync`, or `Array.from`, or uses a fixture identifier.
304
+ * Keeps the match narrow to avoid flagging ordinary test setup.
305
+ *
306
+ * @param source - Comment-stripped body text of a test block.
307
+ * @returns `true` when a fixture-related call or case-insensitive fixture identifier is present, otherwise `false`.
308
+ */
214
309
  function hasFixtureSetupSignal(source: string): boolean {
215
310
  return /\b(?:analyseFixture|writeFileSync|mkdtempSync|Array\.from)\s*\(/.test(source) || hasFixtureIdentifier(source);
216
311
  }
217
312
 
218
- // Substring (not word boundary) match because fixture identifiers in real projects include forms
219
- // like `userFixtureA`, `manyFixtureRows`, etc. Lowercased so casing variants all match.
313
+ /**
314
+ * Checks whether `source` contains an identifier-shaped token with `fixture` anywhere in its name, ignoring case.
315
+ * Substring matching is intentional because fixture identifiers include names such as `userFixtureA` and `manyFixtureRows`.
316
+ *
317
+ * @param source - Source text scanned for identifier tokens.
318
+ * @returns `true` if any identifier token contains `fixture` case-insensitively, otherwise `false`.
319
+ */
220
320
  function hasFixtureIdentifier(source: string): boolean {
221
321
  for (const match of source.matchAll(/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g)) {
222
322
  if ((match[0] ?? "").toLowerCase().includes("fixture")) {
@@ -226,20 +326,35 @@ function hasFixtureIdentifier(source: string): boolean {
226
326
  return false;
227
327
  }
228
328
 
229
- // Two conjoint conditions: enough lines AND at least one declarative keyword. Short strings or
230
- // pure prose templates don't need a purpose comment; only code-shaped fixtures do.
329
+ /**
330
+ * Checks whether template literal `text` exceeds `FIXTURE_PURPOSE_MIN_LINES` and contains a declarative code keyword.
331
+ * Short strings or pure prose templates are skipped because only code-shaped fixtures require a purpose comment.
332
+ *
333
+ * @param text - Template literal contents extracted from a fixture candidate line.
334
+ * @returns `true` when both the line-count threshold and code-keyword check pass, otherwise `false`.
335
+ */
231
336
  function isLargeSourceFixtureText(text: string): boolean {
232
337
  return fixtureLineCount(text) > FIXTURE_PURPOSE_MIN_LINES && /\b(?:function|class|interface|type|enum|const|let|var|import|export|test|it)\b/.test(text);
233
338
  }
234
339
 
235
- // Newline-count, not "nonblank-line count" - the rule cares about apparent fixture size as the
236
- // maintainer sees it, including blank padding.
340
+ /**
341
+ * Counts the LF or CRLF lines in `text`, including blank padding for the size threshold.
342
+ * Empty text counts as one line, and a trailing newline adds an empty final line.
343
+ *
344
+ * @param text - Fixture text whose line count is measured.
345
+ * @returns Total number of lines produced by splitting on LF or CRLF newlines.
346
+ */
237
347
  function fixtureLineCount(text: string): number {
238
348
  return text.split(/\r?\n/).length;
239
349
  }
240
350
 
241
- // Index → line lookup support. Used by the fixture-template detector to map a byte offset to a
242
- // (line, column) coordinate without splitting the whole source on every query.
351
+ /**
352
+ * Computes each line's starting UTF-16 offset in `source` for locating fixture templates by line number.
353
+ * Index 0 always holds 0 for the first line, including empty strings, and each LF character adds the next offset.
354
+ *
355
+ * @param source - Full source text to index by line start.
356
+ * @returns Array of zero-based UTF-16 character offsets indexed by zero-based line number.
357
+ */
243
358
  function sourceLineStartOffsets(source: string): number[] {
244
359
  const offsets = [0];
245
360
  for (let index = 0; index < source.length; index += 1) {
@@ -250,8 +365,14 @@ function sourceLineStartOffsets(source: string): number[] {
250
365
  return offsets;
251
366
  }
252
367
 
253
- // Walks forward from the line's start offset to find the opening backtick on that line, then
254
- // searches for its match. Returns undefined when no template starts on the line.
368
+ /**
369
+ * Locates the first backtick on one-based `lineNumber` and extracts the template literal text up to its closing backtick.
370
+ *
371
+ * @param source - Full file text containing the template literal.
372
+ * @param lineOffsets - Precomputed UTF-16 line-start offsets for `source`.
373
+ * @param lineNumber - One-based line number where the opening backtick is expected.
374
+ * @returns Enclosed template text, or `undefined` if the line, opening backtick, or unescaped closing backtick is missing.
375
+ */
255
376
  function templateLiteralAtLine(source: string, lineOffsets: number[], lineNumber: number): string | undefined {
256
377
  const start = lineOffsets[lineNumber - 1];
257
378
  if (start === undefined) {
@@ -266,8 +387,14 @@ function templateLiteralAtLine(source: string, lineOffsets: number[], lineNumber
266
387
  return end === undefined ? undefined : source.slice(firstBacktick + 1, end);
267
388
  }
268
389
 
269
- // Linear walk respecting `\`` escapes. Does NOT handle `${…}` interpolation specially - fixture
270
- // templates rarely contain nested backticks, and a stricter parse would not help the rule's signal.
390
+ /**
391
+ * Searches `source` from `startIndex` (immediately after the opening backtick) for the next unescaped backtick.
392
+ * Backslash escapes are skipped and `${...}` interpolations are not parsed.
393
+ *
394
+ * @param source - Full source string being scanned.
395
+ * @param startIndex - Zero-based character index immediately following the opening backtick.
396
+ * @returns Index of the closing backtick in `source`, or `undefined` if none is found before end-of-file.
397
+ */
271
398
  function closingTemplateLiteralIndex(source: string, startIndex: number): number | undefined {
272
399
  let isEscaped = false;
273
400
  for (let index = startIndex; index < source.length; index += 1) {
@@ -287,19 +414,59 @@ function closingTemplateLiteralIndex(source: string, startIndex: number): number
287
414
  return undefined;
288
415
  }
289
416
 
290
- // Two acceptable positions: a comment on the candidate line itself, or one directly above with
291
- // nothing but blank lines in between. Anything farther away cannot be claimed as documentation.
417
+ /**
418
+ * Checks whether the candidate at one-based `line` has a qualifying purpose comment in `comments`.
419
+ * Evaluates a spanning same-line comment alone first, then checks the nearest preceding comment across a blank-only gap,
420
+ * combining adjacent line comments only for that preceding header.
421
+ *
422
+ * @param lines - File lines used to verify only blank lines intervene between a preceding comment and `line`.
423
+ * @param comments - Parsed comment records for the file in source order.
424
+ * @param line - One-based candidate anchor line number.
425
+ * @returns `true` if a same-line comment or contiguous preceding comment header qualifies, otherwise `false`.
426
+ */
292
427
  function hasFixturePurposeComment(lines: string[], comments: CommentRecord[], line: number): boolean {
293
428
  const sameLine = comments.find((comment) => comment.line <= line && comment.endLine >= line);
294
- if (sameLine && hasFixturePurposeMarker(sameLine.text)) {
429
+ if (sameLine && isFixturePurposeComment(sameLine.text)) {
295
430
  return true;
296
431
  }
297
432
  const leading = leadingFixturePurposeComment(lines, comments, line);
298
- return Boolean(leading && hasFixturePurposeMarker(leading.text));
433
+ return Boolean(leading && isFixturePurposeComment(combinedContextLineComment(comments, leading).text));
434
+ }
435
+
436
+ // This word-count threshold accepts a comment as a purpose statement even without the vocabulary
437
+ // fast path, because grading wording by keyword list sent maintainers into rewrite loops when a
438
+ // genuine explanation missed the exact words. Shorter comments still need a vocabulary word.
439
+ const FIXTURE_PURPOSE_MIN_WORDS = 8;
440
+
441
+ /**
442
+ * Checks whether comment `text` qualifies as a fixture explanation via purpose vocabulary or minimum word count.
443
+ *
444
+ * @param text - Normalized comment body text to evaluate.
445
+ * @returns `true` if `text` contains a purpose marker or at least `FIXTURE_PURPOSE_MIN_WORDS` words, else `false`.
446
+ */
447
+ function isFixturePurposeComment(text: string): boolean {
448
+ return hasFixturePurposeMarker(text) || fixtureCommentWordCount(text) >= FIXTURE_PURPOSE_MIN_WORDS;
299
449
  }
300
450
 
301
- // Like `leadingCommentForLine` but with the fixture-specific blank-gap predicate that allows for
302
- // slightly more spacing than the documentation-rule version.
451
+ /**
452
+ * Counts alphanumeric word-like tokens in comment text so punctuation-only fragments do not count as substantive prose.
453
+ *
454
+ * @param text - Comment body text split on whitespace.
455
+ * @returns Number of whitespace-delimited tokens containing at least one ASCII letter or digit.
456
+ */
457
+ function fixtureCommentWordCount(text: string): number {
458
+ return text.split(/\s+/).filter((token) => /[A-Za-z0-9]/.test(token)).length;
459
+ }
460
+
461
+ /**
462
+ * Finds the nearest comment in `comments` immediately above `line` separated by only blank lines.
463
+ * Fixture-purpose counterpart to `leadingCommentForLine`.
464
+ *
465
+ * @param lines - File lines inspected to confirm no non-blank code lies between the comment and `line`.
466
+ * @param comments - Parsed comment records for the file in source order.
467
+ * @param line - One-based anchor line of the fixture or test declaration.
468
+ * @returns Nearest preceding `CommentRecord` across a blank-only gap, or `undefined` if none qualifies.
469
+ */
303
470
  function leadingFixturePurposeComment(lines: string[], comments: CommentRecord[], line: number): CommentRecord | undefined {
304
471
  for (let index = comments.length - 1; index >= 0; index -= 1) {
305
472
  const comment = comments[index];
@@ -314,8 +481,15 @@ function leadingFixturePurposeComment(lines: string[], comments: CommentRecord[]
314
481
  return undefined;
315
482
  }
316
483
 
317
- // Identical to `hasOnlyBlankLines` but with an inclusive upper bound - fixtures may have one
318
- // extra blank line of breathing room above them that ordinary declaration comments do not.
484
+ /**
485
+ * Checks whether `lines` contains only blank text from one-based `startLine` through `endLine`, inclusive.
486
+ * Missing line entries count as blank and an empty range returns `true`.
487
+ *
488
+ * @param lines - Zero-indexed array of file lines.
489
+ * @param startLine - Inclusive one-based first line number of the gap to inspect.
490
+ * @param endLine - Inclusive one-based last line number of the gap to inspect.
491
+ * @returns `true` if every line in the range is blank or missing, otherwise `false`.
492
+ */
319
493
  function hasOnlyBlankFixturePurposeGap(lines: string[], startLine: number, endLine: number): boolean {
320
494
  for (let line = startLine; line <= endLine; line += 1) {
321
495
  if ((lines[line - 1] ?? "").trim() !== "") {
@@ -325,8 +499,12 @@ function hasOnlyBlankFixturePurposeGap(lines: string[], startLine: number, endLi
325
499
  return true;
326
500
  }
327
501
 
328
- // Vocabulary list of words a meaningful fixture-purpose comment is expected to use (fixture,
329
- // covers, regression, baseline, fingerprint, …). Project task references count as well.
502
+ /**
503
+ * Checks whether comment `text` contains a recognized fixture-purpose term such as `fingerprint`, ignoring case.
504
+ *
505
+ * @param text - Comment body text checked for purpose vocabulary markers.
506
+ * @returns `true` if a purpose marker word or phrase matches case-insensitively, otherwise `false`.
507
+ */
330
508
  function hasFixturePurposeMarker(text: string): boolean {
331
- return /\b(?:fixture|covers|reproduces|regression|scanner|parse|baseline|fingerprint|noise|valid case|invalid case|because|M\d{1,3})\b/i.test(text) || /\.goat-flow\/tasks\//.test(text);
509
+ return /\b(?:fixture|covers|reproduces|regression|scanner|parse|baseline|fingerprint|noise|valid case|invalid case|because)\b/i.test(text);
332
510
  }