@blundergoat/gruff-ts 0.3.2 → 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 +54 -1
- package/README.md +16 -6
- package/SECURITY.md +2 -1
- package/docs/README.md +1 -4
- package/docs/agent-hook.md +15 -3
- package/docs/configuration.md +47 -1
- package/docs/dashboard.md +3 -3
- package/docs/reports-and-ci.md +36 -0
- package/docs/rules.md +52 -37
- package/package.json +1 -1
- package/src/analyser.ts +540 -154
- package/src/baseline-options.ts +90 -0
- package/src/baseline.ts +39 -3
- package/src/blocks.ts +116 -77
- package/src/changed-regions.ts +80 -11
- package/src/class-rules.ts +226 -76
- package/src/cli-program.ts +65 -15
- package/src/cli.ts +4 -2
- 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/dead-code-rules.ts +10 -3
- package/src/discovery.ts +66 -22
- 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 +120 -27
- package/src/init-config.ts +15 -5
- package/src/line-rules.ts +175 -19
- package/src/naming-pushers.ts +26 -5
- package/src/parsed-script.ts +652 -0
- package/src/process-exec-metadata.ts +163 -0
- package/src/profiles.ts +14 -0
- package/src/project-config-rules.ts +36 -18
- package/src/project-rules.ts +159 -42
- package/src/public-exports.ts +220 -0
- package/src/report-renderers.ts +58 -4
- package/src/rules.ts +15 -15
- package/src/scoring.ts +13 -4
- package/src/security-flow-rules.ts +169 -24
- package/src/sensitive-data-rules.ts +256 -80
- package/src/source-text.ts +9 -26
- package/src/static-analysis-redundant-rules.ts +46 -2
- 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 +17 -0
package/src/findings.ts
CHANGED
|
@@ -10,6 +10,9 @@ interface FindingInput {
|
|
|
10
10
|
filePath: string;
|
|
11
11
|
line?: number;
|
|
12
12
|
endLine?: number;
|
|
13
|
+
// One-based match column. Deliberately NOT part of the fingerprint hash (ADR-017): it only
|
|
14
|
+
// discriminates same-line occurrences in report dedupe and enriches SARIF/JSON locations.
|
|
15
|
+
column?: number;
|
|
13
16
|
severity: Severity;
|
|
14
17
|
pillar: Pillar;
|
|
15
18
|
confidence: Confidence;
|
|
@@ -32,6 +35,7 @@ function makeFinding(input: FindingInput): Finding {
|
|
|
32
35
|
filePath: input.filePath,
|
|
33
36
|
...(input.line ? { line: input.line } : {}),
|
|
34
37
|
...(input.endLine ? { endLine: input.endLine } : {}),
|
|
38
|
+
...(input.column ? { column: input.column } : {}),
|
|
35
39
|
severity: input.severity,
|
|
36
40
|
pillar: input.pillar,
|
|
37
41
|
secondaryPillars: [],
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// pass - template-literal fixtures, generated array fixtures, and high-setup test blocks - then
|
|
3
3
|
// reports `docs.fixture-purpose-missing` for each candidate without a nearby explanation comment.
|
|
4
4
|
import { type FunctionBlock, setupLineCount } from "./blocks.ts";
|
|
5
|
-
import { type CommentRecord } from "./comment-scanner.ts";
|
|
5
|
+
import { combinedContextLineComment, type CommentRecord } from "./comment-scanner.ts";
|
|
6
6
|
import { type SourceFile } from "./discovery.ts";
|
|
7
7
|
import { makeFinding } from "./findings.ts";
|
|
8
8
|
import { isFixtureLikePath, isTestPath } from "./project-rules.ts";
|
|
@@ -50,14 +50,14 @@ export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
|
|
|
50
50
|
findings.push(
|
|
51
51
|
makeFinding({
|
|
52
52
|
ruleId: "docs.fixture-purpose-missing",
|
|
53
|
-
message:
|
|
53
|
+
message: fixturePurposeMessage(candidate),
|
|
54
54
|
filePath: file.displayPath,
|
|
55
55
|
line: candidate.line,
|
|
56
56
|
severity: "advisory",
|
|
57
57
|
pillar: "documentation",
|
|
58
58
|
confidence: "medium",
|
|
59
59
|
symbol: candidate.symbol,
|
|
60
|
-
remediation:
|
|
60
|
+
remediation: fixturePurposeRemediation(candidate),
|
|
61
61
|
metadata: {
|
|
62
62
|
targetKind: candidate.targetKind,
|
|
63
63
|
fixtureLines: candidate.lineCount,
|
|
@@ -67,6 +67,24 @@ export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
|
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
// The finding is anchored where the accepted comment position is, so the message must name the
|
|
71
|
+
// construct at that anchor: the test declaration for setup candidates, the fixture otherwise.
|
|
72
|
+
function fixturePurposeMessage(candidate: FixturePurposeCandidate): string {
|
|
73
|
+
if (candidate.targetKind === "test-setup") {
|
|
74
|
+
return `Test \`${candidate.symbol}\` builds a large fixture setup without a purpose comment above the test.`;
|
|
75
|
+
}
|
|
76
|
+
return `Large fixture source near \`${candidate.symbol}\` is missing a purpose comment.`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// The stated fix must be the fix that clears the finding: both texts name the accepted comment
|
|
80
|
+
// positions that `hasFixturePurposeComment` checks.
|
|
81
|
+
function fixturePurposeRemediation(candidate: FixturePurposeCandidate): string {
|
|
82
|
+
if (candidate.targetKind === "test-setup") {
|
|
83
|
+
return "Add a comment directly above the test declaration explaining what scanner path, regression, or fixture behavior this setup covers.";
|
|
84
|
+
}
|
|
85
|
+
return "Add a comment on or directly above the fixture explaining what scanner path, regression, or fixture behavior this source covers.";
|
|
86
|
+
}
|
|
87
|
+
|
|
70
88
|
// Three candidate kinds collected in one pass: template-literal fixtures, generated array fixtures,
|
|
71
89
|
// and test setup blocks. `occupiedLines` tracks the first two so the third doesn't double-report.
|
|
72
90
|
function fixturePurposeCandidates(source: string, codeSource: string, blocks: FunctionBlock[]): FixturePurposeCandidate[] {
|
|
@@ -289,13 +307,29 @@ function closingTemplateLiteralIndex(source: string, startIndex: number): number
|
|
|
289
307
|
|
|
290
308
|
// Two acceptable positions: a comment on the candidate line itself, or one directly above with
|
|
291
309
|
// nothing but blank lines in between. Anything farther away cannot be claimed as documentation.
|
|
310
|
+
// A stacked `//` header counts as one comment, so a purpose statement on an earlier line clears.
|
|
292
311
|
function hasFixturePurposeComment(lines: string[], comments: CommentRecord[], line: number): boolean {
|
|
293
312
|
const sameLine = comments.find((comment) => comment.line <= line && comment.endLine >= line);
|
|
294
|
-
if (sameLine &&
|
|
313
|
+
if (sameLine && isFixturePurposeComment(sameLine.text)) {
|
|
295
314
|
return true;
|
|
296
315
|
}
|
|
297
316
|
const leading = leadingFixturePurposeComment(lines, comments, line);
|
|
298
|
-
return Boolean(leading &&
|
|
317
|
+
return Boolean(leading && isFixturePurposeComment(combinedContextLineComment(comments, leading).text));
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// This word-count threshold accepts a comment as a purpose statement even without the vocabulary
|
|
321
|
+
// fast path, because grading wording by keyword list sent maintainers into rewrite loops when a
|
|
322
|
+
// genuine explanation missed the exact words. Shorter comments still need a vocabulary word.
|
|
323
|
+
const FIXTURE_PURPOSE_MIN_WORDS = 8;
|
|
324
|
+
|
|
325
|
+
// Either acceptance path used by `hasFixturePurposeComment`: vocabulary or substantive prose.
|
|
326
|
+
function isFixturePurposeComment(text: string): boolean {
|
|
327
|
+
return hasFixturePurposeMarker(text) || fixtureCommentWordCount(text) >= FIXTURE_PURPOSE_MIN_WORDS;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// Counts word-like tokens; punctuation-only fragments do not make a comment substantive.
|
|
331
|
+
function fixtureCommentWordCount(text: string): number {
|
|
332
|
+
return text.split(/\s+/).filter((token) => /[A-Za-z0-9]/.test(token)).length;
|
|
299
333
|
}
|
|
300
334
|
|
|
301
335
|
// Like `leadingCommentForLine` but with the fixture-specific blank-gap predicate that allows for
|
|
@@ -41,19 +41,38 @@ interface WorkflowCommand {
|
|
|
41
41
|
line: WorkflowLine;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
// GitHub's 2026-07-12 workflow table defines the current write-capable keys below.
|
|
45
|
+
// `repository-projects` remains so users scanning legacy Enterprise workflows still see the risk.
|
|
44
46
|
const WRITE_PERMISSION_SCOPES = new Set([
|
|
45
47
|
"actions",
|
|
48
|
+
"artifact-metadata",
|
|
49
|
+
"attestations",
|
|
46
50
|
"checks",
|
|
51
|
+
"code-quality",
|
|
47
52
|
"contents",
|
|
48
53
|
"deployments",
|
|
54
|
+
"discussions",
|
|
55
|
+
"id-token",
|
|
49
56
|
"issues",
|
|
50
57
|
"packages",
|
|
58
|
+
"pages",
|
|
51
59
|
"pull-requests",
|
|
52
60
|
"repository-projects",
|
|
53
61
|
"security-events",
|
|
54
62
|
"statuses",
|
|
55
63
|
]);
|
|
56
64
|
|
|
65
|
+
// These two scopes mint a short-lived OIDC token or a build attestation. Neither grants write access
|
|
66
|
+
// to any repository resource, and GitHub documents both as the recommended alternative to storing
|
|
67
|
+
// long-lived credentials, so a workflow that requests them is not over-permissioned. Reporting them
|
|
68
|
+
// pushed users away from keyless auth and toward the static secrets this pillar exists to remove.
|
|
69
|
+
// They still reach `broadPermissionSignal`, where a pull_request_target workflow hands that minting
|
|
70
|
+
// power to untrusted pull-request code.
|
|
71
|
+
const CAPABILITY_PERMISSION_SCOPES = new Set([
|
|
72
|
+
"attestations",
|
|
73
|
+
"id-token",
|
|
74
|
+
]);
|
|
75
|
+
|
|
57
76
|
// Stable rule contract: workflow-only checks ignore non-workflow YAML so example docs avoid findings.
|
|
58
77
|
function analyseGithubActionsRules(file: SourceFile, source: string, findings: Finding[]): void {
|
|
59
78
|
if (!isGithubWorkflowPath(file.displayPath)) {
|
|
@@ -196,10 +215,14 @@ function closeBlockWhenOutdented(state: IndentedBlockState, line: WorkflowLine):
|
|
|
196
215
|
}
|
|
197
216
|
}
|
|
198
217
|
|
|
199
|
-
// Extracts
|
|
218
|
+
// Extracts the write scopes that grant a repository resource, which is what this rule reports.
|
|
200
219
|
function scopedWritePermission(line: WorkflowLine): string | undefined {
|
|
201
220
|
const scoped = line.trimmed.match(/^([a-z-]+):\s*write\b/i);
|
|
202
221
|
const scope = scoped?.[1] ?? "";
|
|
222
|
+
// A capability scope grants no repository resource, so requesting one is not a broad permission.
|
|
223
|
+
if (CAPABILITY_PERMISSION_SCOPES.has(scope)) {
|
|
224
|
+
return undefined;
|
|
225
|
+
}
|
|
203
226
|
return WRITE_PERMISSION_SCOPES.has(scope) ? scope : undefined;
|
|
204
227
|
}
|
|
205
228
|
|
package/src/hook-contract.ts
CHANGED
|
@@ -12,7 +12,10 @@ import type { AnalysisOptions, AnalysisReport, Finding, Severity, SkippedPath }
|
|
|
12
12
|
|
|
13
13
|
type HookScope = "line" | "symbol" | "file" | "project";
|
|
14
14
|
type FlagOrder = "any" | "flags-before-path";
|
|
15
|
-
type
|
|
15
|
+
type HookAnalysisViews = { currentReport: AnalysisReport; scopedReport: AnalysisReport };
|
|
16
|
+
type HookAnalysisRunner = ((options: AnalysisOptions) => AnalysisReport) & {
|
|
17
|
+
hookViews?: (currentOptions: AnalysisOptions, scopedOptions: AnalysisOptions, hasChangedRegion: boolean) => HookAnalysisViews;
|
|
18
|
+
};
|
|
16
19
|
|
|
17
20
|
// Inputs for one hook render: full-scan options, changed-region options, and optional baseline/diff
|
|
18
21
|
// bases used for new-only filtering.
|
|
@@ -29,11 +32,23 @@ interface HookReport {
|
|
|
29
32
|
contractVersion: "gruff.hook.v1";
|
|
30
33
|
analyzer: { name: "gruff-ts"; version: string };
|
|
31
34
|
findings: HookFinding[];
|
|
35
|
+
// File-scoped parse/read diagnostics relevant to the analysed change, reported in-band. The
|
|
36
|
+
// default hook exit stays 0; only an explicit --fail-on-diagnostics run turns these into exit 2.
|
|
37
|
+
diagnostics: HookDiagnostic[];
|
|
32
38
|
suppressed: { count: number };
|
|
33
39
|
ignored: { paths: SkippedPath[] };
|
|
34
40
|
config: { schemaOk: boolean; error: string | null };
|
|
35
41
|
}
|
|
36
42
|
|
|
43
|
+
// One diagnostic projected into the hook contract: what kind of problem, where, and the message a
|
|
44
|
+
// consumer can surface. `file`/`line` are absent for operational diagnostics with no anchor.
|
|
45
|
+
interface HookDiagnostic {
|
|
46
|
+
type: string;
|
|
47
|
+
message: string;
|
|
48
|
+
file?: string;
|
|
49
|
+
line?: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
37
52
|
// A finding projected into the hook contract, with enum scope and non-null remediation, keyed for
|
|
38
53
|
// new-only tracking by the stable identity and fingerprint.
|
|
39
54
|
interface HookFinding {
|
|
@@ -44,6 +59,9 @@ interface HookFinding {
|
|
|
44
59
|
file: string;
|
|
45
60
|
line?: number;
|
|
46
61
|
endLine?: number;
|
|
62
|
+
// One-based match column, present when the scanner pinpointed the occurrence. Two secrets on one
|
|
63
|
+
// line share every other field, so this is the only thing that lets a consumer tell them apart.
|
|
64
|
+
column?: number;
|
|
47
65
|
symbol: string | null;
|
|
48
66
|
message: string;
|
|
49
67
|
remediation: string;
|
|
@@ -83,23 +101,35 @@ export function renderHookCapabilities(): string {
|
|
|
83
101
|
stableIdentity: true,
|
|
84
102
|
ignoreReport: true,
|
|
85
103
|
newOnly: true,
|
|
104
|
+
// Producer advertisement only: diagnostics are always reported in-band; the advertised
|
|
105
|
+
// failOnDiagnostics flag is the explicit consumer request that changes exit semantics.
|
|
106
|
+
diagnostics: true,
|
|
86
107
|
},
|
|
87
|
-
flags: { changedRanges: "--changed-ranges", diff: "--diff", baseline: "--baseline" },
|
|
108
|
+
flags: { changedRanges: "--changed-ranges", diff: "--diff", baseline: "--baseline", failOnDiagnostics: "--fail-on-diagnostics" },
|
|
88
109
|
flagOrder: "any" satisfies FlagOrder,
|
|
89
110
|
}, null, 2) + "\n";
|
|
90
111
|
}
|
|
91
112
|
|
|
92
|
-
// Runs the analysis
|
|
93
|
-
//
|
|
113
|
+
// Runs the analysis and projects it into the gruff.hook.v1 envelope: scoped findings, suppressed
|
|
114
|
+
// count, ignored paths, and a schema-ok config block.
|
|
94
115
|
export function renderHookReport(runAnalyse: HookAnalysisRunner, input: HookReportInput): string {
|
|
95
|
-
const currentReport = runAnalyse
|
|
96
|
-
const scopedReport = input.hasChangedRegion ? runAnalyse(input.scopedOptions) : currentReport;
|
|
116
|
+
const { currentReport, scopedReport } = hookAnalysisViews(runAnalyse, input);
|
|
97
117
|
const baseIdentities = hookBaseIdentities(runAnalyse, input, currentReport);
|
|
98
118
|
const findings = hookFindings(currentReport, scopedReport, input.hasChangedRegion, baseIdentities);
|
|
99
119
|
const suppressedCount = hookSuppressedCount(scopedReport, findings, input.hasChangedRegion);
|
|
100
120
|
return JSON.stringify(hookReport(scopedReport, findings, suppressedCount, true, null), null, 2) + "\n";
|
|
101
121
|
}
|
|
102
122
|
|
|
123
|
+
// Selects the optimized hook view when available, otherwise falls back to one or two analyse calls.
|
|
124
|
+
function hookAnalysisViews(runAnalyse: HookAnalysisRunner, input: HookReportInput): HookAnalysisViews {
|
|
125
|
+
if (runAnalyse.hookViews) {
|
|
126
|
+
return runAnalyse.hookViews(input.currentOptions, input.scopedOptions, input.hasChangedRegion);
|
|
127
|
+
}
|
|
128
|
+
const currentReport = runAnalyse(input.currentOptions);
|
|
129
|
+
const scopedReport = input.hasChangedRegion ? runAnalyse(input.scopedOptions) : currentReport;
|
|
130
|
+
return { currentReport, scopedReport };
|
|
131
|
+
}
|
|
132
|
+
|
|
103
133
|
// Emits a gruff.hook.v1 envelope for an operational failure (config rejected, bad baseline, git
|
|
104
134
|
// error) so the consumer always receives JSON with config.error set instead of a crash.
|
|
105
135
|
export function renderHookConfigError(message: string, remediation: string): string {
|
|
@@ -107,24 +137,45 @@ export function renderHookConfigError(message: string, remediation: string): str
|
|
|
107
137
|
return JSON.stringify(hookReport(undefined, [], 0, false, error), null, 2) + "\n";
|
|
108
138
|
}
|
|
109
139
|
|
|
110
|
-
// Assembles the gruff.hook.v1 envelope (sorted findings, suppressed count, ignored
|
|
111
|
-
// as the stable gruff.hook.v1 output contract.
|
|
140
|
+
// Assembles the gruff.hook.v1 envelope (sorted findings, diagnostics, suppressed count, ignored
|
|
141
|
+
// paths, config) as the stable gruff.hook.v1 output contract.
|
|
112
142
|
function hookReport(report: AnalysisReport | undefined, findings: HookFinding[], suppressedCount: number, isSchemaOk: boolean, error: string | null): HookReport {
|
|
113
143
|
return {
|
|
114
144
|
contractVersion: HOOK_CONTRACT_VERSION,
|
|
115
145
|
analyzer: analyzerInfo(),
|
|
116
146
|
findings: sortHookFindings(findings),
|
|
147
|
+
diagnostics: (report?.diagnostics ?? []).map(toHookDiagnostic),
|
|
117
148
|
suppressed: { count: suppressedCount },
|
|
118
149
|
ignored: { paths: report?.paths.skipped ?? [] },
|
|
119
150
|
config: { schemaOk: isSchemaOk, error },
|
|
120
151
|
};
|
|
121
152
|
}
|
|
122
153
|
|
|
154
|
+
// Projects one run diagnostic into the hook contract's shape; never throws - absent anchors are omitted.
|
|
155
|
+
function toHookDiagnostic(diagnostic: { diagnosticType: string; message: string; filePath?: string; line?: number }): HookDiagnostic {
|
|
156
|
+
return {
|
|
157
|
+
type: diagnostic.diagnosticType,
|
|
158
|
+
message: diagnostic.message,
|
|
159
|
+
...(diagnostic.filePath === undefined ? {} : { file: diagnostic.filePath }),
|
|
160
|
+
...(diagnostic.line === undefined ? {} : { line: diagnostic.line }),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Counts the diagnostics in a rendered gruff.hook.v1 envelope so the CLI can apply the explicit
|
|
165
|
+
// --fail-on-diagnostics exit policy without re-running analysis or duplicating envelope knowledge.
|
|
166
|
+
export function hookRenderedDiagnosticsCount(renderedEnvelope: string): number {
|
|
167
|
+
const payload = JSON.parse(renderedEnvelope) as { diagnostics?: unknown[] };
|
|
168
|
+
return Array.isArray(payload.diagnostics) ? payload.diagnostics.length : 0;
|
|
169
|
+
}
|
|
170
|
+
|
|
123
171
|
// Analyzer identity block shared by the capability and report envelopes.
|
|
124
172
|
function analyzerInfo(): { name: "gruff-ts"; version: string } {
|
|
125
173
|
return { name: "gruff-ts", version: VERSION };
|
|
126
174
|
}
|
|
127
175
|
|
|
176
|
+
// Builds the hook finding list: changed-region scoping drops inherited file findings, then
|
|
177
|
+
// new-only filtering re-admits file/project findings absent from the base identities.
|
|
178
|
+
// Invariant: suppressed.count arithmetic must stay exact across both filtering stages.
|
|
128
179
|
function hookFindings(
|
|
129
180
|
currentReport: AnalysisReport,
|
|
130
181
|
scopedReport: AnalysisReport,
|
|
@@ -133,11 +184,13 @@ function hookFindings(
|
|
|
133
184
|
): HookFinding[] {
|
|
134
185
|
const scopedFindings = scopedReport.findings
|
|
135
186
|
.map(toHookFinding)
|
|
136
|
-
.filter((finding) => !hasChangedRegion ||
|
|
187
|
+
.filter((finding) => !hasChangedRegion || finding.scope !== "file");
|
|
137
188
|
const withNewFileAndProject = hasChangedRegion && baseIdentities
|
|
138
189
|
? [...scopedFindings, ...newFileAndProjectFindings(currentReport, scopedFindings, baseIdentities)]
|
|
139
190
|
: scopedFindings;
|
|
140
|
-
return baseIdentities
|
|
191
|
+
return baseIdentities
|
|
192
|
+
? withNewFileAndProject.filter((finding) => !baselineMatchIdentities(finding).some((identity) => baseIdentities.has(identity)))
|
|
193
|
+
: withNewFileAndProject;
|
|
141
194
|
}
|
|
142
195
|
|
|
143
196
|
// Collects file- and project-scope findings that are new since the base, excluding any already
|
|
@@ -175,6 +228,7 @@ function toHookFinding(finding: Finding): HookFinding {
|
|
|
175
228
|
file: finding.filePath,
|
|
176
229
|
...(finding.line === undefined ? {} : { line: finding.line }),
|
|
177
230
|
...(finding.endLine === undefined ? {} : { endLine: finding.endLine }),
|
|
231
|
+
...(finding.column === undefined ? {} : { column: finding.column }),
|
|
178
232
|
symbol: finding.symbol ?? null,
|
|
179
233
|
message: finding.message,
|
|
180
234
|
remediation: finding.remediation ?? DESCRIPTORS.get(finding.ruleId)?.remediation ?? "Review and address this finding.",
|
|
@@ -241,25 +295,45 @@ function metricMetadata(measured: unknown, threshold: unknown, unit: string): Re
|
|
|
241
295
|
// Hashes (ruleId, filePath, scope component) into the 16-hex hook identity; line-insensitive so it
|
|
242
296
|
// stays the stable cross-edit key for new-only filtering.
|
|
243
297
|
function hookStableIdentity(finding: Finding, scope: HookScope): string {
|
|
244
|
-
|
|
298
|
+
return identityHash(finding.ruleId, finding.filePath, stableIdentityComponent(finding, scope));
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// The one place the 16-hex identity is derived, so every caller hashes the same tuple.
|
|
302
|
+
function identityHash(ruleId: string, filePath: string, component: string): string {
|
|
245
303
|
return createHash("sha256")
|
|
246
|
-
.update([
|
|
304
|
+
.update([ruleId, filePath, component].join("\0"))
|
|
247
305
|
.digest("hex")
|
|
248
306
|
.slice(0, 16);
|
|
249
307
|
}
|
|
250
308
|
|
|
251
|
-
//
|
|
252
|
-
|
|
309
|
+
// Identities one emitted finding answers to when matched against a base set. gruff.baseline.v1
|
|
310
|
+
// stores no column, so a baseline recomputes the column-free key; a finding that now reports a
|
|
311
|
+
// column must still recognise it, or every previously accepted secret comes back on the next run.
|
|
312
|
+
// Same-line occurrences share that older key, which is the baseline limitation ADR-017 documents:
|
|
313
|
+
// accepting one accepts every secret on its line. The wire identity stays column-aware, so a
|
|
314
|
+
// consumer tracking findings by identity still sees the two occurrences as separate.
|
|
315
|
+
function baselineMatchIdentities(finding: HookFinding): string[] {
|
|
316
|
+
if (finding.column === undefined) {
|
|
317
|
+
return [finding.stableIdentity];
|
|
318
|
+
}
|
|
319
|
+
const columnFreeComponent = stableIdentityComponent({
|
|
320
|
+
message: finding.message,
|
|
321
|
+
ruleId: finding.ruleId,
|
|
322
|
+
...(finding.symbol === null ? {} : { symbol: finding.symbol }),
|
|
323
|
+
}, finding.scope);
|
|
324
|
+
return [finding.stableIdentity, identityHash(finding.ruleId, finding.file, columnFreeComponent)];
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// Derives the per-occurrence component of the stable hook identity: scope token, symbol, or message
|
|
328
|
+
// plus match column.
|
|
329
|
+
function stableIdentityComponent(finding: { message: string; ruleId: string; symbol?: string; column?: number }, scope: HookScope): string {
|
|
253
330
|
if (scope === "file") {
|
|
254
331
|
return scope;
|
|
255
332
|
}
|
|
256
333
|
if (scope === "project") {
|
|
257
|
-
// Project rules are value-insensitive on their measurement, but
|
|
258
|
-
//
|
|
259
|
-
//
|
|
260
|
-
// cycle path (carried in `symbol`) is the only discriminator; folding it in keeps distinct
|
|
261
|
-
// cycles distinct so baselining one never suppresses a genuinely new one. A project finding with
|
|
262
|
-
// no symbol falls back to the bare scope token, preserving its value-insensitive identity.
|
|
334
|
+
// Project rules are value-insensitive on their measurement, but component-level findings still
|
|
335
|
+
// need a stable occurrence key. design.circular-import carries the canonical sorted SCC member
|
|
336
|
+
// list in `symbol`; folding it in keeps independent components distinct without line sensitivity.
|
|
263
337
|
return finding.symbol && finding.symbol.length > 0 ? `project:${finding.symbol}` : scope;
|
|
264
338
|
}
|
|
265
339
|
if (finding.symbol && finding.symbol.length > 0) {
|
|
@@ -267,11 +341,14 @@ function stableIdentityComponent(finding: { message: string; ruleId: string; sym
|
|
|
267
341
|
}
|
|
268
342
|
// Symbol-less line findings (e.g. each hardcoded secret) key on the message so several same-rule
|
|
269
343
|
// findings in one file get distinct identities. A value-insensitive `metric:${scope}` token
|
|
270
|
-
// collapsed them all, letting one baselined finding suppress later new ones in the same file.
|
|
271
|
-
//
|
|
272
|
-
|
|
273
|
-
//
|
|
274
|
-
|
|
344
|
+
// collapsed them all, letting one baselined finding suppress later new ones in the same file. file
|
|
345
|
+
// scope above stays fully value-insensitive; project scope folds in a canonical symbol when present.
|
|
346
|
+
const messageComponent = `message:${finding.message}`;
|
|
347
|
+
// The redacted preview alone stopped separating occurrences once short secrets became fully
|
|
348
|
+
// masked: two 20-character keys on one line produce the same preview, so the same message. The
|
|
349
|
+
// match column separates them and names no line, so an edit above the finding still keeps the
|
|
350
|
+
// identity stable. Scanners that report a whole line supply no column and keep the older key.
|
|
351
|
+
return finding.column === undefined ? messageComponent : `${messageComponent}\0column:${finding.column}`;
|
|
275
352
|
}
|
|
276
353
|
|
|
277
354
|
// Builds the base identity set (from a baseline file and/or a diff base) that new-only filtering
|
|
@@ -303,7 +380,8 @@ function stableIdentitiesFromBaseline(path: string): Set<string> {
|
|
|
303
380
|
}
|
|
304
381
|
|
|
305
382
|
// Resolves one baseline entry to hook identities: its stored identity, or a recomputed one from
|
|
306
|
-
// ruleId, filePath, and scope.
|
|
383
|
+
// ruleId, filePath, and scope. The recomputed key carries no column because gruff.baseline.v1 stores
|
|
384
|
+
// none; `baselineMatchIdentities` is what lets a column-bearing finding still match it.
|
|
307
385
|
function stableIdentityFromBaselineEntry(entry: BaselineEntry): string[] {
|
|
308
386
|
if (typeof entry.stableIdentity === "string") {
|
|
309
387
|
return [entry.stableIdentity];
|
|
@@ -337,6 +415,8 @@ function baselineScopeForRule(ruleId: string): HookScope {
|
|
|
337
415
|
return "line";
|
|
338
416
|
}
|
|
339
417
|
|
|
418
|
+
// Replays the diff base ref and returns its findings' stable hook identities for new-only filtering.
|
|
419
|
+
// Writes a temp tree, spawns git to materialize base files, and must clean both up afterward.
|
|
340
420
|
function stableIdentitiesFromDiffBase(
|
|
341
421
|
runAnalyse: HookAnalysisRunner,
|
|
342
422
|
options: AnalysisOptions,
|
|
@@ -347,7 +427,7 @@ function stableIdentitiesFromDiffBase(
|
|
|
347
427
|
if (ref === undefined) {
|
|
348
428
|
return new Set();
|
|
349
429
|
}
|
|
350
|
-
const files = [...new Set(currentReport.findings.
|
|
430
|
+
const files = [...new Set(currentReport.findings.flatMap(findingBasePaths))];
|
|
351
431
|
if (files.length === 0) {
|
|
352
432
|
return new Set();
|
|
353
433
|
}
|
|
@@ -367,6 +447,19 @@ function stableIdentitiesFromDiffBase(
|
|
|
367
447
|
}
|
|
368
448
|
}
|
|
369
449
|
|
|
450
|
+
/*
|
|
451
|
+
* A finding's base context is its anchor plus any project-relationship members from
|
|
452
|
+
* `metadata.files`. Contract invariant: without every SCC member at the base ref, the replay
|
|
453
|
+
* cannot reconstruct the cycle identity and a pre-existing cycle would be reported as new.
|
|
454
|
+
*/
|
|
455
|
+
function findingBasePaths(finding: Finding): string[] {
|
|
456
|
+
const memberFiles = finding.metadata.files;
|
|
457
|
+
if (!Array.isArray(memberFiles)) {
|
|
458
|
+
return [finding.filePath];
|
|
459
|
+
}
|
|
460
|
+
return [finding.filePath, ...memberFiles.filter((file): file is string => typeof file === "string")];
|
|
461
|
+
}
|
|
462
|
+
|
|
370
463
|
// Resolves a diff-base selector to the git rev whose blobs are the new-only base. "unstaged" diffs
|
|
371
464
|
// the worktree against the index, so its base is the index ("" rev -> `git show :path`); "-" (stdin
|
|
372
465
|
// patch) has no materializable base. Returns undefined only when no base can be replayed.
|
package/src/init-config.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
// Renders the default .gruff-ts.yaml file from the rule descriptor registry
|
|
2
|
-
//
|
|
1
|
+
// Renders the default .gruff-ts.yaml file from the rule descriptor registry.
|
|
2
|
+
// `gruff-ts init` uses it to give a new project the analyser's effective defaults.
|
|
3
|
+
// Users reach this file through the generated config they review before their first scan.
|
|
3
4
|
import { existsSync, writeFileSync } from "node:fs";
|
|
4
5
|
import { join } from "node:path";
|
|
5
6
|
import { createInterface } from "node:readline/promises";
|
|
@@ -24,7 +25,7 @@ const RULE_OPTION_DEFAULTS: Readonly<Record<string, Readonly<Record<string, numb
|
|
|
24
25
|
// Universal-programming abbreviations that earn their place across nearly any codebase; project-specific
|
|
25
26
|
// vocabulary (domain acronyms) should be appended in the user's config rather than added here.
|
|
26
27
|
const DEFAULT_ACCEPTED_ABBREVIATIONS: readonly string[] = [
|
|
27
|
-
"age", "app", "
|
|
28
|
+
"age", "app", "db", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url",
|
|
28
29
|
];
|
|
29
30
|
|
|
30
31
|
// Result of an init write attempt, including the no-clobber branch for existing config files.
|
|
@@ -192,12 +193,15 @@ function renderPathsSection(ignoredPaths: readonly string[]): string {
|
|
|
192
193
|
].join("\n");
|
|
193
194
|
}
|
|
194
195
|
|
|
195
|
-
//
|
|
196
|
-
//
|
|
196
|
+
// Shows users which short identifier terms avoid naming findings in a newly initialized project.
|
|
197
|
+
// The other naming allowlists stay commented so users can discover them without changing defaults.
|
|
197
198
|
function renderAllowlistsSection(): string {
|
|
198
199
|
return [
|
|
199
200
|
"allowlists:",
|
|
201
|
+
" # Abbreviations listed here are accepted in identifiers without a naming finding.",
|
|
202
|
+
" # Replace this list with the short terms reviewers accept in this project.",
|
|
200
203
|
" acceptedAbbreviations:",
|
|
204
|
+
// Each family term is visible so a user can review or replace the complete list in generated YAML.
|
|
201
205
|
...DEFAULT_ACCEPTED_ABBREVIATIONS.map((abbreviation) => ` - ${abbreviation}`),
|
|
202
206
|
" secretPreviews: []",
|
|
203
207
|
" # Names that trigger naming.generic-function. Each key replaces the built-in",
|
|
@@ -207,6 +211,12 @@ function renderAllowlistsSection(): string {
|
|
|
207
211
|
" # Exact public/CLI/DTO boolean names accepted by naming.boolean-prefix.",
|
|
208
212
|
" # Default: [all, apply, check, dev, enabled, force, fresh, harness, json, ok, verbose, yes]",
|
|
209
213
|
" # acceptedBooleanNames: [all, apply, check, dev, enabled, force, fresh, harness, json, ok, verbose, yes]",
|
|
214
|
+
" # Exact fileBase:ClassName pairs accepted by naming.class-file-mismatch.",
|
|
215
|
+
" # Default: []",
|
|
216
|
+
" # acceptedClassFilePairs: [focusModeTranscript:TranscriptFocusController]",
|
|
217
|
+
" # Exact wire_name:internalName alias pairs accepted within one naming owner.",
|
|
218
|
+
" # Default: []",
|
|
219
|
+
" # acceptedCasingPairs: [note_id:noteId]",
|
|
210
220
|
" # Accepted prefixes for boolean identifiers. Names without one of these",
|
|
211
221
|
" # prefixes trigger naming.boolean-prefix.",
|
|
212
222
|
" # Default: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires, allow, check, enable, exclude, include, omit, skip, with, without]",
|