@intentius/chant 0.124.78 → 0.124.79

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 (150) hide show
  1. package/dist/action-pins.d.ts.map +1 -1
  2. package/dist/action-pins.js +1 -2
  3. package/dist/change-set.d.ts +10 -1
  4. package/dist/change-set.d.ts.map +1 -1
  5. package/dist/change-set.js +4 -1
  6. package/dist/ci-agent.d.ts +16 -2
  7. package/dist/ci-agent.d.ts.map +1 -1
  8. package/dist/ci-agent.js +6 -1
  9. package/dist/ci-commit.d.ts.map +1 -1
  10. package/dist/ci-commit.js +2 -3
  11. package/dist/ci-product.d.ts +6 -2
  12. package/dist/ci-product.d.ts.map +1 -1
  13. package/dist/ci-product.js +5 -1
  14. package/dist/cli/handlers/release.d.ts +8 -0
  15. package/dist/cli/handlers/release.d.ts.map +1 -1
  16. package/dist/cli/handlers/release.js +64 -2
  17. package/dist/cli/handlers/run-wave.js +1 -0
  18. package/dist/cli/main.d.ts.map +1 -1
  19. package/dist/cli/main.js +7 -0
  20. package/dist/cli/mcp/product-tools.d.ts +6 -0
  21. package/dist/cli/mcp/product-tools.d.ts.map +1 -1
  22. package/dist/cli/mcp/product-tools.js +7 -0
  23. package/dist/cli/mcp/read-only.d.ts +12 -0
  24. package/dist/cli/mcp/read-only.d.ts.map +1 -1
  25. package/dist/cli/mcp/read-only.js +16 -0
  26. package/dist/cli/mcp/server.d.ts +11 -0
  27. package/dist/cli/mcp/server.d.ts.map +1 -1
  28. package/dist/cli/mcp/server.js +26 -5
  29. package/dist/cli/mcp/types.d.ts +5 -1
  30. package/dist/cli/mcp/types.d.ts.map +1 -1
  31. package/dist/components/capability.d.ts +42 -0
  32. package/dist/components/capability.d.ts.map +1 -1
  33. package/dist/components/group-digest.d.ts +17 -0
  34. package/dist/components/group-digest.d.ts.map +1 -0
  35. package/dist/components/group-digest.js +18 -0
  36. package/dist/components/groups.d.ts +2 -11
  37. package/dist/components/groups.d.ts.map +1 -1
  38. package/dist/components/groups.js +2 -12
  39. package/dist/components/index.d.ts +1 -1
  40. package/dist/components/index.d.ts.map +1 -1
  41. package/dist/config.d.ts +14 -0
  42. package/dist/config.d.ts.map +1 -1
  43. package/dist/config.js +5 -0
  44. package/dist/lexicon.d.ts.map +1 -1
  45. package/dist/lexicon.js +1 -2
  46. package/dist/lifecycle/release-cut.d.ts +7 -1
  47. package/dist/lifecycle/release-cut.d.ts.map +1 -1
  48. package/dist/lifecycle/release-cut.js +1 -0
  49. package/dist/lifecycle/release-images.d.ts +12 -3
  50. package/dist/lifecycle/release-images.d.ts.map +1 -1
  51. package/dist/lifecycle/release-images.js +6 -7
  52. package/dist/lifecycle/release-publish.d.ts +8 -1
  53. package/dist/lifecycle/release-publish.d.ts.map +1 -1
  54. package/dist/lifecycle/release-publish.js +30 -3
  55. package/dist/lifecycle/release-version.d.ts +86 -0
  56. package/dist/lifecycle/release-version.d.ts.map +1 -0
  57. package/dist/lifecycle/release-version.js +209 -0
  58. package/dist/mcp/types.d.ts +26 -0
  59. package/dist/mcp/types.d.ts.map +1 -1
  60. package/dist/notify-product.d.ts.map +1 -1
  61. package/dist/notify-product.js +1 -2
  62. package/dist/op/activities/review-product.d.ts.map +1 -1
  63. package/dist/op/activities/review-product.js +1 -2
  64. package/dist/op/gate.d.ts +17 -0
  65. package/dist/op/gate.d.ts.map +1 -1
  66. package/dist/op/gate.js +36 -0
  67. package/dist/op/index.d.ts +8 -6
  68. package/dist/op/index.d.ts.map +1 -1
  69. package/dist/op/index.js +5 -4
  70. package/dist/op/op-waves-after-plan.d.ts +76 -1
  71. package/dist/op/op-waves-after-plan.d.ts.map +1 -1
  72. package/dist/op/op-waves-after-plan.js +142 -3
  73. package/dist/op/op-waves-capability-spec.js +1 -2
  74. package/dist/op/op-waves-capability.d.ts +89 -2
  75. package/dist/op/op-waves-capability.d.ts.map +1 -1
  76. package/dist/op/op-waves-capability.js +215 -7
  77. package/dist/op/op-waves-run-hooks.d.ts +104 -0
  78. package/dist/op/op-waves-run-hooks.d.ts.map +1 -0
  79. package/dist/op/op-waves-run-hooks.js +146 -0
  80. package/dist/op/op-waves-run.d.ts +21 -0
  81. package/dist/op/op-waves-run.d.ts.map +1 -1
  82. package/dist/op/op-waves-run.js +233 -13
  83. package/dist/op/op-waves.d.ts +11 -1
  84. package/dist/op/op-waves.d.ts.map +1 -1
  85. package/dist/op/op-waves.js +7 -1
  86. package/dist/op/runtime.d.ts +2 -0
  87. package/dist/op/runtime.d.ts.map +1 -1
  88. package/dist/pr-plan-note.d.ts.map +1 -1
  89. package/dist/pr-plan-note.js +1 -2
  90. package/dist/release-floors.d.ts +5 -1
  91. package/dist/release-floors.d.ts.map +1 -1
  92. package/dist/release-floors.js +9 -5
  93. package/dist/wave-runtime.mjs +314 -314
  94. package/dist/workspace/change-set.schema.json +7 -0
  95. package/dist/workspace/release-workflow.d.ts +7 -0
  96. package/dist/workspace/release-workflow.d.ts.map +1 -1
  97. package/dist/workspace/release-workflow.js +11 -1
  98. package/package.json +1 -1
  99. package/src/action-pins.test.ts +1 -2
  100. package/src/action-pins.ts +1 -3
  101. package/src/change-set.test.ts +20 -0
  102. package/src/change-set.ts +11 -1
  103. package/src/ci-agent.test.ts +9 -0
  104. package/src/ci-agent.ts +15 -2
  105. package/src/ci-commit.test.ts +2 -3
  106. package/src/ci-commit.ts +2 -3
  107. package/src/ci-product.ts +6 -2
  108. package/src/cli/handlers/release.ts +55 -2
  109. package/src/cli/handlers/run-wave.ts +1 -0
  110. package/src/cli/main.ts +7 -0
  111. package/src/cli/mcp/product-tools.test.ts +50 -0
  112. package/src/cli/mcp/product-tools.ts +8 -0
  113. package/src/cli/mcp/read-only.ts +19 -0
  114. package/src/cli/mcp/server.test.ts +30 -0
  115. package/src/cli/mcp/server.ts +28 -5
  116. package/src/cli/mcp/types.ts +6 -1
  117. package/src/components/capability.ts +41 -0
  118. package/src/components/group-digest.ts +20 -0
  119. package/src/components/groups.ts +3 -13
  120. package/src/components/index.ts +2 -0
  121. package/src/config.ts +15 -0
  122. package/src/lexicon.ts +1 -2
  123. package/src/lifecycle/release-cut.ts +11 -0
  124. package/src/lifecycle/release-images-dockerfile.test.ts +10 -2
  125. package/src/lifecycle/release-images.ts +12 -8
  126. package/src/lifecycle/release-publish.ts +34 -3
  127. package/src/lifecycle/release-version.test.ts +155 -0
  128. package/src/lifecycle/release-version.ts +227 -0
  129. package/src/mcp/types.ts +27 -0
  130. package/src/notify-message-words.test.ts +1 -2
  131. package/src/notify-product.ts +1 -2
  132. package/src/op/activities/review-product.ts +1 -2
  133. package/src/op/gate.ts +46 -0
  134. package/src/op/index.ts +10 -4
  135. package/src/op/op-waves-after-plan-wave.test.ts +226 -0
  136. package/src/op/op-waves-after-plan.ts +170 -5
  137. package/src/op/op-waves-capability-spec.ts +1 -1
  138. package/src/op/op-waves-capability.test.ts +6 -0
  139. package/src/op/op-waves-capability.ts +243 -10
  140. package/src/op/op-waves-run-hooks.test.ts +184 -0
  141. package/src/op/op-waves-run-hooks.ts +195 -0
  142. package/src/op/op-waves-run.ts +240 -16
  143. package/src/op/op-waves-step-wave.test.ts +277 -0
  144. package/src/op/op-waves.ts +15 -2
  145. package/src/op/runtime.ts +2 -0
  146. package/src/pr-plan-note.ts +1 -2
  147. package/src/release-floors.ts +11 -5
  148. package/src/workspace/change-set.schema.json +7 -0
  149. package/src/workspace/release-workflow.test.ts +18 -0
  150. package/src/workspace/release-workflow.ts +21 -1
