@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,5 +1,7 @@
1
- // Static-analysis-redundant assertion scanner for test blocks. It reports tests that only prove
2
- // TypeScript-visible code shape, keeping the main per-test-block pass focused on orchestration.
1
+ // Detects tests whose assertions only re-verify facts TypeScript's type checker already proves at compile time.
2
+ //
3
+ // Keeps the main per-test-block pass in `test-block-rules.ts` focused on structural orchestration.
4
+ // Distinguishes runtime payload checks from redundant shape or importability sentinels before emitting advisories.
3
5
  import { type FunctionBlock } from "./blocks.ts";
4
6
  import { type SourceFile } from "./discovery.ts";
5
7
  import { makeFinding } from "./findings.ts";
@@ -67,9 +69,17 @@ const NON_NULLABLE_DECLARATION_PATTERNS = [
67
69
  /\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\([^)]*\)\s*:\s*([A-Za-z_$][A-Za-z0-9_$<>,\s.[\]]*)\s*=>/g,
68
70
  ] as const;
69
71
 
70
- /*
71
- * Reports stable `test-quality.static-analysis-redundant-test` findings. The contract keeps source
72
- * proof and recommendation in metadata because reviewers need the assertion and proof side by side.
72
+ /**
73
+ * Report stable test-quality.static-analysis-redundant-test findings with the assertion, proof, and recommendation together for review.
74
+ * The finding location stands in when the candidate has no proof location.
75
+ *
76
+ * @param file - source file used to locate findings and their evidence
77
+ * @param block - test block that supplies the name and starting line
78
+ * @param rawBody - original test text used to match assertions and compute line offsets
79
+ * @param codeBody - test text used to confirm matches occur in executable code
80
+ * @param staticContext - surrounding source used to establish static facts
81
+ * @param findings - caller's list that receives each qualifying advisory
82
+ * @returns Nothing. Appends findings and their review evidence to the supplied list.
73
83
  */
