@blundergoat/gruff-ts 0.4.0 → 0.5.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.
- package/CHANGELOG.md +41 -1
- package/README.md +16 -6
- package/SECURITY.md +2 -1
- package/docs/README.md +1 -4
- package/docs/agent-hook.md +14 -2
- package/docs/configuration.md +32 -1
- package/docs/dashboard.md +3 -3
- package/docs/reports-and-ci.md +15 -0
- package/docs/rules.md +35 -29
- package/package.json +1 -1
- package/src/analyser.ts +163 -53
- package/src/baseline.ts +39 -3
- package/src/blocks.ts +116 -77
- package/src/changed-regions.ts +59 -11
- package/src/class-rules.ts +226 -76
- package/src/cli-program.ts +61 -14
- package/src/cli.ts +1 -0
- package/src/comment-rules.ts +58 -13
- package/src/comment-scanner.ts +27 -0
- package/src/complexity-metrics.ts +244 -0
- package/src/config.ts +56 -16
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +9 -10
- package/src/discovery.ts +39 -19
- package/src/doc-rules.ts +22 -53
- package/src/findings-helpers.ts +127 -1
- package/src/findings.ts +4 -0
- package/src/fixture-purpose-rules.ts +39 -5
- package/src/github-actions-rules.ts +24 -1
- package/src/hook-contract.ts +85 -14
- package/src/init-config.ts +15 -5
- package/src/line-rules.ts +54 -5
- package/src/naming-pushers.ts +26 -5
- package/src/parsed-script.ts +652 -0
- package/src/process-exec-metadata.ts +16 -6
- package/src/profiles.ts +14 -0
- package/src/project-config-rules.ts +15 -10
- package/src/public-exports.ts +220 -0
- package/src/report-renderers.ts +55 -4
- package/src/rules.ts +11 -11
- package/src/scoring.ts +13 -4
- package/src/security-flow-rules.ts +169 -24
- package/src/sensitive-data-rules.ts +132 -78
- package/src/source-text.ts +4 -46
- package/src/test-block-rules.ts +118 -14
- package/src/test-fixtures.ts +4 -1
- package/src/text-scans.ts +8 -1
- package/src/types.ts +5 -3
package/src/blocks.ts
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
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";
|
|
5
5
|
import { hasLeadingCommentBeforeLines } from "./comment-scanner.ts";
|
|
6
|
+
import { baseComplexityMetrics, complexityMetrics as measureComplexity, type ComplexityMetrics } from "./complexity-metrics.ts";
|
|
6
7
|
import { type SourceFile } from "./discovery.ts";
|
|
7
8
|
import { makeFinding } from "./findings.ts";
|
|
8
|
-
import { escapeRegex, isGenericName, lineOffset } from "./findings-helpers.ts";
|
|
9
|
-
import {
|
|
9
|
+
import { escapeRegex, isGenericName, lineOffset, parameterNames } from "./findings-helpers.ts";
|
|
10
|
+
import { callableMatchPoints, type ParsedScript } from "./parsed-script.ts";
|
|
10
11
|
import type { Config, Finding, Pillar, Severity } from "./types.ts";
|
|
11
12
|
|
|
12
13
|
// Parsed callable body shared by every block-level rule (size, complexity, naming, docs). The
|
|
@@ -15,27 +16,28 @@ import type { Config, Finding, Pillar, Severity } from "./types.ts";
|
|
|
15
16
|
export interface FunctionBlock {
|
|
16
17
|
name: string;
|
|
17
18
|
params: string;
|
|
19
|
+
// AST parameter count; absent only for legacy regex-derived blocks.
|
|
20
|
+
parameterCount?: number;
|
|
21
|
+
// Shared syntax metric; absent only for legacy regex span probes.
|
|
22
|
+
complexityMetrics?: ComplexityMetrics;
|
|
23
|
+
// AST-known body presence; absent only for legacy regex-derived blocks.
|
|
24
|
+
hasBody?: boolean;
|
|
18
25
|
startLine: number;
|
|
19
26
|
lineCount: number;
|
|
20
27
|
body: string;
|
|
21
28
|
codeBody: string;
|
|
22
29
|
isPublic: boolean;
|
|
23
|
-
// True
|
|
24
|
-
//
|
|
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.
|
|
30
|
+
// True for exported/re-exported module APIs; unlike `isPublic`, class modifiers do not qualify.
|
|
31
|
+
// This selects warning-tier API docs while internal helpers remain advisory.
|
|
28
32
|
isExported: boolean;
|
|
29
33
|
isTest: boolean;
|
|
30
34
|
hasLeadingComment: boolean;
|
|
31
35
|
declarationLine: number;
|
|
32
36
|
}
|
|
33
37
|
|
|
34
|
-
// Working state for
|
|
35
|
-
//
|
|
36
|
-
//
|
|
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).
|
|
38
|
+
// Working state for one file's block discovery. Patterns are precompiled once, while
|
|
39
|
+
// `reExportedNames` carries the file-level module API classification that a declaration-line
|
|
40
|
+
// check would miss. CLI users reach this state whenever script block rules run.
|
|
39
41
|
interface FunctionBlockScan {
|
|
40
42
|
lines: string[];
|
|
41
43
|
codeLines: string[];
|
|
@@ -59,6 +61,8 @@ export interface BlockRuleContext {
|
|
|
59
61
|
block: FunctionBlock;
|
|
60
62
|
config: Config;
|
|
61
63
|
findings: Finding[];
|
|
64
|
+
complexityMetrics: ComplexityMetrics;
|
|
65
|
+
// Retained alias used by the generic-parameter naming gate.
|
|
62
66
|
cyclomatic: number;
|
|
63
67
|
functionBody: string;
|
|
64
68
|
}
|
|
@@ -109,16 +113,18 @@ export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Fi
|
|
|
109
113
|
});
|
|
110
114
|
}
|
|
111
115
|
|
|
112
|
-
//
|
|
113
|
-
//
|
|
114
|
-
// resulting struct is part of the stable rule-context contract every per-block helper consumes.
|
|
116
|
+
// Threads one parsed complexity result and body through each block rule. Legacy span-only callers
|
|
117
|
+
// receive base complexity because no extra parse is allowed; this preserves the report invariant.
|
|
115
118
|
export function blockRuleContext(file: SourceFile, block: FunctionBlock, config: Config, findings: Finding[]): BlockRuleContext {
|
|
119
|
+
// A regex-only caller has no shared syntax node, so it receives the neutral base measurement.
|
|
120
|
+
const sharedComplexityMetrics = block.complexityMetrics ?? baseComplexityMetrics();
|
|
116
121
|
return {
|
|
117
122
|
file,
|
|
118
123
|
block,
|
|
119
124
|
config,
|
|
120
125
|
findings,
|
|
121
|
-
|
|
126
|
+
complexityMetrics: sharedComplexityMetrics,
|
|
127
|
+
cyclomatic: sharedComplexityMetrics.cyclomatic,
|
|
122
128
|
functionBody: functionBodyContent(block.codeBody),
|
|
123
129
|
};
|
|
124
130
|
}
|
|
@@ -158,10 +164,11 @@ function pushFunctionLengthFinding(context: BlockRuleContext): void {
|
|
|
158
164
|
}
|
|
159
165
|
}
|
|
160
166
|
|
|
161
|
-
// Default threshold 7.
|
|
162
|
-
//
|
|
167
|
+
// Default threshold 7. Uses the actual AST parameter count from the shared parse; the comma split
|
|
168
|
+
// only remains as the fallback for regex-discovered blocks in non-script text, where commas inside
|
|
169
|
+
// generics, tuples, or defaults cannot occur. Reports `size.parameter-count` when exceeded.
|
|
163
170
|
function pushParameterCountFinding(context: BlockRuleContext): void {
|
|
164
|
-
const params = context.block.params.split(",").map((value) => value.trim()).filter(Boolean).length;
|
|
171
|
+
const params = context.block.parameterCount ?? context.block.params.split(",").map((value) => value.trim()).filter(Boolean).length;
|
|
165
172
|
const parameterCountThreshold = threshold(context.config, "size.parameter-count", 7);
|
|
166
173
|
if (params > parameterCountThreshold) {
|
|
167
174
|
context.findings.push(blockFindingWithMetadata({
|
|
@@ -176,8 +183,7 @@ function pushParameterCountFinding(context: BlockRuleContext): void {
|
|
|
176
183
|
}
|
|
177
184
|
}
|
|
178
185
|
|
|
179
|
-
// Default threshold 15.
|
|
180
|
-
// `blockRuleContext` for the pre-computed value. Reports `complexity.cyclomatic` when exceeded.
|
|
186
|
+
// Default threshold 15. Reports the shared syntax-node decision count to CLI and JSON users.
|
|
181
187
|
function pushCyclomaticFinding(context: BlockRuleContext): void {
|
|
182
188
|
const cyclomaticThreshold = threshold(context.config, "complexity.cyclomatic", 15);
|
|
183
189
|
if (context.cyclomatic > cyclomaticThreshold) {
|
|
@@ -188,15 +194,14 @@ function pushCyclomaticFinding(context: BlockRuleContext): void {
|
|
|
188
194
|
block: context.block,
|
|
189
195
|
severity: ruleSeverity(context.config, "complexity.cyclomatic", "warning"),
|
|
190
196
|
pillar: "complexity",
|
|
191
|
-
metadata: { complexity: context.cyclomatic, threshold: cyclomaticThreshold },
|
|
197
|
+
metadata: { complexity: context.cyclomatic, threshold: cyclomaticThreshold, breakdown: context.complexityMetrics.breakdown },
|
|
192
198
|
}));
|
|
193
199
|
}
|
|
194
200
|
}
|
|
195
201
|
|
|
196
|
-
// Default threshold 15.
|
|
197
|
-
// "deeply nested" intuition pure cyclomatic misses. Reports `complexity.cognitive` when exceeded.
|
|
202
|
+
// Default threshold 15. Reports decisions plus shared control-flow nesting to CLI and JSON users.
|
|
198
203
|
function pushCognitiveFinding(context: BlockRuleContext): void {
|
|
199
|
-
const cognitive = context.
|
|
204
|
+
const cognitive = context.complexityMetrics.cognitive;
|
|
200
205
|
const cognitiveThreshold = threshold(context.config, "complexity.cognitive", 15);
|
|
201
206
|
if (cognitive > cognitiveThreshold) {
|
|
202
207
|
context.findings.push(blockFindingWithMetadata({
|
|
@@ -206,7 +211,7 @@ function pushCognitiveFinding(context: BlockRuleContext): void {
|
|
|
206
211
|
block: context.block,
|
|
207
212
|
severity: ruleSeverity(context.config, "complexity.cognitive", "warning"),
|
|
208
213
|
pillar: "complexity",
|
|
209
|
-
metadata: { complexity: cognitive, threshold: cognitiveThreshold },
|
|
214
|
+
metadata: { complexity: cognitive, threshold: cognitiveThreshold, breakdown: context.complexityMetrics.breakdown },
|
|
210
215
|
}));
|
|
211
216
|
}
|
|
212
217
|
}
|
|
@@ -282,6 +287,11 @@ function pushUnusedParameterFindings(context: BlockRuleContext): void {
|
|
|
282
287
|
// overload signatures - all of which look like a function declaration ending in `;` rather than `{`,
|
|
283
288
|
// and have no real body to check for emptiness or parameter usage.
|
|
284
289
|
function isBodyLessDeclaration(block: FunctionBlock): boolean {
|
|
290
|
+
// The shared parse already knows; the text walk below only covers legacy regex-derived blocks,
|
|
291
|
+
// and it misreads a multi-line signature whose first line stops at the open paren.
|
|
292
|
+
if (block.hasBody !== undefined) {
|
|
293
|
+
return !block.hasBody;
|
|
294
|
+
}
|
|
285
295
|
for (const rawLine of block.codeBody.split("\n")) {
|
|
286
296
|
const trimmed = rawLine.trim();
|
|
287
297
|
if (trimmed === "" || trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
|
|
@@ -413,21 +423,6 @@ function terminalBareReturnLines(source: string): number[] {
|
|
|
413
423
|
return [];
|
|
414
424
|
}
|
|
415
425
|
|
|
416
|
-
// Splits on `,` then strips visibility modifiers, `...rest`, default values, and type annotations
|
|
417
|
-
// in that order. Final filter rejects entries whose name isn't a plain identifier - destructured
|
|
418
|
-
// parameters land in that bucket and are intentionally invisible to per-parameter rules.
|
|
419
|
-
export function parameterNames(params: string): Array<{ name: string; raw: string }> {
|
|
420
|
-
return params
|
|
421
|
-
.split(",")
|
|
422
|
-
.map((parameter) => parameter.trim())
|
|
423
|
-
.filter(Boolean)
|
|
424
|
-
.map((raw) => {
|
|
425
|
-
const stripped = raw.replace(/^(?:public|private|protected|readonly)\s+/, "").replace(/^\.\.\./, "");
|
|
426
|
-
const name = stripped.split(/[?:=]/)[0]?.trim() ?? "";
|
|
427
|
-
return { name, raw: stripped };
|
|
428
|
-
})
|
|
429
|
-
.filter((parameter) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(parameter.name));
|
|
430
|
-
}
|
|
431
426
|
|
|
432
427
|
// Detects the `const x = expr; return x;` pattern. The regex backreference `\1` enforces that the
|
|
433
428
|
// returned identifier matches the declared one - used by `waste.redundant-variable` to surface
|
|
@@ -440,48 +435,83 @@ function redundantVariableReturns(source: string): Array<{ name: string; lineOff
|
|
|
440
435
|
return results.filter((result) => result.name !== "");
|
|
441
436
|
}
|
|
442
437
|
|
|
443
|
-
// Deepest `{` / `}` nesting reached across the body, minus one so the body's own outer braces
|
|
444
|
-
// don't count. The `Math.max(0, …)` clamp protects against unbalanced inputs - feeds the nesting
|
|
445
|
-
// component of `complexity.cognitive` and must stay deterministic across runs.
|
|
446
|
-
export function maxNestingDepth(source: string): number {
|
|
447
|
-
let depth = 0;
|
|
448
|
-
let maxDepth = 0;
|
|
449
|
-
for (const character of source) {
|
|
450
|
-
if (character === "{") {
|
|
451
|
-
depth += 1;
|
|
452
|
-
maxDepth = Math.max(maxDepth, depth);
|
|
453
|
-
} else if (character === "}") {
|
|
454
|
-
depth = Math.max(0, depth - 1);
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
return Math.max(0, maxDepth - 1);
|
|
458
|
-
}
|
|
459
|
-
|
|
460
438
|
// Matches `test("…", …)` and `it("…", …)` openers. Used both by the function-block parser to
|
|
461
439
|
// pick the right pattern and by setup detection to skip the test wrapper line itself.
|
|
462
440
|
function isTestInvocationLine(line: string): boolean {
|
|
463
441
|
return /^\s*(?:test|it)\s*\(/.test(line);
|
|
464
442
|
}
|
|
465
443
|
|
|
466
|
-
//
|
|
467
|
-
//
|
|
468
|
-
|
|
469
|
-
export function functionBlocks(source: string, codeSource = source): FunctionBlock[] {
|
|
444
|
+
// Builds report blocks from the shared syntax tree while preserving anchors and fingerprints.
|
|
445
|
+
// Span-only utilities without a parse retain the legacy regex walk.
|
|
446
|
+
export function functionBlocks(source: string, codeSource = source, parsed?: ParsedScript): FunctionBlock[] {
|
|
470
447
|
const scan: FunctionBlockScan = {
|
|
471
448
|
lines: source.split(/\r?\n/),
|
|
472
449
|
codeLines: codeSource.split(/\r?\n/),
|
|
473
450
|
patterns: FUNCTION_BLOCK_PATTERNS,
|
|
474
451
|
reExportedNames: collectReExportedNames(codeSource),
|
|
475
452
|
};
|
|
476
|
-
const
|
|
453
|
+
const matchPoints = matchPointsFor(scan, parsed);
|
|
454
|
+
const ownedCallableNodes = new Set<import("typescript").Node>();
|
|
455
|
+
// Every AST-backed block owns one callable body; regex-only span probes have no syntax node.
|
|
456
|
+
for (const point of matchPoints) {
|
|
457
|
+
// A missing node means a caller requested the legacy regex discovery path without reparsing.
|
|
458
|
+
if (point.callableNode) {
|
|
459
|
+
ownedCallableNodes.add(point.callableNode);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
// Each stable block receives one metric result based on the final one-block-per-line ownership set.
|
|
463
|
+
return matchPoints.map((point) => functionBlockFromPoint(scan, point, ownedCallableNodes));
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// One callable hit used to build the block that report rules inspect.
|
|
467
|
+
// Parsed hits carry their node and exact range; legacy span probes carry only text coordinates.
|
|
468
|
+
// Empty optional fields mean the caller deliberately supplied no shared parse.
|
|
469
|
+
interface BlockMatchPoint {
|
|
470
|
+
lineIndex: number;
|
|
471
|
+
// AST-known first line of the declaration; regex points leave it absent and keep the name line.
|
|
472
|
+
declarationLineIndex?: number;
|
|
473
|
+
// AST-known end line; regex points keep the legacy brace walk instead.
|
|
474
|
+
endLineIndex?: number;
|
|
475
|
+
name: string;
|
|
476
|
+
params: string;
|
|
477
|
+
parameterCount?: number;
|
|
478
|
+
// AST-known body presence; regex points leave it absent and fall back to the text heuristic.
|
|
479
|
+
hasBody?: boolean;
|
|
480
|
+
// AST-backed visibility; regex points leave these absent and retain the text fallback.
|
|
481
|
+
isDirectlyExported?: boolean;
|
|
482
|
+
isExplicitlyPublic?: boolean;
|
|
483
|
+
isModuleScoped?: boolean;
|
|
484
|
+
callableNode?: import("typescript").Node;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// Chooses the discovery mode: AST points from the shared parse, or the legacy regex line walk.
|
|
488
|
+
function matchPointsFor(scan: FunctionBlockScan, parsed: ParsedScript | undefined): BlockMatchPoint[] {
|
|
489
|
+
// A normal script scan already owns one ParsedScript and must reuse its callable points here.
|
|
490
|
+
if (parsed) {
|
|
491
|
+
return callableMatchPoints(parsed).map((point) => ({
|
|
492
|
+
lineIndex: point.lineIndex,
|
|
493
|
+
declarationLineIndex: point.declarationLineIndex,
|
|
494
|
+
endLineIndex: point.endLineIndex,
|
|
495
|
+
name: point.name,
|
|
496
|
+
params: point.params,
|
|
497
|
+
parameterCount: point.parameterCount,
|
|
498
|
+
hasBody: point.hasBody,
|
|
499
|
+
isDirectlyExported: point.isDirectlyExported,
|
|
500
|
+
isExplicitlyPublic: point.isExplicitlyPublic,
|
|
501
|
+
isModuleScoped: point.isModuleScoped,
|
|
502
|
+
callableNode: point.callableNode,
|
|
503
|
+
}));
|
|
504
|
+
}
|
|
505
|
+
const points: BlockMatchPoint[] = [];
|
|
506
|
+
// Span-only utilities still use the legacy masked-line inventory without triggering a parse.
|
|
477
507
|
scan.codeLines.forEach((line, index) => {
|
|
478
508
|
const match = functionBlockMatch(scan, line, index);
|
|
479
|
-
|
|
480
|
-
|
|
509
|
+
// Only lines that contain a supported callable shape become legacy block points.
|
|
510
|
+
if (match) {
|
|
511
|
+
points.push({ lineIndex: index, name: match[1] ?? "", params: match[2] ?? "" });
|
|
481
512
|
}
|
|
482
|
-
blocks.push(functionBlockFromMatch(scan, match, index));
|
|
483
513
|
});
|
|
484
|
-
return
|
|
514
|
+
return points;
|
|
485
515
|
}
|
|
486
516
|
|
|
487
517
|
/*
|
|
@@ -560,25 +590,34 @@ function functionPatternMatch(pattern: RegExp, patternIndex: number, line: strin
|
|
|
560
590
|
return match;
|
|
561
591
|
}
|
|
562
592
|
|
|
563
|
-
// Promotes a
|
|
564
|
-
//
|
|
565
|
-
|
|
566
|
-
|
|
593
|
+
// Promotes a discovery point into the shared block used by report rules and context documentation.
|
|
594
|
+
// Parsed points receive one syntax metric; legacy span-only points keep that field absent.
|
|
595
|
+
function functionBlockFromPoint(scan: FunctionBlockScan, point: BlockMatchPoint, ownedCallableNodes: ReadonlySet<import("typescript").Node>): FunctionBlock {
|
|
596
|
+
const index = point.lineIndex;
|
|
567
597
|
const start = functionStartIndex(scan.lines, index);
|
|
568
|
-
const end = functionEndIndex(scan, index);
|
|
598
|
+
const end = point.endLineIndex ?? functionEndIndex(scan, index);
|
|
569
599
|
const body = scan.lines.slice(start, end + 1).join("\n");
|
|
570
600
|
const codeBody = scan.codeLines.slice(start, end + 1).join("\n");
|
|
601
|
+
// A missing callable node identifies a legacy range probe, where base metrics are chosen later.
|
|
602
|
+
const sharedComplexityMetrics = point.callableNode ? measureComplexity(point.callableNode, ownedCallableNodes) : undefined;
|
|
603
|
+
// Parsed blocks expose metrics to both consumers; absent values stay omitted for exact optionals.
|
|
571
604
|
return {
|
|
572
|
-
name:
|
|
573
|
-
params:
|
|
605
|
+
name: point.name,
|
|
606
|
+
params: point.params,
|
|
607
|
+
...(point.parameterCount === undefined ? {} : { parameterCount: point.parameterCount }),
|
|
608
|
+
...(point.hasBody === undefined ? {} : { hasBody: point.hasBody }),
|
|
609
|
+
...(sharedComplexityMetrics === undefined ? {} : { complexityMetrics: sharedComplexityMetrics }),
|
|
574
610
|
startLine: start + 1,
|
|
575
611
|
lineCount: end - start + 1,
|
|
576
612
|
body,
|
|
577
613
|
codeBody,
|
|
578
|
-
isPublic: /\bexport\b|\bpublic\b/.test(scan.codeLines.slice(start, index + 1).join("\n")),
|
|
579
|
-
isExported: /^\s*export\b/.test(scan.codeLines[index] ?? "")
|
|
614
|
+
isPublic: point.isExplicitlyPublic ?? /\bexport\b|\bpublic\b/.test(scan.codeLines.slice(start, index + 1).join("\n")),
|
|
615
|
+
isExported: (point.isDirectlyExported ?? /^\s*export\b/.test(scan.codeLines[index] ?? ""))
|
|
616
|
+
|| point.isModuleScoped !== false && scan.reExportedNames.has(point.name),
|
|
580
617
|
isTest: isTestInvocationLine(scan.codeLines[index] ?? ""),
|
|
581
|
-
|
|
618
|
+
// Look upward from the declaration, not the name: a split-line `export async function` header
|
|
619
|
+
// would otherwise hide the declaration's own docblock behind its modifier line.
|
|
620
|
+
hasLeadingComment: hasLeadingCommentBeforeLines(scan.lines, (point.declarationLineIndex ?? index) + 1),
|
|
582
621
|
declarationLine: index + 1,
|
|
583
622
|
};
|
|
584
623
|
}
|
package/src/changed-regions.ts
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
import { execFileSync } from "node:child_process";
|
|
4
4
|
import { functionBlocks } from "./blocks.ts";
|
|
5
5
|
import type { SourceFile } from "./discovery.ts";
|
|
6
|
+
import type { ParsedScript } from "./parsed-script.ts";
|
|
6
7
|
import { maskNonCode } from "./source-text.ts";
|
|
7
|
-
import type { AnalysisOptions, ChangedScopeMode, Finding } from "./types.ts";
|
|
8
|
+
import type { AnalysisOptions, ChangedScopeMode, Finding, RunDiagnostic } from "./types.ts";
|
|
8
9
|
|
|
9
10
|
// Inclusive line range from a changed hunk or explicit `--changed-ranges` input.
|
|
10
11
|
export interface ChangedRange {
|
|
@@ -27,6 +28,7 @@ export interface ChangedRegionScope {
|
|
|
27
28
|
interface SourceSnapshot {
|
|
28
29
|
file: SourceFile;
|
|
29
30
|
source: string;
|
|
31
|
+
parsed?: ParsedScript;
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
// Named source span used to keep symbol-scope findings when their declaration overlaps a hunk.
|
|
@@ -69,7 +71,33 @@ export function changedRegionScope(options: AnalysisOptions): ChangedRegionScope
|
|
|
69
71
|
return undefined;
|
|
70
72
|
}
|
|
71
73
|
|
|
74
|
+
// Diagnostic types that describe one analysed file's content or readability. Only these are
|
|
75
|
+
// file-scoped under diff filtering; operational diagnostics (missing paths, history errors) always
|
|
76
|
+
// stay, because they describe the request rather than an unchanged context file.
|
|
77
|
+
const FILE_CONTENT_DIAGNOSTIC_TYPES = new Set(["parse-error", "read-error"]);
|
|
78
|
+
|
|
79
|
+
/*
|
|
80
|
+
* Applies the file-scoped diagnostics policy to a changed-region run: a full scan keeps every
|
|
81
|
+
* diagnostic; explicit `--changed-ranges` keeps every diagnostic of each requested file (a syntax
|
|
82
|
+
* error breaks parsing of the whole file, so ranges never filter diagnostics); `--diff`/`--since`
|
|
83
|
+
* keeps only diagnostics from changed target files, so a pre-existing broken context file no
|
|
84
|
+
* longer fails a clean diff. Operational diagnostics are never dropped.
|
|
85
|
+
*/
|
|
86
|
+
export function filterScopedDiagnostics(diagnostics: RunDiagnostic[], scope: ChangedRegionScope | undefined): RunDiagnostic[] {
|
|
87
|
+
if (!scope || scope.explicitRanges !== undefined) {
|
|
88
|
+
return diagnostics;
|
|
89
|
+
}
|
|
90
|
+
return diagnostics.filter((diagnostic) => {
|
|
91
|
+
// Operational diagnostics (missing-path, history-error) describe the request, not file content.
|
|
92
|
+
if (!diagnostic.filePath || !FILE_CONTENT_DIAGNOSTIC_TYPES.has(diagnostic.diagnosticType)) {
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
return scope.changedFiles.has(diagnostic.filePath) || scope.wholeFiles.has(diagnostic.filePath);
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
72
99
|
// Applies changed-region filtering to findings and reports how many pre-existing findings dropped.
|
|
100
|
+
// Invariant: kept plus suppressedCount always equals the pre-filter total - the hook's arithmetic contract.
|
|
73
101
|
export function filterChangedFindings(
|
|
74
102
|
findings: Finding[],
|
|
75
103
|
scope: ChangedRegionScope | undefined,
|
|
@@ -91,7 +119,8 @@ export function filterChangedFindings(
|
|
|
91
119
|
return { findings: kept, suppressedCount };
|
|
92
120
|
}
|
|
93
121
|
|
|
94
|
-
// Keeps a finding when its own line, enclosing declaration, or changed-file scope intersects the
|
|
122
|
+
// Keeps a finding when its own line, enclosing declaration, or changed-file scope intersects the
|
|
123
|
+
// change. Invariant: findings outside the requested change must stay suppressed - the agent-gate contract.
|
|
95
124
|
function isFindingInChangedScope(
|
|
96
125
|
finding: Finding,
|
|
97
126
|
scope: ChangedRegionScope,
|
|
@@ -117,6 +146,18 @@ function isFindingInChangedScope(
|
|
|
117
146
|
if (overlapsAny(findingRange, changedRanges)) {
|
|
118
147
|
return true;
|
|
119
148
|
}
|
|
149
|
+
return symbolScopeWidensFinding(finding, scope, sources, declarationsByFile, changedRanges);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Symbol scope widens a finding through its enclosing declaration: an edit anywhere inside a
|
|
153
|
+
// callable keeps that callable's findings. Invariant: file-wide findings must never widen this way.
|
|
154
|
+
function symbolScopeWidensFinding(
|
|
155
|
+
finding: Finding,
|
|
156
|
+
scope: ChangedRegionScope,
|
|
157
|
+
sources: Map<string, SourceSnapshot>,
|
|
158
|
+
declarationsByFile: Map<string, DeclarationRegion[]>,
|
|
159
|
+
changedRanges: ChangedRange[],
|
|
160
|
+
): boolean {
|
|
120
161
|
if (scope.mode !== "symbol" || isFileWideFinding(finding)) {
|
|
121
162
|
return false;
|
|
122
163
|
}
|
|
@@ -149,6 +190,7 @@ function rangesForFindingFile(scope: ChangedRegionScope, filePath: string): Chan
|
|
|
149
190
|
}
|
|
150
191
|
|
|
151
192
|
// Resolves the narrowest declaration around a finding so symbol-scope mode can keep whole callables.
|
|
193
|
+
// Invariant: the smallest enclosing span wins, so sibling declarations never widen each other's findings.
|
|
152
194
|
function enclosingDeclaration(
|
|
153
195
|
finding: Finding,
|
|
154
196
|
sources: Map<string, SourceSnapshot>,
|
|
@@ -160,7 +202,7 @@ function enclosingDeclaration(
|
|
|
160
202
|
}
|
|
161
203
|
let declarations = declarationsByFile.get(finding.filePath);
|
|
162
204
|
if (!declarations) {
|
|
163
|
-
declarations = declarationRegions(source.source);
|
|
205
|
+
declarations = declarationRegions(source.source, source.parsed);
|
|
164
206
|
declarationsByFile.set(finding.filePath, declarations);
|
|
165
207
|
}
|
|
166
208
|
const line = finding.line ?? 1;
|
|
@@ -172,10 +214,10 @@ function enclosingDeclaration(
|
|
|
172
214
|
}
|
|
173
215
|
|
|
174
216
|
// Combines function and class/interface spans into one declaration inventory per source file.
|
|
175
|
-
function declarationRegions(source: string): DeclarationRegion[] {
|
|
217
|
+
function declarationRegions(source: string, parsed?: ParsedScript): DeclarationRegion[] {
|
|
176
218
|
const codeSource = maskNonCode(source);
|
|
177
219
|
return [
|
|
178
|
-
...functionBlocks(source, codeSource).map((block) => ({
|
|
220
|
+
...functionBlocks(source, codeSource, parsed).map((block) => ({
|
|
179
221
|
name: block.name,
|
|
180
222
|
start: block.startLine,
|
|
181
223
|
end: block.startLine + block.lineCount - 1,
|
|
@@ -255,25 +297,31 @@ function parseChangedRange(rawRange: string): ChangedRange {
|
|
|
255
297
|
return { start, end };
|
|
256
298
|
}
|
|
257
299
|
|
|
258
|
-
|
|
300
|
+
/*
|
|
301
|
+
* Produces a changed-region scope from a named git diff mode or arbitrary git ref. Every git diff
|
|
302
|
+
* runs in git's relative-path mode, so paths arrive relative to the analysis root (the process
|
|
303
|
+
* cwd) and match finding display paths even when the scan starts from a nested package directory
|
|
304
|
+
* inside the repository. Invariant: from the repo root that mode is a no-op, so root-run diffs
|
|
305
|
+
* are byte-identical to the previous behavior.
|
|
306
|
+
*/
|
|
259
307
|
function gitDiffScope(mode: string, changedScope: ChangedScopeMode): ChangedRegionScope {
|
|
260
308
|
if (mode === "staged") {
|
|
261
|
-
return parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope);
|
|
309
|
+
return parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff", "--relative"]), changedScope);
|
|
262
310
|
}
|
|
263
311
|
if (mode === "unstaged") {
|
|
264
|
-
return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope);
|
|
312
|
+
return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff", "--relative"]), changedScope);
|
|
265
313
|
}
|
|
266
314
|
if (mode === "working-tree") {
|
|
267
315
|
return mergeScopes(
|
|
268
316
|
[
|
|
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),
|
|
317
|
+
parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff", "--relative"]), changedScope),
|
|
318
|
+
parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff", "--relative"]), changedScope),
|
|
271
319
|
untrackedFileScope(changedScope),
|
|
272
320
|
],
|
|
273
321
|
changedScope,
|
|
274
322
|
);
|
|
275
323
|
}
|
|
276
|
-
return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff", "--end-of-options", mode]), changedScope);
|
|
324
|
+
return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff", "--relative", "--end-of-options", mode]), changedScope);
|
|
277
325
|
}
|
|
278
326
|
|
|
279
327
|
// Parses a unified diff into file-level and hunk-level scope.
|