@blundergoat/gruff-ts 0.3.0 → 0.3.2

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## v0.3.2 - 2026-06-09
4
+
5
+ - **Agent-hook contract v1** - adds `gruff-ts hook` and `gruff-ts hook --capabilities --format=json`, advertising `gruff.hook.v1` with `flagOrder:"any"`. Hook JSON uses the cross-analyzer contract fields (`file`, `scope`, `suppressed.count`, `ignored.paths`, `config.error`) with non-null remediation, stable hook identities, and machine-readable threshold metadata. Hook mode exits `0` when analysis runs, omits file/project-scope findings under changed-region attribution, and uses stable identity for baseline/diff new-only filtering (`--diff unstaged` compares against the index, `suppressed.count` never double-counts a re-emitted finding, and distinct project-scope findings such as separate import cycles anchored to one file keep distinct identities so baselining one never suppresses another). Operational failures (missing/malformed baseline, `--diff`/`--since` outside a git repo) report in-band as `config.error` with exit `2` rather than crashing. The conformance tests cover capabilities, scopes/enums, remediation, threshold metadata, stable identity across line/value changes (including multiple same-rule findings in one file and distinct import cycles sharing an anchor file), baseline and diff new-only, operational-failure JSON, flag ordering, advisory exit, ignored paths, and config-error JSON. Existing `analyse` / `summary` / `report` schema versions and exit semantics are unchanged. (`src/hook-contract.ts`, `src/cli-program.ts`, `src/hook-contract.test.ts`)
6
+ - **Changed-region symbol scope drops inherited file-wide findings** - `--changed-scope symbol` now suppresses file-wide and file-aggregate findings when the changed range does not touch their anchor/span, so inherited debt such as `size.file-length` is counted in `suppressedCount` instead of reported on unrelated edits. Use `--changed-scope file` for CI workflows that intentionally want every finding from a touched file, including deletion-only edits. Full scans still report every file-wide finding. No severity, threshold, rule-id, or pillar change. (`src/changed-regions.ts`, `src/changed-region-scope.test.ts`, `src/changed-region-contract.test.ts`)
7
+ - **Threshold findings expose reviewable measurements** - `size.file-length`, `size.function-length`, `size.parameter-count`, `complexity.cyclomatic`, `complexity.cognitive`, `sensitive-data.high-entropy-string`, and `sensitive-data.hardcoded-env-value` now carry additive `measured`/`threshold` measurement metadata, and block-anchored findings carry `endLine` spans so hook output can attribute symbol-scope findings without message parsing. `size.file-length` also gets finding-level remediation from the descriptor text. Existing fingerprints stay stable. (`src/analyser.ts`, `src/blocks.ts`, `src/findings.ts`, `src/sensitive-data-rules.ts`)
8
+
9
+ ## v0.3.1 - 2026-06-03
10
+
11
+ - **JSON finding path alias and stable identity** - `analyse --format=json` and `report --format=json` now emit canonical `findings[].file` alongside the existing `findings[].filePath`; `filePath` is deprecated and will be removed in the next release. Findings also carry `stableIdentity`, a line-insensitive 16-hex identity for external diff tooling. Existing `fingerprint` values, baselines, SARIF fingerprints, dashboard data, and in-memory `filePath` consumers are unchanged.
12
+ - **Test-quality static-analysis redundancy rule and low-signal retirements** - adds `test-quality.static-analysis-redundant-test`, an advisory rule for tests that mostly assert statically knowable code shape instead of behaviour (for example `typeof exportedFunction === "function"`, direct `instanceof` construction, or non-null assertions against visible non-nullable return declarations). Findings include static-proof metadata and keep runtime payload/callable assertions quiet. The low-signal `test-quality.missing-nearby-test` project-layout rule and `test-quality.setup-bloat` setup-size rule are removed from the catalogue and config defaults; stale config entries are ignored. (`src/test-block-rules.ts`, `src/project-rules.ts`, `src/rules.ts`)
13
+ - **Per-rule `severity:` overrides now apply to the descriptor-driven line rules** - the `security.*`, `modernisation.*`, and `waste.*` regex line checks (for example `security.new-function`, `security.eval-call`) emitted findings with a hardcoded severity, so a project's `rules.<id>.severity` override in `.gruff-ts.yaml` was silently ignored. `pushPatternCheckFindings` now resolves severity through `ruleSeverity`, like every other pillar; the descriptor severity stays the default. A project running a legitimate `new Function`/eval shape (such as a transpile-then-execute test loader) can set `security.new-function: { severity: warning }` to keep the finding visible without failing an `--fail-on error` gate. No default severity, schema, or `Finding` shape change. (`src/line-rules.ts`, `src/security-and-config.test.ts`)
14
+
3
15
  ## v0.3.0 - 2026-05-30
