@blundergoat/gruff-ts 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -1,12 +1,12 @@
1
- // Per-test-block rule pass: assertion quality (no-assertions, trivial, snapshot-only,
2
- // no-throw-only, exception-type-only, magic-number), mock quality (unused-mock, mock-only-test),
3
- // global-state-mutation, and structural checks (sleep/loop/conditional/only-skip).
4
- // Invoked from the analyseBlocks orchestrator when `block.isTest` is true.
1
+ // Evaluates test-quality rules on each parsed `test(...)` or `it(...)` block in a project scan.
2
+ //
3
+ // Checks for unlabeled loops inside tests and overly broad test structure patterns while exempting clear table-driven tests.
4
+ // Called by the block orchestrator whenever a discovered callable is flagged as a test registration.
5
5
  import { blockFinding, blockFindingWithMetadata, type FunctionBlock, hasAssertion } from "./blocks.ts";
6
6
  import { type SourceFile } from "./discovery.ts";
7
7
  import { escapeRegex } from "./findings-helpers.ts";
8
8
  import { pushStaticAnalysisRedundantTestFindings, type StaticAnalysisSourceContext } from "./static-analysis-redundant-rules.ts";
9
- import { countMatches } from "./text-scans.ts";
9
+ import { countMatches, matchingCloseParen } from "./text-scans.ts";
10
10
  import type { Finding, Severity } from "./types.ts";
11
11
 
12
12
  // Provisional rule output gathered during a test-block walk. Built before the surrounding context
@@ -17,17 +17,14 @@ interface TestBlockCheck {
17
17
  severity: Severity;
18
18
  }
19
19
 
20
- // Captures one assertion matcher plus the capture indexes that hold actual expression and literal.
21
- interface MagicNumberAssertionPattern {
22
- pattern: RegExp;
23
- expressionIndex: number;
24
- matcherIndex?: number;
25
- valueIndex: number;
26
- }
27
-
28
- /*
29
- * Reached when `block.isTest` is true. Four sub-passes in a stable, deterministic order: assertion
30
- * quality, mock quality, global-state-mutation, structural rules.
20
+ /**
21
+ * Check a test block in stable order: assertion quality, mock quality, shared-state mutation, and loop structure.
22
+ *
23
+ * @param file - source file used to locate findings
24
+ * @param block - test block whose executable text and location the checks use
25
+ * @param findings - caller's list that receives findings from every check
26
+ * @param staticContext - surrounding source for assertion analysis; omission limits it to the block's own source and starting line
27
+ * @returns Nothing. Appends the findings from this test block to the supplied list.
31
28
  */
32
29
  export function analyseTestBlock(file: SourceFile, block: FunctionBlock, findings: Finding[], staticContext?: StaticAnalysisSourceContext): void {
33
30
  const body = block.codeBody;
@@ -38,55 +35,49 @@ export function analyseTestBlock(file: SourceFile, block: FunctionBlock, finding
38
35
  analyseTestStructureChecks(file, block, body, findings);
39
36
  }
40
37
 
41
- // Five assertion-shape checks (no-assertions, trivial, snapshot-only, no-throw-only, exception-type-only)
42
- // plus the magic-number sub-pass. Reports findings with stable test-block metadata.
38
+ /**
39
+ * Checks the test body for assertion-quality problems and static-analysis redundancy.
40
+ * Uses the block's original text and staticContext to assess whether static evidence makes an assertion redundant.
41
+ *
42
+ * @param file - source file used to anchor stable findings
43
+ * @param block - test block providing original text and location metadata for findings
44
+ * @param body - masked test body scanned by assertion-quality checks
45
+ * @param staticContext - surrounding source context used to evaluate redundant assertions
46
+ * @param findings - caller's list that receives findings from both checks
47
+ * @returns Nothing. Appends stable findings from both assertion-quality checks to the supplied list.
48
+ */
43
49
  function analyseAssertionQuality(file: SourceFile, block: FunctionBlock, body: string, staticContext: StaticAnalysisSourceContext, findings: Finding[]): void {
44
50
  for (const check of assertionQualityChecks(block, body)) {
45
51
  findings.push(blockFinding({ ruleId: check.ruleId, message: check.message, file, block, severity: check.severity, pillar: "test-quality" }));
46
52
  }
47
- pushMagicNumberAssertionFindings(file, block, body, findings);
48
53
  pushStaticAnalysisRedundantTestFindings(file, block, block.body, body, staticContext, findings);
49
54
  }
50
55
 
51
- // Lazy evaluation: only checks whose `active` predicate fired are returned. The five rule IDs are
52
- // part of the public test-quality pillar; their ordering here is the stable emission order.
56
+ /**
57
+ * Return active assertion-quality checks for the masked test body.
58
+ * Predicates are evaluated before filtering, and retained checks keep their declared emission order.
59
+ *
60
+ * @param block - test block whose name appears in emitted check messages
61
+ * @param body - masked test body scanned for trivial assertions
62
+ * @returns Matched assertion-quality checks in declared order, or an empty list when none matched.
63
+ */
53
64
  function assertionQualityChecks(block: FunctionBlock, body: string): TestBlockCheck[] {
54
65
  const testName = block.name;
55
66
  const checks: Array<TestBlockCheck & { active: boolean }> = [
56
- { active: !hasAssertion(body), ruleId: "test-quality.no-assertions", message: `Test \`${testName}\` does not appear to make an assertion.`, severity: "warning" },
57
67
  { active: hasTrivialAssertion(body), ruleId: "test-quality.trivial-assertion", message: `Test \`${testName}\` contains an assertion that compares a value to itself.`, severity: "warning" },
58
- { active: isSnapshotOnlyTest(body), ruleId: "test-quality.snapshot-only-test", message: `Test \`${testName}\` relies only on snapshot assertions.`, severity: "advisory" },
59
- { active: isNoThrowOnlyTest(body), ruleId: "test-quality.no-throw-only-test", message: `Test \`${testName}\` only verifies that code does not throw.`, severity: "advisory" },
60
- { active: hasExceptionTypeOnlyAssertion(body), ruleId: "test-quality.exception-type-only", message: `Test \`${testName}\` checks only the exception type.`, severity: "advisory" },
61
68
  ];
62
69
  return checks.filter((check) => check.active).map(({ active: _active, ...check }) => check);
63
70
  }
64
71
 
65
- /*
66
- * Targets `expect(x).toBe(42)` / `assert.equal(x, 42)` patterns where 42 has no name. Reports
67
- * `test-quality.magic-number-assertion` with stable literal metadata for downstream review tools.
72
+ /**
73
+ * Checks the test body for unused mock variables.
74
+ *
75
+ * @param file - source file used to locate each advisory
76
+ * @param block - test block used to anchor each advisory
77
+ * @param body - masked test body scanned for unused mock declarations
78
+ * @param findings - caller's list that receives one advisory per unused mock
79
+ * @returns Nothing. Appends one stable test-quality.unused-mock finding with the mock name to the supplied list for each match.
68
80
  */
69
- function pushMagicNumberAssertionFindings(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
70
- if (isConstantContractTestName(block.name)) {
71
- return;
72
- }
73
- for (const assertion of magicNumberAssertions(body)) {
74
- findings.push(
75
- blockFindingWithMetadata({
76
- ruleId: "test-quality.magic-number-assertion",
77
- message: `Test \`${block.name}\` asserts against unexplained numeric literal ${assertion.value}.`,
78
- file,
79
- block,
80
- severity: "advisory",
81
- pillar: "test-quality",
82
- metadata: { value: assertion.value },
83
- }),
84
- );
85
- }
86
- }
87
-
88
- // Two distinct findings emitted from one walk: per-unused-mock and a single mock-only flag.
89
- // Reports `test-quality.unused-mock` / `test-quality.mock-only-test` with stable test-block metadata.
90
81
  function analyseMockQuality(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
91
82
  const unusedMocks = unusedMockVariables(body);
92
83
  for (const mock of unusedMocks) {
@@ -102,38 +93,44 @@ function analyseMockQuality(file: SourceFile, block: FunctionBlock, body: string
102
93
  }),
103
94
  );
104
95
  }
