@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,2142 @@
1
+ import { i as isLocalPreviewStage, n as executeAlchemyEntry, r as resolveAlchemyChildCwd, s as ALCHEMY_BASELINE } from "../execute-alchemy-entry-CZ7Knz4q.js";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import { appendFileSync, closeSync, openSync, readFileSync } from "node:fs";
6
+ import * as Alchemy from "alchemy";
7
+ import * as Output from "alchemy/Output";
8
+ import { tryFindProviderByType } from "alchemy/Provider";
9
+ import * as Effect from "effect/Effect";
10
+ import * as Layer from "effect/Layer";
11
+ import * as Option from "effect/Option";
12
+ import { State } from "alchemy/State";
13
+ import { allStages, deleteState } from "alchemy/State/Tree";
14
+ import { isDeepStrictEqual } from "node:util";
15
+ //#region src/alchemy/evaluate-stack.ts
16
+ var EvaluationProviders = class extends Alchemy.ProviderCollection()("factory-ci/evaluate-stack") {};
17
+ /** The lifecycle every provider evaluates with: read and list answer "absent"; a plan never applies. */
18
+ const absentProvider = (type) => ({
19
+ delete: () => Effect.die(`evaluateStack never deletes ${type}`),
20
+ list: () => Effect.succeed([]),
21
+ read: () => Effect.succeed(void 0),
22
+ reconcile: () => Effect.die(`evaluateStack never reconciles ${type}`)
23
+ });
24
+ /** Wrap the consumer's providers: Alchemy's own lookup finds each one, then its probes are stubbed. */
25
+ const evaluationProviders = (providers) => Layer.effect(EvaluationProviders, Effect.map(Effect.context(), (context) => ({
26
+ get: (type) => {
27
+ const found = Effect.provide(tryFindProviderByType(type), context);
28
+ return {
29
+ ...Option.getOrUndefined(Effect.runSync(found)),
30
+ ...absentProvider(type),
31
+ modes: void 0
32
+ };
33
+ },
34
+ kind: "ProviderCollection",
35
+ providers: {}
36
+ }))).pipe(Layer.provide(providers ?? Layer.empty));
37
+ /** The logical ids one prop's value references, or nothing when it references none. */
38
+ const upstreamOfProps = (props) => {
39
+ const byProp = {};
40
+ for (const [key, value] of Object.entries(props)) {
41
+ const ids = Object.values(Output.upstreamAny(value)).map((node) => node.LogicalId);
42
+ if (ids.length > 0) byProp[key] = ids;
43
+ }
44
+ return byProp;
45
+ };
46
+ /** Map plan nodes to the graph. A binding row carries Alchemy's Worker shape, `{ bindings: [{ name, type }] }`. */
47
+ const toGraph = (plan) => ({
48
+ bindings: Object.values(plan.resources).flatMap(({ bindings, resource }) => bindings.flatMap((row) => {
49
+ const target = Object.values(Output.upstreamAny(row.data))[0]?.LogicalId;
50
+ return (row.data?.bindings ?? []).map((entry) => ({
51
+ name: entry.name ?? row.sid,
52
+ target,
53
+ type: entry.type ?? "unknown",
54
+ worker: resource.LogicalId
55
+ }));
56
+ })),
57
+ resources: Object.values(plan.resources).map(({ resource }) => ({
58
+ id: resource.LogicalId,
59
+ props: resource.Props ?? {},
60
+ type: resource.Type,
61
+ upstreamByProp: upstreamOfProps(resource.Props ?? {})
62
+ }))
63
+ });
64
+ /**
65
+ * Run a stack program at `stage` and build the graph Alchemy would plan, with no state and no network:
66
+ * `Plan.make` runs under `inMemoryState()` and every provider read and list answers "absent".
67
+ */
68
+ const evaluateStack = ({ name, program, providers, stage }) => {
69
+ const stack = {
70
+ actions: {},
71
+ bindings: {},
72
+ name,
73
+ resources: {},
74
+ stage
75
+ };
76
+ const evaluation = program.pipe(Effect.flatMap((output) => Alchemy.Plan.make({
77
+ ...stack,
78
+ output
79
+ })), Effect.map(toGraph), Effect.provide(Layer.mergeAll(Layer.succeed(Alchemy.Stack, stack), Layer.succeed(Alchemy.Stage, stage), Alchemy.inMemoryState(), evaluationProviders(providers))), Effect.scoped);
80
+ return Effect.runPromise(evaluation);
81
+ };
82
+ //#endregion
83
+ //#region src/alchemy/retained-identity.ts
84
+ /** Every retained identity that did not hold. */
85
+ var RetainedIdentityError = class extends Error {
86
+ violations;
87
+ constructor(violations) {
88
+ const detail = violations.map(({ marker, reason }) => `${marker.fqn}.${marker.field} (${reason})`).join(", ");
89
+ super(`Retained resource identities did not hold: ${detail}.`);
90
+ this.name = "RetainedIdentityError";
91
+ this.violations = violations;
92
+ }
93
+ };
94
+ /**
95
+ * Read a persisted-state document into a snapshot of one stage.
96
+ *
97
+ * The persisted-state document holds every record in scope
98
+ * (`{ resources: [{ stack, stage, fqn, state }] }`); a single-record document
99
+ * is not this shape. A document covering the whole estate holds one fqn once
100
+ * per stage, so a marker naming it would match whichever record sorted
101
+ * first — a `prod` identity asserted against a `dev` record. `scope` narrows
102
+ * the document to the stack and stage the markers are about.
103
+ *
104
+ * Throws on anything that is not a resource inventory, and on a scoped
105
+ * document that still records one fqn twice. A state this module cannot read
106
+ * unambiguously is never treated as a state with nothing in it, because that
107
+ * reading turns a broken read into a passing assert.
108
+ */
109
+ const parseStateSnapshot = (text, scope = {}) => {
110
+ let parsed;
111
+ try {
112
+ parsed = JSON.parse(text);
113
+ } catch {
114
+ throw new TypeError("Alchemy state is not valid structured data.");
115
+ }
116
+ if (typeof parsed !== "object" || parsed === null || !("resources" in parsed) || !Array.isArray(parsed.resources)) throw new TypeError("Alchemy state does not contain a resource inventory.");
117
+ const recorded = parsed.resources.filter(({ stack }) => scope.stack === void 0 || stack === scope.stack).filter(({ stage }) => scope.stage === void 0 || stage === scope.stage);
118
+ const repeated = recorded.map(({ fqn }) => String(fqn)).filter((fqn, index, all) => all.indexOf(fqn) !== index);
119
+ if (repeated.length > 0) throw new TypeError(`Alchemy state records ${[...new Set(repeated)].toSorted().join(", ")} more than once: narrow the export to one stack and stage.`);
120
+ return { resources: recorded };
121
+ };
122
+ /**
123
+ * The identity a snapshot records for a marker, or `undefined` when the
124
+ * snapshot records no resource that matches the marker.
125
+ */
126
+ const recordedIdentity = (snapshot, marker) => {
127
+ const state = snapshot.resources.find(({ fqn }) => fqn === marker.fqn)?.state;
128
+ if (state === void 0 || state.fqn !== marker.fqn || state.kind !== void 0 && state.kind !== "resource" || state.resourceType !== marker.resourceType) return;
129
+ const value = state[marker.section]?.[marker.field];
130
+ return typeof value === "string" && value !== "" ? value : void 0;
131
+ };
132
+ const violationFor = (marker, after, before) => {
133
+ const recordedAfter = recordedIdentity(after, marker);
134
+ if (recordedAfter === void 0) return {
135
+ marker,
136
+ reason: "missing"
137
+ };
138
+ if (marker.value !== void 0 && marker.value !== recordedAfter) return {
139
+ after: recordedAfter,
140
+ marker,
141
+ reason: "unexpected"
142
+ };
143
+ if (before === void 0) return;
144
+ const recordedBefore = recordedIdentity(before, marker);
145
+ if (recordedBefore !== void 0 && recordedBefore !== recordedAfter) return {
146
+ after: recordedAfter,
147
+ before: recordedBefore,
148
+ marker,
149
+ reason: "changed"
150
+ };
151
+ };
152
+ /**
153
+ * Throw `RetainedIdentityError` unless every retained identity still holds.
154
+ *
155
+ * A marker that names no `value` and has no `before` snapshot to compare
156
+ * against asserts nothing, so it is a `TypeError` rather than a pass. So is an
157
+ * empty marker list: a check with nothing in it must not read as a proof.
158
+ */
159
+ const assertRetainedIdentities = ({ after, before, markers }) => {
160
+ if (markers.length === 0) throw new TypeError("assertRetainedIdentities needs at least one retained identity marker.");
161
+ for (const marker of markers) if (marker.value === void 0 && before === void 0) throw new TypeError(`Retained identity ${marker.fqn}.${marker.field} asserts nothing: give it a value or pass a before snapshot.`);
162
+ const violations = markers.map((marker) => violationFor(marker, after, before)).filter((violation) => violation !== void 0);
163
+ if (violations.length > 0) throw new RetainedIdentityError(violations);
164
+ };
165
+ //#endregion
166
+ //#region src/alchemy/credential-preflight.ts
167
+ /**
168
+ * Cloudflare credential preflight for an Alchemy deploy.
169
+ *
170
+ * Two projects built this twice. Paitronage
171
+ * (`scripts/alchemy/credential-preflight.ts` plus
172
+ * `scripts/alchemy/cloudflare-token-policy.ts`) and firedup
173
+ * (`scripts/alchemy/local-credentials.ts`) both resolve a Cloudflare API
174
+ * token, verify it is live, and refuse to deploy unless its permission groups
175
+ * match an exact reviewed list. What repeats is the check. What does not
176
+ * repeat is the account, the permission list, the resource scope, and where
177
+ * the credential comes from, so every one of those is an input.
178
+ *
179
+ * **No credential value is ever printed.** Errors name environment variables and
180
+ * missing groups from the caller-owned permission requirements. Untrusted API
181
+ * status, receipt group names, and resource identifiers are never reflected.
182
+ * The result carries the token id, which Cloudflare's own verification endpoint
183
+ * returns and which is not a secret.
184
+ */
185
+ const CLOUDFLARE_API = "https://api.cloudflare.com/client/v4";
186
+ /**
187
+ * The environment variables a hosted deploy carries and a trusted-local
188
+ * deploy must not. A trusted-local run resolves its credential from the
189
+ * project's own secret manager; an ambient token there means the run is not
190
+ * the run it claims to be.
191
+ */
192
+ const HOSTED_CLOUDFLARE_CREDENTIAL_NAMES = ["CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_API_TOKEN"];
193
+ /**
194
+ * Cloudflare could not be asked. A caller distinguishes this from a policy
195
+ * mismatch: an unreachable API is a transient condition, and a token whose
196
+ * permissions are wrong is not.
197
+ */
198
+ var CloudflareCredentialUnavailableError = class extends Error {
199
+ constructor(message = "Cloudflare credential inspection is unavailable.") {
200
+ super(message);
201
+ this.name = "CloudflareCredentialUnavailableError";
202
+ }
203
+ };
204
+ /** The exact source literals this preflight accepts. */
205
+ const CREDENTIAL_SOURCES = new Set(["hosted", "trusted-local"]);
206
+ const present = (environment, name) => Boolean(environment[name]?.trim());
207
+ const assertCredentialPosture = (source, accountId, environment) => {
208
+ if (!CREDENTIAL_SOURCES.has(source)) throw new Error("Credential preflight has an unknown credential source.");
209
+ if (source === "hosted") {
210
+ const missing = HOSTED_CLOUDFLARE_CREDENTIAL_NAMES.filter((name) => !present(environment, name));
211
+ if (missing.length > 0) throw new Error(`Hosted credential preflight is missing: ${missing.join(", ")}`);
212
+ if (environment.CLOUDFLARE_ACCOUNT_ID?.trim() !== accountId) throw new Error("Hosted credential preflight found a different Cloudflare account than the deploy allows.");
213
+ return;
214
+ }
215
+ const ambient = HOSTED_CLOUDFLARE_CREDENTIAL_NAMES.filter((name) => present(environment, name));
216
+ if (ambient.length > 0) throw new Error(`Trusted-local credential preflight must not run with hosted credentials in the environment: ${ambient.join(", ")}`);
217
+ };
218
+ const cloudflareJson = async (url, token, fetchImplementation) => {
219
+ let response;
220
+ try {
221
+ response = await fetchImplementation(url, { headers: { Authorization: `Bearer ${token}` } });
222
+ } catch {
223
+ throw new CloudflareCredentialUnavailableError();
224
+ }
225
+ if (response.status === 429 || response.status >= 500) throw new CloudflareCredentialUnavailableError();
226
+ let envelope;
227
+ try {
228
+ envelope = await response.json();
229
+ } catch {
230
+ throw new CloudflareCredentialUnavailableError();
231
+ }
232
+ if (!(response.ok && envelope.success) || envelope.result === void 0) throw new Error("Cloudflare credential inspection failed.");
233
+ return envelope.result;
234
+ };
235
+ const parseReviewedTokenPolicy = (policyJson) => {
236
+ let parsed;
237
+ try {
238
+ parsed = JSON.parse(policyJson);
239
+ } catch {
240
+ throw new Error("Cloudflare token policy metadata is not valid JSON.");
241
+ }
242
+ if (typeof parsed !== "object" || parsed === null || !("tokenId" in parsed) || typeof parsed.tokenId !== "string" || !parsed.tokenId || !("policies" in parsed) || !Array.isArray(parsed.policies)) throw new Error("Cloudflare token policy metadata has an invalid shape.");
243
+ return parsed;
244
+ };
245
+ const isPolicyShaped = (policy) => typeof policy === "object" && policy !== null && Array.isArray(policy.permission_groups) && typeof policy.resources === "object" && policy.resources !== null && !Array.isArray(policy.resources);
246
+ const permissionGroupsFromPolicies = (policies, resourcesFor) => {
247
+ const found = [];
248
+ for (const policy of policies) {
249
+ if (!isPolicyShaped(policy)) throw new Error("Cloudflare token policy has an invalid shape.");
250
+ if (policy.permission_groups.length === 0) throw new Error("Cloudflare token policy has no permission groups.");
251
+ if (policy.effect !== "allow") throw new Error("Cloudflare token must carry allow policies only.");
252
+ if (Object.values(policy.resources).some((selection) => selection !== "*")) throw new Error("Cloudflare token policy has an invalid resource value.");
253
+ const scope = new Set(Object.keys(policy.resources));
254
+ for (const permission of policy.permission_groups) {
255
+ if (!permission?.name) throw new Error("Cloudflare token has an unnamed permission group.");
256
+ found.push(permission.name);
257
+ const expected = new Set(resourcesFor(permission.name));
258
+ if (expected.size === 0) throw new Error("Cloudflare token policy has no expected resource scope.");
259
+ if (scope.size !== expected.size || [...scope].some((resource) => !expected.has(resource))) throw new Error("Cloudflare token policy has an unexpected resource scope.");
260
+ }
261
+ }
262
+ return found;
263
+ };
264
+ const assertExactPermissionGroups = (found, required) => {
265
+ const expected = new Set(required);
266
+ const received = new Set(found);
267
+ const missing = [...expected].filter((name) => !received.has(name));
268
+ const extra = [...received].filter((name) => !expected.has(name));
269
+ const duplicates = found.filter((name, index) => found.indexOf(name) !== index);
270
+ if (missing.length > 0 || extra.length > 0 || duplicates.length > 0) throw new Error(`Cloudflare permission mismatch; missing: ${missing.join(", ") || "none"}; extra count: ${extra.length}; duplicate count: ${duplicates.length}`);
271
+ };
272
+ const assertRequiredPermissionGroups = (required) => {
273
+ if (required.some((name) => !name.trim())) throw new Error("Credential preflight requires named permission groups; a blank name matches nothing.");
274
+ const duplicates = required.filter((name, index) => required.indexOf(name) !== index);
275
+ if (duplicates.length > 0) throw new Error(`Credential preflight requires a permission group list with no repeats; repeated: ${[...new Set(duplicates)].join(", ")}`);
276
+ };
277
+ /**
278
+ * Calls the project's resolver and converts any failure into one fixed
279
+ * message.
280
+ *
281
+ * A resolver reads a secret manager. Its error can quote the value it was
282
+ * reading, or carry it on an attached property. Nothing from the original
283
+ * error survives: no message, no `cause`, no copied property.
284
+ */
285
+ const resolveResolvedCredential = async (resolveCredential, environment) => {
286
+ try {
287
+ return await resolveCredential(environment);
288
+ } catch {
289
+ throw new CloudflareCredentialUnavailableError("Cloudflare credential resolution failed.");
290
+ }
291
+ };
292
+ /**
293
+ * Resolves the deploy's Cloudflare credential posture and checks the token
294
+ * against the reviewed policy document.
295
+ *
296
+ * The check is: the environment matches the declared source, the credential
297
+ * resolves, Cloudflare reports the token active, the reviewed policy names
298
+ * that same token, every policy is an allow policy scoped to the resources
299
+ * the project expects, and the permission groups match the required list with
300
+ * no group missing, extra, or repeated.
301
+ *
302
+ * The permission groups come from the reviewed policy document, not from
303
+ * Cloudflare. This function never reads live permissions from the Cloudflare
304
+ * API. A token whose permissions changed after the review still passes, as
305
+ * long as Cloudflare reports it active and the document still matches its id.
306
+ * See issue #1010.
307
+ *
308
+ * Throws on any failure. {@link CloudflareCredentialUnavailableError} means
309
+ * Cloudflare could not be asked; every other error means the credential is
310
+ * wrong. Nothing it throws, and nothing it returns, carries a secret value.
311
+ */
312
+ const credentialPreflight = async ({ accountId, environment, fetchImplementation = fetch, requiredPermissionGroups, resolveCredential, resourcesFor, source, tokenKind = "account" }) => {
313
+ if (tokenKind !== "account" && tokenKind !== "user") throw new Error("Credential preflight has an unknown token kind.");
314
+ if (!accountId.trim()) throw new Error("Credential preflight requires a Cloudflare account id.");
315
+ if (requiredPermissionGroups.length === 0) throw new Error("Credential preflight requires at least one permission group; an empty list would admit any token.");
316
+ assertRequiredPermissionGroups(requiredPermissionGroups);
317
+ assertCredentialPosture(source, accountId, environment);
318
+ const accountResource = `com.cloudflare.api.account.${accountId}`;
319
+ const scopeFor = resourcesFor ?? (() => [accountResource]);
320
+ const credential = await resolveResolvedCredential(resolveCredential, environment);
321
+ if (!(credential.token.trim() && credential.policyJson.trim())) throw new Error("Credential preflight resolved an empty credential.");
322
+ if (source === "hosted" && credential.token.trim() !== environment.CLOUDFLARE_API_TOKEN?.trim()) throw new Error("Hosted credential preflight resolved a token that is not the environment token.");
323
+ const verification = await cloudflareJson(tokenKind === "user" ? `${CLOUDFLARE_API}/user/tokens/verify` : `${CLOUDFLARE_API}/accounts/${accountId}/tokens/verify`, credential.token, fetchImplementation);
324
+ if (verification.status !== "active") throw new Error("Cloudflare token is not active.");
325
+ const reviewed = parseReviewedTokenPolicy(credential.policyJson);
326
+ if (reviewed.tokenId !== verification.id) throw new Error("Cloudflare token policy metadata does not describe the live token.");
327
+ const found = permissionGroupsFromPolicies(reviewed.policies, scopeFor);
328
+ assertExactPermissionGroups(found, requiredPermissionGroups);
329
+ return {
330
+ accountId,
331
+ permissionGroups: found.toSorted(),
332
+ source,
333
+ tokenId: verification.id
334
+ };
335
+ };
336
+ //#endregion
337
+ //#region src/alchemy/stage-policy.ts
338
+ /**
339
+ * Stage and stack pairing, and protected-stage policy, from a project-supplied
340
+ * table (#991).
341
+ *
342
+ * Two projects wrote the same three questions twice — is this stage protected,
343
+ * is it disposable, and may this stack run it — and each answered them with its
344
+ * own stage names hard-coded into the answer. The names differ; the questions
345
+ * do not. This module owns the questions. A project supplies the table and gets
346
+ * decisions back, so no project or stack name appears here.
347
+ *
348
+ * One stage name does appear: `local`. It names the local emulator rather than
349
+ * any project's estate, every project spells it the same way, and the question
350
+ * it answers — is this the emulated stage — has one answer for the whole fleet.
351
+ * See {@link isLocalEmulationStage}.
352
+ *
353
+ * The disposable grammar this package already owns (`disposable-stage.ts`) is
354
+ * available as a matcher rather than assumed, because a project's disposable
355
+ * set is wider than that one grammar.
356
+ */
357
+ /** Every stage the shared disposable grammar recognises. */
358
+ const LOCAL_PREVIEW_STAGES = (stage) => isLocalPreviewStage(stage);
359
+ /**
360
+ * Test a pattern without carrying state between calls.
361
+ *
362
+ * A `RegExp` with `g` or `y` advances `lastIndex` on every match, so the same
363
+ * pattern answers "yes" and then "no" for the same stage. A policy that
364
+ * alternates is worse than one that always refuses, so a flagged pattern is
365
+ * tested through a fresh copy whose `lastIndex` starts at zero. The copy
366
+ * carries the complete flags: `y` anchors the match at `lastIndex`, so
367
+ * dropping it would let `/prod/y` accept a stage named `pre-prod` that the
368
+ * project's own pattern rejects. The caller's own `RegExp` is never written
369
+ * to, so a frozen one still works.
370
+ */
371
+ const statelessTest$1 = (pattern, stage) => pattern.global || pattern.sticky ? new RegExp(pattern.source, pattern.flags).test(stage) : pattern.test(stage);
372
+ const stageMatches = (matcher, stage) => {
373
+ if (typeof matcher === "function") return matcher(stage);
374
+ if (Array.isArray(matcher)) return matcher.includes(stage);
375
+ return statelessTest$1(matcher, stage);
376
+ };
377
+ /** A matcher that accepts a stage any of `matchers` accepts. */
378
+ const anyStage = (...matchers) => (stage) => matchers.some((matcher) => stageMatches(matcher, stage));
379
+ /**
380
+ * A policy refusal. The `code` is the stable part: a project maps it onto its
381
+ * own lifecycle failure envelope, and the message is for a human.
382
+ */
383
+ var StagePolicyError = class extends Error {
384
+ code;
385
+ constructor(code, message) {
386
+ super(message);
387
+ this.name = "StagePolicyError";
388
+ this.code = code;
389
+ }
390
+ };
391
+ const assertTable = (table) => {
392
+ const seen = /* @__PURE__ */ new Set();
393
+ for (const entry of table.stacks ?? []) {
394
+ if (!entry.stack) throw new TypeError("Every stack ownership entry needs a stack name.");
395
+ if (seen.has(entry.stack)) throw new TypeError(`Stack "${entry.stack}" appears twice in the stack registry.`);
396
+ seen.add(entry.stack);
397
+ }
398
+ };
399
+ /**
400
+ * Is this the stage that runs against the local emulator?
401
+ *
402
+ * True for the literal `local` and nothing else (#991). Two projects and HQ
403
+ * each answered this with their own rule — a refusal list, a constant, and
404
+ * `$(whoami)` — and all three meant the same single name, so the answer is one
405
+ * literal rather than a pattern or a table. A disposable preview stage such as
406
+ * `local-pr-1-abcdef0` shares the prefix but runs against a real account, so it
407
+ * is false here. The comparison is exact: no trim and no case folding, because
408
+ * a stage name reaches Alchemy exactly as it is spelled.
409
+ *
410
+ * This question is deliberately outside {@link stagePolicy}: a project's table
411
+ * classifies the stages of its own estate, and the emulated stage belongs to
412
+ * no estate.
413
+ */
414
+ const isLocalEmulationStage = (stage) => stage === "local";
415
+ /**
416
+ * Read a project's stage table and answer the stage questions from it.
417
+ *
418
+ * A stage the table classifies as both protected and disposable is a table
419
+ * defect, not a stage a caller may act on, so every query on it throws.
420
+ */
421
+ const stagePolicy = (table) => {
422
+ assertTable(table);
423
+ const classify = (stage) => {
424
+ const isProtected = stageMatches(table.stages.protected, stage);
425
+ const isDisposable = stageMatches(table.stages.disposable, stage);
426
+ if (isProtected && isDisposable) throw new StagePolicyError("AMBIGUOUS_STAGE", `Stage "${stage}" is declared both protected and disposable.`);
427
+ return {
428
+ isDisposable,
429
+ isProtected
430
+ };
431
+ };
432
+ const isProtectedStage = (stage) => classify(stage).isProtected;
433
+ const isDisposableStage = (stage) => classify(stage).isDisposable;
434
+ const isKnownStage = (stage) => {
435
+ const { isDisposable, isProtected } = classify(stage);
436
+ return isProtected || isDisposable;
437
+ };
438
+ const assertKnownStage = (stage) => {
439
+ if (!isKnownStage(stage)) throw new StagePolicyError("UNKNOWN_STAGE", `Unsupported Alchemy stage: ${stage}`);
440
+ };
441
+ const assertDestructiveStage = (stage) => {
442
+ assertKnownStage(stage);
443
+ if (isProtectedStage(stage)) throw new StagePolicyError("PROTECTED_STAGE", `Refusing destructive operation for protected stage: ${stage}`);
444
+ };
445
+ const assertStackOwnsStage = (stack, stage) => {
446
+ assertKnownStage(stage);
447
+ const registry = table.stacks;
448
+ if (registry === void 0) return;
449
+ const entry = registry.find((candidate) => candidate.stack === stack);
450
+ if (entry === void 0) throw new StagePolicyError("UNKNOWN_STACK", `Unsupported Alchemy stack: ${stack}`);
451
+ const owner = registry.find((candidate) => candidate.stack !== stack && candidate.claims !== void 0 && stageMatches(candidate.claims, stage));
452
+ if (owner !== void 0) throw new StagePolicyError("STAGE_NOT_OWNED", `Stage ${stage} belongs only to stack ${owner.stack}, not ${stack}.`);
453
+ if (entry.stages !== void 0 && !stageMatches(entry.stages, stage)) throw new StagePolicyError("STAGE_NOT_OWNED", `Stack ${stack} does not run stage ${stage}.`);
454
+ };
455
+ return {
456
+ assertDestructiveStage,
457
+ assertKnownStage,
458
+ assertStackOwnsStage,
459
+ isDisposableStage,
460
+ isKnownStage,
461
+ isProtectedStage
462
+ };
463
+ };
464
+ //#endregion
465
+ //#region src/alchemy/local-emulation.ts
466
+ /**
467
+ * The child environment a local-emulation Alchemy run needs (#1168).
468
+ *
469
+ * Alchemy refuses to start when `CLOUDFLARE_ACCOUNT_ID` is missing or
470
+ * malformed, even for a run that only drives the local emulator and calls no
471
+ * Cloudflare API. Every project worked around that by handing the child a real
472
+ * account id and a real token, so a purely local run carried live credentials.
473
+ * This module hands it a sentinel pair instead: a well-formed account id that
474
+ * addresses no account, and a token that is not a token.
475
+ *
476
+ * The helper never reads a real credential. It reads one variable — the
477
+ * live-binding opt-in — and nothing else. The presence of a real credential in
478
+ * the parent environment is never the signal: a developer who is logged in to
479
+ * Cloudflare still gets the sentinel pair unless the opt-in says otherwise.
480
+ *
481
+ * Scrubbing an ambient token out of the child is the launcher's job, not this
482
+ * module's. This module owns the environment shape only.
483
+ */
484
+ const [ACCOUNT_ID_NAME, API_TOKEN_NAME] = HOSTED_CLOUDFLARE_CREDENTIAL_NAMES;
485
+ /**
486
+ * A well-formed Cloudflare account id that addresses no account.
487
+ *
488
+ * Alchemy validates the value against `/^[0-9a-f]{32}$/i` and rejects
489
+ * placeholders such as `""` or `dummy` with an authentication error before any
490
+ * run starts. The check is `validateAccountId`, in
491
+ * `alchemy/lib/Cloudflare/Auth/AuthProvider.js` at 2.0.0-beta.76 and in
492
+ * `alchemy/lib/Cloudflare/Auth/AuthConfig.js` at 2.0.0-beta.77. The file name
493
+ * moves; the pattern is the same in both. Thirty-two zeros pass that shape
494
+ * check and route to nothing.
495
+ */
496
+ const SENTINEL_ACCOUNT_ID = "0".repeat(32);
497
+ /**
498
+ * A token that is not a token. It is spelled as words, so no secret scanner
499
+ * reads it as a credential and no reader mistakes it for one. Any API call
500
+ * made with it fails, which is the intended outcome: a local-emulation run
501
+ * must reach no Cloudflare account.
502
+ */
503
+ const SENTINEL_API_TOKEN = "factory-ci-local-emulation-no-cloudflare-token";
504
+ /**
505
+ * The one way a real credential reaches a local-emulation child. Set it to a
506
+ * non-empty value and this helper returns no sentinel, so whatever
507
+ * `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` the parent carries pass
508
+ * through untouched and the run may bind a live Cloudflare resource.
509
+ */
510
+ const LIVE_BINDING_OPT_IN = "FACTORY_CI_LIVE_CLOUDFLARE_BINDING";
511
+ /**
512
+ * Build the Cloudflare variables a local-emulation child is launched with.
513
+ *
514
+ * Returns exactly two variables for the local-emulation stage, or no variables
515
+ * when the live-binding opt-in is set. The result is an overlay: merge it over
516
+ * the child environment the launcher has otherwise assembled.
517
+ *
518
+ * Throws for any other stage. A non-local stage deploys to a real account, so
519
+ * a sentinel there would break that deploy, and returning nothing instead
520
+ * would let a caller believe a local run was protected when it was not.
521
+ */
522
+ const localEmulationEnvironment = (options) => {
523
+ const { environment = process.env, stage } = options;
524
+ if (!isLocalEmulationStage(stage)) throw new Error(`localEmulationEnvironment is only for the local-emulation stage, not "${stage}".`);
525
+ if ((environment[LIVE_BINDING_OPT_IN] ?? "").trim().length > 0) return {};
526
+ return {
527
+ [ACCOUNT_ID_NAME]: SENTINEL_ACCOUNT_ID,
528
+ [API_TOKEN_NAME]: SENTINEL_API_TOKEN
529
+ };
530
+ };
531
+ //#endregion
532
+ //#region src/alchemy/destroy-postcondition.ts
533
+ /**
534
+ * Read the state store through the project's reader.
535
+ *
536
+ * A reader addresses a state store with a credential, and its failure can
537
+ * quote the URL, the header, or the token it was reading with. Nothing from
538
+ * the original error survives: no message, no `cause`, no copied property.
539
+ * This is the policy `credentialPreflight` applies to `resolveCredential`, for
540
+ * the same reason.
541
+ */
542
+ const readState = async (stateReader, target) => {
543
+ try {
544
+ return await stateReader(target);
545
+ } catch {
546
+ throw new Error(`The destroy postcondition for ${target.stack} into ${target.stage} could not read the state store.`);
547
+ }
548
+ };
549
+ /**
550
+ * Proves a destroy left no resource registered for the stage.
551
+ *
552
+ * Throws when the store still lists resources, naming them in sorted order,
553
+ * and throws when the reader returns anything other than a list of resource
554
+ * identifiers. A reader that throws fails the postcondition too, under a fixed
555
+ * message that carries nothing the reader's own error said. Resource
556
+ * identifiers are names, never values.
557
+ */
558
+ const assertDestroyLeftNothing = async ({ stack, stage, stateReader }) => {
559
+ if (!(stack.trim() && stage.trim())) throw new Error("The destroy postcondition requires a stack and a stage.");
560
+ if (stack !== stack.trim() || stage !== stage.trim()) throw new Error("The destroy postcondition requires a stack and a stage with no surrounding whitespace.");
561
+ const listed = await readState(stateReader, {
562
+ stack,
563
+ stage
564
+ });
565
+ if (!Array.isArray(listed) || listed.some((resource) => typeof resource !== "string" || !resource.trim())) throw new Error(`The destroy postcondition for ${stack} into ${stage} could not read a resource list from the state store.`);
566
+ const remaining = [...listed].toSorted();
567
+ if (remaining.length > 0) throw new Error(`Alchemy destroy left ${remaining.length} resource registered for ${stack} in ${stage}: ${remaining.join(", ")}`);
568
+ };
569
+ //#endregion
570
+ //#region src/alchemy/plan-effects.ts
571
+ /**
572
+ * The plan-output adapter (#1077): the one reader of what the installed
573
+ * Alchemy CLI prints for a plan.
574
+ *
575
+ * Alchemy has no structured plan output at the fleet baseline, so the plan
576
+ * is read from the lines `formatPlanLines` in `alchemy/src/Cli/LoggingCli.ts`
577
+ * prints: one `Plan:` summary, one `[fqn] action` line per resource, one
578
+ * `[fqn/name] action` line per binding of that resource, and one
579
+ * `[fqn] run|drop [action]` line per task. Paitronage and HQ each wrote this
580
+ * reader; this is the one copy, and it is bound to the Alchemy version whose
581
+ * renderer it reads. A consumer running a different Alchemy is refused by
582
+ * `runAlchemyLifecycle` before any child runs, so a renderer change cannot
583
+ * be read as a plan with different effects.
584
+ *
585
+ * The renderer logs every line through Effect's pretty console logger, so a
586
+ * line arrives as `[HH:MM:SS.mmm] INFO (#1): <line>`, and coloured when the
587
+ * child inherits `FORCE_COLOR`. Both wrappers are stripped before a line is
588
+ * read. The captured output under `tests/fixtures/plan-output/beta-77/` is
589
+ * the evidence for every shape this file reads.
590
+ *
591
+ * The adapter fails on anything it does not recognise: no summary, two
592
+ * summaries, an action outside the known set, a summary it cannot parse, a
593
+ * summary whose counts do not equal the lines under it, or rows the summary
594
+ * can place in more than one way. An effect it could not account for is
595
+ * never reported as zero.
596
+ *
597
+ * Two readings share that work. `parsePlanEffects` answers what the plan
598
+ * does, which is what the lifecycle's admission rules read. `canonicalPlan`
599
+ * answers what the plan *is*, as a stable string: the rows the renderer
600
+ * printed and the reading of them, with the per-run logger metadata it also
601
+ * prints left out. `firstDeployPlanHash` hashes that string, so a plan
602
+ * reviewed at one moment and deployed at another is the same plan (#1232).
603
+ */
604
+ /** The Alchemy version whose plan renderer this adapter reads. */
605
+ const PLAN_OUTPUT_ALCHEMY_VERSION = ALCHEMY_BASELINE.alchemy;
606
+ /**
607
+ * Every action a resource row can carry. The first six are the actions the
608
+ * summary counts, in the order the renderer prints them; `noop` rows print
609
+ * under the summary but are never counted in it.
610
+ */
611
+ const PLAN_ACTIONS = [
612
+ "create",
613
+ "update",
614
+ "adopted",
615
+ "replace",
616
+ "delete",
617
+ "orphaned",
618
+ "noop"
619
+ ];
620
+ /** The actions the summary counts. */
621
+ const SUMMARY_ACTIONS = PLAN_ACTIONS.filter((action) => action !== "noop");
622
+ /** The adapter could not read the output. `reason` is the whole detail. */
623
+ var PlanEffectsError = class extends Error {
624
+ reason;
625
+ constructor(reason) {
626
+ super(`Alchemy plan output was not readable: ${reason}.`);
627
+ this.name = "PlanEffectsError";
628
+ this.reason = reason;
629
+ }
630
+ };
631
+ const ACTION_SET = new Set(PLAN_ACTIONS);
632
+ const BINDING_ACTIONS = new Set([
633
+ "create",
634
+ "noop",
635
+ "unbind",
636
+ "update"
637
+ ]);
638
+ const TASK_ACTIONS = new Set(["drop", "run"]);
639
+ const ansiPattern = new RegExp(`${String.fromCodePoint(27)}\\[[0-?]*[ -/]*[@-~]`, "gu");
640
+ /**
641
+ * The prefix Effect's pretty console logger puts before every line the
642
+ * renderer logs. Optional, so output that was not logged through it (an
643
+ * apply session's stack output, a scripted CLI in a test) reads the same.
644
+ */
645
+ const EFFECT_LOG_PREFIX = /^\[\d{2}:\d{2}:\d{2}\.\d{3}\] (?:ALL|TRACE|DEBUG|INFO|WARN|ERROR|FATAL|NONE) \(#\d+\)(?: [^:]+)?:(?: |$)/u;
646
+ const ROW_PATTERN = /^\[(?<tag>[^\]]+)\]\s+(?<action>\S+)/u;
647
+ const TASK_ROW_PATTERN = /^\[(?<tag>[^\]]+)\]\s+(?<action>\S+)\s+\[action\]$/u;
648
+ const SUMMARY_PREFIX = "Plan:";
649
+ /** Every resource row is `noop`; there may be rows. */
650
+ const NO_CHANGES = "Plan: no changes";
651
+ /** The stack declares nothing and persists nothing; there are no rows. */
652
+ const NO_RESOURCES = "Plan: no resources";
653
+ const SUMMARY_ACTION_ITEM = /^(?<count>\d+) to (?<action>create|update|adopted|replace|delete|orphaned)$/u;
654
+ const SUMMARY_BINDINGS_ITEM = /^(?<count>\d+) binding changes$/u;
655
+ const SUMMARY_TASKS_ITEM = /^(?<count>\d+) tasks$/u;
656
+ const zeroCounts = () => ({
657
+ adopted: 0,
658
+ create: 0,
659
+ delete: 0,
660
+ noop: 0,
661
+ orphaned: 0,
662
+ replace: 0,
663
+ update: 0
664
+ });
665
+ const isPlanAction = (action) => ACTION_SET.has(action);
666
+ const isTaskAction = (action) => TASK_ACTIONS.has(action);
667
+ /**
668
+ * The rows under the summary, up to the first line that is not a row. An
669
+ * apply session prints its progress after a blank line, so that line ends
670
+ * the plan. A task row is told apart by its `[action]` suffix; a resource
671
+ * row and a binding row are told apart by `readRows` below.
672
+ */
673
+ const rowsUnder = (lines, summaryIndex) => {
674
+ const rows = [];
675
+ const tasks = [];
676
+ for (const line of lines.slice(summaryIndex + 1)) {
677
+ const task = TASK_ROW_PATTERN.exec(line)?.groups;
678
+ if (task?.tag !== void 0 && task.action !== void 0) {
679
+ if (!isTaskAction(task.action)) throw new PlanEffectsError("unknown-action");
680
+ tasks.push({
681
+ action: task.action,
682
+ id: task.tag
683
+ });
684
+ continue;
685
+ }
686
+ const row = ROW_PATTERN.exec(line)?.groups;
687
+ if (row?.tag === void 0 || row.action === void 0) break;
688
+ if (!(isPlanAction(row.action) || BINDING_ACTIONS.has(row.action))) throw new PlanEffectsError("unknown-action");
689
+ rows.push({
690
+ action: row.action,
691
+ tag: row.tag
692
+ });
693
+ }
694
+ return {
695
+ rows,
696
+ tasks
697
+ };
698
+ };
699
+ /**
700
+ * The one reading of the rows as resources and bindings whose counts equal
701
+ * the summary. No such reading is a count mismatch; two are refused as
702
+ * ambiguous rather than guessed.
703
+ *
704
+ * A binding row is tagged `<resource fqn>/<name>` and printed directly under
705
+ * its resource, so it always extends the FQN of the last resource row. A
706
+ * resource inside a namespace is tagged the same way, and when it follows a
707
+ * resource whose FQN is its namespace path the two rows look alike:
708
+ * `prefix/plan.txt` under the fixtures prints `[Parent/bound] create` and
709
+ * `[Parent/Zed] create` under `[Parent] create`. The renderer gives no other
710
+ * evidence, so a row that extends the last resource's FQN is read both ways
711
+ * and the summary decides: it counts resources per action and the binding
712
+ * rows with a change, and only a reading that adds up to it survives.
713
+ *
714
+ * A `noop` row is counted by neither, so the summary cannot place it. Such a
715
+ * row extending the last resource's FQN is read as a binding: a `noop` row
716
+ * drives no decision (`runAlchemyLifecycle` reads only rows with work), and
717
+ * a plan's bindings are far more often `noop` than its namespaced resources
718
+ * are named after a sibling. `prefix/noop.txt` is that residual.
719
+ *
720
+ * The search counts readings, stopping at two, and is memoised on what the
721
+ * rest of the rows can depend on: the position, the last resource's FQN,
722
+ * and the `create` and `update` resources read so far (every other counted
723
+ * row is a resource, `unbind` is a binding, and `noop` is placed by rule, so
724
+ * those tallies follow from the position). A plan with many resources each
725
+ * followed by rows that extend its FQN then costs the product of the row
726
+ * count and the two tallies, not the product of the readings of each group.
727
+ * The first reading found is kept; every branch is on a row with work, so a
728
+ * second reading always places a row with work differently.
729
+ */
730
+ const readRows = (rows, stated) => {
731
+ const seen = zeroCounts();
732
+ const resources = [];
733
+ let bindingChanges = 0;
734
+ let first;
735
+ const memo = /* @__PURE__ */ new Map();
736
+ const visit = (index, owner) => {
737
+ const row = rows[index];
738
+ if (row === void 0) {
739
+ if (bindingChanges !== stated.bindingChanges || SUMMARY_ACTIONS.some((action) => seen[action] !== stated.counts[action])) return 0;
740
+ first ??= [...resources];
741
+ return 1;
742
+ }
743
+ const key = JSON.stringify([
744
+ index,
745
+ owner,
746
+ seen.create,
747
+ seen.update
748
+ ]);
749
+ const known = memo.get(key);
750
+ if (known !== void 0) return known;
751
+ let readings = 0;
752
+ const { action, tag } = row;
753
+ if (owner !== void 0 && tag.startsWith(`${owner}/`) && BINDING_ACTIONS.has(action)) {
754
+ if (action === "noop") return visit(index + 1, owner);
755
+ bindingChanges += 1;
756
+ if (bindingChanges <= stated.bindingChanges) readings += visit(index + 1, owner);
757
+ bindingChanges -= 1;
758
+ }
759
+ if (readings < 2 && isPlanAction(action)) {
760
+ seen[action] += 1;
761
+ resources.push({
762
+ action,
763
+ id: tag
764
+ });
765
+ if (action === "noop" || seen[action] <= stated.counts[action]) readings += visit(index + 1, tag);
766
+ resources.pop();
767
+ seen[action] -= 1;
768
+ }
769
+ const capped = Math.min(readings, 2);
770
+ memo.set(key, capped);
771
+ return capped;
772
+ };
773
+ const readings = visit(0);
774
+ if (first === void 0 || readings === 0) throw new PlanEffectsError("count-mismatch");
775
+ if (readings > 1) throw new PlanEffectsError("ambiguous-rows");
776
+ return {
777
+ bindingChanges: stated.bindingChanges,
778
+ resources: first
779
+ };
780
+ };
781
+ /**
782
+ * The counts the summary states, in the order Alchemy prints them: the six
783
+ * actions, then `N binding changes`, then `N tasks`, each only when non-zero.
784
+ * The summary is rebuilt from what was read and must equal the line, so a
785
+ * summary with an extra clause, a repeated part, or a different order is
786
+ * refused instead of partially read.
787
+ */
788
+ const countsStated = (summary) => {
789
+ const counts = zeroCounts();
790
+ let bindingChanges = 0;
791
+ let tasks = 0;
792
+ for (const item of summary.slice(5).trim().split(", ")) {
793
+ const action = SUMMARY_ACTION_ITEM.exec(item)?.groups;
794
+ const bindings = SUMMARY_BINDINGS_ITEM.exec(item)?.groups;
795
+ const taskCount = SUMMARY_TASKS_ITEM.exec(item)?.groups;
796
+ if (action?.action && isPlanAction(action.action)) counts[action.action] = Number(action.count);
797
+ else if (bindings) bindingChanges = Number(bindings.count);
798
+ else if (taskCount) tasks = Number(taskCount.count);
799
+ else throw new PlanEffectsError("summary-unrecognized");
800
+ }
801
+ const canonical = [
802
+ ...SUMMARY_ACTIONS.filter((action) => counts[action] > 0).map((action) => `${counts[action]} to ${action}`),
803
+ ...bindingChanges > 0 ? [`${bindingChanges} binding changes`] : [],
804
+ ...tasks > 0 ? [`${tasks} tasks`] : []
805
+ ].join(", ");
806
+ if (canonical === "" || `${SUMMARY_PREFIX} ${canonical}` !== summary) throw new PlanEffectsError("summary-unrecognized");
807
+ return {
808
+ bindingChanges,
809
+ counts,
810
+ tasks
811
+ };
812
+ };
813
+ /**
814
+ * Split the output into the one summary line and the rows under it. This is
815
+ * the whole of what the renderer's output is read as; `planEffects` below
816
+ * interprets it, and `canonicalPlan` serialises it.
817
+ */
818
+ const planLines = (output) => {
819
+ const lines = output.replaceAll(ansiPattern, "").split("\n").map((line) => line.replace(EFFECT_LOG_PREFIX, "").trim());
820
+ const summaryIndexes = lines.flatMap((line, index) => line.startsWith(SUMMARY_PREFIX) ? [index] : []);
821
+ if (summaryIndexes.length === 0) throw new PlanEffectsError("no-summary");
822
+ if (summaryIndexes.length > 1) throw new PlanEffectsError("multiple-summaries");
823
+ const summaryIndex = summaryIndexes[0] ?? 0;
824
+ return {
825
+ summary: lines[summaryIndex] ?? "",
826
+ ...rowsUnder(lines, summaryIndex)
827
+ };
828
+ };
829
+ /** What the summary and the rows under it say the plan does. */
830
+ const planEffects = ({ rows, summary, tasks }) => {
831
+ if (summary === NO_RESOURCES) {
832
+ if (rows.length > 0 || tasks.length > 0) throw new PlanEffectsError("effects-under-no-changes");
833
+ return {
834
+ bindingChanges: 0,
835
+ counts: zeroCounts(),
836
+ resources: [],
837
+ tasks: []
838
+ };
839
+ }
840
+ const stated = summary === NO_CHANGES ? {
841
+ bindingChanges: 0,
842
+ counts: zeroCounts(),
843
+ tasks: 0
844
+ } : countsStated(summary);
845
+ if (tasks.length !== stated.tasks) throw new PlanEffectsError("count-mismatch");
846
+ const { bindingChanges, resources } = readRows(rows, stated);
847
+ const counts = zeroCounts();
848
+ for (const { action } of resources) counts[action] += 1;
849
+ return {
850
+ bindingChanges,
851
+ counts,
852
+ resources,
853
+ tasks
854
+ };
855
+ };
856
+ /**
857
+ * Read one plan from Alchemy CLI output.
858
+ *
859
+ * Throws `PlanEffectsError` on output the adapter cannot account for. The
860
+ * output itself never appears in the error.
861
+ */
862
+ const parsePlanEffects = (output) => planEffects(planLines(output));
863
+ const compareText = (left, right) => {
864
+ if (left < right) return -1;
865
+ return left > right ? 1 : 0;
866
+ };
867
+ const compareCanonicalRows = (left, right) => compareText(left.kind, right.kind) || compareText(left.tag, right.tag) || compareText(left.action, right.action);
868
+ const compareResources = (left, right) => compareText(left.id, right.id) || compareText(left.action, right.action);
869
+ /**
870
+ * The plan as a stable string: what the renderer said about the plan, with
871
+ * what it said about the run that printed it left out.
872
+ *
873
+ * A plan carries no resource properties — the renderer prints a summary and
874
+ * one `[tag] action` row per resource, binding and task, and nothing else.
875
+ * So the canonical form is the summary line, every row under it as
876
+ * `{ action, kind, tag }`, and the reading of those rows `parsePlanEffects`
877
+ * arrives at (`resources` and `bindingChanges`). What is left out is the
878
+ * logger's timestamps and fiber ids, the `Plan ready (2.9s)` duration, ANSI
879
+ * colour, and everything after the rows: per-run facts about the process,
880
+ * not about the plan, and hashing them is why a reviewed plan could never be
881
+ * deployed (#1232).
882
+ *
883
+ * The rows and the reading each say something the other does not, so both
884
+ * are kept:
885
+ *
886
+ * - Every row is kept, including binding rows and `noop` rows, because
887
+ * `PlanEffects` reduces bindings to a count. A binding renamed with the
888
+ * count unchanged is one `PlanEffects` value and two row multisets.
889
+ * - The reading is kept because the rows alone do not say which of them are
890
+ * resources. A binding row and a namespaced resource row print alike —
891
+ * `[Parent/bound] create` and `[Parent/Zed] create` under
892
+ * `[Parent] create` — and only print order and the summary's counts tell
893
+ * them apart. Sorting the rows drops the order, so swapping those two rows
894
+ * is two plans creating different resources over one row multiset. The
895
+ * resource list the summary forces is what separates them.
896
+ *
897
+ * Together they pin the bindings too: the rows are the whole multiset and
898
+ * the resources are a sub-multiset of it, so the bindings are what remains.
899
+ *
900
+ * Rows and resources are both sorted, keeping duplicates, because print
901
+ * order is the renderer's traversal and authorizes nothing on its own: a
902
+ * plan that printed the same resources and bindings in another order must
903
+ * not read as a different plan.
904
+ *
905
+ * The full `parsePlanEffects` validation runs first, so anything the adapter
906
+ * refuses is refused here too (`PlanEffectsError`). Output it cannot account
907
+ * for is never canonicalised, and so is never authorized. `rowsUnder` stops
908
+ * at the first line that is not a row, so a log line interleaved into the
909
+ * rows on a chattier run drops the rows after it: an uncounted (`noop`) row
910
+ * lost that way changes the hash, and a row with work lost that way fails
911
+ * the summary's counts (`count-mismatch`). Either way the run is refused
912
+ * rather than admitted on less than the plan.
913
+ */
914
+ const canonicalPlan = (output) => {
915
+ const lines = planLines(output);
916
+ const { bindingChanges, resources } = planEffects(lines);
917
+ const rows = [...lines.rows.map(({ action, tag }) => ({
918
+ action,
919
+ kind: "row",
920
+ tag
921
+ })), ...lines.tasks.map(({ action, id }) => ({
922
+ action,
923
+ kind: "task",
924
+ tag: id
925
+ }))].toSorted(compareCanonicalRows);
926
+ return JSON.stringify({
927
+ bindingChanges,
928
+ resources: resources.toSorted(compareResources),
929
+ rows,
930
+ summary: lines.summary
931
+ });
932
+ };
933
+ //#endregion
934
+ //#region src/alchemy/first-deploy-authorization.ts
935
+ /**
936
+ * First-deploy authorization by plan hash.
937
+ *
938
+ * The first deploy of a stack into a stage is the one deploy no earlier state
939
+ * can constrain: there is nothing to diff against, so the plan is the only
940
+ * description of what is about to be created. Paitronage binds that plan to an
941
+ * operator decision by hashing it and comparing the hash against a reviewed
942
+ * value (`firstDeployPlanSha256` and `assertFirstDeployEntry` in
943
+ * `tools/alchemy/src/internal/lifecycle.ts`).
944
+ *
945
+ * The generic form keeps the binding and drops the project's stage policy.
946
+ * Which stages are eligible, and where the authorized hashes are kept, stay
947
+ * with the project. This function answers one question: does this exact plan
948
+ * appear on the list the project authorized?
949
+ *
950
+ * It fails closed. An empty list, a malformed list entry, an empty plan, plan
951
+ * output the plan adapter cannot read, and an unlisted hash are all refusals.
952
+ *
953
+ * What the hash binds is the plan, not the run that printed it: the summary
954
+ * line and every row's tag and action, with the target and the reviewed
955
+ * source. Alchemy's renderer logs each line through Effect's pretty console
956
+ * logger and prints its own elapsed duration, so the verbatim output carries
957
+ * a timestamp per line, a fiber id, `Plan ready (2.9s)`, and colour when the
958
+ * child inherits `FORCE_COLOR` — all facts about one process, none about the
959
+ * plan. Hashing them meant a reviewed plan could never be redeployed at its
960
+ * reviewed hash (#1232), so `canonicalPlan` is hashed instead.
961
+ */
962
+ const sha256 = (value) => createHash("sha256").update(value).digest("hex");
963
+ /**
964
+ * Which plan representation the payload hashes. It is part of the payload so
965
+ * a hash can never be read as one of a different shape.
966
+ */
967
+ const PLAN_HASH_FORMAT = "canonical-plan-v1";
968
+ const HASH_PATTERN = /^[0-9a-f]{64}$/u;
969
+ const SOURCE_SHA_PATTERN = /^[0-9a-f]{40}$/u;
970
+ /**
971
+ * The hash a first deploy is authorized by: the plan, the target, and the
972
+ * reviewed source, in one payload.
973
+ *
974
+ * The plan enters the payload as the sha256 of `canonicalPlan`, so the value
975
+ * that is compared never embeds plan output, and two runs of one plan agree.
976
+ * Bound: the summary line, every row's tag and action (resource, binding and
977
+ * task rows alike, `noop` included), which of those rows are resources and
978
+ * which are bindings, the stack, the stage, and the source SHA. Not bound:
979
+ * logger timestamps and fiber ids, the run's elapsed durations, ANSI colour,
980
+ * progress lines, and the order the rows were printed in.
981
+ *
982
+ * Row order is not bound but the reading of the rows is, because they are
983
+ * not the same fact. Order alone used to carry which rows are a resource's
984
+ * bindings and which are resources inside its namespace; the canonical form
985
+ * states that outright, so two plans creating different resources can never
986
+ * agree merely by printing one multiset of rows two ways.
987
+ *
988
+ * `planFormat` names that shape. A hash issued by an earlier version of this
989
+ * function, which hashed the verbatim output, can never equal one issued
990
+ * now — those hashes were not reproducible in the first place, so they
991
+ * authorized nothing that could be deployed.
992
+ *
993
+ * Throws a `PlanEffectsError` when the plan adapter cannot account for the
994
+ * output: an unreadable plan is refused, never hashed.
995
+ */
996
+ const firstDeployPlanHash = ({ planText, sourceSha, stack, stage }) => {
997
+ if (!(stack.trim() && stage.trim())) throw new Error("First-deploy authorization requires a stack and a stage.");
998
+ if (stack !== stack.trim() || stage !== stage.trim() || sourceSha !== null && sourceSha !== sourceSha.trim()) throw new Error("First-deploy authorization requires a stack, a stage, and a source SHA with no surrounding whitespace.");
999
+ if (sourceSha !== null && !SOURCE_SHA_PATTERN.test(sourceSha)) throw new Error("First-deploy authorization requires a full lowercase 40-character source SHA, or null.");
1000
+ if (!planText.trim()) throw new Error("First-deploy authorization requires plan output; an empty plan describes nothing.");
1001
+ if (!planText.isWellFormed()) throw new Error("First-deploy authorization requires well-formed plan output.");
1002
+ return sha256(JSON.stringify({
1003
+ operation: "deploy",
1004
+ planFormat: PLAN_HASH_FORMAT,
1005
+ planSha256: sha256(canonicalPlan(planText)),
1006
+ sourceSha,
1007
+ stack,
1008
+ stage
1009
+ }));
1010
+ };
1011
+ /**
1012
+ * Admits a first deploy only when its plan hash is one the project
1013
+ * authorized.
1014
+ *
1015
+ * The thrown message carries the computed hash, which is what an operator
1016
+ * adds to the authorization list after reading the plan. It never carries the
1017
+ * plan text.
1018
+ */
1019
+ const firstDeployAuthorization = ({ authorizedHashes, planText, sourceSha, stack, stage }) => {
1020
+ const planHash = firstDeployPlanHash({
1021
+ planText,
1022
+ sourceSha,
1023
+ stack,
1024
+ stage
1025
+ });
1026
+ const malformed = authorizedHashes.filter((hash) => !HASH_PATTERN.test(hash.trim().toLowerCase()));
1027
+ if (malformed.length > 0) throw new Error(`First-deploy authorization list holds ${malformed.length} entry that is not a sha256 hash.`);
1028
+ const authorized = new Set(authorizedHashes.map((hash) => hash.trim().toLowerCase()));
1029
+ if (authorized.size === 0) throw new Error(`First deploy of ${stack} into ${stage} is not authorized: the authorization list is empty. Reviewed plan hash: ${planHash}`);
1030
+ if (!authorized.has(planHash)) throw new Error(`First deploy of ${stack} into ${stage} is not authorized. Reviewed plan hash: ${planHash}`);
1031
+ return { planHash };
1032
+ };
1033
+ //#endregion
1034
+ //#region src/alchemy/url-implies-auth.ts
1035
+ /** The Alchemy resource type a Cloudflare Worker plans as, at beta.76. */
1036
+ const WORKER_TYPE = "Cloudflare.Worker";
1037
+ /** The Alchemy resource type a Cloudflare Access application plans as, at beta.76. */
1038
+ const ACCESS_APPLICATION_TYPE = "Cloudflare.Access.Application";
1039
+ /** Every offending Worker in one throw, so a stack is fixed in one pass. */
1040
+ var UrlImpliesAuthError = class extends Error {
1041
+ violations;
1042
+ constructor(violations) {
1043
+ const described = violations.map(({ reason, worker }) => reason === "allowance-without-reason" ? `${worker} (allowlisted with an empty reason)` : `${worker} (no auth binding, no Access application, no allowance)`).join(", ");
1044
+ super(`${violations.length} publicly reachable Worker declares no authentication: ${described}`);
1045
+ this.name = "UrlImpliesAuthError";
1046
+ this.violations = violations;
1047
+ }
1048
+ };
1049
+ /** `workersDev` is a boolean or a config object; both spellings can be off. */
1050
+ const workersDevReachable = (workersDev) => {
1051
+ if (typeof workersDev === "boolean") return workersDev;
1052
+ if (typeof workersDev !== "object" || workersDev === null) return false;
1053
+ const { enabled, previewsEnabled } = workersDev;
1054
+ return enabled !== false || previewsEnabled !== false;
1055
+ };
1056
+ /** `domain` is a hostname, a config object with a `name`, or `null` to detach. */
1057
+ const domainReachable = (domain) => {
1058
+ if (typeof domain === "string") return domain.trim().length > 0;
1059
+ if (typeof domain !== "object" || domain === null) return false;
1060
+ const { name } = domain;
1061
+ return typeof name === "string" && name.trim().length > 0;
1062
+ };
1063
+ /** `routes` is a list of zone patterns. Any entry publishes the Worker. */
1064
+ const routesReachable = (routes) => Array.isArray(routes) && routes.length > 0;
1065
+ /** The Worker's own `access` prop: a shared application, or a dedicated one. */
1066
+ const enrollsInAccess = (access) => access !== void 0 && access !== null;
1067
+ /** Is this Worker reachable from the internet by what the stack declares? */
1068
+ const publiclyReachable = ({ props }) => workersDevReachable(props.workersDev) || domainReachable(props.domain) || routesReachable(props.routes);
1069
+ /**
1070
+ * Test a pattern without carrying state between Workers.
1071
+ *
1072
+ * A `RegExp` with `g` or `y` advances `lastIndex` on every match, so the same
1073
+ * pattern answers "yes" for the first Worker and "no" for the second Worker
1074
+ * with the same binding name. A guard that alternates is worse than one that
1075
+ * always refuses, so a flagged pattern is tested through a fresh copy whose
1076
+ * `lastIndex` starts at zero. The copy carries the complete flags: `y`
1077
+ * anchors the match at `lastIndex`, so dropping it would let `/TOKEN/y`
1078
+ * credit a binding named `X_TOKEN` that the caller's pattern rejects. The
1079
+ * caller's own `RegExp` is never written to, so a frozen one still works.
1080
+ * Same isolation `stage-policy` already applies to stage names.
1081
+ */
1082
+ const statelessTest = (pattern, name) => pattern.global || pattern.sticky ? new RegExp(pattern.source, pattern.flags).test(name) : pattern.test(name);
1083
+ const matchesAuthBindingName = (matcher, name) => matcher instanceof RegExp ? statelessTest(matcher, name) : matcher(name);
1084
+ /**
1085
+ * The Workers a Cloudflare Access application gates in production.
1086
+ *
1087
+ * A Worker enrolled through its own `access` prop is read from the Worker
1088
+ * instead — Alchemy pushes that enrollment onto the application at deploy
1089
+ * time, so the application's planned props never name it. What is left is an
1090
+ * application that declares its own `destinations`: `all_workers` covers the
1091
+ * whole account, and a `worker` destination covers the Workers this
1092
+ * application references. The graph resolves those references per prop, so
1093
+ * only the ids the application's own `destinations` prop names are credited:
1094
+ * a Worker some other prop happens to mention is not gated by this
1095
+ * application.
1096
+ *
1097
+ * Within `destinations` the graph resolves a destination's `workerId` to a
1098
+ * logical id but not to the destination that holds it, so an application that
1099
+ * also declares a `preview_worker` destination is credited with nothing: its
1100
+ * production and preview references are indistinguishable here, and crediting
1101
+ * a preview-only reference would pass an open Worker.
1102
+ */
1103
+ const accessProtectedWorkers = (resources) => {
1104
+ const workers = /* @__PURE__ */ new Set();
1105
+ let accountWide = false;
1106
+ for (const resource of resources) {
1107
+ if (resource.type !== ACCESS_APPLICATION_TYPE) continue;
1108
+ const destinations = Array.isArray(resource.props.destinations) ? resource.props.destinations : [];
1109
+ const types = new Set(destinations.map((destination) => typeof destination === "object" && destination !== null ? destination.type : void 0));
1110
+ if (types.has("all_workers")) accountWide = true;
1111
+ if (types.has("worker") && !types.has("preview_worker")) for (const id of resource.upstreamByProp.destinations ?? []) workers.add(id);
1112
+ }
1113
+ return {
1114
+ accountWide,
1115
+ workers
1116
+ };
1117
+ };
1118
+ /**
1119
+ * Proves every publicly reachable Worker in the graph declares an
1120
+ * authentication mechanism.
1121
+ *
1122
+ * A Worker passes when it enrolls in Cloudflare Access (its own `access`
1123
+ * prop, or an Access application that declares a destination for it), when it
1124
+ * carries a `secrets_store_secret` binding whose name the caller's matcher
1125
+ * accepts, or when the allowlist names it with a reason. Otherwise it is a
1126
+ * violation, and every violation in the graph is reported in one
1127
+ * `UrlImpliesAuthError`.
1128
+ */
1129
+ const assertUrlImpliesAuth = (graph, { allowlist = [], authBindingName }) => {
1130
+ const allowed = new Map(allowlist.map(({ reason, worker }) => [worker, reason]));
1131
+ const access = accessProtectedWorkers(graph.resources);
1132
+ const violations = [];
1133
+ for (const resource of graph.resources) {
1134
+ if (resource.type !== WORKER_TYPE || !publiclyReachable(resource)) continue;
1135
+ if (allowed.has(resource.id)) {
1136
+ if (allowed.get(resource.id)?.trim()) continue;
1137
+ violations.push({
1138
+ reason: "allowance-without-reason",
1139
+ worker: resource.id
1140
+ });
1141
+ continue;
1142
+ }
1143
+ if (!(enrollsInAccess(resource.props.access) || access.accountWide || access.workers.has(resource.id) || graph.bindings.some((binding) => binding.worker === resource.id && binding.type === "secrets_store_secret" && matchesAuthBindingName(authBindingName, binding.name)))) violations.push({
1144
+ reason: "unauthenticated",
1145
+ worker: resource.id
1146
+ });
1147
+ }
1148
+ if (violations.length > 0) throw new UrlImpliesAuthError(violations);
1149
+ };
1150
+ //#endregion
1151
+ //#region src/alchemy/secret-name-policy.ts
1152
+ /**
1153
+ * A secret-name redaction policy for `executeAlchemyEntry`'s `redact` hook.
1154
+ *
1155
+ * `executeAlchemyEntry` already applies a caller-supplied `redact` to captured
1156
+ * stdout and stderr and states that this package supplies no policy. This
1157
+ * builds one from names the project passes, and nothing more: there is no new
1158
+ * mechanism and no secret-name list of our own.
1159
+ *
1160
+ * The policy is fail-closed at construction. A named secret that is absent, or
1161
+ * too short to replace safely, throws while the policy is being built —
1162
+ * before any output exists to redact. The alternative is a policy that quietly
1163
+ * covers less than the caller believes it covers.
1164
+ */
1165
+ /** What a redacted value is replaced with. */
1166
+ const SECRET_REDACTION_PLACEHOLDER = "[REDACTED]";
1167
+ /**
1168
+ * The shortest value that may be replaced. A short value occurs in ordinary
1169
+ * output by chance, so replacing it would erase unrelated text and hide what
1170
+ * the run actually did.
1171
+ */
1172
+ const MINIMUM_REDACTABLE_SECRET_LENGTH = 8;
1173
+ /**
1174
+ * Builds the `redact` function `executeAlchemyEntry` takes.
1175
+ *
1176
+ * Every named value is replaced with {@link SECRET_REDACTION_PLACEHOLDER}.
1177
+ * The value is trimmed first: an environment value routinely carries a
1178
+ * trailing newline that the secret itself does not, and replacing the raw
1179
+ * form would swallow the line break that follows the secret in the output.
1180
+ * Longer values are replaced first, so a secret that contains another secret
1181
+ * leaves no fragment behind.
1182
+ *
1183
+ * The policy replaces verbatim substrings of each named value only. A value
1184
+ * that the output re-encodes passes through unredacted. URL-encoded,
1185
+ * base64, and JSON-escaped forms are all such re-encodings. A project that
1186
+ * prints a secret in one of those forms must not rely on this policy for it.
1187
+ * See issue #1011.
1188
+ *
1189
+ * An empty `names` list yields a pass-through function only when `values` is
1190
+ * also empty: a project with no secrets in its Alchemy output declares none,
1191
+ * and gets no redaction. Empty names beside a populated `values` map is
1192
+ * refused, because that is a caller who meant to declare something.
1193
+ */
1194
+ const secretNamePolicy = ({ names, values }) => {
1195
+ if (names.length === 0 && Object.keys(values).length > 0) throw new Error("secretNamePolicy needs at least one name when values are present");
1196
+ const declared = [...new Set(names)].toSorted();
1197
+ const absent = declared.filter((name) => !values[name]?.trim());
1198
+ if (absent.length > 0) throw new Error(`Secret-name policy declares values that are absent: ${absent.join(", ")}`);
1199
+ const short = declared.filter((name) => (values[name] ?? "").trim().length < 8);
1200
+ if (short.length > 0) throw new Error(`Secret-name policy declares values shorter than 8 characters, which cannot be redacted safely: ${short.join(", ")}`);
1201
+ const secrets = [...new Set(declared.map((name) => (values[name] ?? "").trim()))].toSorted((left, right) => right.length - left.length);
1202
+ return (text) => {
1203
+ let redacted = text;
1204
+ for (const secret of secrets) redacted = redacted.replaceAll(secret, SECRET_REDACTION_PLACEHOLDER);
1205
+ return redacted;
1206
+ };
1207
+ };
1208
+ //#endregion
1209
+ //#region src/alchemy/lifecycle-failure.ts
1210
+ /**
1211
+ * The one sentence each code is reported with. The table is the whole
1212
+ * vocabulary: a message that is not in it cannot be raised.
1213
+ */
1214
+ const LIFECYCLE_FAILURE_MESSAGES = {
1215
+ AMBIGUOUS_RESOURCE: "The plan prints one resource id for more than one resource.",
1216
+ AMBIGUOUS_STAGE: "The stage table declares the stage both protected and disposable.",
1217
+ CHILD_DIAGNOSTICS_UNWRITABLE: "The requested child diagnostics file could not be written.",
1218
+ CHILD_FAILED: "The Alchemy child did not exit successfully.",
1219
+ DEPLOY_INCOMPLETE: "The deploy completed without the persisted state its plan described.",
1220
+ DESTROY_RESIDUE: "The destroy left persisted state registered for the stage.",
1221
+ EFFECT_NOT_PERMITTED: "The plan holds a resource effect the policy does not permit.",
1222
+ FIRST_DEPLOY_UNAUTHORIZED: "The first deploy of the stage is not authorized for this plan.",
1223
+ INVALID_POLICY: "The lifecycle policy is malformed.",
1224
+ INVALID_REQUEST: "The lifecycle request is malformed.",
1225
+ LEASE_RELEASE_FAILED: "The stage lease could not be released and may still be held.",
1226
+ NOT_CONVERGED: "The post-deploy plan is not a no-op.",
1227
+ OWNERSHIP_LOST: "The stage ownership lease was lost during the operation.",
1228
+ PREPARATION_FAILED: "The Alchemy entry could not be prepared.",
1229
+ PROTECTED_STAGE: "The stage is protected and refuses destructive operations.",
1230
+ RESOURCE_IDENTITY_MISMATCH: "A retained resource identity does not hold for the stage.",
1231
+ STAGE_HELD: "Another holder owns the stage.",
1232
+ STAGE_NOT_OWNED: "The stack does not own the stage.",
1233
+ STATE_CHANGED: "Persisted state changed during a read-only operation.",
1234
+ STATE_STORE_INVALID: "The state store returned state that cannot be read.",
1235
+ STATE_STORE_UNAVAILABLE: "The state store could not be read.",
1236
+ UNKNOWN_EFFECT: "The Alchemy output holds an effect the adapter cannot read.",
1237
+ UNKNOWN_STACK: "The stack is not in the stage table.",
1238
+ UNKNOWN_STAGE: "The stage is not in the stage table.",
1239
+ UNSUPPORTED_ALCHEMY_VERSION: "The installed Alchemy is not the version this adapter reads."
1240
+ };
1241
+ /** A sanitized lifecycle failure. See the module comment. */
1242
+ var AlchemyLifecycleError = class extends Error {
1243
+ childDiagnosticsPath;
1244
+ code;
1245
+ mutation;
1246
+ operation;
1247
+ phase;
1248
+ planHash;
1249
+ constructor(fields) {
1250
+ super(LIFECYCLE_FAILURE_MESSAGES[fields.code]);
1251
+ this.name = "AlchemyLifecycleError";
1252
+ this.code = fields.code;
1253
+ this.mutation = fields.mutation;
1254
+ this.operation = fields.operation;
1255
+ this.phase = fields.phase;
1256
+ if (fields.childDiagnosticsPath !== void 0) this.childDiagnosticsPath = fields.childDiagnosticsPath;
1257
+ if (fields.planHash !== void 0) this.planHash = fields.planHash;
1258
+ }
1259
+ /** The fields an evidence sink prints. Fixed shape, fixed words. */
1260
+ toJSON() {
1261
+ return {
1262
+ ...this.childDiagnosticsPath === void 0 ? {} : { childDiagnosticsPath: this.childDiagnosticsPath },
1263
+ code: this.code,
1264
+ message: this.message,
1265
+ mutation: this.mutation,
1266
+ operation: this.operation,
1267
+ phase: this.phase,
1268
+ ...this.planHash === void 0 ? {} : { planHash: this.planHash }
1269
+ };
1270
+ }
1271
+ };
1272
+ const isAlchemyLifecycleError = (error) => error instanceof AlchemyLifecycleError;
1273
+ //#endregion
1274
+ //#region src/alchemy/state-tree.ts
1275
+ /**
1276
+ * One read and delete surface over a state layer.
1277
+ *
1278
+ * Alchemy's `State/Tree` module answers "which `(stack, stage)` pairs does
1279
+ * this store hold" and "remove one stage" against the `State` service
1280
+ * interface, so it works over any state layer a consumer configured,
1281
+ * including `@patronage/alchemy-d1-state`. This module is the typed entry to
1282
+ * those two operations plus the record read, and it launches no child
1283
+ * process: every answer comes from the state layer the caller passes in.
1284
+ *
1285
+ * The caller owns the state layer and the policy. This module owns the
1286
+ * address: a `(stack, stage)` pair is one stack and one stage, and nothing
1287
+ * else. `Tree` addresses a stage by the path `stack/stage`, so an empty or
1288
+ * padded stage collapses that path to the stack and a delete meant for one
1289
+ * stage removes every stage of the stack. `assertStageAddress` refuses those
1290
+ * inputs before any path is built.
1291
+ *
1292
+ * Which stages a consumer may delete stays with the consumer: this module
1293
+ * deletes the stage it is given.
1294
+ */
1295
+ const isRecord$1 = (value) => typeof value === "object" && value !== null;
1296
+ /**
1297
+ * Refuse a stack or stage name that does not address exactly one scope.
1298
+ *
1299
+ * `Tree` splits a path on `/` and drops empty and `.` segments, so `""`,
1300
+ * `"."`, a padded name and a name holding a separator all address something
1301
+ * other than the one stage the caller named. A stage read from an
1302
+ * environment variable carries a trailing newline often enough to matter.
1303
+ */
1304
+ const assertStageAddress = (field, value) => {
1305
+ if (value !== value.trim() || value === "") throw new Error(`A state ${field} must be a non-empty name with no surrounding whitespace.`);
1306
+ if (value.includes("/") || value === "." || value === "..") throw new Error(`A state ${field} must name one scope: '/', '.' and '..' are not allowed.`);
1307
+ };
1308
+ /** Run one `Tree` effect over the caller's state layer. */
1309
+ const overState = (state, effect) => Effect.runPromise(Effect.provideService(effect, State, Effect.succeed(state)));
1310
+ /**
1311
+ * Every `(stack, stage)` pair the state layer holds, or the subset a filter
1312
+ * pins. Ordered by stack then stage.
1313
+ *
1314
+ * The pairs come from the store's own `listStacks` and `listStages`, so an
1315
+ * empty result is the store reporting nothing, never a read this module
1316
+ * could not make: a state layer that cannot be read fails instead.
1317
+ */
1318
+ const inventoryStages = async (state, filter = {}) => {
1319
+ if (filter.stack !== void 0) assertStageAddress("stack", filter.stack);
1320
+ if (filter.stage !== void 0) assertStageAddress("stage", filter.stage);
1321
+ return (await overState(state, allStages(filter))).map(({ stack, stage }) => ({
1322
+ stack,
1323
+ stage
1324
+ }));
1325
+ };
1326
+ /**
1327
+ * The persisted-state document for one stage, as `parseStateSnapshot` reads
1328
+ * it: `{ resources: [{ stack, stage, fqn, state }] }`, ordered by fqn.
1329
+ *
1330
+ * The read is the one `runAlchemyLifecycle` already makes — the atomic stage
1331
+ * view, then each listed resource record — so a caller holding the document
1332
+ * and a caller holding the lifecycle see the same records. A listed resource
1333
+ * with no readable record fails the read; it is never left out, because a
1334
+ * short document reads as a stage with less in it than it has.
1335
+ *
1336
+ * A stage the store does not hold reads as a document with no resource in
1337
+ * it, the same reading the lifecycle takes for a first deploy. Only a stage
1338
+ * the store cannot read fails. `deleteStageRows` answers an absent stage the
1339
+ * other way, because it addresses a path rather than a stage view.
1340
+ */
1341
+ const readStageSnapshot = async (state, target) => {
1342
+ assertStageAddress("stack", target.stack);
1343
+ assertStageAddress("stage", target.stage);
1344
+ const scope = {
1345
+ stack: target.stack,
1346
+ stage: target.stage
1347
+ };
1348
+ const view = await Effect.runPromise(state.snapshotStage(scope));
1349
+ if (!Array.isArray(view.resources) || view.resources.some((fqn) => typeof fqn !== "string" || fqn === "")) throw new Error(`The state layer returned no resource list for ${target.stack} in ${target.stage}.`);
1350
+ const resources = await Promise.all([...view.resources].toSorted().map(async (fqn) => ({
1351
+ ...scope,
1352
+ fqn,
1353
+ state: await Effect.runPromise(state.get({
1354
+ ...scope,
1355
+ fqn
1356
+ }))
1357
+ })));
1358
+ if (resources.some((resource) => !isRecord$1(resource.state))) throw new Error(`The state layer listed a resource it could not read for ${target.stack} in ${target.stage}.`);
1359
+ return JSON.stringify({ resources });
1360
+ };
1361
+ /**
1362
+ * Remove every row the state layer holds for one stage. Other stages of the
1363
+ * same stack keep every row.
1364
+ *
1365
+ * A stage the store does not hold is refused by the state layer rather than
1366
+ * reported as removed, so a caller never reads a mistyped stage as a stage
1367
+ * that was already empty.
1368
+ */
1369
+ const deleteStageRows = async (state, target) => {
1370
+ assertStageAddress("stack", target.stack);
1371
+ assertStageAddress("stage", target.stage);
1372
+ await overState(state, deleteState({
1373
+ path: `${target.stack}/${target.stage}`,
1374
+ recursive: true
1375
+ }));
1376
+ };
1377
+ //#endregion
1378
+ //#region src/alchemy/child-diagnostics.ts
1379
+ /**
1380
+ * The optional record of what an Alchemy child printed (#1260).
1381
+ *
1382
+ * `runAlchemyLifecycle` reports a failed child as `CHILD_FAILED` and nothing
1383
+ * else: the child's output is parsed and dropped, so no secret in it can
1384
+ * reach a job log or an evidence file through the operation. That is the
1385
+ * right default and it stays the default. It also leaves an operator with a
1386
+ * failure code and no record of what failed, which twice cost a paitronage
1387
+ * investigation its evidence.
1388
+ *
1389
+ * This is the opt-in other half: a consumer that names a file gets every
1390
+ * child's streams appended to it, each stream passed whole through the
1391
+ * consumer's own redactor, under a header naming the child. The consumer chooses the path
1392
+ * and owns the redactor; this module never picks either, and nothing here
1393
+ * changes what the lifecycle decides.
1394
+ *
1395
+ * The file is opened, and the header written, **before** the child starts,
1396
+ * so an unwritable path is known before anything runs and a parent that dies
1397
+ * mid-child still leaves the marker for the child that was in flight. The
1398
+ * streams themselves arrive after the child exits, because the child is
1399
+ * captured (`spawnSync`), not streamed.
1400
+ *
1401
+ * Nothing here throws into the lifecycle's control flow once the handle is
1402
+ * open. A write failure is retained and reported by the caller under its own
1403
+ * failure code, because a record that could not be written is a different
1404
+ * fact from a child that failed, and reporting it as the second one would
1405
+ * put a false cause in front of the operator this file exists for. When the
1406
+ * caller reports it — up front, or only after the operation has run to the
1407
+ * end — is the caller's rule, not this module's; see `runAlchemyLifecycle`.
1408
+ */
1409
+ const streamSection = (label, text, redact) => {
1410
+ if (text === null || text === "") return `--- ${label}: empty ---\n`;
1411
+ const body = redact(text);
1412
+ return `--- ${label} ---\n${body.endsWith("\n") ? body : `${body}\n`}`;
1413
+ };
1414
+ /**
1415
+ * Open the record for one child and write its header.
1416
+ *
1417
+ * Throws when the file cannot be opened or the header cannot be written.
1418
+ * That throw happens before the child is launched, so a caller that has not
1419
+ * yet mutated anything can refuse the run with the stage still untouched.
1420
+ */
1421
+ const openChildDiagnostics = ({ child, diagnostics, operation, stack, stage }) => {
1422
+ const handle = openSync(diagnostics.path, "a");
1423
+ let retained;
1424
+ const guard = (write) => {
1425
+ try {
1426
+ write();
1427
+ } catch (error) {
1428
+ retained ??= error instanceof Error ? error : new Error(String(error));
1429
+ }
1430
+ };
1431
+ try {
1432
+ appendFileSync(handle, `\n===== ${operation} ${child} child — ${stack}/${stage} — ${(/* @__PURE__ */ new Date()).toISOString()} =====\n`);
1433
+ } catch (error) {
1434
+ closeSync(handle);
1435
+ throw error;
1436
+ }
1437
+ return {
1438
+ append: ({ stderr, stdout }) => {
1439
+ guard(() => {
1440
+ appendFileSync(handle, streamSection("stdout", stdout, diagnostics.redact));
1441
+ appendFileSync(handle, streamSection("stderr", stderr, diagnostics.redact));
1442
+ });
1443
+ },
1444
+ close: () => {
1445
+ guard(() => {
1446
+ closeSync(handle);
1447
+ });
1448
+ },
1449
+ failure: () => retained
1450
+ };
1451
+ };
1452
+ //#endregion
1453
+ //#region src/alchemy/lifecycle.ts
1454
+ /**
1455
+ * The shared Alchemy lifecycle operation (#1077).
1456
+ *
1457
+ * One function, `runAlchemyLifecycle`, owns the order in which a plan, a
1458
+ * deploy, or a destroy runs: request and admission checks, stage ownership
1459
+ * around every persisted-state read, the pre- and post-state snapshots, the
1460
+ * child executions, the effect policy, and the postconditions. A consumer
1461
+ * passes typed policy and two narrow capabilities — the state store from
1462
+ * `@patronage/alchemy-d1-state` and the Alchemy entry to execute — and gets
1463
+ * back a fixed-shape result or an `AlchemyLifecycleError`. It cannot call the
1464
+ * steps in another order, because it does not call the steps.
1465
+ *
1466
+ * Paitronage and HQ each reconstructed this sequence from the guards in
1467
+ * `./` and got parts of it wrong in different ways (paitronage#1917): a
1468
+ * post-child failure reported as not started, an empty-stage cleanup racing
1469
+ * a concurrent write, a plan whose immutability check ignored stack output.
1470
+ * The sequence below is the one both were reaching for.
1471
+ *
1472
+ * What stays with the consumer: the resource graph, the credentials and
1473
+ * environment the child runs with, the stage table, the retained-identity
1474
+ * markers, the first-deploy authorization list, and the state store's own
1475
+ * configuration. This module learns none of them.
1476
+ */
1477
+ const OPERATIONS = new Set([
1478
+ "plan",
1479
+ "deploy",
1480
+ "destroy"
1481
+ ]);
1482
+ /** No resource record, and an output row that is absent or `{}` (#1074). */
1483
+ const isEmptyState = (persisted) => persisted.resources.length === 0 && (!persisted.output.present || persisted.output.empty);
1484
+ const ownershipRefusal = (error) => {
1485
+ if (typeof error === "object" && error !== null && "_tag" in error && error._tag === "StageOwnershipError" && "reason" in error && (error.reason === "held" || error.reason === "lost")) return error.reason;
1486
+ };
1487
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1488
+ /**
1489
+ * The `version` of the `alchemy` manifest that owns `cliPath`: the nearest
1490
+ * `package.json` above it whose `name` is `alchemy`. Throws when none is
1491
+ * found before the filesystem root.
1492
+ */
1493
+ const alchemyManifestVersion = (cliPath) => {
1494
+ let directory = path.dirname(cliPath);
1495
+ for (;;) {
1496
+ let manifest;
1497
+ try {
1498
+ manifest = JSON.parse(readFileSync(path.join(directory, "package.json"), "utf-8"));
1499
+ } catch {
1500
+ manifest = void 0;
1501
+ }
1502
+ if (isRecord(manifest) && manifest.name === "alchemy") return manifest.version;
1503
+ const parent = path.dirname(directory);
1504
+ if (parent === directory) throw new Error("no alchemy manifest above the CLI");
1505
+ directory = parent;
1506
+ }
1507
+ };
1508
+ const persistedToSnapshot = (target, persisted) => ({ resources: persisted.resources.map(({ fqn, state }) => ({
1509
+ fqn,
1510
+ stack: target.stack,
1511
+ stage: target.stage,
1512
+ state
1513
+ })) });
1514
+ /** The run's fixed context: one request, one policy, one prepared entry. */
1515
+ /**
1516
+ * A persisted record whose last apply did not finish. Alchemy 2.0.0-beta.76
1517
+ * plans `create` for a `creating` record (a create that was interrupted)
1518
+ * and for a `deleting` one (a delete that was interrupted while the
1519
+ * resource is still declared), and both finish at the same FQN.
1520
+ */
1521
+ const IN_FLIGHT_STATUSES = new Set(["creating", "deleting"]);
1522
+ const statusOf = (record) => isRecord(record.state) ? record.state.status : void 0;
1523
+ /**
1524
+ * Resolve plan rows onto persisted FQNs. A row's `id` is the FQN Alchemy
1525
+ * printed in its tag, which is the identity the resource is persisted under
1526
+ * (epic #1165, D1), so a row resolves only to the candidate that is that
1527
+ * FQN exactly. A row with no candidate is `undefined`, and the caller
1528
+ * refuses rather than guessing.
1529
+ */
1530
+ const resolveRows = (rows, candidates) => {
1531
+ const resolved = [];
1532
+ for (const { id } of rows) {
1533
+ if (!candidates.includes(id)) return;
1534
+ resolved.push(id);
1535
+ }
1536
+ return resolved;
1537
+ };
1538
+ /**
1539
+ * Two rows with one FQN name one persisted identity twice. Alchemy keys a
1540
+ * plan by FQN, so its renderer cannot print this; output that does is not a
1541
+ * plan this operation can bind to, and is refused rather than read.
1542
+ */
1543
+ const hasRepeatedIds = (effects) => new Set(effects.resources.map(({ id }) => id)).size !== effects.resources.length;
1544
+ /** Whether a lease still fences the stage, by the store's own fenced renewal. */
1545
+ const fenceState = async (lease) => {
1546
+ try {
1547
+ await Effect.runPromise(lease.renew());
1548
+ return "held";
1549
+ } catch (error) {
1550
+ return ownershipRefusal(error) === "lost" ? "lost" : "unreachable";
1551
+ }
1552
+ };
1553
+ /** Release on the way out of a failed window; the failure is what is reported. */
1554
+ const releaseQuietly = async (lease) => {
1555
+ try {
1556
+ await Effect.runPromise(lease.release());
1557
+ } catch {}
1558
+ };
1559
+ /** The run's fixed context: one request, one policy, one prepared entry. */
1560
+ var LifecycleRun = class {
1561
+ request;
1562
+ policy;
1563
+ state;
1564
+ entry;
1565
+ childDiagnostics;
1566
+ /**
1567
+ * A diagnostics write that failed after a mutating child had started, held
1568
+ * until the operation has run to its end. See `noteDiagnosticsFailure`.
1569
+ */
1570
+ diagnosticsUnwritable = false;
1571
+ bundledEntry;
1572
+ /** What the run has done to the stage so far. Only children advance it. */
1573
+ certainty = "not-started";
1574
+ constructor(options) {
1575
+ this.request = options.request;
1576
+ this.policy = options.policy;
1577
+ this.state = options.state;
1578
+ this.entry = options.entry;
1579
+ this.childDiagnostics = options.childDiagnostics;
1580
+ }
1581
+ fail(code, phase, extra = {}) {
1582
+ const { namesDiagnostics, planHash } = extra;
1583
+ const diagnosticsPath = namesDiagnostics === true ? this.childDiagnostics?.path : void 0;
1584
+ return new AlchemyLifecycleError({
1585
+ ...diagnosticsPath === void 0 ? {} : { childDiagnosticsPath: diagnosticsPath },
1586
+ code,
1587
+ mutation: this.certainty,
1588
+ operation: this.request.operation,
1589
+ phase,
1590
+ ...planHash === void 0 ? {} : { planHash }
1591
+ });
1592
+ }
1593
+ get target() {
1594
+ return {
1595
+ stack: this.request.stack,
1596
+ stage: this.request.stage
1597
+ };
1598
+ }
1599
+ validateRequest() {
1600
+ const { operation, stack, stage } = this.request;
1601
+ if (!OPERATIONS.has(operation) || typeof stack !== "string" || typeof stage !== "string" || stack.trim() === "" || stage.trim() === "" || stack !== stack.trim() || stage !== stage.trim()) throw this.fail("INVALID_REQUEST", "request");
1602
+ if (typeof this.policy.holder !== "string" || this.policy.holder.trim() === "") throw this.fail("INVALID_POLICY", "request");
1603
+ }
1604
+ admitStage() {
1605
+ let table;
1606
+ try {
1607
+ table = stagePolicy(this.policy.stages);
1608
+ } catch {
1609
+ throw this.fail("INVALID_POLICY", "request");
1610
+ }
1611
+ try {
1612
+ table.assertStackOwnsStage(this.request.stack, this.request.stage);
1613
+ if (this.request.operation === "destroy") table.assertDestructiveStage(this.request.stage);
1614
+ return { isProtected: table.isProtectedStage(this.request.stage) };
1615
+ } catch (error) {
1616
+ if (error instanceof StagePolicyError) throw this.fail(error.code, "admission");
1617
+ throw this.fail("INVALID_POLICY", "request");
1618
+ }
1619
+ }
1620
+ /**
1621
+ * The consumer's installed Alchemy must be the version whose plan output
1622
+ * the adapter reads. Checked before any child runs.
1623
+ *
1624
+ * The version is read from the manifest of the package that owns the CLI
1625
+ * the children run: resolve `alchemy/bin/alchemy.js` from the consumer
1626
+ * (the one specifier `executeAlchemyEntry` resolves, and one the package
1627
+ * exports), then walk up to the nearest `package.json` named `alchemy`
1628
+ * and read it from disk. `alchemy/package.json` is not on the package's
1629
+ * `exports` map at the baseline, so resolving it as a module specifier
1630
+ * fails on the real package; a file read does not consult `exports`.
1631
+ */
1632
+ installedAlchemyVersion() {
1633
+ let version;
1634
+ try {
1635
+ version = alchemyManifestVersion(createRequire(this.entry.from).resolve("alchemy/bin/alchemy.js"));
1636
+ } catch {
1637
+ throw this.fail("PREPARATION_FAILED", "admission");
1638
+ }
1639
+ if (version !== PLAN_OUTPUT_ALCHEMY_VERSION) throw this.fail("UNSUPPORTED_ALCHEMY_VERSION", "admission");
1640
+ return version;
1641
+ }
1642
+ async prepareEntry() {
1643
+ if (this.entry.bundledEntry !== void 0) {
1644
+ this.bundledEntry = this.entry.bundledEntry;
1645
+ return;
1646
+ }
1647
+ try {
1648
+ const { bundleAlchemyEntry } = await import("../bundle-alchemy-entry-CT5hCphA.js").then((n) => n.n);
1649
+ this.bundledEntry = await bundleAlchemyEntry(this.entry.bundle);
1650
+ } catch {
1651
+ throw this.fail("PREPARATION_FAILED", "admission");
1652
+ }
1653
+ }
1654
+ /**
1655
+ * Run `body` under one stage lease. The lease is acquired at
1656
+ * `acquirePhase`, and every child `body` launches carries it, so no other
1657
+ * writer can reach the stage from the first read to the last decision,
1658
+ * and a child that writes can only do so under this lease.
1659
+ *
1660
+ * Acceptance is the fenced renewal: it changes no rows unless this
1661
+ * holder's unexpired row is still there, and fails with `lost` when the
1662
+ * lease expired or was taken over. `body` calls `accept` after its reads
1663
+ * and before any decision that precedes a mutation, so nothing is applied
1664
+ * on reads the lease did not cover. Independently of that, **every exit
1665
+ * from the window passes the fence**: whether `body` returned or threw,
1666
+ * and wherever it threw from, the lease is checked before the outcome is
1667
+ * classified. A lost lease is `OWNERSHIP_LOST` at the phase the run was
1668
+ * in, ahead of whatever else was found there. No early return or new
1669
+ * throw inside `body` can skip that check, because it is not in `body`.
1670
+ * A store that cannot be reached for the check while the body's own
1671
+ * failure stands reports the body's failure; a fence that holds lets a
1672
+ * genuine store or child failure through unchanged.
1673
+ *
1674
+ * A successful release proves nothing (see `StageLease`); a release that
1675
+ * fails after a good body is `LEASE_RELEASE_FAILED` at `releasePhase`.
1676
+ */
1677
+ async withLease(acquirePhase, releasePhase, body) {
1678
+ let lease;
1679
+ try {
1680
+ lease = await Effect.runPromise(this.state.acquireStageOwnership({
1681
+ ...this.target,
1682
+ holder: this.policy.holder,
1683
+ ...this.policy.ownershipTtlMillis === void 0 ? {} : { ttlMillis: this.policy.ownershipTtlMillis }
1684
+ }));
1685
+ } catch (error) {
1686
+ throw this.fail(ownershipRefusal(error) === "held" ? "STAGE_HELD" : "STATE_STORE_UNAVAILABLE", acquirePhase);
1687
+ }
1688
+ const accept = (phase) => this.fromStore(phase, lease.renew());
1689
+ let value;
1690
+ let failed = false;
1691
+ let thrown;
1692
+ try {
1693
+ value = await body(lease, accept);
1694
+ } catch (error) {
1695
+ failed = true;
1696
+ thrown = error;
1697
+ }
1698
+ const fence = await fenceState(lease);
1699
+ const failure = failed ? this.classifyStateFailure(thrown, acquirePhase) : void 0;
1700
+ const phase = failure?.phase ?? releasePhase;
1701
+ if (fence === "lost") {
1702
+ await releaseQuietly(lease);
1703
+ throw this.fail("OWNERSHIP_LOST", phase);
1704
+ }
1705
+ if (failure !== void 0) {
1706
+ await releaseQuietly(lease);
1707
+ throw failure;
1708
+ }
1709
+ if (fence === "unreachable") {
1710
+ await releaseQuietly(lease);
1711
+ throw this.fail("STATE_STORE_UNAVAILABLE", phase);
1712
+ }
1713
+ try {
1714
+ await Effect.runPromise(lease.release());
1715
+ } catch {
1716
+ throw this.fail("LEASE_RELEASE_FAILED", releasePhase);
1717
+ }
1718
+ return value;
1719
+ }
1720
+ /** Run one store effect; its failure becomes a fixed code at `phase`. */
1721
+ async fromStore(phase, effect) {
1722
+ try {
1723
+ return await Effect.runPromise(effect);
1724
+ } catch (error) {
1725
+ throw this.classifyStateFailure(error, phase);
1726
+ }
1727
+ }
1728
+ classifyStateFailure(error, phase) {
1729
+ if (error instanceof AlchemyLifecycleError) return error;
1730
+ const refusal = ownershipRefusal(error);
1731
+ if (refusal === "lost") return this.fail("OWNERSHIP_LOST", phase);
1732
+ if (refusal === "held") return this.fail("STAGE_HELD", phase);
1733
+ return this.fail("STATE_STORE_UNAVAILABLE", phase);
1734
+ }
1735
+ /** Every resource record and the stack output. Call under the lease. */
1736
+ async readPersistedState(phase) {
1737
+ const view = await this.fromStore(phase, this.state.snapshotStage(this.target));
1738
+ if (!Array.isArray(view.resources) || view.resources.some((fqn) => typeof fqn !== "string" || fqn === "")) throw this.fail("STATE_STORE_INVALID", phase);
1739
+ const records = await Promise.all([...view.resources].toSorted().map(async (fqn) => ({
1740
+ fqn,
1741
+ state: await this.fromStore(phase, this.state.get({
1742
+ ...this.target,
1743
+ fqn
1744
+ }))
1745
+ })));
1746
+ if (records.some(({ state }) => !isRecord(state))) throw this.fail("STATE_STORE_INVALID", phase);
1747
+ return {
1748
+ output: view.output,
1749
+ resources: records
1750
+ };
1751
+ }
1752
+ stageArgs() {
1753
+ return ["--stage", this.request.stage];
1754
+ }
1755
+ /**
1756
+ * Where a diagnostics write failure is reported.
1757
+ *
1758
+ * Before any mutating child has started, it is reported here and now: the
1759
+ * operator asked for a record, the record cannot be kept, and nothing has
1760
+ * been changed yet, so refusing costs nothing.
1761
+ *
1762
+ * Once a deploy or destroy child has started, it is **retained** and
1763
+ * reported only after the operation has run to its end, the way a failed
1764
+ * lease release is. The apply succeeded; failing here would abandon the
1765
+ * convergence check on a good deploy and invite an operator to destroy and
1766
+ * retry a stage that is fine. A missing record is not a reason to treat a
1767
+ * successful mutation as a failed one, and the run still ends in
1768
+ * `CHILD_DIAGNOSTICS_UNWRITABLE` — after the postconditions have run, with
1769
+ * the mutation certainty the operation actually reached.
1770
+ */
1771
+ noteDiagnosticsFailure(failed) {
1772
+ if (!failed) return;
1773
+ this.diagnosticsUnwritable = true;
1774
+ if (this.certainty !== "mutation-may-have-occurred") throw this.fail("CHILD_DIAGNOSTICS_UNWRITABLE", "execution", { namesDiagnostics: true });
1775
+ }
1776
+ /**
1777
+ * The retained record failure, once the operation itself is complete. The
1778
+ * operation's own failures are reported ahead of it, as they are for a
1779
+ * failed lease release.
1780
+ */
1781
+ assertDiagnosticsWritten() {
1782
+ if (this.diagnosticsUnwritable) throw this.fail("CHILD_DIAGNOSTICS_UNWRITABLE", "execution", { namesDiagnostics: true });
1783
+ }
1784
+ /**
1785
+ * The diagnostics section for one child, opened and headed before the
1786
+ * child starts. A path that cannot be opened refuses the run while nothing
1787
+ * has been mutated; after that it is retained and the child runs without a
1788
+ * record rather than a good apply being abandoned over one.
1789
+ */
1790
+ openDiagnostics(child) {
1791
+ if (this.childDiagnostics === void 0) return;
1792
+ try {
1793
+ return openChildDiagnostics({
1794
+ child,
1795
+ diagnostics: this.childDiagnostics,
1796
+ operation: this.request.operation,
1797
+ stack: this.request.stack,
1798
+ stage: this.request.stage
1799
+ });
1800
+ } catch {
1801
+ this.noteDiagnosticsFailure(true);
1802
+ return;
1803
+ }
1804
+ }
1805
+ /**
1806
+ * Run one child under `lease` and return its stdout for parsing. Its output
1807
+ * goes nowhere else unless the consumer asked for `childDiagnostics`, which
1808
+ * writes a redacted copy and never touches what is returned here. The
1809
+ * child's environment carries the lease, so the adapter in the child adopts
1810
+ * it rather than taking its own: there is no child without a lease, and a
1811
+ * child that writes outside this lease is refused by the store, not by this
1812
+ * module. A `plan` child leaves the certainty where it is unless it is the
1813
+ * first child; a mutating child advances it before it starts.
1814
+ */
1815
+ async runChild(child, args, lease) {
1816
+ if (this.bundledEntry === void 0) throw this.fail("PREPARATION_FAILED", "admission");
1817
+ const record = this.openDiagnostics(child);
1818
+ if (child !== "plan") this.certainty = "mutation-may-have-occurred";
1819
+ else if (this.certainty === "not-started") this.certainty = "read-only-started";
1820
+ const { env, from } = this.entry;
1821
+ let stdout;
1822
+ try {
1823
+ stdout = (await executeAlchemyEntry({
1824
+ args: [...args, ...this.entry.envFile === void 0 ? [] : ["--env-file", this.entry.envFile]],
1825
+ bundledEntry: this.bundledEntry,
1826
+ cwd: resolveAlchemyChildCwd(this.entry),
1827
+ env: {
1828
+ ...env ?? process.env,
1829
+ ...lease.childEnvironment()
1830
+ },
1831
+ from,
1832
+ maxBuffer: 67108864,
1833
+ ...record === void 0 ? {} : { onCaptured: record.append },
1834
+ stdio: "pipe"
1835
+ })).stdout ?? "";
1836
+ } catch {
1837
+ stdout = void 0;
1838
+ }
1839
+ record?.close();
1840
+ if (stdout === void 0) throw this.fail("CHILD_FAILED", "execution", { namesDiagnostics: true });
1841
+ this.noteDiagnosticsFailure(record?.failure() !== void 0);
1842
+ return stdout;
1843
+ }
1844
+ effectsOf(output, phase) {
1845
+ let effects;
1846
+ try {
1847
+ effects = parsePlanEffects(output);
1848
+ } catch {
1849
+ throw this.fail("UNKNOWN_EFFECT", phase);
1850
+ }
1851
+ if (hasRepeatedIds(effects)) throw this.fail("AMBIGUOUS_RESOURCE", phase);
1852
+ return effects;
1853
+ }
1854
+ planArgs(adopt) {
1855
+ return [
1856
+ "deploy",
1857
+ "--dry-run",
1858
+ ...adopt ? ["--adopt"] : [],
1859
+ ...this.stageArgs()
1860
+ ];
1861
+ }
1862
+ /**
1863
+ * A dry-run plan bracketed by two persisted-state reads, all under the
1864
+ * lease the caller holds, so no other writer can reach the stage while the
1865
+ * child plans. The lease is accepted, at `phase`, before anything is
1866
+ * decided on: a child that could not adopt a lease this run has lost is
1867
+ * the lease loss (`OWNERSHIP_LOST`), not a child failure, and the parent's
1868
+ * own fenced renewal is what tells the two apart, never the child's
1869
+ * output. The reads must still agree: a planning child that wrote is
1870
+ * reported as `STATE_CHANGED`, ahead of the child's own exit status. A
1871
+ * child that failed under a lease that held is `CHILD_FAILED`.
1872
+ */
1873
+ async readOnlyPlan(args, lease, accept, phase) {
1874
+ const before = await this.readPersistedState("state");
1875
+ let text = "";
1876
+ let childFailure;
1877
+ try {
1878
+ text = await this.runChild("plan", args, lease);
1879
+ } catch (error) {
1880
+ childFailure = error;
1881
+ }
1882
+ const after = await this.readPersistedState("postcondition");
1883
+ await accept(phase);
1884
+ if (!isDeepStrictEqual(before, after)) throw this.fail("STATE_CHANGED", "postcondition");
1885
+ if (childFailure !== void 0) throw childFailure;
1886
+ return {
1887
+ before,
1888
+ effects: this.effectsOf(text, "postcondition"),
1889
+ text
1890
+ };
1891
+ }
1892
+ planHashOf(text) {
1893
+ const { firstDeploy } = this.policy;
1894
+ if (firstDeploy === void 0) return;
1895
+ try {
1896
+ return firstDeployPlanHash({
1897
+ planText: text,
1898
+ sourceSha: firstDeploy.sourceSha,
1899
+ stack: this.request.stack,
1900
+ stage: this.request.stage
1901
+ });
1902
+ } catch {
1903
+ throw this.fail("INVALID_POLICY", "admission");
1904
+ }
1905
+ }
1906
+ async plan(alchemyVersion, isProtected) {
1907
+ const { before, effects, text } = await this.withLease("state", "state", async (lease, accept) => await this.readOnlyPlan(this.planArgs(this.policy.adopt === true), lease, accept, "state"));
1908
+ const firstDeploy = isProtected && isEmptyState(before);
1909
+ const planHash = firstDeploy ? this.planHashOf(text) : void 0;
1910
+ return {
1911
+ alchemyVersion,
1912
+ effects,
1913
+ firstDeploy,
1914
+ mutation: "read-only-started",
1915
+ operation: "plan",
1916
+ ...planHash === void 0 ? {} : { planHash },
1917
+ stack: this.request.stack,
1918
+ stage: this.request.stage
1919
+ };
1920
+ }
1921
+ admitFirstDeploy(effects, text) {
1922
+ if (effects.counts.update + effects.counts.replace + effects.counts.delete + effects.counts.orphaned > 0) throw this.fail("EFFECT_NOT_PERMITTED", "admission");
1923
+ const planHash = this.planHashOf(text);
1924
+ const { firstDeploy } = this.policy;
1925
+ if (firstDeploy === void 0 || planHash === void 0) throw this.fail("FIRST_DEPLOY_UNAUTHORIZED", "admission");
1926
+ try {
1927
+ firstDeployAuthorization({
1928
+ authorizedHashes: firstDeploy.authorizedHashes,
1929
+ planText: text,
1930
+ sourceSha: firstDeploy.sourceSha,
1931
+ stack: this.request.stack,
1932
+ stage: this.request.stage
1933
+ });
1934
+ } catch {
1935
+ throw this.fail("FIRST_DEPLOY_UNAUTHORIZED", "admission", { planHash });
1936
+ }
1937
+ }
1938
+ retainedMarkers() {
1939
+ const markers = this.policy.retainedIdentities ?? [];
1940
+ if (markers.length === 0 || markers.some((marker) => marker.value === void 0)) throw this.fail("INVALID_POLICY", "admission");
1941
+ return markers;
1942
+ }
1943
+ assertRetained(after, before, phase) {
1944
+ try {
1945
+ assertRetainedIdentities({
1946
+ after,
1947
+ markers: this.retainedMarkers(),
1948
+ ...before === void 0 ? {} : { before }
1949
+ });
1950
+ } catch (error) {
1951
+ if (error instanceof AlchemyLifecycleError) throw error;
1952
+ throw this.fail("RESOURCE_IDENTITY_MISMATCH", phase);
1953
+ }
1954
+ }
1955
+ /** Admit the read-only plan of a deploy. Runs under the lease. */
1956
+ admitDeploy(before, effects, text, isProtected, firstDeploy) {
1957
+ if (firstDeploy) {
1958
+ this.admitFirstDeploy(effects, text);
1959
+ return;
1960
+ }
1961
+ if (!isProtected) return;
1962
+ if (effects.counts.replace + effects.counts.delete + effects.counts.orphaned > 0) throw this.fail("EFFECT_NOT_PERMITTED", "admission");
1963
+ this.assertRetained(persistedToSnapshot(this.target, before), void 0, "admission");
1964
+ }
1965
+ /**
1966
+ * The plan said what it would create; the state must now record it. A
1967
+ * planned create resolves to exactly one candidate FQN. A candidate is a
1968
+ * record settled after the apply that either was not recorded before it,
1969
+ * or was recorded in flight (`creating`, `deleting`) **and is the FQN the
1970
+ * create row names**: an interrupted deploy's retry creates at the same
1971
+ * FQN, and that recovery is the ordinary accident this operation exists
1972
+ * for.
1973
+ *
1974
+ * A plan row carries the resource's FQN, so a row names one persisted
1975
+ * identity exactly, under any namespace. An in-flight record at another
1976
+ * FQN (`other/Worker` for a `[Worker]` row) is not the one the row names,
1977
+ * so it never qualifies as a recovery. No candidate is a create that did
1978
+ * not happen.
1979
+ */
1980
+ createdFqns(before, after, effects) {
1981
+ const planned = effects.resources.filter(({ action }) => action === "create");
1982
+ const namedByRow = new Set(planned.map(({ id }) => id));
1983
+ const priorFqns = new Set(before.resources.map(({ fqn }) => fqn));
1984
+ const inFlightBefore = new Set(before.resources.filter((record) => IN_FLIGHT_STATUSES.has(statusOf(record))).map(({ fqn }) => fqn));
1985
+ const created = resolveRows(planned, after.resources.filter((record) => !IN_FLIGHT_STATUSES.has(statusOf(record))).filter(({ fqn }) => !priorFqns.has(fqn) || inFlightBefore.has(fqn) && namedByRow.has(fqn)).map(({ fqn }) => fqn));
1986
+ if (created === void 0) throw this.fail("DEPLOY_INCOMPLETE", "postcondition");
1987
+ return created;
1988
+ }
1989
+ assertConverged(effects, after) {
1990
+ const tolerated = new Set(this.policy.nonConvergentResources);
1991
+ if (effects.bindingChanges > 0) throw this.fail("NOT_CONVERGED", "postcondition");
1992
+ if (effects.tasks.length > 0) throw this.fail("NOT_CONVERGED", "postcondition");
1993
+ const pending = effects.resources.filter(({ action }) => action !== "noop");
1994
+ const fqns = resolveRows(pending, after.resources.map(({ fqn }) => fqn));
1995
+ if (fqns === void 0) throw this.fail("NOT_CONVERGED", "postcondition");
1996
+ if (pending.some(({ action }, index) => !(action === "update" && tolerated.has(fqns[index] ?? "")))) throw this.fail("NOT_CONVERGED", "postcondition");
1997
+ }
1998
+ async deploy(alchemyVersion, isProtected) {
1999
+ const adopt = this.policy.adopt === true;
2000
+ const { convergence, created, effects, firstDeploy } = await this.withLease("state", "postcondition", async (lease, accept) => {
2001
+ const plan = await this.readOnlyPlan(this.planArgs(adopt), lease, accept, "state");
2002
+ const admittedFirstDeploy = isProtected && isEmptyState(plan.before);
2003
+ this.admitDeploy(plan.before, plan.effects, plan.text, isProtected, admittedFirstDeploy);
2004
+ await this.runChild("deploy", [
2005
+ "deploy",
2006
+ ...adopt ? ["--adopt"] : [],
2007
+ ...this.stageArgs(),
2008
+ "--yes"
2009
+ ], lease);
2010
+ const post = await this.readOnlyPlan(this.planArgs(false), lease, accept, "postcondition");
2011
+ const after = post.before;
2012
+ if (after.resources.length === 0) throw this.fail("DEPLOY_INCOMPLETE", "postcondition");
2013
+ const createdNow = this.createdFqns(plan.before, after, plan.effects);
2014
+ if (isProtected && !admittedFirstDeploy) this.assertRetained(persistedToSnapshot(this.target, after), persistedToSnapshot(this.target, plan.before), "postcondition");
2015
+ this.assertConverged(post.effects, after);
2016
+ return {
2017
+ convergence: post.effects,
2018
+ created: createdNow,
2019
+ effects: plan.effects,
2020
+ firstDeploy: admittedFirstDeploy
2021
+ };
2022
+ });
2023
+ return {
2024
+ alchemyVersion,
2025
+ convergence,
2026
+ created,
2027
+ effects,
2028
+ firstDeploy,
2029
+ mutation: "mutation-may-have-occurred",
2030
+ operation: "deploy",
2031
+ stack: this.request.stack,
2032
+ stage: this.request.stage
2033
+ };
2034
+ }
2035
+ async destroy(alchemyVersion) {
2036
+ const { cleanup, effects } = await this.withLease("state", "postcondition", async (lease, accept) => {
2037
+ const text = await this.runChild("destroy", [
2038
+ "destroy",
2039
+ ...this.stageArgs(),
2040
+ "--yes"
2041
+ ], lease);
2042
+ const destroyed = this.effectsOf(text, "postcondition");
2043
+ const view = await this.fromStore("postcondition", this.state.snapshotStage(this.target));
2044
+ await accept("postcondition");
2045
+ if (view.empty !== true) throw this.fail("DESTROY_RESIDUE", "postcondition");
2046
+ const outcome = await this.fromStore("postcondition", lease.deleteEmptyStage());
2047
+ if (outcome === "occupied") throw this.fail("DESTROY_RESIDUE", "postcondition");
2048
+ return {
2049
+ cleanup: outcome,
2050
+ effects: destroyed
2051
+ };
2052
+ });
2053
+ return {
2054
+ alchemyVersion,
2055
+ cleanup,
2056
+ effects,
2057
+ firstDeploy: false,
2058
+ mutation: "mutation-may-have-occurred",
2059
+ operation: "destroy",
2060
+ stack: this.request.stack,
2061
+ stage: this.request.stage
2062
+ };
2063
+ }
2064
+ };
2065
+ /**
2066
+ * Run one lifecycle operation, in the one order the operation runs in.
2067
+ *
2068
+ * `plan`: read the persisted state under the stage lease, run the dry-run
2069
+ * child, read the state again, and refuse if anything — a resource record
2070
+ * or the stack output — changed. Returns the plan's effects and, for an
2071
+ * empty stage with a first-deploy policy, the hash an operator authorizes.
2072
+ *
2073
+ * `deploy`: the same read-only plan, then admission on it. An empty stage is
2074
+ * a first deploy: the plan may only create, and its hash must be on the
2075
+ * authorized list. A protected stage with state refuses `replace` and
2076
+ * `delete`, and its retained identities must hold before the apply. Then the
2077
+ * apply child, then the persisted state again: it must record what the plan
2078
+ * created and, on a protected stage, the same identities as before. Then a
2079
+ * second dry-run plan, which must be a no-op except an `update` on a resource
2080
+ * the policy names non-convergent. A binding change or a task row in that
2081
+ * plan is work left behind, and no policy tolerates it.
2082
+ *
2083
+ * `destroy`: refused on a protected stage. Then, under the stage lease, the
2084
+ * destroy child, then the atomic stage view must be empty and the empty
2085
+ * output row is removed. An unreadable store fails; it never reads as empty.
2086
+ *
2087
+ * Each operation holds one stage lease from its first read to its last
2088
+ * decision, and every child adopts it through its environment. The stage is
2089
+ * never unowned while an operation runs, so no other writer can interleave,
2090
+ * and a child that takes no ownership is refused by the store at its first
2091
+ * write.
2092
+ *
2093
+ * Every failure is an `AlchemyLifecycleError`. After a deploy or destroy
2094
+ * child was started, no failure reports `not-started`.
2095
+ *
2096
+ * `childDiagnostics` is the one opt-in that keeps what the children printed:
2097
+ * both streams of every child, each passed whole through the consumer's own
2098
+ * redactor, are appended to the consumer's own file under a per-child
2099
+ * header, and a `CHILD_FAILED` then names that path so an operator knows
2100
+ * where to look. Nothing about the operation changes otherwise: a record
2101
+ * that cannot be written refuses the run only while nothing has been
2102
+ * mutated, and after that is reported as `CHILD_DIAGNOSTICS_UNWRITABLE` once
2103
+ * the operation has finished, never in place of its postconditions.
2104
+ */
2105
+ const runAlchemyLifecycle = async (options) => {
2106
+ const run = new LifecycleRun(options);
2107
+ run.validateRequest();
2108
+ const { isProtected } = run.admitStage();
2109
+ const alchemyVersion = run.installedAlchemyVersion();
2110
+ await run.prepareEntry();
2111
+ const result = await (async () => {
2112
+ switch (options.request.operation) {
2113
+ case "plan": return await run.plan(alchemyVersion, isProtected);
2114
+ case "deploy": return await run.deploy(alchemyVersion, isProtected);
2115
+ default: return await run.destroy(alchemyVersion);
2116
+ }
2117
+ })();
2118
+ run.assertDiagnosticsWritten();
2119
+ return result;
2120
+ };
2121
+ //#endregion
2122
+ //#region src/alchemy/index.ts
2123
+ /**
2124
+ * The `@patronage/factory-ci/alchemy` subpath: the only place in this package
2125
+ * where `alchemy` or `effect` may be imported (ADR 0031).
2126
+ *
2127
+ * Both are **optional** peer dependencies, so a consumer that never imports
2128
+ * this subpath installs the package with neither. Anything exported from here
2129
+ * may assume the consumer's own copy of each is resolvable; the package root
2130
+ * may never assume that, and a test proves the root import graph names
2131
+ * neither.
2132
+ *
2133
+ * Stage policy, retained-identity asserts, the lifecycle guards, the graph
2134
+ * invariants, and stack evaluation live here. The guards import neither
2135
+ * package: they are the
2136
+ * checks that surround an Alchemy run, not the run. `evaluateStack` imports
2137
+ * both.
2138
+ */
2139
+ /** The specifier a consumer imports this surface by. */
2140
+ const ALCHEMY_SUBPATH = "@patronage/factory-ci/alchemy";
2141
+ //#endregion
2142
+ export { ALCHEMY_SUBPATH, AlchemyLifecycleError, CloudflareCredentialUnavailableError, HOSTED_CLOUDFLARE_CREDENTIAL_NAMES, LIFECYCLE_FAILURE_MESSAGES, LOCAL_PREVIEW_STAGES, MINIMUM_REDACTABLE_SECRET_LENGTH, PLAN_ACTIONS, PLAN_OUTPUT_ALCHEMY_VERSION, PlanEffectsError, RetainedIdentityError, SECRET_REDACTION_PLACEHOLDER, StagePolicyError, UrlImpliesAuthError, anyStage, assertDestroyLeftNothing, assertRetainedIdentities, assertUrlImpliesAuth, credentialPreflight, deleteStageRows, evaluateStack, firstDeployAuthorization, firstDeployPlanHash, inventoryStages, isAlchemyLifecycleError, isLocalEmulationStage, localEmulationEnvironment, parsePlanEffects, parseStateSnapshot, readStageSnapshot, runAlchemyLifecycle, secretNamePolicy, stagePolicy };