@intentius/chant-lexicon-pulumi 0.124.85 → 0.124.86

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.
package/src/stack-ops.ts CHANGED
@@ -1,9 +1,18 @@
1
1
  /**
2
2
  * Gated stack operations (#4578): a stack's export, a stuck lock's release,
3
- * and a move of resources between stacks, each run only after a gated
4
- * request (#4551) is approved on the workspace ledger. INTENTIUS/plywood#16
5
- * puts its `export`, `cancel` and `move` verbs on these; plywood holds the
6
- * words only.
3
+ * a move of resources between stacks and a day-2 action, each run only
4
+ * after a gated request (#4551) is approved on the workspace ledger.
5
+ * INTENTIUS/plywood#16 puts its `export`, `cancel`, `move` and `action`
6
+ * verbs on these; plywood holds the words only.
7
+ *
8
+ * Since #4808 each one runs on chant core's walk rather than one of its
9
+ * own: the export is core's `exportStateVersion` over a Pulumi
10
+ * {@link pulumiStackVersionSource}, the cancel is core's `releaseStateLock`
11
+ * over a Pulumi lock source, the move is core's `runStateMigration` over a
12
+ * Pulumi migration engine, and the action is core's `gatedOp`. So each one
13
+ * gets what core's adapters check: the export of one version, the live-run
14
+ * check before a cancel, and the check that nothing moved between a move's
15
+ * plan and its write.
7
16
  *
8
17
  * ## The request
9
18
  *
@@ -13,40 +22,51 @@
13
22
  *
14
23
  * | Operation | kind | subject (the gate) | fields |
15
24
  * |---|---|---|---|
16
- * | export | `stack-export` | `<stack>` | `stack`, `engine`, `deliver: requester` |
17
- * | cancel | `stack-cancel` | `<stack>` | `stack`, `lockId` |
18
- * | move | `stack-move` | `move:<source>:<dest>` | `source`, `dest`, `engine`, `urns` (sorted, comma-joined) |
25
+ * | export | `stack-export` | `<stack>` | `location`, `version_id` |
26
+ * | cancel | `stack-cancel` | `<stack>` | `location`, `id` (the lock id) |
27
+ * | move | `stack-move` | `move:<source>:<dest>` | `source`, `dest`, `engine`, `urns` (sorted, comma-joined), `roots`, `proof` (the plan's digest) |
19
28
  * | action | `stack-action` | `action:<stack>:<name>` (the URN without a name) | `stack`, `urn`, `engine`, `preview` (the preview's digest), `name` when given |
20
29
  *
21
30
  * The first call records the pending fact and answers `waiting` with the
22
31
  * `chant approve` command. A later call with the same request reuses the
23
32
  * standing request's `at`, so it digests the same and finds the approval.
24
33
  * The requester's own approval never counts (`refused`). Once approved, the
25
- * request is spent (`spendGatedRequest`, pushed before anything runs), the
26
- * operation runs, and a `finished` line records how it ended with flat
27
- * facts: never the export's content, only its digest and size.
34
+ * request is spent (pushed before anything runs), the operation runs, and a
35
+ * `finished` line records how it ended with flat facts: never a state's
36
+ * content, only digests, ids and counts.
28
37
  *
29
38
  * ## What runs
30
39
  *
31
- * - export: `pulumi stack export --stack <s>` (`plunge stack export` on
32
- * plunge), the read form #4546 allows. The output goes to the requester's
33
- * machine only: a file outside every git working tree, mode 600, never
34
- * overwritten, and the call is refused in CI (`CI`, `GITHUB_ACTIONS`,
35
- * `GITLAB_CI`, `FORGEJO_ACTIONS`), where it would become a job artifact.
36
- * - cancel: `pulumi cancel --yes --stack <s>`, after checking the stack's
37
- * lock is still the one approved when the backend is a `file://` path
38
- * (`.pulumi/locks/...`); another backend's lock is read by the caller's
39
- * `readLockId`, or the check is reported as not made. A stack on plunge is
40
- * refused: plunge keeps no stack lock.
41
- * - move: both stacks preview first, and the move runs only when the
42
- * previews change nothing but the moved resources (each a delete in the
43
- * source and a create of the same type and name in the destination), so
44
- * the move leaves both previewing no change. On plunge, `plunge stack move
45
- * ... --json` plans it as well and its refusals refuse the request. Then
46
- * `pulumi state move --source --dest --yes <urn>...` on stock, or `plunge
47
- * stack move ... --json --yes` (INTENTIUS/plunge#56). Both stacks preview
48
- * again afterwards; a change left on either finishes the request `failed`
49
- * with the changes named.
40
+ * - export: the version asked for, else the one the stack holds now. On a
41
+ * backend that numbers its updates (Pulumi Cloud) the version is the
42
+ * update's number from `stack history`, and the approved call runs
43
+ * `pulumi stack export --stack <s> --version <n>`. A file backend, a
44
+ * bucket and plunge number none, so there the version is the `sha256:`
45
+ * digest of the stack's export now, and the approved call writes the
46
+ * export only while its digest is still that one; a stack updated after
47
+ * the approval asks again. The output goes to the requester's machine
48
+ * only: a file outside every git working tree, mode 600, never
49
+ * overwritten, and the call is refused in CI.
50
+ * - cancel: the lock is read first (a `file://` backend's lock file under
51
+ * `.pulumi/locks/...`, or the caller's `readLockId`); an approved lock
52
+ * that is not the one held is refused before anything is asked. While a
53
+ * run of the repository that began before the lock was taken is alive,
54
+ * nothing is asked ({@link PulumiStackOpRefused} `live-run`), and the runs
55
+ * are read again just before the spend (`held`). Then `pulumi cancel
56
+ * --yes --stack <s>`, and the lock is read again to check it went. A stack
57
+ * on plunge is refused: plunge keeps no stack lock.
58
+ * - move: both stacks preview first, and the move is asked for only when
59
+ * the previews change nothing but the moved resources (each a delete in
60
+ * the source and a create of the same type and name in the destination).
61
+ * On plunge, `plunge stack move ... --json` plans it as well and its
62
+ * refusals refuse the request. The request binds each stack's export
63
+ * digest, so a stack updated before the approval asks again. Approved,
64
+ * each stack's export is read again just before the write, and one that
65
+ * is not the planned one refuses the move with nothing moved (`failed`,
66
+ * `check: "moved"`). Then `pulumi state move --source --dest --yes
67
+ * <urn>...` on stock, or `plunge stack move ... --json --yes`
68
+ * (INTENTIUS/plunge#56), and both stacks preview again; a change left on
69
+ * either finishes the request `failed` with the changes named.
50
70
  *
51
71
  * - action (#4654): a day-2 action is a `command:` resource
52
72
  * (`command:local:Command`, `command:remote:Command`) whose replacement is
@@ -61,22 +81,21 @@
61
81
  * lines. A request that applied answers `spent` to the same call, unless
62
82
  * the caller asks `anew`.
63
83
  *
64
- * The writes go through `runGatedPulumi` and `runGatedPlunge`
65
- * (`./run.ts`), whose fixed forms are the whole of what may run.
84
+ * The writes go through `runGatedPulumi` and `runGatedPlunge`, and the
85
+ * version reads through `runStackOpReadPulumi` (`./run.ts`), whose fixed
86
+ * forms are the whole of what may run.
66
87
  */
67
88
  import { createHash } from "node:crypto";
68
- import { existsSync, readdirSync, writeFileSync } from "node:fs";
69
- import { dirname, isAbsolute, join, resolve } from "node:path";
89
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
90
+ import { isAbsolute, join, resolve } from "node:path";
70
91
  import type { ChangeSetPart } from "@intentius/chant/change-set";
