@blundergoat/gruff-ts 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +49 -50
  4. package/SECURITY.md +18 -31
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -10
  8. package/docs/agent-hook.md +32 -35
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +160 -89
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -172
  15. package/docs/rules.md +126 -98
  16. package/package.json +10 -8
  17. package/src/analyser.ts +817 -323
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +62 -68
  22. package/src/blocks.ts +512 -336
  23. package/src/changed-regions.ts +380 -79
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +445 -436
  26. package/src/cli-program.ts +915 -172
  27. package/src/cli.ts +9 -3
  28. package/src/comment-rules.ts +236 -418
  29. package/src/comment-scanner.ts +339 -47
  30. package/src/complexity-metrics.ts +111 -35
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +751 -223
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +182 -54
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +493 -140
  40. package/src/doc-rules.ts +602 -126
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +134 -109
  43. package/src/findings.ts +47 -27
  44. package/src/fixture-purpose-rules.ts +194 -50
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +328 -121
  47. package/src/hook-contract.ts +681 -255
  48. package/src/init-config.ts +163 -118
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -468
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +32 -127
  54. package/src/parsed-script.ts +868 -314
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +86 -74
  57. package/src/project-config-rules.ts +324 -140
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +102 -38
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +821 -203
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +249 -55
  66. package/src/security-flow-rules.ts +791 -115
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +460 -387
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +378 -104
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +343 -253
  73. package/src/text-scans.ts +62 -11
  74. package/src/types.ts +220 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -163
  77. package/src/test-fixtures.ts +0 -671
@@ -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 { combinedContextLineComment, 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,72 +30,75 @@ 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, source, 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, source: string, 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, source, 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
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
  }
