@patronage/software-factory 1.0.0-alpha.47 → 1.0.0-alpha.49

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.
package/dist/ci.js ADDED
@@ -0,0 +1,4519 @@
1
+ import { createSign, randomUUID } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
4
+ import { execFileSync, spawn } from "node:child_process";
5
+ import { once } from "node:events";
6
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
7
+ import { createRequire } from "node:module";
8
+ import { arch, availableParallelism, cpus, platform, release, totalmem } from "node:os";
9
+ import path from "node:path";
10
+ import { performance } from "node:perf_hooks";
11
+ // ../factory-ci/dist/index.js
12
+ /**
13
+ * The canonical Node 24 family shared by factory-project workflows.
14
+ *
15
+ * Consumers must pass this (or their own complete family) to
16
+ * `factoryWorkflow`; there is deliberately no implicit default. Every action
17
+ * in this family declares `runs.using: node24` at the named release.
18
+ */
19
+ const NODE_PNPM_ACTION_FAMILY_NODE24 = {
20
+ checkout: {
21
+ tag: "v7.0.1",
22
+ uses: "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1"
23
+ },
24
+ id: "node-pnpm-node24",
25
+ setupNode: {
26
+ tag: "v7.0.0",
27
+ uses: "actions/setup-node@820762786026740c76f36085b0efc47a31fe5020"
28
+ },
29
+ setupPnpm: {
30
+ tag: "v6.0.9",
31
+ uses: "pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271"
32
+ }
33
+ };
34
+ /**
35
+ * The one `actions/upload-artifact` pin every workflow generator shares
36
+ * (#887). Two callers pinned two different commits of the same tag family;
37
+ * naming the pin here makes that drift impossible the same way the Node/pnpm
38
+ * family does. A caller passes this through `factoryWorkflow`'s
39
+ * `additionalActions.uploadArtifact` explicitly — the catalog names the pin,
40
+ * it does not inject the upload step.
41
+ */
42
+ const UPLOAD_ARTIFACT = {
43
+ tag: "v4.6.2",
44
+ uses: "actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02"
45
+ };
46
+ /**
47
+ * Pull-request events that can create or refresh a Factory candidate run.
48
+ *
49
+ * GitHub's draft boolean remains the lifecycle authority: these triggers make
50
+ * a run visible, while `factoryCandidateOrPushCondition` keeps substantive
51
+ * jobs idle until the pull request is a candidate.
52
+ */
53
+ const FACTORY_CANDIDATE_PULL_REQUEST_TYPES = Object.freeze([
54
+ "opened",
55
+ "synchronize",
56
+ "reopened",
57
+ "ready_for_review"
58
+ ]);
59
+ /**
60
+ * Build a GitHub Actions job condition for candidate PRs and merge-target
61
+ * pushes. The caller owns triggers, jobs, runners, permissions, and topology.
62
+ */
63
+ const factoryCandidateOrPushCondition = (candidateCondition) => {
64
+ return ["github.event_name == 'push'", `(${[
65
+ "github.event_name == 'pull_request'",
66
+ "github.event.pull_request.draft != true",
67
+ ...candidateCondition ? [candidateCondition] : []
68
+ ].join(" && ")})`].join(" || ");
69
+ };
70
+ /**
71
+ * The disposable Alchemy stage a local preview deploy runs in:
72
+ * `local-pr-<pr>-<short sha>` (#268).
73
+ *
74
+ * A stage that does not match is not disposable, and destructive operations
75
+ * must refuse it.
76
+ */
77
+ const LOCAL_PREVIEW_STAGE_PATTERN = /^local-pr-(?<pr>[1-9]\d*)-(?<sha>[0-9a-f]{7,40})$/u;
78
+ /**
79
+ * Interpret an untrusted stage name through the one disposable-stage grammar.
80
+ * Returns `null` rather than throwing when the value or expected ownership
81
+ * does not match.
82
+ */
83
+ const parseLocalPreviewStage = (stage, expected = {}) => {
84
+ const match = LOCAL_PREVIEW_STAGE_PATTERN.exec(stage);
85
+ if (!match?.groups) return null;
86
+ const pr = Number(match.groups.pr);
87
+ const headShaPrefix = match.groups.sha;
88
+ if (!Number.isSafeInteger(pr) || expected.pr !== void 0 && pr !== expected.pr) return null;
89
+ if (expected.headSha !== void 0) {
90
+ const headSha = expected.headSha.trim().toLowerCase();
91
+ if (!/^[0-9a-f]{40}$/u.test(headSha) || !headSha.startsWith(headShaPrefix)) return null;
92
+ }
93
+ return {
94
+ headShaPrefix,
95
+ pr,
96
+ stage
97
+ };
98
+ };
99
+ /**
100
+ * Whether `stage` is disposable. Pass `pr` to also require PR ownership.
101
+ */
102
+ const isLocalPreviewStage = (stage, pr) => parseLocalPreviewStage(stage, pr === void 0 ? {} : { pr }) !== null;
103
+ /**
104
+ * Build the disposable stage name for a pull request head.
105
+ *
106
+ * Throws when the inputs cannot produce a valid stage, so a caller can never
107
+ * deploy into a name the cleanup sweep will not recognise.
108
+ */
109
+ const localPreviewStage = (options) => {
110
+ const { headSha, pr, shaLength = 12 } = options;
111
+ if (!Number.isSafeInteger(pr) || pr < 1) throw new Error(`pr must be a positive safe integer, got ${pr}.`);
112
+ if (!Number.isInteger(shaLength) || shaLength < 7 || shaLength > 40) throw new Error(`shaLength must be an integer from 7 through 40, got ${shaLength}.`);
113
+ const normalizedHead = headSha.trim().toLowerCase();
114
+ if (!/^[0-9a-f]{40}$/u.test(normalizedHead)) throw new Error(`headSha must be exactly 40 hexadecimal characters, got "${headSha}".`);
115
+ return `local-pr-${pr}-${normalizedHead.slice(0, shaLength)}`;
116
+ };
117
+ const EMPTY_STATE = Object.freeze({ registrations: Object.freeze([]) });
118
+ const DETACHED_PROOF_BRANCH = "(detached)";
119
+ /**
120
+ * The branch name adds no guarantee. Record the sentinel unless the checkout
121
+ * is actually on the PR head branch.
122
+ */
123
+ const proofBranch = (candidate) => candidate.branch.length > 0 && candidate.branch === candidate.prHeadRef ? void 0 : DETACHED_PROOF_BRANCH;
124
+ const registrationKey$1 = (row) => `${row.stack}:${row.stage}`;
125
+ const disposableStage = (stage, candidate) => {
126
+ const parsed = parseLocalPreviewStage(stage, {
127
+ headSha: candidate.headSha,
128
+ pr: candidate.pr
129
+ });
130
+ if (parsed === null) throw new Error(`Preview proof stage must be a disposable local-pr stage owned by PR #${candidate.pr} at this head.`);
131
+ return parsed.stage;
132
+ };
133
+ const assertAdmissibleCandidate = (candidate, stage) => {
134
+ if (candidate.isDraft) throw new Error(`PR #${candidate.pr} is a draft; preview proof registers only after the pull request is marked ready for review.`);
135
+ if (candidate.prState !== "OPEN") throw new Error("Preview proof requires an open pull request.");
136
+ const errors = [];
137
+ if (candidate.dirty) errors.push("Worktree must be clean.");
138
+ if (candidate.headSha !== candidate.prHeadSha) errors.push("HEAD is stale for the current PR head.");
139
+ if (candidate.repository !== candidate.prRepository) errors.push("PR head repository does not match the current repository.");
140
+ if (errors.length > 0) throw new Error(errors.join("\n"));
141
+ return disposableStage(stage, candidate);
142
+ };
143
+ const SHA_PATTERN$1 = /^[0-9a-f]{7,40}$/u;
144
+ const assertPassingEnvelope = (evidence, headSha) => {
145
+ if (evidence.outcome !== "pass" || evidence.headSha !== headSha || evidence.check.trim().length === 0 || !SHA_PATTERN$1.test(evidence.patchId) || !SHA_PATTERN$1.test(evidence.mergeBaseSha)) throw new Error("Preview proof requires a passing evidence envelope at the candidate head.");
146
+ };
147
+ const replaceRegistration$1 = (state, next) => {
148
+ const key = registrationKey$1(next);
149
+ return { registrations: [...state.registrations.filter((row) => registrationKey$1(row) !== key), next] };
150
+ };
151
+ const empty = () => EMPTY_STATE;
152
+ const resolve = (state, query = {}) => state.registrations.filter((row) => (query.pr === void 0 || row.pr === query.pr) && (query.stack === void 0 || row.stack === query.stack) && (query.stage === void 0 || row.stage === query.stage));
153
+ const transition = (state, event) => {
154
+ if (event.type === "begin") {
155
+ assertAdmissibleCandidate(event.candidate, event.stage);
156
+ return state;
157
+ }
158
+ if (event.type === "register") {
159
+ const stage = assertAdmissibleCandidate(event.candidate, event.stage);
160
+ if (event.smoke.outcome !== "passed") throw new Error("Preview proof requires passed smoke evidence.");
161
+ if (event.convergence.status !== "passed") throw new Error("Preview proof requires passed convergence evidence.");
162
+ if (!event.stack || !event.url) throw new Error("Preview proof registration requires a stack and URL.");
163
+ assertPassingEnvelope(event.evidence, event.candidate.headSha);
164
+ const branch = proofBranch(event.candidate);
165
+ return replaceRegistration$1(state, {
166
+ ...branch === void 0 ? {} : { branch },
167
+ cleanup: {
168
+ evidence: [],
169
+ outcome: "pending"
170
+ },
171
+ convergence: {
172
+ detail: event.convergence.detail,
173
+ status: "passed"
174
+ },
175
+ headSha: event.candidate.headSha,
176
+ pr: event.candidate.pr,
177
+ proof: {
178
+ check: event.evidence.check,
179
+ headSha: event.evidence.headSha,
180
+ mergeBaseSha: event.evidence.mergeBaseSha,
181
+ patchId: event.evidence.patchId
182
+ },
183
+ smoke: {
184
+ detail: event.smoke.detail,
185
+ outcome: "passed"
186
+ },
187
+ source: "local-self-certified",
188
+ stack: event.stack,
189
+ stage,
190
+ url: event.url
191
+ });
192
+ }
193
+ const existing = state.registrations.find((row) => row.pr === event.pr && row.stack === event.stack && row.stage === event.stage);
194
+ if (!existing) throw new Error(`Preview proof cleanup requires a registration for ${event.stack}/${event.stage}.`);
195
+ const cleanup = event.runUrl === void 0 ? {
196
+ evidence: event.evidence,
197
+ outcome: event.outcome
198
+ } : {
199
+ evidence: event.evidence,
200
+ outcome: event.outcome,
201
+ runUrl: event.runUrl
202
+ };
203
+ return replaceRegistration$1(state, {
204
+ ...existing,
205
+ cleanup
206
+ });
207
+ };
208
+ const recover = (state, event) => {
209
+ if (state.registrations.find((row) => row.pr === event.pr && row.stack === event.stack && row.stage === event.stage)?.cleanup.outcome !== "failed") throw new Error("Preview proof recovery re-enters cleanup only from a failed outcome.");
210
+ return transition(state, event);
211
+ };
212
+ const previewProofLifecycle = {
213
+ empty,
214
+ recover,
215
+ resolve,
216
+ transition
217
+ };
218
+ /**
219
+ * One GitHub JSON request with bounded transport retries (#830, #923).
220
+ *
221
+ * Both GitHub callers in this package share this primitive: the preview-proof
222
+ * inventory and the GitHub App token mint. Each attempt gets a fresh timeout
223
+ * signal. A transport failure — a rejected fetch, a timeout, a transient HTTP
224
+ * status, or a body that dies mid-read — retries with doubling backoff and
225
+ * exhausts into the caller's transport error. A permanent HTTP refusal throws
226
+ * the caller's refusal error on its first response.
227
+ *
228
+ * Retrying a write is safe here: check-run payloads are idempotent per stack
229
+ * and stage, and a token mint issues a fresh token per call.
230
+ */
231
+ const GITHUB_API_VERSION = "2022-11-28";
232
+ /**
233
+ * Default total transport attempts per request, the first one included. A
234
+ * caller whose request has a fallback overrides it with 1 (#938).
235
+ */
236
+ const TRANSPORT_RETRY_ATTEMPTS = 3;
237
+ /** Delay before the first retry; each further retry doubles it. */
238
+ const TRANSPORT_RETRY_BACKOFF_MS = 500;
239
+ const defaultTransportWait = (ms) => setTimeout$1(ms);
240
+ let transportWait = defaultTransportWait;
241
+ /**
242
+ * Bounded transport retries could not reach the GitHub App endpoint (#923).
243
+ * The reason is credential-free, so it is safe to log. Re-exported from
244
+ * `github-app-token.ts`, which owns the mint surface.
245
+ */
246
+ var GitHubAppTokenTransportError = class extends Error {
247
+ /** How many transport attempts were made before giving up. */
248
+ attempts;
249
+ /** The last transient HTTP status, when the server answered at all. */
250
+ status;
251
+ constructor(reason, attempts, status) {
252
+ super(`GitHub App token transport failed after ${attempts} attempt(s): ${reason}`);
253
+ this.name = "GitHubAppTokenTransportError";
254
+ this.attempts = attempts;
255
+ if (status !== void 0) this.status = status;
256
+ }
257
+ };
258
+ /**
259
+ * Transient statuses are the ones where GitHub never judged the content — a
260
+ * request timeout (408), a rate limit (429), or the server failing (5xx) — so
261
+ * the same bytes can still succeed. Every other non-2xx is GitHub refusing
262
+ * this request and repeats on retry.
263
+ */
264
+ const isTransientStatus = (status) => status === 408 || status === 429 || status >= 500;
265
+ /**
266
+ * A bounded, credential-free description of a transport failure. The raw
267
+ * error may retain the request and its `Authorization` header; only the name
268
+ * and a truncated message survive.
269
+ */
270
+ const boundedTransportReason = (error) => error instanceof Error ? `${error.name}: ${error.message}`.slice(0, 200) : "unknown transport error";
271
+ /**
272
+ * One attempt with a fresh timeout signal. A transport failure is reported as
273
+ * an outcome so the caller can retry; a permanent HTTP refusal throws here.
274
+ */
275
+ const githubJsonAttempt = async (options, errors) => {
276
+ let response;
277
+ try {
278
+ response = await options.fetch(options.url, {
279
+ body: options.body,
280
+ headers: {
281
+ Accept: "application/vnd.github+json",
282
+ Authorization: `Bearer ${options.token}`,
283
+ "X-GitHub-Api-Version": GITHUB_API_VERSION,
284
+ ...options.closeConnection ? { Connection: "close" } : {},
285
+ ...options.body === void 0 ? {} : { "Content-Type": "application/json" }
286
+ },
287
+ method: options.method,
288
+ signal: AbortSignal.timeout(options.timeoutMs)
289
+ });
290
+ } catch (error) {
291
+ return {
292
+ ok: false,
293
+ reason: boundedTransportReason(error)
294
+ };
295
+ }
296
+ if (!response.ok) {
297
+ if (!isTransientStatus(response.status)) throw errors.refusal(response.status, response.statusText);
298
+ return {
299
+ ok: false,
300
+ reason: `GitHub API ${response.status} ${response.statusText}`,
301
+ status: response.status
302
+ };
303
+ }
304
+ try {
305
+ return {
306
+ ok: true,
307
+ value: await response.json()
308
+ };
309
+ } catch (error) {
310
+ return {
311
+ ok: false,
312
+ reason: boundedTransportReason(error)
313
+ };
314
+ }
315
+ };
316
+ /** Run one GitHub JSON request with bounded transport retries. */
317
+ const githubJson$1 = async (options, errors) => {
318
+ const attempts = Math.max(1, options.attempts ?? TRANSPORT_RETRY_ATTEMPTS);
319
+ let outcome = await githubJsonAttempt(options, errors);
320
+ for (let attempt = 2; attempt <= attempts && !outcome.ok; attempt += 1) {
321
+ await transportWait(TRANSPORT_RETRY_BACKOFF_MS * 2 ** (attempt - 2));
322
+ outcome = await githubJsonAttempt(options, errors);
323
+ }
324
+ if (outcome.ok) return outcome.value;
325
+ throw errors.transport(outcome, attempts);
326
+ };
327
+ /**
328
+ * Minting a GitHub App installation token: the RS256 app JWT, the optional
329
+ * installation lookup, and the token exchange (#617).
330
+ *
331
+ * Only the *mechanism* lives here. Where the private key comes from, how the
332
+ * app id is configured, and what the token is then used for stay with each
333
+ * consumer: this module is handed credentials and returns a token.
334
+ */
335
+ /** The default request budget, matching the factory's other GitHub writes. */
336
+ const DEFAULT_TIMEOUT_MS$2 = 5e3;
337
+ /** Nine-minute JWT lifetime, backdated a minute against runner clock skew. */
338
+ const JWT_BACKDATE_SECONDS = 60;
339
+ const JWT_LIFETIME_SECONDS = 600;
340
+ /** Carries the HTTP status so a caller can tell a retryable failure apart. */
341
+ var GitHubApiError = class extends Error {
342
+ status;
343
+ constructor(status, statusText) {
344
+ super(`GitHub API ${status} ${statusText}`);
345
+ this.name = "GitHubApiError";
346
+ this.status = status;
347
+ }
348
+ };
349
+ /** The Factory App broker's token: repo-scoped Checks write, nothing else. */
350
+ const FACTORY_APP_BROKER_TOKEN_PERMISSIONS = { checks: "write" };
351
+ const base64url = (value) => Buffer.from(value).toString("base64url");
352
+ /**
353
+ * The signed app JWT GitHub accepts as `Authorization: Bearer` for the App
354
+ * endpoints. `iss` is stringified because GitHub accepts either spelling and a
355
+ * numeric app id must not depend on JSON's number formatting.
356
+ *
357
+ * The signature is produced from the key on disk and returned; the key
358
+ * material itself never leaves this call.
359
+ */
360
+ const githubAppJwt = (credentials, options = {}) => {
361
+ const nowMs = (options.now ?? Date.now)();
362
+ const issuedAt = Math.floor(nowMs / 1e3) - JWT_BACKDATE_SECONDS;
363
+ const unsigned = `${base64url(JSON.stringify({
364
+ alg: "RS256",
365
+ typ: "JWT"
366
+ }))}.${base64url(JSON.stringify({
367
+ exp: issuedAt + JWT_LIFETIME_SECONDS,
368
+ iat: issuedAt,
369
+ iss: String(credentials.appId)
370
+ }))}`;
371
+ const readKey = options.readPrivateKey ?? readFileSync;
372
+ const signer = createSign("RSA-SHA256");
373
+ signer.update(unsigned);
374
+ signer.end();
375
+ return `${unsigned}.${signer.sign(readKey(credentials.privateKeyPath), "base64url")}`;
376
+ };
377
+ const githubAppJson = (request, url, jwt, method, budget) => githubJson$1({
378
+ attempts: budget.attempts,
379
+ ...budget.body === void 0 ? {} : { body: budget.body },
380
+ closeConnection: true,
381
+ fetch: request,
382
+ method,
383
+ timeoutMs: budget.timeoutMs,
384
+ token: jwt,
385
+ url
386
+ }, {
387
+ refusal: (status, statusText) => new GitHubApiError(status, statusText),
388
+ transport: (failure, attempts) => new GitHubAppTokenTransportError(failure.reason, attempts, failure.status)
389
+ });
390
+ const installationAccountLogin = (installation) => {
391
+ const { account } = installation;
392
+ if (typeof account !== "object" || account === null) return;
393
+ const { login } = account;
394
+ return typeof login === "string" ? login : void 0;
395
+ };
396
+ /**
397
+ * Mint an installation access token for one repository.
398
+ *
399
+ * When the credentials omit `installationId`, the installation is discovered
400
+ * from the repository first — the same call every consumer had written for
401
+ * itself. A pinned `installationId` is looked up instead, and the mint is
402
+ * refused unless that installation's account is the repository owner (GitHub
403
+ * logins compare case-insensitively): a `repositories` restriction names
404
+ * repositories without an owner, so a pin for one account must not mint for
405
+ * a same-named repository under another (#1428). Nothing is cached: the token
406
+ * is returned to the caller and this module keeps no copy.
407
+ */
408
+ const mintInstallationToken = async (input, options = {}) => {
409
+ const { credentials } = input;
410
+ const request = options.fetch ?? fetch;
411
+ const budget = {
412
+ attempts: options.transportAttempts,
413
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS$2
414
+ };
415
+ const jwt = githubAppJwt(credentials, options);
416
+ let { installationId } = credentials;
417
+ if (installationId === void 0) {
418
+ const installation = await githubAppJson(request, `https://api.github.com/repos/${input.owner}/${input.repo}/installation`, jwt, "GET", budget);
419
+ if (typeof installation.id !== "number") throw new TypeError("GitHub App installation response omitted id");
420
+ installationId = installation.id;
421
+ } else {
422
+ const pinned = await githubAppJson(request, `https://api.github.com/app/installations/${installationId}`, jwt, "GET", budget);
423
+ const accountLogin = installationAccountLogin(pinned);
424
+ if (accountLogin === void 0) throw new TypeError("GitHub App installation response omitted account login");
425
+ if (accountLogin.toLowerCase() !== input.owner.toLowerCase()) throw new Error(`GitHub App installation ${installationId} belongs to ${accountLogin}, not ${input.owner}; refusing to mint a token for ${input.owner}/${input.repo}`);
426
+ }
427
+ const restriction = input.permissions === void 0 && input.repositories === void 0 ? void 0 : JSON.stringify({
428
+ ...input.permissions === void 0 ? {} : { permissions: input.permissions },
429
+ ...input.repositories === void 0 ? {} : { repositories: [...input.repositories] }
430
+ });
431
+ const minted = await githubAppJson(request, `https://api.github.com/app/installations/${installationId}/access_tokens`, jwt, "POST", restriction === void 0 ? budget : {
432
+ ...budget,
433
+ body: restriction
434
+ });
435
+ if (typeof minted.token !== "string") throw new TypeError("GitHub App token response omitted token");
436
+ return minted.token;
437
+ };
438
+ /**
439
+ * The GitHub-side **proof-reuse gate** (ADR 0022, #309, #317).
440
+ *
441
+ * It answers one question, before checkout and before install: may this job
442
+ * reuse the local verification the factory already published for *this exact
443
+ * head*? On a pull request the head is the PR branch tip. On a push to the
444
+ * default branch, a **merge fallback** extends "this exact head" to "this
445
+ * exact tree": a merge whose tree is byte-identical to the producing pull
446
+ * request's proven head tree reuses that head's proof, but only when the proof
447
+ * is a whole-tree run that *executed* every command the surface requires
448
+ * (#1658). Impact-stamp releases and diff-scoped runs never count on a push,
449
+ * because a merge target is owed the whole tree (#931). Refusing runs hosted
450
+ * CI; it never fails the candidate.
451
+ *
452
+ * What a consumer chooses is only *what its guarded surface requires*: the
453
+ * plain profile command objects that surface selects. Everything else below is
454
+ * the same for every consumer and every surface.
455
+ */
456
+ /**
457
+ * Escaped so the emitted text carries a GitHub Actions expression rather than
458
+ * this file carrying a JavaScript template hole.
459
+ */
460
+ const githubExpression$1 = (expression) => `\${{ ${expression} }}`;
461
+ /** A braced shell expansion that has to survive TypeScript interpolation. */
462
+ const shellExpansion$1 = (expression) => `\${${expression}}`;
463
+ /**
464
+ * Single-quote a value for the emitted script. Every non-literal value that
465
+ * reaches the script goes through this.
466
+ *
467
+ * `JSON.stringify` is *not* a shell quoter — it escapes `"` and `\` and leaves
468
+ * `'` untouched — so interpolating a JSON document straight into a
469
+ * single-quoted assignment lets one apostrophe in a profile command name close
470
+ * the assignment and run the remainder as shell. Names are charset-validated
471
+ * before they get here; this is the second layer, so the interpolation stays
472
+ * safe if that validation is ever loosened.
473
+ */
474
+ const shellSingleQuote = (value) => `'${value.replaceAll("'", String.raw`'\''`)}'`;
475
+ /**
476
+ * The check run the gate reads. Fixed: `patronage-factory/pr-verify` is also
477
+ * postable as a *commit status* by any token with write access, so only the
478
+ * Checks API is ever consulted and only under this exact name.
479
+ */
480
+ const FACTORY_PROOF_GATE_CHECK_NAME = "patronage-factory/pr-verify";
481
+ /**
482
+ * The Patronage Factory GitHub App, pinned (ADR 0022). A runner has no
483
+ * operator user config to read the producing App identity from, and the
484
+ * identity is a trust predicate, so it is not a repository variable a consumer
485
+ * can point somewhere else. Neither the id nor the slug is a secret: GitHub
486
+ * returns `app.id` on every check run it serves.
487
+ */
488
+ const FACTORY_PROOF_GATE_APP_ID = "4314840";
489
+ /** Step id the guard condition refers to. */
490
+ const FACTORY_PROOF_GATE_STEP_ID = "factory-proof";
491
+ /**
492
+ * Human-visible name of the gate step as the Actions jobs API serves it. A
493
+ * read-only run analyzer (`psf ci:analyze`, #647) matches on this name to
494
+ * classify a run as proof-reuse versus full fallback, so it is exported from
495
+ * exactly the module that writes it — matching on a re-typed copy would drift.
496
+ */
497
+ const FACTORY_PROOF_GATE_STEP_NAME = "Check for factory proof of this head";
498
+ /**
499
+ * The shell the gate runs under, and it is a correctness requirement rather
500
+ * than a preference.
501
+ *
502
+ * GitHub's default for a `run:` step is `bash -e {0}`: **errexit comes from
503
+ * the invocation, not from the script**, and no `set +e` in the script body
504
+ * can be relied on to express the intent because the abort happens at the
505
+ * failing command. The whole fail-open design below — every path reaching one
506
+ * final `GITHUB_OUTPUT` write, no `set -e` — is void under that default. It
507
+ * was: the gate died at a `read` returning 1 at EOF, two seconds in, with no
508
+ * stdout, no verdict and no `reason`, so reuse collapsed to never *and* the
509
+ * signal built to reveal that could not fire (#319).
510
+ *
511
+ * A `shell:` value containing `{0}` is used verbatim by the runner, so this
512
+ * form supplies no `-e`. The shorthand `shell: bash` must never be used here:
513
+ * it expands to `bash --noprofile --norc -eo pipefail {0}`. `pipefail` is set
514
+ * by the script itself.
515
+ *
516
+ * The script is additionally written to survive errexit anyway. Both layers
517
+ * are deliberate: this one states the contract, that one means a runner which
518
+ * ignores it still gets a decision.
519
+ */
520
+ const FACTORY_PROOF_GATE_SHELL = "bash --noprofile --norc {0}";
521
+ /** Output the verdict is written to. `true` — and only `true` — skips. */
522
+ const FACTORY_PROOF_GATE_OUTPUT = "reuse-proof";
523
+ /**
524
+ * Machine-readable refusal category. Fleet-status reads this: it is what makes
525
+ * a reuse-collapses-to-never regression visible instead of hidden behind
526
+ * fail-open, which by construction looks exactly like healthy full CI.
527
+ */
528
+ const FACTORY_PROOF_GATE_REASON_OUTPUT = "reason";
529
+ /**
530
+ * Recorded verification mode, when the gate could read one. Diagnostic
531
+ * metadata only — never an authorization condition (ADR 0022). A reduced-mode
532
+ * proof that executed every command the surface requires is reusable.
533
+ */
534
+ const FACTORY_PROOF_GATE_MODE_OUTPUT = "mode";
535
+ /** Exact Checks API URL of the proof generation selected by the gate. */
536
+ const FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT = "source-check-url";
537
+ /**
538
+ * The commit whose proof was reused, when the gate reused one. On a pull
539
+ * request it is the head itself; on a merge-target push it is the producing
540
+ * pull request's head, a different commit than the pushed one (#1658). Empty
541
+ * on every refusal.
542
+ */
543
+ const FACTORY_PROOF_GATE_SOURCE_HEAD_OUTPUT = "source-head";
544
+ /**
545
+ * Guard for every step the gate protects. Deliberately `!= 'true'` and not
546
+ * `== 'false'`: an unset, empty, or garbled output must run the suite.
547
+ */
548
+ const FACTORY_PROOF_GATE_GUARD = `steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_OUTPUT} != 'true'`;
549
+ /**
550
+ * Pull requests, plus pushes to the default branch (#611, #1658) — the gate's
551
+ * single condition.
552
+ *
553
+ * A merge target's guarantee is about the whole tree, not the diff. A squash
554
+ * merge mints a new commit, so no proof is ever written for the merged SHA;
555
+ * the push path exists only for the merge fallback, which reuses the
556
+ * producing pull request's head proof when the merge tree *is* that head's
557
+ * tree and the proof's whole-tree run executed every command the surface
558
+ * requires.
559
+ *
560
+ * #931 is why both conditions are load-bearing. A `main` push once reused an
561
+ * impact-scoped candidate proof, executed no command for an untouched
562
+ * package, and left that package red for three days. An impact-scoped proof
563
+ * is a sound gate for the candidate and an unsound one for the merge target,
564
+ * so a push credits no `notRequiredCommands` release. The same holds for a
565
+ * command that ran but scoped itself to the diff through the run context
566
+ * (`psf affected`): only a proof recording `runScope: "whole-tree"` counts.
567
+ * Anything else runs the full battery.
568
+ *
569
+ * The push side is deliberately the default branch only. Which branches
570
+ * trigger a workflow at all stays repository-owned; this condition only keeps
571
+ * the gate from consulting proof on pushes that are not merges into the
572
+ * default branch.
573
+ */
574
+ const FACTORY_PROOF_GATE_IF = "github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch))";
575
+ /**
576
+ * The complete refusal vocabulary: the only distinctions the gate can make
577
+ * from its Checks API reads.
578
+ *
579
+ * - `proven` a covering, passing, unambiguous proof for this exact head
580
+ * - `none` no App-verified factory check run at this commit
581
+ * - `pending` the newest generation had not completed when this job read it
582
+ * - `failed` the newest generation records no pass
583
+ * - `unreadable` it passed but carries no binding for this repository and head
584
+ * - `incomplete` its executed plus stamp-authorized released commands do not
585
+ * cover every required command
586
+ * - `ambiguous` two different generations share the newest instant, the
587
+ * newest repeats another run's verdict with no proof time to
588
+ * tell them apart, a run's start time cannot be ranked, the
589
+ * newest pass records no verification start beside another run
590
+ * at this head (#1514), or the newest pass started before
591
+ * another run at this head was posted
592
+ * - `error` the gate could not reach a decision (fail open)
593
+ */
594
+ const FACTORY_PROOF_GATE_REASONS = [
595
+ "proven",
596
+ "none",
597
+ "pending",
598
+ "failed",
599
+ "unreadable",
600
+ "incomplete",
601
+ "ambiguous",
602
+ "error"
603
+ ];
604
+ /**
605
+ * Command identities are baked into the emitted script, so their charset is a
606
+ * safety property, not a style rule. `surface` has always gone through
607
+ * `safeLabel` for this reason; `name` needs the same treatment.
608
+ *
609
+ * Deliberately a strict allow-list rather than a quote-escaper: a name is an
610
+ * identifier, and every identity across the fleet's profiles today is
611
+ * `[a-z0-9:-]`. Anything outside this — hostile or merely a stray apostrophe —
612
+ * makes the whole selection unusable, which degrades to the refusing script.
613
+ * A stray apostrophe reaching interpolation would otherwise kill the step with
614
+ * a bash syntax error *before* the single `GITHUB_OUTPUT` write, so reuse
615
+ * would collapse to never with no `reason` written at all — the silent
616
+ * regression the vocabulary exists to make visible.
617
+ */
618
+ const COMMAND_IDENTITY = /^\w[\w.:@/-]*$/u;
619
+ const COMMAND_IDENTITY_MAX_LENGTH = 120;
620
+ /**
621
+ * The impact-stamp interpretation the paired factory packages currently
622
+ * share. A release recorded under any other version is an unmodelled input and
623
+ * cannot subtract hosted work. This is intentionally fail-closed and moves in
624
+ * lockstep with the proof/check-payload producer.
625
+ */
626
+ const TRUSTED_IMPACT_STAMP_VERSION = 4;
627
+ /**
628
+ * The verify modes the CLI reads a payload under (`isResolvedPrVerifyMode` in
629
+ * `software-factory/src/pr-verify-mode.ts`). factory-ci cannot import it, so
630
+ * the list is repeated here, and the software-factory differential suite pins
631
+ * the two lists together (#1510).
632
+ */
633
+ const RESOLVED_VERIFY_MODES = [
634
+ "docs-only",
635
+ "trivial",
636
+ "full"
637
+ ];
638
+ /**
639
+ * The check-text size over which the CLI drops a transported typed proof
640
+ * (`readTransportedVerifyProof` in
641
+ * `software-factory/src/pr-verify-check-payload.ts`), in UTF-8 bytes of the
642
+ * raw text it parsed, fence included (#1510).
643
+ */
644
+ const TRANSPORT_CAP_BYTES = 6e4;
645
+ const isProofReuseCommand = (value) => {
646
+ if (!(value && typeof value === "object")) return false;
647
+ const entry = value;
648
+ return typeof entry.command === "string" && entry.command.length > 0 && typeof entry.name === "string" && entry.name.length <= COMMAND_IDENTITY_MAX_LENGTH && COMMAND_IDENTITY.test(entry.name);
649
+ };
650
+ /**
651
+ * The command identities a guarded surface requires, derived from the profile
652
+ * command objects that surface selected. This is the single derivation: the
653
+ * gate script and the static coverage assertion both go through it, so a
654
+ * consumer can never have one notion of "required" at generation time and
655
+ * another at assertion time.
656
+ *
657
+ * `undefined` means the selection is unusable — not an array, empty, or
658
+ * carrying an entry whose `command` is blank or whose `name` is not a plain
659
+ * command identity, or carrying duplicate names. A name is the executable
660
+ * authorization identity recorded in proof, so two commands may never collapse
661
+ * behind one. An empty required set would make *every* passing proof trivially
662
+ * covering, so it is never silently treated as "requires nothing"; callers
663
+ * must refuse instead.
664
+ */
665
+ const proofReuseRequiredCommands = (commands) => {
666
+ if (!(Array.isArray(commands) && commands.length > 0)) return;
667
+ if (!commands.every(isProofReuseCommand)) return;
668
+ const names = commands.map(({ name }) => name);
669
+ if (new Set(names).size !== names.length) return;
670
+ return names.toSorted();
671
+ };
672
+ /**
673
+ * Resolve command identities to their `ProofReuseCommand` objects (ADR 0021).
674
+ * Which names a surface requires is the consumer's choice; this is only the
675
+ * lookup. A name with no catalog entry throws at generation time, because a
676
+ * required set that quietly loses an entry makes any passing proof covering.
677
+ * The message says "the profile's command catalog" rather than a file name,
678
+ * since not every consumer's catalog is `software-factory.profile.json`.
679
+ */
680
+ const resolveProofReuseCommands = (catalog, names, selectionLabel) => names.map((name) => {
681
+ const command = catalog.find((entry) => entry.name === name);
682
+ if (!command) {
683
+ const location = selectionLabel ? `Proof-reuse selection for the ${selectionLabel} surface names` : "Proof-reuse selection names";
684
+ throw new Error(`${location} "${name}", which the profile's command catalog does not define.`);
685
+ }
686
+ return {
687
+ command: command.command,
688
+ name: command.name
689
+ };
690
+ });
691
+ /**
692
+ * jq program: every page of the Checks API result in, four sanitized lines
693
+ * (`reason`, `mode`, uncovered commands, source URL) out.
694
+ *
695
+ * `$creditReleases` is `true` on a pull request and `false` on any push,
696
+ * the merge fallback included. With it `false`, a validated
697
+ * `notRequiredCommands` release still covers nothing, and the proof must
698
+ * also record `runScope: "whole-tree"`: `pr:verify` hands each command the
699
+ * diff, and a command may scope itself to it (`psf affected`), so a command
700
+ * name in `executedCommands` says the command ran, not that it covered the
701
+ * tree. Only a whole-tree run's executed commands are what a merge target is
702
+ * owed (#931, #1658). Without it, `whole-tree run` is reported missing.
703
+ *
704
+ * The input is what `gh api --paginate` actually writes: the pages
705
+ * *concatenated* as a stream of top-level response objects, not merged into
706
+ * one document and not wrapped in an array. That is why the script invokes
707
+ * `jq -s` and why this program opens with `.[] | (.check_runs // [])[]`. A
708
+ * test double that emits `[{ "check_runs": [...] }]` instead is a different
709
+ * shape: `jq` fails with `Cannot index array with string ("check_runs")`, the
710
+ * script lands on `reason=error`, and — because the gate fails open — the
711
+ * result looks exactly like healthy full CI. Stub `gh` with a bare response
712
+ * object per page.
713
+ *
714
+ * `binding` recovers the machine-readable payload from `output.text`
715
+ * (preferred) or `output.summary`, which the factory writes as a fenced JSON
716
+ * document. Anything unparseable degrades to `null`, and therefore to a
717
+ * refusal.
718
+ *
719
+ * This is the *second* parser of that payload, and it does not reimplement
720
+ * the first: `parsePrVerifyCheckPayload`
721
+ * (`software-factory/src/pr-verify-check-payload.ts`) regex-extracts the fenced
722
+ * block up to the next line that starts with a fence and `JSON.parse`s it,
723
+ * while this one strips every such line and `fromjson`s what remains. The
724
+ * writer renders JSON, whose strings hold no raw line feed, between one
725
+ * opening and one closing fence line, so on its text the two read the same
726
+ * JSON, three backticks inside a string included. On other text they can
727
+ * differ in either direction. Prose around the fence parses there and refuses
728
+ * here; the test suite asserts that the exact shape the renderer emits is
729
+ * proven here and that the prose-wrapped shape refuses. Text that parses here
730
+ * and not there is part of the trust boundary below.
731
+ *
732
+ * Once parsed, a payload is read by the CLI's readability rules (#1510).
733
+ * `bound` requires the binding's
734
+ * `kind`, `schemaVersion` 1, this head, this repository and a resolved verify
735
+ * mode (`resolvedMode`, the CLI's `isResolvedPrVerifyMode`), and the verdict
736
+ * stage refuses a run that is not `bound` as `unreadable`; an `outcome` other
737
+ * than `passed` is never a pass. `binding` drops a transported typed proof
738
+ * (`verificationProof`) when the text it parsed, fence included, is over
739
+ * 60,000 UTF-8 bytes, as `readTransportedVerifyProof` does, so the run is a
740
+ * pass with no typed proof to both readers. On text the writer never emits,
741
+ * this reader can still read a payload differently; see the trust boundary
742
+ * below.
743
+ *
744
+ * A passing generation is ordered by when its verification started, never
745
+ * later than when its run reached GitHub and never by when its verification
746
+ * ended (#1409, #1490). Every other run is ordered by when it reached GitHub
747
+ * (#1506). It is the rule `fetchPrVerifyProofBinding` applies
748
+ * (`software-factory/src/github-check-runs.ts`), mirrored here because this
749
+ * reader is jq in generated CI and cannot import it:
750
+ *
751
+ * - A passing run (`passing`) is completed with conclusion `success`, and its
752
+ * binding is bound to this head and repository with outcome `passed`. When it
753
+ * transports a typed proof (`verificationProof`) whose start is computable
754
+ * (`proofStart`: its `endedAt` minus its `durationMs`), it is ordered at that
755
+ * start, or at its own `started_at` when that is earlier. Such runs with the
756
+ * same binding, status and conclusion are one generation posted more than
757
+ * once (`pr:verify` posts, `pr:publish` re-posts), ordered at the earliest of
758
+ * its members' instants, whatever order GitHub serves them in. A re-post does
759
+ * not move the proof's start, so a re-post of an older pass never outranks a
760
+ * newer failure, and a post plus its re-post is no tie.
761
+ * - Any other run is its own generation at its `started_at`: one still
762
+ * running, a failure or cancellation whether or not it carries a proof, an
763
+ * unbound one, or a pass with no usable typed proof (over the text cap,
764
+ * written before proofs travelled, or with no computable start). A run is
765
+ * created no earlier than its verification began, so `started_at` is an
766
+ * upper bound on that start. Ranking there can only make such a run newer
767
+ * than it is, so it vetoes more, never less.
768
+ * - A pass with no usable typed proof is reused only when it is the only run
769
+ * at this head (#1514). Its verification started at some unknown instant
770
+ * no later than its `started_at`, so another run posted before that
771
+ * `started_at` may still have been posted after the pass began: a pass
772
+ * verified before a failure but posted after it would otherwise outrank
773
+ * the failure. Ranked at its post, such a pass can only veto more as an
774
+ * older run; as the newest it is `ambiguous` beside any other run. Proofs
775
+ * over the text cap are rare, so refusing costs a hosted run.
776
+ * - Neither `endedAt` nor a passing run's `started_at` is its start. The
777
+ * factory posts a `pr-verify` run only once verification has finished, so
778
+ * both say when it ended, and an older pass ordered there would hide a run
779
+ * that started after the pass began: still running, or failed (#1490). A
780
+ * pass's `started_at` only caps its proof's start. A failure's `started_at`
781
+ * is when it was posted, not when it started, and that is deliberate: a
782
+ * veto's instant only has to be no earlier than its start.
783
+ * - Only a pass is ordered by its proof because this reader cannot run the
784
+ * proof schema (#1506). The CLI drops a payload whose proof fails that
785
+ * schema and orders the run at its `started_at`; ordered by its proof's
786
+ * claimed start, a failure carrying a malformed proof ranked under an older
787
+ * pass here, and the gate returned `proven` where the CLI refused. For an
788
+ * honest proof, `started_at` is no earlier than `endedAt`, which is no
789
+ * earlier than the start, so the cap changes nothing for a valid pass.
790
+ * - A pass is reused only when its verification started strictly after every
791
+ * other run at this head was posted (#1506). Its start is its instant: its
792
+ * proof's start, capped as above, or its `started_at` when it is ordered
793
+ * there. Every other run's post is its `started_at`, rounded down to the
794
+ * whole second. Only the pass's own generation is left out: its re-post
795
+ * group, or, for a pass with no typed proof, that run alone
796
+ * (`ownGeneration`). At most one generation can satisfy this, and that one
797
+ * is the newest, so the gate selects the newest generation and, when it is
798
+ * a pass (`passing`), refuses it as `ambiguous` unless every other run was
799
+ * posted before its instant. When the newest generation is not a pass, the
800
+ * verdict is a refusal anyway, so its reason (`failed`, `pending`, ...)
801
+ * stands and the check does not run.
802
+ * - The check exists because any other run may be ordered earlier than its
803
+ * post by a proof this reader cannot validate: a pass that only claims
804
+ * `passed` looks to jq exactly like one the CLI validates. Without it, a
805
+ * successful run whose malformed proof claimed an early start ranked under
806
+ * an older pass, whether that pass was ordered by its proof or at its
807
+ * `started_at`, and the gate reused the older pass where the CLI, which
808
+ * drops that payload and ranks the run at its `started_at`, refused. With
809
+ * it, whether a pass may be reused never consults another run's proof
810
+ * fields, only when each other run was posted, which GitHub records. Those
811
+ * fields can only cause a refusal; they never hide a veto. The pass's own
812
+ * clock is capped at its post, so it can only count against that pass.
813
+ * - Two changes on valid input follow, and both only add refusals, each
814
+ * costing one hosted run in a rare case. A failure carrying a proof is
815
+ * ordered when it was posted instead of when it started, so an older failure
816
+ * that finished after a newer pass began now refuses reuse. Two pass
817
+ * generations whose verifications overlapped now refuse, as does an older
818
+ * pass re-posted after a newer pass started. Passes that ran one after the
819
+ * other, and a pass with its own re-posts, are reused as before.
820
+ * - The hosted gate's trust boundary is a class. This reader does not
821
+ * reimplement the CLI's payload parser. On payloads the factory's writer
822
+ * emits, both readers select the same pass or both refuse: the differential
823
+ * suite, `software-factory/src/pr-verify-reuse-differential.test.ts`,
824
+ * asserts it over 10,561 generated run sets. On App-signed text the writer
825
+ * never emits, the two can differ in either direction. The known instances
826
+ * where this gate reuses and the CLI refuses are: (a) a reused run whose
827
+ * typed proof fails `validatePrVerifyProof`; (b) a newest pass that repeats
828
+ * another run's verdict only once the CLI normalizes that run's payload, say
829
+ * by dropping a key, since the CLI compares normalized payloads and this
830
+ * reader raw ones; (c) a payload in `output.summary` beside a text payload
831
+ * the CLI cannot read, which the CLI reads from the summary and this reader
832
+ * from the text; (d) text that this reader's strip-and-`fromjson` reads and
833
+ * the CLI's fence match or `JSON.parse` refuses, such as a closing fence
834
+ * with no opening one, a doubled opening fence, a fence line inside the
835
+ * JSON, a payload split across two fenced blocks, or a number literal such
836
+ * as `NaN` where the jq in use accepts it (jq 1.8 does). Mirroring any of it
837
+ * would turn this reader into a parser. Only the factory App can post the
838
+ * run, and that identity bounds the whole class (#1511).
839
+ * - A run not ordered by a typed proof carries no generation identity, so it
840
+ * is never grouped. Two separate executions with the same command names and
841
+ * verdict post the same compact binding, and so does a re-post. When the
842
+ * newest generation is one of these and repeats another run's verdict
843
+ * (binding, status and conclusion), it could be a re-post of an older
844
+ * verdict or a new one, so it is `ambiguous`. Proofs that size are rare;
845
+ * refusing costs a hosted run.
846
+ *
847
+ * Two different generations that share the newest instant are `ambiguous`
848
+ * rather than arbitrarily resolved: the gate cannot tell which one describes
849
+ * the tree, and silently picking either is exactly the kind of coin-flip
850
+ * authorization this whole mechanism exists to remove.
851
+ *
852
+ * Every instant is a whole epoch second, rounded down. A `started_at` keeps
853
+ * its whole second, so `…:00Z` and `…:00.500Z` compare equal. A proof's start
854
+ * is `floor((endedAt - durationMs) / 1000)` with `endedAt` in epoch
855
+ * milliseconds, its fraction read to the millisecond the way `Date.parse`
856
+ * reads it. Rounding down is monotonic, so it can merge two instants into a
857
+ * tie, which is `ambiguous`, but never invert them. It also fails closed: a
858
+ * proof's start never moves later, so it never outranks an unbound run in the
859
+ * same second. The TypeScript reader rounds the same way, so the two agree on
860
+ * every canonical instant. Two genuine verification generations within the
861
+ * same second at the same head is not a real state.
862
+ *
863
+ * `fromdateiso8601` reads only canonical UTC, and the gate never asks it to
864
+ * read anything else. Every candidate must carry a canonical UTC
865
+ * `started_at`, and one that does not makes the newest generation
866
+ * unestablishable, which is `ambiguous`. A typed proof whose `endedAt` is not
867
+ * canonical UTC, or whose `durationMs` is missing or not a finite non-negative
868
+ * number, records no start, and its run falls back to `started_at` like any
869
+ * other run without a typed proof. Refusing costs a hosted run; ranking an
870
+ * unorderable set could authorize the wrong one.
871
+ */
872
+ const GATE_JQ = String.raw`
873
+ def binding:
874
+ [ .output.text, .output.summary ]
875
+ | map(select(type == "string"))
876
+ | map(. as $text
877
+ | (split("\n") | map(select(startswith("${"```"}") | not)) | join("\n")
878
+ | try fromjson catch null)
879
+ | select(type == "object")
880
+ | if ($text | utf8bytelength) > ${TRANSPORT_CAP_BYTES}
881
+ then del(.verificationProof)
882
+ else .
883
+ end)
884
+ | .[0];
885
+
886
+ def resolvedMode:
887
+ IN(${RESOLVED_VERIFY_MODES.map((mode) => JSON.stringify(mode)).join(", ")});
888
+
889
+ def startedAt: (.started_at // "") | tostring;
890
+
891
+ def rankable:
892
+ test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z$");
893
+
894
+ def wholeSecond: sub("\\.[0-9]+Z$"; "Z");
895
+
896
+ def epochSecond:
897
+ if type == "string" and rankable
898
+ then (try (wholeSecond | fromdateiso8601) catch null)
899
+ else null
900
+ end;
901
+
902
+ def millisecondPart:
903
+ ((capture("\\.(?<digits>[0-9]+)Z$") | .digits) // "") + "000"
904
+ | .[0:3]
905
+ | tonumber;
906
+
907
+ def bound:
908
+ (.binding | type) == "object"
909
+ and .binding.kind == "pr-verify-proof-binding"
910
+ and .binding.schemaVersion == 1
911
+ and .binding.headSha == $sha
912
+ and .binding.repository == $repository
913
+ and (.binding.mode | resolvedMode);
914
+
915
+ def passing:
916
+ .status == "completed"
917
+ and .conclusion == "success"
918
+ and bound
919
+ and .binding.outcome == "passed";
920
+
921
+ def proofStart:
922
+ if bound and (.binding.verificationProof | type) == "object" then
923
+ .binding.verificationProof as $proof
924
+ | ($proof.endedAt | epochSecond) as $ended
925
+ | $proof.durationMs as $duration
926
+ | if $ended != null
927
+ and ($duration | type) == "number"
928
+ and ($duration | isinfinite | not)
929
+ and $duration >= 0
930
+ then ($ended * 1000 + ($proof.endedAt | millisecondPart) - $duration)
931
+ / 1000
932
+ | floor
933
+ else null
934
+ end
935
+ else null
936
+ end;
937
+
938
+ def sameVerdict($other):
939
+ bound
940
+ and .status == $other.status
941
+ and .conclusion == $other.conclusion
942
+ and .binding == $other.binding;
943
+
944
+ def ownGeneration($generation):
945
+ if $generation.recorded
946
+ then .recorded and sameVerdict($generation)
947
+ else .index == $generation.index
948
+ end;
949
+
950
+ def nonemptyString:
951
+ type == "string" and length > 0;
952
+
953
+ def distinctNames:
954
+ (map(.name) | length) == (map(.name) | unique | length);
955
+
956
+ def releaseAuthorized($release; $commands; $stamp):
957
+ ([ $commands[] | select(.name == $release.name) ]) as $commandRows
958
+ | ([ $stamp.targets[] | select(.name == $release.impactTarget) ]) as $targetRows
959
+ | ($commandRows | length) == 1
960
+ and $commandRows[0].impactTarget == $release.impactTarget
961
+ and ($targetRows | length) == 1
962
+ and $targetRows[0].impact == "not-affected";
963
+
964
+ [ .[]
965
+ | (.check_runs // [])[]
966
+ | select(.name == $name)
967
+ | select(((.app.id // "") | tostring) == $app)
968
+ | { started: startedAt,
969
+ status: (.status // ""),
970
+ conclusion: (.conclusion // ""),
971
+ url: ((.html_url // "") | tostring),
972
+ binding: binding }
973
+ ] as $runs
974
+ | ($runs | map(.started | epochSecond != null) | all) as $orderable
975
+ | [ range(0; $runs | length) as $index
976
+ | $runs[$index]
977
+ | (.started | epochSecond) as $posted
978
+ | (if passing then proofStart else null end) as $start
979
+ | . + { at: ([$start, $posted] | map(select(. != null)) | min),
980
+ index: $index,
981
+ recorded: ($start != null) }
982
+ ] as $observed
983
+ | ( [ $observed[] | select(.recorded | not) ]
984
+ + ( [ $observed[] | select(.recorded) ]
985
+ | group_by([.status, .conclusion, .binding])
986
+ | map(.[0] + { at: (map(.at) | min) }) ) ) as $generations
987
+ | ($generations | map(.at) | max) as $newest
988
+ | [ $generations[] | select(.at == $newest) ] as $generation
989
+ | (if ($runs | length) == 0 then ["none", "", "", ""]
990
+ elif ($orderable | not) then ["ambiguous", "", "", ""]
991
+ elif ($generation | length) != 1 then ["ambiguous", "", "", ""]
992
+ elif ($generation[0] as $newestRun
993
+ | ($newestRun.recorded | not)
994
+ and ([ $runs[] | select(sameVerdict($newestRun)) ] | length) > 1)
995
+ then ["ambiguous", "", "", ""]
996
+ elif ($generation[0] as $newestRun
997
+ | ($newestRun | passing)
998
+ and ($newestRun.recorded | not)
999
+ and ($runs | length) > 1)
1000
+ then ["ambiguous", "", "", ""]
1001
+ elif ($generation[0] as $newestRun
1002
+ | ($newestRun | passing)
1003
+ and any($observed[] | select(ownGeneration($newestRun) | not);
1004
+ (.started | epochSecond) >= $newestRun.at))
1005
+ then ["ambiguous", "", "", ""]
1006
+ else
1007
+ $generation[0] as $run
1008
+ | (if ($run.binding | type) == "object" then $run.binding else {} end) as $proof
1009
+ | (($proof.mode // "") | tostring) as $mode
1010
+ | (($proof.executedCommands // []) | map(select(type == "string"))) as $executed
1011
+ | ($proof | has("notRequiredCommands")) as $hasReleases
1012
+ | (if $hasReleases then $proof.notRequiredCommands else [] end) as $releases
1013
+ | ($proof.verificationCommands // null) as $commands
1014
+ | ($proof.impactStamp // null) as $stamp
1015
+ | (if ($hasReleases | not) then true
1016
+ else
1017
+ ($proof.proofSchemaVersion == 4)
1018
+ and ($releases | type) == "array"
1019
+ and ($releases | length) > 0
1020
+ and ($releases | all(.[];
1021
+ type == "object"
1022
+ and (.name | nonemptyString)
1023
+ and (.impactTarget | nonemptyString)
1024
+ and (.basis | nonemptyString)))
1025
+ and ($releases | distinctNames)
1026
+ and ($commands | type) == "array"
1027
+ and ($commands | all(.[];
1028
+ type == "object"
1029
+ and (.name | nonemptyString)
1030
+ and ((has("impactTarget") | not) or (.impactTarget | nonemptyString))))
1031
+ and ($commands | distinctNames)
1032
+ and ($stamp | type) == "object"
1033
+ and ($stamp.stampVersion == ${TRUSTED_IMPACT_STAMP_VERSION})
1034
+ and ($stamp.basis == "target-scoped")
1035
+ and (($stamp.reasons | type) == "array")
1036
+ and ($stamp.reasons | all(.[]; type == "string"))
1037
+ and (($stamp.unsubscribedPaths | type) == "array")
1038
+ and ($stamp.unsubscribedPaths | all(.[]; type == "string"))
1039
+ and (($stamp.targets | type) == "array")
1040
+ and ($stamp.targets | all(.[];
1041
+ type == "object"
1042
+ and (.name | nonemptyString)
1043
+ and (.basis | nonemptyString)
1044
+ and ((.impact == "affected") or (.impact == "not-affected"))
1045
+ and ((.subscribedPaths | type) == "array")
1046
+ and (.subscribedPaths | all(.[]; type == "string"))))
1047
+ and ($stamp.targets | distinctNames)
1048
+ and (([$releases[].name] - $executed | length) == ($releases | length))
1049
+ and ($releases | all(.[]; releaseAuthorized(.; $commands; $stamp)))
1050
+ end) as $releasesValid
1051
+ | (if $releasesValid and $creditReleases
1052
+ then [$releases[].name]
1053
+ else []
1054
+ end) as $released
1055
+ | ($creditReleases or ($proof.runScope == "whole-tree")) as $wholeTree
1056
+ | ( ($required - $executed - $released)
1057
+ + (if $wholeTree then [] else ["whole-tree run"] end) ) as $missing
1058
+ | (if $run.status != "completed" then "pending"
1059
+ elif $run.conclusion != "success" then "failed"
1060
+ elif ($run | bound | not) then "unreadable"
1061
+ elif $proof.outcome != "passed" then "failed"
1062
+ elif ($required | length) == 0 then "incomplete"
1063
+ elif ($releasesValid | not) then "incomplete"
1064
+ elif ($missing | length) != 0 then "incomplete"
1065
+ else "proven"
1066
+ end) as $reason
1067
+ | [$reason, $mode, ($missing | join(", ")), $run.url]
1068
+ end)
1069
+ | map(gsub("[\\r\\n\\t]"; " "))
1070
+ | join("\n")
1071
+ `.trim();
1072
+ const CORRECTIVE_LINE = "Run `psf pr:verify` before publishing to reuse local proof and avoid a duplicate server run.";
1073
+ /**
1074
+ * Emitted when a consumer's command selection is unusable. Mirrors the
1075
+ * retired hosted docs-only detector: a malformed profile slice degrades to the
1076
+ * conservative answer at *runtime* rather than throwing at generation time,
1077
+ * because the input is JSON that may be absent or reshaped. The loud signal is
1078
+ * the static coverage assertion, plus `reason=error` on the step output.
1079
+ */
1080
+ const UNUSABLE_SELECTION_SCRIPT = String.raw`{
1081
+ printf '${FACTORY_PROOF_GATE_OUTPUT}=false\n'
1082
+ printf '${FACTORY_PROOF_GATE_REASON_OUTPUT}=error\n'
1083
+ } >> "${shellExpansion$1("GITHUB_OUTPUT:-/dev/null")}"`;
1084
+ /** Surface labels reach markdown, so only a plain, bounded label survives. */
1085
+ const safeLabel$1 = (surface) => {
1086
+ const cleaned = (typeof surface === "string" ? surface : "").replaceAll(/[^\w -]/gu, "").trim().slice(0, 60);
1087
+ return cleaned.length > 0 ? cleaned : "verification";
1088
+ };
1089
+ /**
1090
+ * The push-event merge fallback (#611, restored with executed-only coverage
1091
+ * by #1658). Emitted into every gate script; on a pull request event it is
1092
+ * inert.
1093
+ */
1094
+ const MERGE_FALLBACK_BLOCK = String.raw`# Merge fallback (#611, #1658). A squash merge mints a new commit, so the
1095
+ # direct read at a pushed merge-target head finds nothing even when the
1096
+ # factory proved the producing pull request head. Only when the direct read
1097
+ # found no generation at all on a push event, look up the producing pull
1098
+ # request and reuse its head proof, and only when:
1099
+ #
1100
+ # - the merge commit's TREE id equals the proven head's tree id, which makes
1101
+ # the pushed content byte-identical to what was verified. That is a clean
1102
+ # squash of a head that already contained the previous default-branch tip.
1103
+ # Patch identity was considered and rejected as the comparator: git
1104
+ # patch-id normalizes whitespace and ignores base motion, so an identical
1105
+ # patch can still produce an integrated tree that was never tested. Tree
1106
+ # identity also makes "no other merge landed in between" unnecessary to
1107
+ # check separately: if one had, the trees would differ.
1108
+ # - the proof EXECUTED every command this surface requires, in a run that
1109
+ # handed every command the whole tree (runScope "whole-tree"). Impact-stamp
1110
+ # releases are not credited here (gate_lookup ... false), and neither is a
1111
+ # diff-scoped run, whose commands may have scoped themselves to the diff:
1112
+ # both are weaker than the whole tree a merge target is owed (#931).
1113
+ #
1114
+ # Everything else -- no unique merged producing PR, an unreadable commit, a
1115
+ # proof that is anything but proven, an executed set that does not cover the
1116
+ # surface, or tree drift from a dirty or stale merge -- leaves the direct
1117
+ # "none" refusal standing, so the full suite runs (fail open).
1118
+ if [ "$reason" = 'none' ] && [ "${shellExpansion$1("GITHUB_EVENT_NAME:-")}" = 'push' ]; then
1119
+ producing_head=''
1120
+ producing_number=''
1121
+ producing_row=''
1122
+ merge_tree=''
1123
+ head_tree=''
1124
+ if ! producing_pulls=$(gh api --method GET --paginate \
1125
+ "repos/$GITHUB_REPOSITORY/commits/$HEAD_SHA/pulls" \
1126
+ -f per_page=100 2>&1); then
1127
+ detail="producing pull request unreadable: $producing_pulls"
1128
+ elif ! producing_row=$(jq -r -s \
1129
+ --arg sha "$HEAD_SHA" \
1130
+ '[ add[]?
1131
+ | select((.merged_at // null) != null)
1132
+ | select((.merge_commit_sha // "") == $sha)
1133
+ | [((.head.sha // "") | tostring), ((.number // "") | tostring)]
1134
+ | join(" ") ]
1135
+ | if length == 1 then .[0] else "" end' 2>&1 <<< "$producing_pulls"); then
1136
+ detail="producing pull request unreadable: $producing_row"
1137
+ producing_row=''
1138
+ fi
1139
+ if [ -n "$producing_row" ]; then
1140
+ read -r producing_head producing_number <<< "$producing_row" || :
1141
+ fi
1142
+ if [ -n "$detail" ]; then
1143
+ :
1144
+ elif ! [[ "$producing_head" =~ ^[0-9a-f]{40}$ ]] \
1145
+ || ! [[ "$producing_number" =~ ^[0-9]+$ ]]; then
1146
+ detail='no single merged producing pull request at this commit'
1147
+ producing_head=''
1148
+ elif ! merge_commit=$(gh api --method GET \
1149
+ "repos/$GITHUB_REPOSITORY/commits/$HEAD_SHA" 2>&1); then
1150
+ detail="merge commit unreadable: $merge_commit"
1151
+ elif ! merge_tree=$(jq -r \
1152
+ '(.commit.tree.sha // "") | tostring' 2>&1 <<< "$merge_commit"); then
1153
+ detail="merge commit unreadable: $merge_tree"
1154
+ merge_tree=''
1155
+ elif ! [[ "$merge_tree" =~ ^[0-9a-f]{40}$ ]]; then
1156
+ detail='merge commit carries no readable tree id'
1157
+ merge_tree=''
1158
+ elif ! head_commit=$(gh api --method GET \
1159
+ "repos/$GITHUB_REPOSITORY/commits/$producing_head" 2>&1); then
1160
+ detail="producing head commit unreadable: $head_commit"
1161
+ elif ! head_tree=$(jq -r \
1162
+ '(.commit.tree.sha // "") | tostring' 2>&1 <<< "$head_commit"); then
1163
+ detail="producing head commit unreadable: $head_tree"
1164
+ head_tree=''
1165
+ elif ! [[ "$head_tree" =~ ^[0-9a-f]{40}$ ]]; then
1166
+ detail='producing head commit carries no readable tree id'
1167
+ head_tree=''
1168
+ elif [ "$merge_tree" != "$head_tree" ]; then
1169
+ detail="tree drift: the merge result is not the tree proven at pull request #$producing_number head $producing_head"
1170
+ merge_tree=''
1171
+ fi
1172
+ if [ -z "$detail" ] \
1173
+ && [[ "$producing_head" =~ ^[0-9a-f]{40}$ ]] \
1174
+ && [[ "$merge_tree" =~ ^[0-9a-f]{40}$ ]] \
1175
+ && [ "$merge_tree" = "$head_tree" ]; then
1176
+ gate_lookup "$producing_head" false
1177
+ if [ "$lookup_reason" = 'proven' ]; then
1178
+ reason=proven
1179
+ mode="$lookup_mode"
1180
+ missing=''
1181
+ source_url="$lookup_url"
1182
+ proof_head="$producing_head"
1183
+ merge_note="pull request #$producing_number. The merge result's tree \`$merge_tree\` is byte-identical to the tree proven at its head \`$producing_head\`, and that proof's whole-tree run executed every command this surface requires"
1184
+ elif [ "$lookup_reason" = 'incomplete' ]; then
1185
+ detail="producing pull request #$producing_number proof not reusable (incomplete: a merge target counts only the commands a whole-tree run executed; missing: $lookup_missing)"
1186
+ else
1187
+ detail="producing pull request #$producing_number proof not reusable ($lookup_reason) $lookup_detail"
1188
+ fi
1189
+ fi
1190
+ fi`;
1191
+ const gateScript = (required, surface) => String.raw`
1192
+ set -uo pipefail
1193
+
1194
+ CHECK_NAME=${shellSingleQuote(FACTORY_PROOF_GATE_CHECK_NAME)}
1195
+ FACTORY_APP_ID=${shellSingleQuote(FACTORY_PROOF_GATE_APP_ID)}
1196
+ REQUIRED_COMMANDS=${shellSingleQuote(JSON.stringify(required))}
1197
+ SURFACE=${shellSingleQuote(surface)}
1198
+
1199
+ reason=error
1200
+ detail=''
1201
+ mode=''
1202
+ missing=''
1203
+ source_url=''
1204
+ proof_head=''
1205
+ merge_note=''
1206
+
1207
+ # One proof lookup at one commit. Sets lookup_reason / lookup_mode /
1208
+ # lookup_missing / lookup_url, or lookup_detail when the read itself
1209
+ # failed. Always returns 0: every caller must reach the single
1210
+ # GITHUB_OUTPUT write below whatever this function meets.
1211
+ #
1212
+ # $2 is whether impact-stamp releases may cover a required command: 'true'
1213
+ # on a pull request, 'false' on any push, where only executed commands count
1214
+ # because a merge target is owed the whole tree (#931, #1658). Anything but
1215
+ # 'true' is false.
1216
+ #
1217
+ # filter=all with full pagination is load-bearing (ADR 0022). GitHub's
1218
+ # default "latest" filter is ordered by completion, so a newer generation
1219
+ # that is still running can be hidden behind an older completed one — the
1220
+ # gate would then read a stale pass as current.
1221
+ gate_lookup() {
1222
+ lookup_reason=error
1223
+ lookup_mode=''
1224
+ lookup_missing=''
1225
+ lookup_url=''
1226
+ lookup_detail=''
1227
+ lookup_credit=false
1228
+ if [ "${shellExpansion$1("2:-")}" = 'true' ]; then
1229
+ lookup_credit=true
1230
+ fi
1231
+ if ! lookup_response=$(gh api --method GET --paginate \
1232
+ "repos/$GITHUB_REPOSITORY/commits/$1/check-runs" \
1233
+ -f "check_name=$CHECK_NAME" \
1234
+ -f filter=all \
1235
+ -f per_page=100 2>&1); then
1236
+ lookup_detail="checks API unreadable: $lookup_response"
1237
+ return 0
1238
+ fi
1239
+ # A herestring, not printf piped into jq: the lookup starts jq alone,
1240
+ # with no pipeline around it (#1096).
1241
+ if ! lookup_finding=$(jq -r -s \
1242
+ --arg name "$CHECK_NAME" \
1243
+ --arg app "$FACTORY_APP_ID" \
1244
+ --arg sha "$1" \
1245
+ --arg repository "$GITHUB_REPOSITORY" \
1246
+ --argjson required "$REQUIRED_COMMANDS" \
1247
+ --argjson creditReleases "$lookup_credit" \
1248
+ '${GATE_JQ}' 2>&1 <<< "$lookup_response"); then
1249
+ lookup_detail="unreadable proof binding: $lookup_finding"
1250
+ return 0
1251
+ fi
1252
+ # Four separate reads, not one IFS split: tab is IFS whitespace, so a
1253
+ # split would collapse the empty fields the vocabulary relies on.
1254
+ #
1255
+ # The trailing "|| :" on each read is load-bearing. "missing" is empty for
1256
+ # every verdict except "incomplete", so jq's third field is the empty
1257
+ # string, command substitution strips the trailing newline, and the third
1258
+ # read reaches EOF -- having correctly assigned "" -- and returns 1. Under
1259
+ # an errexit shell that return value kills the step before the single
1260
+ # GITHUB_OUTPUT write below, which is exactly how this gate failed in
1261
+ # hosted CI on every decidable verdict while every test passed (#319).
1262
+ {
1263
+ IFS= read -r lookup_reason || :
1264
+ IFS= read -r lookup_mode || :
1265
+ IFS= read -r lookup_missing || :
1266
+ IFS= read -r lookup_url || :
1267
+ } <<< "$lookup_finding"
1268
+ case "$lookup_reason" in
1269
+ proven | none | pending | failed | unreadable | incomplete | ambiguous) ;;
1270
+ *)
1271
+ lookup_detail="unexpected gate result: $lookup_reason"
1272
+ lookup_reason=error
1273
+ ;;
1274
+ esac
1275
+ return 0
1276
+ }
1277
+
1278
+ if [ -z "${shellExpansion$1("HEAD_SHA:-")}" ]; then
1279
+ detail='no verification head SHA'
1280
+ elif [ -z "${shellExpansion$1("GITHUB_REPOSITORY:-")}" ]; then
1281
+ detail='no repository name'
1282
+ else
1283
+ # A push is a merge target even when the pushed tip is a candidate's own
1284
+ # head (a fast-forward), so it credits executed commands only there too.
1285
+ direct_credit=true
1286
+ if [ "${shellExpansion$1("GITHUB_EVENT_NAME:-")}" = 'push' ]; then
1287
+ direct_credit=false
1288
+ fi
1289
+ gate_lookup "$HEAD_SHA" "$direct_credit"
1290
+ reason="$lookup_reason"
1291
+ detail="$lookup_detail"
1292
+ mode="$lookup_mode"
1293
+ missing="$lookup_missing"
1294
+ source_url="$lookup_url"
1295
+ if [ "$reason" = 'proven' ]; then
1296
+ proof_head="$HEAD_SHA"
1297
+ fi
1298
+ fi
1299
+
1300
+ ${MERGE_FALLBACK_BLOCK}
1301
+
1302
+ # The binding is App-verified, but it still reaches markdown. Only a plain
1303
+ # lowercase token is quoted back; anything else is reported as unknown.
1304
+ case "$mode" in
1305
+ '') ;;
1306
+ *[!a-z-]*) mode='unknown' ;;
1307
+ esac
1308
+
1309
+ verdict=false
1310
+ if [ "$reason" = 'proven' ]; then
1311
+ verdict=true
1312
+ else
1313
+ proof_head=''
1314
+ fi
1315
+
1316
+ # detail can carry arbitrary gh or jq error text. Collapse it to one bounded
1317
+ # line so it cannot restructure the summary it is written into. Builtin
1318
+ # expansions, not printf | tr | cut: each process the script starts waits for
1319
+ # a CPU on a loaded machine, and these two pipelines were most of the
1320
+ # processes every gate run started (#1096).
1321
+ detail=${shellExpansion$1(String.raw`detail//[$'\n\r\t']/ `)}
1322
+ detail=${shellExpansion$1("detail:0:240")}
1323
+ missing=${shellExpansion$1(String.raw`missing//[$'\n\r\t']/ `)}
1324
+ missing=${shellExpansion$1("missing:0:240")}
1325
+ if ! [[ "$source_url" =~ ^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/runs/[0-9]+$ ]]; then
1326
+ source_url=''
1327
+ fi
1328
+
1329
+ SUMMARY="${shellExpansion$1("GITHUB_STEP_SUMMARY:-/dev/null")}"
1330
+ say() { printf '%s\n' "$1" >> "$SUMMARY"; }
1331
+
1332
+ say "## Proof reuse: $SURFACE"
1333
+ say ''
1334
+
1335
+ case "$reason" in
1336
+ proven)
1337
+ echo "Factory proof: reusing local verification of $proof_head; skipping the $SURFACE suite."
1338
+ say "Skipped. The factory already verified this exact content, so this job did not run the $SURFACE suite a second time."
1339
+ say ''
1340
+ if [ -n "$source_url" ]; then
1341
+ say "- Reused proof: [\`$CHECK_NAME\`]($source_url), published by the pinned factory GitHub App."
1342
+ else
1343
+ say "- Reused proof: the \`$CHECK_NAME\` check run published by the pinned factory GitHub App."
1344
+ fi
1345
+ say "- Covers head: \`$proof_head\`"
1346
+ if [ -n "$merge_note" ]; then
1347
+ say "- Merge-target reuse: $merge_note."
1348
+ fi
1349
+ say "- Recorded mode: \`$mode\` (diagnostic only), outcome \`passed\`."
1350
+ ;;
1351
+ none)
1352
+ say 'Ran the full suite. No trusted factory proof covers this commit.'
1353
+ say ''
1354
+ say "The factory GitHub App has published no \`$CHECK_NAME\` check run at head \`$HEAD_SHA\`. Proof is keyed to the commit, so proof written for any other commit is not visible here. A pull request opened by hand carries no factory proof at all, which is normal."
1355
+ if [ -n "$detail" ]; then
1356
+ say ''
1357
+ say "- Merge fallback: $detail"
1358
+ fi
1359
+ say ''
1360
+ say '${CORRECTIVE_LINE}'
1361
+ ;;
1362
+ pending)
1363
+ say 'Ran the full suite. The factory proof for this commit had not finished when this job read it.'
1364
+ say ''
1365
+ say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` was still in progress. The gate reads one snapshot at job start and does not wait."
1366
+ say ''
1367
+ say "Let \`psf pr:verify\` finish before publishing, so its proof is on the commit before this job reads it."
1368
+ ;;
1369
+ failed)
1370
+ say 'Ran the full suite. The factory proof for this commit records no pass.'
1371
+ say ''
1372
+ say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` finished without a passing conclusion, so it establishes nothing about this tree."
1373
+ say ''
1374
+ say '${CORRECTIVE_LINE}'
1375
+ ;;
1376
+ unreadable)
1377
+ say 'Ran the full suite. The factory check run for this commit carries no proof this job can read.'
1378
+ say ''
1379
+ say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` passed, but it carries no machine-readable binding naming this repository and this head, or one written to a schema this job does not recognize."
1380
+ say ''
1381
+ say '${CORRECTIVE_LINE}'
1382
+ ;;
1383
+ incomplete)
1384
+ say "Ran the full suite. The factory proof for this commit does not cover every command the $SURFACE surface requires."
1385
+ say ''
1386
+ if [ "${shellExpansion$1("GITHUB_EVENT_NAME:-")}" = 'push' ]; then
1387
+ say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` passed, but a merge target counts only the commands a whole-tree run executed, and those do not cover this surface. Missing: \`$missing\`"
1388
+ else
1389
+ say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` passed, but its executed commands plus stamp-authorized \`notRequiredCommands\` do not cover this surface. Missing: \`$missing\`"
1390
+ fi
1391
+ say ''
1392
+ say '${CORRECTIVE_LINE}'
1393
+ ;;
1394
+ ambiguous)
1395
+ say 'Ran the full suite. The newest factory proof for this commit is ambiguous.'
1396
+ say ''
1397
+ say "Two different \`$CHECK_NAME\` proofs at head \`$HEAD_SHA\` share the newest generation, the newest repeats an earlier run's verdict with no proof time to tell them apart, a run's start time cannot be ranked, the newest pass records no verification start beside another run at this head, or the newest pass started before another run at this head was posted, so there is no single newest generation to trust. The gate refuses rather than picking one."
1398
+ say ''
1399
+ say '${CORRECTIVE_LINE}'
1400
+ ;;
1401
+ *)
1402
+ say 'Ran the full suite. The proof gate could not reach a decision.'
1403
+ say ''
1404
+ say 'The gate fails open by design: when it cannot tell whether proof exists, every command runs. Nothing about this pull request is implied.'
1405
+ say ''
1406
+ say " $detail"
1407
+ ;;
1408
+ esac
1409
+ say ''
1410
+
1411
+ if [ "$verdict" != 'true' ]; then
1412
+ echo "No reusable factory proof for ${shellExpansion$1("HEAD_SHA:-<unknown>")}; running the $SURFACE suite ($reason). $detail"
1413
+ fi
1414
+
1415
+ # The only write. A crash before this line leaves the output unset, the guard
1416
+ # reads empty, and every guarded step runs — the fail-open path.
1417
+ {
1418
+ printf '${FACTORY_PROOF_GATE_OUTPUT}=%s\n' "$verdict"
1419
+ printf '${FACTORY_PROOF_GATE_REASON_OUTPUT}=%s\n' "$reason"
1420
+ printf '${FACTORY_PROOF_GATE_MODE_OUTPUT}=%s\n' "$mode"
1421
+ printf '${FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT}=%s\n' "$source_url"
1422
+ printf '${FACTORY_PROOF_GATE_SOURCE_HEAD_OUTPUT}=%s\n' "$proof_head"
1423
+ } >> "${shellExpansion$1("GITHUB_OUTPUT:-/dev/null")}"
1424
+ `.trim();
1425
+ /**
1426
+ * The gate script. Exported so it can be executed directly under test against
1427
+ * a stubbed `gh`, rather than only asserted against as workflow text — the
1428
+ * script is the security boundary, and asserting on generated YAML would leave
1429
+ * its actual decisions untested.
1430
+ *
1431
+ * Note the deliberate absence of `set -e`: every failure path has to reach the
1432
+ * final write, and that write must emit `false`. Omitting it is necessary but
1433
+ * not sufficient — the runner supplies `-e` unless the step declares
1434
+ * `FACTORY_PROOF_GATE_SHELL` — so the script is also written to reach that
1435
+ * write under errexit, and the tests execute it both ways.
1436
+ */
1437
+ const factoryProofGateScript = ({ commands, surface }) => {
1438
+ const required = proofReuseRequiredCommands(commands);
1439
+ return required ? gateScript(required, safeLabel$1(surface)) : UNUSABLE_SELECTION_SCRIPT;
1440
+ };
1441
+ /**
1442
+ * The step itself, structurally accepted by gagen's `step()` without adding a
1443
+ * gagen runtime dependency. It belongs first in the job it guards: a few API
1444
+ * reads with the default `GITHUB_TOKEN`, no checkout, no install, so a proven
1445
+ * head costs a runner nothing beyond job startup. A pull request read needs
1446
+ * only `checks: read`. The merge fallback on a default-branch push also reads
1447
+ * the producing pull request (`pull-requests: read`) and the two commit
1448
+ * objects whose tree ids it compares (`contents: read`). A job that grants
1449
+ * less loses only the fallback: the failed read degrades to the full suite.
1450
+ *
1451
+ * A **step, not a job**, and that is not a style preference. A separate gate
1452
+ * job that errored would leave the guarded job `skipped`, and a summary job
1453
+ * that only fails on `failure`/`cancelled` would still report green — a Checks
1454
+ * API outage would silently skip verification. As a step it fails open by
1455
+ * construction: the step errors, the output is never written, the guard reads
1456
+ * empty, and every command runs.
1457
+ */
1458
+ const factoryProofGateStep = (options) => Object.freeze({
1459
+ continueOnError: true,
1460
+ env: Object.freeze({
1461
+ GH_TOKEN: githubExpression$1("secrets.GITHUB_TOKEN"),
1462
+ HEAD_SHA: githubExpression$1("github.event.pull_request.head.sha || github.sha")
1463
+ }),
1464
+ id: FACTORY_PROOF_GATE_STEP_ID,
1465
+ if: FACTORY_PROOF_GATE_IF,
1466
+ name: FACTORY_PROOF_GATE_STEP_NAME,
1467
+ run: factoryProofGateScript(options),
1468
+ shell: FACTORY_PROOF_GATE_SHELL
1469
+ });
1470
+ /**
1471
+ * The static coverage assertion, as a report.
1472
+ *
1473
+ * Runtime command coverage is authoritative — the gate's `incomplete` refusal
1474
+ * is the backstop that cannot be bypassed. This is the compile-time guard in
1475
+ * front of it: it fails a consumer's build the moment a workflow skips work
1476
+ * that no selected profile command runs, rather than letting the drift show up
1477
+ * as CI quietly verifying nothing. The drift is real history: #227 wired a
1478
+ * workspace member into CI while the profile never learned about it.
1479
+ */
1480
+ const proofReuseCoverage = ({ commands, skipped }) => {
1481
+ const requiredCommands = proofReuseRequiredCommands(commands) ?? [];
1482
+ const proven = new Set(requiredCommands.length > 0 ? commands.map(({ command }) => command.trim()) : []);
1483
+ const uncovered = [...new Set((Array.isArray(skipped) ? skipped : []).map((command) => String(command).trim()).filter((command) => command.length > 0 && !proven.has(command)))].toSorted();
1484
+ return Object.freeze({
1485
+ covered: requiredCommands.length > 0 && uncovered.length === 0,
1486
+ requiredCommands,
1487
+ uncovered
1488
+ });
1489
+ };
1490
+ /** `proofReuseCoverage`, as a build failure. */
1491
+ const assertProofReuseCoverage = (input) => {
1492
+ const report = proofReuseCoverage(input);
1493
+ if (report.covered) return report;
1494
+ const surface = safeLabel$1(input.surface ?? "");
1495
+ const problem = report.requiredCommands.length === 0 ? "selects no usable profile commands, so any passing proof would trivially cover it" : `skips work no selected profile command runs: ${report.uncovered.join(", ")}`;
1496
+ throw new Error(`Proof-reuse coverage failed: the ${surface} surface ${problem}. Add the command to software-factory.profile.json (and to this surface's selection), or stop skipping it.`);
1497
+ };
1498
+ /**
1499
+ * Hosted preview-proof inventory (#639): persist and list Factory-App
1500
+ * registrations, and record cleanup outcomes, without PR comments.
1501
+ *
1502
+ * `list` is a read over App-owned commit check-runs and works with a workflow
1503
+ * `GITHUB_TOKEN`. `persist` and `recordCleanup` write those check-runs, which
1504
+ * GitHub only allows the producing App to update. Pass an installation token
1505
+ * the caller minted; this package does not read operator config or hold
1506
+ * secrets. Cleanup writes go through `previewProofLifecycle.transition` with
1507
+ * `{ type: "cleanup" }`. Outcomes are never inferred from whether a stage
1508
+ * still exists.
1509
+ *
1510
+ * Transient transport failures are retried with bounded backoff and then
1511
+ * surface as `PreviewProofTransportError` (#830). A failure from `persist` or
1512
+ * `recordCleanup` is an evidence-registration failure, never a failed
1513
+ * deployment: the caller retains the healthy disposable stage, records its own
1514
+ * proof BLOCKED (never PASS), and re-runs registration at the same head —
1515
+ * writes are keyed by stack and stage, so resuming needs no redeploy.
1516
+ * Admission stays fail-closed on its own: an unregistered proof never
1517
+ * satisfies the preview demand.
1518
+ */
1519
+ /** Check-run name that carries one registration JSON payload. Not a gate. */
1520
+ const PREVIEW_PROOF_INVENTORY_CHECK_NAME = "patronage-factory/preview-proof";
1521
+ /**
1522
+ * Least privilege for a job whose `GITHUB_TOKEN` calls `list`. A
1523
+ * `permissions` block zeroes every unlisted scope, and `list` reads five
1524
+ * endpoints: `pulls/{pr}`, `pulls/{pr}/commits`, and the GraphQL force-push
1525
+ * timeline (`pull-requests`), `compare` (`contents`), and
1526
+ * `commits/{sha}/check-runs` (`checks`). A job
1527
+ * that omits `pull-requests: read` fails with 403 on a same-repository PR
1528
+ * and skips every destroy matrix (#859). Give the discovery job this object.
1529
+ */
1530
+ const PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS = Object.freeze({
1531
+ checks: "read",
1532
+ contents: "read",
1533
+ "pull-requests": "read"
1534
+ });
1535
+ const INVENTORY_KIND = "patronage-factory-preview-proof";
1536
+ const INVENTORY_SCHEMA_VERSION = 1;
1537
+ const DEFAULT_TIMEOUT_MS$1 = 5e3;
1538
+ const CHECK_RUNS_PER_PAGE = 100;
1539
+ const COMMITS_PER_PAGE = 100;
1540
+ const MAX_CHECK_RUN_PAGES = 10;
1541
+ const MAX_COMMIT_PAGES = 20;
1542
+ /** GitHub's documented hard cap on `GET /pulls/{pr}/commits`. */
1543
+ const GITHUB_PULL_COMMITS_CAP = 250;
1544
+ const FORCE_PUSH_TIMELINE_PER_PAGE = 100;
1545
+ const MAX_FORCE_PUSH_PAGES = 20;
1546
+ const GRAPHQL_FORCE_PUSH_BEFORE = `query PreviewProofForcePushBefore($owner: String!, $name: String!, $pr: Int!, $first: Int!, $cursor: String) {
1547
+ repository(owner: $owner, name: $name) {
1548
+ pullRequest(number: $pr) {
1549
+ timelineItems(itemTypes: [HEAD_REF_FORCE_PUSHED_EVENT], first: $first, after: $cursor) {
1550
+ nodes {
1551
+ ... on HeadRefForcePushedEvent {
1552
+ beforeCommit { oid }
1553
+ }
1554
+ }
1555
+ pageInfo { endCursor hasNextPage }
1556
+ }
1557
+ }
1558
+ }
1559
+ }`;
1560
+ const SHA_PATTERN = /^[0-9a-f]{7,40}$/u;
1561
+ const FULL_SHA_PATTERN$1 = /^[0-9a-f]{40}$/u;
1562
+ const isRecord$2 = (value) => typeof value === "object" && value !== null;
1563
+ const isCleanupStatus = (value) => value === "failed" || value === "passed" || value === "pending";
1564
+ const readStringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value : null;
1565
+ const readIdentity = (value) => {
1566
+ if (typeof value.pr !== "number" || !Number.isInteger(value.pr) || value.pr <= 0 || typeof value.headSha !== "string" || !FULL_SHA_PATTERN$1.test(value.headSha) || typeof value.stack !== "string" || value.stack.length === 0 || typeof value.stage !== "string" || typeof value.url !== "string" || value.url.length === 0) return null;
1567
+ const parsedStage = parseLocalPreviewStage(value.stage, {
1568
+ headSha: value.headSha,
1569
+ pr: value.pr
1570
+ });
1571
+ if (parsedStage === null) return null;
1572
+ return {
1573
+ headSha: value.headSha,
1574
+ pr: value.pr,
1575
+ stack: value.stack,
1576
+ stage: parsedStage.stage,
1577
+ url: value.url
1578
+ };
1579
+ };
1580
+ const readCleanup = (value) => {
1581
+ if (!isRecord$2(value.cleanup) || !isCleanupStatus(value.cleanup.outcome)) return null;
1582
+ const evidence = readStringArray(value.cleanup.evidence);
1583
+ if (evidence === null) return null;
1584
+ return typeof value.cleanup.runUrl === "string" && value.cleanup.runUrl.length > 0 ? {
1585
+ evidence,
1586
+ outcome: value.cleanup.outcome,
1587
+ runUrl: value.cleanup.runUrl
1588
+ } : {
1589
+ evidence,
1590
+ outcome: value.cleanup.outcome
1591
+ };
1592
+ };
1593
+ const readPassingChecks = (value) => {
1594
+ if (!isRecord$2(value.convergence) || !isRecord$2(value.smoke)) return null;
1595
+ if (value.convergence.status !== "passed" || typeof value.convergence.detail !== "string" || value.smoke.outcome !== "passed" || typeof value.smoke.detail !== "string") return null;
1596
+ return {
1597
+ convergence: {
1598
+ detail: value.convergence.detail,
1599
+ status: "passed"
1600
+ },
1601
+ smoke: {
1602
+ detail: value.smoke.detail,
1603
+ outcome: "passed"
1604
+ }
1605
+ };
1606
+ };
1607
+ const readProof = (value, headSha) => {
1608
+ if (!isRecord$2(value.proof)) return null;
1609
+ if (typeof value.proof.check !== "string" || value.proof.check.trim().length === 0 || value.proof.headSha !== headSha || typeof value.proof.mergeBaseSha !== "string" || !SHA_PATTERN.test(value.proof.mergeBaseSha) || typeof value.proof.patchId !== "string" || !SHA_PATTERN.test(value.proof.patchId)) return null;
1610
+ return {
1611
+ check: value.proof.check,
1612
+ headSha: value.proof.headSha,
1613
+ mergeBaseSha: value.proof.mergeBaseSha,
1614
+ patchId: value.proof.patchId
1615
+ };
1616
+ };
1617
+ /**
1618
+ * Rebuild a registration from untrusted JSON. Extra keys (comment ids, seed
1619
+ * fields, stack unions) are dropped. Invalid identity returns `null`.
1620
+ */
1621
+ const readPreviewProofRegistration = (value) => {
1622
+ if (!isRecord$2(value) || value.source !== "local-self-certified") return null;
1623
+ const identity = readIdentity(value);
1624
+ const cleanup = readCleanup(value);
1625
+ const passing = readPassingChecks(value);
1626
+ const proof = identity === null ? null : readProof(value, identity.headSha);
1627
+ if (identity === null || cleanup === null || passing === null || proof === null) return null;
1628
+ return {
1629
+ cleanup,
1630
+ convergence: passing.convergence,
1631
+ headSha: identity.headSha,
1632
+ pr: identity.pr,
1633
+ proof,
1634
+ smoke: passing.smoke,
1635
+ source: "local-self-certified",
1636
+ stack: identity.stack,
1637
+ stage: identity.stage,
1638
+ url: identity.url
1639
+ };
1640
+ };
1641
+ const readInventoryPayload = (value) => {
1642
+ if (!isRecord$2(value) || value.kind !== INVENTORY_KIND || value.schemaVersion !== INVENTORY_SCHEMA_VERSION) return null;
1643
+ return readPreviewProofRegistration(value.registration);
1644
+ };
1645
+ const assertPersistableRegistration = (registration) => {
1646
+ const read = readPreviewProofRegistration(registration);
1647
+ if (read === null) throw new Error("Preview proof inventory cannot persist an invalid registration.");
1648
+ return read;
1649
+ };
1650
+ const registrationKey = (row) => `${row.stack}:${row.stage}`;
1651
+ const replaceRegistration = (rows, next) => [...rows.filter((row) => registrationKey(row) !== registrationKey(next)), next];
1652
+ const memoryKey = (owner, repo, pr) => `${owner}/${repo}#${pr}`;
1653
+ /** Reached by callers as `previewProofInventory.memoryStore`. */
1654
+ const memoryStore = () => {
1655
+ const byPr = /* @__PURE__ */ new Map();
1656
+ return {
1657
+ list: (input) => Promise.resolve([...byPr.get(memoryKey(input.owner, input.repo, input.pr)) ?? []]),
1658
+ put: (input) => {
1659
+ const registration = assertPersistableRegistration(input.registration);
1660
+ const key = memoryKey(input.owner, input.repo, registration.pr);
1661
+ byPr.set(key, replaceRegistration(byPr.get(key) ?? [], registration));
1662
+ return Promise.resolve();
1663
+ }
1664
+ };
1665
+ };
1666
+ /**
1667
+ * The transport gave out — a network-level rejection (EPIPE, DNS, an aborted
1668
+ * or timed-out request) or a transient HTTP status — and bounded retries did
1669
+ * not recover it. GitHub never judged the content, so this is never a
1670
+ * validation verdict and never a deployment failure. Only a bounded reason
1671
+ * string is retained: the raw transport error can hold the request and its
1672
+ * `Authorization` header, so it is deliberately discarded.
1673
+ */
1674
+ var PreviewProofTransportError = class extends Error {
1675
+ /** How many transport attempts were made before giving up. */
1676
+ attempts;
1677
+ /** The last transient HTTP status, when the server answered at all. */
1678
+ status;
1679
+ constructor(reason, attempts, status) {
1680
+ super(`Preview proof inventory transport failed after ${attempts} attempt(s): ${reason}`);
1681
+ this.name = "PreviewProofTransportError";
1682
+ this.attempts = attempts;
1683
+ if (status !== void 0) this.status = status;
1684
+ }
1685
+ };
1686
+ const githubJson = (request, url, token, init, timeoutMs) => githubJson$1({
1687
+ ...init,
1688
+ fetch: request,
1689
+ timeoutMs,
1690
+ token,
1691
+ url
1692
+ }, {
1693
+ refusal: (status, statusText) => new GitHubApiError(status, statusText),
1694
+ transport: (failure, attempts) => new PreviewProofTransportError(failure.reason, attempts, failure.status)
1695
+ });
1696
+ const githubGraphql = async (request, token, timeoutMs, query, variables) => {
1697
+ const served = await githubJson(request, "https://api.github.com/graphql", token, {
1698
+ body: JSON.stringify({
1699
+ query,
1700
+ variables
1701
+ }),
1702
+ method: "POST"
1703
+ }, timeoutMs);
1704
+ if (!isRecord$2(served)) throw new TypeError("GitHub GraphQL response was not an object");
1705
+ if (served.errors !== void 0) {
1706
+ const details = Array.isArray(served.errors) ? served.errors.flatMap((entry) => isRecord$2(entry) ? [[entry.type, entry.message].filter((part) => typeof part === "string").join(": ")] : []).filter((detail) => detail.length > 0).join("; ") : "";
1707
+ throw new Error(details.length > 0 ? `Preview proof inventory GraphQL query failed: ${details}` : "Preview proof inventory GraphQL query failed.");
1708
+ }
1709
+ return served.data;
1710
+ };
1711
+ const repoApi = (owner, repo) => `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
1712
+ const isServedCheckRun = (value) => isRecord$2(value);
1713
+ const producedByFactoryApp = (run) => String(run.app?.id ?? "") === FACTORY_PROOF_GATE_APP_ID;
1714
+ const assertFactoryAppWrite = (value) => {
1715
+ if (!isServedCheckRun(value) || !producedByFactoryApp(value)) throw new Error("Preview proof inventory write must be owned by the Factory App.");
1716
+ return value;
1717
+ };
1718
+ const registrationFromCheckRun = (run, expectedHeadSha) => {
1719
+ if (!producedByFactoryApp(run) || run.name !== "patronage-factory/preview-proof" || typeof run.head_sha !== "string" || !FULL_SHA_PATTERN$1.test(run.head_sha)) return null;
1720
+ const text = run.output?.text;
1721
+ if (typeof text !== "string" || text.length === 0) return null;
1722
+ let registration;
1723
+ try {
1724
+ registration = readInventoryPayload(JSON.parse(text));
1725
+ } catch {
1726
+ return null;
1727
+ }
1728
+ if (registration === null || run.head_sha !== registration.headSha || expectedHeadSha !== void 0 && run.head_sha !== expectedHeadSha) return null;
1729
+ return registration;
1730
+ };
1731
+ const checkRunOutput = (registration) => {
1732
+ const title = `Preview proof ${registration.stack}/${registration.stage}`.slice(0, 255);
1733
+ return {
1734
+ summary: `cleanup ${registration.cleanup.outcome}`,
1735
+ text: JSON.stringify({
1736
+ kind: INVENTORY_KIND,
1737
+ registration,
1738
+ schemaVersion: INVENTORY_SCHEMA_VERSION
1739
+ }),
1740
+ title
1741
+ };
1742
+ };
1743
+ const checkRunCreateBody = (registration) => ({
1744
+ conclusion: "neutral",
1745
+ head_sha: registration.headSha,
1746
+ name: PREVIEW_PROOF_INVENTORY_CHECK_NAME,
1747
+ output: checkRunOutput(registration),
1748
+ status: "completed"
1749
+ });
1750
+ const checkRunUpdateBody = (registration) => ({
1751
+ conclusion: "neutral",
1752
+ name: PREVIEW_PROOF_INVENTORY_CHECK_NAME,
1753
+ output: checkRunOutput(registration),
1754
+ status: "completed"
1755
+ });
1756
+ const collectPages = async (loadPage, pageSize, maxPages, exhaustedMessage) => {
1757
+ const collected = [];
1758
+ for (let page = 1; page <= maxPages; page += 1) {
1759
+ const rows = await loadPage(page);
1760
+ collected.push(...rows);
1761
+ if (rows.length < pageSize) return collected;
1762
+ }
1763
+ throw new Error(exhaustedMessage);
1764
+ };
1765
+ const mapPool = async (items, concurrency, mapper) => {
1766
+ if (items.length === 0) return [];
1767
+ const results = [];
1768
+ let next = 0;
1769
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, async () => {
1770
+ while (next < items.length) {
1771
+ const index = next;
1772
+ next += 1;
1773
+ const item = items[index];
1774
+ if (item === void 0) return;
1775
+ results[index] = await mapper(item);
1776
+ }
1777
+ }));
1778
+ return results;
1779
+ };
1780
+ const listCompareCommitShas = (request, token, timeoutMs, owner, repo, baseSha, headSha) => collectPages(async (page) => {
1781
+ const query = new URLSearchParams({
1782
+ page: String(page),
1783
+ per_page: String(COMMITS_PER_PAGE)
1784
+ });
1785
+ const compared = await githubJson(request, `${repoApi(owner, repo)}/compare/${encodeURIComponent(baseSha)}...${encodeURIComponent(headSha)}?${query.toString()}`, token, { method: "GET" }, timeoutMs);
1786
+ if (!isRecord$2(compared) || !Array.isArray(compared.commits)) throw new TypeError("GitHub compare response omitted commits");
1787
+ return compared.commits.flatMap((commit) => isRecord$2(commit) && typeof commit.sha === "string" ? [commit.sha] : []);
1788
+ }, COMMITS_PER_PAGE, MAX_COMMIT_PAGES, "Preview proof inventory compare listing exhausted pagination before GitHub returned a final page.");
1789
+ const listForcePushBeforeShas = async (request, token, timeoutMs, owner, repo, pr) => {
1790
+ const shas = [];
1791
+ let cursor;
1792
+ for (let page = 1; page <= MAX_FORCE_PUSH_PAGES; page += 1) {
1793
+ const data = await githubGraphql(request, token, timeoutMs, GRAPHQL_FORCE_PUSH_BEFORE, {
1794
+ cursor: cursor ?? null,
1795
+ first: FORCE_PUSH_TIMELINE_PER_PAGE,
1796
+ name: repo,
1797
+ owner,
1798
+ pr
1799
+ });
1800
+ if (!isRecord$2(data) || !isRecord$2(data.repository) || !isRecord$2(data.repository.pullRequest) || !isRecord$2(data.repository.pullRequest.timelineItems)) throw new TypeError("GitHub GraphQL force-push timeline omitted timelineItems");
1801
+ const items = data.repository.pullRequest.timelineItems;
1802
+ if (!Array.isArray(items.nodes) || !isRecord$2(items.pageInfo)) throw new TypeError("GitHub GraphQL force-push timeline omitted nodes");
1803
+ for (const node of items.nodes) {
1804
+ if (!isRecord$2(node) || !isRecord$2(node.beforeCommit) || typeof node.beforeCommit.oid !== "string" || !FULL_SHA_PATTERN$1.test(node.beforeCommit.oid)) continue;
1805
+ shas.push(node.beforeCommit.oid);
1806
+ }
1807
+ if (items.pageInfo.hasNextPage !== true) return shas;
1808
+ if (typeof items.pageInfo.endCursor !== "string" || items.pageInfo.endCursor.length === 0) throw new TypeError("GitHub GraphQL force-push timeline omitted endCursor");
1809
+ cursor = items.pageInfo.endCursor;
1810
+ }
1811
+ throw new Error("Preview proof inventory force-push timeline exhausted pagination before GitHub returned a final page.");
1812
+ };
1813
+ const listPullRequestCommitShas = (request, token, timeoutMs, owner, repo, pr) => collectPages(async (page) => {
1814
+ const query = new URLSearchParams({
1815
+ page: String(page),
1816
+ per_page: String(COMMITS_PER_PAGE)
1817
+ });
1818
+ const commits = await githubJson(request, `${repoApi(owner, repo)}/pulls/${pr}/commits?${query.toString()}`, token, { method: "GET" }, timeoutMs);
1819
+ if (!Array.isArray(commits)) throw new TypeError("GitHub pull request commits response was not an array");
1820
+ return commits.flatMap((commit) => isRecord$2(commit) && typeof commit.sha === "string" ? [commit.sha] : []);
1821
+ }, COMMITS_PER_PAGE, MAX_COMMIT_PAGES, "Preview proof inventory commit listing exhausted pagination before GitHub returned a final page.");
1822
+ const readPullBaseSha = (pull) => {
1823
+ if (!isRecord$2(pull.base) || typeof pull.base.sha !== "string") throw new TypeError("GitHub pull request response omitted base.sha");
1824
+ return pull.base.sha;
1825
+ };
1826
+ /**
1827
+ * Current head, replaced heads from force-push, the commits each replaced head
1828
+ * carried, and PR commits. The pull-commits endpoint silently stops at 250 and
1829
+ * never lists a rebased-away head, so those two cases use compare pagination
1830
+ * and the force-push timeline. A persist, then a fast-forward, then a rebase
1831
+ * leaves the persist SHA behind the replaced head, so each replaced head is
1832
+ * also walked back to the base (#796).
1833
+ */
1834
+ const listCommitShasForPull = async (request, token, timeoutMs, owner, repo, pr) => {
1835
+ const pull = await githubJson(request, `${repoApi(owner, repo)}/pulls/${pr}`, token, { method: "GET" }, timeoutMs);
1836
+ if (!isRecord$2(pull) || !isRecord$2(pull.head) || typeof pull.head.sha !== "string") throw new TypeError("GitHub pull request response omitted head.sha");
1837
+ const pullCommits = await listPullRequestCommitShas(request, token, timeoutMs, owner, repo, pr);
1838
+ let older = pullCommits;
1839
+ if (pullCommits.length >= GITHUB_PULL_COMMITS_CAP) older = await listCompareCommitShas(request, token, timeoutMs, owner, repo, readPullBaseSha(pull), pull.head.sha);
1840
+ const previousHeads = await listForcePushBeforeShas(request, token, timeoutMs, owner, repo, pr);
1841
+ let replaced = [];
1842
+ if (previousHeads.length > 0) {
1843
+ const baseSha = readPullBaseSha(pull);
1844
+ replaced = (await mapPool(previousHeads, 8, (previousHead) => listCompareCommitShas(request, token, timeoutMs, owner, repo, baseSha, previousHead))).flatMap((history) => [...history].toReversed());
1845
+ }
1846
+ const shas = [];
1847
+ const seen = /* @__PURE__ */ new Set();
1848
+ for (const sha of [
1849
+ pull.head.sha,
1850
+ ...previousHeads,
1851
+ ...older.toReversed(),
1852
+ ...replaced
1853
+ ]) if (!seen.has(sha)) {
1854
+ seen.add(sha);
1855
+ shas.push(sha);
1856
+ }
1857
+ return shas;
1858
+ };
1859
+ const listCheckRunsOnSha = (request, token, timeoutMs, owner, repo, sha) => collectPages(async (page) => {
1860
+ const query = new URLSearchParams({
1861
+ check_name: PREVIEW_PROOF_INVENTORY_CHECK_NAME,
1862
+ filter: "all",
1863
+ page: String(page),
1864
+ per_page: String(CHECK_RUNS_PER_PAGE)
1865
+ });
1866
+ const served = await githubJson(request, `${repoApi(owner, repo)}/commits/${encodeURIComponent(sha)}/check-runs?${query.toString()}`, token, { method: "GET" }, timeoutMs);
1867
+ if (!isRecord$2(served) || !Array.isArray(served.check_runs)) throw new TypeError("GitHub check-runs response omitted check_runs");
1868
+ return served.check_runs.filter((run) => isServedCheckRun(run));
1869
+ }, CHECK_RUNS_PER_PAGE, MAX_CHECK_RUN_PAGES, "Preview proof inventory check-run listing exhausted pagination before GitHub returned a final page.");
1870
+ const compareCheckRunsNewestFirst = (left, right) => {
1871
+ const leftMs = Date.parse(left.started_at ?? "");
1872
+ const rightMs = Date.parse(right.started_at ?? "");
1873
+ if (Number.isFinite(leftMs) && Number.isFinite(rightMs)) return rightMs - leftMs || (right.id ?? 0) - (left.id ?? 0);
1874
+ return (right.id ?? 0) - (left.id ?? 0);
1875
+ };
1876
+ const takeNewestRegistrations = (runsBySha, pr) => {
1877
+ const byKey = /* @__PURE__ */ new Map();
1878
+ for (const { runs, sha } of runsBySha) for (const run of [...runs].toSorted(compareCheckRunsNewestFirst)) {
1879
+ const registration = registrationFromCheckRun(run, sha);
1880
+ if (registration === null || registration.pr !== pr) continue;
1881
+ const key = registrationKey(registration);
1882
+ if (!byKey.has(key)) byKey.set(key, registration);
1883
+ }
1884
+ return [...byKey.values()];
1885
+ };
1886
+ /** Reached by callers as `previewProofInventory.githubStore`. */
1887
+ const githubStore = (transport) => {
1888
+ const request = transport.fetch ?? fetch;
1889
+ const timeoutMs = transport.timeoutMs ?? DEFAULT_TIMEOUT_MS$1;
1890
+ const { token } = transport;
1891
+ return {
1892
+ list: async (input) => {
1893
+ const shas = await listCommitShasForPull(request, token, timeoutMs, input.owner, input.repo, input.pr);
1894
+ const runsBySha = await mapPool(shas, 8, async (sha) => ({
1895
+ runs: await listCheckRunsOnSha(request, token, timeoutMs, input.owner, input.repo, sha),
1896
+ sha
1897
+ }));
1898
+ return takeNewestRegistrations(runsBySha, input.pr);
1899
+ },
1900
+ put: async (input) => {
1901
+ const registration = assertPersistableRegistration(input.registration);
1902
+ const existing = [...await listCheckRunsOnSha(request, token, timeoutMs, input.owner, input.repo, registration.headSha)].toSorted(compareCheckRunsNewestFirst).find((run) => {
1903
+ const row = registrationFromCheckRun(run, registration.headSha);
1904
+ return row !== null && row.pr === registration.pr && row.stack === registration.stack && row.stage === registration.stage && typeof run.id === "number";
1905
+ });
1906
+ if (existing?.id === void 0) {
1907
+ assertFactoryAppWrite(await githubJson(request, `${repoApi(input.owner, input.repo)}/check-runs`, token, {
1908
+ body: JSON.stringify(checkRunCreateBody(registration)),
1909
+ method: "POST"
1910
+ }, timeoutMs));
1911
+ return;
1912
+ }
1913
+ assertFactoryAppWrite(await githubJson(request, `${repoApi(input.owner, input.repo)}/check-runs/${existing.id}`, token, {
1914
+ body: JSON.stringify(checkRunUpdateBody(registration)),
1915
+ method: "PATCH"
1916
+ }, timeoutMs));
1917
+ }
1918
+ };
1919
+ };
1920
+ const resolveStore = (access) => {
1921
+ if (access.store !== void 0) return access.store;
1922
+ if (access.token !== void 0 && access.token.length > 0) return githubStore({
1923
+ fetch: access.fetch,
1924
+ timeoutMs: access.timeoutMs,
1925
+ token: access.token
1926
+ });
1927
+ throw new Error("Preview proof inventory requires a store or a GitHub token.");
1928
+ };
1929
+ const list = async (input, access) => {
1930
+ return (await resolveStore(access).list({
1931
+ owner: input.owner,
1932
+ pr: input.pr,
1933
+ repo: input.repo
1934
+ })).filter((row) => (input.stack === void 0 || row.stack === input.stack) && (input.stage === void 0 || row.stage === input.stage));
1935
+ };
1936
+ const persist = async (input, access) => {
1937
+ const registration = assertPersistableRegistration(input.registration);
1938
+ await resolveStore(access).put({
1939
+ owner: input.owner,
1940
+ registration,
1941
+ repo: input.repo
1942
+ });
1943
+ };
1944
+ const recordCleanup = async (input, access) => {
1945
+ const parsedStage = parseLocalPreviewStage(input.stage, input.headSha === void 0 ? { pr: input.pr } : {
1946
+ headSha: input.headSha,
1947
+ pr: input.pr
1948
+ });
1949
+ if (parsedStage === null) throw new Error(`Preview proof stage must be a disposable local-pr stage owned by PR #${input.pr} at this head.`);
1950
+ const store = resolveStore(access);
1951
+ const listed = await store.list({
1952
+ owner: input.owner,
1953
+ pr: input.pr,
1954
+ repo: input.repo
1955
+ });
1956
+ const existing = listed.find((row) => row.pr === input.pr && row.stack === input.stack && row.stage === parsedStage.stage);
1957
+ if (input.headSha !== void 0 && existing !== void 0 && existing.headSha !== input.headSha) throw new Error("Preview proof identity does not match the cleanup target.");
1958
+ const next = previewProofLifecycle.transition({ registrations: listed }, {
1959
+ evidence: input.evidence,
1960
+ outcome: input.outcome,
1961
+ pr: input.pr,
1962
+ ...input.runUrl === void 0 ? {} : { runUrl: input.runUrl },
1963
+ stack: input.stack,
1964
+ stage: parsedStage.stage,
1965
+ type: "cleanup"
1966
+ });
1967
+ const [updated] = previewProofLifecycle.resolve(next, {
1968
+ pr: input.pr,
1969
+ stack: input.stack,
1970
+ stage: parsedStage.stage
1971
+ });
1972
+ if (updated === void 0) throw new Error(`Preview proof cleanup requires a registration for ${input.stack}/${parsedStage.stage}.`);
1973
+ await store.put({
1974
+ owner: input.owner,
1975
+ registration: updated,
1976
+ repo: input.repo
1977
+ });
1978
+ return updated;
1979
+ };
1980
+ const previewProofInventory = {
1981
+ githubStore,
1982
+ list,
1983
+ listPermissions: PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS,
1984
+ memoryStore,
1985
+ persist,
1986
+ recordCleanup
1987
+ };
1988
+ const PINNED_ACTION_PATTERN = /^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/u;
1989
+ const ACTION_TAG_PATTERN = /^v\d+(?:\.\d+){0,2}$/u;
1990
+ const actionRepository = (action) => action.uses.slice(0, action.uses.indexOf("@"));
1991
+ /** Shared validator for every action pin emitted by factory-ci helpers. */
1992
+ const assertPinnedAction = (name, action, expectedRepository) => {
1993
+ if (!PINNED_ACTION_PATTERN.test(action.uses)) throw new Error(`${name} must use owner/repository@<40-character commit SHA>, got "${action.uses}".`);
1994
+ if (expectedRepository && actionRepository(action) !== expectedRepository) throw new Error(`${name} must pin ${expectedRepository}, got ${actionRepository(action)}.`);
1995
+ if (!ACTION_TAG_PATTERN.test(action.tag)) throw new Error(`${name} tag must be vN, vN.N, or vN.N.N, got "${action.tag}".`);
1996
+ };
1997
+ const RESERVED_ACTION_NAMES = /* @__PURE__ */ new Set([
1998
+ "checkout",
1999
+ "setupNode",
2000
+ "setupPnpm"
2001
+ ]);
2002
+ /**
2003
+ * Stable identifiers for the setup steps a generated workflow always emits,
2004
+ * in emission order. A consumer selects steps by role instead of locating
2005
+ * them by display name or by array position/length, so renaming a step or
2006
+ * adding a new supported role never breaks role-based composition (#1076).
2007
+ */
2008
+ const SETUP_STEP_ROLES = Object.freeze([
2009
+ "checkout",
2010
+ "setupPnpm",
2011
+ "setupNode",
2012
+ "install"
2013
+ ]);
2014
+ const assertSingleLine$3 = (name, value) => {
2015
+ if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
2016
+ };
2017
+ const usesStep = (fallbackName, action) => ({
2018
+ name: fallbackName,
2019
+ uses: action.uses
2020
+ });
2021
+ const assertActionFamily = (family) => {
2022
+ assertSingleLine$3("actionFamily.id", family.id);
2023
+ assertPinnedAction("checkout", family.checkout, "actions/checkout");
2024
+ assertPinnedAction("setupNode", family.setupNode, "actions/setup-node");
2025
+ assertPinnedAction("setupPnpm", family.setupPnpm, "pnpm/action-setup");
2026
+ };
2027
+ const assertAdditionalActions = (actions) => {
2028
+ for (const [name, action] of Object.entries(actions)) {
2029
+ if (RESERVED_ACTION_NAMES.has(name)) throw new Error(`${name} is reserved by the Node/pnpm action family and cannot be replaced by additionalActions.`);
2030
+ assertPinnedAction(name, action);
2031
+ }
2032
+ };
2033
+ const checkoutInputs = (checkout) => {
2034
+ if (checkout === void 0) return;
2035
+ const inputs = {};
2036
+ if (checkout.fetchDepth !== void 0) {
2037
+ if (!Number.isSafeInteger(checkout.fetchDepth) || checkout.fetchDepth < 0) throw new Error("checkout.fetchDepth must be a non-negative integer.");
2038
+ inputs["fetch-depth"] = String(checkout.fetchDepth);
2039
+ }
2040
+ if (checkout.ref) inputs.ref = checkout.ref;
2041
+ return Object.keys(inputs).length > 0 ? inputs : void 0;
2042
+ };
2043
+ const setupStepsByRole = (family, setup = {}) => {
2044
+ const installRun = setup.install?.run ?? "pnpm install --frozen-lockfile";
2045
+ if (/(?:^|\s)--ignore-scripts(?:\s|$)/u.test(installRun)) throw new Error("The install step must not use --ignore-scripts; workspace prepare scripts build required package artifacts.");
2046
+ const { checkout, setupNode } = setup;
2047
+ const checkoutWith = checkoutInputs(checkout);
2048
+ return Object.freeze({
2049
+ checkout: {
2050
+ name: checkout?.name ?? "Checkout",
2051
+ uses: family.checkout.uses,
2052
+ ...checkoutWith ? { with: checkoutWith } : {}
2053
+ },
2054
+ install: {
2055
+ name: setup.install?.name ?? "Install workspace",
2056
+ run: installRun
2057
+ },
2058
+ setupNode: {
2059
+ name: "Setup Node",
2060
+ uses: family.setupNode.uses,
2061
+ with: {
2062
+ cache: "pnpm",
2063
+ ...setupNode?.cacheDependencyPath ? { "cache-dependency-path": setupNode.cacheDependencyPath } : {},
2064
+ "node-version-file": setupNode?.nodeVersionFile ?? ".nvmrc"
2065
+ }
2066
+ },
2067
+ setupPnpm: usesStep("Setup pnpm", family.setupPnpm)
2068
+ });
2069
+ };
2070
+ /**
2071
+ * Select setup steps by stable role, in the order the roles are given.
2072
+ *
2073
+ * This is the supported alternative to destructuring `setupSteps` by array
2074
+ * position or asserting its length: a caller names exactly the roles it
2075
+ * needs (for example, every role but `checkout`, to follow its own
2076
+ * head-pinned checkout with the shared pnpm/Node/install sequence), and that
2077
+ * selection survives a renamed step or an added role.
2078
+ */
2079
+ const setupStepsForRoles = (artifact, roles) => Object.freeze(roles.map((role) => artifact.setupStepsByRole[role]));
2080
+ /**
2081
+ * Own one generated workflow source's action pins, setup block, provenance
2082
+ * banner, and gagen pinning policy as a single artifact.
2083
+ *
2084
+ * The caller still owns workflow topology, jobs, runners, permissions, and
2085
+ * every deployment policy decision.
2086
+ */
2087
+ const factoryWorkflow = (options) => {
2088
+ assertSingleLine$3("generated.source", options.generated.source);
2089
+ assertSingleLine$3("generated.regenerate", options.generated.regenerate);
2090
+ assertActionFamily(options.actionFamily);
2091
+ assertAdditionalActions(options.additionalActions ?? {});
2092
+ const actions = Object.freeze({
2093
+ checkout: options.actionFamily.checkout,
2094
+ setupNode: options.actionFamily.setupNode,
2095
+ setupPnpm: options.actionFamily.setupPnpm,
2096
+ ...options.additionalActions ?? {}
2097
+ });
2098
+ const stepsByRole = setupStepsByRole(options.actionFamily, options.setup);
2099
+ return Object.freeze({
2100
+ actionFamilyId: options.actionFamily.id,
2101
+ actions,
2102
+ setupSteps: Object.freeze(SETUP_STEP_ROLES.map((role) => stepsByRole[role])),
2103
+ setupStepsByRole: stepsByRole,
2104
+ writeOptions: Object.freeze({
2105
+ header: [`# GENERATED BY ${options.generated.source} -- DO NOT EDIT.`, `# Regenerate: ${options.generated.regenerate}`].join("\n"),
2106
+ pinDeps: false
2107
+ })
2108
+ });
2109
+ };
2110
+ /**
2111
+ * Pinned Cursor OIDC trust predicates for the Factory App broker (#949).
2112
+ *
2113
+ * The broker verifies a Cursor-managed Cloud Agent JWT and mints a
2114
+ * repo-scoped Factory App installation token. Audience, issuer, and JWKS are
2115
+ * not consumer settings: a knob that pointed them elsewhere would be the
2116
+ * whole mechanism undone, the same reason {@link FACTORY_PROOF_GATE_APP_ID}
2117
+ * is pinned.
2118
+ */
2119
+ /** Cursor's OIDC issuer. Tokens minted on the agent VM carry this `iss`. */
2120
+ const FACTORY_CURSOR_OIDC_ISSUER = "https://api.cursor.com";
2121
+ /** JWKS the broker uses to verify RS256 signatures. */
2122
+ const FACTORY_CURSOR_OIDC_JWKS_URL = "https://api.cursor.com/keys";
2123
+ /**
2124
+ * Audience a Cursor-managed VM must mint with. The CLI and the broker share
2125
+ * this string; Cursor does not allowlist audiences.
2126
+ */
2127
+ const FACTORY_CURSOR_OIDC_AUDIENCE = "Factory";
2128
+ /**
2129
+ * Runtime claim a Cursor-managed Cloud Agent VM always presents. Self-hosted
2130
+ * workers are not this broker's callers.
2131
+ */
2132
+ const FACTORY_CURSOR_OIDC_MANAGED_RUNTIME = "managed";
2133
+ /** HQ route that exchanges a verified Cursor OIDC JWT for an App token. */
2134
+ const FACTORY_APP_BROKER_PATH = "/api/factory-app/installation-token";
2135
+ /** Production broker origin. The CLI pins this; it is not profile-declared. */
2136
+ const FACTORY_APP_BROKER_ORIGIN = "https://hq.patronage.com";
2137
+ /** Generic timing and presentation steps around the proof-reuse gate (#652). */
2138
+ const githubExpression = (expression) => `\${{ ${expression} }}`;
2139
+ const shellExpansion = (expression) => `\${${expression}}`;
2140
+ const safeLabel = (surface) => {
2141
+ const cleaned = (typeof surface === "string" ? surface : "").replaceAll(/[^\w -]/gu, "").trim().slice(0, 60);
2142
+ return cleaned.length > 0 ? cleaned : "verification";
2143
+ };
2144
+ const FACTORY_PROOF_TIMING_STEP_ID = "ci-timing";
2145
+ const FACTORY_PROOF_TIMING_START_STEP_NAME = "Start CI timing";
2146
+ const FACTORY_PROOF_TIMING_SUMMARY_STEP_NAME = "Record proof-reuse timing";
2147
+ const factoryProofTimingStartStep = () => Object.freeze({
2148
+ continueOnError: true,
2149
+ id: FACTORY_PROOF_TIMING_STEP_ID,
2150
+ name: FACTORY_PROOF_TIMING_START_STEP_NAME,
2151
+ run: String.raw`started_ms="$(node -e 'process.stdout.write(String(Date.now()))')"
2152
+ printf 'started_ms=%s\n' "$started_ms" >> "$GITHUB_OUTPUT"`
2153
+ });
2154
+ const factoryProofReuseSummaryScript = ({ surface }) => {
2155
+ const label = safeLabel(surface);
2156
+ return String.raw`now_ms="$(node -e 'process.stdout.write(String(Date.now()))')"
2157
+ ci_started_ms="${shellExpansion("CI_STARTED_MS:-")}"
2158
+
2159
+ SUMMARY="${shellExpansion("GITHUB_STEP_SUMMARY:-/dev/null")}"
2160
+ say() { printf '%s\n' "$1" >> "$SUMMARY"; }
2161
+
2162
+ say '## ${label} timing'
2163
+ say ''
2164
+
2165
+ if [ "${shellExpansion("GITHUB_EVENT_NAME:-")}" = 'push' ] && [ -z "${shellExpansion("PROOF_REASON:-")}" ]; then
2166
+ # A push run with no recorded reason is one where the gate step's condition
2167
+ # kept it off entirely: a push to a ref other than the default branch.
2168
+ say '- Path: full execution, no proof consulted'
2169
+ say '- Proof-reuse gate: did not run on this ref; the full suite ran.'
2170
+ say "- Verified head: \`${shellExpansion("GITHUB_SHA:-unknown")}\`"
2171
+ echo "::notice title=Factory proof reuse::The proof-reuse gate did not run on this ref; the full ${label} suite executed."
2172
+ elif [ "${shellExpansion("PROOF_REUSED:-")}" = 'true' ]; then
2173
+ say '- Path: trusted local proof reused'
2174
+ if [ -n "${shellExpansion("PROOF_SOURCE_URL:-")}" ]; then
2175
+ say "- Reused proof: [exact source check](${shellExpansion("PROOF_SOURCE_URL")})"
2176
+ fi
2177
+ # On a merge-target push the reused proof is the producing pull request
2178
+ # head's, a different commit than the pushed one (#1658).
2179
+ bound_head="${shellExpansion("PROOF_SOURCE_HEAD:-")}"
2180
+ if [ -z "$bound_head" ]; then
2181
+ bound_head="${shellExpansion("PROOF_HEAD_SHA:-unknown")}"
2182
+ fi
2183
+ say "- Bound head: \`$bound_head\`"
2184
+ if [ "$bound_head" != "${shellExpansion("PROOF_HEAD_SHA:-")}" ]; then
2185
+ say "- Merge target: \`${shellExpansion("PROOF_HEAD_SHA:-unknown")}\` has the same tree as the proven head"
2186
+ fi
2187
+ say "- Factory verification mode: ${shellExpansion("PROOF_MODE:-unavailable")} (diagnostic only)"
2188
+ echo "::notice title=Factory proof reuse::Reused trusted local proof for ${label} at $bound_head."
2189
+ else
2190
+ say "- Path: full GitHub CI fallback (${shellExpansion("PROOF_REASON:-error")})"
2191
+ say "- Bound head: \`${shellExpansion("PROOF_HEAD_SHA:-unknown")}\`"
2192
+ say "- Factory verification mode: ${shellExpansion("PROOF_MODE:-unavailable")} (diagnostic only)"
2193
+ echo "::notice title=Factory proof reuse::No reusable proof for ${label}; the full hosted suite executed (${shellExpansion("PROOF_REASON:-error")})."
2194
+ fi
2195
+
2196
+ if [[ "$ci_started_ms" =~ ^[0-9]+$ ]]; then
2197
+ say "- GitHub workflow execution after the proof gate: $((now_ms - ci_started_ms)) ms"
2198
+ else
2199
+ say '- GitHub workflow execution after the proof gate: unavailable'
2200
+ fi
2201
+ say ''`;
2202
+ };
2203
+ const factoryProofReuseSummaryStep = (options) => Object.freeze({
2204
+ continueOnError: true,
2205
+ env: Object.freeze({
2206
+ CI_STARTED_MS: githubExpression(`steps.${FACTORY_PROOF_TIMING_STEP_ID}.outputs.started_ms`),
2207
+ PROOF_HEAD_SHA: githubExpression("github.event.pull_request.head.sha || github.sha"),
2208
+ PROOF_MODE: githubExpression(`steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_MODE_OUTPUT}`),
2209
+ PROOF_REASON: githubExpression(`steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_REASON_OUTPUT}`),
2210
+ PROOF_REUSED: githubExpression(`steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_OUTPUT}`),
2211
+ PROOF_SOURCE_HEAD: githubExpression(`steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_SOURCE_HEAD_OUTPUT}`),
2212
+ PROOF_SOURCE_URL: githubExpression(`steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT}`)
2213
+ }),
2214
+ if: "always()",
2215
+ name: FACTORY_PROOF_TIMING_SUMMARY_STEP_NAME,
2216
+ run: factoryProofReuseSummaryScript(options)
2217
+ });
2218
+ const impactDemandConditions = (options) => {
2219
+ const targetOutput = (targetName) => {
2220
+ const output = options.targetOutputs[targetName];
2221
+ if (output === void 0) throw new Error(`Unknown ${options.label} impact target "${targetName}".`);
2222
+ return output;
2223
+ };
2224
+ const condition = (source, outcomeKey, output) => `${source}.${outcomeKey} != 'success' || ${source}.outputs.${options.decisionOutput} != 'usable' || ${source}.outputs.${output} != 'withdrawn'`;
2225
+ return Object.freeze({
2226
+ demandedIf: (targetName, decisionJob) => {
2227
+ const output = targetOutput(targetName);
2228
+ if (decisionJob.trim().length === 0) throw new Error(`A cross-job ${options.label} impact condition requires the decision job id.`);
2229
+ return `always() && (${condition(`needs.${decisionJob}`, "result", output)})`;
2230
+ },
2231
+ demandedIfAtStep: (targetName) => condition(`steps.${options.stepId}`, "outcome", targetOutput(targetName))
2232
+ });
2233
+ };
2234
+ /**
2235
+ * `@patronage/software-factory` publishes two dist entries. `dist/index.js` is
2236
+ * the package export: consumers import it, so it runs no command. `dist/cli.js`
2237
+ * is the bin, and it is the only entry that runs one (software-factory#386).
2238
+ *
2239
+ * A workflow step that invokes `dist/index.js` therefore loads a library and
2240
+ * exits 0 — a green step that did nothing. This guard makes a generator refuse
2241
+ * that `cli` at generation time, where the failure is loud, instead of letting
2242
+ * it reach CI where the failure is silent. Invoke the bin by name (`psf`,
2243
+ * `pnpm exec psf`, `pnpm dlx psf`) or by the `dist/cli.js` path.
2244
+ */
2245
+ const INERT_ENTRY_PATTERN = /(?:^|[/\\])dist[/\\]index\.js(?:["'\s]|$)/u;
2246
+ /** Shared validator for every `cli` string a factory-ci generator emits. */
2247
+ const assertRunnableCli = (name, cli) => {
2248
+ if (INERT_ENTRY_PATTERN.test(cli)) throw new Error(`${name} must invoke the software-factory bin, not the package entry dist/index.js, which imports as a library and exits 0 without running the command. Use the bin name (for example "pnpm exec psf") or dist/cli.js. Got "${cli}".`);
2249
+ };
2250
+ const FACTORY_PRODUCTION_IMPACT_STEP_ID = "production_impact";
2251
+ const FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT = "decision";
2252
+ const FACTORY_PRODUCTION_IMPACT_BASIS_OUTPUT = "basis";
2253
+ const FACTORY_PRODUCTION_IMPACT_UNSUBSCRIBED_OUTPUT = "unsubscribed_paths";
2254
+ const OUTPUT_NAME_PATTERN = /[^a-z0-9_]+/gu;
2255
+ const shellQuote$2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
2256
+ /** Stable GitHub-output key for one declared target. */
2257
+ const productionImpactTargetOutput = (targetName) => {
2258
+ const normalized = targetName.toLowerCase().replaceAll(OUTPUT_NAME_PATTERN, "_").replaceAll(/^_+|_+$/gu, "");
2259
+ if (normalized.length === 0) throw new Error(`Impact target name "${targetName}" has no output-safe characters.`);
2260
+ return `target_${normalized}`;
2261
+ };
2262
+ /**
2263
+ * Generate the small factory-owned decision seam for a consumer production
2264
+ * workflow. Consumers retain jobs, deploy commands, credentials, topology,
2265
+ * health checks, and convergence checks; this artifact supplies the decision
2266
+ * step, per-target withdrawal conditions, and the receipt steps that record
2267
+ * what each deploy job did.
2268
+ *
2269
+ * The decision step resolves each target's demand from its last trusted
2270
+ * successful deployment receipt, never from the push's before commit. The
2271
+ * decision checkout needs full history (`fetchDepth: 0`) so the baseline
2272
+ * commit is reachable; a shallow checkout keeps every target demanded.
2273
+ */
2274
+ const factoryProductionImpactWorkflow = (options) => {
2275
+ const targetOutputs = Object.fromEntries(options.targets.map((target) => [target, productionImpactTargetOutput(target)]));
2276
+ if (new Set(Object.values(targetOutputs)).size !== options.targets.length) throw new Error("Impact target names must map to distinct GitHub output keys.");
2277
+ const candidate = options.candidate ?? `\${{ github.sha }}`;
2278
+ const cli = options.cli ?? "pnpm exec psf";
2279
+ assertRunnableCli("cli", cli);
2280
+ const profile = options.profilePath ? ` --profile ${shellQuote$2(options.profilePath)}` : "";
2281
+ const stage = options.stage ? ` --stage ${shellQuote$2(options.stage)}` : "";
2282
+ const env = {
2283
+ FACTORY_CANDIDATE_SHA: candidate,
2284
+ GH_TOKEN: `\${{ github.token }}`
2285
+ };
2286
+ const decisionStep = {
2287
+ continueOnError: true,
2288
+ env,
2289
+ id: FACTORY_PRODUCTION_IMPACT_STEP_ID,
2290
+ name: "Resolve production deployment demand",
2291
+ run: `${cli} production:impact --candidate "$FACTORY_CANDIDATE_SHA" --github-output "$GITHUB_OUTPUT" --github-summary "$GITHUB_STEP_SUMMARY"${profile}${stage}`
2292
+ };
2293
+ const conditions = impactDemandConditions({
2294
+ decisionOutput: FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT,
2295
+ label: "production",
2296
+ stepId: FACTORY_PRODUCTION_IMPACT_STEP_ID,
2297
+ targetOutputs
2298
+ });
2299
+ const receiptSteps = (targetName) => {
2300
+ const output = targetOutputs[targetName];
2301
+ if (output === void 0) throw new Error(`Unknown production impact target "${targetName}".`);
2302
+ const successStepId = `receipt_${output}`;
2303
+ const deploymentId = `\${{ steps.${successStepId}.outputs.deployment_id }}`;
2304
+ return Object.freeze([
2305
+ Object.freeze({
2306
+ env,
2307
+ id: successStepId,
2308
+ if: "success()",
2309
+ name: `Publish success deployment receipt for ${targetName}`,
2310
+ run: `${cli} production:impact --publish-receipt success --target ${shellQuote$2(targetName)} --candidate "$FACTORY_CANDIDATE_SHA" --github-output "$GITHUB_OUTPUT" --github-summary "$GITHUB_STEP_SUMMARY"${stage}`
2311
+ }),
2312
+ Object.freeze({
2313
+ env: { FACTORY_DEPLOYMENT_ID: deploymentId },
2314
+ if: "success()",
2315
+ name: `Bind deployment receipt ${deploymentId}`,
2316
+ run: "test -n \"$FACTORY_DEPLOYMENT_ID\""
2317
+ }),
2318
+ Object.freeze({
2319
+ env,
2320
+ if: "failure()",
2321
+ name: `Publish failure deployment receipt for ${targetName}`,
2322
+ run: `${cli} production:impact --publish-receipt failure --target ${shellQuote$2(targetName)} --candidate "$FACTORY_CANDIDATE_SHA" --github-summary "$GITHUB_STEP_SUMMARY"${stage}`
2323
+ })
2324
+ ]);
2325
+ };
2326
+ return Object.freeze({
2327
+ decisionJobOutputs: Object.freeze({
2328
+ basis: `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${FACTORY_PRODUCTION_IMPACT_BASIS_OUTPUT} }}`,
2329
+ decision: `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT} }}`,
2330
+ unsubscribed_paths: `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${FACTORY_PRODUCTION_IMPACT_UNSUBSCRIBED_OUTPUT} }}`,
2331
+ ...Object.fromEntries(Object.values(targetOutputs).map((output) => [output, `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${output} }}`]))
2332
+ }),
2333
+ decisionStep: Object.freeze(decisionStep),
2334
+ demandedIf: conditions.demandedIf,
2335
+ demandedIfAtStep: conditions.demandedIfAtStep,
2336
+ permissions: Object.freeze({
2337
+ actions: "read",
2338
+ contents: "read",
2339
+ deployments: "write"
2340
+ }),
2341
+ receiptSteps,
2342
+ targetOutputs: Object.freeze(targetOutputs)
2343
+ });
2344
+ };
2345
+ const FACTORY_CANDIDATE_IMPACT_STEP_ID = "candidate_impact";
2346
+ const FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT = "decision";
2347
+ const FACTORY_CANDIDATE_IMPACT_BASIS_OUTPUT = "basis";
2348
+ const FACTORY_CANDIDATE_IMPACT_INERT_OUTPUT = "inert_paths";
2349
+ const FACTORY_CANDIDATE_IMPACT_UNSUBSCRIBED_OUTPUT = "unsubscribed_paths";
2350
+ const shellQuote$1 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
2351
+ /**
2352
+ * Generate the factory-owned candidate routing seam for a consumer
2353
+ * pull-request workflow (#741). The decision step calls
2354
+ * `psf candidate:impact` with the pull request's exact base/head commits, so
2355
+ * the canonical profile impact declarations and dependency graph route the
2356
+ * run — never a second path matcher. Consumers retain jobs, surface names,
2357
+ * runners, commands, and credentials; this artifact supplies only the
2358
+ * decision step and per-target withdrawal conditions. Target output keys are
2359
+ * the same stable contract the production decision seam writes.
2360
+ *
2361
+ * The decision checkout must have the exact head commit checked out and the
2362
+ * base commit reachable (`fetchDepth: 0`, `ref` = the head SHA); anything
2363
+ * else refuses withdrawal and keeps every target demanded.
2364
+ */
2365
+ const factoryCandidateImpactWorkflow = (options) => {
2366
+ const targetOutputs = Object.fromEntries(options.targets.map((target) => [target, productionImpactTargetOutput(target)]));
2367
+ if (new Set(Object.values(targetOutputs)).size !== options.targets.length) throw new Error("Impact target names must map to distinct GitHub output keys.");
2368
+ const base = options.base ?? `\${{ github.event.pull_request.base.sha }}`;
2369
+ const head = options.head ?? `\${{ github.event.pull_request.head.sha }}`;
2370
+ const cli = options.cli ?? "pnpm exec psf";
2371
+ assertRunnableCli("cli", cli);
2372
+ const profile = options.profilePath ? ` --profile ${shellQuote$1(options.profilePath)}` : "";
2373
+ const decisionStep = {
2374
+ continueOnError: true,
2375
+ env: {
2376
+ FACTORY_BASE_SHA: base,
2377
+ FACTORY_HEAD_SHA: head
2378
+ },
2379
+ id: FACTORY_CANDIDATE_IMPACT_STEP_ID,
2380
+ name: "Classify candidate impact",
2381
+ run: `${cli} candidate:impact --base "$FACTORY_BASE_SHA" --head "$FACTORY_HEAD_SHA" --github-output "$GITHUB_OUTPUT" --github-summary "$GITHUB_STEP_SUMMARY"${profile}`
2382
+ };
2383
+ const conditions = impactDemandConditions({
2384
+ decisionOutput: FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT,
2385
+ label: "candidate",
2386
+ stepId: FACTORY_CANDIDATE_IMPACT_STEP_ID,
2387
+ targetOutputs
2388
+ });
2389
+ return Object.freeze({
2390
+ decisionJobOutputs: Object.freeze({
2391
+ basis: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_BASIS_OUTPUT} }}`,
2392
+ decision: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT} }}`,
2393
+ inert_paths: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_INERT_OUTPUT} }}`,
2394
+ unsubscribed_paths: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_UNSUBSCRIBED_OUTPUT} }}`,
2395
+ ...Object.fromEntries(Object.values(targetOutputs).map((output) => [output, `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${output} }}`]))
2396
+ }),
2397
+ decisionStep: Object.freeze(decisionStep),
2398
+ demandedIf: conditions.demandedIf,
2399
+ demandedIfAtStep: conditions.demandedIfAtStep,
2400
+ targetOutputs: Object.freeze(targetOutputs)
2401
+ });
2402
+ };
2403
+ const FACTORY_LIFECYCLE_CONTRACT_JOB_ID = "factory-contracts";
2404
+ const FACTORY_LIFECYCLE_CONTRACT_JOB_NAME = "Factory / Alchemy Contracts";
2405
+ const JOB_ID_PATTERN$1 = /^[A-Za-z_][A-Za-z0-9_-]*$/u;
2406
+ const PACKAGE_NAME = "(?:@[A-Za-z0-9._~-]+\\/)?[A-Za-z0-9._~-]+";
2407
+ const COLON_SCRIPT = "[A-Za-z][\\w.-]*:[\\w:.-]+";
2408
+ const RUN_SCRIPT = "[A-Za-z][\\w:.-]*";
2409
+ const PNPM = `pnpm(?: --filter(?:=| )${PACKAGE_NAME})?`;
2410
+ const OTHER_MANAGER = "(?:bun|npm|yarn)";
2411
+ const ALLOWED_PACKAGE_SCRIPT = new RegExp(`^(?:${PNPM} run ${RUN_SCRIPT}|${PNPM} ${COLON_SCRIPT}|${OTHER_MANAGER} run ${RUN_SCRIPT}|${OTHER_MANAGER} ${COLON_SCRIPT})$`, "u");
2412
+ const CREDENTIAL_ENV = /ALCHEMY_PASSWORD|CLOUDFLARE_|CF_API_|secrets\./u;
2413
+ const SHELL_OPERATOR = /&&|\|\||;|\||`|\$\(|\$\{|\$[A-Za-z_*@#?!$0-9-]/u;
2414
+ const EVIDENCE_SUMMARY = `{
2415
+ echo "## Factory contract evidence"
2416
+ echo
2417
+ echo "- Status: $JOB_STATUS"
2418
+ echo "- Covers the consumer's declared Alchemy/product-stack lifecycle contracts."
2419
+ echo "- This static lane is non-credentialed and does not prove live deploy, D1, smoke, convergence, or cleanup."
2420
+ } >> "$GITHUB_STEP_SUMMARY"`;
2421
+ const assertSingleLine$2 = (name, value) => {
2422
+ if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
2423
+ };
2424
+ const assertPackageScriptCommand = (command) => {
2425
+ assertSingleLine$2("lifecycleContract.command", command);
2426
+ if (CREDENTIAL_ENV.test(command)) throw new Error("lifecycleContract.command must not interpolate GitHub secrets or credential environment names.");
2427
+ if (SHELL_OPERATOR.test(command)) throw new Error("lifecycleContract.command must not include a shell operator or environment expansion.");
2428
+ if (!ALLOWED_PACKAGE_SCRIPT.test(command)) throw new Error("lifecycleContract.command must be a package script invocation (`run <script>` or a colon-namespaced shorthand), never a package-manager builtin or a direct Vitest run.");
2429
+ };
2430
+ /**
2431
+ * Generate the factory-owned non-credentialed lifecycle-contract lane
2432
+ * (#765). Consumers declare the package-script command in
2433
+ * `software-factory.profile.json`; this helper never loads that profile.
2434
+ * Callers pass the parsed declaration (or omit it) and include or skip the
2435
+ * returned job. Setup, runners, topology, and credentials stay with the
2436
+ * caller — and this lane must never receive credentials.
2437
+ *
2438
+ * The generated steps run only the declared package script and write an
2439
+ * always() evidence summary of what the lane proves and does not prove.
2440
+ * The command must be a package-script invocation: `run <script>`, or a
2441
+ * shorthand whose script name contains `:` (`pnpm test:factory`). Optional
2442
+ * pnpm `--filter <pkg>` may precede either form. Shell operators, credential
2443
+ * env, extra flags, and direct Vitest are refused.
2444
+ */
2445
+ const factoryLifecycleContractLane = (declaration) => {
2446
+ if (declaration === void 0) return;
2447
+ assertPackageScriptCommand(declaration.command);
2448
+ const jobId = declaration.jobId ?? "factory-contracts";
2449
+ const jobName = declaration.jobName ?? "Factory / Alchemy Contracts";
2450
+ if (!JOB_ID_PATTERN$1.test(jobId)) throw new Error("lifecycleContract.jobId must be a GitHub Actions job id.");
2451
+ assertSingleLine$2("lifecycleContract.jobName", jobName);
2452
+ const runStep = Object.freeze({
2453
+ name: "Run lifecycle contracts",
2454
+ run: declaration.command
2455
+ });
2456
+ const summaryStep = Object.freeze({
2457
+ env: Object.freeze({ JOB_STATUS: `\${{ job.status }}` }),
2458
+ if: "always()",
2459
+ name: "Summarize factory-contract evidence",
2460
+ run: EVIDENCE_SUMMARY
2461
+ });
2462
+ return Object.freeze({
2463
+ jobId,
2464
+ jobName,
2465
+ steps: Object.freeze([runStep, summaryStep])
2466
+ });
2467
+ };
2468
+ /**
2469
+ * The merge-freeze writer job (#356, ADR 0016; #429 for the
2470
+ * merge-target namespace; #872 for this package).
2471
+ *
2472
+ * A consumer's generated merge-target-push Verify workflow is the ONLY
2473
+ * producer of `patronage-factory/merge-freeze` generations: a red
2474
+ * push-triggered Verify completes a generation active, a green one completes
2475
+ * it inactive, and no command, scheduled job, or second workflow writes this
2476
+ * check run. The operator override (`demand:waive --demand merge-freeze`)
2477
+ * waives the demand for one candidate during a fix-forward; it never writes
2478
+ * here.
2479
+ *
2480
+ * The write mirrors what the factory package's merge-freeze reader parses:
2481
+ * create the run `in_progress` with no `started_at` (GitHub stamps the
2482
+ * generation clock — the ordering rule itself is owned by the reader), then
2483
+ * PATCH it completed with the reader-shaped state payload in `output.text`.
2484
+ * The consumer's workflow test executes this exact script against a stubbed
2485
+ * `gh` and parses the emitted payload with `validateMergeFreezeState`, so
2486
+ * writer and reader cannot drift silently.
2487
+ *
2488
+ * Those two API calls are what the reader's two settling phases observe
2489
+ * (#890). Before the POST the merge target carries no generation at all, which
2490
+ * a reader reports as `awaiting-generation` while the pushed hosted verify run
2491
+ * is still pending. Between the POST and the PATCH the generation exists with
2492
+ * no `output.text`, which a reader reports as `running-generation`. Only the
2493
+ * PATCH writes a verdict, so neither phase is one.
2494
+ *
2495
+ * Failure posture is deliberately fail-closed and the opposite of the
2496
+ * proof-reuse gate's fail-open shell: this step runs under the runner's
2497
+ * default `bash -e {0}`, so any API refusal aborts the step, the generation
2498
+ * stays absent or `in_progress`, and every `pr:ready` arming-time read of
2499
+ * that tip (#477) refuses until a later push writes a green generation.
2500
+ *
2501
+ * **Ownership line.** This package owns the check name, the App identity, the
2502
+ * `create-github-app-token` inputs, the result fold, the merge-target `if`,
2503
+ * and the job's `permissions`. The caller owns the runner, the `needs` list
2504
+ * of every authoritative verification leaf, the timeout, and any extra env.
2505
+ */
2506
+ /** The one check-run name every merge-freeze reader pins. */
2507
+ const FACTORY_MERGE_FREEZE_CHECK_NAME = "patronage-factory/merge-freeze";
2508
+ const FACTORY_MERGE_FREEZE_JOB_ID = "freeze";
2509
+ const FACTORY_MERGE_FREEZE_JOB_NAME = "Report the merge freeze";
2510
+ /** Step id the token step exposes its installation token under. */
2511
+ const FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID = "factory-app-token";
2512
+ /**
2513
+ * The GitHub Actions expression that folds the needed jobs' results into the
2514
+ * one word the script branches on. It mirrors the `verify` summary job's
2515
+ * failure condition exactly: any failed or cancelled needed job is a red
2516
+ * merge target.
2517
+ */
2518
+ const FACTORY_MERGE_FREEZE_VERIFY_RESULT_EXPRESSION = `\${{ (contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) && 'failure' || 'success' }}`;
2519
+ /**
2520
+ * The literal factory merge-target namespace, as a `github.ref` predicate
2521
+ * (#429).
2522
+ *
2523
+ * `main` plus the repository-owned `epic/**` integration branches, and
2524
+ * nothing else. Deliberately literal rather than profile-declared: one
2525
+ * implementation per contract, no configuration machinery for a two-element
2526
+ * namespace whose second element is a namespace prefix the repository itself
2527
+ * owns. `epic/` needs the trailing slash — `startsWith` would otherwise admit
2528
+ * `epicness/…`, which is not a merge target.
2529
+ *
2530
+ * A caller's `push` trigger branch list names the same namespace. That list
2531
+ * decides which events produce a run at all; this predicate decides which of
2532
+ * those runs may write a generation.
2533
+ */
2534
+ const FACTORY_MERGE_TARGET_REF_CONDITION = ["github.ref == 'refs/heads/main'", "startsWith(github.ref, 'refs/heads/epic/')"].join(" || ");
2535
+ /**
2536
+ * `always()` is load-bearing: the red path is the whole point, so the job must
2537
+ * run when a needed verification job failed. `github.event_name == 'push'` is
2538
+ * load-bearing twice over: a `pull_request` run must never write a generation
2539
+ * (its `github.sha` is a synthetic merge commit that no base tip is ever read
2540
+ * at), and a `pull_request` trigger with an `epic/**` base list would
2541
+ * otherwise reach this job.
2542
+ */
2543
+ const FACTORY_MERGE_FREEZE_IF = `always() && github.event_name == 'push' && (${FACTORY_MERGE_TARGET_REF_CONDITION})`;
2544
+ /**
2545
+ * Least privilege for the writer job: no `GITHUB_TOKEN` scope at all.
2546
+ *
2547
+ * Both Checks API calls run under the App installation token minted in the
2548
+ * first step (`GH_TOKEN: steps.factory-app-token.outputs.token`), and the job
2549
+ * never checks out the repository. So the job uses no `GITHUB_TOKEN` scope,
2550
+ * and an empty block is the honest declaration. A `checks: write` here would
2551
+ * hand every adopter an unused write scope (#884).
2552
+ */
2553
+ const FACTORY_MERGE_FREEZE_PERMISSIONS = Object.freeze({});
2554
+ /**
2555
+ * The script the freeze step runs. Environment contract:
2556
+ * - `GH_TOKEN`: an installation token for the pinned Patronage Factory App —
2557
+ * the check run must carry that App's identity or every reader rejects it.
2558
+ * - `VERIFY_RESULT`: `success` or `failure` (see the fold expression above).
2559
+ * - `VERIFY_JOBS`: JSON `needs` context; only job results are retained.
2560
+ * - `GITHUB_SHA` / `GITHUB_REPOSITORY` / `GITHUB_SERVER_URL` /
2561
+ * `GITHUB_RUN_ID` / `GITHUB_RUN_ATTEMPT` / `GITHUB_REF_NAME`: runner-provided.
2562
+ *
2563
+ * `GITHUB_REF_NAME` is the merge target this run pushed to — `main` or an
2564
+ * `epic/**` integration branch (#429). The job is gated to `push` events on
2565
+ * exactly those refs, so the branch name is always the short name of a
2566
+ * repository-owned merge target and never a pull-request merge ref. It
2567
+ * appears in recovery guidance because a reader of an epic-targeting
2568
+ * candidate must be told which branch owns the generation. A later green
2569
+ * generation on that branch's current tip clears it, including a rerun.
2570
+ */
2571
+ const factoryMergeFreezeScript = () => [
2572
+ `sha="$GITHUB_SHA"`,
2573
+ `branch="$GITHUB_REF_NAME"`,
2574
+ `repo="$GITHUB_REPOSITORY"`,
2575
+ `run_url="$GITHUB_SERVER_URL/$repo/actions/runs/$GITHUB_RUN_ID/attempts/$GITHUB_RUN_ATTEMPT"`,
2576
+ `verification=$(jq -cen --argjson needs "$VERIFY_JOBS" --argjson runId "$GITHUB_RUN_ID" --argjson runAttempt "$GITHUB_RUN_ATTEMPT" '`,
2577
+ ` def positiveInteger: type == "number" and . > 0 and floor == .;`,
2578
+ ` if ($runId | positiveInteger) and ($runAttempt | positiveInteger) and ($needs | type == "object" and length > 0) then`,
2579
+ ` {runId: $runId, runAttempt: $runAttempt, jobs: ($needs | map_values(.result))}`,
2580
+ ` | select(all(.jobs[]; . == "success" or . == "failure" or . == "cancelled" or . == "skipped"))`,
2581
+ ` else empty end')`,
2582
+ `cancelled=$(jq 'any(.jobs[]; . == "cancelled")' <<<"$verification")`,
2583
+ `failed=$(jq 'any(.jobs[]; . == "failure")' <<<"$verification")`,
2584
+ `created=$(gh api --method POST "repos/$repo/check-runs" \\`,
2585
+ ` -f "name=${FACTORY_MERGE_FREEZE_CHECK_NAME}" \\`,
2586
+ ` -f "head_sha=$sha" \\`,
2587
+ ` -f "status=in_progress" \\`,
2588
+ ` -f "details_url=$run_url" \\`,
2589
+ ` -f "output[title]=merge freeze generation in progress" \\`,
2590
+ ` -f "output[summary]=This generation blocks factory merge handoffs until the merge-target Verify result is recorded.")`,
2591
+ `id=$(jq -r '.id' <<<"$created")`,
2592
+ `case "$id" in`,
2593
+ ` ''|*[!0-9]*) echo "unusable check-run id: $id" >&2; exit 1;;`,
2594
+ `esac`,
2595
+ `if [ "$VERIFY_RESULT" = 'success' ]; then`,
2596
+ ` active=false; outcome=inactive; conclusion=success`,
2597
+ ` reason="Merge-target Verify passed on $branch at $sha ($run_url)."`,
2598
+ `else`,
2599
+ ` active=true; outcome=active; conclusion=failure`,
2600
+ ` if [ "$cancelled" = 'true' ] && [ "$failed" = 'false' ]; then`,
2601
+ ` reason="Required verification was cancelled on $branch at $sha in attempt $GITHUB_RUN_ATTEMPT; verification did not complete. Inspect and rerun this attempt; a successful Verify on the current $branch tip clears the freeze ($run_url)."`,
2602
+ ` elif [ "$cancelled" = 'true' ]; then`,
2603
+ ` reason="Required verification failed and was cancelled on $branch at $sha in attempt $GITHUB_RUN_ATTEMPT; inspect both outcomes, fix forward or revert on $branch, or rerun after resolving the failure ($run_url)."`,
2604
+ ` else`,
2605
+ ` reason="Merge-target Verify failed on $branch at $sha in attempt $GITHUB_RUN_ATTEMPT; fix forward or revert on $branch, or rerun after resolving the failure. A successful Verify on the current $branch tip clears this freeze ($run_url)."`,
2606
+ ` fi`,
2607
+ `fi`,
2608
+ `state=$(jq -cn --argjson active "$active" --argjson id "$id" --arg headSha "$sha" --arg outcome "$outcome" --arg reason "$reason" --argjson verification "$verification" \\`,
2609
+ ` '{active: $active, generationId: $id, headSha: $headSha, outcome: $outcome, reason: $reason, recordedAt: (now | todate), schemaVersion: 1, verification: $verification}')`,
2610
+ `gh api --method PATCH "repos/$repo/check-runs/$id" \\`,
2611
+ ` -f "status=completed" \\`,
2612
+ ` -f "conclusion=$conclusion" \\`,
2613
+ ` -f "details_url=$run_url" \\`,
2614
+ ` -f "output[title]=merge freeze $outcome" \\`,
2615
+ ` -f "output[summary]=$reason" \\`,
2616
+ ` -f "output[text]=$state" >/dev/null`,
2617
+ `echo "merge-freeze generation $id completed $outcome on $branch at $sha"`
2618
+ ].join("\n");
2619
+ /**
2620
+ * Build the merge-freeze writer job.
2621
+ *
2622
+ * An empty `needs` list is refused: a fold over no verification leaf is
2623
+ * always `success`, so such a job would write a green generation for a merge
2624
+ * target nothing verified — the exact failure the freeze exists to prevent.
2625
+ */
2626
+ const factoryMergeFreezeJob = (options) => {
2627
+ assertPinnedAction("createGithubAppToken", options.createGithubAppToken, "actions/create-github-app-token");
2628
+ if (options.needs.length === 0) throw new Error("factoryMergeFreezeJob needs at least one verification job: a fold over no needed job always reports success, so the freeze would report a merge target nothing verified as green.");
2629
+ const mintStep = Object.freeze({
2630
+ id: FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID,
2631
+ name: "Mint the factory App token",
2632
+ uses: options.createGithubAppToken.uses,
2633
+ with: Object.freeze({
2634
+ "client-id": FACTORY_PROOF_GATE_APP_ID,
2635
+ "private-key": `\${{ secrets.FACTORY_GITHUB_APP_PRIVATE_KEY }}`
2636
+ })
2637
+ });
2638
+ const reportStep = Object.freeze({
2639
+ env: Object.freeze({
2640
+ GH_TOKEN: `\${{ steps.${FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID}.outputs.token }}`,
2641
+ VERIFY_JOBS: `\${{ toJSON(needs) }}`,
2642
+ VERIFY_RESULT: options.verifyResultExpression ?? "${{ (contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) && 'failure' || 'success' }}"
2643
+ }),
2644
+ name: "Complete the merge-freeze generation",
2645
+ run: factoryMergeFreezeScript()
2646
+ });
2647
+ return Object.freeze({
2648
+ if: FACTORY_MERGE_FREEZE_IF,
2649
+ jobId: FACTORY_MERGE_FREEZE_JOB_ID,
2650
+ jobName: FACTORY_MERGE_FREEZE_JOB_NAME,
2651
+ needs: Object.freeze([...options.needs]),
2652
+ permissions: FACTORY_MERGE_FREEZE_PERMISSIONS,
2653
+ steps: Object.freeze([mintStep, reportStep])
2654
+ });
2655
+ };
2656
+ const FACTORY_PR_STATUS_HUD_JOB_ID = "status-hud";
2657
+ const FACTORY_PR_STATUS_HUD_JOB_NAME = "Present PR status HUD";
2658
+ const FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID = "factory-app-token";
2659
+ const FACTORY_PR_STATUS_HUD_PLAN_PATH = ".factory-memory/preview-plan.json";
2660
+ /**
2661
+ * Presentation is independent of deploy demand. Callers who `needs` the jobs
2662
+ * that settle HUD sources (verify, deploy) must keep this `always()` so a
2663
+ * skipped or withdrawn deploy still publishes Skipped rows.
2664
+ */
2665
+ const FACTORY_PR_STATUS_HUD_IF = "always() && github.event_name == 'pull_request' && github.event.pull_request.draft != true";
2666
+ /**
2667
+ * Least privilege for the job that runs the present step. The present step
2668
+ * is an inventory `list`, so the job needs exactly the inventory's read
2669
+ * permissions (#825, #859).
2670
+ */
2671
+ const FACTORY_PR_STATUS_HUD_PERMISSIONS = PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS;
2672
+ const FACTORY_PR_STATUS_HUD_CONCURRENCY = Object.freeze({
2673
+ cancelInProgress: false,
2674
+ group: `status-hud-\${{ github.repository }}-\${{ github.event.pull_request.number }}`
2675
+ });
2676
+ const defaultCli = "psf";
2677
+ const factoryPrStatusHudWorkflow = (options) => {
2678
+ assertPinnedAction("createGithubAppToken", options.createGithubAppToken, "actions/create-github-app-token");
2679
+ const cli = options.cli || defaultCli;
2680
+ assertRunnableCli("cli", cli);
2681
+ const mintStep = Object.freeze({
2682
+ id: FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID,
2683
+ name: "Mint the factory App token",
2684
+ uses: options.createGithubAppToken.uses,
2685
+ with: Object.freeze({
2686
+ "client-id": FACTORY_PROOF_GATE_APP_ID,
2687
+ "private-key": `\${{ secrets.FACTORY_GITHUB_APP_PRIVATE_KEY }}`
2688
+ })
2689
+ });
2690
+ const presentStep = Object.freeze({
2691
+ env: Object.freeze({
2692
+ FACTORY_GITHUB_APP_TOKEN: `\${{ steps.${FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID}.outputs.token }}`,
2693
+ FACTORY_HEAD_SHA: `\${{ github.event.pull_request.head.sha }}`,
2694
+ FACTORY_OWNER: `\${{ github.repository_owner }}`,
2695
+ FACTORY_PR: `\${{ github.event.pull_request.number }}`,
2696
+ FACTORY_REPO: `\${{ github.event.repository.name }}`,
2697
+ GITHUB_TOKEN: `\${{ github.token }}`
2698
+ }),
2699
+ name: "Present the PR status HUD",
2700
+ run: `${cli} pr:status-hud --head "$FACTORY_HEAD_SHA" --owner "$FACTORY_OWNER" --repo "$FACTORY_REPO" --pr "$FACTORY_PR"`
2701
+ });
2702
+ return Object.freeze({
2703
+ concurrency: FACTORY_PR_STATUS_HUD_CONCURRENCY,
2704
+ if: FACTORY_PR_STATUS_HUD_IF,
2705
+ jobId: FACTORY_PR_STATUS_HUD_JOB_ID,
2706
+ jobName: FACTORY_PR_STATUS_HUD_JOB_NAME,
2707
+ permissions: FACTORY_PR_STATUS_HUD_PERMISSIONS,
2708
+ presentSteps: Object.freeze([mintStep, presentStep])
2709
+ });
2710
+ };
2711
+ const FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_ID = "stage-residue-audit";
2712
+ const FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_NAME = "Stage residue audit";
2713
+ const JOB_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]*$/u;
2714
+ const STACK_JOB_SAFE = /[^A-Za-z0-9_-]+/gu;
2715
+ const assertSingleLine$1 = (name, value) => {
2716
+ if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
2717
+ };
2718
+ const previewCleanupDestroyJobId = (stack) => {
2719
+ assertSingleLine$1("cleanup stack", stack);
2720
+ const suffix = stack.replaceAll(STACK_JOB_SAFE, "-").replaceAll(/^-+|-+$/gu, "");
2721
+ if (suffix.length === 0) throw new Error(`Cleanup stack "${stack}" has no job-id-safe characters.`);
2722
+ const jobId = `destroy-${suffix}`;
2723
+ if (!JOB_ID_PATTERN.test(jobId)) throw new Error(`Cleanup destroy job id "${jobId}" is not a GitHub Actions job id.`);
2724
+ return jobId;
2725
+ };
2726
+ /**
2727
+ * Generate the factory-owned preview-cleanup topology (#764): one destroy
2728
+ * job identity per stack, then exactly one stage-wide residue-audit job
2729
+ * that `needs` every destroy. The audit is whole-stage — this helper never
2730
+ * threads a stack name or path filter into it. Callers own destroy steps,
2731
+ * what counts as residue, credentials, and runners.
2732
+ */
2733
+ const factoryPreviewCleanupTopology = (options) => {
2734
+ if (options.stacks.length === 0) throw new Error("Preview cleanup topology requires at least one stack so the audit can depend on every destroy.");
2735
+ const destroyJobs = options.stacks.map((stack) => Object.freeze({
2736
+ jobId: previewCleanupDestroyJobId(stack),
2737
+ stack
2738
+ }));
2739
+ const destroyJobIds = destroyJobs.map(({ jobId }) => jobId);
2740
+ if (new Set(destroyJobIds).size !== destroyJobIds.length) throw new Error("Cleanup stack names must map to distinct destroy job ids.");
2741
+ assertSingleLine$1("audit.command", options.audit.command);
2742
+ const jobId = options.audit.jobId ?? "stage-residue-audit";
2743
+ const jobName = options.audit.jobName ?? "Stage residue audit";
2744
+ if (!JOB_ID_PATTERN.test(jobId)) throw new Error("audit.jobId must be a GitHub Actions job id.");
2745
+ assertSingleLine$1("audit.jobName", jobName);
2746
+ if (destroyJobIds.includes(jobId)) throw new Error("audit.jobId must not collide with a destroy job id.");
2747
+ const auditStep = Object.freeze({
2748
+ name: "Assert stage absent",
2749
+ run: options.audit.command
2750
+ });
2751
+ return Object.freeze({
2752
+ auditJob: Object.freeze({
2753
+ if: "always()",
2754
+ jobId,
2755
+ jobName,
2756
+ needs: Object.freeze([...destroyJobIds]),
2757
+ steps: Object.freeze([auditStep])
2758
+ }),
2759
+ destroyJobs: Object.freeze(destroyJobs)
2760
+ });
2761
+ };
2762
+ const DEFAULT_SWEEP_MAX_TARGETS = 50;
2763
+ /** GitHub refuses a matrix with more than 256 entries. */
2764
+ const MATRIX_ENTRY_LIMIT$1 = 256;
2765
+ const DEFAULT_TIMEOUT_MS = 5e3;
2766
+ const PULL_STATE_CONCURRENCY = 8;
2767
+ const STACK_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u;
2768
+ const HOSTED_STAGE_PREFIX_PATTERN = /^[a-z][a-z0-9-]*-$/u;
2769
+ const OUTPUT_KEY_UNSAFE = /[^a-z0-9_]+/gu;
2770
+ const FULL_SHA_PATTERN = /^[0-9a-f]{40}$/u;
2771
+ const isRecord$1 = (value) => typeof value === "object" && value !== null;
2772
+ /** The GitHub-output key a stack's matrix and presence flag use. */
2773
+ const previewCleanupStackOutputKey = (stack) => {
2774
+ const key = stack.toLowerCase().replaceAll(OUTPUT_KEY_UNSAFE, "_").replaceAll(/^_+|_+$/gu, "");
2775
+ if (key.length === 0) throw new Error(`Cleanup stack "${stack}" has no output-safe characters.`);
2776
+ return key;
2777
+ };
2778
+ /**
2779
+ * Validate a stack policy. Throws on an empty or duplicate stack list, a
2780
+ * stack name a shell or GitHub output could misread, an alias to an
2781
+ * undeclared stack, or a hosted prefix that is not `<word>-`.
2782
+ */
2783
+ const assertPreviewCleanupStackPolicy = (policy) => {
2784
+ if (policy.stacks.length === 0) throw new Error("Preview cleanup requires at least one stack.");
2785
+ for (const stack of policy.stacks) if (!STACK_NAME_PATTERN.test(stack)) throw new Error(`Cleanup stack "${stack}" must match ${STACK_NAME_PATTERN.source}.`);
2786
+ if (new Set(policy.stacks).size !== policy.stacks.length) throw new Error("Cleanup stacks must be distinct.");
2787
+ const keys = policy.stacks.map(previewCleanupStackOutputKey);
2788
+ if (new Set(keys).size !== keys.length) throw new Error("Cleanup stacks must map to distinct output keys.");
2789
+ for (const [alias, stack] of Object.entries(policy.stackAliases ?? {})) {
2790
+ if (!STACK_NAME_PATTERN.test(alias)) throw new Error(`Cleanup stack alias "${alias}" must match ${STACK_NAME_PATTERN.source}.`);
2791
+ if (!policy.stacks.includes(stack)) throw new Error(`Cleanup stack alias "${alias}" names undeclared stack "${stack}".`);
2792
+ }
2793
+ if (policy.hostedStagePrefix !== void 0 && (!HOSTED_STAGE_PREFIX_PATTERN.test(policy.hostedStagePrefix) || policy.hostedStagePrefix.startsWith("local-"))) throw new Error(`hostedStagePrefix must look like "pr-" and must not overlap the disposable local grammar, got "${policy.hostedStagePrefix}".`);
2794
+ };
2795
+ const resolveStack = (policy, stack) => {
2796
+ if (policy.stacks.includes(stack)) return stack;
2797
+ const aliased = policy.stackAliases?.[stack];
2798
+ return aliased !== void 0 && policy.stacks.includes(aliased) ? aliased : void 0;
2799
+ };
2800
+ /** The PR a hosted stage belongs to, or `null` when it is not one. */
2801
+ const parseHostedPreviewStage = (stage, prefix) => {
2802
+ if (!stage.startsWith(prefix)) return null;
2803
+ const digits = stage.slice(prefix.length);
2804
+ if (!/^[1-9]\d*$/u.test(digits)) return null;
2805
+ const pr = Number(digits);
2806
+ return Number.isSafeInteger(pr) ? pr : null;
2807
+ };
2808
+ /** The PR that owns a disposable stage, or `null` when it is not disposable. */
2809
+ const disposableStageOwner = (policy, stage) => parseLocalPreviewStage(stage)?.pr ?? (policy.hostedStagePrefix === void 0 ? null : parseHostedPreviewStage(stage, policy.hostedStagePrefix));
2810
+ const targetKey = (target) => `${target.stack}\u0000${target.stage}`;
2811
+ const compareTargets = (left, right) => left.pr - right.pr || left.stack.localeCompare(right.stack) || left.stage.localeCompare(right.stage);
2812
+ const assertPositivePr = (pr) => {
2813
+ if (!Number.isSafeInteger(pr) || pr < 1) throw new Error(`Cleanup PR must be a positive integer, got ${pr}.`);
2814
+ };
2815
+ /**
2816
+ * Targets for one closed PR: its inventory registrations united with the
2817
+ * residue the consumer still sees for it. Only the PR's own `local-pr-<pr>-*`
2818
+ * stages and its hosted stage survive, in declared stacks. A registration
2819
+ * wins a collision so its head SHA reaches the cleanup record. A registration
2820
+ * whose cleanup already passed is skipped unless the residue still lists it.
2821
+ */
2822
+ const discoverPreviewCleanupTargets = (input) => {
2823
+ assertPreviewCleanupStackPolicy(input);
2824
+ assertPositivePr(input.pr);
2825
+ const hostedStage = input.hostedStagePrefix === void 0 ? void 0 : `${input.hostedStagePrefix}${input.pr}`;
2826
+ const byKey = /* @__PURE__ */ new Map();
2827
+ const residueKeys = new Set(input.residue.flatMap((row) => {
2828
+ const stack = resolveStack(input, row.stack);
2829
+ return stack === void 0 ? [] : [targetKey({
2830
+ stack,
2831
+ stage: row.stage
2832
+ })];
2833
+ }));
2834
+ for (const row of input.registrations) {
2835
+ const stack = resolveStack(input, row.stack);
2836
+ const settled = stack !== void 0 && row.cleanup.outcome === "passed" && !residueKeys.has(targetKey({
2837
+ stack,
2838
+ stage: row.stage
2839
+ }));
2840
+ if (row.pr === input.pr && stack !== void 0 && !settled && isLocalPreviewStage(row.stage, input.pr)) {
2841
+ const target = {
2842
+ headSha: row.headSha,
2843
+ pr: input.pr,
2844
+ stack,
2845
+ stage: row.stage
2846
+ };
2847
+ byKey.set(targetKey(target), target);
2848
+ }
2849
+ }
2850
+ for (const row of input.residue) {
2851
+ const stack = resolveStack(input, row.stack);
2852
+ if (stack !== void 0 && (isLocalPreviewStage(row.stage, input.pr) || row.stage === hostedStage)) {
2853
+ const target = {
2854
+ pr: input.pr,
2855
+ stack,
2856
+ stage: row.stage
2857
+ };
2858
+ if (!byKey.has(targetKey(target))) byKey.set(targetKey(target), target);
2859
+ }
2860
+ }
2861
+ return Object.freeze([...byKey.values()].toSorted(compareTargets));
2862
+ };
2863
+ /**
2864
+ * The PRs whose disposable stages appear in the residue. The sweep reads
2865
+ * their state before it decides anything.
2866
+ */
2867
+ const previewCleanupResiduePullRequests = (policy, residue) => {
2868
+ assertPreviewCleanupStackPolicy(policy);
2869
+ const prs = /* @__PURE__ */ new Set();
2870
+ for (const row of residue) {
2871
+ const pr = resolveStack(policy, row.stack) === void 0 ? null : disposableStageOwner(policy, row.stage);
2872
+ if (pr !== null) prs.add(pr);
2873
+ }
2874
+ return Object.freeze([...prs].toSorted((left, right) => left - right));
2875
+ };
2876
+ /**
2877
+ * Targets for the scheduled sweep: disposable residue whose PR GitHub
2878
+ * reports closed. It fails closed. A stage that does not parse as disposable,
2879
+ * a stack the consumer did not declare, and a PR that is open or whose state
2880
+ * is unknown are all retained.
2881
+ */
2882
+ const discoverOrphanedPreviewCleanupTargets = (input) => {
2883
+ assertPreviewCleanupStackPolicy(input);
2884
+ const maxTargets = input.maxTargets ?? DEFAULT_SWEEP_MAX_TARGETS;
2885
+ if (!Number.isInteger(maxTargets) || maxTargets < 1 || maxTargets > MATRIX_ENTRY_LIMIT$1) throw new Error(`maxTargets must be an integer from 1 through ${MATRIX_ENTRY_LIMIT$1}, got ${maxTargets}.`);
2886
+ const byKey = /* @__PURE__ */ new Map();
2887
+ for (const row of input.residue) {
2888
+ const stack = resolveStack(input, row.stack);
2889
+ const pr = disposableStageOwner(input, row.stage);
2890
+ if (stack !== void 0 && pr !== null && input.pullRequestStates.get(pr) === "closed") {
2891
+ const target = {
2892
+ pr,
2893
+ stack,
2894
+ stage: row.stage
2895
+ };
2896
+ byKey.set(targetKey(target), target);
2897
+ }
2898
+ }
2899
+ const byStage = /* @__PURE__ */ new Map();
2900
+ for (const target of [...byKey.values()].toSorted(compareTargets)) byStage.set(target.stage, [...byStage.get(target.stage) ?? [], target]);
2901
+ const taken = [];
2902
+ let deferred = 0;
2903
+ for (const group of byStage.values()) if (deferred === 0 && (taken.length === 0 || taken.length + group.length <= maxTargets)) taken.push(...group);
2904
+ else deferred += group.length;
2905
+ return Object.freeze({
2906
+ deferred,
2907
+ targets: Object.freeze(taken)
2908
+ });
2909
+ };
2910
+ /**
2911
+ * The `$GITHUB_OUTPUT` lines the cleanup workflow's discover job publishes:
2912
+ * `has_targets`, `targets`, and for each declared stack `has_<key>` and
2913
+ * `<key>_matrix`. A stack with no target still gets `has_<key>=false`, so
2914
+ * its destroy job skips instead of expanding an empty matrix.
2915
+ */
2916
+ const previewCleanupGithubOutput = (policy, targets) => {
2917
+ assertPreviewCleanupStackPolicy(policy);
2918
+ const lines = [`has_targets=${targets.length > 0}`, `targets=${JSON.stringify(targets)}`];
2919
+ for (const stack of policy.stacks) {
2920
+ const key = previewCleanupStackOutputKey(stack);
2921
+ const include = targets.filter((target) => target.stack === stack);
2922
+ if (include.length > MATRIX_ENTRY_LIMIT$1) throw new Error(`Cleanup stack "${stack}" has ${include.length} targets; a GitHub matrix holds at most ${MATRIX_ENTRY_LIMIT$1}.`);
2923
+ lines.push(`has_${key}=${include.length > 0}`, `${key}_matrix=${JSON.stringify({ include })}`);
2924
+ }
2925
+ return `${lines.join("\n")}\n`;
2926
+ };
2927
+ /** Parse untrusted residue JSON: an array of `{ stack, stage }` rows. */
2928
+ const parsePreviewCleanupResidue = (value) => {
2929
+ if (!Array.isArray(value)) throw new TypeError("Preview cleanup residue must be a JSON array.");
2930
+ return Object.freeze(value.map((row, index) => {
2931
+ if (!isRecord$1(row) || typeof row.stack !== "string" || typeof row.stage !== "string") throw new TypeError(`Preview cleanup residue row ${index} must have string stack and stage.`);
2932
+ return Object.freeze({
2933
+ stack: row.stack,
2934
+ stage: row.stage
2935
+ });
2936
+ }));
2937
+ };
2938
+ /**
2939
+ * Parse untrusted target JSON (the discover job's `targets` output). Every
2940
+ * row must still be a disposable stage owned by its own PR, so a tampered
2941
+ * output cannot widen the audit or a record.
2942
+ */
2943
+ const parsePreviewCleanupTargets = (policy, value) => {
2944
+ assertPreviewCleanupStackPolicy(policy);
2945
+ if (!Array.isArray(value)) throw new TypeError("Preview cleanup targets must be a JSON array.");
2946
+ return Object.freeze(value.map((row, index) => {
2947
+ if (!isRecord$1(row) || typeof row.pr !== "number" || typeof row.stack !== "string" || typeof row.stage !== "string" || row.headSha !== void 0 && (typeof row.headSha !== "string" || !FULL_SHA_PATTERN.test(row.headSha))) throw new TypeError(`Preview cleanup target ${index} is malformed.`);
2948
+ if (!policy.stacks.includes(row.stack) || disposableStageOwner(policy, row.stage) !== row.pr) throw new Error(`Preview cleanup target ${row.stack}/${row.stage} is not a disposable stage of PR #${row.pr} in a declared stack.`);
2949
+ return Object.freeze({
2950
+ ...typeof row.headSha === "string" ? { headSha: row.headSha } : {},
2951
+ pr: row.pr,
2952
+ stack: row.stack,
2953
+ stage: row.stage
2954
+ });
2955
+ }));
2956
+ };
2957
+ /**
2958
+ * The whole-stage audit after every destroy. Any residue row whose stage
2959
+ * is a target stage fails it, whatever stack the reader assigned the row,
2960
+ * because a sibling stack's leftovers are the same stage's residue.
2961
+ */
2962
+ const assertPreviewCleanupTargetsAbsent = (targets, residue) => {
2963
+ const stages = new Set(targets.map(({ stage }) => stage));
2964
+ const remaining = residue.filter(({ stage }) => stages.has(stage));
2965
+ if (remaining.length > 0) throw new Error(`Disposable stage residue remains: ${remaining.map(({ stack, stage }) => `${stack}/${stage}`).toSorted().join(", ")}`);
2966
+ };
2967
+ const storeFor = (role, access) => {
2968
+ if (access.store !== void 0) return access.store;
2969
+ if (access.token === void 0 || access.token.length === 0) throw new Error(`Preview cleanup ${role} access requires a token.`);
2970
+ return previewProofInventory.githubStore({
2971
+ ...access.fetch === void 0 ? {} : { fetch: access.fetch },
2972
+ ...access.timeoutMs === void 0 ? {} : { timeoutMs: access.timeoutMs },
2973
+ token: access.token
2974
+ });
2975
+ };
2976
+ /**
2977
+ * Record one stack destroy's outcome on the inventory registration it
2978
+ * cleaned up. A stage nothing registered (residue-only, or a hosted stage)
2979
+ * returns `unregistered` without writing. A registration whose last cleanup
2980
+ * failed is recovered through the same cleanup transition.
2981
+ */
2982
+ const recordPreviewCleanupOutcome = async (input, access) => {
2983
+ assertPositivePr(input.pr);
2984
+ if (!isLocalPreviewStage(input.stage, input.pr)) return { kind: "unregistered" };
2985
+ const readStore = storeFor("read", access.read);
2986
+ const writeStore = storeFor("write", access.write);
2987
+ const store = {
2988
+ list: (query) => readStore.list(query),
2989
+ put: (write) => writeStore.put(write)
2990
+ };
2991
+ const canonical = (stack) => input.stackAliases?.[stack] ?? stack;
2992
+ const existing = (await previewProofInventory.list({
2993
+ owner: input.owner,
2994
+ pr: input.pr,
2995
+ repo: input.repo,
2996
+ stage: input.stage
2997
+ }, { store })).find((row) => row.pr === input.pr && row.stage === input.stage && canonical(row.stack) === canonical(input.stack));
2998
+ if (existing === void 0) return { kind: "unregistered" };
2999
+ const registration = await previewProofInventory.recordCleanup({
3000
+ evidence: input.evidence,
3001
+ ...input.headSha === void 0 ? {} : { headSha: input.headSha },
3002
+ outcome: input.outcome,
3003
+ owner: input.owner,
3004
+ pr: input.pr,
3005
+ repo: input.repo,
3006
+ ...input.runUrl === void 0 ? {} : { runUrl: input.runUrl },
3007
+ stack: existing.stack,
3008
+ stage: existing.stage
3009
+ }, { store });
3010
+ return {
3011
+ kind: existing.cleanup.outcome === "failed" ? "recovered" : "recorded",
3012
+ registration
3013
+ };
3014
+ };
3015
+ const readPullRequestState = async (input, access) => {
3016
+ let pull;
3017
+ try {
3018
+ pull = await githubJson$1({
3019
+ fetch: access.fetch ?? fetch,
3020
+ method: "GET",
3021
+ timeoutMs: access.timeoutMs ?? DEFAULT_TIMEOUT_MS,
3022
+ token: access.token,
3023
+ url: `https://api.github.com/repos/${encodeURIComponent(input.owner)}/${encodeURIComponent(input.repo)}/pulls/${input.pr}`
3024
+ }, {
3025
+ refusal: (status, statusText) => new GitHubApiError(status, statusText),
3026
+ transport: (failure, attempts) => new PreviewProofTransportError(failure.reason, attempts, failure.status)
3027
+ });
3028
+ } catch (error) {
3029
+ if (error instanceof GitHubApiError && error.status === 404) return null;
3030
+ throw error;
3031
+ }
3032
+ if (!isRecord$1(pull) || pull.number !== input.pr || pull.state !== "open" && pull.state !== "closed") throw new Error(`GitHub returned an unreadable pull request #${input.pr}.`);
3033
+ return pull.state;
3034
+ };
3035
+ /**
3036
+ * Ask GitHub for each PR's state. A PR GitHub does not know is left out of
3037
+ * the map, so the sweep retains its stages.
3038
+ */
3039
+ const readPullRequestStates = async (input, access) => {
3040
+ const states = /* @__PURE__ */ new Map();
3041
+ for (let start = 0; start < input.prs.length; start += PULL_STATE_CONCURRENCY) {
3042
+ const batch = input.prs.slice(start, start + PULL_STATE_CONCURRENCY);
3043
+ const read = await Promise.all(batch.map(async (pr) => ({
3044
+ pr,
3045
+ state: await readPullRequestState({
3046
+ owner: input.owner,
3047
+ pr,
3048
+ repo: input.repo
3049
+ }, access)
3050
+ })));
3051
+ for (const { pr, state } of read) if (state !== null) states.set(pr, state);
3052
+ }
3053
+ return states;
3054
+ };
3055
+ const FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID = "discover";
3056
+ const FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_NAME = "Discover preview cleanup targets";
3057
+ const FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID = "targets";
3058
+ const FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID = "destroy";
3059
+ const FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID = "factory-app-token";
3060
+ const FACTORY_PREVIEW_CLEANUP_DEFAULT_SWEEP_CRON = "23 6 * * *";
3061
+ /**
3062
+ * A closed pull request whose head lives in this repository. A fork's head
3063
+ * never reaches a job that holds cleanup credentials.
3064
+ */
3065
+ const FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION = "github.event_name == 'pull_request_target' && github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository";
3066
+ /**
3067
+ * The sweep: the schedule, which GitHub always runs on the default branch,
3068
+ * or a manual dispatch from the default branch.
3069
+ */
3070
+ const FACTORY_PREVIEW_CLEANUP_SWEEP_CONDITION = "github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch))";
3071
+ /**
3072
+ * The ref every cleanup job checks out: the default branch's trusted code,
3073
+ * never the closed PR's head. Empty on `schedule`, where the checkout
3074
+ * already defaults to the default branch.
3075
+ */
3076
+ const FACTORY_PREVIEW_CLEANUP_CHECKOUT_REF = `\${{ github.event.repository.default_branch }}`;
3077
+ const RESIDUE_PATH = "$RUNNER_TEMP/factory-preview-cleanup-residue.json";
3078
+ const RESIDUE_AFTER_PATH = "$RUNNER_TEMP/factory-preview-cleanup-residue-after.json";
3079
+ const EVIDENCE_PATH = "$RUNNER_TEMP/factory-preview-cleanup-evidence.txt";
3080
+ const ENVIRONMENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/u;
3081
+ const CRON_PATTERN = /^\S+(?: \S+){4}$/u;
3082
+ /** GitHub refuses a matrix with more than 256 entries. */
3083
+ const MATRIX_ENTRY_LIMIT = 256;
3084
+ const shellQuote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
3085
+ const assertSingleLine = (name, value) => {
3086
+ if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
3087
+ };
3088
+ const policyFlags = (policy) => [
3089
+ ...policy.stacks.map((stack) => `--stack ${shellQuote(stack)}`),
3090
+ ...Object.entries(policy.stackAliases ?? {}).toSorted(([left], [right]) => left.localeCompare(right)).map(([alias, stack]) => `--stack-alias ${shellQuote(`${alias}=${stack}`)}`),
3091
+ ...policy.hostedStagePrefix === void 0 ? [] : [`--hosted-stage-prefix ${shellQuote(policy.hostedStagePrefix)}`]
3092
+ ].join(" ");
3093
+ const discoverScript = (cli, flags, sweep) => {
3094
+ const prMode = `${cli} preview:cleanup --action discover --pr "$FACTORY_PREVIEW_CLEANUP_PR" --residue "${RESIDUE_PATH}" ${flags} --github-output "$GITHUB_OUTPUT"`;
3095
+ if (sweep === false) return prMode;
3096
+ const maxTargets = sweep?.maxTargets === void 0 ? "" : ` --max-targets ${sweep.maxTargets}`;
3097
+ return [
3098
+ "if [ \"$GITHUB_EVENT_NAME\" = pull_request_target ]; then",
3099
+ ` ${prMode}`,
3100
+ "else",
3101
+ ` ${cli} preview:cleanup --action sweep --residue "${RESIDUE_PATH}" ${flags}${maxTargets} --github-output "$GITHUB_OUTPUT"`,
3102
+ "fi"
3103
+ ].join("\n");
3104
+ };
3105
+ const destroyScript = (destroyCommand) => [
3106
+ `evidence="${EVIDENCE_PATH}"`,
3107
+ ": > \"$evidence\"",
3108
+ "export FACTORY_PREVIEW_CLEANUP_EVIDENCE=\"$evidence\"",
3109
+ "echo \"evidence=$evidence\" >> \"$GITHUB_OUTPUT\"",
3110
+ "target=\"$FACTORY_PREVIEW_CLEANUP_STACK/$FACTORY_PREVIEW_CLEANUP_STAGE\"",
3111
+ `if ( ${destroyCommand} ); then`,
3112
+ " echo \"destroy exited 0 for $target\" >> \"$evidence\"",
3113
+ " echo \"outcome=passed\" >> \"$GITHUB_OUTPUT\"",
3114
+ "else",
3115
+ " status=$?",
3116
+ " echo \"destroy exited $status for $target; the stage may remain and the stage residue audit decides\" >> \"$evidence\"",
3117
+ " echo \"outcome=failed\" >> \"$GITHUB_OUTPUT\"",
3118
+ "fi",
3119
+ "cat \"$evidence\"",
3120
+ "cat \"$evidence\" >> \"$GITHUB_STEP_SUMMARY\""
3121
+ ].join("\n");
3122
+ /**
3123
+ * Generate the factory-owned closed-PR preview cleanup and orphan sweep
3124
+ * (#1540) on top of `factoryPreviewCleanupTopology`:
3125
+ *
3126
+ * - `discover` reads the consumer's residue and, for a closed same-repo PR,
3127
+ * unites it with the PR's inventory registrations; for the sweep, keeps the
3128
+ * residue of PRs GitHub reports closed. It publishes one matrix per stack.
3129
+ * - one destroy job per stack runs the consumer's destroy for each matrix
3130
+ * target, then records the outcome on the inventory with the Factory App.
3131
+ * - one stage-wide audit re-reads the residue after every destroy and fails
3132
+ * if any target stage remains, in any stack.
3133
+ *
3134
+ * Every credentialed job runs in the consumer's GitHub environment, never
3135
+ * behind a production deploy flag. The caller prepends its own setup steps
3136
+ * (checked out at `checkoutRef`), and adds `runsOn` and credential `env`.
3137
+ */
3138
+ const factoryPreviewCleanupWorkflow = (options) => {
3139
+ assertPreviewCleanupStackPolicy(options);
3140
+ assertPinnedAction("createGithubAppToken", options.createGithubAppToken, "actions/create-github-app-token");
3141
+ const cli = options.cli ?? "pnpm exec psf";
3142
+ assertRunnableCli("cli", cli);
3143
+ assertSingleLine("cli", cli);
3144
+ assertSingleLine("residueCommand", options.residueCommand);
3145
+ assertSingleLine("destroyCommand", options.destroyCommand);
3146
+ if (!ENVIRONMENT_PATTERN.test(options.environment)) throw new Error("environment must name the GitHub environment that gates cleanup credentials.");
3147
+ const { sweep } = options;
3148
+ const cron = sweep === false ? void 0 : sweep?.cron ?? "23 6 * * *";
3149
+ if (cron !== void 0 && !CRON_PATTERN.test(cron)) throw new Error(`sweep.cron must have five fields, got "${cron}".`);
3150
+ const maxTargets = sweep === false ? void 0 : sweep?.maxTargets;
3151
+ if (maxTargets !== void 0 && (!Number.isInteger(maxTargets) || maxTargets < 1 || maxTargets > MATRIX_ENTRY_LIMIT)) throw new Error(`sweep.maxTargets must be an integer from 1 through ${MATRIX_ENTRY_LIMIT}, got ${maxTargets}.`);
3152
+ const concurrencyGroup = options.concurrencyGroup ?? `factory-preview-cleanup-\${{ github.repository }}-\${{ matrix.stack }}-\${{ matrix.stage }}`;
3153
+ assertSingleLine("concurrencyGroup", concurrencyGroup);
3154
+ const flags = policyFlags(options);
3155
+ const discoverIf = sweep === false ? FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION : `(${FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION}) || (${FACTORY_PREVIEW_CLEANUP_SWEEP_CONDITION})`;
3156
+ const discoverOutput = (name) => `\${{ steps.${FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID}.outputs.${name} }}`;
3157
+ const outputs = {
3158
+ has_targets: discoverOutput("has_targets"),
3159
+ targets: discoverOutput("targets")
3160
+ };
3161
+ for (const stack of options.stacks) {
3162
+ const key = previewCleanupStackOutputKey(stack);
3163
+ outputs[`has_${key}`] = discoverOutput(`has_${key}`);
3164
+ outputs[`${key}_matrix`] = discoverOutput(`${key}_matrix`);
3165
+ }
3166
+ const discoverJob = Object.freeze({
3167
+ environment: options.environment,
3168
+ if: discoverIf,
3169
+ jobId: FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID,
3170
+ jobName: FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_NAME,
3171
+ outputs: Object.freeze(outputs),
3172
+ permissions: PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS,
3173
+ steps: Object.freeze([Object.freeze({
3174
+ name: "Read preview residue",
3175
+ run: `${options.residueCommand} > "${RESIDUE_PATH}"`
3176
+ }), Object.freeze({
3177
+ env: Object.freeze({
3178
+ FACTORY_PREVIEW_CLEANUP_PR: `\${{ github.event.pull_request.number }}`,
3179
+ GITHUB_TOKEN: `\${{ github.token }}`
3180
+ }),
3181
+ id: FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID,
3182
+ name: "Discover cleanup targets",
3183
+ run: discoverScript(cli, flags, sweep)
3184
+ })])
3185
+ });
3186
+ const topology = factoryPreviewCleanupTopology({
3187
+ audit: { command: `${options.residueCommand} > "${RESIDUE_AFTER_PATH}" && ${cli} preview:cleanup --action audit --residue "${RESIDUE_AFTER_PATH}" --targets "$FACTORY_PREVIEW_CLEANUP_TARGETS" ${flags}` },
3188
+ stacks: options.stacks
3189
+ });
3190
+ if (topology.destroyJobs.some(({ jobId }) => jobId === "discover")) throw new Error("A cleanup stack's destroy job id collides with discover.");
3191
+ const matrixEnv = Object.freeze({
3192
+ FACTORY_PREVIEW_CLEANUP_HEAD_SHA: `\${{ matrix.headSha }}`,
3193
+ FACTORY_PREVIEW_CLEANUP_PR: `\${{ matrix.pr }}`,
3194
+ FACTORY_PREVIEW_CLEANUP_STACK: `\${{ matrix.stack }}`,
3195
+ FACTORY_PREVIEW_CLEANUP_STAGE: `\${{ matrix.stage }}`
3196
+ });
3197
+ const destroyOutput = (name) => `\${{ steps.${FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID}.outputs.${name} }}`;
3198
+ const destroyedIf = `always() && steps.${FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID}.outputs.outcome != ''`;
3199
+ const destroySteps = Object.freeze([
3200
+ Object.freeze({
3201
+ env: matrixEnv,
3202
+ id: FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID,
3203
+ name: "Destroy the stage",
3204
+ run: destroyScript(options.destroyCommand)
3205
+ }),
3206
+ Object.freeze({
3207
+ id: FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID,
3208
+ if: destroyedIf,
3209
+ name: "Mint the factory App token",
3210
+ uses: options.createGithubAppToken.uses,
3211
+ with: Object.freeze({
3212
+ "client-id": FACTORY_PROOF_GATE_APP_ID,
3213
+ "private-key": `\${{ secrets.FACTORY_GITHUB_APP_PRIVATE_KEY }}`
3214
+ })
3215
+ }),
3216
+ Object.freeze({
3217
+ env: Object.freeze({
3218
+ ...matrixEnv,
3219
+ FACTORY_GITHUB_APP_TOKEN: `\${{ steps.${FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID}.outputs.token }}`,
3220
+ FACTORY_PREVIEW_CLEANUP_EVIDENCE: destroyOutput("evidence"),
3221
+ FACTORY_PREVIEW_CLEANUP_OUTCOME: destroyOutput("outcome"),
3222
+ GITHUB_TOKEN: `\${{ github.token }}`
3223
+ }),
3224
+ if: destroyedIf,
3225
+ name: "Record the cleanup outcome",
3226
+ run: `${cli} preview:cleanup --action record --pr "$FACTORY_PREVIEW_CLEANUP_PR" --target-stack "$FACTORY_PREVIEW_CLEANUP_STACK" --target-stage "$FACTORY_PREVIEW_CLEANUP_STAGE" --outcome "$FACTORY_PREVIEW_CLEANUP_OUTCOME" --evidence-file "$FACTORY_PREVIEW_CLEANUP_EVIDENCE" \${FACTORY_PREVIEW_CLEANUP_HEAD_SHA:+--head-sha "$FACTORY_PREVIEW_CLEANUP_HEAD_SHA"} ${flags}`
3227
+ }),
3228
+ Object.freeze({
3229
+ env: Object.freeze({ FACTORY_PREVIEW_CLEANUP_OUTCOME: destroyOutput("outcome") }),
3230
+ if: "always()",
3231
+ name: "Require a passed destroy",
3232
+ run: "test \"$FACTORY_PREVIEW_CLEANUP_OUTCOME\" = passed"
3233
+ })
3234
+ ]);
3235
+ const destroyJobs = topology.destroyJobs.map(({ jobId, stack }) => {
3236
+ const key = previewCleanupStackOutputKey(stack);
3237
+ return Object.freeze({
3238
+ concurrency: Object.freeze({
3239
+ cancelInProgress: false,
3240
+ group: concurrencyGroup
3241
+ }),
3242
+ environment: options.environment,
3243
+ if: `needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.has_${key} == 'true'`,
3244
+ jobId,
3245
+ jobName: `Destroy ${stack}`,
3246
+ needs: Object.freeze([FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID]),
3247
+ permissions: PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS,
3248
+ stack,
3249
+ steps: destroySteps,
3250
+ strategy: Object.freeze({
3251
+ failFast: false,
3252
+ matrix: Object.freeze({ include: `\${{ fromJSON(needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.${key}_matrix).include }}` })
3253
+ })
3254
+ });
3255
+ });
3256
+ const auditJob = Object.freeze({
3257
+ env: Object.freeze({ FACTORY_PREVIEW_CLEANUP_TARGETS: `\${{ needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.targets }}` }),
3258
+ environment: options.environment,
3259
+ if: `${topology.auditJob.if} && needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.result == 'success' && needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.has_targets == 'true'`,
3260
+ jobId: topology.auditJob.jobId,
3261
+ jobName: topology.auditJob.jobName,
3262
+ needs: Object.freeze([FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID, ...topology.auditJob.needs]),
3263
+ permissions: Object.freeze({ contents: "read" }),
3264
+ steps: topology.auditJob.steps
3265
+ });
3266
+ const on = { pull_request_target: Object.freeze({ types: Object.freeze(["closed"]) }) };
3267
+ if (cron !== void 0) {
3268
+ on.schedule = Object.freeze([Object.freeze({ cron })]);
3269
+ on.workflow_dispatch = Object.freeze({});
3270
+ }
3271
+ return Object.freeze({
3272
+ auditJob,
3273
+ checkoutRef: FACTORY_PREVIEW_CLEANUP_CHECKOUT_REF,
3274
+ destroyJobs: Object.freeze(destroyJobs),
3275
+ discoverJob,
3276
+ on: Object.freeze(on),
3277
+ permissions: Object.freeze({ contents: "read" })
3278
+ });
3279
+ };
3280
+ /** Receipt transport only. The consumer owns selection, lifecycle, smoke, and freshness. */
3281
+ const factoryPreviewReceiptWorkflow = (options) => {
3282
+ if (!/^preview:[a-z][a-z0-9-]*$/u.test(options.target)) throw new Error("Preview receipts require a declared preview target name.");
3283
+ const cli = options.cli ?? "pnpm exec psf";
3284
+ assertRunnableCli("cli", cli);
3285
+ const id = `preview_intent_${options.target.slice(8).replaceAll("-", "_")}`;
3286
+ const deploymentId = `\${{ steps.${id}.outputs.deployment_id }}`;
3287
+ const hasIntent = `steps.${id}.outputs.deployment_id != ''`;
3288
+ const env = {
3289
+ FACTORY_PREVIEW_PR: options.pr ?? `\${{ github.event.pull_request.number }}`,
3290
+ GH_TOKEN: `\${{ github.token }}`
3291
+ };
3292
+ const command = `${cli} preview:receipt --pr "$FACTORY_PREVIEW_PR" --target '${options.target}'`;
3293
+ return Object.freeze({
3294
+ beginStep: Object.freeze({
3295
+ env,
3296
+ id,
3297
+ name: `Record preview intent for ${options.target}`,
3298
+ run: `${command} --action begin --github-output "$GITHUB_OUTPUT"`
3299
+ }),
3300
+ completionSteps: Object.freeze([
3301
+ Object.freeze({
3302
+ env: {
3303
+ ...env,
3304
+ FACTORY_DEPLOYMENT_ID: deploymentId
3305
+ },
3306
+ if: `success() && ${hasIntent}`,
3307
+ name: `Complete preview receipt for ${options.target}`,
3308
+ run: `${command} --action complete --deployment-id "$FACTORY_DEPLOYMENT_ID" --outcome success`
3309
+ }),
3310
+ Object.freeze({
3311
+ env: { FACTORY_DEPLOYMENT_ID: deploymentId },
3312
+ if: `success() && ${hasIntent}`,
3313
+ name: `Bind deployment receipt ${deploymentId}`,
3314
+ run: "test -n \"$FACTORY_DEPLOYMENT_ID\""
3315
+ }),
3316
+ Object.freeze({
3317
+ env: {
3318
+ ...env,
3319
+ FACTORY_DEPLOYMENT_ID: deploymentId
3320
+ },
3321
+ if: `failure() && ${hasIntent}`,
3322
+ name: `Fail preview receipt for ${options.target}`,
3323
+ run: `${command} --action complete --deployment-id "$FACTORY_DEPLOYMENT_ID" --outcome failure`
3324
+ })
3325
+ ]),
3326
+ invalidateStep: Object.freeze({
3327
+ env,
3328
+ name: `Invalidate preview receipts for ${options.target}`,
3329
+ run: `${command} --action invalidate`
3330
+ }),
3331
+ permissions: Object.freeze({
3332
+ actions: "read",
3333
+ contents: "read",
3334
+ deployments: "write",
3335
+ "pull-requests": "read"
3336
+ })
3337
+ });
3338
+ };
3339
+ /** `owner/repo` slice of the catalog's `UPLOAD_ARTIFACT` pin, derived rather
3340
+ * than repeated as a literal, so a repository rename here cannot drift from
3341
+ * the pin it validates against. */
3342
+ const UPLOAD_ARTIFACT_REPOSITORY = UPLOAD_ARTIFACT.uses.slice(0, UPLOAD_ARTIFACT.uses.indexOf("@"));
3343
+ const FACTORY_PUSH_IDENTITY_SCHEMA_VERSION = 1;
3344
+ const FACTORY_PUSH_IDENTITY_ARTIFACT_PREFIX = "factory-push-identity";
3345
+ const FACTORY_PUSH_IDENTITY_RECORD_STEP_ID = "factory_push_identity_record";
3346
+ const FACTORY_PUSH_IDENTITY_LOOKUP_STEP_ID = "factory_push_identity_lookup";
3347
+ const FACTORY_PUSH_IDENTITY_DOWNLOAD_STEP_ID = "factory_push_identity_download";
3348
+ const FACTORY_PUSH_IDENTITY_CHECKOUT_STEP_ID = "factory_push_identity_checkout";
3349
+ const FACTORY_PUSH_IDENTITY_VALIDATE_STEP_ID = "factory_push_identity";
3350
+ const ARTIFACT_MAX_BYTES = 16384;
3351
+ const ENVELOPE_MAX_BYTES = 4096;
3352
+ const expression = (value) => `\${{ ${value} }}`;
3353
+ const artifactName = (runId) => `${FACTORY_PUSH_IDENTITY_ARTIFACT_PREFIX}-${runId}`;
3354
+ const producerScript = String.raw`identity="$RUNNER_TEMP/factory-push-identity.json"
3355
+ produced=false
3356
+ reason='producer_error'
3357
+ before=''
3358
+ event_after=''
3359
+ rm -f "$identity"
3360
+
3361
+ is_hex_sha() {
3362
+ [ "$(printf '%s' "$1" | wc -c | tr -d '[:space:]')" -eq 40 ] &&
3363
+ case "$1" in *[!0-9a-f]*) false;; *) true;; esac
3364
+ }
3365
+
3366
+ is_nonzero_sha() {
3367
+ is_hex_sha "$1" && [ "$1" != '0000000000000000000000000000000000000000' ]
3368
+ }
3369
+
3370
+ if [ "$GITHUB_EVENT_NAME" != 'push' ]; then
3371
+ reason='not_push_event'
3372
+ elif ! printf '%s' "$GITHUB_REPOSITORY" | grep -Eq '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$'; then
3373
+ reason='repository_invalid'
3374
+ elif ! printf '%s' "$GITHUB_RUN_ID" | grep -Eq '^[1-9][0-9]*$'; then
3375
+ reason='run_id_invalid'
3376
+ elif ! before="$(jq -er '.before | select(type == "string")' "$GITHUB_EVENT_PATH" 2>/dev/null)"; then
3377
+ reason='event_before_missing'
3378
+ elif ! event_after="$(jq -er '.after | select(type == "string")' "$GITHUB_EVENT_PATH" 2>/dev/null)"; then
3379
+ reason='event_after_missing'
3380
+ elif ! is_hex_sha "$before"; then
3381
+ reason='event_before_invalid'
3382
+ elif ! is_nonzero_sha "$event_after" || ! is_nonzero_sha "$GITHUB_SHA"; then
3383
+ reason='event_after_invalid'
3384
+ elif [ "$event_after" != "$GITHUB_SHA" ]; then
3385
+ reason='event_after_mismatch'
3386
+ elif jq -cn \
3387
+ --argjson schemaVersion '${1}' \
3388
+ --arg repository "$GITHUB_REPOSITORY" \
3389
+ --arg runId "$GITHUB_RUN_ID" \
3390
+ --arg before "$before" \
3391
+ --arg after "$event_after" \
3392
+ '{schemaVersion: $schemaVersion, repository: $repository, runId: $runId, before: $before, after: $after}' > "$identity"; then
3393
+ produced=true
3394
+ reason='produced'
3395
+ fi
3396
+
3397
+ printf 'produced=%s\nreason=%s\n' "$produced" "$reason" >> "$GITHUB_OUTPUT"
3398
+ {
3399
+ printf '## Exact push identity producer\n\n'
3400
+ printf -- '- Status: %s\n' "$reason"
3401
+ printf -- '- Repository/run: %s / %s\n' "$GITHUB_REPOSITORY" "$GITHUB_RUN_ID"
3402
+ if [ "$produced" = true ]; then
3403
+ printf -- '- Bound push: %s → %s\n' "$before" "$event_after"
3404
+ else
3405
+ printf -- '- Identity transport was not produced; downstream classification will refuse withdrawal.\n'
3406
+ fi
3407
+ } >> "$GITHUB_STEP_SUMMARY"`;
3408
+ const lookupScript = String.raw`status='refused'
3409
+ reason='artifact_lookup_failed'
3410
+ artifact_id=''
3411
+ matches="$RUNNER_TEMP/factory-push-identity-artifacts.tsv"
3412
+ artifact_name='${FACTORY_PUSH_IDENTITY_ARTIFACT_PREFIX}-'"$EXPECTED_RUN_ID"
3413
+ rm -f "$matches"
3414
+
3415
+ is_sha() {
3416
+ [ "$(printf '%s' "$1" | wc -c | tr -d '[:space:]')" -eq 40 ] &&
3417
+ [ "$1" != '0000000000000000000000000000000000000000' ] &&
3418
+ case "$1" in *[!0-9a-f]*) false;; *) true;; esac
3419
+ }
3420
+
3421
+ if [ "$EXPECTED_EVENT_NAME" != 'workflow_run' ]; then
3422
+ reason='event_not_workflow_run'
3423
+ elif [ "$EXPECTED_WORKFLOW_EVENT" != 'push' ]; then
3424
+ reason='triggering_workflow_not_push'
3425
+ elif [ "$EXPECTED_CONCLUSION" != 'success' ]; then
3426
+ reason='triggering_workflow_not_successful'
3427
+ elif [ "$EXPECTED_WORKFLOW_REPOSITORY" != "$EXPECTED_REPOSITORY" ]; then
3428
+ reason='triggering_repository_mismatch'
3429
+ elif ! printf '%s' "$EXPECTED_REPOSITORY" | grep -Eq '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$'; then
3430
+ reason='triggering_repository_invalid'
3431
+ elif ! printf '%s' "$EXPECTED_RUN_ID" | grep -Eq '^[1-9][0-9]*$'; then
3432
+ reason='triggering_run_id_invalid'
3433
+ elif ! is_sha "$EXPECTED_AFTER_SHA"; then
3434
+ reason='triggering_head_sha_invalid'
3435
+ elif ! gh api --paginate \
3436
+ "repos/$EXPECTED_REPOSITORY/actions/runs/$EXPECTED_RUN_ID/artifacts?per_page=100" \
3437
+ --jq ".artifacts[] | select(.name == \"$artifact_name\") | [.id, .size_in_bytes, .expired] | @tsv" \
3438
+ > "$matches" 2>/dev/null; then
3439
+ reason='artifact_lookup_failed'
3440
+ else
3441
+ count="$(awk 'END { print NR + 0 }' "$matches")"
3442
+ if [ "$count" -eq 0 ]; then
3443
+ reason='artifact_missing'
3444
+ elif [ "$count" -ne 1 ]; then
3445
+ reason='artifact_duplicate'
3446
+ else
3447
+ IFS="$(printf '\t')" read -r artifact_id artifact_size artifact_expired < "$matches" || true
3448
+ if ! printf '%s' "$artifact_id" | grep -Eq '^[1-9][0-9]*$' ||
3449
+ ! printf '%s' "$artifact_size" | grep -Eq '^[0-9]+$' ||
3450
+ { [ "$artifact_expired" != 'false' ] && [ "$artifact_expired" != 'true' ]; }; then
3451
+ reason='artifact_metadata_invalid'
3452
+ artifact_id=''
3453
+ elif [ "$artifact_expired" = 'true' ]; then
3454
+ reason='artifact_expired'
3455
+ artifact_id=''
3456
+ elif [ "$artifact_size" -gt '${ARTIFACT_MAX_BYTES}' ]; then
3457
+ reason='artifact_oversized'
3458
+ artifact_id=''
3459
+ else
3460
+ status='available'
3461
+ reason='artifact_available'
3462
+ fi
3463
+ fi
3464
+ fi
3465
+
3466
+ printf 'status=%s\nreason=%s\nartifact_id=%s\n' "$status" "$reason" "$artifact_id" >> "$GITHUB_OUTPUT"`;
3467
+ const validationScript = String.raw`disposition='refused'
3468
+ reason='validation_error'
3469
+ before=''
3470
+ after=''
3471
+ identity_directory="$RUNNER_TEMP/factory-push-identity"
3472
+ identity="$identity_directory/factory-push-identity.json"
3473
+ artifact_name='${FACTORY_PUSH_IDENTITY_ARTIFACT_PREFIX}-'"$EXPECTED_RUN_ID"
3474
+
3475
+ is_sha() {
3476
+ [ "$(printf '%s' "$1" | wc -c | tr -d '[:space:]')" -eq 40 ] &&
3477
+ [ "$1" != '0000000000000000000000000000000000000000' ] &&
3478
+ case "$1" in *[!0-9a-f]*) false;; *) true;; esac
3479
+ }
3480
+
3481
+ if [ "$EXPECTED_EVENT_NAME" != 'workflow_run' ]; then
3482
+ reason='event_not_workflow_run'
3483
+ elif [ "$EXPECTED_WORKFLOW_EVENT" != 'push' ]; then
3484
+ reason='triggering_workflow_not_push'
3485
+ elif [ "$EXPECTED_CONCLUSION" != 'success' ]; then
3486
+ reason='triggering_workflow_not_successful'
3487
+ elif [ "$EXPECTED_WORKFLOW_REPOSITORY" != "$EXPECTED_REPOSITORY" ]; then
3488
+ reason='triggering_repository_mismatch'
3489
+ elif ! printf '%s' "$EXPECTED_REPOSITORY" | grep -Eq '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$'; then
3490
+ reason='triggering_repository_invalid'
3491
+ elif ! printf '%s' "$EXPECTED_RUN_ID" | grep -Eq '^[1-9][0-9]*$'; then
3492
+ reason='triggering_run_id_invalid'
3493
+ elif ! is_sha "$EXPECTED_AFTER_SHA"; then
3494
+ reason='triggering_head_sha_invalid'
3495
+ elif [ "$LOOKUP_STATUS" != 'available' ]; then
3496
+ if [ -n "$LOOKUP_REASON" ]; then
3497
+ reason="$LOOKUP_REASON"
3498
+ else
3499
+ reason='artifact_lookup_failed'
3500
+ fi
3501
+ elif [ "$DOWNLOAD_OUTCOME" != 'success' ]; then
3502
+ reason='artifact_download_failed'
3503
+ elif [ "$CHECKOUT_OUTCOME" != 'success' ]; then
3504
+ reason='checkout_failed'
3505
+ elif [ ! -d "$identity_directory" ]; then
3506
+ reason='artifact_contents_missing'
3507
+ else
3508
+ entry_count="$(find "$identity_directory" -mindepth 1 -maxdepth 1 -print 2>/dev/null | awk 'END { print NR + 0 }')"
3509
+ if [ "$entry_count" -ne 1 ] || [ ! -f "$identity" ] || [ -L "$identity" ]; then
3510
+ reason='artifact_contents_invalid'
3511
+ else
3512
+ envelope_size="$(wc -c < "$identity" | tr -d '[:space:]')"
3513
+ if ! printf '%s' "$envelope_size" | grep -Eq '^[0-9]+$'; then
3514
+ reason='envelope_size_unreadable'
3515
+ elif [ "$envelope_size" -gt '${ENVELOPE_MAX_BYTES}' ]; then
3516
+ reason='envelope_oversized'
3517
+ elif ! jq -e --argjson schemaVersion '${1}' '
3518
+ type == "object" and
3519
+ keys == ["after", "before", "repository", "runId", "schemaVersion"] and
3520
+ .schemaVersion == $schemaVersion and
3521
+ (.repository | type == "string") and
3522
+ (.runId | type == "string" and test("^[1-9][0-9]*$")) and
3523
+ (.before | type == "string" and test("^[0-9a-f]{40}$") and (test("^0{40}$") | not)) and
3524
+ (.after | type == "string" and test("^[0-9a-f]{40}$") and (test("^0{40}$") | not))
3525
+ ' "$identity" >/dev/null 2>&1; then
3526
+ reason='envelope_malformed'
3527
+ else
3528
+ repository="$(jq -r '.repository' "$identity")"
3529
+ run_id="$(jq -r '.runId' "$identity")"
3530
+ before="$(jq -r '.before' "$identity")"
3531
+ after="$(jq -r '.after' "$identity")"
3532
+
3533
+ if [ "$repository" != "$EXPECTED_REPOSITORY" ]; then
3534
+ reason='envelope_repository_mismatch'
3535
+ elif [ "$run_id" != "$EXPECTED_RUN_ID" ]; then
3536
+ reason='envelope_run_id_mismatch'
3537
+ elif [ "$after" != "$EXPECTED_AFTER_SHA" ]; then
3538
+ reason='envelope_after_mismatch'
3539
+ elif ! actual_head="$(git rev-parse --verify HEAD 2>/dev/null)" || [ "$actual_head" != "$EXPECTED_AFTER_SHA" ]; then
3540
+ reason='checkout_head_mismatch'
3541
+ elif ! git cat-file -e "$before^{commit}" 2>/dev/null || ! git cat-file -e "$after^{commit}" 2>/dev/null; then
3542
+ reason='envelope_commit_unreachable'
3543
+ elif [ "$before" = "$after" ]; then
3544
+ reason='envelope_commits_contradictory'
3545
+ elif ! git merge-base --is-ancestor "$before" "$after"; then
3546
+ reason='before_not_ancestor'
3547
+ else
3548
+ disposition='usable'
3549
+ reason='identity_bound'
3550
+ fi
3551
+ fi
3552
+ fi
3553
+ fi
3554
+
3555
+ if [ "$disposition" != 'usable' ]; then
3556
+ before=''
3557
+ after=''
3558
+ fi
3559
+
3560
+ provenance="$(jq -cn \
3561
+ --argjson schemaVersion '${1}' \
3562
+ --arg disposition "$disposition" \
3563
+ --arg reason "$reason" \
3564
+ --arg repository "$EXPECTED_REPOSITORY" \
3565
+ --arg runId "$EXPECTED_RUN_ID" \
3566
+ --arg expectedAfter "$EXPECTED_AFTER_SHA" \
3567
+ --arg artifactName "$artifact_name" \
3568
+ --arg artifactId "$ARTIFACT_ID" \
3569
+ --arg before "$before" \
3570
+ --arg after "$after" \
3571
+ '{schemaVersion: $schemaVersion, disposition: $disposition, reason: $reason, repository: $repository, runId: $runId, expectedAfter: $expectedAfter, artifactName: $artifactName, artifactId: (if $artifactId == "" then null else $artifactId end), before: (if $before == "" then null else $before end), after: (if $after == "" then null else $after end)}')"
3572
+
3573
+ printf 'disposition=%s\nreason=%s\nbefore=%s\nafter=%s\nprovenance=%s\n' \
3574
+ "$disposition" "$reason" "$before" "$after" "$provenance" >> "$GITHUB_OUTPUT"
3575
+ {
3576
+ printf '## Exact push identity\n\n'
3577
+ printf -- '- Disposition: %s\n' "$disposition"
3578
+ printf -- '- Reason: %s\n' "$reason"
3579
+ printf -- '- Repository/run: %s / %s\n' "$EXPECTED_REPOSITORY" "$EXPECTED_RUN_ID"
3580
+ printf -- '- Expected verified head: %s\n' "$EXPECTED_AFTER_SHA"
3581
+ if [ "$disposition" = 'usable' ]; then
3582
+ printf -- '- Bound push: %s → %s\n' "$before" "$after"
3583
+ else
3584
+ printf -- '- Production impact classification refused; every consumer-owned production target remains demanded.\n'
3585
+ fi
3586
+ printf '\nFactory telemetry provenance: %s\n' "$provenance"
3587
+ } >> "$GITHUB_STEP_SUMMARY"`;
3588
+ /**
3589
+ * Record and upload the exact push-event identity without changing the Verify
3590
+ * result when transport is unavailable. Place these steps after verification.
3591
+ */
3592
+ const factoryPushIdentityProducer = (options) => {
3593
+ assertPinnedAction("uploadArtifact", options.uploadArtifact, UPLOAD_ARTIFACT_REPOSITORY);
3594
+ const condition = options.if ? `github.event_name == 'push' && (${options.if})` : "github.event_name == 'push'";
3595
+ const name = artifactName(expression("github.run_id"));
3596
+ return Object.freeze({
3597
+ artifactName: name,
3598
+ steps: Object.freeze([{
3599
+ continueOnError: true,
3600
+ id: FACTORY_PUSH_IDENTITY_RECORD_STEP_ID,
3601
+ if: condition,
3602
+ name: "Record exact push identity",
3603
+ run: producerScript
3604
+ }, {
3605
+ continueOnError: true,
3606
+ if: `${condition} && steps.${FACTORY_PUSH_IDENTITY_RECORD_STEP_ID}.outputs.produced == 'true'`,
3607
+ name: "Upload exact push identity",
3608
+ uses: options.uploadArtifact.uses,
3609
+ with: {
3610
+ "if-no-files-found": "error",
3611
+ name,
3612
+ path: `${expression("runner.temp")}/factory-push-identity.json`,
3613
+ "retention-days": "7"
3614
+ }
3615
+ }])
3616
+ });
3617
+ };
3618
+ /**
3619
+ * Download and validate identity from exactly the triggering workflow run in
3620
+ * the current repository. Every failure becomes a typed refusal; consumers
3621
+ * retain deploy policy, credentials, commands, topology, and convergence.
3622
+ */
3623
+ const factoryPushIdentityConsumer = (options) => {
3624
+ assertPinnedAction("checkout", options.checkout, "actions/checkout");
3625
+ assertPinnedAction("downloadArtifact", options.downloadArtifact, "actions/download-artifact");
3626
+ const currentRepository = expression("github.repository");
3627
+ const triggeringRun = expression("github.event.workflow_run.id");
3628
+ const triggeringHead = expression("github.event.workflow_run.head_sha");
3629
+ const lookupOutput = (name) => expression(`steps.${FACTORY_PUSH_IDENTITY_LOOKUP_STEP_ID}.outputs.${name}`);
3630
+ const validateOutput = (name) => expression(`steps.${FACTORY_PUSH_IDENTITY_VALIDATE_STEP_ID}.outputs.${name}`);
3631
+ const contextEnvironment = {
3632
+ EXPECTED_AFTER_SHA: triggeringHead,
3633
+ EXPECTED_CONCLUSION: expression("github.event.workflow_run.conclusion"),
3634
+ EXPECTED_EVENT_NAME: expression("github.event_name"),
3635
+ EXPECTED_REPOSITORY: currentRepository,
3636
+ EXPECTED_RUN_ID: triggeringRun,
3637
+ EXPECTED_WORKFLOW_EVENT: expression("github.event.workflow_run.event"),
3638
+ EXPECTED_WORKFLOW_REPOSITORY: expression("github.event.workflow_run.repository.full_name")
3639
+ };
3640
+ const steps = [
3641
+ {
3642
+ continueOnError: true,
3643
+ env: {
3644
+ GH_TOKEN: expression("github.token"),
3645
+ ...contextEnvironment
3646
+ },
3647
+ id: FACTORY_PUSH_IDENTITY_LOOKUP_STEP_ID,
3648
+ name: "Resolve exact push identity artifact",
3649
+ run: lookupScript
3650
+ },
3651
+ {
3652
+ continueOnError: true,
3653
+ id: FACTORY_PUSH_IDENTITY_DOWNLOAD_STEP_ID,
3654
+ if: `steps.${FACTORY_PUSH_IDENTITY_LOOKUP_STEP_ID}.outputs.status == 'available'`,
3655
+ name: "Download exact push identity",
3656
+ uses: options.downloadArtifact.uses,
3657
+ with: {
3658
+ "artifact-ids": lookupOutput("artifact_id"),
3659
+ "github-token": expression("github.token"),
3660
+ path: `${expression("runner.temp")}/factory-push-identity`,
3661
+ repository: currentRepository,
3662
+ "run-id": triggeringRun
3663
+ }
3664
+ },
3665
+ {
3666
+ continueOnError: true,
3667
+ id: FACTORY_PUSH_IDENTITY_CHECKOUT_STEP_ID,
3668
+ if: `steps.${FACTORY_PUSH_IDENTITY_LOOKUP_STEP_ID}.outputs.status == 'available'`,
3669
+ name: "Checkout exact verified head",
3670
+ uses: options.checkout.uses,
3671
+ with: {
3672
+ "fetch-depth": "0",
3673
+ ref: triggeringHead
3674
+ }
3675
+ },
3676
+ {
3677
+ continueOnError: true,
3678
+ env: {
3679
+ ARTIFACT_ID: lookupOutput("artifact_id"),
3680
+ CHECKOUT_OUTCOME: expression(`steps.${FACTORY_PUSH_IDENTITY_CHECKOUT_STEP_ID}.outcome`),
3681
+ DOWNLOAD_OUTCOME: expression(`steps.${FACTORY_PUSH_IDENTITY_DOWNLOAD_STEP_ID}.outcome`),
3682
+ LOOKUP_REASON: lookupOutput("reason"),
3683
+ LOOKUP_STATUS: lookupOutput("status"),
3684
+ ...contextEnvironment
3685
+ },
3686
+ id: FACTORY_PUSH_IDENTITY_VALIDATE_STEP_ID,
3687
+ if: "always()",
3688
+ name: "Validate exact push identity",
3689
+ run: validationScript
3690
+ }
3691
+ ];
3692
+ return Object.freeze({
3693
+ outputs: Object.freeze({
3694
+ after: validateOutput("after"),
3695
+ before: validateOutput("before"),
3696
+ disposition: validateOutput("disposition"),
3697
+ provenance: validateOutput("provenance"),
3698
+ reason: validateOutput("reason")
3699
+ }),
3700
+ requiredPermissions: Object.freeze({
3701
+ actions: "read",
3702
+ contents: "read"
3703
+ }),
3704
+ steps: Object.freeze(steps),
3705
+ usableIf: `steps.${FACTORY_PUSH_IDENTITY_VALIDATE_STEP_ID}.outputs.disposition == 'usable'`
3706
+ });
3707
+ };
3708
+ /**
3709
+ * Vitest suite profiling — the measurement mechanics behind a CI runner
3710
+ * comparison (#640, #647).
3711
+ *
3712
+ * A profile is a machine-readable record of N serial Vitest runs at one worker
3713
+ * count, carrying per-file and per-test timings, aggregate duration statistics,
3714
+ * and the hardware the samples actually ran on. The hardware capture is the
3715
+ * point: the #640 Depot comparison only resolved because every sample recorded
3716
+ * its `cpuModel`, which split otherwise-identical 4-CPU runs into two
3717
+ * non-overlapping populations.
3718
+ *
3719
+ * Everything a repository decides stays with the repository: worker counts,
3720
+ * sample counts, output paths, runner labels, and which suite to run at all.
3721
+ * This module owns the schema, the report parsing, the environment capture, and
3722
+ * the atomic write.
3723
+ */
3724
+ /** Schema version of the emitted profile document. */
3725
+ const VITEST_PROFILE_SCHEMA_VERSION = 1;
3726
+ /** `tool` discriminator every emitted profile carries. */
3727
+ const VITEST_PROFILE_TOOL = "factory-ci-vitest-profile";
3728
+ const RUN_TIMEOUT_MS = 9e5;
3729
+ const TERMINATION_GRACE_MS = 5e3;
3730
+ /**
3731
+ * A sample failed. The partial profile is already on disk; `exitCode` is the
3732
+ * status a caller should exit with.
3733
+ */
3734
+ var VitestProfileError = class extends Error {
3735
+ exitCode;
3736
+ constructor(message, exitCode) {
3737
+ super(message);
3738
+ this.name = "VitestProfileError";
3739
+ this.exitCode = exitCode;
3740
+ }
3741
+ };
3742
+ const durationSummary = (durations) => {
3743
+ const sorted = durations.toSorted((left, right) => left - right);
3744
+ const middle = Math.floor(sorted.length / 2);
3745
+ const median = sorted.length % 2 === 0 ? ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2 : sorted[middle] ?? 0;
3746
+ return {
3747
+ maximum: sorted.at(-1) ?? 0,
3748
+ mean: durations.reduce((sum, value) => sum + value, 0) / durations.length,
3749
+ median,
3750
+ minimum: sorted[0] ?? 0
3751
+ };
3752
+ };
3753
+ const relativePath = (cwd, file) => path.relative(cwd, file).split(path.sep).join("/");
3754
+ /**
3755
+ * Fold one Vitest JSON report into a profile sample: file and test timings,
3756
+ * both sorted slowest first, plus the run's counts. A missing report (crash,
3757
+ * timeout, unwritable output) yields a sample with `reportAvailable: false`
3758
+ * rather than nothing at all.
3759
+ */
3760
+ const normalizeVitestProfileSample = (report, input) => {
3761
+ const files = (report?.testResults ?? []).map((file) => ({
3762
+ durationMs: Math.max(0, file.endTime - file.startTime),
3763
+ path: relativePath(input.cwd, file.name),
3764
+ status: file.status
3765
+ })).toSorted((left, right) => right.durationMs - left.durationMs);
3766
+ const tests = (report?.testResults ?? []).flatMap((file) => file.assertionResults.map((test) => ({
3767
+ durationMs: Math.max(0, test.duration ?? 0),
3768
+ file: relativePath(input.cwd, file.name),
3769
+ name: test.fullName,
3770
+ status: test.status
3771
+ }))).toSorted((left, right) => right.durationMs - left.durationMs);
3772
+ return {
3773
+ counts: report ? {
3774
+ failed: report.numFailedTests,
3775
+ passed: report.numPassedTests,
3776
+ pending: report.numPendingTests,
3777
+ suites: report.numTotalTestSuites,
3778
+ tests: report.numTotalTests,
3779
+ todo: report.numTodoTests
3780
+ } : null,
3781
+ durationMs: input.durationMs,
3782
+ endedAt: input.endedAt.toISOString(),
3783
+ exitCode: input.exitCode,
3784
+ failure: input.failure ?? null,
3785
+ files,
3786
+ reportAvailable: report !== null,
3787
+ sample: input.sample,
3788
+ startedAt: input.startedAt.toISOString(),
3789
+ tests
3790
+ };
3791
+ };
3792
+ const aggregateSlowFiles = (runs, limit) => {
3793
+ const durations = /* @__PURE__ */ new Map();
3794
+ for (const file of runs.flatMap((run) => run.files)) {
3795
+ const recorded = durations.get(file.path) ?? [];
3796
+ recorded.push(file.durationMs);
3797
+ durations.set(file.path, recorded);
3798
+ }
3799
+ return [...durations].map(([filePath, values]) => ({
3800
+ durationMs: durationSummary(values),
3801
+ path: filePath,
3802
+ samples: values.length
3803
+ })).toSorted((left, right) => right.durationMs.median - left.durationMs.median).slice(0, limit);
3804
+ };
3805
+ const aggregateSlowTests = (runs, limit) => {
3806
+ const timings = /* @__PURE__ */ new Map();
3807
+ for (const test of runs.flatMap((run) => run.tests)) {
3808
+ const key = `${test.file}\0${test.name}`;
3809
+ const recorded = timings.get(key) ?? {
3810
+ durations: [],
3811
+ file: test.file,
3812
+ name: test.name
3813
+ };
3814
+ recorded.durations.push(test.durationMs);
3815
+ timings.set(key, recorded);
3816
+ }
3817
+ return [...timings.values()].map(({ durations, file, name }) => ({
3818
+ durationMs: durationSummary(durations),
3819
+ file,
3820
+ name,
3821
+ samples: durations.length
3822
+ })).toSorted((left, right) => right.durationMs.median - left.durationMs.median).slice(0, limit);
3823
+ };
3824
+ const gitValue = (cwd, args) => {
3825
+ try {
3826
+ return execFileSync("git", args, {
3827
+ cwd,
3828
+ encoding: "utf-8",
3829
+ stdio: [
3830
+ "ignore",
3831
+ "pipe",
3832
+ "ignore"
3833
+ ]
3834
+ }).trim();
3835
+ } catch {
3836
+ return null;
3837
+ }
3838
+ };
3839
+ const resolveVitestPackage = (cwd) => createRequire(path.join(path.resolve(cwd), "noop.js")).resolve("vitest/package.json");
3840
+ /**
3841
+ * Record the machine and commit a profile was taken on. Vitest's version is
3842
+ * resolved from `cwd`, so it is the consumer's Vitest and not this package's.
3843
+ * Git failures degrade to `null` — an artifact from a tarball checkout is still
3844
+ * a usable measurement.
3845
+ */
3846
+ const captureVitestProfileEnvironment = async (options) => {
3847
+ const gitDirectory = options.gitDirectory ?? options.cwd;
3848
+ let vitestVersion = "unknown";
3849
+ try {
3850
+ vitestVersion = JSON.parse(await readFile(resolveVitestPackage(options.cwd), "utf-8")).version ?? "unknown";
3851
+ } catch {
3852
+ vitestVersion = "unknown";
3853
+ }
3854
+ const processors = cpus();
3855
+ const status = gitValue(gitDirectory, ["status", "--porcelain"]);
3856
+ return {
3857
+ arch: arch(),
3858
+ availableParallelism: availableParallelism(),
3859
+ cpuCount: processors.length,
3860
+ cpuModel: processors[0]?.model ?? null,
3861
+ gitDirty: status === null ? null : status.length > 0,
3862
+ gitHead: gitValue(gitDirectory, ["rev-parse", "HEAD"]),
3863
+ node: process.version,
3864
+ osRelease: release(),
3865
+ platform: platform(),
3866
+ totalMemoryBytes: totalmem(),
3867
+ vitest: vitestVersion
3868
+ };
3869
+ };
3870
+ const spawnVitest = async ({ cwd, maxWorkers, reportPath, stdio }) => {
3871
+ const vitestCli = path.join(path.dirname(resolveVitestPackage(cwd)), "vitest.mjs");
3872
+ const started = performance.now();
3873
+ const child = spawn(process.execPath, [
3874
+ vitestCli,
3875
+ "run",
3876
+ "--reporter=json",
3877
+ `--outputFile=${reportPath}`,
3878
+ `--maxWorkers=${maxWorkers}`
3879
+ ], {
3880
+ cwd,
3881
+ stdio
3882
+ });
3883
+ let timedOut = false;
3884
+ let forceKillTimer;
3885
+ const timeoutTimer = setTimeout(() => {
3886
+ timedOut = true;
3887
+ child.kill("SIGTERM");
3888
+ forceKillTimer = setTimeout(() => {
3889
+ child.kill("SIGKILL");
3890
+ }, TERMINATION_GRACE_MS);
3891
+ }, RUN_TIMEOUT_MS);
3892
+ let exitCode = 0;
3893
+ let failure = null;
3894
+ try {
3895
+ const [code, signal] = await once(child, "exit");
3896
+ exitCode = code ?? (signal ? 1 : 0);
3897
+ } catch (error) {
3898
+ exitCode = 1;
3899
+ failure = `Vitest could not start: ${error instanceof Error ? error.message : String(error)}`;
3900
+ } finally {
3901
+ clearTimeout(timeoutTimer);
3902
+ if (forceKillTimer) clearTimeout(forceKillTimer);
3903
+ }
3904
+ if (timedOut) failure = `Vitest profile sample exceeded ${RUN_TIMEOUT_MS}ms and was terminated.`;
3905
+ let report = null;
3906
+ try {
3907
+ report = JSON.parse(await readFile(reportPath, "utf-8"));
3908
+ } catch (error) {
3909
+ const reportFailure = `Vitest JSON report unavailable: ${error instanceof Error ? error.message : String(error)}`;
3910
+ failure = failure ? `${failure} ${reportFailure}` : reportFailure;
3911
+ }
3912
+ return {
3913
+ durationMs: Math.max(0, performance.now() - started),
3914
+ exitCode: timedOut ? 1 : exitCode,
3915
+ failure,
3916
+ report
3917
+ };
3918
+ };
3919
+ /**
3920
+ * Write a profile document atomically: a partial file must never be readable
3921
+ * as a complete measurement, and the profile is rewritten after every sample.
3922
+ */
3923
+ const writeVitestProfile = async (outputPath, profile) => {
3924
+ await mkdir(path.dirname(outputPath), { recursive: true });
3925
+ const temporaryPath = `${outputPath}.tmp`;
3926
+ await writeFile(temporaryPath, `${JSON.stringify(profile, null, 2)}\n`, "utf-8");
3927
+ await rename(temporaryPath, outputPath);
3928
+ };
3929
+ /**
3930
+ * Take `samples` serial Vitest runs at one worker count and persist the profile
3931
+ * after each one. Samples never overlap: concurrent runs would measure CPU and
3932
+ * I/O contention instead of the worker count under test. A failing sample
3933
+ * throws `VitestProfileError` with the partial profile already written.
3934
+ */
3935
+ const runVitestProfile = async (options, dependencies = {}) => {
3936
+ if (!Number.isSafeInteger(options.samples) || options.samples < 1) throw new Error("runVitestProfile: samples must be a positive integer.");
3937
+ const now = dependencies.now ?? (() => /* @__PURE__ */ new Date());
3938
+ const runSample = dependencies.runSample ?? spawnVitest;
3939
+ const writeResult = dependencies.writeResult ?? writeVitestProfile;
3940
+ const startedAt = now();
3941
+ const rawRoot = path.join(`${options.outputPath}.raw`, randomUUID());
3942
+ await mkdir(rawRoot, { recursive: true });
3943
+ const profile = {
3944
+ command: [
3945
+ "vitest",
3946
+ "run",
3947
+ "--reporter=json",
3948
+ `--maxWorkers=${options.maxWorkers}`
3949
+ ],
3950
+ endedAt: startedAt.toISOString(),
3951
+ environment: await captureVitestProfileEnvironment({
3952
+ cwd: options.cwd,
3953
+ gitDirectory: options.gitDirectory
3954
+ }),
3955
+ options: {
3956
+ maxWorkers: options.maxWorkers,
3957
+ samples: options.samples,
3958
+ slowLimit: options.slowLimit
3959
+ },
3960
+ rawReportDirectory: rawRoot,
3961
+ runs: [],
3962
+ schemaVersion: 1,
3963
+ startedAt: startedAt.toISOString(),
3964
+ summary: {
3965
+ durationMs: {
3966
+ maximum: 0,
3967
+ mean: 0,
3968
+ median: 0,
3969
+ minimum: 0
3970
+ },
3971
+ slowFiles: [],
3972
+ slowTests: []
3973
+ },
3974
+ tool: VITEST_PROFILE_TOOL
3975
+ };
3976
+ for (let sample = 1; sample <= options.samples; sample += 1) {
3977
+ let hookFailure;
3978
+ try {
3979
+ options.onSampleStart?.({
3980
+ maxWorkers: options.maxWorkers,
3981
+ sample,
3982
+ samples: options.samples
3983
+ });
3984
+ } catch (error) {
3985
+ hookFailure = { error };
3986
+ }
3987
+ const sampleStartedAt = now();
3988
+ const reportPath = path.join(rawRoot, `sample-${sample}.json`);
3989
+ const execution = await runSample({
3990
+ cwd: options.cwd,
3991
+ maxWorkers: options.maxWorkers,
3992
+ reportPath,
3993
+ sample,
3994
+ stdio: options.stdio ?? "inherit"
3995
+ });
3996
+ const sampleEndedAt = now();
3997
+ const normalized = normalizeVitestProfileSample(execution.report, {
3998
+ cwd: options.cwd,
3999
+ durationMs: execution.durationMs,
4000
+ endedAt: sampleEndedAt,
4001
+ exitCode: execution.exitCode,
4002
+ failure: execution.failure,
4003
+ sample,
4004
+ startedAt: sampleStartedAt
4005
+ });
4006
+ profile.runs.push(normalized);
4007
+ profile.endedAt = sampleEndedAt.toISOString();
4008
+ profile.summary = {
4009
+ durationMs: durationSummary(profile.runs.map((run) => run.durationMs)),
4010
+ slowFiles: aggregateSlowFiles(profile.runs, options.slowLimit),
4011
+ slowTests: aggregateSlowTests(profile.runs, options.slowLimit)
4012
+ };
4013
+ await writeResult(options.outputPath, profile);
4014
+ try {
4015
+ options.onSampleComplete?.({
4016
+ result: normalized,
4017
+ sample,
4018
+ samples: options.samples
4019
+ });
4020
+ } catch (error) {
4021
+ hookFailure ??= { error };
4022
+ }
4023
+ if (execution.exitCode !== 0 || execution.report?.success !== true) throw new VitestProfileError(`Vitest profile sample ${sample} failed; partial results saved.`, execution.exitCode || 1);
4024
+ if (hookFailure) throw hookFailure.error;
4025
+ }
4026
+ return profile;
4027
+ };
4028
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4029
+ const isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
4030
+ const durationSummaryFailure = (value, where) => {
4031
+ if (!isRecord(value)) return `${where} is not an object`;
4032
+ const missing = [
4033
+ "maximum",
4034
+ "mean",
4035
+ "median",
4036
+ "minimum"
4037
+ ].find((field) => !isFiniteNumber(value[field]));
4038
+ return missing === void 0 ? void 0 : `${where}.${missing} is not a finite number`;
4039
+ };
4040
+ const environmentFailure = (value) => {
4041
+ if (!isRecord(value)) return "environment is not an object";
4042
+ if (!(typeof value.cpuModel === "string" || value.cpuModel === null)) return "environment.cpuModel is neither a string nor null";
4043
+ if (!isFiniteNumber(value.cpuCount)) return "environment.cpuCount is not a finite number";
4044
+ };
4045
+ /** The count fields the writer emits; every one must be a finite number. */
4046
+ const COUNT_FIELDS = [
4047
+ "failed",
4048
+ "passed",
4049
+ "pending",
4050
+ "suites",
4051
+ "tests",
4052
+ "todo"
4053
+ ];
4054
+ const runFailure = (value, index) => {
4055
+ if (!isRecord(value)) return `runs[${index}] is not an object`;
4056
+ if (!isFiniteNumber(value.durationMs)) return `runs[${index}].durationMs is not a finite number`;
4057
+ if (value.counts === null) return;
4058
+ if (!isRecord(value.counts)) return `runs[${index}].counts is neither an object nor null`;
4059
+ const { counts } = value;
4060
+ const missing = COUNT_FIELDS.find((field) => !isFiniteNumber(counts[field]));
4061
+ return missing === void 0 ? void 0 : `runs[${index}].counts.${missing} is not a finite number`;
4062
+ };
4063
+ const slowEntryFailure = (value, where, labelField) => {
4064
+ if (!isRecord(value)) return `${where} is not an object`;
4065
+ if (typeof value[labelField] !== "string") return `${where}.${labelField} is not a string`;
4066
+ if (labelField === "name" && typeof value.file !== "string") return `${where}.file is not a string`;
4067
+ return durationSummaryFailure(value.durationMs, `${where}.durationMs`);
4068
+ };
4069
+ const summaryFailure = (value) => {
4070
+ if (!isRecord(value)) return "summary is not an object";
4071
+ const durations = durationSummaryFailure(value.durationMs, "summary.durationMs");
4072
+ if (durations !== void 0) return durations;
4073
+ if (!Array.isArray(value.slowFiles)) return "summary.slowFiles is not an array";
4074
+ for (const [index, entry] of value.slowFiles.entries()) {
4075
+ const failure = slowEntryFailure(entry, `summary.slowFiles[${index}]`, "path");
4076
+ if (failure !== void 0) return failure;
4077
+ }
4078
+ if (!Array.isArray(value.slowTests)) return "summary.slowTests is not an array";
4079
+ for (const [index, entry] of value.slowTests.entries()) {
4080
+ const failure = slowEntryFailure(entry, `summary.slowTests[${index}]`, "name");
4081
+ if (failure !== void 0) return failure;
4082
+ }
4083
+ };
4084
+ /**
4085
+ * Check one parsed JSON document against the profile contract the writer
4086
+ * emits. Returns the typed profile on success and the first mismatch reason
4087
+ * otherwise — never a partially-usable value.
4088
+ */
4089
+ const readVitestProfileDocument = (value) => {
4090
+ if (!isRecord(value)) return {
4091
+ kind: "unrecognized",
4092
+ reason: "the document is not an object"
4093
+ };
4094
+ if (value.tool !== "factory-ci-vitest-profile") return {
4095
+ kind: "unrecognized",
4096
+ reason: `tool is ${JSON.stringify(value.tool)} rather than "${VITEST_PROFILE_TOOL}"`
4097
+ };
4098
+ if (value.schemaVersion !== 1) return {
4099
+ kind: "unrecognized",
4100
+ reason: `schemaVersion is ${JSON.stringify(value.schemaVersion)} rather than 1`
4101
+ };
4102
+ if (!(Array.isArray(value.command) && value.command.every((part) => typeof part === "string"))) return {
4103
+ kind: "unrecognized",
4104
+ reason: "command is not an array of strings"
4105
+ };
4106
+ const environment = environmentFailure(value.environment);
4107
+ if (environment !== void 0) return {
4108
+ kind: "unrecognized",
4109
+ reason: environment
4110
+ };
4111
+ if (!isRecord(value.options)) return {
4112
+ kind: "unrecognized",
4113
+ reason: "options is not an object"
4114
+ };
4115
+ if (!isFiniteNumber(value.options.maxWorkers)) return {
4116
+ kind: "unrecognized",
4117
+ reason: "options.maxWorkers is not a finite number"
4118
+ };
4119
+ if (!Array.isArray(value.runs)) return {
4120
+ kind: "unrecognized",
4121
+ reason: "runs is not an array"
4122
+ };
4123
+ for (const [index, run] of value.runs.entries()) {
4124
+ const failure = runFailure(run, index);
4125
+ if (failure !== void 0) return {
4126
+ kind: "unrecognized",
4127
+ reason: failure
4128
+ };
4129
+ }
4130
+ const summary = summaryFailure(value.summary);
4131
+ if (summary !== void 0) return {
4132
+ kind: "unrecognized",
4133
+ reason: summary
4134
+ };
4135
+ return {
4136
+ kind: "profile",
4137
+ profile: value
4138
+ };
4139
+ };
4140
+ const DEPOT_LABEL = "depot-ubuntu-24.04";
4141
+ const HOSTED_LABEL = "ubuntu-latest";
4142
+ const isOverride = (decision) => typeof decision === "object";
4143
+ const homeForKind = (kind) => {
4144
+ switch (kind) {
4145
+ case "sustained-compute":
4146
+ case "rounding-tax": return "depot";
4147
+ case "app-token":
4148
+ case "deploy-credentials": return "hosted";
4149
+ default: return kind;
4150
+ }
4151
+ };
4152
+ const labelForHome = (home) => home === "depot" ? DEPOT_LABEL : HOSTED_LABEL;
4153
+ const assertOverrideWhy = (why) => {
4154
+ if (why.includes("\n") || why.includes("\r") || why.trim().length === 0) throw new Error("factoryVerifyRunner override requires a non-empty single-line why");
4155
+ };
4156
+ const factoryVerifyRunner = (decision) => {
4157
+ if (isOverride(decision)) {
4158
+ assertOverrideWhy(decision.why);
4159
+ return Object.freeze({
4160
+ decision,
4161
+ home: decision.home,
4162
+ label: labelForHome(decision.home),
4163
+ why: decision.why
4164
+ });
4165
+ }
4166
+ const home = homeForKind(decision);
4167
+ return Object.freeze({
4168
+ decision,
4169
+ home,
4170
+ label: labelForHome(home)
4171
+ });
4172
+ };
4173
+ const indentOf$1 = (line) => line.length - line.trimStart().length;
4174
+ const unquote$1 = (raw) => {
4175
+ const value = raw.trim();
4176
+ if (value.startsWith("'") && value.endsWith("'") && value.length > 1) return value.slice(1, -1).replaceAll("''", "'");
4177
+ if (value.startsWith("\"") && value.endsWith("\"") && value.length > 1) return value.slice(1, -1);
4178
+ return value;
4179
+ };
4180
+ const JOB_ID = /^[\w-]+$/u;
4181
+ const MATRIX_EXPRESSION = /\$\{\{\s*matrix\b/u;
4182
+ const throwNonScalarRunsOn = (jobId) => {
4183
+ throw new Error(`job ${jobId} uses a list, group, or matrix runs-on; Verify policy accepts a scalar label only`);
4184
+ };
4185
+ const verifyWorkflowJobRunners = (yaml) => {
4186
+ const lines = yaml.split("\n");
4187
+ const jobsLine = lines.findIndex((line) => line.trim() === "jobs:");
4188
+ if (jobsLine === -1) return {};
4189
+ const jobsIndent = indentOf$1(lines[jobsLine]);
4190
+ const jobIdIndent = jobsIndent + 2;
4191
+ const jobKeyIndent = jobIdIndent + 2;
4192
+ const runners = {};
4193
+ for (let index = jobsLine + 1; index < lines.length; index += 1) {
4194
+ const line = lines[index];
4195
+ if (line.trim().length === 0) continue;
4196
+ const indent = indentOf$1(line);
4197
+ if (indent <= jobsIndent) break;
4198
+ if (indent !== jobIdIndent) continue;
4199
+ const trimmed = line.trim();
4200
+ if (!trimmed.endsWith(":") || trimmed.includes(" ")) continue;
4201
+ const jobId = trimmed.slice(0, -1);
4202
+ if (!JOB_ID.test(jobId)) continue;
4203
+ let runsOn;
4204
+ for (let cursor = index + 1; cursor < lines.length; cursor += 1) {
4205
+ const candidate = lines[cursor];
4206
+ if (candidate.trim().length === 0) continue;
4207
+ const candidateIndent = indentOf$1(candidate);
4208
+ if (candidateIndent <= jobIdIndent) break;
4209
+ if (candidateIndent !== jobKeyIndent) continue;
4210
+ const rest = candidate.trimStart();
4211
+ if (!rest.startsWith("runs-on:")) continue;
4212
+ const inline = rest.slice(8).trim();
4213
+ if (inline.length === 0) throwNonScalarRunsOn(jobId);
4214
+ if (inline.startsWith("[") || inline.startsWith("{")) throwNonScalarRunsOn(jobId);
4215
+ const label = unquote$1(inline);
4216
+ if (MATRIX_EXPRESSION.test(label)) throwNonScalarRunsOn(jobId);
4217
+ runsOn = label;
4218
+ break;
4219
+ }
4220
+ if (runsOn === void 0) throw new Error(`job ${jobId} has no runs-on`);
4221
+ runners[jobId] = runsOn;
4222
+ }
4223
+ return runners;
4224
+ };
4225
+ const isDeployCredentials = (runner) => runner.decision === "deploy-credentials";
4226
+ const verifyRunnerPolicy = (yaml, input) => {
4227
+ const actual = verifyWorkflowJobRunners(yaml);
4228
+ const declared = Object.keys(input.jobs);
4229
+ const undeclared = Object.keys(actual).filter((jobId) => input.jobs[jobId] === void 0).toSorted();
4230
+ const missing = declared.filter((jobId) => actual[jobId] === void 0).toSorted();
4231
+ const mismatches = declared.filter((jobId) => actual[jobId] !== void 0 && actual[jobId] !== input.jobs[jobId].label).toSorted().map((jobId) => ({
4232
+ actual: actual[jobId],
4233
+ expected: input.jobs[jobId].label,
4234
+ jobId
4235
+ }));
4236
+ const forbiddenKinds = declared.filter((jobId) => isDeployCredentials(input.jobs[jobId])).toSorted();
4237
+ return Object.freeze({
4238
+ forbiddenKinds,
4239
+ mismatches,
4240
+ missing,
4241
+ ok: undeclared.length === 0 && missing.length === 0 && mismatches.length === 0 && forbiddenKinds.length === 0,
4242
+ undeclared
4243
+ });
4244
+ };
4245
+ const assertVerifyRunnerPolicy = (yaml, input) => {
4246
+ const report = verifyRunnerPolicy(yaml, input);
4247
+ if (report.ok) return report;
4248
+ const details = [];
4249
+ if (report.undeclared.length > 0) details.push(`undeclared jobs: ${report.undeclared.join(", ")}`);
4250
+ if (report.missing.length > 0) details.push(`missing from YAML: ${report.missing.join(", ")}`);
4251
+ for (const mismatch of report.mismatches) details.push(`${mismatch.jobId} runs-on ${mismatch.actual}, expected ${mismatch.expected}`);
4252
+ if (report.forbiddenKinds.length > 0) details.push(`deploy-credentials is illegal inside Verify: ${report.forbiddenKinds.join(", ")}`);
4253
+ throw new Error(`${input.source} Verify runner policy failed:\n${details.map((detail) => ` - ${detail}`).join("\n")}`);
4254
+ };
4255
+ const RUN_KEY = /^(?<indent>\s*)(?:-\s+)?run:(?<inline>.*)$/u;
4256
+ /**
4257
+ * GitHub evaluates `${{ }}` before bash ever sees the script, and what it
4258
+ * substitutes is not knowable here. Neutralizing each expression to one plain
4259
+ * word is what the runner's *shape* looks like: a value in argument position.
4260
+ * Leaving them in would make every workflow fail to parse; expanding them to
4261
+ * nothing would silently change quoting.
4262
+ *
4263
+ * Scanned rather than matched with a lazy regex, because `}}` occurs inside
4264
+ * Actions string literals: `format('refs/{{0}}', github.ref_name)` escapes a
4265
+ * literal brace pair that way, and stopping there would leave half an
4266
+ * expression in the script and report a parse error the runner never sees.
4267
+ */
4268
+ const neutralizeExpressions = (script) => {
4269
+ let out = "";
4270
+ let cursor = 0;
4271
+ while (cursor < script.length) {
4272
+ const start = script.indexOf("${{", cursor);
4273
+ if (start === -1) {
4274
+ out += script.slice(cursor);
4275
+ break;
4276
+ }
4277
+ out += script.slice(cursor, start);
4278
+ let scan = start + 3;
4279
+ let quote;
4280
+ let end = -1;
4281
+ while (scan < script.length) {
4282
+ const char = script[scan];
4283
+ if (quote === void 0) {
4284
+ if (char === "'" || char === "\"") quote = char;
4285
+ else if (char === "}" && script[scan + 1] === "}") {
4286
+ end = scan + 2;
4287
+ break;
4288
+ }
4289
+ } else if (char === quote) {
4290
+ if (script[scan + 1] === quote) scan += 1;
4291
+ else quote = void 0;
4292
+ }
4293
+ scan += 1;
4294
+ }
4295
+ if (end === -1) {
4296
+ out += script.slice(start);
4297
+ break;
4298
+ }
4299
+ out += "FACTORY_ACTIONS_EXPRESSION";
4300
+ cursor = end;
4301
+ }
4302
+ return out;
4303
+ };
4304
+ /** Strip one layer of YAML single quoting from a scalar value. */
4305
+ const unquote = (raw) => {
4306
+ const value = raw.trim();
4307
+ if (value.startsWith("'") && value.endsWith("'") && value.length > 1) return value.slice(1, -1).replaceAll("''", "'");
4308
+ return value;
4309
+ };
4310
+ const indentOf = (line) => line.length - line.trimStart().length;
4311
+ /**
4312
+ * Where a mapping key sits, counting the `- ` sequence marker as indentation:
4313
+ * `- name:` and the `run:` below it are siblings in the same step even though
4314
+ * their raw columns differ by two.
4315
+ */
4316
+ const keyIndentOf = (line) => indentOf(line) + (line.trimStart().startsWith("- ") ? 2 : 0);
4317
+ /** A sibling scalar of the `run:` key under inspection, when the line is one. */
4318
+ const keyValueAt = (line, indent, key) => {
4319
+ if (keyIndentOf(line) !== indent) return;
4320
+ const rest = line.trimStart().replace(/^-\s+/u, "");
4321
+ return rest.startsWith(`${key}:`) ? rest.slice(key.length + 1) : void 0;
4322
+ };
4323
+ /**
4324
+ * Every `defaults: { run: { shell } }` in the document, with the span it
4325
+ * governs: the mapping that declares it, which is the whole workflow at the
4326
+ * top level and one job under `jobs:`.
4327
+ *
4328
+ * GitHub resolves a step's interpreter as step `shell:`, then the job's
4329
+ * default, then the workflow's, then bash. A scanner that only looked at the
4330
+ * step would call every step in a `defaults.run.shell: sh` workflow bash and
4331
+ * report a pass for scripts `sh` cannot parse — the very false negative this
4332
+ * control exists to close.
4333
+ */
4334
+ const defaultShellScopes = (lines) => {
4335
+ const scopes = [];
4336
+ for (const [index, line] of lines.entries()) {
4337
+ if (line.trim() !== "defaults:") continue;
4338
+ const depth = keyIndentOf(line);
4339
+ const shell = (() => {
4340
+ let inRun = false;
4341
+ for (let cursor = index + 1; cursor < lines.length; cursor += 1) {
4342
+ const candidate = lines[cursor];
4343
+ if (candidate.trim().length === 0) continue;
4344
+ if (keyIndentOf(candidate) <= depth) return;
4345
+ if (keyValueAt(candidate, depth + 2, "run") !== void 0) {
4346
+ inRun = true;
4347
+ continue;
4348
+ }
4349
+ if (keyIndentOf(candidate) <= depth + 2) {
4350
+ inRun = false;
4351
+ continue;
4352
+ }
4353
+ const value = inRun ? keyValueAt(candidate, depth + 4, "shell") : void 0;
4354
+ if (value !== void 0) return unquote(value);
4355
+ }
4356
+ })();
4357
+ if (shell === void 0) continue;
4358
+ let start = 0;
4359
+ for (let cursor = index - 1; cursor >= 0; cursor -= 1) if (lines[cursor].trim().length > 0 && keyIndentOf(lines[cursor]) < depth) {
4360
+ start = cursor;
4361
+ break;
4362
+ }
4363
+ let end = lines.length;
4364
+ for (let cursor = index + 1; cursor < lines.length; cursor += 1) if (lines[cursor].trim().length > 0 && keyIndentOf(lines[cursor]) < depth) {
4365
+ end = cursor;
4366
+ break;
4367
+ }
4368
+ scopes.push({
4369
+ depth,
4370
+ end,
4371
+ shell,
4372
+ start
4373
+ });
4374
+ }
4375
+ return scopes;
4376
+ };
4377
+ /** The innermost `defaults.run.shell` governing a line, if any. */
4378
+ const inheritedShell = (scopes, index) => scopes.filter((scope) => index >= scope.start && index < scope.end).toSorted((left, right) => right.depth - left.depth).at(0)?.shell;
4379
+ /**
4380
+ * Every `run:` block in a generated workflow, paired with the `shell:` its
4381
+ * step declares.
4382
+ *
4383
+ * Deliberately a scanner over the emitted text and not a YAML parse: this
4384
+ * package takes no dependency it does not need, and the emitted shape is one
4385
+ * generator's output, not arbitrary YAML. It reads both block scalars
4386
+ * (`run: |-`) and inline scripts.
4387
+ */
4388
+ const workflowRunBlocks = (yaml) => {
4389
+ const lines = yaml.split("\n");
4390
+ const scopes = defaultShellScopes(lines);
4391
+ const blocks = [];
4392
+ for (const [index, line] of lines.entries()) {
4393
+ const match = RUN_KEY.exec(line);
4394
+ if (match?.groups === void 0) continue;
4395
+ const keyIndent = keyIndentOf(line);
4396
+ const inline = match.groups.inline.trim();
4397
+ let script;
4398
+ let end = index;
4399
+ if (inline.startsWith(">")) throw new Error(`folded (\`run: >\`) scripts are not supported: YAML folds their line breaks into spaces, so what bash parses is not what is written. Use a literal block (\`run: |\`).`);
4400
+ if (inline.trimStart().startsWith("\"")) throw new Error(`double-quoted \`run:\` scalars are not supported: their YAML escapes would have to be decoded before bash sees them. Use a literal block (\`run: |\`) or an unquoted scalar.`);
4401
+ if (inline.startsWith("|")) {
4402
+ const body = [];
4403
+ for (let cursor = index + 1; cursor < lines.length; cursor += 1) {
4404
+ const candidate = lines[cursor];
4405
+ if (candidate.trim().length > 0 && indentOf(candidate) <= keyIndent) break;
4406
+ body.push(candidate);
4407
+ end = cursor;
4408
+ }
4409
+ const strip = Math.min(...body.filter((entry) => entry.trim().length > 0).map((entry) => indentOf(entry)));
4410
+ script = body.map((entry) => entry.slice(strip)).join("\n");
4411
+ } else if (inline.length > 0) script = unquote(inline);
4412
+ else continue;
4413
+ let shell;
4414
+ let step;
4415
+ const readSibling = (line_) => {
4416
+ shell ??= keyValueAt(line_, keyIndent, "shell");
4417
+ step ??= keyValueAt(line_, keyIndent, "name");
4418
+ };
4419
+ for (let cursor = index; cursor >= 0 && keyIndentOf(lines[cursor]) >= keyIndent; cursor -= 1) {
4420
+ readSibling(lines[cursor]);
4421
+ if (lines[cursor].trimStart().startsWith("- ")) break;
4422
+ }
4423
+ for (let cursor = end + 1; cursor < lines.length; cursor += 1) {
4424
+ if (keyIndentOf(lines[cursor]) < keyIndent || lines[cursor].trimStart().startsWith("- ")) break;
4425
+ readSibling(lines[cursor]);
4426
+ }
4427
+ const effectiveShell = shell === void 0 ? inheritedShell(scopes, index) : unquote(shell);
4428
+ blocks.push({
4429
+ script,
4430
+ ...effectiveShell === void 0 ? {} : { shell: effectiveShell },
4431
+ ...step === void 0 ? {} : { step: unquote(step) }
4432
+ });
4433
+ }
4434
+ return blocks;
4435
+ };
4436
+ /** `NAME=value` in a shell command template, as `env` takes them. */
4437
+ const ASSIGNMENT = /^[A-Za-z_]\w*=/u;
4438
+ /**
4439
+ * Interpreters GitHub supports that this control deliberately leaves alone.
4440
+ * Named rather than inferred, so an unfamiliar command fails loudly instead of
4441
+ * being skipped as though it had been considered.
4442
+ */
4443
+ const NON_SHELL_INTERPRETERS = /* @__PURE__ */ new Set([
4444
+ "cmd",
4445
+ "powershell",
4446
+ "pwsh",
4447
+ "python",
4448
+ "python3"
4449
+ ]);
4450
+ /**
4451
+ * The interpreter that will parse a step's script, or `undefined` for one this
4452
+ * control leaves alone.
4453
+ *
4454
+ * A step declaring no shell gets bash: that is GitHub's default for `run:` on
4455
+ * Linux runners. A step declaring `sh` gets `sh`, because the runner runs it
4456
+ * with `sh` — whose grammar is narrower than bash's, so parsing it with bash
4457
+ * would report a pass for a script the runner cannot run. Anything else
4458
+ * (pwsh, python, cmd) is not this control's business.
4459
+ */
4460
+ const parserFor = (shell) => {
4461
+ if (shell === void 0) return ["bash"];
4462
+ const argv = [];
4463
+ let interpreter;
4464
+ for (const token of shell.trim().split(/\s+/u)) {
4465
+ if (token === "{0}") break;
4466
+ if (interpreter !== void 0) {
4467
+ argv.push(token);
4468
+ continue;
4469
+ }
4470
+ const executable = token.slice(token.lastIndexOf("/") + 1);
4471
+ if (executable === "bash" || executable === "sh") interpreter = token;
4472
+ else if (!(executable === "env" || token.startsWith("-") || ASSIGNMENT.test(token))) {
4473
+ if (NON_SHELL_INTERPRETERS.has(executable)) return;
4474
+ throw new Error(`unrecognized \`shell:\` command: ${shell}. This control parses bash and sh scripts and knowingly skips pwsh, powershell, python, and cmd; it refuses rather than guess at anything else.`);
4475
+ }
4476
+ argv.push(token);
4477
+ }
4478
+ if (interpreter === void 0) throw new Error(`unrecognized \`shell:\` command: ${shell}. No interpreter to parse the script with.`);
4479
+ return argv;
4480
+ };
4481
+ /** Every `run:` block its interpreter refuses to parse. Empty means sound. */
4482
+ const workflowShellParseFailures = (yaml) => {
4483
+ const failures = [];
4484
+ for (const block of workflowRunBlocks(yaml)) {
4485
+ const parser = parserFor(block.shell);
4486
+ if (parser === void 0) continue;
4487
+ const [executable, ...parserArgs] = parser;
4488
+ const script = neutralizeExpressions(block.script);
4489
+ try {
4490
+ execFileSync(executable, [...parserArgs, "-n"], {
4491
+ input: script,
4492
+ stdio: [
4493
+ "pipe",
4494
+ "ignore",
4495
+ "pipe"
4496
+ ]
4497
+ });
4498
+ } catch (error) {
4499
+ failures.push({
4500
+ script,
4501
+ ...block.step === void 0 ? {} : { step: block.step },
4502
+ stderr: String(error.stderr ?? error).trim()
4503
+ });
4504
+ }
4505
+ }
4506
+ return failures;
4507
+ };
4508
+ /**
4509
+ * Fail the generated-workflow lint when any embedded `run:` block is not
4510
+ * parseable bash. Call it on the YAML a generator is about to write, so the
4511
+ * defect is caught at generation rather than by the runner.
4512
+ */
4513
+ const assertWorkflowShellParses = (yaml, options) => {
4514
+ const failures = workflowShellParseFailures(yaml);
4515
+ if (failures.length === 0) return;
4516
+ const detail = failures.map((failure) => ` - ${failure.step ?? "unnamed step"}: ${failure.stderr.replaceAll("\n", "\n ")}`).join("\n");
4517
+ throw new Error(`${options.source} emits shell bash cannot parse; the runner would treat it as a no-op:\n${detail}`);
4518
+ };
4519
+ export { FACTORY_APP_BROKER_ORIGIN, FACTORY_APP_BROKER_PATH, FACTORY_APP_BROKER_TOKEN_PERMISSIONS, FACTORY_CANDIDATE_IMPACT_BASIS_OUTPUT, FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT, FACTORY_CANDIDATE_IMPACT_INERT_OUTPUT, FACTORY_CANDIDATE_IMPACT_STEP_ID, FACTORY_CANDIDATE_IMPACT_UNSUBSCRIBED_OUTPUT, FACTORY_CANDIDATE_PULL_REQUEST_TYPES, FACTORY_CURSOR_OIDC_AUDIENCE, FACTORY_CURSOR_OIDC_ISSUER, FACTORY_CURSOR_OIDC_JWKS_URL, FACTORY_CURSOR_OIDC_MANAGED_RUNTIME, FACTORY_LIFECYCLE_CONTRACT_JOB_ID, FACTORY_LIFECYCLE_CONTRACT_JOB_NAME, FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID, FACTORY_MERGE_FREEZE_CHECK_NAME, FACTORY_MERGE_FREEZE_IF, FACTORY_MERGE_FREEZE_JOB_ID, FACTORY_MERGE_FREEZE_JOB_NAME, FACTORY_MERGE_FREEZE_PERMISSIONS, FACTORY_MERGE_FREEZE_VERIFY_RESULT_EXPRESSION, FACTORY_MERGE_TARGET_REF_CONDITION, FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID, FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_ID, FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_NAME, FACTORY_PREVIEW_CLEANUP_CHECKOUT_REF, FACTORY_PREVIEW_CLEANUP_DEFAULT_SWEEP_CRON, FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID, FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID, FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_NAME, FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID, FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION, FACTORY_PREVIEW_CLEANUP_SWEEP_CONDITION, FACTORY_PRODUCTION_IMPACT_BASIS_OUTPUT, FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT, FACTORY_PRODUCTION_IMPACT_STEP_ID, FACTORY_PRODUCTION_IMPACT_UNSUBSCRIBED_OUTPUT, FACTORY_PROOF_GATE_APP_ID, FACTORY_PROOF_GATE_CHECK_NAME, FACTORY_PROOF_GATE_GUARD, FACTORY_PROOF_GATE_IF, FACTORY_PROOF_GATE_MODE_OUTPUT, FACTORY_PROOF_GATE_OUTPUT, FACTORY_PROOF_GATE_REASONS, FACTORY_PROOF_GATE_REASON_OUTPUT, FACTORY_PROOF_GATE_SHELL, FACTORY_PROOF_GATE_SOURCE_HEAD_OUTPUT, FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT, FACTORY_PROOF_GATE_STEP_ID, FACTORY_PROOF_GATE_STEP_NAME, FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID, FACTORY_PR_STATUS_HUD_CONCURRENCY, FACTORY_PR_STATUS_HUD_IF, FACTORY_PR_STATUS_HUD_JOB_ID, FACTORY_PR_STATUS_HUD_JOB_NAME, FACTORY_PR_STATUS_HUD_PERMISSIONS, FACTORY_PR_STATUS_HUD_PLAN_PATH, FACTORY_PUSH_IDENTITY_SCHEMA_VERSION, GitHubApiError, GitHubAppTokenTransportError, NODE_PNPM_ACTION_FAMILY_NODE24, PREVIEW_PROOF_INVENTORY_CHECK_NAME, PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS, PreviewProofTransportError, SETUP_STEP_ROLES, UPLOAD_ARTIFACT, VITEST_PROFILE_SCHEMA_VERSION, VITEST_PROFILE_TOOL, VitestProfileError, assertPreviewCleanupStackPolicy, assertPreviewCleanupTargetsAbsent, assertProofReuseCoverage, assertVerifyRunnerPolicy, assertWorkflowShellParses, captureVitestProfileEnvironment, discoverOrphanedPreviewCleanupTargets, discoverPreviewCleanupTargets, factoryCandidateImpactWorkflow, factoryCandidateOrPushCondition, factoryLifecycleContractLane, factoryMergeFreezeJob, factoryMergeFreezeScript, factoryPrStatusHudWorkflow, factoryPreviewCleanupTopology, factoryPreviewCleanupWorkflow, factoryPreviewReceiptWorkflow, factoryProductionImpactWorkflow, factoryProofGateScript, factoryProofGateStep, factoryProofReuseSummaryStep, factoryProofTimingStartStep, factoryPushIdentityConsumer, factoryPushIdentityProducer, factoryVerifyRunner, factoryWorkflow, githubAppJwt, isLocalPreviewStage, localPreviewStage, mintInstallationToken, normalizeVitestProfileSample, parseHostedPreviewStage, parseLocalPreviewStage, parsePreviewCleanupResidue, parsePreviewCleanupTargets, previewCleanupDestroyJobId, previewCleanupGithubOutput, previewCleanupResiduePullRequests, previewCleanupStackOutputKey, previewProofInventory, previewProofLifecycle, productionImpactTargetOutput, proofReuseCoverage, proofReuseRequiredCommands, readPullRequestStates, readVitestProfileDocument, recordPreviewCleanupOutcome, resolveProofReuseCommands, runVitestProfile, setupStepsForRoles, verifyRunnerPolicy, workflowRunBlocks, workflowShellParseFailures, writeVitestProfile };