71
- import type {
72
- finishGatedRequest as FinishGatedRequest,
73
- readGatedRequests as ReadGatedRequests,
74
- requestGate as RequestGate,
75
- spendGatedRequest as SpendGatedRequest,
76
- GatedRequest,
77
- GatedRequestRules,
78
- RequestGateResult,
79
- } from "@intentius/chant/lifecycle/gated-request";
92
+ import type { ForgeOverrides } from "@intentius/chant/forge-flags";
93
+ import { chantGatedLedger, gatedOp, type GatedOpAct, type GatedRequestLedger } from "@intentius/chant/lifecycle/gated-op";
94
+ import type { GatedRequest, GatedRequestRules } from "@intentius/chant/lifecycle/gated-request";
95
+ import type { ForgeTargetOptions } from "@intentius/chant/pr-forge";
96
+ import { exportStateVersion, StateExportError, type StateVersionSource } from "@intentius/chant/state-export";
97
+ import { runStateMigration, type MigrationCheck, type MigrationRootPlan, type StateMigrationEngine } from "@intentius/chant/state-migration";
98
+ import { describeRun, forgeLiveRuns, releaseStateLock, type LiveRun, type LockInfo, type StateLockSource } from "@intentius/chant/state-unlock";
80
99
  import { parsePulumiUrn, pulumiNodeKey } from "@intentius/chant/pulumi-urn";
81
100
  import { pulumiStackBackend } from "./adopt";
82
101
  import { pulumiExportResources, pulumiPreviewDigest, pulumiSteps, PULUMI_UNCHANGED_OPS } from "./change-set";
@@ -90,11 +109,14 @@ import {
90
109
  pulumiActionUpArgs,
91
110
  pulumiCancelArgs,
92
111
  pulumiRunFailure,
112
+ pulumiStackExportVersionArgs,
113
+ pulumiStackHistoryArgs,
93
114
  pulumiStateMoveArgs,
94
115
  runAllowedPlunge,
95
116
  runAllowedPulumi,
96
117
  runGatedPlunge,
97
118
  runGatedPulumi,
119
+ runStackOpReadPulumi,
98
120
  type PulumiRunner,
99
121
  } from "./run";
100
122
  import { isObject } from "./values";
@@ -104,13 +126,8 @@ export const PULUMI_STACK_OPS_OP = "pulumi-stack-ops";
104
126
 
105
127
  export type PulumiStackOpKind = "stack-export" | "stack-cancel" | "stack-move" | "stack-action";
106
128
 
107
- /** chant's gated-request API (#4551), injectable for tests. */
108
- export interface GatedRequestApi {
109
- requestGate: typeof RequestGate;
110
- spendGatedRequest: typeof SpendGatedRequest;
111
- finishGatedRequest: typeof FinishGatedRequest;
112
- readGatedRequests: typeof ReadGatedRequests;
113
- }
129
+ /** chant's gated-request ledger (#4551), injectable for tests: core's `GatedRequestLedger`. */
130
+ export type GatedRequestApi = GatedRequestLedger;
114
131
 
115
132
  /** What every operation takes. */
