@patronage/factory-ci 1.0.0-alpha.4 → 1.0.0-alpha.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +712 -10
  2. package/dist/.build-fingerprint.json +3 -0
  3. package/dist/alchemy/index.d.ts +1174 -0
  4. package/dist/alchemy/index.js +2142 -0
  5. package/dist/bundle-alchemy-entry-CT5hCphA.js +112 -0
  6. package/dist/execute-alchemy-entry-B397GSk5.d.ts +134 -0
  7. package/dist/execute-alchemy-entry-CZ7Knz4q.js +160 -0
  8. package/dist/index.d.ts +1205 -87
  9. package/dist/index.js +2752 -317
  10. package/package.json +28 -10
  11. package/src/actions.ts +13 -0
  12. package/src/alchemy/child-diagnostics.ts +148 -0
  13. package/src/alchemy/credential-preflight.ts +428 -0
  14. package/src/alchemy/destroy-postcondition.ts +103 -0
  15. package/src/alchemy/evaluate-stack.ts +153 -0
  16. package/src/alchemy/first-deploy-authorization.ts +194 -0
  17. package/src/alchemy/index.ts +144 -0
  18. package/src/alchemy/lifecycle-failure.ts +174 -0
  19. package/src/alchemy/lifecycle.ts +1330 -0
  20. package/src/alchemy/local-emulation.ts +89 -0
  21. package/src/alchemy/plan-effects.ts +510 -0
  22. package/src/alchemy/retained-identity.ts +248 -0
  23. package/src/alchemy/secret-name-policy.ts +96 -0
  24. package/src/alchemy/stage-policy.ts +269 -0
  25. package/src/alchemy/state-tree.ts +168 -0
  26. package/src/alchemy/url-implies-auth.ts +264 -0
  27. package/src/alchemy-baseline.ts +75 -0
  28. package/src/bundle-alchemy-entry.ts +5 -0
  29. package/src/candidate-impact-workflow.ts +110 -0
  30. package/src/candidate-lifecycle.ts +29 -0
  31. package/src/cursor-oidc.ts +33 -0
  32. package/src/execute-alchemy-entry.ts +128 -8
  33. package/src/factory-workflow.ts +83 -40
  34. package/src/github-app-token.ts +92 -18
  35. package/src/github-transport.ts +186 -0
  36. package/src/impact-demand-condition.ts +67 -0
  37. package/src/index.ts +174 -0
  38. package/src/lifecycle-contract-lane.ts +113 -0
  39. package/src/merge-freeze-job.ts +253 -0
  40. package/src/pinned-action.ts +30 -0
  41. package/src/pr-status-hud-workflow.ts +96 -0
  42. package/src/preview-cleanup-topology.ts +115 -0
  43. package/src/preview-proof-inventory.ts +1092 -0
  44. package/src/preview-proof-lifecycle.ts +328 -0
  45. package/src/preview-receipt-workflow.ts +83 -0
  46. package/src/production-impact-workflow.ts +181 -0
  47. package/src/proof-reuse-gate.ts +223 -48
  48. package/src/proof-reuse-presentation.ts +131 -0
  49. package/src/push-identity-workflow.ts +463 -0
  50. package/src/runnable-cli.ts +27 -0
  51. package/src/verify-runner-policy.ts +290 -0
  52. package/src/vitest-profile-reader.test.ts +208 -0
  53. package/src/vitest-profile-reader.ts +225 -0
  54. package/src/vitest-profile.ts +631 -0
package/dist/index.js CHANGED
@@ -1,10 +1,15 @@
1
+ import { t as bundleAlchemyEntry } from "./bundle-alchemy-entry-CT5hCphA.js";
2
+ import { a as localPreviewStage, c as assertAlchemyBaseline, i as isLocalPreviewStage, n as executeAlchemyEntry, o as parseLocalPreviewStage, s as ALCHEMY_BASELINE, t as EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER } from "./execute-alchemy-entry-CZ7Knz4q.js";
1
3
  import { createRequire } from "node:module";
2
- import { mkdir } from "node:fs/promises";
4
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
5
  import path from "node:path";
4
- import { build } from "esbuild";
5
- import { createSign } from "node:crypto";
6
+ import { createSign, randomUUID } from "node:crypto";
6
7
  import { readFileSync } from "node:fs";
7
- import { execFileSync, spawnSync } from "node:child_process";
8
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
9
+ import { execFileSync, spawn } from "node:child_process";
10
+ import { once } from "node:events";
11
+ import { arch, availableParallelism, cpus, platform, release, totalmem } from "node:os";
12
+ import { performance } from "node:perf_hooks";
8
13
  //#region src/actions.ts
9
14
  /**
10
15
  * The canonical Node 24 family shared by factory-project workflows.
@@ -28,236 +33,257 @@ const NODE_PNPM_ACTION_FAMILY_NODE24 = {
28
33
  uses: "pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271"
29
34
  }
30
35
  };
31
- //#endregion
32
- //#region src/bundle-alchemy-entry.ts
33
36
  /**
34
- * Alchemy and Effect must resolve from the *consumer's* node_modules at run
35
- * time, never from the bundle: Alchemy's resource registry and Effect's
36
- * service tags are identity-sensitive, and a second copy silently breaks both.
37
+ * The one `actions/upload-artifact` pin every workflow generator shares
38
+ * (#887). Two callers pinned two different commits of the same tag family;
39
+ * naming the pin here makes that drift impossible the same way the Node/pnpm
40
+ * family does. A caller passes this through `factoryWorkflow`'s
41
+ * `additionalActions.uploadArtifact` explicitly — the catalog names the pin,
42
+ * it does not inject the upload step.
37
43
  */
38
- const ALCHEMY_EXTERNALS = [
39
- "alchemy",
40
- "alchemy/*",
41
- "effect",
42
- "effect/*"
43
- ];
44
+ const UPLOAD_ARTIFACT = {
45
+ tag: "v4.6.2",
46
+ uses: "actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02"
47
+ };
48
+ //#endregion
49
+ //#region src/candidate-lifecycle.ts
44
50
  /**
45
- * The package names behind `ALCHEMY_EXTERNALS`, derived rather than restated so
46
- * a future external can never be guarded by only one of two lists.
51
+ * Pull-request events that can create or refresh a Factory candidate run.
52
+ *
53
+ * GitHub's draft boolean remains the lifecycle authority: these triggers make
54
+ * a run visible, while `factoryCandidateOrPushCondition` keeps substantive
55
+ * jobs idle until the pull request is a candidate.
47
56
  */
48
- const RESERVED_ALIAS_PACKAGES = [...new Set(ALCHEMY_EXTERNALS.map((external) => external.replace(/\/\*$/u, "").toLowerCase()))];
49
- const reservedAliasKey = (key) => RESERVED_ALIAS_PACKAGES.find((name) => key === name || key.startsWith(`${name}/`));
57
+ const FACTORY_CANDIDATE_PULL_REQUEST_TYPES = Object.freeze([
58
+ "opened",
59
+ "synchronize",
60
+ "reopened",
61
+ "ready_for_review"
62
+ ]);
50
63
  /**
51
- * Refuse an alias *key* that is itself a reserved package or one of its
52
- * subpaths. esbuild substitutes aliases before it decides what is external, so
53
- * such a key defeats `external` outright. Keys are compared, never resolved,
54
- * which is what makes string matching sound here.
64
+ * Build a GitHub Actions job condition for candidate PRs and merge-target
65
+ * pushes. The caller owns triggers, jobs, runners, permissions, and topology.
55
66
  */
56
- const assertAliasKeysAreAdmissible = (alias) => {
57
- for (const key of Object.keys(alias)) {
58
- const reserved = reservedAliasKey(key);
59
- if (reserved) throw new Error(`bundleAlchemyEntry cannot alias "${key}": ${reserved} must stay external because its identity is shared with the consumer's runtime, and esbuild applies aliases before external matching. Point the consumer's own resolution at one copy instead.`);
60
- }
67
+ const factoryCandidateOrPushCondition = (candidateCondition) => {
68
+ return ["github.event_name == 'push'", `(${[
69
+ "github.event_name == 'pull_request'",
70
+ "github.event.pull_request.draft != true",
71
+ ...candidateCondition ? [candidateCondition] : []
72
+ ].join(" && ")})`].join(" || ");
61
73
  };
74
+ //#endregion
75
+ //#region src/preview-proof-lifecycle.ts
76
+ const EMPTY_STATE = Object.freeze({ registrations: Object.freeze([]) });
77
+ const DETACHED_PROOF_BRANCH = "(detached)";
62
78
  /**
63
- * Whether a bundled input lives inside a reserved package.
64
- *
65
- * Metafile inputs are paths esbuild resolved and normalized itself, so
66
- * comparing whole segments here answers what was *bundled* rather than how the
67
- * config was spelled. Segments are compared case-insensitively: on a
68
- * case-insensitive filesystem `node_modules/Effect/…` resolves to the real
69
- * package and the metafile keeps the caller's spelling.
79
+ * The branch name adds no guarantee. Record the sentinel unless the checkout
80
+ * is actually on the PR head branch.
70
81
  */
71
- const isReservedInput = (input) => {
72
- const segments = input.toLowerCase().split(/[/\\]+/u);
73
- return segments.some((segment, position) => position > 0 && segments[position - 1] === "node_modules" && RESERVED_ALIAS_PACKAGES.includes(segment));
82
+ const proofBranch = (candidate) => candidate.branch.length > 0 && candidate.branch === candidate.prHeadRef ? void 0 : DETACHED_PROOF_BRANCH;
83
+ const registrationKey$1 = (row) => `${row.stack}:${row.stage}`;
84
+ const disposableStage = (stage, candidate) => {
85
+ const parsed = parseLocalPreviewStage(stage, {
86
+ headSha: candidate.headSha,
87
+ pr: candidate.pr
88
+ });
89
+ if (parsed === null) throw new Error(`Preview proof stage must be a disposable local-pr stage owned by PR #${candidate.pr} at this head.`);
90
+ return parsed.stage;
74
91
  };
75
- /**
76
- * Assert the externals contract against the bundle esbuild actually produced.
77
- *
78
- * Checking alias *values* instead was unsound by construction: `..` segments,
79
- * symlinks, and every other spelling of the same file each need another string
80
- * rule, and the scanner loses. The metafile records the inputs after esbuild's
81
- * own resolution and normalization, so one check closes the whole class —
82
- * whatever route reached an identity-sensitive package, it shows up here.
83
- */
84
- const assertNoReservedInputs = (inputs) => {
85
- const offenders = inputs.filter(isReservedInput);
86
- if (offenders.length > 0) throw new Error(`bundleAlchemyEntry refused a bundle carrying a second copy of an identity-sensitive package: ${offenders.join(", ")}. Those packages must resolve from the consumer's runtime, so nothing may pull their files into the bundle — an alias that re-exports them by bare specifier stays external and is fine.`);
92
+ const assertAdmissibleCandidate = (candidate, stage) => {
93
+ 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.`);
94
+ if (candidate.prState !== "OPEN") throw new Error("Preview proof requires an open pull request.");
95
+ const errors = [];
96
+ if (candidate.dirty) errors.push("Worktree must be clean.");
97
+ if (candidate.headSha !== candidate.prHeadSha) errors.push("HEAD is stale for the current PR head.");
98
+ if (candidate.repository !== candidate.prRepository) errors.push("PR head repository does not match the current repository.");
99
+ if (errors.length > 0) throw new Error(errors.join("\n"));
100
+ return disposableStage(stage, candidate);
87
101
  };
88
- /**
89
- * Pre-bundle an Alchemy entry to a single ESM file, keeping `alchemy` and
90
- * `effect` external (#268).
91
- *
92
- * Both repos that deploy through Alchemy wrote this: the Alchemy CLI runs a
93
- * JavaScript entry, so a TypeScript `alchemy.run.ts` has to be flattened
94
- * first, and the flattening must not swallow the two packages whose identity
95
- * matters. Firedup additionally resolved esbuild *through vite* because it had
96
- * no direct dependency on it; here esbuild is a plain dependency of this
97
- * package and that hack can be deleted.
98
- *
99
- * Returns the absolute path of the file written.
100
- */
101
- const bundleAlchemyEntry = async (options) => {
102
- if (options.alias) assertAliasKeysAreAdmissible(options.alias);
103
- const root = options.absWorkingDir ? path.resolve(options.absWorkingDir) : process.cwd();
104
- const outfile = path.resolve(root, options.outfile);
105
- await mkdir(path.dirname(outfile), { recursive: true });
106
- const result = await build({
107
- absWorkingDir: root,
108
- bundle: true,
109
- entryPoints: [path.resolve(root, options.entry)],
110
- external: ALCHEMY_EXTERNALS,
111
- format: "esm",
112
- metafile: true,
113
- outfile,
114
- packages: options.packages ?? "external",
115
- platform: "node",
116
- sourcemap: options.sourcemap ?? false,
117
- target: options.target ?? "node24",
118
- ...options.alias ? { alias: { ...options.alias } } : {},
119
- ...options.tsconfig ? { tsconfig: path.resolve(root, options.tsconfig) } : {}
102
+ const SHA_PATTERN$1 = /^[0-9a-f]{7,40}$/u;
103
+ const assertPassingEnvelope = (evidence, headSha) => {
104
+ 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.");
105
+ };
106
+ const replaceRegistration$1 = (state, next) => {
107
+ const key = registrationKey$1(next);
108
+ return { registrations: [...state.registrations.filter((row) => registrationKey$1(row) !== key), next] };
109
+ };
110
+ const empty = () => EMPTY_STATE;
111
+ 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));
112
+ const transition = (state, event) => {
113
+ if (event.type === "begin") {
114
+ assertAdmissibleCandidate(event.candidate, event.stage);
115
+ return state;
116
+ }
117
+ if (event.type === "register") {
118
+ const stage = assertAdmissibleCandidate(event.candidate, event.stage);
119
+ if (event.smoke.outcome !== "passed") throw new Error("Preview proof requires passed smoke evidence.");
120
+ if (event.convergence.status !== "passed") throw new Error("Preview proof requires passed convergence evidence.");
121
+ if (!event.stack || !event.url) throw new Error("Preview proof registration requires a stack and URL.");
122
+ assertPassingEnvelope(event.evidence, event.candidate.headSha);
123
+ const branch = proofBranch(event.candidate);
124
+ return replaceRegistration$1(state, {
125
+ ...branch === void 0 ? {} : { branch },
126
+ cleanup: {
127
+ evidence: [],
128
+ outcome: "pending"
129
+ },
130
+ convergence: {
131
+ detail: event.convergence.detail,
132
+ status: "passed"
133
+ },
134
+ headSha: event.candidate.headSha,
135
+ pr: event.candidate.pr,
136
+ proof: {
137
+ check: event.evidence.check,
138
+ headSha: event.evidence.headSha,
139
+ mergeBaseSha: event.evidence.mergeBaseSha,
140
+ patchId: event.evidence.patchId
141
+ },
142
+ smoke: {
143
+ detail: event.smoke.detail,
144
+ outcome: "passed"
145
+ },
146
+ source: "local-self-certified",
147
+ stack: event.stack,
148
+ stage,
149
+ url: event.url
150
+ });
151
+ }
152
+ const existing = state.registrations.find((row) => row.pr === event.pr && row.stack === event.stack && row.stage === event.stage);
153
+ if (!existing) throw new Error(`Preview proof cleanup requires a registration for ${event.stack}/${event.stage}.`);
154
+ const cleanup = event.runUrl === void 0 ? {
155
+ evidence: event.evidence,
156
+ outcome: event.outcome
157
+ } : {
158
+ evidence: event.evidence,
159
+ outcome: event.outcome,
160
+ runUrl: event.runUrl
161
+ };
162
+ return replaceRegistration$1(state, {
163
+ ...existing,
164
+ cleanup
120
165
  });
121
- assertNoReservedInputs(Object.keys(result.metafile.inputs));
122
- return outfile;
166
+ };
167
+ const recover = (state, event) => {
168
+ 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.");
169
+ return transition(state, event);
170
+ };
171
+ const previewProofLifecycle = {
172
+ empty,
173
+ recover,
174
+ resolve,
175
+ transition
123
176
  };
124
177
  //#endregion
125
- //#region src/disposable-stage.ts
178
+ //#region src/github-transport.ts
126
179
  /**
127
- * The disposable Alchemy stage a local preview deploy runs in:
128
- * `local-pr-<pr>-<short sha>` (#268).
180
+ * One GitHub JSON request with bounded transport retries (#830, #923).
129
181
  *
130
- * Two repos invented this grammar independently and then had to agree on it
131
- * anyway, because the same cleanup sweeps delete these stages. A stage that
132
- * does not match is not disposable, and destructive operations must refuse it.
133
- */
134
- const LOCAL_PREVIEW_STAGE_PATTERN = /^local-pr-(?<pr>[1-9]\d*)-(?<sha>[0-9a-f]{7,40})$/u;
135
- /**
136
- * Interpret an untrusted stage name through the one disposable-stage grammar.
137
- * Returns `null` rather than throwing when the value or expected ownership
138
- * does not match.
139
- */
140
- const parseLocalPreviewStage = (stage, expected = {}) => {
141
- const match = LOCAL_PREVIEW_STAGE_PATTERN.exec(stage);
142
- if (!match?.groups) return null;
143
- const pr = Number(match.groups.pr);
144
- const headShaPrefix = match.groups.sha;
145
- if (!Number.isSafeInteger(pr) || expected.pr !== void 0 && pr !== expected.pr) return null;
146
- if (expected.headSha !== void 0) {
147
- const headSha = expected.headSha.trim().toLowerCase();
148
- if (!/^[0-9a-f]{40}$/u.test(headSha) || !headSha.startsWith(headShaPrefix)) return null;
149
- }
150
- return {
151
- headShaPrefix,
152
- pr,
153
- stage
154
- };
155
- };
182
+ * Both GitHub callers in this package share this primitive: the preview-proof
183
+ * inventory and the GitHub App token mint. Each attempt gets a fresh timeout
184
+ * signal. A transport failure — a rejected fetch, a timeout, a transient HTTP
185
+ * status, or a body that dies mid-read — retries with doubling backoff and
186
+ * exhausts into the caller's transport error. A permanent HTTP refusal throws
187
+ * the caller's refusal error on its first response.
188
+ *
189
+ * Retrying a write is safe here: check-run payloads are idempotent per stack
190
+ * and stage, and a token mint issues a fresh token per call.
191
+ */
192
+ const GITHUB_API_VERSION = "2022-11-28";
156
193
  /**
157
- * Whether `stage` is disposable. Pass `pr` to also require PR ownership.
194
+ * Default total transport attempts per request, the first one included. A
195
+ * caller whose request has a fallback overrides it with 1 (#938).
158
196
  */
159
- const isLocalPreviewStage = (stage, pr) => parseLocalPreviewStage(stage, pr === void 0 ? {} : { pr }) !== null;
197
+ const TRANSPORT_RETRY_ATTEMPTS = 3;
198
+ /** Delay before the first retry; each further retry doubles it. */
199
+ const TRANSPORT_RETRY_BACKOFF_MS = 500;
200
+ const defaultTransportWait = (ms) => setTimeout$1(ms);
201
+ let transportWait = defaultTransportWait;
160
202
  /**
161
- * Build the disposable stage name for a pull request head.
162
- *
163
- * Throws when the inputs cannot produce a valid stage, so a caller can never
164
- * deploy into a name the cleanup sweep will not recognise.
203
+ * Bounded transport retries could not reach the GitHub App endpoint (#923).
204
+ * The reason is credential-free, so it is safe to log. Re-exported from
205
+ * `github-app-token.ts`, which owns the mint surface.
165
206
  */
166
- const localPreviewStage = (options) => {
167
- const { headSha, pr, shaLength = 12 } = options;
168
- if (!Number.isSafeInteger(pr) || pr < 1) throw new Error(`pr must be a positive safe integer, got ${pr}.`);
169
- if (!Number.isInteger(shaLength) || shaLength < 7 || shaLength > 40) throw new Error(`shaLength must be an integer from 7 through 40, got ${shaLength}.`);
170
- const normalizedHead = headSha.trim().toLowerCase();
171
- if (!/^[0-9a-f]{40}$/u.test(normalizedHead)) throw new Error(`headSha must be exactly 40 hexadecimal characters, got "${headSha}".`);
172
- return `local-pr-${pr}-${normalizedHead.slice(0, shaLength)}`;
173
- };
174
- //#endregion
175
- //#region src/factory-workflow.ts
176
- const PINNED_ACTION_PATTERN = /^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/u;
177
- const ACTION_TAG_PATTERN = /^v\d+(?:\.\d+){0,2}$/u;
178
- const RESERVED_ACTION_NAMES = new Set([
179
- "checkout",
180
- "setupNode",
181
- "setupPnpm"
182
- ]);
183
- const assertSingleLine = (name, value) => {
184
- if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
185
- };
186
- const actionRepository = (action) => action.uses.slice(0, action.uses.indexOf("@"));
187
- const assertPinnedAction = (name, action, expectedRepository) => {
188
- if (!PINNED_ACTION_PATTERN.test(action.uses)) throw new Error(`${name} must use owner/repository@<40-character commit SHA>, got "${action.uses}".`);
189
- if (expectedRepository && actionRepository(action) !== expectedRepository) throw new Error(`${name} must pin ${expectedRepository}, got ${actionRepository(action)}.`);
190
- if (!ACTION_TAG_PATTERN.test(action.tag)) throw new Error(`${name} tag must be vN, vN.N, or vN.N.N, got "${action.tag}".`);
191
- };
192
- const usesStep = (fallbackName, action) => ({
193
- name: fallbackName,
194
- uses: action.uses
195
- });
196
- const assertActionFamily = (family) => {
197
- assertSingleLine("actionFamily.id", family.id);
198
- assertPinnedAction("checkout", family.checkout, "actions/checkout");
199
- assertPinnedAction("setupNode", family.setupNode, "actions/setup-node");
200
- assertPinnedAction("setupPnpm", family.setupPnpm, "pnpm/action-setup");
201
- };
202
- const assertAdditionalActions = (actions) => {
203
- for (const [name, action] of Object.entries(actions)) {
204
- if (RESERVED_ACTION_NAMES.has(name)) throw new Error(`${name} is reserved by the Node/pnpm action family and cannot be replaced by additionalActions.`);
205
- assertPinnedAction(name, action);
207
+ var GitHubAppTokenTransportError = class extends Error {
208
+ /** How many transport attempts were made before giving up. */
209
+ attempts;
210
+ /** The last transient HTTP status, when the server answered at all. */
211
+ status;
212
+ constructor(reason, attempts, status) {
213
+ super(`GitHub App token transport failed after ${attempts} attempt(s): ${reason}`);
214
+ this.name = "GitHubAppTokenTransportError";
215
+ this.attempts = attempts;
216
+ if (status !== void 0) this.status = status;
206
217
  }
207
218
  };
208
- const setupSteps = (family, setup = {}) => {
209
- const installRun = setup.install?.run ?? "pnpm install --frozen-lockfile";
210
- 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.");
211
- const { checkout, setupNode } = setup;
212
- return Object.freeze([
213
- {
214
- name: checkout?.name ?? "Checkout",
215
- uses: family.checkout.uses,
216
- ...checkout?.ref ? { with: { ref: checkout.ref } } : {}
217
- },
218
- usesStep("Setup pnpm", family.setupPnpm),
219
- {
220
- name: "Setup Node",
221
- uses: family.setupNode.uses,
222
- with: {
223
- cache: "pnpm",
224
- ...setupNode?.cacheDependencyPath ? { "cache-dependency-path": setupNode.cacheDependencyPath } : {},
225
- "node-version-file": setupNode?.nodeVersionFile ?? ".nvmrc"
226
- }
227
- },
228
- {
229
- name: setup.install?.name ?? "Install workspace",
230
- run: installRun
231
- }
232
- ]);
233
- };
234
219
  /**
235
- * Own one generated workflow source's action pins, setup block, provenance
236
- * banner, and gagen pinning policy as a single artifact.
237
- *
238
- * The caller still owns workflow topology, jobs, runners, permissions, and
239
- * every deployment policy decision.
220
+ * Transient statuses are the ones where GitHub never judged the content — a
221
+ * request timeout (408), a rate limit (429), or the server failing (5xx) — so
222
+ * the same bytes can still succeed. Every other non-2xx is GitHub refusing
223
+ * this request and repeats on retry.
240
224
  */
241
- const factoryWorkflow = (options) => {
242
- assertSingleLine("generated.source", options.generated.source);
243
- assertSingleLine("generated.regenerate", options.generated.regenerate);
244
- assertActionFamily(options.actionFamily);
245
- assertAdditionalActions(options.additionalActions ?? {});
246
- const actions = Object.freeze({
247
- checkout: options.actionFamily.checkout,
248
- setupNode: options.actionFamily.setupNode,
249
- setupPnpm: options.actionFamily.setupPnpm,
250
- ...options.additionalActions ?? {}
251
- });
252
- return Object.freeze({
253
- actionFamilyId: options.actionFamily.id,
254
- actions,
255
- setupSteps: setupSteps(options.actionFamily, options.setup),
256
- writeOptions: Object.freeze({
257
- header: [`# GENERATED BY ${options.generated.source} -- DO NOT EDIT.`, `# Regenerate: ${options.generated.regenerate}`].join("\n"),
258
- pinDeps: false
259
- })
260
- });
225
+ const isTransientStatus = (status) => status === 408 || status === 429 || status >= 500;
226
+ /**
227
+ * A bounded, credential-free description of a transport failure. The raw
228
+ * error may retain the request and its `Authorization` header; only the name
229
+ * and a truncated message survive.
230
+ */
231
+ const boundedTransportReason = (error) => error instanceof Error ? `${error.name}: ${error.message}`.slice(0, 200) : "unknown transport error";
232
+ /**
233
+ * One attempt with a fresh timeout signal. A transport failure is reported as
234
+ * an outcome so the caller can retry; a permanent HTTP refusal throws here.
235
+ */
236
+ const githubJsonAttempt = async (options, errors) => {
237
+ let response;
238
+ try {
239
+ response = await options.fetch(options.url, {
240
+ body: options.body,
241
+ headers: {
242
+ Accept: "application/vnd.github+json",
243
+ Authorization: `Bearer ${options.token}`,
244
+ "X-GitHub-Api-Version": GITHUB_API_VERSION,
245
+ ...options.closeConnection ? { Connection: "close" } : {},
246
+ ...options.body === void 0 ? {} : { "Content-Type": "application/json" }
247
+ },
248
+ method: options.method,
249
+ signal: AbortSignal.timeout(options.timeoutMs)
250
+ });
251
+ } catch (error) {
252
+ return {
253
+ ok: false,
254
+ reason: boundedTransportReason(error)
255
+ };
256
+ }
257
+ if (!response.ok) {
258
+ if (!isTransientStatus(response.status)) throw errors.refusal(response.status, response.statusText);
259
+ return {
260
+ ok: false,
261
+ reason: `GitHub API ${response.status} ${response.statusText}`,
262
+ status: response.status
263
+ };
264
+ }
265
+ try {
266
+ return {
267
+ ok: true,
268
+ value: await response.json()
269
+ };
270
+ } catch (error) {
271
+ return {
272
+ ok: false,
273
+ reason: boundedTransportReason(error)
274
+ };
275
+ }
276
+ };
277
+ /** Run one GitHub JSON request with bounded transport retries. */
278
+ const githubJson$1 = async (options, errors) => {
279
+ const attempts = Math.max(1, options.attempts ?? TRANSPORT_RETRY_ATTEMPTS);
280
+ let outcome = await githubJsonAttempt(options, errors);
281
+ for (let attempt = 2; attempt <= attempts && !outcome.ok; attempt += 1) {
282
+ await transportWait(TRANSPORT_RETRY_BACKOFF_MS * 2 ** (attempt - 2));
283
+ outcome = await githubJsonAttempt(options, errors);
284
+ }
285
+ if (outcome.ok) return outcome.value;
286
+ throw errors.transport(outcome, attempts);
261
287
  };
