@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
@@ -1,20 +1,14 @@
1
- // Every documentation, comment-quality, fixture-purpose, stale-reference, context-doc,
2
- // magic-threshold, and restating-signature rule. The biggest of the rule-pack modules; the
3
- // orchestrator `analyseCommentQualityRules` fans out per-comment / per-declaration / per-block
4
- // passes that all share a stable, deterministic emission order.
5
- import { existsSync } from "node:fs";
6
- import { dirname as dirnamePath, resolve } from "node:path";
7
- import { cwd } from "node:process";
1
+ // Every comment-quality, fixture-purpose and context-doc rule. The orchestrator
2
+ // `analyseCommentQualityRules` fans out per-comment / per-declaration / per-block passes that all
3
+ // share a stable, deterministic emission order.
8
4
  import { type FunctionBlock } from "./blocks.ts";
9
- import { type CommentRecord } from "./comment-scanner.ts";
5
+ import { combinedContextLineComment, type CommentRecord, isOverviewOrDividerCommentAt } from "./comment-scanner.ts";
10
6
  import { type SourceFile } from "./discovery.ts";
11
7
  import { type ExportedDeclaration, interfaceDeclarations } from "./doc-rules.ts";
12
8
  import { type CommentedDeclaration, pushDeclarationContextFindings, pushFunctionContextFindings } from "./context-doc-rules.ts";
13
9
  import { makeFinding } from "./findings.ts";
14
10
  import { splitIdentifierWords } from "./findings-helpers.ts";
15
11
  import { pushFixturePurposeFindings } from "./fixture-purpose-rules.ts";
16
- import { isTestPath } from "./project-rules.ts";
17
- import { ruleDescriptors } from "./rules.ts";
18
12
  import type { Config, Finding } from "./types.ts";
19
13
 
