@blundergoat/gruff-ts 0.1.1 → 0.3.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 (52) hide show
  1. package/CHANGELOG.md +55 -19
  2. package/README.md +103 -35
  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 +60 -3
  7. package/docs/dashboard.md +7 -0
  8. package/docs/output-formats.md +11 -1
  9. package/docs/philosophy.md +21 -0
  10. package/docs/releasing.md +12 -11
  11. package/docs/reports-and-ci.md +5 -2
  12. package/docs/rules.md +24 -15
  13. package/package.json +5 -5
  14. package/scripts/bump-version.sh +20 -4
  15. package/scripts/preflight-checks.sh +4 -41
  16. package/src/analyser.ts +47 -34
  17. package/src/blocks.ts +82 -75
  18. package/src/changed-regions.ts +390 -0
  19. package/src/check-ignore.ts +49 -0
  20. package/src/class-rules.ts +80 -33
  21. package/src/cli-program.ts +209 -51
  22. package/src/comment-rules.ts +4 -0
  23. package/src/config-load-error.ts +18 -0
  24. package/src/config-parse.ts +458 -0
  25. package/src/config-preservation.ts +64 -0
  26. package/src/config.ts +311 -428
  27. package/src/constants.ts +10 -2
  28. package/src/context-doc-rules.ts +2 -4
  29. package/src/dashboard.ts +8 -5
  30. package/src/dead-code-rules.ts +60 -14
  31. package/src/discovery.ts +88 -32
  32. package/src/doc-rules.ts +3 -3
  33. package/src/findings-helpers.ts +58 -5
  34. package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
  35. package/src/init-config.ts +94 -31
  36. package/src/line-rules.ts +58 -4
  37. package/src/naming-pushers.ts +42 -7
  38. package/src/pillar-summary.ts +129 -0
  39. package/src/profiles.ts +232 -0
  40. package/src/project-config-rules.ts +5 -5
  41. package/src/project-rules.ts +2 -1
  42. package/src/report-html.ts +404 -0
  43. package/src/report-renderers.ts +210 -397
  44. package/src/rule-list.ts +85 -1
  45. package/src/rules.ts +28 -27
  46. package/src/safety-rules.ts +22 -7
  47. package/src/scoring.ts +78 -8
  48. package/src/security-flow-rules.ts +533 -0
  49. package/src/sensitive-data-rules.ts +138 -2
  50. package/src/test-block-rules.ts +140 -7
  51. package/src/test-fixtures.ts +59 -13
  52. package/src/types.ts +108 -5
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.
@@ -22,17 +20,27 @@ export interface FunctionBlock {
22
20
  body: string;
23
21
  codeBody: string;
24
22
  isPublic: boolean;
23
+ // True when the function declaration line itself starts with `export`. Distinct from `isPublic`,
24
+ // which also matches class `public` modifiers - exports are the top-level API surface, while a
25
+ // public class method is internal to an exported (or unexported) class. The doc rule splits
26
+ // severity on this distinction: exported functions warrant warning-tier doc requirements,
27
+ // internal helpers stay advisory.
28
+ isExported: boolean;
25
29
  isTest: boolean;
26
30
  hasLeadingComment: boolean;
27
31
  declarationLine: number;
28
32
  }
29
33
 
30
34
  // Working state for the function-block parser. Patterns are precompiled once per file so each
31
- // callable detection doesn't re-instantiate the same RegExp objects.
35
+ // callable detection doesn't re-instantiate the same RegExp objects. `reExportedNames` carries
36
+ // the file-level scan of `export { foo }` / `export default foo` so a declaration like
37
+ // `function foo() {}` later re-exported via `export { foo }` is still classified as exported
38
+ // (the line-local `^export` check alone would miss this common pattern).
32
39
  interface FunctionBlockScan {
33
40
  lines: string[];
34
41
  codeLines: string[];
35
42
  patterns: RegExp[];
43
+ reExportedNames: ReadonlySet<string>;
36
44
  }
37
45
 
38
46
  const FUNCTION_BLOCK_PATTERNS = functionBlockPatterns();
@@ -55,13 +63,6 @@ export interface BlockRuleContext {
55
63
  functionBody: string;
56
64
  }
