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
@@ -10,11 +10,11 @@ import semver from 'semver';
10
10
  import { createHash } from 'node:crypto';
11
11
  import { resolve } from 'node:path';
12
12
  import { readCache, readCacheEntry, writeCache } from './cache.js';
13
+ import { GIT_SHA_RE } from './org-schema.js';
13
14
  import { redact } from './redact.js';
14
15
 
15
16
  const API = 'https://api.github.com';
16
17
  const IN_FLIGHT = new Map();
17
- const COMMIT_SHA_RE = /^[0-9a-f]{40}$/i;
18
18
 
19
19
  /**
20
20
  * Resolve the API token. Precedence: explicit param > GITHUB_TOKEN > GH_TOKEN.
@@ -37,6 +37,7 @@ export function resolveToken(explicit) {
37
37
  * @param {string} [opts.cwd]
38
38
  * @param {boolean} [opts.useCache]
39
39
  * @param {(event: {attempt: number, maxRetries: number, reason: 'network'|'rate-limit'|'server-error', delayMs: number, status?: number}) => void|Promise<void>} [opts.onRetry]
40
+ * @param {(event: {status: number, rateLimit: object|null}) => void|Promise<void>} [opts.onResponse]
40
41
  * @returns {Promise<{status: number, body: unknown}>}
41
42
  */