74
84
  export function pushStaticAnalysisRedundantTestFindings(file: SourceFile, block: FunctionBlock, rawBody: string, codeBody: string, staticContext: StaticAnalysisSourceContext, findings: Finding[]): void {
75
85
  for (const candidate of staticAnalysisRedundantAssertions(file, block, rawBody, codeBody, staticContext)) {
@@ -101,7 +111,16 @@ export function pushStaticAnalysisRedundantTestFindings(file: SourceFile, block:
101
111
  }
102
112
  }
103
113
 
104
- // Runs the three static-shape detectors and preserves deterministic source-order emission.
114
+ /**
115
+ * Collect redundant assertion candidates with recommendations for a test block in deterministic source order.
116
+ *
117
+ * @param file - source file used to anchor proof locations
118
+ * @param block - test block checked for importability-sentinel naming and declaration line offsets
119
+ * @param rawSource - raw test body text matched for assertions and local declarations
120
+ * @param codeSource - masked test body text used to confirm matches lie in executable code
121
+ * @param staticContext - surrounding file source used to gather function declaration and import facts
122
+ * @returns Redundant assertion candidates sorted by source index.
123
+ */
105
124
  function staticAnalysisRedundantAssertions(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string, staticContext: StaticAnalysisSourceContext): StaticAnalysisRedundantAssertion[] {
106
125
  return [
107
126
  ...typeofFunctionAssertions(file, rawSource, codeSource, staticContext),
@@ -112,20 +131,46 @@ function staticAnalysisRedundantAssertions(file: SourceFile, block: FunctionBloc
112
131
  .sort((left, right) => left.index - right.index);
113
132
  }
114
133
 
115
- // Detects `typeof x === "function"`-style assertions when TypeScript already proves the function.
134
+ /**
135
+ * Detect `typeof x === "function"`-style assertions when TypeScript already proves the function binding.
136
+ *
137
+ * @param file - source file used to anchor static proof locations
138
+ * @param rawSource - raw test body text scanned against typeof-function assertion patterns
139
+ * @param codeSource - masked test body text used to confirm matches lie in executable code
140
+ * @param staticContext - surrounding file source scanned for function declarations and static imports
141
+ * @returns Matching typeof-function redundant assertion candidates across all supported patterns.
142
+ */
116
143
  function typeofFunctionAssertions(file: SourceFile, rawSource: string, codeSource: string, staticContext: StaticAnalysisSourceContext): StaticAnalysisRedundantAssertion[] {
117
144
  const functionFacts = staticFunctionFacts(file, staticContext);
118
145
  return TYPEOF_FUNCTION_ASSERTION_PATTERNS.flatMap((pattern) => typeofFunctionAssertionsForPattern(file, rawSource, codeSource, functionFacts, pattern));
119
146
  }
120
147
 
121
- // Evaluates one typeof-function assertion grammar while keeping executable-source checks local.
148
+ /**
149
+ * Apply one typeof-function assertion pattern to raw test source and keep candidates backed by static facts.
150
+ *
151
+ * @param file - source file forwarded to the shared candidate builder
152
+ * @param rawSource - raw test body text matched with the assertion pattern
153
+ * @param codeSource - masked test body text used to screen out non-executable matches
154
+ * @param functionFacts - collected identifier and namespace-import facts used as static evidence
155
+ * @param pattern - global regular expression matching one typeof-function assertion form
156
+ * @returns Qualifying typeof-function candidates for this pattern, or an empty array when none qualify.
157
+ */
122
158
  function typeofFunctionAssertionsForPattern(file: SourceFile, rawSource: string, codeSource: string, functionFacts: StaticFunctionFacts, pattern: RegExp): StaticAnalysisRedundantAssertion[] {
123
159
  return [...rawSource.matchAll(pattern)]
124
160
  .map((match) => typeofFunctionCandidateFromMatch(file, rawSource, codeSource, functionFacts, match))
125
161
  .filter(isStaticAnalysisRedundantAssertion);
126
162
  }
127
163
 
128
- // Builds one typeof-function candidate only when the expression has static declaration evidence.
164
+ /**
165
+ * Convert one typeof-function regex match into a redundant-assertion candidate when static evidence exists.
166
+ *
167
+ * @param file - source file forwarded to the shared candidate builder (not retained)
168
+ * @param rawSource - raw test body text forwarded to the shared candidate builder (not retained)
169
+ * @param codeSource - masked test body text used to verify the match is executable code
170
+ * @param functionFacts - collected identifier and namespace-import facts used to look up the tested expression
171
+ * @param match - regex match carrying the assertion slice, start index, and captured target expression
172
+ * @returns Candidate with static fact and proof, or undefined when non-executable or lacking a static fact.
173
+ */
129
174
  function typeofFunctionCandidateFromMatch(file: SourceFile, rawSource: string, codeSource: string, functionFacts: StaticFunctionFacts, match: RegExpMatchArray): StaticAnalysisRedundantAssertion | undefined {
130
175
  const index = match.index ?? 0;
131
176
  if (!isExecutableAssertionAt(codeSource, index)) {
@@ -146,7 +191,13 @@ function typeofFunctionCandidateFromMatch(file: SourceFile, rawSource: string, c
146
191
  });
147
192
  }
148
193
 
149
- // Gathers declaration and import facts from the full source context once per test-block scan.
194
+ /**
195
+ * Collect identifier and namespace-import function facts from the surrounding source context.
196
+ *
197
+ * @param file - source file whose display path anchors generated proof locations
198
+ * @param context - full-file raw and masked source context with starting line offset
199
+ * @returns Collected identifier and namespace-import function fact maps.
200
+ */
150
201
  function staticFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext): StaticFunctionFacts {
151
202
  const facts: StaticFunctionFacts = { identifiers: new Map(), namespaceImports: new Map() };
152
203
  pushFunctionDeclarationFacts(file, context, facts.identifiers);
@@ -155,7 +206,14 @@ function staticFunctionFacts(file: SourceFile, context: StaticAnalysisSourceCont
155
206
  return facts;
156
207
  }
157
208
 
158
- // Adds facts for `function name()` declarations because comments and strings can mimic syntax.
209
+ /**
210
+ * Record facts for executable function declarations, checking masked source because comments and strings can mimic declarations.
211
+ *
212
+ * @param file - source file whose display path anchors proof locations
213
+ * @param context - source context supplying raw source, masked code source, and start line
214
+ * @param facts - identifier fact map populated in place, replacing any existing entry with the same name
215
+ * @returns Nothing. Adds executable function declaration facts to `facts` in place.
216
+ */
159
217
  function pushFunctionDeclarationFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
160
218
  for (const match of context.source.matchAll(/\bfunction\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/g)) {
161
219
  const index = match.index ?? 0;
@@ -172,7 +230,14 @@ function pushFunctionDeclarationFacts(file: SourceFile, context: StaticAnalysisS
172
230
  }
173
231
  }
174
232
 
175
- // Adds facts for const-bound functions because these declarations are common test helper shapes.
233
+ /**
234
+ * Record facts for executable const-bound functions because these declarations are common test helper shapes.
235
+ *
236
+ * @param file - source file whose display path anchors proof locations
237
+ * @param context - source context supplying raw source, masked code source, and start line
238
+ * @param facts - identifier fact map populated in place, replacing any existing entry with the same name
239
+ * @returns Nothing. Reads executable declarations from `context` and adds entries to `facts` in place.
240
+ */
176
241
  function pushConstFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
177
242
  const pattern = /\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?(?:function\b|(?:\([^)]*\)|[A-Za-z_$][A-Za-z0-9_$]*)\s*(?::\s*[^=;]+?)?=>)/g;
178
243
  for (const match of context.source.matchAll(pattern)) {
@@ -190,13 +255,27 @@ function pushConstFunctionFacts(file: SourceFile, context: StaticAnalysisSourceC
190
255
  }
191
256
  }
192
257
 
193
- // Dispatches named and namespace import evidence into separate maps for later expression lookup.
258
+ /**
259
+ * Dispatch named and namespace import evidence into separate fact maps for later expression lookup.
260
+ *
261
+ * @param file - source file whose display path anchors proof locations
262
+ * @param context - source context supplying raw source, masked code source, and start line
263
+ * @param facts - fact bundle whose `identifiers` and `namespaceImports` maps are populated in place
264
+ * @returns Nothing. Reads `context` and mutates `facts.identifiers` and `facts.namespaceImports` in place.
265
+ */
194
266
  function pushImportFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: StaticFunctionFacts): void {
195
267
  pushNamedImportFunctionFacts(file, context, facts.identifiers);
196
268
  pushNamespaceImportFunctionFacts(file, context, facts.namespaceImports);
197
269
  }
198
270
 
199
- // Adds facts for static named imports, including aliases, when the import is executable code.
271
+ /**
272
+ * Record facts for static named imports, including aliases, while skipping type-only imports and specifiers.
273
+ *
274
+ * @param file - source file whose display path anchors proof locations
275
+ * @param context - source context supplying raw source, masked code source, and start line
276
+ * @param facts - identifier fact map populated in place, replacing any existing entry with the same local name
277
+ * @returns Nothing. Adds executable named-import facts to `facts` in place.
278
+ */
200
279
  function pushNamedImportFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
201
280
  for (const match of context.source.matchAll(/\bimport\s+(?!type\b)\{([^}]+)\}\s*from\b/g)) {
202
281
  const index = match.index ?? 0;
@@ -210,7 +289,14 @@ function pushNamedImportFunctionFacts(file: SourceFile, context: StaticAnalysisS
210
289
  }
211
290
  }