@@ -109,8 +106,14 @@ function analyseFunctionContextCommentQuality(input: FunctionContextCommentQuali
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, source: string, comment: CommentRecord, findings: Finding[]): void {
136
+ function pushTodoWithoutTrackingFinding(file: SourceFile, source: string, comment: CommentRecord, findings: Finding[], trackingTokens: readonly RegExp[]): void {
129
137
  const marker = todoMarker(source, comment);
130
- if (!marker || hasTodoTracking(comment.text)) {
138
+ if (!marker || hasTodoTracking(comment.text, trackingTokens)) {
131
139
  return;
132
140
  }
133
141
  findings.push(
@@ -145,9 +153,14 @@ function pushTodoWithoutTrackingFinding(file: SourceFile, source: string, commen
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. A marker must INTRODUCE a comment body line - prose
150
- // that merely mentions a marker word (quoted, backticked, or mid-sentence) stays quiet.
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
+ */
151
164
  function todoMarker(source: string, comment: CommentRecord): string | undefined {
152
165
  for (const line of commentBodyLines(source, comment)) {
153
166
  const marker = leadingTodoMarker(line);
@@ -158,9 +171,14 @@ function todoMarker(source: string, comment: CommentRecord): string | undefined
158
171
  return undefined;
159
172
  }
160
173
 
161
- // One body line per physical comment line: the trimmed `//` text, or each block-comment line with
162
- // its `*` decoration stripped. Lines inside ``` fences are dropped so marker examples shown in
163
- // doc comments cannot become findings.
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
+ */
164
182
  function commentBodyLines(source: string, comment: CommentRecord): string[] {
165
183
  if (comment.kind === "line") {
166
184
  return [comment.text];
@@ -181,9 +199,13 @@ function commentBodyLines(source: string, comment: CommentRecord): string[] {
181
199
  return lines;
182
200
  }
183
201
 
184
- // Leading-marker grammar: optional list bullet, the marker word, then a delimiter real markers use
185
- // (":", "(", "-", whitespace, or end of line). Any other next character - a quote, slash, or
186
- // backtick - means the line talks ABOUT a marker instead of being one.
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
+ */
187
209
  function leadingTodoMarker(line: string): string | undefined {
188
210
  const match = line.match(/^(?:(?:[-*>]|\d+[.)])\s+)?(TODO|FIXME|HACK|XXX)\b(.*)$/i);
189
211
  const marker = match?.[1];
@@ -198,28 +220,35 @@ const TODO_TRACKING_PATTERNS = [
198
220
  /https?:\/\//i,
199
221
  /(?:^|\s)#\d+\b/,
200
222
  /\bGH-\d+\b/i,
201
- /\bM\d{1,3}\b/,
202
- /\.goat-flow\/tasks\//,
203
- /\bADR-\d{3}\b/i,
204
223
  /\b\d{4}-\d{2}-\d{2}\b/,
205
224
  /\bowner\s*:/i,
206
225
  ] as const;
207
226
 
208
- // Eight accepted tracking forms (URL, #123, GH-123, M123, .goat-flow/tasks, ADR-001, ISO date,
209
- // `owner:`). The stable set is intentionally generous so projects with different ticketing systems
210
- // can comply without changing their conventions.
211
- function hasTodoTracking(text: string): boolean {
212
- return TODO_TRACKING_PATTERNS.some((pattern) => pattern.test(text));
213
- }
214
-
215
- /*
216
- * Targets `eslint-disable`, `biome-ignore`, coverage `istanbul ignore`, etc. when no maintainer
217
- * rationale is attached - the false-positive escape hatch is explicit because TS suppression
218
- * 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.
219
248
  */
220
- function pushSuppressionWithoutRationaleFinding(file: SourceFile, comment: CommentRecord, findings: Finding[]): void {
249
+ function pushSuppressionWithoutRationaleFinding(file: SourceFile, comment: CommentRecord, hasAttachedRationale: boolean, findings: Finding[], trackingTokens: readonly RegExp[]): void {
221
250
  const suppression = suppressionDirective(comment.text);
222
- if (!suppression || hasSuppressionRationale(comment.text)) {
251
+ if (!suppression || hasAttachedRationale || hasSuppressionRationale(comment.text, trackingTokens)) {
223
252
  return;
224
253
  }
225
254
  findings.push(
@@ -237,320 +266,85 @@ function pushSuppressionWithoutRationaleFinding(file: SourceFile, comment: Comme
237
266
  );
238
267
  }
239
268
 
240
- // Returns the suppression keyword that triggered the rule. `@ts-*` directives are explicitly
241
- // excluded - they have their own dedicated rule (`pushTsDirectiveFinding`).
242
- function suppressionDirective(text: string): string | undefined {
243
- if (/@ts-(?:ignore|expect-error|nocheck|check)\b/.test(text)) {
244
- return undefined;
245
- }
246
- const match = text.match(/\b(eslint-disable(?:-next-line|-line)?|biome-ignore|oxlint-disable|istanbul ignore|c8 ignore|v8 ignore|prettier-ignore)\b/i);
247
- return match?.[1];
248
- }
249
-
250
- // Accepted rationale forms: explanatory keywords (because, intentional, false positive, tracked in),
251
- // project task markers (M123, ADR-XXX, GH-123), explicit `reason:`, a tracking URL, or a #issue.
252
- export function hasSuppressionRationale(text: string): boolean {
253
- 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);
254
- }
255
-
256
- /*
257
- * Scans the comment text for path-shaped references and reports any that resolve to nothing on
258
- * disk. Historical-context comments (migration notes, legacy markers) are exempted on purpose
259
- * because they intentionally name removed files. Reports the stable `docs.stale-comment` finding.
260
- */
261
- function pushStaleFileReferenceFindings(file: SourceFile, comment: CommentRecord, findings: Finding[]): void {
262
- if (isHistoricalContextComment(comment.text)) {
263
- return;
264
- }
265
- 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)) {
266
- const referencedPath = match[1] ?? "";
267
- if (referencedPathExists(file, referencedPath)) {
268
- continue;
269
- }
270
- findings.push(staleCommentFinding(file, comment, `Comment references missing path \`${referencedPath}\`.`, { staleReference: referencedPath, referenceType: "path" }));
271
- }
272
- }
273
-
274
- // Tries both the project-root and same-directory interpretations because comments are inconsistent
275
- // about which they imply. Either match is enough to consider the reference live.
276
- function referencedPathExists(file: SourceFile, referencedPath: string): boolean {
277
- const fromProject = resolve(cwd(), referencedPath);
278
- const fromFile = resolve(dirnamePath(file.absolutePath), referencedPath);
279
- return existsSync(fromProject) || existsSync(fromFile);
280
- }
281
-
282
- /*
283
- * Walks every `pillar.rule-id` shape in the comment and reports those not in the descriptor set.
284
- * Historical-context comments stay exempt so removed rules can remain referenced in lessons text.
285
- * Reports the stable `docs.stale-comment` finding for each stale rule id.
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.
286
277
  */
287
- function pushStaleRuleReferenceFindings(file: SourceFile, comment: CommentRecord, ruleIdSet: Set<string>, findings: Finding[]): void {
288
- if (isHistoricalContextComment(comment.text)) {
289
- return;
290
- }
291
- 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)) {
292
- const ruleId = match[1] ?? "";
293
- if (ruleIdSet.has(ruleId)) {
294
- 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);
295
288
  }
296
- findings.push(staleCommentFinding(file, comment, `Comment references unknown rule id \`${ruleId}\`.`, { staleReference: ruleId, referenceType: "ruleId" }));
297
- }
298
- }
299
-
300
- /*
301
- * Each double-dash option in a comment must appear in `cliFlags` (parsed from the CLI source) or
302
- * it counts as a stale reference. The rule's value is catching gruff-ts maintainers who rename a
303
- * flag and forget to update its references - so the check only fires when the comment also names
304
- * gruff-ts (or invokes the gruff/gruff-ts binary). In any other project, flag references belong to
305
- * that project's CLI, not gruff-ts, and validating them against gruff-ts's own option surface
306
- * produces only noise. Reports the stable `docs.stale-comment` finding for each unknown option.
307
- */
308
- function pushStaleCliFlagReferenceFindings(file: SourceFile, comment: CommentRecord, optionFlagSet: Set<string>, findings: Finding[]): void {
309
- if (isHistoricalContextComment(comment.text)) {
310
- return;
311
- }
312
- if (!mentionsGruffCli(comment.text)) {
313
- return;
314
- }
315
- for (const match of comment.text.matchAll(/(?<![A-Za-z0-9])--[a-z][a-z0-9-]*/g)) {
316
- const flag = match[0] ?? "";
317
- if (optionFlagSet.has(flag)) {
318
- 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;
319
295
  }
320
- findings.push(staleCommentFinding(file, comment, `Comment references unknown CLI flag \`${flag}\`.`, { staleReference: flag, referenceType: "cliFlag" }));
321
- }
322
- }
323
-
324
- // True when the comment names the gruff-ts CLI by binary or product name. Acts as the activation
325
- // gate for the unknown-CLI-flag check; comments that talk about other tools' flags never trip it.
326
- function mentionsGruffCli(text: string): boolean {
327
- return /\bgruff(?:-ts)?\b/i.test(text);
328
- }
329
-
330
- // Static list of valid CLI options. Hand-curated rather than parsed from the Commander definition
331
- // at runtime because the stale-CLI-flag rule must not depend on import order - both files would
332
- // otherwise have to load the analyser to power their checks.
333
- function knownCliFlags(): Set<string> {
334
- return new Set([
335
- "--ansi",
336
- "--baseline",
337
- "--config",
338
- "--diff",
339
- "--changed-ranges",
340
- "--changed-scope",
341
- "--fail-on",
342
- "--fail-on-diagnostics",
343
- "--force",
344
- "--format",
345
- "--generate-baseline",
346
- "--help",
347
- "--history-file",
348
- "--host",
349
- "--include-ignored",
350
- "--no-ansi",
351
- "--no-baseline",
352
- "--no-config",
353
- "--no-interaction",
354
- "--output",
355
- "--port",
356
- "--profile",
357
- "--project-root",
358
- "--quiet",
359
- "--silent",
360
- "--since",
361
- "--top",
362
- "--verbose",
363
- "--version",
364
- ]);
365
- }
366
-
367
- // A comment whose prose names a different symbol than the declaration directly below it. The
368
- // historical-context escape hatch keeps migration notes (which intentionally name removed symbols)
369
- // quiet. Reports `docs.stale-comment` with stable metadata.
370
- function pushStaleDeclarationCommentFinding(file: SourceFile, comment: CommentRecord, declaration: CommentedDeclaration, findings: Finding[]): void {
371
- if (isHistoricalContextComment(comment.text)) {
372
- return;
373
- }
374
- const referencedName = referencedDeclarationName(comment.text, declaration.kind);
375
- if (!referencedName || referencedName === declaration.name) {
376
- return;
377
- }
378
- findings.push(staleCommentFinding(file, comment, `Comment names \`${referencedName}\` but documents \`${declaration.name}\`.`, { staleReference: referencedName, referenceType: declaration.kind, symbol: declaration.name }));
379
- }
380
-
381
- // Two-pass match: either `<kind> name` (e.g., "function fooBar") or leading `name <kind|helper|
382
- // method|contract|type>`. Both forms appear in real comments and either is sufficient evidence
383
- // that the comment intends to name a specific symbol.
384
- function referencedDeclarationName(text: string, kind: CommentedDeclaration["kind"]): string | undefined {
385
- const directBackticked = text.match(new RegExp(["\\b", kind, "\\s+`([A-Za-z_$][A-Za-z0-9_$]*)`"].join(""), "i"));
386
- if (directBackticked?.[1]) {
387
- return directBackticked[1];
388
- }
389
- const directCodeLike = text.match(new RegExp(["\\b", kind, "\\s+([A-Za-z_$][A-Za-z0-9_$]*)"].join(""), "i"));
390
- if (directCodeLike?.[1] && isCodeLikeIdentifier(directCodeLike[1])) {
391
- return directCodeLike[1];
392
- }
393
- return leadingReferencedDeclarationName(text, kind);
394
- }
395
-
396
- // The leading form is intentionally stricter than `<kind> name`: ordinary English such as
397
- // "Read-only filesystem interface" or "Symlink helper" must not become a stale-symbol finding.
398
- function leadingReferencedDeclarationName(text: string, kind: CommentedDeclaration["kind"]): string | undefined {
399
- const backticked = text.match(new RegExp(["^`([A-Za-z_$][A-Za-z0-9_$]*)`\\s+(?:", kind, "|helper|method|contract|type)\\b"].join(""), "i"));
400
- if (backticked?.[1]) {
401
- return backticked[1];
402
- }
403
- const codeLike = text.match(new RegExp(["^([A-Za-z_$][A-Za-z0-9_$]*)\\s+(?:", kind, "|helper|method|contract|type)\\b"].join(""), "i"));
404
- if (codeLike?.[1] && isCodeLikeIdentifier(codeLike[1])) {
405
- return codeLike[1];
406
296
  }
407
- return undefined;
408
- }
409
-
410
- // Requires a real identifier marker beyond normal prose capitalization.
411
- function isCodeLikeIdentifier(name: string): boolean {
412
- return /[A-Z].*[A-Z]|[a-z][A-Z]|[_$]|\d/.test(name);
297
+ return attached;
413
298
  }
414
299
 
415
- /*
416
- * Public block-doc comments are exempted on purpose because their first words usually mirror the
417
- * API surface - that's the documented JSDoc convention, not a useless docblock. Reports the stable
418
- * `docs.useless-docblock` finding otherwise.
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.
419
307
  */
420
- function pushRestatingSignatureCommentFinding(file: SourceFile, comment: CommentRecord, declaration: CommentedDeclaration, findings: Finding[]): void {
421
- if (declaration.kind === "function" && declaration.isPublic && comment.kind === "block") {
422
- return;
423
- }
424
- if (!isRestatingSignatureComment(comment.text, declaration.name, declaration.kind)) {
425
- return;
426
- }
427
- findings.push(
428
- makeFinding({
429
- ruleId: "docs.useless-docblock",
430
- message: `Comment for \`${declaration.name}\` only restates the signature.`,
431
- filePath: file.displayPath,
432
- line: comment.line,
433
- severity: "advisory",
434
- pillar: "documentation",
435
- confidence: "medium",
436
- symbol: declaration.name,
437
- remediation: "Update the JSDoc so it documents the current signature and return value.",
438
- metadata: {},
439
- }),
440
- );
308
+ function startsItsLine(source: string, commentStart: number): boolean {
309
+ const lineStart = source.lastIndexOf("\n", commentStart - 1) + 1;
310
+ return source.slice(lineStart, commentStart).trim() === "";
441
311
  }
442
312
 
443
- /*
444
- * Test files are exempt because their `expect(x).toBe(42)` patterns legitimately contain
445
- * unexplained numbers. For every production source line, the rule looks for either a named
446
- * threshold/limit/cap or a `threshold(config, …)` default call, then checks that a nearby comment
447
- * explains it. Reports the stable `docs.magic-threshold-without-rationale` finding.
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.
448
319
  */
449
- function pushMagicThresholdFindings(file: SourceFile, lines: string[], codeSource: string, comments: CommentRecord[], findings: Finding[]): void {
450
- if (isTestPath(file.displayPath) || !hasMagicThresholdSignal(codeSource)) {
451
- return;
452
- }
453
- const codeLines = codeSource.split(/\r?\n/);
454
- codeLines.forEach((codeLine, index) => {
455
- const candidate = magicThresholdCandidate(lines[index] ?? "", codeLine);
456
- if (!candidate || hasNearbyThresholdRationale(lines, comments, index + 1)) {
457
- return;
458
- }
459
- findings.push(
460
- makeFinding({
461
- ruleId: "docs.magic-threshold-without-rationale",
462
- message: `Threshold-like value \`${candidate.label}\` lacks a nearby rationale comment.`,
463
- filePath: file.displayPath,
464
- line: index + 1,
465
- severity: "advisory",
466
- pillar: "documentation",
467
- confidence: "medium",
468
- symbol: candidate.label,
469
- remediation: "Add a nearby comment explaining the threshold, limit, budget, or default.",
470
- metadata: { value: candidate.value, thresholdKind: candidate.kind },
471
- }),
472
- );
473
- });
474
- }
475
-
476
- // Cheap whole-file preflight for the two shapes `magicThresholdCandidate` can report.
477
- function hasMagicThresholdSignal(codeSource: string): boolean {
478
- 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);
479
- }
480
-
481
- // Two candidate sources: a named constant (`const maxThings = N`) or a `threshold()` default call.
482
- // Either is treated as policy-shaped numeric - ordinary arithmetic constants stay quiet.
483
- function magicThresholdCandidate(rawLine: string, codeLine: string): MagicThresholdCandidate | undefined {
484
- return namedThresholdCandidate(rawLine, codeLine) ?? configDefaultThresholdCandidate(rawLine, codeLine);
485
- }
486
-
487
- // Identifiers ending in Threshold/Limit/Cap/Budget/Timeout/Tolerance/Weight/Score/Max/Min/Default/
488
- // Entropy/Length signal "policy number". `-1`, `0`, `1`, `2` are exempt because they're usually sentinels.
489
- // Gates on the masked `codeLine` so template-literal fixture content (where the same line appears as
490
- // source text but inside a backtick) does not trip the rule.
491
- function namedThresholdCandidate(rawLine: string, codeLine: string): MagicThresholdCandidate | undefined {
492
- 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)) {
493
- return undefined;
494
- }
495
- 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);
496
- const label = named?.[1];
497
- const thresholdValue = named?.[2];
498
- if (!label) {
499
- return undefined;
500
- }
501
- if (!thresholdValue || isCommonSafeNumber(thresholdValue)) {
502
- return undefined;
503
- }
504
- return { label, value: thresholdValue, kind: "named-threshold" };
505
- }
506
-
507
- // Cheap gate first: only look for the four-arg `threshold(config, "rule", "key", N)` form when the
508
- // masked code actually contains `threshold(`. Required because labels come from raw text but the
509
- // call shape must originate in executable code - masked code is the only stable signal for that.
510
- function configDefaultThresholdCandidate(rawLine: string, codeLine: string): MagicThresholdCandidate | undefined {
511
- if (!/\bthreshold\s*\(/.test(codeLine)) {
512
- return undefined;
513
- }
514
- const thresholdDefault = rawLine.match(/\bthreshold\s*\([^)]*,\s*["']([^"']+)["']\s*,\s*["']([^"']+)["']\s*,\s*(-?\d+(?:\.\d+)?)\s*\)/);
515
- const ruleId = thresholdDefault?.[1];
516
- const key = thresholdDefault?.[2];
517
- const thresholdValue = thresholdDefault?.[3];
518
- if (!ruleId || !key) {
519
- return undefined;
520
- }
521
- if (!thresholdValue || isCommonSafeNumber(thresholdValue)) {
320
+ function suppressionDirective(text: string): string | undefined {
321
+ if (/@ts-(?:ignore|expect-error|nocheck|check)\b/.test(text)) {
522
322
  return undefined;
523
323
  }
524
- return { label: `${ruleId}.${key}`, value: thresholdValue, kind: "config-default" };
525
- }
526
-
527
- // Four sentinel values that recur as "counter starts", "boolean toggle as int", and "default
528
- // count" without being policy decisions. Anything outside this set is treated as a threshold.
529
- function isCommonSafeNumber(numericLiteral: string): boolean {
530
- return ["-1", "0", "1", "2"].includes(numericLiteral);
531
- }
532
-
533
- // Two acceptable positions for the explanatory comment: same line as the constant, or directly
534
- // above with a blank-line gap. Mirrors `hasFixturePurposeComment` adjacency rules, including
535
- // reading a stacked `//` header as one comment so rationale on an earlier line counts.
536
- function hasNearbyThresholdRationale(lines: string[], comments: CommentRecord[], line: number): boolean {
537
- const sameLine = comments.find((comment) => comment.line <= line && comment.endLine >= line);
538
- if (sameLine && hasThresholdRationaleMarker(sameLine.text)) {
539
- return true;
540
- }
541
- const leading = leadingCommentForLine(lines, comments, line);
542
- return Boolean(leading && hasThresholdRationaleMarker(combinedContextLineComment(comments, leading).text));
543
- }
544
-
545
- // Vocabulary used by the magic-threshold rule. A numeric constant followed by a comment containing
546
- // any of these words is treated as "explained".
547
- function hasThresholdRationaleMarker(text: string): boolean {
548
- 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];
549
326
  }
550
327
 
551
- // Three-tier test: useful-context vocabulary short-circuits as "not restating"; identical
552
- // word sequences are restating; near-identical sequences (one extra trailing word) are restating.
553
- // 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
+ */
554
348
  function isRestatingSignatureComment(text: string, name: string, kind: CommentedDeclaration["kind"]): boolean {
555
349
  if (hasUsefulCommentContext(text)) {
556
350
  return false;
@@ -566,8 +360,13 @@ function isRestatingSignatureComment(text: string, name: string, kind: Commented
566
360
  return words.length <= nameWords.length + 1 && sameWords(words.slice(0, nameWords.length), nameWords);
567
361
  }
568
362
 
569
- // Strips backticks, splits on non-identifier characters, then further splits each fragment into
570
- // 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
+ */
571
370
  function normalizedCommentWords(text: string): string[] {
572
371
  return text
573
372
  .replace(/`/g, " ")
@@ -578,58 +377,57 @@ function normalizedCommentWords(text: string): string[] {
578
377
  .filter(Boolean);
579
378
  }
580
379
 
581
- // Stop-word list that filters out grammatical scaffolding before name comparison. Includes the
582
- // 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
+ */
583
387
  function restatementStopWords(kind: CommentedDeclaration["kind"]): Set<string> {
584
388
  return new Set(["a", "an", "the", "this", "that", "function", "method", "helper", "type", "declaration", kind]);
585
389
  }
586
390
 
587
- // Trailing-`s` stripping for words longer than 3 characters. Crude but adequate for restating-
588
- // 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
+ */
589
398
  function stemCommentWord(word: string): string {
590
399
  return word.length > 3 && word.endsWith("s") ? word.slice(0, -1) : word;
591
400
  }
592
401
 
593
- // Pointwise equality between two stemmed word arrays. Used by `isRestatingSignatureComment` to
594
- // 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
+ */
595
409
  function sameWords(left: string[], right: string[]): boolean {
596
410
  return left.length === right.length && left.every((word, index) => word === right[index]);
597
411
  }
598
412
 
599
- // The shared "this comment carries real signal" vocabulary. Any match here exempts the comment
600
- // 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
+ */
601
419
  function hasUsefulCommentContext(text: string): boolean {
602
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);
603
421
  }
604
422
 
605
- // Five vocabulary markers signal "this comment is intentionally about removed/old code". The
606
- // stale-reference rules all consult this so legacy notes can keep naming removed paths/symbols.
607
- function isHistoricalContextComment(text: string): boolean {
608
- return /\b(?:previously|legacy|compat|migration|ADR)\b/i.test(text);
609
- }
610
-
611
- // Single makeFinding factory for every stale-comment variant. `symbol` is omitted (not set to
612
- // undefined) via conditional spread because exactOptionalPropertyTypes treats the two as different
613
- // shapes - the omission keeps stable fingerprints round-tripping across baseline reads and writes.
614
- function staleCommentFinding(file: SourceFile, comment: CommentRecord, message: string, metadata: Record<string, string>): Finding {
615
- const symbol = metadata["symbol"];
616
- return makeFinding({
617
- ruleId: "docs.stale-comment",
618
- message,
619
- filePath: file.displayPath,
620
- line: comment.line,
621
- severity: "advisory",
622
- pillar: "documentation",
623
- confidence: "medium",
624
- ...(symbol ? { symbol } : {}),
625
- remediation: "Update the comment reference or add historical context that explains why it remains useful.",
626
- metadata,
627
- });
628
- }
629
-
630
- // Reverse scan through the comment list - the closest comment whose `endLine < line` wins, but
631
- // only when nothing but blank lines sits between them. Anything else means the comment documents
632
- // 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
+ */
633
431
  function leadingCommentForLine(lines: string[], comments: CommentRecord[], line: number): CommentRecord | undefined {
634
432
  for (let index = comments.length - 1; index >= 0; index -= 1) {
635
433
  const comment = comments[index];
@@ -644,8 +442,28 @@ function leadingCommentForLine(lines: string[], comments: CommentRecord[], line:
644
442
  return undefined;
645
443
  }
646
444
 
647
- // Tighter sibling of `hasOnlyBlankFixturePurposeGap` - exclusive upper bound. Used by
648
- // `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
+ */
649
467
  function hasOnlyBlankLines(lines: string[], startLine: number, endLine: number): boolean {
650
468
  for (let line = startLine; line < endLine; line += 1) {
651
469
  if ((lines[line - 1] ?? "").trim() !== "") {