262
288
  //#endregion
263
289
  //#region src/github-app-token.ts
@@ -273,7 +299,7 @@ const factoryWorkflow = (options) => {
273
299
  * returns a token.
274
300
  */
275
301
  /** The default request budget, matching the factory's other GitHub writes. */
276
- const DEFAULT_TIMEOUT_MS = 5e3;
302
+ const DEFAULT_TIMEOUT_MS$1 = 5e3;
277
303
  /** Nine-minute JWT lifetime, backdated a minute against runner clock skew. */
278
304
  const JWT_BACKDATE_SECONDS = 60;
279
305
  const JWT_LIFETIME_SECONDS = 600;
@@ -286,6 +312,8 @@ var GitHubApiError = class extends Error {
286
312
  this.status = status;
287
313
  }
288
314
  };
315
+ /** The Factory App broker's token: repo-scoped Checks write, nothing else. */
316
+ const FACTORY_APP_BROKER_TOKEN_PERMISSIONS = { checks: "write" };
289
317
  const base64url = (value) => Buffer.from(value).toString("base64url");
290
318
  /**
291
319
  * The signed app JWT GitHub accepts as `Authorization: Bearer` for the App
@@ -312,19 +340,19 @@ const githubAppJwt = (credentials, options = {}) => {
312
340
  signer.end();
313
341
  return `${unsigned}.${signer.sign(readKey(credentials.privateKeyPath), "base64url")}`;
314
342
  };
315
- const githubAppJson = async (request, url, jwt, method, timeoutMs) => {
316
- const response = await request(url, {
317
- headers: {
318
- Accept: "application/vnd.github+json",
319
- Authorization: `Bearer ${jwt}`,
320
- "X-GitHub-Api-Version": "2022-11-28"
321
- },
322
- method,
323
- signal: AbortSignal.timeout(timeoutMs)
324
- });
325
- if (!response.ok) throw new GitHubApiError(response.status, response.statusText);
326
- return await response.json();
327
- };
343
+ const githubAppJson = (request, url, jwt, method, budget) => githubJson$1({
344
+ attempts: budget.attempts,
345
+ ...budget.body === void 0 ? {} : { body: budget.body },
346
+ closeConnection: true,
347
+ fetch: request,
348
+ method,
349
+ timeoutMs: budget.timeoutMs,
350
+ token: jwt,
351
+ url
352
+ }, {
353
+ refusal: (status, statusText) => new GitHubApiError(status, statusText),
354
+ transport: (failure, attempts) => new GitHubAppTokenTransportError(failure.reason, attempts, failure.status)
355
+ });
328
356
  /**
329
357
  * Mint an installation access token for one repository.
330
358
  *
@@ -336,57 +364,38 @@ const githubAppJson = async (request, url, jwt, method, timeoutMs) => {
336
364
  const mintInstallationToken = async (input, options = {}) => {
337
365
  const { credentials } = input;
338
366
  const request = options.fetch ?? fetch;
339
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
367
+ const budget = {
368
+ attempts: options.transportAttempts,
369
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS$1
370
+ };
340
371
  const jwt = githubAppJwt(credentials, options);
341
372
  let { installationId } = credentials;
342
373
  if (installationId === void 0) {
343
- const installation = await githubAppJson(request, `https://api.github.com/repos/${input.owner}/${input.repo}/installation`, jwt, "GET", timeoutMs);
374
+ const installation = await githubAppJson(request, `https://api.github.com/repos/${input.owner}/${input.repo}/installation`, jwt, "GET", budget);
344
375
  if (typeof installation.id !== "number") throw new TypeError("GitHub App installation response omitted id");
345
376
  installationId = installation.id;
346
377
  }
347
- const minted = await githubAppJson(request, `https://api.github.com/app/installations/${installationId}/access_tokens`, jwt, "POST", timeoutMs);
378
+ const restriction = input.permissions === void 0 && input.repositories === void 0 ? void 0 : JSON.stringify({
379
+ ...input.permissions === void 0 ? {} : { permissions: input.permissions },
380
+ ...input.repositories === void 0 ? {} : { repositories: [...input.repositories] }
381
+ });
382
+ const minted = await githubAppJson(request, `https://api.github.com/app/installations/${installationId}/access_tokens`, jwt, "POST", restriction === void 0 ? budget : {
383
+ ...budget,
384
+ body: restriction
385
+ });
348
386
  if (typeof minted.token !== "string") throw new TypeError("GitHub App token response omitted token");
349
387
  return minted.token;
350
388
  };
351
389
  //#endregion
352
- //#region src/execute-alchemy-entry.ts
353
- /**
354
- * Bundle a consumer-owned Alchemy entry, resolve that consumer's Alchemy CLI,
355
- * run it under the current Node binary, and return only on a successful exit.
356
- *
357
- * Deploy/destroy/plan selection, stage admission, credentials, and every
358
- * convergence or destructive-change policy remain the caller's responsibility.
359
- */
360
- const executeAlchemyEntry = async (options) => {
361
- const cliEntry = createRequire(options.from).resolve("alchemy/bin/alchemy.js");
362
- const bundledEntry = await bundleAlchemyEntry(options.bundle);
363
- const result = spawnSync(process.execPath, [
364
- cliEntry,
365
- ...options.args,
366
- bundledEntry
367
- ], {
368
- cwd: options.cwd ?? options.bundle.absWorkingDir ?? process.cwd(),
369
- encoding: "utf-8",
370
- env: options.env ?? process.env,
371
- stdio: options.stdio ?? "inherit"
372
- });
373
- if (result.error) throw new Error("Failed to start the Alchemy CLI.");
374
- if (result.signal) throw new Error(`Alchemy CLI terminated by signal ${result.signal}.`);
375
- if (result.status !== 0) throw new Error(result.status === null ? "Alchemy CLI exited without reporting a status." : `Alchemy CLI exited with status ${result.status}.`);
376
- return {
377
- bundledEntry,
378
- stderr: result.stderr,
379
- stdout: result.stdout
380
- };
381
- };
382
- //#endregion
383
390
  //#region src/proof-reuse-gate.ts
384
391
  /**
385
392
  * The GitHub-side **proof-reuse gate** (ADR 0022, #309, #317).
386
393
  *
387
394
  * It answers one question, before checkout and before install: may this job
388
395
  * reuse the local verification the factory already published for *this exact
389
- * head*? Refusing runs hosted CI; it never fails the candidate. Three
396
+ * head*? It asks that only on a pull request, so every default-branch push
397
+ * executes the full hosted suite (#863). Refusing runs hosted CI; it never
398
+ * fails the candidate. Three
390
399
  * repositories had independently grown their own answer to that question and
391
400
  * had already drifted apart, so the answer lives here once, with the App
392
401
  * identity, check name, step identity, output names, guard, and every trust
@@ -400,9 +409,9 @@ const executeAlchemyEntry = async (options) => {
400
409
  * Escaped so the emitted text carries a GitHub Actions expression rather than
401
410
  * this file carrying a JavaScript template hole.
402
411
  */
403
- const githubExpression = (expression) => `\${{ ${expression} }}`;
412
+ const githubExpression$1 = (expression) => `\${{ ${expression} }}`;
404
413
  /** A braced shell expansion that has to survive TypeScript interpolation. */
405
- const shellExpansion = (expression) => `\${${expression}}`;
414
+ const shellExpansion$1 = (expression) => `\${${expression}}`;
406
415
  /**
407
416
  * Single-quote a value for the emitted script. Every non-literal value that
408
417
  * reaches the script goes through this.
@@ -432,6 +441,13 @@ const FACTORY_PROOF_GATE_APP_ID = "4314840";
432
441
  /** Step id the guard condition refers to. */
433
442
  const FACTORY_PROOF_GATE_STEP_ID = "factory-proof";
434
443
  /**
444
+ * Human-visible name of the gate step as the Actions jobs API serves it. A
445
+ * read-only run analyzer (`psf ci:analyze`, #647) matches on this name to
446
+ * classify a run as proof-reuse versus full fallback, so it is exported from
447
+ * exactly the module that writes it — matching on a re-typed copy would drift.
448
+ */
449
+ const FACTORY_PROOF_GATE_STEP_NAME = "Check for factory proof of this head";
450
+ /**
435
451
  * The shell the gate runs under, and it is a correctness requirement rather
436
452
  * than a preference.
437
453
  *
@@ -468,27 +484,40 @@ const FACTORY_PROOF_GATE_REASON_OUTPUT = "reason";
468
484
  * proof that executed every command the surface requires is reusable.
469
485
  */
470
486
  const FACTORY_PROOF_GATE_MODE_OUTPUT = "mode";
487
+ /** Exact Checks API URL of the proof generation selected by the gate. */
488
+ const FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT = "source-check-url";
471
489
  /**
472
490
  * Guard for every step the gate protects. Deliberately `!= 'true'` and not
473
491
  * `== 'false'`: an unset, empty, or garbled output must run the suite.
474
492
  */
475
493
  const FACTORY_PROOF_GATE_GUARD = `steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_OUTPUT} != 'true'`;
476
494
  /**
477
- * Pull requests only. A push to a protected branch must never skip: deploy
478
- * gates wait for a green required check at the *merged* SHA, and no local
479
- * proof was ever written for that tree.
495
+ * Pull requests only — the gate's single condition (#873, default since #863,
496
+ * the only mode since the merge-target opt-out was deleted).
497
+ *
498
+ * A merge target's guarantee is about the whole tree, not the diff. A
499
+ * candidate proof only ever binds the diff the candidate was scoped to, so
500
+ * reusing it on the merged commit proves less than the merge target needs.
501
+ * #931 is that defect observed — a `main` push reused a candidate proof,
502
+ * executed no command, and left a red package unnoticed for three days. Every
503
+ * default-branch push therefore executes the full hosted suite, whatever
504
+ * proof exists.
505
+ *
506
+ * Which branches trigger the workflow at all stays repository-owned. This
507
+ * condition only keeps the gate from consulting proof outside a pull request.
480
508
  */
481
509
  const FACTORY_PROOF_GATE_IF = "github.event_name == 'pull_request'";
482
510
  /**
483
511
  * The complete refusal vocabulary. Deliberately few, because these are the
484
- * only distinctions the gate can honestly make from one Checks API read.
512
+ * only distinctions the gate can honestly make from its Checks API reads.
485
513
  *
486
514
  * - `proven` a covering, passing, unambiguous proof for this exact head
487
515
  * - `none` no App-verified factory check run at this commit
488
516
  * - `pending` the newest generation had not completed when this job read it
489
517
  * - `failed` the newest generation records no pass
490
518
  * - `unreadable` it passed but carries no binding for this repository and head
491
- * - `incomplete` it passed but did not execute every required command
519
+ * - `incomplete` its executed plus stamp-authorized released commands do not
520
+ * cover every required command
492
521
  * - `ambiguous` two newest generations share the greatest start time
493
522
  * - `error` the gate could not reach a decision (fail open)
494
523
  *
@@ -522,6 +551,13 @@ const FACTORY_PROOF_GATE_REASONS = [
522
551
  */
523
552
  const COMMAND_IDENTITY = /^\w[\w.:@/-]*$/u;
524
553
  const COMMAND_IDENTITY_MAX_LENGTH = 120;
554
+ /**
555
+ * The impact-stamp interpretation the paired factory packages currently
556
+ * share. A release recorded under any other version is an unmodelled input and
557
+ * cannot subtract hosted work. This is intentionally fail-closed and moves in
558
+ * lockstep with the proof/check-payload producer.
559
+ */
560
+ const TRUSTED_IMPACT_STAMP_VERSION = 4;
525
561
  const isProofReuseCommand = (value) => {
526
562
  if (!(value && typeof value === "object")) return false;
527
563
  const entry = value;
@@ -550,8 +586,46 @@ const proofReuseRequiredCommands = (commands) => {
550
586
  return names.toSorted();
551
587
  };
552
588
  /**
553
- * jq program: every page of the Checks API result in, three sanitized lines
554
- * (`reason`, `mode`, missing commands) out.
589
+ * Resolve command *identities* to their `ProofReuseCommand` objects (ADR
590
+ * 0021).
591
+ *
592
+ * Selection by name is deliberately a consumer decision (proof-surfaces.ts in
593
+ * software-factory-hq, the `paitronage:verify` filter in paitronage's
594
+ * `verify.ts`): only the consumer knows which named commands a guarded
595
+ * surface requires. What both of those implementations independently
596
+ * hand-rolled is the same lookup — find each name in the profile's command
597
+ * catalog, and refuse to silently shrink the required set when a name has no
598
+ * entry. That lookup is what this function is: the mechanic, not the
599
+ * selection.
600
+ *
601
+ * Throwing at generation time (rather than returning `undefined` or an empty
602
+ * array) is deliberate: a name with no catalog entry is a mistake in the
603
+ * generator source, not a runtime condition a consumer should have to check
604
+ * for, and a required set that quietly loses an entry is exactly what makes a
605
+ * passing proof trivially "covering".
606
+ *
607
+ * `selectionLabel` names the failure, nothing else: it is not part of the
608
+ * selection this function resolves, only prose a consumer supplies for its
609
+ * own thrown error (e.g. HQ's surface name, "core" or "docs"). The message
610
+ * deliberately says "the profile's command catalog" rather than naming
611
+ * `software-factory.profile.json`: a fleet-generic library must not assume
612
+ * every consumer's catalog is that exact file, so this wording differs
613
+ * on purpose from the HQ-local message it replaced.
614
+ */
615
+ const resolveProofReuseCommands = (catalog, names, selectionLabel) => names.map((name) => {
616
+ const command = catalog.find((entry) => entry.name === name);
617
+ if (!command) {
618
+ const location = selectionLabel ? `Proof-reuse selection for the ${selectionLabel} surface names` : "Proof-reuse selection names";
619
+ throw new Error(`${location} "${name}", which the profile's command catalog does not define.`);
620
+ }
621
+ return {
622
+ command: command.command,
623
+ name: command.name
624
+ };
625
+ });
626
+ /**
627
+ * jq program: every page of the Checks API result in, four sanitized lines
628
+ * (`reason`, `mode`, uncovered commands, source URL) out.
555
629
  *
556
630
  * The input is what `gh api --paginate` actually writes: the pages
557
631
  * *concatenated* as a stream of top-level response objects, not merged into
@@ -608,6 +682,20 @@ def startedAt: (.started_at // "") | tostring;
608
682
  def rankable:
609
683
  test("^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z$");
610
684
 
685
+ def nonemptyString:
686
+ type == "string" and length > 0;
687
+
688
+ def distinctNames:
689
+ (map(.name) | length) == (map(.name) | unique | length);
690
+
691
+ def releaseAuthorized($release; $commands; $stamp):
692
+ ([ $commands[] | select(.name == $release.name) ]) as $commandRows
693
+ | ([ $stamp.targets[] | select(.name == $release.impactTarget) ]) as $targetRows
694
+ | ($commandRows | length) == 1
695
+ and $commandRows[0].impactTarget == $release.impactTarget
696
+ and ($targetRows | length) == 1
697
+ and $targetRows[0].impact == "not-affected";
698
+
611
699
  [ .[]
612
700
  | (.check_runs // [])[]
613
701
  | select(.name == $name)
@@ -615,20 +703,62 @@ def rankable:
615
703
  | { started: startedAt,
616
704
  status: (.status // ""),
617
705
  conclusion: (.conclusion // ""),
706
+ url: ((.html_url // "") | tostring),
618
707
  binding: binding }
619
708
  ] as $runs
620
709
  | ($runs | map(.started | rankable) | all) as $orderable
621
710
  | ($runs | map(.started | sub("\\.[0-9]+Z$"; "Z")) | max) as $newest
622
711
  | [ $runs[] | select((.started | sub("\\.[0-9]+Z$"; "Z")) == $newest) ] as $generation
623
- | (if ($runs | length) == 0 then ["none", "", ""]
624
- elif ($orderable | not) then ["ambiguous", "", ""]
625
- elif ($generation | length) != 1 then ["ambiguous", "", ""]
712
+ | (if ($runs | length) == 0 then ["none", "", "", ""]
713
+ elif ($orderable | not) then ["ambiguous", "", "", ""]
714
+ elif ($generation | length) != 1 then ["ambiguous", "", "", ""]
626
715
  else
627
716
  $generation[0] as $run
628
717
  | (if ($run.binding | type) == "object" then $run.binding else {} end) as $proof
629
718
  | (($proof.mode // "") | tostring) as $mode
630
719
  | (($proof.executedCommands // []) | map(select(type == "string"))) as $executed
631
- | ($required - $executed) as $missing
720
+ | ($proof | has("notRequiredCommands")) as $hasReleases
721
+ | (if $hasReleases then $proof.notRequiredCommands else [] end) as $releases
722
+ | ($proof.verificationCommands // null) as $commands
723
+ | ($proof.impactStamp // null) as $stamp
724
+ | (if ($hasReleases | not) then true
725
+ else
726
+ ($proof.proofSchemaVersion == 4)
727
+ and ($releases | type) == "array"
728
+ and ($releases | length) > 0
729
+ and ($releases | all(.[];
730
+ type == "object"
731
+ and (.name | nonemptyString)
732
+ and (.impactTarget | nonemptyString)
733
+ and (.basis | nonemptyString)))
734
+ and ($releases | distinctNames)
735
+ and ($commands | type) == "array"
736
+ and ($commands | all(.[];
737
+ type == "object"
738
+ and (.name | nonemptyString)
739
+ and ((has("impactTarget") | not) or (.impactTarget | nonemptyString))))
740
+ and ($commands | distinctNames)
741
+ and ($stamp | type) == "object"
742
+ and ($stamp.stampVersion == ${TRUSTED_IMPACT_STAMP_VERSION})
743
+ and ($stamp.basis == "target-scoped")
744
+ and (($stamp.reasons | type) == "array")
745
+ and ($stamp.reasons | all(.[]; type == "string"))
746
+ and (($stamp.unsubscribedPaths | type) == "array")
747
+ and ($stamp.unsubscribedPaths | all(.[]; type == "string"))
748
+ and (($stamp.targets | type) == "array")
749
+ and ($stamp.targets | all(.[];
750
+ type == "object"
751
+ and (.name | nonemptyString)
752
+ and (.basis | nonemptyString)
753
+ and ((.impact == "affected") or (.impact == "not-affected"))
754
+ and ((.subscribedPaths | type) == "array")
755
+ and (.subscribedPaths | all(.[]; type == "string"))))
756
+ and ($stamp.targets | distinctNames)
757
+ and (([$releases[].name] - $executed | length) == ($releases | length))
758
+ and ($releases | all(.[]; releaseAuthorized(.; $commands; $stamp)))
759
+ end) as $releasesValid
760
+ | (if $releasesValid then [$releases[].name] else [] end) as $released
761
+ | ($required - $executed - $released) as $missing
632
762
  | (if $run.status != "completed" then "pending"
633
763
  elif $run.conclusion != "success" then "failed"
634
764
  elif (($run.binding | type) != "object")
@@ -638,10 +768,11 @@ def rankable:
638
768
  or ($proof.repository != $repository) then "unreadable"
639
769
  elif $proof.outcome != "passed" then "failed"
640
770
  elif ($required | length) == 0 then "incomplete"
771
+ elif ($releasesValid | not) then "incomplete"
641
772
  elif ($missing | length) != 0 then "incomplete"
642
773
  else "proven"
643
774
  end) as $reason
644
- | [$reason, $mode, ($missing | join(", "))]
775
+ | [$reason, $mode, ($missing | join(", ")), $run.url]
645
776
  end)
646
777
  | map(gsub("[\\r\\n\\t]"; " "))
647
778
  | join("\n")
@@ -666,9 +797,9 @@ const CORRECTIVE_LINE = "Run `psf pr:verify` before publishing to reuse local pr
666
797
  const UNUSABLE_SELECTION_SCRIPT = String.raw`{
667
798
  printf '${FACTORY_PROOF_GATE_OUTPUT}=false\n'
668
799
  printf '${FACTORY_PROOF_GATE_REASON_OUTPUT}=error\n'
669
- } >> "${shellExpansion("GITHUB_OUTPUT:-/dev/null")}"`;
800
+ } >> "${shellExpansion$1("GITHUB_OUTPUT:-/dev/null")}"`;
670
801
  /** Surface labels reach markdown, so only a plain, bounded label survives. */
671
- const safeLabel = (surface) => {
802
+ const safeLabel$1 = (surface) => {
672
803
  const cleaned = (typeof surface === "string" ? surface : "").replaceAll(/[^\w -]/gu, "").trim().slice(0, 60);
673
804
  return cleaned.length > 0 ? cleaned : "verification";
674
805
  };
@@ -684,31 +815,42 @@ reason=error
684
815
  detail=''
685
816
  mode=''
686
817
  missing=''
818
+ source_url=''
687
819
 
820
+ # One proof lookup at one commit. Sets lookup_reason / lookup_mode /
821
+ # lookup_missing / lookup_url, or lookup_detail when the read itself
822
+ # failed. Always returns 0: every caller must reach the single
823
+ # GITHUB_OUTPUT write below whatever this function meets.
824
+ #
688
825
  # filter=all with full pagination is load-bearing (ADR 0022). GitHub's
689
826
  # default "latest" filter is ordered by completion, so a newer generation
690
827
  # that is still running can be hidden behind an older completed one — the
691
828
  # gate would then read a stale pass as current.
692
- if [ -z "${shellExpansion("HEAD_SHA:-")}" ]; then
693
- detail='no pull request head SHA'
694
- elif [ -z "${shellExpansion("GITHUB_REPOSITORY:-")}" ]; then
695
- detail='no repository name'
696
- elif ! response=$(gh api --method GET --paginate \
697
- "repos/$GITHUB_REPOSITORY/commits/$HEAD_SHA/check-runs" \
698
- -f "check_name=$CHECK_NAME" \
699
- -f filter=all \
700
- -f per_page=100 2>&1); then
701
- detail="checks API unreadable: $response"
702
- elif ! finding=$(printf '%s' "$response" | jq -r -s \
703
- --arg name "$CHECK_NAME" \
704
- --arg app "$FACTORY_APP_ID" \
705
- --arg sha "$HEAD_SHA" \
706
- --arg repository "$GITHUB_REPOSITORY" \
707
- --argjson required "$REQUIRED_COMMANDS" \
708
- '${GATE_JQ}' 2>&1); then
709
- detail="unreadable proof binding: $finding"
710
- else
711
- # Three separate reads, not one IFS split: tab is IFS whitespace, so a
829
+ gate_lookup() {
830
+ lookup_reason=error
831
+ lookup_mode=''
832
+ lookup_missing=''
833
+ lookup_url=''
834
+ lookup_detail=''
835
+ if ! lookup_response=$(gh api --method GET --paginate \
836
+ "repos/$GITHUB_REPOSITORY/commits/$1/check-runs" \
837
+ -f "check_name=$CHECK_NAME" \
838
+ -f filter=all \
839
+ -f per_page=100 2>&1); then
840
+ lookup_detail="checks API unreadable: $lookup_response"
841
+ return 0
842
+ fi
843
+ if ! lookup_finding=$(printf '%s' "$lookup_response" | jq -r -s \
844
+ --arg name "$CHECK_NAME" \
845
+ --arg app "$FACTORY_APP_ID" \
846
+ --arg sha "$1" \
847
+ --arg repository "$GITHUB_REPOSITORY" \
848
+ --argjson required "$REQUIRED_COMMANDS" \
849
+ '${GATE_JQ}' 2>&1); then
850
+ lookup_detail="unreadable proof binding: $lookup_finding"
851
+ return 0
852
+ fi
853
+ # Four separate reads, not one IFS split: tab is IFS whitespace, so a
712
854
  # split would collapse the empty fields the vocabulary relies on.
713
855
  #
714
856
  # The trailing "|| :" on each read is load-bearing. "missing" is empty for
@@ -719,17 +861,32 @@ else
719
861
  # GITHUB_OUTPUT write below, which is exactly how this gate failed in
720
862
  # hosted CI on every decidable verdict while every test passed (#319).
721
863
  {
722
- IFS= read -r reason || :
723
- IFS= read -r mode || :
724
- IFS= read -r missing || :
725
- } <<< "$finding"
726
- case "$reason" in
864
+ IFS= read -r lookup_reason || :
865
+ IFS= read -r lookup_mode || :
866
+ IFS= read -r lookup_missing || :
867
+ IFS= read -r lookup_url || :
868
+ } <<< "$lookup_finding"
869
+ case "$lookup_reason" in
727
870
  proven | none | pending | failed | unreadable | incomplete | ambiguous) ;;
728
871
  *)