212
291
 
213
- // Adds facts for namespace imports because `namespace.member` assertions need import-level proof.
292
+ /**
293
+ * Record facts for namespace imports because namespace member assertions need import-level proof.
294
+ *
295
+ * @param file - source file whose display path anchors proof locations
296
+ * @param context - source context supplying raw source, masked code source, and start line
297
+ * @param facts - namespace-import fact map populated in place, replacing any existing entry with the same name
298
+ * @returns Nothing. Adds executable namespace-import facts to `facts` in place.
299
+ */
214
300
  function pushNamespaceImportFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
215
301
  for (const match of context.source.matchAll(/\bimport\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\b/g)) {
216
302
  const index = match.index ?? 0;
@@ -227,7 +313,13 @@ function pushNamespaceImportFunctionFacts(file: SourceFile, context: StaticAnaly
227
313
  }
228
314
  }
229
315
 
230
- // Builds the reviewer-facing fact text for one named import.
316
+ /**
317
+ * Build the reviewer-facing static fact record for one named import binding.
318
+ *
319
+ * @param importedName - local binding name embedded in the generated static fact text
320
+ * @param proof - formatted `path:line` proof location preserved as `sourceProof`
321
+ * @returns Static function fact containing the named-import explanation and source proof.
322
+ */
231
323
  function namedImportFunctionFact(importedName: string, proof: string): StaticFunctionFact {
232
324
  return {
233
325
  staticFact: `\`${importedName}\` is a static ES module named import, so TypeScript can validate the imported binding's declared function type without executing this test assertion.`,
@@ -235,7 +327,12 @@ function namedImportFunctionFact(importedName: string, proof: string): StaticFun
235
327
  };
236
328
  }
