@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
@@ -0,0 +1,328 @@
1
+ import { parseLocalPreviewStage } from "./disposable-stage.ts";
2
+ import type { LocalPreviewStage } from "./disposable-stage.ts";
3
+
4
+ /**
5
+ * Preview-proof lifecycle: admit a disposable preview, register envelope-bound
6
+ * proof at head, and record cleanup. One `transition` path owns those state
7
+ * changes. Recovery (#766) re-enters cleanup through the same event. Hosted
8
+ * inventory listing and cleanup-outcome persistence live in
9
+ * `previewProofInventory`, which sits on the registration read model `resolve`
10
+ * already returns.
11
+ *
12
+ * Proof sits entirely on one side of GitHub's draft/ready boundary
13
+ * (paitronage#1089): a draft candidate cannot begin or register. Machine
14
+ * evidence is the envelope at head (#355), never a PR comment. The SHA and
15
+ * repository bind that proof (#1312): a detached HEAD or a branch name that
16
+ * differs from the PR head is the same commit, and the registration records
17
+ * `branch: "(detached)"`.
18
+ */
19
+
20
+ export type PreviewProofCleanupStatus = "failed" | "passed" | "pending";
21
+
22
+ export interface PreviewProofCandidate {
23
+ readonly branch: string;
24
+ readonly dirty: boolean;
25
+ readonly headSha: string;
26
+ readonly isDraft: boolean;
27
+ readonly pr: number;
28
+ readonly prHeadRef: string;
29
+ readonly prHeadSha: string;
30
+ readonly prRepository: string;
31
+ readonly prState: "CLOSED" | "MERGED" | "OPEN";
32
+ readonly repository: string;
33
+ }
34
+
35
+ export interface PreviewProofEnvelopeEvidence {
36
+ readonly check: string;
37
+ readonly headSha: string;
38
+ readonly mergeBaseSha: string;
39
+ readonly outcome: "fail" | "pass";
40
+ readonly patchId: string;
41
+ }
42
+
43
+ export interface PreviewProofCleanupOutcome {
44
+ readonly evidence: readonly string[];
45
+ readonly outcome: Exclude<PreviewProofCleanupStatus, "pending">;
46
+ readonly runUrl?: string;
47
+ }
48
+
49
+ export interface PreviewProofRegistration {
50
+ /**
51
+ * Present only when the checkout is detached or its branch name is not the
52
+ * PR head. The `(detached)` sentinel is on the lifecycle registration
53
+ * `transition` returns, and `previewProofInventory` does not persist it.
54
+ * It is not a branch to check out.
55
+ */
56
+ readonly branch?: "(detached)";
57
+ readonly cleanup: {
58
+ readonly evidence: readonly string[];
59
+ readonly outcome: PreviewProofCleanupStatus;
60
+ readonly runUrl?: string;
61
+ };
62
+ readonly convergence: { readonly detail: string; readonly status: "passed" };
63
+ readonly headSha: string;
64
+ readonly pr: number;
65
+ readonly proof: {
66
+ readonly check: string;
67
+ readonly headSha: string;
68
+ readonly mergeBaseSha: string;
69
+ readonly patchId: string;
70
+ };
71
+ readonly smoke: { readonly detail: string; readonly outcome: "passed" };
72
+ readonly source: "local-self-certified";
73
+ readonly stack: string;
74
+ readonly stage: LocalPreviewStage;
75
+ readonly url: string;
76
+ }
77
+
78
+ export interface PreviewProofLifecycleState {
79
+ readonly registrations: readonly PreviewProofRegistration[];
80
+ }
81
+
82
+ export type PreviewProofLifecycleEvent =
83
+ | {
84
+ readonly candidate: PreviewProofCandidate;
85
+ readonly stage: string;
86
+ readonly type: "begin";
87
+ }
88
+ | {
89
+ readonly candidate: PreviewProofCandidate;
90
+ readonly convergence: {
91
+ readonly detail: string;
92
+ readonly status: "failed" | "passed";
93
+ };
94
+ readonly evidence: PreviewProofEnvelopeEvidence;
95
+ readonly smoke: {
96
+ readonly detail: string;
97
+ readonly outcome: "failed" | "passed";
98
+ };
99
+ readonly stack: string;
100
+ readonly stage: string;
101
+ readonly type: "register";
102
+ readonly url: string;
103
+ }
104
+ | {
105
+ readonly evidence: readonly string[];
106
+ readonly outcome: Exclude<PreviewProofCleanupStatus, "pending">;
107
+ readonly pr: number;
108
+ readonly runUrl?: string;
109
+ readonly stack: string;
110
+ readonly stage: string;
111
+ readonly type: "cleanup";
112
+ };
113
+
114
+ export interface PreviewProofResolveQuery {
115
+ readonly pr?: number;
116
+ readonly stack?: string;
117
+ readonly stage?: string;
118
+ }
119
+
120
+ const EMPTY_STATE: PreviewProofLifecycleState = Object.freeze({
121
+ registrations: Object.freeze([]),
122
+ });
123
+
124
+ const DETACHED_PROOF_BRANCH = "(detached)" as const;
125
+
126
+ /**
127
+ * The branch name adds no guarantee. Record the sentinel unless the checkout
128
+ * is actually on the PR head branch.
129
+ */
130
+ const proofBranch = (
131
+ candidate: PreviewProofCandidate
132
+ ): typeof DETACHED_PROOF_BRANCH | undefined =>
133
+ candidate.branch.length > 0 && candidate.branch === candidate.prHeadRef
134
+ ? undefined
135
+ : DETACHED_PROOF_BRANCH;
136
+
137
+ const registrationKey = (row: {
138
+ readonly stack: string;
139
+ readonly stage: string;
140
+ }): string => `${row.stack}:${row.stage}`;
141
+
142
+ const disposableStage = (
143
+ stage: string,
144
+ candidate: PreviewProofCandidate
145
+ ): LocalPreviewStage => {
146
+ const parsed = parseLocalPreviewStage(stage, {
147
+ headSha: candidate.headSha,
148
+ pr: candidate.pr,
149
+ });
150
+ if (parsed === null) {
151
+ throw new Error(
152
+ `Preview proof stage must be a disposable local-pr stage owned by PR #${candidate.pr} at this head.`
153
+ );
154
+ }
155
+ return parsed.stage;
156
+ };
157
+
158
+ const assertAdmissibleCandidate = (
159
+ candidate: PreviewProofCandidate,
160
+ stage: string
161
+ ): LocalPreviewStage => {
162
+ if (candidate.isDraft) {
163
+ throw new Error(
164
+ `PR #${candidate.pr} is a draft; preview proof registers only after the pull request is marked ready for review.`
165
+ );
166
+ }
167
+ if (candidate.prState !== "OPEN") {
168
+ throw new Error("Preview proof requires an open pull request.");
169
+ }
170
+
171
+ const errors: string[] = [];
172
+ if (candidate.dirty) {
173
+ errors.push("Worktree must be clean.");
174
+ }
175
+ if (candidate.headSha !== candidate.prHeadSha) {
176
+ errors.push("HEAD is stale for the current PR head.");
177
+ }
178
+ if (candidate.repository !== candidate.prRepository) {
179
+ errors.push("PR head repository does not match the current repository.");
180
+ }
181
+ if (errors.length > 0) {
182
+ throw new Error(errors.join("\n"));
183
+ }
184
+
185
+ return disposableStage(stage, candidate);
186
+ };
187
+
188
+ const SHA_PATTERN = /^[0-9a-f]{7,40}$/u;
189
+
190
+ const assertPassingEnvelope = (
191
+ evidence: PreviewProofEnvelopeEvidence,
192
+ headSha: string
193
+ ): void => {
194
+ if (
195
+ evidence.outcome !== "pass" ||
196
+ evidence.headSha !== headSha ||
197
+ evidence.check.trim().length === 0 ||
198
+ !SHA_PATTERN.test(evidence.patchId) ||
199
+ !SHA_PATTERN.test(evidence.mergeBaseSha)
200
+ ) {
201
+ throw new Error(
202
+ "Preview proof requires a passing evidence envelope at the candidate head."
203
+ );
204
+ }
205
+ };
206
+
207
+ const replaceRegistration = (
208
+ state: PreviewProofLifecycleState,
209
+ next: PreviewProofRegistration
210
+ ): PreviewProofLifecycleState => {
211
+ const key = registrationKey(next);
212
+ const registrations = [
213
+ ...state.registrations.filter((row) => registrationKey(row) !== key),
214
+ next,
215
+ ];
216
+ return { registrations };
217
+ };
218
+
219
+ const empty = (): PreviewProofLifecycleState => EMPTY_STATE;
220
+
221
+ const resolve = (
222
+ state: PreviewProofLifecycleState,
223
+ query: PreviewProofResolveQuery = {}
224
+ ): readonly PreviewProofRegistration[] =>
225
+ state.registrations.filter(
226
+ (row) =>
227
+ (query.pr === undefined || row.pr === query.pr) &&
228
+ (query.stack === undefined || row.stack === query.stack) &&
229
+ (query.stage === undefined || row.stage === query.stage)
230
+ );
231
+
232
+ const transition = (
233
+ state: PreviewProofLifecycleState,
234
+ event: PreviewProofLifecycleEvent
235
+ ): PreviewProofLifecycleState => {
236
+ if (event.type === "begin") {
237
+ assertAdmissibleCandidate(event.candidate, event.stage);
238
+ return state;
239
+ }
240
+
241
+ if (event.type === "register") {
242
+ const stage = assertAdmissibleCandidate(event.candidate, event.stage);
243
+ if (event.smoke.outcome !== "passed") {
244
+ throw new Error("Preview proof requires passed smoke evidence.");
245
+ }
246
+ if (event.convergence.status !== "passed") {
247
+ throw new Error("Preview proof requires passed convergence evidence.");
248
+ }
249
+ if (!event.stack || !event.url) {
250
+ throw new Error("Preview proof registration requires a stack and URL.");
251
+ }
252
+ assertPassingEnvelope(event.evidence, event.candidate.headSha);
253
+ const branch = proofBranch(event.candidate);
254
+
255
+ return replaceRegistration(state, {
256
+ ...(branch === undefined ? {} : { branch }),
257
+ cleanup: { evidence: [], outcome: "pending" },
258
+ convergence: {
259
+ detail: event.convergence.detail,
260
+ status: "passed",
261
+ },
262
+ headSha: event.candidate.headSha,
263
+ pr: event.candidate.pr,
264
+ proof: {
265
+ check: event.evidence.check,
266
+ headSha: event.evidence.headSha,
267
+ mergeBaseSha: event.evidence.mergeBaseSha,
268
+ patchId: event.evidence.patchId,
269
+ },
270
+ smoke: { detail: event.smoke.detail, outcome: "passed" },
271
+ source: "local-self-certified",
272
+ stack: event.stack,
273
+ stage,
274
+ url: event.url,
275
+ });
276
+ }
277
+
278
+ const existing = state.registrations.find(
279
+ (row) =>
280
+ row.pr === event.pr &&
281
+ row.stack === event.stack &&
282
+ row.stage === event.stage
283
+ );
284
+ if (!existing) {
285
+ throw new Error(
286
+ `Preview proof cleanup requires a registration for ${event.stack}/${event.stage}.`
287
+ );
288
+ }
289
+
290
+ const cleanup =
291
+ event.runUrl === undefined
292
+ ? { evidence: event.evidence, outcome: event.outcome }
293
+ : {
294
+ evidence: event.evidence,
295
+ outcome: event.outcome,
296
+ runUrl: event.runUrl,
297
+ };
298
+
299
+ return replaceRegistration(state, {
300
+ ...existing,
301
+ cleanup,
302
+ });
303
+ };
304
+
305
+ const recover = (
306
+ state: PreviewProofLifecycleState,
307
+ event: Extract<PreviewProofLifecycleEvent, { type: "cleanup" }>
308
+ ): PreviewProofLifecycleState => {
309
+ const existing = state.registrations.find(
310
+ (row) =>
311
+ row.pr === event.pr &&
312
+ row.stack === event.stack &&
313
+ row.stage === event.stage
314
+ );
315
+ if (existing?.cleanup.outcome !== "failed") {
316
+ throw new Error(
317
+ "Preview proof recovery re-enters cleanup only from a failed outcome."
318
+ );
319
+ }
320
+ return transition(state, event);
321
+ };
322
+
323
+ export const previewProofLifecycle = {
324
+ empty,
325
+ recover,
326
+ resolve,
327
+ transition,
328
+ } as const;
@@ -0,0 +1,83 @@
1
+ import type { WorkflowStep } from "./factory-workflow.ts";
2
+ import { assertRunnableCli } from "./runnable-cli.ts";
3
+
4
+ export interface FactoryPreviewReceiptWorkflowOptions {
5
+ readonly target: string;
6
+ readonly cli?: string;
7
+ /** Caller-owned PR number expression, passed through the environment. */
8
+ readonly pr?: string;
9
+ }
10
+
11
+ export interface FactoryPreviewReceiptWorkflow {
12
+ /** Place before the selected target's first mutation, under its selection guard. */
13
+ readonly beginStep: WorkflowStep;
14
+ /** Append after consumer deploy and required smoke steps. Never rename the bind step. */
15
+ readonly completionSteps: readonly WorkflowStep[];
16
+ /** Place before cleanup, including cleanup of a failed/unregistered deployment. */
17
+ readonly invalidateStep: WorkflowStep;
18
+ readonly permissions: Readonly<{
19
+ actions: "read";
20
+ contents: "read";
21
+ deployments: "write";
22
+ "pull-requests": "read";
23
+ }>;
24
+ }
25
+
26
+ /** Receipt transport only. The consumer owns selection, lifecycle, smoke, and freshness. */
27
+ export const factoryPreviewReceiptWorkflow = (
28
+ options: FactoryPreviewReceiptWorkflowOptions
29
+ ): FactoryPreviewReceiptWorkflow => {
30
+ if (!/^preview:[a-z][a-z0-9-]*$/u.test(options.target)) {
31
+ throw new Error("Preview receipts require a declared preview target name.");
32
+ }
33
+ const cli = options.cli ?? "pnpm exec psf";
34
+ assertRunnableCli("cli", cli);
35
+ const id = `preview_intent_${options.target.slice("preview:".length).replaceAll("-", "_")}`;
36
+ const deploymentId = `\${{ steps.${id}.outputs.deployment_id }}`;
37
+ const hasIntent = `steps.${id}.outputs.deployment_id != ''`;
38
+ const env = {
39
+ FACTORY_PREVIEW_PR:
40
+ options.pr ?? `\${{ github.event.pull_request.number }}`,
41
+ GH_TOKEN: `\${{ github.token }}`,
42
+ };
43
+ const command = `${cli} preview:receipt --pr "$FACTORY_PREVIEW_PR" --target '${options.target}'`;
44
+ return Object.freeze({
45
+ beginStep: Object.freeze({
46
+ env,
47
+ id,
48
+ name: `Record preview intent for ${options.target}`,
49
+ run: `${command} --action begin --github-output "$GITHUB_OUTPUT"`,
50
+ }),
51
+ completionSteps: Object.freeze([
52
+ Object.freeze({
53
+ env: { ...env, FACTORY_DEPLOYMENT_ID: deploymentId },
54
+ if: `success() && ${hasIntent}`,
55
+ name: `Complete preview receipt for ${options.target}`,
56
+ run: `${command} --action complete --deployment-id "$FACTORY_DEPLOYMENT_ID" --outcome success`,
57
+ }),
58
+ Object.freeze({
59
+ env: { FACTORY_DEPLOYMENT_ID: deploymentId },
60
+ if: `success() && ${hasIntent}`,
61
+ name: `Bind deployment receipt ${deploymentId}`,
62
+ run: 'test -n "$FACTORY_DEPLOYMENT_ID"',
63
+ }),
64
+ Object.freeze({
65
+ env: { ...env, FACTORY_DEPLOYMENT_ID: deploymentId },
66
+ if: `failure() && ${hasIntent}`,
67
+ name: `Fail preview receipt for ${options.target}`,
68
+ run: `${command} --action complete --deployment-id "$FACTORY_DEPLOYMENT_ID" --outcome failure`,
69
+ }),
70
+ ]),
71
+ invalidateStep: Object.freeze({
72
+ env,
73
+ name: `Invalidate preview receipts for ${options.target}`,
74
+ run: `${command} --action invalidate`,
75
+ }),
76
+ permissions: Object.freeze({
77
+ actions: "read",
78
+ contents: "read",
79
+ deployments: "write",
80
+ "pull-requests": "read",
81
+ } as const),
82
+ });
83
+ };
@@ -0,0 +1,181 @@
1
+ import type { WorkflowStep } from "./factory-workflow.ts";
2
+ import { impactDemandConditions } from "./impact-demand-condition.ts";
3
+ import { assertRunnableCli } from "./runnable-cli.ts";
4
+
5
+ export const FACTORY_PRODUCTION_IMPACT_STEP_ID = "production_impact";
6
+ export const FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT = "decision";
7
+ export const FACTORY_PRODUCTION_IMPACT_BASIS_OUTPUT = "basis";
8
+ export const FACTORY_PRODUCTION_IMPACT_UNSUBSCRIBED_OUTPUT =
9
+ "unsubscribed_paths";
10
+
11
+ const OUTPUT_NAME_PATTERN = /[^a-z0-9_]+/gu;
12
+ const shellQuote = (value: string): string =>
13
+ `'${value.replaceAll("'", `'"'"'`)}'`;
14
+
15
+ /** Stable GitHub-output key for one declared target. */
16
+ export const productionImpactTargetOutput = (targetName: string): string => {
17
+ const normalized = targetName
18
+ .toLowerCase()
19
+ .replaceAll(OUTPUT_NAME_PATTERN, "_")
20
+ .replaceAll(/^_+|_+$/gu, "");
21
+ if (normalized.length === 0) {
22
+ throw new Error(
23
+ `Impact target name "${targetName}" has no output-safe characters.`
24
+ );
25
+ }
26
+ return `target_${normalized}`;
27
+ };
28
+
29
+ export interface FactoryProductionImpactWorkflowOptions {
30
+ /** The checked-out candidate commit. Defaults to `github.sha`. */
31
+ readonly candidate?: string;
32
+ readonly cli?: string;
33
+ readonly profilePath?: string;
34
+ /** Deployment stage the receipts are bound to, when the consumer has one. */
35
+ readonly stage?: string;
36
+ readonly targets: readonly string[];
37
+ }
38
+
39
+ export interface FactoryProductionImpactWorkflow {
40
+ /** Outputs for a caller-owned decision job that subsequent jobs may consume. */
41
+ readonly decisionJobOutputs: Readonly<Record<string, string>>;
42
+ readonly decisionStep: WorkflowStep;
43
+ /**
44
+ * A fail-open cross-job condition: only an explicit usable withdrawal skips
45
+ * work. The decision job id is required.
46
+ */
47
+ readonly demandedIf: (targetName: string, decisionJob: string) => string;
48
+ /** The same fail-open condition for a step in the decision job. */
49
+ readonly demandedIfAtStep: (targetName: string) => string;
50
+ /** Permissions every job that runs the decision step or a receipt step declares for `github.token`. */
51
+ readonly permissions: Readonly<{
52
+ actions: "read";
53
+ contents: "read";
54
+ deployments: "write";
55
+ }>;
56
+ /**
57
+ * The receipt steps a deploy job appends after its deploy and health steps,
58
+ * in order: a success receipt that runs when every earlier step succeeded
59
+ * and outputs the new deployment id; a bind step whose name carries that id
60
+ * and whose presence in GitHub's job record is the reader's proof that this
61
+ * run created that record; and a failure receipt that runs when a step
62
+ * failed. Only a bound success receipt advances the target's baseline. Do
63
+ * not rename or reorder them.
64
+ */
65
+ readonly receiptSteps: (targetName: string) => readonly WorkflowStep[];
66
+ readonly targetOutputs: Readonly<Record<string, string>>;
67
+ }
68
+
69
+ /**
70
+ * Generate the small factory-owned decision seam for a consumer production
71
+ * workflow. Consumers retain jobs, deploy commands, credentials, topology,
72
+ * health checks, and convergence checks; this artifact supplies the decision
73
+ * step, per-target withdrawal conditions, and the receipt steps that record
74
+ * what each deploy job did.
75
+ *
76
+ * The decision step resolves each target's demand from its last trusted
77
+ * successful deployment receipt, never from the push's before commit. The
78
+ * decision checkout needs full history (`fetchDepth: 0`) so the baseline
79
+ * commit is reachable; a shallow checkout keeps every target demanded.
80
+ */
81
+ export const factoryProductionImpactWorkflow = (
82
+ options: FactoryProductionImpactWorkflowOptions
83
+ ): FactoryProductionImpactWorkflow => {
84
+ const targetOutputs = Object.fromEntries(
85
+ options.targets.map((target) => [
86
+ target,
87
+ productionImpactTargetOutput(target),
88
+ ])
89
+ );
90
+ if (new Set(Object.values(targetOutputs)).size !== options.targets.length) {
91
+ throw new Error(
92
+ "Impact target names must map to distinct GitHub output keys."
93
+ );
94
+ }
95
+
96
+ const candidate = options.candidate ?? `\${{ github.sha }}`;
97
+ const cli = options.cli ?? "pnpm exec psf";
98
+ assertRunnableCli("cli", cli);
99
+ const profile = options.profilePath
100
+ ? ` --profile ${shellQuote(options.profilePath)}`
101
+ : "";
102
+ const stage = options.stage ? ` --stage ${shellQuote(options.stage)}` : "";
103
+ const env = {
104
+ FACTORY_CANDIDATE_SHA: candidate,
105
+ GH_TOKEN: `\${{ github.token }}`,
106
+ } as const;
107
+ const decisionStep: WorkflowStep = {
108
+ continueOnError: true,
109
+ env,
110
+ id: FACTORY_PRODUCTION_IMPACT_STEP_ID,
111
+ name: "Resolve production deployment demand",
112
+ run: `${cli} production:impact --candidate "$FACTORY_CANDIDATE_SHA" --github-output "$GITHUB_OUTPUT" --github-summary "$GITHUB_STEP_SUMMARY"${profile}${stage}`,
113
+ };
114
+
115
+ const conditions = impactDemandConditions({
116
+ decisionOutput: FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT,
117
+ label: "production",
118
+ stepId: FACTORY_PRODUCTION_IMPACT_STEP_ID,
119
+ targetOutputs,
120
+ });
121
+
122
+ const receiptSteps = (targetName: string): readonly WorkflowStep[] => {
123
+ const output = targetOutputs[targetName];
124
+ if (output === undefined) {
125
+ throw new Error(`Unknown production impact target "${targetName}".`);
126
+ }
127
+ const successStepId = `receipt_${output}`;
128
+ const deploymentId = `\${{ steps.${successStepId}.outputs.deployment_id }}`;
129
+ return Object.freeze([
130
+ Object.freeze({
131
+ env,
132
+ id: successStepId,
133
+ if: "success()",
134
+ name: `Publish success deployment receipt for ${targetName}`,
135
+ run: `${cli} production:impact --publish-receipt success --target ${shellQuote(targetName)} --candidate "$FACTORY_CANDIDATE_SHA" --github-output "$GITHUB_OUTPUT" --github-summary "$GITHUB_STEP_SUMMARY"${stage}`,
136
+ }),
137
+ // The bind step. Its name is the reader's writer binding: the reader
138
+ // looks up `Bind deployment receipt <id>` in GitHub's job record for
139
+ // the run the receipt names, and `boundReceiptStepName` in
140
+ // software-factory renders that text. The id is server-assigned and
141
+ // known only to the run that created the record, so a copied payload
142
+ // on another record has no bind step.
143
+ Object.freeze({
144
+ env: { FACTORY_DEPLOYMENT_ID: deploymentId },
145
+ if: "success()",
146
+ name: `Bind deployment receipt ${deploymentId}`,
147
+ run: 'test -n "$FACTORY_DEPLOYMENT_ID"',
148
+ }),
149
+ Object.freeze({
150
+ env,
151
+ if: "failure()",
152
+ name: `Publish failure deployment receipt for ${targetName}`,
153
+ run: `${cli} production:impact --publish-receipt failure --target ${shellQuote(targetName)} --candidate "$FACTORY_CANDIDATE_SHA" --github-summary "$GITHUB_STEP_SUMMARY"${stage}`,
154
+ }),
155
+ ]);
156
+ };
157
+
158
+ return Object.freeze({
159
+ decisionJobOutputs: Object.freeze({
160
+ basis: `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${FACTORY_PRODUCTION_IMPACT_BASIS_OUTPUT} }}`,
161
+ decision: `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${FACTORY_PRODUCTION_IMPACT_DECISION_OUTPUT} }}`,
162
+ unsubscribed_paths: `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${FACTORY_PRODUCTION_IMPACT_UNSUBSCRIBED_OUTPUT} }}`,
163
+ ...Object.fromEntries(
164
+ Object.values(targetOutputs).map((output) => [
165
+ output,
166
+ `\${{ steps.${FACTORY_PRODUCTION_IMPACT_STEP_ID}.outputs.${output} }}`,
167
+ ])
168
+ ),
169
+ }),
170
+ decisionStep: Object.freeze(decisionStep),
171
+ demandedIf: conditions.demandedIf,
172
+ demandedIfAtStep: conditions.demandedIfAtStep,
173
+ permissions: Object.freeze({
174
+ actions: "read",
175
+ contents: "read",
176
+ deployments: "write",
177
+ } as const),
178
+ receiptSteps,
179
+ targetOutputs: Object.freeze(targetOutputs),
180
+ });
181
+ };