@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
@@ -0,0 +1,867 @@
1
+ // Saves reviewed findings for `analyse --generate-baseline` and loads those reviews for `analyse --baseline`.
2
+ //
3
+ // Moving code leaves a review in place. An extra occurrence beyond the reviewed count appears as new.
4
+ // Sensitive findings contribute counts only. Users upgrading a 0.5 file can carry their reviews forward with `--migrate-baseline`.
5
+ import { lstatSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { type DeclarationPositionResolver, findingIdentities, isBaselineEligible, TOOL_LANGUAGE, type FindingIdentity } from "./baseline-identity.ts";
8
+ import type { Finding } from "./types.ts";
9
+
10
+ // The family baseline this port writes and reads; a file naming anything else is refused rather than guessed at.
11
+ export const BASELINE_SCHEMA_VERSION = "gruff.baseline.v3";
12
+
13
+ // The one baseline name every port writes and auto-discovers, and therefore the one a generate must protect.
14
+ export const DEFAULT_BASELINE_FILENAME = "gruff-baseline.json";
15
+
16
+ // The 0.5 baseline a migration accepts as input; reading one for suppression fails closed and names the command.
17
+ export const LEGACY_BASELINE_SCHEMA_VERSION = "gruff.baseline.v1";
18
+
19
+ // Keys a v3 row may never carry; each one is a way a stored baseline could expire on an edit or leak a finding's text.
20
+ const FORBIDDEN_OCCURRENCE_KEYS = ["line", "endLine", "column", "message", "severity", "confidence"];
21
+
22
+ // Why a generated baseline stores no sensitive occurrence, written into the file so a reader meets the rule there.
23
+ const SENSITIVE_INELIGIBILITY_REASON =
24
+ "Sensitive findings are never baselinable; they are counted here and stay visible until fixed or excluded with a reason.";
25
+
26
+ // Where a finding with no line sorts when a reviewed count is spent, so an unlocated occurrence is always spent last.
27
+ const UNLOCATED_SPEND_LINE = Number.MAX_SAFE_INTEGER;
28
+
29
+ // The three keys the five 0.5 writers used for their row list: go and py wrote findings, php wrote groups, and rs and
30
+ // ts wrote entries. A file naming two of them cannot be read the same way twice, so a migration refuses it.
31
+ const LEGACY_ROW_CONTAINERS = ["findings", "groups", "entries"] as const;
32
+
33
+ // The family ports a baseline may name as its writer (gruff-spec `contracts/core/baseline.v3.json`, search: `toolLanguage`).
34
+ const FAMILY_TOOL_LANGUAGES: ReadonlySet<string> = new Set(["go", "php", "py", "rs", "ts"]);
35
+
36
+ /*
37
+ * One reviewed row: a line-free identity and how many occurrences of it the team signed off.
38
+ * Matching reads the identity and the count and nothing else; the rule, path, and subject exist so a reviewer can
39
+ * read the file.
40
+ */
41
+ export interface BaselineEntry {
42
+ identity: string;
43
+ count: number;
44
+ ruleId?: string;
45
+ path?: string;
46
+ subject?: string;
47
+ }
48
+
49
+ // One identity that covers two declarations, so neither of them can be hidden and the run names both subjects.
50
+ export interface BaselineCollision {
51
+ identity: string;
52
+ ruleId: string;
53
+ path: string;
54
+ subjects: string[];
55
+ }
56
+
57
+ /*
58
+ * How one run met the baseline: what stays hidden, what the user must still act on, and what could not be told apart.
59
+ * `absent` counts the reviewed occurrences that are gone, which is debt the user has since fixed.
60
+ */
61
+ export interface BaselineCounts {
62
+ new: number;
63
+ unchanged: number;
64
+ absent: number;
65
+ collision: number;
66
+ notEligible: number;
67
+ }
68
+
69
+ // The gated findings plus the accounting behind them; every collision becomes one diagnostic the user reads.
70
+ // Stable contract: `findings` is the gated set the user must act on, and every collision here suppressed nothing.
71
+ export interface BaselineApplication {
72
+ findings: Finding[];
73
+ /** What the baseline made of each finding handed in, in that order, so a caller can report a status per finding. */
74
+ statuses: string[];
75
+ counts: BaselineCounts;
76
+ collisions: BaselineCollision[];
77
+ resolved: BaselineEntry[];
78
+ entries: number;
79
+ }
80
+
81
+ // What a migration wrote, so the command can tell the user what carried across from their 0.5 file.
82
+ export interface BaselineMigration {
83
+ entries: number;
84
+ accepted: number;
85
+ sensitiveCounted: number;
86
+ }
87
+
88
+ // The whole baseline document, as written and as read back on the next run.
89
+ // Stable contract: this is the `gruff.baseline.v3` schema on disk; adding a positional field to a row would break every stored review.
90
+ interface BaselineDocument {
91
+ schemaVersion: string;
92
+ toolLanguage: string;
93
+ generatedAt: string;
94
+ occurrences: BaselineEntry[];
95
+ sensitive: { eligible: false; reason: string; counts: { total: number; byRule: Record<string, number> } };
96
+ }
97
+
98
+ /**
99
+ * Writes a timestamped baseline of the run's reviewed debt with one row per identity in stable ascending identity order.
100
+ * Sensitive findings contribute to a count without an occurrence row.
101
+ *
102
+ * @param path - destination file to write or replace
103
+ * @param findings - current findings to aggregate into baseline rows
104
+ * @param declarationPosition - optional resolver for declaration positions. Omit it to rank by finding line.
105
+ * @returns The number of occurrence rows written, or zero when no finding has an identity.
106
+ * @throws {BaselineFileError} when the temporary write or replacement fails.
107
+ */
108
+ export function writeBaseline(path: string, findings: Finding[], declarationPosition?: DeclarationPositionResolver): number {
109
+ const document = baselineDocument(findings, declarationPosition);
110
+ try {
111
+ // Stage the replacement beside the destination so an interrupted write leaves the user's earlier baseline intact.
112
+ const temporaryDirectory = mkdtempSync(join(dirname(path), ".gruff-baseline-"));
113
+ try {
114
+ const temporaryPath = join(temporaryDirectory, "baseline.json");
115
+ writeFileSync(temporaryPath, `${JSON.stringify(document, null, 2)}\n`);
116
+ renameSync(temporaryPath, path);
117
+ } finally {
118
+ rmSync(temporaryDirectory, { recursive: true, force: true });
119
+ }
120
+ } catch (error) {
121
+ // A user may choose a baseline destination in a read-only checkout.
122
+ throw new BaselineFileError(`baseline ${path} cannot be written: ${unreadableReason(error)}`);
123
+ }
124
+ return document.occurrences.length;
125
+ }
126
+
127
+ /**
128
+ * Counts the secrets a generated baseline recorded without storing, so the run can report what it set aside.
129
+ * Stable contract: the count is derived from the same document a write would produce, so the two can never disagree.
130
+ *
131
+ * @param findings - current findings to inspect for sensitive occurrences
132
+ * @param declarationPosition - optional resolver for declaration positions; omit it to rank by finding line
133
+ * @returns Total number of sensitive findings counted across all rules.
134
+ */
135
+ export function sensitiveCountOf(findings: Finding[], declarationPosition?: DeclarationPositionResolver): number {
136
+ return baselineDocument(findings, declarationPosition).sensitive.counts.total;
137
+ }
138
+
139
+ /**
140
+ * Apply reviewed counts in stable location order so matching hides the same occurrences for identical inputs.
141
+ * Hide unchanged occurrences only. Collisions and ineligible findings remain visible.
142
+ *
143
+ * @param path - baseline file to read and validate
144
+ * @param findings - current findings to classify against reviewed counts
145
+ * @param declarationPosition - optional resolver for declaration positions. Omit it to rank by finding line.
146
+ * @returns Visible findings, per-input statuses, counts, collisions, resolved review rows and the baseline entry total.
147
+ * @throws {BaselineFileError} - the baseline cannot be read or validated for this run.
148
+ */
149
+ export function applyBaseline(path: string, findings: Finding[], declarationPosition?: DeclarationPositionResolver): BaselineApplication {
150
+ const document = readBaselineDocument(path);
151
+ const reviewed = new Map(document.occurrences.map((entry) => [entry.identity, entry]));
152
+ const identities = findingIdentities(findings, declarationPosition);
153
+ const groups = groupByIdentity(findings, identities);
154
+ const statuses = classify(findings, identities, groups, reviewed);
155
+ const resolved = resolvedSurplus(document.occurrences, groups, statuses);
156
+
157
+ return {
158
+ findings: findings.filter((_, index) => statuses[index] !== "unchanged"),
159
+ statuses,
160
+ counts: {
161
+ new: statuses.filter((status) => status === "new").length,
162
+ unchanged: statuses.filter((status) => status === "unchanged").length,
163
+ absent: resolved.reduce((total, entry) => total + entry.count, 0),
164
+ collision: statuses.filter((status) => status === "collision").length,
165
+ notEligible: statuses.filter((status) => status === "notEligible").length,
166
+ },
167
+ collisions: collidedIdentities(groups),
168
+ resolved,
169
+ entries: document.occurrences.length,
170
+ };
171
+ }
172
+
173
+ /**
174
+ * Matches the legacy input's reviews against the current findings and writes their v3 identities to a separate output path.
175
+ * The input is opened only for reading, and its contents are verified unchanged after writing.
176
+ *
177
+ * @param inputPath - legacy 0.5 baseline file to read without modifying
178
+ * @param outputPath - separate destination path to write the migrated v3 baseline
179
+ * @param findings - current findings eligible to inherit legacy reviews
180
+ * @param declarationPosition - optional resolver for declaration positions; omit it to default to finding lines
181
+ * @returns Counts of written occurrence rows, matched findings, and findings tallied in the sensitive summary.
182
+ * @throws {BaselineFileError} - the paths name the same file or the legacy schema or row container is invalid
183
+ * @throws {Error} - a file operation fails or the input bytes differ after the write
184
+ */
185
+ export function migrateBaseline(inputPath: string, outputPath: string, findings: Finding[], declarationPosition?: DeclarationPositionResolver): BaselineMigration {
186
+ requireDistinctPaths(inputPath, outputPath);
187
+ let original: Buffer;
188
+ try {
189
+ original = readFileSync(inputPath);
190
+ } catch (error) {
191
+ // For example, `--migrate-baseline old.json` points to a file omitted from this checkout.
192
+ throw new BaselineFileError(`migration input ${inputPath} cannot be read: ${unreadableReason(error)}`);
193
+ }
194
+ const accepted = acceptedByLegacy(legacyRows(inputPath, original), findings);
195
+ const entries = writeBaseline(outputPath, accepted, declarationPosition);
196
+
197
+ // The 0.5 file is the user's way back, so the migration proves it survived rather than assuming it did.
198
+ if (!readFileSync(inputPath).equals(original)) {
199
+ throw new Error(`migration changed its own input: ${inputPath}`);
200
+ }
201
+
202
+ return { entries, accepted: accepted.length, sensitiveCounted: sensitiveCountOf(accepted, declarationPosition) };
203
+ }
204
+
205
+ /**
206
+ * Guard the shared default filename because regenerating after an upgrade could overwrite the legacy baseline needed for rollback.
207
+ * Generation proceeds for an absent path or a baseline that can be read by this analyzer.
208
+ *
209
+ * @param outputPath - proposed baseline destination, checked only when it uses the shared default filename
210
+ * @param shouldForce - explicit user permission to bypass the overwrite guard
211
+ * @returns Nothing. Allows the caller to continue when the overwrite guard passes.
212
+ * @throws {BaselineFileError} - force is off and the existing default path cannot be read as a current regular baseline file.
213
+ */
214
+ export function requireOverwritableDefaultPath(outputPath: string, shouldForce: boolean): void {
215
+ // An explicit force flag or a different filename bypasses the shared-default safeguard; compare case-insensitively for macOS/Windows paths.
216
+ if (shouldForce || basename(outputPath).toLowerCase() !== DEFAULT_BASELINE_FILENAME) {
217
+ return;
218
+ }
219
+ try {
220
+ // A directory or symlink at the default filename needs an explicit overwrite decision from the user.
221
+ if (!lstatSync(outputPath).isFile()) {
222
+ throw new BaselineFileError(`baseline ${outputPath} is not a regular file`);
223
+ }
224
+ readBaselineDocument(outputPath);
225
+ } catch (error) {
226
+ // A project generating its first baseline has no previous review file to protect.
227
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
228
+ return;
229
+ }
230
+ throw new BaselineFileError(`${unreadableReason(error)}; generating over it would destroy the retreat path. Pass --force to overwrite it or choose a different output path.`);
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Builds a timestamped baseline document from the scan findings, with one row per identity in stable order.
236
+ *
237
+ * @param findings - scan findings to aggregate into baseline rows and sensitive counts
238
+ * @param declarationPosition - optional resolver for declaration positions; without it, finding lines are used
239
+ * @returns Timestamped baseline document with sorted occurrence rows and sensitive rule totals.
240
+ */
241
+ function baselineDocument(findings: Finding[], declarationPosition?: DeclarationPositionResolver): BaselineDocument {
242
+ const identities = findingIdentities(findings, declarationPosition);
243
+ const rows = new Map<string, BaselineEntry>();
244
+ const sensitiveByRule: Record<string, number> = {};
245
+
246
+ // A review covers one occurrence for each eligible finding in the scan snapshot.
247
+ findings.forEach((finding, index) => {
248
+ const named = identities[index];
249
+ // An absent identity leaves this finding visible on later runs.
250
+ if (named === undefined) {
251
+ // Sensitive findings still contribute to the category totals. The first finding for a rule starts at zero.
252
+ if (!isBaselineEligible(finding)) {
253
+ sensitiveByRule[finding.ruleId] = (sensitiveByRule[finding.ruleId] ?? 0) + 1;
254
+ }
255
+ return;
256
+ }
257
+ // The first occurrence creates a row. Later matches extend the same review count.
258
+ const existing = rows.get(named.identity);
259
+ rows.set(named.identity, {
260
+ identity: named.identity,
261
+ count: (existing?.count ?? 0) + 1,
262
+ ruleId: finding.ruleId,
263
+ path: finding.filePath,
264
+ subject: named.subject,
265
+ });
266
+ });
267
+
268
+ const total = Object.values(sensitiveByRule).reduce((sum, count) => sum + count, 0);
269
+ return {
270
+ schemaVersion: BASELINE_SCHEMA_VERSION,
271
+ toolLanguage: TOOL_LANGUAGE,
272
+ generatedAt: new Date().toISOString(),
273
+ occurrences: [...rows.values()].sort((left, right) => left.identity.localeCompare(right.identity)),
274
+ sensitive: {
275
+ eligible: false,
276
+ reason: SENSITIVE_INELIGIBILITY_REASON,
277
+ counts: { total, byRule: Object.fromEntries(Object.entries(sensitiveByRule).sort(([left], [right]) => left.localeCompare(right))) },
278
+ },
279
+ };
280
+ }
281
+
282
+ /**
283
+ * Signals a baseline that cannot be safely applied or written.
284
+ *
285
+ * For example, `analyse --baseline review.json` reports `baseline-error` and exits 2 if that review file contains broken JSON.
286
+ * The CLI can then surface a file or migration error without applying any of its review rows.
287
+ */
288
+ export class BaselineFileError extends Error {}
289
+
290
+ /**
291
+ * Reads and validates the v3 baseline at path for this tool language, including every occurrence row.
292
+ *
293
+ * @param path - baseline file path to read and validate
294
+ * @returns Validated baseline document with checked occurrence rows.
295
+ * @throws {BaselineFileError} - the file is unreadable, malformed, from an unsupported schema or port, or contains an invalid row
296
+ */
297
+ function readBaselineDocument(path: string): BaselineDocument {
298
+ const parsed = parsedBaselineFile(path);
299
+ // A 0.5 file fails closed and names the command that carries its reviews forward, so nothing is silently dropped.
300
+ if (parsed.schemaVersion === LEGACY_BASELINE_SCHEMA_VERSION) {
301
+ throw new BaselineFileError(
302
+ `baseline ${path} is a 0.5 baseline; migrate it to a separate file with \`gruff-ts analyse --migrate-baseline ${path} --generate-baseline <new path>\`, the original is preserved`,
303
+ );
304
+ }
305
+ // Reject files whose review format this version cannot interpret.
306
+ if (parsed.schemaVersion !== BASELINE_SCHEMA_VERSION) {
307
+ throw new BaselineFileError(`unsupported baseline schema in ${path}`);
308
+ }
309
+ // A baseline names its writer, so another port's file is refused instead of reporting every row resolved.
310
+ if (parsed.toolLanguage !== TOOL_LANGUAGE) {
311
+ throw new BaselineFileError(`baseline ${path} was written by ${writerName(parsed.toolLanguage)} and this run is ${TOOL_LANGUAGE}; baselines are not shared across languages`);
312
+ }
313
+ // A review with no entries can use an empty list. An omitted list cannot establish what was reviewed.
314
+ if (!parsed.occurrences) {
315
+ throw new BaselineFileError(`baseline ${path} occurrences must be a list`);
316
+ }
317
+ const occurrences = parsed.occurrences.map((row, index) => validatedRow(path, row, index));
318
+ // A hand-edited duplicate would make the reviewed count for that finding ambiguous.
319
+ if (new Set(occurrences.map((entry) => entry.identity)).size !== occurrences.length) {
320
+ throw new BaselineFileError(`baseline ${path} contains a duplicate occurrence identity`);
321
+ }
322
+ return { ...(parsed as BaselineDocument), occurrences };
323
+ }
324
+
325
+ // A baseline file as parsed, before its rows are validated: every field may be missing and a row may be anything.
326
+ type ParsedBaselineFile = Omit<Partial<BaselineDocument>, "occurrences"> & { occurrences?: unknown[] };
327
+
328
+ /**
329
+ * Reads and parses the baseline file at path as a JSON object, checking that its occurrence list is an array when present.
330
+ * The caller still checks the schema, writer language, and individual rows before applying any review.
331
+ *
332
+ * @param path - baseline file path to read from disk and parse as JSON
333
+ * @returns Parsed baseline object with unvalidated fields and optional occurrences list.
334
+ * @throws {BaselineFileError} - reading or parsing fails, the root is not an object, or occurrences is present without an array
335
+ */
336
+ function parsedBaselineFile(path: string): ParsedBaselineFile {
337
+ let parsed: unknown;
338
+ try {
339
+ parsed = JSON.parse(readFileSync(path, "utf8"));
340
+ } catch (error) {
341
+ throw new BaselineFileError(`baseline ${path} cannot be read: ${unreadableReason(error)}`);
342
+ }
343
+ // `null`, a list or a bare value has no schema to read, so the file is refused before any field is.
344
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
345
+ throw new BaselineFileError(`baseline ${path} must be a JSON object`);
346
+ }
347
+ const occurrences = (parsed as { occurrences?: unknown }).occurrences;
348
+ // Rows are validated one by one, which needs a list to walk.
349
+ if (occurrences !== undefined && !Array.isArray(occurrences)) {
350
+ throw new BaselineFileError(`baseline ${path} occurrences must be a list`);
351
+ }
352
+ return parsed as ParsedBaselineFile;
353
+ }
354
+
355
+ /**
356
+ * Turns a baseline read or parse error into diagnostic text, with a fixed reason for a missing file.
357
+ * Replaces JSON syntax errors with a fixed reason because parser messages can quote file contents. Other error messages pass through.
358
+ *
359
+ * @param error - caught filesystem or JSON parse error to describe
360
+ * @returns Sanitized diagnostic reason string for the failure.
361
+ */
362
+ function unreadableReason(error: unknown): string {
363
+ if ((error as { code?: unknown }).code === "ENOENT") {
364
+ return "the file does not exist";
365
+ }
366
+ if (error instanceof SyntaxError) {
367
+ return "the file is not valid JSON";
368
+ }
369
+ return error instanceof Error ? error.message : String(error);
370
+ }
371
+
372
+ /**
373
+ * Names the port that wrote a refused baseline without quoting arbitrary file input.
374
+ *
375
+ * @param toolLanguage - raw toolLanguage field read from the baseline document
376
+ * @returns Family port language name when recognized, or "an unrecognised port" otherwise.
377
+ */
378
+ function writerName(toolLanguage: unknown): string {
379
+ return typeof toolLanguage === "string" && FAMILY_TOOL_LANGUAGES.has(toolLanguage) ? toolLanguage : "an unrecognised port";
380
+ }
381
+
382
+ /**
383
+ * Validates a candidate baseline row and returns the reviewed entry, copying only nonempty text for optional descriptions.
384
+ *
385
+ * @param path - baseline file path used to locate an invalid entry in diagnostics
386
+ * @param candidate - raw parsed row value to validate
387
+ * @param index - zero-based index of the candidate in occurrences for error reporting
388
+ * @returns Normalized baseline entry containing identity, count, and any nonempty optional fields.
389
+ * @throws {BaselineFileError} - the candidate is not an object row, its identity or count is invalid, or a forbidden key is present
390
+ */
391
+ function validatedRow(path: string, candidate: unknown, index: number): BaselineEntry {
392
+ // A row that is not an object has no identity to match, so the file is refused as written.
393
+ if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) {
394
+ throw new BaselineFileError(`baseline ${path} occurrences[${index}] must be an object`);
395
+ }
396
+ const row = candidate as Record<string, unknown>;
397
+ const identity = row.identity;
398
+ // The baseline schema requires 16 lowercase hex characters so that reviewed rows share one digest format.
399
+ if (typeof identity !== "string" || !/^[0-9a-f]{16}$/u.test(identity)) {
400
+ throw new BaselineFileError(`baseline ${path} occurrences[${index}].identity must be 16 lowercase hex characters`);
401
+ }
402
+ const count = row.count;
403
+ // A reviewed row needs a positive whole count to give it a usable suppression budget.
404
+ if (typeof count !== "number" || !Number.isInteger(count) || count < 1) {
405
+ throw new BaselineFileError(`baseline ${path} occurrences[${index}].count must be a positive integer`);
406
+ }
407
+ for (const forbidden of FORBIDDEN_OCCURRENCE_KEYS) {
408
+ // Refuse positional and diagnostic fields to keep line numbers and raw diagnostic details out of the reviewed row.
409
+ if (forbidden in row) {
410
+ throw new BaselineFileError(`baseline ${path} occurrences[${index}] carries forbidden key "${forbidden}"`);
411
+ }
412
+ }
413
+ return { identity, count, ...optionalText(row, "ruleId"), ...optionalText(row, "path"), ...optionalText(row, "subject") };
414
+ }
415
+
416
+ /**
417
+ * Extracts an optional string field from a baseline row only when it contains nonempty text.
418
+ *
419
+ * @param row - parsed baseline row object to inspect
420
+ * @param key - property name to read from the row
421
+ * @returns Single-entry object with the field value, or an empty object so absent or empty fields are omitted.
422
+ */
423
+ function optionalText(row: Record<string, unknown>, key: string): Record<string, string> {
424
+ const storedText = row[key];
425
+ return typeof storedText === "string" && storedText.length > 0 ? { [key]: storedText } : {};
426
+ }
427
+
428
+ // Every occurrence of one identity in this run, plus what it takes to judge them together.
429
+ interface IdentityGroup {
430
+ indexes: number[];
431
+ declarations: Set<string>;
432
+ subjects: string[];
433
+ ruleId: string;
434
+ path: string;
435
+ }
436
+
437
+ /**
438
+ * Groups current findings by stable baseline identity for matching and collision reporting.
439
+ * Each group retains finding indexes, declaration keys, and distinct subjects.
440
+ *
441
+ * @param findings - current findings in scan order
442
+ * @param identities - computed identity per finding in matching array order, or undefined when ineligible
443
+ * @returns Map keyed by stable baseline identity containing each group's indexes, declarations, subjects, ruleId, and path.
444
+ */
445
+ function groupByIdentity(findings: Finding[], identities: Array<FindingIdentity | undefined>): Map<string, IdentityGroup> {
446
+ const groups = new Map<string, IdentityGroup>();
447
+ findings.forEach((finding, index) => {
448
+ const named = identities[index];
449
+ // Findings without an identity stay outside the groups, so baseline review rows cannot hide them.
450
+ if (named === undefined) {
451
+ return;
452
+ }
453
+ const group = groups.get(named.identity) ?? { indexes: [], declarations: new Set<string>(), subjects: [], ruleId: finding.ruleId, path: finding.filePath };
454
+ group.indexes.push(index);
455
+ group.declarations.add(named.declarationKey);
456
+ if (!group.subjects.includes(named.subject)) {
457
+ group.subjects.push(named.subject);
458
+ }
459
+ groups.set(named.identity, group);
460
+ });
461
+ return groups;
462
+ }
463
+
464
+ /**
465
+ * Spend reviewed counts in stable line and column order so that identical inputs cover the same occurrences.
466
+ *
467
+ * @param findings - current findings whose locations determine spend order
468
+ * @param identities - identity per finding in input order, with undefined marking an ineligible occurrence
469
+ * @param groups - identity groups used to detect claims spanning multiple declarations
470
+ * @param reviewed - baseline counts by identity, with missing entries providing no allowance
471
+ * @returns One status per finding in input order. Unchanged marks a covered occurrence, and other statuses keep it visible.
472
+ */
473
+ function classify(findings: Finding[], identities: Array<FindingIdentity | undefined>, groups: Map<string, IdentityGroup>, reviewed: Map<string, BaselineEntry>): string[] {
474
+ const statuses = findings.map(() => "new");
475
+ const spentPerIdentity = new Map<string, number>();
476
+
477
+ for (const index of spendOrder(findings)) {
478
+ const named = identities[index];
479
+ // A finding without an identity is ineligible, so a reviewed row cannot hide it.
480
+ if (named === undefined) {
481
+ statuses[index] = "notEligible";
482
+ continue;
483
+ }
484
+ // An identity spanning multiple declarations is ambiguous, so every occurrence with that identity stays visible.
485
+ if ((groups.get(named.identity)?.declarations.size ?? 0) > 1) {
486
+ statuses[index] = "collision";
487
+ continue;
488
+ }
489
+ const spent = spentPerIdentity.get(named.identity) ?? 0;
490
+ statuses[index] = spent < (reviewed.get(named.identity)?.count ?? 0) ? "unchanged" : "new";
491
+ spentPerIdentity.set(named.identity, spent + 1);
492
+ }
493
+ return statuses;
494
+ }
495
+
496
+ /**
497
+ * Computes finding indexes in stable reviewed-count spend order, sorted by line then column.
498
+ * A missing line uses the last-line sentinel, and a missing column sorts as zero.
499
+ *
500
+ * @param findings - current findings whose locations determine spend order
501
+ * @returns Array of zero-based indexes into findings in deterministic spend order.
502
+ */
503
+ function spendOrder(findings: Finding[]): number[] {
504
+ return findings
505
+ .map((_, index) => index)
506
+ .sort((left, right) => {
507
+ const leftFinding = findings[left];
508
+ const rightFinding = findings[right];
509
+ return (leftFinding?.line ?? UNLOCATED_SPEND_LINE) - (rightFinding?.line ?? UNLOCATED_SPEND_LINE) || (leftFinding?.column ?? 0) - (rightFinding?.column ?? 0);
510
+ });
511
+ }
512
+
513
+ /**
514
+ * Computes reviewed rows whose counts exceed current group sizes, with each count set to the number absent from this scan.
515
+ * Collided identities are excluded; when an identity has no current group, its full reviewed count is resolved.
516
+ *
517
+ * @param entries - baseline entries from the stored review file
518
+ * @param groups - current scan findings grouped by baseline identity
519
+ * @param statuses - per-finding classification statuses used to detect collisions
520
+ * @returns Copies of resolved baseline entries with counts reduced to the absent surplus.
521
+ */
522
+ function resolvedSurplus(entries: BaselineEntry[], groups: Map<string, IdentityGroup>, statuses: string[]): BaselineEntry[] {
523
+ return entries.flatMap((entry) => {
524
+ const group = groups.get(entry.identity);
525
+ // A collided identity is accounted for by its collision; counting it resolved would double-report it.
526
+ if (group !== undefined && statuses[group.indexes[0] ?? 0] === "collision") {
527
+ return [];
528
+ }
529
+ const surplus = entry.count - (group?.indexes.length ?? 0);
530
+ return surplus > 0 ? [{ ...entry, count: surplus }] : [];
531
+ });
532
+ }
533
+
534
+ /**
535
+ * Builds diagnostic collision records for every identity group that spans multiple declarations.
536
+ *
537
+ * @param groups - current scan findings grouped by baseline identity
538
+ * @returns Collision records containing each ambiguous identity's rule, path, and known subjects.
539
+ */
540
+ function collidedIdentities(groups: Map<string, IdentityGroup>): BaselineCollision[] {
541
+ return [...groups.entries()]
542
+ .filter(([, group]) => group.declarations.size > 1)
543
+ .map(([identity, group]) => ({ identity, ruleId: group.ruleId, path: group.path, subjects: group.subjects }));
544
+ }
545
+
546
+ /**
547
+ * Protects the original baseline by verifying that the migration input and output paths refer to distinct files.
548
+ * A new destination can pass the path check without an inode comparison.
549
+ *
550
+ * @param inputPath - existing legacy baseline file path
551
+ * @param outputPath - proposed destination path for the migrated baseline
552
+ * @returns Nothing. Allows migration to proceed when the paths are distinct.
553
+ * @throws {BaselineFileError} - the input and output paths compare equal after resolution or have matching device and inode numbers.
554
+ */
555
+ function requireDistinctPaths(inputPath: string, outputPath: string): void {
556
+ const resolvedInput = resolvedFilePath(inputPath);
557
+ // A symlink or a hard link would make the "different" output the same bytes, destroying the retreat path.
558
+ if (resolvedInput === resolvedFilePath(outputPath) || sameInode(inputPath, outputPath)) {
559
+ throw new BaselineFileError(`migration output must be a different file from its input: ${inputPath}`);
560
+ }
561
+ }
562
+
563
+ /**
564
+ * Resolves a migration path to its canonical filesystem location, falling back to the supplied spelling on failure.
565
+ *
566
+ * @param path - file path to canonicalize via the filesystem
567
+ * @returns Canonical real path, or the original path when filesystem resolution fails.
568
+ */
569
+ function resolvedFilePath(path: string): string {
570
+ try {
571
+ return realpathSync(path);
572
+ } catch {
573
+ // A new output may have no target yet, so the caller can still compare its spelling and check inode identity separately.
574
+ return path;
575
+ }
576
+ }
577
+
578
+ /**
579
+ * Checks whether two paths refer to the same underlying file on disk, including via a hard link.
580
+ *
581
+ * @param inputPath - first file path to stat
582
+ * @param outputPath - second file path to stat
583
+ * @returns True when both paths share a device and inode, or false if either stat fails.
584
+ */
585
+ function sameInode(inputPath: string, outputPath: string): boolean {
586
+ try {
587
+ const input = statSync(inputPath);
588
+ const output = statSync(outputPath);
589
+ return input.dev === output.dev && input.ino === output.ino;
590
+ } catch {
591
+ // A new output normally has no inode yet, leaving the caller's resolved-path comparison as the other alias check.
592
+ return false;
593
+ }
594
+ }
595
+
596
+ /**
597
+ * Reads and validates the 0.5 review rows for `analyse --migrate-baseline`. An empty list carries forward zero reviews.
598
+ * Invariant: a file with conflicting row lists leaves the user's previous reviews ambiguous, so migration requires exactly one list.
599
+ *
600
+ * @param path - legacy baseline file path used in error diagnostics
601
+ * @param contents - raw file bytes already read from the legacy baseline
602
+ * @returns Validated legacy row objects from the single row container.
603
+ * @throws {BaselineFileError} when the input is not a valid 0.5 baseline with exactly one row container.
604
+ */
605
+ function legacyRows(path: string, contents: Buffer): Array<Record<string, unknown>> {
606
+ let parsed: Record<string, unknown> | null;
607
+ try {
608
+ parsed = JSON.parse(contents.toString("utf8")) as Record<string, unknown> | null;
609
+ } catch (error) {
610
+ // A legacy JSON file can contain a merge-conflict marker after a branch merge.
611
+ throw new BaselineFileError(`migration input ${path} cannot be read: ${unreadableReason(error)}`);
612
+ }
613
+ // A null object or a newer file does not provide the 0.5 review format migration expects.
614
+ if (parsed?.schemaVersion !== LEGACY_BASELINE_SCHEMA_VERSION) {
615
+ throw new BaselineFileError(`migration input ${path} is not a 0.5 baseline`);
616
+ }
617
+ const present = LEGACY_ROW_CONTAINERS.filter((container) => Array.isArray(parsed[container]));
618
+ // When two valid lists exist, the user must choose which list represents the reviews they want to keep.
619
+ if (present.length > 1) {
620
+ throw new BaselineFileError(`migration input ${path} carries more than one row container (${present.join(", ")}); a migration input must name exactly one`);
621
+ }
622
+ const rows = present.length === 1 ? parsed[present[0] as string] : undefined;
623
+ // Missing review lists usually mean the wrong input file was supplied.
624
+ if (!Array.isArray(rows)) {
625
+ throw new BaselineFileError(`migration input ${path} must carry an "entries" or "findings" list`);
626
+ }
627
+ return rows.map((row: unknown, index) => {
628
+ // Each review needs named fields. A blank list item cannot be matched to a finding.
629
+ if (typeof row !== "object" || row === null || Array.isArray(row)) {
630
+ throw new BaselineFileError(`migration input ${path} row ${index} must be an object`);
631
+ }
632
+ const entry = row as Record<string, unknown>;
633
+ // Check both legacy path names and the optional details used to match a review.
634
+ for (const key of ["ruleId", "filePath", "file", "symbol", "message"]) {
635
+ // An omitted detail is valid. A number or null can accidentally broaden which current findings match.
636
+ if (entry[key] !== undefined && typeof entry[key] !== "string") {
637
+ throw new BaselineFileError(`migration input ${path} row ${index}.${key} must be a string`);
638
+ }
639
+ }
640
+ return entry;
641
+ });
642
+ }
643
+
644
+ // The fields of one 0.5 baseline row that decide which current finding inherits its review.
645
+ interface LegacyRowCriteria {
646
+ ruleId: string;
647
+ path: string;
648
+ symbol: string;
649
+ message: string;
650
+ line?: number;
651
+ }
652
+
653
+ /**
654
+ * Carries reviews forward from a 0.5 baseline: each old row can cover one current finding with the same rule and file.
655
+ *
656
+ * A row must also agree on any symbol and message it stored, and a row on the finding's own line is preferred.
657
+ * Matching runs per file so the most findings keep a review, even when one row stored only a symbol and another only a message.
658
+ *
659
+ * @param rows - legacy occurrence rows that supply one unit of acceptance each
660
+ * @param findings - current findings eligible to consume that acceptance
661
+ * @returns Current findings covered by the legacy rows in stable spend order, or an empty list when none match.
662
+ */
663
+ function acceptedByLegacy(rows: Array<Record<string, unknown>>, findings: Finding[]): Finding[] {
664
+ const rowsByGroup = new Map<string, LegacyRowCriteria[]>();
665
+ for (const row of rows) {
666
+ const criteria = legacyRowCriteria(row);
667
+ const groupKey = `${criteria.ruleId}\0${criteria.path}`;
668
+ const group = rowsByGroup.get(groupKey) ?? [];
669
+ group.push(criteria);
670
+ rowsByGroup.set(groupKey, group);
671
+ }
672
+ const orderedIndices = spendOrder(findings);
673
+ const findingsByGroup = new Map<string, number[]>();
674
+ // Group current findings by rule and file in spend order, so each group is matched only against old rows for that same file.
675
+ for (const findingIndex of orderedIndices) {
676
+ const finding = findings[findingIndex];
677
+ // spendOrder only returns positions inside the list; this guard satisfies the type checker.
678
+ if (finding === undefined) {
679
+ continue;
680
+ }
681
+ const groupKey = `${finding.ruleId}\0${finding.filePath}`;
682
+ // A finding with no 0.5 row for its rule and file has no old review to inherit, so it stays new.
683
+ if (!rowsByGroup.has(groupKey)) {
684
+ continue;
685
+ }
686
+ const group = findingsByGroup.get(groupKey) ?? [];
687
+ group.push(findingIndex);
688
+ findingsByGroup.set(groupKey, group);
689
+ }
690
+ const matchedIndices = new Set<number>();
691
+ // Match each rule-and-file group on its own, so one file's old reviews never cover another file's findings.
692
+ for (const [groupKey, groupFindingIndices] of findingsByGroup) {
693
+ const groupRows = rowsByGroup.get(groupKey) ?? [];
694
+ // Collect every finding in this group that inherited a 0.5 review.
695
+ for (const matched of matchLegacyGroup(groupFindingIndices, groupRows, findings)) {
696
+ matchedIndices.add(matched);
697
+ }
698
+ }
699
+ // Return matched findings in stable line/column spend order.
700
+ return orderedIndices
701
+ .filter((index) => matchedIndices.has(index))
702
+ .map((index) => findings[index])
703
+ .filter((finding): finding is Finding => finding !== undefined);
704
+ }
705
+
706
+ /**
707
+ * Pairs findings with old 0.5 rows for one rule and file, giving each row to at most one finding, the same way on every run.
708
+ *
709
+ * First, findings still on their old row's line claim those rows.
710
+ * Then the rest take any compatible row, moving earlier picks when that lets more findings keep a review without dropping any.
711
+ *
712
+ * @param findingIndices - finding indexes in stable spend order sharing one `(ruleId, path)` group
713
+ * @param groupRows - legacy 0.5 rows sharing the same `(ruleId, path)` group
714
+ * @param findings - full findings array indexed by `findingIndices`
715
+ * @returns Finding indexes matched to distinct legacy rows in this group.
716
+ */
717
+ function matchLegacyGroup(findingIndices: readonly number[], groupRows: readonly LegacyRowCriteria[], findings: readonly Finding[]): number[] {
718
+ const exactLineRowsByFinding = findingIndices.map((findingIndex) => compatibleLegacyRows(findings[findingIndex], groupRows, true));
719
+ const compatibleRowsByFinding = findingIndices.map((findingIndex) => compatibleLegacyRows(findings[findingIndex], groupRows, false));
720
+ const rowOwner = new Array<number>(groupRows.length).fill(-1);
721
+ const matchedFindingSlots = new Set<number>();
722
+
723
+ // Pass 1: claim exact-line matches first so unchanged occurrences keep their own reviewed rows.
724
+ for (let slot = 0; slot < findingIndices.length && matchedFindingSlots.size < groupRows.length; slot += 1) {
725
+ // A finding still on its old row's line claims that row before any looser match can take it.
726
+ if ((exactLineRowsByFinding[slot]?.length ?? 0) > 0
727
+ && tryAugmentLegacyMatch(slot, exactLineRowsByFinding, rowOwner, new Uint8Array(groupRows.length))) {
728
+ matchedFindingSlots.add(slot);
729
+ }
730
+ }
731
+ // Pass 2: match remaining findings (rearranging earlier picks when needed) so the most findings keep a review.
732
+ // Both passes stop once every old row has an owner, so surplus findings in a large file never start a search that cannot succeed.
733
+ for (let slot = 0; slot < findingIndices.length && matchedFindingSlots.size < groupRows.length; slot += 1) {
734
+ // A finding without an exact-line row takes any compatible row; earlier picks may move to other rows so more findings fit.
735
+ if (!matchedFindingSlots.has(slot) && tryAugmentLegacyMatch(slot, compatibleRowsByFinding, rowOwner, new Uint8Array(groupRows.length))) {
736
+ matchedFindingSlots.add(slot);
737
+ }
738
+ }
739
+ return [...matchedFindingSlots].flatMap((slot) => {
740
+ const findingIndex = findingIndices[slot];
741
+ return findingIndex === undefined ? [] : [findingIndex];
742
+ });
743
+ }
744
+
745
+ /**
746
+ * Tries to give one finding an old row, moving other findings to their own spare rows when that frees one up.
747
+ * Updates `rowOwner` and `visitedRows` in place.
748
+ *
749
+ * @param slot - finding slot index in the current `(ruleId, path)` group
750
+ * @param compatibleRowsBySlot - ordered compatible legacy-row indexes for each finding slot; an empty list leaves the finding unmatched
751
+ * @param rowOwner - mutable mapping from legacy-row index to owning finding slot (or `-1` if free)
752
+ * @param visitedRows - per-attempt visited flags preventing cycles in the augmenting search
753
+ * @returns True if a compatible row was assigned (directly or by moving earlier picks); otherwise false.
754
+ */
755
+ function tryAugmentLegacyMatch(
756
+ slot: number,
757
+ compatibleRowsBySlot: ReadonlyArray<readonly number[]>,
758
+ rowOwner: number[],
759
+ visitedRows: Uint8Array,
760
+ ): boolean {
761
+ // A free compatible row is taken straight away, so a large group of interchangeable rows never needs a deep search.
762
+ for (const rowIndex of compatibleRowsBySlot[slot] ?? []) {
763
+ // Claim the first unvisited compatible row that no other finding owns yet.
764
+ if (visitedRows[rowIndex] !== 1 && (rowOwner[rowIndex] ?? -1) === -1) {
765
+ visitedRows[rowIndex] = 1;
766
+ rowOwner[rowIndex] = slot;
767
+ return true;
768
+ }
769
+ }
770
+ // Try the finding's compatible old rows, most specific first.
771
+ for (const rowIndex of compatibleRowsBySlot[slot] ?? []) {
772
+ // Each row is tried once per search, which stops two findings from swapping the same row forever.
773
+ if (visitedRows[rowIndex] === 1) {
774
+ continue;
775
+ }
776
+ visitedRows[rowIndex] = 1;
777
+ const owner = rowOwner[rowIndex] ?? -1;
778
+ // Take a free row, or move the row's current finding to another row it fits, so both findings keep a review.
779
+ if (owner === -1 || tryAugmentLegacyMatch(owner, compatibleRowsBySlot, rowOwner, visitedRows)) {
780
+ rowOwner[rowIndex] = slot;
781
+ return true;
782
+ }
783
+ }
784
+ return false;
785
+ }
786
+
787
+ /**
788
+ * Lists legacy row indexes compatible with `finding` in stable deterministic order (descending specificity score, then declaration order).
789
+ *
790
+ * @param finding - current finding to compare against group legacy rows; `undefined` matches no rows
791
+ * @param groupRows - legacy rows in the same `(ruleId, path)` group; an empty list returns no matches
792
+ * @param requireExactLine - when true, keeps only rows whose stored numeric `line` equals `finding.line`
793
+ * @returns Compatible row indexes sorted by descending specificity score, tie-broken by declaration order, or an empty list when none match.
794
+ */
795
+ function compatibleLegacyRows(finding: Finding | undefined, groupRows: readonly LegacyRowCriteria[], requireExactLine: boolean): number[] {
796
+ // A position without a finding matches no rows.
797
+ if (finding === undefined) {
798
+ return [];
799
+ }
800
+ const scored: Array<{ rowIndex: number; score: number }> = [];
801
+ // Score every old row for this rule and file against the finding.
802
+ for (const [rowIndex, row] of groupRows.entries()) {
803
+ const score = legacyMatchScore(row, finding, requireExactLine);
804
+ // Keep only rows whose stored symbol, message and line agree with this finding.
805
+ if (score !== undefined) {
806
+ scored.push({ rowIndex, score });
807
+ }
808
+ }
809
+ return scored.sort((left, right) => right.score - left.score || left.rowIndex - right.rowIndex).map((entry) => entry.rowIndex);
810
+ }
811
+
812
+ /**
813
+ * Computes a deterministic compatibility score for one legacy row against a finding, or undefined when incompatible.
814
+ * Stable ordering: `symbol+message` (6) > `symbol` (4) > `message` (2) > `rule+path` (0), with `+1` for an exact line match.
815
+ *
816
+ * @param row - parsed 0.5 legacy row criteria
817
+ * @param finding - current finding being tested for compatibility
818
+ * @param requireExactLine - when true, rejects rows without an exact line match to `finding.line`
819
+ * @returns Non-negative specificity score when compatible, or undefined when symbol, message, or required line differs.
820
+ */
821
+ function legacyMatchScore(row: LegacyRowCriteria, finding: Finding, requireExactLine: boolean): number | undefined {
822
+ const symbol = finding.symbol ?? "";
823
+ // An old row that stored a symbol only covers findings in that same symbol.
824
+ if (row.symbol.length > 0 && row.symbol !== symbol) {
825
+ return undefined;
826
+ }
827
+ // An old row that stored a message only covers findings with exactly that message.
828
+ if (row.message.length > 0 && row.message !== finding.message) {
829
+ return undefined;
830
+ }
831
+ const isExactLine = row.line !== undefined && finding.line === row.line;
832
+ // In the exact-line pass, a row stored for another line is left for the second pass.
833
+ if (requireExactLine && !isExactLine) {
834
+ return undefined;
835
+ }
836
+ const baseScore = (row.symbol.length > 0 ? 4 : 0) + (row.message.length > 0 ? 2 : 0);
837
+ return baseScore + (isExactLine ? 1 : 0);
838
+ }
839
+
840
+ /**
841
+ * Extracts normalized matching criteria from one validated 0.5 legacy row, retaining positive integer `line` when present.
842
+ *
843
+ * @param row - validated raw 0.5 row object
844
+ * @returns Normalized criteria carrying ruleId, path, symbol, message, and optional positive integer line.
845
+ */
846
+ function legacyRowCriteria(row: Record<string, unknown>): LegacyRowCriteria {
847
+ const rawLine = row.line;
848
+ return {
849
+ ruleId: rowText(row, "ruleId"),
850
+ path: rowText(row, "filePath") || rowText(row, "file"),
851
+ symbol: rowText(row, "symbol"),
852
+ message: rowText(row, "message"),
853
+ ...(typeof rawLine === "number" && Number.isInteger(rawLine) && rawLine > 0 ? { line: rawLine } : {}),
854
+ };
855
+ }
856
+
857
+ /**
858
+ * Reads an optional string field from a legacy baseline row with an empty-string fallback.
859
+ *
860
+ * @param row - legacy baseline row object to inspect
861
+ * @param key - property name to read from the row
862
+ * @returns String value of the field, or empty string when absent or non-string.
863
+ */
864
+ function rowText(row: Record<string, unknown>, key: string): string {
865
+ const storedText = row[key];
866
+ return typeof storedText === "string" ? storedText : "";
867
+ }