237
329
 
238
- // Normalises `import { original as local }` clauses to the local binding names used in tests.
330
+ /**
331
+ * Extract local value binding names from a braced named-import clause, omitting empty, type-only, and unsupported specifiers.
332
+ *
333
+ * @param importClause - comma-separated specifier text inside an `import { ... }` clause
334
+ * @returns Local value binding names available to assertions, or an empty array if none remain.
335
+ */
239
336
  function namedImportLocals(importClause: string): string[] {
240
337
  return importClause
241
338
  .split(",")
@@ -243,7 +340,12 @@ function namedImportLocals(importClause: string): string[] {
243
340
  .filter((value): value is string => value !== undefined);
244
341
  }
245
342
 
246
- // Returns the local binding name for one named import specifier, ignoring type-only entries.
343
+ /**
344
+ * Extract the local binding name from a single named-import specifier, ignoring empty and type-only entries.
345
+ *
346
+ * @param specifier - single comma-separated import specifier segment to inspect
347
+ * @returns Local identifier or alias name, or undefined for empty, `type`-prefixed, or unsupported forms.
348
+ */
247
349
  function namedImportLocal(specifier: string): string | undefined {
248
350
  const trimmed = specifier.trim();
249
351
  if (trimmed === "" || /^type\b/.test(trimmed)) {
@@ -257,7 +359,14 @@ function namedImportLocal(specifier: string): string | undefined {
257
359
  return direct?.[1];
258
360
  }
259
361
 
260
- // Looks up direct identifiers and namespace-member expressions against static import facts.
362
+ /**
363
+ * Look up declaration or import evidence for a tested expression using identifier and namespace-import facts.
364
+ * For namespace members, evidence comes from the namespace import and the member name is checked only for identifier syntax.
365
+ *
366
+ * @param expression - target identifier or `namespace.member` expression from a `typeof` assertion
367
+ * @param facts - collected identifier and namespace-import facts for the file
368
+ * @returns Matching static fact, or undefined unless an identifier or valid namespace member matches.
369
+ */
261
370
  function staticFunctionFactForExpression(expression: string, facts: StaticFunctionFacts): StaticFunctionFact | undefined {
262
371
  const direct = facts.identifiers.get(expression);
263
372
  if (direct) {
@@ -279,24 +388,54 @@ function staticFunctionFactForExpression(expression: string, facts: StaticFuncti
279
388
  };
280
389
  }
281
390
 
282
- // Converts a byte offset in the source context into the display path and 1-based proof line.
391
+ /**
392
+ * Format a `displayPath:line` proof string for a UTF-16 code-unit offset within the source context.
393
+ *
394
+ * @param file - source file providing the display path
395
+ * @param context - source context supplying `source` and its 1-based `startLine`
396
+ * @param index - UTF-16 code-unit index within `context.source`
397
+ * @returns Formatted `path:line` proof location anchored at `context.startLine`.
398
+ */
283
399
  function sourceProof(file: SourceFile, context: StaticAnalysisSourceContext, index: number): string {
284
400
  return `${file.displayPath}:${context.startLine + lineOffset(context.source, index)}`;
285
401
  }
286
402
 
287
- // Detects self-instance assertions where the constructor expression itself proves the relationship.
403
+ /**
404
+ * Detect `new Foo() instanceof Foo`-style assertions where the constructor expression itself proves the instance relationship.
405
+ *
406
+ * @param file - source file forwarded to the shared candidate builder
407
+ * @param rawSource - raw test body text scanned against direct-construction assertion patterns
408
+ * @param codeSource - masked test body text used to confirm matches lie in executable code
409
+ * @returns Qualifying direct-construction redundant assertion candidates across all supported patterns.
410
+ */
288
411
  function directConstructionInstanceAssertions(file: SourceFile, rawSource: string, codeSource: string): StaticAnalysisRedundantAssertion[] {
289
412
  return DIRECT_CONSTRUCTION_ASSERTION_PATTERNS.flatMap((pattern) => directConstructionInstanceAssertionsForPattern(file, rawSource, codeSource, pattern));
290
413
  }
291
414
 
292
- // Evaluates one direct-construction assertion grammar against executable test code.
415
+ /**
416
+ * Evaluate one direct-construction assertion pattern against executable test code.
417
+ *
418
+ * @param file - source file forwarded to the shared candidate builder (not retained)
419
+ * @param rawSource - raw test body text matched with the global assertion pattern
420
+ * @param codeSource - masked test body text used to validate executable match positions
421
+ * @param pattern - global regular expression matching one direct-construction assertion grammar
422
+ * @returns Surviving direct-construction candidates, or an empty array when none qualify.
423
+ */
293
424
  function directConstructionInstanceAssertionsForPattern(file: SourceFile, rawSource: string, codeSource: string, pattern: RegExp): StaticAnalysisRedundantAssertion[] {
294
425
  return [...rawSource.matchAll(pattern)]
295
426
  .map((match) => directConstructionInstanceCandidate(file, rawSource, codeSource, match))
296
427
  .filter(isStaticAnalysisRedundantAssertion);
297
428
  }
298
429
 
299
- // Builds one direct-construction candidate with a source-order index for stable sorting.
430
+ /**
431
+ * Build one direct-construction candidate with a source-order index for stable sorting.
432
+ *
433
+ * @param file - source file forwarded to the shared candidate builder (not retained)
434
+ * @param rawSource - raw test body text forwarded to the shared candidate builder (not retained)
435
+ * @param codeSource - masked test body text used to confirm the match is in executable code
436
+ * @param match - regex match supplying the assertion text, index, and constructed class name
437
+ * @returns Candidate for an executable match, or undefined when the match is masked.
438
+ */
300
439
  function directConstructionInstanceCandidate(file: SourceFile, rawSource: string, codeSource: string, match: RegExpMatchArray): StaticAnalysisRedundantAssertion | undefined {
301
440
  const index = match.index ?? 0;
302
441
  if (!isExecutableAssertionAt(codeSource, index)) {
@@ -312,20 +451,48 @@ function directConstructionInstanceCandidate(file: SourceFile, rawSource: string
312
451
  });
313
452
  }
314
453
 
315
- // Detects assertions that only check non-nullability already guaranteed by a return type.
454
+ /**
455
+ * Detect assertions that repeat non-nullability already declared on a local function return annotation.
456
+ *
457
+ * @param file - source file whose display path anchors declaration proof locations
458
+ * @param block - test block providing the starting line for declaration offsets
459
+ * @param rawSource - raw test body text read for local declarations and non-nullability assertions
460
+ * @param codeSource - masked test body text used to reject masked declaration and assertion positions
461
+ * @returns Matching non-nullable-return candidates, or an empty array when none qualify.
462
+ */
316
463
  function nonNullableReturnAssertions(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string): StaticAnalysisRedundantAssertion[] {
317
464
  const declarations = nonNullableReturnDeclarations(rawSource, codeSource);
318
465
  return NON_NULLABLE_ASSERTION_PATTERNS.flatMap((pattern) => nonNullableReturnAssertionsForPattern(file, block, rawSource, codeSource, declarations, pattern));
319
466
  }
320
467
 
321
- // Evaluates one non-nullable assertion grammar against collected return-type declarations.
468
+ /**
469
+ * Evaluate one non-nullable assertion pattern against collected local return-type declarations.
470
+ *
471
+ * @param file - source file whose display path anchors declaration proof locations
472
+ * @param block - test block providing the starting line for declaration offsets
473
+ * @param rawSource - raw test body text matched against the global assertion pattern
474
+ * @param codeSource - masked test body text used to verify executable assertion positions
475
+ * @param declarations - map of local declarations with non-nullable return annotations
476
+ * @param pattern - global regular expression matching one non-nullable assertion grammar
477
+ * @returns Matching candidates for this pattern, or an empty array when none qualify.
478
+ */
322
479
  function nonNullableReturnAssertionsForPattern(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string, declarations: Map<string, NonNullableReturnDeclaration>, pattern: RegExp): StaticAnalysisRedundantAssertion[] {
323
480
  return [...rawSource.matchAll(pattern)]
324
481
  .map((match) => nonNullableReturnCandidate(file, block, rawSource, codeSource, declarations, match))
325
482
  .filter(isStaticAnalysisRedundantAssertion);
326
483
  }
327
484
 
328
- // Builds one non-nullable-return candidate only when declaration evidence exists.
485
+ /**
486
+ * Build one non-nullable-return candidate only when matching local declaration evidence exists.
487
+ *
488
+ * @param file - source file used to format the declaration proof path
489
+ * @param block - test block whose `startLine` anchors the declaration line offset
490
+ * @param rawSource - raw test body text forwarded to the shared candidate builder (not retained)
491
+ * @param codeSource - masked test body text used to reject masked match positions
492
+ * @param declarations - collected local declarations keyed by callee name
493
+ * @param match - regex match providing the assertion text, index, and called function name
494
+ * @returns Candidate only for an executable match backed by a declaration, otherwise undefined.
495
+ */
329
496
  function nonNullableReturnCandidate(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string, declarations: Map<string, NonNullableReturnDeclaration>, match: RegExpMatchArray): StaticAnalysisRedundantAssertion | undefined {
330
497
  const index = match.index ?? 0;
331
498
  if (!isExecutableAssertionAt(codeSource, index)) {
@@ -345,7 +512,13 @@ function nonNullableReturnCandidate(file: SourceFile, block: FunctionBlock, rawS
345
512
  });
346
513
  }
347
514
 
348
- // Collects function and const-arrow declarations whose return type excludes null and undefined.
515
+ /**
516
+ * Collect local function and const-arrow declarations whose return annotations pass the non-nullability text check.
517
+ *
518
+ * @param source - raw source text scanned for local declaration signatures
519
+ * @param codeSource - masked source text used to filter out non-executable declarations
520
+ * @returns Map of qualifying declarations keyed by function name, empty when none qualify.
521
+ */
349
522
  function nonNullableReturnDeclarations(source: string, codeSource: string): Map<string, NonNullableReturnDeclaration> {
350
523
  const declarations = new Map<string, NonNullableReturnDeclaration>();
351
524
  for (const pattern of NON_NULLABLE_DECLARATION_PATTERNS) {
@@ -354,7 +527,15 @@ function nonNullableReturnDeclarations(source: string, codeSource: string): Map<
354
527
  return declarations;
355
528
  }
356
529
 
357
- // Adds declaration evidence for one grammar while ignoring masked comments and strings.
530
+ /**
531
+ * Collect non-nullable return declaration evidence for one declaration grammar while ignoring masked comments and strings.
532
+ *
533
+ * @param declarations - declaration map mutated in place with accepted entries, replacing duplicates by name
534
+ * @param source - raw source text matched against the declaration pattern
535
+ * @param codeSource - masked source text used to reject masked declaration matches
536
+ * @param pattern - global regular expression matching one annotated declaration grammar
537
+ * @returns Nothing. Mutates `declarations` in place with qualifying return types and line offsets.
538
+ */
358
539
  function pushNonNullableReturnDeclarationsForPattern(declarations: Map<string, NonNullableReturnDeclaration>, source: string, codeSource: string, pattern: RegExp): void {
359
540
  for (const match of source.matchAll(pattern)) {
360
541
  if (!isExecutableFunctionDeclarationAt(codeSource, match.index ?? 0)) {
@@ -364,7 +545,12 @@ function pushNonNullableReturnDeclarationsForPattern(declarations: Map<string, N
364
545
  }
365
546
  }
366
547
 
367
- // Gives each static-shape candidate the shared confidence and remediation contract.
548
+ /**
549
+ * Assemble a redundant-assertion candidate with default high confidence and shared removal advice, omitting context fields.
550
+ *
551
+ * @param args - candidate payload fields plus transient `file` and `source` context fields to strip
552
+ * @returns Candidate object with `confidence` set to `"high"` and the shared `recommendation`.
553
+ */
368
554
  function staticRedundantCandidate(args: Omit<StaticAnalysisRedundantAssertion, "confidence" | "recommendation"> & { file: SourceFile; source: string }): StaticAnalysisRedundantAssertion {
369
555
  const { file: _file, source: _source, ...candidate } = args;
370
556
  return {
@@ -374,7 +560,13 @@ function staticRedundantCandidate(args: Omit<StaticAnalysisRedundantAssertion, "
374
560
  };
375
561
  }
376
562
 
377
- // Downgrades importability sentinel tests to review/document guidance instead of delete guidance.
563
+ /**
564
+ * Downgrade importability sentinel tests to review-or-document guidance instead of mechanical deletion advice.
565
+ *
566
+ * @param block - test block whose name is checked for importability-sentinel cues
567
+ * @param candidate - candidate assertion evaluated for static-import proof without mutating the input
568
+ * @returns Medium-confidence copy with sentinel guidance when applicable, or `candidate` unchanged.
569
+ */
378
570
  function staticAnalysisActionabilityCandidate(block: FunctionBlock, candidate: StaticAnalysisRedundantAssertion): StaticAnalysisRedundantAssertion {
379
571
  if (!isImportabilitySentinelCandidate(block, candidate)) {
380
572
  return candidate;
@@ -389,22 +581,44 @@ function staticAnalysisActionabilityCandidate(block: FunctionBlock, candidate: S
389
581
  };
390
582
  }
391
583
 
392
- // Sentinel candidates need both a module-load style test name and static import evidence.
584
+ /**
585
+ * Check whether a candidate represents an importability sentinel combining module-load test naming and static import evidence.
586
+ *
587
+ * @param block - test block supplying the test name
588
+ * @param candidate - candidate carrying static fact text and optional source proof
589
+ * @returns True when both the test name and candidate proof indicate an importability sentinel.
590
+ */
393
591
  function isImportabilitySentinelCandidate(block: FunctionBlock, candidate: StaticAnalysisRedundantAssertion): boolean {
394
592
  return hasImportabilitySentinelName(block.name) && hasStaticImportProof(candidate);
395
593
  }
396
594
 
397
- // Test names that say export/import/module contract imply the assertion may protect wiring.
595
+ /**
596
+ * Check whether a test name contains importability, module-load, load-graph, export, or contract cues suggesting a wiring check.
597
+ *
598
+ * @param testName - display name of the test block under review
599
+ * @returns True if `testName` matches any importability-sentinel keyword.
600
+ */
398
601
  function hasImportabilitySentinelName(testName: string): boolean {
399
602
  return /\b(?:importability|module[-\s]+load|load[-\s]+graph|exports?|contract)\b/i.test(testName);
400
603
  }
401
604
 
402
- // Static import proof distinguishes module-load sentinels from ordinary type-shape assertions.
605
+ /**
606
+ * Check whether a candidate carries static-import proof distinguishing module-load sentinels from ordinary type-shape assertions.
607
+ *
608
+ * @param candidate - candidate whose `sourceProof` and `staticFact` fields are inspected
609
+ * @returns True when `sourceProof` is defined and `staticFact` mentions both `import` and `static`/`statically`.
610
+ */
403
611
  function hasStaticImportProof(candidate: StaticAnalysisRedundantAssertion): boolean {
404
612
  return candidate.sourceProof !== undefined && /\bimport\b/i.test(candidate.staticFact) && /\bstatic(?:ally)?\b/i.test(candidate.staticFact);
405
613
  }
406
614
 
407
- // Renders the finding message from the final confidence/actionability decision.
615
+ /**
616
+ * Render the reviewer-facing finding message from the final confidence and actionability decision.
617
+ *
618
+ * @param block - test block supplying the test name embedded in the message
619
+ * @param candidate - final candidate supplying confidence, normalized assertion, and optional sentinel category
620
+ * @returns Formatted message with sentinel review wording or standard redundant-candidate wording.
621
+ */
408
622
  function staticAnalysisRedundantMessage(block: FunctionBlock, candidate: StaticAnalysisRedundantAssertion): string {
409
623
  if (candidate.reasonCategory === "importability-sentinel") {
410
624
  return `Review importability sentinel: ${candidate.confidence} confidence. Test \`${block.name}\` asserts static import shape rather than behaviour: ${candidate.assertion}.`;
@@ -412,32 +626,69 @@ function staticAnalysisRedundantMessage(block: FunctionBlock, candidate: StaticA
412
626
  return `Static-analysis-redundant candidate: ${candidate.confidence} confidence. Test \`${block.name}\` asserts code shape rather than behaviour: ${candidate.assertion}.`;
413
627
  }
414
628
 
415
- // Type guard used after optional candidate builders so callers keep precise arrays.
629
+ /**
630
+ * Narrow optional candidate results after pattern matching so callers retain a non-nullable array.
631
+ *
632
+ * @param candidate - candidate value or undefined returned from a single-match builder
633
+ * @returns True when `candidate` is defined, narrowing its type; false for undefined.
634
+ */
416
635
  function isStaticAnalysisRedundantAssertion(candidate: StaticAnalysisRedundantAssertion | undefined): candidate is StaticAnalysisRedundantAssertion {
417
636
  return candidate !== undefined;
418
637
  }
419
638
 
420
- // Collapses whitespace so finding messages carry readable one-line assertion snippets.
639
+ /**
640
+ * Collapse internal whitespace runs and trim an assertion match into a readable one-line snippet.
641
+ *
642
+ * @param assertion - raw matched assertion substring from the test body
643
+ * @returns Normalized single-line assertion text.
644
+ */
421
645
  function normalizedAssertionText(assertion: string): string {
422
646
  return assertion.replace(/\s+/g, " ").trim();
423
647
  }
424
648
 
425
- // Checks masked code at the match offset so comment/string matches cannot create findings.
649
+ /**
650
+ * Verify that an assertion match starts on executable `assert` or `expect` tokens rather than masked text.
651
+ *
652
+ * @param codeSource - masked source text where comments and strings are blanked out
653
+ * @param index - starting UTF-16 offset of the raw assertion match
654
+ * @returns True if `assert` or `expect` appears as a whole word within the 12-character slice at `index`.
655
+ */
426
656
  function isExecutableAssertionAt(codeSource: string, index: number): boolean {
427
657
  return /\b(?:assert|expect)\b/.test(codeSource.slice(index, index + 12));
428
658
  }
429
659
 
430
- // Checks masked code at the match offset so comment/string declarations are ignored.
660
+ /**
661
+ * Verify that a declaration match starts on executable `function` or `const` tokens rather than masked text.
662
+ *
663
+ * @param codeSource - masked source text where comments and strings are blanked out
664
+ * @param index - starting UTF-16 offset of the raw declaration match
665
+ * @returns True if `function` or `const` appears as a whole word within the 12-character slice at `index`.
666
+ */
431
667
  function isExecutableFunctionDeclarationAt(codeSource: string, index: number): boolean {
432
668
  return /\b(?:function|const)\b/.test(codeSource.slice(index, index + 12));
433
669
  }
434
670
 
435
- // Checks masked code at the match offset so commented import examples are ignored.
671
+ /**
672
+ * Verify that an import match starts on an executable `import` keyword rather than masked text.
673
+ *
674
+ * @param codeSource - masked source text where comments and strings are blanked out
675
+ * @param index - starting UTF-16 offset of the raw import match
676
+ * @returns True if `import` appears as a whole word within the 12-character slice at `index`.
677
+ */
436
678
  function isExecutableImportAt(codeSource: string, index: number): boolean {
437
679
  return /\bimport\b/.test(codeSource.slice(index, index + 12));
438
680
  }
439
681
 
440
- // Stores one declaration only when the name is present and the return type is non-nullable.
682
+ /**
683
+ * Store one declaration only when `name` is non-empty and its normalized return annotation passes the non-nullability text check.
684
+ *
685
+ * @param declarations - declaration map updated in place under `name`, replacing any existing entry
686
+ * @param source - raw source text used with `index` to compute the declaration line offset
687
+ * @param index - UTF-16 offset of the declaration match in `source`
688
+ * @param name - declared function or const-arrow identifier name
689
+ * @param returnType - raw captured return-type annotation normalized before validation
690
+ * @returns Nothing. Updates `declarations` in place, or leaves it unchanged for empty names or rejected return types.
691
+ */
441
692
  function pushNonNullableReturnDeclaration(declarations: Map<string, NonNullableReturnDeclaration>, source: string, index: number, name: string, returnType: string): void {
442
693
  const normalizedReturnType = returnType.replace(/\s+/g, " ").trim();
443
694
  if (!name || !isNonNullableReturnType(normalizedReturnType)) {
@@ -446,7 +697,13 @@ function pushNonNullableReturnDeclaration(declarations: Map<string, NonNullableR
446
697
  declarations.set(name, { name, returnType: normalizedReturnType, lineOffset: lineOffset(source, index) });
447
698
  }
448
699
 
449
- // Treats explicit nullable, unknown, and non-returning types as not useful static proof.
700
+ /**
701
+ * Assess whether a normalized return-type annotation serves as non-nullability evidence.
702
+ * Rejects empty text, standalone `any`/`unknown`/`void`/`null`/`undefined`/`never`, and annotations mentioning `null` or `undefined`.
703
+ *
704
+ * @param returnType - trimmed, whitespace-normalized return-type annotation text
705
+ * @returns True when the annotation names a non-nullable return type; false otherwise.
706
+ */
450
707
  function isNonNullableReturnType(returnType: string): boolean {
451
708
  if (returnType === "" || /^(?:any|unknown|void|null|undefined|never)$/.test(returnType)) {
452
709
  return false;