20
14
  type CommentQualityRuleInput = {
@@ -36,81 +30,90 @@ type FunctionContextCommentQualityInput = {
36
30
  findings: Finding[];
37
31
  };
38
32
 
39
- type MagicThresholdCandidate = {
40
- label: string;
41
- value: string;
42
- kind: string;
43
- };
44
-
45
- const DESCRIPTOR_IDS = new Set(ruleDescriptors().map((descriptor) => descriptor.ruleId));
46
- const CLI_FLAGS = knownCliFlags();
47
-
48
-
49
- /*
50
- * Coordinator for every comment-quality rule. Comments and declarations are parsed once and the
51
- * rule descriptor + CLI flag sets are computed once, so every sub-rule sees the same stable inputs.
33
+ /**
34
+ * Runs the comment-quality checks using the source text, parsed comments, declaration blocks, and configuration in `input`.
35
+ * Shares parsed inputs so that all checks resolve against the same source locations.
36
+ *
37
+ * @param input - Bundle containing the file identity, source texts, parsed blocks and comments, config, and findings collector.
38
+ * @returns Nothing. Appends findings for violations of the comment-quality contract to `input.findings`.
52
39
  */
53
40
  export function analyseCommentQualityRules(input: CommentQualityRuleInput): void {
54
41
  const { file, source, codeSource, blocks, comments, config, findings } = input;
55
42
  const lines = source.split(/\r?\n/);
56
43
  const declarations = commentedDeclarations(blocks, interfaceDeclarations(source, codeSource));
57
44
 
58
- analyseStandaloneCommentQuality(file, comments, DESCRIPTOR_IDS, CLI_FLAGS, findings);
45
+ analyseStandaloneCommentQuality(file, source, comments, findings, config.trackingTokens);
59
46
  analyseCommentedDeclarationQuality(file, lines, comments, declarations, findings);
60
47
  analyseFunctionContextCommentQuality({ file, lines, comments, blocks, config, findings });
61
- pushMagicThresholdFindings(file, lines, codeSource, comments, findings);
62
48
  pushFixturePurposeFindings({ file, source, codeSource, lines, comments, blocks, findings });
63
49
  }
64
50
 
65
- /*
66
- * Five per-comment rules (task tracking, suppression rationale, stale file refs, stale rule refs,
67
- * stale CLI flag refs) that run on every comment regardless of whether it documents a declaration.
68
- * Stable, deterministic emission order across the five sub-checks.
51
+ /**
52
+ * Checks comments for task tracking and suppression rationale in stable input order.
53
+ *
54
+ * @param file - source file whose path identifies violations
55
+ * @param source - file text used to check marker context and locate attached rationale
56
+ * @param comments - parsed comments to check, including those that document no declaration
57
+ * @param findings - shared list to which violations are appended
58
+ * @param trackingTokens - patterns for accepted tracking references. Testing a global or sticky pattern can change its lastIndex.
59
+ * @returns nothing. Appends violations to findings.
69
60
  */
70
- function analyseStandaloneCommentQuality(file: SourceFile, comments: CommentRecord[], ruleIdSet: Set<string>, optionFlagSet: Set<string>, findings: Finding[]): void {
61
+ function analyseStandaloneCommentQuality(file: SourceFile, source: string, comments: CommentRecord[], findings: Finding[], trackingTokens: readonly RegExp[]): void {
62
+ const attachedRationale = directivesWithAttachedRationale(source, comments, trackingTokens);
71
63
  for (const comment of comments) {
72
- pushTodoWithoutTrackingFinding(file, comment, findings);
73
- pushSuppressionWithoutRationaleFinding(file, comment, findings);
74
- pushStaleFileReferenceFindings(file, comment, findings);
75
- pushStaleRuleReferenceFindings(file, comment, ruleIdSet, findings);
76
- pushStaleCliFlagReferenceFindings(file, comment, optionFlagSet, findings);
64
+ pushTodoWithoutTrackingFinding(file, source, comment, findings, trackingTokens);
65
+ pushSuppressionWithoutRationaleFinding(file, comment, attachedRationale.has(comment), findings, trackingTokens);
77
66
  }
78
67
  }
79
68
 
80
- /*
81
- * Per-declaration rules that need both the declaration metadata and its leading comment. Each
82
- * declaration is checked against three rules (stale reference, restating signature, context-doc)
83
- * in their stable, deterministic order.
69
+ /**
70
+ * Run declaration context rules that need metadata and a leading comment, in stable input order.
71
+ * Skip comments that only restate the signature because they supply no context to judge.
72
+ *
73
+ * @param file - Source file to which findings are attributed.
74
+ * @param lines - Source lines used to locate each declaration's leading comment.
75
+ * @param comments - Comment records used to find and assemble the declaration's context.
76
+ * @param declarations - Ordered declarations to check.
77
+ * @param findings - Collector that receives context findings.
78
+ * @returns Nothing. Appends findings for declarations with a leading comment that supplies context.
84
79
  */
85
80
  function analyseCommentedDeclarationQuality(file: SourceFile, lines: string[], comments: CommentRecord[], declarations: CommentedDeclaration[], findings: Finding[]): void {
86
81
  for (const declaration of declarations) {
87
- const comment = leadingCommentForLine(lines, comments, declaration.line);
82
+ const comment = declaration.kind === "function" ? functionLeadingComment(lines, comments, declaration.line) : leadingCommentForLine(lines, comments, declaration.line);
88
83
  if (!comment) {
89
84
  continue;
90
85
  }
91
- pushStaleDeclarationCommentFinding(file, comment, declaration, findings);
92
- pushRestatingSignatureCommentFinding(file, comment, declaration, findings);
93
86
  if (!isRestatingSignatureComment(comment.text, declaration.name, declaration.kind)) {
94
- pushDeclarationContextFindings(file, lines, declaration, comment, findings);
87
+ pushDeclarationContextFindings(file, lines, declaration, combinedContextLineComment(comments, comment), findings);
95
88
  }
96
89
  }
97
90
  }
98
91
 
99
- // Function-only context-doc rule. Restating-signature comments are skipped first because the
100
- // useless-docblock rule has already flagged them; running context checks on top would be redundant noise.
92
+ /**
93
+ * Checks leading function comments from `input` against function context rules, skipping missing or signature-only comments.
94
+ *
95
+ * @param input - Bundle providing file identity, source lines, parsed comments, function blocks, config, and findings collector.
96
+ * @returns Nothing. Appends context findings for qualifying function comments to `input.findings`.
97
+ */
101
98
  function analyseFunctionContextCommentQuality(input: FunctionContextCommentQualityInput): void {
102
99
  const { file, lines, comments, blocks, config, findings } = input;
103
100
  for (const block of blocks) {
104
- const comment = leadingCommentForLine(lines, comments, block.declarationLine);
101
+ const comment = functionLeadingComment(lines, comments, block.declarationLine);
105
102
  if (!comment || isRestatingSignatureComment(comment.text, block.name, "function")) {
106
103
  continue;
107
104
  }
108
- pushFunctionContextFindings(file, block, comment, config, findings);
105
+ pushFunctionContextFindings(file, block, combinedContextLineComment(comments, comment), config, findings);
109
106
  }
110
107
  }
111
108
 
112
- // Combines callable blocks and exported interfaces into one homogeneous list for the comment-quality
113
- // rules. Test blocks are excluded because their `test("…")` description is the documentation.
109
+ /**
110
+ * Combines callable blocks and exported interfaces into one homogeneous list for comment-quality rules.
111
+ * Test blocks are excluded because their test description serves as the documentation.
112
+ *
113
+ * @param blocks - Parsed function blocks from the source file, including test blocks that will be filtered out.
114
+ * @param interfaces - Exported interface declarations extracted from the source file.
115
+ * @returns Ordered commented declaration descriptors covering non-test functions and exported interfaces.
116
+ */
114
117
  function commentedDeclarations(blocks: FunctionBlock[], interfaces: ExportedDeclaration[]): CommentedDeclaration[] {
115
118
  return [
116
119
  ...blocks
@@ -120,14 +123,19 @@ function commentedDeclarations(blocks: FunctionBlock[], interfaces: ExportedDecl
120
123
  ];
121
124
  }
122
125
 
123
- /*
124
- * One finding per comment containing an untracked task marker. The reported marker keyword is
125
- * preserved in stable metadata so consumers can group by marker kind. Reports the stable
126
- * untracked-task-marker finding when no tracking reference is attached.
126
+ /**
127
+ * Flags task comments without tracking and keeps the marker keyword in stable metadata so consumers can group by marker kind.
128
+ *
129
+ * @param file - source file whose display path anchors the finding
130
+ * @param source - original source used to identify the task marker
131
+ * @param comment - candidate comment whose text is checked for tracking and whose line anchors the finding
132
+ * @param findings - collector for docs.todo-without-tracking findings
133
+ * @param trackingTokens - project patterns used alongside built-in forms. Testing a global or sticky pattern can change its lastIndex.
134
+ * @returns Nothing. It appends one finding for a comment with a recognized marker and no accepted tracking.
127
135
  */
128
- function pushTodoWithoutTrackingFinding(file: SourceFile, comment: CommentRecord, findings: Finding[]): void {
129
- const marker = todoMarker(comment.text);
130
- if (!marker || hasTodoTracking(comment.text)) {
136
+ function pushTodoWithoutTrackingFinding(file: SourceFile, source: string, comment: CommentRecord, findings: Finding[], trackingTokens: readonly RegExp[]): void {
137
+ const marker = todoMarker(source, comment);
138
+ if (!marker || hasTodoTracking(comment.text, trackingTokens)) {
131
139
  return;
132
140
  }
133
141
  findings.push(
@@ -145,38 +153,102 @@ function pushTodoWithoutTrackingFinding(file: SourceFile, comment: CommentRecord
145
153
  );
146
154
  }
147
155
 
148
- // Four canonical task-marker words, returned in uppercase so the finding message reads consistently
149
- // regardless of how the maintainer wrote them.
150
- function todoMarker(text: string): string | undefined {
151
- return text.match(/\b(TODO|FIXME|HACK|XXX)\b/i)?.[1]?.toUpperCase();
156
+ /**
157
+ * Finds the first leading task marker in the recorded comment body, skipping mid-sentence mentions and fenced lines in block comments.
158
+ * A marker may follow a list or quote prefix.
159
+ *
160
+ * @param source - Full file text used to slice block comment contents.
161
+ * @param comment - Comment record whose body lines are inspected for a leading marker.
162
+ * @returns Uppercase marker spelling for a consistent finding message, or `undefined` when no body line introduces a task.
163
+ */
164
+ function todoMarker(source: string, comment: CommentRecord): string | undefined {
165
+ for (const line of commentBodyLines(source, comment)) {
166
+ const marker = leadingTodoMarker(line);
167
+ if (marker) {
168
+ return marker;
169
+ }
170
+ }
171
+ return undefined;
172
+ }
173
+
174
+ /**
175
+ * Extracts normalized body lines for a comment while stripping block decoration and surrounding whitespace.
176
+ * Omits fenced code delimiters and their contents to ignore marker examples inside documentation.
177
+ *
178
+ * @param source - Full file text used to read block comment contents via `comment` offsets.
179
+ * @param comment - Parsed comment record, either line or block.
180
+ * @returns Body lines from `comment.text` for line comments or unfenced stripped lines sliced from `source` for block comments.
181
+ */
182
+ function commentBodyLines(source: string, comment: CommentRecord): string[] {
183
+ if (comment.kind === "line") {
184
+ return [comment.text];
185
+ }
186
+ const body = source.slice(comment.startIndex + 2, Math.max(comment.startIndex + 2, comment.endIndex - 1));
187
+ const lines: string[] = [];
188
+ let isInsideFence = false;
189
+ for (const rawLine of body.split(/\r?\n/)) {
190
+ const line = rawLine.replace(/^[ \t]*\*[ \t]?/, "").trim();
191
+ if (line.startsWith("```")) {
192
+ isInsideFence = !isInsideFence;
193
+ continue;
194
+ }
195
+ if (!isInsideFence) {
196
+ lines.push(line);
197
+ }
198
+ }
199
+ return lines;
200
+ }
201
+
202
+ /**
203
+ * Extracts a leading task marker from a comment body line, optionally after a list bullet or greater-than quote prefix.
204
+ * The marker must end the line or be followed by a colon, opening parenthesis, hyphen, or whitespace.
205
+ *
206
+ * @param line - Single stripped comment body line to inspect.
207
+ * @returns Uppercase marker name when present with an allowed separator, or `undefined` otherwise.
208
+ */
209
+ function leadingTodoMarker(line: string): string | undefined {
210
+ const match = line.match(/^(?:(?:[-*>]|\d+[.)])\s+)?(TODO|FIXME|HACK|XXX)\b(.*)$/i);
211
+ const marker = match?.[1];
212
+ if (!marker) {
213
+ return undefined;
214
+ }
215
+ const rest = match?.[2] ?? "";
216
+ return rest === "" || /^[\s:(-]/.test(rest) ? marker.toUpperCase() : undefined;
152
217
  }
153
218
 
154
219
  const TODO_TRACKING_PATTERNS = [
155
220
  /https?:\/\//i,
156
221
  /(?:^|\s)#\d+\b/,
157
222
  /\bGH-\d+\b/i,
158
- /\bM\d{1,3}\b/,
159
- /\.goat-flow\/tasks\//,
160
- /\bADR-\d{3}\b/i,
161
223
  /\b\d{4}-\d{2}-\d{2}\b/,
162
224
  /\bowner\s*:/i,
163
225
  ] as const;
164
226
 
165
- // Eight accepted tracking forms (URL, #123, GH-123, M123, .goat-flow/tasks, ADR-001, ISO date,
166
- // `owner:`). The stable set is intentionally generous so projects with different ticketing systems
167
- // can comply without changing their conventions.
168
- function hasTodoTracking(text: string): boolean {
169
- return TODO_TRACKING_PATTERNS.some((pattern) => pattern.test(text));
170
- }
171
-
172
- /*
173
- * Targets `eslint-disable`, `biome-ignore`, coverage `istanbul ignore`, etc. when no maintainer
174
- * rationale is attached - the false-positive escape hatch is explicit because TS suppression
175
- * directives have their own dedicated rule. Reports the stable `docs.suppression-without-rationale` finding.
227
+ /**
228
+ * Checks whether task comment text contains a built-in tracking reference or matches any configured project token.
229
+ * With no project patterns, only the built-in forms qualify.
230
+ *
231
+ * @param text - Comment text to test for a URL, issue number, date, owner tag, or custom tracking token.
232
+ * @param trackingTokens - Extra project regexes; testing a global or sticky pattern can mutate its `lastIndex`.
233
+ * @returns `true` when `text` matches a built-in tracking form or any pattern in `trackingTokens`, `false` otherwise.
234
+ */
235
+ function hasTodoTracking(text: string, trackingTokens: readonly RegExp[] = []): boolean {
236
+ return TODO_TRACKING_PATTERNS.some((pattern) => pattern.test(text)) || trackingTokens.some((token) => token.test(text));
237
+ }
238
+
239
+ /**
240
+ * Flags tool suppressions that lack a rationale on the directive or in attached line comments. TypeScript directives are excluded.
241
+ *
242
+ * @param file - source file whose display path anchors the finding
243
+ * @param comment - candidate directive text and source line
244
+ * @param hasAttachedRationale - whether an attached comment already explains the suppression
245
+ * @param findings - collector for the stable docs.suppression-without-rationale finding
246
+ * @param trackingTokens - project patterns accepted as rationale on the directive. A global or sticky pattern can have its lastIndex changed.
247
+ * @returns Nothing. It appends one finding for a recognized suppression with no accepted rationale.
176
248
  */
177
- function pushSuppressionWithoutRationaleFinding(file: SourceFile, comment: CommentRecord, findings: Finding[]): void {
249
+ function pushSuppressionWithoutRationaleFinding(file: SourceFile, comment: CommentRecord, hasAttachedRationale: boolean, findings: Finding[], trackingTokens: readonly RegExp[]): void {
178
250
  const suppression = suppressionDirective(comment.text);
179
- if (!suppression || hasSuppressionRationale(comment.text)) {
251
+ if (!suppression || hasAttachedRationale || hasSuppressionRationale(comment.text, trackingTokens)) {
180
252
  return;
181
253
  }
182
254
  findings.push(
@@ -194,318 +266,85 @@ function pushSuppressionWithoutRationaleFinding(file: SourceFile, comment: Comme
194
266
  );
195
267
  }
196
268
 
197
- // Returns the suppression keyword that triggered the rule. `@ts-*` directives are explicitly
198
- // excluded - they have their own dedicated rule (`pushTsDirectiveFinding`).
199
- function suppressionDirective(text: string): string | undefined {
200
- if (/@ts-(?:ignore|expect-error|nocheck|check)\b/.test(text)) {
201
- return undefined;
202
- }
203
- const match = text.match(/\b(eslint-disable(?:-next-line|-line)?|biome-ignore|oxlint-disable|istanbul ignore|c8 ignore|v8 ignore|prettier-ignore)\b/i);
204
- return match?.[1];
205
- }
206
-
207
- // Accepted rationale forms: explanatory keywords (because, intentional, false positive, tracked in),
208
- // project task markers (M123, ADR-XXX, GH-123), explicit `reason:`, a tracking URL, or a #issue.
209
- export function hasSuppressionRationale(text: string): boolean {
210
- return /\b(?:because|intentional|false positive|tracked in|M\d{1,3}|ADR-\d{3}|GH-\d+)\b/i.test(text) || /\breason\s*:/i.test(text) || /(?:^|\s)#\d+\b/.test(text) || /https?:\/\//i.test(text) || /\.goat-flow\/tasks\//.test(text);
211
- }
212
-
213
- /*
214
- * Scans the comment text for path-shaped references and reports any that resolve to nothing on
215
- * disk. Historical-context comments (migration notes, legacy markers) are exempted on purpose
216
- * because they intentionally name removed files. Reports the stable `docs.stale-comment` finding.
269
+ /**
270
+ * Collects standalone non-TypeScript suppressions explained by adjacent preceding line comments.
271
+ * Blank lines, code, block or trailing comments, and recognized suppressions break the run so rationale stays local.
272
+ *
273
+ * @param source - Full file text used to verify whether each comment starts on its own line.
274
+ * @param comments - Parsed comments in source order.
275
+ * @param trackingTokens - Extra rationale patterns; testing global or sticky regexes can change their `lastIndex`.
276
+ * @returns Suppression comment records with attached preceding rationale, or an empty set when none qualify.
217
277
  */
218
- function pushStaleFileReferenceFindings(file: SourceFile, comment: CommentRecord, findings: Finding[]): void {
219
- if (isHistoricalContextComment(comment.text)) {
220
- return;
221
- }
222
- for (const match of comment.text.matchAll(/[`'"]((?:\.{1,2}\/|src\/|bin\/|scripts\/|docs\/|fixtures\/|\.goat-flow\/)[A-Za-z0-9_./-]+\.(?:ts|tsx|js|json|ya?ml|toml|md|sh))[`'"]/g)) {
223
- const referencedPath = match[1] ?? "";
224
- if (referencedPathExists(file, referencedPath)) {
225
- continue;
278
+ function directivesWithAttachedRationale(source: string, comments: readonly CommentRecord[], trackingTokens: readonly RegExp[]): Set<CommentRecord> {
279
+ const attached = new Set<CommentRecord>();
280
+ let blockEndLine = -1;
281
+ let hasBlockRationale = false;
282
+ for (const comment of comments) {
283
+ const isStandalone = comment.kind === "line" && startsItsLine(source, comment.startIndex);
284
+ const isDirective = suppressionDirective(comment.text) !== undefined;
285
+ const continuesBlock = isStandalone && comment.line === blockEndLine + 1;
286
+ if (isDirective && continuesBlock && hasBlockRationale) {
287
+ attached.add(comment);
226
288
  }
227
- findings.push(staleCommentFinding(file, comment, `Comment references missing path \`${referencedPath}\`.`, { staleReference: referencedPath, referenceType: "path" }));
228
- }
229
- }
230
-
231
- // Tries both the project-root and same-directory interpretations because comments are inconsistent
232
- // about which they imply. Either match is enough to consider the reference live.
233
- function referencedPathExists(file: SourceFile, referencedPath: string): boolean {
234
- const fromProject = resolve(cwd(), referencedPath);
235
- const fromFile = resolve(dirnamePath(file.absolutePath), referencedPath);
236
- return existsSync(fromProject) || existsSync(fromFile);
237
- }
238
-
239
- /*
240
- * Walks every `pillar.rule-id` shape in the comment and reports those not in the descriptor set.
241
- * Historical-context comments stay exempt so removed rules can remain referenced in lessons text.
242
- * Reports the stable `docs.stale-comment` finding for each stale rule id.
243
- */
244
- function pushStaleRuleReferenceFindings(file: SourceFile, comment: CommentRecord, ruleIdSet: Set<string>, findings: Finding[]): void {
245
- if (isHistoricalContextComment(comment.text)) {
246
- return;
247
- }
248
- for (const match of comment.text.matchAll(/\b((?:complexity|dead-code|design|docs|modernisation|naming|security|sensitive-data|size|test-quality|waste)\.[a-z0-9-]+)\b/g)) {
249
- const ruleId = match[1] ?? "";
250
- if (ruleIdSet.has(ruleId)) {
251
- continue;
289
+ if (isStandalone && !isDirective) {
290
+ hasBlockRationale = (continuesBlock && hasBlockRationale) || hasSuppressionRationale(comment.text, trackingTokens);
291
+ blockEndLine = comment.line;
292
+ } else {
293
+ blockEndLine = -1;
294
+ hasBlockRationale = false;
252
295
  }
253
- findings.push(staleCommentFinding(file, comment, `Comment references unknown rule id \`${ruleId}\`.`, { staleReference: ruleId, referenceType: "ruleId" }));
254
296
  }
297
+ return attached;
255
298
  }
256
299
 
257
- /*
258
- * Each double-dash option in a comment must appear in `cliFlags` (parsed from the CLI source) or
259
- * it counts as a stale reference. The rule's value is catching gruff-ts maintainers who rename a
260
- * flag and forget to update its references - so the check only fires when the comment also names
261
- * gruff-ts (or invokes the gruff/gruff-ts binary). In any other project, flag references belong to
262
- * that project's CLI, not gruff-ts, and validating them against gruff-ts's own option surface
263
- * produces only noise. Reports the stable `docs.stale-comment` finding for each unknown option.
300
+ /**
301
+ * Determines whether a comment begins on a line with only leading whitespace before it.
302
+ * A trailing comment breaks the run of standalone comments that can supply suppression rationale.
303
+ *
304
+ * @param source - Full file text containing the comment.
305
+ * @param commentStart - Zero-based character offset where the comment begins in `source`.
306
+ * @returns `true` when text between the preceding newline and `commentStart` is only whitespace.
264
307
  */
265
- function pushStaleCliFlagReferenceFindings(file: SourceFile, comment: CommentRecord, optionFlagSet: Set<string>, findings: Finding[]): void {
266
- if (isHistoricalContextComment(comment.text)) {
267
- return;
268
- }
269
- if (!mentionsGruffCli(comment.text)) {
270
- return;
271
- }
272
- for (const match of comment.text.matchAll(/(?<![A-Za-z0-9])--[a-z][a-z0-9-]*/g)) {
273
- const flag = match[0] ?? "";
274
- if (optionFlagSet.has(flag)) {
275
- continue;
276
- }
277
- findings.push(staleCommentFinding(file, comment, `Comment references unknown CLI flag \`${flag}\`.`, { staleReference: flag, referenceType: "cliFlag" }));
278
- }
308
+ function startsItsLine(source: string, commentStart: number): boolean {
309
+ const lineStart = source.lastIndexOf("\n", commentStart - 1) + 1;
310
+ return source.slice(lineStart, commentStart).trim() === "";
279
311
  }
280
312
 
281
- // True when the comment names the gruff-ts CLI by binary or product name. Acts as the activation
282
- // gate for the unknown-CLI-flag check; comments that talk about other tools' flags never trip it.
283
- function mentionsGruffCli(text: string): boolean {
284
- return /\bgruff(?:-ts)?\b/i.test(text);
285
- }
286
-
287
- // Static list of valid CLI options. Hand-curated rather than parsed from the Commander definition
288
- // at runtime because the stale-CLI-flag rule must not depend on import order - both files would
289
- // otherwise have to load the analyser to power their checks.
290
- function knownCliFlags(): Set<string> {
291
- return new Set([
292
- "--ansi",
293
- "--baseline",
294
- "--config",
295
- "--diff",
296
- "--changed-ranges",
297
- "--changed-scope",
298
- "--fail-on",
299
- "--force",
300
- "--format",
301
- "--generate-baseline",
302
- "--help",
303
- "--history-file",
304
- "--host",
305
- "--include-ignored",
306
- "--no-ansi",
307
- "--no-baseline",
308
- "--no-config",
309
- "--no-interaction",
310
- "--output",
311
- "--port",
312
- "--profile",
313
- "--project-root",
314
- "--quiet",
315
- "--silent",
316
- "--since",
317
- "--top",
318
- "--verbose",
319
- "--version",
320
- ]);
321
- }
322
-
323
- // A comment whose prose names a different symbol than the declaration directly below it. The
324
- // historical-context escape hatch keeps migration notes (which intentionally name removed symbols)
325
- // quiet. Reports `docs.stale-comment` with stable metadata.
326
- function pushStaleDeclarationCommentFinding(file: SourceFile, comment: CommentRecord, declaration: CommentedDeclaration, findings: Finding[]): void {
327
- if (isHistoricalContextComment(comment.text)) {
328
- return;
329
- }
330
- const referencedName = referencedDeclarationName(comment.text, declaration.kind);
331
- if (!referencedName || referencedName === declaration.name) {
332
- return;
333
- }
334
- findings.push(staleCommentFinding(file, comment, `Comment names \`${referencedName}\` but documents \`${declaration.name}\`.`, { staleReference: referencedName, referenceType: declaration.kind, symbol: declaration.name }));
335
- }
336
-
337
- // Two-pass match: either `<kind> name` (e.g., "function fooBar") or leading `name <kind|helper|
338
- // method|contract|type>`. Both forms appear in real comments and either is sufficient evidence
339
- // that the comment intends to name a specific symbol.
340
- function referencedDeclarationName(text: string, kind: CommentedDeclaration["kind"]): string | undefined {
341
- const directBackticked = text.match(new RegExp(["\\b", kind, "\\s+`([A-Za-z_$][A-Za-z0-9_$]*)`"].join(""), "i"));
342
- if (directBackticked?.[1]) {
343
- return directBackticked[1];
344
- }
345
- const directCodeLike = text.match(new RegExp(["\\b", kind, "\\s+([A-Za-z_$][A-Za-z0-9_$]*)"].join(""), "i"));
346
- if (directCodeLike?.[1] && isCodeLikeIdentifier(directCodeLike[1])) {
347
- return directCodeLike[1];
348
- }
349
- return leadingReferencedDeclarationName(text, kind);
350
- }
351
-
352
- // The leading form is intentionally stricter than `<kind> name`: ordinary English such as
353
- // "Read-only filesystem interface" or "Symlink helper" must not become a stale-symbol finding.
354
- function leadingReferencedDeclarationName(text: string, kind: CommentedDeclaration["kind"]): string | undefined {
355
- const backticked = text.match(new RegExp(["^`([A-Za-z_$][A-Za-z0-9_$]*)`\\s+(?:", kind, "|helper|method|contract|type)\\b"].join(""), "i"));
356
- if (backticked?.[1]) {
357
- return backticked[1];
358
- }
359
- const codeLike = text.match(new RegExp(["^([A-Za-z_$][A-Za-z0-9_$]*)\\s+(?:", kind, "|helper|method|contract|type)\\b"].join(""), "i"));
360
- if (codeLike?.[1] && isCodeLikeIdentifier(codeLike[1])) {
361
- return codeLike[1];
362
- }
363
- return undefined;
364
- }
365
-
366
- // Requires a real identifier marker beyond normal prose capitalization.
367
- function isCodeLikeIdentifier(name: string): boolean {
368
- return /[A-Z].*[A-Z]|[a-z][A-Z]|[_$]|\d/.test(name);
369
- }
370
-
371
- /*
372
- * Public block-doc comments are exempted on purpose because their first words usually mirror the
373
- * API surface - that's the documented JSDoc convention, not a useless docblock. Reports the stable
374
- * `docs.useless-docblock` finding otherwise.
313
+ /**
314
+ * Identifies a supported linter or coverage suppression keyword in comment text, excluding TypeScript directives.
315
+ * TypeScript ignore, expect-error, nocheck, and check directives yield `undefined` so the TypeScript-specific check handles them.
316
+ *
317
+ * @param text - Comment text to scan for a supported suppression directive.
318
+ * @returns Matched suppression keyword, or `undefined` when absent or handled as a TypeScript directive.
375
319
  */
376
- function pushRestatingSignatureCommentFinding(file: SourceFile, comment: CommentRecord, declaration: CommentedDeclaration, findings: Finding[]): void {
377
- if (declaration.kind === "function" && declaration.isPublic && comment.kind === "block") {
378
- return;
379
- }
380
- if (!isRestatingSignatureComment(comment.text, declaration.name, declaration.kind)) {
381
- return;
382
- }
383
- findings.push(
384
- makeFinding({
385
- ruleId: "docs.useless-docblock",
386
- message: `Comment for \`${declaration.name}\` only restates the signature.`,
387
- filePath: file.displayPath,
388
- line: comment.line,
389
- severity: "advisory",
390
- pillar: "documentation",
391
- confidence: "medium",
392
- symbol: declaration.name,
393
- remediation: "Update the JSDoc so it documents the current signature and return value.",
394
- metadata: {},
395
- }),
396
- );
397
- }
398
-
399
- /*
400
- * Test files are exempt because their `expect(x).toBe(42)` patterns legitimately contain
401
- * unexplained numbers. For every production source line, the rule looks for either a named
402
- * threshold/limit/cap or a `threshold(config, …)` default call, then checks that a nearby comment
403
- * explains it. Reports the stable `docs.magic-threshold-without-rationale` finding.
404
- */
405
- function pushMagicThresholdFindings(file: SourceFile, lines: string[], codeSource: string, comments: CommentRecord[], findings: Finding[]): void {
406
- if (isTestPath(file.displayPath) || !hasMagicThresholdSignal(codeSource)) {
407
- return;
408
- }
409
- const codeLines = codeSource.split(/\r?\n/);
410
- codeLines.forEach((codeLine, index) => {
411
- const candidate = magicThresholdCandidate(lines[index] ?? "", codeLine);
412
- if (!candidate || hasNearbyThresholdRationale(lines, comments, index + 1)) {
413
- return;
414
- }
415
- findings.push(
416
- makeFinding({
417
- ruleId: "docs.magic-threshold-without-rationale",
418
- message: `Threshold-like value \`${candidate.label}\` lacks a nearby rationale comment.`,
419
- filePath: file.displayPath,
420
- line: index + 1,
421
- severity: "advisory",
422
- pillar: "documentation",
423
- confidence: "medium",
424
- symbol: candidate.label,
425
- remediation: "Add a nearby comment explaining the threshold, limit, budget, or default.",
426
- metadata: { value: candidate.value, thresholdKind: candidate.kind },
427
- }),
428
- );
429
- });
430
- }
431
-
432
- // Cheap whole-file preflight for the two shapes `magicThresholdCandidate` can report.
433
- function hasMagicThresholdSignal(codeSource: string): boolean {
434
- return /\bthreshold\s*\(/.test(codeSource) || /\b(?:const|let|var)\s+[A-Za-z_$][A-Za-z0-9_$]*(?:Threshold|Limit|Cap|Budget|Timeout|Tolerance|Weight|Score|Max|Min|Default|Entropy|Length)[A-Za-z0-9_$]*\b/i.test(codeSource);
435
- }
436
-
437
- // Two candidate sources: a named constant (`const maxThings = N`) or a `threshold()` default call.
438
- // Either is treated as policy-shaped numeric - ordinary arithmetic constants stay quiet.
439
- function magicThresholdCandidate(rawLine: string, codeLine: string): MagicThresholdCandidate | undefined {
440
- return namedThresholdCandidate(rawLine, codeLine) ?? configDefaultThresholdCandidate(rawLine, codeLine);
441
- }
442
-
443
- // Identifiers ending in Threshold/Limit/Cap/Budget/Timeout/Tolerance/Weight/Score/Max/Min/Default/
444
- // Entropy/Length signal "policy number". `-1`, `0`, `1`, `2` are exempt because they're usually sentinels.
445
- // Gates on the masked `codeLine` so template-literal fixture content (where the same line appears as
446
- // source text but inside a backtick) does not trip the rule.
447
- function namedThresholdCandidate(rawLine: string, codeLine: string): MagicThresholdCandidate | undefined {
448
- if (!/\b(?:const|let|var)\s+[A-Za-z_$][A-Za-z0-9_$]*(?:Threshold|Limit|Cap|Budget|Timeout|Tolerance|Weight|Score|Max|Min|Default|Entropy|Length)[A-Za-z0-9_$]*\b/i.test(codeLine)) {
449
- return undefined;
450
- }
451
- const named = rawLine.match(/\b(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*(?:Threshold|Limit|Cap|Budget|Timeout|Tolerance|Weight|Score|Max|Min|Default|Entropy|Length)[A-Za-z0-9_$]*)\b[^=\n]*=\s*(-?\d+(?:\.\d+)?)/i);
452
- const label = named?.[1];
453
- const thresholdValue = named?.[2];
454
- if (!label) {
455
- return undefined;
456
- }
457
- if (!thresholdValue || isCommonSafeNumber(thresholdValue)) {
458
- return undefined;
459
- }
460
- return { label, value: thresholdValue, kind: "named-threshold" };
461
- }
462
-
463
- // Cheap gate first: only look for the four-arg `threshold(config, "rule", "key", N)` form when the
464
- // masked code actually contains `threshold(`. Required because labels come from raw text but the
465
- // call shape must originate in executable code - masked code is the only stable signal for that.
466
- function configDefaultThresholdCandidate(rawLine: string, codeLine: string): MagicThresholdCandidate | undefined {
467
- if (!/\bthreshold\s*\(/.test(codeLine)) {
468
- return undefined;
469
- }
470
- const thresholdDefault = rawLine.match(/\bthreshold\s*\([^)]*,\s*["']([^"']+)["']\s*,\s*["']([^"']+)["']\s*,\s*(-?\d+(?:\.\d+)?)\s*\)/);
471
- const ruleId = thresholdDefault?.[1];
472
- const key = thresholdDefault?.[2];
473
- const thresholdValue = thresholdDefault?.[3];
474
- if (!ruleId || !key) {
475
- return undefined;
476
- }
477
- if (!thresholdValue || isCommonSafeNumber(thresholdValue)) {
320
+ function suppressionDirective(text: string): string | undefined {
321
+ if (/@ts-(?:ignore|expect-error|nocheck|check)\b/.test(text)) {
478
322
  return undefined;
479
323
  }
480
- return { label: `${ruleId}.${key}`, value: thresholdValue, kind: "config-default" };
481
- }
482
-
483
- // Four sentinel values that recur as "counter starts", "boolean toggle as int", and "default
484
- // count" without being policy decisions. Anything outside this set is treated as a threshold.
485
- function isCommonSafeNumber(numericLiteral: string): boolean {
486
- return ["-1", "0", "1", "2"].includes(numericLiteral);
487
- }
488
-
489
- // Two acceptable positions for the explanatory comment: same line as the constant, or directly
490
- // above with a blank-line gap. Mirrors `hasFixturePurposeComment` adjacency rules.
491
- function hasNearbyThresholdRationale(lines: string[], comments: CommentRecord[], line: number): boolean {
492
- const sameLine = comments.find((comment) => comment.line <= line && comment.endLine >= line);
493
- if (sameLine && hasThresholdRationaleMarker(sameLine.text)) {
494
- return true;
495
- }
496
- const leading = leadingCommentForLine(lines, comments, line);
497
- return Boolean(leading && hasThresholdRationaleMarker(leading.text));
498
- }
499
-
500
- // Vocabulary used by the magic-threshold rule. A numeric constant followed by a comment containing
501
- // any of these words is treated as "explained".
502
- function hasThresholdRationaleMarker(text: string): boolean {
503
- return /\b(?:threshold|limit|cap|budget|tuned|default|because|empirical)\b/i.test(text);
324
+ const match = text.match(/\b(eslint-disable(?:-next-line|-line)?|biome-ignore|oxlint-disable|istanbul ignore|c8 ignore|v8 ignore|prettier-ignore)\b/i);
325
+ return match?.[1];
504
326
  }
505
327
 
506
- // Three-tier test: useful-context vocabulary short-circuits as "not restating"; identical
507
- // word sequences are restating; near-identical sequences (one extra trailing word) are restating.
508
- // The result drives the `docs.useless-docblock` rule.
328
+ /**
329
+ * Checks whether suppression comment text contains an explanatory rationale cue, issue reference, URL, or tracking token.
330
+ *
331
+ * @param text - Comment text to test for rationale phrases, `reason:` labels, issue numbers, URLs, or custom patterns.
332
+ * @param trackingTokens - Project tracking regexes; testing a global or sticky pattern can change its `lastIndex`.
333
+ * @returns `true` when `text` matches any built-in rationale cue or pattern in `trackingTokens`.
334
+ */
335
+ export function hasSuppressionRationale(text: string, trackingTokens: readonly RegExp[] = []): boolean {
336
+ return /\b(?:because|intentional|false positive|tracked in|GH-\d+)\b/i.test(text) || /\breason\s*:/i.test(text) || /(?:^|\s)#\d+\b/.test(text) || /https?:\/\//i.test(text) || trackingTokens.some((token) => token.test(text));
337
+ }
338
+
339
+ /**
340
+ * Checks whether a declaration comment merely restates its signature instead of adding context.
341
+ * Context cues exempt the comment; otherwise empty remaining words, a name match, or one extra trailing word counts as restating.
342
+ *
343
+ * @param text - Comment text to evaluate against the declaration name.
344
+ * @param name - Identifier name of the commented declaration.
345
+ * @param kind - Declaration kind used to exclude generic kind words before comparing.
346
+ * @returns `false` when context cues are present; otherwise `true` if remaining words only match `name` (with at most one extra word).
347
+ */
509
348
  function isRestatingSignatureComment(text: string, name: string, kind: CommentedDeclaration["kind"]): boolean {
510
349
  if (hasUsefulCommentContext(text)) {
511
350
  return false;
@@ -521,8 +360,13 @@ function isRestatingSignatureComment(text: string, name: string, kind: Commented
521
360
  return words.length <= nameWords.length + 1 && sameWords(words.slice(0, nameWords.length), nameWords);
522
361
  }
523
362
 
524
- // Strips backticks, splits on non-identifier characters, then further splits each fragment into
525
- // identifier-style words. The flat list lets the comparator compare on a per-word basis.
363
+ /**
364
+ * Splits comment text into identifier-style words for comparison with a declaration name.
365
+ * An empty list leaves the comparator with no words to distinguish the comment from the signature.
366
+ *
367
+ * @param text - Raw comment text to tokenize and split on identifier boundaries.
368
+ * @returns Non-empty word tokens extracted from `text`.
369
+ */
526
370
  function normalizedCommentWords(text: string): string[] {
527
371
  return text
528
372
  .replace(/`/g, " ")
@@ -533,58 +377,57 @@ function normalizedCommentWords(text: string): string[] {
533
377
  .filter(Boolean);
534
378
  }
535
379
 
536
- // Stop-word list that filters out grammatical scaffolding before name comparison. Includes the
537
- // declaration kind itself so a kind-and-name pair is judged on the name alone.
380
+ /**
381
+ * Builds the stop-word set that filters out grammatical scaffolding before name comparison.
382
+ * Includes the declaration kind itself so a kind-and-name pair is judged on the name alone.
383
+ *
384
+ * @param kind - Declaration kind added to the generic scaffolding words.
385
+ * @returns Lowercase stop words to strip from normalized comment words.
386
+ */
538
387
  function restatementStopWords(kind: CommentedDeclaration["kind"]): Set<string> {
539
388
  return new Set(["a", "an", "the", "this", "that", "function", "method", "helper", "type", "declaration", kind]);
540
389
  }
541
390
 
542
- // Trailing-`s` stripping for words longer than 3 characters. Crude but adequate for restating-
543
- // signature detection - covers `findings`/`finding`, `imports`/`import`, etc.
391
+ /**
392
+ * Strips a trailing `s` from words longer than three characters for crude plural normalization in restatement detection.
393
+ * Covers pairs such as `findings`/`finding` and `imports`/`import`.
394
+ *
395
+ * @param word - Normalized word token to stem.
396
+ * @returns `word` without its trailing `s` when length exceeds 3, or `word` unchanged otherwise.
397
+ */
544
398
  function stemCommentWord(word: string): string {
545
399
  return word.length > 3 && word.endsWith("s") ? word.slice(0, -1) : word;
546
400
  }
547
401
 
548
- // Pointwise equality between two stemmed word arrays. Used by `isRestatingSignatureComment` to
549
- // compare the comment's first words against the declaration name's words.
402
+ /**
403
+ * Checks pointwise equality between two stemmed word lists for `isRestatingSignatureComment`.
404
+ *
405
+ * @param left - First stemmed word sequence to compare.
406
+ * @param right - Second stemmed word sequence to compare.
407
+ * @returns `true` when `left` and `right` have the same length and matching elements at every position.
408
+ */
550
409
  function sameWords(left: string[], right: string[]): boolean {
551
410
  return left.length === right.length && left.every((word, index) => word === right[index]);
552
411
  }
553
412
 
554
- // The shared "this comment carries real signal" vocabulary. Any match here exempts the comment
555
- // from the useless-docblock and stale-reference rules.
413
+ /**
414
+ * Checks whether a candidate comment contains a context keyword that exempts it from signature-restatement detection.
415
+ *
416
+ * @param text - Comment text to scan for rationale, contract, invariant, or side-effect keywords.
417
+ * @returns `true` when `text` contains a recognized context keyword.
418
+ */
556
419
  function hasUsefulCommentContext(text: string): boolean {
557
420
  return /\b(?:because|why|intentional|tradeoff|compat|avoid|preserve|invariant|contract|side effect|throws|writes|reads|persists|fallback|recover|stable|deterministic|schema|fingerprint)\b/i.test(text);
558
421
  }
559
422
 
560
- // Five vocabulary markers signal "this comment is intentionally about removed/old code". The
561
- // stale-reference rules all consult this so legacy notes can keep naming removed paths/symbols.
562
- function isHistoricalContextComment(text: string): boolean {
563
- return /\b(?:previously|legacy|compat|migration|ADR)\b/i.test(text);
564
- }
565
-
566
- // Single makeFinding factory for every stale-comment variant. `symbol` is omitted (not set to
567
- // undefined) via conditional spread because exactOptionalPropertyTypes treats the two as different
568
- // shapes - the omission keeps stable fingerprints round-tripping across baseline reads and writes.
569
- function staleCommentFinding(file: SourceFile, comment: CommentRecord, message: string, metadata: Record<string, string>): Finding {
570
- const symbol = metadata["symbol"];
571
- return makeFinding({
572
- ruleId: "docs.stale-comment",
573
- message,
574
- filePath: file.displayPath,
575
- line: comment.line,
576
- severity: "advisory",
577
- pillar: "documentation",
578
- confidence: "medium",
579
- ...(symbol ? { symbol } : {}),
580
- remediation: "Update the comment reference or add historical context that explains why it remains useful.",
581
- metadata,
582
- });
583
- }
584
-
585
- // Reverse scan through the comment list - the closest comment whose `endLine < line` wins, but
586
- // only when nothing but blank lines sits between them. Anything else means the comment documents
587
- // a different declaration.
423
+ /**
424
+ * Finds the closest preceding comment record for a declaration line when only blank lines separate them.
425
+ *
426
+ * @param lines - Source lines used to verify that the gap after the comment is empty.
427
+ * @param comments - Ordered comment records from the file.
428
+ * @param line - One-based line number of the declaration.
429
+ * @returns Closest preceding comment separated only by blank lines, or `undefined` if none can attach.
430
+ */
588
431
  function leadingCommentForLine(lines: string[], comments: CommentRecord[], line: number): CommentRecord | undefined {
589
432
  for (let index = comments.length - 1; index >= 0; index -= 1) {
590
433
  const comment = comments[index];
@@ -599,8 +442,28 @@ function leadingCommentForLine(lines: string[], comments: CommentRecord[], line:
599
442
  return undefined;
600
443
  }
601
444
 
602
- // Tighter sibling of `hasOnlyBlankFixturePurposeGap` - exclusive upper bound. Used by
603
- // `leadingCommentForLine` to confirm no executable token sits between a comment and its declaration.
445
+ /**
446
+ * Finds the leading comment for a function at a one-based line, excluding divider and file-overview comments.
447
+ *
448
+ * @param lines - Source lines passed to `leadingCommentForLine` and overview/divider detection.
449
+ * @param comments - Ordered comment records from the file.
450
+ * @param line - One-based declaration line of the function.
451
+ * @returns Attached comment record, or `undefined` if none precedes the function or it is a divider or file overview.
452
+ */
453
+ function functionLeadingComment(lines: string[], comments: CommentRecord[], line: number): CommentRecord | undefined {
454
+ const comment = leadingCommentForLine(lines, comments, line);
455
+ return comment && !isOverviewOrDividerCommentAt(lines, comment.line - 1, comment.endLine - 1, line - 1) ? comment : undefined;
456
+ }
457
+
458
+ /**
459
+ * Checks that every one-based line in `[startLine, endLine)` is blank so `leadingCommentForLine` can confirm no code intervenes.
460
+ * Tighter sibling of `hasOnlyBlankFixturePurposeGap` with an exclusive upper bound.
461
+ *
462
+ * @param lines - Zero-indexed source file lines.
463
+ * @param startLine - Inclusive one-based start line of the gap to check.
464
+ * @param endLine - Exclusive one-based end line of the gap to check.
465
+ * @returns `true` when every line in `[startLine, endLine)` contains only whitespace.
466
+ */
604
467
  function hasOnlyBlankLines(lines: string[], startLine: number, endLine: number): boolean {
605
468
  for (let line = startLine; line < endLine; line += 1) {
606
469
  if ((lines[line - 1] ?? "").trim() !== "") {