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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +712 -10
  2. package/dist/.build-fingerprint.json +3 -0
  3. package/dist/alchemy/index.d.ts +1174 -0
  4. package/dist/alchemy/index.js +2142 -0
  5. package/dist/bundle-alchemy-entry-CT5hCphA.js +112 -0
  6. package/dist/execute-alchemy-entry-B397GSk5.d.ts +134 -0
  7. package/dist/execute-alchemy-entry-CZ7Knz4q.js +160 -0
  8. package/dist/index.d.ts +1205 -87
  9. package/dist/index.js +2752 -317
  10. package/package.json +28 -10
  11. package/src/actions.ts +13 -0
  12. package/src/alchemy/child-diagnostics.ts +148 -0
  13. package/src/alchemy/credential-preflight.ts +428 -0
  14. package/src/alchemy/destroy-postcondition.ts +103 -0
  15. package/src/alchemy/evaluate-stack.ts +153 -0
  16. package/src/alchemy/first-deploy-authorization.ts +194 -0
  17. package/src/alchemy/index.ts +144 -0
  18. package/src/alchemy/lifecycle-failure.ts +174 -0
  19. package/src/alchemy/lifecycle.ts +1330 -0
  20. package/src/alchemy/local-emulation.ts +89 -0
  21. package/src/alchemy/plan-effects.ts +510 -0
  22. package/src/alchemy/retained-identity.ts +248 -0
  23. package/src/alchemy/secret-name-policy.ts +96 -0
  24. package/src/alchemy/stage-policy.ts +269 -0
  25. package/src/alchemy/state-tree.ts +168 -0
  26. package/src/alchemy/url-implies-auth.ts +264 -0
  27. package/src/alchemy-baseline.ts +75 -0
  28. package/src/bundle-alchemy-entry.ts +5 -0
  29. package/src/candidate-impact-workflow.ts +110 -0
  30. package/src/candidate-lifecycle.ts +29 -0
  31. package/src/cursor-oidc.ts +33 -0
  32. package/src/execute-alchemy-entry.ts +128 -8
  33. package/src/factory-workflow.ts +83 -40
  34. package/src/github-app-token.ts +92 -18
  35. package/src/github-transport.ts +186 -0
  36. package/src/impact-demand-condition.ts +67 -0
  37. package/src/index.ts +174 -0
  38. package/src/lifecycle-contract-lane.ts +113 -0
  39. package/src/merge-freeze-job.ts +253 -0
  40. package/src/pinned-action.ts +30 -0
  41. package/src/pr-status-hud-workflow.ts +96 -0
  42. package/src/preview-cleanup-topology.ts +115 -0
  43. package/src/preview-proof-inventory.ts +1092 -0
  44. package/src/preview-proof-lifecycle.ts +328 -0
  45. package/src/preview-receipt-workflow.ts +83 -0
  46. package/src/production-impact-workflow.ts +181 -0
  47. package/src/proof-reuse-gate.ts +223 -48
  48. package/src/proof-reuse-presentation.ts +131 -0
  49. package/src/push-identity-workflow.ts +463 -0
  50. package/src/runnable-cli.ts +27 -0
  51. package/src/verify-runner-policy.ts +290 -0
  52. package/src/vitest-profile-reader.test.ts +208 -0
  53. package/src/vitest-profile-reader.ts +225 -0
  54. package/src/vitest-profile.ts +631 -0