@@ -0,0 +1,226 @@
1
+ /**
2
+ * The after-plan hook's wave answer (#4842): what a product adds to the wave
3
+ * as a whole once it read every run's plan. Pending fact fields, digest
4
+ * members that are no run, holds, overriders, and the gate report chant
5
+ * stores beside the pending fact.
6
+ */
7
+
8
+ import { describe, expect, test } from "vitest";
9
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { tmpdir } from "node:os";
12
+ import type { OpWavesSpec } from "./op-waves";
13
+ import { runOpWave, opWaveSetDigest, type OpWaveShowAtBase } from "./op-waves-run";
14
+ import { memoryGateLedgerPort, opWaveGateReportPath } from "./gate";
15
+ import { CapabilityRegistry, type Capability } from "../components/capability";
16
+ import type { ChangeSetPart } from "../change-set";
17
+ import { opWaveAfterPlanWaveResultProblems, opWaveAfterPlanResultProblems, type OpWaveAfterPlanWave } from "./op-waves-after-plan";
18
+
19
+ const digest = (n: string) => `sha256:${n.repeat(64)}`;
20
+ const NOW = "2026-11-08T00:00:00.000Z";
21
+
22
+ const part = (member: string): ChangeSetPart => ({
23
+ member: { member, lexicon: "terraform", planner: "chant", status: "planned", planDigest: digest("9"), holes: [] },
24
+ entries: [{ member, address: `aws_s3_bucket.${member}`, type: "aws_s3_bucket", action: "create" } as ChangeSetPart["entries"][number]],
25
+ });
26
+
27
+ function capability(digests: Record<string, string>): { registry: CapabilityRegistry; ran: string[] } {
28
+ const ran: string[] = [];
29
+ const cap: Capability<Record<string, unknown>, unknown> = {
30
+ kind: "fake-apply",
31
+ async plan(_ctx, input) {
32
+ const root = String(input.root);
33
+ return { member: root, planDigest: digests[root]!, artifact: { planFile: `${root}.tfplan` }, changeSet: part(root) };
34
+ },
35
+ async run(_ctx, input) {
36
+ ran.push(String(input.root));
37
+ return {};
38
+ },
39
+ };
40
+ return { registry: new CapabilityRegistry().register(cap), ran };
41
+ }
42
+
43
+ const base = (gate: "never" | "always"): OpWavesSpec => ({
44
+ name: "tf-apply",
45
+ op: "tf-apply",
46
+ gateName: "wave-{k}",
47
+ step: { kind: "fake-apply", root: "{target}" },
48
+ waves: [{ name: "wave-1", runs: [{ target: "network" }, { target: "app" }], gate }],
49
+ });
50
+
51
+ const digests = { network: digest("1"), app: digest("2") };
52
+
53
+ function harness(spec: OpWavesSpec) {
54
+ const cwd = mkdtempSync(join(tmpdir(), "op-waves-wave-answer-"));
55
+ const show: OpWaveShowAtBase = () => ({ sha: "b".repeat(40), text: JSON.stringify(spec) });
56
+ return { cwd, show, done: () => rmSync(cwd, { recursive: true, force: true }) };
57
+ }
58
+
59
+ describe("the after-plan hook's wave answer (#4842)", () => {
60
+ test("pending fields, digest members and holds: the wave waits whatever its gate, and its digest covers the members", async () => {
61
+ const spec = base("never");
62
+ const h = harness(spec);
63
+ const { registry, ran } = capability(digests);
64
+ const gates = memoryGateLedgerPort();
65
+ const seen: OpWaveAfterPlanWave[] = [];
66
+ const cost = { member: "(monthly cost)", planDigest: digest("7") };
67
+ const result = await runOpWave({
68
+ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, show: h.show, gates, capabilities: registry, now: NOW, log: () => {},
69
+ afterPlan: {
70
+ name: "terragucci",
71
+ run: () => {},
72
+ wave: (w) => {
73
+ seen.push(w);
74
+ return { pending: { description: "wave 1 of 1: network, app", commit: "c".repeat(40) }, members: [cost], holds: ["app reads network's vpc_id, unknown when the change was reviewed"] };
75
+ },
76
+ },
77
+ });
78
+ expect(seen.map((w) => [w.wave, w.job, w.runs.map((r) => r.target)])).toEqual([[1, "wave", ["network", "app"]]]);
79
+ expect(result.exitCode).toBe(3);
80
+ expect(ran).toEqual([]);
81
+ expect(result.decision?.heldBy).toEqual(["app reads network's vpc_id, unknown when the change was reviewed"]);
82
+ expect(result.decision?.extras).toEqual([cost]);
83
+ const members = [{ member: "network", planDigest: digests.network }, { member: "app", planDigest: digests.app }];
84
+ expect(result.decision?.digest).toBe(opWaveSetDigest(spec, members, [cost]));
85
+ expect(gates.appended[0]).toMatchObject({ op: "tf-apply", gate: "wave-1", description: "wave 1 of 1: network, app", commit: "c".repeat(40) });
86
+ h.done();
87
+ });
88
+
89
+ test("the report is stored beside the pending fact it asks approval for, once", async () => {
90
+ const spec = base("always");
91
+ const h = harness(spec);
92
+ const { registry } = capability(digests);
93
+ const gates = memoryGateLedgerPort();
94
+ const go = (report: string) =>
95
+ runOpWave({ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, show: h.show, gates, capabilities: registry, now: NOW, log: () => {}, afterPlan: { name: "terragucci", run: () => {}, wave: () => ({ report }) } });
96
+ const first = await go('{"roots":["network","app"]}');
97
+ expect(first.exitCode).toBe(3);
98
+ const at = opWaveGateReportPath("tf-apply", "wave-1", first.decision!.digest);
99
+ expect(at).toBe(`_gates/tf-apply/wave-1/${first.decision!.digest.replace(":", "_")}.json`);
100
+ expect(gates.reports.get(at)).toBe('{"roots":["network","app"]}');
101
+ const again = await go('{"roots":["changed"]}');
102
+ expect(again.decision!.digest).toBe(first.decision!.digest);
103
+ expect(gates.reports.get(at)).toBe('{"roots":["network","app"]}');
104
+ h.done();
105
+ });
106
+
107
+ test("a wave that needs no approval stores no report", async () => {
108
+ const spec = base("never");
109
+ const h = harness(spec);
110
+ const { registry, ran } = capability(digests);
111
+ const gates = memoryGateLedgerPort();
112
+ const result = await runOpWave({ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, show: h.show, gates, capabilities: registry, now: NOW, log: () => {}, afterPlan: { name: "terragucci", run: () => {}, wave: () => ({ report: "{}" }) } });
113
+ expect(result.exitCode).toBe(0);
114
+ expect(ran).toEqual(["network", "app"]);
115
+ expect(gates.reports.size).toBe(0);
116
+ h.done();
117
+ });
118
+
119
+ test("after an approval of other plans, the report of the plans now and of the plans approved are written for the respond job", async () => {
120
+ const spec = base("always");
121
+ const h = harness(spec);
122
+ const { registry } = capability(digests);
123
+ const was = digest("9");
124
+ const gates = memoryGateLedgerPort({ resolutions: [{ version: 1, op: "tf-apply", gate: "wave-1", resolvedBy: "alice", timestamp: "2026-11-07T00:00:00Z", planDigest: was }] });
125
+ gates.reports.set(opWaveGateReportPath("tf-apply", "wave-1", was), '{"roots":["network"]}');
126
+ const result = await runOpWave({ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, show: h.show, gates, capabilities: registry, now: NOW, log: () => {}, afterPlan: { name: "terragucci", run: () => {}, wave: () => ({ report: '{"roots":["network","app"]}' }) } });
127
+ expect(result.exitCode).toBe(3);
128
+ expect(result.decision?.mismatch).toMatchObject({ approved: was, resolvedBy: "alice" });
129
+ expect(result.decision?.reports).toEqual({ current: ".chant/op-waves/tf-apply/wave-1/report/current.json", approved: ".chant/op-waves/tf-apply/wave-1/report/approved.json" });
130
+ expect(readFileSync(join(h.cwd, result.decision!.reports!.current), "utf-8")).toBe('{"roots":["network","app"]}');
131
+ expect(readFileSync(join(h.cwd, result.decision!.reports!.approved!), "utf-8")).toBe('{"roots":["network"]}');
132
+ h.done();
133
+ });
134
+
135
+ test("with no report kept for the plans approved, only the report of the plans now is written", async () => {
136
+ const spec = base("always");
137
+ const h = harness(spec);
138
+ const { registry } = capability(digests);
139
+ const gates = memoryGateLedgerPort({ resolutions: [{ version: 1, op: "tf-apply", gate: "wave-1", resolvedBy: "alice", timestamp: "2026-11-07T00:00:00Z", planDigest: digest("9") }] });
140
+ const result = await runOpWave({ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, show: h.show, gates, capabilities: registry, now: NOW, log: () => {}, afterPlan: { name: "terragucci", run: () => {}, wave: () => ({ report: "{}" }) } });
141
+ expect(result.decision?.reports).toEqual({ current: ".chant/op-waves/tf-apply/wave-1/report/current.json" });
142
+ expect(existsSync(join(h.cwd, ".chant/op-waves/tf-apply/wave-1/report/approved.json"))).toBe(false);
143
+ h.done();
144
+ });
145
+
146
+ test("the wave answer's overriders replace the list at base, and a run's own overriders replace them for that run", async () => {
147
+ const { overrideDigest } = await import("../override-gate");
148
+ const spec = base("never");
149
+ const od = overrideDigest("app", digests.app, ["no-public-s3"]);
150
+ const override = { version: 1 as const, op: "policy-override", gate: "app", resolvedBy: "github:carol", timestamp: "2026-11-07T00:00:00Z", planDigest: od, note: "the bucket is the public docs site" };
151
+ const deny = (target: string) => ({ policy: target === "app" ? [{ source: "terragucci", result: "denied" as const, rules: ["no-public-s3"] }] : [] });
152
+ // The wave's list names someone else: carol's override does not count.
153
+ const h = harness(spec);
154
+ const { registry, ran } = capability(digests);
155
+ const refused = await runOpWave({
156
+ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, show: h.show, gates: memoryGateLedgerPort({ resolutions: [override] }), capabilities: registry, now: NOW, log: () => {},
157
+ afterPlan: { name: "terragucci", run: (r) => deny(r.target), wave: () => ({ overriders: ["github:dave"], overridersSource: "policy.override in terragucci.yml" }) },
158
+ });
159
+ expect(refused.exitCode).toBe(7);
160
+ expect(refused.decision?.refused).toMatchObject({ runs: ["app"], overridersSource: "policy.override in terragucci.yml" });
161
+ expect(ran).toEqual([]);
162
+ // app's own list names carol: her override lets it through.
163
+ const gates = memoryGateLedgerPort({ resolutions: [override] });
164
+ const passed = await runOpWave({
165
+ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, show: h.show, gates, capabilities: registry, now: NOW, log: () => {},
166
+ afterPlan: { name: "terragucci", run: (r) => ({ ...deny(r.target), ...(r.target === "app" ? { overriders: ["github:carol"] } : {}) }), wave: () => ({ overriders: ["github:dave"] }) },
167
+ });
168
+ expect(passed.exitCode).toBe(0);
169
+ expect(passed.decision?.members.find((m) => m.member === "app")).toMatchObject({ override: { by: "github:carol", digest: od } });
170
+ expect(ran).toEqual(["network", "app"]);
171
+ h.done();
172
+ });
173
+
174
+ test("a wave answer that throws fails the wave before the gate under fail, and holds it under approve", async () => {
175
+ const spec = base("never");
176
+ const h = harness(spec);
177
+ const { registry, ran } = capability(digests);
178
+ const failed = await runOpWave({
179
+ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, show: h.show, gates: memoryGateLedgerPort(), capabilities: registry, now: NOW, log: () => {},
180
+ afterPlan: { name: "terragucci", run: () => {}, wave: () => { throw new Error("the estimator did not run"); } },
181
+ });
182
+ expect(failed.exitCode).toBe(1);
183
+ expect(failed.decision).toBeUndefined();
184
+ expect(failed.hooks.filter((o) => o.moment === "after-plan").map((o) => [o.target ?? "(wave)", o.outcome])).toEqual([["network", "passed"], ["app", "passed"], ["(wave)", "failed"]]);
185
+ const held = await runOpWave({
186
+ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, show: h.show, gates: memoryGateLedgerPort(), capabilities: registry, now: NOW, log: () => {},
187
+ afterPlan: { name: "terragucci", onFailure: "approve", run: () => {}, wave: () => { throw new Error("the estimator did not run"); } },
188
+ });
189
+ expect(held.exitCode).toBe(3);
190
+ expect(held.decision?.heldBy).toEqual(["after-plan hook terragucci (wave 1)"]);
191
+ expect(ran).toEqual([]);
192
+ h.done();
193
+ });
194
+
195
+ test("a hook with no wave answer leaves the wave as it was", async () => {
196
+ const spec = base("never");
197
+ const h = harness(spec);
198
+ const { registry } = capability(digests);
199
+ const gates = memoryGateLedgerPort();
200
+ const result = await runOpWave({ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, show: h.show, gates, capabilities: registry, now: NOW, log: () => {}, afterPlan: { name: "terragucci", run: () => {} } });
201
+ expect(result.exitCode).toBe(0);
202
+ expect(result.decision?.extras).toBeUndefined();
203
+ expect(result.decision?.reports).toBeUndefined();
204
+ h.done();
205
+ });
206
+
207
+ test("the answers are checked", () => {
208
+ expect(opWaveAfterPlanWaveResultProblems({ pending: { op: "x" }, overriders: [1], members: [{ member: "network", planDigest: digest("1") }, { member: "" }], holds: [""], report: 3 }, ["network"])).toEqual([
209
+ "`pending` cannot set op, which chant writes",
210
+ "`overriders` must be a list of principals",
211
+ "member network is also a run's target; a digest member that is no run needs a name of its own",
212
+ "each of `members` needs a member and a planDigest",
213
+ "`holds` must be a list of reasons, each a line saying why the wave waits for a person",
214
+ "`report` must be the report's text",
215
+ ]);
216
+ expect(opWaveAfterPlanWaveResultProblems(undefined, [])).toEqual([]);
217
+ expect(opWaveAfterPlanResultProblems({ overriders: "carol" })).toEqual(["`overriders` must be a list of principals"]);
218
+ });
219
+
220
+ test("the floor is the next release", async () => {
221
+ const entry = await import("./index");
222
+ const { NEXT_RELEASE } = await import("../release-floors");
223
+ expect(entry.OP_WAVE_AFTER_PLAN_WAVE_FLOOR).toBe(NEXT_RELEASE);
224
+ });
225
+ });
226
+
@@ -20,13 +20,43 @@
20
20
  * The spec's command hooks at `hooks.after.plan` keep running where they
