@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,1330 @@
1
+ /**
2
+ * The shared Alchemy lifecycle operation (#1077).
3
+ *
4
+ * One function, `runAlchemyLifecycle`, owns the order in which a plan, a
5
+ * deploy, or a destroy runs: request and admission checks, stage ownership
6
+ * around every persisted-state read, the pre- and post-state snapshots, the
7
+ * child executions, the effect policy, and the postconditions. A consumer
8
+ * passes typed policy and two narrow capabilities — the state store from
9
+ * `@patronage/alchemy-d1-state` and the Alchemy entry to execute — and gets
10
+ * back a fixed-shape result or an `AlchemyLifecycleError`. It cannot call the
11
+ * steps in another order, because it does not call the steps.
12
+ *
13
+ * Paitronage and HQ each reconstructed this sequence from the guards in
14
+ * `./` and got parts of it wrong in different ways (paitronage#1917): a
15
+ * post-child failure reported as not started, an empty-stage cleanup racing
16
+ * a concurrent write, a plan whose immutability check ignored stack output.
17
+ * The sequence below is the one both were reaching for.
18
+ *
19
+ * What stays with the consumer: the resource graph, the credentials and
20
+ * environment the child runs with, the stage table, the retained-identity
21
+ * markers, the first-deploy authorization list, and the state store's own
22
+ * configuration. This module learns none of them.
23
+ */
24
+
25
+ import { readFileSync } from "node:fs";
26
+ import { createRequire } from "node:module";
27
+ import path from "node:path";
28
+ import { isDeepStrictEqual } from "node:util";
29
+
30
+ import * as Effect from "effect/Effect";
31
+
32
+ import {
33
+ EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER,
34
+ executeAlchemyEntry,
35
+ resolveAlchemyChildCwd,
36
+ } from "../execute-alchemy-entry.ts";
37
+ import type { ExecuteAlchemyEntryOptions } from "../execute-alchemy-entry.ts";
38
+ import { openChildDiagnostics } from "./child-diagnostics.ts";
39
+ import type {
40
+ ChildDiagnostics,
41
+ ChildDiagnosticsSection,
42
+ } from "./child-diagnostics.ts";
43
+ import {
44
+ firstDeployAuthorization,
45
+ firstDeployPlanHash,
46
+ } from "./first-deploy-authorization.ts";
47
+ import { AlchemyLifecycleError } from "./lifecycle-failure.ts";
48
+ import type {
49
+ AlchemyLifecycleFailureCode,
50
+ AlchemyLifecycleOperation,
51
+ AlchemyLifecyclePhase,
52
+ MutationCertainty,
53
+ } from "./lifecycle-failure.ts";
54
+ import {
55
+ parsePlanEffects,
56
+ PLAN_OUTPUT_ALCHEMY_VERSION,
57
+ } from "./plan-effects.ts";
58
+ import type { PlanEffects, PlanResourceEffect } from "./plan-effects.ts";
59
+ import { assertRetainedIdentities } from "./retained-identity.ts";
60
+ import type {
61
+ RetainedIdentityMarker,
62
+ StateSnapshot,
63
+ StateSnapshotResource,
64
+ } from "./retained-identity.ts";
65
+ import { stagePolicy, StagePolicyError } from "./stage-policy.ts";
66
+ import type { StagePolicyTable } from "./stage-policy.ts";
67
+
68
+ export interface AlchemyLifecycleRequest {
69
+ readonly operation: AlchemyLifecycleOperation;
70
+ readonly stack: string;
71
+ readonly stage: string;
72
+ }
73
+
74
+ export interface StageTarget {
75
+ readonly stack: string;
76
+ readonly stage: string;
77
+ }
78
+
79
+ /** Whether a stack output row exists and what it holds. */
80
+ export type StackOutputOccupancy =
81
+ | { readonly present: false }
82
+ | {
83
+ readonly present: true;
84
+ readonly empty: boolean;
85
+ readonly value: unknown;
86
+ };
87
+
88
+ /**
89
+ * One consistent read of a stage, as `@patronage/alchemy-d1-state` returns
90
+ * it from a single statement. An unreadable stage fails; it is never an
91
+ * empty view.
92
+ */
93
+ export interface StageSnapshotView {
94
+ /** Decoded resource FQNs. */
95
+ readonly resources: readonly string[];
96
+ readonly output: StackOutputOccupancy;
97
+ /** No resources and an absent or `{}` output row. */
98
+ readonly empty: boolean;
99
+ }
100
+
101
+ export type StageCleanupOutcome = "removed" | "absent" | "occupied";
102
+
103
+ /**
104
+ * A held stage lease, as `@patronage/alchemy-d1-state` returns it.
105
+ *
106
+ * `release` is idempotent there: it succeeds when the row is gone or belongs
107
+ * to a later holder. So a release that succeeds proves nothing about
108
+ * ownership. `renew` is the fenced operation: it changes zero rows and fails
109
+ * with `lost` unless this holder's unexpired row is still there. The
110
+ * lifecycle renews before it accepts anything it read under the lease.
111
+ *
112
+ * `childEnvironment` is how the lease crosses a process boundary: the
113
+ * entries a child's environment must carry for the adapter in that child to
114
+ * adopt this lease. Every child the lifecycle launches carries them.
115
+ */
116
+ export interface StageLease {
117
+ /** Drop the lease. Idempotent; never an ownership signal. */
118
+ readonly release: () => Effect.Effect<void, unknown>;
119
+ /** Extend the lease. Fails with `lost` once the lease is gone. */
120
+ readonly renew: () => Effect.Effect<void, unknown>;
121
+ /**
122
+ * The environment entries a child needs to adopt this lease. They carry
123
+ * the bearer token, so they go into a child's environment and nowhere
124
+ * else: never into a result, a failure, or a log.
125
+ */
126
+ readonly childEnvironment: () => Readonly<Record<string, string>>;
127
+ /**
128
+ * Atomically remove the stack output row if, in the same statement, it is
129
+ * `{}` and no resource rows exist. Never deletes a resource row.
130
+ */
131
+ readonly deleteEmptyStage: () => Effect.Effect<StageCleanupOutcome, unknown>;
132
+ }
133
+
134
+ /**
135
+ * The state capability: the subset of `D1StateService` the lifecycle reads
136
+ * through. `@patronage/alchemy-d1-state` satisfies it structurally; this
137
+ * package does not import that package and learns no table or account.
138
+ */
139
+ export interface StageStateStore {
140
+ readonly snapshotStage: (
141
+ target: StageTarget
142
+ ) => Effect.Effect<StageSnapshotView, unknown>;
143
+ readonly get: (
144
+ request: StageTarget & { readonly fqn: string }
145
+ ) => Effect.Effect<unknown, unknown>;
146
+ readonly acquireStageOwnership: (
147
+ request: StageTarget & {
148
+ readonly holder: string;
149
+ readonly ttlMillis?: number;
150
+ }
151
+ ) => Effect.Effect<StageLease, unknown>;
152
+ }
153
+
154
+ export interface FirstDeployPolicy {
155
+ /** The plan hashes an operator authorized. Owned by the consumer. */
156
+ readonly authorizedHashes: readonly string[];
157
+ /**
158
+ * The reviewed source commit the plan is bound to, or `null` to bind the
159
+ * plan to no commit. See `firstDeployPlanHash`.
160
+ */
161
+ readonly sourceSha: string | null;
162
+ }
163
+
164
+ export interface AlchemyLifecyclePolicy {
165
+ /** The consumer's stage table. */
166
+ readonly stages: StagePolicyTable;
167
+ /** The label the stage lease is held under, such as a CI run id. */
168
+ readonly holder: string;
169
+ /** Lease length in milliseconds. The store's default applies when omitted. */
170
+ readonly ownershipTtlMillis?: number;
171
+ /**
172
+ * The physical identities a protected stage retains. Required for a
173
+ * deploy into a protected stage that already holds state; checked before
174
+ * the apply against the recorded values, and after it against the
175
+ * pre-apply snapshot.
176
+ */
177
+ readonly retainedIdentities?: readonly RetainedIdentityMarker[];
178
+ /**
179
+ * Authorizes the one deploy no earlier state constrains. A deploy into an
180
+ * empty stage with no policy here is refused.
181
+ */
182
+ readonly firstDeploy?: FirstDeployPolicy;
183
+ /** Pass `--adopt` to the deploy plan and apply. HQ's `v1` cutover flag. */
184
+ readonly adopt?: boolean;
185
+ /**
186
+ * Persisted FQNs whose `update` the post-deploy plan tolerates. A Worker
187
+ * carrying a write-only secret binding re-plans as `update` on every
188
+ * deploy because the value can never be read back; that is a property of
189
+ * the secret, not drift. Only `update` is tolerated, only on these FQNs.
190
+ * A top-level resource's FQN is its logical id; a nested one is
191
+ * `namespace/id`. A binding change is never tolerated: the plan adapter
192
+ * attributes no binding row to a resource, so a plan with binding work is
193
+ * not converged whatever this list names.
194
+ */
195
+ readonly nonConvergentResources?: readonly string[];
196
+ }
197
+
198
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
199
+ ? Omit<T, K>
200
+ : never;
201
+
202
+ /**
203
+ * The entry capability: what `executeAlchemyEntry` needs minus what the
204
+ * lifecycle decides. Arguments are the lifecycle's; stdio is always piped so
205
+ * the plan can be read; the capture limit is `EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER`.
206
+ * There is no `redact` because `redact` shapes what the child hands back,
207
+ * and the plan text must be the child's own bytes. There is no `onCaptured`
208
+ * for the same reason in the other direction: the sink is the lifecycle's,
209
+ * so a consumer-supplied one would be dropped, and an option that
210
+ * type-checks and does nothing is worse than one that does not exist. By
211
+ * default the captured output is parsed and dropped, written nowhere, so
212
+ * nothing in it can reach a job log or an evidence file through this
213
+ * operation; a consumer that wants a record opts in with `childDiagnostics`,
214
+ * which owns its own redactor and its own file.
215
+ */
216
+ export type AlchemyLifecycleEntry = DistributiveOmit<
217
+ ExecuteAlchemyEntryOptions,
218
+ "args" | "onCaptured" | "stdio" | "maxBuffer" | "redact"
219
+ > & {
220
+ /** Explicit dotenv file for every child; omitted preserves Alchemy defaults. */
221
+ readonly envFile?: string;
222
+ };
223
+
224
+ type LifecycleChild = "plan" | "deploy" | "destroy";
225
+
226
+ export interface RunAlchemyLifecycleOptions {
227
+ readonly request: AlchemyLifecycleRequest;
228
+ readonly policy: AlchemyLifecyclePolicy;
229
+ readonly state: StageStateStore;
230
+ readonly entry: AlchemyLifecycleEntry;
231
+ /**
232
+ * Opt in to keeping what the children printed (#1260). Omitted, the
233
+ * captured output is parsed and dropped, exactly as before: this is the
234
+ * only way any of it reaches a file through this operation.
235
+ *
236
+ * Set, every child of the operation — the dry runs, the apply, the
237
+ * destroy — has both streams appended to `path`, each stream passed whole
238
+ * through `redact` (never a line at a time, so a declared value that
239
+ * spans lines is covered), under a header naming the child. The consumer
240
+ * chooses the
241
+ * path and supplies the redactor; the lifecycle chooses neither and holds
242
+ * no secret-name list. `secretNamePolicy({ names, values })` from this
243
+ * subpath builds the redactor from the names the consumer declares.
244
+ *
245
+ * The record is a copy: the plan text the operation parses and hashes is
246
+ * the child's own output, untouched by `redact`. Writing it changes no
247
+ * exit status and no decision here, and a write that fails is reported as
248
+ * `CHILD_DIAGNOSTICS_UNWRITABLE` rather than as a child failure — up front
249
+ * while nothing has been mutated, and otherwise only after the operation
250
+ * has run to its end, so a record that could not be kept never abandons a
251
+ * good apply before its convergence check.
252
+ */
253
+ readonly childDiagnostics?: ChildDiagnostics;
254
+ }
255
+
256
+ export interface AlchemyLifecycleResult {
257
+ readonly operation: AlchemyLifecycleOperation;
258
+ readonly stack: string;
259
+ readonly stage: string;
260
+ /** What the run did to the stage. A plan never mutates. */
261
+ readonly mutation: Exclude<MutationCertainty, "not-started">;
262
+ /** The installed Alchemy version the children ran under. */
263
+ readonly alchemyVersion: string;
264
+ /** A protected stage held no state before the operation. */
265
+ readonly firstDeploy: boolean;
266
+ /** The plan the operation read (plan), applied (deploy), or destroyed. */
267
+ readonly effects: PlanEffects;
268
+ /**
269
+ * The persisted FQN of every resource the deploy's plan created, resolved
270
+ * against the state recorded after the apply. Present on deploy only.
271
+ */
272
+ readonly created?: readonly string[];
273
+ /** The post-deploy plan. Present on deploy only. */
274
+ readonly convergence?: PlanEffects;
275
+ /** The reviewed first-deploy hash. Present on a plan of an empty stage with a first-deploy policy. */
276
+ readonly planHash?: string;
277
+ /** What the empty-stage cleanup did. Present on destroy only. */
278
+ readonly cleanup?: StageCleanupOutcome;
279
+ }
280
+
281
+ const OPERATIONS: ReadonlySet<string> = new Set<AlchemyLifecycleOperation>([
282
+ "plan",
283
+ "deploy",
284
+ "destroy",
285
+ ]);
286
+
287
+ /** Persisted state of one stage: every resource record and the stack output. */
288
+ interface PersistedState {
289
+ readonly output: StackOutputOccupancy;
290
+ readonly resources: readonly {
291
+ readonly fqn: string;
292
+ readonly state: unknown;
293
+ }[];
294
+ }
295
+
296
+ /** No resource record, and an output row that is absent or `{}` (#1074). */
297
+ const isEmptyState = (persisted: PersistedState): boolean =>
298
+ persisted.resources.length === 0 &&
299
+ (!persisted.output.present || persisted.output.empty);
300
+
301
+ const ownershipRefusal = (error: unknown): "held" | "lost" | undefined => {
302
+ if (
303
+ typeof error === "object" &&
304
+ error !== null &&
305
+ "_tag" in error &&
306
+ error._tag === "StageOwnershipError" &&
307
+ "reason" in error &&
308
+ (error.reason === "held" || error.reason === "lost")
309
+ ) {
310
+ return error.reason;
311
+ }
312
+ return undefined;
313
+ };
314
+
315
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
316
+ typeof value === "object" && value !== null && !Array.isArray(value);
317
+
318
+ /**
319
+ * The `version` of the `alchemy` manifest that owns `cliPath`: the nearest
320
+ * `package.json` above it whose `name` is `alchemy`. Throws when none is
321
+ * found before the filesystem root.
322
+ */
323
+ const alchemyManifestVersion = (cliPath: string): unknown => {
324
+ let directory = path.dirname(cliPath);
325
+ for (;;) {
326
+ let manifest: unknown;
327
+ try {
328
+ manifest = JSON.parse(
329
+ readFileSync(path.join(directory, "package.json"), "utf-8")
330
+ ) as unknown;
331
+ } catch {
332
+ manifest = undefined;
333
+ }
334
+ if (isRecord(manifest) && manifest.name === "alchemy") {
335
+ return manifest.version;
336
+ }
337
+ const parent = path.dirname(directory);
338
+ if (parent === directory) {
339
+ throw new Error("no alchemy manifest above the CLI");
340
+ }
341
+ directory = parent;
342
+ }
343
+ };
344
+
345
+ const persistedToSnapshot = (
346
+ target: StageTarget,
347
+ persisted: PersistedState
348
+ ): StateSnapshot => ({
349
+ resources: persisted.resources.map(
350
+ ({ fqn, state }): StateSnapshotResource => ({
351
+ fqn,
352
+ stack: target.stack,
353
+ stage: target.stage,
354
+ state: state as StateSnapshotResource["state"],
355
+ })
356
+ ),
357
+ });
358
+
359
+ /** The run's fixed context: one request, one policy, one prepared entry. */
360
+ /**
361
+ * A persisted record whose last apply did not finish. Alchemy 2.0.0-beta.76
362
+ * plans `create` for a `creating` record (a create that was interrupted)
363
+ * and for a `deleting` one (a delete that was interrupted while the
364
+ * resource is still declared), and both finish at the same FQN.
365
+ */
366
+ const IN_FLIGHT_STATUSES: ReadonlySet<unknown> = new Set([
367
+ "creating",
368
+ "deleting",
369
+ ]);
370
+
371
+ const statusOf = (record: { readonly state: unknown }): unknown =>
372
+ isRecord(record.state) ? record.state.status : undefined;
373
+
374
+ /**
375
+ * Resolve plan rows onto persisted FQNs. A row's `id` is the FQN Alchemy
376
+ * printed in its tag, which is the identity the resource is persisted under
377
+ * (epic #1165, D1), so a row resolves only to the candidate that is that
378
+ * FQN exactly. A row with no candidate is `undefined`, and the caller
379
+ * refuses rather than guessing.
380
+ */
381
+ const resolveRows = (
382
+ rows: readonly PlanResourceEffect[],
383
+ candidates: readonly string[]
384
+ ): readonly string[] | undefined => {
385
+ const resolved: string[] = [];
386
+ for (const { id } of rows) {
387
+ if (!candidates.includes(id)) {
388
+ return undefined;
389
+ }
390
+ resolved.push(id);
391
+ }
392
+ return resolved;
393
+ };
394
+
395
+ /**
396
+ * Two rows with one FQN name one persisted identity twice. Alchemy keys a
397
+ * plan by FQN, so its renderer cannot print this; output that does is not a
398
+ * plan this operation can bind to, and is refused rather than read.
399
+ */
400
+ const hasRepeatedIds = (effects: PlanEffects): boolean =>
401
+ new Set(effects.resources.map(({ id }) => id)).size !==
402
+ effects.resources.length;
403
+
404
+ /** Whether a lease still fences the stage, by the store's own fenced renewal. */
405
+ const fenceState = async (
406
+ lease: StageLease
407
+ ): Promise<"held" | "lost" | "unreachable"> => {
408
+ try {
409
+ await Effect.runPromise(lease.renew());
410
+ return "held";
411
+ } catch (error) {
412
+ return ownershipRefusal(error) === "lost" ? "lost" : "unreachable";
413
+ }
414
+ };
415
+
416
+ /** Release on the way out of a failed window; the failure is what is reported. */
417
+ const releaseQuietly = async (lease: StageLease): Promise<void> => {
418
+ try {
419
+ await Effect.runPromise(lease.release());
420
+ } catch {
421
+ // The window's failure is the one to report.
422
+ }
423
+ };
424
+
425
+ /** The run's fixed context: one request, one policy, one prepared entry. */
426
+ class LifecycleRun {
427
+ private readonly request: AlchemyLifecycleRequest;
428
+ private readonly policy: AlchemyLifecyclePolicy;
429
+ private readonly state: StageStateStore;
430
+ private readonly entry: AlchemyLifecycleEntry;
431
+ private readonly childDiagnostics: ChildDiagnostics | undefined;
432
+ /**
433
+ * A diagnostics write that failed after a mutating child had started, held
434
+ * until the operation has run to its end. See `noteDiagnosticsFailure`.
435
+ */
436
+ private diagnosticsUnwritable = false;
437
+ private bundledEntry: string | undefined;
438
+ /** What the run has done to the stage so far. Only children advance it. */
439
+ private certainty: MutationCertainty = "not-started";
440
+
441
+ constructor(options: RunAlchemyLifecycleOptions) {
442
+ this.request = options.request;
443
+ this.policy = options.policy;
444
+ this.state = options.state;
445
+ this.entry = options.entry;
446
+ this.childDiagnostics = options.childDiagnostics;
447
+ }
448
+
449
+ private fail(
450
+ code: AlchemyLifecycleFailureCode,
451
+ phase: AlchemyLifecyclePhase,
452
+ extra: {
453
+ /** Name the diagnostics file, on a failure about a child. */
454
+ readonly namesDiagnostics?: boolean;
455
+ readonly planHash?: string;
456
+ } = {}
457
+ ): AlchemyLifecycleError {
458
+ const { namesDiagnostics, planHash } = extra;
459
+ const diagnosticsPath =
460
+ namesDiagnostics === true ? this.childDiagnostics?.path : undefined;
461
+ return new AlchemyLifecycleError({
462
+ ...(diagnosticsPath === undefined
463
+ ? {}
464
+ : { childDiagnosticsPath: diagnosticsPath }),
465
+ code,
466
+ mutation: this.certainty,
467
+ operation: this.request.operation,
468
+ phase,
469
+ ...(planHash === undefined ? {} : { planHash }),
470
+ });
471
+ }
472
+
473
+ private get target(): StageTarget {
474
+ return { stack: this.request.stack, stage: this.request.stage };
475
+ }
476
+
477
+ // ── request and admission ────────────────────────────────────────────
478
+
479
+ validateRequest(): void {
480
+ const { operation, stack, stage } = this.request;
481
+ if (
482
+ !OPERATIONS.has(operation) ||
483
+ typeof stack !== "string" ||
484
+ typeof stage !== "string" ||
485
+ stack.trim() === "" ||
486
+ stage.trim() === "" ||
487
+ stack !== stack.trim() ||
488
+ stage !== stage.trim()
489
+ ) {
490
+ throw this.fail("INVALID_REQUEST", "request");
491
+ }
492
+ if (
493
+ typeof this.policy.holder !== "string" ||
494
+ this.policy.holder.trim() === ""
495
+ ) {
496
+ throw this.fail("INVALID_POLICY", "request");
497
+ }
498
+ }
499
+
500
+ admitStage(): { readonly isProtected: boolean } {
501
+ let table: ReturnType<typeof stagePolicy>;
502
+ try {
503
+ table = stagePolicy(this.policy.stages);
504
+ } catch {
505
+ throw this.fail("INVALID_POLICY", "request");
506
+ }
507
+ try {
508
+ table.assertStackOwnsStage(this.request.stack, this.request.stage);
509
+ if (this.request.operation === "destroy") {
510
+ table.assertDestructiveStage(this.request.stage);
511
+ }
512
+ return { isProtected: table.isProtectedStage(this.request.stage) };
513
+ } catch (error) {
514
+ if (error instanceof StagePolicyError) {
515
+ throw this.fail(error.code, "admission");
516
+ }
517
+ throw this.fail("INVALID_POLICY", "request");
518
+ }
519
+ }
520
+
521
+ /**
522
+ * The consumer's installed Alchemy must be the version whose plan output
523
+ * the adapter reads. Checked before any child runs.
524
+ *
525
+ * The version is read from the manifest of the package that owns the CLI
526
+ * the children run: resolve `alchemy/bin/alchemy.js` from the consumer
527
+ * (the one specifier `executeAlchemyEntry` resolves, and one the package
528
+ * exports), then walk up to the nearest `package.json` named `alchemy`
529
+ * and read it from disk. `alchemy/package.json` is not on the package's
530
+ * `exports` map at the baseline, so resolving it as a module specifier
531
+ * fails on the real package; a file read does not consult `exports`.
532
+ */
533
+ installedAlchemyVersion(): string {
534
+ let version: unknown;
535
+ try {
536
+ const cli = createRequire(this.entry.from).resolve(
537
+ "alchemy/bin/alchemy.js"
538
+ );
539
+ version = alchemyManifestVersion(cli);
540
+ } catch {
541
+ throw this.fail("PREPARATION_FAILED", "admission");
542
+ }
543
+ if (version !== PLAN_OUTPUT_ALCHEMY_VERSION) {
544
+ throw this.fail("UNSUPPORTED_ALCHEMY_VERSION", "admission");
545
+ }
546
+ return version;
547
+ }
548
+
549
+ async prepareEntry(): Promise<void> {
550
+ if (this.entry.bundledEntry !== undefined) {
551
+ this.bundledEntry = this.entry.bundledEntry;
552
+ return;
553
+ }
554
+ try {
555
+ // On demand, as in `executeAlchemyEntry`: esbuild loads only for a
556
+ // consumer that asks this package to bundle.
557
+ const { bundleAlchemyEntry } = await import("../bundle-alchemy-entry.ts");
558
+ this.bundledEntry = await bundleAlchemyEntry(this.entry.bundle);
559
+ } catch {
560
+ throw this.fail("PREPARATION_FAILED", "admission");
561
+ }
562
+ }
563
+
564
+ // ── state ────────────────────────────────────────────────────────────
565
+
566
+ /**
567
+ * Run `body` under one stage lease. The lease is acquired at
568
+ * `acquirePhase`, and every child `body` launches carries it, so no other
569
+ * writer can reach the stage from the first read to the last decision,
570
+ * and a child that writes can only do so under this lease.
571
+ *
572
+ * Acceptance is the fenced renewal: it changes no rows unless this
573
+ * holder's unexpired row is still there, and fails with `lost` when the
574
+ * lease expired or was taken over. `body` calls `accept` after its reads
575
+ * and before any decision that precedes a mutation, so nothing is applied
576
+ * on reads the lease did not cover. Independently of that, **every exit
577
+ * from the window passes the fence**: whether `body` returned or threw,
578
+ * and wherever it threw from, the lease is checked before the outcome is
579
+ * classified. A lost lease is `OWNERSHIP_LOST` at the phase the run was
580
+ * in, ahead of whatever else was found there. No early return or new
581
+ * throw inside `body` can skip that check, because it is not in `body`.
582
+ * A store that cannot be reached for the check while the body's own
583
+ * failure stands reports the body's failure; a fence that holds lets a
584
+ * genuine store or child failure through unchanged.
585
+ *
586
+ * A successful release proves nothing (see `StageLease`); a release that
587
+ * fails after a good body is `LEASE_RELEASE_FAILED` at `releasePhase`.
588
+ */
589
+ private async withLease<T>(
590
+ acquirePhase: AlchemyLifecyclePhase,
591
+ releasePhase: AlchemyLifecyclePhase,
592
+ body: (
593
+ lease: StageLease,
594
+ accept: (phase: AlchemyLifecyclePhase) => Promise<void>
595
+ ) => Promise<T>
596
+ ): Promise<T> {
597
+ let lease: StageLease;
598
+ try {
599
+ lease = await Effect.runPromise(
600
+ this.state.acquireStageOwnership({
601
+ ...this.target,
602
+ holder: this.policy.holder,
603
+ ...(this.policy.ownershipTtlMillis === undefined
604
+ ? {}
605
+ : { ttlMillis: this.policy.ownershipTtlMillis }),
606
+ })
607
+ );
608
+ } catch (error) {
609
+ throw this.fail(
610
+ ownershipRefusal(error) === "held"
611
+ ? "STAGE_HELD"
612
+ : "STATE_STORE_UNAVAILABLE",
613
+ acquirePhase
614
+ );
615
+ }
616
+ const accept = (phase: AlchemyLifecyclePhase): Promise<void> =>
617
+ this.fromStore(phase, lease.renew());
618
+ let value: T | undefined;
619
+ let failed = false;
620
+ let thrown: unknown;
621
+ try {
622
+ value = await body(lease, accept);
623
+ } catch (error) {
624
+ failed = true;
625
+ thrown = error;
626
+ }
627
+ // The fence check no path through the window can skip.
628
+ const fence = await fenceState(lease);
629
+ const failure = failed
630
+ ? this.classifyStateFailure(thrown, acquirePhase)
631
+ : undefined;
632
+ const phase = failure?.phase ?? releasePhase;
633
+ if (fence === "lost") {
634
+ await releaseQuietly(lease);
635
+ throw this.fail("OWNERSHIP_LOST", phase);
636
+ }
637
+ if (failure !== undefined) {
638
+ await releaseQuietly(lease);
639
+ throw failure;
640
+ }
641
+ if (fence === "unreachable") {
642
+ await releaseQuietly(lease);
643
+ throw this.fail("STATE_STORE_UNAVAILABLE", phase);
644
+ }
645
+ try {
646
+ await Effect.runPromise(lease.release());
647
+ } catch {
648
+ // Release carries no ownership-loss signal: it succeeds once the row
649
+ // is gone or belongs to a later holder. A release that fails is a
650
+ // different fact: the store could not be reached, and this holder's
651
+ // row may still be there, blocking the stage until it expires.
652
+ throw this.fail("LEASE_RELEASE_FAILED", releasePhase);
653
+ }
654
+ return value as T;
655
+ }
656
+
657
+ /** Run one store effect; its failure becomes a fixed code at `phase`. */
658
+ private async fromStore<T>(
659
+ phase: AlchemyLifecyclePhase,
660
+ effect: Effect.Effect<T, unknown>
661
+ ): Promise<T> {
662
+ try {
663
+ return await Effect.runPromise(effect);
664
+ } catch (error) {
665
+ throw this.classifyStateFailure(error, phase);
666
+ }
667
+ }
668
+
669
+ private classifyStateFailure(
670
+ error: unknown,
671
+ phase: AlchemyLifecyclePhase
672
+ ): AlchemyLifecycleError {
673
+ if (error instanceof AlchemyLifecycleError) {
674
+ return error;
675
+ }
676
+ const refusal = ownershipRefusal(error);
677
+ if (refusal === "lost") {
678
+ return this.fail("OWNERSHIP_LOST", phase);
679
+ }
680
+ if (refusal === "held") {
681
+ return this.fail("STAGE_HELD", phase);
682
+ }
683
+ return this.fail("STATE_STORE_UNAVAILABLE", phase);
684
+ }
685
+
686
+ /** Every resource record and the stack output. Call under the lease. */
687
+ private async readPersistedState(
688
+ phase: AlchemyLifecyclePhase
689
+ ): Promise<PersistedState> {
690
+ const view = await this.fromStore(
691
+ phase,
692
+ this.state.snapshotStage(this.target)
693
+ );
694
+ if (
695
+ !Array.isArray(view.resources) ||
696
+ view.resources.some((fqn) => typeof fqn !== "string" || fqn === "")
697
+ ) {
698
+ throw this.fail("STATE_STORE_INVALID", phase);
699
+ }
700
+ const records = await Promise.all(
701
+ [...view.resources].toSorted().map(async (fqn) => ({
702
+ fqn,
703
+ state: await this.fromStore(
704
+ phase,
705
+ this.state.get({ ...this.target, fqn })
706
+ ),
707
+ }))
708
+ );
709
+ if (records.some(({ state }) => !isRecord(state))) {
710
+ // A listed resource with no readable record is not a resource the
711
+ // check can pass over.
712
+ throw this.fail("STATE_STORE_INVALID", phase);
713
+ }
714
+ return { output: view.output, resources: records };
715
+ }
716
+
717
+ // ── execution ────────────────────────────────────────────────────────
718
+
719
+ private stageArgs(): readonly string[] {
720
+ return ["--stage", this.request.stage];
721
+ }
722
+
723
+ /**
724
+ * Where a diagnostics write failure is reported.
725
+ *
726
+ * Before any mutating child has started, it is reported here and now: the
727
+ * operator asked for a record, the record cannot be kept, and nothing has
728
+ * been changed yet, so refusing costs nothing.
729
+ *
730
+ * Once a deploy or destroy child has started, it is **retained** and
731
+ * reported only after the operation has run to its end, the way a failed
732
+ * lease release is. The apply succeeded; failing here would abandon the
733
+ * convergence check on a good deploy and invite an operator to destroy and
734
+ * retry a stage that is fine. A missing record is not a reason to treat a
735
+ * successful mutation as a failed one, and the run still ends in
736
+ * `CHILD_DIAGNOSTICS_UNWRITABLE` — after the postconditions have run, with
737
+ * the mutation certainty the operation actually reached.
738
+ */
739
+ private noteDiagnosticsFailure(failed: boolean): void {
740
+ if (!failed) {
741
+ return;
742
+ }
743
+ this.diagnosticsUnwritable = true;
744
+ if (this.certainty !== "mutation-may-have-occurred") {
745
+ throw this.fail("CHILD_DIAGNOSTICS_UNWRITABLE", "execution", {
746
+ namesDiagnostics: true,
747
+ });
748
+ }
749
+ }
750
+
751
+ /**
752
+ * The retained record failure, once the operation itself is complete. The
753
+ * operation's own failures are reported ahead of it, as they are for a
754
+ * failed lease release.
755
+ */
756
+ assertDiagnosticsWritten(): void {
757
+ if (this.diagnosticsUnwritable) {
758
+ throw this.fail("CHILD_DIAGNOSTICS_UNWRITABLE", "execution", {
759
+ namesDiagnostics: true,
760
+ });
761
+ }
762
+ }
763
+
764
+ /**
765
+ * The diagnostics section for one child, opened and headed before the
766
+ * child starts. A path that cannot be opened refuses the run while nothing
767
+ * has been mutated; after that it is retained and the child runs without a
768
+ * record rather than a good apply being abandoned over one.
769
+ */
770
+ private openDiagnostics(
771
+ child: LifecycleChild
772
+ ): ChildDiagnosticsSection | undefined {
773
+ if (this.childDiagnostics === undefined) {
774
+ return undefined;
775
+ }
776
+ try {
777
+ return openChildDiagnostics({
778
+ child,
779
+ diagnostics: this.childDiagnostics,
780
+ operation: this.request.operation,
781
+ stack: this.request.stack,
782
+ stage: this.request.stage,
783
+ });
784
+ } catch {
785
+ this.noteDiagnosticsFailure(true);
786
+ return undefined;
787
+ }
788
+ }
789
+
790
+ /**
791
+ * Run one child under `lease` and return its stdout for parsing. Its output
792
+ * goes nowhere else unless the consumer asked for `childDiagnostics`, which
793
+ * writes a redacted copy and never touches what is returned here. The
794
+ * child's environment carries the lease, so the adapter in the child adopts
795
+ * it rather than taking its own: there is no child without a lease, and a
796
+ * child that writes outside this lease is refused by the store, not by this
797
+ * module. A `plan` child leaves the certainty where it is unless it is the
798
+ * first child; a mutating child advances it before it starts.
799
+ */
800
+ private async runChild(
801
+ child: LifecycleChild,
802
+ args: readonly string[],
803
+ lease: StageLease
804
+ ): Promise<string> {
805
+ if (this.bundledEntry === undefined) {
806
+ throw this.fail("PREPARATION_FAILED", "admission");
807
+ }
808
+ const record = this.openDiagnostics(child);
809
+ if (child !== "plan") {
810
+ this.certainty = "mutation-may-have-occurred";
811
+ } else if (this.certainty === "not-started") {
812
+ this.certainty = "read-only-started";
813
+ }
814
+ const { env, from } = this.entry;
815
+ let stdout: string | undefined;
816
+ try {
817
+ const result = await executeAlchemyEntry({
818
+ args: [
819
+ ...args,
820
+ ...(this.entry.envFile === undefined
821
+ ? []
822
+ : ["--env-file", this.entry.envFile]),
823
+ ],
824
+ bundledEntry: this.bundledEntry,
825
+ // The bundle was prepared up front, so the child is handed its path
826
+ // and the bundle root would otherwise be lost. Resolve the working
827
+ // directory through the same chain `executeAlchemyEntry` uses.
828
+ cwd: resolveAlchemyChildCwd(this.entry),
829
+ env: { ...(env ?? process.env), ...lease.childEnvironment() },
830
+ from,
831
+ maxBuffer: EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER,
832
+ // The record is written from the raw capture and redacted on its
833
+ // way to the file, so no `redact` runs over what is returned: the
834
+ // plan text parsed and hashed below is the child's own bytes.
835
+ ...(record === undefined ? {} : { onCaptured: record.append }),
836
+ stdio: "pipe",
837
+ });
838
+ stdout = result.stdout ?? "";
839
+ } catch {
840
+ // Held, not thrown yet: the record is closed first, and a child that
841
+ // failed is the finding, ahead of a record that could not be written.
842
+ stdout = undefined;
843
+ }
844
+ record?.close();
845
+ if (stdout === undefined) {
846
+ throw this.fail("CHILD_FAILED", "execution", {
847
+ namesDiagnostics: true,
848
+ });
849
+ }
850
+ this.noteDiagnosticsFailure(record?.failure() !== undefined);
851
+ return stdout;
852
+ }
853
+
854
+ private effectsOf(output: string, phase: AlchemyLifecyclePhase): PlanEffects {
855
+ let effects: PlanEffects;
856
+ try {
857
+ effects = parsePlanEffects(output);
858
+ } catch {
859
+ throw this.fail("UNKNOWN_EFFECT", phase);
860
+ }
861
+ if (hasRepeatedIds(effects)) {
862
+ // Two rows with one FQN name one identity twice, so no check below
863
+ // could bind to either.
864
+ throw this.fail("AMBIGUOUS_RESOURCE", phase);
865
+ }
866
+ return effects;
867
+ }
868
+
869
+ private planArgs(adopt: boolean): readonly string[] {
870
+ return [
871
+ "deploy",
872
+ "--dry-run",
873
+ ...(adopt ? ["--adopt"] : []),
874
+ ...this.stageArgs(),
875
+ ];
876
+ }
877
+
878
+ /**
879
+ * A dry-run plan bracketed by two persisted-state reads, all under the
880
+ * lease the caller holds, so no other writer can reach the stage while the
881
+ * child plans. The lease is accepted, at `phase`, before anything is
882
+ * decided on: a child that could not adopt a lease this run has lost is
883
+ * the lease loss (`OWNERSHIP_LOST`), not a child failure, and the parent's
884
+ * own fenced renewal is what tells the two apart, never the child's
885
+ * output. The reads must still agree: a planning child that wrote is
886
+ * reported as `STATE_CHANGED`, ahead of the child's own exit status. A
887
+ * child that failed under a lease that held is `CHILD_FAILED`.
888
+ */
889
+ private async readOnlyPlan(
890
+ args: readonly string[],
891
+ lease: StageLease,
892
+ accept: (phase: AlchemyLifecyclePhase) => Promise<void>,
893
+ phase: AlchemyLifecyclePhase
894
+ ): Promise<{
895
+ readonly before: PersistedState;
896
+ readonly effects: PlanEffects;
897
+ readonly text: string;
898
+ }> {
899
+ const before = await this.readPersistedState("state");
900
+ let text = "";
901
+ let childFailure: AlchemyLifecycleError | undefined;
902
+ try {
903
+ text = await this.runChild("plan", args, lease);
904
+ } catch (error) {
905
+ childFailure = error as AlchemyLifecycleError;
906
+ }
907
+ const after = await this.readPersistedState("postcondition");
908
+ await accept(phase);
909
+ if (!isDeepStrictEqual(before, after)) {
910
+ throw this.fail("STATE_CHANGED", "postcondition");
911
+ }
912
+ if (childFailure !== undefined) {
913
+ throw childFailure;
914
+ }
915
+ return { before, effects: this.effectsOf(text, "postcondition"), text };
916
+ }
917
+
918
+ // ── operations ───────────────────────────────────────────────────────
919
+
920
+ private planHashOf(text: string): string | undefined {
921
+ const { firstDeploy } = this.policy;
922
+ if (firstDeploy === undefined) {
923
+ return undefined;
924
+ }
925
+ try {
926
+ return firstDeployPlanHash({
927
+ planText: text,
928
+ sourceSha: firstDeploy.sourceSha,
929
+ stack: this.request.stack,
930
+ stage: this.request.stage,
931
+ });
932
+ } catch {
933
+ throw this.fail("INVALID_POLICY", "admission");
934
+ }
935
+ }
936
+
937
+ async plan(
938
+ alchemyVersion: string,
939
+ isProtected: boolean
940
+ ): Promise<AlchemyLifecycleResult> {
941
+ const { before, effects, text } = await this.withLease(
942
+ "state",
943
+ "state",
944
+ async (lease, accept) =>
945
+ await this.readOnlyPlan(
946
+ this.planArgs(this.policy.adopt === true),
947
+ lease,
948
+ accept,
949
+ "state"
950
+ )
951
+ );
952
+ const firstDeploy = isProtected && isEmptyState(before);
953
+ const planHash = firstDeploy ? this.planHashOf(text) : undefined;
954
+ return {
955
+ alchemyVersion,
956
+ effects,
957
+ firstDeploy,
958
+ mutation: "read-only-started",
959
+ operation: "plan",
960
+ ...(planHash === undefined ? {} : { planHash }),
961
+ stack: this.request.stack,
962
+ stage: this.request.stage,
963
+ };
964
+ }
965
+
966
+ private admitFirstDeploy(effects: PlanEffects, text: string): void {
967
+ // A first deploy may only create or adopt: `adopted` is the create of a
968
+ // resource the provider already finds, and it only plans for a record
969
+ // with no prior state. `orphaned` drops a state row, as `delete` does.
970
+ if (
971
+ effects.counts.update +
972
+ effects.counts.replace +
973
+ effects.counts.delete +
974
+ effects.counts.orphaned >
975
+ 0
976
+ ) {
977
+ throw this.fail("EFFECT_NOT_PERMITTED", "admission");
978
+ }
979
+ const planHash = this.planHashOf(text);
980
+ const { firstDeploy } = this.policy;
981
+ if (firstDeploy === undefined || planHash === undefined) {
982
+ throw this.fail("FIRST_DEPLOY_UNAUTHORIZED", "admission");
983
+ }
984
+ try {
985
+ firstDeployAuthorization({
986
+ authorizedHashes: firstDeploy.authorizedHashes,
987
+ planText: text,
988
+ sourceSha: firstDeploy.sourceSha,
989
+ stack: this.request.stack,
990
+ stage: this.request.stage,
991
+ });
992
+ } catch {
993
+ throw this.fail("FIRST_DEPLOY_UNAUTHORIZED", "admission", { planHash });
994
+ }
995
+ }
996
+
997
+ private retainedMarkers(): readonly RetainedIdentityMarker[] {
998
+ const markers = this.policy.retainedIdentities ?? [];
999
+ if (
1000
+ markers.length === 0 ||
1001
+ markers.some((marker) => marker.value === undefined)
1002
+ ) {
1003
+ // A protected stage with no named identities, or a marker with no
1004
+ // expected value, asserts nothing before the apply.
1005
+ throw this.fail("INVALID_POLICY", "admission");
1006
+ }
1007
+ return markers;
1008
+ }
1009
+
1010
+ private assertRetained(
1011
+ after: StateSnapshot,
1012
+ before: StateSnapshot | undefined,
1013
+ phase: AlchemyLifecyclePhase
1014
+ ): void {
1015
+ try {
1016
+ assertRetainedIdentities({
1017
+ after,
1018
+ markers: this.retainedMarkers(),
1019
+ ...(before === undefined ? {} : { before }),
1020
+ });
1021
+ } catch (error) {
1022
+ if (error instanceof AlchemyLifecycleError) {
1023
+ throw error;
1024
+ }
1025
+ throw this.fail("RESOURCE_IDENTITY_MISMATCH", phase);
1026
+ }
1027
+ }
1028
+
1029
+ /** Admit the read-only plan of a deploy. Runs under the lease. */
1030
+ private admitDeploy(
1031
+ before: PersistedState,
1032
+ effects: PlanEffects,
1033
+ text: string,
1034
+ isProtected: boolean,
1035
+ firstDeploy: boolean
1036
+ ): void {
1037
+ if (firstDeploy) {
1038
+ this.admitFirstDeploy(effects, text);
1039
+ return;
1040
+ }
1041
+ if (!isProtected) {
1042
+ return;
1043
+ }
1044
+ // `orphaned` leaves the cloud object alone but drops its state row, so
1045
+ // the stage forgets a frozen identity as surely as a `delete` does.
1046
+ if (
1047
+ effects.counts.replace + effects.counts.delete + effects.counts.orphaned >
1048
+ 0
1049
+ ) {
1050
+ throw this.fail("EFFECT_NOT_PERMITTED", "admission");
1051
+ }
1052
+ this.assertRetained(
1053
+ persistedToSnapshot(this.target, before),
1054
+ undefined,
1055
+ "admission"
1056
+ );
1057
+ }
1058
+
1059
+ /**
1060
+ * The plan said what it would create; the state must now record it. A
1061
+ * planned create resolves to exactly one candidate FQN. A candidate is a
1062
+ * record settled after the apply that either was not recorded before it,
1063
+ * or was recorded in flight (`creating`, `deleting`) **and is the FQN the
1064
+ * create row names**: an interrupted deploy's retry creates at the same
1065
+ * FQN, and that recovery is the ordinary accident this operation exists
1066
+ * for.
1067
+ *
1068
+ * A plan row carries the resource's FQN, so a row names one persisted
1069
+ * identity exactly, under any namespace. An in-flight record at another
1070
+ * FQN (`other/Worker` for a `[Worker]` row) is not the one the row names,
1071
+ * so it never qualifies as a recovery. No candidate is a create that did
1072
+ * not happen.
1073
+ */
1074
+ private createdFqns(
1075
+ before: PersistedState,
1076
+ after: PersistedState,
1077
+ effects: PlanEffects
1078
+ ): readonly string[] {
1079
+ const planned = effects.resources.filter(
1080
+ ({ action }) => action === "create"
1081
+ );
1082
+ const namedByRow = new Set(planned.map(({ id }) => id));
1083
+ const priorFqns = new Set(before.resources.map(({ fqn }) => fqn));
1084
+ const inFlightBefore = new Set(
1085
+ before.resources
1086
+ .filter((record) => IN_FLIGHT_STATUSES.has(statusOf(record)))
1087
+ .map(({ fqn }) => fqn)
1088
+ );
1089
+ const candidates = after.resources
1090
+ .filter((record) => !IN_FLIGHT_STATUSES.has(statusOf(record)))
1091
+ .filter(
1092
+ ({ fqn }) =>
1093
+ !priorFqns.has(fqn) ||
1094
+ (inFlightBefore.has(fqn) && namedByRow.has(fqn))
1095
+ )
1096
+ .map(({ fqn }) => fqn);
1097
+ const created = resolveRows(planned, candidates);
1098
+ if (created === undefined) {
1099
+ throw this.fail("DEPLOY_INCOMPLETE", "postcondition");
1100
+ }
1101
+ return created;
1102
+ }
1103
+
1104
+ private assertConverged(effects: PlanEffects, after: PersistedState): void {
1105
+ const tolerated = new Set(this.policy.nonConvergentResources);
1106
+ // A binding row with work is work the apply left behind, even under a
1107
+ // `noop` resource: a provider with its own `diff` decides the resource's
1108
+ // action apart from its binding rows. The adapter counts binding changes
1109
+ // but attributes none to a resource, so no policy can tolerate one.
1110
+ if (effects.bindingChanges > 0) {
1111
+ throw this.fail("NOT_CONVERGED", "postcondition");
1112
+ }
1113
+ // A task row prints only when the task still has work (`run`) or is
1114
+ // still to be dropped, so any task row is work the apply left behind.
1115
+ if (effects.tasks.length > 0) {
1116
+ throw this.fail("NOT_CONVERGED", "postcondition");
1117
+ }
1118
+ const pending = effects.resources.filter(({ action }) => action !== "noop");
1119
+ // A converged stage records every resource the plan names, so each
1120
+ // pending row must resolve to exactly one recorded FQN.
1121
+ const fqns = resolveRows(
1122
+ pending,
1123
+ after.resources.map(({ fqn }) => fqn)
1124
+ );
1125
+ if (fqns === undefined) {
1126
+ throw this.fail("NOT_CONVERGED", "postcondition");
1127
+ }
1128
+ const unresolved = pending.some(
1129
+ ({ action }, index) =>
1130
+ !(action === "update" && tolerated.has(fqns[index] ?? ""))
1131
+ );
1132
+ if (unresolved) {
1133
+ throw this.fail("NOT_CONVERGED", "postcondition");
1134
+ }
1135
+ }
1136
+
1137
+ async deploy(
1138
+ alchemyVersion: string,
1139
+ isProtected: boolean
1140
+ ): Promise<AlchemyLifecycleResult> {
1141
+ const adopt = this.policy.adopt === true;
1142
+ // One lease from the first admission read to the convergence decision.
1143
+ // The apply child adopts it, so the stage is never unowned between the
1144
+ // admitted plan and the apply, and never unowned while the child runs.
1145
+ const { convergence, created, effects, firstDeploy } = await this.withLease(
1146
+ "state",
1147
+ "postcondition",
1148
+ async (lease, accept) => {
1149
+ const plan = await this.readOnlyPlan(
1150
+ this.planArgs(adopt),
1151
+ lease,
1152
+ accept,
1153
+ "state"
1154
+ );
1155
+ // Only a protected stage has a first deploy to authorize: a disposable
1156
+ // stage is created fresh on every run and constrained by nothing.
1157
+ const admittedFirstDeploy = isProtected && isEmptyState(plan.before);
1158
+ this.admitDeploy(
1159
+ plan.before,
1160
+ plan.effects,
1161
+ plan.text,
1162
+ isProtected,
1163
+ admittedFirstDeploy
1164
+ );
1165
+
1166
+ await this.runChild(
1167
+ "deploy",
1168
+ [
1169
+ "deploy",
1170
+ ...(adopt ? ["--adopt"] : []),
1171
+ ...this.stageArgs(),
1172
+ "--yes",
1173
+ ],
1174
+ lease
1175
+ );
1176
+
1177
+ // The convergence dry-run is the same read-only plan as admission's:
1178
+ // the state read before it is the post-apply state the
1179
+ // postconditions are checked against, and the read after it refuses
1180
+ // a child that wrote.
1181
+ const post = await this.readOnlyPlan(
1182
+ this.planArgs(false),
1183
+ lease,
1184
+ accept,
1185
+ "postcondition"
1186
+ );
1187
+ const after = post.before;
1188
+ if (after.resources.length === 0) {
1189
+ throw this.fail("DEPLOY_INCOMPLETE", "postcondition");
1190
+ }
1191
+ const createdNow = this.createdFqns(plan.before, after, plan.effects);
1192
+ if (isProtected && !admittedFirstDeploy) {
1193
+ this.assertRetained(
1194
+ persistedToSnapshot(this.target, after),
1195
+ persistedToSnapshot(this.target, plan.before),
1196
+ "postcondition"
1197
+ );
1198
+ }
1199
+ this.assertConverged(post.effects, after);
1200
+ return {
1201
+ convergence: post.effects,
1202
+ created: createdNow,
1203
+ effects: plan.effects,
1204
+ firstDeploy: admittedFirstDeploy,
1205
+ };
1206
+ }
1207
+ );
1208
+
1209
+ return {
1210
+ alchemyVersion,
1211
+ convergence,
1212
+ created,
1213
+ effects,
1214
+ firstDeploy,
1215
+ mutation: "mutation-may-have-occurred",
1216
+ operation: "deploy",
1217
+ stack: this.request.stack,
1218
+ stage: this.request.stage,
1219
+ };
1220
+ }
1221
+
1222
+ async destroy(alchemyVersion: string): Promise<AlchemyLifecycleResult> {
1223
+ // One lease across the destroy child and the cleanup that follows it.
1224
+ const { cleanup, effects } = await this.withLease(
1225
+ "state",
1226
+ "postcondition",
1227
+ async (lease, accept) => {
1228
+ const text = await this.runChild(
1229
+ "destroy",
1230
+ ["destroy", ...this.stageArgs(), "--yes"],
1231
+ lease
1232
+ );
1233
+ const destroyed = this.effectsOf(text, "postcondition");
1234
+ const view = await this.fromStore(
1235
+ "postcondition",
1236
+ this.state.snapshotStage(this.target)
1237
+ );
1238
+ await accept("postcondition");
1239
+ if (view.empty !== true) {
1240
+ throw this.fail("DESTROY_RESIDUE", "postcondition");
1241
+ }
1242
+ const outcome = await this.fromStore(
1243
+ "postcondition",
1244
+ lease.deleteEmptyStage()
1245
+ );
1246
+ if (outcome === "occupied") {
1247
+ throw this.fail("DESTROY_RESIDUE", "postcondition");
1248
+ }
1249
+ return { cleanup: outcome, effects: destroyed };
1250
+ }
1251
+ );
1252
+ return {
1253
+ alchemyVersion,
1254
+ cleanup,
1255
+ effects,
1256
+ firstDeploy: false,
1257
+ mutation: "mutation-may-have-occurred",
1258
+ operation: "destroy",
1259
+ stack: this.request.stack,
1260
+ stage: this.request.stage,
1261
+ };
1262
+ }
1263
+ }
1264
+
1265
+ /**
1266
+ * Run one lifecycle operation, in the one order the operation runs in.
1267
+ *
1268
+ * `plan`: read the persisted state under the stage lease, run the dry-run
1269
+ * child, read the state again, and refuse if anything — a resource record
1270
+ * or the stack output — changed. Returns the plan's effects and, for an
1271
+ * empty stage with a first-deploy policy, the hash an operator authorizes.
1272
+ *
1273
+ * `deploy`: the same read-only plan, then admission on it. An empty stage is
1274
+ * a first deploy: the plan may only create, and its hash must be on the
1275
+ * authorized list. A protected stage with state refuses `replace` and
1276
+ * `delete`, and its retained identities must hold before the apply. Then the
1277
+ * apply child, then the persisted state again: it must record what the plan
1278
+ * created and, on a protected stage, the same identities as before. Then a
1279
+ * second dry-run plan, which must be a no-op except an `update` on a resource
1280
+ * the policy names non-convergent. A binding change or a task row in that
1281
+ * plan is work left behind, and no policy tolerates it.
1282
+ *
1283
+ * `destroy`: refused on a protected stage. Then, under the stage lease, the
1284
+ * destroy child, then the atomic stage view must be empty and the empty
1285
+ * output row is removed. An unreadable store fails; it never reads as empty.
1286
+ *
1287
+ * Each operation holds one stage lease from its first read to its last
1288
+ * decision, and every child adopts it through its environment. The stage is
1289
+ * never unowned while an operation runs, so no other writer can interleave,
1290
+ * and a child that takes no ownership is refused by the store at its first
1291
+ * write.
1292
+ *
1293
+ * Every failure is an `AlchemyLifecycleError`. After a deploy or destroy
1294
+ * child was started, no failure reports `not-started`.
1295
+ *
1296
+ * `childDiagnostics` is the one opt-in that keeps what the children printed:
1297
+ * both streams of every child, each passed whole through the consumer's own
1298
+ * redactor, are appended to the consumer's own file under a per-child
1299
+ * header, and a `CHILD_FAILED` then names that path so an operator knows
1300
+ * where to look. Nothing about the operation changes otherwise: a record
1301
+ * that cannot be written refuses the run only while nothing has been
1302
+ * mutated, and after that is reported as `CHILD_DIAGNOSTICS_UNWRITABLE` once
1303
+ * the operation has finished, never in place of its postconditions.
1304
+ */
1305
+ export const runAlchemyLifecycle = async (
1306
+ options: RunAlchemyLifecycleOptions
1307
+ ): Promise<AlchemyLifecycleResult> => {
1308
+ const run = new LifecycleRun(options);
1309
+ run.validateRequest();
1310
+ const { isProtected } = run.admitStage();
1311
+ const alchemyVersion = run.installedAlchemyVersion();
1312
+ await run.prepareEntry();
1313
+ const result = await (async () => {
1314
+ switch (options.request.operation) {
1315
+ case "plan": {
1316
+ return await run.plan(alchemyVersion, isProtected);
1317
+ }
1318
+ case "deploy": {
1319
+ return await run.deploy(alchemyVersion, isProtected);
1320
+ }
1321
+ default: {
1322
+ return await run.destroy(alchemyVersion);
1323
+ }
1324
+ }
1325
+ })();
1326
+ // Last, so a diagnostics write that failed after the apply never stands in
1327
+ // the way of the convergence check it would otherwise abandon.
1328
+ run.assertDiagnosticsWritten();
1329
+ return result;
1330
+ };