@blundergoat/gruff-ts 0.2.0 → 0.3.1

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 (48) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +81 -13
  3. package/docs/README.md +2 -0
  4. package/docs/agent-hook.md +80 -0
  5. package/docs/ci-integration.md +16 -0
  6. package/docs/configuration.md +21 -5
  7. package/docs/output-formats.md +10 -0
  8. package/docs/philosophy.md +21 -0
  9. package/docs/releasing.md +5 -5
  10. package/docs/rules.md +26 -18
  11. package/package.json +5 -5
  12. package/scripts/bump-version.sh +1 -1
  13. package/src/analyser.ts +48 -37
  14. package/src/blocks.ts +23 -70
  15. package/src/changed-regions.ts +390 -0
  16. package/src/check-ignore.ts +49 -0
  17. package/src/class-rules.ts +80 -33
  18. package/src/cli-program.ts +106 -12
  19. package/src/comment-rules.ts +5 -1
  20. package/src/config-parse.ts +458 -0
  21. package/src/config-preservation.ts +1 -1
  22. package/src/config.ts +215 -460
  23. package/src/constants.ts +1 -1
  24. package/src/context-doc-rules.ts +2 -4
  25. package/src/dashboard.ts +7 -4
  26. package/src/discovery.ts +88 -32
  27. package/src/findings-helpers.ts +41 -5
  28. package/src/findings.ts +10 -0
  29. package/src/fixture-purpose-rules.ts +7 -9
  30. package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
  31. package/src/init-config.ts +3 -0
  32. package/src/line-rules.ts +7 -5
  33. package/src/naming-pushers.ts +35 -6
  34. package/src/profiles.ts +231 -0
  35. package/src/project-config-rules.ts +5 -5
  36. package/src/project-rules.ts +6 -117
  37. package/src/report-html.ts +1 -1
  38. package/src/report-renderers.ts +98 -7
  39. package/src/rule-list.ts +23 -2
  40. package/src/rules.ts +11 -12
  41. package/src/safety-rules.ts +16 -6
  42. package/src/scoring.ts +43 -5
  43. package/src/security-flow-rules.ts +533 -0
  44. package/src/sensitive-data-rules.ts +138 -2
  45. package/src/static-analysis-redundant-rules.ts +411 -0
  46. package/src/test-block-rules.ts +115 -53
  47. package/src/test-fixtures.ts +50 -9
  48. package/src/types.ts +79 -2
package/src/analyser.ts CHANGED
@@ -5,19 +5,21 @@ import { existsSync, readFileSync } from "node:fs";
5
5
  import { cwd } from "node:process";
6
6
  import { basename, join } from "node:path";
7
7
  import { applyBaseline, dedupeFindings, DEFAULT_BASELINE, recordHistory, writeBaseline } from "./baseline.ts";
8
+ import { changedRegionScope, filterChangedFindings } from "./changed-regions.ts";
8
9
  import { loadConfig, optionNumber, ruleEnabled, ruleSeverity, threshold } from "./config.ts";
9
10
  import { VERSION } from "./constants.ts";
10
11
  import { absolutize, discoverSources, displayPath, type SourceFile } from "./discovery.ts";
11
12
  import { makeFinding } from "./findings.ts";
12
- import { changedFiles, finding } from "./findings-helpers.ts";
13
+ import { finding } from "./findings-helpers.ts";
13
14
  import { commentRecords } from "./comment-scanner.ts";
14
- import { analyseArchitectureRules, analyseTestAdequacyRules, buildProjectIndex, exportedSurface, isProductionSourcePath, isTestPath, type ProjectSource } from "./project-rules.ts";
15
+ import { analyseArchitectureRules, buildProjectIndex, isProductionSourcePath, isTestPath, type ProjectSource } from "./project-rules.ts";
15
16
  import { analyseBlockRules, type BlockRuleContext, blockRuleContext, type FunctionBlock, functionBlocks, parameterNames } from "./blocks.ts";
16
17
  import { analyseClassRules, analyseAcronymCase, analyseInconsistentCasing, analyseInterfaceFields, collectDeclaredIdentifiers } from "./class-rules.ts";