105
- if (isMockOnlyTest(body)) {
106
- findings.push(blockFinding({ ruleId: "test-quality.mock-only-test", message: `Test \`${block.name}\` only verifies mock interaction.`, file, block, severity: "advisory", pillar: "test-quality" }));
107
- }
108
96
  }
109
97
 
110
- // Reports the stable `test-quality.global-state-mutation` finding contract for state leaks.
98
+ /**
99
+ * Checks the test body for changes to process or runtime state that other tests may share.
100
+ *
101
+ * @param file - source file used to locate the warning
102
+ * @param block - test block used to anchor and name the warning
103
+ * @param body - masked test body checked for shared-state assignments
104
+ * @param findings - caller's list that receives the warning when a mutation matches
105
+ * @returns Nothing. On a match, appends a stable test-quality.global-state-mutation warning for the supplied file and block to findings.
106
+ */
111
107
  function analyseGlobalStateMutation(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
112
108
  if (hasGlobalStateMutation(body)) {
113
109
  findings.push(blockFinding({ ruleId: "test-quality.global-state-mutation", message: `Test \`${block.name}\` mutates global process or runtime state.`, file, block, severity: "warning", pillar: "test-quality" }));
114
110
  }
115
111
  }
116
112
 
117
- // Pattern-driven checks for sleep/loop/conditional logic plus the `.only`/`.skip` commit gate.
118
- // Reports each detected structural issue as a stable test-quality finding.
113
+ /**
114
+ * Flag loops that may hide which test iteration failed. Confidence is medium because the label heuristic can miss indirect messages.
115
+ *
116
+ * @param file - source file used to locate the advisory
117
+ * @param block - test block used to anchor and name the advisory
118
+ * @param body - test code checked for loops the heuristic considers reportable
119
+ * @param findings - caller's list that receives the advisory
120
+ * @returns Nothing. Appends a stable test-quality.loop-in-test finding when the heuristic matches.
121
+ */
119
122
  function analyseTestStructureChecks(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
120
- const checks: Array<[string, boolean, string]> = [
121
- ["test-quality.sleep-in-test", /\b(setTimeout|sleep|waitForTimeout)\s*\(/.test(body), "Test sleeps instead of synchronising on behaviour."],
122
- ["test-quality.loop-in-test", controlFlowContainsNonFixtureLoop(body), "Test contains loop logic around assertions."],
123
- ["test-quality.conditional-logic", controlFlowContainsAssertion(body, /\b(?:if|switch)\b/g), "Test contains conditional logic around assertions."],
124
- ["test-quality.only-skip", /\.(only|skip)\s*\(/.test(body), "Focused or skipped test is committed."],
125
- ];
126
- for (const [ruleId, active, message] of checks) {
127
- if (active) {
128
- findings.push(blockFinding({ ruleId, message, file, block, severity: "advisory", pillar: "test-quality" }));
129
- }
123
+ if (controlFlowContainsNonFixtureLoop(body)) {
124
+ findings.push(blockFindingWithMetadata({ ruleId: "test-quality.loop-in-test", message: "Test contains loop logic that hides which iteration failed.", file, block, severity: "advisory", pillar: "test-quality", metadata: {} }));
130
125
  }
131
126
  }
132
127
 
133
- // Loop variant of `controlFlowContainsAssertion` that suppresses fixture loops (table-test pattern):
134
- // loops over a literal array or `Object.entries|keys|values` of a literal where every code path
135
- // inside the body reaches an assertion. The existing rule fires on ANY loop wrapping an assertion;
136
- // this widens the precision so parametric coverage doesn't read as control-flow noise.
128
+ /**
129
+ * Checks whether masked source contains a reportable for or while loop with an assertion.
130
+ *
131
+ * @param source - masked test body scanned for loop segments
132
+ * @returns True when a loop with an assertion is exempt by neither fixture nor labeled-case checks; false otherwise.
133
+ */
137
134
  function controlFlowContainsNonFixtureLoop(source: string): boolean {
138
135
  for (const match of source.matchAll(/\b(?:for|while)\b/g)) {
139
136
  const start = match.index ?? 0;
@@ -144,34 +141,239 @@ function controlFlowContainsNonFixtureLoop(source: string): boolean {
144
141
  if (isFixtureLoop(source, start, segment)) {
145
142
  continue;
146
143
  }
144
+ if (isLabeledCaseLoop(segment)) {
145
+ continue;
146
+ }
147
147
  return true;
148
148
  }
149
149
  return false;
150
150
  }
151
151
 
152
- // A "fixture loop" is the table-test pattern: iterable is an inline fixture OR a local const-bound
153
- // fixture table, AND every path through the body terminates in an assertion call. Guard branches
154
- // without assertions are allowed, but assertion-bearing branches still opt out.
155
- function isFixtureLoop(source: string, start: number, segment: string): boolean {
156
- const braceIndex = segment.indexOf("{");
157
- const header = braceIndex === -1 ? segment : segment.slice(0, braceIndex);
158
- if (!hasFixtureIterable(source, start, header)) {
152
+ /**
153
+ * Checks whether a loop can skip the loop-in-test finding because its recognized assertions identify the failed case.
154
+ * A multiline message can mention the label. A supported expected operand must equal the label name after trimming.
155
+ * A label can be a loop binding or a const whose initializer mentions that binding directly.
156
+ *
157
+ * @param segment - masked loop text containing the header and body to check
158
+ * @returns True if each recognized chain has a label. False for an unrecognized loop, an unsafe branch, or missing bindings or recognized calls.
159
+ */
160
+ function isLabeledCaseLoop(segment: string): boolean {
161
+ const parts = loopSegmentParts(segment);
162
+ if (!parts) {
159
163
  return false;
160
164
  }
161
- if (braceIndex === -1) {
165
+ if (hasUnsafeFixtureLoopBranch("", parts.body)) {
166
+ return false;
167
+ }
168
+ const boundNames = loopBoundNames(parts.header);
169
+ if (boundNames.length === 0) {
170
+ return false;
171
+ }
172
+ // Reject the exemption when the loop mixes in assertion forms (`should.be`, `.resolves`/`.rejects`) that have no verified per-case label.
173
+ if (/\.\s*should\s*\.\s*be\s*\./.test(parts.body) || /\.\s*(?:rejects|resolves)\b/.test(parts.body)) {
174
+ return false;
175
+ }
176
+ const assertionCalls = assertionCallChains(parts.body);
177
+ if (assertionCalls.length === 0) {
178
+ return false;
179
+ }
180
+ const labelNames = [...boundNames, ...loopDerivedLocalNames(parts.body, boundNames)];
181
+ return assertionCalls.every((call) => hasLoopCaseLabel(call, labelNames));
182
+ }
183
+
184
+ // Only call forms with supported per-case label arguments can clear a loop warning; `.should.be` matchers have no proved label form.
185
+ const ASSERTION_CALL_OPENER = /\b(?:assert(?:\.[A-Za-z]+|[A-Z][A-Za-z0-9_$]*)?|expect(?:\.(?:assertions|hasAssertions)|[A-Z][A-Za-z0-9_$]*)?|[A-Za-z_$][A-Za-z0-9_$]*Check)\s*(?:<(?!\s)(?:(?!&&|\|\|)[^;\r\n])+>\s*)?\(/g;
186
+ // One chained call such as `.toBe(` after a closed call.
187
+ const CHAINED_CALL_LINK = /^\s*\.\s*[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^;]*?>\s*)?\(/;
188
+
189
+ /**
190
+ * Return recognized assertion-chain slices from the masked loop body, including nested assertion calls inside outer assertion arguments.
191
+ * Skip an unmatched opening call or member-chained property call; if a later chained call is unclosed, retain the complete prefix already measured.
192
+ *
193
+ * @param body - masked loop body scanned for assertion openers and chained calls
194
+ * @returns Matched assertion-chain slices in source order, or an empty list when no opener can be matched.
195
+ */
196
+ function assertionCallChains(body: string): string[] {
197
+ const calls: string[] = [];
198
+ for (const match of body.matchAll(ASSERTION_CALL_OPENER)) {
199
+ const start = match.index ?? 0;
200
+ // Skip member calls chained onto an earlier expression (such as `foo.expectCheck(`), while keeping nested standalone assertions checked.
201
+ if (start > 0 && body[start - 1] === ".") {
202
+ continue;
203
+ }
204
+ let close = matchingCloseParen(body, start + match[0].length - 1);
205
+ if (close === undefined) {
206
+ continue;
207
+ }
208
+ for (let link = body.slice(close + 1).match(CHAINED_CALL_LINK); link; link = body.slice(close + 1).match(CHAINED_CALL_LINK)) {
209
+ const linkClose = matchingCloseParen(body, close + link[0].length);
210
+ if (linkClose === undefined) {
211
+ break;
212
+ }
213
+ close = linkClose;
214
+ }
215
+ calls.push(body.slice(start, close + 1));
216
+ }
217
+ return calls;
218
+ }
219
+
220
+ /**
221
+ * Return const-local names whose initializer text in body has a whole-word match from boundNames, for use as assertion labels.
222
+ * Follow one level only; locals derived solely from other derived locals and unmatched declarations are excluded.
223
+ *
224
+ * @param body - masked loop body searched for const declarations
225
+ * @param boundNames - loop-bound identifier names tested against each const initializer
226
+ * @returns Derived local names eligible as assertion labels.
227
+ */
228
+ function loopDerivedLocalNames(body: string, boundNames: string[]): string[] {
229
+ const derived: string[] = [];
230
+ for (const match of body.matchAll(/\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*([^;\n]+)/g)) {
231
+ const initializer = match[2] ?? "";
232
+ if (boundNames.some((name) => new RegExp(`\\b${escapeRegex(name)}\\b`).test(initializer))) {
233
+ derived.push(match[1] ?? "");
234
+ }
235
+ }
236
+ return derived.filter(Boolean);
237
+ }
238
+
239
+ /**
240
+ * Extract identifier names bound by for-of, for-in or C-style headers.
241
+ * While-loops bind nothing here, so they never take the labeled opt-out.
242
+ *
243
+ * @param header - loop header text preceding the body brace
244
+ * @returns Bound identifier names from the loop header, or an empty list when none are declared.
245
+ */
246
+ function loopBoundNames(header: string): string[] {
247
+ const binding = header.match(/\b(?:const|let|var)\s+([^)]*?)\s+(?:of|in)\b/)?.[1]
248
+ ?? header.match(/\b(?:let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/)?.[1]
249
+ ?? "";
250
+ return [...binding.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)].map((match) => match[0] ?? "").filter(Boolean);
251
+ }
252
+
253
+ /**
254
+ * Return whether the assertion call text in statement labels a case with one of the loop bindings or derived locals.
255
+ * Looks for a whole-word match in argument three for binary assert calls or argument two otherwise, plus bare expected operands.
256
+ *
257
+ * @param statement - recognized assertion-chain text from a loop body
258
+ * @param boundNames - loop bindings and derived local names accepted as case labels
259
+ * @returns True when the assertion message or expected operand matches a label name; false otherwise.
260
+ */
261
+ function hasLoopCaseLabel(statement: string, boundNames: string[]): boolean {
262
+ const argumentsList = assertionArguments(statement);
263
+ const isBinaryAssert = /^assert\.(?:(?:not)?(?:strictEqual|deepStrictEqual|equal|deepEqual)|throws|rejects|match|doesNotMatch)\b/i.test(statement);
264
+ const isExpect = /^expect\s*\(/.test(statement);
265
+ const message = argumentsList[isBinaryAssert ? 2 : 1] ?? "";
266
+ const matcher = isExpect ? statement.slice((matchingCloseParen(statement, statement.indexOf("(")) ?? statement.length) + 1) : "";
267
+ const expected = isBinaryAssert ? argumentsList[1] ?? "" : isExpect ? assertionArguments(matcher)[0] ?? "" : "";
268
+ return boundNames.some((name) => new RegExp(`\\b${escapeRegex(name)}\\b`).test(message) || expected.trim() === name);
269
+ }
270
+
271
+ /**
272
+ * Return comma-separated argument slices from statement's outer call; strings and comments must already be masked.
273
+ * Nested delimiters stay within a slice.
274
+ *
275
+ * @param statement - masked call expression whose outer argument list is split
276
+ * @returns Argument slices from the outer call (retaining an interior slice on an empty call), or an empty list if parentheses are unmatched.
277
+ */
278
+ function assertionArguments(statement: string): string[] {
279
+ const open = statement.indexOf("(");
280
+ const close = matchingCloseParen(statement, open);
281
+ if (open < 0 || close === undefined) {
282
+ return [];
283
+ }
284
+ const argumentsList: string[] = [];
285
+ let depth = 0;
286
+ let start = open + 1;
287
+ for (let index = start; index < close; index += 1) {
288
+ const character = statement[index] ?? "";
289
+ if ("([{".includes(character)) depth += 1;
290
+ else if (")]}".includes(character)) depth -= 1;
291
+ else if (character === "," && depth === 0) {
292
+ argumentsList.push(statement.slice(start, index));
293
+ start = index + 1;
294
+ }
295
+ }
296
+ argumentsList.push(statement.slice(start, close));
297
+ return argumentsList;
298
+ }
299
+
300
+ /**
301
+ * Return whether segment has an accepted fixture iterable and a final non-ignored statement starting with a recognized assertion.
302
+ * Switch, case, or default markers disqualify the loop; an assertion-bearing if disqualifies it unless matched as a fixture guard.
303
+ *
304
+ * @param source - masked source surrounding the loop for preceding declaration lookup
305
+ * @param start - character offset in source where the loop keyword begins
306
+ * @param segment - bounded loop text containing header and body
307
+ * @returns True when the loop iterates an accepted fixture table safely and ends with a recognized assertion; false otherwise.
308
+ */
309
+ function isFixtureLoop(source: string, start: number, segment: string): boolean {
310
+ const parts = loopSegmentParts(segment);
311
+ if (!parts || !hasFixtureIterable(source, start, parts.header)) {
162
312
  return false;
163
313
  }
164
- const body = segment.slice(braceIndex + 1, segment.length - 1);
165
- if (hasUnsafeFixtureLoopBranch(source.slice(0, start + braceIndex + 1), body)) {
314
+ if (hasUnsafeFixtureLoopBranch(source.slice(0, start + parts.bodyBraceIndex + 1), parts.body)) {
166
315
  return false;
167
316
  }
168
- const statements = body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement));
317
+ // A bare void-name marker can follow the terminal assertion without disqualifying the loop. A void-wrapped call still counts.
318
+ const statements = parts.body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement) && !/^void\s+[A-Za-z_$][A-Za-z0-9_$]*$/.test(statement));
169
319
  const lastStatement = statements[statements.length - 1] ?? "";
170
320
  return /^(?:assert\.[a-z]+\s*\(|expect\s*\(|[a-z][A-Za-z0-9_]*\.should(?:Be|Equal)?\s*\()/i.test(lastStatement);
171
321
  }
172
322
 
173
- // Fixture sweeps may carry invariant guards such as `if (expectedIds.has(case.id))`; other branches
174
- // still opt out because they can hide case-specific expectations inside the loop.
323
+ /**
324
+ * Splits a loop segment into header and body at the body-opening brace, walking past the header's balanced parentheses first
325
+ * so that a destructured binding such as `for (const { name } of rows)` does not end the header at the destructuring brace.
326
+ *
327
+ * @param segment - bounded loop text beginning at the loop keyword
328
+ * @returns Header slice, body interior slice, and body-brace offset, or undefined for braceless or unclosed headers.
329
+ */
330
+ function loopSegmentParts(segment: string): { header: string; body: string; bodyBraceIndex: number } | undefined {
331
+ const parenIndex = segment.indexOf("(");
332
+ if (parenIndex === -1) {
333
+ return undefined;
334
+ }
335
+ const headerCloseIndex = matchingHeaderCloseParen(segment, parenIndex);
336
+ if (headerCloseIndex === undefined) {
337
+ return undefined;
338
+ }
339
+ const bodyBraceIndex = segment.indexOf("{", headerCloseIndex);
340
+ if (bodyBraceIndex === -1) {
341
+ return undefined;
342
+ }
343
+ return { header: segment.slice(0, bodyBraceIndex), body: segment.slice(bodyBraceIndex + 1, segment.length - 1), bodyBraceIndex };
344
+ }
345
+
346
+ /**
347
+ * Find the closing-parenthesis index for the loop-header opener at parenIndex in segment, counting nested parentheses.
348
+ *
349
+ * @param segment - loop text containing the header parentheses
350
+ * @param parenIndex - offset of the header's opening parenthesis inside segment
351
+ * @returns Closing-parenthesis offset in segment, or undefined if the outer group does not close before segment ends.
352
+ */
353
+ function matchingHeaderCloseParen(segment: string, parenIndex: number): number | undefined {
354
+ let depth = 0;
355
+ for (let index = parenIndex; index < segment.length; index += 1) {
356
+ const character = segment[index];
357
+ if (character === "(") {
358
+ depth += 1;
359
+ } else if (character === ")") {
360
+ depth -= 1;
361
+ if (depth === 0) {
362
+ return index;
363
+ }
364
+ }
365
+ }
366
+ return undefined;
367
+ }
368
+
369
+ /**
370
+ * Return whether loop body contains a switch-like construct or an assertion-bearing if segment without a recognized fixture-membership guard.
371
+ * Other if segments without assertions do not reject the fixture loop.
372
+ *
373
+ * @param sourceBeforeLoopBody - preceding source text supplying declarations for fixture guard lookup
374
+ * @param body - loop body text checked for switch markers and conditional assertions
375
+ * @returns True when an unsafe switch or unguarded assertion branch is found; false otherwise.
376
+ */
175
377
  function hasUnsafeFixtureLoopBranch(sourceBeforeLoopBody: string, body: string): boolean {
176
378
  if (/\bswitch\s*\(|\bcase\s|\bdefault\s*:/.test(body)) {
177
379
  return true;
@@ -187,9 +389,14 @@ function hasUnsafeFixtureLoopBranch(sourceBeforeLoopBody: string, body: string):
187
389
  return false;
188
390
  }
189
391
 
190
- // Inline fixture tables cover `for (... of [...])` and `Object.entries({ ... })`. Const-bound
191
- // tables cover the common contract-test shape where the named case table is declared immediately
192
- // before the sweep for readability.
392
+ /**
393
+ * Return whether header looks like an inline fixture iterable or names a recognized fixture constant or const-bound table.
394
+ *
395
+ * @param source - masked source providing preceding declarations for const-bound lookup
396
+ * @param start - character offset in source where the loop begins
397
+ * @param header - loop header text inspected for an inline or named fixture iterable
398
+ * @returns True when the header iterates a recognized fixture iterable; false when no accepted shape was found.
399
+ */
193
400
  function hasFixtureIterable(source: string, start: number, header: string): boolean {
194
401
  if (/\bof\s*\[/.test(header) || /\bof\s+Object\.(?:entries|keys|values)\s*\(/.test(header)) {
195
402
  return true;
@@ -198,8 +405,14 @@ function hasFixtureIterable(source: string, start: number, header: string): bool
198
405
  return iterableName !== "" && (isFixtureConstantIterableName(iterableName) || hasConstBoundFixtureIterable(source.slice(0, start), iterableName));
199
406
  }
200
407
 
201
- // Accepts const-bound fixture loops only when the iterable name and initializer both look like a
202
- // deterministic case table or discovered fixture set.
408
+ /**
409
+ * Return whether iterableName has fixture vocabulary and a const assignment in sourceBeforeLoop with an accepted initializer shape.
410
+ * The assignment text must reach a semicolon at the end of the prefix; arrays, Object.entries/keys/values, or discovery calls qualify.
411
+ *
412
+ * @param sourceBeforeLoop - source prefix preceding the loop header
413
+ * @param iterableName - identifier bound by the loop's `of` clause
414
+ * @returns True when the identifier matches fixture vocabulary and an accepted const initializer; false otherwise.
415
+ */
203
416
  function hasConstBoundFixtureIterable(sourceBeforeLoop: string, iterableName: string): boolean {
204
417
  if (!isFixtureIterableName(iterableName)) {
205
418
  return false;
@@ -209,41 +422,58 @@ function hasConstBoundFixtureIterable(sourceBeforeLoop: string, iterableName: st
209
422
  return initializer.startsWith("[") || /^Object\.(?:entries|keys|values)\s*\(/.test(initializer) || isFixtureDiscoveryCall(initializer);
210
423
  }
211
424
 
212
- // Limits const-bound loop suppression to table/sweep vocabulary rather than arbitrary arrays.
425
+ /**
426
+ * Check whether an identifier carries a recognized fixture-table suffix for the loop-exemption heuristic.
427
+ *
428
+ * @param name - identifier name from a loop iterable
429
+ * @returns True when the name ends with an accepted fixture-table suffix; false otherwise.
430
+ */
213
431
  function isFixtureIterableName(name: string): boolean {
214
432
  return /(?:agents|cases|checks|entries|examples|fixtures|files|ids|paths|records|scenarios|scores|snapshots)$/i.test(name);
215
433
  }
216
434
 
217
- // UPPER_CASE fixture constants such as HARNESS_CHECKS are named case tables even when imported.
435
+ /**
436
+ * Check whether an identifier uses only uppercase letters, digits and underscores and has a fixture suffix; no local declaration is required.
437
+ *
438
+ * @param name - identifier name from a loop iterable
439
+ * @returns True when the name matches constant-case naming and a fixture suffix; false otherwise.
440
+ */
218
441
  function isFixtureConstantIterableName(name: string): boolean {
219
442
  return /^[A-Z0-9_]+$/.test(name) && isFixtureIterableName(name);
220
443
  }
221
444
 
222
- // Recognises local fixture discovery calls used by contract sweeps without accepting unknown calls.
445
+ /**
446
+ * Check whether initializer contains a call named glob, globSync, readdir, readdirSync, or beginning with discover, find or list.
447
+ * This name heuristic does not verify where the function was declared or whether it discovers fixtures.
448
+ *
449
+ * @param initializer - trimmed initializer expression from a const fixture binding
450
+ * @returns True when a recognized discovery call pattern appears in the initializer; false otherwise.
451
+ */
223
452
  function isFixtureDiscoveryCall(initializer: string): boolean {
224
453
  return /\b(?:glob|globSync|readdir|readdirSync|discover[A-Za-z0-9_$]*|find[A-Za-z0-9_$]*|list[A-Za-z0-9_$]*)\s*\(/.test(initializer);
225
454
  }
226
455
 
227
- // Structural loop/branch findings now require the control flow to wrap an assertion; setup-only
228
- // conditionals and fixture-building loops are noisy but not direct test-quality failures.
229
- function controlFlowContainsAssertion(source: string, pattern: RegExp): boolean {
230
- for (const match of source.matchAll(pattern)) {
231
- const start = match.index ?? 0;
232
- const segment = controlFlowSegment(source, start);
233
- if (hasAssertion(segment) && !isInvariantAssertionConditional(source, start, segment)) {
234
- return true;
235
- }
236
- }
237
- return false;
238
- }
239
-
240
- // Accepts guard conditionals whose assertion proves a shared invariant rather than branch policy.
456
+ /**
457
+ * Check whether segment's condition matches the fixture-membership guard heuristic using source text before offset start.
458
+ * The invariant heuristic checks text before the first opening brace as the condition; with no brace, the guard cannot qualify.
459
+ *
460
+ * @param source - preceding source text containing declarations visible before the conditional
461
+ * @param start - character offset in source where the conditional segment starts
462
+ * @param segment - conditional segment text beginning at `if`
463
+ * @returns True when the condition matches the fixture-membership guard heuristic; false otherwise.
464
+ */
241
465
  function isInvariantAssertionConditional(source: string, start: number, segment: string): boolean {
242
466
  const condition = segment.slice(0, Math.max(0, segment.indexOf("{"))).trim();
243
467
  return isFixtureMembershipGuard(source.slice(0, start), condition);
244
468
  }
245
469
 
246
- // Membership guards over const-bound fixtures keep invariant sweeps readable.
470
+ /**
471
+ * Check whether condition's first has/includes target is declared as a const with a new Set or array initializer in sourceBeforeCondition.
472
+ *
473
+ * @param sourceBeforeCondition - source prefix preceding the conditional statement
474
+ * @param condition - conditional header text before the opening brace
475
+ * @returns True when the guarded target is declared as a const Set or array; false when the target or declaration cannot be matched.
476
+ */
247
477
  function isFixtureMembershipGuard(sourceBeforeCondition: string, condition: string): boolean {
248
478
  const guardTarget = condition.match(/\b([A-Za-z_$][A-Za-z0-9_$]*)\.(?:has|includes)\s*\(/)?.[1] ?? "";
249
479
  if (!guardTarget) {
@@ -252,18 +482,55 @@ function isFixtureMembershipGuard(sourceBeforeCondition: string, condition: stri
252
482
  return new RegExp(`\\bconst\\s+${escapeRegex(guardTarget)}\\s*=\\s*(?:new\\s+Set\\s*\\(|\\[)`).test(sourceBeforeCondition);
253
483
  }
254
484
 
255
- // Captures the smallest control-flow segment so assertion detection does not scan the whole test.
485
+ /**
486
+ * Extract bounded control-flow text in masked source beginning at keyword offset start for assertion detection.
487
+ * With no same-line body brace, returns the rest of that line; an unmatched brace limits the result to the header and opening brace.
488
+ *
489
+ * @param source - masked source text containing the control-flow construct
490
+ * @param start - character offset in source where the control-flow keyword begins
491
+ * @returns Bounded control-flow slice starting at the keyword offset.
492
+ */
256
493
  function controlFlowSegment(source: string, start: number): string {
257
494
  const lineEnd = source.indexOf("\n", start);
258
- const openBrace = source.indexOf("{", start);
259
- if (openBrace === -1 || (lineEnd !== -1 && openBrace > lineEnd)) {
495
+ const openBrace = controlFlowBodyBraceIndex(source, start, lineEnd);
496
+ if (openBrace === undefined) {
260
497
  return source.slice(start, lineEnd === -1 ? source.length : lineEnd);
261
498
  }
262
499
  const closeBrace = matchingCloseBrace(source, openBrace);
263
500
  return source.slice(start, closeBrace === undefined ? openBrace + 1 : closeBrace + 1);
264
501
  }
265
502
 
266
- // Lightweight brace matcher for already-isolated test block text; enough to bound loop/if bodies.
503
+ /**
504
+ * In masked source, scan from the keyword offset start up to lineEnd for the first opening brace outside parentheses.
505
+ *
506
+ * @param source - masked source text being scanned
507
+ * @param start - character offset of the control-flow keyword
508
+ * @param lineEnd - end-of-line offset bounding the scan, or -1 to scan to the end of source
509
+ * @returns Offset of the first body-opening brace outside parentheses, or undefined if none is found.
510
+ */
511
+ function controlFlowBodyBraceIndex(source: string, start: number, lineEnd: number): number | undefined {
512
+ const limit = lineEnd === -1 ? source.length : lineEnd;
513
+ let parenDepth = 0;
514
+ for (let index = start; index < limit; index += 1) {
515
+ const character = source[index];
516
+ if (character === "(") {
517
+ parenDepth += 1;
518
+ } else if (character === ")") {
519
+ parenDepth = Math.max(0, parenDepth - 1);
520
+ } else if (character === "{" && parenDepth === 0) {
521
+ return index;
522
+ }
523
+ }
524
+ return undefined;
525
+ }
526
+
527
+ /**
528
+ * Find the closing-brace index for the opening-brace offset openBrace in masked source, to bound a loop or conditional body.
529
+ *
530
+ * @param source - masked source text containing the braced block
531
+ * @param openBrace - offset of the opening brace in source
532
+ * @returns Offset of the matching closing brace, or undefined when the braces never balance before source ends.
533
+ */
267
534
  function matchingCloseBrace(source: string, openBrace: number): number | undefined {
268
535
  let depth = 0;
269
536
  for (let index = openBrace; index < source.length; index += 1) {
@@ -280,16 +547,22 @@ function matchingCloseBrace(source: string, openBrace: number): number | undefin
280
547
  return undefined;
281
548
  }
282
549
 
283
- // Aggregator over the three trivial-assertion shapes - literal-comparison, mirrored-`assert`
284
- // arguments, mirrored-`expect` arguments. Splitting the checks keeps each regex focused and
285
- // debuggable while this top-level keeps the call site for `test-quality.trivial-assertion` short.
550
+ /**
551
+ * Check whether the test source contains assert.ok(true) or matching operands in supported assert or expect equality checks.
552
+ *
553
+ * @param source - masked test body scanned for trivial assertions
554
+ * @returns True when a trivial assertion form matches; false when none match, so the caller can skip `test-quality.trivial-assertion`.
555
+ */
286
556
  function hasTrivialAssertion(source: string): boolean {
287
557
  return hasLiteralTrivialAssertion(source) || hasRepeatedAssertArgument(source) || hasRepeatedExpectArgument(source);
288
558
  }
289
559
 
290
- // Targets `assert.ok(true)` and `assert.equal(literal, sameLiteral)` shapes - both prove nothing
291
- // at runtime. The backreference `\1` is what makes the second pattern detect mirrored literals
292
- // across the supported `equal` / `strictEqual` / `deepEqual` variants.
560
+ /**
561
+ * Check for supported assert.ok(true) or identical-literal equality patterns in source.
562
+ *
563
+ * @param source - masked test body scanned for literal trivial assertions
564
+ * @returns True when a literal trivial assertion matches; false otherwise.
565
+ */
293
566
  function hasLiteralTrivialAssertion(source: string): boolean {
294
567
  return (
295
568
  /\bassert\.ok\s*\(\s*true\s*\)/.test(source) ||
@@ -297,9 +570,13 @@ function hasLiteralTrivialAssertion(source: string): boolean {
297
570
  );
298
571
  }
299
572
 
300
- // Walks every `assert.equal(a, b)` call and normalises both arguments before comparison so that
301
- // `foo;` and `foo` collapse to the same key. Mirrored expressions indicate the assertion would
302
- // pass regardless of behaviour - reports as a trivial assertion.
573
+ /**
574
+ * Walks every `assert.equal(a, b)` call and normalises both arguments before comparison so that
575
+ * `foo;` and `foo` collapse to the same key, because mirrored expressions pass regardless of behaviour.
576
+ *
577
+ * @param source - masked test body scanned for repeated assert arguments
578
+ * @returns True when an assert equality call compares identical normalized arguments; false otherwise.
579
+ */
303
580
  function hasRepeatedAssertArgument(source: string): boolean {
304
581
  for (const match of source.matchAll(/\bassert\.(?:equal|strictEqual|deepEqual)\s*\(\s*([^,\n]+?)\s*,\s*([^,\n)]+?)(?:\s*,|\s*\))/g)) {
305
582
  if (normalizeAssertionExpression(match[1] ?? "") === normalizeAssertionExpression(match[2] ?? "")) {
@@ -309,9 +586,13 @@ function hasRepeatedAssertArgument(source: string): boolean {
309
586
  return false;
310
587
  }
311
588
 
312
- // Jest/Vitest counterpart to `hasRepeatedAssertArgument`. Targets `expect(a).toBe(b)` and the
313
- // equality variants; the matcher set is intentionally narrow so async / negation forms don't
314
- // produce false positives on argument equality.
589
+ /**
590
+ * Check whether source contains a direct expect equality call using toBe, toEqual or toStrictEqual with identical normalized argument text.
591
+ * Async and negated matcher chains do not match.
592
+ *
593
+ * @param source - masked test body scanned for repeated expect arguments
594
+ * @returns True when a direct expect equality call has identical normalized operands; false means no supported pair was found.
595
+ */
315
596
  function hasRepeatedExpectArgument(source: string): boolean {
316
597
  for (const match of source.matchAll(/\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*to(?:Be|Equal|StrictEqual)\s*\(\s*([^)]+?)\s*\)/g)) {
317
598
  if (normalizeAssertionExpression(match[1] ?? "") === normalizeAssertionExpression(match[2] ?? "")) {
@@ -321,94 +602,23 @@ function hasRepeatedExpectArgument(source: string): boolean {
321
602
  return false;
322
603
  }
323
604
 
324
- // Trims whitespace and strips a trailing semicolon so that `foo;` and `foo` compare as equal -
325
- // preserves the deterministic mirrored-argument detection across whitespace variations.
605
+ /**
606
+ * Build expression's comparison key after trimming surrounding whitespace and one trailing semicolon, so mirrored arguments compare equally.
607
+ *
608
+ * @param expression - raw operand text captured from an assertion call
609
+ * @returns Normalized comparison key for the assertion operand.
610
+ */
326
611
  function normalizeAssertionExpression(expression: string): string {
327
612
  return expression.trim().replace(/;$/, "");
328
613
  }
329
614
 
330
- // Strips every snapshot-shaped assertion plus `expect.assertions(...)` and re-checks whether any
331
- // assertion remains. A body that empties out is flagged for `test-quality.snapshot-only-test`,
332
- // since snapshot fixtures alone don't constrain behaviour.
333
- function isSnapshotOnlyTest(source: string): boolean {
334
- if (!/\.\s*toMatch(?:Inline)?Snapshot\s*\(/.test(source)) {
335
- return false;
336
- }
337
- const withoutSnapshots = source
338
- .replace(/\bexpect\s*\([\s\S]*?\)\s*\.\s*toMatch(?:Inline)?Snapshot\s*\([^)]*\)\s*;?/g, "")
339
- .replace(/\bexpect\.(?:assertions|hasAssertions)\s*\([^)]*\)\s*;?/g, "");
340
- return !hasAssertion(withoutSnapshots);
341
- }
342
-
343
- // Same shape as `isSnapshotOnlyTest` but for `doesNotThrow` / `not.toThrow`. A test that asserts
344
- // only the absence of an exception is weak - `test-quality.no-throw-only-test` reports it so
345
- // authors can add a real behaviour assertion alongside.
346
- function isNoThrowOnlyTest(source: string): boolean {
347
- if (!/\bassert\.doesNotThrow\s*\(|\.\s*not\s*\.\s*toThrow\s*\(/.test(source)) {
348
- return false;
349
- }
350
- const withoutNoThrow = source
351
- .replace(/\bassert\.doesNotThrow\s*\([\s\S]*?\)\s*;?/g, "")
352
- .replace(/\bexpect\s*\([\s\S]*?\)\s*\.\s*not\s*\.\s*toThrow\s*\([^)]*\)\s*;?/g, "")
353
- .replace(/\bexpect\.(?:assertions|hasAssertions)\s*\([^)]*\)\s*;?/g, "");
354
- return !hasAssertion(withoutNoThrow);
355
- }
356
-
357
- // Pulls every numeric expected value out of `expect(...).toBe(n)` and `assert.equal(actual, n)`
358
- // shapes. Small cardinalities and length/count matchers are excluded because the literal often is
359
- // the test contract; larger opaque values still surface for naming or rationale.
360
- function magicNumberAssertions(source: string): Array<{ value: number }> {
361
- return MAGIC_NUMBER_ASSERTION_PATTERNS.flatMap((candidate) => magicNumberAssertionMatches(source, candidate));
362
- }
363
-
364
- const MAGIC_NUMBER_ASSERTION_PATTERNS: MagicNumberAssertionPattern[] = [
365
- { pattern: /\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*(to(?:Be|Equal|HaveLength|HaveCount))\s*\(\s*(-?\d+(?:\.\d+)?)\s*\)/g, expressionIndex: 1, matcherIndex: 2, valueIndex: 3 },
366
- { pattern: /\bassert\.(?:equal|strictEqual|deepEqual)\s*\(\s*([^,\n]+?)\s*,\s*(-?\d+(?:\.\d+)?)(?:\s*,|\s*\))/g, expressionIndex: 1, valueIndex: 2 },
367
- ];
368
-
369
- // Extracts reportable numeric literals for one assertion grammar while keeping HTTP statuses quiet.
370
- function magicNumberAssertionMatches(source: string, candidate: MagicNumberAssertionPattern): Array<{ value: number }> {
371
- const results: Array<{ value: number }> = [];
372
- for (const match of source.matchAll(candidate.pattern)) {
373
- const expression = match[candidate.expressionIndex] ?? "";
374
- const matcher = candidate.matcherIndex === undefined ? "" : match[candidate.matcherIndex] ?? "";
375
- const expectedNumber = Number(match[candidate.valueIndex] ?? "0");
376
- if (!isIgnoredMagicNumberAssertion(expression, matcher, expectedNumber)) {
377
- results.push({ value: expectedNumber });
378
- }
379
- }
380
- return results;
381
- }
382
-
383
- // Centralises the rule's non-findings so cardinal, count, and HTTP-status exemptions stay aligned.
384
- function isIgnoredMagicNumberAssertion(expression: string, matcher: string, expectedNumber: number): boolean {
385
- return isSmallCardinal(expectedNumber) || isLengthOrCountMatcher(matcher) || isHttpStatusAssertion(expression, expectedNumber);
386
- }
387
-
388
- // Small integer cardinals usually express the expected case count directly.
389
- function isSmallCardinal(cardinal: number): boolean {
390
- return Number.isInteger(cardinal) && cardinal >= -1 && cardinal <= 3;
391
- }
392
-
393
- // Length/count matchers already name the measurement, so the numeric literal is the assertion.
394
- function isLengthOrCountMatcher(matcher: string): boolean {
395
- return matcher === "toHaveLength" || matcher === "toHaveCount";
396
- }
397
-
398
- // Contract-named tests may assert the documented number directly; the name supplies the rationale.
399
- function isConstantContractTestName(name: string): boolean {
400
- return /\b(?:constant|threshold|limit|budget|default|contract)\b/i.test(name);
401
- }
402
-
403
- // HTTP response status codes are intentionally numeric at assertion sites; naming every 200/404
404
- // would add ceremony without making the test clearer.
405
- function isHttpStatusAssertion(expression: string, expectedNumber: number): boolean {
406
- return Number.isInteger(expectedNumber) && expectedNumber >= 100 && expectedNumber <= 599 && /\b(?:status|statusCode)\b/.test(expression);
407
- }
408
-
409
- // `const mockX = vi.fn(...)` declarations whose binding appears only once in the body - that one
410
- // occurrence is the declaration itself, so the mock is created but never wired in. Reports the
411
- // names for `test-quality.unused-mock` to anchor on.
615
+ /**
616
+ * Find `const mockX = vi.fn(...)` declarations whose binding appears only once in the body,
617
+ * because that single occurrence is the declaration itself and the mock is never wired in.
618
+ *
619
+ * @param source - masked test body scanned for mock variable declarations and references
620
+ * @returns Unused mock variable names for `test-quality.unused-mock` to anchor on.
621
+ */
412
622
  function unusedMockVariables(source: string): string[] {
413
623
  const names: string[] = [];
414
624
  for (const match of source.matchAll(/\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:(?:vi|jest)\.fn|sinon\.stub|createMock|mock)\s*\(/g)) {
@@ -423,29 +633,13 @@ function unusedMockVariables(source: string): string[] {
423
633
  return names;
424
634
  }
425
635
 
426
- // Three gates in order: a mock factory must exist, a mock-call matcher must be asserted, and
427
- // *every* `expect(target)` argument must look like a mock/stub/spy name. All three together
428
- // signal a test that only verifies its own scaffolding - flagged for `test-quality.mock-only-test`.
429
- function isMockOnlyTest(source: string): boolean {
430
- if (!/\b(?:vi|jest)\.fn\s*\(|\b(?:createMock|mock|sinon\.stub)\s*\(/.test(source)) {
431
- return false;
432
- }
433
- if (!/\.(?:toHaveBeenCalled|toHaveBeenCalledWith|toHaveBeenNthCalledWith|toBeCalled|toBeCalledWith)\s*\(/.test(source)) {
434
- return false;
435
- }
436
- const targets = [...source.matchAll(/\bexpect\s*\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\)/g)].map((match) => match[1] ?? "");
437
- return targets.length > 0 && targets.every((target) => /(?:mock|stub|spy)$/i.test(target));
438
- }
439
-
440
- // `toThrow(Error)` / `assert.throws(fn, Error)` constrain only the constructor, not the message
441
- // or properties. Reports `test-quality.exception-type-only` so authors tighten the assertion.
442
- function hasExceptionTypeOnlyAssertion(source: string): boolean {
443
- return /\.toThrow\s*\(\s*(?:Error|[A-Z][A-Za-z0-9_$]*Error)\s*\)/.test(source) || /\bassert\.throws\s*\([^,\n]+,\s*(?:Error|[A-Z][A-Za-z0-9_$]*Error)\s*\)/.test(source);
444
- }
445
-
446
- // Three known anti-patterns: writing to `process.env`, writing to `globalThis.*`, or reassigning
447
- // `Date.now` / `Math.random`. Each leaks state across tests; reports
448
- // `test-quality.global-state-mutation` so the author isolates the fixture.
636
+ /**
637
+ * Check whether source matches the supported process.env, globalThis, Date.now or Math.random assignment patterns.
638
+ * This textual check does not establish whether state is restored.
639
+ *
640
+ * @param source - masked test body scanned for shared-state assignments
641
+ * @returns True when a supported shared-state assignment pattern matches, used to report possible mutation; false otherwise.
642
+ */
449
643
  function hasGlobalStateMutation(source: string): boolean {
450
644
  return /\bprocess\.env\.[A-Za-z0-9_]+\s*=/.test(source) || /\bglobalThis\.[A-Za-z0-9_$]+\s*=/.test(source) || /\b(?:Date\.now|Math\.random)\s*=/.test(source);
451
645
  }