57
65
 
58
- // NPath approximation result. `isCapped: true` signals the value hit `NPATH_CAP` and is a lower
59
- // bound - the finding message uses this to mark capped values rather than implying precision.
60
- export interface NpathResult {
61
- value: number;
62
- isCapped: boolean;
63
- }
64
-
65
66
  // Input bundle for `blockFinding()`. The block reference replaces the explicit line: the builder
66
67
  // reads `block.startLine` and `block.name` so the stable finding anchor and symbol metadata stay
67
68
  // in sync with the parsed callable across every block-level rule.
@@ -90,7 +91,7 @@ export function blockFinding(args: BlockFindingArgs): Finding {
90
91
  }
91
92
 
92
93
  // Block-anchored variant that ships rule-specific metadata. Confidence defaults to "medium"
93
- // 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
94
95
  // definitive defects; the metadata payload is part of each rule's stable fingerprint contract.
95
96
  export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Finding {
96
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 });
@@ -120,8 +121,6 @@ export function analyseBlockRules(context: BlockRuleContext): void {
120
121
  pushParameterCountFinding(context);
121
122
  pushCyclomaticFinding(context);
122
123
  pushCognitiveFinding(context);
123
- pushNpathFinding(context);
124
- pushGodFunctionFinding(context);
125
124
  pushGenericFunctionFinding(context);
126
125
  pushMissingFunctionDocFinding(context);
127
126
  pushEmptyFunctionFinding(context);
@@ -165,41 +164,6 @@ function pushCognitiveFinding(context: BlockRuleContext): void {
165
164
  }
166
165
  }
167
166
 
168
- // Default threshold 200. NPath is the number of possible execution paths; the message marks
169
- // `capped` when the calculation hit `NPATH_CAP` so reviewers know it's a lower bound. Reports `complexity.npath`.
170
- function pushNpathFinding(context: BlockRuleContext): void {
171
- const npath = approximateNpath(context.functionBody);
172
- const npathThreshold = threshold(context.config, "complexity.npath", 200);
173
- if (npath.value > npathThreshold) {
174
- context.findings.push(npathFinding(context, npath, npathThreshold, ruleSeverity(context.config, "complexity.npath", "warning")));
175
- }
176
- }
177
-
178
- /*
179
- * Stable `complexity.npath` finding factory. `capped` and `cap` are surfaced in metadata so
180
- * downstream tooling can distinguish "5000" from "≥ NPATH_CAP" - both would render as the same
181
- * value otherwise.
182
- */
183
- function npathFinding(context: BlockRuleContext, npath: NpathResult, thresholdValue: number, severity: Severity): Finding {
184
- return blockFindingWithMetadata({
185
- ruleId: "complexity.npath",
186
- message: `Function \`${context.block.name}\` has approximate NPath complexity ${npath.value} above the threshold of ${thresholdValue} (capped at ${NPATH_CAP}).`,
187
- file: context.file,
188
- block: context.block,
189
- severity,
190
- pillar: "complexity",
191
- metadata: { npath: npath.value, capped: npath.isCapped, cap: NPATH_CAP, threshold: thresholdValue },
192
- });
193
- }
194
-
195
- // Combined-shape rule: long (>45 lines) AND complex (cyclomatic >10). Thresholds are hard-coded
196
- // because "god function" is a design heuristic, not a per-rule tunable. Reports `design.god-function`.
197
- function pushGodFunctionFinding(context: BlockRuleContext): void {
198
- if (context.block.lineCount > 45 && context.cyclomatic > 10) {
199
- 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" }));
200
- }
201
- }
202
-
203
167
  // Names like `process`, `handle`, `run` from `config.bannedGenericNames`. The list is user-configurable;
204
168
  // the rule body itself just consults the config. Reports `naming.generic-function`.
205
169
  function pushGenericFunctionFinding(context: BlockRuleContext): void {
@@ -208,12 +172,20 @@ function pushGenericFunctionFinding(context: BlockRuleContext): void {
208
172
  }
209
173
  }
210
174
 