17
18
  import { analyseDeadCode, analyseUnreachable, analyseUnusedImports } from "./dead-code-rules.ts";
18
19
  import { analyseCommentQualityRules } from "./comment-rules.ts";
19
20
  import { analyseDocRules, analyseFileOverviewDoc, analyseInterfaceDocs } from "./doc-rules.ts";
20
21
  import { analyseLineRules } from "./line-rules.ts";
22
+ import { analyseSecurityFlow } from "./security-flow-rules.ts";
21
23
  import { pushBooleanPrefixAt, pushIdentifierQualityAt, pushNegativeBooleanAt, pushShortVariableAt } from "./naming-pushers.ts";
22
24
  import { analyseTestBlock } from "./test-block-rules.ts";
23
25
  import { analyseGithubActionsRules } from "./github-actions-rules.ts";
@@ -25,7 +27,7 @@ import { analyseProjectConfigRules } from "./project-config-rules.ts";
25
27
  import { scoreReport, summarize } from "./scoring.ts";
26
28
  import { analyseSensitiveData } from "./sensitive-data-rules.ts";
27
29
  import { maskNonCode, maskTemplateLiteralBodies, parseDiagnostics } from "./source-text.ts";
28
- import type { AnalysisOptions, AnalysisReport, Config, Finding, RunDiagnostic } from "./types.ts";
30
+ import type { AnalysisOptions, AnalysisReport, Config, Finding, RunDiagnostic, SkippedPath } from "./types.ts";
29
31
 
