@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.
- package/CHANGELOG.md +123 -1
- package/CONTRIBUTING.md +32 -25
- package/README.md +55 -46
- package/SECURITY.md +18 -30
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -13
- package/docs/agent-hook.md +33 -24
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +173 -71
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -157
- package/docs/rules.md +140 -106
- package/package.json +10 -8
- package/src/analyser.ts +886 -282
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +85 -55
- package/src/blocks.ts +579 -364
- package/src/changed-regions.ts +414 -65
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +461 -302
- package/src/cli-program.ts +956 -166
- package/src/cli.ts +9 -2
- package/src/comment-rules.ts +277 -414
- package/src/comment-scanner.ts +363 -44
- package/src/complexity-metrics.ts +320 -0
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +778 -210
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +188 -61
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +521 -148
- package/src/doc-rules.ts +592 -147
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +240 -89
- package/src/findings.ts +48 -24
- package/src/fixture-purpose-rules.ts +226 -48
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +336 -106
- package/src/hook-contract.ts +708 -211
- package/src/init-config.ts +169 -114
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -419
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +33 -107
- package/src/parsed-script.ts +1206 -0
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +97 -71
- package/src/project-config-rules.ts +335 -146
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +284 -0
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +864 -195
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +255 -52
- package/src/security-flow-rules.ts +930 -109
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +502 -375
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +380 -148
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +422 -228
- package/src/text-scans.ts +67 -9
- package/src/types.ts +222 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -153
- package/src/test-fixtures.ts +0 -668
package/src/baseline-options.ts
CHANGED
|
@@ -1,19 +1,27 @@
|
|
|
1
|
-
// Baseline option handling for `analyse`: chooses explicit
|
|
2
|
-
//
|
|
1
|
+
// Baseline option handling for `analyse`: chooses the explicit or default baseline, hides the debt the user
|
|
2
|
+
// already reviewed, carries a 0.5 file forward on request, and writes a generated baseline.
|
|
3
|
+
//
|
|
4
|
+
// The matching rules live in `baseline-file.ts`; this module is the part a user's flags reach, so it owns which
|
|
5
|
+
// action a run takes and what the report says about it.
|
|
3
6
|
import { existsSync } from "node:fs";
|
|
4
7
|
import { join } from "node:path";
|
|
5
|
-
import { applyBaseline,
|
|
8
|
+
import { applyBaseline, BaselineFileError, migrateBaseline, requireOverwritableDefaultPath, sensitiveCountOf, writeBaseline, type BaselineCollision } from "./baseline-file.ts";
|
|
9
|
+
import { type DeclarationPositionResolver, declarationPositionFromSpans, type DeclarationSpan } from "./baseline-identity.ts";
|
|
10
|
+
import { DEFAULT_BASELINE } from "./baseline.ts";
|
|
6
11
|
import { absolutize, displayPath } from "./discovery.ts";
|
|
7
|
-
import type { AnalysisOptions, AnalysisReport, Finding } from "./types.ts";
|
|
12
|
+
import type { AnalysisOptions, AnalysisReport, Finding, RunDiagnostic } from "./types.ts";
|
|
8
13
|
|
|
9
14
|
/*
|
|
10
|
-
* Result of applying
|
|
11
|
-
*
|
|
12
|
-
*
|
|
15
|
+
* Result of applying, migrating, or generating a baseline. The optional `baseline` matches native baseline
|
|
16
|
+
* metadata and is present only when a file was used or written.
|
|
17
|
+
*
|
|
18
|
+
* Invariant: `baseline` is absent unless a file was used or written; `diagnostics` carries one entry per collision
|
|
19
|
+
* the run could not tell apart, and one entry when the baseline could not be read at all.
|
|
13
20
|
*/
|
|
14
21
|
export interface BaselineApplication {
|
|
15
22
|
findings: Finding[];
|
|
16
23
|
baseline?: NonNullable<AnalysisReport["baseline"]>;
|
|
24
|
+
diagnostics: RunDiagnostic[];
|
|
17
25
|
}
|
|
18
26
|
|
|
19
27
|
// Resolved baseline path plus the provenance string emitted in the report. `source` distinguishes
|
|
@@ -21,70 +29,167 @@ export interface BaselineApplication {
|
|
|
21
29
|
interface BaselineSelection {
|
|
22
30
|
path: string;
|
|
23
31
|
source: string;
|
|
32
|
+
// The path as the user wrote it, or the default file name, so a diagnostic never prints this machine's absolute path.
|
|
33
|
+
label: string;
|
|
24
34
|
}
|
|
25
35
|
|
|
26
|
-
/*
|
|
27
|
-
|
|
28
|
-
*
|
|
29
|
-
*
|
|
36
|
+
/* --generate-baseline takes precedence over --no-baseline so that generation can write without applying an existing baseline. */
|
|
37
|
+
/**
|
|
38
|
+
* Apply the stable baseline selection contract to hide reviewed findings. Generation writes a baseline and keeps all findings.
|
|
39
|
+
*
|
|
40
|
+
* @param projectRoot - Directory used to resolve relative baseline paths and locate the default file.
|
|
41
|
+
* @param options - Selects generation, migration, skipping or baseline application and supplies any explicit paths.
|
|
42
|
+
* @param findings - Findings to record in the generated baseline or compare against the selected baseline.
|
|
43
|
+
* @param declarationSpans - Supplies start lines so that same-named declarations rank separately. Unmatched findings use their own lines.
|
|
44
|
+
* @param unusableBaseline - Diagnose mode turns a baseline file error into a fatal diagnostic and keeps all findings. Throw mode is the default.
|
|
45
|
+
* @returns Findings, diagnostics and optional baseline metadata. Skipping or finding no baseline keeps all findings and yields no diagnostics.
|
|
46
|
+
* @throws {BaselineFileError} - When generation or application raises a baseline file error in throw mode.
|
|
47
|
+
* @throws {Error} - When another generation or application error propagates in either mode.
|
|
30
48
|
*/
|
|
31
|
-
export function applyBaselineOptions(projectRoot: string, options: AnalysisOptions, findings: Finding[]): BaselineApplication {
|
|
49
|
+
export function applyBaselineOptions(projectRoot: string, options: AnalysisOptions, findings: Finding[], declarationSpans = new Map<string, DeclarationSpan[]>(), unusableBaseline: "throw" | "diagnose" = "throw"): BaselineApplication {
|
|
50
|
+
const declarationPosition = declarationPositionFromSpans(declarationSpans);
|
|
32
51
|
if (options.generateBaseline) {
|
|
33
|
-
|
|
52
|
+
try {
|
|
53
|
+
return generateBaselineResult(projectRoot, options, findings, declarationPosition);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
// For example, running `--generate-baseline` over an existing 0.5 default baseline without `--force`, or passing a bad `--migrate-baseline`.
|
|
56
|
+
// In diagnose mode, keep all findings visible and invalidate the run with a path-safe diagnostic.
|
|
57
|
+
if (unusableBaseline === "diagnose" && error instanceof BaselineFileError) {
|
|
58
|
+
return { findings, diagnostics: [{ diagnosticType: "baseline-error", message: sanitizeGenerationErrorMessage(projectRoot, options, error.message) }] };
|
|
59
|
+
}
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
34
62
|
}
|
|
35
63
|
|
|
36
64
|
if (options.shouldSkipBaseline) {
|
|
37
|
-
return { findings };
|
|
65
|
+
return { findings, diagnostics: [] };
|
|
38
66
|
}
|
|
39
67
|
|
|
40
68
|
const selected = selectedBaseline(projectRoot, options);
|
|
41
69
|
if (!selected) {
|
|
42
|
-
return { findings };
|
|
70
|
+
return { findings, diagnostics: [] };
|
|
43
71
|
}
|
|
44
72
|
|
|
45
|
-
|
|
73
|
+
try {
|
|
74
|
+
return applySelectedBaseline(projectRoot, selected, findings, declarationPosition);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
// For example, passing `--baseline missing.json` or pointing at a corrupt or wrong-schema baseline file.
|
|
77
|
+
// In diagnose mode, keep all findings visible and report the caller's path label in the fatal diagnostic.
|
|
78
|
+
if (unusableBaseline === "diagnose" && error instanceof BaselineFileError) {
|
|
79
|
+
return { findings, diagnostics: [{ diagnosticType: "baseline-error", message: error.message.replaceAll(selected.path, selected.label) }] };
|
|
80
|
+
}
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
46
83
|
}
|
|
47
84
|
|
|
48
|
-
|
|
49
|
-
* Writes
|
|
50
|
-
*
|
|
85
|
+
/**
|
|
86
|
+
* Writes eligible baseline entries or carries forward matching reviews with --migrate-baseline while preserving the input file.
|
|
87
|
+
* Stable contract: returns every finding with write metadata, zero suppressions, and an empty diagnostics list.
|
|
88
|
+
*
|
|
89
|
+
* @param projectRoot - Base directory used to resolve relative target and migration paths and format the output display path.
|
|
90
|
+
* @param options - Supplies the generate target path, optional migrate source path, and force-overwrite flag.
|
|
91
|
+
* @param findings - Findings to write or migrate and count for sensitive-data metadata.
|
|
92
|
+
* @param declarationPosition - Resolves enclosing declaration positions for stable baseline identities.
|
|
93
|
+
* @returns Every finding unchanged along with generated or migrated baseline metadata and an empty diagnostics list.
|
|
51
94
|
*/
|
|
52
|
-
function generateBaselineResult(projectRoot: string,
|
|
53
|
-
const baselinePath = absolutize(projectRoot,
|
|
54
|
-
|
|
95
|
+
function generateBaselineResult(projectRoot: string, options: AnalysisOptions, findings: Finding[], declarationPosition: DeclarationPositionResolver): BaselineApplication {
|
|
96
|
+
const baselinePath = absolutize(projectRoot, options.generateBaseline ?? DEFAULT_BASELINE);
|
|
97
|
+
// A generate at the shared default path never destroys a 0.5 baseline by accident; --force is the way to mean it.
|
|
98
|
+
requireOverwritableDefaultPath(baselinePath, options.shouldForceBaselineOverwrite === true);
|
|
99
|
+
const migratePath = options.migrateBaseline;
|
|
100
|
+
const written = migratePath
|
|
101
|
+
? migrateBaseline(absolutize(projectRoot, migratePath), baselinePath, findings, declarationPosition)
|
|
102
|
+
: { entries: writeBaseline(baselinePath, findings, declarationPosition), sensitiveCounted: sensitiveCountOf(findings, declarationPosition) };
|
|
103
|
+
|
|
55
104
|
return {
|
|
56
105
|
findings,
|
|
57
106
|
baseline: {
|
|
58
107
|
path: displayPath(projectRoot, baselinePath),
|
|
59
|
-
source: "generated",
|
|
108
|
+
source: migratePath ? "migrated" : "generated",
|
|
60
109
|
suppressed: 0,
|
|
61
110
|
generated: true,
|
|
111
|
+
entries: written.entries,
|
|
112
|
+
sensitiveCounted: written.sensitiveCounted,
|
|
62
113
|
},
|
|
114
|
+
diagnostics: [],
|
|
63
115
|
};
|
|
64
116
|
}
|
|
65
117
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
118
|
+
/**
|
|
119
|
+
* Apply the selected baseline and derive report counts from the same result so that they agree with the filtered findings.
|
|
120
|
+
*
|
|
121
|
+
* @param projectRoot - base used to display the selected baseline path
|
|
122
|
+
* @param selected - baseline path to read and selection source to record
|
|
123
|
+
* @param findings - current findings to match against reviewed counts
|
|
124
|
+
* @param declarationPosition - resolves declaration positions for stable baseline identities
|
|
125
|
+
* @returns Visible findings, baseline metadata, and non-fatal diagnostics for any collisions.
|
|
126
|
+
* @throws {BaselineFileError} - the selected baseline cannot be read or applied.
|
|
127
|
+
*/
|
|
128
|
+
function applySelectedBaseline(projectRoot: string, selected: BaselineSelection, findings: Finding[], declarationPosition: DeclarationPositionResolver): BaselineApplication {
|
|
129
|
+
const application = applyBaseline(selected.path, findings, declarationPosition);
|
|
71
130
|
return {
|
|
72
|
-
findings:
|
|
131
|
+
findings: application.findings,
|
|
73
132
|
baseline: {
|
|
74
133
|
path: displayPath(projectRoot, selected.path),
|
|
75
134
|
source: selected.source,
|
|
76
|
-
suppressed:
|
|
135
|
+
suppressed: application.counts.unchanged,
|
|
77
136
|
generated: false,
|
|
137
|
+
entries: application.entries,
|
|
138
|
+
newFindings: application.counts.new + application.counts.collision + application.counts.notEligible,
|
|
139
|
+
unchangedFindings: application.counts.unchanged,
|
|
140
|
+
resolvedFindings: application.counts.absent,
|
|
78
141
|
},
|
|
142
|
+
diagnostics: application.collisions.map(collisionDiagnostic),
|
|
79
143
|
};
|
|
80
144
|
}
|
|
81
145
|
|
|
82
|
-
|
|
83
|
-
|
|
146
|
+
/**
|
|
147
|
+
* Builds a non-fatal diagnostic for a baseline collision.
|
|
148
|
+
* Under the baseline contract, findings sharing the identity stay visible, so their severities can still affect the run's result.
|
|
149
|
+
*
|
|
150
|
+
* @param collision - Collision record providing the shared identity, rule ID, file path, and colliding subjects.
|
|
151
|
+
* @returns Non-fatal diagnostic naming the colliding review's identity, rule, path, and reported subjects.
|
|
152
|
+
*/
|
|
153
|
+
function collisionDiagnostic(collision: BaselineCollision): RunDiagnostic {
|
|
154
|
+
return {
|
|
155
|
+
diagnosticType: "baseline-collision",
|
|
156
|
+
message: `collision: identity ${collision.identity} covers ${collision.subjects.length} declarations of ${collision.subjects.join(", ")} for rule ${collision.ruleId} in ${collision.path}; none is suppressed`,
|
|
157
|
+
filePath: collision.path,
|
|
158
|
+
invalidatesRun: false,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Selects the baseline path, source, and display label from options, resolving relative paths against projectRoot.
|
|
164
|
+
* Without an explicit path, selects gruff-baseline.json only if it exists at projectRoot; the no-baseline contract keeps all findings visible.
|
|
165
|
+
*
|
|
166
|
+
* @param projectRoot - Base directory used to resolve explicit relative paths or locate the default baseline file.
|
|
167
|
+
* @param options - Supplies an optional explicit baseline path.
|
|
168
|
+
* @returns Selected baseline path, source, and display label, or undefined when no explicit path is set and no default file exists.
|
|
169
|
+
*/
|
|
84
170
|
function selectedBaseline(projectRoot: string, options: AnalysisOptions): BaselineSelection | undefined {
|
|
85
171
|
if (options.baseline) {
|
|
86
|
-
return { path: absolutize(projectRoot, options.baseline), source: "explicit" };
|
|
172
|
+
return { path: absolutize(projectRoot, options.baseline), source: "explicit", label: options.baseline };
|
|
87
173
|
}
|
|
88
174
|
const defaultBaseline = join(projectRoot, DEFAULT_BASELINE);
|
|
89
|
-
return existsSync(defaultBaseline) ? { path: defaultBaseline, source: "default" } : undefined;
|
|
175
|
+
return existsSync(defaultBaseline) ? { path: defaultBaseline, source: "default", label: DEFAULT_BASELINE } : undefined;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Replaces resolved absolute baseline and migration paths inside a generation diagnostic with the caller's path labels.
|
|
180
|
+
* Keeps host filesystem locations out of machine JSON and SARIF error messages.
|
|
181
|
+
*
|
|
182
|
+
* @param projectRoot - Base directory used to resolve the caller's generate and migrate path arguments.
|
|
183
|
+
* @param options - Analysis options with path labels; omitted `generateBaseline` uses `DEFAULT_BASELINE`, omitted `migrateBaseline` skips it.
|
|
184
|
+
* @param message - Raw baseline file error message produced during generation or migration.
|
|
185
|
+
* @returns Sanitized diagnostic message with resolved paths replaced by their caller-supplied labels.
|
|
186
|
+
*/
|
|
187
|
+
function sanitizeGenerationErrorMessage(projectRoot: string, options: AnalysisOptions, message: string): string {
|
|
188
|
+
const generateLabel = options.generateBaseline ?? DEFAULT_BASELINE;
|
|
189
|
+
let sanitized = message.replaceAll(absolutize(projectRoot, generateLabel), generateLabel);
|
|
190
|
+
// With --migrate-baseline, the old baseline's path is also shown the way the user typed it.
|
|
191
|
+
if (options.migrateBaseline !== undefined) {
|
|
192
|
+
sanitized = sanitized.replaceAll(absolutize(projectRoot, options.migrateBaseline), options.migrateBaseline);
|
|
193
|
+
}
|
|
194
|
+
return sanitized;
|
|
90
195
|
}
|
package/src/baseline.ts
CHANGED
|
@@ -1,84 +1,73 @@
|
|
|
1
|
-
//
|
|
1
|
+
// File overview: Saves score history and keeps findings in a predictable order.
|
|
2
|
+
//
|
|
3
|
+
// A user who passes `--history-file` gets one score entry for a valid full scan, which the dashboard can plot.
|
|
4
|
+
// The ordering and duplicate checks also keep the reports and baseline comparisons stable between scans.
|
|
2
5
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
6
|
import { isAbsolute, join, relative } from "node:path";
|
|
4
|
-
import {
|
|
5
|
-
import type { Finding, RunDiagnostic } from "./types.ts";
|
|
7
|
+
import type { AnalysisReport, Finding, RunDiagnostic } from "./types.ts";
|
|
6
8
|
|
|
7
9
|
const DEFAULT_BASELINE = "gruff-baseline.json";
|
|
8
10
|
|
|
9
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Resolves a path against the project root unless it is already absolute.
|
|
13
|
+
*
|
|
14
|
+
* @param projectRoot - base project directory the CLI was launched against
|
|
15
|
+
* @param path - candidate path that may be relative or already absolute
|
|
16
|
+
* @returns The unchanged absolute path, or `path` joined onto `projectRoot`.
|
|
17
|
+
*/
|
|
10
18
|
function absolutize(projectRoot: string, path: string): string {
|
|
11
19
|
return isAbsolute(path) ? path : join(projectRoot, path);
|
|
12
20
|
}
|
|
13
21
|
|
|
14
|
-
|
|
15
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Formats a path in project-relative POSIX form with forward slashes.
|
|
24
|
+
* The report contract uses POSIX-style display paths on every platform; "" collapses to "." for a stable history label.
|
|
25
|
+
*
|
|
26
|
+
* @param projectRoot - base directory used to compute the relative path
|
|
27
|
+
* @param path - target file or directory path to format
|
|
28
|
+
* @returns The forward-slash relative path, or "." when `path` matches `projectRoot`.
|
|
29
|
+
*/
|
|
16
30
|
function displayPath(projectRoot: string, path: string): string {
|
|
17
31
|
const relativePath = relative(projectRoot, path).replaceAll("\\", "/");
|
|
18
32
|
return relativePath === "" ? "." : relativePath;
|
|
19
33
|
}
|
|
20
34
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
entries: findings.map((finding) => ({
|
|
32
|
-
fingerprint: finding.fingerprint,
|
|
33
|
-
ruleId: finding.ruleId,
|
|
34
|
-
filePath: finding.filePath,
|
|
35
|
-
line: finding.line,
|
|
36
|
-
symbol: finding.symbol,
|
|
37
|
-
message: finding.message,
|
|
38
|
-
})),
|
|
39
|
-
},
|
|
40
|
-
null,
|
|
41
|
-
2,
|
|
42
|
-
),
|
|
43
|
-
);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// Suppresses any finding whose (fingerprint, ruleId, filePath) tuple appears in the baseline.
|
|
47
|
-
// Drift between versions would let stale suppressions leak in, so the operator must regenerate
|
|
48
|
-
// against the current CLI; reads the baseline file and throws on an unknown schema version.
|
|
49
|
-
function applyBaseline(path: string, findings: Finding[]): Finding[] {
|
|
50
|
-
const baselineFile = JSON.parse(readFileSync(path, "utf8")) as { schemaVersion?: string; entries?: Array<{ fingerprint: string; ruleId: string; filePath: string }> };
|
|
51
|
-
if (baselineFile.schemaVersion !== "gruff.baseline.v1") {
|
|
52
|
-
throw new Error(`unsupported baseline schema in ${path}`);
|
|
53
|
-
}
|
|
54
|
-
const keys = new Set((baselineFile.entries ?? []).map((entry) => [entry.fingerprint, entry.ruleId, entry.filePath].join("\0")));
|
|
55
|
-
return findings.filter((finding) => !keys.has([finding.fingerprint, finding.ruleId, finding.filePath].join("\0")));
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/*
|
|
59
|
-
* Appends one row to the score-history JSON file and trims to the most recent 100 entries so the
|
|
60
|
-
* dashboard sparkline never grows unbounded. The stable contract: writes via writeFileSync, and on
|
|
61
|
-
* persistence failure it reports a `history-error` diagnostic and recovers - a flaky history file
|
|
62
|
-
* must not fail the analysis run.
|
|
35
|
+
/**
|
|
36
|
+
* Append the result of a valid full scan for the dashboard's score trend.
|
|
37
|
+
* Invariant: keep the latest 100 entries. A missing history file starts a new trend.
|
|
38
|
+
*
|
|
39
|
+
* @param projectRoot - base directory for resolving the history path and displaying it in a diagnostic
|
|
40
|
+
* @param historyFile - destination from `--history-file`. A missing file starts with no earlier score entries.
|
|
41
|
+
* @param score - score for the same run. A null composite means no files could be scored.
|
|
42
|
+
* @param findings - count of findings in that run
|
|
43
|
+
* @param diagnostics - run diagnostics array that receives a history-error if recording fails
|
|
44
|
+
* @returns Nothing. It writes the updated history or appends a failure diagnostic.
|
|
63
45
|
*/
|
|
64
|
-
function recordHistory(projectRoot: string, historyFile: string,
|
|
46
|
+
function recordHistory(projectRoot: string, historyFile: string, score: AnalysisReport["score"], findings: number, diagnostics: RunDiagnostic[]): void {
|
|
65
47
|
const path = absolutize(projectRoot, historyFile);
|
|
66
48
|
try {
|
|
49
|
+
// A first run has no history file to read, so the dashboard gets one point after this write.
|
|
67
50
|
const entries = existsSync(path) ? (JSON.parse(readFileSync(path, "utf8")) as unknown[]) : [];
|
|
68
|
-
entries.push({ recordedAt: new Date().toISOString(), findings
|
|
51
|
+
entries.push({ recordedAt: new Date().toISOString(), findings, score: score.composite });
|
|
69
52
|
writeFileSync(path, JSON.stringify(entries.slice(-100), null, 2));
|
|
70
53
|
} catch (error) {
|
|
54
|
+
// A read-only directory or a malformed existing history file adds a diagnostic to the scan report.
|
|
71
55
|
diagnostics.push({ diagnosticType: "history-error", message: `Unable to write history file: ${String(error)}`, filePath: displayPath(projectRoot, path) });
|
|
72
56
|
}
|
|
73
57
|
}
|
|
74
58
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
59
|
+
/**
|
|
60
|
+
* Keeps the first finding per dedupe key in input order while preserving original fingerprints.
|
|
61
|
+
* Only docs.missing-public-doc findings with a symbol key on rule, path, and symbol; others use fingerprint and column.
|
|
62
|
+
* Columns preserve separate same-line matches, while gruff.baseline.v3 uses line-free matching per ADR-017.
|
|
63
|
+
*
|
|
64
|
+
* @param findings - candidate findings to deduplicate in their current order
|
|
65
|
+
* @returns A filtered array containing the first occurrence of each dedupe key.
|
|
66
|
+
*/
|
|
78
67
|
function dedupeFindings(findings: Finding[]): Finding[] {
|
|
79
68
|
const seen = new Set<string>();
|
|
80
69
|
return findings.filter((finding) => {
|
|
81
|
-
const key = finding
|
|
70
|
+
const key = dedupeKey(finding);
|
|
82
71
|
if (seen.has(key)) {
|
|
83
72
|
return false;
|
|
84
73
|
}
|
|
@@ -87,4 +76,45 @@ function dedupeFindings(findings: Finding[]): Finding[] {
|
|
|
87
76
|
});
|
|
88
77
|
}
|
|
89
78
|
|
|
90
|
-
|
|
79
|
+
/**
|
|
80
|
+
* Builds a stable in-memory dedupe key for a finding, keeping distinct columns separate on the same line.
|
|
81
|
+
* Outside docs.missing-public-doc with a symbol, findings without a column group by fingerprint alone.
|
|
82
|
+
* The key stays in memory per ADR-017 so applyBaseline receives deduplicated findings with original fingerprints.
|
|
83
|
+
*
|
|
84
|
+
* @param finding - finding whose rule, path, symbol, fingerprint, and column determine the key
|
|
85
|
+
* @returns The NUL-delimited in-memory dedupe key, or the bare fingerprint when no column or per-symbol key applies.
|
|
86
|
+
*/
|
|
87
|
+
function dedupeKey(finding: Finding): string {
|
|
88
|
+
// One file legitimately surfaces many undocumented public symbols; keep each per-symbol entry.
|
|
89
|
+
if (finding.ruleId === "docs.missing-public-doc" && finding.symbol) {
|
|
90
|
+
return [finding.ruleId, finding.filePath, finding.symbol].join("\0");
|
|
91
|
+
}
|
|
92
|
+
// A column means the scanner pinpointed the occurrence; same-line occurrences stay distinct.
|
|
93
|
+
if (finding.column !== undefined) {
|
|
94
|
+
return [finding.fingerprint, String(finding.column)].join("\0");
|
|
95
|
+
}
|
|
96
|
+
return finding.fingerprint;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Sorts and mutates the caller's findings in place by path, line, rule, and message for a stable report order; ties put a non-eval sink first.
|
|
101
|
+
* Missing lines sort as zero, then duplicates are removed while preserving the sorted order.
|
|
102
|
+
*
|
|
103
|
+
* @param findings - caller array sorted in place before deduplication
|
|
104
|
+
* @returns A new array containing the first occurrence of each dedupe key in sorted order.
|
|
105
|
+
*/
|
|
106
|
+
function sortedUniqueFindings(findings: Finding[]): Finding[] {
|
|
107
|
+
findings.sort(
|
|
108
|
+
(left, right) =>
|
|
109
|
+
left.filePath.localeCompare(right.filePath) ||
|
|
110
|
+
(left.line ?? 0) - (right.line ?? 0) ||
|
|
111
|
+
left.ruleId.localeCompare(right.ruleId) ||
|
|
112
|
+
left.message.localeCompare(right.message) ||
|
|
113
|
+
// Same-line deserialization sinks collapse to the first one kept, so a non-eval sink goes first: security.eval-call already reports
|
|
114
|
+
// the eval, and keeping the eval form would let duplicate-claim merging drop a tainted `vm.runInNewContext(x)` beside it.
|
|
115
|
+
Number(left.metadata.sinkForm === "eval") - Number(right.metadata.sinkForm === "eval"),
|
|
116
|
+
);
|
|
117
|
+
return dedupeFindings(findings);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export { DEFAULT_BASELINE, recordHistory, dedupeFindings, sortedUniqueFindings };
|