@blundergoat/gruff-ts 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -1,10 +1,25 @@
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.
1
+ // Selects the findings that belong to a user's Git changes, patch, or explicit line ranges.
2
+ //
3
+ // Use `analyse --diff staged` to review the next commit, or `--changed-ranges` for specific lines.
4
+ // A full scan supplies context for findings that span functions, files, or imports.
3
5
  import { execFileSync } from "node:child_process";
6
+ import { cwd } from "node:process";
4
7
  import { functionBlocks } from "./blocks.ts";
5
8
  import type { SourceFile } from "./discovery.ts";
9
+ import type { ParsedScript } from "./parsed-script.ts";
6
10
  import { maskNonCode } from "./source-text.ts";
7
- import type { AnalysisOptions, ChangedScopeMode, Finding } from "./types.ts";
11
+ import type { AnalysisOptions, ChangedScopeMode, Finding, RunDiagnostic } from "./types.ts";
12
+
13
+ /**
14
+ * Signals that Gruff could not read the lines the user asked to review.
15
+ *
16
+ * For example, a mistyped revision makes `analyse --since` fail with a `changed-region` diagnostic.
17
+ * Hooks can show the same diagnostic when an edit could not be reviewed.
18
+ */
19
+ export class ChangedRegionError extends Error {}
20
+
21
+ // The diagnostic type both the hook and `analyse` give a ChangedRegionError.
22
+ export const CHANGED_REGION_DIAGNOSTIC_TYPE = "changed-region";
8
23
 
9
24
  // Inclusive line range from a changed hunk or explicit `--changed-ranges` input.