30
32
  /**
31
33
  * Analyse the configured paths and return the stable gruff.analysis.v2 report contract.
@@ -38,7 +40,7 @@ export function analyse(options: AnalysisOptions): AnalysisReport {
38
40
  const config = loadConfig(projectRoot, options);
39
41
  const diagnostics: RunDiagnostic[] = [];
40
42
  const discovery = discoverSources(projectRoot, options, config);
41
- filterDiffSources(discovery, options);
43
+ const changedScope = changedRegionScope(options);
42
44
  pushMissingPathDiagnostics(discovery.missingPaths, diagnostics);
43
45
 
44
46
  const scanned = scanDiscoveredSources(discovery.files, config, diagnostics);
@@ -47,12 +49,13 @@ export function analyse(options: AnalysisOptions): AnalysisReport {
47
49
  ...analyseProjectIndex(scanned.projectSources, config).filter((finding) => ruleEnabled(config, finding.ruleId)),
48
50
  ]);
49
51
  const baselineResult = applyBaselineOptions(projectRoot, options, allFindings);
52
+ const changedResult = filterChangedFindings(baselineResult.findings, changedScope, scanned.sources);
50
53
 
51
54
  if (options.historyFile) {
52
- recordHistory(projectRoot, options.historyFile, baselineResult.findings, diagnostics);
55
+ recordHistory(projectRoot, options.historyFile, changedResult.findings, diagnostics);
53
56
  }
54
57
 
55
- return buildAnalysisReport(projectRoot, options, discovery, diagnostics, baselineResult);
58
+ return buildAnalysisReport(projectRoot, options, discovery, diagnostics, { ...baselineResult, findings: changedResult.findings }, changedResult.suppressedCount);
56
59
  }
57
60
 
58
61
  function buildAnalysisReport(
@@ -61,6 +64,7 @@ function buildAnalysisReport(
61
64
  discovery: DiscoverySummary,
62
65
  diagnostics: RunDiagnostic[],
63
66
  baselineResult: BaselineApplication,
67
+ suppressedCount?: number,
64
68
  ): AnalysisReport {
65
69
  const findings = baselineResult.findings;
66
70
  return {
@@ -76,10 +80,12 @@ function buildAnalysisReport(
76
80
  paths: {
77
81
  analysedFiles: discovery.files.length,
78
82
  ignoredPaths: discovery.ignoredPaths,
83
+ skipped: discovery.skipped,
79
84
  missingPaths: discovery.missingPaths,
80
85
  },
81
86
  diagnostics,
82
87
  findings,
88
+ ...(suppressedCount === undefined ? {} : { suppressedCount }),
83
89
  score: scoreReport(findings),
84
90
  ...(baselineResult.baseline ? { baseline: baselineResult.baseline } : {}),
85
91
  };
@@ -90,6 +96,7 @@ function buildAnalysisReport(
90
96
  interface DiscoverySummary {
91
97
  files: SourceFile[];
92
98
  ignoredPaths: string[];
99
+ skipped: SkippedPath[];
93
100
  missingPaths: string[];
94
101
  }
95
102
 
@@ -98,6 +105,7 @@ interface DiscoverySummary {
98
105
  interface SourceScanResult {
99
106
  findings: Finding[];
100
107
  projectSources: ProjectSource[];
108
+ sources: Map<string, { file: SourceFile; source: string }>;
101
109
  }
102
110
 
103
111
  /*
@@ -117,16 +125,6 @@ interface BaselineSelection {
117
125
  source: string;
118
126
  }
119
127
 
120
- // Mutates `discovery.files` in place to retain only paths that changed against the diff base.
121
- // Required when `--diff` is set so the scan does not waste time on unchanged files; no-op otherwise.
122
- function filterDiffSources(discovery: DiscoverySummary, options: AnalysisOptions): void {
123
- if (!options.diff) {
124
- return;
125
- }
126
- const changed = changedFiles(options.diff);
127
- discovery.files = discovery.files.filter((file) => changed.has(file.displayPath));
128
- }
129
-
130
128
  // Emits a `missing-path` diagnostic per path that the user requested but discovery could not
131
129
  // resolve. Diagnostics force a non-zero exit (see `exitFor`); never throws - partial scans should still report.
132
130
  function pushMissingPathDiagnostics(missingPaths: string[], diagnostics: RunDiagnostic[]): void {
@@ -147,9 +145,11 @@ function pushMissingPathDiagnostics(missingPaths: string[], diagnostics: RunDiag
147
145
  function scanDiscoveredSources(files: SourceFile[], config: Config, diagnostics: RunDiagnostic[]): SourceScanResult {
148
146
  const findings: Finding[] = [];
149
147
  const projectSources: ProjectSource[] = [];
148
+ const sources = new Map<string, { file: SourceFile; source: string }>();
150
149
  for (const file of files) {
151
150
  try {
152
151
  const source = readFileSync(file.absolutePath, "utf8");
152
+ sources.set(file.displayPath, { file, source });
153
153
  if (shouldRetainProjectSource(file, source)) {
154
154
  projectSources.push(projectSource(file, source));
155
155
  }
@@ -164,7 +164,7 @@ function scanDiscoveredSources(files: SourceFile[], config: Config, diagnostics:
164
164
  });
165
165
  }
166
166
  }
167
- return { findings, projectSources };
167
+ return { findings, projectSources, sources };
168
168
  }
169
169
 
170
170
  // Retains production files for exported-surface checks, tests for central-suite import coverage,
@@ -178,8 +178,7 @@ function shouldRetainProjectSource(file: SourceFile, source: string): boolean {
178
178
  function projectSource(file: SourceFile, source: string): ProjectSource {
179
179
  const lines = source.split(/\r?\n/);
180
180
  const templateMaskedLines = hasImportSyntaxCandidate(source) ? maskTemplateLiteralBodies(source).split(/\r?\n/) : lines;
181
- const surface = isProductionSourcePath(file.displayPath) ? exportedSurface(source) : undefined;
182
- return { file, lines, templateMaskedLines, ...(surface ? { exportedSurface: surface } : {}) };
181
+ return { file, lines, templateMaskedLines };
183
182
  }
184
183
 
185
184
  // Cheap prefilter for files that might contain real import/export edges or fixture strings that
@@ -284,23 +283,17 @@ function analyseProjectIndex(projectSources: ProjectSource[], config: Config): F
284
283
  const index = buildProjectIndex(projectSources);
285
284
  const findings: Finding[] = [];
286
285
  analyseArchitectureRules(index, config, findings);
287
- analyseTestAdequacyRules(index, findings);
288
286
  return findings;
289
287
  }
290
288
 
291
289
  /*
292
- * Per-file text-pillar rules run before script-only rules because config, workflow, CSS, and
290
+ * Per-file text-pillar rules run before script-only rules because config, workflow, and
293
291
  * secret surfaces are not TypeScript. The order is a stable baseline contract: reshuffling these
294
292
  * checks changes same-line finding order for machine reports.
295
293
  */