4
16
 
5
17
  0.3.0 release. Changes since 0.2.0: three breaking rule removals (`complexity.npath`; `size.stylesheet-length` with CSS dropped from scanned file types; and the `design.god-function` composite), region-scoped incremental analysis, authoritative `paths.ignore` with a new `check-ignore` command, sensitive-data PHI/GCP detection, named config profiles with `extends:` inheritance, and a documentation reframe around gruff's purpose - governing AI-generated code so a human who did not write it can sign off on it.
package/CONTRIBUTING.md CHANGED
@@ -47,7 +47,7 @@ The runtime lives under `src/`:
47
47
  packs, fixtures, reports, and CLI surfaces.
48
48
 
49
49
  Keep changes small and local. Do not add runtime dependencies beyond
50
- `commander` and `tsx` unless that direction is explicitly accepted first.
50
+ `commander`, `tsx`, and `typescript` unless that direction is explicitly accepted first.
51
51
 
52
52
  ## Rules For Rule Changes
53
53
 
package/README.md CHANGED
@@ -20,11 +20,11 @@ Used as a hook on an agent's output, gruff-ts is a forcing function rather than
20
20
 
21
21
  | Field | Value |
22
22
  | --- | --- |
23
- | Release line | Published `0.3.0` package line |
23
+ | Release line | Published `0.3.2` package line |
24
24
  | Runtime | Node.js `22+` |
25
25
  | Package | `@blundergoat/gruff-ts` |
26
26
  | Binary | `gruff-ts` |
27
- | Rule catalogue | 121 rules across 11 pillars |
27
+ | Rule catalogue | 120 rules across 11 pillars |
28
28
  | Primary config | `.gruff-ts.yaml`; `.gruff.json`, `.gruff.yaml`, and `.gruff.yml` are fallback files |
29
29
  | Analysis schema | `gruff.analysis.v2` |
30
30
  | Baseline schema | `gruff.baseline.v1` |
@@ -223,7 +223,7 @@ Semantics:
223
223
 
224
224
  ## Rules And Pillars
225
225
 
226
- The current catalogue contains 121 rules:
226
+ The current catalogue contains 120 rules:
227
227
 
228
228
  | Pillar | Rules |
229
229
  | --- | ---: |
@@ -237,12 +237,24 @@ The current catalogue contains 121 rules:
237
237
  | `security` | 29 |
238
238
  | `sensitive-data` | 10 |
239
239
  | `size` | 3 |
240
- | `test-quality` | 15 |
240
+ | `test-quality` | 14 |
241
241
 
242
242
  Use `npx gruff-ts list-rules --format=json` for exact rule IDs, severities, confidence levels, remediation text, thresholds, and options.
243
243
 
244
244
  ## Baselines And Changed-Code Scans
245
245
 
246
+ For editor and coding-agent feedback, prefer the analyzer-owned hook contract:
247
+
248
+ ```bash
249
+ npx gruff-ts hook --format=json --changed-ranges "3-3,8-10" src/foo.ts
250
+ npx gruff-ts hook --capabilities --format=json
251
+ ```
252
+
253
+ `hook` emits `gruff.hook.v1` JSON with normalized `file`, `scope`, `suppressed.count`,
254
+ `ignored.paths`, non-null `remediation`, stable identities, and threshold metadata. Hook mode is
255
+ advisory: findings exit `0`; operational failures such as invalid config exit `2` and are reported
256
+ in `config.error`.
257
+
246
258
  Baselines suppress reviewed findings by stable fingerprint:
247
259
 
248
260
  ```bash
@@ -268,6 +280,10 @@ npx gruff-ts analyse --format=json --since HEAD src/foo.ts
268
280
  git diff | npx gruff-ts analyse --format=json --diff -
269
281
  ```
270
282
 
283
+ Use `--changed-scope file` when a CI workflow intentionally wants every finding from touched
284
+ files, including file-wide metrics such as `size.file-length`. The default `symbol` scope keeps
285
+ the coding-agent feedback focused on the changed line or enclosing declaration.
286
+
271
287
  JSON output keeps the normal `findings` array and adds `suppressedCount` when changed-region filtering is active.
272
288
 
273
289
  ## Dashboard
@@ -316,7 +332,6 @@ Source lives under `src/`: `src/cli.ts` is the bootstrap, `src/cli-program.ts` o
316
332
  - [Configuration](docs/configuration.md)
317
333
  - [Rules catalogue](docs/rules.md)