42
43
  export function ghFetch(options) {
@@ -63,10 +64,14 @@ async function ghFetchInternal({
63
64
  cwd = process.cwd(),
64
65
  useCache = true,
65
66
  onRetry,
67
+ onResponse,
66
68
  }) {
67
69
  if (onRetry !== undefined && typeof onRetry !== 'function') {
68
70
  throw new Error('onRetry must be a function');
69
71
  }
72
+ if (onResponse !== undefined && typeof onResponse !== 'function') {
73
+ throw new Error('onResponse must be a function');
74
+ }
70
75
  const cacheKey = requestCacheKey(url, token);
71
76
  const cached = useCache
72
77
  ? await readCacheEntry({ key: cacheKey, cwd, allowExpired: true })
@@ -110,11 +115,28 @@ async function ghFetchInternal({
110
115
  etag: cached.etag,
111
116
  cwd,
112
117
  });
118
+ await notifyResponse(onResponse, response);
113
119
  return { status: 200, body: cached.value };
114
120
  }
115
- if ((response.status === 403 && remaining === '0') || response.status === 429) {
121
+ const retryAfterHeader = response.headers.get('retry-after');
122
+ const isRateLimit = (response.status === 403 && (remaining === '0' || retryAfterHeader !== null))
123
+ || response.status === 429;
124
+ if (isRateLimit) {
125
+ let retryAfterMs = 0;
126
+ if (retryAfterHeader) {
127
+ if (/^\d+$/.test(retryAfterHeader)) {
128
+ retryAfterMs = Number(retryAfterHeader) * 1000;
129
+ } else {
130
+ const parsedDate = Date.parse(retryAfterHeader);
131
+ if (Number.isFinite(parsedDate) && parsedDate > Date.now()) {
132
+ retryAfterMs = parsedDate - Date.now();
133
+ }
134
+ }
135
+ }
116
136
  const reset = Number(response.headers.get('x-ratelimit-reset') ?? 0) * 1000;
117
- const wait = Math.max(reset - Date.now(), backoff(attempt));
137
+ const wait = retryAfterMs > 0
138
+ ? retryAfterMs
139
+ : Math.max(reset - Date.now(), backoff(attempt));
118
140
  if (attempt >= retries) {
119
141
  const resetMessage = Number.isFinite(reset) && reset > Date.now()
120
142
  ? `; resets at ${new Date(reset).toISOString()}`
@@ -158,6 +180,7 @@ async function ghFetchInternal({
158
180
  cwd,
159
181
  });
160
182
  }
183
+ await notifyResponse(onResponse, response);
161
184
  return { status: response.status, body };
162
185
  }
163
186
  }
@@ -179,6 +202,40 @@ async function notifyRetry(onRetry, event) {
179
202
  if (onRetry) await onRetry(event);
180
203
  }
181
204
 
205
+ async function notifyResponse(onResponse, response) {
206
+ if (!onResponse) return;
207
+ const integerHeader = name => {
208
+ const value = response.headers.get(name);
209
+ if (value === null || !/^\d+$/.test(value)) return undefined;
210
+ const parsed = Number(value);
211
+ return Number.isSafeInteger(parsed) ? parsed : undefined;
212
+ };
213
+ const limit = integerHeader('x-ratelimit-limit');
214
+ const remaining = integerHeader('x-ratelimit-remaining');
215
+ const used = integerHeader('x-ratelimit-used');
216
+ const reset = integerHeader('x-ratelimit-reset');
217
+ const rawResource = response.headers.get('x-ratelimit-resource');
218
+ const resource = rawResource && /^[A-Za-z0-9_.-]{1,64}$/.test(rawResource)
219
+ ? rawResource
220
+ : undefined;
221
+ const resetDate = reset === undefined ? null : new Date(reset * 1000);
222
+ const resetAt = resetDate && !Number.isNaN(resetDate.getTime())
223
+ ? resetDate.toISOString()
224
+ : undefined;
225
+ const hasRateLimit = [limit, remaining, used, reset, resource]
226
+ .some(value => value !== undefined);
227
+ await onResponse({
228
+ status: response.status,
229
+ rateLimit: hasRateLimit ? {
230
+ ...(limit === undefined ? {} : { limit }),
231
+ ...(remaining === undefined ? {} : { remaining }),
232
+ ...(used === undefined ? {} : { used }),
233
+ ...(resetAt === undefined ? {} : { resetAt }),
234
+ ...(resource === undefined ? {} : { resource }),
235
+ } : null,
236
+ });
237
+ }
238
+
182
239
  /**
183
240
  * Resolve a ref (tag, branch, or commit-ish) to an immutable commit SHA.
184
241
  *
@@ -192,7 +249,7 @@ async function notifyRetry(onRetry, event) {
192
249
  */
193
250
  export async function resolveRefToSha({ owner, repo, ref, token, cwd }) {
194
251
  // Already a full SHA?
195
- if (COMMIT_SHA_RE.test(ref)) {
252
+ if (GIT_SHA_RE.test(ref)) {
196
253
  return { sha: ref.toLowerCase(), type: 'commit' };
197
254
  }
198
255
  // Try as tag.
@@ -200,7 +257,7 @@ export async function resolveRefToSha({ owner, repo, ref, token, cwd }) {
200
257
  const tagRes = await ghFetch({ url: tagUrl, token, cwd });
201
258
  if (tagRes.status === 200 && tagRes.body && typeof tagRes.body === 'object') {
202
259
  const obj = tagRes.body.object;
203
- if (obj && COMMIT_SHA_RE.test(String(obj.sha))) {
260
+ if (obj && GIT_SHA_RE.test(String(obj.sha))) {
204
261
  if (obj.type === 'tag') {
205
262
  const sha = await dereferenceTagToCommit({
206
263
  owner,
@@ -223,14 +280,14 @@ export async function resolveRefToSha({ owner, repo, ref, token, cwd }) {
223
280
  if (
224
281
  branchRes.status === 200
225
282
  && branchRes.body?.object?.type === 'commit'
226
- && COMMIT_SHA_RE.test(String(branchRes.body.object.sha))
283
+ && GIT_SHA_RE.test(String(branchRes.body.object.sha))
227
284
  ) {
228
285
  return { sha: String(branchRes.body.object.sha).toLowerCase(), type: 'branch' };
229
286
  }
230
287
  // Try as commit.
231
288
  const commitUrl = `${API}/repos/${owner}/${repo}/commits/${encodeURIComponent(ref)}`;
232
289
  const commitRes = await ghFetch({ url: commitUrl, token, cwd });
233
- if (commitRes.status === 200 && COMMIT_SHA_RE.test(String(commitRes.body?.sha))) {
290
+ if (commitRes.status === 200 && GIT_SHA_RE.test(String(commitRes.body?.sha))) {
234
291
  return { sha: String(commitRes.body.sha).toLowerCase(), type: 'commit' };
235
292
  }
236
293
  throw new Error(`could not resolve ${owner}/${repo}@${ref}`);
@@ -245,7 +302,7 @@ async function dereferenceTagToCommit({ owner, repo, sha, token, cwd }) {
245
302
  if (
246
303
  response.status !== 200
247
304
  || !target
248
- || !COMMIT_SHA_RE.test(String(target.sha))
305
+ || !GIT_SHA_RE.test(String(target.sha))
249
306
  ) {
250
307
  throw new Error(`could not dereference annotated tag ${owner}/${repo}@${sha}`);
251
308
  }
@@ -263,7 +320,7 @@ async function dereferenceTagToCommit({ owner, repo, sha, token, cwd }) {
263
320
  * commits API rather than merely looking like a SHA.
264
321
  */
265
322
  export async function verifyCommitInRepo({ owner, repo, sha, token, cwd }) {
266
- if (!COMMIT_SHA_RE.test(sha)) {
323
+ if (!GIT_SHA_RE.test(sha)) {
267
324
  throw new Error(`invalid commit SHA for ${owner}/${repo}`);
268
325
  }
269
326
  const url = `${API}/repos/${owner}/${repo}/commits/${encodeURIComponent(sha)}`;
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Shared JSDoc type definitions for audit findings and organization reports.
3
+ * This module has no runtime exports; files that opt in with `// @ts-check`
4
+ * import the types with `import('./types.js')`.
5
+ */
6
+
7
+ /**
8
+ * @typedef {'low'|'medium'|'high'|'critical'} Severity
9
+ */
10
+
11
+ /**
12
+ * One audit finding as produced by `audit` and `auditSources`.
13
+ *
14
+ * @typedef {object} Finding
15
+ * @property {string} id Stable source-occurrence ID.
16
+ * @property {string} [fingerprint] Line-independent baseline identity.
17
+ * @property {string} ruleId Rule that produced the finding, or `parse-error`.
18
+ * @property {Severity} severity
19
+ * @property {string} file Path of the audited file.
20
+ * @property {number} line One-based line, or 0 when there is no line.
21
+ * @property {Record<string, unknown>} fields Rule-specific structured evidence.
22
+ * @property {string} [explain] Remediation text, present when requested.
23
+ */
24
+
25
+ /**
26
+ * A finding reported by an organization scan, with its repository and source
27
+ * locations.
28
+ *
29
+ * @typedef {Finding & {
30
+ * repository: string,
31
+ * branch: string|null,
32
+ * url: string,
33
+ * path: string,
34
+ * blobSha: string|null,
35
+ * permalink: string
36
+ * }} OrganizationFinding
37
+ */
38
+
39
+ /**
40
+ * One workflow file selected for a repository, whether or not it could be read.
41
+ *
42
+ * @typedef {object} FileDetail
43
+ * @property {string} path Repo-relative POSIX path.
44
+ * @property {string|null} blobSha Lowercase 40-hex blob ID from the tree entry.
45
+ * @property {number|null} bytes Decoded size when read, else tree size, else null.
46
+ * @property {'scanned'|'parse-error'|'unreadable'} status
47
+ * @property {number} findings Unsuppressed findings reported for this file.
48
+ * @property {string} permalink Link pinned to the scanned commit.
49
+ */
50
+
51
+ /**
52
+ * @typedef {object} RepositoryInfo
53
+ * @property {string} owner
54
+ * @property {string} name
55
+ * @property {string} fullName
56
+ * @property {string|null} defaultBranch
57
+ * @property {'public'|'private'|'internal'} visibility
58
+ * @property {string} htmlUrl
59
+ */
60
+
61
+ /**
62
+ * The scan result for one repository in the public report document.
63
+ *
64
+ * @typedef {object} RepositoryResult
65
+ * @property {RepositoryInfo} repository
66
+ * @property {{branch: string|null, treeSha: string|null, commitSha: string|null}} revision
67
+ * @property {string[]} files Workflow files that were read and audited.
68
+ * @property {FileDetail[]} fileDetails Every selected workflow file, sorted by path.
69
+ * @property {OrganizationFinding[]} findings
70
+ * @property {Array<{repository: string, path?: string, error: string, permalink?: string}>} errors
71
+ * @property {Record<string, number>} summary
72
+ * @property {'OK'|'FAIL'} status
73
+ */
74
+
75
+ /**
76
+ * The credential-redacted public organization report document.
77
+ *
78
+ * @typedef {object} OrganizationReport
79
+ * @property {'1.0'} schemaVersion
80
+ * @property {string} organization
81
+ * @property {{generation: number, identity: string}} analysis
82
+ * @property {Record<string, any>} scope
83
+ * @property {Record<string, any>} coverage
84
+ * @property {RepositoryResult[]} repositories
85
+ * @property {OrganizationFinding[]} findings Flattened across repositories.
86
+ * @property {RepositoryResult['errors']} errors Flattened across repositories.
87
+ * @property {Record<string, number>} summary
88
+ * @property {{path: string|null, suppressed: number}} baseline
89
+ * @property {string|null} configPath
90
+ * @property {Record<string, any>} [comparison]
91
+ * @property {'OK'|'FAIL'} status
92
+ */
93
+
94
+ /**
95
+ * The raw value returned by `scanOrganization`, before redaction and before
96
+ * paths are made relative. Its shape matches the public report document.
97
+ *
98
+ * @typedef {Omit<OrganizationReport, 'schemaVersion'>} OrganizationScanResult
99
+ */
100
+
101
+ /**
102
+ * Options accepted by `scanOrganization`.
103
+ *
104
+ * @typedef {object} OrganizationScanOptions
105
+ * @property {string} organization
106
+ * @property {string} cwd
107
+ * @property {string} [token]
108
+ * @property {string[]} [repositories]
109
+ * @property {'all'|'public'|'private'|'internal'} visibility
110
+ * @property {boolean} includeArchived
111
+ * @property {boolean} includeDisabled
112
+ * @property {boolean} includeForks
113
+ * @property {number} [maxRepositories]
114
+ * @property {number} [concurrency]
115
+ * @property {Severity} [severity]
116
+ * @property {boolean} explain
117
+ * @property {string|false} [configPath]
118
+ * @property {string} [baseline]
119
+ * @property {string} [checkpointPath]
120
+ * @property {boolean} [resume]
121
+ * @property {(event: ScanProgressEvent) => void|Promise<void>} [onProgress]
122
+ */
123
+
124
+ /**
125
+ * A progress event emitted during an organization scan. `type` names the event;
126
+ * the remaining fields are event-specific.
127
+ *
128
+ * @typedef {{type: string, reused?: boolean} & Record<string, any>} ScanProgressEvent
129
+ */
130
+
131
+ /**
132
+ * A labeled line-oriented record shared by TOON, text, CSV, SARIF, and HTML.
133
+ *
134
+ * @typedef {{label: string, fields: Record<string, unknown>}} ReportRecord
135
+ */
136
+
137
+ export {};
package/src/lib/writer.js CHANGED
@@ -44,6 +44,9 @@ export async function writeFileGuarded({ path, content, dryRun = true, cwd = pro
44
44
  if (entry.isSymbolicLink()) {
45
45
  throw new Error(`refusing to write through a symlink: ${path}`);
46
46
  }
47
+ if (!entry.isFile()) {
48
+ throw new Error(`refusing to replace a non-file path: ${path}`);
49
+ }
47
50
  existingMode = entry.mode & 0o777;
48
51
  } catch (error) {
49
52
  if (error.code !== 'ENOENT') throw error;
@@ -60,6 +60,10 @@ function checkoutProtection(step) {
60
60
  return { active: false, reason: 'unknown-or-unprotected-version' };
61
61
  }
62
62
 
63
+ /**
64
+ * Describe an unprotected checkout of pull-request code, or return null when
65
+ * the step is unrelated or has recognized checkout protection.
66
+ */
63
67
  export function checkoutOfUntrustedPr(step) {
64
68
  if (!step.uses) return null;
65
69
  if (
@@ -88,6 +92,7 @@ export function checkoutOfUntrustedPr(step) {
88
92
  };
89
93
  }
90
94
 
95
+ /** Return whether a shell step directly fetches pull-request-controlled code. */
91
96
  export function fetchesUntrustedPrCode(step) {
92
97
  if (typeof step.run !== 'string') return false;
93
98
  if (/\bgh\s+pr\s+(?:checkout|co)\b/i.test(step.run)) return true;
@@ -5,14 +5,13 @@
5
5
  * write access), making them an unstable supply-chain link.
6
6
  */
7
7
 
8
+ import { GIT_SHA_RE } from '../lib/org-schema.js';
8
9
  import { collectUses } from '../lib/parser.js';
9
10
 
10
11
  export const id = 'unpinned-action';
11
12
  export const severity = 'high';
12
13
  export const description = 'External action or reusable workflow is not pinned to a full commit SHA.';
13
14
 
14
- const SHA_RE = /^[0-9a-f]{40}$/i;
15
-
16
15
  /**
17
16
  * @param {import('../lib/parser.js').WorkflowDoc} workflow
18
17
  * @returns {Array<{id: string, severity: string, line: number, fields: object, explain: string}>}
@@ -21,7 +20,7 @@ export function check(workflow) {
21
20
  const findings = [];
22
21
  for (const { ref } of collectUses(workflow)) {
23
22
  if (ref.kind !== 'external' && ref.kind !== 'reusable-workflow') continue;
24
- if (ref.ref && SHA_RE.test(ref.ref)) continue;
23
+ if (ref.ref && GIT_SHA_RE.test(ref.ref)) continue;
25
24
  findings.push({
26
25
  id,
27
26
  severity,
@@ -1,3 +1,5 @@
1
+ import { isRecord } from '../lib/org-schema.js';
2
+
1
3
  export const id = 'workflow-structure';
2
4
  export const severity = 'medium';
3
5
  export const description = 'Workflow or composite action contains invalid or ambiguous GitHub Actions syntax.';
@@ -376,10 +378,6 @@ function validRunnerSelector(value) {
376
378
  return groupValid || labelsValid;
377
379
  }
378
380
 
379
- function isRecord(value) {
380
- return value !== null && typeof value === 'object' && !Array.isArray(value);
381
- }
382
-
383
381
  function finding(line, issue, explain, job) {
384
382
  return {
385
383
  id,
package/src/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // Runtime version embedded in the GitHub Action bundle. The version-sync check
2
2
  // keeps this value aligned with package.json, the lockfile, and plugin metadata.
3
- export const VERSION = '0.3.0';
3
+ export const VERSION = '0.6.0';
@@ -1,175 +0,0 @@
1
- /**
2
- * Explicit AI-agent execution defaults.
3
- *
4
- * There is no reliable cross-agent runtime signal, so callers opt in through
5
- * `--agent-mode` or ACTIONS_WARDEN_MODE=agent. Organization artifact names are
6
- * derived from the same identity used to validate resumable checkpoints.
7
- */
8
-
9
- import { createHash } from 'node:crypto';
10
- import { lstat } from 'node:fs/promises';
11
- import { resolve } from 'node:path';
12
- import { loadBaseline } from './baseline.js';
13
- import { loadConfig } from './config.js';
14
- import { format } from './formatter.js';
15
- import { createOrganizationCheckpointIdentity } from './org-checkpoint.js';
16
- import { RULES } from '../rules/index.js';
17
-
18
- export const AGENT_MODE_ENVIRONMENT_VARIABLE = 'ACTIONS_WARDEN_MODE';
19
-
20
- const ORGANIZATION_RE = /^[A-Za-z0-9_.-]+$/;
21
- const REPORT_EXTENSIONS = Object.freeze({
22
- json: 'json',
23
- sarif: 'sarif',
24
- text: 'txt',
25
- toon: 'toon',
26
- });
27
-
28
- /**
29
- * Resolve explicit CLI precedence over the environment opt-in.
30
- *
31
- * @param {object} options
32
- * @param {boolean} [options.optionValue]
33
- * @param {string} [options.optionSource]
34
- * @param {string} [options.environmentValue]
35
- */
36
- export function resolveAgentMode({ optionValue, optionSource, environmentValue } = {}) {
37
- if (optionSource === 'cli') return Boolean(optionValue);
38
- if (environmentValue === undefined || environmentValue === '') return false;
39
- if (environmentValue !== 'agent') {
40
- throw new Error(`${AGENT_MODE_ENVIRONMENT_VARIABLE} must be "agent" when set`);
41
- }
42
- return true;
43
- }
44
-
45
- /**
46
- * Build stable, scope-specific paths for an agent-initiated organization scan.
47
- *
48
- * @param {object} options
49
- * @param {string} options.organization
50
- * @param {string} options.cwd
51
- * @param {string[]} [options.repositories]
52
- * @param {'all'|'public'|'private'|'internal'} options.visibility
53
- * @param {boolean} options.includeArchived
54
- * @param {boolean} options.includeDisabled
55
- * @param {boolean} options.includeForks
56
- * @param {number} [options.maxRepositories]
57
- * @param {'low'|'medium'|'high'|'critical'} [options.severity]
58
- * @param {boolean} options.explain
59
- * @param {string|false} [options.configPath]
60
- * @param {string} [options.baseline]
61
- * @param {'toon'|'json'|'text'|'sarif'} options.reportFormat
62
- */
63
- export async function createOrganizationAgentArtifacts({
64
- organization,
65
- cwd,
66
- repositories,
67
- visibility,
68
- includeArchived,
69
- includeDisabled,
70
- includeForks,
71
- maxRepositories,
72
- severity,
73
- explain,
74
- configPath,
75
- baseline,
76
- reportFormat,
77
- }) {
78
- validateOrganization(organization);
79
- const patterns = normalizePatterns(repositories);
80
- const config = await loadConfig({
81
- cwd,
82
- path: configPath,
83
- ruleIds: RULES.map(rule => rule.id),
84
- });
85
- const baselinePath = baseline ?? config.baseline;
86
- const baselineData = baselinePath
87
- ? await loadBaseline({ path: baselinePath, cwd })
88
- : { path: null, ids: new Set(), fingerprints: new Set() };
89
- const identity = createOrganizationCheckpointIdentity({
90
- organization,
91
- repositories: patterns,
92
- visibility,
93
- includeArchived,
94
- includeDisabled,
95
- includeForks,
96
- maxRepositories,
97
- severity,
98
- explain,
99
- config,
100
- baselineData,
101
- });
102
- const key = createHash('sha256')
103
- .update(JSON.stringify(identity))
104
- .digest('hex')
105
- .slice(0, 32);
106
- const groupedKey = key.match(/.{8}/g).join('.');
107
- const checkpointPath = `.actions-warden-agent.${groupedKey}.checkpoint.json`;
108
- const reportExtension = REPORT_EXTENSIONS[reportFormat];
109
- if (!reportExtension) throw new Error(`invalid agent report format: ${reportFormat}`);
110
- const reportPath = `.actions-warden-agent.${groupedKey}.report.${reportExtension}`;
111
-
112
- return {
113
- checkpointPath,
114
- reportPath,
115
- resume: await pathExists(resolve(cwd, checkpointPath)),
116
- };
117
- }
118
-
119
- /**
120
- * Render the bounded stdout contract emitted after an agent-mode file report.
121
- */
122
- export function renderOrganizationAgentReceipt({
123
- result,
124
- reportPath,
125
- reportFormat,
126
- checkpointPath,
127
- resumed,
128
- }) {
129
- return format('json', [], {
130
- status: result.status,
131
- json: {
132
- schemaVersion: '1.0',
133
- kind: 'actions-warden-agent-receipt',
134
- command: 'org-scan',
135
- organization: result.organization,
136
- status: result.status,
137
- summary: result.summary,
138
- report: {
139
- path: reportPath,
140
- format: reportFormat,
141
- },
142
- checkpoint: {
143
- path: checkpointPath,
144
- resumed,
145
- },
146
- },
147
- });
148
- }
149
-
150
- function validateOrganization(organization) {
151
- if (
152
- typeof organization !== 'string'
153
- || !ORGANIZATION_RE.test(organization)
154
- || organization === '.'
155
- || organization === '..'
156
- ) throw new Error('invalid organization');
157
- }
158
-
159
- function normalizePatterns(patterns) {
160
- if (patterns === undefined) return [];
161
- if (!Array.isArray(patterns) || patterns.some(pattern => typeof pattern !== 'string' || !pattern)) {
162
- throw new Error('repository filters must be non-empty strings');
163
- }
164
- return [...new Set(patterns)];
165
- }
166
-
167
- async function pathExists(path) {
168
- try {
169
- await lstat(path);
170
- return true;
171
- } catch (error) {
172
- if (error.code === 'ENOENT') return false;
173
- throw error;
174
- }
175
- }