@intentius/chant 0.124.58 → 0.124.59

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 (70) hide show
  1. package/dist/ci-product.d.ts.map +1 -1
  2. package/dist/ci-product.js +1 -2
  3. package/dist/cli/handlers/lifecycle-drift.d.ts +2 -1
  4. package/dist/cli/handlers/lifecycle-drift.d.ts.map +1 -1
  5. package/dist/cli/handlers/lifecycle-drift.js +4 -2
  6. package/dist/cli/handlers/lock.d.ts.map +1 -1
  7. package/dist/cli/handlers/lock.js +45 -2
  8. package/dist/cli/main.d.ts.map +1 -1
  9. package/dist/cli/main.js +5 -1
  10. package/dist/cli/mcp/product-tools.d.ts.map +1 -1
  11. package/dist/cli/mcp/product-tools.js +1 -2
  12. package/dist/cli/parse-args.d.ts.map +1 -1
  13. package/dist/cli/parse-args.js +18 -0
  14. package/dist/cli/registry.d.ts +6 -0
  15. package/dist/cli/registry.d.ts.map +1 -1
  16. package/dist/drift-record.d.ts +5 -0
  17. package/dist/drift-record.d.ts.map +1 -1
  18. package/dist/e2e-harness/index.d.ts.map +1 -1
  19. package/dist/e2e-harness/index.js +1 -2
  20. package/dist/lifecycle/lock-beat.d.ts +27 -0
  21. package/dist/lifecycle/lock-beat.d.ts.map +1 -0
  22. package/dist/lifecycle/lock-beat.js +84 -0
  23. package/dist/lifecycle/resource-lock.d.ts +54 -1
  24. package/dist/lifecycle/resource-lock.d.ts.map +1 -1
  25. package/dist/lifecycle/resource-lock.js +128 -7
  26. package/dist/op/activities/activity-contracts.d.ts +4 -4
  27. package/dist/op/index.d.ts +1 -1
  28. package/dist/op/index.d.ts.map +1 -1
  29. package/dist/op/index.js +1 -1
  30. package/dist/op/op-waves-notify.d.ts.map +1 -1
  31. package/dist/op/op-waves-notify.js +11 -0
  32. package/dist/op/op-waves-run.d.ts +28 -1
  33. package/dist/op/op-waves-run.d.ts.map +1 -1
  34. package/dist/op/op-waves-run.js +92 -7
  35. package/dist/op/op-waves.d.ts +12 -1
  36. package/dist/op/op-waves.d.ts.map +1 -1
  37. package/dist/op/op-waves.js +9 -2
  38. package/dist/release-floors.d.ts +1 -1
  39. package/dist/release-floors.js +1 -1
  40. package/dist/template-request/template-request.d.ts.map +1 -1
  41. package/dist/template-request/template-request.js +1 -2
  42. package/dist/wave-runtime.mjs +298 -298
  43. package/dist/workspace/drift-cli.d.ts +13 -1
  44. package/dist/workspace/drift-cli.d.ts.map +1 -1
  45. package/dist/workspace/drift-cli.js +19 -3
  46. package/package.json +1 -1
  47. package/src/ci-product.ts +1 -2
  48. package/src/cli/handlers/lifecycle-drift.test.ts +52 -0
  49. package/src/cli/handlers/lifecycle-drift.ts +4 -2
  50. package/src/cli/handlers/lock.ts +41 -2
  51. package/src/cli/main.ts +5 -1
  52. package/src/cli/mcp/product-tools.test.ts +1 -2
  53. package/src/cli/mcp/product-tools.ts +1 -2
  54. package/src/cli/parse-args.ts +12 -0
  55. package/src/cli/registry.ts +6 -0
  56. package/src/drift-record.ts +5 -0
  57. package/src/e2e-harness/index.ts +1 -2
  58. package/src/lifecycle/lock-beat.ts +99 -0
  59. package/src/lifecycle/resource-lock-liveness.test.ts +289 -0
  60. package/src/lifecycle/resource-lock.ts +143 -8
  61. package/src/op/index.ts +1 -0
  62. package/src/op/op-waves-notify.ts +11 -0
  63. package/src/op/op-waves-preview.test.ts +167 -0
  64. package/src/op/op-waves-run.ts +116 -8
  65. package/src/op/op-waves.ts +20 -3
  66. package/src/release-floors.ts +1 -1
  67. package/src/template-request/template-request.test.ts +1 -2
  68. package/src/template-request/template-request.ts +1 -2
  69. package/src/workspace/drift-cli.test.ts +35 -1
  70. package/src/workspace/drift-cli.ts +21 -3