318
334
  - [Reports and CI](docs/reports-and-ci.md)
319
- - [Release checklist](docs/releasing.md)
320
335
  - [Contributing](CONTRIBUTING.md)
321
336
  - [Security](SECURITY.md)
322
337
 
package/SECURITY.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  | Version | Supported |
6
6
  | --- | --- |
7
- | 0.1.x | Yes |
7
+ | 0.3.x | Yes |
8
8
 
9
9
  ## Reporting A Vulnerability
10
10
 
package/docs/README.md CHANGED
@@ -11,7 +11,6 @@ Use these docs with the top-level README for the stable user-facing surface.
11
11
  - [Output Formats](output-formats.md) - text, JSON, HTML, Markdown, GitHub annotations, hotspot, and SARIF.
12
12
  - [CI Integration](ci-integration.md) - GitHub Actions, SARIF upload, baselines, and diff scans.
13
13
  - [Dashboard](dashboard.md) - local dashboard flags and safety model.
14
- - [Releasing](releasing.md) - release checks and packaging notes.
15
14
 
16
15
  ## Extra Docs
17
16
 
@@ -6,12 +6,24 @@ gruff-ts is built to govern AI-generated code (see [Philosophy](philosophy.md) f
6
6
 
7
7
  A coding agent will rewrite code until the checks pass. gruff-ts turns that into leverage: run it on the agent's change and gate on the result, so the agent has to resolve findings - add the missing doc comment, cut the unverifiable branching, drop the unsafe call, replace the mock-only test - before the change reaches you. What lands is already shaped for sign-off.
8
8
 
9
- The gate is the exit code:
9
+ For CI-style gates, `analyse` owns the exit code:
10
10
 
11
11
  - `0` - no finding met the `--fail-on` level; the change passes.
12
12
  - `1` - at least one finding met `--fail-on`; the agent must fix and re-run.
13
13
  - `2` - fatal (bad input, parse or config error); stop and surface it.
14
14
 
15
+ For editor or PostToolUse feedback, use the analyzer-owned hook contract instead:
16
+
17
+ ```bash
18
+ gruff-ts hook --format json --changed-ranges "12-40,88-90" src/foo.ts
19
+ gruff-ts hook --capabilities --format json
20
+ ```
21
+
22
+ `hook` emits `gruff.hook.v1` JSON with normalized `file`, `scope`, `suppressed.count`,
23
+ `ignored.paths`, non-null `remediation`, stable identities, and machine-readable threshold
24
+ metadata. Hook mode is advisory: findings exit `0`; config failures are returned in
25
+ `config.error` and exit `2`.
26
+
15
27
  ## Scan the change, not the repo
16
28
 
17
29
  > **Goal:** govern only the code the agent changed, not the whole repo - so the agent resolves findings in its own diff and a clean change is never blocked by pre-existing findings elsewhere.
@@ -35,7 +47,7 @@ npx gruff-ts analyse --changed-ranges "12-40,88-90" src/foo.ts --fail-on=warning
35
47
  git diff | npx gruff-ts analyse --diff - --fail-on=warning
36
48
  ```
37
49
 
38
- Changed-region scans keep only findings attributable to the changed hunk or its enclosing symbol, so the agent fixes its own work instead of inheriting the whole backlog.
50
+ Changed-region scans keep only findings attributable to the changed hunk or its enclosing symbol, so the agent fixes its own work instead of inheriting the whole backlog. In `hook` mode, whole-file metrics such as `size.file-length` are omitted under changed-region attribution and counted in `suppressed.count`; they return only in full-scan hook output or when `--baseline` / `--diff` shows their stable identity is new. In `analyse`, use `--changed-scope file` for CI jobs that intentionally want every finding from a touched file.
39
51
 
40
52
  ## Respect the project's ignore policy
41
53
 
@@ -254,7 +254,4 @@ rules:
254
254
  size.function-length:
255
255
  threshold: 30
256
256
  severity: warning
257
- test-quality.setup-bloat:
258
- threshold: 12
259
- severity: advisory
260
257
  ```
package/docs/rules.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Rules
2
2
 
3
- `gruff-ts` exposes 121 rules across 11 pillars. This list is generated from the
3
+ `gruff-ts` exposes 120 rules across 11 pillars. This list is generated from the
4
4
  public rule catalogue used by `gruff-ts list-rules`; severity, confidence,
5
5
  thresholds, and option names are the defaults before project config overrides.
6
6
 
@@ -30,7 +30,7 @@ gruff-ts list-rules --format=json
30
30
  - security: 29
31
31
  - sensitive-data: 10
32
32
  - size: 3
33
- - test-quality: 15
33
+ - test-quality: 14
34
34
 
35
35
  ## Complexity
36
36
 
@@ -54,9 +54,10 @@ gruff-ts list-rules --format=json
54
54
  - `docs.fixture-purpose-missing` (advisory; medium confidence): Flags large or scanner-relevant fixtures without a nearby purpose comment.
55
55
  - `docs.magic-threshold-without-rationale` (advisory; medium confidence): Flags threshold-like numeric values without a nearby rationale comment.
56
56
  - `docs.missing-error-behavior-doc` (advisory; medium confidence): Flags commented functions whose error behavior is not described.
57
+ - `docs.missing-exported-function-doc` (warning; medium confidence): Flags exported functions without a leading maintainer comment.
57
58
  - `docs.missing-file-overview` (advisory; medium confidence): Flags source files without a top-of-file purpose comment.
58
- - `docs.missing-function-doc` (advisory; medium confidence): Flags functions without a leading maintainer comment.
59
59
  - `docs.missing-interface-doc` (advisory; medium confidence): Flags interfaces without a leading maintainer comment.
60
+ - `docs.missing-internal-function-doc` (advisory; medium confidence): Flags internal helper functions without a leading maintainer comment.
60
61
  - `docs.missing-invariant-doc` (advisory; medium confidence): Flags commented declarations that own schema, fingerprint, baseline, or determinism contracts without saying so.
61
62
  - `docs.missing-param-tag` (advisory; medium confidence): Flags documented exports with parameters missing @param tags.
62
63
  - `docs.missing-public-doc` (advisory; medium confidence): Flags exported class, type, and enum APIs without a nearby doc comment.
@@ -157,14 +158,13 @@ gruff-ts list-rules --format=json
157
158
  - `test-quality.global-state-mutation` (warning; high confidence): Flags tests mutating process or global runtime state.
158
159
  - `test-quality.loop-in-test` (advisory; high confidence): Flags loops inside test bodies.
159
160
  - `test-quality.magic-number-assertion` (advisory; medium confidence): Flags assertions against unexplained numeric literals.
160
- - `test-quality.missing-nearby-test` (advisory; medium confidence): Flags exported production files without nearby tests.
161
161
  - `test-quality.mock-only-test` (advisory; high confidence): Flags tests that only verify mock interaction.
162
162
  - `test-quality.no-assertions` (warning; high confidence): Flags tests without apparent assertions.
163
163
  - `test-quality.no-throw-only-test` (advisory; high confidence): Flags tests that only assert code does not throw.
164
164
  - `test-quality.only-skip` (advisory; high confidence): Flags focused or skipped test markers.
165
- - `test-quality.setup-bloat` (advisory; medium confidence; threshold 12): Flags tests with too much setup before the first assertion.
166
165
  - `test-quality.sleep-in-test` (advisory; high confidence): Flags sleeps in tests.
167
166
  - `test-quality.snapshot-only-test` (advisory; high confidence): Flags tests that rely only on snapshots.
167
+ - `test-quality.static-analysis-redundant-test` (advisory; high confidence): Flags tests that primarily assert code shape rather than behavior.
168
168
  - `test-quality.trivial-assertion` (warning; high confidence): Flags tautological assertions.
169
169
  - `test-quality.unused-mock` (advisory; medium confidence): Flags mocks created but not used.
170
170
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@blundergoat/gruff-ts",
3
- "version": "0.3.0",
4
- "description": "Governs AI-generated code so a human can verify it: a TypeScript/JavaScript static analyzer - 119 rules across 11 quality pillars, SARIF output, baselines, and a local dashboard.",
3
+ "version": "0.3.2",
4
+ "description": "Governs AI-generated code so a human can verify it: a TypeScript/JavaScript static analyzer - 120 rules across 11 quality pillars, SARIF output, baselines, and a local dashboard.",
5
5
  "license": "MIT",
6
6
  "author": "Matthew Hansen (https://www.blundergoat.com/about)",
7
7
  "homepage": "https://github.com/blundergoat/gruff-ts#readme",
@@ -36,6 +36,21 @@
36
36
  "node": ">=22"
37
37
  },
