@patronage/factory-ci 1.0.0-alpha.43 → 1.0.0-alpha.45

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.
@@ -0,0 +1,422 @@
1
+ import type { PinnedAction } from "./actions.ts";
2
+ import type { WorkflowStep } from "./factory-workflow.ts";
3
+ import { assertPinnedAction } from "./pinned-action.ts";
4
+ import { factoryPreviewCleanupTopology } from "./preview-cleanup-topology.ts";
5
+ import {
6
+ assertPreviewCleanupStackPolicy,
7
+ previewCleanupStackOutputKey,
8
+ } from "./preview-cleanup.ts";
9
+ import type { PreviewCleanupStackPolicy } from "./preview-cleanup.ts";
10
+ import { PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS } from "./preview-proof-inventory.ts";
11
+ import { FACTORY_PROOF_GATE_APP_ID } from "./proof-reuse-gate.ts";
12
+ import { assertRunnableCli } from "./runnable-cli.ts";
13
+
14
+ export const FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID = "discover";
15
+ export const FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_NAME =
16
+ "Discover preview cleanup targets";
17
+ export const FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID = "targets";
18
+ export const FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID = "destroy";
19
+ export const FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID = "factory-app-token";
20
+ export const FACTORY_PREVIEW_CLEANUP_DEFAULT_SWEEP_CRON = "23 6 * * *";
21
+
22
+ /**
23
+ * A closed pull request whose head lives in this repository. A fork's head
24
+ * never reaches a job that holds cleanup credentials.
25
+ */
26
+ export const FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION =
27
+ "github.event_name == 'pull_request_target' && github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository";
28
+
29
+ /**
30
+ * The sweep: the schedule, which GitHub always runs on the default branch,
31
+ * or a manual dispatch from the default branch.
32
+ */
33
+ export const FACTORY_PREVIEW_CLEANUP_SWEEP_CONDITION =
34
+ "github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch))";
35
+
36
+ /**
37
+ * The ref every cleanup job checks out: the default branch's trusted code,
38
+ * never the closed PR's head. Empty on `schedule`, where the checkout
39
+ * already defaults to the default branch.
40
+ */
41
+ export const FACTORY_PREVIEW_CLEANUP_CHECKOUT_REF = `\${{ github.event.repository.default_branch }}`;
42
+
43
+ const RESIDUE_PATH = "$RUNNER_TEMP/factory-preview-cleanup-residue.json";
44
+ const RESIDUE_AFTER_PATH =
45
+ "$RUNNER_TEMP/factory-preview-cleanup-residue-after.json";
46
+ const EVIDENCE_PATH = "$RUNNER_TEMP/factory-preview-cleanup-evidence.txt";
47
+ const ENVIRONMENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/u;
48
+ const CRON_PATTERN = /^\S+(?: \S+){4}$/u;
49
+ /** GitHub refuses a matrix with more than 256 entries. */
50
+ const MATRIX_ENTRY_LIMIT = 256;
51
+
52
+ export interface FactoryPreviewCleanupWorkflowOptions extends PreviewCleanupStackPolicy {
53
+ readonly cli?: string;
54
+ /**
55
+ * The workflow's concurrency group for one destroy. It may read
56
+ * `matrix.stack`, `matrix.stage` and `matrix.pr`. Share it with the
57
+ * consumer's deploy job when a deploy and a destroy must not race.
58
+ */
59
+ readonly concurrencyGroup?: string;
60
+ /** The pinned `actions/create-github-app-token` the caller declared. */
61
+ readonly createGithubAppToken: PinnedAction;
62
+ /**
63
+ * One shell line that destroys `$FACTORY_PREVIEW_CLEANUP_STAGE` of
64
+ * `$FACTORY_PREVIEW_CLEANUP_STACK` and exits non-zero when it did not. It
65
+ * may append evidence lines to `$FACTORY_PREVIEW_CLEANUP_EVIDENCE`.
66
+ */
67
+ readonly destroyCommand: string;
68
+ /**
69
+ * The GitHub environment every job that holds cleanup credentials runs
70
+ * in. Its protection rules, not a production deploy flag, gate cleanup.
71
+ */
72
+ readonly environment: string;
73
+ /**
74
+ * One shell line that prints the consumer's residue as JSON
75
+ * `[{ "stack": …, "stage": … }]` on stdout: Alchemy state and any physical
76
+ * resources the consumer can attribute to a stack and stage.
77
+ */
78
+ readonly residueCommand: string;
79
+ /** The scheduled orphan sweep. Pass `false` to generate PR-close cleanup only. */
80
+ readonly sweep?:
81
+ | false
82
+ | {
83
+ /** Defaults to `FACTORY_PREVIEW_CLEANUP_DEFAULT_SWEEP_CRON`. */
84
+ readonly cron?: string;
85
+ /**
86
+ * Targets per sweep run. Defaults to 50. Stages are taken whole, so a
87
+ * run exceeds it only when its first stage has more stacks than this.
88
+ */
89
+ readonly maxTargets?: number;
90
+ };
91
+ }
92
+
93
+ export interface FactoryPreviewCleanupWorkflowJob {
94
+ readonly environment: string;
95
+ readonly if: string;
96
+ readonly jobId: string;
97
+ readonly jobName: string;
98
+ readonly permissions: Readonly<Record<string, "read" | "write">>;
99
+ /** Append after the caller's setup steps. */
100
+ readonly steps: readonly WorkflowStep[];
101
+ }
102
+
103
+ export interface FactoryPreviewCleanupWorkflowDiscoverJob extends FactoryPreviewCleanupWorkflowJob {
104
+ readonly outputs: Readonly<Record<string, string>>;
105
+ }
106
+
107
+ export interface FactoryPreviewCleanupWorkflowDestroyJob extends FactoryPreviewCleanupWorkflowJob {
108
+ readonly concurrency: {
109
+ readonly cancelInProgress: false;
110
+ readonly group: string;
111
+ };
112
+ /** Always the discover job's id. */
113
+ readonly needs: readonly string[];
114
+ readonly stack: string;
115
+ readonly strategy: {
116
+ readonly failFast: false;
117
+ readonly matrix: { readonly include: string };
118
+ };
119
+ }
120
+
121
+ export interface FactoryPreviewCleanupWorkflowAuditJob extends FactoryPreviewCleanupWorkflowJob {
122
+ /** Merge into the job's own `env` alongside the caller's credentials. */
123
+ readonly env: Readonly<Record<string, string>>;
124
+ /** The discover job, then every destroy job. */
125
+ readonly needs: readonly string[];
126
+ }
127
+
128
+ export interface FactoryPreviewCleanupWorkflow {
129
+ readonly auditJob: FactoryPreviewCleanupWorkflowAuditJob;
130
+ /** Pass to the checkout step of every job. */
131
+ readonly checkoutRef: typeof FACTORY_PREVIEW_CLEANUP_CHECKOUT_REF;
132
+ readonly destroyJobs: readonly FactoryPreviewCleanupWorkflowDestroyJob[];
133
+ readonly discoverJob: FactoryPreviewCleanupWorkflowDiscoverJob;
134
+ readonly on: Readonly<Record<string, unknown>>;
135
+ readonly permissions: Readonly<{ contents: "read" }>;
136
+ }
137
+
138
+ const shellQuote = (value: string): string =>
139
+ `'${value.replaceAll("'", `'"'"'`)}'`;
140
+
141
+ const assertSingleLine = (name: string, value: string): void => {
142
+ if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) {
143
+ throw new Error(`${name} must be a single non-empty line.`);
144
+ }
145
+ };
146
+
147
+ const policyFlags = (policy: PreviewCleanupStackPolicy): string =>
148
+ [
149
+ ...policy.stacks.map((stack) => `--stack ${shellQuote(stack)}`),
150
+ ...Object.entries(policy.stackAliases ?? {})
151
+ .toSorted(([left], [right]) => left.localeCompare(right))
152
+ .map(
153
+ ([alias, stack]) => `--stack-alias ${shellQuote(`${alias}=${stack}`)}`
154
+ ),
155
+ ...(policy.hostedStagePrefix === undefined
156
+ ? []
157
+ : [`--hosted-stage-prefix ${shellQuote(policy.hostedStagePrefix)}`]),
158
+ ].join(" ");
159
+
160
+ const discoverScript = (
161
+ cli: string,
162
+ flags: string,
163
+ sweep: FactoryPreviewCleanupWorkflowOptions["sweep"]
164
+ ): string => {
165
+ const prMode = `${cli} preview:cleanup --action discover --pr "$FACTORY_PREVIEW_CLEANUP_PR" --residue "${RESIDUE_PATH}" ${flags} --github-output "$GITHUB_OUTPUT"`;
166
+ if (sweep === false) {
167
+ return prMode;
168
+ }
169
+ const maxTargets =
170
+ sweep?.maxTargets === undefined ? "" : ` --max-targets ${sweep.maxTargets}`;
171
+ return [
172
+ 'if [ "$GITHUB_EVENT_NAME" = pull_request_target ]; then',
173
+ ` ${prMode}`,
174
+ "else",
175
+ ` ${cli} preview:cleanup --action sweep --residue "${RESIDUE_PATH}" ${flags}${maxTargets} --github-output "$GITHUB_OUTPUT"`,
176
+ "fi",
177
+ ].join("\n");
178
+ };
179
+
180
+ const destroyScript = (destroyCommand: string): string =>
181
+ [
182
+ `evidence="${EVIDENCE_PATH}"`,
183
+ ': > "$evidence"',
184
+ 'export FACTORY_PREVIEW_CLEANUP_EVIDENCE="$evidence"',
185
+ 'echo "evidence=$evidence" >> "$GITHUB_OUTPUT"',
186
+ 'target="$FACTORY_PREVIEW_CLEANUP_STACK/$FACTORY_PREVIEW_CLEANUP_STAGE"',
187
+ `if ( ${destroyCommand} ); then`,
188
+ ' echo "destroy exited 0 for $target" >> "$evidence"',
189
+ ' echo "outcome=passed" >> "$GITHUB_OUTPUT"',
190
+ "else",
191
+ " status=$?",
192
+ ' echo "destroy exited $status for $target; the stage may remain and the stage residue audit decides" >> "$evidence"',
193
+ ' echo "outcome=failed" >> "$GITHUB_OUTPUT"',
194
+ "fi",
195
+ 'cat "$evidence"',
196
+ 'cat "$evidence" >> "$GITHUB_STEP_SUMMARY"',
197
+ ].join("\n");
198
+
199
+ /**
200
+ * Generate the factory-owned closed-PR preview cleanup and orphan sweep
201
+ * (#1540) on top of `factoryPreviewCleanupTopology`:
202
+ *
203
+ * - `discover` reads the consumer's residue and, for a closed same-repo PR,
204
+ * unites it with the PR's inventory registrations; for the sweep, keeps the
205
+ * residue of PRs GitHub reports closed. It publishes one matrix per stack.
206
+ * - one destroy job per stack runs the consumer's destroy for each matrix
207
+ * target, then records the outcome on the inventory with the Factory App.
208
+ * - one stage-wide audit re-reads the residue after every destroy and fails
209
+ * if any target stage remains, in any stack.
210
+ *
211
+ * Every credentialed job runs in the consumer's GitHub environment, never
212
+ * behind a production deploy flag. The caller prepends its own setup steps
213
+ * (checked out at `checkoutRef`), and adds `runsOn` and credential `env`.
214
+ */
215
+ export const factoryPreviewCleanupWorkflow = (
216
+ options: FactoryPreviewCleanupWorkflowOptions
217
+ ): FactoryPreviewCleanupWorkflow => {
218
+ assertPreviewCleanupStackPolicy(options);
219
+ assertPinnedAction(
220
+ "createGithubAppToken",
221
+ options.createGithubAppToken,
222
+ "actions/create-github-app-token"
223
+ );
224
+ const cli = options.cli ?? "pnpm exec psf";
225
+ assertRunnableCli("cli", cli);
226
+ assertSingleLine("cli", cli);
227
+ assertSingleLine("residueCommand", options.residueCommand);
228
+ assertSingleLine("destroyCommand", options.destroyCommand);
229
+ if (!ENVIRONMENT_PATTERN.test(options.environment)) {
230
+ throw new Error(
231
+ "environment must name the GitHub environment that gates cleanup credentials."
232
+ );
233
+ }
234
+ const { sweep } = options;
235
+ const cron =
236
+ sweep === false
237
+ ? undefined
238
+ : (sweep?.cron ?? FACTORY_PREVIEW_CLEANUP_DEFAULT_SWEEP_CRON);
239
+ if (cron !== undefined && !CRON_PATTERN.test(cron)) {
240
+ throw new Error(`sweep.cron must have five fields, got "${cron}".`);
241
+ }
242
+ const maxTargets = sweep === false ? undefined : sweep?.maxTargets;
243
+ if (
244
+ maxTargets !== undefined &&
245
+ (!Number.isInteger(maxTargets) ||
246
+ maxTargets < 1 ||
247
+ maxTargets > MATRIX_ENTRY_LIMIT)
248
+ ) {
249
+ throw new Error(
250
+ `sweep.maxTargets must be an integer from 1 through ${MATRIX_ENTRY_LIMIT}, got ${maxTargets}.`
251
+ );
252
+ }
253
+ const concurrencyGroup =
254
+ options.concurrencyGroup ??
255
+ `factory-preview-cleanup-\${{ github.repository }}-\${{ matrix.stack }}-\${{ matrix.stage }}`;
256
+ assertSingleLine("concurrencyGroup", concurrencyGroup);
257
+
258
+ const flags = policyFlags(options);
259
+ const discoverIf =
260
+ sweep === false
261
+ ? FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION
262
+ : `(${FACTORY_PREVIEW_CLEANUP_PR_CLOSED_CONDITION}) || (${FACTORY_PREVIEW_CLEANUP_SWEEP_CONDITION})`;
263
+ const discoverOutput = (name: string) =>
264
+ `\${{ steps.${FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID}.outputs.${name} }}`;
265
+ const outputs: Record<string, string> = {
266
+ has_targets: discoverOutput("has_targets"),
267
+ targets: discoverOutput("targets"),
268
+ };
269
+ for (const stack of options.stacks) {
270
+ const key = previewCleanupStackOutputKey(stack);
271
+ outputs[`has_${key}`] = discoverOutput(`has_${key}`);
272
+ outputs[`${key}_matrix`] = discoverOutput(`${key}_matrix`);
273
+ }
274
+
275
+ const discoverJob: FactoryPreviewCleanupWorkflowDiscoverJob = Object.freeze({
276
+ environment: options.environment,
277
+ if: discoverIf,
278
+ jobId: FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID,
279
+ jobName: FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_NAME,
280
+ outputs: Object.freeze(outputs),
281
+ permissions: PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS,
282
+ steps: Object.freeze([
283
+ Object.freeze({
284
+ name: "Read preview residue",
285
+ run: `${options.residueCommand} > "${RESIDUE_PATH}"`,
286
+ }),
287
+ Object.freeze({
288
+ env: Object.freeze({
289
+ FACTORY_PREVIEW_CLEANUP_PR: `\${{ github.event.pull_request.number }}`,
290
+ GITHUB_TOKEN: `\${{ github.token }}`,
291
+ }),
292
+ id: FACTORY_PREVIEW_CLEANUP_DISCOVER_STEP_ID,
293
+ name: "Discover cleanup targets",
294
+ run: discoverScript(cli, flags, sweep),
295
+ }),
296
+ ]),
297
+ });
298
+
299
+ const topology = factoryPreviewCleanupTopology({
300
+ audit: {
301
+ command: `${options.residueCommand} > "${RESIDUE_AFTER_PATH}" && ${cli} preview:cleanup --action audit --residue "${RESIDUE_AFTER_PATH}" --targets "$FACTORY_PREVIEW_CLEANUP_TARGETS" ${flags}`,
302
+ },
303
+ stacks: options.stacks,
304
+ });
305
+ if (
306
+ topology.destroyJobs.some(
307
+ ({ jobId }) => jobId === FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID
308
+ )
309
+ ) {
310
+ throw new Error("A cleanup stack's destroy job id collides with discover.");
311
+ }
312
+
313
+ const matrixEnv = Object.freeze({
314
+ FACTORY_PREVIEW_CLEANUP_HEAD_SHA: `\${{ matrix.headSha }}`,
315
+ FACTORY_PREVIEW_CLEANUP_PR: `\${{ matrix.pr }}`,
316
+ FACTORY_PREVIEW_CLEANUP_STACK: `\${{ matrix.stack }}`,
317
+ FACTORY_PREVIEW_CLEANUP_STAGE: `\${{ matrix.stage }}`,
318
+ });
319
+ const destroyOutput = (name: string) =>
320
+ `\${{ steps.${FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID}.outputs.${name} }}`;
321
+ // Record only what the destroy step reported; a setup failure before it
322
+ // leaves nothing to record and the stage to the next sweep.
323
+ const destroyedIf = `always() && steps.${FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID}.outputs.outcome != ''`;
324
+ const destroySteps: readonly WorkflowStep[] = Object.freeze([
325
+ Object.freeze({
326
+ env: matrixEnv,
327
+ id: FACTORY_PREVIEW_CLEANUP_DESTROY_STEP_ID,
328
+ name: "Destroy the stage",
329
+ run: destroyScript(options.destroyCommand),
330
+ }),
331
+ // Unscoped mint, like the HUD and freeze jobs: a permission subset 422s
332
+ // because the installation was never granted it.
333
+ Object.freeze({
334
+ id: FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID,
335
+ if: destroyedIf,
336
+ name: "Mint the factory App token",
337
+ uses: options.createGithubAppToken.uses,
338
+ with: Object.freeze({
339
+ "client-id": FACTORY_PROOF_GATE_APP_ID,
340
+ "private-key": `\${{ secrets.FACTORY_GITHUB_APP_PRIVATE_KEY }}`,
341
+ }),
342
+ }),
343
+ Object.freeze({
344
+ env: Object.freeze({
345
+ ...matrixEnv,
346
+ FACTORY_GITHUB_APP_TOKEN: `\${{ steps.${FACTORY_PREVIEW_CLEANUP_APP_TOKEN_STEP_ID}.outputs.token }}`,
347
+ FACTORY_PREVIEW_CLEANUP_EVIDENCE: destroyOutput("evidence"),
348
+ FACTORY_PREVIEW_CLEANUP_OUTCOME: destroyOutput("outcome"),
349
+ GITHUB_TOKEN: `\${{ github.token }}`,
350
+ }),
351
+ if: destroyedIf,
352
+ name: "Record the cleanup outcome",
353
+ run: `${cli} preview:cleanup --action record --pr "$FACTORY_PREVIEW_CLEANUP_PR" --target-stack "$FACTORY_PREVIEW_CLEANUP_STACK" --target-stage "$FACTORY_PREVIEW_CLEANUP_STAGE" --outcome "$FACTORY_PREVIEW_CLEANUP_OUTCOME" --evidence-file "$FACTORY_PREVIEW_CLEANUP_EVIDENCE" \${FACTORY_PREVIEW_CLEANUP_HEAD_SHA:+--head-sha "$FACTORY_PREVIEW_CLEANUP_HEAD_SHA"} ${flags}`,
354
+ }),
355
+ Object.freeze({
356
+ env: Object.freeze({
357
+ FACTORY_PREVIEW_CLEANUP_OUTCOME: destroyOutput("outcome"),
358
+ }),
359
+ if: "always()",
360
+ name: "Require a passed destroy",
361
+ run: 'test "$FACTORY_PREVIEW_CLEANUP_OUTCOME" = passed',
362
+ }),
363
+ ]);
364
+
365
+ const destroyJobs = topology.destroyJobs.map(({ jobId, stack }) => {
366
+ const key = previewCleanupStackOutputKey(stack);
367
+ return Object.freeze({
368
+ concurrency: Object.freeze({
369
+ cancelInProgress: false as const,
370
+ group: concurrencyGroup,
371
+ }),
372
+ environment: options.environment,
373
+ if: `needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.has_${key} == 'true'`,
374
+ jobId,
375
+ jobName: `Destroy ${stack}`,
376
+ needs: Object.freeze([FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID]),
377
+ // `list` reads with the workflow token; the App token writes.
378
+ permissions: PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS,
379
+ stack,
380
+ steps: destroySteps,
381
+ strategy: Object.freeze({
382
+ failFast: false as const,
383
+ matrix: Object.freeze({
384
+ include: `\${{ fromJSON(needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.${key}_matrix).include }}`,
385
+ }),
386
+ }),
387
+ });
388
+ });
389
+
390
+ const auditJob: FactoryPreviewCleanupWorkflowAuditJob = Object.freeze({
391
+ env: Object.freeze({
392
+ FACTORY_PREVIEW_CLEANUP_TARGETS: `\${{ needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.targets }}`,
393
+ }),
394
+ environment: options.environment,
395
+ if: `${topology.auditJob.if} && needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.result == 'success' && needs.${FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID}.outputs.has_targets == 'true'`,
396
+ jobId: topology.auditJob.jobId,
397
+ jobName: topology.auditJob.jobName,
398
+ needs: Object.freeze([
399
+ FACTORY_PREVIEW_CLEANUP_DISCOVER_JOB_ID,
400
+ ...topology.auditJob.needs,
401
+ ]),
402
+ permissions: Object.freeze({ contents: "read" as const }),
403
+ steps: topology.auditJob.steps,
404
+ });
405
+
406
+ const on: Record<string, unknown> = {
407
+ pull_request_target: Object.freeze({ types: Object.freeze(["closed"]) }),
408
+ };
409
+ if (cron !== undefined) {
410
+ on.schedule = Object.freeze([Object.freeze({ cron })]);
411
+ on.workflow_dispatch = Object.freeze({});
412
+ }
413
+
414
+ return Object.freeze({
415
+ auditJob,
416
+ checkoutRef: FACTORY_PREVIEW_CLEANUP_CHECKOUT_REF,
417
+ destroyJobs: Object.freeze(destroyJobs),
418
+ discoverJob,
419
+ on: Object.freeze(on),
420
+ permissions: Object.freeze({ contents: "read" as const }),
421
+ });
422
+ };