21
21
  * ran: after the set digest, before the gate settles. A `perRun` one gets
22
22
  * `{planJson}`, `CHANT_PLAN_DIGEST` and `CHANT_PLAN_JSON` the same way.
23
+ *
24
+ * ## The wave answer (#4842)
25
+ *
26
+ * A hook's `wave`, when it has one, is called once per job after its `run`
27
+ * was called for each of its runs, with all of them. It answers for the wave
28
+ * as a whole, as a plans file does for a wave-level plan command:
29
+ *
30
+ * - `pending`: fields for the pending fact (a `description`, the commit it
31
+ * planned), under the plans file's rules (`pendingFields`).
32
+ * - `members`: digest members that are no run, such as the wave's monthly
33
+ * cost from the product's own estimator.
34
+ * - `holds`: reasons the wave waits for a person whatever its gate, one line
35
+ * each, as a held hook's.
36
+ * - `overriders` and `overridersSource`: who may override a denial, in place
37
+ * of the overriders file at base. A run's own answer can name its own
38
+ * `overriders`, which count for that run in place of the wave's.
39
+ * - `report`: the product's report of these plans. When the wave waits,
40
+ * chant stores it beside the pending fact, at
41
+ * `_gates/<op>/<gate>/<digest>.json`, once. When the plans moved after an
42
+ * approval, chant writes it and the report stored for the approved plans
43
+ * to `.chant/op-waves/<name>/wave-<k>/report/` (`current.json`,
44
+ * `approved.json`) and names them on the decision, for the job that
45
+ * explains the refusal.
46
+ *
47
+ * A `wave` that throws follows the hook's `onFailure`, as `run` does.
23
48
  */
