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

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