actions-warden 0.3.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 (78) hide show
  1. package/AGENTS.md +60 -12
  2. package/CONTRIBUTING.md +6 -2
  3. package/README.md +180 -58
  4. package/RELEASING.md +3 -2
  5. package/SECURITY.md +23 -8
  6. package/docs/AI-AGENTS.md +125 -29
  7. package/docs/CLI.md +346 -69
  8. package/docs/CONFIGURATION.md +34 -11
  9. package/docs/DEVELOPMENT.md +114 -18
  10. package/docs/GITHUB-ACTION.md +163 -29
  11. package/docs/JAVASCRIPT-API.md +177 -11
  12. package/docs/OUTPUTS.md +408 -40
  13. package/docs/README.md +1 -1
  14. package/examples/README.md +21 -0
  15. package/examples/baseline-adoption/README.md +79 -0
  16. package/examples/baseline-adoption/github-actions.yml +56 -0
  17. package/examples/baseline-adoption/policy.yml +7 -0
  18. package/examples/ci-violation-reporting/README.md +82 -0
  19. package/examples/ci-violation-reporting/github-actions.yml +55 -0
  20. package/examples/ci-violation-reporting/policy.yml +7 -0
  21. package/examples/ci-violation-reporting/violating-workflow.yml +17 -0
  22. package/examples/csv-reporting/README.md +50 -0
  23. package/examples/csv-reporting/github-actions.yml +59 -0
  24. package/examples/html-organization-report/README.md +35 -0
  25. package/examples/html-organization-report/github-actions.yml +61 -0
  26. package/examples/notifications/README.md +67 -0
  27. package/examples/notifications/github-actions.yml +163 -0
  28. package/examples/org-scan.yml +24 -5
  29. package/examples/sarif-code-scanning/README.md +42 -0
  30. package/examples/sarif-code-scanning/github-actions.yml +66 -0
  31. package/examples/upgrade-pr.yml +1 -1
  32. package/llms.txt +14 -5
  33. package/package.json +8 -4
  34. package/skills/actions-warden/SKILL.md +91 -39
  35. package/src/action.js +353 -187
  36. package/src/cli.js +416 -209
  37. package/src/commands/audit.js +17 -30
  38. package/src/commands/org-scan.js +452 -286
  39. package/src/commands/pin.js +9 -5
  40. package/src/commands/report.js +7 -2
  41. package/src/commands/upgrade.js +9 -5
  42. package/src/commands/verify.js +24 -4
  43. package/src/index.js +5 -1
  44. package/src/lib/action-summary.js +656 -0
  45. package/src/lib/annotations.js +4 -6
  46. package/src/lib/baseline.js +11 -1
  47. package/src/lib/config.js +10 -5
  48. package/src/lib/destination.js +98 -0
  49. package/src/lib/execution.js +5 -1
  50. package/src/lib/formats/csv.js +125 -0
  51. package/src/lib/formats/html.js +394 -0
  52. package/src/lib/formats/json.js +17 -0
  53. package/src/lib/formats/sarif.js +229 -0
  54. package/src/lib/formats/text.js +30 -0
  55. package/src/lib/formats/toon.js +50 -0
  56. package/src/lib/formatter.js +25 -192
  57. package/src/lib/github-org.js +208 -102
  58. package/src/lib/org-artifacts.js +211 -0
  59. package/src/lib/org-checkpoint.js +159 -35
  60. package/src/lib/org-progress.js +182 -4
  61. package/src/lib/org-report-comparison.js +505 -0
  62. package/src/lib/org-report-directory.js +251 -0
  63. package/src/lib/org-report.js +223 -0
  64. package/src/lib/org-run.js +305 -0
  65. package/src/lib/org-schema.js +89 -0
  66. package/src/lib/org-source-links.js +39 -0
  67. package/src/lib/parser.js +5 -0
  68. package/src/lib/path-equality.js +30 -0
  69. package/src/lib/paths.js +18 -1
  70. package/src/lib/redact.js +58 -7
  71. package/src/lib/resolver.js +66 -9
  72. package/src/lib/types.js +137 -0
  73. package/src/lib/writer.js +3 -0
  74. package/src/rules/pull-request-target-checkout.js +5 -0
  75. package/src/rules/unpinned-action.js +2 -3
  76. package/src/rules/workflow-structure.js +2 -4
  77. package/src/version.js +1 -1
  78. package/src/lib/agent-mode.js +0 -175