211
- // Every non-test function must carry a leading comment. Test blocks are exempted because their
212
- // `test("name", …)` description already documents intent. Reports `docs.missing-function-doc`.
175
+ /*
176
+ * Every non-test function must carry a leading comment. Test blocks are exempted because their
177
+ * `test("name", …)` description already documents intent. Reports
178
+ * `docs.missing-exported-function-doc` (warning, higher cost of omission on the public API
179
+ * surface) when `isExported` is true, `docs.missing-internal-function-doc` (advisory) otherwise.
180
+ */
213
181
  function pushMissingFunctionDocFinding(context: BlockRuleContext): void {
214
- if (!context.block.isTest && !context.block.hasLeadingComment) {
215
- context.findings.push(blockFinding({ ruleId: "docs.missing-function-doc", message: `Function \`${context.block.name}\` is missing a leading maintainer comment.`, file: context.file, block: context.block, severity: "advisory", pillar: "documentation" }));
182
+ if (context.block.isTest || context.block.hasLeadingComment) {
183
+ return;
216
184
  }
185
+ const ruleId = context.block.isExported ? "docs.missing-exported-function-doc" : "docs.missing-internal-function-doc";
186
+ const severity = context.block.isExported ? "warning" : "advisory";
187
+ const audience = context.block.isExported ? "exported" : "internal";
188
+ context.findings.push(blockFinding({ ruleId, message: `${audience === "exported" ? "Exported" : "Internal"} function \`${context.block.name}\` is missing a leading maintainer comment.`, file: context.file, block: context.block, severity, pillar: "documentation" }));
217
189
  }
218
190
 
219
191
  // Empty bodies are sometimes intentional placeholders, hence the advisory severity rather than
@@ -223,10 +195,28 @@ function pushEmptyFunctionFinding(context: BlockRuleContext): void {
223
195
  return;
224
196
  }
225
197
  if (isEmptyFunctionBody(context.block.codeBody)) {
198
+ if (isDocumentedEmptyTestDouble(context)) {
199
+ return;
200
+ }
226
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" }));
227
202
  }
228
203
  }
229
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
+
230
220
  // `_`-prefixed parameters are exempted (the standard "intentionally unused" convention).
231
221
  // Reports `waste.unused-parameter` for parameter names that never appear in the callable body.
232
222
  function pushUnusedParameterFindings(context: BlockRuleContext): void {
@@ -336,25 +326,6 @@ function pushUselessReturnFindings(context: BlockRuleContext): void {
336
326
  }
337
327
  }
338
328
 
339
- // Approximation: each decision keyword (`if`, `case`, `catch`, loops) and short-circuit operator
340
- // doubles the count. Optional chaining is stripped first so `a?.b` and `??` don't inflate the
341
- // signal. Capped at `NPATH_CAP` - the `capped` flag tells callers to report the value as ≥, not =.
342
- export function approximateNpath(source: string): NpathResult {
343
- let pathCount = 1;
344
- let isCapped = false;
345
- const normalized = source.replace(/\?\./g, "").replace(/\?\?/g, "");
346
- const decisionCount = countMatches(normalized, /\b(if|else if|case|catch|for|while)\b|\?|&&|\|\|/g);
347
- for (let index = 0; index < decisionCount; index += 1) {
348
- pathCount *= 2;
349
- if (pathCount >= NPATH_CAP) {
350
- pathCount = NPATH_CAP;
351
- isCapped = true;
352
- break;
353
- }
354
- }
355
- return { value: pathCount, isCapped };
356
- }
357
-
358
329
  // Strips line and block comments before measuring - a body containing only documentation is still
359
330
  // considered empty for the `waste.empty-function` check, since no executable statements run.
360
331
  function isEmptyFunctionBody(source: string): boolean {
@@ -453,6 +424,7 @@ export function functionBlocks(source: string, codeSource = source): FunctionBlo
453
424
  lines: source.split(/\r?\n/),
454
425
  codeLines: codeSource.split(/\r?\n/),
455
426
  patterns: FUNCTION_BLOCK_PATTERNS,
427
+ reExportedNames: collectReExportedNames(codeSource),
456
428
  };
457
429
  const blocks: FunctionBlock[] = [];
