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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +713 -11
  2. package/dist/.build-fingerprint.json +3 -0
  3. package/dist/alchemy/index.d.ts +1174 -0
  4. package/dist/alchemy/index.js +2142 -0
  5. package/dist/bundle-alchemy-entry-CT5hCphA.js +112 -0
  6. package/dist/execute-alchemy-entry-B0lBN-YZ.js +160 -0
  7. package/dist/execute-alchemy-entry-B397GSk5.d.ts +134 -0
  8. package/dist/index.d.ts +1218 -93
  9. package/dist/index.js +2841 -333
  10. package/package.json +28 -10
  11. package/src/actions.ts +13 -0
  12. package/src/alchemy/child-diagnostics.ts +148 -0
  13. package/src/alchemy/credential-preflight.ts +428 -0
  14. package/src/alchemy/destroy-postcondition.ts +103 -0
  15. package/src/alchemy/evaluate-stack.ts +153 -0
  16. package/src/alchemy/first-deploy-authorization.ts +194 -0
  17. package/src/alchemy/index.ts +144 -0
  18. package/src/alchemy/lifecycle-failure.ts +174 -0
  19. package/src/alchemy/lifecycle.ts +1330 -0
  20. package/src/alchemy/local-emulation.ts +89 -0
  21. package/src/alchemy/plan-effects.ts +510 -0
  22. package/src/alchemy/retained-identity.ts +248 -0
  23. package/src/alchemy/secret-name-policy.ts +96 -0
  24. package/src/alchemy/stage-policy.ts +269 -0
  25. package/src/alchemy/state-tree.ts +168 -0
  26. package/src/alchemy/url-implies-auth.ts +264 -0
  27. package/src/alchemy-baseline.ts +75 -0
  28. package/src/bundle-alchemy-entry.ts +5 -0
  29. package/src/candidate-impact-workflow.ts +110 -0
  30. package/src/candidate-lifecycle.ts +29 -0
  31. package/src/cursor-oidc.ts +33 -0
  32. package/src/execute-alchemy-entry.ts +128 -8
  33. package/src/factory-workflow.ts +83 -40
  34. package/src/github-app-token.ts +131 -22
  35. package/src/github-transport.ts +186 -0
  36. package/src/impact-demand-condition.ts +67 -0
  37. package/src/index.ts +174 -0
  38. package/src/lifecycle-contract-lane.ts +113 -0
  39. package/src/merge-freeze-job.ts +253 -0
  40. package/src/pinned-action.ts +30 -0
  41. package/src/pr-status-hud-workflow.ts +96 -0
  42. package/src/preview-cleanup-topology.ts +115 -0
  43. package/src/preview-proof-inventory.ts +1092 -0
  44. package/src/preview-proof-lifecycle.ts +328 -0
  45. package/src/preview-receipt-workflow.ts +83 -0
  46. package/src/production-impact-workflow.ts +181 -0
  47. package/src/proof-reuse-gate.ts +297 -63
  48. package/src/proof-reuse-presentation.ts +131 -0
  49. package/src/push-identity-workflow.ts +463 -0
  50. package/src/runnable-cli.ts +27 -0
  51. package/src/verify-runner-policy.ts +290 -0
  52. package/src/vitest-profile-reader.test.ts +208 -0
  53. package/src/vitest-profile-reader.ts +225 -0
  54. package/src/vitest-profile.ts +631 -0