24
49
 
25
50
  import { isAbsolute } from "node:path";
51
+ import { NEXT_RELEASE } from "../release-floors";
26
52
  import type { ChangeSetPart } from "../change-set";
27
53
  import type { OpRunPolicyRow } from "./runtime";
54
+ import type { WaveMember } from "../wave-engine";
28
55
  import { OP_WAVE_HOOK_FAILURES, opWaveHookRuns, type OpWaveHookFailure } from "./op-waves";
29
- import type { OpWaveHookOutcome } from "./stage-hooks";
56
+ import { OP_WAVE_PENDING_RESERVED, type OpWaveHookOutcome } from "./stage-hooks";
57
+
58
+ /** The first chant whose after-plan hooks answer for the wave as a whole (`wave`), take a run's own `overriders`, and whose wave keeps the hook's report beside its pending fact (#4842). */
59
+ export const OP_WAVE_AFTER_PLAN_WAVE_FLOOR = NEXT_RELEASE;
30
60
 
31
61
  /** One planned run, as an after-plan hook in the job's process sees it (#4614). */
32
62
  export interface OpWaveAfterPlanRun {
@@ -64,6 +94,36 @@ export interface OpWaveAfterPlanResult {
64
94
  policy?: OpRunPolicyRow[];
65
95
  /** Files the hook wrote for the run, relative to the job's directory. */
66
96
  files?: string[];
97
+ /** Who may override this run's denial (#4842), in place of the wave's overriders. */
98
+ overriders?: string[];
99
+ }
100
+
101
+ /** A job's planned runs, as a hook's wave answer sees them (#4842). */
102
+ export interface OpWaveAfterPlanWave {
103
+ spec: string;
104
+ op: string;
105
+ wave: number;
106
+ waveName: string;
107
+ job: OpWaveAfterPlanRun["job"];
108
+ /** The runs the hook is for, in the wave's order, as its `run` saw each. */
109
+ runs: OpWaveAfterPlanRun[];
110
+ cwd: string;
111
+ }
112
+
113
+ /** What a hook adds to the wave as a whole (#4842). */
114
+ export interface OpWaveAfterPlanWaveResult {
115
+ /** Fields for the wave's pending fact, as a plans file's `pending`. */
116
+ pending?: Record<string, unknown>;
117
+ /** Digest members that are no run, such as the wave's cost. */
118
+ members?: WaveMember[];
119
+ /** Why the wave waits for a person whatever its gate, a line each. */
120
+ holds?: string[];
121
+ /** Who may override a denial, in place of the overriders file at base. */
122
+ overriders?: string[];
123
+ /** Where those overriders come from, for a refusal: "policy.override in terragucci.yml". */
124
+ overridersSource?: string;
125
+ /** The product's report of these plans: stored beside the pending fact, and written for the respond job after the plans moved. */
126
+ report?: string;
67
127
  }
68
128
 
69
129
  /** An after-plan hook in the wave job's process (#4614). */
@@ -75,6 +135,8 @@ export interface OpWaveAfterPlanHook {
75
135
  /** The runs it is for, as a command hook's `targets`. Default: every run. */
76
136
  targets?: string[];
77
137
  run(planned: OpWaveAfterPlanRun): OpWaveAfterPlanResult | void | Promise<OpWaveAfterPlanResult | void>;
138
+ /** Called once per job after `run` for each of its runs (#4842): what the hook adds to the wave. */
139
+ wave?(planned: OpWaveAfterPlanWave): OpWaveAfterPlanWaveResult | void | Promise<OpWaveAfterPlanWaveResult | void>;
78
140
  }
79
141
 
80
142
  const ROW_RESULTS: ReadonlyArray<OpRunPolicyRow["result"]> = ["passed", "warned", "denied", "held"];
@@ -90,6 +152,7 @@ export function opWaveAfterPlanProblems(hooks: unknown): string[] {
90
152
  if (!hook || typeof hook !== "object") return void problems.push(`${at} must be { name, run, onFailure?, targets? }`);
91
153
  if (typeof hook.name !== "string" || hook.name.trim() === "") problems.push(`${at} needs a name`);
92
154
  if (typeof hook.run !== "function") problems.push(`${at} needs a run function`);
155
+ if (hook.wave !== undefined && typeof hook.wave !== "function") problems.push(`${at}.wave must be a function`);
93
156
  if (hook.onFailure !== undefined && !OP_WAVE_HOOK_FAILURES.includes(hook.onFailure)) problems.push(`${at} has onFailure "${String(hook.onFailure)}"; use ${OP_WAVE_HOOK_FAILURES.join(" or ")}`);
94
157
  if (hook.targets !== undefined && (!Array.isArray(hook.targets) || hook.targets.length === 0 || !hook.targets.every((t) => typeof t === "string" && t !== ""))) problems.push(`${at}.targets must be a non-empty list of targets or patterns`);
95
158
  });