38
38
  "type": "module",
39
+ "files": [
40
+ "bin/",
41
+ "src/",
42
+ "!src/**/*.test.ts",
43
+ "!src/fixtures/",
44
+ "docs/",
45
+ "!docs/releasing.md",
46
+ "!docs/coding-standards/",
47
+ "tsconfig.json",
48
+ "README.md",
49
+ "LICENSE",
50
+ "CHANGELOG.md",
51
+ "CONTRIBUTING.md",
52
+ "SECURITY.md"
53
+ ],
39
54
  "bin": {
40
55
  "gruff-ts": "bin/gruff-ts"
41
56
  },
package/src/analyser.ts CHANGED
@@ -12,7 +12,7 @@ import { absolutize, discoverSources, displayPath, type SourceFile } from "./dis
12
12
  import { makeFinding } from "./findings.ts";
13
13
  import { finding } from "./findings-helpers.ts";
14
14
  import { commentRecords } from "./comment-scanner.ts";
15
- 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";
16
16
  import { analyseBlockRules, type BlockRuleContext, blockRuleContext, type FunctionBlock, functionBlocks, parameterNames } from "./blocks.ts";
17
17
  import { analyseClassRules, analyseAcronymCase, analyseInconsistentCasing, analyseInterfaceFields, collectDeclaredIdentifiers } from "./class-rules.ts";