296
294
  function analyseTextRules(file: SourceFile, source: string, config: Config, findings: Finding[]): void {
297
295
  const lines = lineCount(source);
298
- if (isCssPath(file.displayPath)) {
299
- const stylesheetThreshold = threshold(config, "size.stylesheet-length", 1500);
300
- if (lines > stylesheetThreshold) {
301
- findings.push(finding({ ruleId: "size.stylesheet-length", message: `Stylesheet has ${lines} lines, above the threshold of ${stylesheetThreshold}.`, file, line: 1, severity: ruleSeverity(config, "size.stylesheet-length", "warning"), pillar: "size" }));
302
- }
303
- } else if (!isGeneratedLockfile(file.displayPath)) {
296
+ if (!isGeneratedLockfile(file.displayPath)) {
304
297
  const fileLengthThreshold = threshold(config, "size.file-length", 750);
305
298
  if (lines > fileLengthThreshold) {
306
299
  findings.push(finding({ ruleId: "size.file-length", message: `File has ${lines} lines, above the threshold of ${fileLengthThreshold}.`, file, line: 1, severity: ruleSeverity(config, "size.file-length", "warning"), pillar: "size" }));
@@ -312,12 +305,6 @@ function analyseTextRules(file: SourceFile, source: string, config: Config, find
312
305
  analyseProjectConfigRules(file, source, findings);
313
306
  }
314
307
 
315
- // CSS paths use a dedicated size rule (`size.stylesheet-length`) so stylesheets can have a
316
- // different threshold and message from generic source files.
317
- function isCssPath(displayPath: string): boolean {
318
- return displayPath.toLowerCase().endsWith(".css");
319
- }
320
-
321
308
  // Counts the same logical lines as `source.split(/\r?\n/)` without allocating the full line array.
322
309
  function lineCount(source: string): number {
323
310
  let count = 1;
@@ -345,9 +332,10 @@ function analyseTypeScriptRules(file: SourceFile, source: string, config: Config
345
332
  const blocks = functionBlocks(source, codeSource);
346
333
  const comments = commentRecords(source);
347
334
  analyseFileOverviewDoc(file, source, findings);
348
- analyseBlocks(file, blocks, config, findings);
335
+ analyseBlocks(file, source, codeSource, blocks, config, findings);
349
336
  analyseUnusedImports(file, codeSource, source, findings);
350
337
  analyseLineRules(file, source, codeSource, config, findings);
338
+ analyseSecurityFlow(file, source, findings);
351
339
  analyseUnreachable(file, codeSource, findings);
352
340
  analyseDocRules(file, source, codeSource, findings);
353
341
  analyseInterfaceDocs(file, source, codeSource, findings);
@@ -365,13 +353,13 @@ function analyseTypeScriptRules(file: SourceFile, source: string, config: Config
365
353
  // separately so blocks.ts can stay independent of the naming-pusher and test-block-rule modules;
366
354
  // the per-rule emission order from `analyseBlockRules` is the stable fingerprint contract every
367
355
  // Finding depends on for deterministic baseline matching.
368
- function analyseBlocks(file: SourceFile, blocks: FunctionBlock[], config: Config, findings: Finding[]): void {
356
+ function analyseBlocks(file: SourceFile, source: string, codeSource: string, blocks: FunctionBlock[], config: Config, findings: Finding[]): void {
369
357
  for (const block of blocks) {
370
358
  const context = blockRuleContext(file, block, config, findings);
371
359
  analyseBlockRules(context);
372
360
  pushParameterNamingFindings(context);
373
361
  if (block.isTest) {
374
- analyseTestBlock(file, block, config, findings);
362
+ analyseTestBlock(file, block, findings, { source, codeSource, startLine: 1 });
375
363
  }
376
364
  }
377
365
  }
@@ -384,7 +372,9 @@ function pushParameterNamingFindings(context: BlockRuleContext): void {
384
372
  const line = context.block.declarationLine;
385
373
  const params = parameterNames(context.block.params);
386
374
  for (const parameter of params) {
387
- pushShortVariableAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
375
+ if (!isComparatorShortParameter(context, params, parameter.name)) {
376
+ pushShortVariableAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
377
+ }
388
378
  pushIdentifierQualityAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
389
379
  if (isBooleanParameter(parameter.raw)) {
390
380
  pushBooleanPrefixAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
@@ -396,6 +386,27 @@ function pushParameterNamingFindings(context: BlockRuleContext): void {
396
386
  }
397
387
  }
398
388
 
389
+ // `(a, b)` is a conventional comparator pair when the callable is explicitly shaped like sorting.
390
+ // Keep the exemption narrow so arbitrary two-parameter helpers still need domain names.
391
+ function isComparatorShortParameter(context: BlockRuleContext, params: Array<{ name: string; raw: string }>, name: string): boolean {
392
+ const names = params.map((parameter) => parameter.name);
393
+ if (names.length !== 2 || names[0] !== "a" || names[1] !== "b" || (name !== "a" && name !== "b")) {
394
+ return false;
395
+ }
396
+ return isComparatorCallable(context.block.name, context.block.codeBody);
397
+ }
398
+
399
+ // Comparator-shaped callables are either named for ordering (`compare*`, `*Comparator`, `byName`) or
400
+ // their body performs the standard locale/numeric ordering expression over both parameters.
401
+ function isComparatorCallable(name: string, codeBody: string): boolean {
402
+ return (
403
+ /^(?:compare[A-Z0-9_]?|.*Comparator$|by[A-Z])/.test(name) ||
404
+ /\.localeCompare\s*\(/.test(codeBody) ||
405
+ /\breturn\s+a\b[\s\S]*?(?:-\s*b\b|[<>]=?\s*b\b)/.test(codeBody) ||
406
+ /\breturn\s+b\b[\s\S]*?(?:-\s*a\b|[<>]=?\s*a\b)/.test(codeBody)
407
+ );
408
+ }
409
+
399
410
  // Generic-parameter rule is context-gated: only fires when the surrounding function is itself
400
411
  // large enough to deserve attention (long, complex, or many parameters). Keeps noise down on
401
412
  // trivial helpers that legitimately accept a `value` argument.
package/src/blocks.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Function-block parsing + per-block rule pass (size, complexity, NPath, god-function, doc,
1
+ // Function-block parsing + per-block rule pass (size, complexity, doc,
2
2
  // empty-function, unused-parameter, redundant-variable, useless-return) and the block-anchored
3
3
  // finding factories. Pulls the parser and the rules that operate on parsed blocks out of cli.ts.
4
4
  import { ruleSeverity, threshold } from "./config.ts";
@@ -9,8 +9,6 @@ import { escapeRegex, isGenericName, lineOffset } from "./findings-helpers.ts";
9
9
  import { countMatches } from "./text-scans.ts";
10
10
  import type { Config, Finding, Pillar, Severity } from "./types.ts";
11
11
 
12
- const NPATH_CAP = 1_000_000;
13
-
14
12
  // Parsed callable body shared by every block-level rule (size, complexity, naming, docs). The
15
13
  // `body` / `codeBody` split (raw text vs. comment-masked) lets rules choose between literal
16
14
  // inspection and code-only matching without re-running the masker.
@@ -65,13 +63,6 @@ export interface BlockRuleContext {
65
63
  functionBody: string;
66
64
  }
67
65
 
68
- // NPath approximation result. `isCapped: true` signals the value hit `NPATH_CAP` and is a lower
69
- // bound - the finding message uses this to mark capped values rather than implying precision.
70
- export interface NpathResult {
71
- value: number;
72
- isCapped: boolean;
73
- }
74
-
75
66
  // Input bundle for `blockFinding()`. The block reference replaces the explicit line: the builder
76
67
  // reads `block.startLine` and `block.name` so the stable finding anchor and symbol metadata stay
77
68
  // in sync with the parsed callable across every block-level rule.
@@ -100,7 +91,7 @@ export function blockFinding(args: BlockFindingArgs): Finding {
100
91
  }
101
92
 
102
93
  // Block-anchored variant that ships rule-specific metadata. Confidence defaults to "medium"
103
- // because metadata-carrying rules (size, complexity, NPath) report measurements rather than
94
+ // because metadata-carrying rules (e.g. test-quality magic-number) report measurements rather than
104
95
  // definitive defects; the metadata payload is part of each rule's stable fingerprint contract.
105
96
  export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Finding {
106
97
  return makeFinding({ ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.block.startLine, severity: args.severity, pillar: args.pillar, confidence: "medium", symbol: args.block.name, metadata: args.metadata });
@@ -130,8 +121,6 @@ export function analyseBlockRules(context: BlockRuleContext): void {
130
121
  pushParameterCountFinding(context);
131
122
  pushCyclomaticFinding(context);
132
123
  pushCognitiveFinding(context);
133
- pushNpathFinding(context);
134
- pushGodFunctionFinding(context);
135
124
  pushGenericFunctionFinding(context);
136
125
  pushMissingFunctionDocFinding(context);
137
126
  pushEmptyFunctionFinding(context);
@@ -175,41 +164,6 @@ function pushCognitiveFinding(context: BlockRuleContext): void {
175
164
  }
176
165
  }
177
166
 
178
- // Default threshold 200. NPath is the number of possible execution paths; the message marks
179
- // `capped` when the calculation hit `NPATH_CAP` so reviewers know it's a lower bound. Reports `complexity.npath`.
180
- function pushNpathFinding(context: BlockRuleContext): void {
181
- const npath = approximateNpath(context.functionBody);
182
- const npathThreshold = threshold(context.config, "complexity.npath", 200);
183
- if (npath.value > npathThreshold) {
184
- context.findings.push(npathFinding(context, npath, npathThreshold, ruleSeverity(context.config, "complexity.npath", "warning")));
185
- }
186
- }
187
-
188
- /*
189
- * Stable `complexity.npath` finding factory. `capped` and `cap` are surfaced in metadata so
190
- * downstream tooling can distinguish "5000" from "≥ NPATH_CAP" - both would render as the same
191
- * value otherwise.
192
- */
193
- function npathFinding(context: BlockRuleContext, npath: NpathResult, thresholdValue: number, severity: Severity): Finding {
194
- return blockFindingWithMetadata({
195
- ruleId: "complexity.npath",
196
- message: `Function \`${context.block.name}\` has approximate NPath complexity ${npath.value} above the threshold of ${thresholdValue} (capped at ${NPATH_CAP}).`,
197
- file: context.file,
198
- block: context.block,
199
- severity,
200
- pillar: "complexity",
201
- metadata: { npath: npath.value, capped: npath.isCapped, cap: NPATH_CAP, threshold: thresholdValue },
202
- });
203
- }
204
-
205
- // Combined-shape rule: long (>45 lines) AND complex (cyclomatic >10). Thresholds are hard-coded
206
- // because "god function" is a design heuristic, not a per-rule tunable. Reports `design.god-function`.
207
- function pushGodFunctionFinding(context: BlockRuleContext): void {
208
- if (context.block.lineCount > 45 && context.cyclomatic > 10) {
209
- context.findings.push(blockFinding({ ruleId: "design.god-function", message: `Function \`${context.block.name}\` is both long and complex.`, file: context.file, block: context.block, severity: "warning", pillar: "design" }));
210
- }
211
- }
212
-
213
167
  // Names like `process`, `handle`, `run` from `config.bannedGenericNames`. The list is user-configurable;
214
168
  // the rule body itself just consults the config. Reports `naming.generic-function`.
215
169
  function pushGenericFunctionFinding(context: BlockRuleContext): void {
@@ -241,10 +195,28 @@ function pushEmptyFunctionFinding(context: BlockRuleContext): void {
241
195
  return;
242
196
  }
243
197
  if (isEmptyFunctionBody(context.block.codeBody)) {
198
+ if (isDocumentedEmptyTestDouble(context)) {
199
+ return;
200
+ }
244
201
  context.findings.push(blockFinding({ ruleId: "waste.empty-function", message: `Function \`${context.block.name}\` has no executable body.`, file: context.file, block: context.block, severity: "advisory", pillar: "maintainability" }));
245
202
  }
246
203
  }
247
204
 
205
+ // Empty test doubles can be required by external interfaces when the body carries a rationale.
206
+ function isDocumentedEmptyTestDouble(context: BlockRuleContext): boolean {
207
+ return isTestOrFixturePath(context.file.displayPath) && hasEmptyTestDoubleRationale(context.block.body);
208
+ }
209
+
210
+ // Test and fixture paths are the only places where empty protocol stubs are normal.
211
+ function isTestOrFixturePath(path: string): boolean {
212
+ return /(?:^|\/)(?:__tests__|tests?|spec|__fixtures__|fixtures?|testdata)\//.test(path) || /\.(?:test|spec)\.[cm]?[tj]sx?$/.test(path);
213
+ }
214
+
215
+ // Requires an explicit no-op/stub/fake rationale so real empty implementations still surface.
216
+ function hasEmptyTestDoubleRationale(source: string): boolean {
217
+ return /(?:\/\/|\/\*)/.test(source) && /\b(?:intentional no-op|test double|stub|fake|interface contract)\b/i.test(source);
218
+ }
219
+
248
220
  // `_`-prefixed parameters are exempted (the standard "intentionally unused" convention).
249
221
  // Reports `waste.unused-parameter` for parameter names that never appear in the callable body.
250
222
  function pushUnusedParameterFindings(context: BlockRuleContext): void {
@@ -354,25 +326,6 @@ function pushUselessReturnFindings(context: BlockRuleContext): void {
354
326
  }
355
327
  }
356
328
 
357
- // Approximation: each decision keyword (`if`, `case`, `catch`, loops) and short-circuit operator
358
- // doubles the count. Optional chaining is stripped first so `a?.b` and `??` don't inflate the
359
- // signal. Capped at `NPATH_CAP` - the `capped` flag tells callers to report the value as ≥, not =.
360
- export function approximateNpath(source: string): NpathResult {
361
- let pathCount = 1;
362
- let isCapped = false;
363
- const normalized = source.replace(/\?\./g, "").replace(/\?\?/g, "");
364
- const decisionCount = countMatches(normalized, /\b(if|else if|case|catch|for|while)\b|\?|&&|\|\|/g);
365
- for (let index = 0; index < decisionCount; index += 1) {
366
- pathCount *= 2;
367
- if (pathCount >= NPATH_CAP) {
368
- pathCount = NPATH_CAP;
369
- isCapped = true;
370
- break;
371
- }
372
- }
373
- return { value: pathCount, isCapped };
374
- }
375
-
376
329
  // Strips line and block comments before measuring - a body containing only documentation is still
377
330
  // considered empty for the `waste.empty-function` check, since no executable statements run.
378
331
  function isEmptyFunctionBody(source: string): boolean {
@@ -716,9 +669,9 @@ export function hasAssertion(source: string): boolean {
716
669
  return false;
717
670
  }
718
671
 
719
- // Setup-bloat metric: counts non-ignorable lines preceding the first assertion in the body. Stops
720
- // as soon as an assertion appears, so the value never overshoots the actual prologue length used
721
- // by `test-quality.setup-bloat`.
672
+ // Counts non-ignorable lines preceding the first assertion in a test body. Stops as soon as an
673
+ // assertion appears, so the value never overshoots the actual prologue length. Used by
674
+ // `docs.fixture-purpose-missing` to size test-setup fixtures.
722
675
  export function setupLineCount(source: string): number {
723
676
  let count = 0;
724
677
  for (const line of functionBodyContent(source).split(/\r?\n/)) {