458
430
  scan.codeLines.forEach((line, index) => {
@@ -465,15 +437,49 @@ export function functionBlocks(source: string, codeSource = source): FunctionBlo
465
437
  return blocks;
466
438
  }
467
439
 
440
+ /*
441
+ * File-level scan for re-exported local declarations. Matches `export { foo }`, `export { foo as
442
+ * bar }` (the local name `foo` is recorded, not the renamed `bar`), and `export default foo`
443
+ * (bare-identifier form - `export default function ...` is matched via pattern 2 in
444
+ * functionBlockPatterns instead, then classified exported because the line itself starts with
445
+ * `export`). Re-export-from clauses (`export { foo } from "./other"`) are intentionally skipped
446
+ * via the negative lookahead: those names are not local declarations of this file, so promoting
447
+ * a same-named local to "exported" would emit a false missing-public-doc finding.
448
+ *
449
+ * Operates on the masked codeSource so `export { foo }` inside a string literal or comment is
450
+ * skipped. Multi-line export blocks work because `[^}]+` spans newlines, and the lookahead
451
+ * spans whitespace and blanked-comment runs that the masker collapses to spaces.
452
+ */
453
+ function collectReExportedNames(codeSource: string): ReadonlySet<string> {
454
+ const names = new Set<string>();
455
+ for (const match of codeSource.matchAll(/export\s*\{([^}]+)\}(?!\s*from\b)/g)) {
456
+ for (const entry of (match[1] ?? "").split(",")) {
457
+ const local = entry.trim().split(/\s+as\s+/)[0]?.trim();
458
+ if (local && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(local)) {
459
+ names.add(local);
460
+ }
461
+ }
462
+ }
463
+ for (const match of codeSource.matchAll(/^\s*export\s+default\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*;?\s*$/gm)) {
464
+ if (match[1]) {
465
+ names.add(match[1]);
466
+ }
467
+ }
468
+ return names;
469
+ }
470
+
468
471
  // Four callable shapes in the order `functionBlockMatch` tries them: `test()` / `it()` bodies,
469
472
  // `function` declarations, class methods, and arrow assignments. Pattern[0] is intentionally