@@ -0,0 +1,505 @@
1
+ /**
2
+ * Deterministic comparison of complete organization JSON reports.
3
+ *
4
+ * Resolution claims fail closed: a previous finding is resolved only when the
5
+ * current report used the same analysis identity and successfully covered the
6
+ * finding's repository. Missing or failed repositories make findings unknown.
7
+ */
8
+
9
+ import { readFile, stat } from 'node:fs/promises';
10
+ import { resolveRepositoryFile } from './config.js';
11
+ import {
12
+ NAME_RE,
13
+ SEVERITIES,
14
+ VISIBILITIES,
15
+ isJsonValue,
16
+ isRecord,
17
+ } from './org-schema.js';
18
+
19
+ const MAX_ORGANIZATION_REPORT_BYTES = 256 * 1024 * 1024;
20
+ const ANALYSIS_ID_RE = /^[0-9a-f]{64}$/;
21
+ const FINDING_ID_RE = /^[0-9a-f]{16}$/;
22
+
23
+ /**
24
+ * Load and validate an organization JSON report from inside the working
25
+ * directory, with a bounded read and real-path escape protection.
26
+ */
27
+ export async function loadOrganizationReport({ path, cwd = process.cwd() }) {
28
+ const resolvedPath = await resolveRepositoryFile(path, cwd);
29
+ const metadata = await stat(resolvedPath);
30
+ if (!metadata.isFile()) throw new Error('previous organization report must be a file');
31
+ if (metadata.size > MAX_ORGANIZATION_REPORT_BYTES) {
32
+ throw new Error(
33
+ `previous organization report exceeds ${MAX_ORGANIZATION_REPORT_BYTES} bytes`,
34
+ );
35
+ }
36
+ let report;
37
+ try {
38
+ report = JSON.parse(await readFile(resolvedPath, 'utf8'));
39
+ } catch (error) {
40
+ if (error instanceof SyntaxError) {
41
+ throw new Error('previous organization report is not valid JSON');
42
+ }
43
+ throw error;
44
+ }
45
+ return validateOrganizationReport(report, 'previous');
46
+ }
47
+
48
+ /**
49
+ * Compare two validated organization reports by semantic finding fingerprint.
50
+ * Returned arrays are deterministically ordered and retain complete finding
51
+ * evidence from the report where each classification originated.
52
+ */
53
+ export function compareOrganizationReports({ previous, current }) {
54
+ const before = validateOrganizationReport(previous, 'previous');
55
+ const after = validateOrganizationReport(current, 'current');
56
+ if (before.organization.toLocaleLowerCase() !== after.organization.toLocaleLowerCase()) {
57
+ throw new Error('organization reports belong to different organizations');
58
+ }
59
+ if (
60
+ before.analysis.generation !== after.analysis.generation
61
+ || before.analysis.identity !== after.analysis.identity
62
+ ) {
63
+ throw new Error(
64
+ 'previous organization report does not match the current analysis scope and policy',
65
+ );
66
+ }
67
+
68
+ const previousRepositories = repositoryMap(before.repositories, 'previous');
69
+ const currentRepositories = repositoryMap(after.repositories, 'current');
70
+ const previousFindings = findingMap(before.findings, 'previous');
71
+ const currentFindings = findingMap(after.findings, 'current');
72
+ const newFindings = [];
73
+ const resolvedFindings = [];
74
+ const unchangedFindings = [];
75
+ const unknownFindings = [];
76
+
77
+ for (const [key, finding] of currentFindings) {
78
+ if (previousFindings.has(key)) {
79
+ unchangedFindings.push(finding);
80
+ previousFindings.delete(key);
81
+ } else {
82
+ newFindings.push(finding);
83
+ }
84
+ }
85
+ for (const finding of previousFindings.values()) {
86
+ const repository = currentRepositories.get(finding.repository.toLocaleLowerCase());
87
+ if (repository && repositoryCoverageComplete(repository, after.coverage)) resolvedFindings.push(finding);
88
+ else unknownFindings.push(finding);
89
+ }
90
+
91
+ const previousNames = [...previousRepositories.keys()];
92
+ const currentNames = [...currentRepositories.keys()];
93
+ const added = currentNames.filter(name => !previousRepositories.has(name)).sort();
94
+ const removed = previousNames.filter(name => !currentRepositories.has(name)).sort();
95
+ const failed = [...currentRepositories]
96
+ .filter(([, repository]) => !repositoryCoverageComplete(repository, after.coverage))
97
+ .map(([name]) => name)
98
+ .sort();
99
+ const comparable = currentNames.filter(name => (
100
+ previousRepositories.has(name)
101
+ && repositoryCoverageComplete(currentRepositories.get(name), after.coverage)
102
+ )).length;
103
+
104
+ newFindings.sort(compareFindings);
105
+ resolvedFindings.sort(compareFindings);
106
+ unchangedFindings.sort(compareFindings);
107
+ unknownFindings.sort(compareFindings);
108
+ const complete = after.coverage.complete === true
109
+ && removed.length === 0
110
+ && failed.length === 0
111
+ && after.errors.length === 0;
112
+
113
+ return {
114
+ schemaVersion: '1.0',
115
+ analysis: { ...after.analysis },
116
+ repositories: {
117
+ previous: previousRepositories.size,
118
+ current: currentRepositories.size,
119
+ comparable,
120
+ added,
121
+ removed,
122
+ failed,
123
+ },
124
+ findings: {
125
+ new: newFindings,
126
+ resolved: resolvedFindings,
127
+ unchanged: unchangedFindings,
128
+ unknown: unknownFindings,
129
+ },
130
+ summary: {
131
+ newFindings: newFindings.length,
132
+ resolvedFindings: resolvedFindings.length,
133
+ unchangedFindings: unchangedFindings.length,
134
+ unknownFindings: unknownFindings.length,
135
+ repositoriesComparable: comparable,
136
+ repositoriesAdded: added.length,
137
+ repositoriesRemoved: removed.length,
138
+ repositoriesFailed: failed.length,
139
+ complete,
140
+ },
141
+ };
142
+ }
143
+
144
+ function validateOrganizationReport(report, label) {
145
+ if (!isRecord(report) || report.schemaVersion !== '1.0') {
146
+ throw new Error(`${label} organization report schemaVersion must be "1.0"`);
147
+ }
148
+ if (typeof report.organization !== 'string' || !report.organization) {
149
+ throw new Error(`${label} organization report organization is invalid`);
150
+ }
151
+ if (
152
+ !isRecord(report.analysis)
153
+ || !Number.isSafeInteger(report.analysis.generation)
154
+ || report.analysis.generation < 1
155
+ || typeof report.analysis.identity !== 'string'
156
+ || !ANALYSIS_ID_RE.test(report.analysis.identity)
157
+ ) {
158
+ throw new Error(`${label} organization report analysis identity is invalid`);
159
+ }
160
+ if (!Array.isArray(report.repositories)) {
161
+ throw new Error(`${label} organization report repositories must be an array`);
162
+ }
163
+ if (!Array.isArray(report.findings)) {
164
+ throw new Error(`${label} organization report findings must be an array`);
165
+ }
166
+ if (!Array.isArray(report.errors)) {
167
+ throw new Error(`${label} organization report errors must be an array`);
168
+ }
169
+ if (!isRecord(report.summary)) {
170
+ throw new Error(`${label} organization report summary is invalid`);
171
+ }
172
+ if (!['OK', 'FAIL'].includes(report.status)) {
173
+ throw new Error(`${label} organization report status is invalid`);
174
+ }
175
+ validateScope(report.scope, label);
176
+ validateBaselineAndConfig(report, label);
177
+ const repositories = repositoryMap(report.repositories, label);
178
+ const findings = findingMap(report.findings, label);
179
+ for (const finding of findings.values()) {
180
+ if (!repositories.has(finding.repository.toLocaleLowerCase())) {
181
+ throw new Error(
182
+ `${label} organization report finding references an unknown repository`,
183
+ );
184
+ }
185
+ }
186
+ validateReportEvidence({ report, repositories, findings, label });
187
+ validateCoverage(report.coverage, label, repositories);
188
+ if (
189
+ !Number.isSafeInteger(report.summary.findings)
190
+ || report.summary.findings !== findings.size
191
+ ) {
192
+ throw new Error(`${label} organization report finding summary is inconsistent`);
193
+ }
194
+ // Status describes the selected repositories. Coverage separately records
195
+ // whether an intentional repository cap prevented a complete organization scan.
196
+ const expectedReportStatus = report.findings.length === 0 && report.errors.length === 0
197
+ ? 'OK'
198
+ : 'FAIL';
199
+ if (report.status !== expectedReportStatus) {
200
+ throw new Error(`${label} organization report status is inconsistent`);
201
+ }
202
+ return report;
203
+ }
204
+
205
+ function validateScope(scope, label) {
206
+ if (!isRecord(scope)) {
207
+ throw new Error(`${label} organization report scope is invalid`);
208
+ }
209
+ if (!Array.isArray(scope.repositories) || scope.repositories.some(r => typeof r !== 'string')) {
210
+ throw new Error(`${label} organization report scope repositories is invalid`);
211
+ }
212
+ if (!VISIBILITIES.has(scope.visibility)) {
213
+ throw new Error(`${label} organization report scope visibility is invalid`);
214
+ }
215
+ for (const flag of ['includeArchived', 'includeDisabled', 'includeForks']) {
216
+ if (typeof scope[flag] !== 'boolean') {
217
+ throw new Error(`${label} organization report scope ${flag} is invalid`);
218
+ }
219
+ }
220
+ if (
221
+ scope.maxRepositories !== null
222
+ && (!Number.isSafeInteger(scope.maxRepositories) || scope.maxRepositories <= 0)
223
+ ) {
224
+ throw new Error(`${label} organization report scope maxRepositories is invalid`);
225
+ }
226
+ if (scope.severity !== null && !SEVERITIES.has(scope.severity)) {
227
+ throw new Error(`${label} organization report scope severity is invalid`);
228
+ }
229
+ if (scope.explain !== undefined && typeof scope.explain !== 'boolean') {
230
+ throw new Error(`${label} organization report scope explain is invalid`);
231
+ }
232
+ if (
233
+ scope.concurrency !== undefined
234
+ && (!Number.isSafeInteger(scope.concurrency) || scope.concurrency <= 0)
235
+ ) {
236
+ throw new Error(`${label} organization report scope concurrency is invalid`);
237
+ }
238
+ }
239
+
240
+ function validateCoverage(coverage, label, repositories) {
241
+ if (!isRecord(coverage)) {
242
+ throw new Error(`${label} organization report coverage is invalid`);
243
+ }
244
+ for (const flag of [
245
+ 'complete',
246
+ 'enumerationComplete',
247
+ 'selectedRepositoriesComplete',
248
+ 'eligibleRepositoriesComplete',
249
+ 'limitedByMaxRepositories',
250
+ ]) {
251
+ if (typeof coverage[flag] !== 'boolean') {
252
+ throw new Error(`${label} organization report coverage ${flag} is invalid`);
253
+ }
254
+ }
255
+ if (
256
+ !Number.isSafeInteger(coverage.repositoriesOmittedByLimit)
257
+ || coverage.repositoriesOmittedByLimit < 0
258
+ ) {
259
+ throw new Error(`${label} organization report coverage repositoriesOmittedByLimit is invalid`);
260
+ }
261
+ if (
262
+ !Array.isArray(coverage.incompleteRepositories)
263
+ || coverage.incompleteRepositories.some(r => typeof r !== 'string')
264
+ ) {
265
+ throw new Error(`${label} organization report coverage incompleteRepositories is invalid`);
266
+ }
267
+ const incompleteSet = new Set(coverage.incompleteRepositories.map(r => r.toLowerCase()));
268
+ for (const repoName of incompleteSet) {
269
+ if (!repositories.has(repoName)) {
270
+ throw new Error(`${label} organization report coverage references unknown incomplete repository ${repoName}`);
271
+ }
272
+ }
273
+ for (const [name, repo] of repositories) {
274
+ const hasFailure = repo.errors.length > 0 || repo.findings.some(f => f?.ruleId === 'parse-error');
275
+ if (hasFailure && !incompleteSet.has(name)) {
276
+ throw new Error(`${label} organization report coverage is inconsistent: failed repository ${repo.repository?.fullName} not marked incomplete`);
277
+ }
278
+ if (!hasFailure && incompleteSet.has(name)) {
279
+ throw new Error(`${label} organization report coverage is inconsistent: error-free repository ${repo.repository?.fullName} marked incomplete`);
280
+ }
281
+ }
282
+ if (coverage.selectedRepositoriesComplete !== (incompleteSet.size === 0)) {
283
+ throw new Error(`${label} organization report coverage selectedRepositoriesComplete is inconsistent`);
284
+ }
285
+ if (coverage.complete !== (incompleteSet.size === 0 && !coverage.limitedByMaxRepositories && coverage.enumerationComplete && coverage.selectedRepositoriesComplete && coverage.eligibleRepositoriesComplete)) {
286
+ throw new Error(`${label} organization report coverage complete is inconsistent`);
287
+ }
288
+ }
289
+
290
+ function validateBaselineAndConfig(report, label) {
291
+ if (!isRecord(report.baseline)) {
292
+ throw new Error(`${label} organization report baseline is invalid`);
293
+ }
294
+ if (report.baseline.path !== null && typeof report.baseline.path !== 'string') {
295
+ throw new Error(`${label} organization report baseline path is invalid`);
296
+ }
297
+ if (!Number.isSafeInteger(report.baseline.suppressed) || report.baseline.suppressed < 0) {
298
+ throw new Error(`${label} organization report baseline suppressed is invalid`);
299
+ }
300
+ if (report.configPath !== null && typeof report.configPath !== 'string') {
301
+ throw new Error(`${label} organization report configPath is invalid`);
302
+ }
303
+ }
304
+
305
+ function repositoryMap(repositories, label) {
306
+ const mapped = new Map();
307
+ for (const result of repositories) {
308
+ if (!isRecord(result)) {
309
+ throw new Error(`${label} organization report contains an invalid repository result`);
310
+ }
311
+ const repoInfo = result.repository;
312
+ if (!isRecord(repoInfo) || typeof repoInfo.fullName !== 'string') {
313
+ throw new Error(`${label} organization report contains an invalid repository result`);
314
+ }
315
+ const name = repoInfo.fullName;
316
+ const parts = name.split('/');
317
+ if (
318
+ parts.length !== 2
319
+ || parts.some(part => !NAME_RE.test(part) || part === '.' || part === '..')
320
+ || !Array.isArray(result.errors)
321
+ || !Array.isArray(result.findings)
322
+ || !Array.isArray(result.files)
323
+ || !isRecord(result.summary)
324
+ || !['OK', 'FAIL'].includes(result.status)
325
+ ) {
326
+ throw new Error(`${label} organization report contains an invalid repository result`);
327
+ }
328
+ if (
329
+ !Number.isSafeInteger(result.summary.findings)
330
+ || result.summary.findings !== result.findings.length
331
+ ) {
332
+ throw new Error(`${label} organization report repository summary is inconsistent for ${name}`);
333
+ }
334
+ const expectedStatus = (result.findings.length === 0 && result.errors.length === 0) ? 'OK' : 'FAIL';
335
+ if (result.status !== expectedStatus) {
336
+ throw new Error(`${label} organization report repository status is inconsistent for ${name}`);
337
+ }
338
+ const key = name.toLocaleLowerCase();
339
+ if (mapped.has(key)) {
340
+ throw new Error(`${label} organization report contains duplicate repository ${name}`);
341
+ }
342
+ mapped.set(key, result);
343
+ }
344
+ return mapped;
345
+ }
346
+
347
+ /**
348
+ * Validate that the flattened evidence is an exact, order-independent copy of
349
+ * the evidence owned by each repository result. Counts alone are insufficient:
350
+ * a report could otherwise replace one finding or error with unrelated data.
351
+ */
352
+ function validateReportEvidence({ report, repositories, findings, label }) {
353
+ const nestedFindings = new Map();
354
+ const nestedErrors = [];
355
+
356
+ for (const [repositoryKey, result] of repositories) {
357
+ const repositoryName = result.repository.fullName;
358
+ const repositoryFindings = findingMap(
359
+ result.findings,
360
+ label,
361
+ ` repository ${repositoryName}`,
362
+ );
363
+ for (const [key, finding] of repositoryFindings) {
364
+ if (finding.repository.toLocaleLowerCase() !== repositoryKey) {
365
+ throw new Error(
366
+ `${label} organization report repository ${repositoryName} contains a finding for another repository`,
367
+ );
368
+ }
369
+ if (nestedFindings.has(key)) {
370
+ throw new Error(`${label} organization report contains duplicate finding identity`);
371
+ }
372
+ nestedFindings.set(key, finding);
373
+ }
374
+ for (const error of result.errors) {
375
+ nestedErrors.push(validateReportError(error, {
376
+ label,
377
+ expectedRepository: repositoryName,
378
+ }));
379
+ }
380
+ }
381
+
382
+ if (!sameRecordMap(findings, nestedFindings)) {
383
+ throw new Error(`${label} organization report findings are inconsistent with repository results`);
384
+ }
385
+
386
+ const flattenedErrors = report.errors.map(error => {
387
+ const validated = validateReportError(error, { label });
388
+ if (!repositories.has(validated.repository.toLocaleLowerCase())) {
389
+ throw new Error(
390
+ `${label} organization report error references an unknown repository`,
391
+ );
392
+ }
393
+ return validated;
394
+ });
395
+ if (!sameRecordMultiset(flattenedErrors, nestedErrors)) {
396
+ throw new Error(`${label} organization report errors are inconsistent with repository results`);
397
+ }
398
+ }
399
+
400
+ function validateReportError(error, { label, expectedRepository } = {}) {
401
+ if (
402
+ !isRecord(error)
403
+ || !isJsonValue(error)
404
+ || typeof error.repository !== 'string'
405
+ || !error.repository
406
+ || typeof error.error !== 'string'
407
+ || (error.path !== undefined && typeof error.path !== 'string')
408
+ ) {
409
+ throw new Error(`${label} organization report contains an invalid error`);
410
+ }
411
+ if (
412
+ expectedRepository !== undefined
413
+ && error.repository.toLocaleLowerCase() !== expectedRepository.toLocaleLowerCase()
414
+ ) {
415
+ throw new Error(
416
+ `${label} organization report repository ${expectedRepository} contains an error for another repository`,
417
+ );
418
+ }
419
+ return error;
420
+ }
421
+
422
+ function sameRecordMap(left, right) {
423
+ if (left.size !== right.size) return false;
424
+ for (const [key, value] of left) {
425
+ if (!right.has(key) || stableJson(value) !== stableJson(right.get(key))) return false;
426
+ }
427
+ return true;
428
+ }
429
+
430
+ function sameRecordMultiset(left, right) {
431
+ if (left.length !== right.length) return false;
432
+ const counts = new Map();
433
+ for (const value of left) {
434
+ const key = stableJson(value);
435
+ counts.set(key, (counts.get(key) ?? 0) + 1);
436
+ }
437
+ for (const value of right) {
438
+ const key = stableJson(value);
439
+ const count = counts.get(key) ?? 0;
440
+ if (count === 0) return false;
441
+ if (count === 1) counts.delete(key);
442
+ else counts.set(key, count - 1);
443
+ }
444
+ return counts.size === 0;
445
+ }
446
+
447
+ function stableJson(value) {
448
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
449
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;
450
+ return `{${Object.keys(value)
451
+ .sort()
452
+ .map(key => `${JSON.stringify(key)}:${stableJson(value[key])}`)
453
+ .join(',')}}`;
454
+ }
455
+
456
+ function repositoryCoverageComplete(repository, coverage) {
457
+ const incompleteSet = new Set(
458
+ (coverage?.incompleteRepositories ?? []).map(name => name.toLowerCase()),
459
+ );
460
+ return repository.errors.length === 0
461
+ && !repository.findings.some(finding => finding?.ruleId === 'parse-error')
462
+ && !incompleteSet.has(repository.repository.fullName.toLowerCase());
463
+ }
464
+
465
+ function findingMap(findings, label, context = '') {
466
+ const mapped = new Map();
467
+ for (const finding of findings) {
468
+ if (
469
+ !isRecord(finding)
470
+ || !isJsonValue(finding)
471
+ || typeof finding.repository !== 'string'
472
+ || typeof finding.id !== 'string'
473
+ || !FINDING_ID_RE.test(finding.id)
474
+ || (finding.fingerprint !== undefined
475
+ && (typeof finding.fingerprint !== 'string'
476
+ || !FINDING_ID_RE.test(finding.fingerprint)))
477
+ || typeof finding.ruleId !== 'string'
478
+ || !finding.ruleId
479
+ || !SEVERITIES.has(finding.severity)
480
+ || typeof finding.file !== 'string'
481
+ || !Number.isSafeInteger(finding.line)
482
+ || (finding.fields !== undefined
483
+ && (!isRecord(finding.fields) || !isJsonValue(finding.fields)))
484
+ ) {
485
+ throw new Error(`${label} organization report${context} contains an invalid finding`);
486
+ }
487
+ const identity = finding.fingerprint ?? finding.id;
488
+ const key = `${finding.repository.toLocaleLowerCase()}\0${identity}`;
489
+ if (mapped.has(key)) {
490
+ throw new Error(
491
+ `${label} organization report${context} contains duplicate finding identity`,
492
+ );
493
+ }
494
+ mapped.set(key, finding);
495
+ }
496
+ return mapped;
497
+ }
498
+
499
+ function compareFindings(left, right) {
500
+ return left.repository.localeCompare(right.repository)
501
+ || left.file.localeCompare(right.file)
502
+ || left.line - right.line
503
+ || left.ruleId.localeCompare(right.ruleId)
504
+ || left.id.localeCompare(right.id);
505
+ }