18
18
  import { analyseDeadCode, analyseUnreachable, analyseUnusedImports } from "./dead-code-rules.ts";
@@ -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,7 +283,6 @@ 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
 
@@ -298,7 +296,19 @@ function analyseTextRules(file: SourceFile, source: string, config: Config, find
298
296
  if (!isGeneratedLockfile(file.displayPath)) {
299
297
  const fileLengthThreshold = threshold(config, "size.file-length", 750);
300
298
  if (lines > fileLengthThreshold) {
301
- 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" }));
299
+ findings.push(
300
+ makeFinding({
301
+ ruleId: "size.file-length",
302
+ message: `File has ${lines} lines, above the threshold of ${fileLengthThreshold}.`,
303
+ filePath: file.displayPath,
304
+ line: 1,
305
+ severity: ruleSeverity(config, "size.file-length", "warning"),
306
+ pillar: "size",
307
+ confidence: "high",
308
+ remediation: "Split unrelated responsibilities into smaller files. Or raise rules.size.file-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.",
309
+ metadata: { lines, threshold: fileLengthThreshold },
310
+ }),
311
+ );
302
312
  }
303
313
  }
304
314
 
@@ -334,7 +344,7 @@ function analyseTypeScriptRules(file: SourceFile, source: string, config: Config
334
344
  const blocks = functionBlocks(source, codeSource);
335
345
  const comments = commentRecords(source);
336
346
  analyseFileOverviewDoc(file, source, findings);
337
- analyseBlocks(file, blocks, config, findings);
347
+ analyseBlocks(file, source, codeSource, blocks, config, findings);
338
348
  analyseUnusedImports(file, codeSource, source, findings);
339
349
  analyseLineRules(file, source, codeSource, config, findings);
340
350
  analyseSecurityFlow(file, source, findings);
@@ -355,13 +365,13 @@ function analyseTypeScriptRules(file: SourceFile, source: string, config: Config
355
365
  // separately so blocks.ts can stay independent of the naming-pusher and test-block-rule modules;
356
366
  // the per-rule emission order from `analyseBlockRules` is the stable fingerprint contract every
357
367
  // Finding depends on for deterministic baseline matching.
358
- function analyseBlocks(file: SourceFile, blocks: FunctionBlock[], config: Config, findings: Finding[]): void {
368
+ function analyseBlocks(file: SourceFile, source: string, codeSource: string, blocks: FunctionBlock[], config: Config, findings: Finding[]): void {
359
369
  for (const block of blocks) {
360
370
  const context = blockRuleContext(file, block, config, findings);
361
371
  analyseBlockRules(context);
362
372
  pushParameterNamingFindings(context);
363
373
  if (block.isTest) {
364
- analyseTestBlock(file, block, config, findings);
374
+ analyseTestBlock(file, block, findings, { source, codeSource, startLine: 1 });
365
375
  }
366
376
  }
367
377
  }
package/src/blocks.ts CHANGED
@@ -87,14 +87,26 @@ export interface BlockFindingWithMetadataArgs extends BlockFindingArgs {
87
87
  // needing metadata or lower confidence go through `blockFindingWithMetadata` to keep the
88
88
  // per-rule fingerprint shape stable.
89
89
  export function blockFinding(args: BlockFindingArgs): Finding {
90
- return makeFinding({ ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.block.startLine, severity: args.severity, pillar: args.pillar, confidence: "high", symbol: args.block.name });
90
+ const endLine = args.block.startLine + args.block.lineCount - 1;
91
+ return makeFinding({ ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.block.startLine, endLine, severity: args.severity, pillar: args.pillar, confidence: "high", symbol: args.block.name });
91
92
  }
92
93
 
93
94
  // Block-anchored variant that ships rule-specific metadata. Confidence defaults to "medium"
94
95
  // because metadata-carrying rules (e.g. test-quality magic-number) report measurements rather than
95
96
  // definitive defects; the metadata payload is part of each rule's stable fingerprint contract.
96
97
  export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Finding {
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 });
98
+ return makeFinding({
99
+ ruleId: args.ruleId,
100
+ message: args.message,
101
+ filePath: args.file.displayPath,
102
+ line: args.block.startLine,
103
+ endLine: args.block.startLine + args.block.lineCount - 1,
104
+ severity: args.severity,
105
+ pillar: args.pillar,
106
+ confidence: "medium",
107
+ symbol: args.block.name,
108
+ metadata: args.metadata,
109
+ });
98
110
  }
99
111
 
100
112
  // Computes cyclomatic and function-body once and threads them through the per-block rule pipeline.
@@ -134,7 +146,15 @@ export function analyseBlockRules(context: BlockRuleContext): void {
134
146
  function pushFunctionLengthFinding(context: BlockRuleContext): void {
135
147
  const functionLengthThreshold = threshold(context.config, "size.function-length", 200);
136
148
  if (context.block.lineCount > functionLengthThreshold) {
137
- context.findings.push(blockFinding({ ruleId: "size.function-length", message: `Function \`${context.block.name}\` has ${context.block.lineCount} lines, above the threshold of ${functionLengthThreshold}.`, file: context.file, block: context.block, severity: ruleSeverity(context.config, "size.function-length", "warning"), pillar: "size" }));
149
+ context.findings.push(blockFindingWithMetadata({
150
+ ruleId: "size.function-length",
151
+ message: `Function \`${context.block.name}\` has ${context.block.lineCount} lines, above the threshold of ${functionLengthThreshold}.`,
152
+ file: context.file,
153
+ block: context.block,
154
+ severity: ruleSeverity(context.config, "size.function-length", "warning"),
155
+ pillar: "size",
156
+ metadata: { lines: context.block.lineCount, threshold: functionLengthThreshold },
157
+ }));
138
158
  }
139
159
  }
140
160
 
@@ -142,16 +162,34 @@ function pushFunctionLengthFinding(context: BlockRuleContext): void {
142
162
  // already validated the signature shape upstream. Reports `size.parameter-count` when exceeded.
143
163
  function pushParameterCountFinding(context: BlockRuleContext): void {
144
164
  const params = context.block.params.split(",").map((value) => value.trim()).filter(Boolean).length;
145
- if (params > threshold(context.config, "size.parameter-count", 7)) {
146
- context.findings.push(blockFinding({ ruleId: "size.parameter-count", message: `Function \`${context.block.name}\` declares ${params} parameters.`, file: context.file, block: context.block, severity: ruleSeverity(context.config, "size.parameter-count", "warning"), pillar: "size" }));
165
+ const parameterCountThreshold = threshold(context.config, "size.parameter-count", 7);
166
+ if (params > parameterCountThreshold) {
167
+ context.findings.push(blockFindingWithMetadata({
168
+ ruleId: "size.parameter-count",
169
+ message: `Function \`${context.block.name}\` declares ${params} parameters.`,
170
+ file: context.file,
171
+ block: context.block,
172
+ severity: ruleSeverity(context.config, "size.parameter-count", "warning"),
173
+ pillar: "size",
174
+ metadata: { parameters: params, threshold: parameterCountThreshold },
175
+ }));
147
176
  }
148
177
  }
149
178
 
150
179
  // Default threshold 15. Counts conditional keywords + boolean operators in the code body - see
151
180
  // `blockRuleContext` for the pre-computed value. Reports `complexity.cyclomatic` when exceeded.
152
181
  function pushCyclomaticFinding(context: BlockRuleContext): void {
153
- if (context.cyclomatic > threshold(context.config, "complexity.cyclomatic", 15)) {
154
- context.findings.push(blockFinding({ ruleId: "complexity.cyclomatic", message: `Function \`${context.block.name}\` has cyclomatic complexity ${context.cyclomatic}.`, file: context.file, block: context.block, severity: ruleSeverity(context.config, "complexity.cyclomatic", "warning"), pillar: "complexity" }));
182
+ const cyclomaticThreshold = threshold(context.config, "complexity.cyclomatic", 15);
183
+ if (context.cyclomatic > cyclomaticThreshold) {
184
+ context.findings.push(blockFindingWithMetadata({
185
+ ruleId: "complexity.cyclomatic",
186
+ message: `Function \`${context.block.name}\` has cyclomatic complexity ${context.cyclomatic}.`,
187
+ file: context.file,
188
+ block: context.block,
189
+ severity: ruleSeverity(context.config, "complexity.cyclomatic", "warning"),
190
+ pillar: "complexity",
191
+ metadata: { complexity: context.cyclomatic, threshold: cyclomaticThreshold },
192
+ }));
155
193
  }
156
194
  }
157
195
 
@@ -159,8 +197,17 @@ function pushCyclomaticFinding(context: BlockRuleContext): void {
159
197
  // "deeply nested" intuition pure cyclomatic misses. Reports `complexity.cognitive` when exceeded.
160
198
  function pushCognitiveFinding(context: BlockRuleContext): void {
161
199
  const cognitive = context.cyclomatic + maxNestingDepth(context.block.codeBody);
162
- if (cognitive > threshold(context.config, "complexity.cognitive", 15)) {
163
- context.findings.push(blockFinding({ ruleId: "complexity.cognitive", message: `Function \`${context.block.name}\` has cognitive complexity ${cognitive}.`, file: context.file, block: context.block, severity: ruleSeverity(context.config, "complexity.cognitive", "warning"), pillar: "complexity" }));
200
+ const cognitiveThreshold = threshold(context.config, "complexity.cognitive", 15);
201
+ if (cognitive > cognitiveThreshold) {
202
+ context.findings.push(blockFindingWithMetadata({
203
+ ruleId: "complexity.cognitive",
204
+ message: `Function \`${context.block.name}\` has cognitive complexity ${cognitive}.`,
205
+ file: context.file,
206
+ block: context.block,
207
+ severity: ruleSeverity(context.config, "complexity.cognitive", "warning"),
208
+ pillar: "complexity",
209
+ metadata: { complexity: cognitive, threshold: cognitiveThreshold },
210
+ }));
164
211
  }
165
212
  }
166
213
 
@@ -669,9 +716,9 @@ export function hasAssertion(source: string): boolean {
669
716
  return false;
670
717
  }
671
718
 
672
- // Setup-bloat metric: counts non-ignorable lines preceding the first assertion in the body. Stops
673
- // as soon as an assertion appears, so the value never overshoots the actual prologue length used
674
- // by `test-quality.setup-bloat`.
719
+ // Counts non-ignorable lines preceding the first assertion in a test body. Stops as soon as an
720
+ // assertion appears, so the value never overshoots the actual prologue length. Used by
721
+ // `docs.fixture-purpose-missing` to size test-setup fixtures.
675
722
  export function setupLineCount(source: string): number {
676
723
  let count = 0;
677
724
  for (const line of functionBodyContent(source).split(/\r?\n/)) {
@@ -17,6 +17,9 @@ export interface ChangedRegionScope {
17
17
  mode: ChangedScopeMode;
18
18
  rangesByFile: Map<string, ChangedRange[]>;
19
19
  wholeFiles: Set<string>;
20
+ // Every file that appears in the diff, including deletion-only files that contribute no target-side
21
+ // ranges. `file` scope keeps all findings in any changed file, so it consults this set, not ranges.
22
+ changedFiles: Set<string>;
20
23
  explicitRanges?: ChangedRange[];
21
24
  }
22
25
 
@@ -45,7 +48,7 @@ const FILE_WIDE_RULE_IDS = new Set(["design.large-module-concentration", "docs.m
45
48
  // Builds the changed-region scope requested by CLI options. Throws on stdin diffs missing patch text.
46
49
  export function changedRegionScope(options: AnalysisOptions): ChangedRegionScope | undefined {
47
50
  if (options.changedRanges) {
48
- return { mode: options.changedScope, rangesByFile: new Map(), wholeFiles: new Set(), explicitRanges: parseChangedRanges(options.changedRanges) };
51
+ return { mode: options.changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set(), explicitRanges: parseChangedRanges(options.changedRanges) };
49
52
  }
50
53
  if (options.diffPatch !== undefined) {
51
54
  return parseUnifiedDiff(options.diffPatch, options.changedScope);
@@ -84,7 +87,7 @@ export function filterChangedFindings(
84
87
  return { findings: kept, suppressedCount };
85
88
  }
86
89
 
87
- // Keeps a finding when its own line or enclosing declaration intersects the changed scope.
90
+ // Keeps a finding when its own line, enclosing declaration, or changed-file scope intersects the change.
88
91
  function isFindingInChangedScope(
89
92
  finding: Finding,
90
93
  scope: ChangedRegionScope,
@@ -94,27 +97,29 @@ function isFindingInChangedScope(
94
97
  if (scope.wholeFiles.has(finding.filePath)) {
95
98
  return true;
96
99
  }
100
+ // `file` scope keeps every finding in a changed file, so it must answer before the range check:
101
+ // a deletion-only edit produces no target-side ranges but still counts as touching the file.
102
+ if (scope.mode === "file") {
103
+ return scope.explicitRanges !== undefined || scope.changedFiles.has(finding.filePath);
104
+ }
97
105
  const changedRanges = rangesForFindingFile(scope, finding.filePath);
98
106
  if (changedRanges.length === 0) {
99
107
  return false;
100
108
  }
101
- if (isFileWideFinding(finding) && (scope.rangesByFile.has(finding.filePath) || scope.explicitRanges)) {
102
- return true;
103
- }
104
109
  const findingRange = { start: finding.line ?? 1, end: finding.endLine ?? finding.line ?? 1 };
105
110
  if (overlapsAny(findingRange, changedRanges)) {
106
111
  return true;
107
112
  }
108
- if (scope.mode === "hunk") {
113
+ if (scope.mode !== "symbol" || isFileWideFinding(finding)) {
109
114
  return false;
110
115
  }
111
116
  const declaration = enclosingDeclaration(finding, sources, declarationsByFile);
112
117
  return declaration !== undefined && overlapsAny(declaration, changedRanges);
113
118
  }
114
119
 
115
- // Invariant: file-wide findings are line-1 anchors kept when any hunk changes the file.
120
+ // Invariant: file-wide findings are line-1 anchors with no declaration to widen through.
116
121
  function isFileWideFinding(finding: Finding): boolean {
117
- return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1 && finding.symbol === undefined;
122
+ return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1;
118
123
  }
119
124
 
120
125
  // Looks up explicit line ranges first because `--changed-ranges` applies to every selected file.
@@ -252,7 +257,7 @@ function gitDiffScope(mode: string, changedScope: ChangedScopeMode): ChangedRegi
252
257
 
253
258
  // Parses a unified diff into file-level and hunk-level scope.
254
259
  function parseUnifiedDiff(diffText: string, changedScope: ChangedScopeMode): ChangedRegionScope {
255
- const scope: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set() };
260
+ const scope: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set() };
256
261
  const state: DiffParseState = { currentFile: undefined, isNewFile: false, targetLine: undefined };
257
262
  for (const line of diffText.split(/\r?\n/)) {
258
263
  applyDiffLine(scope, state, line);
@@ -287,8 +292,11 @@ function applyTargetFileLine(scope: ChangedRegionScope, state: DiffParseState, l
287
292
  const path = diffPath(line.slice(4));
288
293
  state.currentFile = path === "/dev/null" ? undefined : path;
289
294
  state.targetLine = undefined;
290
- if (state.currentFile && state.isNewFile) {
291
- scope.wholeFiles.add(state.currentFile);
295
+ if (state.currentFile) {
296
+ scope.changedFiles.add(state.currentFile);
297
+ if (state.isNewFile) {
298
+ scope.wholeFiles.add(state.currentFile);
299
+ }
292
300
  }
293
301
  return true;
294
302
  }
@@ -337,17 +345,17 @@ function diffPath(rawPath: string): string {
337
345
 
338
346
  // Treats untracked files as whole-file changed because git has no hunks for them yet.
339
347
  function untrackedFileScope(changedScope: ChangedScopeMode): ChangedRegionScope {
340
- return {
341
- mode: changedScope,
342
- rangesByFile: new Map(),
343
- wholeFiles: new Set(gitOutput(["ls-files", "--others", "--exclude-standard"]).split(/\r?\n/).filter(Boolean).map((path) => path.replaceAll("\\", "/"))),
344
- };
348
+ const untracked = new Set(gitOutput(["ls-files", "--others", "--exclude-standard"]).split(/\r?\n/).filter(Boolean).map((path) => path.replaceAll("\\", "/")));
349
+ return { mode: changedScope, rangesByFile: new Map(), wholeFiles: untracked, changedFiles: new Set(untracked) };
345
350
  }
346
351
 
347
352
  // Unions staged, unstaged, and untracked scopes while whole-file changes dominate hunk ranges.
348
353
  function mergeScopes(scopes: ChangedRegionScope[], changedScope: ChangedScopeMode): ChangedRegionScope {
349
- const merged: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set() };
354
+ const merged: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set() };
350
355
  for (const scope of scopes) {
356
+ for (const file of scope.changedFiles) {
357
+ merged.changedFiles.add(file);
358
+ }
351
359
  for (const file of scope.wholeFiles) {
352
360
  merged.wholeFiles.add(file);
353
361
  merged.rangesByFile.delete(file);