470
- // first because test bodies must match before the generic arrow pattern claims them.
473
+ // first because test bodies must match before the generic arrow pattern claims them. Pattern[1]
474
+ // accepts an optional `default` after `export` so `export default function foo() {}` parses into
475
+ // a FunctionBlock - the CHANGELOG's exported-doc-rule contract advertises that shape and the
476
+ // missing `default` token previously made those declarations invisible to every block-level rule.
471
477
  function functionBlockPatterns(): RegExp[] {
472
478
  return [
473
479
  /^\s*(?:test|it)\s*\(\s*["'`]([^"'`]+)["'`]\s*,\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
474
- /^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)/,
480
+ /^\s*(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)/,
475
481
  /^\s*(?:public|private|protected)?\s*(?:async\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)\s*[:{]/,
476
- /^\s*(?:const|let)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
482
+ /^\s*(?:export\s+)?(?:const|let)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>/,
477
483
  ];
478
484
  }
479
485
 
@@ -523,6 +529,7 @@ function functionBlockFromMatch(scan: FunctionBlockScan, match: RegExpMatchArray
523
529
  body,
524
530
  codeBody,
525
531
  isPublic: /\bexport\b|\bpublic\b/.test(scan.codeLines.slice(start, index + 1).join("\n")),
532
+ isExported: /^\s*export\b/.test(scan.codeLines[index] ?? "") || scan.reExportedNames.has(match[1] ?? ""),
526
533
  isTest: isTestInvocationLine(scan.codeLines[index] ?? ""),
527
534
  hasLeadingComment: hasLeadingCommentBeforeLines(scan.lines, index + 1),
528
535
  declarationLine: index + 1,
@@ -0,0 +1,390 @@
1
+ // Diff-aware changed-region filtering for analyse runs. The public JSON finding shape stays intact:
2
+ // this module only decides which already-produced findings are attributable to the requested change.
3
+ import { execFileSync } from "node:child_process";
4
+ import { functionBlocks } from "./blocks.ts";
5
+ import type { SourceFile } from "./discovery.ts";
6
+ import { maskNonCode } from "./source-text.ts";
7
+ import type { AnalysisOptions, ChangedScopeMode, Finding } from "./types.ts";
8
+
9
+ // Inclusive line range from a changed hunk or explicit `--changed-ranges` input.
10
+ export interface ChangedRange {
11
+ start: number;
12
+ end: number;
13
+ }
14
+
15
+ // Complete changed-region filter state used after the full report is generated.
16
+ export interface ChangedRegionScope {
17
+ mode: ChangedScopeMode;
18
+ rangesByFile: Map<string, ChangedRange[]>;
19
+ wholeFiles: Set<string>;
20
+ explicitRanges?: ChangedRange[];
21
+ }
22
+
23
+ // Source text paired with discovery metadata so findings can be expanded to symbols.
24
+ interface SourceSnapshot {
25
+ file: SourceFile;
26
+ source: string;
27
+ }
28
+
29
+ // Named source span used to keep symbol-scope findings when their declaration overlaps a hunk.
30
+ interface DeclarationRegion {
31
+ name: string;
32
+ start: number;
33
+ end: number;
34
+ }
35
+
36
+ // Mutable state for the current file while walking a unified diff line by line.
37
+ interface DiffParseState {
38
+ currentFile: string | undefined;
39
+ isNewFile: boolean;
40
+ targetLine: number | undefined;
41
+ }
42
+
43
+ const FILE_WIDE_RULE_IDS = new Set(["design.large-module-concentration", "docs.missing-file-overview", "size.file-length"]);
44
+
45
+ // Builds the changed-region scope requested by CLI options. Throws on stdin diffs missing patch text.
46
+ export function changedRegionScope(options: AnalysisOptions): ChangedRegionScope | undefined {
47
+ if (options.changedRanges) {
48
+ return { mode: options.changedScope, rangesByFile: new Map(), wholeFiles: new Set(), explicitRanges: parseChangedRanges(options.changedRanges) };
49
+ }
50
+ if (options.diffPatch !== undefined) {
51
+ return parseUnifiedDiff(options.diffPatch, options.changedScope);
52
+ }
53
+ if (options.since) {
54
+ return gitDiffScope(options.since, options.changedScope);
55
+ }
56
+ if (options.diff) {
57
+ if (options.diff === "-") {
58
+ throw new Error("--diff - requires diffPatch input; the CLI reads stdin before analysis.");
59
+ }
60
+ return gitDiffScope(options.diff, options.changedScope);
61
+ }
62
+ return undefined;
63
+ }
64
+
65
+ // Applies changed-region filtering to findings and reports how many pre-existing findings dropped.
66
+ export function filterChangedFindings(
67
+ findings: Finding[],
68
+ scope: ChangedRegionScope | undefined,
69
+ sources: Map<string, SourceSnapshot>,
70
+ ): { findings: Finding[]; suppressedCount?: number } {
71
+ if (!scope) {
72
+ return { findings };
73
+ }
74
+ const declarationsByFile = new Map<string, DeclarationRegion[]>();
75
+ const kept: Finding[] = [];
76
+ let suppressedCount = 0;
77
+ for (const finding of findings) {
78
+ if (isFindingInChangedScope(finding, scope, sources, declarationsByFile)) {
79
+ kept.push(finding);
80
+ } else {
81
+ suppressedCount += 1;
82
+ }
83
+ }
84
+ return { findings: kept, suppressedCount };
85
+ }
86
+
87
+ // Keeps a finding when its own line or enclosing declaration intersects the changed scope.
88
+ function isFindingInChangedScope(
89
+ finding: Finding,
90
+ scope: ChangedRegionScope,
91
+ sources: Map<string, SourceSnapshot>,
92
+ declarationsByFile: Map<string, DeclarationRegion[]>,
93
+ ): boolean {
94
+ if (scope.wholeFiles.has(finding.filePath)) {
95
+ return true;
96
+ }
97
+ const changedRanges = rangesForFindingFile(scope, finding.filePath);
98
+ if (changedRanges.length === 0) {
99
+ return false;
100
+ }
101
+ if (isFileWideFinding(finding) && (scope.rangesByFile.has(finding.filePath) || scope.explicitRanges)) {
102
+ return true;
103
+ }
104
+ const findingRange = { start: finding.line ?? 1, end: finding.endLine ?? finding.line ?? 1 };
105
+ if (overlapsAny(findingRange, changedRanges)) {
106
+ return true;
107
+ }
108
+ if (scope.mode === "hunk") {
109
+ return false;
110
+ }
111
+ const declaration = enclosingDeclaration(finding, sources, declarationsByFile);
112
+ return declaration !== undefined && overlapsAny(declaration, changedRanges);
113
+ }
114
+
115
+ // Invariant: file-wide findings are line-1 anchors kept when any hunk changes the file.
116
+ function isFileWideFinding(finding: Finding): boolean {
117
+ return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1 && finding.symbol === undefined;
118
+ }
119
+
120
+ // Looks up explicit line ranges first because `--changed-ranges` applies to every selected file.
121
+ function rangesForFindingFile(scope: ChangedRegionScope, filePath: string): ChangedRange[] {
122
+ return scope.explicitRanges ?? scope.rangesByFile.get(filePath) ?? [];
123
+ }
124
+
125
+ // Resolves the narrowest declaration around a finding so symbol-scope mode can keep whole callables.
126
+ function enclosingDeclaration(
127
+ finding: Finding,
128
+ sources: Map<string, SourceSnapshot>,
129
+ declarationsByFile: Map<string, DeclarationRegion[]>,
130
+ ): DeclarationRegion | undefined {
131
+ const source = sources.get(finding.filePath);
132
+ if (!source?.file.isScript) {
133
+ return undefined;
134
+ }
135
+ let declarations = declarationsByFile.get(finding.filePath);
136
+ if (!declarations) {
137
+ declarations = declarationRegions(source.source);
138
+ declarationsByFile.set(finding.filePath, declarations);
139
+ }
140
+ const line = finding.line ?? 1;
141
+ const named = finding.symbol
142
+ ? declarations.filter((region) => region.name === finding.symbol && line >= region.start && line <= region.end)
143
+ : [];
144
+ const candidates = named.length > 0 ? named : declarations.filter((region) => line >= region.start && line <= region.end);
145
+ return candidates.sort((left, right) => (left.end - left.start) - (right.end - right.start))[0];
146
+ }
147
+
148
+ // Combines function and class/interface spans into one declaration inventory per source file.
149
+ function declarationRegions(source: string): DeclarationRegion[] {
150
+ const codeSource = maskNonCode(source);
151
+ return [
152
+ ...functionBlocks(source, codeSource).map((block) => ({
153
+ name: block.name,
154
+ start: block.startLine,
155
+ end: block.startLine + block.lineCount - 1,
156
+ })),
157
+ ...classLikeRegions(codeSource),
158
+ ];
159
+ }
160
+
161
+ // Finds class and interface spans that the function-block lexer intentionally does not emit.
162
+ function classLikeRegions(codeSource: string): DeclarationRegion[] {
163
+ const lines = codeSource.split(/\r?\n/);
164
+ const regions: DeclarationRegion[] = [];
165
+ lines.forEach((line, index) => {
166
+ const match = line.match(/^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:class|interface)\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/);
167
+ if (!match?.[1]) {
168
+ return;
169
+ }
170
+ regions.push({ name: match[1], start: index + 1, end: bracedRegionEnd(lines, index) });
171
+ });
172
+ return regions;
173
+ }
174
+
175
+ // Walks brace depth from a class/interface declaration to estimate its closing line.
176
+ function bracedRegionEnd(lines: string[], startIndex: number): number {
177
+ let depth = 0;
178
+ let hasSeenOpen = false;
179
+ for (let index = startIndex; index < lines.length; index += 1) {
180
+ for (const character of lines[index] ?? "") {
181
+ if (character === "{") {
182
+ depth += 1;
183
+ hasSeenOpen = true;
184
+ } else if (character === "}") {
185
+ depth -= 1;
186
+ }
187
+ }
188
+ if (hasSeenOpen && depth <= 0) {
189
+ return index + 1;
190
+ }
191
+ }
192
+ return startIndex + 1;
193
+ }
194
+
195
+ // Checks whether a finding or declaration span intersects any changed hunk.
196
+ function overlapsAny(range: ChangedRange, changedRanges: ChangedRange[]): boolean {
197
+ return changedRanges.some((changedRange) => rangesOverlap(range, changedRange));
198
+ }
199
+
200
+ // Inclusive range overlap test for one-based source line numbers.
201
+ function rangesOverlap(left: ChangedRange, right: ChangedRange): boolean {
202
+ return left.start <= right.end && right.start <= left.end;
203
+ }
204
+
205
+ // Parses the comma-separated CLI range syntax and throws validation errors for malformed ranges.
206
+ function parseChangedRanges(rawRanges: string): ChangedRange[] {
207
+ const ranges = rawRanges
208
+ .split(",")
209
+ .map((part) => part.trim())
210
+ .filter(Boolean)
211
+ .map(parseChangedRange);
212
+ if (ranges.length === 0) {
213
+ throw new Error("--changed-ranges must include at least one range such as 3-3 or 8-10");
214
+ }
215
+ return mergeRanges(ranges);
216
+ }
217
+
218
+ // Parses one `N` or `N-M` range and throws the CLI-facing validation error for invalid input.
219
+ function parseChangedRange(rawRange: string): ChangedRange {
220
+ const match = rawRange.match(/^(\d+)(?:-(\d+))?$/);
221
+ if (!match?.[1]) {
222
+ throw new Error(`invalid --changed-ranges entry: ${rawRange}`);
223
+ }
224
+ const start = Number(match[1]);
225
+ const end = Number(match[2] ?? match[1]);
226
+ if (start < 1 || end < start) {
227
+ throw new Error(`invalid --changed-ranges entry: ${rawRange}`);
228
+ }
229
+ return { start, end };
230
+ }
231
+
232
+ // Produces a changed-region scope from a named git diff mode or arbitrary git ref.
233
+ function gitDiffScope(mode: string, changedScope: ChangedScopeMode): ChangedRegionScope {
234
+ if (mode === "staged") {
235
+ return parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope);
236
+ }
237
+ if (mode === "unstaged") {
238
+ return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope);
239
+ }
240
+ if (mode === "working-tree") {
241
+ return mergeScopes(
242
+ [
243
+ parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope),
244
+ parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope),
245
+ untrackedFileScope(changedScope),
246
+ ],
247
+ changedScope,
248
+ );
249
+ }
250
+ return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff", "--end-of-options", mode]), changedScope);
251
+ }
252
+
253
+ // Parses a unified diff into file-level and hunk-level scope.
254
+ function parseUnifiedDiff(diffText: string, changedScope: ChangedScopeMode): ChangedRegionScope {
255
+ const scope: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set() };
256
+ const state: DiffParseState = { currentFile: undefined, isNewFile: false, targetLine: undefined };
257
+ for (const line of diffText.split(/\r?\n/)) {
258
+ applyDiffLine(scope, state, line);
259
+ }
260
+ return scope;
261
+ }
262
+
263
+ // Dispatches one unified-diff line to the smallest applicable state transition.
264
+ function applyDiffLine(scope: ChangedRegionScope, state: DiffParseState, line: string): void {
265
+ if (line.startsWith("diff --git ")) {
266
+ state.currentFile = undefined;
267
+ state.isNewFile = false;
268
+ state.targetLine = undefined;
269
+ return;
270
+ }
271
+ if (line.startsWith("new file mode ") || line === "--- /dev/null") {
272
+ state.isNewFile = true;
273
+ return;
274
+ }
275
+ if (applyTargetFileLine(scope, state, line)) {
276
+ return;
277
+ }
278
+ if (applyHunkHeader(scope, state, line)) {
279
+ return;
280
+ }
281
+ applyHunkBodyLine(scope, state, line);
282
+ }
283
+
284
+ // Handles `+++` target-file headers, including new files that should keep all findings.
285
+ function applyTargetFileLine(scope: ChangedRegionScope, state: DiffParseState, line: string): boolean {
286
+ if (line.startsWith("+++ ")) {
287
+ const path = diffPath(line.slice(4));
288
+ state.currentFile = path === "/dev/null" ? undefined : path;
289
+ state.targetLine = undefined;
290
+ if (state.currentFile && state.isNewFile) {
291
+ scope.wholeFiles.add(state.currentFile);
292
+ }
293
+ return true;
294
+ }
295
+ return false;
296
+ }
297
+
298
+ // Starts tracking target-side line numbers for the current hunk.
299
+ function applyHunkHeader(scope: ChangedRegionScope, state: DiffParseState, line: string): boolean {
300
+ const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);
301
+ if (!hunk) {
302
+ return false;
303
+ }
304
+ if (!hunk[1] || !state.currentFile || scope.wholeFiles.has(state.currentFile)) {
305
+ state.targetLine = undefined;
306
+ return true;
307
+ }
308
+ const start = Math.max(1, Number(hunk[1]));
309
+ const length = hunk[2] === undefined ? 1 : Number(hunk[2]);
310
+ state.targetLine = length === 0 ? undefined : start;
311
+ return true;
312
+ }
313
+
314
+ // Adds only real target-side additions from the hunk body; context lines just advance the cursor.
315
+ function applyHunkBodyLine(scope: ChangedRegionScope, state: DiffParseState, line: string): void {
316
+ if (!state.currentFile || state.targetLine === undefined || scope.wholeFiles.has(state.currentFile)) {
317
+ return;
318
+ }
319
+ if (line.startsWith("+")) {
320
+ addRange(scope.rangesByFile, state.currentFile, { start: state.targetLine, end: state.targetLine });
321
+ state.targetLine += 1;
322
+ return;
323
+ }
324
+ if (line.startsWith(" ")) {
325
+ state.targetLine += 1;
326
+ }
327
+ }
328
+
329
+ // Normalizes the `+++ b/path` header path into the same display path discovery uses.
330
+ function diffPath(rawPath: string): string {
331
+ const trimmed = rawPath.trim();
332
+ if (trimmed === "/dev/null") {
333
+ return trimmed;
334
+ }
335
+ return trimmed.replace(/^"?(?:a|b)\//, "").replace(/"$/, "").replaceAll("\\", "/");
336
+ }
337
+
338
+ // Treats untracked files as whole-file changed because git has no hunks for them yet.
339
+ 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
+ };
345
+ }
346
+
347
+ // Unions staged, unstaged, and untracked scopes while whole-file changes dominate hunk ranges.
348
+ function mergeScopes(scopes: ChangedRegionScope[], changedScope: ChangedScopeMode): ChangedRegionScope {
349
+ const merged: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set() };
350
+ for (const scope of scopes) {
351
+ for (const file of scope.wholeFiles) {
352
+ merged.wholeFiles.add(file);
353
+ merged.rangesByFile.delete(file);
354
+ }
355
+ for (const [file, ranges] of scope.rangesByFile) {
356
+ if (merged.wholeFiles.has(file)) {
357
+ continue;
358
+ }
359
+ for (const range of ranges) {
360
+ addRange(merged.rangesByFile, file, range);
361
+ }
362
+ }
363
+ }
364
+ return merged;
365
+ }
366
+
367
+ // Inserts a range for one file and immediately coalesces adjacent hunks.
368
+ function addRange(rangesByFile: Map<string, ChangedRange[]>, filePath: string, range: ChangedRange): void {
369
+ rangesByFile.set(filePath, mergeRanges([...(rangesByFile.get(filePath) ?? []), range]));
370
+ }
371
+
372
+ // Sorts and merges overlapping or adjacent line ranges so downstream checks stay deterministic.
373
+ function mergeRanges(ranges: ChangedRange[]): ChangedRange[] {
374
+ const sorted = [...ranges].sort((left, right) => left.start - right.start || left.end - right.end);
375
+ const merged: ChangedRange[] = [];
376
+ for (const range of sorted) {
377
+ const previous = merged[merged.length - 1];
378
+ if (!previous || range.start > previous.end + 1) {
379
+ merged.push({ ...range });
380
+ continue;
381
+ }
382
+ previous.end = Math.max(previous.end, range.end);
383
+ }
384
+ return merged;
385
+ }
386
+
387
+ // Spawns `git` through a fixed argv vector; callers construct argv arrays without interpolation.
388
+ function gitOutput(args: string[]): string {
389
+ return execFileSync("git", args, { encoding: "utf8" });
390
+ }