@blundergoat/gruff-ts 0.5.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 +82 -0
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +49 -50
  4. package/SECURITY.md +18 -31
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -10
  8. package/docs/agent-hook.md +32 -35
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +160 -89
  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 -172
  15. package/docs/rules.md +126 -98
  16. package/package.json +10 -8
  17. package/src/analyser.ts +817 -323
  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 +62 -68
  22. package/src/blocks.ts +512 -336
  23. package/src/changed-regions.ts +380 -79
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +445 -436
  26. package/src/cli-program.ts +915 -172
  27. package/src/cli.ts +9 -3
  28. package/src/comment-rules.ts +236 -418
  29. package/src/comment-scanner.ts +339 -47
  30. package/src/complexity-metrics.ts +111 -35
  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 +751 -223
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +182 -54
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +493 -140
  40. package/src/doc-rules.ts +602 -126
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +134 -109
  43. package/src/findings.ts +47 -27
  44. package/src/fixture-purpose-rules.ts +194 -50
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +328 -121
  47. package/src/hook-contract.ts +681 -255
  48. package/src/init-config.ts +163 -118
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -468
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +32 -127
  54. package/src/parsed-script.ts +868 -314
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +86 -74
  57. package/src/project-config-rules.ts +324 -140
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +102 -38
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +821 -203
  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 +249 -55
  66. package/src/security-flow-rules.ts +791 -115
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +460 -387
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +378 -104
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +343 -253
  73. package/src/text-scans.ts +62 -11
  74. package/src/types.ts +220 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -163
  77. package/src/test-fixtures.ts +0 -671
