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,656 @@
1
+ /**
2
+ * Bounded, redacted GitHub Actions job summaries and numeric output metrics.
3
+ *
4
+ * Command payloads can contain attacker-controlled workflow and GitHub API
5
+ * data. Keep that data in plain escaped table cells; never turn it into links
6
+ * or copy the complete serialized report into the job summary.
7
+ */
8
+
9
+ import { isAbsolute, resolve } from 'node:path';
10
+ import { canonicalPath } from './identity.js';
11
+ import { SEVERITY_LEVELS } from './org-schema.js';
12
+ import { redact } from './redact.js';
13
+ import { listRules } from '../rules/index.js';
14
+
15
+ const SEVERITIES_DESCENDING = [...SEVERITY_LEVELS].reverse();
16
+ const SEVERITY_ORDER = new Map(
17
+ SEVERITIES_DESCENDING.map((severity, index) => [severity, index]),
18
+ );
19
+ const MAX_ROWS_PER_SECTION = 10;
20
+ const MAX_CELL_LENGTH = 240;
21
+
22
+ /** Hard ceiling for Markdown written to the GitHub Actions job summary. */
23
+ export const MAX_ACTION_SUMMARY_LENGTH = 32_000;
24
+
25
+ const RULE_DESCRIPTIONS = new Map([
26
+ ...listRules().map(rule => [rule.id, rule.description]),
27
+ ['parse-error', 'Fix the workflow YAML syntax before relying on the scan result.'],
28
+ ]);
29
+
30
+ /**
31
+ * GitHub Action output names and their corresponding metric object keys.
32
+ * Every numeric output is written for every command, using zero when it does
33
+ * not apply, so downstream expressions do not need command-specific guards.
34
+ */
35
+ export const ACTION_NUMERIC_OUTPUTS = Object.freeze([
36
+ ['findings', 'findings'],
37
+ ['total-findings', 'totalFindings'],
38
+ ['critical', 'critical'],
39
+ ['high', 'high'],
40
+ ['medium', 'medium'],
41
+ ['low', 'low'],
42
+ ['suppressed', 'suppressed'],
43
+ ['errors', 'errors'],
44
+ ['repositories-discovered', 'repositoriesDiscovered'],
45
+ ['repositories-selected', 'repositoriesSelected'],
46
+ ['repositories-scanned', 'repositoriesScanned'],
47
+ ['repositories-resumed', 'repositoriesResumed'],
48
+ ['repositories-failed', 'repositoriesFailed'],
49
+ ['new-findings', 'newFindings'],
50
+ ['resolved-findings', 'resolvedFindings'],
51
+ ['unchanged-findings', 'unchangedFindings'],
52
+ ['unknown-findings', 'unknownFindings'],
53
+ ]);
54
+
55
+ /** Return the complete, zero-filled shape used for stable numeric outputs. */
56
+ export function emptyActionMetrics({ errors = 0 } = {}) {
57
+ return {
58
+ findings: 0,
59
+ totalFindings: 0,
60
+ critical: 0,
61
+ high: 0,
62
+ medium: 0,
63
+ low: 0,
64
+ suppressed: 0,
65
+ errors: count(errors),
66
+ repositoriesDiscovered: 0,
67
+ repositoriesSelected: 0,
68
+ repositoriesScanned: 0,
69
+ repositoriesResumed: 0,
70
+ repositoriesFailed: 0,
71
+ newFindings: 0,
72
+ resolvedFindings: 0,
73
+ unchangedFindings: 0,
74
+ unknownFindings: 0,
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Derive stable numeric Action outputs without changing any command result or
80
+ * serialized JSON/SARIF contract.
81
+ */
82
+ export function collectActionMetrics({ command, result, repositoriesReused = 0 }) {
83
+ const findings = findingsFor(command, result);
84
+ const summary = findingSummaryFor(command, result);
85
+ const severityCounts = summarizeSeverities(findings);
86
+ const suppressed = count(summary?.suppressed);
87
+ const activeFindings = count(summary?.findings, findings.length);
88
+ const metrics = {
89
+ ...emptyActionMetrics(),
90
+ findings: activeFindings,
91
+ totalFindings: count(summary?.totalFindings, activeFindings + suppressed),
92
+ critical: count(summary?.critical, severityCounts.critical),
93
+ high: count(summary?.high, severityCounts.high),
94
+ medium: count(summary?.medium, severityCounts.medium),
95
+ low: count(summary?.low, severityCounts.low),
96
+ suppressed,
97
+ errors: operationalErrorsFor(command, result).length,
98
+ };
99
+
100
+ if (command === 'org-scan') {
101
+ metrics.repositoriesDiscovered = count(summary?.repositoriesDiscovered);
102
+ metrics.repositoriesSelected = count(summary?.repositoriesSelected);
103
+ metrics.repositoriesScanned = count(summary?.repositoriesScanned);
104
+ metrics.repositoriesResumed = count(repositoriesReused);
105
+ metrics.repositoriesFailed = count(summary?.repositoriesFailed);
106
+ metrics.newFindings = count(result?.comparison?.summary?.newFindings);
107
+ metrics.resolvedFindings = count(result?.comparison?.summary?.resolvedFindings);
108
+ metrics.unchangedFindings = count(result?.comparison?.summary?.unchangedFindings);
109
+ metrics.unknownFindings = count(result?.comparison?.summary?.unknownFindings);
110
+ }
111
+ return metrics;
112
+ }
113
+
114
+ /**
115
+ * Render a concise GitHub-flavored Markdown job summary.
116
+ */
117
+ export function renderActionSummary({
118
+ command,
119
+ result,
120
+ cwd = process.cwd(),
121
+ metrics = collectActionMetrics({ command, result }),
122
+ annotations = 0,
123
+ annotationsSkipped = 0,
124
+ reportPath = '',
125
+ checkpointPath = '',
126
+ checkpointResumed = false,
127
+ repositoriesReused = metrics.repositoriesResumed,
128
+ write = false,
129
+ }) {
130
+ const sections = [
131
+ `### actions-warden (${markdownText(command, 64)})`,
132
+ renderTable(
133
+ ['Result', 'Value'],
134
+ overviewRows({
135
+ command,
136
+ result,
137
+ cwd,
138
+ metrics,
139
+ annotations,
140
+ annotationsSkipped,
141
+ reportPath,
142
+ checkpointPath,
143
+ checkpointResumed,
144
+ repositoriesReused,
145
+ write,
146
+ }),
147
+ new Set([1]),
148
+ ),
149
+ ];
150
+
151
+ const findings = findingsFor(command, result);
152
+ if (findingSummaryFor(command, result)) {
153
+ sections.push(renderSeveritySection(metrics));
154
+ }
155
+ if (command === 'org-scan') {
156
+ sections.push(renderOrganizationCoverage(result.summary, result.coverage));
157
+ if (result.comparison) sections.push(renderComparison(result.comparison));
158
+ }
159
+ if (findings.length > 0) {
160
+ sections.push(renderRuleBreakdown(findings));
161
+ sections.push(renderFindingDetails({ command, result, findings, cwd }));
162
+ }
163
+
164
+ const changes = changesFor(command, result);
165
+ if (changes.length > 0) {
166
+ sections.push(renderChanges(changes, cwd, write && command !== 'report'));
167
+ }
168
+
169
+ const skipped = skippedFor(command, result);
170
+ if (skipped.length > 0) sections.push(renderSkipped(skipped, cwd));
171
+
172
+ const warnings = command === 'verify' ? array(result?.warnings) : [];
173
+ if (warnings.length > 0) sections.push(renderWarnings(warnings, cwd));
174
+
175
+ const errors = operationalErrorsFor(command, result);
176
+ if (errors.length > 0) sections.push(renderErrors(errors, cwd));
177
+
178
+ return boundSummary(`${sections.filter(Boolean).join('\n\n')}\n`);
179
+ }
180
+
181
+ /**
182
+ * Render an invocation-level failure when no normal command result exists.
183
+ */
184
+ export function renderActionFailureSummary({
185
+ command,
186
+ message,
187
+ annotations = 0,
188
+ }) {
189
+ const summary = [
190
+ `### actions-warden (${markdownText(command, 64)})`,
191
+ renderTable(['Result', 'Value'], [
192
+ ['Status', 'FAIL'],
193
+ ['Operational errors', 1],
194
+ ['Annotations', `${count(annotations)} emitted`],
195
+ ], new Set([1])),
196
+ '#### Invocation error',
197
+ markdownText(message || 'actions-warden could not complete the requested command.', 2_000),
198
+ ].join('\n\n');
199
+ return boundSummary(`${summary}\n`);
200
+ }
201
+
202
+ function overviewRows({
203
+ command,
204
+ result,
205
+ cwd,
206
+ metrics,
207
+ annotations,
208
+ annotationsSkipped,
209
+ reportPath,
210
+ checkpointPath,
211
+ checkpointResumed,
212
+ repositoriesReused,
213
+ write,
214
+ }) {
215
+ const rows = [['Status', result?.status ?? 'UNKNOWN']];
216
+ const summary = findingSummaryFor(command, result);
217
+
218
+ if (summary) {
219
+ rows.push(
220
+ ['Files scanned', count(summary.files)],
221
+ ['Active findings', metrics.findings],
222
+ ['Total findings before baseline', metrics.totalFindings],
223
+ ['Suppressed by baseline', metrics.suppressed],
224
+ ['Operational errors', metrics.errors],
225
+ );
226
+ } else if (command === 'pin') {
227
+ rows.push(
228
+ [write ? 'Changes applied' : 'Changes planned', array(result?.changes).length],
229
+ ['Operational errors', metrics.errors],
230
+ );
231
+ } else if (command === 'upgrade') {
232
+ rows.push(
233
+ [write ? 'Changes applied' : 'Changes planned', array(result?.changes).length],
234
+ ['Upgrades skipped', array(result?.skipped).length],
235
+ ['Operational errors', metrics.errors],
236
+ );
237
+ } else if (command === 'verify') {
238
+ rows.push(
239
+ ['Files scanned', array(result?.files).length],
240
+ ['References verified', array(result?.checks).length],
241
+ ['Warnings', array(result?.warnings).length],
242
+ ['Operational errors', metrics.errors],
243
+ );
244
+ } else if (command === 'rules') {
245
+ rows.push(['Rules listed', listRules().length]);
246
+ }
247
+
248
+ if (command === 'report') {
249
+ rows.push(
250
+ ['Pin changes planned', array(result?.pin?.changes).length],
251
+ ['Upgrade changes planned', array(result?.upgrade?.changes).length],
252
+ ['Upgrades skipped', array(result?.upgrade?.skipped).length],
253
+ );
254
+ }
255
+ if (command === 'org-scan') rows.splice(1, 0, ['Organization', result?.organization ?? '']);
256
+
257
+ rows.push([
258
+ 'Annotations',
259
+ `${count(annotations)} emitted; ${count(annotationsSkipped)} omitted`,
260
+ ]);
261
+ if (reportPath) rows.push(['Saved report', workspacePath(reportPath, cwd)]);
262
+ if (command === 'org-scan' && checkpointPath) {
263
+ rows.push(
264
+ ['Checkpoint', workspacePath(checkpointPath, cwd)],
265
+ ['Checkpoint resumed', checkpointResumed ? 'yes' : 'no'],
266
+ ['Repositories reused', count(repositoriesReused)],
267
+ );
268
+ }
269
+ return rows;
270
+ }
271
+
272
+ function renderSeveritySection(metrics) {
273
+ return [
274
+ '#### Severity breakdown',
275
+ renderTable(
276
+ ['Critical', 'High', 'Medium', 'Low'],
277
+ [[metrics.critical, metrics.high, metrics.medium, metrics.low]],
278
+ new Set([0, 1, 2, 3]),
279
+ ),
280
+ ].join('\n\n');
281
+ }
282
+
283
+ function renderOrganizationCoverage(summary = {}, coverage = {}) {
284
+ return [
285
+ '#### Repository coverage',
286
+ renderTable(['Coverage', 'Count'], [
287
+ ['Eligible coverage complete', coverage.complete === true ? 'yes' : 'no'],
288
+ ['Discovered', count(summary.repositoriesDiscovered)],
289
+ ['Eligible', count(summary.repositoriesEligible)],
290
+ ['Selected', count(summary.repositoriesSelected)],
291
+ ['Scanned', count(summary.repositoriesScanned)],
292
+ ['With workflows', count(summary.repositoriesWithWorkflows)],
293
+ ['With findings', count(summary.repositoriesWithFindings)],
294
+ ['Failed', count(summary.repositoriesFailed)],
295
+ ['Skipped by scope', count(summary.repositoriesSkipped)],
296
+ ['Omitted by repository limit', count(coverage.repositoriesOmittedByLimit)],
297
+ ['Incomplete repositories', array(coverage.incompleteRepositories).length],
298
+ ], new Set([1])),
299
+ ].join('\n\n');
300
+ }
301
+
302
+ function renderComparison(comparison) {
303
+ const summary = comparison?.summary ?? {};
304
+ return [
305
+ '#### Change since previous report',
306
+ renderTable(['Change', 'Count'], [
307
+ ['New findings', count(summary.newFindings)],
308
+ ['Resolved findings', count(summary.resolvedFindings)],
309
+ ['Unchanged findings', count(summary.unchangedFindings)],
310
+ ['Unknown resolution', count(summary.unknownFindings)],
311
+ ['Comparable repositories', count(summary.repositoriesComparable)],
312
+ ['Removed repositories', count(summary.repositoriesRemoved)],
313
+ ['Failed repositories', count(summary.repositoriesFailed)],
314
+ ['Comparison complete', summary.complete === true ? 'yes' : 'no'],
315
+ ], new Set([1])),
316
+ ].join('\n\n');
317
+ }
318
+
319
+ function renderRuleBreakdown(findings) {
320
+ const byRule = new Map();
321
+ for (const finding of findings) {
322
+ const ruleId = String(finding?.ruleId ?? 'unknown');
323
+ const severity = normalizeSeverity(finding?.severity);
324
+ const record = byRule.get(ruleId) ?? {
325
+ ruleId,
326
+ critical: 0,
327
+ high: 0,
328
+ medium: 0,
329
+ low: 0,
330
+ total: 0,
331
+ };
332
+ record[severity] += 1;
333
+ record.total += 1;
334
+ byRule.set(ruleId, record);
335
+ }
336
+ const records = [...byRule.values()].sort((left, right) => (
337
+ right.total - left.total || compareText(left.ruleId, right.ruleId)
338
+ ));
339
+ const visible = records.slice(0, MAX_ROWS_PER_SECTION);
340
+ const section = [
341
+ '#### Findings by rule',
342
+ renderTable(
343
+ ['Rule', 'Critical', 'High', 'Medium', 'Low', 'Total'],
344
+ visible.map(record => [
345
+ record.ruleId,
346
+ record.critical,
347
+ record.high,
348
+ record.medium,
349
+ record.low,
350
+ record.total,
351
+ ]),
352
+ new Set([1, 2, 3, 4, 5]),
353
+ ),
354
+ ];
355
+ if (records.length > visible.length) section.push(showingNote(visible.length, records.length, 'rules'));
356
+ return section.join('\n\n');
357
+ }
358
+
359
+ function renderFindingDetails({ command, result, findings, cwd }) {
360
+ const explanations = findingExplanations(command, result);
361
+ const sorted = [...findings].sort((left, right) => (
362
+ severityRank(left?.severity) - severityRank(right?.severity)
363
+ || compareText(location(left, cwd), location(right, cwd))
364
+ || count(left?.line) - count(right?.line)
365
+ || compareText(left?.ruleId, right?.ruleId)
366
+ || compareText(left?.id, right?.id)
367
+ ));
368
+ const visible = sorted.slice(0, MAX_ROWS_PER_SECTION);
369
+ const section = [
370
+ '#### Top findings',
371
+ renderTable(['Severity', 'Rule', 'Location', 'ID', 'Remediation'], visible.map(finding => [
372
+ normalizeSeverity(finding?.severity),
373
+ finding?.ruleId ?? 'unknown',
374
+ location(finding, cwd),
375
+ finding?.id ?? '',
376
+ finding?.explain
377
+ ?? explanations.get(finding?.id)
378
+ ?? RULE_DESCRIPTIONS.get(finding?.ruleId)
379
+ ?? 'Review the complete report evidence and update the workflow safely.',
380
+ ])),
381
+ ];
382
+ if (findings.length > visible.length) {
383
+ section.push(showingNote(visible.length, findings.length, 'findings'));
384
+ }
385
+ return section.join('\n\n');
386
+ }
387
+
388
+ function renderChanges(changes, cwd, applied) {
389
+ const sorted = [...changes].sort((left, right) => (
390
+ compareText(left.stage, right.stage)
391
+ || compareText(location(left.change, cwd), location(right.change, cwd))
392
+ || compareText(left.change?.action, right.change?.action)
393
+ || compareText(left.change?.id, right.change?.id)
394
+ ));
395
+ const visible = sorted.slice(0, MAX_ROWS_PER_SECTION);
396
+ const section = [
397
+ applied ? '#### Applied changes' : '#### Planned changes',
398
+ renderTable(['Stage', 'Action', 'From', 'To', 'Location', 'ID'], visible.map(({ stage, change }) => [
399
+ stage,
400
+ change?.action ?? '',
401
+ change?.fromVersion ?? change?.fromRef ?? '',
402
+ stage === 'pin' ? change?.toSha ?? '' : change?.toTag ?? change?.toSha ?? '',
403
+ location(change, cwd),
404
+ change?.id ?? '',
405
+ ])),
406
+ ];
407
+ if (changes.length > visible.length) {
408
+ section.push(showingNote(visible.length, changes.length, 'changes'));
409
+ }
410
+ return section.join('\n\n');
411
+ }
412
+
413
+ function renderSkipped(skipped, cwd) {
414
+ const sorted = [...skipped].sort((left, right) => (
415
+ compareText(location(left, cwd), location(right, cwd))
416
+ || compareText(left?.action, right?.action)
417
+ || compareText(left?.tag, right?.tag)
418
+ ));
419
+ const visible = sorted.slice(0, MAX_ROWS_PER_SECTION);
420
+ const section = [
421
+ '#### Skipped upgrades',
422
+ renderTable(['Action', 'Candidate', 'Reason', 'Age', 'Location'], visible.map(skip => [
423
+ skip?.action ?? '',
424
+ skip?.tag ?? '',
425
+ skip?.reason ?? '',
426
+ skip?.ageDays === undefined
427
+ ? skip?.ageSource ?? ''
428
+ : `${count(skip.ageDays)} days${skip?.ageSource ? ` (${skip.ageSource})` : ''}`,
429
+ location(skip, cwd),
430
+ ])),
431
+ ];
432
+ if (skipped.length > visible.length) {
433
+ section.push(showingNote(visible.length, skipped.length, 'skipped upgrades'));
434
+ }
435
+ return section.join('\n\n');
436
+ }
437
+
438
+ function renderWarnings(warnings, cwd) {
439
+ const sorted = [...warnings].sort(compareDiagnostics(cwd));
440
+ const visible = sorted.slice(0, MAX_ROWS_PER_SECTION);
441
+ const section = [
442
+ '#### Verification warnings',
443
+ renderTable(['Location', 'Action', 'Warning', 'ID'], visible.map(warning => [
444
+ location(warning, cwd),
445
+ warning?.action ?? '',
446
+ warning?.warning ?? 'Verification warning.',
447
+ warning?.id ?? '',
448
+ ])),
449
+ ];
450
+ if (warnings.length > visible.length) {
451
+ section.push(showingNote(visible.length, warnings.length, 'warnings'));
452
+ }
453
+ return section.join('\n\n');
454
+ }
455
+
456
+ function renderErrors(errors, cwd) {
457
+ const sorted = [...errors].sort((left, right) => (
458
+ compareText(left.stage, right.stage)
459
+ || compareDiagnostics(cwd)(left.error, right.error)
460
+ ));
461
+ const visible = sorted.slice(0, MAX_ROWS_PER_SECTION);
462
+ const section = [
463
+ '#### Operational errors',
464
+ renderTable(['Stage', 'Location', 'Subject', 'Error'], visible.map(({ stage, error }) => [
465
+ stage,
466
+ location(error, cwd),
467
+ error?.action ?? error?.repository ?? '',
468
+ error?.error ?? 'actions-warden reported an operational error.',
469
+ ])),
470
+ ];
471
+ if (errors.length > visible.length) {
472
+ section.push(showingNote(visible.length, errors.length, 'errors'));
473
+ }
474
+ return section.join('\n\n');
475
+ }
476
+
477
+ function findingsFor(command, result) {
478
+ if (command === 'audit' || command === 'org-scan') return array(result?.findings);
479
+ if (command === 'report') return array(result?.audit?.findings);
480
+ return [];
481
+ }
482
+
483
+ function findingSummaryFor(command, result) {
484
+ if (command === 'audit' || command === 'org-scan') return result?.summary;
485
+ if (command === 'report') return result?.audit?.summary;
486
+ return undefined;
487
+ }
488
+
489
+ function findingExplanations(command, result) {
490
+ const auditResult = command === 'report' ? result?.audit : command === 'audit' ? result : undefined;
491
+ return new Map(array(auditResult?.allFindings)
492
+ .filter(finding => finding?.id && finding?.explain)
493
+ .map(finding => [finding.id, finding.explain]));
494
+ }
495
+
496
+ function changesFor(command, result) {
497
+ if (command === 'pin' || command === 'upgrade') {
498
+ return array(result?.changes).map(change => ({ stage: command, change }));
499
+ }
500
+ if (command === 'report') {
501
+ return [
502
+ ...array(result?.pin?.changes).map(change => ({ stage: 'pin', change })),
503
+ ...array(result?.upgrade?.changes).map(change => ({ stage: 'upgrade', change })),
504
+ ];
505
+ }
506
+ return [];
507
+ }
508
+
509
+ function skippedFor(command, result) {
510
+ if (command === 'upgrade') return array(result?.skipped);
511
+ if (command === 'report') return array(result?.upgrade?.skipped);
512
+ return [];
513
+ }
514
+
515
+ function operationalErrorsFor(command, result) {
516
+ const errors = [];
517
+ const explanations = findingExplanations(command, result);
518
+ for (const finding of findingsFor(command, result)) {
519
+ if (finding?.ruleId !== 'parse-error') continue;
520
+ errors.push({
521
+ stage: 'parse',
522
+ error: {
523
+ ...finding,
524
+ error: finding.explain
525
+ ?? explanations.get(finding.id)
526
+ ?? 'Workflow YAML could not be parsed.',
527
+ },
528
+ });
529
+ }
530
+
531
+ if (command === 'pin' || command === 'upgrade' || command === 'verify') {
532
+ errors.push(...array(result?.errors).map(error => ({ stage: command, error })));
533
+ } else if (command === 'report') {
534
+ errors.push(
535
+ ...array(result?.pin?.errors).map(error => ({ stage: 'pin', error })),
536
+ ...array(result?.upgrade?.errors).map(error => ({ stage: 'upgrade', error })),
537
+ );
538
+ } else if (command === 'org-scan') {
539
+ errors.push(...array(result?.errors).map(error => ({ stage: 'org-scan', error })));
540
+ }
541
+ return errors;
542
+ }
543
+
544
+ function summarizeSeverities(findings) {
545
+ const summary = { critical: 0, high: 0, medium: 0, low: 0 };
546
+ for (const finding of findings) summary[normalizeSeverity(finding?.severity)] += 1;
547
+ return summary;
548
+ }
549
+
550
+ function location(diagnostic, cwd) {
551
+ let value = '';
552
+ if (typeof diagnostic?.file === 'string' && diagnostic.file) {
553
+ value = workspacePath(diagnostic.file, cwd);
554
+ } else if (typeof diagnostic?.path === 'string' && diagnostic.path) {
555
+ value = diagnostic?.repository
556
+ ? `${diagnostic.repository}/${diagnostic.path}`
557
+ : diagnostic.path;
558
+ } else if (typeof diagnostic?.repository === 'string') {
559
+ value = diagnostic.repository;
560
+ }
561
+ const line = positiveInteger(diagnostic?.line);
562
+ return `${value || '—'}${line ? `:${line}` : ''}`;
563
+ }
564
+
565
+ function workspacePath(file, cwd) {
566
+ if (typeof file !== 'string' || !file || file.includes('\0')) return '—';
567
+ try {
568
+ const absolute = isAbsolute(file) ? file : resolve(cwd, file);
569
+ const relative = canonicalPath(absolute, resolve(cwd));
570
+ if (relative === '') return '.';
571
+ if (relative === '..' || relative.startsWith('../')) return '(outside working directory)';
572
+ return relative;
573
+ } catch {
574
+ return '(invalid path)';
575
+ }
576
+ }
577
+
578
+ function compareDiagnostics(cwd) {
579
+ return (left, right) => (
580
+ compareText(location(left, cwd), location(right, cwd))
581
+ || count(left?.line) - count(right?.line)
582
+ || compareText(left?.action, right?.action)
583
+ || compareText(left?.id, right?.id)
584
+ || compareText(left?.error ?? left?.warning, right?.error ?? right?.warning)
585
+ );
586
+ }
587
+
588
+ function renderTable(headers, rows, numericColumns = new Set()) {
589
+ const renderedHeaders = headers.map(header => markdownText(header, 80));
590
+ const separator = headers.map((_, index) => numericColumns.has(index) ? '---:' : '---');
591
+ return [
592
+ `| ${renderedHeaders.join(' | ')} |`,
593
+ `| ${separator.join(' | ')} |`,
594
+ ...rows.map(row => (
595
+ `| ${headers.map((_, index) => markdownText(row[index] ?? '', MAX_CELL_LENGTH)).join(' | ')} |`
596
+ )),
597
+ ].join('\n');
598
+ }
599
+
600
+ function markdownText(value, maxLength = MAX_CELL_LENGTH) {
601
+ const withoutControls = [...redact(value)].map(character => {
602
+ const codePoint = character.codePointAt(0);
603
+ return codePoint <= 0x1f || codePoint === 0x7f ? ' ' : character;
604
+ }).join('');
605
+ const normalized = withoutControls
606
+ .replace(/\s+/g, ' ')
607
+ .trim();
608
+ const truncated = truncate(normalized, maxLength);
609
+ return truncated
610
+ .replaceAll('&', '&amp;')
611
+ .replaceAll('<', '&lt;')
612
+ .replaceAll('>', '&gt;')
613
+ .replace(/[\\`*_[\]#|]/g, character => `&#${character.codePointAt(0)};`);
614
+ }
615
+
616
+ function showingNote(visible, total, label) {
617
+ return `_Showing ${visible} of ${total} ${label}; all records remain in the command output and any saved report._`;
618
+ }
619
+
620
+ function boundSummary(summary) {
621
+ if (summary.length <= MAX_ACTION_SUMMARY_LENGTH) return summary;
622
+ const marker = '\n\n_Summary truncated; use the complete command output or saved report._\n';
623
+ return `${summary.slice(0, MAX_ACTION_SUMMARY_LENGTH - marker.length).trimEnd()}${marker}`;
624
+ }
625
+
626
+ function normalizeSeverity(value) {
627
+ return SEVERITY_ORDER.has(value) ? value : 'low';
628
+ }
629
+
630
+ function severityRank(value) {
631
+ return SEVERITY_ORDER.get(value) ?? SEVERITIES_DESCENDING.length;
632
+ }
633
+
634
+ function array(value) {
635
+ return Array.isArray(value) ? value : [];
636
+ }
637
+
638
+ function count(value, fallback = 0) {
639
+ return Number.isSafeInteger(value) && value >= 0 ? value : fallback;
640
+ }
641
+
642
+ function positiveInteger(value) {
643
+ const number = Number(value);
644
+ return Number.isSafeInteger(number) && number > 0 ? number : undefined;
645
+ }
646
+
647
+ function compareText(left, right) {
648
+ const a = String(left ?? '');
649
+ const b = String(right ?? '');
650
+ return a < b ? -1 : a > b ? 1 : 0;
651
+ }
652
+
653
+ function truncate(value, maxLength) {
654
+ if (value.length <= maxLength) return value;
655
+ return `${value.slice(0, Math.max(0, maxLength - 1))}…`;
656
+ }
@@ -7,6 +7,7 @@
7
7
 
8
8
  import { isAbsolute, relative, resolve, sep } from 'node:path';
9
9
  import { listRules } from '../rules/index.js';
10
+ import { SEVERITY_LEVELS } from './org-schema.js';
10
11
  import { redact } from './redact.js';
11
12
 
12
13
  const LEVEL_ORDER = new Map([
@@ -14,12 +15,9 @@ const LEVEL_ORDER = new Map([
14
15
  ['warning', 1],
15
16
  ['notice', 2],
16
17
  ]);
17
- const SEVERITY_ORDER = new Map([
18
- ['critical', 0],
19
- ['high', 1],
20
- ['medium', 2],
21
- ['low', 3],
22
- ]);
18
+ const SEVERITY_ORDER = new Map(
19
+ [...SEVERITY_LEVELS].reverse().map((severity, index) => [severity, index]),
20
+ );
23
21
  const RULE_DESCRIPTIONS = new Map(
24
22
  listRules().map(rule => [rule.id, rule.description]),
25
23
  );
@@ -3,7 +3,17 @@ import { canonicalPath, occurrenceId } from './identity.js';
3
3
  import { resolveRepositoryFile } from './config.js';
4
4
 
5
5
  /**
6
- * Load a versioned baseline and return its finding IDs.
6
+ * Create a baseline that suppresses nothing.
7
+ *
8
+ * @returns {{path: null, ids: Set<string>, fingerprints: Set<string>}}
9
+ */
10
+ export function emptyBaseline() {
11
+ return { path: null, ids: new Set(), fingerprints: new Set() };
12
+ }
13
+
14
+ /**
15
+ * Load a versioned baseline and return its finding IDs and semantic
16
+ * fingerprints.
7
17
  */
8
18
  export async function loadBaseline({ path, cwd = process.cwd() }) {
9
19
  const resolvedPath = await resolveRepositoryFile(path, cwd);