@@ -99,8 +162,8 @@ export function opWaveAfterPlanProblems(hooks: unknown): string[] {
99
162
  /** What is wrong with one answer of a hook, empty when nothing is. */
100
163
  export function opWaveAfterPlanResultProblems(value: unknown): string[] {
101
164
  if (value === undefined || value === null) return [];
102
- if (typeof value !== "object" || Array.isArray(value)) return ["the answer must be { policy?, files? }"];
103
- const r = value as { policy?: unknown; files?: unknown };
165
+ if (typeof value !== "object" || Array.isArray(value)) return ["the answer must be { policy?, files?, overriders? }"];
166
+ const r = value as { policy?: unknown; files?: unknown; overriders?: unknown };
104
167
  const problems: string[] = [];
105
168
  if (r.policy !== undefined) {
106
169
  if (!Array.isArray(r.policy)) problems.push("`policy` must be a list of rows");
@@ -117,6 +180,46 @@ export function opWaveAfterPlanResultProblems(value: unknown): string[] {
117
180
  if (r.files !== undefined && (!Array.isArray(r.files) || !r.files.every((f) => typeof f === "string" && f !== "" && !isAbsolute(f) && !f.split("/").includes("..")))) {
118
181
  problems.push("`files` must be paths inside the job's directory, relative to it");
119
182
  }
183
+ if (r.overriders !== undefined && !principals(r.overriders)) problems.push("`overriders` must be a list of principals");
184
+ return problems;
185
+ }
186
+
187
+ const principals = (v: unknown): v is string[] => Array.isArray(v) && v.every((p) => typeof p === "string" && p.trim() !== "");
188
+
189
+ /** What is wrong with one wave answer (#4842), empty when nothing is. `targets` are the wave's runs, which no digest member may be named. */
190
+ export function opWaveAfterPlanWaveResultProblems(value: unknown, targets: readonly string[]): string[] {
191
+ if (value === undefined || value === null) return [];
192
+ if (typeof value !== "object" || Array.isArray(value)) return ["the wave answer must be { pending?, members?, holds?, overriders?, overridersSource?, report? }"];
193
+ const r = value as Record<string, unknown>;
194
+ const problems: string[] = [];
195
+ if (r.pending !== undefined) {
196
+ const p = r.pending;
197
+ if (p === null || typeof p !== "object" || Array.isArray(p)) problems.push("`pending` must be an object of fields for the pending fact");
198
+ else {
199
+ const reserved = Object.keys(p).filter((key) => (OP_WAVE_PENDING_RESERVED as readonly string[]).includes(key));
200
+ if (reserved.length > 0) problems.push(`\`pending\` cannot set ${reserved.join(", ")}, which chant writes`);
201
+ if ("description" in p && typeof (p as { description?: unknown }).description !== "string") problems.push("`pending.description` must be a string");
202
+ }
203
+ }
204
+ if (r.overriders !== undefined && !principals(r.overriders)) problems.push("`overriders` must be a list of principals");
205
+ if (r.overridersSource !== undefined && (typeof r.overridersSource !== "string" || r.overridersSource.trim() === "")) problems.push("`overridersSource` must say where the overriders come from");
206
+ if (r.members !== undefined) {
207
+ if (!Array.isArray(r.members)) problems.push("`members` must be a list of { member, planDigest }");
208
+ else {
209
+ const seen = new Set<string>();
210
+ for (const m of r.members as Array<Partial<WaveMember> | null>) {
211
+ if (!m || typeof m.member !== "string" || m.member === "" || typeof m.planDigest !== "string" || m.planDigest === "") {
212
+ problems.push("each of `members` needs a member and a planDigest");
213
+ continue;
214
+ }
215
+ if (targets.includes(m.member)) problems.push(`member ${m.member} is also a run's target; a digest member that is no run needs a name of its own`);
216
+ else if (seen.has(m.member)) problems.push(`\`members\` names ${m.member} twice`);
217
+ seen.add(m.member);
218
+ }
219
+ }
220
+ }
221
+ if (r.holds !== undefined && !(Array.isArray(r.holds) && r.holds.every((h) => typeof h === "string" && h.trim() !== ""))) problems.push("`holds` must be a list of reasons, each a line saying why the wave waits for a person");
222
+ if (r.report !== undefined && typeof r.report !== "string") problems.push("`report` must be the report's text");
120
223
  return problems;
121
224
  }
122
225
 
@@ -125,6 +228,18 @@ export interface OpWaveAfterPlanRunOutcome {
125
228
  /** The hooks' rows, in order. */
126
229
  policy: OpRunPolicyRow[];
127
230
  files: string[];
231
+ /** Who may override its denial (#4842), when a hook named anyone: the last hook's list. */
232
+ overriders?: string[];
233
+ }
234
+
235
+ /** What the hooks' wave answers came to (#4842), each hook's in order. */
236
+ export interface OpWaveAfterPlanWaveOutcome {
237
+ pending?: Record<string, unknown>;
238
+ members: WaveMember[];
239
+ holds: string[];
240
+ overriders?: string[];
241
+ overridersSource?: string;
242
+ report?: string;
128
243
  }
129
244
 
130
245
  /** What the after-plan hooks in the job's process came to (#4614). */
@@ -136,6 +251,8 @@ export interface OpWaveAfterPlanOutcome {
136
251
  outcomes: OpWaveHookOutcome[];
137
252
  /** Each run's rows and files, by target, for the runs a hook answered. */
138
253
  runs: Map<string, OpWaveAfterPlanRunOutcome>;
254
+ /** The wave answers (#4842). */
255
+ wave: OpWaveAfterPlanWaveOutcome;
139
256
  }
140
257
 
141
258
  /**
@@ -149,9 +266,11 @@ export async function runOpWaveAfterPlanHooks(
149
266
  runs: readonly OpWaveAfterPlanRun[],
150
267
  log: (line: string) => void,
151
268
  ): Promise<OpWaveAfterPlanOutcome> {
152
- const out: OpWaveAfterPlanOutcome = { holds: [], outcomes: [], runs: new Map() };
269
+ const out: OpWaveAfterPlanOutcome = { holds: [], outcomes: [], runs: new Map(), wave: { members: [], holds: [] } };
270
+ const targets = runs.map((r) => r.target);
153
271
  for (const hook of hooks) {
154
- for (const run of opWaveHookRuns(hook, runs)) {
272
+ const mine = opWaveHookRuns(hook, runs);
273
+ for (const run of mine) {
155
274
  const label = `after-plan hook ${hook.name} (${run.target})`;
156
275
  let problem: string | undefined;
157
276
  let answer: OpWaveAfterPlanResult | void = undefined;
@@ -171,6 +290,11 @@ export async function runOpWaveAfterPlanHooks(
171
290
  for (const f of answer.files ?? []) if (!got.files.includes(f)) got.files.push(f);
172
291
  out.runs.set(run.target, got);
173
292
  }
293
+ if (answer?.overriders) {
294
+ const got = out.runs.get(run.target) ?? { policy: [], files: [] };
295
+ got.overriders = [...new Set(answer.overriders)].sort();
296
+ out.runs.set(run.target, got);
297
+ }
174
298
  continue;
175
299
  }
176
300
  if (hook.onFailure === "approve") {
@@ -184,10 +308,49 @@ export async function runOpWaveAfterPlanHooks(
184
308
  log(problem);
185
309
  return out;
186
310
  }
311
+ if (!hook.wave || mine.length === 0) continue;
312
+ // #4842: the hook's answer for the wave, once its runs were each answered.
313
+ const first = mine[0]!;
314
+ const label = `after-plan hook ${hook.name} (wave ${first.wave})`;
315
+ let problem: string | undefined;
316
+ let answer: OpWaveAfterPlanWaveResult | void = undefined;
317
+ try {
318
+ answer = await hook.wave({ spec: first.spec, op: first.op, wave: first.wave, waveName: first.waveName, job: first.job, runs: [...mine], cwd: first.cwd });
319
+ const wrong = opWaveAfterPlanWaveResultProblems(answer, targets);
320
+ if (wrong.length > 0) problem = `${label} answered with ${wrong.join("; ")}`;
321
+ } catch (err) {
322
+ problem = `${label} failed: ${err instanceof Error ? err.message : String(err)}`;
323
+ }
324
+ const base = { moment: "after-plan" as const, name: hook.name };
325
+ if (problem === undefined) {
326
+ out.outcomes.push({ ...base, exit: 0, outcome: "passed" });
327
+ if (answer) foldWaveAnswer(out.wave, answer);
328
+ continue;
329
+ }
330
+ if (hook.onFailure === "approve") {
331
+ out.outcomes.push({ ...base, exit: 1, outcome: "held" });
332
+ out.holds.push(label);
333
+ log(`${problem}, so wave ${first.wave} (${first.waveName}) waits for an approval of its set digest`);
334
+ continue;
335
+ }
336
+ out.outcomes.push({ ...base, exit: 1, outcome: "failed" });
337
+ out.failed = problem;
338
+ log(problem);
339
+ return out;
187
340
  }
188
341
  return out;
189
342
  }
190
343
 
344
+ /** Fold one hook's wave answer into what the answers so far came to: fields and lists add up, a later list of overriders or report wins. */
345
+ function foldWaveAnswer(into: OpWaveAfterPlanWaveOutcome, answer: OpWaveAfterPlanWaveResult): void {
346
+ if (answer.pending && Object.keys(answer.pending).length > 0) into.pending = { ...into.pending, ...answer.pending };
347
+ for (const m of answer.members ?? []) if (!into.members.some((x) => x.member === m.member)) into.members.push({ member: m.member, planDigest: m.planDigest });
348
+ for (const h of answer.holds ?? []) if (!into.holds.includes(h)) into.holds.push(h);
349
+ if (answer.overriders) into.overriders = [...new Set(answer.overriders)].sort();
350
+ if (answer.overridersSource) into.overridersSource = answer.overridersSource;
351
+ if (answer.report !== undefined) into.report = answer.report;
352
+ }
353
+
191
354
  /** Fold policy rows into a run's denial and hold: the rules of every `denied` row, and of every `held` row. */
192
355
  export function foldPolicyRows(
193
356
  rows: readonly OpRunPolicyRow[],
@@ -216,6 +379,8 @@ export interface ProductWaveHook {
216
379
  capabilities?: import("../components/capability").CapabilityRegistry;
217
380
  /** How the spec's command hooks run, when they call back into the product's process (`RunOpWaveOptions.hookExec`). */
218
381
  hookExec?: import("./stage-hooks").OpWaveAsyncExec;
382
+ /** Hooks around each run of a wave with a `step` (#4842, `RunOpWaveOptions.runHooks`). */
383
+ runHooks?: import("./op-waves-run-hooks").OpWaveRunHooks | readonly import("./op-waves-run-hooks").OpWaveRunHooks[];
219
384
  }
220
385
 
221
386
  let activeWave: ProductWaveHook | undefined;
@@ -62,7 +62,7 @@ export function opWaveStepProblems(spec: Pick<OpWavesSpec, "step" | "plan" | "ap
62
62
  }
63
63
  if (spec.hooks?.apply?.runBy === "apply") problems.push("`hooks.apply.runBy: \"apply\"` hands the apply-stage hooks to an apply command, and a `step` has none; leave runBy as chant");
64
64
  for (const wave of spec.waves) {
65
- if (wave.discover) problems.push(`wave "${wave.name}" discovers its runs, which only \`planWave\` can report; a \`step\` plans the runs the spec lists`);
65
+ // #4842: a step's capability finds a discovering wave's runs (`discoverRuns`), checked when the wave plans.
66
66
  if (wave.hooks?.apply?.runBy === "apply") problems.push(`wave "${wave.name}" hands its apply-stage hooks to an apply command, and a \`step\` has none`);
67
67
  for (const run of wave.runs ?? []) {
68
68
  const input = run.input as unknown;
@@ -214,4 +214,10 @@ describe("the step and holds settings (#4545)", () => {
214
214
  expect(partEffects(part("a", "delete"))).toEqual({ empty: false, destructive: true });
215
215
  expect(partEffects(undefined)).toEqual({ empty: false, destructive: false });
216
216
  });
217
+
218
+ test("a part whose plan changes only outputs is not empty (#4849)", () => {
219
+ const p = part("a", "no-op");
220
+ expect(partEffects({ ...p, member: { ...p.member, outputs: ["url"] } })).toEqual({ empty: false, destructive: false });
221
+ expect(partEffects({ ...p, member: { ...p.member, outputs: [] } })).toEqual({ empty: true, destructive: false });
222
+ });
217
223
  });