@@ -0,0 +1,1174 @@
1
+ import { n as ExecuteAlchemyEntryOptions } from "../execute-alchemy-entry-B397GSk5.js";
2
+ import * as Alchemy from "alchemy";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+ import { StateService } from "alchemy/State";
6
+ import { ProviderServices } from "alchemy/Stack";
7
+
8
+ //#region src/alchemy/evaluate-stack.d.ts
9
+ interface EvaluatedResource {
10
+ id: string;
11
+ type: string;
12
+ props: Record<string, unknown>;
13
+ /**
14
+ * Cross-resource references, kept per top-level prop: each key is a prop
15
+ * this resource declares, and the value names the logical ids that prop's
16
+ * value references. A prop that holds an unresolved Alchemy output names its
17
+ * producer here, which is the only way to read a cross-resource reference
18
+ * out of raw props: an output is a function, so the prop says nothing on its
19
+ * own.
20
+ *
21
+ * A prop that references nothing carries no key, so the map holds only the
22
+ * props that reference something. The references are kept per prop and never
23
+ * pooled, because a caller asking "which Workers does this application's
24
+ * `destinations` name" must not be answered with an id some other prop
25
+ * happened to mention.
26
+ */
27
+ upstreamByProp: Record<string, string[]>;
28
+ }
29
+ interface EvaluatedBinding {
30
+ worker: string;
31
+ name: string;
32
+ type: string;
33
+ target?: string;
34
+ }
35
+ interface EvaluatedGraph {
36
+ resources: EvaluatedResource[];
37
+ bindings: EvaluatedBinding[];
38
+ }
39
+ interface EvaluateStackInput {
40
+ /** The stack name and program: the first and last arguments the consumer gives `Alchemy.Stack`. */
41
+ name: string;
42
+ program: Effect.Effect<unknown, unknown, Alchemy.Stack | Alchemy.Stage | ProviderServices>;
43
+ stage: string;
44
+ /** A provider layer to wrap. Each provider it registers keeps its identity but never probes. */
45
+ providers?: Layer.Layer<never>;
46
+ }
47
+ /**
48
+ * Run a stack program at `stage` and build the graph Alchemy would plan, with no state and no network:
49
+ * `Plan.make` runs under `inMemoryState()` and every provider read and list answers "absent".
50
+ */
51
+ declare const evaluateStack: ({
52
+ name,
53
+ program,
54
+ providers,
55
+ stage
56
+ }: EvaluateStackInput) => Promise<EvaluatedGraph>;
57
+ //#endregion
58
+ //#region src/alchemy/retained-identity.d.ts
59
+ /**
60
+ * Retained-identity asserts over Alchemy state snapshots (#991).
61
+ *
62
+ * A protected stage's value is the physical resources it already owns: a D1
63
+ * database id, an R2 bucket name, a Worker name. An Alchemy deploy that no
64
+ * longer recognises one of them does not fail — it creates a second one and
65
+ * leaves the first orphaned with the data still in it. The only cheap moment
66
+ * to catch that is before the deploy runs, by reading the recorded state and
67
+ * checking that every identity the project says it retains is still there and
68
+ * still the same.
69
+ *
70
+ * The project supplies the markers. This module carries no resource names.
71
+ */
72
+ /** Where in a recorded resource an identity field lives. */
73
+ type RetainedIdentitySection = "attr" | "props";
74
+ /** One physical identity a project refuses to let move. */
75
+ interface RetainedIdentityMarker {
76
+ /** The resource's fully qualified name in Alchemy state. */
77
+ readonly fqn: string;
78
+ /** The Alchemy resource type the recorded resource must report. */
79
+ readonly resourceType: string;
80
+ /** Which recorded section holds the identity field. */
81
+ readonly section: RetainedIdentitySection;
82
+ /** The identity field itself, such as `databaseId` or `bucketName`. */
83
+ readonly field: string;
84
+ /**
85
+ * The exact value the identity must hold. Omit only when a `before`
86
+ * snapshot supplies the expectation instead.
87
+ */
88
+ readonly value?: string;
89
+ }
90
+ /**
91
+ * One resource record in the persisted-state document: the `(stack, stage,
92
+ * fqn)` address, and under `state` the persisted record itself.
93
+ */
94
+ interface StateSnapshotResource {
95
+ readonly stack?: unknown;
96
+ readonly stage?: unknown;
97
+ readonly fqn?: unknown;
98
+ readonly state?: {
99
+ readonly attr?: Record<string, unknown>;
100
+ readonly props?: Record<string, unknown>;
101
+ readonly fqn?: unknown;
102
+ readonly kind?: unknown;
103
+ readonly resourceType?: unknown;
104
+ };
105
+ }
106
+ /** Which stack and stage a snapshot is read for. */
107
+ interface StateSnapshotScope {
108
+ /** Keep only records this stack owns. Omit when the document holds one. */
109
+ readonly stack?: string;
110
+ /** Keep only records this stage owns. Omit when the document holds one. */
111
+ readonly stage?: string;
112
+ }
113
+ /**
114
+ * A recorded stage state: the whole persisted-state document.
115
+ *
116
+ * An evaluated stack graph is a different artifact with the same identities in
117
+ * it. A caller holding one projects it onto this shape at the call site;
118
+ * epic #985 node D owns that graph type, and this module deliberately does not
119
+ * import it so the two land independently.
120
+ */
121
+ interface StateSnapshot {
122
+ readonly resources: readonly StateSnapshotResource[];
123
+ }
124
+ type RetainedIdentityViolationReason = /** No recorded resource matches the marker's fqn, type, and shape. */"missing" /** The recorded identity is not the value the marker names. */ | "unexpected" /** The identity differs between the two snapshots. */ | "changed";
125
+ interface RetainedIdentityViolation {
126
+ readonly marker: RetainedIdentityMarker;
127
+ readonly reason: RetainedIdentityViolationReason;
128
+ /** The identity the `after` snapshot records, when it records one. */
129
+ readonly after?: string;
130
+ /** The identity the `before` snapshot records, when one was given. */
131
+ readonly before?: string;
132
+ }
133
+ /** Every retained identity that did not hold. */
134
+ declare class RetainedIdentityError extends Error {
135
+ readonly violations: readonly RetainedIdentityViolation[];
136
+ constructor(violations: readonly RetainedIdentityViolation[]);
137
+ }
138
+ /**
139
+ * Read a persisted-state document into a snapshot of one stage.
140
+ *
141
+ * The persisted-state document holds every record in scope
142
+ * (`{ resources: [{ stack, stage, fqn, state }] }`); a single-record document
143
+ * is not this shape. A document covering the whole estate holds one fqn once
144
+ * per stage, so a marker naming it would match whichever record sorted
145
+ * first — a `prod` identity asserted against a `dev` record. `scope` narrows
146
+ * the document to the stack and stage the markers are about.
147
+ *
148
+ * Throws on anything that is not a resource inventory, and on a scoped
149
+ * document that still records one fqn twice. A state this module cannot read
150
+ * unambiguously is never treated as a state with nothing in it, because that
151
+ * reading turns a broken read into a passing assert.
152
+ */
153
+ declare const parseStateSnapshot: (text: string, scope?: StateSnapshotScope) => StateSnapshot;
154
+ interface AssertRetainedIdentitiesOptions {
155
+ /**
156
+ * The state the operation would run against. Every marker is checked
157
+ * against this snapshot.
158
+ */
159
+ readonly after: StateSnapshot;
160
+ /**
161
+ * The state recorded before. Supply it to catch an identity that moved
162
+ * between the two. Omit only when every marker names its own `value`.
163
+ */
164
+ readonly before?: StateSnapshot;
165
+ /** The identities the project retains. Must not be empty. */
166
+ readonly markers: readonly RetainedIdentityMarker[];
167
+ }
168
+ /**
169
+ * Throw `RetainedIdentityError` unless every retained identity still holds.
170
+ *
171
+ * A marker that names no `value` and has no `before` snapshot to compare
172
+ * against asserts nothing, so it is a `TypeError` rather than a pass. So is an
173
+ * empty marker list: a check with nothing in it must not read as a proof.
174
+ */
175
+ declare const assertRetainedIdentities: ({
176
+ after,
177
+ before,
178
+ markers
179
+ }: AssertRetainedIdentitiesOptions) => void;
180
+ //#endregion
181
+ //#region src/alchemy/local-emulation.d.ts
182
+ /**
183
+ * The child environment a local-emulation Alchemy run needs (#1168).
184
+ *
185
+ * Alchemy refuses to start when `CLOUDFLARE_ACCOUNT_ID` is missing or
186
+ * malformed, even for a run that only drives the local emulator and calls no
187
+ * Cloudflare API. Every project worked around that by handing the child a real
188
+ * account id and a real token, so a purely local run carried live credentials.
189
+ * This module hands it a sentinel pair instead: a well-formed account id that
190
+ * addresses no account, and a token that is not a token.
191
+ *
192
+ * The helper never reads a real credential. It reads one variable — the
193
+ * live-binding opt-in — and nothing else. The presence of a real credential in
194
+ * the parent environment is never the signal: a developer who is logged in to
195
+ * Cloudflare still gets the sentinel pair unless the opt-in says otherwise.
196
+ *
197
+ * Scrubbing an ambient token out of the child is the launcher's job, not this
198
+ * module's. This module owns the environment shape only.
199
+ */
200
+ /**
201
+ * Build the Cloudflare variables a local-emulation child is launched with.
202
+ *
203
+ * Returns exactly two variables for the local-emulation stage, or no variables
204
+ * when the live-binding opt-in is set. The result is an overlay: merge it over
205
+ * the child environment the launcher has otherwise assembled.
206
+ *
207
+ * Throws for any other stage. A non-local stage deploys to a real account, so
208
+ * a sentinel there would break that deploy, and returning nothing instead
209
+ * would let a caller believe a local run was protected when it was not.
210
+ */
211
+ declare const localEmulationEnvironment: (options: {
212
+ /**
213
+ * Where the opt-in is read from. Defaults to this process's environment. No
214
+ * other variable is read.
215
+ */
216
+ readonly environment?: Readonly<Record<string, string | undefined>>; /** The Alchemy stage the child runs. */
217
+ readonly stage: string;
218
+ }) => Readonly<Record<string, string>>;
219
+ //#endregion
220
+ //#region src/alchemy/stage-policy.d.ts
221
+ /**
222
+ * Stage and stack pairing, and protected-stage policy, from a project-supplied
223
+ * table (#991).
224
+ *
225
+ * Two projects wrote the same three questions twice — is this stage protected,
226
+ * is it disposable, and may this stack run it — and each answered them with its
227
+ * own stage names hard-coded into the answer. The names differ; the questions
228
+ * do not. This module owns the questions. A project supplies the table and gets
229
+ * decisions back, so no project or stack name appears here.
230
+ *
231
+ * One stage name does appear: `local`. It names the local emulator rather than
232
+ * any project's estate, every project spells it the same way, and the question
233
+ * it answers — is this the emulated stage — has one answer for the whole fleet.
234
+ * See {@link isLocalEmulationStage}.
235
+ *
236
+ * The disposable grammar this package already owns (`disposable-stage.ts`) is
237
+ * available as a matcher rather than assumed, because a project's disposable
238
+ * set is wider than that one grammar.
239
+ */
240
+ /**
241
+ * How a table names a set of stages: an exact list, a pattern, or a predicate
242
+ * for a set the project resolves itself (a stage backed by a config file, say).
243
+ */
244
+ type StageMatcher = readonly string[] | RegExp | ((stage: string) => boolean);
245
+ /** Every stage the shared disposable grammar recognises. */
246
+ declare const LOCAL_PREVIEW_STAGES: StageMatcher;
247
+ /** A matcher that accepts a stage any of `matchers` accepts. */
248
+ declare const anyStage: (...matchers: readonly StageMatcher[]) => StageMatcher;
249
+ /** One stack's claim on stages, in either or both directions. */
250
+ interface StackStageOwnership {
251
+ /** The stack this entry describes. */
252
+ readonly stack: string;
253
+ /**
254
+ * The only stages this stack may run. Omit when the stack runs any known
255
+ * stage no other stack claims.
256
+ */
257
+ readonly stages?: StageMatcher;
258
+ /**
259
+ * Stages no other stack may run. Omit when the stack claims none of its
260
+ * stages exclusively. Declaring the same matcher as `stages` and `claims`
261
+ * pairs a stack and its stages in both directions.
262
+ */
263
+ readonly claims?: StageMatcher;
264
+ }
265
+ interface StagePolicyTable {
266
+ readonly stages: {
267
+ /** Stages that hold real state and refuse destructive operations. */readonly protected: StageMatcher; /** Stages a cleanup sweep may create and delete freely. */
268
+ readonly disposable: StageMatcher;
269
+ };
270
+ /**
271
+ * The project's whole stack registry. When present, a stack outside it is
272
+ * refused, so a typo cannot pass as an unconstrained stack. Omit to leave
273
+ * stack ownership unpoliced.
274
+ */
275
+ readonly stacks?: readonly StackStageOwnership[];
276
+ }
277
+ type StagePolicyErrorCode = /** The stage is neither protected nor disposable. */"UNKNOWN_STAGE" /** The table classifies the stage as both protected and disposable. */ | "AMBIGUOUS_STAGE" /** A destructive operation was asked for on a protected stage. */ | "PROTECTED_STAGE" /** The stack is not in the table's registry. */ | "UNKNOWN_STACK" /** The stack and the stage are not paired by the table. */ | "STAGE_NOT_OWNED";
278
+ /**
279
+ * A policy refusal. The `code` is the stable part: a project maps it onto its
280
+ * own lifecycle failure envelope, and the message is for a human.
281
+ */
282
+ declare class StagePolicyError extends Error {
283
+ readonly code: StagePolicyErrorCode;
284
+ constructor(code: StagePolicyErrorCode, message: string);
285
+ }
286
+ interface StagePolicy {
287
+ /** Whether the stage holds real state. */
288
+ readonly isProtectedStage: (stage: string) => boolean;
289
+ /** Whether a cleanup sweep may delete the stage. */
290
+ readonly isDisposableStage: (stage: string) => boolean;
291
+ /** Whether the table classifies the stage at all. */
292
+ readonly isKnownStage: (stage: string) => boolean;
293
+ /** Throw unless the table classifies the stage. */
294
+ readonly assertKnownStage: (stage: string) => void;
295
+ /** Throw unless the stage is known and disposable. */
296
+ readonly assertDestructiveStage: (stage: string) => void;
297
+ /** Throw unless the table pairs the stack and the stage. */
298
+ readonly assertStackOwnsStage: (stack: string, stage: string) => void;
299
+ }
300
+ /**
301
+ * Is this the stage that runs against the local emulator?
302
+ *
303
+ * True for the literal `local` and nothing else (#991). Two projects and HQ
304
+ * each answered this with their own rule — a refusal list, a constant, and
305
+ * `$(whoami)` — and all three meant the same single name, so the answer is one
306
+ * literal rather than a pattern or a table. A disposable preview stage such as
307
+ * `local-pr-1-abcdef0` shares the prefix but runs against a real account, so it
308
+ * is false here. The comparison is exact: no trim and no case folding, because
309
+ * a stage name reaches Alchemy exactly as it is spelled.
310
+ *
311
+ * This question is deliberately outside {@link stagePolicy}: a project's table
312
+ * classifies the stages of its own estate, and the emulated stage belongs to
313
+ * no estate.
314
+ */
315
+ declare const isLocalEmulationStage: (stage: string) => boolean;
316
+ /**
317
+ * Read a project's stage table and answer the stage questions from it.
318
+ *
319
+ * A stage the table classifies as both protected and disposable is a table
320
+ * defect, not a stage a caller may act on, so every query on it throws.
321
+ */
322
+ declare const stagePolicy: (table: StagePolicyTable) => StagePolicy;
323
+ //#endregion
324
+ //#region src/alchemy/credential-preflight.d.ts
325
+ /**
326
+ * Cloudflare credential preflight for an Alchemy deploy.
327
+ *
328
+ * Two projects built this twice. Paitronage
329
+ * (`scripts/alchemy/credential-preflight.ts` plus
330
+ * `scripts/alchemy/cloudflare-token-policy.ts`) and firedup
331
+ * (`scripts/alchemy/local-credentials.ts`) both resolve a Cloudflare API
332
+ * token, verify it is live, and refuse to deploy unless its permission groups
333
+ * match an exact reviewed list. What repeats is the check. What does not
334
+ * repeat is the account, the permission list, the resource scope, and where
335
+ * the credential comes from, so every one of those is an input.
336
+ *
337
+ * **No credential value is ever printed.** Errors name environment variables and
338
+ * missing groups from the caller-owned permission requirements. Untrusted API
339
+ * status, receipt group names, and resource identifiers are never reflected.
340
+ * The result carries the token id, which Cloudflare's own verification endpoint
341
+ * returns and which is not a secret.
342
+ */
343
+ /** Where the deploy's Cloudflare credential comes from. */
344
+ type CredentialSource = "hosted" | "trusted-local";
345
+ /** Ownership of the token, independent of where its value is resolved. */
346
+ type CloudflareTokenKind = "account" | "user";
347
+ /**
348
+ * The environment variables a hosted deploy carries and a trusted-local
349
+ * deploy must not. A trusted-local run resolves its credential from the
350
+ * project's own secret manager; an ambient token there means the run is not
351
+ * the run it claims to be.
352
+ */
353
+ declare const HOSTED_CLOUDFLARE_CREDENTIAL_NAMES: readonly ["CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_API_TOKEN"];
354
+ /** The token and the reviewed policy document that describes it. */
355
+ interface CloudflareCredential {
356
+ /**
357
+ * The reviewed token policy, as JSON. It carries `tokenId` and `policies`;
358
+ * the id must match the live token, and the policies must reduce to the
359
+ * required permission groups.
360
+ */
361
+ readonly policyJson: string;
362
+ /** The Cloudflare API token. Never logged, never returned. */
363
+ readonly token: string;
364
+ }
365
+ interface CredentialPreflightOptions {
366
+ /** The Cloudflare account the deploy is allowed to touch. */
367
+ readonly accountId: string;
368
+ /** The process environment the deploy would run under. */
369
+ readonly environment: Readonly<Record<string, string | undefined>>;
370
+ /** Test and offline seam. Defaults to the global `fetch`. */
371
+ readonly fetchImplementation?: typeof fetch;
372
+ /**
373
+ * The exact permission groups the token must carry — no more, no fewer.
374
+ * The list is the project's, not this package's. An empty list is refused:
375
+ * it would admit any token.
376
+ */
377
+ readonly requiredPermissionGroups: readonly string[];
378
+ /**
379
+ * Produces the credential for this source. Hosted implementations read the
380
+ * environment; trusted-local implementations read the project's secret
381
+ * manager. The returned value never leaves this function.
382
+ */
383
+ readonly resolveCredential: (environment: Readonly<Record<string, string | undefined>>) => CloudflareCredential | Promise<CloudflareCredential>;
384
+ /**
385
+ * The exact resource identifiers a permission group is allowed to be
386
+ * scoped to. Defaults to the account resource alone. A project whose token
387
+ * carries zone-scoped groups returns that group's zone resources here.
388
+ */
389
+ readonly resourcesFor?: (permissionGroup: string) => readonly string[];
390
+ readonly source: CredentialSource;
391
+ /** Defaults to account-owned token verification. No endpoint fallback is attempted. */
392
+ readonly tokenKind?: CloudflareTokenKind;
393
+ }
394
+ interface CredentialPreflightResult {
395
+ readonly accountId: string;
396
+ /** The verified permission groups, sorted. Never a secret. */
397
+ readonly permissionGroups: readonly string[];
398
+ readonly source: CredentialSource;
399
+ /** Cloudflare's own id for the verified token. Not the token. */
400
+ readonly tokenId: string;
401
+ }
402
+ /**
403
+ * Cloudflare could not be asked. A caller distinguishes this from a policy
404
+ * mismatch: an unreachable API is a transient condition, and a token whose
405
+ * permissions are wrong is not.
406
+ */
407
+ declare class CloudflareCredentialUnavailableError extends Error {
408
+ constructor(message?: string);
409
+ }
410
+ /**
411
+ * Resolves the deploy's Cloudflare credential posture and checks the token
412
+ * against the reviewed policy document.
413
+ *
414
+ * The check is: the environment matches the declared source, the credential
415
+ * resolves, Cloudflare reports the token active, the reviewed policy names
416
+ * that same token, every policy is an allow policy scoped to the resources
417
+ * the project expects, and the permission groups match the required list with
418
+ * no group missing, extra, or repeated.
419
+ *
420
+ * The permission groups come from the reviewed policy document, not from
421
+ * Cloudflare. This function never reads live permissions from the Cloudflare
422
+ * API. A token whose permissions changed after the review still passes, as
423
+ * long as Cloudflare reports it active and the document still matches its id.
424
+ * See issue #1010.
425
+ *
426
+ * Throws on any failure. {@link CloudflareCredentialUnavailableError} means
427
+ * Cloudflare could not be asked; every other error means the credential is
428
+ * wrong. Nothing it throws, and nothing it returns, carries a secret value.
429
+ */
430
+ declare const credentialPreflight: ({
431
+ accountId,
432
+ environment,
433
+ fetchImplementation,
434
+ requiredPermissionGroups,
435
+ resolveCredential,
436
+ resourcesFor,
437
+ source,
438
+ tokenKind
439
+ }: CredentialPreflightOptions) => Promise<CredentialPreflightResult>;
440
+ //#endregion
441
+ //#region src/alchemy/destroy-postcondition.d.ts
442
+ /**
443
+ * The destroy postcondition: a destroyed stage owns nothing.
444
+ *
445
+ * Alchemy's `destroy` can exit zero while the state store still lists
446
+ * resources for the stage — a partial destroy, a resource whose delete failed
447
+ * quietly, or a state row that was never removed. Paitronage checks the state
448
+ * store after the child exits rather than trusting the exit code
449
+ * (`runAlchemyLifecycle`, the `"Alchemy destroy left target-stage state
450
+ * registered."` branch). Firedup carries no equivalent, which is exactly the
451
+ * gap this closes.
452
+ *
453
+ * Reading the state store is the project's job: only the project knows which
454
+ * store it configured and how to address a stage in it. This function owns the
455
+ * postcondition, and it refuses to pass on a reader that reported nothing
456
+ * usable — a check that cannot fail is not a check.
457
+ */
458
+ interface StageStateTarget {
459
+ readonly stack: string;
460
+ readonly stage: string;
461
+ }
462
+ /**
463
+ * Lists the resource identifiers the state store still holds for one stage.
464
+ * Returns an empty array for a stage the store does not know. It must not
465
+ * return an empty array for a stage it could not read; it throws instead.
466
+ */
467
+ type StageStateReader = (target: StageStateTarget) => readonly string[] | Promise<readonly string[]>;
468
+ interface AssertDestroyLeftNothingOptions extends StageStateTarget {
469
+ readonly stateReader: StageStateReader;
470
+ }
471
+ /**
472
+ * Proves a destroy left no resource registered for the stage.
473
+ *
474
+ * Throws when the store still lists resources, naming them in sorted order,
475
+ * and throws when the reader returns anything other than a list of resource
476
+ * identifiers. A reader that throws fails the postcondition too, under a fixed
477
+ * message that carries nothing the reader's own error said. Resource
478
+ * identifiers are names, never values.
479
+ */
480
+ declare const assertDestroyLeftNothing: ({
481
+ stack,
482
+ stage,
483
+ stateReader
484
+ }: AssertDestroyLeftNothingOptions) => Promise<void>;
485
+ //#endregion
486
+ //#region src/alchemy/first-deploy-authorization.d.ts
487
+ interface FirstDeployPlanHashOptions {
488
+ /**
489
+ * The Alchemy CLI's plan output, verbatim. It is canonicalised and hashed
490
+ * here; it is never stored and never logged.
491
+ */
492
+ readonly planText: string;
493
+ /**
494
+ * The reviewed source commit this plan was produced from, as a full
495
+ * lowercase 40-character SHA, or `null` when the project binds the plan to
496
+ * no commit. The field is required so that choice is written down: an
497
+ * omitted field and a deliberate `null` are not the same decision, and only
498
+ * the second one is allowed.
499
+ */
500
+ readonly sourceSha: string | null;
501
+ readonly stack: string;
502
+ readonly stage: string;
503
+ }
504
+ type FirstDeployAuthorizationOptions = FirstDeployPlanHashOptions & {
505
+ /**
506
+ * The plan hashes an operator authorized for a first deploy. The project
507
+ * owns the list; this package neither stores nor edits it.
508
+ */
509
+ readonly authorizedHashes: readonly string[];
510
+ };
511
+ interface FirstDeployAuthorization {
512
+ /** The hash that matched. An operator adds this value to authorize. */
513
+ readonly planHash: string;
514
+ }
515
+ /**
516
+ * The hash a first deploy is authorized by: the plan, the target, and the
517
+ * reviewed source, in one payload.
518
+ *
519
+ * The plan enters the payload as the sha256 of `canonicalPlan`, so the value
520
+ * that is compared never embeds plan output, and two runs of one plan agree.
521
+ * Bound: the summary line, every row's tag and action (resource, binding and
522
+ * task rows alike, `noop` included), which of those rows are resources and
523
+ * which are bindings, the stack, the stage, and the source SHA. Not bound:
524
+ * logger timestamps and fiber ids, the run's elapsed durations, ANSI colour,
525
+ * progress lines, and the order the rows were printed in.
526
+ *
527
+ * Row order is not bound but the reading of the rows is, because they are
528
+ * not the same fact. Order alone used to carry which rows are a resource's
529
+ * bindings and which are resources inside its namespace; the canonical form
530
+ * states that outright, so two plans creating different resources can never
531
+ * agree merely by printing one multiset of rows two ways.
532
+ *
533
+ * `planFormat` names that shape. A hash issued by an earlier version of this
534
+ * function, which hashed the verbatim output, can never equal one issued
535
+ * now — those hashes were not reproducible in the first place, so they
536
+ * authorized nothing that could be deployed.
537
+ *
538
+ * Throws a `PlanEffectsError` when the plan adapter cannot account for the
539
+ * output: an unreadable plan is refused, never hashed.
540
+ */
541
+ declare const firstDeployPlanHash: ({
542
+ planText,
543
+ sourceSha,
544
+ stack,
545
+ stage
546
+ }: FirstDeployPlanHashOptions) => string;
547
+ /**
548
+ * Admits a first deploy only when its plan hash is one the project
549
+ * authorized.
550
+ *
551
+ * The thrown message carries the computed hash, which is what an operator
552
+ * adds to the authorization list after reading the plan. It never carries the
553
+ * plan text.
554
+ */
555
+ declare const firstDeployAuthorization: ({
556
+ authorizedHashes,
557
+ planText,
558
+ sourceSha,
559
+ stack,
560
+ stage
561
+ }: FirstDeployAuthorizationOptions) => FirstDeployAuthorization;
562
+ //#endregion
563
+ //#region src/alchemy/url-implies-auth.d.ts
564
+ /** One Worker the project has decided may stay reachable without a declared guard. */
565
+ interface UrlImpliesAuthAllowance {
566
+ /** The Worker's logical id, as the graph reports it. */
567
+ readonly worker: string;
568
+ /** Why this Worker is public. An empty reason is not an answer. */
569
+ readonly reason: string;
570
+ }
571
+ /**
572
+ * Recognises the binding name a project's auth secret carries. A `RegExp` is
573
+ * tested against the binding name; a predicate is called with it.
574
+ */
575
+ type AuthBindingNameMatcher = RegExp | ((name: string) => boolean);
576
+ interface AssertUrlImpliesAuthOptions {
577
+ /** The `secrets_store_secret` binding names this project accepts as auth. */
578
+ readonly authBindingName: AuthBindingNameMatcher;
579
+ /** Workers exempted by a written decision. Every entry needs a reason. */
580
+ readonly allowlist?: readonly UrlImpliesAuthAllowance[];
581
+ }
582
+ /** Why one Worker failed the invariant. */
583
+ type UrlImpliesAuthViolationReason = /** The Worker is reachable and the graph shows no guard and no allowance. */"unauthenticated" /** An allowlist entry names the Worker but states no reason. */ | "allowance-without-reason";
584
+ interface UrlImpliesAuthViolation {
585
+ readonly worker: string;
586
+ readonly reason: UrlImpliesAuthViolationReason;
587
+ }
588
+ /** Every offending Worker in one throw, so a stack is fixed in one pass. */
589
+ declare class UrlImpliesAuthError extends Error {
590
+ readonly violations: readonly UrlImpliesAuthViolation[];
591
+ constructor(violations: readonly UrlImpliesAuthViolation[]);
592
+ }
593
+ /**
594
+ * Proves every publicly reachable Worker in the graph declares an
595
+ * authentication mechanism.
596
+ *
597
+ * A Worker passes when it enrolls in Cloudflare Access (its own `access`
598
+ * prop, or an Access application that declares a destination for it), when it
599
+ * carries a `secrets_store_secret` binding whose name the caller's matcher
600
+ * accepts, or when the allowlist names it with a reason. Otherwise it is a
601
+ * violation, and every violation in the graph is reported in one
602
+ * `UrlImpliesAuthError`.
603
+ */
604
+ declare const assertUrlImpliesAuth: (graph: EvaluatedGraph, {
605
+ allowlist,
606
+ authBindingName
607
+ }: AssertUrlImpliesAuthOptions) => void;
608
+ //#endregion
609
+ //#region src/alchemy/secret-name-policy.d.ts
610
+ /**
611
+ * A secret-name redaction policy for `executeAlchemyEntry`'s `redact` hook.
612
+ *
613
+ * `executeAlchemyEntry` already applies a caller-supplied `redact` to captured
614
+ * stdout and stderr and states that this package supplies no policy. This
615
+ * builds one from names the project passes, and nothing more: there is no new
616
+ * mechanism and no secret-name list of our own.
617
+ *
618
+ * The policy is fail-closed at construction. A named secret that is absent, or
619
+ * too short to replace safely, throws while the policy is being built —
620
+ * before any output exists to redact. The alternative is a policy that quietly
621
+ * covers less than the caller believes it covers.
622
+ */
623
+ /** What a redacted value is replaced with. */
624
+ declare const SECRET_REDACTION_PLACEHOLDER = "[REDACTED]";
625
+ /**
626
+ * The shortest value that may be replaced. A short value occurs in ordinary
627
+ * output by chance, so replacing it would erase unrelated text and hide what
628
+ * the run actually did.
629
+ */
630
+ declare const MINIMUM_REDACTABLE_SECRET_LENGTH = 8;
631
+ interface SecretNamePolicyOptions {
632
+ /**
633
+ * The names of the values to redact. The project owns this list; this
634
+ * package neither ships one nor infers one from a name pattern.
635
+ */
636
+ readonly names: readonly string[];
637
+ /** Where those names are read from, normally the child's environment. */
638
+ readonly values: Readonly<Record<string, string | undefined>>;
639
+ }
640
+ /**
641
+ * Builds the `redact` function `executeAlchemyEntry` takes.
642
+ *
643
+ * Every named value is replaced with {@link SECRET_REDACTION_PLACEHOLDER}.
644
+ * The value is trimmed first: an environment value routinely carries a
645
+ * trailing newline that the secret itself does not, and replacing the raw
646
+ * form would swallow the line break that follows the secret in the output.
647
+ * Longer values are replaced first, so a secret that contains another secret
648
+ * leaves no fragment behind.
649
+ *
650
+ * The policy replaces verbatim substrings of each named value only. A value
651
+ * that the output re-encodes passes through unredacted. URL-encoded,
652
+ * base64, and JSON-escaped forms are all such re-encodings. A project that
653
+ * prints a secret in one of those forms must not rely on this policy for it.
654
+ * See issue #1011.
655
+ *
656
+ * An empty `names` list yields a pass-through function only when `values` is
657
+ * also empty: a project with no secrets in its Alchemy output declares none,
658
+ * and gets no redaction. Empty names beside a populated `values` map is
659
+ * refused, because that is a caller who meant to declare something.
660
+ */
661
+ declare const secretNamePolicy: ({
662
+ names,
663
+ values
664
+ }: SecretNamePolicyOptions) => ((text: string) => string);
665
+ //#endregion
666
+ //#region src/alchemy/lifecycle-failure.d.ts
667
+ /**
668
+ * The lifecycle failure envelope (#1077).
669
+ *
670
+ * Every failure `runAlchemyLifecycle` raises is one of these. The code, the
671
+ * phase, and the mutation certainty are enumerated; the message is a fixed
672
+ * sentence looked up by code. Nothing a child process printed, nothing a
673
+ * state store said, and nothing a credential resolver quoted ever reaches
674
+ * the message, and no failure carries a `cause`. Evidence sinks (`--json`,
675
+ * the job summary) can print any field of this error verbatim. The one thing
676
+ * a failure may say about a child's output is where a consumer asked for it
677
+ * to be written (`childDiagnosticsPath`), which is a path the consumer chose
678
+ * and never the output.
679
+ */
680
+ type AlchemyLifecycleOperation = "plan" | "deploy" | "destroy";
681
+ /** Where in the sequence the failure was raised. */
682
+ type AlchemyLifecyclePhase = /** The request itself or the policy is malformed. */"request" /** A pre-mutation check refused the operation. */ | "admission" /** The state store could not be read or owned. */ | "state" /** The Alchemy child failed. */ | "execution" /** A check after the child ran did not hold. */ | "postcondition";
683
+ /**
684
+ * What the failure says about the target stage. `not-started` means no
685
+ * child ran. `read-only-started` means only a planning child ran: no child
686
+ * that can mutate was started. `mutation-may-have-occurred` means a deploy
687
+ * or destroy child was started, so the stage may differ from before.
688
+ */
689
+ type MutationCertainty = "not-started" | "read-only-started" | "mutation-may-have-occurred";
690
+ type AlchemyLifecycleFailureCode = "INVALID_REQUEST" | "INVALID_POLICY" | "UNSUPPORTED_ALCHEMY_VERSION" | "UNKNOWN_STAGE" | "AMBIGUOUS_STAGE" | "PROTECTED_STAGE" | "UNKNOWN_STACK" | "STAGE_NOT_OWNED" | "PREPARATION_FAILED" | "STAGE_HELD" | "OWNERSHIP_LOST" | "LEASE_RELEASE_FAILED" | "STATE_STORE_UNAVAILABLE" | "STATE_STORE_INVALID" | "STATE_CHANGED" | "RESOURCE_IDENTITY_MISMATCH" | "FIRST_DEPLOY_UNAUTHORIZED" | "EFFECT_NOT_PERMITTED" | "UNKNOWN_EFFECT" | "AMBIGUOUS_RESOURCE" | "CHILD_FAILED" | "CHILD_DIAGNOSTICS_UNWRITABLE" | "DEPLOY_INCOMPLETE" | "NOT_CONVERGED" | "DESTROY_RESIDUE";
691
+ /**
692
+ * The one sentence each code is reported with. The table is the whole
693
+ * vocabulary: a message that is not in it cannot be raised.
694
+ */
695
+ declare const LIFECYCLE_FAILURE_MESSAGES: Readonly<Record<AlchemyLifecycleFailureCode, string>>;
696
+ interface AlchemyLifecycleFailureFields {
697
+ /**
698
+ * The file the run's child output was being written to, on a child
699
+ * failure of a run that asked for one. It is a path, so an operator knows
700
+ * where to look; the output itself is never here and never in the message.
701
+ */
702
+ readonly childDiagnosticsPath?: string;
703
+ readonly code: AlchemyLifecycleFailureCode;
704
+ readonly mutation: MutationCertainty;
705
+ readonly operation: AlchemyLifecycleOperation;
706
+ readonly phase: AlchemyLifecyclePhase;
707
+ /**
708
+ * The reviewed plan hash, on `FIRST_DEPLOY_UNAUTHORIZED` only. It is the
709
+ * value an operator authorizes, and it is a hash, never plan text.
710
+ */
711
+ readonly planHash?: string;
712
+ }
713
+ /** A sanitized lifecycle failure. See the module comment. */
714
+ declare class AlchemyLifecycleError extends Error implements AlchemyLifecycleFailureFields {
715
+ readonly childDiagnosticsPath?: string;
716
+ readonly code: AlchemyLifecycleFailureCode;
717
+ readonly mutation: MutationCertainty;
718
+ readonly operation: AlchemyLifecycleOperation;
719
+ readonly phase: AlchemyLifecyclePhase;
720
+ readonly planHash?: string;
721
+ constructor(fields: AlchemyLifecycleFailureFields);
722
+ /** The fields an evidence sink prints. Fixed shape, fixed words. */
723
+ toJSON(): AlchemyLifecycleFailureFields & {
724
+ readonly message: string;
725
+ };
726
+ }
727
+ declare const isAlchemyLifecycleError: (error: unknown) => error is AlchemyLifecycleError;
728
+ //#endregion
729
+ //#region src/alchemy/plan-effects.d.ts
730
+ /**
731
+ * The plan-output adapter (#1077): the one reader of what the installed
732
+ * Alchemy CLI prints for a plan.
733
+ *
734
+ * Alchemy has no structured plan output at the fleet baseline, so the plan
735
+ * is read from the lines `formatPlanLines` in `alchemy/src/Cli/LoggingCli.ts`
736
+ * prints: one `Plan:` summary, one `[fqn] action` line per resource, one
737
+ * `[fqn/name] action` line per binding of that resource, and one
738
+ * `[fqn] run|drop [action]` line per task. Paitronage and HQ each wrote this
739
+ * reader; this is the one copy, and it is bound to the Alchemy version whose
740
+ * renderer it reads. A consumer running a different Alchemy is refused by
741
+ * `runAlchemyLifecycle` before any child runs, so a renderer change cannot
742
+ * be read as a plan with different effects.
743
+ *
744
+ * The renderer logs every line through Effect's pretty console logger, so a
745
+ * line arrives as `[HH:MM:SS.mmm] INFO (#1): <line>`, and coloured when the
746
+ * child inherits `FORCE_COLOR`. Both wrappers are stripped before a line is
747
+ * read. The captured output under `tests/fixtures/plan-output/beta-81/` is
748
+ * the evidence for every shape this file reads.
749
+ *
750
+ * The adapter fails on anything it does not recognise: no summary, two
751
+ * summaries, an action outside the known set, a summary it cannot parse, a
752
+ * summary whose counts do not equal the lines under it, or rows the summary
753
+ * can place in more than one way. An effect it could not account for is
754
+ * never reported as zero.
755
+ *
756
+ * Two readings share that work. `parsePlanEffects` answers what the plan
757
+ * does, which is what the lifecycle's admission rules read. `canonicalPlan`
758
+ * answers what the plan *is*, as a stable string: the rows the renderer
759
+ * printed and the reading of them, with the per-run logger metadata it also
760
+ * prints left out. `firstDeployPlanHash` hashes that string, so a plan
761
+ * reviewed at one moment and deployed at another is the same plan (#1232).
762
+ */
763
+ /** The Alchemy version whose plan renderer this adapter reads. */
764
+ declare const PLAN_OUTPUT_ALCHEMY_VERSION: string;
765
+ /**
766
+ * Every action a resource row can carry. The first six are the actions the
767
+ * summary counts, in the order the renderer prints them; `noop` rows print
768
+ * under the summary but are never counted in it.
769
+ */
770
+ declare const PLAN_ACTIONS: readonly ["create", "update", "adopted", "replace", "delete", "orphaned", "noop"];
771
+ type PlanAction = (typeof PLAN_ACTIONS)[number];
772
+ /** One top-level resource row of a plan. */
773
+ interface PlanResourceEffect {
774
+ readonly action: PlanAction;
775
+ /**
776
+ * The fully qualified name Alchemy printed in the row's tag: the namespace
777
+ * path and the logical id joined by `/`. A top-level resource's FQN is its
778
+ * logical id. This is the identity Alchemy persists the resource under.
779
+ */
780
+ readonly id: string;
781
+ }
782
+ type PlanTaskAction = "drop" | "run";
783
+ /** One task (`Action`) row of a plan. A task with nothing to do prints no row. */
784
+ interface PlanTaskEffect {
785
+ readonly action: PlanTaskAction;
786
+ /** The task's fully qualified name, as printed in the row's tag. */
787
+ readonly id: string;
788
+ }
789
+ interface PlanEffects {
790
+ /**
791
+ * Resource count per action. The six summary actions are what the summary
792
+ * line states; `noop` is counted from the rows, as the summary omits it.
793
+ */
794
+ readonly counts: Readonly<Record<PlanAction, number>>;
795
+ /** Every resource row, in the order printed. */
796
+ readonly resources: readonly PlanResourceEffect[];
797
+ /** Binding rows with a change, as the summary's `N binding changes` states. */
798
+ readonly bindingChanges: number;
799
+ /** Every task row, in the order printed. */
800
+ readonly tasks: readonly PlanTaskEffect[];
801
+ }
802
+ type PlanEffectsRejection = "no-summary" | "multiple-summaries" | "unknown-action" | "summary-unrecognized" | "count-mismatch" | "ambiguous-rows" | "effects-under-no-changes";
803
+ /** The adapter could not read the output. `reason` is the whole detail. */
804
+ declare class PlanEffectsError extends Error {
805
+ readonly reason: PlanEffectsRejection;
806
+ constructor(reason: PlanEffectsRejection);
807
+ }
808
+ /**
809
+ * Read one plan from Alchemy CLI output.
810
+ *
811
+ * Throws `PlanEffectsError` on output the adapter cannot account for. The
812
+ * output itself never appears in the error.
813
+ */
814
+ declare const parsePlanEffects: (output: string) => PlanEffects;
815
+ //#endregion
816
+ //#region src/alchemy/child-diagnostics.d.ts
817
+ /**
818
+ * The optional record of what an Alchemy child printed (#1260).
819
+ *
820
+ * `runAlchemyLifecycle` reports a failed child as `CHILD_FAILED` and nothing
821
+ * else: the child's output is parsed and dropped, so no secret in it can
822
+ * reach a job log or an evidence file through the operation. That is the
823
+ * right default and it stays the default. It also leaves an operator with a
824
+ * failure code and no record of what failed, which twice cost a paitronage
825
+ * investigation its evidence.
826
+ *
827
+ * This is the opt-in other half: a consumer that names a file gets every
828
+ * child's streams appended to it, each stream passed whole through the
829
+ * consumer's own redactor, under a header naming the child. The consumer chooses the path
830
+ * and owns the redactor; this module never picks either, and nothing here
831
+ * changes what the lifecycle decides.
832
+ *
833
+ * The file is opened, and the header written, **before** the child starts,
834
+ * so an unwritable path is known before anything runs and a parent that dies
835
+ * mid-child still leaves the marker for the child that was in flight. The
836
+ * streams themselves arrive after the child exits, because the child is
837
+ * captured (`spawnSync`), not streamed.
838
+ *
839
+ * Nothing here throws into the lifecycle's control flow once the handle is
840
+ * open. A write failure is retained and reported by the caller under its own
841
+ * failure code, because a record that could not be written is a different
842
+ * fact from a child that failed, and reporting it as the second one would
843
+ * put a false cause in front of the operator this file exists for. When the
844
+ * caller reports it — up front, or only after the operation has run to the
845
+ * end — is the caller's rule, not this module's; see `runAlchemyLifecycle`.
846
+ */
847
+ interface ChildDiagnostics {
848
+ /**
849
+ * The file every child's output is appended to. The consumer chooses it,
850
+ * and it belongs outside the repository and outside any uploaded artifact:
851
+ * redaction covers the declared secret names and nothing else, so a value
852
+ * the consumer did not declare reaches this file verbatim.
853
+ */
854
+ readonly path: string;
855
+ /**
856
+ * Applied to each captured stream **as one piece of text** before it
857
+ * reaches the file. The consumer owns it; `secretNamePolicy({ names,
858
+ * values })` builds the usual one.
859
+ *
860
+ * Whole text, not a line at a time, because a declared value can itself
861
+ * span lines — a PEM private key, a pasted service-account JSON — and a
862
+ * per-line pass would find no line holding the whole value and write every
863
+ * one of them verbatim. A redactor that works line by line is still
864
+ * correct here; one that needs the whole text only works here.
865
+ */
866
+ readonly redact: (text: string) => string;
867
+ }
868
+ //#endregion
869
+ //#region src/alchemy/lifecycle.d.ts
870
+ interface AlchemyLifecycleRequest {
871
+ readonly operation: AlchemyLifecycleOperation;
872
+ readonly stack: string;
873
+ readonly stage: string;
874
+ }
875
+ interface StageTarget {
876
+ readonly stack: string;
877
+ readonly stage: string;
878
+ }
879
+ /** Whether a stack output row exists and what it holds. */
880
+ type StackOutputOccupancy = {
881
+ readonly present: false;
882
+ } | {
883
+ readonly present: true;
884
+ readonly empty: boolean;
885
+ readonly value: unknown;
886
+ };
887
+ /**
888
+ * One consistent read of a stage, as `@patronage/alchemy-d1-state` returns
889
+ * it from a single statement. An unreadable stage fails; it is never an
890
+ * empty view.
891
+ */
892
+ interface StageSnapshotView {
893
+ /** Decoded resource FQNs. */
894
+ readonly resources: readonly string[];
895
+ readonly output: StackOutputOccupancy;
896
+ /** No resources and an absent or `{}` output row. */
897
+ readonly empty: boolean;
898
+ }
899
+ type StageCleanupOutcome = "removed" | "absent" | "occupied";
900
+ /**
901
+ * A held stage lease, as `@patronage/alchemy-d1-state` returns it.
902
+ *
903
+ * `release` is idempotent there: it succeeds when the row is gone or belongs
904
+ * to a later holder. So a release that succeeds proves nothing about
905
+ * ownership. `renew` is the fenced operation: it changes zero rows and fails
906
+ * with `lost` unless this holder's unexpired row is still there. The
907
+ * lifecycle renews before it accepts anything it read under the lease.
908
+ *
909
+ * `childEnvironment` is how the lease crosses a process boundary: the
910
+ * entries a child's environment must carry for the adapter in that child to
911
+ * adopt this lease. Every child the lifecycle launches carries them.
912
+ */
913
+ interface StageLease {
914
+ /** Drop the lease. Idempotent; never an ownership signal. */
915
+ readonly release: () => Effect.Effect<void, unknown>;
916
+ /** Extend the lease. Fails with `lost` once the lease is gone. */
917
+ readonly renew: () => Effect.Effect<void, unknown>;
918
+ /**
919
+ * The environment entries a child needs to adopt this lease. They carry
920
+ * the bearer token, so they go into a child's environment and nowhere
921
+ * else: never into a result, a failure, or a log.
922
+ */
923
+ readonly childEnvironment: () => Readonly<Record<string, string>>;
924
+ /**
925
+ * Atomically remove the stack output row if, in the same statement, it is
926
+ * `{}` and no resource rows exist. Never deletes a resource row.
927
+ */
928
+ readonly deleteEmptyStage: () => Effect.Effect<StageCleanupOutcome, unknown>;
929
+ }
930
+ /**
931
+ * The state capability: the subset of `D1StateService` the lifecycle reads
932
+ * through. `@patronage/alchemy-d1-state` satisfies it structurally; this
933
+ * package does not import that package and learns no table or account.
934
+ */
935
+ interface StageStateStore {
936
+ readonly snapshotStage: (target: StageTarget) => Effect.Effect<StageSnapshotView, unknown>;
937
+ readonly get: (request: StageTarget & {
938
+ readonly fqn: string;
939
+ }) => Effect.Effect<unknown, unknown>;
940
+ readonly acquireStageOwnership: (request: StageTarget & {
941
+ readonly holder: string;
942
+ readonly ttlMillis?: number;
943
+ }) => Effect.Effect<StageLease, unknown>;
944
+ }
945
+ interface FirstDeployPolicy {
946
+ /** The plan hashes an operator authorized. Owned by the consumer. */
947
+ readonly authorizedHashes: readonly string[];
948
+ /**
949
+ * The reviewed source commit the plan is bound to, or `null` to bind the
950
+ * plan to no commit. See `firstDeployPlanHash`.
951
+ */
952
+ readonly sourceSha: string | null;
953
+ }
954
+ interface AlchemyLifecyclePolicy {
955
+ /** The consumer's stage table. */
956
+ readonly stages: StagePolicyTable;
957
+ /** The label the stage lease is held under, such as a CI run id. */
958
+ readonly holder: string;
959
+ /** Lease length in milliseconds. The store's default applies when omitted. */
960
+ readonly ownershipTtlMillis?: number;
961
+ /**
962
+ * The physical identities a protected stage retains. Required for a
963
+ * deploy into a protected stage that already holds state; checked before
964
+ * the apply against the recorded values, and after it against the
965
+ * pre-apply snapshot.
966
+ */
967
+ readonly retainedIdentities?: readonly RetainedIdentityMarker[];
968
+ /**
969
+ * Authorizes the one deploy no earlier state constrains. A deploy into an
970
+ * empty stage with no policy here is refused.
971
+ */
972
+ readonly firstDeploy?: FirstDeployPolicy;
973
+ /** Pass `--adopt` to the deploy plan and apply. HQ's `v1` cutover flag. */
974
+ readonly adopt?: boolean;
975
+ /**
976
+ * Persisted FQNs whose `update` the post-deploy plan tolerates. A Worker
977
+ * carrying a write-only secret binding re-plans as `update` on every
978
+ * deploy because the value can never be read back; that is a property of
979
+ * the secret, not drift. Only `update` is tolerated, only on these FQNs.
980
+ * A top-level resource's FQN is its logical id; a nested one is
981
+ * `namespace/id`. A binding change is never tolerated: the plan adapter
982
+ * attributes no binding row to a resource, so a plan with binding work is
983
+ * not converged whatever this list names.
984
+ */
985
+ readonly nonConvergentResources?: readonly string[];
986
+ }
987
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
988
+ /**
989
+ * The entry capability: what `executeAlchemyEntry` needs minus what the
990
+ * lifecycle decides. Arguments are the lifecycle's; stdio is always piped so
991
+ * the plan can be read; the capture limit is `EXECUTE_ALCHEMY_ENTRY_MAX_BUFFER`.
992
+ * There is no `redact` because `redact` shapes what the child hands back,
993
+ * and the plan text must be the child's own bytes. There is no `onCaptured`
994
+ * for the same reason in the other direction: the sink is the lifecycle's,
995
+ * so a consumer-supplied one would be dropped, and an option that
996
+ * type-checks and does nothing is worse than one that does not exist. By
997
+ * default the captured output is parsed and dropped, written nowhere, so
998
+ * nothing in it can reach a job log or an evidence file through this
999
+ * operation; a consumer that wants a record opts in with `childDiagnostics`,
1000
+ * which owns its own redactor and its own file.
1001
+ */
1002
+ type AlchemyLifecycleEntry = DistributiveOmit<ExecuteAlchemyEntryOptions, "args" | "onCaptured" | "stdio" | "maxBuffer" | "redact"> & {
1003
+ /** Explicit dotenv file for every child; omitted preserves Alchemy defaults. */readonly envFile?: string;
1004
+ };
1005
+ interface RunAlchemyLifecycleOptions {
1006
+ readonly request: AlchemyLifecycleRequest;
1007
+ readonly policy: AlchemyLifecyclePolicy;
1008
+ readonly state: StageStateStore;
1009
+ readonly entry: AlchemyLifecycleEntry;
1010
+ /**
1011
+ * Opt in to keeping what the children printed (#1260). Omitted, the
1012
+ * captured output is parsed and dropped, exactly as before: this is the
1013
+ * only way any of it reaches a file through this operation.
1014
+ *
1015
+ * Set, every child of the operation — the dry runs, the apply, the
1016
+ * destroy — has both streams appended to `path`, each stream passed whole
1017
+ * through `redact` (never a line at a time, so a declared value that
1018
+ * spans lines is covered), under a header naming the child. The consumer
1019
+ * chooses the
1020
+ * path and supplies the redactor; the lifecycle chooses neither and holds
1021
+ * no secret-name list. `secretNamePolicy({ names, values })` from this
1022
+ * subpath builds the redactor from the names the consumer declares.
1023
+ *
1024
+ * The record is a copy: the plan text the operation parses and hashes is
1025
+ * the child's own output, untouched by `redact`. Writing it changes no
1026
+ * exit status and no decision here, and a write that fails is reported as
1027
+ * `CHILD_DIAGNOSTICS_UNWRITABLE` rather than as a child failure — up front
1028
+ * while nothing has been mutated, and otherwise only after the operation
1029
+ * has run to its end, so a record that could not be kept never abandons a
1030
+ * good apply before its convergence check.
1031
+ */
1032
+ readonly childDiagnostics?: ChildDiagnostics;
1033
+ }
1034
+ interface AlchemyLifecycleResult {
1035
+ readonly operation: AlchemyLifecycleOperation;
1036
+ readonly stack: string;
1037
+ readonly stage: string;
1038
+ /** What the run did to the stage. A plan never mutates. */
1039
+ readonly mutation: Exclude<MutationCertainty, "not-started">;
1040
+ /** The installed Alchemy version the children ran under. */
1041
+ readonly alchemyVersion: string;
1042
+ /** A protected stage held no state before the operation. */
1043
+ readonly firstDeploy: boolean;
1044
+ /** The plan the operation read (plan), applied (deploy), or destroyed. */
1045
+ readonly effects: PlanEffects;
1046
+ /**
1047
+ * The persisted FQN of every resource the deploy's plan created, resolved
1048
+ * against the state recorded after the apply. Present on deploy only.
1049
+ */
1050
+ readonly created?: readonly string[];
1051
+ /** The post-deploy plan. Present on deploy only. */
1052
+ readonly convergence?: PlanEffects;
1053
+ /** The reviewed first-deploy hash. Present on a plan of an empty stage with a first-deploy policy. */
1054
+ readonly planHash?: string;
1055
+ /** What the empty-stage cleanup did. Present on destroy only. */
1056
+ readonly cleanup?: StageCleanupOutcome;
1057
+ }
1058
+ /**
1059
+ * Run one lifecycle operation, in the one order the operation runs in.
1060
+ *
1061
+ * `plan`: read the persisted state under the stage lease, run the dry-run
1062
+ * child, read the state again, and refuse if anything — a resource record
1063
+ * or the stack output — changed. Returns the plan's effects and, for an
1064
+ * empty stage with a first-deploy policy, the hash an operator authorizes.
1065
+ *
1066
+ * `deploy`: the same read-only plan, then admission on it. An empty stage is
1067
+ * a first deploy: the plan may only create, and its hash must be on the
1068
+ * authorized list. A protected stage with state refuses `replace` and
1069
+ * `delete`, and its retained identities must hold before the apply. Then the
1070
+ * apply child, then the persisted state again: it must record what the plan
1071
+ * created and, on a protected stage, the same identities as before. Then a
1072
+ * second dry-run plan, which must be a no-op except an `update` on a resource
1073
+ * the policy names non-convergent. A binding change or a task row in that
1074
+ * plan is work left behind, and no policy tolerates it.
1075
+ *
1076
+ * `destroy`: refused on a protected stage. Then, under the stage lease, the
1077
+ * destroy child, then the atomic stage view must be empty and the empty
1078
+ * output row is removed. An unreadable store fails; it never reads as empty.
1079
+ *
1080
+ * Each operation holds one stage lease from its first read to its last
1081
+ * decision, and every child adopts it through its environment. The stage is
1082
+ * never unowned while an operation runs, so no other writer can interleave,
1083
+ * and a child that takes no ownership is refused by the store at its first
1084
+ * write.
1085
+ *
1086
+ * Every failure is an `AlchemyLifecycleError`. After a deploy or destroy
1087
+ * child was started, no failure reports `not-started`.
1088
+ *
1089
+ * `childDiagnostics` is the one opt-in that keeps what the children printed:
1090
+ * both streams of every child, each passed whole through the consumer's own
1091
+ * redactor, are appended to the consumer's own file under a per-child
1092
+ * header, and a `CHILD_FAILED` then names that path so an operator knows
1093
+ * where to look. Nothing about the operation changes otherwise: a record
1094
+ * that cannot be written refuses the run only while nothing has been
1095
+ * mutated, and after that is reported as `CHILD_DIAGNOSTICS_UNWRITABLE` once
1096
+ * the operation has finished, never in place of its postconditions.
1097
+ */
1098
+ declare const runAlchemyLifecycle: (options: RunAlchemyLifecycleOptions) => Promise<AlchemyLifecycleResult>;
1099
+ //#endregion
1100
+ //#region src/alchemy/state-tree.d.ts
1101
+ /**
1102
+ * The subset of the state layer the record read goes through: the atomic
1103
+ * stage view and the per-resource record. `@patronage/alchemy-d1-state`
1104
+ * satisfies it structurally, the same way `runAlchemyLifecycle` takes it.
1105
+ */
1106
+ type StageRecordStore = Pick<StageStateStore, "get" | "snapshotStage">;
1107
+ /**
1108
+ * Pins part of the inventory.
1109
+ *
1110
+ * A pinned `stack` or `stage` is taken at face value and skips the matching
1111
+ * list call, because naming a scope is not a claim that it exists. So a
1112
+ * pinned `stage` returns that stage once per stack whether or not the stack
1113
+ * holds it. Pass no filter to inventory what the store actually holds.
1114
+ */
1115
+ interface StageFilter {
1116
+ readonly stack?: string;
1117
+ readonly stage?: string;
1118
+ }
1119
+ /**
1120
+ * Every `(stack, stage)` pair the state layer holds, or the subset a filter
1121
+ * pins. Ordered by stack then stage.
1122
+ *
1123
+ * The pairs come from the store's own `listStacks` and `listStages`, so an
1124
+ * empty result is the store reporting nothing, never a read this module
1125
+ * could not make: a state layer that cannot be read fails instead.
1126
+ */
1127
+ declare const inventoryStages: (state: StateService, filter?: StageFilter) => Promise<readonly StageTarget[]>;
1128
+ /**
1129
+ * The persisted-state document for one stage, as `parseStateSnapshot` reads
1130
+ * it: `{ resources: [{ stack, stage, fqn, state }] }`, ordered by fqn.
1131
+ *
1132
+ * The read is the one `runAlchemyLifecycle` already makes — the atomic stage
1133
+ * view, then each listed resource record — so a caller holding the document
1134
+ * and a caller holding the lifecycle see the same records. A listed resource
1135
+ * with no readable record fails the read; it is never left out, because a
1136
+ * short document reads as a stage with less in it than it has.
1137
+ *
1138
+ * A stage the store does not hold reads as a document with no resource in
1139
+ * it, the same reading the lifecycle takes for a first deploy. Only a stage
1140
+ * the store cannot read fails. `deleteStageRows` answers an absent stage the
1141
+ * other way, because it addresses a path rather than a stage view.
1142
+ */
1143
+ declare const readStageSnapshot: (state: StageRecordStore, target: StageTarget) => Promise<string>;
1144
+ /**
1145
+ * Remove every row the state layer holds for one stage. Other stages of the
1146
+ * same stack keep every row.
1147
+ *
1148
+ * A stage the store does not hold is refused by the state layer rather than
1149
+ * reported as removed, so a caller never reads a mistyped stage as a stage
1150
+ * that was already empty.
1151
+ */
1152
+ declare const deleteStageRows: (state: StateService, target: StageTarget) => Promise<void>;
1153
+ //#endregion
1154
+ //#region src/alchemy/index.d.ts
1155
+ /**
1156
+ * The `@patronage/factory-ci/alchemy` subpath: the only place in this package
1157
+ * where `alchemy` or `effect` may be imported (ADR 0031).
1158
+ *
1159
+ * Both are **optional** peer dependencies, so a consumer that never imports
1160
+ * this subpath installs the package with neither. Anything exported from here
1161
+ * may assume the consumer's own copy of each is resolvable; the package root
1162
+ * may never assume that, and a test proves the root import graph names
1163
+ * neither.
1164
+ *
1165
+ * Stage policy, retained-identity asserts, the lifecycle guards, the graph
1166
+ * invariants, and stack evaluation live here. The guards import neither
1167
+ * package: they are the
1168
+ * checks that surround an Alchemy run, not the run. `evaluateStack` imports
1169
+ * both.
1170
+ */
1171
+ /** The specifier a consumer imports this surface by. */
1172
+ declare const ALCHEMY_SUBPATH = "@patronage/factory-ci/alchemy";
1173
+ //#endregion
1174
+ export { ALCHEMY_SUBPATH, type AlchemyLifecycleEntry, AlchemyLifecycleError, type AlchemyLifecycleFailureCode, type AlchemyLifecycleFailureFields, type AlchemyLifecycleOperation, type AlchemyLifecyclePhase, type AlchemyLifecyclePolicy, type AlchemyLifecycleRequest, type AlchemyLifecycleResult, type AssertDestroyLeftNothingOptions, type AssertRetainedIdentitiesOptions, type AssertUrlImpliesAuthOptions, type AuthBindingNameMatcher, type ChildDiagnostics, type CloudflareCredential, CloudflareCredentialUnavailableError, type CloudflareTokenKind, type CredentialPreflightOptions, type CredentialPreflightResult, type CredentialSource, type EvaluateStackInput, type EvaluatedBinding, type EvaluatedGraph, type EvaluatedResource, type FirstDeployAuthorization, type FirstDeployAuthorizationOptions, type FirstDeployPlanHashOptions, type FirstDeployPolicy, HOSTED_CLOUDFLARE_CREDENTIAL_NAMES, LIFECYCLE_FAILURE_MESSAGES, LOCAL_PREVIEW_STAGES, MINIMUM_REDACTABLE_SECRET_LENGTH, type MutationCertainty, PLAN_ACTIONS, PLAN_OUTPUT_ALCHEMY_VERSION, type PlanAction, type PlanEffects, PlanEffectsError, type PlanEffectsRejection, type PlanResourceEffect, type PlanTaskAction, type PlanTaskEffect, RetainedIdentityError, type RetainedIdentityMarker, type RetainedIdentitySection, type RetainedIdentityViolation, type RetainedIdentityViolationReason, type RunAlchemyLifecycleOptions, SECRET_REDACTION_PLACEHOLDER, type SecretNamePolicyOptions, type StackOutputOccupancy, type StackStageOwnership, type StageCleanupOutcome, type StageLease, type StageMatcher, type StagePolicy, StagePolicyError, type StagePolicyErrorCode, type StagePolicyTable, type StageSnapshotView, type StageStateReader, type StageStateStore, type StageStateTarget, type StageTarget, type StateSnapshot, type StateSnapshotResource, type StateSnapshotScope, type UrlImpliesAuthAllowance, UrlImpliesAuthError, type UrlImpliesAuthViolation, type UrlImpliesAuthViolationReason, anyStage, assertDestroyLeftNothing, assertRetainedIdentities, assertUrlImpliesAuth, credentialPreflight, deleteStageRows, evaluateStack, firstDeployAuthorization, firstDeployPlanHash, inventoryStages, isAlchemyLifecycleError, isLocalEmulationStage, localEmulationEnvironment, parsePlanEffects, parseStateSnapshot, readStageSnapshot, runAlchemyLifecycle, secretNamePolicy, stagePolicy };