@@ -1,19 +1,27 @@
1
- // Baseline option handling for `analyse`: chooses explicit/default baselines, applies
2
- // suppression, and writes generated baselines while preserving the report metadata shape.
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, DEFAULT_BASELINE, writeBaseline } from "./baseline.ts";
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 a baseline (suppression) or generating a new one. The optional `baseline`
11
- * matches the `gruff.analysis.v2` schema's baseline metadata - present only when a baseline file
12
- * was actually used or generated, so the report stays stable across baseline-disabled runs.
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
- * Three-way baseline dispatcher. `--generate-baseline` wins (writes a new file, returns findings
28
- * unchanged); `--no-baseline` skips entirely; otherwise look for an explicit or default baseline.
29
- * The stable identity tuple (fingerprint, ruleId, filePath) drives suppression matching.
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
- return generateBaselineResult(projectRoot, options.generateBaseline, findings);
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
- return applySelectedBaseline(projectRoot, selected, findings);
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 the baseline file via writeBaseline and returns the report-shaped metadata. `suppressed: 0`
50
- * because generation does not filter findings - every current finding is captured in the stable baseline.
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, baselineFile: string, findings: Finding[]): BaselineApplication {
53
- const baselinePath = absolutize(projectRoot, baselineFile);
54
- writeBaseline(baselinePath, findings);
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
- // Loads the baseline file and filters findings whose identity tuple matches. `suppressed` is
67
- // computed from the size delta so the stable baseline report metadata stays accurate.
68
- function applySelectedBaseline(projectRoot: string, selected: BaselineSelection, findings: Finding[]): BaselineApplication {
69
- const before = findings.length;
70
- const filteredFindings = applyBaseline(selected.path, findings);
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: filteredFindings,
131
+ findings: application.findings,
73
132
  baseline: {
74
133
  path: displayPath(projectRoot, selected.path),
75
134
  source: selected.source,
76
- suppressed: before - filteredFindings.length,
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
- // Picks an explicit `--baseline` path first, then the conventional `gruff-baseline.json` at the
83
- // project root. Returning undefined means "no baseline" - the stable contract preserves report shape.
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,83 +1,69 @@
1
- // Baseline persistence helpers for stable suppression files and score history side effects.
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 { scoreReport } from "./scoring.ts";
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
- // Treats already-absolute paths as-is; otherwise anchors at the project root the CLI was launched against.
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
- // Project-relative form with forward slashes - the report contract uses POSIX-style display paths on
15
- // every platform. "" collapses to "." so the project root has a stable label in history entries.
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
- // `gruff.baseline.v1`: writes the fingerprint plus the identity tuple used by `applyBaseline`.
22
- // `message` is persisted for human review; `applyBaseline` ignores it so cosmetic message changes
23
- // do not invalidate baselines. Bump schema before adding required fields; persists to disk via writeFileSync.
24
- function writeBaseline(path: string, findings: Finding[]): void {
25
- writeFileSync(
26
- path,
27
- JSON.stringify(
28
- {
29
- schemaVersion: "gruff.baseline.v1",
30
- generatedAt: new Date().toISOString(),
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, findings: Finding[], diagnostics: RunDiagnostic[]): void {
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: findings.length, score: scoreReport(findings).composite });
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
- // `docs.missing-public-doc` is keyed by (ruleId, filePath, symbol) instead of fingerprint because one
76
- // file can legitimately surface multiple undocumented public symbols and they must each survive dedupe.
77
- // All other rules collapse on their fingerprint, extended by the match column when one is present
78
- // (ADR-017): two distinct secrets on one line share a line-keyed fingerprint, and without the column
79
- // discriminator the second occurrence would be silently dropped from every report and the hook.
80
- // The extended key is in-memory only - fingerprint values and `gruff.baseline.v1` matching are unchanged.
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
+ */
81
67
  function dedupeFindings(findings: Finding[]): Finding[] {
82
68
  const seen = new Set<string>();
83
69
  return findings.filter((finding) => {
@@ -90,19 +76,19 @@ function dedupeFindings(findings: Finding[]): Finding[] {
90
76
  });
91
77
  }
92
78
 
93
- // Derives the in-memory dedupe key for one finding, so same-line occurrences with distinct
94
- // columns survive dedupe as separate findings (ADR-017). Invariant: the key is never serialized
95
- // and never feeds `applyBaseline` - fingerprint values and baseline matching stay byte-identical.
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
+ */
96
87
  function dedupeKey(finding: Finding): string {
97
88
  // One file legitimately surfaces many undocumented public symbols; keep each per-symbol entry.
98
89
  if (finding.ruleId === "docs.missing-public-doc" && finding.symbol) {
99
90
  return [finding.ruleId, finding.filePath, finding.symbol].join("\0");
100
91
  }
101
- // Casing drift is scoped to a lexical owner. Preserve owner-distinct diagnostics in memory
102
- // without changing their public line-keyed fingerprints or baseline matching contract.
103
- if (finding.ruleId === "naming.inconsistent-casing" && typeof finding.metadata.ownerId === "string") {
104
- return [finding.fingerprint, finding.metadata.ownerId].join("\0");
105
- }
106
92
  // A column means the scanner pinpointed the occurrence; same-line occurrences stay distinct.
107
93
  if (finding.column !== undefined) {
108
94
  return [finding.fingerprint, String(finding.column)].join("\0");
@@ -110,17 +96,25 @@ function dedupeKey(finding: Finding): string {
110
96
  return finding.fingerprint;
111
97
  }
112
98
 
113
- // Canonical finding ordering: (filePath, line, ruleId, message). The same tuple is part of the
114
- // stable baseline matching contract, so changing the comparator would churn every existing baseline.
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
+ */
115
106
  function sortedUniqueFindings(findings: Finding[]): Finding[] {
116
107
  findings.sort(
117
108
  (left, right) =>
118
109
  left.filePath.localeCompare(right.filePath) ||
119
110
  (left.line ?? 0) - (right.line ?? 0) ||
120
111
  left.ruleId.localeCompare(right.ruleId) ||
121
- left.message.localeCompare(right.message),
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"),
122
116
  );
123
117
  return dedupeFindings(findings);
124
118
  }
125
119
 
126
- export { DEFAULT_BASELINE, writeBaseline, applyBaseline, recordHistory, dedupeFindings, sortedUniqueFindings };
120
+ export { DEFAULT_BASELINE, recordHistory, dedupeFindings, sortedUniqueFindings };