729
- detail="unexpected gate result: $reason"
730
- reason=error
872
+ lookup_detail="unexpected gate result: $lookup_reason"
873
+ lookup_reason=error
731
874
  ;;
732
875
  esac
876
+ return 0
877
+ }
878
+
879
+ if [ -z "${shellExpansion$1("HEAD_SHA:-")}" ]; then
880
+ detail='no verification head SHA'
881
+ elif [ -z "${shellExpansion$1("GITHUB_REPOSITORY:-")}" ]; then
882
+ detail='no repository name'
883
+ else
884
+ gate_lookup "$HEAD_SHA"
885
+ reason="$lookup_reason"
886
+ detail="$lookup_detail"
887
+ mode="$lookup_mode"
888
+ missing="$lookup_missing"
889
+ source_url="$lookup_url"
733
890
  fi
734
891
 
735
892
  # The binding is App-verified, but it still reaches markdown. Only a plain
@@ -748,8 +905,11 @@ fi
748
905
  # line so it cannot restructure the summary it is written into.
749
906
  detail=$(printf '%s' "$detail" | tr '\n\r\t' ' ' | cut -c1-240)
750
907
  missing=$(printf '%s' "$missing" | tr '\n\r\t' ' ' | cut -c1-240)
908
+ if ! [[ "$source_url" =~ ^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/runs/[0-9]+$ ]]; then
909
+ source_url=''
910
+ fi
751
911
 
752
- SUMMARY="${shellExpansion("GITHUB_STEP_SUMMARY:-/dev/null")}"
912
+ SUMMARY="${shellExpansion$1("GITHUB_STEP_SUMMARY:-/dev/null")}"
753
913
  say() { printf '%s\n' "$1" >> "$SUMMARY"; }
754
914
 
755
915
  say "## Proof reuse: $SURFACE"
@@ -758,9 +918,13 @@ say ''
758
918
  case "$reason" in
759
919
  proven)
760
920
  echo "Factory proof: reusing local verification of $HEAD_SHA; skipping the $SURFACE suite."
761
- say "Skipped. The factory already verified this exact commit, so this job did not run the $SURFACE suite a second time."
921
+ say "Skipped. The factory already verified this exact content, so this job did not run the $SURFACE suite a second time."
762
922
  say ''
763
- say "- Reused proof: the \`$CHECK_NAME\` check run published by the pinned factory GitHub App."
923
+ if [ -n "$source_url" ]; then
924
+ say "- Reused proof: [\`$CHECK_NAME\`]($source_url), published by the pinned factory GitHub App."
925
+ else
926
+ say "- Reused proof: the \`$CHECK_NAME\` check run published by the pinned factory GitHub App."
927
+ fi
764
928
  say "- Covers head: \`$HEAD_SHA\`"
765
929
  say "- Recorded mode: \`$mode\` (diagnostic only), outcome \`passed\`."
766
930
  ;;
@@ -795,7 +959,7 @@ case "$reason" in
795
959
  incomplete)
796
960
  say "Ran the full suite. The factory proof for this commit does not cover every command the $SURFACE surface requires."
797
961
  say ''
798
- say "The newest \`$CHECK_NAME\` check run at head \`$HEAD_SHA\` passed, but its \`executedCommands\` is missing: \`$missing\`"
962
+ 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\`"
799
963
  say ''
800
964
  say '${CORRECTIVE_LINE}'
801
965
  ;;
@@ -817,7 +981,7 @@ esac
817
981
  say ''
818
982
 
819
983
  if [ "$verdict" != 'true' ]; then
820
- echo "No reusable factory proof for ${shellExpansion("HEAD_SHA:-<unknown>")}; running the $SURFACE suite ($reason). $detail"
984
+ echo "No reusable factory proof for ${shellExpansion$1("HEAD_SHA:-<unknown>")}; running the $SURFACE suite ($reason). $detail"
821
985
  fi
822
986
 
823
987
  # The only write. A crash before this line leaves the output unset, the guard
@@ -826,7 +990,8 @@ fi
826
990
  printf '${FACTORY_PROOF_GATE_OUTPUT}=%s\n' "$verdict"
827
991
  printf '${FACTORY_PROOF_GATE_REASON_OUTPUT}=%s\n' "$reason"
828
992
  printf '${FACTORY_PROOF_GATE_MODE_OUTPUT}=%s\n' "$mode"
829
- } >> "${shellExpansion("GITHUB_OUTPUT:-/dev/null")}"
993
+ printf '${FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT}=%s\n' "$source_url"
994
+ } >> "${shellExpansion$1("GITHUB_OUTPUT:-/dev/null")}"
830
995
  `.trim();
831
996
  /**
832
997
  * The gate script. Exported so it can be executed directly under test against
@@ -842,13 +1007,14 @@ fi
842
1007
  */
843
1008
  const factoryProofGateScript = ({ commands, surface }) => {
844
1009
  const required = proofReuseRequiredCommands(commands);
845
- return required ? gateScript(required, safeLabel(surface)) : UNUSABLE_SELECTION_SCRIPT;
1010
+ return required ? gateScript(required, safeLabel$1(surface)) : UNUSABLE_SELECTION_SCRIPT;
846
1011
  };