116
133
  export interface PulumiStackOpCommon {
@@ -122,8 +139,10 @@ export interface PulumiStackOpCommon {
122
139
  op?: string;
123
140
  /** Where the workspace ledger is read and written. Default the process's cwd. */
124
141
  ledgerCwd?: string;
125
- /** How long the pending fact stands. Default the gate default. */
142
+ /** How long the pending fact stands. Default 48h. */
126
143
  expiry?: string;
144
+ /** The ref the rules are read at. */
145
+ base?: string;
127
146
  now?: string;
128
147
  run?: PulumiRunner;
129
148
  plunge?: PulumiRunner;
@@ -131,6 +150,9 @@ export interface PulumiStackOpCommon {
131
150
  gated?: GatedRequestApi;
132
151
  }
133
152
 
153
+ /** Which of core's checks stopped an operation that was approved (#4808): a state that moved between the plan and the write. */
154
+ export type PulumiStackOpCheck = "moved";
155
+
134
156
  /** How a call ended. Only `done` and `failed` ran anything. */
135
157
  export type PulumiStackOpOutcome<T> =
136
158
  | { status: "waiting"; digest: string; request: GatedRequest; command: string }
@@ -138,70 +160,42 @@ export type PulumiStackOpOutcome<T> =
138
160
  | { status: "refused"; digest: string; request: GatedRequest; by: string; reason: string; command: string }
139
161
  /** It ran already under an approval; a request runs once. */
140
162
  | { status: "spent"; digest: string; request: GatedRequest }
141
- | { status: "done"; digest: string; request: GatedRequest; result: T }
142
- | { status: "failed"; digest: string; request: GatedRequest; error: string };
143
-
144
- async function gatedApi(given?: GatedRequestApi): Promise<GatedRequestApi> {
145
- if (given) return given;
146
- try {
147
- const mod = (await import("@intentius/chant/lifecycle/gated-request")) as Partial<GatedRequestApi>;
148
- if (mod.requestGate && mod.spendGatedRequest && mod.finishGatedRequest && mod.readGatedRequests) return mod as GatedRequestApi;
149
- } catch {
150
- // Fall through to the refusal.
163
+ | { status: "done"; digest: string; request: GatedRequest; result: T; approvedBy?: string; recorded?: boolean }
164
+ | { status: "failed"; digest: string; request: GatedRequest; error: string; check?: PulumiStackOpCheck; recorded?: boolean };
165
+
166
+ /** Why an operation was refused without acting (#4808). `held` was approved and stays unspent. */
167
+ export type PulumiStackOpRefusal = "live-run" | "held" | "lock-gone";
168
+
169
+ /** An operation core's checks refused before it acted: `code` says which, `runs` names the live runs. */
170
+ export class PulumiStackOpRefused extends Error {
171
+ readonly code: PulumiStackOpRefusal;
172
+ readonly runs: LiveRun[];
173
+ readonly digest?: string;
174
+ constructor(code: PulumiStackOpRefusal, message: string, extra: { runs?: LiveRun[]; digest?: string } = {}) {
175
+ super(`${code}: ${message}`);
176
+ this.name = "PulumiStackOpRefused";
177
+ this.code = code;
178
+ this.runs = extra.runs ?? [];
179
+ if (extra.digest) this.digest = extra.digest;
151
180
  }
152
- throw new Error("this chant has no gated requests (#4551), so a gated stack operation cannot be asked for; upgrade @intentius/chant");
153
181
  }
154
182
 
155
- const sameFields = (a: Record<string, string>, b: Record<string, string>): boolean =>
156
- Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([k, v]) => b[k] === v);
157
-
158
- /**
159
- * Ask for the request, and run `act` once it is approved: the shared walk of
160
- * every operation. `precheck` runs after the approval and before the request
161
- * is spent, so a refusal there leaves the approval unspent.
162
- */
163
- async function askThenAct<T>(
164
- common: PulumiStackOpCommon,
165
- kind: PulumiStackOpKind,
166
- subject: string,
167
- fields: Record<string, string>,
168
- description: string,
169
- act: () => Promise<{ result: T; detail: Record<string, string | number | boolean>; failed?: string }>,
170
- precheck?: () => Promise<void>,
171
- options: { reuseApplied?: boolean } = {},
172
- ): Promise<PulumiStackOpOutcome<T>> {
173
- const api = await gatedApi(common.gated);
174
- const op = common.op ?? PULUMI_STACK_OPS_OP;
175
- const cwd = common.ledgerCwd ?? process.cwd();
176
- // With reuseApplied (#4654), a request with these fields that applied already is asked again as itself, so it answers `spent`.
177
- const standing = (await api.readGatedRequests(op, { cwd }).catch(() => []))
178
- .filter((r) => (options.reuseApplied || !r.applied) && r.request.kind === kind && r.request.subject === subject && r.request.by === common.by && sameFields(r.request.fields, fields))
179
- .at(-1);
180
- const request: GatedRequest = { kind, subject, by: common.by, at: standing?.request.at ?? common.now ?? new Date().toISOString(), fields };
181
- const asked: RequestGateResult = await api.requestGate({
182
- op,
183
- request,
183
+ /** The gated-request settings core's walks take, from the common options. */
184
+ function gatedSettings(common: PulumiStackOpCommon) {
185
+ return {
184
186
  rules: common.rules,
185
- description,
186
- cwd,
187
+ ...(common.ledgerCwd ? { cwd: common.ledgerCwd } : {}),
187
188
  ...(common.expiry ? { expiry: common.expiry } : {}),
189
+ ...(common.base ? { base: common.base } : {}),
188
190
  ...(common.now ? { now: common.now } : {}),
189
- });
190
- if (asked.status === "waiting") return { status: "waiting", digest: asked.digest, request: asked.request, command: asked.command };
191
- if (asked.status === "refused") return { status: "refused", digest: asked.digest, request: asked.request, by: asked.by, reason: asked.reason, command: asked.command };
192
- if (asked.status === "spent") return { status: "spent", digest: asked.digest, request: asked.request };
191
+ ...(common.gated ? { ledger: common.gated } : {}),
192
+ };
193
+ }
193
194
 
194
- if (precheck) await precheck();
195
- const applied = await api.spendGatedRequest({ op, gate: subject, digest: asked.digest, approval: asked.approval, cwd, ...(common.now ? { now: common.now } : {}) });
196
- try {
197
- const { result, detail, failed } = await act();
198
- await api.finishGatedRequest({ op, gate: subject, digest: asked.digest, applied: applied.timestamp, result: failed ? "failed" : "applied", detail: failed ? { ...detail, error: failed } : detail, cwd });
199
- return failed ? { status: "failed", digest: asked.digest, request: asked.request, error: failed } : { status: "done", digest: asked.digest, request: asked.request, result };
200
- } catch (err) {
201
- const error = err instanceof Error ? err.message : String(err);
202
- await api.finishGatedRequest({ op, gate: subject, digest: asked.digest, applied: applied.timestamp, result: "failed", detail: { error: error.slice(0, 2000) }, cwd }).catch(() => undefined);
203
- return { status: "failed", digest: asked.digest, request: asked.request, error };
204
- }
195
+ /** The request core asked under `digest`, read back from the ledger, since core's outcomes name only its digest; `fallback` when the ledger has none. */
196
+ async function askedRequest(common: PulumiStackOpCommon, digest: string, fallback: Omit<GatedRequest, "at">): Promise<GatedRequest> {
197
+ const read = digest ? await (common.gated ?? chantGatedLedger).readGatedRequests(common.op ?? PULUMI_STACK_OPS_OP, common.ledgerCwd ? { cwd: common.ledgerCwd } : undefined).catch(() => []) : [];
198
+ return read.find((g) => g.digest === digest)?.request ?? { ...fallback, at: "" };
205
199
  }
206
200
 
207
201
  function stackDirOf(dir: string, cwd?: string): string {
@@ -217,22 +211,107 @@ function why(err: unknown, binary: string): string {
217
211
  return f.missingBinary ? `the ${binary} binary was not found on PATH` : (f.stderr?.trim() || f.message).split("\n").slice(-3).join("\n");
218
212
  }
219
213
 
220
- // ── export ───────────────────────────────────────────────────────────────
214
+ const sha256 = (text: string): string => `sha256:${createHash("sha256").update(text).digest("hex")}`;
215
+
216
+ /** Where a stack's state is, as messages and the record name it: the stack and its backend's URL, never a credential. */
217
+ function stackLocation(dir: string, stack: string, env: Record<string, string | undefined>): string {
218
+ const backend = pulumiStackBackend(dir, { env });
219
+ return `stack ${stack}${backend ? ` at ${backend.url}` : ""}`;
220
+ }
221
221
 
222
- /** The CI variables that mark a job, where an export would become an artifact. */
223
- export const CI_MARKERS = ["CI", "GITHUB_ACTIONS", "GITLAB_CI", "FORGEJO_ACTIONS", "BUILDKITE", "JENKINS_URL"];
224
-
225
- /** The git working tree `path` sits in, or undefined. */
226
- export function enclosingWorkTree(path: string): string | undefined {
227
- let dir = resolve(path);
228
- for (;;) {
229
- if (existsSync(join(dir, ".git"))) return dir;
230
- const up = dirname(dir);
231
- if (up === dir) return undefined;
232
- dir = up;
222
+ /** The stack's export now, under its engine's read form. */
223
+ async function exportNow(opts: { dir: string; stack: string; engine: PulumiMemberEngine; run?: PulumiRunner; plunge?: PulumiRunner }): Promise<string> {
224
+ const args = ["stack", "export", "--stack", opts.stack];
225
+ try {
226
+ const { stdout } = opts.engine === "plunge" ? await runAllowedPlunge(opts.plunge ?? defaultPlungeRunner, args, opts.dir) : await runAllowedPulumi(opts.run ?? defaultPulumiRunner, args, opts.dir);
227
+ return stdout;
228
+ } catch (err) {
229
+ throw new Error(`${opts.engine} ${args.join(" ")} failed: ${why(err, opts.engine)}`);
233
230
  }
234
231
  }
235
232
 
233
+ // ── export ───────────────────────────────────────────────────────────────
234
+
235
+ /** The CI variables that mark a job, where an export would become an artifact. Core's list (`@intentius/chant/state-export`). */
236
+ export { CI_MARKERS, enclosingWorkTree } from "@intentius/chant/state-export";
237
+
238
+ /** A version id that is an update's number, as `stack history` and `stack export --version` take it. */
239
+ const UPDATE_NUMBER = /^[1-9][0-9]*$/;
240
+
241
+ /**
242
+ * A stack's state read by version (#4808), core's `StateVersionSource` for
243
+ * `exportStateVersion`. On a backend that numbers its updates the version
244
+ * is the newest update's number (`stack history --json --page-size 1`), a
245
+ * version is held when it is between 1 and that number, and one is read
246
+ * with `stack export --version <n>`. A backend that numbers none (a file
247
+ * backend answers `0`, plunge keeps no history chant reads) has one version,
248
+ * the one it holds now, named by its export's `sha256:` digest; reading it
249
+ * exports again and refuses an export whose digest moved. `read` keeps the
250
+ * last export's size and resource count for the caller.
251
+ */
252
+ export function pulumiStackVersionSource(opts: { dir: string; stack: string; engine: PulumiMemberEngine; run?: PulumiRunner; plunge?: PulumiRunner; env?: Record<string, string | undefined> }): StateVersionSource & { read?: { bytes: number; resources: number } } {
253
+ const location = stackLocation(opts.dir, opts.stack, opts.env ?? process.env);
254
+ const newest = async (): Promise<number | undefined> => {
255
+ if (opts.engine === "plunge") return undefined;
256
+ let stdout: string;
257
+ try {
258
+ ({ stdout } = await runStackOpReadPulumi(opts.run ?? defaultPulumiRunner, pulumiStackHistoryArgs(opts.stack), opts.dir));
259
+ } catch {
260
+ // A history that cannot be read numbers nothing; the export by digest still stands.
261
+ return undefined;
262
+ }
263
+ try {
264
+ const doc = JSON.parse(stdout) as unknown;
265
+ const first = Array.isArray(doc) ? doc[0] : undefined;
266
+ const v = isObject(first) && typeof first.version === "number" ? first.version : 0;
267
+ return v > 0 ? v : undefined;
268
+ } catch {
269
+ return undefined;
270
+ }
271
+ };
272
+ const checked = (body: string, what: string): string => {
273
+ let resources: number;
274
+ try {
275
+ resources = pulumiExportResources(JSON.parse(body)).length;
276
+ } catch {
277
+ throw new StateExportError(`${what} printed no JSON`);
278
+ }
279
+ source.read = { bytes: Buffer.byteLength(body), resources };
280
+ return body;
281
+ };
282
+ const source: StateVersionSource & { read?: { bytes: number; resources: number } } = {
283
+ location,
284
+ async current() {
285
+ const n = await newest();
286
+ if (n !== undefined) return { exists: true, versionId: String(n) };
287
+ return { exists: true, versionId: sha256(await exportNow(opts)) };
288
+ },
289
+ async hasVersion(id) {
290
+ if (UPDATE_NUMBER.test(id)) {
291
+ const n = await newest();
292
+ return n !== undefined && Number(id) <= n;
293
+ }
294
+ return id.startsWith("sha256:") && (await newest()) === undefined && sha256(await exportNow(opts)) === id;
295
+ },
296
+ async readVersion(id) {
297
+ if (UPDATE_NUMBER.test(id)) {
298
+ const args = pulumiStackExportVersionArgs(opts.stack, id);
299
+ let stdout: string;
300
+ try {
301
+ ({ stdout } = await runStackOpReadPulumi(opts.run ?? defaultPulumiRunner, args, opts.dir));
302
+ } catch (err) {
303
+ throw new StateExportError(`pulumi ${args.join(" ")} failed: ${why(err, "pulumi")}`);
304
+ }
305
+ return checked(stdout, `pulumi ${args.join(" ")}`);
306
+ }
307
+ const body = await exportNow(opts);
308
+ if (sha256(body) !== id) throw new StateExportError(`${location} changed since the request: its export is no longer ${id}, so nothing was written; ask again for the state it holds now`);
309
+ return checked(body, `${opts.engine} stack export --stack ${opts.stack}`);
310
+ },
311
+ };
312
+ return source;
313
+ }
314
+
236
315
  export interface PulumiStackExportOptions extends PulumiStackOpCommon {
237
316
  /** The stack's directory, where `Pulumi.yaml` is. */
238
317
  dir: string;
@@ -241,75 +320,109 @@ export interface PulumiStackExportOptions extends PulumiStackOpCommon {
241
320
  engine?: PulumiMemberEngine;
242
321
  /** Where the export is written on the requester's machine: outside every git working tree, and not there yet. */
243
322
  out: string;
323
+ /** The version to export (#4808): an update's number on a backend that numbers them, else the `sha256:` digest of the export now. Default the version the stack holds now. */
324
+ version?: string;
244
325
  }
245
326
 
246
327
  export interface PulumiStackExportResult {
247
328
  file: string;
329
+ /** The hex SHA-256 of the bytes written. */
248
330
  sha256: string;
249
331
  bytes: number;
250
332
  resources: number;
333
+ /** The version exported (#4808). */
334
+ version: string;
251
335
  }
252
336
 
253
337
  /**
254
- * A stack's export, delivered to the requester's machine after a second
255
- * identity approves it. Refused in CI and for a destination inside a git
256
- * working tree, before anything is asked.
338
+ * A stack's export, one version of it, delivered to the requester's machine
339
+ * after a second identity approves it: core's `exportStateVersion` over
340
+ * {@link pulumiStackVersionSource}. Refused in CI, for a destination inside
341
+ * a git working tree or over a file, and for a version the stack does not
342
+ * have, before anything is asked.
257
343
  */
258
344
  export async function gatedStackExport(opts: PulumiStackExportOptions): Promise<PulumiStackOpOutcome<PulumiStackExportResult>> {
259
345
  const env = opts.env ?? process.env;
260
- const marker = CI_MARKERS.find((k) => env[k] !== undefined && env[k] !== "" && env[k] !== "false");
261
- if (marker) throw new Error(`a stack export goes to the requester's machine only, and ${marker} is set, so this is a CI job whose files can become artifacts; ask for it from your own machine`);
262
- const out = resolve(opts.out);
263
- const tree = enclosingWorkTree(dirname(out));
264
- if (tree) throw new Error(`a stack export never goes into a repository, and ${out} is inside the git working tree ${tree}; name a path outside it`);
265
- if (existsSync(out)) throw new Error(`${out} already exists; a stack export never overwrites a file`);
266
346
  const dir = stackDirOf(opts.dir, opts.cwd);
267
347
  const engine = engineOf(dir, opts.engine, env);
268
- return askThenAct(
269
- opts,
270
- "stack-export",
271
- opts.stack,
272
- { stack: opts.stack, engine, deliver: "requester" },
273
- `export of stack ${opts.stack} to ${opts.by}'s machine`,
274
- async () => {
275
- const args = ["stack", "export", "--stack", opts.stack];
276
- let stdout: string;
277
- try {
278
- ({ stdout } = engine === "plunge" ? await runAllowedPlunge(opts.plunge ?? defaultPlungeRunner, args, dir) : await runAllowedPulumi(opts.run ?? defaultPulumiRunner, args, dir));
279
- } catch (err) {
280
- throw new Error(`${engine} ${args.join(" ")} failed: ${why(err, engine)}`);
281
- }
282
- let resources = 0;
283
- try {
284
- resources = pulumiExportResources(JSON.parse(stdout)).length;
285
- } catch {
286
- throw new Error(`${engine} ${args.join(" ")} printed no JSON`);
287
- }
288
- writeFileSync(out, stdout, { mode: 0o600, flag: "wx" });
289
- const sha256 = createHash("sha256").update(stdout).digest("hex");
290
- const bytes = Buffer.byteLength(stdout);
291
- return { result: { file: out, sha256, bytes, resources }, detail: { sha256, bytes, resources } };
292
- },
293
- );
348
+ const source = pulumiStackVersionSource({ dir, stack: opts.stack, engine, env, ...(opts.run ? { run: opts.run } : {}), ...(opts.plunge ? { plunge: opts.plunge } : {}) });
349
+ const out = resolve(opts.out);
350
+ const r = await exportStateVersion({
351
+ subject: opts.stack,
352
+ by: opts.by,
353
+ source,
354
+ out,
355
+ ...(opts.version ? { version: opts.version } : {}),
356
+ words: { op: opts.op ?? PULUMI_STACK_OPS_OP, kind: "stack-export" },
357
+ env,
358
+ ...gatedSettings(opts),
359
+ });
360
+ const request = await askedRequest(opts, r.digest, { kind: "stack-export", subject: opts.stack, by: opts.by, fields: { location: r.location, version_id: r.version } });
361
+ switch (r.status) {
362
+ case "waiting":
363
+ return { status: "waiting", digest: r.digest, request, command: r.command };
364
+ case "refused":
365
+ return { status: "refused", digest: r.digest, request, by: r.by, reason: r.reason, command: r.command };
366
+ case "spent":
367
+ return { status: "spent", digest: r.digest, request };
368
+ case "failed":
369
+ return { status: "failed", digest: r.digest, request, error: r.error.message, recorded: r.recorded };
370
+ case "written":
371
+ return {
372
+ status: "done",
373
+ digest: r.digest,
374
+ request,
375
+ approvedBy: r.approvedBy,
376
+ recorded: r.recorded,
377
+ result: { file: r.file, sha256: r.contentDigest.replace(/^sha256:/, ""), bytes: source.read?.bytes ?? 0, resources: source.read?.resources ?? 0, version: r.version },
378
+ };
379
+ }
294
380
  }
295
381
 
296
382
  // ── cancel ───────────────────────────────────────────────────────────────
297
383
 
384
+ /** The two lock directories of a DIY backend at `root` for a stack: project-scoped first, then the older layout. */
385
+ function diyLockDirs(root: string, project: string | undefined, stack: string): string[] {
386
+ return [...(project ? [join(root, ".pulumi", "locks", "organization", project, stack)] : []), join(root, ".pulumi", "locks", stack)];
387
+ }
388
+
298
389
  /**
299
390
  * The lock ids a DIY backend at `root` holds for a stack: the file names
300
391
  * under `.pulumi/locks/organization/<project>/<stack>/` (project-scoped
301
392
  * stacks) and `.pulumi/locks/<stack>/` (the older layout), without `.json`.
302
393
  */
303
394
  export function diyStackLockIds(root: string, project: string | undefined, stack: string): string[] {
304
- const dirs = [...(project ? [join(root, ".pulumi", "locks", "organization", project, stack)] : []), join(root, ".pulumi", "locks", stack)];
305
395
  const ids = new Set<string>();
306
- for (const d of dirs) {
396
+ for (const d of diyLockDirs(root, project, stack)) {
307
397
  if (!existsSync(d)) continue;
308
398
  for (const f of readdirSync(d)) if (f.endsWith(".json")) ids.add(f.slice(0, -".json".length));
309
399
  }
310
400
  return [...ids].sort();
311
401
  }
312
402
 
403
+ /**
404
+ * One DIY lock as core's `LockInfo` (#4808): its id, and from the lock
405
+ * file Pulumi writes (`pid`, `username`, `hostname`, `timestamp`) who took
406
+ * it and when, so the live-run check knows which runs could hold it.
407
+ * Undefined when the stack holds no lock of that id.
408
+ */
409
+ export function diyStackLock(root: string, project: string | undefined, stack: string, id: string): LockInfo | undefined {
410
+ for (const d of diyLockDirs(root, project, stack)) {
411
+ const file = join(d, `${id}.json`);
412
+ if (!existsSync(file)) continue;
413
+ let doc: unknown;
414
+ try {
415
+ doc = JSON.parse(readFileSync(file, "utf-8"));
416
+ } catch {
417
+ doc = undefined;
418
+ }
419
+ const s = (k: string): string | undefined => (isObject(doc) && typeof doc[k] === "string" && doc[k] !== "" ? (doc[k] as string) : undefined);
420
+ const who = s("username") && s("hostname") ? `${s("username")}@${s("hostname")}` : s("username");
421
+ return { ID: id, ...(who ? { Who: who } : {}), ...(s("timestamp") ? { Created: s("timestamp")! } : {}) };
422
+ }
423
+ return undefined;
424
+ }
425
+
313
426
  /** A stack's current lock, as {@link pulumiStackLockIds} reads it (#4615). */
314
427
  export interface PulumiStackLocks {
315
428
  /** Whether the backend was read: a `file://` backend chant can list. False for Pulumi Cloud, a bucket, or no backend found. */
@@ -320,6 +433,20 @@ export interface PulumiStackLocks {
320
433
  ids: string[];
321
434
  }
322
435
 
436
+ /** The DIY root and project of a stack on a `file://` backend, or undefined for any other backend. */
437
+ async function diyRootOf(dir: string, env: Record<string, string | undefined>, project?: string): Promise<{ root?: string; project?: string; backend?: string }> {
438
+ const backend = pulumiStackBackend(dir, { env });
439
+ const m = backend ? /^file:\/\/(.*)$/.exec(backend.url) : null;
440
+ if (!m) return backend ? { backend: backend.url } : {};
441
+ const root = isAbsolute(m[1]!) ? m[1]! : resolve(dir, m[1]!);
442
+ let name = project;
443
+ if (!name) {
444
+ const { pulumiYamlName } = await import("./lint/post-synth/member-read-helpers");
445
+ name = pulumiYamlName(dir);
446
+ }
447
+ return { root, backend: backend!.url, ...(name ? { project: name } : {}) };
448
+ }
449
+
323
450
  /**
324
451
  * The lock ids a stack holds now (#4615), for a caller that needs the id
325
452
  * `gatedStackCancel` asks for: the stack's backend from its directory (the
@@ -332,16 +459,9 @@ export async function pulumiStackLockIds(opts: { dir: string; stack: string; cwd
332
459
  const env = opts.env ?? process.env;
333
460
  const dir = stackDirOf(opts.dir, opts.cwd);
334
461
  if (engineOf(dir, opts.engine, env) === "plunge") return { checked: true, ids: [] };
335
- const backend = pulumiStackBackend(dir, { env });
336
- const m = backend ? /^file:\/\/(.*)$/.exec(backend.url) : null;
337
- if (!m) return { checked: false, ...(backend ? { backend: backend.url } : {}), ids: [] };
338
- const root = isAbsolute(m[1]!) ? m[1]! : resolve(dir, m[1]!);
339
- let project = opts.project;
340
- if (!project) {
341
- const { pulumiYamlName } = await import("./lint/post-synth/member-read-helpers");
342
- project = pulumiYamlName(dir);
343
- }
344
- return { checked: true, backend: backend!.url, ids: diyStackLockIds(root, project, opts.stack) };
462
+ const at = await diyRootOf(dir, env, opts.project);
463
+ if (!at.root) return { checked: false, ...(at.backend ? { backend: at.backend } : {}), ids: [] };
464
+ return { checked: true, ...(at.backend ? { backend: at.backend } : {}), ids: diyStackLockIds(at.root, at.project, opts.stack) };
345
465
  }
346
466
 
347
467
  export interface PulumiStackCancelOptions extends PulumiStackOpCommon {
@@ -355,14 +475,42 @@ export interface PulumiStackCancelOptions extends PulumiStackOpCommon {
355
475
  project?: string;
356
476
  /** Reads the stack's current lock id on a backend chant cannot read itself. */
357
477
  readLockId?: () => Promise<string | undefined>;
478
+ /**
479
+ * The repository's runs that have not finished (#4808), read before the
480
+ * request and again just before the spend: while one that began before
481
+ * the lock was taken is alive, nothing is released. A throw refuses the
482
+ * release. Default core's `forgeLiveRuns` of the forge {@link forge}
483
+ * names over the environment (`forgeTargetWith`).
484
+ */
485
+ liveRuns?: () => Promise<LiveRun[]>;
486
+ /** The forge whose runs are read when no `liveRuns` is given: `--forge`, `--repo` and the rest a product's flags give. */
487
+ forge?: ForgeTargetOptions & ForgeOverrides;
488
+ commit?: string;
358
489
  }
359
490
 
360
491
  export interface PulumiStackCancelResult {
361
492
  /** Whether the current lock was read and found to be the approved one before `cancel` ran. */
362
493
  lockChecked: boolean;
494
+ /** How many of the repository's runs were alive at the check, none of them able to hold the lock. */
495
+ liveRuns: number;
496
+ }
497
+
498
+ /** The runs of the forge `forge` names over `env`, as core reads them (#4808). */
499
+ function forgeRuns(env: Record<string, string | undefined>, forge: (ForgeTargetOptions & ForgeOverrides) | undefined): () => Promise<LiveRun[]> {
500
+ return async () => {
501
+ const { forgeTargetWith } = await import("@intentius/chant/forge-flags");
502
+ const t = forgeTargetWith(env, forge ?? {});
503
+ return forgeLiveRuns({ kind: t.kind, apiBase: t.apiBase, repo: t.repo, token: t.token, ...(t.tokenHeader ? { tokenHeader: t.tokenHeader } : {}) });
504
+ };
363
505
  }
364
506
 
365
- /** Release a stuck lock after an approval of its lock id. Refused for plunge, which keeps no stack lock. */
507
+ /**
508
+ * Release a stuck lock after an approval of its lock id, while no run that
509
+ * may hold it is alive: core's `releaseStateLock` over the stack's lock.
510
+ * Refused for plunge, which keeps no stack lock. On a backend chant cannot
511
+ * list and with no `readLockId`, the lock is the one the caller names and
512
+ * `lockChecked` is false.
513
+ */
366
514
  export async function gatedStackCancel(opts: PulumiStackCancelOptions): Promise<PulumiStackOpOutcome<PulumiStackCancelResult>> {
367
515
  const env = opts.env ?? process.env;
368
516
  const dir = stackDirOf(opts.dir, opts.cwd);
@@ -370,48 +518,79 @@ export async function gatedStackCancel(opts: PulumiStackCancelOptions): Promise<
370
518
  if (engine === "plunge") throw new Error(`stack ${opts.stack} runs on plunge, which keeps no stack lock, so there is nothing to cancel; a stuck plunge update is finished by running it again`);
371
519
  if (!opts.lockId || opts.lockId.startsWith("-")) throw new Error("a cancel names the lock id it releases");
372
520
 
373
- const readLock = async (): Promise<{ checked: boolean; ids: string[] }> => {
521
+ const at: { root?: string; project?: string; backend?: string } = opts.readLockId ? {} : await diyRootOf(dir, env, opts.project);
522
+ const checked = opts.readLockId !== undefined || at.root !== undefined;
523
+ const heldIds = async (): Promise<string[]> => {
374
524
  if (opts.readLockId) {
375
525
  const id = await opts.readLockId();
376
- return { checked: true, ids: id ? [id] : [] };
526
+ return id ? [id] : [];
377
527
  }
378
- const locks = await pulumiStackLockIds({ dir, stack: opts.stack, engine, env, ...(opts.project ? { project: opts.project } : {}) });
379
- return { checked: locks.checked, ids: locks.ids };
528
+ return at.root ? diyStackLockIds(at.root, at.project, opts.stack) : [];
380
529
  };
381
-
382
- let checked = false;
383
- return askThenAct(
384
- opts,
385
- "stack-cancel",
386
- opts.stack,
387
- { stack: opts.stack, lockId: opts.lockId },
388
- `release of lock ${opts.lockId} on stack ${opts.stack}`,
389
- async () => {
530
+ if (checked) {
531
+ const ids = await heldIds();
532
+ if (!ids.includes(opts.lockId)) {
533
+ throw new PulumiStackOpRefused(
534
+ "lock-gone",
535
+ `refusing to cancel stack ${opts.stack}: the approved lock ${opts.lockId} is ${ids.length === 0 ? "gone, and the stack holds no lock" : `not the one it holds now (${ids.join(", ")})`}; ask again for the lock it holds`,
536
+ );
537
+ }
538
+ }
539
+ const location = at.root ? `${at.backend} lock of stack ${opts.stack}` : stackLocation(dir, opts.stack, env);
540
+ let released = false;
541
+ const lock: StateLockSource = {
542
+ location,
543
+ async read() {
544
+ // A backend chant cannot list holds the lock the caller names until the release ran.
545
+ if (!checked) return released ? undefined : { ID: opts.lockId };
546
+ if (!(await heldIds()).includes(opts.lockId)) return undefined;
547
+ return (at.root ? diyStackLock(at.root, at.project, opts.stack, opts.lockId) : undefined) ?? { ID: opts.lockId };
548
+ },
549
+ async release() {
390
550
  const args = pulumiCancelArgs({ stack: opts.stack });
391
551
  try {
392
552
  await runGatedPulumi(opts.run ?? defaultPulumiRunner, args, dir);
393
553
  } catch (err) {
394
554
  throw new Error(`pulumi ${args.join(" ")} failed: ${why(err, "pulumi")}`);
395
555
  }
396
- return { result: { lockChecked: checked }, detail: { lockId: opts.lockId, lockChecked: checked } };
397
- },
398
- async () => {
399
- const lock = await readLock();
400
- checked = lock.checked;
401
- if (lock.checked && !lock.ids.includes(opts.lockId)) {
402
- throw new Error(
403
- `refusing to cancel stack ${opts.stack}: the approved lock ${opts.lockId} is ${lock.ids.length === 0 ? "gone, and the stack holds no lock" : `not the one it holds now (${lock.ids.join(", ")})`}; ask again for the lock it holds`,
404
- );
405
- }
556
+ released = true;
406
557
  },
407
- );
558
+ };
559
+ const r = await releaseStateLock({
560
+ subject: opts.stack,
561
+ by: opts.by,
562
+ lock,
563
+ liveRuns: opts.liveRuns ?? forgeRuns(env, opts.forge),
564
+ words: { op: opts.op ?? PULUMI_STACK_OPS_OP, kind: "stack-cancel" },
565
+ ...(opts.commit ? { commit: opts.commit } : {}),
566
+ ...gatedSettings(opts),
567
+ });
568
+ const request = await askedRequest(opts, "digest" in r ? r.digest : "", { kind: "stack-cancel", subject: opts.stack, by: opts.by, fields: { location, id: opts.lockId } });
569
+ switch (r.status) {
570
+ case "free":
571
+ throw new PulumiStackOpRefused("lock-gone", `refusing to cancel stack ${opts.stack}: the approved lock ${opts.lockId} is gone; ask again for the lock it holds`);
572
+ case "alive":
573
+ throw new PulumiStackOpRefused("live-run", `a run that began before ${opts.lockId} was taken is alive, so it may hold the lock, and nothing was asked: ${r.alive.map(describeRun).join("; ")}`, { runs: r.alive });
574
+ case "held":
575
+ throw new PulumiStackOpRefused("held", `${r.reason}; the approval stands unspent, so run the cancel again once that run finished`, { digest: r.digest });
576
+ case "waiting":
577
+ return { status: "waiting", digest: r.digest, request, command: r.command };
578
+ case "refused":
579
+ return { status: "refused", digest: r.digest, request, by: r.by, reason: r.reason, command: r.command };
580
+ case "spent":
581
+ return { status: "spent", digest: r.digest, request };
582
+ case "failed":
583
+ return { status: "failed", digest: r.digest, request, error: r.error.message, recorded: r.recorded };
584
+ case "released":
585
+ return { status: "done", digest: r.digest, request, approvedBy: r.approvedBy, recorded: r.recorded, result: { lockChecked: checked, liveRuns: r.liveRuns } };
586
+ }
408
587
  }
409
588
 
410
589
  // ── move ─────────────────────────────────────────────────────────────────
411
590
 
412
591
  /** One side of a move. */
413
592
  export interface PulumiMoveStack {
414
- /** The member's name, for messages. */
593
+ /** The member's name, for messages and the record. */
415
594
  member: string;
416
595
  /** The stack's directory, where `Pulumi.yaml` is. */
417
596
  dir: string;
@@ -426,6 +605,8 @@ export interface PulumiStackMoveOptions extends PulumiStackOpCommon {
426
605
  urns: string[];
427
606
  cwd?: string;
428
607
  engine?: PulumiMemberEngine;
608
+ runId?: string;
609
+ commit?: string;
429
610
  }
430
611
 
431
612
  export interface PulumiStackMoveResult {
@@ -482,13 +663,23 @@ function moveView(text: string | undefined): { status: string; refusals: { urn?:
482
663
  }
483
664
 
484
665
  /**
485
- * Move resources between two stacks after an approval: `pulumi state move`
486
- * on stock, plunge's marker move on plunge. Refused before anything is asked
487
- * for an empty or non-URN list or two engines.
666
+ * Move resources between two stacks after an approval: core's
667
+ * `runStateMigration` (#4808) with the two stacks as its roots. Each call
668
+ * plans: both previews, plunge's plan on plunge, and each stack's export
669
+ * digest as its state before. The request binds that plan. Approved, the
670
+ * engine reads each export again and refuses a state that moved, runs
671
+ * `pulumi state move` (plunge's marker move on plunge), and previews both
672
+ * stacks again. A Pulumi move's new states are the engine's to write, so
673
+ * each root's `after` digest binds what the move does to it (the stacks and
674
+ * the URNs), not bytes. Pulumi takes each stack's lock inside the move
675
+ * itself; chant takes none, and refuses while a `file://` backend shows
676
+ * either stack locked. Refused before anything is asked for an empty or
677
+ * non-URN list, two engines, or a plan that changes more than the move.
488
678
  */
489
679
  export async function gatedStackMove(opts: PulumiStackMoveOptions): Promise<PulumiStackOpOutcome<PulumiStackMoveResult>> {
490
680
  const env = opts.env ?? process.env;
491
681
  if (opts.urns.length === 0 || !opts.urns.every((u) => u.startsWith("urn:pulumi:"))) throw new Error("a move names the source URNs it moves, each urn:pulumi:...");
682
+ if (opts.source.member === opts.dest.member) throw new Error(`a move is between two members, and both sides are ${opts.source.member}`);
492
683
  const sourceDir = stackDirOf(opts.source.dir, opts.cwd);
493
684
  const destDir = stackDirOf(opts.dest.dir, opts.cwd);
494
685
  const engine = engineOf(sourceDir, opts.engine, env);
@@ -496,28 +687,61 @@ export async function gatedStackMove(opts: PulumiStackMoveOptions): Promise<Pulu
496
687
  if (engine !== destEngine) throw new Error(`${opts.source.member} runs on ${engine} and ${opts.dest.member} on ${destEngine}; a move needs both stacks on one engine`);
497
688
  const urns = [...new Set(opts.urns)].sort();
498
689
  const runners = { ...(opts.run ? { run: opts.run } : {}), ...(opts.plunge ? { plunge: opts.plunge } : {}), engine };
690
+ const sides = [
691
+ { ...opts.source, dir: sourceDir },
692
+ { ...opts.dest, dir: destDir },
693
+ ];
694
+ const side = (member: string) => sides.find((s) => s.member === member)!;
499
695
 
500
696
  const previews = async (): Promise<{ source: ChangeSetPart; dest: ChangeSetPart }> => {
501
- const [s, d] = await Promise.all([
502
- previewPulumiMemberRead({ member: opts.source.member, dir: sourceDir, stack: opts.source.stack, ...runners }),
503
- previewPulumiMemberRead({ member: opts.dest.member, dir: destDir, stack: opts.dest.stack, ...runners }),
504
- ]);
505
- for (const p of [s.part, d.part]) {
697
+ const [s, d] = await Promise.all(sides.map((x) => previewPulumiMemberRead({ member: x.member, dir: x.dir, stack: x.stack, ...runners })));
698
+ for (const p of [s!.part, d!.part]) {
506
699
  if (p.member.status === "failed") throw new Error(`the preview of ${p.member.member} failed: ${p.member.error ?? "no error printed"}`);
507
700
  }
508
- return { source: s.part, dest: d.part };
701
+ return { source: s!.part, dest: d!.part };
509
702
  };
510
703
 
511
- return askThenAct(
512
- opts,
513
- "stack-move",
514
- `move:${opts.source.stack}:${opts.dest.stack}`,
515
- { source: opts.source.stack, dest: opts.dest.stack, engine, urns: urns.join(",") },
516
- `move of ${urns.length} resource(s) from ${opts.source.stack} to ${opts.dest.stack}`,
517
- async () => {
518
- let outcome: unknown;
704
+ // The plan: previews that change only the moved resources, plunge's own plan, each state's digest now.
705
+ const before = await previews();
706
+ const left = moveLeftovers(urns, before.source, before.dest);
707
+ if (left.length > 0) throw new Error(`refusing to move: the previews change more than the moved resources, so the stacks would not preview no change after it: ${left.join("; ")}`);
708
+ if (engine === "plunge") {
709
+ const args = plungeMoveArgs({ source: opts.source.stack, dest: opts.dest.stack, urns });
710
+ let view: ReturnType<typeof moveView>;
711
+ try {
712
+ view = moveView((await runAllowedPlunge(opts.plunge ?? defaultPlungeRunner, args, sourceDir)).stdout);
713
+ } catch (err) {
714
+ view = moveView(pulumiRunFailure(err).stdout);
715
+ if (!view) throw new Error(`plunge ${args.join(" ")} failed: ${why(err, "plunge")}`);
716
+ }
717
+ if (!view || view.status !== "planned") {
718
+ const reasons = view?.refusals.map((r) => `${r.urn ?? ""} ${r.reason}`.trim()).join("; ");
719
+ throw new Error(`refusing to move: plunge's plan is ${view?.status ?? "missing"}${reasons ? `: ${reasons}` : ""}`);
720
+ }
721
+ }
722
+ const digestOf = async (member: string): Promise<string> => sha256(await exportNow({ ...side(member), ...runners }));
723
+ const move = { source: opts.source.stack, dest: opts.dest.stack, urns };
724
+ const proof: MigrationCheck = { changes: [], summary: `the previews change only the ${urns.length} moved resource(s)` };
725
+ const roots: MigrationRootPlan[] = [];
726
+ for (const s of sides) {
727
+ roots.push({ root: s.member, location: stackLocation(s.dir, s.stack, env), before: { digest: await digestOf(s.member) }, after: { digest: sha256(JSON.stringify({ root: s.member, move })) }, proof });
728
+ }
729
+
730
+ let outcome: unknown;
731
+ const migration: StateMigrationEngine = {
732
+ async lock() {
733
+ for (const s of sides) {
734
+ const locks = engine === "plunge" ? { checked: false, ids: [] } : await pulumiStackLockIds({ dir: s.dir, stack: s.stack.split("/").at(-1)!, engine, env });
735
+ if (locks.ids.length > 0) throw new Error(`${s.member} holds lock ${locks.ids.join(", ")}: an update is running on it, so nothing was moved`);
736
+ }
737
+ return async () => undefined;
738
+ },
739
+ async current(root) {
740
+ return { digest: await digestOf(root) };
741
+ },
742
+ async write() {
519
743
  if (engine === "plunge") {
520
- const args = plungeMoveArgs({ source: opts.source.stack, dest: opts.dest.stack, urns, yes: true });
744
+ const args = plungeMoveArgs({ ...move, yes: true });
521
745
  try {
522
746
  const { stdout } = await runGatedPlunge(opts.plunge ?? defaultPlungeRunner, args, sourceDir);
523
747
  outcome = moveView(stdout)?.doc;
@@ -529,44 +753,69 @@ export async function gatedStackMove(opts: PulumiStackMoveOptions): Promise<Pulu
529
753
  }
530
754
  throw new Error(`plunge ${args.join(" ")} failed: ${why(err, "plunge")}`);
531
755
  }
532
- } else {
533
- const args = pulumiStateMoveArgs({ source: opts.source.stack, dest: opts.dest.stack, urns });
534
- try {
535
- await runGatedPulumi(opts.run ?? defaultPulumiRunner, args, sourceDir);
536
- } catch (err) {
537
- throw new Error(`pulumi ${args.join(" ")} failed: ${why(err, "pulumi")}`);
538
- }
756
+ return;
539
757
  }
540
- // Both stacks must preview no change once the move is made.
541
- const after = await previews();
542
- const left = [...changing(after.source).map((e) => `${opts.source.member}: ${e.action} ${e.address}`), ...changing(after.dest).map((e) => `${opts.dest.member}: ${e.action} ${e.address}`)];
543
- const result: PulumiStackMoveResult = { engine, moved: urns, ...(outcome !== undefined ? { outcome } : {}) };
544
- return {
545
- result,
546
- detail: { moved: urns.length, engine, afterNoChange: left.length === 0 },
547
- ...(left.length > 0 ? { failed: `the move ran, and the stacks still preview changes: ${left.join("; ")}` } : {}),
548
- };
549
- },
550
- async () => {
551
- const before = await previews();
552
- const left = moveLeftovers(urns, before.source, before.dest);
553
- if (left.length > 0) throw new Error(`refusing to move: the previews change more than the moved resources, so the stacks would not preview no change after it: ${left.join("; ")}`);
554
- if (engine === "plunge") {
555
- const args = plungeMoveArgs({ source: opts.source.stack, dest: opts.dest.stack, urns });
556
- let view: ReturnType<typeof moveView>;
557
- try {
558
- view = moveView((await runAllowedPlunge(opts.plunge ?? defaultPlungeRunner, args, sourceDir)).stdout);
559
- } catch (err) {
560
- view = moveView(pulumiRunFailure(err).stdout);
561
- if (!view) throw new Error(`plunge ${args.join(" ")} failed: ${why(err, "plunge")}`);
562
- }
563
- if (!view || view.status !== "planned") {
564
- const reasons = view?.refusals.map((r) => `${r.urn ?? ""} ${r.reason}`.trim()).join("; ");
565
- throw new Error(`refusing to move: plunge's plan is ${view?.status ?? "missing"}${reasons ? `: ${reasons}` : ""}`);
566
- }
758
+ const args = pulumiStateMoveArgs(move);
759
+ try {
760
+ await runGatedPulumi(opts.run ?? defaultPulumiRunner, args, sourceDir);
761
+ } catch (err) {
762
+ throw new Error(`pulumi ${args.join(" ")} failed: ${why(err, "pulumi")}`);
567
763
  }
568
764
  },
569
- );
765
+ async verify(root) {
766
+ const s = side(root);
767
+ const { part } = await previewPulumiMemberRead({ member: s.member, dir: s.dir, stack: s.stack, ...runners });
768
+ if (part.member.status === "failed") return { changes: [`the preview failed: ${part.member.error ?? "no error printed"}`], summary: "preview failed" };
769
+ const changes = changing(part).map((e) => `${e.action} ${e.address}`);
770
+ return { changes, summary: changes.length === 0 ? "no change" : `${changes.length} change(s)` };
771
+ },
772
+ };
773
+
774
+ const subject = `move:${opts.source.stack}:${opts.dest.stack}`;
775
+ const fields = { source: opts.source.stack, dest: opts.dest.stack, engine, urns: urns.join(",") };
776
+ const r = await runStateMigration({
777
+ name: subject,
778
+ by: opts.by,
779
+ roots,
780
+ engine: migration,
781
+ words: { op: opts.op ?? PULUMI_STACK_OPS_OP, kind: "stack-move" },
782
+ fields,
783
+ detail: (res) => ({ urns: urns.length, engine, afterNoChange: res.status === "applied" }),
784
+ description: `move of ${urns.length} resource(s) from ${opts.source.stack} to ${opts.dest.stack}`,
785
+ ...(opts.runId ? { runId: opts.runId } : {}),
786
+ ...(opts.commit ? { commit: opts.commit } : {}),
787
+ ...gatedSettings(opts),
788
+ });
789
+ const request = await askedRequest(opts, "digest" in r ? r.digest : "", { kind: "stack-move", subject, by: opts.by, fields });
790
+ switch (r.status) {
791
+ case "proof-failed":
792
+ throw new Error(`refusing to move: ${r.failing.join(", ")} plan changes`);
793
+ case "waiting":
794
+ return { status: "waiting", digest: r.digest, request, command: r.command };
795
+ case "refused":
796
+ return { status: "refused", digest: r.digest, request, by: r.by, reason: r.reason, command: r.command };
797
+ case "spent":
798
+ return { status: "spent", digest: r.digest, request };
799
+ case "approval-moved":
800
+ // An approval of an earlier request for these stacks stands, but their state moved since it (#4806), so it
801
+ // doesn't count for this one, and this request waits for its own.
802
+ return { status: "waiting", digest: r.digest, request, command: r.command };
803
+ case "moved":
804
+ return {
805
+ status: "failed",
806
+ digest: r.digest,
807
+ request,
808
+ check: "moved",
809
+ recorded: r.recorded,
810
+ error: `the state of ${(r.result.moved ?? []).join(", ")} changed since the plan, so nothing was moved; the approval is spent, so ask again for the stacks as they are now`,
811
+ };
812
+ case "failed": {
813
+ const still = (r.result?.roots ?? []).flatMap((x) => (x.verify?.changes ?? []).map((c) => `${x.root}: ${c}`));
814
+ return { status: "failed", digest: r.digest, request, recorded: r.recorded, error: still.length > 0 ? `the move ran, and the stacks still preview changes: ${still.join("; ")}` : r.error };
815
+ }
816
+ case "applied":
817
+ return { status: "done", digest: r.digest, request, approvedBy: r.approvedBy, recorded: r.recorded, result: { engine, moved: urns, ...(outcome !== undefined ? { outcome } : {}) } };
818
+ }
570
819
  }
571
820
 
572
821
  // ── action ───────────────────────────────────────────────────────────────
@@ -708,30 +957,44 @@ export async function gatedStackAction(opts: PulumiStackActionOptions): Promise<
708
957
  const digest = pulumiPreviewDigest(preview, { changedOnly: true });
709
958
  const subject = stackActionSubject(opts.stack, opts.name ?? opts.urn);
710
959
  const fields: Record<string, string> = { stack: opts.stack, urn: opts.urn, engine, preview: digest, ...(opts.name ? { name: opts.name } : {}) };
711
- return askThenAct(
712
- opts,
713
- "stack-action",
714
- subject,
715
- fields,
716
- `action ${opts.name ?? opts.urn} on stack ${opts.stack}: replace ${opts.urn}, requested by ${opts.by}`,
717
- async () => {
960
+ // core's gatedOp (#4808); reuseApplied makes a retried call with the same request answer `spent`.
961
+ const r = await gatedOp<{ result: PulumiStackActionResult; error?: string }>(
962
+ {
963
+ op: opts.op ?? PULUMI_STACK_OPS_OP,
964
+ request: { kind: "stack-action", subject, by: opts.by, fields },
965
+ description: `action ${opts.name ?? opts.urn} on stack ${opts.stack}: replace ${opts.urn}, requested by ${opts.by}`,
966
+ ...(opts.anew ? {} : { reuseApplied: true }),
967
+ ...gatedSettings(opts),
968
+ },
969
+ (async () => {
718
970
  const args = pulumiActionUpArgs(target);
719
971
  try {
720
972
  const done = engine === "plunge" ? await runGatedPlunge(opts.plunge ?? defaultPlungeRunner, args, dir) : await runGatedPulumi(opts.run ?? defaultPulumiRunner, args, dir);
721
973
  const tail = lastLines(done.stdout, 10);
722
- return { result: { urn: opts.urn, engine, preview: digest, exit: 0, tail }, detail: { result: "ok", exit: 0, tail: tail.slice(-400), urn: opts.urn } };
974
+ return { output: { result: { urn: opts.urn, engine, preview: digest, exit: 0, tail } }, detail: { result: "ok", exit: 0, tail: tail.slice(-400), urn: opts.urn } };
723
975
  } catch (err) {
724
976
  const f = pulumiRunFailure(err);
725
977
  const exit = f.exitCode ?? 1;
726
978
  const tail = lastLines(`${f.stdout ?? ""}\n${f.stderr ?? ""}`, 10);
727
- return {
728
- result: { urn: opts.urn, engine, preview: digest, exit, tail },
729
- detail: { result: "failed", exit, tail: tail.slice(-400), urn: opts.urn },
730
- failed: `${engine} ${args.join(" ")} failed: ${why(err, engine)}`,
731
- };
979
+ const error = `${engine} ${args.join(" ")} failed: ${why(err, engine)}`;
980
+ return { output: { result: { urn: opts.urn, engine, preview: digest, exit, tail }, error }, detail: { result: "failed", exit, tail: tail.slice(-400), urn: opts.urn, error: error.slice(0, 400) }, failed: true };
732
981
  }
733
- },
734
- undefined,
735
- { reuseApplied: !opts.anew },
982
+ }) as GatedOpAct<{ result: PulumiStackActionResult; error?: string }>,
736
983
  );
984
+ switch (r.status) {
985
+ case "waiting":
986
+ return { status: "waiting", digest: r.digest, request: r.request, command: r.command };
987
+ case "refused":
988
+ return { status: "refused", digest: r.digest, request: r.request, by: r.by, reason: r.reason, command: r.command };
989
+ case "spent":
990
+ return { status: "spent", digest: r.digest, request: r.request };
991
+ case "held":
992
+ return { status: "failed", digest: r.digest, request: r.request, error: r.reason, recorded: false };
993
+ case "failed":
994
+ return { status: "failed", digest: r.digest, request: r.request, error: r.error.message, recorded: r.recorded };
995
+ case "done":
996
+ return r.output.error !== undefined
997
+ ? { status: "failed", digest: r.digest, request: r.request, error: r.output.error, recorded: r.recorded }
998
+ : { status: "done", digest: r.digest, request: r.request, result: r.output.result, approvedBy: r.approvedBy, recorded: r.recorded };
999
+ }
737
1000
  }