10
25
  export interface ChangedRange {
@@ -27,6 +42,7 @@ export interface ChangedRegionScope {
27
42
  interface SourceSnapshot {
28
43
  file: SourceFile;
29
44
  source: string;
45
+ parsed?: ParsedScript;
30
46
  }
31
47
 
32
48
  // Named source span used to keep symbol-scope findings when their declaration overlaps a hunk.
@@ -49,27 +65,74 @@ const FILE_WIDE_RULE_IDS = new Set(["design.large-module-concentration", "docs.m
49
65
  // so changed-region attribution must consult the member list, not only the anchor `filePath`.
50
66
  const PROJECT_RELATIONSHIP_RULE_IDS = new Set(["design.circular-import"]);
51
67
 
52
- // Builds the changed-region scope requested by CLI options. Throws on stdin diffs missing patch text.
53
- export function changedRegionScope(options: AnalysisOptions): ChangedRegionScope | undefined {
54
- if (options.changedRanges) {
68
+ /**
69
+ * Resolves the changed lines requested for `analyse` or a hook.
70
+ * Explicit ranges take priority, then supplied patch text, then `--since` or `--diff`.
71
+ *
72
+ * @param options - Analysis options carrying changed-range, patch, `--since`, `--diff`, and scope selectors.
73
+ * @param projectRoot - Working directory used when running Git comparisons; defaults to the current working directory.
74
+ * @returns Scope describing the requested changes, or undefined when the user asks for a full scan.
75
+ * @throws {ChangedRegionError} When a range, patch input, or Git comparison cannot be read.
76
+ */
77
+ export function changedRegionScope(options: AnalysisOptions, projectRoot = cwd()): ChangedRegionScope | undefined {
78
+ // Editor integrations can specify the exact line ranges the user edited.
79
+ if (options.changedRanges !== undefined) {
55
80
  return { mode: options.changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set(), explicitRanges: parseChangedRanges(options.changedRanges) };
56
81
  }
82
+ // An empty supplied patch means nothing changed and still takes priority over Git selectors.
57
83
  if (options.diffPatch !== undefined) {
58
84
  return parseUnifiedDiff(options.diffPatch, options.changedScope);
59
85
  }
86
+ // A commit range lets a user see findings introduced since a known revision; `--since` always names a Git ref, never a diff mode keyword.
60
87
  if (options.since) {
61
- return gitDiffScope(options.since, options.changedScope);
88
+ return gitDiffScope(options.since, options.changedScope, projectRoot, false);
62
89
  }
90
+ // A named diff compares the requested part of the checkout, unless `--diff-base` explicitly named a Git ref.
63
91
  if (options.diff) {
92
+ // A lone dash expects patch text from stdin, supplied by the CLI before the scan.
64
93
  if (options.diff === "-") {
65
- throw new Error("--diff - requires diffPatch input; the CLI reads stdin before analysis.");
94
+ throw new ChangedRegionError("--diff - requires diffPatch input; the CLI reads stdin before analysis.");
66
95
  }
67
- return gitDiffScope(options.diff, options.changedScope);
96
+ return gitDiffScope(options.diff, options.changedScope, projectRoot, options.isDiffExplicitRef !== true);
68
97
  }
69
98
  return undefined;
70
99
  }
71
100
 
72
- // Applies changed-region filtering to findings and reports how many pre-existing findings dropped.
101
+ // Diagnostic types that describe one analysed file's content or readability. Only these are
102
+ // file-scoped under diff filtering; operational diagnostics (missing paths, history errors) always
103
+ // stay, because they describe the request rather than an unchanged context file.
104
+ const FILE_CONTENT_DIAGNOSTIC_TYPES = new Set(["bounded-deep-scan", "parse-error", "read-error"]);
105
+
106
+ /**
107
+ * Filters run diagnostics to changed target files when a diff scope is active.
108
+ * Operational diagnostics and diagnostics without a file path always remain.
109
+ *
110
+ * @param diagnostics - Run diagnostics emitted during analysis.
111
+ * @param scope - Active changed-region scope, or undefined for an unscoped run.
112
+ * @returns Input diagnostics unchanged for unscoped or explicit-range runs, or diff-filtered diagnostics keeping changed-file content errors.
113
+ */
114
+ export function filterScopedDiagnostics(diagnostics: RunDiagnostic[], scope: ChangedRegionScope | undefined): RunDiagnostic[] {
115
+ if (!scope || scope.explicitRanges !== undefined) {
116
+ return diagnostics;
117
+ }
118
+ return diagnostics.filter((diagnostic) => {
119
+ // Operational diagnostics (missing-path, history-error) describe the request, not file content.
120
+ if (!diagnostic.filePath || !FILE_CONTENT_DIAGNOSTIC_TYPES.has(diagnostic.diagnosticType)) {
121
+ return true;
122
+ }
123
+ return scope.changedFiles.has(diagnostic.filePath) || scope.wholeFiles.has(diagnostic.filePath);
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Filters findings against the active changed-region scope, using sources to resolve declarations for symbol scope.
129
+ * The invariant is that kept plus suppressed equals the input total when a scope is provided.
130
+ *
131
+ * @param findings - Candidate findings from the full analysis pass.
132
+ * @param scope - Active changed-region scope, or undefined when no filtering is requested.
133
+ * @param sources - Snapshot lookup by file path used to resolve enclosing declarations in symbol scope.
134
+ * @returns Kept findings with suppressedCount when scoped, or the original findings with suppressedCount absent when unscoped.
135
+ */
73
136
  export function filterChangedFindings(
74
137
  findings: Finding[],
75
138
  scope: ChangedRegionScope | undefined,
@@ -91,7 +154,16 @@ export function filterChangedFindings(
91
154
  return { findings: kept, suppressedCount };
92
155
  }
93
156
 
94
- // Keeps a finding when its own line, enclosing declaration, or changed-file scope intersects the change.
157
+ /**
158
+ * Determines whether scope keeps a finding by relationship member, whole file, hunk overlap, or enclosing declaration under the gate contract.
159
+ * Hunk checks use line 1 for an absent start and the start for an absent end; empty ranges disable hunk and symbol matches.
160
+ *
161
+ * @param finding - Finding to evaluate against the active scope.
162
+ * @param scope - Active changed-region selection rules and file ranges.
163
+ * @param sources - Snapshot lookup used to read script sources on declaration cache misses.
164
+ * @param declarationsByFile - Mutates this per-file declaration cache on misses to avoid rebuilding spans during symbol widening.
165
+ * @returns True when the finding belongs in the changed scope under the gate contract; otherwise false.
166
+ */
95
167
  function isFindingInChangedScope(
96
168
  finding: Finding,
97
169
  scope: ChangedRegionScope,
@@ -104,8 +176,7 @@ function isFindingInChangedScope(
104
176
  if (scope.wholeFiles.has(finding.filePath)) {
105
177
  return true;
106
178
  }
107
- // `file` scope keeps every finding in a changed file, so it must answer before the range check:
108
- // a deletion-only edit produces no target-side ranges but still counts as touching the file.
179
+ // File scope runs before line checks so deletion-only edits still count. Explicit ranges make every selected file eligible.
109
180
  if (scope.mode === "file") {
110
181
  return scope.explicitRanges !== undefined || scope.changedFiles.has(finding.filePath);
111
182
  }
@@ -117,6 +188,27 @@ function isFindingInChangedScope(
117
188
  if (overlapsAny(findingRange, changedRanges)) {
118
189
  return true;
119
190
  }
191
+ return symbolScopeWidensFinding(finding, scope, sources, declarationsByFile, changedRanges);
192
+ }
193
+
194
+ /**
195
+ * Checks whether symbol scope widens to keep a finding because its enclosing declaration overlaps changedRanges.
196
+ * The invariant is that file-wide findings and findings without a resolvable declaration never widen.
197
+ *
198
+ * @param finding - Finding outside direct hunk ranges to test for declaration-level widening.
199
+ * @param scope - Active changed-region scope whose mode must be `symbol` for widening to apply.
200
+ * @param sources - Snapshot lookup used to load scripts when resolving declarations.
201
+ * @param declarationsByFile - Mutates this per-file declaration cache on misses while resolving the enclosing declaration.
202
+ * @param changedRanges - Changed line ranges for the finding's file.
203
+ * @returns True when symbol scope keeps the finding because its enclosing declaration overlaps changedRanges; otherwise false.
204
+ */
205
+ function symbolScopeWidensFinding(
206
+ finding: Finding,
207
+ scope: ChangedRegionScope,
208
+ sources: Map<string, SourceSnapshot>,
209
+ declarationsByFile: Map<string, DeclarationRegion[]>,
210
+ changedRanges: ChangedRange[],
211
+ ): boolean {
120
212
  if (scope.mode !== "symbol" || isFileWideFinding(finding)) {
121
213
  return false;
122
214
  }
@@ -124,16 +216,23 @@ function isFindingInChangedScope(
124
216
  return declaration !== undefined && overlapsAny(declaration, changedRanges);
125
217
  }
126
218
 
127
- // Invariant: file-wide findings are line-1 anchors with no declaration to widen through.
219
+ /**
220
+ * Checks whether a finding is a file-wide rule anchored at explicit line 1 so the symbol-scope invariant prevents widening.
221
+ * An absent line leaves the finding eligible for ordinary symbol-scope checks.
222
+ *
223
+ * @param finding - Finding whose rule ID and line anchor are checked.
224
+ * @returns True when a `FILE_WIDE_RULE_IDS` finding has an explicit line 1 anchor; otherwise false.
225
+ */
128
226
  function isFileWideFinding(finding: Finding): boolean {
129
227
  return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1;
130
228
  }
131
229
 
132
- /*
133
- * Keeps a project-relationship finding when any member file participates in the change, matching
134
- * the documented contract "a project relationship that includes the requested file". Explicit
135
- * `--changed-ranges` carry no per-file information (the ranges apply to every selected file), so
136
- * they keep these findings by construction; narrow scans already filtered them to requested files.
230
+ /**
231
+ * Applies the project-relationship scope contract using the files that participate in the change.
232
+ *
233
+ * @param finding - relationship to check. Uses its path if no member array exists. An empty member array matches neither file set.
234
+ * @param scope - selection whose whole-file and changed-file sets identify participating members
235
+ * @returns True for explicit ranges because they apply to every selected file, or if a member is in either file set. Otherwise false.
137
236
  */
138
237
  function projectRelationshipTouchesChange(finding: Finding, scope: ChangedRegionScope): boolean {
139
238
  if (scope.explicitRanges !== undefined) {
@@ -143,12 +242,27 @@ function projectRelationshipTouchesChange(finding: Finding, scope: ChangedRegion
143
242
  return files.some((file) => typeof file === "string" && (scope.wholeFiles.has(file) || scope.changedFiles.has(file)));
144
243
  }
145
244
 
146
- // Looks up explicit line ranges first because `--changed-ranges` applies to every selected file.
245
+ /**
246
+ * Resolves the changed line ranges applicable to a finding's file under the scope contract.
247
+ * Explicit ranges take precedence because they apply to every selected file; an empty list leaves range checks with no target span.
248
+ *
249
+ * @param scope - Active changed-region scope holding explicit ranges and per-file hunk ranges.
250
+ * @param filePath - Path of the finding's file to look up when explicit ranges are absent.
251
+ * @returns Explicit ranges if configured, otherwise the hunk ranges for filePath or an empty list.
252
+ */
147
253
  function rangesForFindingFile(scope: ChangedRegionScope, filePath: string): ChangedRange[] {
148
254
  return scope.explicitRanges ?? scope.rangesByFile.get(filePath) ?? [];
149
255
  }
150
256
 
151
- // Resolves the narrowest declaration around a finding so symbol-scope mode can keep whole callables.
257
+ /**
258
+ * Finds the narrowest declaration around the finding's line, preferring matching symbols for a stable choice.
259
+ * An absent line means line 1; fills declarationsByFile on a cache miss to avoid rebuilding declaration spans.
260
+ *
261
+ * @param finding - Finding whose file, symbol name, and line anchor locate the enclosing declaration.
262
+ * @param sources - Snapshot lookup used to verify script status and retrieve source text on cache misses.
263
+ * @param declarationsByFile - Mutates this per-file declaration cache on misses.
264
+ * @returns Narrowest enclosing declaration region, or undefined when no script or enclosing declaration is available.
265
+ */
152
266
  function enclosingDeclaration(
153
267
  finding: Finding,
154
268
  sources: Map<string, SourceSnapshot>,
@@ -160,7 +274,7 @@ function enclosingDeclaration(
160
274
  }
161
275
  let declarations = declarationsByFile.get(finding.filePath);
162
276
  if (!declarations) {
163
- declarations = declarationRegions(source.source);
277
+ declarations = declarationRegions(source.source, source.parsed);
164
278
  declarationsByFile.set(finding.filePath, declarations);
165
279
  }
166
280
  const line = finding.line ?? 1;
@@ -171,11 +285,18 @@ function enclosingDeclaration(
171
285
  return candidates.sort((left, right) => (left.end - left.start) - (right.end - right.start))[0];
172
286
  }
173
287
 
174
- // Combines function and class/interface spans into one declaration inventory per source file.
175
- function declarationRegions(source: string): DeclarationRegion[] {
288
+ /**
289
+ * Collects function, class, and interface spans in source for symbol scoping.
290
+ * Without the optional shared parse, function spans come from the text-based block scan instead of syntax nodes.
291
+ *
292
+ * @param source - Full file text to scan for function, class, and interface declarations.
293
+ * @param parsed - Optional shared parse supplying syntax for function spans when available.
294
+ * @returns Combined declaration regions across functions, classes, and interfaces.
295
+ */
296
+ function declarationRegions(source: string, parsed?: ParsedScript): DeclarationRegion[] {
176
297
  const codeSource = maskNonCode(source);
177
298
  return [
178
- ...functionBlocks(source, codeSource).map((block) => ({
299
+ ...functionBlocks(source, codeSource, parsed).map((block) => ({
179
300
  name: block.name,
180
301
  start: block.startLine,
181
302
  end: block.startLine + block.lineCount - 1,
@@ -184,7 +305,12 @@ function declarationRegions(source: string): DeclarationRegion[] {
184
305
  ];
185
306
  }
186
307
 
187
- // Finds class and interface spans that the function-block lexer intentionally does not emit.
308
+ /**
309
+ * Extracts named class and interface line spans from masked source text, covering declarations outside the function-block scan.
310
+ *
311
+ * @param codeSource - Source text with comments and non-code literals masked out.
312
+ * @returns Named declaration regions for matched class and interface declarations.
313
+ */
188
314
  function classLikeRegions(codeSource: string): DeclarationRegion[] {
189
315
  const lines = codeSource.split(/\r?\n/);
190
316
  const regions: DeclarationRegion[] = [];
@@ -198,7 +324,14 @@ function classLikeRegions(codeSource: string): DeclarationRegion[] {
198
324
  return regions;
199
325
  }
200
326
 
201
- // Walks brace depth from a class/interface declaration to estimate its closing line.
327
+ /**
328
+ * Estimates a class or interface's one-based closing line by counting braces from the zero-based declaration startIndex.
329
+ * If no closing brace balances the declaration, returns its one-based starting line.
330
+ *
331
+ * @param lines - Masked source lines split at line breaks.
332
+ * @param startIndex - Zero-based line index where the class or interface declaration starts.
333
+ * @returns One-based closing line number, or the starting line when braces never balance.
334
+ */
202
335
  function bracedRegionEnd(lines: string[], startIndex: number): number {
203
336
  let depth = 0;
204
337
  let hasSeenOpen = false;
@@ -218,17 +351,35 @@ function bracedRegionEnd(lines: string[], startIndex: number): number {
218
351
  return startIndex + 1;
219
352
  }
220
353
 
221
- // Checks whether a finding or declaration span intersects any changed hunk.
354
+ /**
355
+ * Checks whether a finding or declaration span intersects any changed hunk.
356
+ *
357
+ * @param range - Inclusive one-based line span to test.
358
+ * @param changedRanges - Changed line ranges for the target file.
359
+ * @returns True when range overlaps at least one entry in changedRanges; otherwise false.
360
+ */
222
361
  function overlapsAny(range: ChangedRange, changedRanges: ChangedRange[]): boolean {
223
362
  return changedRanges.some((changedRange) => rangesOverlap(range, changedRange));
224
363
  }
225
364
 
226
- // Inclusive range overlap test for one-based source line numbers.
365
+ /**
366
+ * Performs an inclusive range overlap test for one-based source line numbers.
367
+ *
368
+ * @param left - First inclusive line range.
369
+ * @param right - Second inclusive line range.
370
+ * @returns True when left and right share at least one line; otherwise false.
371
+ */
227
372
  function rangesOverlap(left: ChangedRange, right: ChangedRange): boolean {
228
373
  return left.start <= right.end && right.start <= left.end;
229
374
  }
230
375
 
231
- // Parses the comma-separated CLI range syntax and throws validation errors for malformed ranges.
376
+ /**
377
+ * Parses sorted, merged line ranges from comma-separated CLI text, skipping blank entries.
378
+ *
379
+ * @param rawRanges - Comma-separated `--changed-ranges` input text.
380
+ * @returns Sorted, merged inclusive line ranges.
381
+ * @throws {ChangedRegionError} When no ranges remain or a nonblank entry is outside the valid N or N-M syntax or bounds.
382
+ */
232
383
  function parseChangedRanges(rawRanges: string): ChangedRange[] {
233
384
  const ranges = rawRanges
234
385
  .split(",")
@@ -236,47 +387,166 @@ function parseChangedRanges(rawRanges: string): ChangedRange[] {
236
387
  .filter(Boolean)
237
388
  .map(parseChangedRange);
238
389
  if (ranges.length === 0) {
239
- throw new Error("--changed-ranges must include at least one range such as 3-3 or 8-10");
390
+ throw new ChangedRegionError("--changed-ranges must include at least one range such as 3-3 or 8-10");
240
391
  }
241
392
  return mergeRanges(ranges);
242
393
  }
243
394
 
244
- // Parses one `N` or `N-M` range and throws the CLI-facing validation error for invalid input.
395
+ /**
396
+ * Parses inclusive line bounds for one `--changed-ranges` entry, using a single number for both bounds.
397
+ *
398
+ * @param rawRange - Trimmed single range token in N or N-M form.
399
+ * @returns Inclusive start and end line numbers for the entry.
400
+ * @throws {ChangedRegionError} When the entry is not N or N-M digits, starts below 1, or ends before it starts.
401
+ */
245
402
  function parseChangedRange(rawRange: string): ChangedRange {
246
403
  const match = rawRange.match(/^(\d+)(?:-(\d+))?$/);
247
404
  if (!match?.[1]) {
248
- throw new Error(`invalid --changed-ranges entry: ${rawRange}`);
405
+ throw new ChangedRegionError(`invalid --changed-ranges entry: ${rawRange}`);
249
406
  }
250
407
  const start = Number(match[1]);
251
408
  const end = Number(match[2] ?? match[1]);
252
409
  if (start < 1 || end < start) {
253
- throw new Error(`invalid --changed-ranges entry: ${rawRange}`);
410
+ throw new ChangedRegionError(`invalid --changed-ranges entry: ${rawRange}`);
254
411
  }
255
412
  return { start, end };
256
413
  }
257
414
 
258
- // Produces a changed-region scope from a named git diff mode or arbitrary git ref.
259
- function gitDiffScope(mode: string, changedScope: ChangedScopeMode): ChangedRegionScope {
260
- if (mode === "staged") {
261
- return parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope);
415
+ /**
416
+ * Builds a changed-region scope from Git diff output, reading paths relative to the scan directory so nested scans match findings.
417
+ * Working-tree mode combines staged, unstaged, and non-ignored untracked changes for a review of all local edits.
418
+ *
419
+ * @param mode - Diff selector: `staged`, `unstaged`, `working-tree` (when `allowDiffModes` is true), or a Git revision expression.
420
+ * @param changedScope - Attribution mode carried onto the resulting scope for downstream filtering.
421
+ * @param projectRoot - Directory passed to Git so reported paths remain relative to the scan root.
422
+ * @param allowDiffModes - true lets `staged`, `unstaged` and `working-tree` pick a mode; false (`--since`, `--diff-base`) reads them as Git refs
423
+ * @returns Scope populated with changed files, whole files, and per-file hunk ranges.
424
+ */
425
+ function gitDiffScope(mode: string, changedScope: ChangedScopeMode, projectRoot: string, allowDiffModes = true): ChangedRegionScope {
426
+ /**
427
+ * Runs `git diff` with paths relative to the selected project so a scan launched from a parent directory sees the right edits.
428
+ *
429
+ * @param extra - Additional Git diff flags or revision arguments appended to the base command.
430
+ * @returns Parsed changed-region scope from the resulting unified diff output.
431
+ */
432
+ const readDiff = (extra: string[]) => parseUnifiedDiff(
433
+ gitOutput(["-c", "core.quotepath=false", "diff", "--unified=0", "--no-color", "--no-ext-diff", "--relative", ...extra], projectRoot),
434
+ changedScope,
435
+ );
436
+ // Mode keywords apply only to --diff; --since and --diff-base treat the value as a Git ref, even a branch named staged.
437
+ if (allowDiffModes) {
438
+ // Staged mode reviews the contents selected for the next commit. Without HEAD every staged file is new, so whole-file coverage needs no renumbering.
439
+ if (mode === "staged") {
440
+ const staged = readDiff(["--cached"]);
441
+ return hasGitHead(projectRoot) ? stagedInWorkingTreeLines(staged, readDiff(["HEAD", "--"]), readDiff([])) : staged;
442
+ }
443
+ // Unstaged mode reviews changes made since the last staging operation.
444
+ if (mode === "unstaged") {
445
+ return readDiff([]);
446
+ }
447
+ // A working-tree review uses `git diff HEAD` when HEAD exists so staged and unstaged edits share exact working-tree line numbers.
448
+ if (mode === "working-tree") {
449
+ const trackedScopes = hasGitHead(projectRoot)
450
+ ? [readDiff(["HEAD", "--"])]
451
+ : [readDiff(["--cached"]), readDiff([])];
452
+ return mergeScopes(
453
+ [...trackedScopes, untrackedFileScope(changedScope, projectRoot)],
454
+ changedScope,
455
+ );
456
+ }
262
457
  }
263
- if (mode === "unstaged") {
264
- return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope);
458
+ // Trailing `--` forces Git to interpret `mode` strictly as a revision expression rather than a path when the ref is missing.
459
+ return readDiff(["--end-of-options", mode, "--"]);
460
+ }
461
+
462
+ /**
463
+ * Renumbers staged ranges in working-tree lines, because the scan reads the working tree while `git diff --cached` numbers the index.
464
+ * For example, two unstaged lines inserted above a staged line 20 move it to line 22, which an index range would miss.
465
+ * A staged line counts when it is new since HEAD and the unstaged edit did not add it; one an unstaged edit rewrote drops out.
466
+ *
467
+ * @param staged - `git diff --cached` scope, which decides the changed files and whole files a staged review covers
468
+ * @param sinceHead - `git diff HEAD` scope: lines new since HEAD, numbered in the working tree
469
+ * @param unstaged - `git diff` scope: lines the unstaged edit added, numbered in the working tree
470
+ * @returns The staged scope with each file's hunk ranges (and newly staged files that also carry unstaged edits) expressed in working-tree lines; files without surviving lines get no ranges.
471
+ */
472
+ function stagedInWorkingTreeLines(staged: ChangedRegionScope, sinceHead: ChangedRegionScope, unstaged: ChangedRegionScope): ChangedRegionScope {
473
+ const rangesByFile = new Map<string, ChangedRange[]>();
474
+ const wholeFiles = new Set<string>();
475
+ for (const file of staged.wholeFiles) {
476
+ const unstagedRanges = unstaged.rangesByFile.get(file);
477
+ if (!unstagedRanges || unstagedRanges.length === 0) {
478
+ wholeFiles.add(file);
479
+ continue;
480
+ }
481
+ const ranges = subtractRanges([{ start: 1, end: Number.MAX_SAFE_INTEGER }], unstagedRanges);
482
+ if (ranges.length > 0) {
483
+ rangesByFile.set(file, ranges);
484
+ }
265
485
  }
266
- if (mode === "working-tree") {
267
- return mergeScopes(
268
- [
269
- parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope),
270
- parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope),
271
- untrackedFileScope(changedScope),
272
- ],
273
- changedScope,
274
- );
486
+ for (const file of staged.rangesByFile.keys()) {
487
+ // A staged rename that unstaged edits pushed past Git's rename threshold reads as a new file since HEAD, so every line is new.
488
+ const newSinceHead = sinceHead.wholeFiles.has(file) ? [{ start: 1, end: Number.MAX_SAFE_INTEGER }] : sinceHead.rangesByFile.get(file) ?? [];
489
+ const ranges = subtractRanges(newSinceHead, unstaged.rangesByFile.get(file) ?? []);
490
+ // A staged hunk whose lines an unstaged edit replaced leaves nothing staged in the working tree to review.
491
+ if (ranges.length > 0) {
492
+ rangesByFile.set(file, ranges);
493
+ }
275
494
  }
276
- return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff", "--end-of-options", mode]), changedScope);
495
+ return { ...staged, wholeFiles, rangesByFile };
277
496
  }
278
497
 
279
- // Parses a unified diff into file-level and hunk-level scope.
498
+ /**
499
+ * Removes every line covered by `removed` from `ranges`, splitting a range when a removed block falls inside it.
500
+ *
501
+ * @param ranges - sorted, merged inclusive ranges to keep lines from
502
+ * @param removed - sorted, merged inclusive ranges whose lines are taken out
503
+ * @returns Sorted inclusive ranges holding the lines of `ranges` outside `removed`; empty when every line is removed.
504
+ */
505
+ function subtractRanges(ranges: ChangedRange[], removed: ChangedRange[]): ChangedRange[] {
506
+ const kept: ChangedRange[] = [];
507
+ for (const range of ranges) {
508
+ let start = range.start;
509
+ for (const cut of removed) {
510
+ // A removed block entirely before the remaining span, or after the range, leaves it whole.
511
+ if (cut.end < start || cut.start > range.end) {
512
+ continue;
513
+ }
514
+ if (cut.start > start) {
515
+ kept.push({ start, end: cut.start - 1 });
516
+ }
517
+ start = cut.end + 1;
518
+ }
519
+ if (start <= range.end) {
520
+ kept.push({ start, end: range.end });
521
+ }
522
+ }
523
+ return kept;
524
+ }
525
+
526
+ /**
527
+ * Spawns `git rev-parse` to check whether `HEAD` exists so `working-tree` can diff against `HEAD` instead of merging index coordinates.
528
+ *
529
+ * @param projectRoot - Directory passed to Git when verifying `HEAD`.
530
+ * @returns True when `HEAD` resolves to a commit; false in a freshly initialized repository with an unborn `HEAD` or outside a repo.
531
+ */
532
+ function hasGitHead(projectRoot: string): boolean {
533
+ try {
534
+ execFileSync("git", ["rev-parse", "--verify", "--quiet", "HEAD"], { cwd: projectRoot, stdio: ["ignore", "ignore", "ignore"] });
535
+ return true;
536
+ } catch {
537
+ // For example, a brand-new repository after `git init` has staged files but no initial commit yet, so `HEAD` does not exist.
538
+ return false;
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Parses changed target files and addition ranges from unified diff text, carrying changedScope forward for later filtering.
544
+ * A new file with a target header gets whole-file coverage; a surviving file with only deletions can be changed without target ranges.
545
+ *
546
+ * @param diffText - Unified diff text to walk line by line; an empty patch yields a scope with no changed files.
547
+ * @param changedScope - Scope attribution mode assigned to the returned scope.
548
+ * @returns Scope containing changed files, whole-file additions, and per-file target addition ranges.
549
+ */
280
550
  function parseUnifiedDiff(diffText: string, changedScope: ChangedScopeMode): ChangedRegionScope {
281
551
  const scope: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set() };
282
552
  const state: DiffParseState = { currentFile: undefined, isNewFile: false, targetLine: undefined };
@@ -286,7 +556,15 @@ function parseUnifiedDiff(diffText: string, changedScope: ChangedScopeMode): Cha
286
556
  return scope;
287
557
  }
288
558
 
289
- // Dispatches one unified-diff line to the smallest applicable state transition.
559
+ /**
560
+ * Reads one unified-diff line and updates state for the current target file and hunk.
561
+ * Mutates scope and state, clearing state at each file header to avoid carrying over the previous file.
562
+ *
563
+ * @param scope - Mutates changedFiles, wholeFiles, and rangesByFile as target headers and additions are encountered.
564
+ * @param state - Mutates per-file parser state across headers and hunk lines.
565
+ * @param line - Single line from the unified diff stream.
566
+ * @returns Nothing. Records changed files and additions in scope and updates state in place.
567
+ */
290
568
  function applyDiffLine(scope: ChangedRegionScope, state: DiffParseState, line: string): void {
291
569
  if (line.startsWith("diff --git ")) {
292
570
  state.currentFile = undefined;
@@ -307,7 +585,15 @@ function applyDiffLine(scope: ChangedRegionScope, state: DiffParseState, line: s
307
585
  applyHunkBodyLine(scope, state, line);
308
586
  }
309
587
 
310
- // Handles `+++` target-file headers, including new files that should keep all findings.
588
+ /**
589
+ * Applies a unified-diff target-file header (`+++ `) by updating state's current file and clearing its hunk cursor.
590
+ * A deleted target leaves no current file; surviving targets enter changedFiles, with whole-file coverage for new files.
591
+ *
592
+ * @param scope - Mutates changedFiles and wholeFiles when a surviving or new target file header is matched.
593
+ * @param state - Mutates currentFile and resets targetLine when the line is a target-file header.
594
+ * @param line - Candidate unified-diff line to inspect.
595
+ * @returns True if line is a target-file header; otherwise false.
596
+ */
311
597
  function applyTargetFileLine(scope: ChangedRegionScope, state: DiffParseState, line: string): boolean {
312
598
  if (line.startsWith("+++ ")) {
313
599
  const path = diffPath(line.slice(4));
@@ -324,7 +610,15 @@ function applyTargetFileLine(scope: ChangedRegionScope, state: DiffParseState, l
324
610
  return false;
325
611
  }
326
612
 
327
- // Starts tracking target-side line numbers for the current hunk.
613
+ /**
614
+ * Applies a unified-diff hunk header (`@@ ... @@`) and updates state's target line cursor for the hunk.
615
+ * A missing target file, whole-file coverage in scope, or a zero-length target hunk clears the cursor and skips line tracking.
616
+ *
617
+ * @param scope - Active diff scope checked for whole-file coverage on the current file.
618
+ * @param state - Mutates targetLine to the hunk's starting line or clears it when tracking should be skipped.
619
+ * @param line - Candidate unified-diff line to inspect.
620
+ * @returns True if line is a hunk header; otherwise false.
621
+ */
328
622
  function applyHunkHeader(scope: ChangedRegionScope, state: DiffParseState, line: string): boolean {
329
623
  const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/);
330
624
  if (!hunk) {
@@ -340,7 +634,15 @@ function applyHunkHeader(scope: ChangedRegionScope, state: DiffParseState, line:
340
634
  return true;
341
635
  }
342
636
 
343
- // Adds only real target-side additions from the hunk body; context lines just advance the cursor.
637
+ /**
638
+ * Reads one hunk body line using state's current file and target cursor, recording additions and advancing the cursor on context lines.
639
+ * Line tracking is skipped when no target file or cursor is active, or for whole-file coverage because the scope already includes every line.
640
+ *
641
+ * @param scope - Mutates rangesByFile on added lines unless whole-file coverage already applies.
642
+ * @param state - Mutates targetLine as added or context lines advance through the hunk.
643
+ * @param line - Hunk body line prefixed with `+`, space, or `-`.
644
+ * @returns Nothing. Updates scope ranges and state's targetLine cursor in place.
645
+ */
344
646
  function applyHunkBodyLine(scope: ChangedRegionScope, state: DiffParseState, line: string): void {
345
647
  if (!state.currentFile || state.targetLine === undefined || scope.wholeFiles.has(state.currentFile)) {
346
648
  return;
@@ -355,7 +657,12 @@ function applyHunkBodyLine(scope: ChangedRegionScope, state: DiffParseState, lin
355
657
  }
356
658
  }
357
659
 
358
- // Normalizes the `+++ b/path` header path into the same display path discovery uses.
660
+ /**
661
+ * Normalizes a unified-diff target-header path for finding lookup while preserving `/dev/null` as the deleted-target marker.
662
+ *
663
+ * @param rawPath - Raw path suffix extracted after the `+++ ` header prefix.
664
+ * @returns Normalized forward-slash path relative to the diff root, or `/dev/null` for deleted targets.
665
+ */
359
666
  function diffPath(rawPath: string): string {
360
667
  const trimmed = rawPath.trim();
361
668
  if (trimmed === "/dev/null") {
@@ -364,13 +671,27 @@ function diffPath(rawPath: string): string {
364
671
  return trimmed.replace(/^"?(?:a|b)\//, "").replace(/"$/, "").replaceAll("\\", "/");
365
672
  }
366
673
 
367
- // Treats untracked files as whole-file changed because git has no hunks for them yet.
368
- function untrackedFileScope(changedScope: ChangedScopeMode): ChangedRegionScope {
369
- const untracked = new Set(gitOutput(["ls-files", "--others", "--exclude-standard"]).split(/\r?\n/).filter(Boolean).map((path) => path.replaceAll("\\", "/")));
674
+ /**
675
+ * Collects new, non-ignored files for a working-tree review because Git has no hunks yet for these files.
676
+ * Reads NUL-separated paths from `git ls-files` to keep filenames with spaces or newlines intact.
677
+ *
678
+ * @param changedScope - Attribution mode assigned to the resulting scope.
679
+ * @param projectRoot - Directory passed to Git when listing untracked files.
680
+ * @returns Scope marking all untracked non-ignored files as whole-file changes, or empty sets if none exist.
681
+ */
682
+ function untrackedFileScope(changedScope: ChangedScopeMode, projectRoot: string): ChangedRegionScope {
683
+ const untracked = new Set(gitOutput(["ls-files", "-z", "--others", "--exclude-standard"], projectRoot).split("\0").filter(Boolean));
370
684
  return { mode: changedScope, rangesByFile: new Map(), wholeFiles: untracked, changedFiles: new Set(untracked) };
371
685
  }
372
686
 
373
- // Unions staged, unstaged, and untracked scopes while whole-file changes dominate hunk ranges.
687
+ /**
688
+ * Combines staged, unstaged, and untracked input scopes into a single scope under changedScope mode.
689
+ * Whole-file coverage takes precedence over hunk ranges for the same file.
690
+ *
691
+ * @param scopes - Input scopes whose changed files, whole files, and hunk ranges are merged.
692
+ * @param changedScope - Attribution mode assigned to the combined scope.
693
+ * @returns New merged scope combining all input changes.
694
+ */
374
695
  function mergeScopes(scopes: ChangedRegionScope[], changedScope: ChangedScopeMode): ChangedRegionScope {
375
696
  const merged: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set() };
376
697
  for (const scope of scopes) {
@@ -393,12 +714,24 @@ function mergeScopes(scopes: ChangedRegionScope[], changedScope: ChangedScopeMod
393
714
  return merged;
394
715
  }
395
716
 
396
- // Inserts a range for one file and immediately coalesces adjacent hunks.
717
+ /**
718
+ * Adds a changed line range to the entry for filePath, creating it if absent and merging overlaps or adjacent ranges.
719
+ *
720
+ * @param rangesByFile - Mutates the per-file range list for filePath in place.
721
+ * @param filePath - Target file path whose changed ranges are being updated.
722
+ * @param range - Inclusive line range to insert and merge.
723
+ * @returns Nothing. Mutates rangesByFile in place with the sorted, merged ranges for filePath.
724
+ */
397
725
  function addRange(rangesByFile: Map<string, ChangedRange[]>, filePath: string, range: ChangedRange): void {
398
726
  rangesByFile.set(filePath, mergeRanges([...(rangesByFile.get(filePath) ?? []), range]));
399
727
  }
400
728
 
401
- // Sorts and merges overlapping or adjacent line ranges so downstream checks stay deterministic.
729
+ /**
730
+ * Builds a sorted list of line ranges, merging overlaps and adjacency so downstream checks stay deterministic.
731
+ *
732
+ * @param ranges - Unsorted or potentially overlapping inclusive line ranges.
733
+ * @returns New sorted, non-overlapping, non-adjacent inclusive line ranges.
734
+ */
402
735
  function mergeRanges(ranges: ChangedRange[]): ChangedRange[] {
403
736
  const sorted = [...ranges].sort((left, right) => left.start - right.start || left.end - right.end);
404
737
  const merged: ChangedRange[] = [];
@@ -413,7 +746,23 @@ function mergeRanges(ranges: ChangedRange[]): ChangedRange[] {
413
746
  return merged;
414
747
  }
415
748
 
416
- // Spawns `git` through a fixed argv vector; callers construct argv arrays without interpolation.
417
- function gitOutput(args: string[]): string {
418
- return execFileSync("git", args, { encoding: "utf8" });
749
+ /**
750
+ * Spawns git with the caller's argument array and returns UTF-8 stdout, which can be empty when git has no changes to report.
751
+ *
752
+ * @param args - Git CLI flags and arguments passed directly to the executable.
753
+ * @param projectRoot - Working directory used for the Git subprocess.
754
+ * @returns UTF-8 standard output produced by Git.
755
+ * @throws {ChangedRegionError} If Git cannot read the changes from projectRoot.
756
+ */
757
+ function gitOutput(args: string[], projectRoot: string): string {
758
+ try {
759
+ return execFileSync("git", args, { cwd: projectRoot, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
760
+ } catch (error) {
761
+ // For example, `--since main` can fail in a shallow checkout where that branch is missing.
762
+ // When Git supplies no detail, the user still sees that the change selection failed.
763
+ const detail = error instanceof Error && "stderr" in error && typeof error.stderr === "string"
764
+ ? error.stderr.split(/\r?\n/u)[0]
765
+ : undefined;
766
+ throw new ChangedRegionError(`Unable to read the requested Git changes${detail ? `: ${detail}` : "."}`);
767
+ }
419
768
  }