847
1012
  /**
848
1013
  * The step itself, structurally accepted by gagen's `step()` without adding a
849
- * gagen runtime dependency. It belongs first in the job it guards: one Checks
850
- * API read with the default `GITHUB_TOKEN` (`checks: read`), no checkout, no
851
- * install, so a proven head costs a runner nothing beyond job startup.
1014
+ * gagen runtime dependency. It belongs first in the job it guards: a few API
1015
+ * reads with the default `GITHUB_TOKEN`, no checkout, no install, so a proven
1016
+ * head costs a runner nothing beyond job startup. The step runs on pull
1017
+ * requests only, so it needs only `checks: read` (#873, #863).
852
1018
  *
853
1019
  * A **step, not a job**, and that is not a style preference. A separate gate
854
1020
  * job that errored would leave the guarded job `skipped`, and a summary job
@@ -860,12 +1026,12 @@ const factoryProofGateScript = ({ commands, surface }) => {
860
1026
  const factoryProofGateStep = (options) => Object.freeze({
861
1027
  continueOnError: true,
862
1028
  env: Object.freeze({
863
- GH_TOKEN: githubExpression("secrets.GITHUB_TOKEN"),
864
- HEAD_SHA: githubExpression("github.event.pull_request.head.sha")
1029
+ GH_TOKEN: githubExpression$1("secrets.GITHUB_TOKEN"),
1030
+ HEAD_SHA: githubExpression$1("github.event.pull_request.head.sha || github.sha")
865
1031
  }),
866
1032
  id: FACTORY_PROOF_GATE_STEP_ID,
867
1033
  if: FACTORY_PROOF_GATE_IF,
868
- name: "Check for factory proof of this head",
1034
+ name: FACTORY_PROOF_GATE_STEP_NAME,
869
1035
  run: factoryProofGateScript(options),
870
1036
  shell: FACTORY_PROOF_GATE_SHELL
871
1037
  });
@@ -893,11 +1059,2280 @@ const proofReuseCoverage = ({ commands, skipped }) => {
893
1059
  const assertProofReuseCoverage = (input) => {
894
1060
  const report = proofReuseCoverage(input);
895
1061
  if (report.covered) return report;
896
- const surface = safeLabel(input.surface ?? "");
1062
+ const surface = safeLabel$1(input.surface ?? "");
897
1063
  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(", ")}`;
898
1064
  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.`);
899
1065
  };
900
1066
  //#endregion
1067
+ //#region src/preview-proof-inventory.ts
1068
+ /**
1069
+ * Hosted preview-proof inventory (#639): persist and list Factory-App
1070
+ * registrations, and record cleanup outcomes, without PR comments.
1071
+ *
1072
+ * `list` is a read over App-owned commit check-runs and works with a workflow
1073
+ * `GITHUB_TOKEN`. `persist` and `recordCleanup` write those check-runs, which
1074
+ * GitHub only allows the producing App to update. Pass an installation token
1075
+ * the caller minted; this package does not read operator config or hold
1076
+ * secrets. Cleanup writes go through `previewProofLifecycle.transition` with
1077
+ * `{ type: "cleanup" }`. Outcomes are never inferred from whether a stage
1078
+ * still exists.
1079
+ *
1080
+ * Transient transport failures are retried with bounded backoff and then
1081
+ * surface as `PreviewProofTransportError` (#830). A failure from `persist` or
1082
+ * `recordCleanup` is an evidence-registration failure, never a failed
1083
+ * deployment: the caller retains the healthy disposable stage, records its own
1084
+ * proof BLOCKED (never PASS), and re-runs registration at the same head —
1085
+ * writes are keyed by stack and stage, so resuming needs no redeploy.
1086
+ * Admission stays fail-closed on its own: an unregistered proof never
1087
+ * satisfies the preview demand.
1088
+ */
1089
+ /** Check-run name that carries one registration JSON payload. Not a gate. */
1090
+ const PREVIEW_PROOF_INVENTORY_CHECK_NAME = "patronage-factory/preview-proof";
1091
+ /**
1092
+ * Least privilege for a job whose `GITHUB_TOKEN` calls `list`. A
1093
+ * `permissions` block zeroes every unlisted scope, and `list` reads five
1094
+ * endpoints: `pulls/{pr}`, `pulls/{pr}/commits`, and the GraphQL force-push
1095
+ * timeline (`pull-requests`), `compare` (`contents`), and
1096
+ * `commits/{sha}/check-runs` (`checks`). A job
1097
+ * that omits `pull-requests: read` fails with 403 on a same-repository PR
1098
+ * and skips every destroy matrix (#859). Give the discovery job this object.
1099
+ */
1100
+ const PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS = Object.freeze({
1101
+ checks: "read",
1102
+ contents: "read",
1103
+ "pull-requests": "read"
1104
+ });
1105
+ const INVENTORY_KIND = "patronage-factory-preview-proof";
1106
+ const INVENTORY_SCHEMA_VERSION = 1;
1107
+ const DEFAULT_TIMEOUT_MS = 5e3;
1108
+ const CHECK_RUNS_PER_PAGE = 100;
1109
+ const COMMITS_PER_PAGE = 100;
1110
+ const MAX_CHECK_RUN_PAGES = 10;
1111
+ const MAX_COMMIT_PAGES = 20;
1112
+ /** GitHub's documented hard cap on `GET /pulls/{pr}/commits`. */
1113
+ const GITHUB_PULL_COMMITS_CAP = 250;
1114
+ const FORCE_PUSH_TIMELINE_PER_PAGE = 100;
1115
+ const MAX_FORCE_PUSH_PAGES = 20;
1116
+ const GRAPHQL_FORCE_PUSH_BEFORE = `query PreviewProofForcePushBefore($owner: String!, $name: String!, $pr: Int!, $first: Int!, $cursor: String) {
1117
+ repository(owner: $owner, name: $name) {
1118
+ pullRequest(number: $pr) {
1119
+ timelineItems(itemTypes: [HEAD_REF_FORCE_PUSHED_EVENT], first: $first, after: $cursor) {
1120
+ nodes {
1121
+ ... on HeadRefForcePushedEvent {
1122
+ beforeCommit { oid }
1123
+ }
1124
+ }
1125
+ pageInfo { endCursor hasNextPage }
1126
+ }
1127
+ }
1128
+ }
1129
+ }`;
1130
+ const SHA_PATTERN = /^[0-9a-f]{7,40}$/u;
1131
+ const FULL_SHA_PATTERN = /^[0-9a-f]{40}$/u;
1132
+ const isRecord$1 = (value) => typeof value === "object" && value !== null;
1133
+ const isCleanupStatus = (value) => value === "failed" || value === "passed" || value === "pending";
1134
+ const readStringArray = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value : null;
1135
+ const readIdentity = (value) => {
1136
+ if (typeof value.pr !== "number" || !Number.isInteger(value.pr) || value.pr <= 0 || typeof value.headSha !== "string" || !FULL_SHA_PATTERN.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;
1137
+ const parsedStage = parseLocalPreviewStage(value.stage, {
1138
+ headSha: value.headSha,
1139
+ pr: value.pr
1140
+ });
1141
+ if (parsedStage === null) return null;
1142
+ return {
1143
+ headSha: value.headSha,
1144
+ pr: value.pr,
1145
+ stack: value.stack,
1146
+ stage: parsedStage.stage,
1147
+ url: value.url
1148
+ };
1149
+ };
1150
+ const readCleanup = (value) => {
1151
+ if (!isRecord$1(value.cleanup) || !isCleanupStatus(value.cleanup.outcome)) return null;
1152
+ const evidence = readStringArray(value.cleanup.evidence);
1153
+ if (evidence === null) return null;
1154
+ return typeof value.cleanup.runUrl === "string" && value.cleanup.runUrl.length > 0 ? {
1155
+ evidence,
1156
+ outcome: value.cleanup.outcome,
1157
+ runUrl: value.cleanup.runUrl
1158
+ } : {
1159
+ evidence,
1160
+ outcome: value.cleanup.outcome
1161
+ };
1162
+ };
1163
+ const readPassingChecks = (value) => {
1164
+ if (!isRecord$1(value.convergence) || !isRecord$1(value.smoke)) return null;
1165
+ if (value.convergence.status !== "passed" || typeof value.convergence.detail !== "string" || value.smoke.outcome !== "passed" || typeof value.smoke.detail !== "string") return null;
1166
+ return {
1167
+ convergence: {
1168
+ detail: value.convergence.detail,
1169
+ status: "passed"
1170
+ },
1171
+ smoke: {
1172
+ detail: value.smoke.detail,
1173
+ outcome: "passed"
1174
+ }
1175
+ };
1176
+ };
1177
+ const readProof = (value, headSha) => {
1178
+ if (!isRecord$1(value.proof)) return null;
1179
+ 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;
1180
+ return {
1181
+ check: value.proof.check,
1182
+ headSha: value.proof.headSha,
1183
+ mergeBaseSha: value.proof.mergeBaseSha,
1184
+ patchId: value.proof.patchId
1185
+ };
1186
+ };
1187
+ /**
1188
+ * Rebuild a registration from untrusted JSON. Extra keys (comment ids, seed
1189
+ * fields, stack unions) are dropped. Invalid identity returns `null`.
1190
+ */
1191
+ const readPreviewProofRegistration = (value) => {
1192
+ if (!isRecord$1(value) || value.source !== "local-self-certified") return null;
1193
+ const identity = readIdentity(value);
1194
+ const cleanup = readCleanup(value);
1195
+ const passing = readPassingChecks(value);
1196
+ const proof = identity === null ? null : readProof(value, identity.headSha);
1197
+ if (identity === null || cleanup === null || passing === null || proof === null) return null;
1198
+ return {
1199
+ cleanup,
1200
+ convergence: passing.convergence,
1201
+ headSha: identity.headSha,
1202
+ pr: identity.pr,
1203
+ proof,
1204
+ smoke: passing.smoke,
1205
+ source: "local-self-certified",
1206
+ stack: identity.stack,
1207
+ stage: identity.stage,
1208
+ url: identity.url
1209
+ };
1210
+ };
1211
+ const readInventoryPayload = (value) => {
1212
+ if (!isRecord$1(value) || value.kind !== INVENTORY_KIND || value.schemaVersion !== INVENTORY_SCHEMA_VERSION) return null;
1213
+ return readPreviewProofRegistration(value.registration);
1214
+ };
1215
+ const assertPersistableRegistration = (registration) => {
1216
+ const read = readPreviewProofRegistration(registration);
1217
+ if (read === null) throw new Error("Preview proof inventory cannot persist an invalid registration.");
1218
+ return read;
1219
+ };
1220
+ const registrationKey = (row) => `${row.stack}:${row.stage}`;
1221
+ const replaceRegistration = (rows, next) => [...rows.filter((row) => registrationKey(row) !== registrationKey(next)), next];
1222
+ const memoryKey = (owner, repo, pr) => `${owner}/${repo}#${pr}`;
1223
+ /** Reached by callers as `previewProofInventory.memoryStore`. */
1224
+ const memoryStore = () => {
1225
+ const byPr = /* @__PURE__ */ new Map();
1226
+ return {
1227
+ list: (input) => Promise.resolve([...byPr.get(memoryKey(input.owner, input.repo, input.pr)) ?? []]),
1228
+ put: (input) => {
1229
+ const registration = assertPersistableRegistration(input.registration);
1230
+ const key = memoryKey(input.owner, input.repo, registration.pr);
1231
+ byPr.set(key, replaceRegistration(byPr.get(key) ?? [], registration));
1232
+ return Promise.resolve();
1233
+ }
1234
+ };
1235
+ };
1236
+ /**
1237
+ * The transport gave out — a network-level rejection (EPIPE, DNS, an aborted
1238
+ * or timed-out request) or a transient HTTP status — and bounded retries did
1239
+ * not recover it. GitHub never judged the content, so this is never a
1240
+ * validation verdict and never a deployment failure. Only a bounded reason
1241
+ * string is retained: the raw transport error can hold the request and its
1242
+ * `Authorization` header, so it is deliberately discarded.
1243
+ */
1244
+ var PreviewProofTransportError = class extends Error {
1245
+ /** How many transport attempts were made before giving up. */
1246
+ attempts;
1247
+ /** The last transient HTTP status, when the server answered at all. */
1248
+ status;
1249
+ constructor(reason, attempts, status) {
1250
+ super(`Preview proof inventory transport failed after ${attempts} attempt(s): ${reason}`);
1251
+ this.name = "PreviewProofTransportError";
1252
+ this.attempts = attempts;
1253
+ if (status !== void 0) this.status = status;
1254
+ }
1255
+ };
1256
+ const githubJson = (request, url, token, init, timeoutMs) => githubJson$1({
1257
+ ...init,
1258
+ fetch: request,
1259
+ timeoutMs,
1260
+ token,
1261
+ url
1262
+ }, {
1263
+ refusal: (status, statusText) => new GitHubApiError(status, statusText),
1264
+ transport: (failure, attempts) => new PreviewProofTransportError(failure.reason, attempts, failure.status)
1265
+ });
1266
+ const githubGraphql = async (request, token, timeoutMs, query, variables) => {
1267
+ const served = await githubJson(request, "https://api.github.com/graphql", token, {
1268
+ body: JSON.stringify({
1269
+ query,
1270
+ variables
1271
+ }),
1272
+ method: "POST"
1273
+ }, timeoutMs);
1274
+ if (!isRecord$1(served)) throw new TypeError("GitHub GraphQL response was not an object");
1275
+ if (served.errors !== void 0) {
1276
+ const details = Array.isArray(served.errors) ? served.errors.flatMap((entry) => isRecord$1(entry) ? [[entry.type, entry.message].filter((part) => typeof part === "string").join(": ")] : []).filter((detail) => detail.length > 0).join("; ") : "";
1277
+ throw new Error(details.length > 0 ? `Preview proof inventory GraphQL query failed: ${details}` : "Preview proof inventory GraphQL query failed.");
1278
+ }
1279
+ return served.data;
1280
+ };
1281
+ const repoApi = (owner, repo) => `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
1282
+ const isServedCheckRun = (value) => isRecord$1(value);
1283
+ const producedByFactoryApp = (run) => String(run.app?.id ?? "") === FACTORY_PROOF_GATE_APP_ID;
1284
+ const assertFactoryAppWrite = (value) => {
1285
+ if (!isServedCheckRun(value) || !producedByFactoryApp(value)) throw new Error("Preview proof inventory write must be owned by the Factory App.");
1286
+ return value;
1287
+ };
1288
+ const registrationFromCheckRun = (run, expectedHeadSha) => {
1289
+ if (!producedByFactoryApp(run) || run.name !== "patronage-factory/preview-proof" || typeof run.head_sha !== "string" || !FULL_SHA_PATTERN.test(run.head_sha)) return null;
1290
+ const text = run.output?.text;
1291
+ if (typeof text !== "string" || text.length === 0) return null;
1292
+ let registration;
1293
+ try {
1294
+ registration = readInventoryPayload(JSON.parse(text));
1295
+ } catch {
1296
+ return null;
1297
+ }
1298
+ if (registration === null || run.head_sha !== registration.headSha || expectedHeadSha !== void 0 && run.head_sha !== expectedHeadSha) return null;
1299
+ return registration;
1300
+ };
1301
+ const checkRunOutput = (registration) => {
1302
+ const title = `Preview proof ${registration.stack}/${registration.stage}`.slice(0, 255);
1303
+ return {
1304
+ summary: `cleanup ${registration.cleanup.outcome}`,
1305
+ text: JSON.stringify({
1306
+ kind: INVENTORY_KIND,
1307
+ registration,
1308
+ schemaVersion: INVENTORY_SCHEMA_VERSION
1309
+ }),
1310
+ title
1311
+ };
1312
+ };
1313
+ const checkRunCreateBody = (registration) => ({
1314
+ conclusion: "neutral",
1315
+ head_sha: registration.headSha,
1316
+ name: PREVIEW_PROOF_INVENTORY_CHECK_NAME,
1317
+ output: checkRunOutput(registration),
1318
+ status: "completed"
1319
+ });
1320
+ const checkRunUpdateBody = (registration) => ({
1321
+ conclusion: "neutral",
1322
+ name: PREVIEW_PROOF_INVENTORY_CHECK_NAME,
1323
+ output: checkRunOutput(registration),
1324
+ status: "completed"
1325
+ });
1326
+ const collectPages = async (loadPage, pageSize, maxPages, exhaustedMessage) => {
1327
+ const collected = [];
1328
+ for (let page = 1; page <= maxPages; page += 1) {
1329
+ const rows = await loadPage(page);
1330
+ collected.push(...rows);
1331
+ if (rows.length < pageSize) return collected;
1332
+ }
1333
+ throw new Error(exhaustedMessage);
1334
+ };
1335
+ const mapPool = async (items, concurrency, mapper) => {
1336
+ if (items.length === 0) return [];
1337
+ const results = [];
1338
+ let next = 0;
1339
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, async () => {
1340
+ while (next < items.length) {
1341
+ const index = next;
1342
+ next += 1;
1343
+ const item = items[index];
1344
+ if (item === void 0) return;
1345
+ results[index] = await mapper(item);
1346
+ }
1347
+ }));
1348
+ return results;
1349
+ };
1350
+ const listCompareCommitShas = (request, token, timeoutMs, owner, repo, baseSha, headSha) => collectPages(async (page) => {
1351
+ const query = new URLSearchParams({
1352
+ page: String(page),
1353
+ per_page: String(COMMITS_PER_PAGE)
1354
+ });
1355
+ const compared = await githubJson(request, `${repoApi(owner, repo)}/compare/${encodeURIComponent(baseSha)}...${encodeURIComponent(headSha)}?${query.toString()}`, token, { method: "GET" }, timeoutMs);
1356
+ if (!isRecord$1(compared) || !Array.isArray(compared.commits)) throw new TypeError("GitHub compare response omitted commits");
1357
+ return compared.commits.flatMap((commit) => isRecord$1(commit) && typeof commit.sha === "string" ? [commit.sha] : []);
1358
+ }, COMMITS_PER_PAGE, MAX_COMMIT_PAGES, "Preview proof inventory compare listing exhausted pagination before GitHub returned a final page.");
1359
+ const listForcePushBeforeShas = async (request, token, timeoutMs, owner, repo, pr) => {
1360
+ const shas = [];
1361
+ let cursor;
1362
+ for (let page = 1; page <= MAX_FORCE_PUSH_PAGES; page += 1) {
1363
+ const data = await githubGraphql(request, token, timeoutMs, GRAPHQL_FORCE_PUSH_BEFORE, {
1364
+ cursor: cursor ?? null,
1365
+ first: FORCE_PUSH_TIMELINE_PER_PAGE,
1366
+ name: repo,
1367
+ owner,
1368
+ pr
1369
+ });
1370
+ if (!isRecord$1(data) || !isRecord$1(data.repository) || !isRecord$1(data.repository.pullRequest) || !isRecord$1(data.repository.pullRequest.timelineItems)) throw new TypeError("GitHub GraphQL force-push timeline omitted timelineItems");
1371
+ const items = data.repository.pullRequest.timelineItems;
1372
+ if (!Array.isArray(items.nodes) || !isRecord$1(items.pageInfo)) throw new TypeError("GitHub GraphQL force-push timeline omitted nodes");
1373
+ for (const node of items.nodes) {
1374
+ if (!isRecord$1(node) || !isRecord$1(node.beforeCommit) || typeof node.beforeCommit.oid !== "string" || !FULL_SHA_PATTERN.test(node.beforeCommit.oid)) continue;
1375
+ shas.push(node.beforeCommit.oid);
1376
+ }
1377
+ if (items.pageInfo.hasNextPage !== true) return shas;
1378
+ if (typeof items.pageInfo.endCursor !== "string" || items.pageInfo.endCursor.length === 0) throw new TypeError("GitHub GraphQL force-push timeline omitted endCursor");
1379
+ cursor = items.pageInfo.endCursor;
1380
+ }
1381
+ throw new Error("Preview proof inventory force-push timeline exhausted pagination before GitHub returned a final page.");
1382
+ };
1383
+ const listPullRequestCommitShas = (request, token, timeoutMs, owner, repo, pr) => collectPages(async (page) => {
1384
+ const query = new URLSearchParams({
1385
+ page: String(page),
1386
+ per_page: String(COMMITS_PER_PAGE)
1387
+ });
1388
+ const commits = await githubJson(request, `${repoApi(owner, repo)}/pulls/${pr}/commits?${query.toString()}`, token, { method: "GET" }, timeoutMs);
1389
+ if (!Array.isArray(commits)) throw new TypeError("GitHub pull request commits response was not an array");
1390
+ return commits.flatMap((commit) => isRecord$1(commit) && typeof commit.sha === "string" ? [commit.sha] : []);
1391
+ }, COMMITS_PER_PAGE, MAX_COMMIT_PAGES, "Preview proof inventory commit listing exhausted pagination before GitHub returned a final page.");
1392
+ const readPullBaseSha = (pull) => {
1393
+ if (!isRecord$1(pull.base) || typeof pull.base.sha !== "string") throw new TypeError("GitHub pull request response omitted base.sha");
1394
+ return pull.base.sha;
1395
+ };
1396
+ /**
1397
+ * Current head, replaced heads from force-push, the commits each replaced head
1398
+ * carried, and PR commits. The pull-commits endpoint silently stops at 250 and
1399
+ * never lists a rebased-away head, so those two cases use compare pagination
1400
+ * and the force-push timeline. A persist, then a fast-forward, then a rebase
1401
+ * leaves the persist SHA behind the replaced head, so each replaced head is
1402
+ * also walked back to the base (#796).
1403
+ */
1404
+ const listCommitShasForPull = async (request, token, timeoutMs, owner, repo, pr) => {
1405
+ const pull = await githubJson(request, `${repoApi(owner, repo)}/pulls/${pr}`, token, { method: "GET" }, timeoutMs);
1406
+ if (!isRecord$1(pull) || !isRecord$1(pull.head) || typeof pull.head.sha !== "string") throw new TypeError("GitHub pull request response omitted head.sha");
1407
+ const pullCommits = await listPullRequestCommitShas(request, token, timeoutMs, owner, repo, pr);
1408
+ let older = pullCommits;
1409
+ if (pullCommits.length >= GITHUB_PULL_COMMITS_CAP) older = await listCompareCommitShas(request, token, timeoutMs, owner, repo, readPullBaseSha(pull), pull.head.sha);
1410
+ const previousHeads = await listForcePushBeforeShas(request, token, timeoutMs, owner, repo, pr);
1411
+ let replaced = [];
1412
+ if (previousHeads.length > 0) {
1413
+ const baseSha = readPullBaseSha(pull);
1414
+ replaced = (await mapPool(previousHeads, 8, (previousHead) => listCompareCommitShas(request, token, timeoutMs, owner, repo, baseSha, previousHead))).flatMap((history) => [...history].toReversed());
1415
+ }
1416
+ const shas = [];
1417
+ const seen = /* @__PURE__ */ new Set();
1418
+ for (const sha of [
1419
+ pull.head.sha,
1420
+ ...previousHeads,
1421
+ ...older.toReversed(),
1422
+ ...replaced
1423
+ ]) if (!seen.has(sha)) {
1424
+ seen.add(sha);
1425
+ shas.push(sha);
1426
+ }
1427
+ return shas;
1428
+ };
1429
+ const listCheckRunsOnSha = (request, token, timeoutMs, owner, repo, sha) => collectPages(async (page) => {
1430
+ const query = new URLSearchParams({
1431
+ check_name: PREVIEW_PROOF_INVENTORY_CHECK_NAME,
1432
+ filter: "all",
1433
+ page: String(page),
1434
+ per_page: String(CHECK_RUNS_PER_PAGE)
1435
+ });
1436
+ const served = await githubJson(request, `${repoApi(owner, repo)}/commits/${encodeURIComponent(sha)}/check-runs?${query.toString()}`, token, { method: "GET" }, timeoutMs);
1437
+ if (!isRecord$1(served) || !Array.isArray(served.check_runs)) throw new TypeError("GitHub check-runs response omitted check_runs");
1438
+ return served.check_runs.filter((run) => isServedCheckRun(run));
1439
+ }, CHECK_RUNS_PER_PAGE, MAX_CHECK_RUN_PAGES, "Preview proof inventory check-run listing exhausted pagination before GitHub returned a final page.");
1440
+ const compareCheckRunsNewestFirst = (left, right) => {
1441
+ const leftMs = Date.parse(left.started_at ?? "");
1442
+ const rightMs = Date.parse(right.started_at ?? "");
1443
+ if (Number.isFinite(leftMs) && Number.isFinite(rightMs)) return rightMs - leftMs || (right.id ?? 0) - (left.id ?? 0);
1444
+ return (right.id ?? 0) - (left.id ?? 0);
1445
+ };
1446
+ const takeNewestRegistrations = (runsBySha, pr) => {
1447
+ const byKey = /* @__PURE__ */ new Map();
1448
+ for (const { runs, sha } of runsBySha) for (const run of [...runs].toSorted(compareCheckRunsNewestFirst)) {
1449
+ const registration = registrationFromCheckRun(run, sha);
1450
+ if (registration === null || registration.pr !== pr) continue;
1451
+ const key = registrationKey(registration);
1452
+ if (!byKey.has(key)) byKey.set(key, registration);
1453
+ }
1454
+ return [...byKey.values()];
1455
+ };
1456
+ /** Reached by callers as `previewProofInventory.githubStore`. */
1457
+ const githubStore = (transport) => {
1458
+ const request = transport.fetch ?? fetch;
1459
+ const timeoutMs = transport.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1460
+ const { token } = transport;
1461
+ return {
1462
+ list: async (input) => {
1463
+ return takeNewestRegistrations(await mapPool(await listCommitShasForPull(request, token, timeoutMs, input.owner, input.repo, input.pr), 8, async (sha) => ({
1464
+ runs: await listCheckRunsOnSha(request, token, timeoutMs, input.owner, input.repo, sha),
1465
+ sha
1466
+ })), input.pr);
1467
+ },
1468
+ put: async (input) => {
1469
+ const registration = assertPersistableRegistration(input.registration);
1470
+ const existing = [...await listCheckRunsOnSha(request, token, timeoutMs, input.owner, input.repo, registration.headSha)].toSorted(compareCheckRunsNewestFirst).find((run) => {
1471
+ const row = registrationFromCheckRun(run, registration.headSha);
1472
+ return row !== null && row.pr === registration.pr && row.stack === registration.stack && row.stage === registration.stage && typeof run.id === "number";
1473
+ });
1474
+ if (existing?.id === void 0) {
1475
+ assertFactoryAppWrite(await githubJson(request, `${repoApi(input.owner, input.repo)}/check-runs`, token, {
1476
+ body: JSON.stringify(checkRunCreateBody(registration)),
1477
+ method: "POST"
1478
+ }, timeoutMs));
1479
+ return;
1480
+ }
1481
+ assertFactoryAppWrite(await githubJson(request, `${repoApi(input.owner, input.repo)}/check-runs/${existing.id}`, token, {
1482
+ body: JSON.stringify(checkRunUpdateBody(registration)),
1483
+ method: "PATCH"
1484
+ }, timeoutMs));
1485
+ }
1486
+ };
1487
+ };
1488
+ const resolveStore = (access) => {
1489
+ if (access.store !== void 0) return access.store;
1490
+ if (access.token !== void 0 && access.token.length > 0) return githubStore({
1491
+ fetch: access.fetch,
1492
+ timeoutMs: access.timeoutMs,
1493
+ token: access.token
1494
+ });
1495
+ throw new Error("Preview proof inventory requires a store or a GitHub token.");
1496
+ };
1497
+ const list = async (input, access) => {
1498
+ return (await resolveStore(access).list({
1499
+ owner: input.owner,
1500
+ pr: input.pr,
1501
+ repo: input.repo
1502
+ })).filter((row) => (input.stack === void 0 || row.stack === input.stack) && (input.stage === void 0 || row.stage === input.stage));
1503
+ };
1504
+ const persist = async (input, access) => {
1505
+ const registration = assertPersistableRegistration(input.registration);
1506
+ await resolveStore(access).put({
1507
+ owner: input.owner,
1508
+ registration,
1509
+ repo: input.repo
1510
+ });
1511
+ };
1512
+ const recordCleanup = async (input, access) => {
1513
+ const parsedStage = parseLocalPreviewStage(input.stage, input.headSha === void 0 ? { pr: input.pr } : {
1514
+ headSha: input.headSha,
1515
+ pr: input.pr
1516
+ });
1517
+ if (parsedStage === null) throw new Error(`Preview proof stage must be a disposable local-pr stage owned by PR #${input.pr} at this head.`);
1518
+ const store = resolveStore(access);
1519
+ const listed = await store.list({
1520
+ owner: input.owner,
1521
+ pr: input.pr,
1522
+ repo: input.repo
1523
+ });
1524
+ const existing = listed.find((row) => row.pr === input.pr && row.stack === input.stack && row.stage === parsedStage.stage);
1525
+ if (input.headSha !== void 0 && existing !== void 0 && existing.headSha !== input.headSha) throw new Error("Preview proof identity does not match the cleanup target.");
1526
+ const next = previewProofLifecycle.transition({ registrations: listed }, {
1527
+ evidence: input.evidence,
1528
+ outcome: input.outcome,
1529
+ pr: input.pr,
1530
+ ...input.runUrl === void 0 ? {} : { runUrl: input.runUrl },
1531
+ stack: input.stack,
1532
+ stage: parsedStage.stage,
1533
+ type: "cleanup"
1534
+ });
1535
+ const [updated] = previewProofLifecycle.resolve(next, {
1536
+ pr: input.pr,
1537
+ stack: input.stack,
1538
+ stage: parsedStage.stage
1539
+ });
1540
+ if (updated === void 0) throw new Error(`Preview proof cleanup requires a registration for ${input.stack}/${parsedStage.stage}.`);
1541
+ await store.put({
1542
+ owner: input.owner,
1543
+ registration: updated,
1544
+ repo: input.repo
1545
+ });
1546
+ return updated;
1547
+ };
1548
+ const previewProofInventory = {
1549
+ githubStore,
1550
+ list,
1551
+ listPermissions: PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS,
1552
+ memoryStore,
1553
+ persist,
1554
+ recordCleanup
1555
+ };
1556
+ //#endregion
1557
+ //#region src/pinned-action.ts
1558
+ const PINNED_ACTION_PATTERN = /^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/u;
1559
+ const ACTION_TAG_PATTERN = /^v\d+(?:\.\d+){0,2}$/u;
1560
+ const actionRepository = (action) => action.uses.slice(0, action.uses.indexOf("@"));
1561
+ /** Shared validator for every action pin emitted by factory-ci helpers. */
1562
+ const assertPinnedAction = (name, action, expectedRepository) => {
1563
+ if (!PINNED_ACTION_PATTERN.test(action.uses)) throw new Error(`${name} must use owner/repository@<40-character commit SHA>, got "${action.uses}".`);
1564
+ if (expectedRepository && actionRepository(action) !== expectedRepository) throw new Error(`${name} must pin ${expectedRepository}, got ${actionRepository(action)}.`);
1565
+ if (!ACTION_TAG_PATTERN.test(action.tag)) throw new Error(`${name} tag must be vN, vN.N, or vN.N.N, got "${action.tag}".`);
1566
+ };
1567
+ //#endregion
1568
+ //#region src/factory-workflow.ts
1569
+ const RESERVED_ACTION_NAMES = new Set([
1570
+ "checkout",
1571
+ "setupNode",
1572
+ "setupPnpm"
1573
+ ]);
1574
+ /**
1575
+ * Stable identifiers for the setup steps a generated workflow always emits,
1576
+ * in emission order. A consumer selects steps by role instead of locating
1577
+ * them by display name or by array position/length, so renaming a step or
1578
+ * adding a new supported role never breaks role-based composition (#1076).
1579
+ */
1580
+ const SETUP_STEP_ROLES = Object.freeze([
1581
+ "checkout",
1582
+ "setupPnpm",
1583
+ "setupNode",
1584
+ "install"
1585
+ ]);
1586
+ const assertSingleLine$2 = (name, value) => {
1587
+ if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
1588
+ };
1589
+ const usesStep = (fallbackName, action) => ({
1590
+ name: fallbackName,
1591
+ uses: action.uses
1592
+ });
1593
+ const assertActionFamily = (family) => {
1594
+ assertSingleLine$2("actionFamily.id", family.id);
1595
+ assertPinnedAction("checkout", family.checkout, "actions/checkout");
1596
+ assertPinnedAction("setupNode", family.setupNode, "actions/setup-node");
1597
+ assertPinnedAction("setupPnpm", family.setupPnpm, "pnpm/action-setup");
1598
+ };
1599
+ const assertAdditionalActions = (actions) => {
1600
+ for (const [name, action] of Object.entries(actions)) {
1601
+ if (RESERVED_ACTION_NAMES.has(name)) throw new Error(`${name} is reserved by the Node/pnpm action family and cannot be replaced by additionalActions.`);
1602
+ assertPinnedAction(name, action);
1603
+ }
1604
+ };
1605
+ const checkoutInputs = (checkout) => {
1606
+ if (checkout === void 0) return;
1607
+ const inputs = {};
1608
+ if (checkout.fetchDepth !== void 0) {
1609
+ if (!Number.isSafeInteger(checkout.fetchDepth) || checkout.fetchDepth < 0) throw new Error("checkout.fetchDepth must be a non-negative integer.");
1610
+ inputs["fetch-depth"] = String(checkout.fetchDepth);
1611
+ }
1612
+ if (checkout.ref) inputs.ref = checkout.ref;
1613
+ return Object.keys(inputs).length > 0 ? inputs : void 0;
1614
+ };
1615
+ const setupStepsByRole = (family, setup = {}) => {
1616
+ const installRun = setup.install?.run ?? "pnpm install --frozen-lockfile";
1617
+ 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.");
1618
+ const { checkout, setupNode } = setup;
1619
+ const checkoutWith = checkoutInputs(checkout);
1620
+ return Object.freeze({
1621
+ checkout: {
1622
+ name: checkout?.name ?? "Checkout",
1623
+ uses: family.checkout.uses,
1624
+ ...checkoutWith ? { with: checkoutWith } : {}
1625
+ },
1626
+ install: {
1627
+ name: setup.install?.name ?? "Install workspace",
1628
+ run: installRun
1629
+ },
1630
+ setupNode: {
1631
+ name: "Setup Node",
1632
+ uses: family.setupNode.uses,
1633
+ with: {
1634
+ cache: "pnpm",
1635
+ ...setupNode?.cacheDependencyPath ? { "cache-dependency-path": setupNode.cacheDependencyPath } : {},
1636
+ "node-version-file": setupNode?.nodeVersionFile ?? ".nvmrc"
1637
+ }
1638
+ },
1639
+ setupPnpm: usesStep("Setup pnpm", family.setupPnpm)
1640
+ });
1641
+ };
1642
+ /**
1643
+ * Select setup steps by stable role, in the order the roles are given.
1644
+ *
1645
+ * This is the supported alternative to destructuring `setupSteps` by array
1646
+ * position or asserting its length: a caller names exactly the roles it
1647
+ * needs (for example, every role but `checkout`, to follow its own
1648
+ * head-pinned checkout with the shared pnpm/Node/install sequence), and that
1649
+ * selection survives a renamed step or an added role.
1650
+ */
1651
+ const setupStepsForRoles = (artifact, roles) => Object.freeze(roles.map((role) => artifact.setupStepsByRole[role]));
1652
+ /**
1653
+ * Own one generated workflow source's action pins, setup block, provenance
1654
+ * banner, and gagen pinning policy as a single artifact.
1655
+ *
1656
+ * The caller still owns workflow topology, jobs, runners, permissions, and
1657
+ * every deployment policy decision.
1658
+ */
1659
+ const factoryWorkflow = (options) => {
1660
+ assertSingleLine$2("generated.source", options.generated.source);
1661
+ assertSingleLine$2("generated.regenerate", options.generated.regenerate);
1662
+ assertActionFamily(options.actionFamily);
1663
+ assertAdditionalActions(options.additionalActions ?? {});
1664
+ const actions = Object.freeze({
1665
+ checkout: options.actionFamily.checkout,
1666
+ setupNode: options.actionFamily.setupNode,
1667
+ setupPnpm: options.actionFamily.setupPnpm,
1668
+ ...options.additionalActions ?? {}
1669
+ });
1670
+ const stepsByRole = setupStepsByRole(options.actionFamily, options.setup);
1671
+ return Object.freeze({
1672
+ actionFamilyId: options.actionFamily.id,
1673
+ actions,
1674
+ setupSteps: Object.freeze(SETUP_STEP_ROLES.map((role) => stepsByRole[role])),
1675
+ setupStepsByRole: stepsByRole,
1676
+ writeOptions: Object.freeze({
1677
+ header: [`# GENERATED BY ${options.generated.source} -- DO NOT EDIT.`, `# Regenerate: ${options.generated.regenerate}`].join("\n"),
1678
+ pinDeps: false
1679
+ })
1680
+ });
1681
+ };
1682
+ //#endregion
1683
+ //#region src/cursor-oidc.ts
1684
+ /**
1685
+ * Pinned Cursor OIDC trust predicates for the Factory App broker (#949).
1686
+ *
1687
+ * The broker verifies a Cursor-managed Cloud Agent JWT and mints a
1688
+ * repo-scoped Factory App installation token. Audience, issuer, and JWKS are
1689
+ * not consumer settings: a knob that pointed them elsewhere would be the
1690
+ * whole mechanism undone, the same reason {@link FACTORY_PROOF_GATE_APP_ID}
1691
+ * is pinned.
1692
+ */
1693
+ /** Cursor's OIDC issuer. Tokens minted on the agent VM carry this `iss`. */
1694
+ const FACTORY_CURSOR_OIDC_ISSUER = "https://api.cursor.com";
1695
+ /** JWKS the broker uses to verify RS256 signatures. */
1696
+ const FACTORY_CURSOR_OIDC_JWKS_URL = "https://api.cursor.com/keys";
1697
+ /**
1698
+ * Audience a Cursor-managed VM must mint with. The CLI and the broker share
1699
+ * this string; Cursor does not allowlist audiences.
1700
+ */
1701
+ const FACTORY_CURSOR_OIDC_AUDIENCE = "Factory";
1702
+ /**
1703
+ * Runtime claim a Cursor-managed Cloud Agent VM always presents. Self-hosted
1704
+ * workers are not this broker's callers.
1705
+ */
1706
+ const FACTORY_CURSOR_OIDC_MANAGED_RUNTIME = "managed";
1707
+ /** HQ route that exchanges a verified Cursor OIDC JWT for an App token. */
1708
+ const FACTORY_APP_BROKER_PATH = "/api/factory-app/installation-token";
1709
+ /** Production broker origin. The CLI pins this; it is not profile-declared. */
1710
+ const FACTORY_APP_BROKER_ORIGIN = "https://hq.patronage.com";
1711
+ //#endregion
1712
+ //#region src/proof-reuse-presentation.ts
1713
+ /** Generic timing and presentation steps around the proof-reuse gate (#652). */
1714
+ const githubExpression = (expression) => `\${{ ${expression} }}`;
1715
+ const shellExpansion = (expression) => `\${${expression}}`;
1716
+ const safeLabel = (surface) => {
1717
+ const cleaned = (typeof surface === "string" ? surface : "").replaceAll(/[^\w -]/gu, "").trim().slice(0, 60);
1718
+ return cleaned.length > 0 ? cleaned : "verification";
1719
+ };
1720
+ const FACTORY_PROOF_TIMING_STEP_ID = "ci-timing";
1721
+ const FACTORY_PROOF_TIMING_START_STEP_NAME = "Start CI timing";
1722
+ const FACTORY_PROOF_TIMING_SUMMARY_STEP_NAME = "Record proof-reuse timing";
1723
+ const factoryProofTimingStartStep = () => Object.freeze({
1724
+ continueOnError: true,
1725
+ id: FACTORY_PROOF_TIMING_STEP_ID,
1726
+ name: FACTORY_PROOF_TIMING_START_STEP_NAME,
1727
+ run: String.raw`started_ms="$(node -e 'process.stdout.write(String(Date.now()))')"
1728
+ printf 'started_ms=%s\n' "$started_ms" >> "$GITHUB_OUTPUT"`
1729
+ });
1730
+ const factoryProofReuseSummaryScript = ({ surface }) => {
1731
+ const label = safeLabel(surface);
1732
+ return String.raw`now_ms="$(node -e 'process.stdout.write(String(Date.now()))')"
1733
+ ci_started_ms="${shellExpansion("CI_STARTED_MS:-")}"
1734
+
1735
+ SUMMARY="${shellExpansion("GITHUB_STEP_SUMMARY:-/dev/null")}"
1736
+ say() { printf '%s\n' "$1" >> "$SUMMARY"; }
1737
+
1738
+ say '## ${label} timing'
1739
+ say ''
1740
+
1741
+ if [ "${shellExpansion("GITHUB_EVENT_NAME:-")}" = 'push' ] && [ -z "${shellExpansion("PROOF_REASON:-")}" ]; then
1742
+ # A push run with no recorded reason is one where the gate step's condition
1743
+ # kept it off entirely, so the full suite ran with no reuse decision. The
1744
+ # gate runs on pull requests only (#863), so that is every push.
1745
+ say '- Path: full execution, no proof consulted'
1746
+ say '- Proof-reuse gate: did not run on this ref; the full suite ran.'
1747
+ say "- Verified head: \`${shellExpansion("GITHUB_SHA:-unknown")}\`"
1748
+ echo "::notice title=Factory proof reuse::The proof-reuse gate did not run on this ref; the full ${label} suite executed."
1749
+ elif [ "${shellExpansion("PROOF_REUSED:-")}" = 'true' ]; then
1750
+ say '- Path: trusted local proof reused'
1751
+ if [ -n "${shellExpansion("PROOF_SOURCE_URL:-")}" ]; then
1752
+ say "- Reused proof: [exact source check](${shellExpansion("PROOF_SOURCE_URL")})"
1753
+ fi
1754
+ say "- Bound head: \`${shellExpansion("PROOF_HEAD_SHA:-unknown")}\`"
1755
+ say "- Factory verification mode: ${shellExpansion("PROOF_MODE:-unavailable")} (diagnostic only)"
1756
+ echo "::notice title=Factory proof reuse::Reused trusted local proof for ${label} at ${shellExpansion("PROOF_HEAD_SHA:-unknown")}."
1757
+ else
1758
+ say "- Path: full GitHub CI fallback (${shellExpansion("PROOF_REASON:-error")})"
1759
+ say "- Bound head: \`${shellExpansion("PROOF_HEAD_SHA:-unknown")}\`"
1760
+ say "- Factory verification mode: ${shellExpansion("PROOF_MODE:-unavailable")} (diagnostic only)"
1761
+ echo "::notice title=Factory proof reuse::No reusable proof for ${label}; the full hosted suite executed (${shellExpansion("PROOF_REASON:-error")})."
1762
+ fi
1763
+
1764
+ if [[ "$ci_started_ms" =~ ^[0-9]+$ ]]; then
1765
+ say "- GitHub workflow execution after the proof gate: $((now_ms - ci_started_ms)) ms"
1766
+ else
1767
+ say '- GitHub workflow execution after the proof gate: unavailable'
1768
+ fi
1769
+ say ''`;
1770
+ };
1771
+ const factoryProofReuseSummaryStep = (options) => Object.freeze({
1772
+ continueOnError: true,
1773
+ env: Object.freeze({
1774
+ CI_STARTED_MS: githubExpression(`steps.${FACTORY_PROOF_TIMING_STEP_ID}.outputs.started_ms`),
1775
+ PROOF_HEAD_SHA: githubExpression("github.event.pull_request.head.sha || github.sha"),
1776
+ PROOF_MODE: githubExpression(`steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_MODE_OUTPUT}`),
1777
+ PROOF_REASON: githubExpression(`steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_REASON_OUTPUT}`),
1778
+ PROOF_REUSED: githubExpression(`steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_OUTPUT}`),
1779
+ PROOF_SOURCE_URL: githubExpression(`steps.${FACTORY_PROOF_GATE_STEP_ID}.outputs.${FACTORY_PROOF_GATE_SOURCE_URL_OUTPUT}`)
1780
+ }),
1781
+ if: "always()",
1782
+ name: FACTORY_PROOF_TIMING_SUMMARY_STEP_NAME,
1783
+ run: factoryProofReuseSummaryScript(options)
1784
+ });
1785
+ //#endregion
1786
+ //#region src/impact-demand-condition.ts
1787
+ const impactDemandConditions = (options) => {
1788
+ const targetOutput = (targetName) => {
1789
+ const output = options.targetOutputs[targetName];
1790
+ if (output === void 0) throw new Error(`Unknown ${options.label} impact target "${targetName}".`);
1791
+ return output;
1792
+ };
1793
+ const condition = (source, outcomeKey, output) => `${source}.${outcomeKey} != 'success' || ${source}.outputs.${options.decisionOutput} != 'usable' || ${source}.outputs.${output} != 'withdrawn'`;
1794
+ return Object.freeze({
1795
+ demandedIf: (targetName, decisionJob) => {
1796
+ const output = targetOutput(targetName);
1797
+ if (decisionJob.trim().length === 0) throw new Error(`A cross-job ${options.label} impact condition requires the decision job id.`);
1798
+ return `always() && (${condition(`needs.${decisionJob}`, "result", output)})`;
1799
+ },
1800
+ demandedIfAtStep: (targetName) => condition(`steps.${options.stepId}`, "outcome", targetOutput(targetName))
1801
+ });
1802
+ };
1803
+ //#endregion
1804
+ //#region src/runnable-cli.ts
1805
+ /**
1806
+ * `@patronage/software-factory` publishes two dist entries. `dist/index.js` is
1807
+ * the package export: consumers import it, so it runs no command. `dist/cli.js`
1808
+ * is the bin, and it is the only entry that runs one (software-factory#386).
1809
+ *
1810
+ * A workflow step that invokes `dist/index.js` therefore loads a library and
1811
+ * exits 0 — a green step that did nothing. This guard makes a generator refuse
1812
+ * that `cli` at generation time, where the failure is loud, instead of letting
1813
+ * it reach CI where the failure is silent. Invoke the bin by name (`psf`,
1814
+ * `pnpm exec psf`, `pnpm dlx psf`) or by the `dist/cli.js` path.
1815
+ */
1816
+ const INERT_ENTRY_PATTERN = /(?:^|[/\\])dist[/\\]index\.js(?:["'\s]|$)/u;
1817
+ /** Shared validator for every `cli` string a factory-ci generator emits. */
1818
+ const assertRunnableCli = (name, cli) => {
1819
+ 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}".`);
1820
+ };
1821
+ //#endregion
1822
+ //#region src/production-impact-workflow.ts
1823
+ const FACTORY_PRODUCTION_IMPACT_STEP_ID = "production_impact";
1824
+ const FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT = "decision";
1825
+ const FACTORY_PRODUCTION_IMPACT_BASIS_OUTPUT = "basis";
1826
+ const FACTORY_PRODUCTION_IMPACT_UNSUBSCRIBED_OUTPUT = "unsubscribed_paths";
1827
+ const OUTPUT_NAME_PATTERN = /[^a-z0-9_]+/gu;
1828
+ const shellQuote$1 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
1829
+ /** Stable GitHub-output key for one declared target. */
1830
+ const productionImpactTargetOutput = (targetName) => {
1831
+ const normalized = targetName.toLowerCase().replaceAll(OUTPUT_NAME_PATTERN, "_").replaceAll(/^_+|_+$/gu, "");
1832
+ if (normalized.length === 0) throw new Error(`Impact target name "${targetName}" has no output-safe characters.`);
1833
+ return `target_${normalized}`;
1834
+ };
1835
+ /**
1836
+ * Generate the small factory-owned decision seam for a consumer production
1837
+ * workflow. Consumers retain jobs, deploy commands, credentials, topology,
1838
+ * health checks, and convergence checks; this artifact supplies the decision
1839
+ * step, per-target withdrawal conditions, and the receipt steps that record
1840
+ * what each deploy job did.
1841
+ *
1842
+ * The decision step resolves each target's demand from its last trusted
1843
+ * successful deployment receipt, never from the push's before commit. The
1844
+ * decision checkout needs full history (`fetchDepth: 0`) so the baseline
1845
+ * commit is reachable; a shallow checkout keeps every target demanded.
1846
+ */
1847
+ const factoryProductionImpactWorkflow = (options) => {
1848
+ const targetOutputs = Object.fromEntries(options.targets.map((target) => [target, productionImpactTargetOutput(target)]));
1849
+ if (new Set(Object.values(targetOutputs)).size !== options.targets.length) throw new Error("Impact target names must map to distinct GitHub output keys.");
1850
+ const candidate = options.candidate ?? `\${{ github.sha }}`;
1851
+ const cli = options.cli ?? "pnpm exec psf";
1852
+ assertRunnableCli("cli", cli);
1853
+ const profile = options.profilePath ? ` --profile ${shellQuote$1(options.profilePath)}` : "";
1854
+ const stage = options.stage ? ` --stage ${shellQuote$1(options.stage)}` : "";
1855
+ const env = {
1856
+ FACTORY_CANDIDATE_SHA: candidate,
1857
+ GH_TOKEN: `\${{ github.token }}`
1858
+ };
1859
+ const decisionStep = {
1860
+ continueOnError: true,
1861
+ env,
1862
+ id: FACTORY_PRODUCTION_IMPACT_STEP_ID,
1863
+ name: "Resolve production deployment demand",
1864
+ run: `${cli} production:impact --candidate "$FACTORY_CANDIDATE_SHA" --github-output "$GITHUB_OUTPUT" --github-summary "$GITHUB_STEP_SUMMARY"${profile}${stage}`
1865
+ };
1866
+ const conditions = impactDemandConditions({
1867
+ decisionOutput: FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT,
1868
+ label: "production",
1869
+ stepId: FACTORY_PRODUCTION_IMPACT_STEP_ID,
1870
+ targetOutputs
1871
+ });
1872
+ const receiptSteps = (targetName) => {
1873
+ const output = targetOutputs[targetName];
1874
+ if (output === void 0) throw new Error(`Unknown production impact target "${targetName}".`);
1875
+ const successStepId = `receipt_${output}`;
1876
+ const deploymentId = `\${{ steps.${successStepId}.outputs.deployment_id }}`;
1877
+ return Object.freeze([
1878
+ Object.freeze({
1879
+ env,
1880
+ id: successStepId,
1881
+ if: "success()",
1882
+ name: `Publish success deployment receipt for ${targetName}`,
1883
+ run: `${cli} production:impact --publish-receipt success --target ${shellQuote$1(targetName)} --candidate "$FACTORY_CANDIDATE_SHA" --github-output "$GITHUB_OUTPUT" --github-summary "$GITHUB_STEP_SUMMARY"${stage}`
1884
+ }),
1885
+ Object.freeze({
1886
+ env: { FACTORY_DEPLOYMENT_ID: deploymentId },
1887
+ if: "success()",
1888
+ name: `Bind deployment receipt ${deploymentId}`,
1889
+ run: "test -n \"$FACTORY_DEPLOYMENT_ID\""
1890
+ }),
1891
+ Object.freeze({
1892
+ env,
1893
+ if: "failure()",
1894
+ name: `Publish failure deployment receipt for ${targetName}`,
1895
+ run: `${cli} production:impact --publish-receipt failure --target ${shellQuote$1(targetName)} --candidate "$FACTORY_CANDIDATE_SHA" --github-summary "$GITHUB_STEP_SUMMARY"${stage}`
1896
+ })
1897
+ ]);
1898
+ };
1899
+ return Object.freeze({
1900
+ decisionJobOutputs: Object.freeze({
1901
+ basis: `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${FACTORY_PRODUCTION_IMPACT_BASIS_OUTPUT} }}`,
1902
+ decision: `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT} }}`,
1903
+ unsubscribed_paths: `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${FACTORY_PRODUCTION_IMPACT_UNSUBSCRIBED_OUTPUT} }}`,
1904
+ ...Object.fromEntries(Object.values(targetOutputs).map((output) => [output, `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${output} }}`]))
1905
+ }),
1906
+ decisionStep: Object.freeze(decisionStep),
1907
+ demandedIf: conditions.demandedIf,
1908
+ demandedIfAtStep: conditions.demandedIfAtStep,
1909
+ permissions: Object.freeze({
1910
+ actions: "read",
1911
+ contents: "read",
1912
+ deployments: "write"
1913
+ }),
1914
+ receiptSteps,
1915
+ targetOutputs: Object.freeze(targetOutputs)
1916
+ });
1917
+ };
1918
+ //#endregion
1919
+ //#region src/candidate-impact-workflow.ts
1920
+ const FACTORY_CANDIDATE_IMPACT_STEP_ID = "candidate_impact";
1921
+ const FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT = "decision";
1922
+ const FACTORY_CANDIDATE_IMPACT_BASIS_OUTPUT = "basis";
1923
+ const FACTORY_CANDIDATE_IMPACT_INERT_OUTPUT = "inert_paths";
1924
+ const FACTORY_CANDIDATE_IMPACT_UNSUBSCRIBED_OUTPUT = "unsubscribed_paths";
1925
+ const shellQuote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
1926
+ /**
1927
+ * Generate the factory-owned candidate routing seam for a consumer
1928
+ * pull-request workflow (#741). The decision step calls
1929
+ * `psf candidate:impact` with the pull request's exact base/head commits, so
1930
+ * the canonical profile impact declarations and dependency graph route the
1931
+ * run — never a second path matcher. Consumers retain jobs, surface names,
1932
+ * runners, commands, and credentials; this artifact supplies only the
1933
+ * decision step and per-target withdrawal conditions. Target output keys are
1934
+ * the same stable contract the production decision seam writes.
1935
+ *
1936
+ * The decision checkout must have the exact head commit checked out and the
1937
+ * base commit reachable (`fetchDepth: 0`, `ref` = the head SHA); anything
1938
+ * else refuses withdrawal and keeps every target demanded.
1939
+ */
1940
+ const factoryCandidateImpactWorkflow = (options) => {
1941
+ const targetOutputs = Object.fromEntries(options.targets.map((target) => [target, productionImpactTargetOutput(target)]));
1942
+ if (new Set(Object.values(targetOutputs)).size !== options.targets.length) throw new Error("Impact target names must map to distinct GitHub output keys.");
1943
+ const base = options.base ?? `\${{ github.event.pull_request.base.sha }}`;
1944
+ const head = options.head ?? `\${{ github.event.pull_request.head.sha }}`;
1945
+ const cli = options.cli ?? "pnpm exec psf";
1946
+ assertRunnableCli("cli", cli);
1947
+ const profile = options.profilePath ? ` --profile ${shellQuote(options.profilePath)}` : "";
1948
+ const decisionStep = {
1949
+ continueOnError: true,
1950
+ env: {
1951
+ FACTORY_BASE_SHA: base,
1952
+ FACTORY_HEAD_SHA: head
1953
+ },
1954
+ id: FACTORY_CANDIDATE_IMPACT_STEP_ID,
1955
+ name: "Classify candidate impact",
1956
+ run: `${cli} candidate:impact --base "$FACTORY_BASE_SHA" --head "$FACTORY_HEAD_SHA" --github-output "$GITHUB_OUTPUT" --github-summary "$GITHUB_STEP_SUMMARY"${profile}`
1957
+ };
1958
+ const conditions = impactDemandConditions({
1959
+ decisionOutput: FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT,
1960
+ label: "candidate",
1961
+ stepId: FACTORY_CANDIDATE_IMPACT_STEP_ID,
1962
+ targetOutputs
1963
+ });
1964
+ return Object.freeze({
1965
+ decisionJobOutputs: Object.freeze({
1966
+ basis: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_BASIS_OUTPUT} }}`,
1967
+ decision: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_DECISION_OUTPUT} }}`,
1968
+ inert_paths: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_INERT_OUTPUT} }}`,
1969
+ unsubscribed_paths: `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${FACTORY_CANDIDATE_IMPACT_UNSUBSCRIBED_OUTPUT} }}`,
1970
+ ...Object.fromEntries(Object.values(targetOutputs).map((output) => [output, `\${{ steps.${FACTORY_CANDIDATE_IMPACT_STEP_ID}.outputs.${output} }}`]))
1971
+ }),
1972
+ decisionStep: Object.freeze(decisionStep),
1973
+ demandedIf: conditions.demandedIf,
1974
+ demandedIfAtStep: conditions.demandedIfAtStep,
1975
+ targetOutputs: Object.freeze(targetOutputs)
1976
+ });
1977
+ };
1978
+ //#endregion
1979
+ //#region src/lifecycle-contract-lane.ts
1980
+ const FACTORY_LIFECYCLE_CONTRACT_JOB_ID = "factory-contracts";
1981
+ const FACTORY_LIFECYCLE_CONTRACT_JOB_NAME = "Factory / Alchemy Contracts";
1982
+ const JOB_ID_PATTERN$1 = /^[A-Za-z_][A-Za-z0-9_-]*$/u;
1983
+ const PACKAGE_NAME = "(?:@[A-Za-z0-9._~-]+\\/)?[A-Za-z0-9._~-]+";
1984
+ const COLON_SCRIPT = "[A-Za-z][\\w.-]*:[\\w:.-]+";
1985
+ const RUN_SCRIPT = "[A-Za-z][\\w:.-]*";
1986
+ const PNPM = `pnpm(?: --filter(?:=| )${PACKAGE_NAME})?`;
1987
+ const OTHER_MANAGER = "(?:bun|npm|yarn)";
1988
+ const ALLOWED_PACKAGE_SCRIPT = new RegExp(`^(?:${PNPM} run ${RUN_SCRIPT}|${PNPM} ${COLON_SCRIPT}|${OTHER_MANAGER} run ${RUN_SCRIPT}|${OTHER_MANAGER} ${COLON_SCRIPT})$`, "u");
1989
+ const CREDENTIAL_ENV = /ALCHEMY_PASSWORD|CLOUDFLARE_|CF_API_|secrets\./u;
1990
+ const SHELL_OPERATOR = /&&|\|\||;|\||`|\$\(|\$\{|\$[A-Za-z_*@#?!$0-9-]/u;
1991
+ const EVIDENCE_SUMMARY = `{
1992
+ echo "## Factory contract evidence"
1993
+ echo
1994
+ echo "- Status: $JOB_STATUS"
1995
+ echo "- Covers the consumer's declared Alchemy/product-stack lifecycle contracts."
1996
+ echo "- This static lane is non-credentialed and does not prove live deploy, D1, smoke, convergence, or cleanup."
1997
+ } >> "$GITHUB_STEP_SUMMARY"`;
1998
+ const assertSingleLine$1 = (name, value) => {
1999
+ if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
2000
+ };
2001
+ const assertPackageScriptCommand = (command) => {
2002
+ assertSingleLine$1("lifecycleContract.command", command);
2003
+ if (CREDENTIAL_ENV.test(command)) throw new Error("lifecycleContract.command must not interpolate GitHub secrets or credential environment names.");
2004
+ if (SHELL_OPERATOR.test(command)) throw new Error("lifecycleContract.command must not include a shell operator or environment expansion.");
2005
+ 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.");
2006
+ };
2007
+ /**
2008
+ * Generate the factory-owned non-credentialed lifecycle-contract lane
2009
+ * (#765). Consumers declare the package-script command in
2010
+ * `software-factory.profile.json`; this helper never loads that profile.
2011
+ * Callers pass the parsed declaration (or omit it) and include or skip the
2012
+ * returned job. Setup, runners, topology, and credentials stay with the
2013
+ * caller — and this lane must never receive credentials.
2014
+ *
2015
+ * The generated steps run only the declared package script and write an
2016
+ * always() evidence summary of what the lane proves and does not prove.
2017
+ * The command must be a package-script invocation: `run <script>`, or a
2018
+ * shorthand whose script name contains `:` (`pnpm test:factory`). Optional
2019
+ * pnpm `--filter <pkg>` may precede either form. Shell operators, credential
2020
+ * env, extra flags, and direct Vitest are refused.
2021
+ */
2022
+ const factoryLifecycleContractLane = (declaration) => {
2023
+ if (declaration === void 0) return;
2024
+ assertPackageScriptCommand(declaration.command);
2025
+ const jobId = declaration.jobId ?? "factory-contracts";
2026
+ const jobName = declaration.jobName ?? "Factory / Alchemy Contracts";
2027
+ if (!JOB_ID_PATTERN$1.test(jobId)) throw new Error("lifecycleContract.jobId must be a GitHub Actions job id.");
2028
+ assertSingleLine$1("lifecycleContract.jobName", jobName);
2029
+ const runStep = Object.freeze({
2030
+ name: "Run lifecycle contracts",
2031
+ run: declaration.command
2032
+ });
2033
+ const summaryStep = Object.freeze({
2034
+ env: Object.freeze({ JOB_STATUS: `\${{ job.status }}` }),
2035
+ if: "always()",
2036
+ name: "Summarize factory-contract evidence",
2037
+ run: EVIDENCE_SUMMARY
2038
+ });
2039
+ return Object.freeze({
2040
+ jobId,
2041
+ jobName,
2042
+ steps: Object.freeze([runStep, summaryStep])
2043
+ });
2044
+ };
2045
+ //#endregion
2046
+ //#region src/merge-freeze-job.ts
2047
+ /**
2048
+ * The merge-freeze writer job (#356, ADR 0016; #429 for the
2049
+ * merge-target namespace; #872 for this package).
2050
+ *
2051
+ * A consumer's generated merge-target-push Verify workflow is the ONLY
2052
+ * producer of `patronage-factory/merge-freeze` generations: a red
2053
+ * push-triggered Verify completes a generation active, a green one completes
2054
+ * it inactive, and no command, scheduled job, or second workflow writes this
2055
+ * check run. The operator override (`demand:waive --demand merge-freeze`)
2056
+ * waives the demand for one candidate during a fix-forward; it never writes
2057
+ * here.
2058
+ *
2059
+ * The write mirrors what the factory package's merge-freeze reader parses:
2060
+ * create the run `in_progress` with no `started_at` (GitHub stamps the
2061
+ * generation clock — the ordering rule itself is owned by the reader), then
2062
+ * PATCH it completed with the reader-shaped state payload in `output.text`.
2063
+ * The consumer's workflow test executes this exact script against a stubbed
2064
+ * `gh` and parses the emitted payload with `validateMergeFreezeState`, so
2065
+ * writer and reader cannot drift silently.
2066
+ *
2067
+ * Those two API calls are what the reader's two settling phases observe
2068
+ * (#890). Before the POST the merge target carries no generation at all, which
2069
+ * a reader reports as `awaiting-generation` while the pushed hosted verify run
2070
+ * is still pending. Between the POST and the PATCH the generation exists with
2071
+ * no `output.text`, which a reader reports as `running-generation`. Only the
2072
+ * PATCH writes a verdict, so neither phase is one.
2073
+ *
2074
+ * Failure posture is deliberately fail-closed and the opposite of the
2075
+ * proof-reuse gate's fail-open shell: this step runs under the runner's
2076
+ * default `bash -e {0}`, so any API refusal aborts the step, the generation
2077
+ * stays absent or `in_progress`, and every `pr:ready` arming-time read of
2078
+ * that tip (#477) refuses until a later push writes a green generation.
2079
+ *
2080
+ * **Ownership line.** This package owns the check name, the App identity, the
2081
+ * `create-github-app-token` inputs, the result fold, the merge-target `if`,
2082
+ * and the job's `permissions`. The caller owns the runner, the `needs` list
2083
+ * of every authoritative verification leaf, the timeout, and any extra env.
2084
+ */
2085
+ /** The one check-run name every merge-freeze reader pins. */
2086
+ const FACTORY_MERGE_FREEZE_CHECK_NAME = "patronage-factory/merge-freeze";
2087
+ const FACTORY_MERGE_FREEZE_JOB_ID = "freeze";
2088
+ const FACTORY_MERGE_FREEZE_JOB_NAME = "Report the merge freeze";
2089
+ /** Step id the token step exposes its installation token under. */
2090
+ const FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID = "factory-app-token";
2091
+ /**
2092
+ * The GitHub Actions expression that folds the needed jobs' results into the
2093
+ * one word the script branches on. It mirrors the `verify` summary job's
2094
+ * failure condition exactly: any failed or cancelled needed job is a red
2095
+ * merge target.
2096
+ */
2097
+ const FACTORY_MERGE_FREEZE_VERIFY_RESULT_EXPRESSION = `\${{ (contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) && 'failure' || 'success' }}`;
2098
+ /**
2099
+ * The literal factory merge-target namespace, as a `github.ref` predicate
2100
+ * (#429).
2101
+ *
2102
+ * `main` plus the repository-owned `epic/**` integration branches, and
2103
+ * nothing else. Deliberately literal rather than profile-declared: one
2104
+ * implementation per contract, no configuration machinery for a two-element
2105
+ * namespace whose second element is a namespace prefix the repository itself
2106
+ * owns. `epic/` needs the trailing slash — `startsWith` would otherwise admit
2107
+ * `epicness/…`, which is not a merge target.
2108
+ *
2109
+ * A caller's `push` trigger branch list names the same namespace. That list
2110
+ * decides which events produce a run at all; this predicate decides which of
2111
+ * those runs may write a generation.
2112
+ */
2113
+ const FACTORY_MERGE_TARGET_REF_CONDITION = ["github.ref == 'refs/heads/main'", "startsWith(github.ref, 'refs/heads/epic/')"].join(" || ");
2114
+ /**
2115
+ * `always()` is load-bearing: the red path is the whole point, so the job must
2116
+ * run when a needed verification job failed. `github.event_name == 'push'` is
2117
+ * load-bearing twice over: a `pull_request` run must never write a generation
2118
+ * (its `github.sha` is a synthetic merge commit that no base tip is ever read
2119
+ * at), and a `pull_request` trigger with an `epic/**` base list would
2120
+ * otherwise reach this job.
2121
+ */
2122
+ const FACTORY_MERGE_FREEZE_IF = `always() && github.event_name == 'push' && (${FACTORY_MERGE_TARGET_REF_CONDITION})`;
2123
+ /**
2124
+ * Least privilege for the writer job: no `GITHUB_TOKEN` scope at all.
2125
+ *
2126
+ * Both Checks API calls run under the App installation token minted in the
2127
+ * first step (`GH_TOKEN: steps.factory-app-token.outputs.token`), and the job
2128
+ * never checks out the repository. So the job uses no `GITHUB_TOKEN` scope,
2129
+ * and an empty block is the honest declaration. A `checks: write` here would
2130
+ * hand every adopter an unused write scope (#884).
2131
+ */
2132
+ const FACTORY_MERGE_FREEZE_PERMISSIONS = Object.freeze({});
2133
+ /**
2134
+ * The script the freeze step runs. Environment contract:
2135
+ * - `GH_TOKEN`: an installation token for the pinned Patronage Factory App —
2136
+ * the check run must carry that App's identity or every reader rejects it.
2137
+ * - `VERIFY_RESULT`: `success` or `failure` (see the fold expression above).
2138
+ * - `VERIFY_JOBS`: JSON `needs` context; only job results are retained.
2139
+ * - `GITHUB_SHA` / `GITHUB_REPOSITORY` / `GITHUB_SERVER_URL` /
2140
+ * `GITHUB_RUN_ID` / `GITHUB_RUN_ATTEMPT` / `GITHUB_REF_NAME`: runner-provided.
2141
+ *
2142
+ * `GITHUB_REF_NAME` is the merge target this run pushed to — `main` or an
2143
+ * `epic/**` integration branch (#429). The job is gated to `push` events on
2144
+ * exactly those refs, so the branch name is always the short name of a
2145
+ * repository-owned merge target and never a pull-request merge ref. It
2146
+ * appears in recovery guidance because a reader of an epic-targeting
2147
+ * candidate must be told which branch owns the generation. A later green
2148
+ * generation on that branch's current tip clears it, including a rerun.
2149
+ */
2150
+ const factoryMergeFreezeScript = () => [
2151
+ `sha="$GITHUB_SHA"`,
2152
+ `branch="$GITHUB_REF_NAME"`,
2153
+ `repo="$GITHUB_REPOSITORY"`,
2154
+ `run_url="$GITHUB_SERVER_URL/$repo/actions/runs/$GITHUB_RUN_ID/attempts/$GITHUB_RUN_ATTEMPT"`,
2155
+ `verification=$(jq -cen --argjson needs "$VERIFY_JOBS" --argjson runId "$GITHUB_RUN_ID" --argjson runAttempt "$GITHUB_RUN_ATTEMPT" '`,
2156
+ ` def positiveInteger: type == "number" and . > 0 and floor == .;`,
2157
+ ` if ($runId | positiveInteger) and ($runAttempt | positiveInteger) and ($needs | type == "object" and length > 0) then`,
2158
+ ` {runId: $runId, runAttempt: $runAttempt, jobs: ($needs | map_values(.result))}`,
2159
+ ` | select(all(.jobs[]; . == "success" or . == "failure" or . == "cancelled" or . == "skipped"))`,
2160
+ ` else empty end')`,
2161
+ `cancelled=$(jq 'any(.jobs[]; . == "cancelled")' <<<"$verification")`,
2162
+ `failed=$(jq 'any(.jobs[]; . == "failure")' <<<"$verification")`,
2163
+ `created=$(gh api --method POST "repos/$repo/check-runs" \\`,
2164
+ ` -f "name=${FACTORY_MERGE_FREEZE_CHECK_NAME}" \\`,
2165
+ ` -f "head_sha=$sha" \\`,
2166
+ ` -f "status=in_progress" \\`,
2167
+ ` -f "details_url=$run_url" \\`,
2168
+ ` -f "output[title]=merge freeze generation in progress" \\`,
2169
+ ` -f "output[summary]=This generation blocks factory merge handoffs until the merge-target Verify result is recorded.")`,
2170
+ `id=$(jq -r '.id' <<<"$created")`,
2171
+ `case "$id" in`,
2172
+ ` ''|*[!0-9]*) echo "unusable check-run id: $id" >&2; exit 1;;`,
2173
+ `esac`,
2174
+ `if [ "$VERIFY_RESULT" = 'success' ]; then`,
2175
+ ` active=false; outcome=inactive; conclusion=success`,
2176
+ ` reason="Merge-target Verify passed on $branch at $sha ($run_url)."`,
2177
+ `else`,
2178
+ ` active=true; outcome=active; conclusion=failure`,
2179
+ ` if [ "$cancelled" = 'true' ] && [ "$failed" = 'false' ]; then`,
2180
+ ` 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)."`,
2181
+ ` elif [ "$cancelled" = 'true' ]; then`,
2182
+ ` 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)."`,
2183
+ ` else`,
2184
+ ` 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)."`,
2185
+ ` fi`,
2186
+ `fi`,
2187
+ `state=$(jq -cn --argjson active "$active" --argjson id "$id" --arg headSha "$sha" --arg outcome "$outcome" --arg reason "$reason" --argjson verification "$verification" \\`,
2188
+ ` '{active: $active, generationId: $id, headSha: $headSha, outcome: $outcome, reason: $reason, recordedAt: (now | todate), schemaVersion: 1, verification: $verification}')`,
2189
+ `gh api --method PATCH "repos/$repo/check-runs/$id" \\`,
2190
+ ` -f "status=completed" \\`,
2191
+ ` -f "conclusion=$conclusion" \\`,
2192
+ ` -f "details_url=$run_url" \\`,
2193
+ ` -f "output[title]=merge freeze $outcome" \\`,
2194
+ ` -f "output[summary]=$reason" \\`,
2195
+ ` -f "output[text]=$state" >/dev/null`,
2196
+ `echo "merge-freeze generation $id completed $outcome on $branch at $sha"`
2197
+ ].join("\n");
2198
+ /**
2199
+ * Build the merge-freeze writer job.
2200
+ *
2201
+ * An empty `needs` list is refused: a fold over no verification leaf is
2202
+ * always `success`, so such a job would write a green generation for a merge
2203
+ * target nothing verified — the exact failure the freeze exists to prevent.
2204
+ */
2205
+ const factoryMergeFreezeJob = (options) => {
2206
+ assertPinnedAction("createGithubAppToken", options.createGithubAppToken, "actions/create-github-app-token");
2207
+ 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.");
2208
+ const mintStep = Object.freeze({
2209
+ id: FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID,
2210
+ name: "Mint the factory App token",
2211
+ uses: options.createGithubAppToken.uses,
2212
+ with: Object.freeze({
2213
+ "client-id": FACTORY_PROOF_GATE_APP_ID,
2214
+ "private-key": `\${{ secrets.FACTORY_GITHUB_APP_PRIVATE_KEY }}`
2215
+ })
2216
+ });
2217
+ const reportStep = Object.freeze({
2218
+ env: Object.freeze({
2219
+ GH_TOKEN: `\${{ steps.${FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID}.outputs.token }}`,
2220
+ VERIFY_JOBS: `\${{ toJSON(needs) }}`,
2221
+ VERIFY_RESULT: options.verifyResultExpression ?? FACTORY_MERGE_FREEZE_VERIFY_RESULT_EXPRESSION
2222
+ }),
2223
+ name: "Complete the merge-freeze generation",
2224
+ run: factoryMergeFreezeScript()
2225
+ });
2226
+ return Object.freeze({
2227
+ if: FACTORY_MERGE_FREEZE_IF,
2228
+ jobId: FACTORY_MERGE_FREEZE_JOB_ID,
2229
+ jobName: FACTORY_MERGE_FREEZE_JOB_NAME,
2230
+ needs: Object.freeze([...options.needs]),
2231
+ permissions: FACTORY_MERGE_FREEZE_PERMISSIONS,
2232
+ steps: Object.freeze([mintStep, reportStep])
2233
+ });
2234
+ };
2235
+ //#endregion
2236
+ //#region src/pr-status-hud-workflow.ts
2237
+ const FACTORY_PR_STATUS_HUD_JOB_ID = "status-hud";
2238
+ const FACTORY_PR_STATUS_HUD_JOB_NAME = "Present PR status HUD";
2239
+ const FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID = "factory-app-token";
2240
+ const FACTORY_PR_STATUS_HUD_PLAN_PATH = ".factory-memory/preview-plan.json";
2241
+ /**
2242
+ * Presentation is independent of deploy demand. Callers who `needs` the jobs
2243
+ * that settle HUD sources (verify, deploy) must keep this `always()` so a
2244
+ * skipped or withdrawn deploy still publishes Skipped rows.
2245
+ */
2246
+ const FACTORY_PR_STATUS_HUD_IF = "always() && github.event_name == 'pull_request' && github.event.pull_request.draft != true";
2247
+ /**
2248
+ * Least privilege for the job that runs the present step. The present step
2249
+ * is an inventory `list`, so the job needs exactly the inventory's read
2250
+ * permissions (#825, #859).
2251
+ */
2252
+ const FACTORY_PR_STATUS_HUD_PERMISSIONS = PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS;
2253
+ const FACTORY_PR_STATUS_HUD_CONCURRENCY = Object.freeze({
2254
+ cancelInProgress: false,
2255
+ group: `status-hud-\${{ github.repository }}-\${{ github.event.pull_request.number }}`
2256
+ });
2257
+ const defaultCli = "psf";
2258
+ const factoryPrStatusHudWorkflow = (options) => {
2259
+ assertPinnedAction("createGithubAppToken", options.createGithubAppToken, "actions/create-github-app-token");
2260
+ const cli = options.cli || defaultCli;
2261
+ assertRunnableCli("cli", cli);
2262
+ const mintStep = Object.freeze({
2263
+ id: FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID,
2264
+ name: "Mint the factory App token",
2265
+ uses: options.createGithubAppToken.uses,
2266
+ with: Object.freeze({
2267
+ "client-id": FACTORY_PROOF_GATE_APP_ID,
2268
+ "private-key": `\${{ secrets.FACTORY_GITHUB_APP_PRIVATE_KEY }}`
2269
+ })
2270
+ });
2271
+ const presentStep = Object.freeze({
2272
+ env: Object.freeze({
2273
+ FACTORY_GITHUB_APP_TOKEN: `\${{ steps.${FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID}.outputs.token }}`,
2274
+ FACTORY_HEAD_SHA: `\${{ github.event.pull_request.head.sha }}`,
2275
+ FACTORY_OWNER: `\${{ github.repository_owner }}`,
2276
+ FACTORY_PR: `\${{ github.event.pull_request.number }}`,
2277
+ FACTORY_REPO: `\${{ github.event.repository.name }}`,
2278
+ GITHUB_TOKEN: `\${{ github.token }}`
2279
+ }),
2280
+ name: "Present the PR status HUD",
2281
+ run: `${cli} pr:status-hud --head "$FACTORY_HEAD_SHA" --owner "$FACTORY_OWNER" --repo "$FACTORY_REPO" --pr "$FACTORY_PR"`
2282
+ });
2283
+ return Object.freeze({
2284
+ concurrency: FACTORY_PR_STATUS_HUD_CONCURRENCY,
2285
+ if: FACTORY_PR_STATUS_HUD_IF,
2286
+ jobId: FACTORY_PR_STATUS_HUD_JOB_ID,
2287
+ jobName: FACTORY_PR_STATUS_HUD_JOB_NAME,
2288
+ permissions: FACTORY_PR_STATUS_HUD_PERMISSIONS,
2289
+ presentSteps: Object.freeze([mintStep, presentStep])
2290
+ });
2291
+ };
2292
+ //#endregion
2293
+ //#region src/preview-cleanup-topology.ts
2294
+ const FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_ID = "stage-residue-audit";
2295
+ const FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_NAME = "Stage residue audit";
2296
+ const JOB_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]*$/u;
2297
+ const STACK_JOB_SAFE = /[^A-Za-z0-9_-]+/gu;
2298
+ const assertSingleLine = (name, value) => {
2299
+ if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) throw new Error(`${name} must be a single non-empty line.`);
2300
+ };
2301
+ const previewCleanupDestroyJobId = (stack) => {
2302
+ assertSingleLine("cleanup stack", stack);
2303
+ const suffix = stack.replaceAll(STACK_JOB_SAFE, "-").replaceAll(/^-+|-+$/gu, "");
2304
+ if (suffix.length === 0) throw new Error(`Cleanup stack "${stack}" has no job-id-safe characters.`);
2305
+ const jobId = `destroy-${suffix}`;
2306
+ if (!JOB_ID_PATTERN.test(jobId)) throw new Error(`Cleanup destroy job id "${jobId}" is not a GitHub Actions job id.`);
2307
+ return jobId;
2308
+ };
2309
+ /**
2310
+ * Generate the factory-owned preview-cleanup topology (#764): one destroy
2311
+ * job identity per stack, then exactly one stage-wide residue-audit job
2312
+ * that `needs` every destroy. The audit is whole-stage — this helper never
2313
+ * threads a stack name or path filter into it. Callers own destroy steps,
2314
+ * what counts as residue, credentials, and runners.
2315
+ */
2316
+ const factoryPreviewCleanupTopology = (options) => {
2317
+ if (options.stacks.length === 0) throw new Error("Preview cleanup topology requires at least one stack so the audit can depend on every destroy.");
2318
+ const destroyJobs = options.stacks.map((stack) => Object.freeze({
2319
+ jobId: previewCleanupDestroyJobId(stack),
2320
+ stack
2321
+ }));
2322
+ const destroyJobIds = destroyJobs.map(({ jobId }) => jobId);
2323
+ if (new Set(destroyJobIds).size !== destroyJobIds.length) throw new Error("Cleanup stack names must map to distinct destroy job ids.");
2324
+ assertSingleLine("audit.command", options.audit.command);
2325
+ const jobId = options.audit.jobId ?? "stage-residue-audit";
2326
+ const jobName = options.audit.jobName ?? "Stage residue audit";
2327
+ if (!JOB_ID_PATTERN.test(jobId)) throw new Error("audit.jobId must be a GitHub Actions job id.");
2328
+ assertSingleLine("audit.jobName", jobName);
2329
+ if (destroyJobIds.includes(jobId)) throw new Error("audit.jobId must not collide with a destroy job id.");
2330
+ const auditStep = Object.freeze({
2331
+ name: "Assert stage absent",
2332
+ run: options.audit.command
2333
+ });
2334
+ return Object.freeze({
2335
+ auditJob: Object.freeze({
2336
+ if: "always()",
2337
+ jobId,
2338
+ jobName,
2339
+ needs: Object.freeze([...destroyJobIds]),
2340
+ steps: Object.freeze([auditStep])
2341
+ }),
2342
+ destroyJobs: Object.freeze(destroyJobs)
2343
+ });
2344
+ };
2345
+ //#endregion
2346
+ //#region src/preview-receipt-workflow.ts
2347
+ /** Receipt transport only. The consumer owns selection, lifecycle, smoke, and freshness. */
2348
+ const factoryPreviewReceiptWorkflow = (options) => {
2349
+ if (!/^preview:[a-z][a-z0-9-]*$/u.test(options.target)) throw new Error("Preview receipts require a declared preview target name.");
2350
+ const cli = options.cli ?? "pnpm exec psf";
2351
+ assertRunnableCli("cli", cli);
2352
+ const id = `preview_intent_${options.target.slice(8).replaceAll("-", "_")}`;
2353
+ const deploymentId = `\${{ steps.${id}.outputs.deployment_id }}`;
2354
+ const hasIntent = `steps.${id}.outputs.deployment_id != ''`;
2355
+ const env = {
2356
+ FACTORY_PREVIEW_PR: options.pr ?? `\${{ github.event.pull_request.number }}`,
2357
+ GH_TOKEN: `\${{ github.token }}`
2358
+ };
2359
+ const command = `${cli} preview:receipt --pr "$FACTORY_PREVIEW_PR" --target '${options.target}'`;
2360
+ return Object.freeze({
2361
+ beginStep: Object.freeze({
2362
+ env,
2363
+ id,
2364
+ name: `Record preview intent for ${options.target}`,
2365
+ run: `${command} --action begin --github-output "$GITHUB_OUTPUT"`
2366
+ }),
2367
+ completionSteps: Object.freeze([
2368
+ Object.freeze({
2369
+ env: {
2370
+ ...env,
2371
+ FACTORY_DEPLOYMENT_ID: deploymentId
2372
+ },
2373
+ if: `success() && ${hasIntent}`,
2374
+ name: `Complete preview receipt for ${options.target}`,
2375
+ run: `${command} --action complete --deployment-id "$FACTORY_DEPLOYMENT_ID" --outcome success`
2376
+ }),
2377
+ Object.freeze({
2378
+ env: { FACTORY_DEPLOYMENT_ID: deploymentId },
2379
+ if: `success() && ${hasIntent}`,
2380
+ name: `Bind deployment receipt ${deploymentId}`,
2381
+ run: "test -n \"$FACTORY_DEPLOYMENT_ID\""
2382
+ }),
2383
+ Object.freeze({
2384
+ env: {
2385
+ ...env,
2386
+ FACTORY_DEPLOYMENT_ID: deploymentId
2387
+ },
2388
+ if: `failure() && ${hasIntent}`,
2389
+ name: `Fail preview receipt for ${options.target}`,
2390
+ run: `${command} --action complete --deployment-id "$FACTORY_DEPLOYMENT_ID" --outcome failure`
2391
+ })
2392
+ ]),
2393
+ invalidateStep: Object.freeze({
2394
+ env,
2395
+ name: `Invalidate preview receipts for ${options.target}`,
2396
+ run: `${command} --action invalidate`
2397
+ }),
2398
+ permissions: Object.freeze({
2399
+ actions: "read",
2400
+ contents: "read",
2401
+ deployments: "write",
2402
+ "pull-requests": "read"
2403
+ })
2404
+ });
2405
+ };
2406
+ //#endregion
2407
+ //#region src/push-identity-workflow.ts
2408
+ /** `owner/repo` slice of the catalog's `UPLOAD_ARTIFACT` pin, derived rather
2409
+ * than repeated as a literal, so a repository rename here cannot drift from
2410
+ * the pin it validates against. */
2411
+ const UPLOAD_ARTIFACT_REPOSITORY = UPLOAD_ARTIFACT.uses.slice(0, UPLOAD_ARTIFACT.uses.indexOf("@"));
2412
+ const FACTORY_PUSH_IDENTITY_SCHEMA_VERSION = 1;
2413
+ /**
2414
+ * The artifact prefix and the five step IDs are module-private. Alpha.13
2415
+ * removed them from the public surface (#719). A caller reads a step ID from
2416
+ * the builder's returned `steps` (`step.id`) or from `artifactName`.
2417
+ */
2418
+ const FACTORY_PUSH_IDENTITY_ARTIFACT_PREFIX = "factory-push-identity";
2419
+ const FACTORY_PUSH_IDENTITY_RECORD_STEP_ID = "factory_push_identity_record";
2420
+ const FACTORY_PUSH_IDENTITY_LOOKUP_STEP_ID = "factory_push_identity_lookup";
2421
+ const FACTORY_PUSH_IDENTITY_DOWNLOAD_STEP_ID = "factory_push_identity_download";
2422
+ const FACTORY_PUSH_IDENTITY_CHECKOUT_STEP_ID = "factory_push_identity_checkout";
2423
+ const FACTORY_PUSH_IDENTITY_VALIDATE_STEP_ID = "factory_push_identity";
2424
+ const ARTIFACT_MAX_BYTES = 16384;
2425
+ const ENVELOPE_MAX_BYTES = 4096;
2426
+ const expression = (value) => `\${{ ${value} }}`;
2427
+ const artifactName = (runId) => `${FACTORY_PUSH_IDENTITY_ARTIFACT_PREFIX}-${runId}`;
2428
+ const producerScript = String.raw`identity="$RUNNER_TEMP/factory-push-identity.json"
2429
+ produced=false
2430
+ reason='producer_error'
2431
+ before=''
2432
+ event_after=''
2433
+ rm -f "$identity"
2434
+
2435
+ is_hex_sha() {
2436
+ [ "$(printf '%s' "$1" | wc -c | tr -d '[:space:]')" -eq 40 ] &&
2437
+ case "$1" in *[!0-9a-f]*) false;; *) true;; esac
2438
+ }
2439
+
2440
+ is_nonzero_sha() {
2441
+ is_hex_sha "$1" && [ "$1" != '0000000000000000000000000000000000000000' ]
2442
+ }
2443
+
2444
+ if [ "$GITHUB_EVENT_NAME" != 'push' ]; then
2445
+ reason='not_push_event'
2446
+ elif ! printf '%s' "$GITHUB_REPOSITORY" | grep -Eq '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$'; then
2447
+ reason='repository_invalid'
2448
+ elif ! printf '%s' "$GITHUB_RUN_ID" | grep -Eq '^[1-9][0-9]*$'; then
2449
+ reason='run_id_invalid'
2450
+ elif ! before="$(jq -er '.before | select(type == "string")' "$GITHUB_EVENT_PATH" 2>/dev/null)"; then
2451
+ reason='event_before_missing'
2452
+ elif ! event_after="$(jq -er '.after | select(type == "string")' "$GITHUB_EVENT_PATH" 2>/dev/null)"; then
2453
+ reason='event_after_missing'
2454
+ elif ! is_hex_sha "$before"; then
2455
+ reason='event_before_invalid'
2456
+ elif ! is_nonzero_sha "$event_after" || ! is_nonzero_sha "$GITHUB_SHA"; then
2457
+ reason='event_after_invalid'
2458
+ elif [ "$event_after" != "$GITHUB_SHA" ]; then
2459
+ reason='event_after_mismatch'
2460
+ elif jq -cn \
2461
+ --argjson schemaVersion '${1}' \
2462
+ --arg repository "$GITHUB_REPOSITORY" \
2463
+ --arg runId "$GITHUB_RUN_ID" \
2464
+ --arg before "$before" \
2465
+ --arg after "$event_after" \
2466
+ '{schemaVersion: $schemaVersion, repository: $repository, runId: $runId, before: $before, after: $after}' > "$identity"; then
2467
+ produced=true
2468
+ reason='produced'
2469
+ fi
2470
+
2471
+ printf 'produced=%s\nreason=%s\n' "$produced" "$reason" >> "$GITHUB_OUTPUT"
2472
+ {
2473
+ printf '## Exact push identity producer\n\n'
2474
+ printf -- '- Status: %s\n' "$reason"
2475
+ printf -- '- Repository/run: %s / %s\n' "$GITHUB_REPOSITORY" "$GITHUB_RUN_ID"
2476
+ if [ "$produced" = true ]; then
2477
+ printf -- '- Bound push: %s → %s\n' "$before" "$event_after"
2478
+ else
2479
+ printf -- '- Identity transport was not produced; downstream classification will refuse withdrawal.\n'
2480
+ fi
2481
+ } >> "$GITHUB_STEP_SUMMARY"`;
2482
+ const lookupScript = String.raw`status='refused'
2483
+ reason='artifact_lookup_failed'
2484
+ artifact_id=''
2485
+ matches="$RUNNER_TEMP/factory-push-identity-artifacts.tsv"
2486
+ artifact_name='${FACTORY_PUSH_IDENTITY_ARTIFACT_PREFIX}-'"$EXPECTED_RUN_ID"
2487
+ rm -f "$matches"
2488
+
2489
+ is_sha() {
2490
+ [ "$(printf '%s' "$1" | wc -c | tr -d '[:space:]')" -eq 40 ] &&
2491
+ [ "$1" != '0000000000000000000000000000000000000000' ] &&
2492
+ case "$1" in *[!0-9a-f]*) false;; *) true;; esac
2493
+ }
2494
+
2495
+ if [ "$EXPECTED_EVENT_NAME" != 'workflow_run' ]; then
2496
+ reason='event_not_workflow_run'
2497
+ elif [ "$EXPECTED_WORKFLOW_EVENT" != 'push' ]; then
2498
+ reason='triggering_workflow_not_push'
2499
+ elif [ "$EXPECTED_CONCLUSION" != 'success' ]; then
2500
+ reason='triggering_workflow_not_successful'
2501
+ elif [ "$EXPECTED_WORKFLOW_REPOSITORY" != "$EXPECTED_REPOSITORY" ]; then
2502
+ reason='triggering_repository_mismatch'
2503
+ elif ! printf '%s' "$EXPECTED_REPOSITORY" | grep -Eq '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$'; then
2504
+ reason='triggering_repository_invalid'
2505
+ elif ! printf '%s' "$EXPECTED_RUN_ID" | grep -Eq '^[1-9][0-9]*$'; then
2506
+ reason='triggering_run_id_invalid'
2507
+ elif ! is_sha "$EXPECTED_AFTER_SHA"; then
2508
+ reason='triggering_head_sha_invalid'
2509
+ elif ! gh api --paginate \
2510
+ "repos/$EXPECTED_REPOSITORY/actions/runs/$EXPECTED_RUN_ID/artifacts?per_page=100" \
2511
+ --jq ".artifacts[] | select(.name == \"$artifact_name\") | [.id, .size_in_bytes, .expired] | @tsv" \
2512
+ > "$matches" 2>/dev/null; then
2513
+ reason='artifact_lookup_failed'
2514
+ else
2515
+ count="$(awk 'END { print NR + 0 }' "$matches")"
2516
+ if [ "$count" -eq 0 ]; then
2517
+ reason='artifact_missing'
2518
+ elif [ "$count" -ne 1 ]; then
2519
+ reason='artifact_duplicate'
2520
+ else
2521
+ IFS="$(printf '\t')" read -r artifact_id artifact_size artifact_expired < "$matches" || true
2522
+ if ! printf '%s' "$artifact_id" | grep -Eq '^[1-9][0-9]*$' ||
2523
+ ! printf '%s' "$artifact_size" | grep -Eq '^[0-9]+$' ||
2524
+ { [ "$artifact_expired" != 'false' ] && [ "$artifact_expired" != 'true' ]; }; then
2525
+ reason='artifact_metadata_invalid'
2526
+ artifact_id=''
2527
+ elif [ "$artifact_expired" = 'true' ]; then
2528
+ reason='artifact_expired'
2529
+ artifact_id=''
2530
+ elif [ "$artifact_size" -gt '${ARTIFACT_MAX_BYTES}' ]; then
2531
+ reason='artifact_oversized'
2532
+ artifact_id=''
2533
+ else
2534
+ status='available'
2535
+ reason='artifact_available'
2536
+ fi
2537
+ fi
2538
+ fi
2539
+
2540
+ printf 'status=%s\nreason=%s\nartifact_id=%s\n' "$status" "$reason" "$artifact_id" >> "$GITHUB_OUTPUT"`;
2541
+ const validationScript = String.raw`disposition='refused'
2542
+ reason='validation_error'
2543
+ before=''
2544
+ after=''
2545
+ identity_directory="$RUNNER_TEMP/factory-push-identity"
2546
+ identity="$identity_directory/factory-push-identity.json"
2547
+ artifact_name='${FACTORY_PUSH_IDENTITY_ARTIFACT_PREFIX}-'"$EXPECTED_RUN_ID"
2548
+
2549
+ is_sha() {
2550
+ [ "$(printf '%s' "$1" | wc -c | tr -d '[:space:]')" -eq 40 ] &&
2551
+ [ "$1" != '0000000000000000000000000000000000000000' ] &&
2552
+ case "$1" in *[!0-9a-f]*) false;; *) true;; esac
2553
+ }
2554
+
2555
+ if [ "$EXPECTED_EVENT_NAME" != 'workflow_run' ]; then
2556
+ reason='event_not_workflow_run'
2557
+ elif [ "$EXPECTED_WORKFLOW_EVENT" != 'push' ]; then
2558
+ reason='triggering_workflow_not_push'
2559
+ elif [ "$EXPECTED_CONCLUSION" != 'success' ]; then
2560
+ reason='triggering_workflow_not_successful'
2561
+ elif [ "$EXPECTED_WORKFLOW_REPOSITORY" != "$EXPECTED_REPOSITORY" ]; then
2562
+ reason='triggering_repository_mismatch'
2563
+ elif ! printf '%s' "$EXPECTED_REPOSITORY" | grep -Eq '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$'; then
2564
+ reason='triggering_repository_invalid'
2565
+ elif ! printf '%s' "$EXPECTED_RUN_ID" | grep -Eq '^[1-9][0-9]*$'; then
2566
+ reason='triggering_run_id_invalid'
2567
+ elif ! is_sha "$EXPECTED_AFTER_SHA"; then
2568
+ reason='triggering_head_sha_invalid'
2569
+ elif [ "$LOOKUP_STATUS" != 'available' ]; then
2570
+ if [ -n "$LOOKUP_REASON" ]; then
2571
+ reason="$LOOKUP_REASON"
2572
+ else
2573
+ reason='artifact_lookup_failed'
2574
+ fi
2575
+ elif [ "$DOWNLOAD_OUTCOME" != 'success' ]; then
2576
+ reason='artifact_download_failed'
2577
+ elif [ "$CHECKOUT_OUTCOME" != 'success' ]; then
2578
+ reason='checkout_failed'
2579
+ elif [ ! -d "$identity_directory" ]; then
2580
+ reason='artifact_contents_missing'
2581
+ else
2582
+ entry_count="$(find "$identity_directory" -mindepth 1 -maxdepth 1 -print 2>/dev/null | awk 'END { print NR + 0 }')"
2583
+ if [ "$entry_count" -ne 1 ] || [ ! -f "$identity" ] || [ -L "$identity" ]; then
2584
+ reason='artifact_contents_invalid'
2585
+ else
2586
+ envelope_size="$(wc -c < "$identity" | tr -d '[:space:]')"
2587
+ if ! printf '%s' "$envelope_size" | grep -Eq '^[0-9]+$'; then
2588
+ reason='envelope_size_unreadable'
2589
+ elif [ "$envelope_size" -gt '${ENVELOPE_MAX_BYTES}' ]; then
2590
+ reason='envelope_oversized'
2591
+ elif ! jq -e --argjson schemaVersion '${1}' '
2592
+ type == "object" and
2593
+ keys == ["after", "before", "repository", "runId", "schemaVersion"] and
2594
+ .schemaVersion == $schemaVersion and
2595
+ (.repository | type == "string") and
2596
+ (.runId | type == "string" and test("^[1-9][0-9]*$")) and
2597
+ (.before | type == "string" and test("^[0-9a-f]{40}$") and (test("^0{40}$") | not)) and
2598
+ (.after | type == "string" and test("^[0-9a-f]{40}$") and (test("^0{40}$") | not))
2599
+ ' "$identity" >/dev/null 2>&1; then
2600
+ reason='envelope_malformed'
2601
+ else
2602
+ repository="$(jq -r '.repository' "$identity")"
2603
+ run_id="$(jq -r '.runId' "$identity")"
2604
+ before="$(jq -r '.before' "$identity")"
2605
+ after="$(jq -r '.after' "$identity")"
2606
+
2607
+ if [ "$repository" != "$EXPECTED_REPOSITORY" ]; then
2608
+ reason='envelope_repository_mismatch'
2609
+ elif [ "$run_id" != "$EXPECTED_RUN_ID" ]; then
2610
+ reason='envelope_run_id_mismatch'
2611
+ elif [ "$after" != "$EXPECTED_AFTER_SHA" ]; then
2612
+ reason='envelope_after_mismatch'
2613
+ elif ! actual_head="$(git rev-parse --verify HEAD 2>/dev/null)" || [ "$actual_head" != "$EXPECTED_AFTER_SHA" ]; then
2614
+ reason='checkout_head_mismatch'
2615
+ elif ! git cat-file -e "$before^{commit}" 2>/dev/null || ! git cat-file -e "$after^{commit}" 2>/dev/null; then
2616
+ reason='envelope_commit_unreachable'
2617
+ elif [ "$before" = "$after" ]; then
2618
+ reason='envelope_commits_contradictory'
2619
+ elif ! git merge-base --is-ancestor "$before" "$after"; then
2620
+ reason='before_not_ancestor'
2621
+ else
2622
+ disposition='usable'
2623
+ reason='identity_bound'
2624
+ fi
2625
+ fi
2626
+ fi
2627
+ fi
2628
+
2629
+ if [ "$disposition" != 'usable' ]; then
2630
+ before=''
2631
+ after=''
2632
+ fi
2633
+
2634
+ provenance="$(jq -cn \
2635
+ --argjson schemaVersion '${1}' \
2636
+ --arg disposition "$disposition" \
2637
+ --arg reason "$reason" \
2638
+ --arg repository "$EXPECTED_REPOSITORY" \
2639
+ --arg runId "$EXPECTED_RUN_ID" \
2640
+ --arg expectedAfter "$EXPECTED_AFTER_SHA" \
2641
+ --arg artifactName "$artifact_name" \
2642
+ --arg artifactId "$ARTIFACT_ID" \
2643
+ --arg before "$before" \
2644
+ --arg after "$after" \
2645
+ '{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)}')"
2646
+
2647
+ printf 'disposition=%s\nreason=%s\nbefore=%s\nafter=%s\nprovenance=%s\n' \
2648
+ "$disposition" "$reason" "$before" "$after" "$provenance" >> "$GITHUB_OUTPUT"
2649
+ {
2650
+ printf '## Exact push identity\n\n'
2651
+ printf -- '- Disposition: %s\n' "$disposition"
2652
+ printf -- '- Reason: %s\n' "$reason"
2653
+ printf -- '- Repository/run: %s / %s\n' "$EXPECTED_REPOSITORY" "$EXPECTED_RUN_ID"
2654
+ printf -- '- Expected verified head: %s\n' "$EXPECTED_AFTER_SHA"
2655
+ if [ "$disposition" = 'usable' ]; then
2656
+ printf -- '- Bound push: %s → %s\n' "$before" "$after"
2657
+ else
2658
+ printf -- '- Production impact classification refused; every consumer-owned production target remains demanded.\n'
2659
+ fi
2660
+ printf '\nFactory telemetry provenance: %s\n' "$provenance"
2661
+ } >> "$GITHUB_STEP_SUMMARY"`;
2662
+ /**
2663
+ * Record and upload the exact push-event identity without changing the Verify
2664
+ * result when transport is unavailable. Place these steps after verification.
2665
+ */
2666
+ const factoryPushIdentityProducer = (options) => {
2667
+ assertPinnedAction("uploadArtifact", options.uploadArtifact, UPLOAD_ARTIFACT_REPOSITORY);
2668
+ const condition = options.if ? `github.event_name == 'push' && (${options.if})` : "github.event_name == 'push'";
2669
+ const name = artifactName(expression("github.run_id"));
2670
+ return Object.freeze({
2671
+ artifactName: name,
2672
+ steps: Object.freeze([{
2673
+ continueOnError: true,
2674
+ id: FACTORY_PUSH_IDENTITY_RECORD_STEP_ID,
2675
+ if: condition,
2676
+ name: "Record exact push identity",
2677
+ run: producerScript
2678
+ }, {
2679
+ continueOnError: true,
2680
+ if: `${condition} && steps.${FACTORY_PUSH_IDENTITY_RECORD_STEP_ID}.outputs.produced == 'true'`,
2681
+ name: "Upload exact push identity",
2682
+ uses: options.uploadArtifact.uses,
2683
+ with: {
2684
+ "if-no-files-found": "error",
2685
+ name,
2686
+ path: `${expression("runner.temp")}/factory-push-identity.json`,
2687
+ "retention-days": "7"
2688
+ }
2689
+ }])
2690
+ });
2691
+ };
2692
+ /**
2693
+ * Download and validate identity from exactly the triggering workflow run in
2694
+ * the current repository. Every failure becomes a typed refusal; consumers
2695
+ * retain deploy policy, credentials, commands, topology, and convergence.
2696
+ */
2697
+ const factoryPushIdentityConsumer = (options) => {
2698
+ assertPinnedAction("checkout", options.checkout, "actions/checkout");
2699
+ assertPinnedAction("downloadArtifact", options.downloadArtifact, "actions/download-artifact");
2700
+ const currentRepository = expression("github.repository");
2701
+ const triggeringRun = expression("github.event.workflow_run.id");
2702
+ const triggeringHead = expression("github.event.workflow_run.head_sha");
2703
+ const lookupOutput = (name) => expression(`steps.${FACTORY_PUSH_IDENTITY_LOOKUP_STEP_ID}.outputs.${name}`);
2704
+ const validateOutput = (name) => expression(`steps.${FACTORY_PUSH_IDENTITY_VALIDATE_STEP_ID}.outputs.${name}`);
2705
+ const contextEnvironment = {
2706
+ EXPECTED_AFTER_SHA: triggeringHead,
2707
+ EXPECTED_CONCLUSION: expression("github.event.workflow_run.conclusion"),
2708
+ EXPECTED_EVENT_NAME: expression("github.event_name"),
2709
+ EXPECTED_REPOSITORY: currentRepository,
2710
+ EXPECTED_RUN_ID: triggeringRun,
2711
+ EXPECTED_WORKFLOW_EVENT: expression("github.event.workflow_run.event"),
2712
+ EXPECTED_WORKFLOW_REPOSITORY: expression("github.event.workflow_run.repository.full_name")
2713
+ };
2714
+ const steps = [
2715
+ {
2716
+ continueOnError: true,
2717
+ env: {
2718
+ GH_TOKEN: expression("github.token"),
2719
+ ...contextEnvironment
2720
+ },
2721
+ id: FACTORY_PUSH_IDENTITY_LOOKUP_STEP_ID,
2722
+ name: "Resolve exact push identity artifact",
2723
+ run: lookupScript
2724
+ },
2725
+ {
2726
+ continueOnError: true,
2727
+ id: FACTORY_PUSH_IDENTITY_DOWNLOAD_STEP_ID,
2728
+ if: `steps.${FACTORY_PUSH_IDENTITY_LOOKUP_STEP_ID}.outputs.status == 'available'`,
2729
+ name: "Download exact push identity",
2730
+ uses: options.downloadArtifact.uses,
2731
+ with: {
2732
+ "artifact-ids": lookupOutput("artifact_id"),
2733
+ "github-token": expression("github.token"),
2734
+ path: `${expression("runner.temp")}/factory-push-identity`,
2735
+ repository: currentRepository,
2736
+ "run-id": triggeringRun
2737
+ }
2738
+ },
2739
+ {
2740
+ continueOnError: true,
2741
+ id: FACTORY_PUSH_IDENTITY_CHECKOUT_STEP_ID,
2742
+ if: `steps.${FACTORY_PUSH_IDENTITY_LOOKUP_STEP_ID}.outputs.status == 'available'`,
2743
+ name: "Checkout exact verified head",
2744
+ uses: options.checkout.uses,
2745
+ with: {
2746
+ "fetch-depth": "0",
2747
+ ref: triggeringHead
2748
+ }
2749
+ },
2750
+ {
2751
+ continueOnError: true,
2752
+ env: {
2753
+ ARTIFACT_ID: lookupOutput("artifact_id"),
2754
+ CHECKOUT_OUTCOME: expression(`steps.${FACTORY_PUSH_IDENTITY_CHECKOUT_STEP_ID}.outcome`),
2755
+ DOWNLOAD_OUTCOME: expression(`steps.${FACTORY_PUSH_IDENTITY_DOWNLOAD_STEP_ID}.outcome`),
2756
+ LOOKUP_REASON: lookupOutput("reason"),
2757
+ LOOKUP_STATUS: lookupOutput("status"),
2758
+ ...contextEnvironment
2759
+ },
2760
+ id: FACTORY_PUSH_IDENTITY_VALIDATE_STEP_ID,
2761
+ if: "always()",
2762
+ name: "Validate exact push identity",
2763
+ run: validationScript
2764
+ }
2765
+ ];
2766
+ return Object.freeze({
2767
+ outputs: Object.freeze({
2768
+ after: validateOutput("after"),
2769
+ before: validateOutput("before"),
2770
+ disposition: validateOutput("disposition"),
2771
+ provenance: validateOutput("provenance"),
2772
+ reason: validateOutput("reason")
2773
+ }),
2774
+ requiredPermissions: Object.freeze({
2775
+ actions: "read",
2776
+ contents: "read"
2777
+ }),
2778
+ steps: Object.freeze(steps),
2779
+ usableIf: `steps.${FACTORY_PUSH_IDENTITY_VALIDATE_STEP_ID}.outputs.disposition == 'usable'`
2780
+ });
2781
+ };
2782
+ //#endregion
2783
+ //#region src/vitest-profile.ts
2784
+ /**
2785
+ * Vitest suite profiling — the measurement mechanics behind a CI runner
2786
+ * comparison (#640, #647).
2787
+ *
2788
+ * A profile is a machine-readable record of N serial Vitest runs at one worker
2789
+ * count, carrying per-file and per-test timings, aggregate duration statistics,
2790
+ * and the hardware the samples actually ran on. The hardware capture is the
2791
+ * point: the #640 Depot comparison only resolved because every sample recorded
2792
+ * its `cpuModel`, which split otherwise-identical 4-CPU runs into two
2793
+ * non-overlapping populations.
2794
+ *
2795
+ * Everything a repository decides stays with the repository: worker counts,
2796
+ * sample counts, output paths, runner labels, and which suite to run at all.
2797
+ * This module owns the schema, the report parsing, the environment capture, and
2798
+ * the atomic write.
2799
+ */
2800
+ /** Schema version of the emitted profile document. */
2801
+ const VITEST_PROFILE_SCHEMA_VERSION = 1;
2802
+ /** `tool` discriminator every emitted profile carries. */
2803
+ const VITEST_PROFILE_TOOL = "factory-ci-vitest-profile";
2804
+ const RUN_TIMEOUT_MS = 15 * 6e4;
2805
+ const TERMINATION_GRACE_MS = 5e3;
2806
+ /**
2807
+ * A sample failed. The partial profile is already on disk; `exitCode` is the
2808
+ * status a caller should exit with.
2809
+ */
2810
+ var VitestProfileError = class extends Error {
2811
+ exitCode;
2812
+ constructor(message, exitCode) {
2813
+ super(message);
2814
+ this.name = "VitestProfileError";
2815
+ this.exitCode = exitCode;
2816
+ }
2817
+ };
2818
+ const durationSummary = (durations) => {
2819
+ const sorted = durations.toSorted((left, right) => left - right);
2820
+ const middle = Math.floor(sorted.length / 2);
2821
+ const median = sorted.length % 2 === 0 ? ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2 : sorted[middle] ?? 0;
2822
+ return {
2823
+ maximum: sorted.at(-1) ?? 0,
2824
+ mean: durations.reduce((sum, value) => sum + value, 0) / durations.length,
2825
+ median,
2826
+ minimum: sorted[0] ?? 0
2827
+ };
2828
+ };
2829
+ const relativePath = (cwd, file) => path.relative(cwd, file).split(path.sep).join("/");
2830
+ /**
2831
+ * Fold one Vitest JSON report into a profile sample: file and test timings,
2832
+ * both sorted slowest first, plus the run's counts. A missing report (crash,
2833
+ * timeout, unwritable output) yields a sample with `reportAvailable: false`
2834
+ * rather than nothing at all.
2835
+ */
2836
+ const normalizeVitestProfileSample = (report, input) => {
2837
+ const files = (report?.testResults ?? []).map((file) => ({
2838
+ durationMs: Math.max(0, file.endTime - file.startTime),
2839
+ path: relativePath(input.cwd, file.name),
2840
+ status: file.status
2841
+ })).toSorted((left, right) => right.durationMs - left.durationMs);
2842
+ const tests = (report?.testResults ?? []).flatMap((file) => file.assertionResults.map((test) => ({
2843
+ durationMs: Math.max(0, test.duration ?? 0),
2844
+ file: relativePath(input.cwd, file.name),
2845
+ name: test.fullName,
2846
+ status: test.status
2847
+ }))).toSorted((left, right) => right.durationMs - left.durationMs);
2848
+ return {
2849
+ counts: report ? {
2850
+ failed: report.numFailedTests,
2851
+ passed: report.numPassedTests,
2852
+ pending: report.numPendingTests,
2853
+ suites: report.numTotalTestSuites,
2854
+ tests: report.numTotalTests,
2855
+ todo: report.numTodoTests
2856
+ } : null,
2857
+ durationMs: input.durationMs,
2858
+ endedAt: input.endedAt.toISOString(),
2859
+ exitCode: input.exitCode,
2860
+ failure: input.failure ?? null,
2861
+ files,
2862
+ reportAvailable: report !== null,
2863
+ sample: input.sample,
2864
+ startedAt: input.startedAt.toISOString(),
2865
+ tests
2866
+ };
2867
+ };
2868
+ const aggregateSlowFiles = (runs, limit) => {
2869
+ const durations = /* @__PURE__ */ new Map();
2870
+ for (const file of runs.flatMap((run) => run.files)) {
2871
+ const recorded = durations.get(file.path) ?? [];
2872
+ recorded.push(file.durationMs);
2873
+ durations.set(file.path, recorded);
2874
+ }
2875
+ return [...durations].map(([filePath, values]) => ({
2876
+ durationMs: durationSummary(values),
2877
+ path: filePath,
2878
+ samples: values.length
2879
+ })).toSorted((left, right) => right.durationMs.median - left.durationMs.median).slice(0, limit);
2880
+ };
2881
+ const aggregateSlowTests = (runs, limit) => {
2882
+ const timings = /* @__PURE__ */ new Map();
2883
+ for (const test of runs.flatMap((run) => run.tests)) {
2884
+ const key = `${test.file}\0${test.name}`;
2885
+ const recorded = timings.get(key) ?? {
2886
+ durations: [],
2887
+ file: test.file,
2888
+ name: test.name
2889
+ };
2890
+ recorded.durations.push(test.durationMs);
2891
+ timings.set(key, recorded);
2892
+ }
2893
+ return [...timings.values()].map(({ durations, file, name }) => ({
2894
+ durationMs: durationSummary(durations),
2895
+ file,
2896
+ name,
2897
+ samples: durations.length
2898
+ })).toSorted((left, right) => right.durationMs.median - left.durationMs.median).slice(0, limit);
2899
+ };
2900
+ const gitValue = (cwd, args) => {
2901
+ try {
2902
+ return execFileSync("git", args, {
2903
+ cwd,
2904
+ encoding: "utf-8",
2905
+ stdio: [
2906
+ "ignore",
2907
+ "pipe",
2908
+ "ignore"
2909
+ ]
2910
+ }).trim();
2911
+ } catch {
2912
+ return null;
2913
+ }
2914
+ };
2915
+ const resolveVitestPackage = (cwd) => createRequire(path.join(path.resolve(cwd), "noop.js")).resolve("vitest/package.json");
2916
+ /**
2917
+ * Record the machine and commit a profile was taken on. Vitest's version is
2918
+ * resolved from `cwd`, so it is the consumer's Vitest and not this package's.
2919
+ * Git failures degrade to `null` — an artifact from a tarball checkout is still
2920
+ * a usable measurement.
2921
+ */
2922
+ const captureVitestProfileEnvironment = async (options) => {
2923
+ const gitDirectory = options.gitDirectory ?? options.cwd;
2924
+ let vitestVersion = "unknown";
2925
+ try {
2926
+ vitestVersion = JSON.parse(await readFile(resolveVitestPackage(options.cwd), "utf-8")).version ?? "unknown";
2927
+ } catch {
2928
+ vitestVersion = "unknown";
2929
+ }
2930
+ const processors = cpus();
2931
+ const status = gitValue(gitDirectory, ["status", "--porcelain"]);
2932
+ return {
2933
+ arch: arch(),
2934
+ availableParallelism: availableParallelism(),
2935
+ cpuCount: processors.length,
2936
+ cpuModel: processors[0]?.model ?? null,
2937
+ gitDirty: status === null ? null : status.length > 0,
2938
+ gitHead: gitValue(gitDirectory, ["rev-parse", "HEAD"]),
2939
+ node: process.version,
2940
+ osRelease: release(),
2941
+ platform: platform(),
2942
+ totalMemoryBytes: totalmem(),
2943
+ vitest: vitestVersion
2944
+ };
2945
+ };
2946
+ const spawnVitest = async ({ cwd, maxWorkers, reportPath, stdio }) => {
2947
+ const vitestCli = path.join(path.dirname(resolveVitestPackage(cwd)), "vitest.mjs");
2948
+ const started = performance.now();
2949
+ const child = spawn(process.execPath, [
2950
+ vitestCli,
2951
+ "run",
2952
+ "--reporter=json",
2953
+ `--outputFile=${reportPath}`,
2954
+ `--maxWorkers=${maxWorkers}`
2955
+ ], {
2956
+ cwd,
2957
+ stdio
2958
+ });
2959
+ let timedOut = false;
2960
+ let forceKillTimer;
2961
+ const timeoutTimer = setTimeout(() => {
2962
+ timedOut = true;
2963
+ child.kill("SIGTERM");
2964
+ forceKillTimer = setTimeout(() => {
2965
+ child.kill("SIGKILL");
2966
+ }, TERMINATION_GRACE_MS);
2967
+ }, RUN_TIMEOUT_MS);
2968
+ let exitCode = 0;
2969
+ let failure = null;
2970
+ try {
2971
+ const [code, signal] = await once(child, "exit");
2972
+ exitCode = code ?? (signal ? 1 : 0);
2973
+ } catch (error) {
2974
+ exitCode = 1;
2975
+ failure = `Vitest could not start: ${error instanceof Error ? error.message : String(error)}`;
2976
+ } finally {
2977
+ clearTimeout(timeoutTimer);
2978
+ if (forceKillTimer) clearTimeout(forceKillTimer);
2979
+ }
2980
+ if (timedOut) failure = `Vitest profile sample exceeded ${RUN_TIMEOUT_MS}ms and was terminated.`;
2981
+ let report = null;
2982
+ try {
2983
+ report = JSON.parse(await readFile(reportPath, "utf-8"));
2984
+ } catch (error) {
2985
+ const reportFailure = `Vitest JSON report unavailable: ${error instanceof Error ? error.message : String(error)}`;
2986
+ failure = failure ? `${failure} ${reportFailure}` : reportFailure;
2987
+ }
2988
+ return {
2989
+ durationMs: Math.max(0, performance.now() - started),
2990
+ exitCode: timedOut ? 1 : exitCode,
2991
+ failure,
2992
+ report
2993
+ };
2994
+ };
2995
+ /**
2996
+ * Write a profile document atomically: a partial file must never be readable
2997
+ * as a complete measurement, and the profile is rewritten after every sample.
2998
+ */
2999
+ const writeVitestProfile = async (outputPath, profile) => {
3000
+ await mkdir(path.dirname(outputPath), { recursive: true });
3001
+ const temporaryPath = `${outputPath}.tmp`;
3002
+ await writeFile(temporaryPath, `${JSON.stringify(profile, null, 2)}\n`, "utf-8");
3003
+ await rename(temporaryPath, outputPath);
3004
+ };
3005
+ /**
3006
+ * Take `samples` serial Vitest runs at one worker count and persist the profile
3007
+ * after each one. Samples never overlap: concurrent runs would measure CPU and
3008
+ * I/O contention instead of the worker count under test. A failing sample
3009
+ * throws `VitestProfileError` with the partial profile already written.
3010
+ */
3011
+ const runVitestProfile = async (options, dependencies = {}) => {
3012
+ if (!Number.isSafeInteger(options.samples) || options.samples < 1) throw new Error("runVitestProfile: samples must be a positive integer.");
3013
+ const now = dependencies.now ?? (() => /* @__PURE__ */ new Date());
3014
+ const runSample = dependencies.runSample ?? spawnVitest;
3015
+ const writeResult = dependencies.writeResult ?? writeVitestProfile;
3016
+ const startedAt = now();
3017
+ const rawRoot = path.join(`${options.outputPath}.raw`, randomUUID());
3018
+ await mkdir(rawRoot, { recursive: true });
3019
+ const profile = {
3020
+ command: [
3021
+ "vitest",
3022
+ "run",
3023
+ "--reporter=json",
3024
+ `--maxWorkers=${options.maxWorkers}`
3025
+ ],
3026
+ endedAt: startedAt.toISOString(),
3027
+ environment: await captureVitestProfileEnvironment({
3028
+ cwd: options.cwd,
3029
+ gitDirectory: options.gitDirectory
3030
+ }),
3031
+ options: {
3032
+ maxWorkers: options.maxWorkers,
3033
+ samples: options.samples,
3034
+ slowLimit: options.slowLimit
3035
+ },
3036
+ rawReportDirectory: rawRoot,
3037
+ runs: [],
3038
+ schemaVersion: 1,
3039
+ startedAt: startedAt.toISOString(),
3040
+ summary: {
3041
+ durationMs: {
3042
+ maximum: 0,
3043
+ mean: 0,
3044
+ median: 0,
3045
+ minimum: 0
3046
+ },
3047
+ slowFiles: [],
3048
+ slowTests: []
3049
+ },
3050
+ tool: VITEST_PROFILE_TOOL
3051
+ };
3052
+ for (let sample = 1; sample <= options.samples; sample += 1) {
3053
+ let hookFailure;
3054
+ try {
3055
+ options.onSampleStart?.({
3056
+ maxWorkers: options.maxWorkers,
3057
+ sample,
3058
+ samples: options.samples
3059
+ });
3060
+ } catch (error) {
3061
+ hookFailure = { error };
3062
+ }
3063
+ const sampleStartedAt = now();
3064
+ const reportPath = path.join(rawRoot, `sample-${sample}.json`);
3065
+ const execution = await runSample({
3066
+ cwd: options.cwd,
3067
+ maxWorkers: options.maxWorkers,
3068
+ reportPath,
3069
+ sample,
3070
+ stdio: options.stdio ?? "inherit"
3071
+ });
3072
+ const sampleEndedAt = now();
3073
+ const normalized = normalizeVitestProfileSample(execution.report, {
3074
+ cwd: options.cwd,
3075
+ durationMs: execution.durationMs,
3076
+ endedAt: sampleEndedAt,
3077
+ exitCode: execution.exitCode,
3078
+ failure: execution.failure,
3079
+ sample,
3080
+ startedAt: sampleStartedAt
3081
+ });
3082
+ profile.runs.push(normalized);
3083
+ profile.endedAt = sampleEndedAt.toISOString();
3084
+ profile.summary = {
3085
+ durationMs: durationSummary(profile.runs.map((run) => run.durationMs)),
3086
+ slowFiles: aggregateSlowFiles(profile.runs, options.slowLimit),
3087
+ slowTests: aggregateSlowTests(profile.runs, options.slowLimit)
3088
+ };
3089
+ await writeResult(options.outputPath, profile);
3090
+ try {
3091
+ options.onSampleComplete?.({
3092
+ result: normalized,
3093
+ sample,
3094
+ samples: options.samples
3095
+ });
3096
+ } catch (error) {
3097
+ hookFailure ??= { error };
3098
+ }
3099
+ if (execution.exitCode !== 0 || execution.report?.success !== true) throw new VitestProfileError(`Vitest profile sample ${sample} failed; partial results saved.`, execution.exitCode || 1);
3100
+ if (hookFailure) throw hookFailure.error;
3101
+ }
3102
+ return profile;
3103
+ };
3104
+ //#endregion
3105
+ //#region src/vitest-profile-reader.ts
3106
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3107
+ const isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
3108
+ const durationSummaryFailure = (value, where) => {
3109
+ if (!isRecord(value)) return `${where} is not an object`;
3110
+ const missing = [
3111
+ "maximum",
3112
+ "mean",
3113
+ "median",
3114
+ "minimum"
3115
+ ].find((field) => !isFiniteNumber(value[field]));
3116
+ return missing === void 0 ? void 0 : `${where}.${missing} is not a finite number`;
3117
+ };
3118
+ const environmentFailure = (value) => {
3119
+ if (!isRecord(value)) return "environment is not an object";
3120
+ if (!(typeof value.cpuModel === "string" || value.cpuModel === null)) return "environment.cpuModel is neither a string nor null";
3121
+ if (!isFiniteNumber(value.cpuCount)) return "environment.cpuCount is not a finite number";
3122
+ };
3123
+ /** The count fields the writer emits; every one must be a finite number. */
3124
+ const COUNT_FIELDS = [
3125
+ "failed",
3126
+ "passed",
3127
+ "pending",
3128
+ "suites",
3129
+ "tests",
3130
+ "todo"
3131
+ ];
3132
+ const runFailure = (value, index) => {
3133
+ if (!isRecord(value)) return `runs[${index}] is not an object`;
3134
+ if (!isFiniteNumber(value.durationMs)) return `runs[${index}].durationMs is not a finite number`;
3135
+ if (value.counts === null) return;
3136
+ if (!isRecord(value.counts)) return `runs[${index}].counts is neither an object nor null`;
3137
+ const { counts } = value;
3138
+ const missing = COUNT_FIELDS.find((field) => !isFiniteNumber(counts[field]));
3139
+ return missing === void 0 ? void 0 : `runs[${index}].counts.${missing} is not a finite number`;
3140
+ };
3141
+ const slowEntryFailure = (value, where, labelField) => {
3142
+ if (!isRecord(value)) return `${where} is not an object`;
3143
+ if (typeof value[labelField] !== "string") return `${where}.${labelField} is not a string`;
3144
+ if (labelField === "name" && typeof value.file !== "string") return `${where}.file is not a string`;
3145
+ return durationSummaryFailure(value.durationMs, `${where}.durationMs`);
3146
+ };
3147
+ const summaryFailure = (value) => {
3148
+ if (!isRecord(value)) return "summary is not an object";
3149
+ const durations = durationSummaryFailure(value.durationMs, "summary.durationMs");
3150
+ if (durations !== void 0) return durations;
3151
+ if (!Array.isArray(value.slowFiles)) return "summary.slowFiles is not an array";
3152
+ for (const [index, entry] of value.slowFiles.entries()) {
3153
+ const failure = slowEntryFailure(entry, `summary.slowFiles[${index}]`, "path");
3154
+ if (failure !== void 0) return failure;
3155
+ }
3156
+ if (!Array.isArray(value.slowTests)) return "summary.slowTests is not an array";
3157
+ for (const [index, entry] of value.slowTests.entries()) {
3158
+ const failure = slowEntryFailure(entry, `summary.slowTests[${index}]`, "name");
3159
+ if (failure !== void 0) return failure;
3160
+ }
3161
+ };
3162
+ /**
3163
+ * Check one parsed JSON document against the profile contract the writer
3164
+ * emits. Returns the typed profile on success and the first mismatch reason
3165
+ * otherwise — never a partially-usable value.
3166
+ */
3167
+ const readVitestProfileDocument = (value) => {
3168
+ if (!isRecord(value)) return {
3169
+ kind: "unrecognized",
3170
+ reason: "the document is not an object"
3171
+ };
3172
+ if (value.tool !== "factory-ci-vitest-profile") return {
3173
+ kind: "unrecognized",
3174
+ reason: `tool is ${JSON.stringify(value.tool)} rather than "${VITEST_PROFILE_TOOL}"`
3175
+ };
3176
+ if (value.schemaVersion !== 1) return {
3177
+ kind: "unrecognized",
3178
+ reason: `schemaVersion is ${JSON.stringify(value.schemaVersion)} rather than 1`
3179
+ };
3180
+ if (!(Array.isArray(value.command) && value.command.every((part) => typeof part === "string"))) return {
3181
+ kind: "unrecognized",
3182
+ reason: "command is not an array of strings"
3183
+ };
3184
+ const environment = environmentFailure(value.environment);
3185
+ if (environment !== void 0) return {
3186
+ kind: "unrecognized",
3187
+ reason: environment
3188
+ };
3189
+ if (!isRecord(value.options)) return {
3190
+ kind: "unrecognized",
3191
+ reason: "options is not an object"
3192
+ };
3193
+ if (!isFiniteNumber(value.options.maxWorkers)) return {
3194
+ kind: "unrecognized",
3195
+ reason: "options.maxWorkers is not a finite number"
3196
+ };
3197
+ if (!Array.isArray(value.runs)) return {
3198
+ kind: "unrecognized",
3199
+ reason: "runs is not an array"
3200
+ };
3201
+ for (const [index, run] of value.runs.entries()) {
3202
+ const failure = runFailure(run, index);
3203
+ if (failure !== void 0) return {
3204
+ kind: "unrecognized",
3205
+ reason: failure
3206
+ };
3207
+ }
3208
+ const summary = summaryFailure(value.summary);
3209
+ if (summary !== void 0) return {
3210
+ kind: "unrecognized",
3211
+ reason: summary
3212
+ };
3213
+ return {
3214
+ kind: "profile",
3215
+ profile: value
3216
+ };
3217
+ };
3218
+ //#endregion
3219
+ //#region src/verify-runner-policy.ts
3220
+ const DEPOT_LABEL = "depot-ubuntu-24.04";
3221
+ const HOSTED_LABEL = "ubuntu-latest";
3222
+ const isOverride = (decision) => typeof decision === "object";
3223
+ const homeForKind = (kind) => {
3224
+ switch (kind) {
3225
+ case "sustained-compute":
3226
+ case "rounding-tax": return "depot";
3227
+ case "app-token":
3228
+ case "deploy-credentials": return "hosted";
3229
+ default: return kind;
3230
+ }
3231
+ };
3232
+ const labelForHome = (home) => home === "depot" ? DEPOT_LABEL : HOSTED_LABEL;
3233
+ const assertOverrideWhy = (why) => {
3234
+ if (why.includes("\n") || why.includes("\r") || why.trim().length === 0) throw new Error("factoryVerifyRunner override requires a non-empty single-line why");
3235
+ };
3236
+ const factoryVerifyRunner = (decision) => {
3237
+ if (isOverride(decision)) {
3238
+ assertOverrideWhy(decision.why);
3239
+ return Object.freeze({
3240
+ decision,
3241
+ home: decision.home,
3242
+ label: labelForHome(decision.home),
3243
+ why: decision.why
3244
+ });
3245
+ }
3246
+ const home = homeForKind(decision);
3247
+ return Object.freeze({
3248
+ decision,
3249
+ home,
3250
+ label: labelForHome(home)
3251
+ });
3252
+ };
3253
+ const indentOf$1 = (line) => line.length - line.trimStart().length;
3254
+ const unquote$1 = (raw) => {
3255
+ const value = raw.trim();
3256
+ if (value.startsWith("'") && value.endsWith("'") && value.length > 1) return value.slice(1, -1).replaceAll("''", "'");
3257
+ if (value.startsWith("\"") && value.endsWith("\"") && value.length > 1) return value.slice(1, -1);
3258
+ return value;
3259
+ };
3260
+ const JOB_ID = /^[\w-]+$/u;
3261
+ const MATRIX_EXPRESSION = /\$\{\{\s*matrix\b/u;
3262
+ const throwNonScalarRunsOn = (jobId) => {
3263
+ throw new Error(`job ${jobId} uses a list, group, or matrix runs-on; Verify policy accepts a scalar label only`);
3264
+ };
3265
+ const verifyWorkflowJobRunners = (yaml) => {
3266
+ const lines = yaml.split("\n");
3267
+ const jobsLine = lines.findIndex((line) => line.trim() === "jobs:");
3268
+ if (jobsLine === -1) return {};
3269
+ const jobsIndent = indentOf$1(lines[jobsLine]);
3270
+ const jobIdIndent = jobsIndent + 2;
3271
+ const jobKeyIndent = jobIdIndent + 2;
3272
+ const runners = {};
3273
+ for (let index = jobsLine + 1; index < lines.length; index += 1) {
3274
+ const line = lines[index];
3275
+ if (line.trim().length === 0) continue;
3276
+ const indent = indentOf$1(line);
3277
+ if (indent <= jobsIndent) break;
3278
+ if (indent !== jobIdIndent) continue;
3279
+ const trimmed = line.trim();
3280
+ if (!trimmed.endsWith(":") || trimmed.includes(" ")) continue;
3281
+ const jobId = trimmed.slice(0, -1);
3282
+ if (!JOB_ID.test(jobId)) continue;
3283
+ let runsOn;
3284
+ for (let cursor = index + 1; cursor < lines.length; cursor += 1) {
3285
+ const candidate = lines[cursor];
3286
+ if (candidate.trim().length === 0) continue;
3287
+ const candidateIndent = indentOf$1(candidate);
3288
+ if (candidateIndent <= jobIdIndent) break;
3289
+ if (candidateIndent !== jobKeyIndent) continue;
3290
+ const rest = candidate.trimStart();
3291
+ if (!rest.startsWith("runs-on:")) continue;
3292
+ const inline = rest.slice(8).trim();
3293
+ if (inline.length === 0) throwNonScalarRunsOn(jobId);
3294
+ if (inline.startsWith("[") || inline.startsWith("{")) throwNonScalarRunsOn(jobId);
3295
+ const label = unquote$1(inline);
3296
+ if (MATRIX_EXPRESSION.test(label)) throwNonScalarRunsOn(jobId);
3297
+ runsOn = label;
3298
+ break;
3299
+ }
3300
+ if (runsOn === void 0) throw new Error(`job ${jobId} has no runs-on`);
3301
+ runners[jobId] = runsOn;
3302
+ }
3303
+ return runners;
3304
+ };
3305
+ const isDeployCredentials = (runner) => runner.decision === "deploy-credentials";
3306
+ const verifyRunnerPolicy = (yaml, input) => {
3307
+ const actual = verifyWorkflowJobRunners(yaml);
3308
+ const declared = Object.keys(input.jobs);
3309
+ const undeclared = Object.keys(actual).filter((jobId) => input.jobs[jobId] === void 0).toSorted();
3310
+ const missing = declared.filter((jobId) => actual[jobId] === void 0).toSorted();
3311
+ const mismatches = declared.filter((jobId) => actual[jobId] !== void 0 && actual[jobId] !== input.jobs[jobId].label).toSorted().map((jobId) => ({
3312
+ actual: actual[jobId],
3313
+ expected: input.jobs[jobId].label,
3314
+ jobId
3315
+ }));
3316
+ const forbiddenKinds = declared.filter((jobId) => isDeployCredentials(input.jobs[jobId])).toSorted();
3317
+ return Object.freeze({
3318
+ forbiddenKinds,
3319
+ mismatches,
3320
+ missing,
3321
+ ok: undeclared.length === 0 && missing.length === 0 && mismatches.length === 0 && forbiddenKinds.length === 0,
3322
+ undeclared
3323
+ });
3324
+ };
3325
+ const assertVerifyRunnerPolicy = (yaml, input) => {
3326
+ const report = verifyRunnerPolicy(yaml, input);
3327
+ if (report.ok) return report;
3328
+ const details = [];
3329
+ if (report.undeclared.length > 0) details.push(`undeclared jobs: ${report.undeclared.join(", ")}`);
3330
+ if (report.missing.length > 0) details.push(`missing from YAML: ${report.missing.join(", ")}`);
3331
+ for (const mismatch of report.mismatches) details.push(`${mismatch.jobId} runs-on ${mismatch.actual}, expected ${mismatch.expected}`);
3332
+ if (report.forbiddenKinds.length > 0) details.push(`deploy-credentials is illegal inside Verify: ${report.forbiddenKinds.join(", ")}`);
3333
+ throw new Error(`${input.source} Verify runner policy failed:\n${details.map((detail) => ` - ${detail}`).join("\n")}`);
3334
+ };
3335
+ //#endregion
901
3336
  //#region src/workflow-shell-lint.ts
902
3337
  const RUN_KEY = /^(?<indent>\s*)(?:-\s+)?run:(?<inline>.*)$/u;
903
3338
  /**
@@ -1162,4 +3597,4 @@ const assertWorkflowShellParses = (yaml, options) => {
1162
3597
  throw new Error(`${options.source} emits shell bash cannot parse; the runner would treat it as a no-op:\n${detail}`);
1163
3598
  };
1164
3599
  //#endregion
1165
- export { 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_STEP_ID, GitHubApiError, NODE_PNPM_ACTION_FAMILY_NODE24, assertProofReuseCoverage, assertWorkflowShellParses, bundleAlchemyEntry, executeAlchemyEntry, factoryProofGateScript, factoryProofGateStep, factoryWorkflow, githubAppJwt, isLocalPreviewStage, localPreviewStage, mintInstallationToken, parseLocalPreviewStage, proofReuseCoverage, proofReuseRequiredCommands, workflowRunBlocks, workflowShellParseFailures };
3600
+ export { ALCHEMY_BASELINE, EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER, 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_AUDIT_JOB_ID, FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_NAME, 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_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, assertAlchemyBaseline, assertProofReuseCoverage, assertVerifyRunnerPolicy, assertWorkflowShellParses, bundleAlchemyEntry, captureVitestProfileEnvironment, executeAlchemyEntry, factoryCandidateImpactWorkflow, factoryCandidateOrPushCondition, factoryLifecycleContractLane, factoryMergeFreezeJob, factoryMergeFreezeScript, factoryPrStatusHudWorkflow, factoryPreviewCleanupTopology, factoryPreviewReceiptWorkflow, factoryProductionImpactWorkflow, factoryProofGateScript, factoryProofGateStep, factoryProofReuseSummaryStep, factoryProofTimingStartStep, factoryPushIdentityConsumer, factoryPushIdentityProducer, factoryVerifyRunner, factoryWorkflow, githubAppJwt, isLocalPreviewStage, localPreviewStage, mintInstallationToken, normalizeVitestProfileSample, parseLocalPreviewStage, previewCleanupDestroyJobId, previewProofInventory, previewProofLifecycle, productionImpactTargetOutput, proofReuseCoverage, proofReuseRequiredCommands, readVitestProfileDocument, resolveProofReuseCommands, runVitestProfile, setupStepsForRoles, verifyRunnerPolicy, workflowRunBlocks, workflowShellParseFailures, writeVitestProfile };