@@ -0,0 +1,253 @@
1
+ import type { PinnedAction } from "./actions.ts";
2
+ import type { WorkflowStep } from "./factory-workflow.ts";
3
+ import { assertPinnedAction } from "./pinned-action.ts";
4
+ import { FACTORY_PROOF_GATE_APP_ID } from "./proof-reuse-gate.ts";
5
+
6
+ /**
7
+ * The merge-freeze writer job (#356, ADR 0016; #429 for the
8
+ * merge-target namespace; #872 for this package).
9
+ *
10
+ * A consumer's generated merge-target-push Verify workflow is the ONLY
11
+ * producer of `patronage-factory/merge-freeze` generations: a red
12
+ * push-triggered Verify completes a generation active, a green one completes
13
+ * it inactive, and no command, scheduled job, or second workflow writes this
14
+ * check run. The operator override (`demand:waive --demand merge-freeze`)
15
+ * waives the demand for one candidate during a fix-forward; it never writes
16
+ * here.
17
+ *
18
+ * The write mirrors what the factory package's merge-freeze reader parses:
19
+ * create the run `in_progress` with no `started_at` (GitHub stamps the
20
+ * generation clock — the ordering rule itself is owned by the reader), then
21
+ * PATCH it completed with the reader-shaped state payload in `output.text`.
22
+ * The consumer's workflow test executes this exact script against a stubbed
23
+ * `gh` and parses the emitted payload with `validateMergeFreezeState`, so
24
+ * writer and reader cannot drift silently.
25
+ *
26
+ * Those two API calls are what the reader's two settling phases observe
27
+ * (#890). Before the POST the merge target carries no generation at all, which
28
+ * a reader reports as `awaiting-generation` while the pushed hosted verify run
29
+ * is still pending. Between the POST and the PATCH the generation exists with
30
+ * no `output.text`, which a reader reports as `running-generation`. Only the
31
+ * PATCH writes a verdict, so neither phase is one.
32
+ *
33
+ * Failure posture is deliberately fail-closed and the opposite of the
34
+ * proof-reuse gate's fail-open shell: this step runs under the runner's
35
+ * default `bash -e {0}`, so any API refusal aborts the step, the generation
36
+ * stays absent or `in_progress`, and every `pr:ready` arming-time read of
37
+ * that tip (#477) refuses until a later push writes a green generation.
38
+ *
39
+ * **Ownership line.** This package owns the check name, the App identity, the
40
+ * `create-github-app-token` inputs, the result fold, the merge-target `if`,
41
+ * and the job's `permissions`. The caller owns the runner, the `needs` list
42
+ * of every authoritative verification leaf, the timeout, and any extra env.
43
+ */
44
+
45
+ /** The one check-run name every merge-freeze reader pins. */
46
+ export const FACTORY_MERGE_FREEZE_CHECK_NAME = "patronage-factory/merge-freeze";
47
+
48
+ export const FACTORY_MERGE_FREEZE_JOB_ID = "freeze";
49
+ export const FACTORY_MERGE_FREEZE_JOB_NAME = "Report the merge freeze";
50
+
51
+ /** Step id the token step exposes its installation token under. */
52
+ export const FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID = "factory-app-token";
53
+
54
+ /**
55
+ * The GitHub Actions expression that folds the needed jobs' results into the
56
+ * one word the script branches on. It mirrors the `verify` summary job's
57
+ * failure condition exactly: any failed or cancelled needed job is a red
58
+ * merge target.
59
+ */
60
+ export const FACTORY_MERGE_FREEZE_VERIFY_RESULT_EXPRESSION = `\${{ (contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) && 'failure' || 'success' }}`;
61
+
62
+ /**
63
+ * The literal factory merge-target namespace, as a `github.ref` predicate
64
+ * (#429).
65
+ *
66
+ * `main` plus the repository-owned `epic/**` integration branches, and
67
+ * nothing else. Deliberately literal rather than profile-declared: one
68
+ * implementation per contract, no configuration machinery for a two-element
69
+ * namespace whose second element is a namespace prefix the repository itself
70
+ * owns. `epic/` needs the trailing slash — `startsWith` would otherwise admit
71
+ * `epicness/…`, which is not a merge target.
72
+ *
73
+ * A caller's `push` trigger branch list names the same namespace. That list
74
+ * decides which events produce a run at all; this predicate decides which of
75
+ * those runs may write a generation.
76
+ */
77
+ export const FACTORY_MERGE_TARGET_REF_CONDITION = [
78
+ "github.ref == 'refs/heads/main'",
79
+ "startsWith(github.ref, 'refs/heads/epic/')",
80
+ ].join(" || ");
81
+
82
+ /**
83
+ * `always()` is load-bearing: the red path is the whole point, so the job must
84
+ * run when a needed verification job failed. `github.event_name == 'push'` is
85
+ * load-bearing twice over: a `pull_request` run must never write a generation
86
+ * (its `github.sha` is a synthetic merge commit that no base tip is ever read
87
+ * at), and a `pull_request` trigger with an `epic/**` base list would
88
+ * otherwise reach this job.
89
+ */
90
+ export const FACTORY_MERGE_FREEZE_IF = `always() && github.event_name == 'push' && (${FACTORY_MERGE_TARGET_REF_CONDITION})`;
91
+
92
+ /**
93
+ * Least privilege for the writer job: no `GITHUB_TOKEN` scope at all.
94
+ *
95
+ * Both Checks API calls run under the App installation token minted in the
96
+ * first step (`GH_TOKEN: steps.factory-app-token.outputs.token`), and the job
97
+ * never checks out the repository. So the job uses no `GITHUB_TOKEN` scope,
98
+ * and an empty block is the honest declaration. A `checks: write` here would
99
+ * hand every adopter an unused write scope (#884).
100
+ */
101
+ export const FACTORY_MERGE_FREEZE_PERMISSIONS = Object.freeze({} as const);
102
+
103
+ /**
104
+ * The script the freeze step runs. Environment contract:
105
+ * - `GH_TOKEN`: an installation token for the pinned Patronage Factory App —
106
+ * the check run must carry that App's identity or every reader rejects it.
107
+ * - `VERIFY_RESULT`: `success` or `failure` (see the fold expression above).
108
+ * - `VERIFY_JOBS`: JSON `needs` context; only job results are retained.
109
+ * - `GITHUB_SHA` / `GITHUB_REPOSITORY` / `GITHUB_SERVER_URL` /
110
+ * `GITHUB_RUN_ID` / `GITHUB_RUN_ATTEMPT` / `GITHUB_REF_NAME`: runner-provided.
111
+ *
112
+ * `GITHUB_REF_NAME` is the merge target this run pushed to — `main` or an
113
+ * `epic/**` integration branch (#429). The job is gated to `push` events on
114
+ * exactly those refs, so the branch name is always the short name of a
115
+ * repository-owned merge target and never a pull-request merge ref. It
116
+ * appears in recovery guidance because a reader of an epic-targeting
117
+ * candidate must be told which branch owns the generation. A later green
118
+ * generation on that branch's current tip clears it, including a rerun.
119
+ */
120
+ export const factoryMergeFreezeScript = (): string =>
121
+ [
122
+ `sha="$GITHUB_SHA"`,
123
+ `branch="$GITHUB_REF_NAME"`,
124
+ `repo="$GITHUB_REPOSITORY"`,
125
+ `run_url="$GITHUB_SERVER_URL/$repo/actions/runs/$GITHUB_RUN_ID/attempts/$GITHUB_RUN_ATTEMPT"`,
126
+ `verification=$(jq -cen --argjson needs "$VERIFY_JOBS" --argjson runId "$GITHUB_RUN_ID" --argjson runAttempt "$GITHUB_RUN_ATTEMPT" '`,
127
+ ` def positiveInteger: type == "number" and . > 0 and floor == .;`,
128
+ ` if ($runId | positiveInteger) and ($runAttempt | positiveInteger) and ($needs | type == "object" and length > 0) then`,
129
+ ` {runId: $runId, runAttempt: $runAttempt, jobs: ($needs | map_values(.result))}`,
130
+ ` | select(all(.jobs[]; . == "success" or . == "failure" or . == "cancelled" or . == "skipped"))`,
131
+ ` else empty end')`,
132
+ `cancelled=$(jq 'any(.jobs[]; . == "cancelled")' <<<"$verification")`,
133
+ `failed=$(jq 'any(.jobs[]; . == "failure")' <<<"$verification")`,
134
+ `created=$(gh api --method POST "repos/$repo/check-runs" \\`,
135
+ ` -f "name=${FACTORY_MERGE_FREEZE_CHECK_NAME}" \\`,
136
+ ` -f "head_sha=$sha" \\`,
137
+ ` -f "status=in_progress" \\`,
138
+ ` -f "details_url=$run_url" \\`,
139
+ ` -f "output[title]=merge freeze generation in progress" \\`,
140
+ ` -f "output[summary]=This generation blocks factory merge handoffs until the merge-target Verify result is recorded.")`,
141
+ `id=$(jq -r '.id' <<<"$created")`,
142
+ `case "$id" in`,
143
+ ` ''|*[!0-9]*) echo "unusable check-run id: $id" >&2; exit 1;;`,
144
+ `esac`,
145
+ `if [ "$VERIFY_RESULT" = 'success' ]; then`,
146
+ ` active=false; outcome=inactive; conclusion=success`,
147
+ ` reason="Merge-target Verify passed on $branch at $sha ($run_url)."`,
148
+ `else`,
149
+ ` active=true; outcome=active; conclusion=failure`,
150
+ ` if [ "$cancelled" = 'true' ] && [ "$failed" = 'false' ]; then`,
151
+ ` 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)."`,
152
+ ` elif [ "$cancelled" = 'true' ]; then`,
153
+ ` 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)."`,
154
+ ` else`,
155
+ ` 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)."`,
156
+ ` fi`,
157
+ `fi`,
158
+ `state=$(jq -cn --argjson active "$active" --argjson id "$id" --arg headSha "$sha" --arg outcome "$outcome" --arg reason "$reason" --argjson verification "$verification" \\`,
159
+ ` '{active: $active, generationId: $id, headSha: $headSha, outcome: $outcome, reason: $reason, recordedAt: (now | todate), schemaVersion: 1, verification: $verification}')`,
160
+ `gh api --method PATCH "repos/$repo/check-runs/$id" \\`,
161
+ ` -f "status=completed" \\`,
162
+ ` -f "conclusion=$conclusion" \\`,
163
+ ` -f "details_url=$run_url" \\`,
164
+ ` -f "output[title]=merge freeze $outcome" \\`,
165
+ ` -f "output[summary]=$reason" \\`,
166
+ ` -f "output[text]=$state" >/dev/null`,
167
+ `echo "merge-freeze generation $id completed $outcome on $branch at $sha"`,
168
+ ].join("\n");
169
+
170
+ export interface FactoryMergeFreezeJobOptions<TNeed> {
171
+ /** The pinned `actions/create-github-app-token` the caller declared. */
172
+ readonly createGithubAppToken: PinnedAction;
173
+ /**
174
+ * Every authoritative verification leaf this generation folds. The elements
175
+ * are whatever the caller's workflow generator uses for `needs:`; they are
176
+ * returned unchanged.
177
+ */
178
+ readonly needs: readonly TNeed[];
179
+ /**
180
+ * Override the result fold. Defaults to
181
+ * `FACTORY_MERGE_FREEZE_VERIFY_RESULT_EXPRESSION`, which is what a caller
182
+ * whose summary job folds `needs.*.result` wants. Supply one only when the
183
+ * caller's red condition is genuinely different.
184
+ */
185
+ readonly verifyResultExpression?: string;
186
+ }
187
+
188
+ export interface FactoryMergeFreezeJob<TNeed> {
189
+ readonly if: typeof FACTORY_MERGE_FREEZE_IF;
190
+ readonly jobId: typeof FACTORY_MERGE_FREEZE_JOB_ID;
191
+ readonly jobName: typeof FACTORY_MERGE_FREEZE_JOB_NAME;
192
+ readonly needs: readonly TNeed[];
193
+ readonly permissions: typeof FACTORY_MERGE_FREEZE_PERMISSIONS;
194
+ readonly steps: readonly WorkflowStep[];
195
+ }
196
+
197
+ /**
198
+ * Build the merge-freeze writer job.
199
+ *
200
+ * An empty `needs` list is refused: a fold over no verification leaf is
201
+ * always `success`, so such a job would write a green generation for a merge
202
+ * target nothing verified — the exact failure the freeze exists to prevent.
203
+ */
204
+ export const factoryMergeFreezeJob = <TNeed>(
205
+ options: FactoryMergeFreezeJobOptions<TNeed>
206
+ ): FactoryMergeFreezeJob<TNeed> => {
207
+ assertPinnedAction(
208
+ "createGithubAppToken",
209
+ options.createGithubAppToken,
210
+ "actions/create-github-app-token"
211
+ );
212
+ if (options.needs.length === 0) {
213
+ throw new Error(
214
+ "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."
215
+ );
216
+ }
217
+
218
+ // Same unscoped mint as the PR status HUD job. A subset (checks/issues/PRs)
219
+ // 422s: those permissions are not granted to this installation.
220
+ const mintStep: WorkflowStep = Object.freeze({
221
+ id: FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID,
222
+ name: "Mint the factory App token",
223
+ uses: options.createGithubAppToken.uses,
224
+ with: Object.freeze({
225
+ // `client-id` superseded `app-id` in v3.2.0 (#581, #592): both inputs
226
+ // reach the same underlying `createAppAuth({ appId })` call, which has
227
+ // always accepted either the numeric App id or the Client id, so a
228
+ // pinned App id keeps authenticating unchanged.
229
+ "client-id": FACTORY_PROOF_GATE_APP_ID,
230
+ "private-key": `\${{ secrets.FACTORY_GITHUB_APP_PRIVATE_KEY }}`,
231
+ }),
232
+ });
233
+ const reportStep: WorkflowStep = Object.freeze({
234
+ env: Object.freeze({
235
+ GH_TOKEN: `\${{ steps.${FACTORY_MERGE_FREEZE_APP_TOKEN_STEP_ID}.outputs.token }}`,
236
+ VERIFY_JOBS: `\${{ toJSON(needs) }}`,
237
+ VERIFY_RESULT:
238
+ options.verifyResultExpression ??
239
+ FACTORY_MERGE_FREEZE_VERIFY_RESULT_EXPRESSION,
240
+ }),
241
+ name: "Complete the merge-freeze generation",
242
+ run: factoryMergeFreezeScript(),
243
+ });
244
+
245
+ return Object.freeze({
246
+ if: FACTORY_MERGE_FREEZE_IF,
247
+ jobId: FACTORY_MERGE_FREEZE_JOB_ID,
248
+ jobName: FACTORY_MERGE_FREEZE_JOB_NAME,
249
+ needs: Object.freeze([...options.needs]),
250
+ permissions: FACTORY_MERGE_FREEZE_PERMISSIONS,
251
+ steps: Object.freeze([mintStep, reportStep]),
252
+ });
253
+ };
@@ -0,0 +1,30 @@
1
+ import type { PinnedAction } from "./actions.ts";
2
+
3
+ const PINNED_ACTION_PATTERN = /^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/u;
4
+ const ACTION_TAG_PATTERN = /^v\d+(?:\.\d+){0,2}$/u;
5
+
6
+ const actionRepository = (action: PinnedAction): string =>
7
+ action.uses.slice(0, action.uses.indexOf("@"));
8
+
9
+ /** Shared validator for every action pin emitted by factory-ci helpers. */
10
+ export const assertPinnedAction = (
11
+ name: string,
12
+ action: PinnedAction,
13
+ expectedRepository?: string
14
+ ): void => {
15
+ if (!PINNED_ACTION_PATTERN.test(action.uses)) {
16
+ throw new Error(
17
+ `${name} must use owner/repository@<40-character commit SHA>, got "${action.uses}".`
18
+ );
19
+ }
20
+ if (expectedRepository && actionRepository(action) !== expectedRepository) {
21
+ throw new Error(
22
+ `${name} must pin ${expectedRepository}, got ${actionRepository(action)}.`
23
+ );
24
+ }
25
+ if (!ACTION_TAG_PATTERN.test(action.tag)) {
26
+ throw new Error(
27
+ `${name} tag must be vN, vN.N, or vN.N.N, got "${action.tag}".`
28
+ );
29
+ }
30
+ };
@@ -0,0 +1,96 @@
1
+ import type { PinnedAction } from "./actions.ts";
2
+ import type { WorkflowStep } from "./factory-workflow.ts";
3
+ import { assertPinnedAction } from "./pinned-action.ts";
4
+ import { PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS } from "./preview-proof-inventory.ts";
5
+ import { FACTORY_PROOF_GATE_APP_ID } from "./proof-reuse-gate.ts";
6
+ import { assertRunnableCli } from "./runnable-cli.ts";
7
+
8
+ export const FACTORY_PR_STATUS_HUD_JOB_ID = "status-hud";
9
+ export const FACTORY_PR_STATUS_HUD_JOB_NAME = "Present PR status HUD";
10
+ export const FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID = "factory-app-token";
11
+ export const FACTORY_PR_STATUS_HUD_PLAN_PATH =
12
+ ".factory-memory/preview-plan.json";
13
+
14
+ /**
15
+ * Presentation is independent of deploy demand. Callers who `needs` the jobs
16
+ * that settle HUD sources (verify, deploy) must keep this `always()` so a
17
+ * skipped or withdrawn deploy still publishes Skipped rows.
18
+ */
19
+ export const FACTORY_PR_STATUS_HUD_IF =
20
+ "always() && github.event_name == 'pull_request' && github.event.pull_request.draft != true";
21
+
22
+ export interface FactoryPrStatusHudWorkflowOptions {
23
+ readonly cli?: string;
24
+ readonly createGithubAppToken: PinnedAction;
25
+ }
26
+
27
+ /**
28
+ * Least privilege for the job that runs the present step. The present step
29
+ * is an inventory `list`, so the job needs exactly the inventory's read
30
+ * permissions (#825, #859).
31
+ */
32
+ export const FACTORY_PR_STATUS_HUD_PERMISSIONS =
33
+ PREVIEW_PROOF_INVENTORY_LIST_PERMISSIONS;
34
+
35
+ export const FACTORY_PR_STATUS_HUD_CONCURRENCY = Object.freeze({
36
+ cancelInProgress: false,
37
+ group: `status-hud-\${{ github.repository }}-\${{ github.event.pull_request.number }}`,
38
+ });
39
+
40
+ export interface FactoryPrStatusHudWorkflow {
41
+ readonly concurrency: typeof FACTORY_PR_STATUS_HUD_CONCURRENCY;
42
+ readonly if: typeof FACTORY_PR_STATUS_HUD_IF;
43
+ readonly jobId: typeof FACTORY_PR_STATUS_HUD_JOB_ID;
44
+ readonly jobName: typeof FACTORY_PR_STATUS_HUD_JOB_NAME;
45
+ readonly permissions: typeof FACTORY_PR_STATUS_HUD_PERMISSIONS;
46
+ readonly presentSteps: readonly WorkflowStep[];
47
+ }
48
+
49
+ const defaultCli = "psf";
50
+
51
+ export const factoryPrStatusHudWorkflow = (
52
+ options: FactoryPrStatusHudWorkflowOptions
53
+ ): FactoryPrStatusHudWorkflow => {
54
+ assertPinnedAction(
55
+ "createGithubAppToken",
56
+ options.createGithubAppToken,
57
+ "actions/create-github-app-token"
58
+ );
59
+ const cli = options.cli || defaultCli;
60
+ assertRunnableCli("cli", cli);
61
+ // Same unscoped mint as the freeze job. A subset (checks/issues/PRs)
62
+ // 422s: those permissions are not granted to this installation.
63
+ const mintStep: WorkflowStep = Object.freeze({
64
+ id: FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID,
65
+ name: "Mint the factory App token",
66
+ uses: options.createGithubAppToken.uses,
67
+ with: Object.freeze({
68
+ "client-id": FACTORY_PROOF_GATE_APP_ID,
69
+ "private-key": `\${{ secrets.FACTORY_GITHUB_APP_PRIVATE_KEY }}`,
70
+ }),
71
+ });
72
+ // The App token owns the HUD comment but has no contents permission, so
73
+ // the force-push timeline read (#819) is FORBIDDEN for it. The workflow
74
+ // token carries the job's `contents: read` and serves that read (#825).
75
+ const presentStep: WorkflowStep = Object.freeze({
76
+ env: Object.freeze({
77
+ FACTORY_GITHUB_APP_TOKEN: `\${{ steps.${FACTORY_PR_STATUS_HUD_APP_TOKEN_STEP_ID}.outputs.token }}`,
78
+ FACTORY_HEAD_SHA: `\${{ github.event.pull_request.head.sha }}`,
79
+ FACTORY_OWNER: `\${{ github.repository_owner }}`,
80
+ FACTORY_PR: `\${{ github.event.pull_request.number }}`,
81
+ FACTORY_REPO: `\${{ github.event.repository.name }}`,
82
+ GITHUB_TOKEN: `\${{ github.token }}`,
83
+ }),
84
+ name: "Present the PR status HUD",
85
+ run: `${cli} pr:status-hud --head "$FACTORY_HEAD_SHA" --owner "$FACTORY_OWNER" --repo "$FACTORY_REPO" --pr "$FACTORY_PR"`,
86
+ });
87
+
88
+ return Object.freeze({
89
+ concurrency: FACTORY_PR_STATUS_HUD_CONCURRENCY,
90
+ if: FACTORY_PR_STATUS_HUD_IF,
91
+ jobId: FACTORY_PR_STATUS_HUD_JOB_ID,
92
+ jobName: FACTORY_PR_STATUS_HUD_JOB_NAME,
93
+ permissions: FACTORY_PR_STATUS_HUD_PERMISSIONS,
94
+ presentSteps: Object.freeze([mintStep, presentStep]),
95
+ });
96
+ };
@@ -0,0 +1,115 @@
1
+ import type { WorkflowStep } from "./factory-workflow.ts";
2
+
3
+ export const FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_ID = "stage-residue-audit";
4
+ export const FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_NAME = "Stage residue audit";
5
+
6
+ const JOB_ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]*$/u;
7
+ const STACK_JOB_SAFE = /[^A-Za-z0-9_-]+/gu;
8
+
9
+ export interface FactoryPreviewCleanupTopologyOptions {
10
+ readonly audit: {
11
+ readonly command: string;
12
+ readonly jobId?: string;
13
+ readonly jobName?: string;
14
+ };
15
+ readonly stacks: readonly string[];
16
+ }
17
+
18
+ export interface FactoryPreviewCleanupDestroyJob {
19
+ readonly jobId: string;
20
+ readonly stack: string;
21
+ }
22
+
23
+ export interface FactoryPreviewCleanupAuditJob {
24
+ readonly if: "always()";
25
+ readonly jobId: string;
26
+ readonly jobName: string;
27
+ readonly needs: readonly string[];
28
+ readonly steps: readonly WorkflowStep[];
29
+ }
30
+
31
+ export interface FactoryPreviewCleanupTopology {
32
+ readonly auditJob: FactoryPreviewCleanupAuditJob;
33
+ readonly destroyJobs: readonly FactoryPreviewCleanupDestroyJob[];
34
+ }
35
+
36
+ const assertSingleLine = (name: string, value: string): void => {
37
+ if (value.trim() !== value || value.length === 0 || /[\r\n]/u.test(value)) {
38
+ throw new Error(`${name} must be a single non-empty line.`);
39
+ }
40
+ };
41
+
42
+ export const previewCleanupDestroyJobId = (stack: string): string => {
43
+ assertSingleLine("cleanup stack", stack);
44
+ const suffix = stack
45
+ .replaceAll(STACK_JOB_SAFE, "-")
46
+ .replaceAll(/^-+|-+$/gu, "");
47
+ if (suffix.length === 0) {
48
+ throw new Error(`Cleanup stack "${stack}" has no job-id-safe characters.`);
49
+ }
50
+ const jobId = `destroy-${suffix}`;
51
+ if (!JOB_ID_PATTERN.test(jobId)) {
52
+ throw new Error(
53
+ `Cleanup destroy job id "${jobId}" is not a GitHub Actions job id.`
54
+ );
55
+ }
56
+ return jobId;
57
+ };
58
+
59
+ /**
60
+ * Generate the factory-owned preview-cleanup topology (#764): one destroy
61
+ * job identity per stack, then exactly one stage-wide residue-audit job
62
+ * that `needs` every destroy. The audit is whole-stage — this helper never
63
+ * threads a stack name or path filter into it. Callers own destroy steps,
64
+ * what counts as residue, credentials, and runners.
65
+ */
66
+ export const factoryPreviewCleanupTopology = (
67
+ options: FactoryPreviewCleanupTopologyOptions
68
+ ): FactoryPreviewCleanupTopology => {
69
+ if (options.stacks.length === 0) {
70
+ throw new Error(
71
+ "Preview cleanup topology requires at least one stack so the audit can depend on every destroy."
72
+ );
73
+ }
74
+
75
+ const destroyJobs = options.stacks.map((stack) =>
76
+ Object.freeze({
77
+ jobId: previewCleanupDestroyJobId(stack),
78
+ stack,
79
+ })
80
+ );
81
+ const destroyJobIds = destroyJobs.map(({ jobId }) => jobId);
82
+ if (new Set(destroyJobIds).size !== destroyJobIds.length) {
83
+ throw new Error(
84
+ "Cleanup stack names must map to distinct destroy job ids."
85
+ );
86
+ }
87
+
88
+ assertSingleLine("audit.command", options.audit.command);
89
+ const jobId = options.audit.jobId ?? FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_ID;
90
+ const jobName =
91
+ options.audit.jobName ?? FACTORY_PREVIEW_CLEANUP_AUDIT_JOB_NAME;
92
+ if (!JOB_ID_PATTERN.test(jobId)) {
93
+ throw new Error("audit.jobId must be a GitHub Actions job id.");
94
+ }
95
+ assertSingleLine("audit.jobName", jobName);
96
+ if (destroyJobIds.includes(jobId)) {
97
+ throw new Error("audit.jobId must not collide with a destroy job id.");
98
+ }
99
+
100
+ const auditStep: WorkflowStep = Object.freeze({
101
+ name: "Assert stage absent",
102
+ run: options.audit.command,
103
+ });
104
+
105
+ return Object.freeze({
106
+ auditJob: Object.freeze({
107
+ if: "always()",
108
+ jobId,
109
+ jobName,
110
+ needs: Object.freeze([...destroyJobIds]),
111
+ steps: Object.freeze([auditStep]),
112
+ }),
113
+ destroyJobs: Object.freeze(destroyJobs),
114
+ });
115
+ };