@@ -0,0 +1,167 @@
1
+ import { afterEach, describe, expect, test } from "vitest";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { assertOpWavesSpec, opWavesPostsApprovalStatus, type OpWavesSpec } from "./op-waves";
6
+ import { OP_WAVES_PREVIEW_FLOOR, readOpWavePolicy, runOpWave, type OpWaveExec, type OpWaveShowAtBase } from "./op-waves-run";
7
+ import { memoryGateLedgerPort } from "./gate";
8
+ import { NEXT_RELEASE } from "../release-floors";
9
+ import { waveSetDigest } from "../gated-waves";
10
+ import type { HeadPlans, MergedReview, ReviewSource } from "./gate-review";
11
+
12
+ const spec: OpWavesSpec = {
13
+ name: "records",
14
+ op: "dns",
15
+ plan: ["tool", "plan", "{target}", "--out", "{plan}"],
16
+ apply: ["tool", "apply", "{target}", "--plan", "{plan}"],
17
+ approvals: { preview: true },
18
+ waves: [{ name: "dev", runs: [{ target: "zone" }], gate: "on-destructive" }],
19
+ };
20
+
21
+ const digest = (n: string) => `sha256:${n.repeat(64)}`;
22
+ const setOf = (n: string) => waveSetDigest([{ member: "zone", planDigest: digest(n) }]);
23
+ const merged: MergedReview = { pr: 7, head: "h".repeat(40), author: "github:dev", approvers: ["github:rev"], refused: [] };
24
+ const reviews = (m: MergedReview | null): ReviewSource => ({ kind: "github", mergedReview: async () => m });
25
+ const recorded = (wave: number, set: string | undefined): ((name: string, head: string) => Promise<HeadPlans | null>) => async (name, head) =>
26
+ set === undefined ? null : { version: 1, name, head, timestamp: "2026-10-30T00:00:00Z", waves: [{ wave, name: "dev", digest: set }] };
27
+
28
+ const dirs: string[] = [];
29
+ afterEach(() => {
30
+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
31
+ });
32
+
33
+ function harness(plan: { planDigest: string; destructive?: boolean }, atBase: OpWavesSpec = spec) {
34
+ const cwd = mkdtempSync(join(tmpdir(), "op-waves-preview-"));
35
+ dirs.push(cwd);
36
+ const calls: string[] = [];
37
+ const exec: OpWaveExec = (argv, dir) => {
38
+ calls.push(argv.join(" "));
39
+ if (argv[1] === "plan") writeFileSync(join(dir, argv[4]!), JSON.stringify(plan));
40
+ return 0;
41
+ };
42
+ const show: OpWaveShowAtBase = () => ({ sha: "b".repeat(40), text: JSON.stringify(atBase) });
43
+ return { cwd, exec, show, applied: () => calls.some((c) => c.startsWith("tool apply")) };
44
+ }
45
+
46
+ const run = (h: ReturnType<typeof harness>, extra: Partial<Parameters<typeof runOpWave>[0]> = {}) =>
47
+ runOpWave({ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, exec: h.exec, show: h.show, gates: memoryGateLedgerPort(), head: "m".repeat(40), now: "2026-10-30T01:00:00Z", log: () => {}, ...extra });
48
+
49
+ describe("a wave applies the plans its pull request previewed (approvals.preview)", () => {
50
+ test("a record that moved between the preview and the merge returns 4 and applies nothing", async () => {
51
+ const h = harness({ planDigest: digest("b") });
52
+ const logs: string[] = [];
53
+ const result = await run(h, { reviews: reviews(merged), headPlans: recorded(1, setOf("a")), log: (l) => logs.push(l) });
54
+ expect(result.exitCode).toBe(4);
55
+ expect(result.moved).toEqual(["zone"]);
56
+ expect(result.decision).toMatchObject({ status: "refused", refused: { reason: "moved", runs: ["zone"] }, preview: { status: "moved", pr: 7, recorded: setOf("a") } });
57
+ expect(result.decision?.refused?.message).toMatch(/the head hhhhhhhhhhhh planned/);
58
+ expect(h.applied()).toBe(false);
59
+ expect(logs.some((l) => /plans moved since #7 previewed them/.test(l))).toBe(true);
60
+ });
61
+
62
+ test("an unchanged record applies, though the gate asks for no approval", async () => {
63
+ const h = harness({ planDigest: digest("a") });
64
+ const result = await run(h, { reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
65
+ expect(result).toMatchObject({ exitCode: 0, applied: ["zone"], decision: { status: "not-required", preview: { status: "matched", pr: 7 } } });
66
+ expect(h.applied()).toBe(true);
67
+ });
68
+
69
+ test("a destructive change still waits for its approval when the preview matches", async () => {
70
+ const h = harness({ planDigest: digest("a"), destructive: true });
71
+ const gates = memoryGateLedgerPort();
72
+ const result = await run(h, { gates, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
73
+ expect(result.exitCode).toBe(3);
74
+ expect(result.decision).toMatchObject({ status: "waiting", preview: { status: "matched" } });
75
+ expect(h.applied()).toBe(false);
76
+ const approved = memoryGateLedgerPort({
77
+ resolutions: [{ version: 1, op: "records", gate: "records-wave-1", resolvedBy: "alice", timestamp: "2026-10-30T00:30:00Z", planDigest: setOf("a") }],
78
+ });
79
+ const again = await run(h, { gates: approved, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
80
+ expect(again).toMatchObject({ exitCode: 0, applied: ["zone"], decision: { status: "approved", approvedBy: "alice" } });
81
+ });
82
+
83
+ test("with no approval required, the wave compares with the digest of the preview it was shown", async () => {
84
+ // gate: never needs nothing, yet the preview still binds the plans.
85
+ const never: OpWavesSpec = { ...spec, waves: [{ ...spec.waves[0]!, gate: "never" }] };
86
+ const moved = harness({ planDigest: digest("c") }, never);
87
+ const refused = await run(moved, { spec: never, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
88
+ expect(refused).toMatchObject({ exitCode: 4, decision: { policy: "never", preview: { status: "moved" } } });
89
+ expect(moved.applied()).toBe(false);
90
+ const same = harness({ planDigest: digest("a") }, never);
91
+ expect(await run(same, { spec: never, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) })).toMatchObject({ exitCode: 0, applied: ["zone"] });
92
+ });
93
+
94
+ test("plans nobody previewed refuse too: no merged pull request, or no record for its head", async () => {
95
+ const direct = harness({ planDigest: digest("a") });
96
+ const none = await run(direct, { reviews: reviews(null), headPlans: recorded(1, setOf("a")) });
97
+ expect(none).toMatchObject({ exitCode: 4, decision: { preview: { status: "unrecorded" } } });
98
+ expect(none.decision?.refused?.message).toMatch(/no merged pull request produced/);
99
+ const unrecorded = harness({ planDigest: digest("a") });
100
+ const missing = await run(unrecorded, { reviews: reviews(merged), headPlans: recorded(1, undefined) });
101
+ expect(missing).toMatchObject({ exitCode: 4, decision: { preview: { status: "unrecorded" } } });
102
+ expect(missing.decision?.refused?.message).toMatch(/--record-plans/);
103
+ expect(direct.applied() || unrecorded.applied()).toBe(false);
104
+ });
105
+
106
+ test("an approval of the plans made now lets a moved wave apply, and the refusal names the command", async () => {
107
+ const h = harness({ planDigest: digest("b") });
108
+ const refused = await run(h, { reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
109
+ expect(refused.decision?.refused?.message).toContain(`chant approve records records-wave-1 ${setOf("b")}`.split(" ").slice(0, 3).join(" "));
110
+ expect(refused.decision?.approve).toContain(setOf("b"));
111
+ const approved = memoryGateLedgerPort({
112
+ resolutions: [{ version: 1, op: "records", gate: "records-wave-1", resolvedBy: "alice", timestamp: "2026-10-30T00:45:00Z", planDigest: setOf("b") }],
113
+ });
114
+ const result = await run(h, { gates: approved, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
115
+ expect(result).toMatchObject({ exitCode: 0, applied: ["zone"], decision: { status: "approved", approvedBy: "alice", preview: { status: "moved", approvedAnyway: true } } });
116
+ });
117
+
118
+ test("a forge that cannot be read fails the wave and applies nothing", async () => {
119
+ const h = harness({ planDigest: digest("a") });
120
+ const broken: ReviewSource = { kind: "github", mergedReview: async () => { throw new Error("403"); } };
121
+ const result = await run(h, { reviews: broken, headPlans: recorded(1, setOf("a")) });
122
+ expect(result.exitCode).toBe(1);
123
+ expect(h.applied()).toBe(false);
124
+ });
125
+
126
+ test("a change cannot switch it off: the setting is read at base", async () => {
127
+ const h = harness({ planDigest: digest("b") });
128
+ const off: OpWavesSpec = { ...spec, approvals: { preview: false } };
129
+ const result = await run(h, { spec: off, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
130
+ expect(result.exitCode).toBe(4);
131
+ const without = harness({ planDigest: digest("b") }, { ...spec, approvals: {} });
132
+ expect(await run(without, { reviews: reviews(merged), headPlans: recorded(1, setOf("a")) })).toMatchObject({ exitCode: 0, applied: ["zone"] });
133
+ });
134
+
135
+ test("a spec without it keeps the behaviour it had", async () => {
136
+ const plain: OpWavesSpec = { ...spec, approvals: {} };
137
+ const h = harness({ planDigest: digest("b") }, plain);
138
+ const result = await run(h, { spec: plain });
139
+ expect(result).toMatchObject({ exitCode: 0, applied: ["zone"], decision: { status: "not-required" } });
140
+ expect(result.decision?.preview).toBeUndefined();
141
+ });
142
+
143
+ test("a share job ends on a moved decision with 4", async () => {
144
+ const wide: OpWavesSpec = { ...spec, waves: [{ name: "dev", runs: [{ target: "zone" }, { target: "zone2" }], gate: "on-destructive", shares: 2 }] };
145
+ const h = harness({ planDigest: digest("b") }, wide);
146
+ const decided = await run(h, { spec: wide, decide: true, reviews: reviews(merged), headPlans: recorded(1, waveSetDigest([{ member: "zone", planDigest: digest("a") }, { member: "zone2", planDigest: digest("a") }])) });
147
+ expect(decided.exitCode).toBe(4);
148
+ const share = await run(h, { spec: wide, share: 1 });
149
+ expect(share.exitCode).toBe(4);
150
+ expect(h.applied()).toBe(false);
151
+ });
152
+ });
153
+
154
+ describe("the setting", () => {
155
+ test("its floor is the next release", () => {
156
+ expect(OP_WAVES_PREVIEW_FLOOR).toBe(NEXT_RELEASE);
157
+ });
158
+
159
+ test("is a boolean, is read at base, and makes the head record its plans", () => {
160
+ expect(() => assertOpWavesSpec(spec)).not.toThrow();
161
+ expect(() => assertOpWavesSpec({ ...spec, approvals: { preview: "yes" } } as unknown as OpWavesSpec)).toThrow(/approvals.preview must be true or false/);
162
+ expect(readOpWavePolicy("waves.json", "dev", "HEAD", "/", () => ({ sha: "b".repeat(40), text: JSON.stringify(spec) })).preview).toBe(true);
163
+ expect(readOpWavePolicy("waves.json", "dev", "HEAD", "/", () => ({ sha: "b".repeat(40), text: JSON.stringify({ ...spec, approvals: {} }) })).preview).toBeUndefined();
164
+ expect(opWavesPostsApprovalStatus(spec)).toBe(true);
165
+ expect(opWavesPostsApprovalStatus({ ...spec, approvals: {} })).toBe(false);
166
+ });
167
+ });
@@ -82,6 +82,7 @@ import type { GatePointAsker } from "../point-decision";
82
82
  import type { WaitingPoint } from "./steward-points";
83
83
  import { isApprovalSpent, type AppliedGateRecord, type FinishedGateRecord } from "../lifecycle/gate-applied";
84
84
  import { samePlanDigest } from "../lifecycle/plan-digest";
85
+ import { NEXT_RELEASE } from "../release-floors";
85
86
  import { isLifecycleLocalNote } from "../lifecycle/local-note";
86
87
  import type { HeadPlans, MergedReview, ReviewSource } from "./gate-review";
87
88
  import type { TrustPolicy } from "../workspace/trust/policy";
@@ -357,6 +358,8 @@ export interface OpWaveDecision {
357
358
  waitingSince?: string;
358
359
  /** While waiting: the newest approval of this gate for another digest, which the plans moved away from. */
359
360
  mismatch?: GateDigestMismatch;
361
+ /** Under `approvals.preview` at base: what the merged pull request's head recorded for this wave, and how the plans now compare with it. */
362
+ preview?: OpWavePreview;
360
363
  /**
361
364
  * Why a `refused` wave applies nothing: the runs the policy denied, and
362
365
  * whether an override stands for an earlier plan or other rules (#3821,
@@ -364,7 +367,7 @@ export interface OpWaveDecision {
364
367
  * it does not pass on (#3836, exit 8), with every run and the `message`.
365
368
  */
366
369
  refused?: {
367
- reason: "policy" | "override-moved" | "point";
370
+ reason: "policy" | "override-moved" | "point" | "moved";
368
371
  runs: string[];
369
372
  message?: string;
370
373
  /** Where the plans file said its overriders come from (#3848), when it did. */
@@ -391,6 +394,28 @@ export interface OpWaveDecision {
391
394
  ciPolicySource?: ResolvedGatePolicySource;
392
395
  }
393
396
 
397
+ /**
398
+ * The plans the merged pull request previewed for a wave, against the plans
399
+ * the wave made now. `matched`: the same set digest, so the wave applies
400
+ * what the pull request showed. `moved`: the head recorded another digest,
401
+ * so a record moved since. `unrecorded`: nothing was recorded to compare
402
+ * with (no merged pull request, no record for its head, or none for this
403
+ * wave).
404
+ */
405
+ export interface OpWavePreview {
406
+ status: "matched" | "moved" | "unrecorded";
407
+ /** The pull request that merged the applied commit. */
408
+ pr?: number;
409
+ /** Its head commit, which `--record-plans` recorded the plans at. */
410
+ head?: string;
411
+ /** The digest the head recorded for this wave. */
412
+ recorded?: string;
413
+ /** Why the plans do not match, for `moved` and `unrecorded`. */
414
+ reason?: string;
415
+ /** Set when an approval of the digest planned now let a wave that did not match apply. */
416
+ approvedAnyway?: true;
417
+ }
418
+
394
419
  /**
395
420
  * What an apply call writes to `CHANT_APPLY_OUTCOME` when it applied nothing
396
421
  * for a reason that is not a failure (#3821). `stood-down`: a newer run (a
@@ -584,6 +609,8 @@ export interface OpWaveBaseRules {
584
609
  holdsRefused?: string;
585
610
  /** `approvals.pullRequest.gate` at base (#4550): the pull request's gate a `pull-request` wave takes its approval from. */
586
611
  pullRequestGate?: string;
612
+ /** `approvals.preview` at base: the wave applies what the merged pull request's head recorded, or refuses (exit 4). */
613
+ preview?: boolean;
587
614
  }
588
615
 
589
616
  const noHooks = (): Record<OpWaveHookMoment, OpWaveHook[]> =>
@@ -616,7 +643,7 @@ export function readOpWavePolicy(
616
643
  const spend = (spec as { approvals?: { spend?: unknown } }).approvals?.spend === true;
617
644
  const neverOverMcp = (spec as { neverOverMcp?: unknown }).neverOverMcp === true;
618
645
  // #3836: the gate's decision point, the spec's for a wave the base does not have yet.
619
- const asks = { ...pointAtBase(spec, name, `${specFile} at ${sha.slice(0, 12)}`), ...quorumAtBase(spec, `${specFile} at ${sha.slice(0, 12)}`), ...holdsAtBase(spec, `${specFile} at ${sha.slice(0, 12)}`), ...pullRequestGateAtBase(spec) };
646
+ const asks = { ...pointAtBase(spec, name, `${specFile} at ${sha.slice(0, 12)}`), ...quorumAtBase(spec, `${specFile} at ${sha.slice(0, 12)}`), ...holdsAtBase(spec, `${specFile} at ${sha.slice(0, 12)}`), ...pullRequestGateAtBase(spec), ...(spec.approvals?.preview === true ? { preview: true } : {}) };
620
647
  const wave = spec.waves.find((w) => w.name === name);
621
648
  if (!wave) return { ...absent, spend, neverOverMcp, ...asks };
622
649
  const policy = wave.gate ?? "always";
@@ -680,6 +707,9 @@ function pointAtBase(spec: OpWavesSpec, name: string, where: string): Pick<OpWav
680
707
  return { point: opWavePointAt(spec, name)! };
681
708
  }
682
709
 
710
+ /** The first chant whose Op waves spec takes `approvals.preview`: a merged wave applies the plans its pull request previewed, or exits 4. */
711
+ export const OP_WAVES_PREVIEW_FLOOR = NEXT_RELEASE;
712
+
683
713
  /** The first chant whose op entry exports {@link opWavePlanPath} (terragucci#1304). */
684
714
  export const OP_WAVE_PLAN_PATH_FLOOR = "0.124.56";
685
715
 
@@ -1935,7 +1965,7 @@ function opWaveRunStatus(result: RunOpWaveResult): { status: OpRunRecordInput["s
1935
1965
  case CHANT_EXIT.waiting:
1936
1966
  return { status: d?.point?.question ? "waiting" : "gated" };
1937
1967
  case CHANT_EXIT.moved:
1938
- return { status: "fail", failure: { code: "moved", reason: `plans moved since the decision: ${result.moved.join(", ") || "(none named)"}` } };
1968
+ return { status: "fail", failure: { code: "moved", reason: d?.refused?.reason === "moved" ? d.refused.message ?? "the plans are not the ones the pull request previewed" : `plans moved since the decision: ${result.moved.join(", ") || "(none named)"}` } };
1939
1969
  case CHANT_EXIT.denied:
1940
1970
  return { status: "fail", failure: { code: "denied", reason: d?.refused?.message ?? `the policy denied ${d?.refused?.runs.join(", ") ?? "a run"}, and no override counts` } };
1941
1971
  case CHANT_EXIT.declined:
@@ -2241,12 +2271,12 @@ function writeOpWaveOutcome(options: RunOpWaveOptions, dir: string, result: RunO
2241
2271
  const otherwise: WaveMemberOutcome["status"] =
2242
2272
  result.exitCode === 0 ? (options.decide ? "decided" : "unchanged")
2243
2273
  : result.exitCode === CHANT_EXIT.waiting ? "waiting"
2244
- : result.exitCode === CHANT_EXIT.denied || result.exitCode === CHANT_EXIT.declined ? "refused"
2274
+ : result.exitCode === CHANT_EXIT.denied || result.exitCode === CHANT_EXIT.declined || result.decision?.refused?.reason === "moved" ? "refused"
2245
2275
  : result.exitCode >= CHANT_EXIT.moved && result.exitCode <= CHANT_EXIT.superseded ? "not-applied"
2246
2276
  : "failed";
2247
2277
  for (const t of targets) {
2248
2278
  const by = result.blocked?.[t];
2249
- out[t] = by !== undefined ? { status: "blocked", by } : applied.has(t) ? { status: "applied" } : failed.has(t) ? { status: "failed" } : moved.has(t) ? { status: "not-applied" } : { status: otherwise };
2279
+ out[t] = by !== undefined ? { status: "blocked", by } : applied.has(t) ? { status: "applied" } : failed.has(t) ? { status: "failed" } : moved.has(t) && result.decision?.refused?.reason !== "moved" ? { status: "not-applied" } : { status: otherwise };
2250
2280
  }
2251
2281
  }
2252
2282
  const part = { ...(options.group !== undefined ? { group: options.group } : {}), ...(options.share !== undefined ? { share: options.share } : {}) };
@@ -2354,7 +2384,7 @@ async function planOpWave(options: RunOpWaveOptions, { k, pass }: WaveAttempt<Ru
2354
2384
  result.decision = decision;
2355
2385
  ctx.gateRule = { approval: decision.approval, base: decision.base, neverOverMcp: decision.neverOverMcp === true };
2356
2386
  if (decision.status === "waiting" || decision.status === "refused") {
2357
- log(`wave ${k} (${wave.name}) is ${decision.status === "refused" ? "refused by its policy" : `waiting on ${decision.heldOn?.gate ?? decision.gate}`}; nothing applied. ${decision.approve ?? ""}`.trim());
2387
+ log(`wave ${k} (${wave.name}) is ${decision.status === "refused" ? (decision.refused?.reason === "moved" ? "refused, its plans moved since the pull request previewed them" : "refused by its policy") : `waiting on ${decision.heldOn?.gate ?? decision.gate}`}; nothing applied. ${decision.approve ?? ""}`.trim());
2358
2388
  return { end: { ...result, exitCode: decision.status === "refused" ? refusedExit(decision) : CHANT_EXIT.waiting } };
2359
2389
  }
2360
2390
  // The share runs the hooks its deciding job read at base, around its own slice.
@@ -2560,12 +2590,26 @@ async function decideOpWave(
2560
2590
  if (was.overridesSpentAt) decision.overridesSpentAt = was.overridesSpentAt;
2561
2591
  }
2562
2592
  if (members.some((m) => m.denied && !m.override)) await settleDenials(ctx, decision, overriders, overridersSource);
2593
+ // `approvals.preview` at base: the merged wave applies what the pull request previewed. Planned again to a digest this job already let through, it has been judged.
2594
+ let unseen = false;
2595
+ if (planned.rules.preview && !kept && decision.status !== "refused") {
2596
+ const seen = await previewOf(options, ctx, digest);
2597
+ if ("error" in seen) return { end: failed(ctx, `wave ${k} (${wave.name}): ${seen.error}, so it cannot be compared with what the pull request previewed and nothing in it was applied`) };
2598
+ decision.preview = seen.preview;
2599
+ unseen = seen.preview.status !== "matched";
2600
+ if (!unseen) log(`wave ${k} (${wave.name}): the plans are the ones pull request #${seen.preview.pr} previewed at ${seen.preview.head?.slice(0, 12)} (${digest})`);
2601
+ else log(`wave ${k} (${wave.name}): ${seen.preview.reason}`);
2602
+ }
2563
2603
  if (kept && was.status === "approved" && decision.status !== "refused") {
2564
2604
  // #3821: planned again after the apply asked to, to the same digest: the approval this job found still holds, and is not spent twice.
2565
2605
  for (const key of ["via", "approvedBy", "approvedAt", "review", "spentAt"] as const) if (was[key] !== undefined) (decision as unknown as Record<string, unknown>)[key] = was[key];
2566
2606
  decision.status = "approved";
2567
2607
  log(`wave ${k} (${wave.name}): planned again to the same digest, so the approval by ${was.approvedBy} still holds`);
2568
- } else if (decision.status !== "refused" && (opWaveNeedsApproval(policy, members) || holds.length > 0)) await settleGate(options, ctx, decision);
2608
+ } else if (decision.status !== "refused" && (unseen || opWaveNeedsApproval(policy, members) || holds.length > 0)) {
2609
+ await settleGate(options, ctx, decision);
2610
+ // Plans nobody previewed apply only under an approval of these very plans, whatever the gate policy says.
2611
+ if (unseen) refuseUnseen(ctx, decision);
2612
+ }
2569
2613
  const code = await decided(ctx, decision, recordPath);
2570
2614
  if (code.exitCode !== 0) return { end: code };
2571
2615
  log(
@@ -2583,6 +2627,66 @@ async function decideOpWave(
2583
2627
  return { go: { runs: wave.runs, earlierHolds: [], recordPath } };
2584
2628
  }
2585
2629
 
2630
+ /**
2631
+ * Compare the wave's set digest with the one the merged pull request's head
2632
+ * recorded for it (`--record-plans`): the plans its reviewers saw. The pull
2633
+ * request is the one the forge says produced the applied commit. Resolves to
2634
+ * `error` only when the forge or the ledger cannot be read, which fails the
2635
+ * wave: a missing answer never stands in for a match.
2636
+ */
2637
+ async function previewOf(options: RunOpWaveOptions, ctx: WaveContext, digest: string): Promise<{ preview: OpWavePreview } | { error: string }> {
2638
+ const { spec, k, cwd } = ctx;
2639
+ const review = await import("./gate-review");
2640
+ const head = options.head ?? execFileSync("git", ["rev-parse", "HEAD"], { cwd, encoding: "utf-8" }).trim();
2641
+ let merged: MergedReview | null;
2642
+ try {
2643
+ merged = await (options.reviews ?? review.reviewSourceFromEnv()).mergedReview(head);
2644
+ } catch (err) {
2645
+ return { error: `the merged pull request could not be read from the forge (${err instanceof Error ? err.message : String(err)})` };
2646
+ }
2647
+ if (!merged) return { preview: { status: "unrecorded", reason: `no merged pull request produced ${head.slice(0, 12)}, so no plans were previewed for it` } };
2648
+ let plans: HeadPlans | null;
2649
+ try {
2650
+ plans = await (options.headPlans ?? ((name, h) => readHeadPlans(name, h, cwd)))(spec.name, merged.head);
2651
+ } catch (err) {
2652
+ return { error: `the plans recorded for #${merged.pr} could not be read (${err instanceof Error ? err.message : String(err)})` };
2653
+ }
2654
+ const seen = { pr: merged.pr, head: merged.head };
2655
+ const recorded = plans?.waves.find((w) => w.wave === k)?.digest;
2656
+ if (recorded === undefined) {
2657
+ return { preview: { status: "unrecorded", ...seen, reason: `no plans are recorded for wave ${k} at the head ${merged.head.slice(0, 12)} of #${merged.pr} (its pipeline runs \`chant run wave --record-plans\`), so nothing was previewed` } };
2658
+ }
2659
+ if (!samePlanDigest(recorded, digest)) {
2660
+ return {
2661
+ preview: {
2662
+ status: "moved",
2663
+ ...seen,
2664
+ recorded,
2665
+ reason: `the plans moved since #${merged.pr} previewed them: the head ${merged.head.slice(0, 12)} planned ${recorded}, and the merge plans ${digest}`,
2666
+ },
2667
+ };
2668
+ }
2669
+ return { preview: { status: "matched", ...seen, recorded } };
2670
+ }
2671
+
2672
+ /**
2673
+ * The gate was asked about plans the pull request did not preview. An
2674
+ * approval of exactly these plans lets the wave apply, since a person saw
2675
+ * them; with none, the wave is refused as moved (exit 4) and the approval
2676
+ * that would let it through is named.
2677
+ */
2678
+ function refuseUnseen(ctx: WaveContext, decision: OpWaveDecision): void {
2679
+ const preview = decision.preview!;
2680
+ if (decision.status === "approved") {
2681
+ preview.approvedAnyway = true;
2682
+ ctx.log(`wave ${ctx.k} (${ctx.wave.name}): ${preview.reason}; it applies under the approval of ${decision.digest} by ${decision.approvedBy}`);
2683
+ return;
2684
+ }
2685
+ const how = decision.approve ? ` Approve these plans to apply them: ${decision.approve}` : "";
2686
+ decision.status = "refused";
2687
+ decision.refused = { reason: "moved", runs: decision.members.map((m) => m.member).sort(), message: `${preview.reason}.${how}` };
2688
+ }
2689
+
2586
2690
  /** Apply a decided wave, or a share's unmoved runs (exit 4 when any moved). */
2587
2691
  async function applyOpWave(options: RunOpWaveOptions, planned: OpWavePlanned, decidedWave: OpWaveDecided): Promise<RunOpWaveResult> {
2588
2692
  const { ctx, decision } = planned;
@@ -2617,6 +2721,10 @@ async function decided(ctx: WaveContext, decision: OpWaveDecision, recordPath: s
2617
2721
  log(`Nothing in wave ${k} (${wave.name}) or after it ran: ${decision.refused.message}`);
2618
2722
  return { ...result, exitCode: CHANT_EXIT.declined };
2619
2723
  }
2724
+ if (decision.status === "refused" && decision.refused?.reason === "moved") {
2725
+ log(`Nothing in wave ${k} (${wave.name}) or after it ran: ${decision.refused.message}`);
2726
+ return { ...result, moved: [...decision.refused.runs], exitCode: CHANT_EXIT.moved };
2727
+ }
2620
2728
  if (decision.status === "refused") {
2621
2729
  log(`Nothing in wave ${k} (${wave.name}) or after it ran: the policy denied ${decision.refused?.runs.join(", ")}, and no override counts for ${decision.refused?.runs.length === 1 ? "it" : "them"}.`);
2622
2730
  return { ...result, exitCode: CHANT_EXIT.denied };
@@ -2787,7 +2895,7 @@ async function spendOverrides(ctx: WaveContext, decision: OpWaveDecision): Promi
2787
2895
 
2788
2896
  /** The exit code of a refused wave: 8 when its decision point refused it (#3836), 7 when the product's policy did (#3821). */
2789
2897
  function refusedExit(decision: OpWaveDecision): number {
2790
- return decision.refused?.reason === "point" ? CHANT_EXIT.declined : CHANT_EXIT.denied;
2898
+ return decision.refused?.reason === "point" ? CHANT_EXIT.declined : decision.refused?.reason === "moved" ? CHANT_EXIT.moved : CHANT_EXIT.denied;
2791
2899
  }
2792
2900
 
2793
2901
  function failed(ctx: WaveContext, line: string): RunOpWaveResult {
@@ -691,6 +691,17 @@ export interface OpWavesOverride {
691
691
 
692
692
  /** What happens to an approval once a wave applies under it (#3784). */
693
693
  export interface OpWavesApprovals {
694
+ /**
695
+ * Apply what the pull request previewed, or refuse. With `preview: true`
696
+ * (read at the base commit, like the policy) a merged wave compares the
697
+ * set digest it plans now with the digest the merged pull request's head
698
+ * recorded for it (`chant run wave --record-plans`), whatever its gate
699
+ * policy and approval mode, and applies only on a match. A different
700
+ * digest, or no record to compare with, refuses the wave with the moved
701
+ * code (4) unless an approval of the digest it plans now stands. Default
702
+ * false: a wave that needs no approval applies what it plans.
703
+ */
704
+ preview?: boolean;
694
705
  /**
695
706
  * Spend it. Before a wave applies under an approval it records that in
696
707
  * `_gates/<name>/applied.jsonl` on `chant/lifecycle`, and from then on the
@@ -802,8 +813,9 @@ export const OP_WAVES_APPROVAL_STATUS_VAR = "CHANT_APPROVAL_STATUS";
802
813
  * from the pull request, by its review (`pr-review`) or by its own approval
803
814
  * (`pull-request`, under the 2026-10-28 ruling).
804
815
  */
805
- export function opWavesPostsApprovalStatus(spec: Pick<OpWavesSpec, "waves">): boolean {
806
- return spec.waves.some((w) => w.approval === "pr-review" || w.approval === "pull-request");
816
+ export function opWavesPostsApprovalStatus(spec: Pick<OpWavesSpec, "waves" | "approvals">): boolean {
817
+ // `approvals.preview` compares the merged wave with the head's recorded plans, so the head must record them.
818
+ return spec.approvals?.preview === true || spec.waves.some((w) => w.approval === "pr-review" || w.approval === "pull-request");
807
819
  }
808
820
 
809
821
  /**
@@ -954,7 +966,12 @@ export function assertOpWavesSpec(spec: OpWavesSpec): void {
954
966
  }
955
967
  continue;
956
968
  }
957
- if (key !== "spend") throw new Error(`${where}: approvals.${key} is not a setting; the ones there are approvals.spend, approvals.quorum, approvals.reviewLedger, approvals.involved and approvals.pullRequest.`);
969
+ if (key === "preview") {
970
+ // The pull request's recorded plans are what the merged wave applies, read at base.
971
+ if (typeof value !== "boolean") throw new Error(`${where}: approvals.preview must be true or false.`);
972
+ continue;
973
+ }
974
+ if (key !== "spend") throw new Error(`${where}: approvals.${key} is not a setting; the ones there are approvals.spend, approvals.preview, approvals.quorum, approvals.reviewLedger, approvals.involved and approvals.pullRequest.`);
958
975
  if (typeof value !== "boolean") throw new Error(`${where}: approvals.spend must be true or false.`);
959
976
  }
960
977
  if ((a as OpWavesApprovals).quorum?.length && (spec.point !== undefined || spec.waves.some((w) => w.point !== undefined))) {
@@ -19,4 +19,4 @@
19
19
  * this constant to the next patch (#4501). The check fails while a floor
20
20
  * still names this constant after its version shipped.
21
21
  */
22
- export const NEXT_RELEASE = "0.124.58";
22
+ export const NEXT_RELEASE = "0.124.59";
@@ -10,7 +10,6 @@ import templateSchema from "./template.schema.json";
10
10
  import pkg from "../../package.json";
11
11
  import { buildReleaseCatalog } from "../lifecycle/release-catalog";
12
12
  import type { ReleaseRecord } from "../lifecycle/release-ledger";
13
- import { NEXT_RELEASE } from "../release-floors";
14
13
  import { resolveProductWords } from "../ci-product-words";
15
14
  import {
16
15
  checkTemplateRequest,
@@ -121,7 +120,7 @@ describe("schemas", () => {
121
120
  });
122
121
 
123
122
  test("the floor is the next release", () => {
124
- expect(TEMPLATE_REQUEST_FLOOR).toBe(NEXT_RELEASE);
123
+ expect(TEMPLATE_REQUEST_FLOOR).toBe("0.124.58");
125
124
  });
126
125
 
127
126
  test("the package exports ./template-request and its schemas", () => {
@@ -12,13 +12,12 @@
12
12
  */
13
13
 
14
14
  import schema from "./template-request.schema.json" with { type: "json" };
15
- import { NEXT_RELEASE } from "../release-floors";
16
15
  import { catalogVersion, type AttestationState, type CatalogComponent, type ReleaseCatalog } from "../lifecycle/release-catalog";
17
16
  import { inputKindProblem, inputRequired, isAppOutputRef, type TemplateSpec } from "./template-spec";
18
17
  import { schemaProblems } from "./validate";
19
18
 
20
19
  /** The first chant that writes and reads template-request/v1 and template.yml/v1 (#4651). */
21
- export const TEMPLATE_REQUEST_FLOOR = NEXT_RELEASE;
20
+ export const TEMPLATE_REQUEST_FLOOR = "0.124.58";
22
21
 
23
22
  /** The request document's `$schema`. */
24
23
  export const TEMPLATE_REQUEST_SCHEMA_ID: string = schema.$id;
@@ -4,10 +4,14 @@
4
4
  * and each member kind answers the reads the table says.
5
5
  */
6
6
 
7
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
7
10
  import { describe, expect, test } from "vitest";
8
11
  import { driftRecord, driftRecordLine, driftSettle, driftStart, type DriftRecord } from "../drift-record";
9
12
  import { readContractSchema } from "./conformance";
10
- import { DRIFT_CONTRACT_VERSION, DRIFT_ERROR_CODES, DRIFT_READS_BY_KIND, DRIFT_RESOURCE_KINDS, driftReadDocument } from "./drift-cli";
13
+ import { DRIFT_CONTRACT_VERSION, DRIFT_ERROR_CODES, DRIFT_READS_BY_KIND, DRIFT_RESOURCE_KINDS, DRIFT_STACK_KINDS, driftReadDocument, readWorkspaceDrift } from "./drift-cli";
14
+ import { parseArgs } from "../cli/parse-args";
11
15
  import driftSchema from "./drift.schema.json";
12
16
 
13
17
  const at = "2026-10-25T09:00:00Z";
@@ -63,3 +67,33 @@ describe("chant workspace drift's document", () => {
63
67
  expect(DRIFT_ERROR_CODES).toContain("no-drift-read");
64
68
  });
65
69
  });
70
+
71
+ describe("chant workspace drift --stack", () => {
72
+ test("is parsed beside --member and --resource", () => {
73
+ const args = parseArgs(["workspace", "drift", "--member", "shop", "--stack", "prod-eu", "--resource", "urn:x"]);
74
+ expect(args.carveStack).toBe("prod-eu");
75
+ expect(args.members).toEqual(["shop"]);
76
+ expect(parseArgs(["workspace", "drift", "--member", "shop"]).carveStack).toBeUndefined();
77
+ });
78
+
79
+ test("only a pulumi member keeps one export per stack", () => {
80
+ expect(DRIFT_STACK_KINDS).toEqual(["pulumi"]);
81
+ for (const kind of DRIFT_STACK_KINDS) expect(DRIFT_READS_BY_KIND[kind]).toBeDefined();
82
+ });
83
+
84
+ test("a member of another kind refuses it with read-unsupported before anything runs", async () => {
85
+ const root = mkdtempSync(join(tmpdir(), "drift-stack-"));
86
+ try {
87
+ mkdirSync(join(root, "infra"));
88
+ writeFileSync(join(root, "chant.workspace.json"), JSON.stringify({ name: "acme", schema: 1, members: [{ name: "infra", dir: "infra", kind: "terraform" }] }));
89
+ const answer = await readWorkspaceDrift({ cwd: root, member: "infra", stack: "prod-eu" });
90
+ expect("error" in answer && answer.error.code).toBe("read-unsupported");
91
+ expect("error" in answer && answer.error.message).toMatch(/--stack reads a stack's export from the index store.*infra is kind terraform/);
92
+ const doc = driftReadDocument("infra", answer);
93
+ const { validate } = readContractSchema("drift");
94
+ expect(validate(doc), JSON.stringify(validate.errors)).toBe(true);
95
+ } finally {
96
+ rmSync(root, { recursive: true, force: true });
97
+ }
98
+ });
99
+ });
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `chant workspace drift [dir] --member <name> [--read <read>] [--resource
3
- * <addr>] [--env <env>] [--stream] [-o <file>]` (behold#995): one member's
3
+ * <addr>] [--stack <name>] [--env <env>] [--stream] [-o <file>]` (behold#995): one member's
4
4
  * drift, read by the engine that owns it, as chant's drift record
5
5
  * (`../drift-record.ts`, #4451).
6
6
  *
@@ -13,6 +13,14 @@
13
13
  * | `choudoufu` | `ownership` | the same, through `choudoufu live-plan -json` (and `live-ls`), or `--read plan` for live-plan with a plan beside it; `--resource <addr>` passes `choudoufu live-plan -resource=<addr>`'s stream through |
14
14
  * | `pulumi` | `refresh` | `chant lifecycle drift` in the member's reader project: the pulumi lexicon's `readDrift`, `pulumi refresh --preview-only --json --target <urn>` per resource in the checked-in export, or `plunge drift --resource <urn> --stream` for a member on plunge; `--resource <urn>` reads that URN alone (#4455) |
15
15
  *
16
+ * `--stack <name>` reads that stack's export for a `pulumi` member, from the
17
+ * index store (`refs/chant/snapshots`), where a member of several stacks
18
+ * holds one export each. Without it the member reads the export its store
19
+ * holds, which is the right one only for a member of one stack. A store with
20
+ * no export for the stack answers `no-drift-read`, naming the stack; it never
21
+ * falls back to another stack's export or the checked-in file. Any other kind
22
+ * answers `read-unsupported`.
23
+ *
16
24
  * Any other kind has no drift read and answers `no-drift-read`. A member of
17
25
  * a package's kind runs in the reader project `workspace graph` writes for it
18
26
  * (`./kind-readers.ts`), under the member's own toolchain, so chant core
@@ -111,7 +119,10 @@ export const DRIFT_RESOURCE_KINDS: readonly string[] = ["choudoufu", "pulumi"];
111
119
  const MEMBER_REFUSED_EXITS: readonly number[] = [1, 3];
112
120
 
113
121
  const USAGE =
114
- "chant workspace drift [dir] --member <name> [--read <state|plan|refresh|live-read|ownership>] [--resource <addr>] [--env <env>] [--components] [--stream] [-o <file>]";
122
+ "chant workspace drift [dir] --member <name> [--read <state|plan|refresh|live-read|ownership>] [--resource <addr>] [--stack <name>] [--env <env>] [--components] [--stream] [-o <file>]";
123
+
124
+ /** The kinds whose engine keeps one export per stack, for `--stack`. */
125
+ export const DRIFT_STACK_KINDS: readonly string[] = ["pulumi"];
115
126
 
116
127
  /** The document `workspace drift` prints: a drift document with the read contract's head. */
117
128
  export type WorkspaceDriftDocument = DriftDocument & {
@@ -127,6 +138,8 @@ export interface DriftQuery {
127
138
  member: string;
128
139
  read?: string;
129
140
  resource?: string;
141
+ /** The stack whose stored export is read (`--stack`), for a pulumi member. */
142
+ stack?: string;
130
143
  env?: string;
131
144
  components?: boolean;
132
145
  }
@@ -229,7 +242,7 @@ interface LexiconDiff {
229
242
  /** The command line the member runs. */
230
243
  function memberArgv(kind: string, query: DriftQuery, read: DriftRead): string[] {
231
244
  if (kind === "chant") return ["lifecycle", "diff", query.env!, "--live", "--json"];
232
- return ["lifecycle", "drift", ".", "--member", query.member, "--read", read, ...(query.resource !== undefined ? ["--resource", query.resource] : [])];
245
+ return ["lifecycle", "drift", ".", "--member", query.member, "--read", read, ...(query.resource !== undefined ? ["--resource", query.resource] : []), ...(query.stack !== undefined ? ["--stack", query.stack] : [])];
233
246
  }
234
247
 
235
248
  /**
@@ -255,6 +268,10 @@ export async function readWorkspaceDrift(query: DriftQuery): Promise<DriftReadRe
255
268
  if (query.resource !== undefined && !DRIFT_RESOURCE_KINDS.includes(entry.kind)) {
256
269
  throw new DriftReadFailure("resource-unsupported", `--resource reads one resource through choudoufu live-plan -resource, pulumi refresh --target or plunge drift --resource; ${query.member} is kind ${entry.kind}`);
257
270
  }
271
+ if (query.stack !== undefined && !DRIFT_STACK_KINDS.includes(entry.kind)) {
272
+ throw new DriftReadFailure("read-unsupported", `--stack reads a stack's export from the index store, which a ${DRIFT_STACK_KINDS.join(" or ")} member has; ${query.member} is kind ${entry.kind}`);
273
+ }
274
+ if (query.stack !== undefined && query.stack.trim() === "") throw new DriftReadFailure("read-unsupported", "--stack needs a stack name");
258
275
  if (entry.kind === "chant" && !query.env) throw new DriftReadFailure("env-required", `${query.member} is a chant member, read live through chant lifecycle diff <env> --live: add --env <env>`);
259
276
 
260
277
  const { registry: kinds, problems } = loadKindRegistry(declaration.pins, located.rootOnDisk);
@@ -349,6 +366,7 @@ export async function runWorkspaceDrift(ctx: CommandContext): Promise<number> {
349
366
  member: members[0],
350
367
  ...(args.driftRead !== undefined ? { read: args.driftRead } : {}),
351
368
  ...(args.resource !== undefined ? { resource: args.resource } : {}),
369
+ ...(args.carveStack !== undefined ? { stack: args.carveStack } : {}),
352
370
  ...(args.env !== undefined ? { env: args.env } : {}),
353
371
  ...(args.components ? { components: true } : {}),
354
372
  });