@intentius/chant 0.124.79 → 0.124.80

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 (75) hide show
  1. package/dist/ci-note-commands.d.ts +199 -0
  2. package/dist/ci-note-commands.d.ts.map +1 -0
  3. package/dist/ci-note-commands.js +372 -0
  4. package/dist/cli/handlers/build.d.ts.map +1 -1
  5. package/dist/cli/handlers/build.js +7 -1
  6. package/dist/cli/handlers/pr-notes.d.ts +13 -0
  7. package/dist/cli/handlers/pr-notes.d.ts.map +1 -0
  8. package/dist/cli/handlers/pr-notes.js +73 -0
  9. package/dist/cli/main.d.ts.map +1 -1
  10. package/dist/cli/main.js +10 -1
  11. package/dist/cli/mcp/product-tools.d.ts.map +1 -1
  12. package/dist/cli/mcp/product-tools.js +1 -2
  13. package/dist/cli/parse-args.d.ts.map +1 -1
  14. package/dist/cli/parse-args.js +10 -0
  15. package/dist/cli/registry.d.ts +4 -0
  16. package/dist/cli/registry.d.ts.map +1 -1
  17. package/dist/components/capability.d.ts +11 -0
  18. package/dist/components/capability.d.ts.map +1 -1
  19. package/dist/components/pr-pipeline.d.ts +22 -0
  20. package/dist/components/pr-pipeline.d.ts.map +1 -1
  21. package/dist/components/pr-pipeline.js +26 -0
  22. package/dist/components/product-pipeline.d.ts +12 -0
  23. package/dist/components/product-pipeline.d.ts.map +1 -1
  24. package/dist/components/product-pipeline.js +5 -1
  25. package/dist/lifecycle/release-version.d.ts.map +1 -1
  26. package/dist/lifecycle/release-version.js +1 -2
  27. package/dist/op/index.d.ts +2 -2
  28. package/dist/op/index.d.ts.map +1 -1
  29. package/dist/op/index.js +1 -1
  30. package/dist/op/op-waves-after-plan.d.ts +33 -0
  31. package/dist/op/op-waves-after-plan.d.ts.map +1 -1
  32. package/dist/op/op-waves-after-plan.js +41 -3
  33. package/dist/op/op-waves-capability.d.ts +4 -1
  34. package/dist/op/op-waves-capability.d.ts.map +1 -1
  35. package/dist/op/op-waves-capability.js +14 -14
  36. package/dist/op/op-waves-run-hooks.d.ts.map +1 -1
  37. package/dist/op/op-waves-run-hooks.js +1 -2
  38. package/dist/op/op-waves-run.d.ts.map +1 -1
  39. package/dist/op/op-waves-run.js +78 -12
  40. package/dist/pr-forge-reads.d.ts +151 -1
  41. package/dist/pr-forge-reads.d.ts.map +1 -1
  42. package/dist/pr-forge-reads.js +265 -1
  43. package/dist/release-floors.d.ts +15 -1
  44. package/dist/release-floors.d.ts.map +1 -1
  45. package/dist/release-floors.js +17 -3
  46. package/dist/wave-runtime.mjs +272 -272
  47. package/package.json +1 -1
  48. package/src/ci-note-commands.test.ts +377 -0
  49. package/src/ci-note-commands.ts +479 -0
  50. package/src/cli/handlers/build.ts +7 -1
  51. package/src/cli/handlers/pr-notes.ts +70 -0
  52. package/src/cli/main.ts +10 -1
  53. package/src/cli/mcp/product-tools.test.ts +1 -2
  54. package/src/cli/mcp/product-tools.ts +1 -2
  55. package/src/cli/parse-args.ts +8 -0
  56. package/src/cli/registry.ts +4 -0
  57. package/src/components/capability.ts +11 -0
  58. package/src/components/pr-pipeline.ts +35 -0
  59. package/src/components/product-pipeline.test.ts +14 -0
  60. package/src/components/product-pipeline.ts +13 -1
  61. package/src/lifecycle/release-version.ts +1 -2
  62. package/src/op/index.ts +2 -2
  63. package/src/op/op-waves-after-plan-wave.test.ts +2 -3
  64. package/src/op/op-waves-after-plan.ts +61 -3
  65. package/src/op/op-waves-capability.test.ts +3 -1
  66. package/src/op/op-waves-capability.ts +17 -17
  67. package/src/op/op-waves-gate-port.test.ts +232 -0
  68. package/src/op/op-waves-run-hooks.test.ts +2 -3
  69. package/src/op/op-waves-run-hooks.ts +1 -2
  70. package/src/op/op-waves-run.ts +78 -14
  71. package/src/op/op-waves-step-wave.test.ts +3 -4
  72. package/src/pr-forge-reads-compare.test.ts +145 -0
  73. package/src/pr-forge-reads.test.ts +203 -0
  74. package/src/pr-forge-reads.ts +398 -1
  75. package/src/release-floors.ts +24 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant",
3
- "version": "0.124.79",
3
+ "version": "0.124.80",
4
4
  "description": "Declarative infrastructure-as-code toolkit — TypeScript on Node.js",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://intentius.io/chant",
@@ -0,0 +1,377 @@
1
+ /**
2
+ * Comment commands on GitLab by polling merge request notes (#4785), against
3
+ * a GitLab API on loopback: who may ask, the ledger and the reply marker that
4
+ * keep a note from being answered twice, the pipeline a command starts with
5
+ * its variables, and the apply job an apply on a merged merge request retries.
6
+ * Ported from terragucci's comment-gitlab.test.ts.
7
+ */
8
+
9
+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from "vitest";
10
+ import { createServer, type Server } from "node:http";
11
+ import type { AddressInfo } from "node:net";
12
+ import { spawnSync } from "node:child_process";
13
+ import { writeFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { withTestDir } from "@intentius/chant-test-utils";
16
+ import { resolveProductWords } from "./ci-product-words";
17
+ import { gitlabForge } from "./pr-forge";
18
+ import { gitlabReads } from "./pr-forge-reads";
19
+ import {
20
+ APPLY_JOBS,
21
+ chantNoteRuns,
22
+ gitlabPipelines,
23
+ ledgerNoteLog,
24
+ memoryNoteLog,
25
+ noteCommandMarker,
26
+ pollNoteCommands,
27
+ type ChantNoteJobs,
28
+ type NoteCommandRuns,
29
+ } from "./ci-note-commands";
30
+
31
+ const NOW = new Date("2026-10-07T12:00:00Z");
32
+ const BOT = 900;
33
+ const MERGE = "a".repeat(40);
34
+ const LATER = "b".repeat(40);
35
+ const HEAD = "c".repeat(40);
36
+ const recent = (minutes: number): string => new Date(NOW.getTime() - minutes * 60_000).toISOString();
37
+ const WORDS = resolveProductWords({ product: "plywood", commands: { preview: "plan", up: "apply", lock: "lock", unlock: "unlock", agent: "agent", fmt: "commit", action: "action" }, verbs: { plan: ["preview", "previewed"], apply: ["update", "updated"] }, noun: ["stack", "stacks"] });
38
+
39
+ interface Call { method: string; path: string; body?: any }
40
+ interface World {
41
+ mrs: any[];
42
+ notes: Record<number, any[]>;
43
+ /** Access levels by user id. */
44
+ members?: Record<number, number>;
45
+ pipelines?: any[];
46
+ jobs?: Record<number, any[]>;
47
+ statuses?: Record<string, any[]>;
48
+ fail?: RegExp;
49
+ }
50
+
51
+ let server: Server;
52
+ let base = "";
53
+ let world: World;
54
+ let calls: Call[] = [];
55
+
56
+ /** A user's id is its name's length plus 100, so a note needs only a username. */
57
+ const uid = (name: string): number => 100 + name.length;
58
+ const user = (name: string) => ({ id: uid(name), username: name });
59
+
60
+ beforeAll(async () => {
61
+ server = createServer((req, res) => {
62
+ let raw = "";
63
+ req.on("data", (c) => (raw += c));
64
+ req.on("end", () => {
65
+ const url = new URL(req.url!, "http://x");
66
+ const path = url.pathname.replace(/^\/api\/v4/, "");
67
+ const method = req.method!;
68
+ const body = raw ? JSON.parse(raw) : undefined;
69
+ calls.push({ method, path: `${path}${url.search}`, body });
70
+ const send = (b: unknown, status = 200) => {
71
+ res.writeHead(status, { "content-type": "application/json" });
72
+ res.end(JSON.stringify(b));
73
+ };
74
+ if (world.fail?.test(`${method} ${path}`)) return send({ message: "boom" }, 500);
75
+ const q = url.searchParams;
76
+ // Lists are one page here.
77
+ if (Number(q.get("page") ?? "1") > 1) return send([]);
78
+ let m: RegExpExecArray | null;
79
+ if (path === "/user") return send({ id: BOT, username: "plywood-bot" });
80
+ if (path === "/users") {
81
+ const name = q.get("username")!;
82
+ return send(Object.values(world.notes).flat().some((n) => n.author?.username === name) ? [user(name)] : []);
83
+ }
84
+ if (path === "/projects/7/merge_requests") return send(world.mrs);
85
+ if ((m = /^\/projects\/7\/members\/all\/(\d+)$/.exec(path))) {
86
+ const level = world.members?.[Number(m[1])];
87
+ return level === undefined ? send({ message: "404 Not found" }, 404) : send({ access_level: level });
88
+ }
89
+ if ((m = /^\/projects\/7\/merge_requests\/(\d+)\/notes\/(\d+)$/.exec(path)) && method === "PUT") {
90
+ const n = (world.notes[Number(m[1])] ?? []).find((x) => x.id === Number(m![2]));
91
+ if (n) n.body = body.body;
92
+ return send(n ?? {});
93
+ }
94
+ if ((m = /^\/projects\/7\/merge_requests\/(\d+)\/notes$/.exec(path))) {
95
+ const iid = Number(m[1]);
96
+ if (method === "POST") {
97
+ const note = { id: 5000 + calls.length, body: body.body, system: false, author: { id: BOT, username: "plywood-bot" }, created_at: NOW.toISOString() };
98
+ (world.notes[iid] ??= []).push(note);
99
+ return send(note, 201);
100
+ }
101
+ return send(world.notes[iid] ?? []);
102
+ }
103
+ if ((m = /^\/projects\/7\/merge_requests\/(\d+)\/pipelines$/.exec(path)) && method === "POST") return send({ id: 77, web_url: "http://gitlab/acme/infra/-/pipelines/77" }, 201);
104
+ if (path === "/projects/7/pipeline" && method === "POST") return send({ id: 78, web_url: "http://gitlab/acme/infra/-/pipelines/78" }, 201);
105
+ if (path === "/projects/7/pipelines") {
106
+ const all = (world.pipelines ?? []).filter((p) => (!q.get("sha") || p.sha === q.get("sha")) && (!q.get("ref") || p.ref === q.get("ref")) && (!q.get("source") || p.source === q.get("source")));
107
+ return send([...all].sort((a, b) => b.id - a.id));
108
+ }
109
+ if ((m = /^\/projects\/7\/pipelines\/(\d+)\/jobs$/.exec(path))) return send(world.jobs?.[Number(m[1])] ?? []);
110
+ if ((m = /^\/projects\/7\/repository\/commits\/([0-9a-f]+)\/statuses$/.exec(path))) return send(world.statuses?.[m[1]!] ?? []);
111
+ if ((m = /^\/projects\/7\/jobs\/(\d+)\/retry$/.exec(path)) && method === "POST") return send({ id: 9000 + Number(m[1]), web_url: `http://gitlab/acme/infra/-/jobs/${9000 + Number(m[1])}` }, 201);
112
+ send({ message: "404 Not found" }, 404);
113
+ });
114
+ });
115
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
116
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/v4`;
117
+ });
118
+
119
+ afterAll(() => new Promise<void>((r) => server.close(() => r())));
120
+
121
+ beforeEach(() => {
122
+ calls = [];
123
+ });
124
+
125
+ const mr = (iid: number, over: Record<string, unknown> = {}) => ({ iid, state: "opened", sha: HEAD, source_branch: `feat-${iid}`, target_branch: "main", source_project_id: 7, target_project_id: 7, updated_at: recent(5), ...over });
126
+ const note = (id: number, body: string, by = "alice", over: Record<string, unknown> = {}) => ({ id, body, system: false, author: user(by), created_at: recent(10), ...over });
127
+
128
+ async function poll(w: World, o: { jobs?: ChantNoteJobs; runs?: NoteCommandRuns; log?: ReturnType<typeof memoryNoteLog>; minRole?: "developer" | "maintainer" } = {}) {
129
+ world = w;
130
+ const opts = { apiBase: base, project: "7", token: "t", host: "gitlab" };
131
+ const log = o.log ?? memoryNoteLog();
132
+ const got = await pollNoteCommands({
133
+ reads: gitlabReads(opts),
134
+ forge: gitlabForge(opts),
135
+ pipelines: gitlabPipelines(opts),
136
+ words: WORDS,
137
+ base: "main",
138
+ runs: o.runs ?? chantNoteRuns(o.jobs ?? {}),
139
+ log,
140
+ now: NOW,
141
+ ...(o.minRole ? { minRole: o.minRole } : {}),
142
+ });
143
+ return { ...got, log };
144
+ }
145
+
146
+ const posts = (what: RegExp) => calls.filter((c) => c.method === "POST" && what.test(c.path));
147
+ const replies = (w: World, iid: number) => (w.notes[iid] ?? []).filter((n) => n.author?.id === BOT).map((n) => n.body as string);
148
+
149
+ describe("pollNoteCommands: plan", () => {
150
+ test("a Developer's plan on an open merge request starts its pipeline, and the reply carries the note's marker", async () => {
151
+ const w: World = { mrs: [mr(3)], notes: { 3: [note(41, "/plywood preview")] }, members: { [uid("alice")]: 30 } };
152
+ const got = await poll(w);
153
+ expect(posts(/\/merge_requests\/3\/pipelines$/)).toHaveLength(1);
154
+ expect(got.outcomes).toMatchObject([{ mr: 3, note: 41, command: "plan", ran: true, replied: true, url: "http://gitlab/acme/infra/-/pipelines/77" }]);
155
+ expect(replies(w, 3)).toEqual([`plywood: started pipeline http://gitlab/acme/infra/-/pipelines/77 to preview !3 again for alice\n\n${noteCommandMarker("plywood", 41)}`]);
156
+ expect(got.log.outcomes.map((r) => [r.mr, r.note])).toEqual([[3, 41]]);
157
+ });
158
+
159
+ test("with the comment preview, a pipeline of the default branch starts with CHANT_PREVIEW_PR and the comment", async () => {
160
+ await poll({ mrs: [mr(3)], notes: { 3: [note(41, "/plywood preview --target aws_s3_bucket.b")] }, members: { [uid("alice")]: 30 } }, { jobs: { preview: true } });
161
+ expect(posts(/\/pipeline$/).map((c) => c.body)).toEqual([
162
+ { ref: "main", variables: [{ key: "CHANT_PREVIEW_PR", value: "3", variable_type: "env_var" }, { key: "CHANT_PREVIEW_COMMENT", value: "/plywood preview --target aws_s3_bucket.b", variable_type: "env_var" }] },
163
+ ]);
164
+ });
165
+
166
+ test("answers a note once: the ledger keeps it, and without the ledger the reply's marker does", async () => {
167
+ const w: World = { mrs: [mr(3)], notes: { 3: [note(41, "/plywood preview")] }, members: { [uid("alice")]: 30 } };
168
+ const log = memoryNoteLog();
169
+ await poll(w, { log });
170
+ calls = [];
171
+ expect((await poll(w, { log })).outcomes).toEqual([]);
172
+ expect(posts(/pipelines?$/)).toEqual([]);
173
+ // A fresh ledger still finds the job's reply.
174
+ expect((await poll(w)).outcomes).toEqual([]);
175
+ expect(posts(/pipelines?$/)).toEqual([]);
176
+ });
177
+
178
+ test("counts only the job's own marker: one a person wrote answers nothing", async () => {
179
+ const w: World = { mrs: [mr(3)], notes: { 3: [note(41, "/plywood preview"), note(42, noteCommandMarker("plywood", 41), "mallory")] }, members: { [uid("alice")]: 30 } };
180
+ expect((await poll(w)).outcomes.map((o) => [o.note, o.ran])).toEqual([[41, true]]);
181
+ });
182
+
183
+ test("a Reporter, or someone who is not a member, gets no reply and nothing runs, and the note is recorded", async () => {
184
+ const w: World = { mrs: [mr(3)], notes: { 3: [note(41, "/plywood preview", "rita"), note(42, "/plywood preview", "nobody")] }, members: { [uid("rita")]: 20 } };
185
+ const got = await poll(w);
186
+ expect(got.outcomes.map((o) => [o.note, o.ran, o.replied, o.reason])).toEqual([
187
+ [41, false, false, "rita is reporter on the project, below developer, so the note is ignored"],
188
+ [42, false, false, "nobody is not a member of the project, so the note is ignored"],
189
+ ]);
190
+ expect(replies(w, 3)).toEqual([]);
191
+ expect(got.log.outcomes).toHaveLength(2);
192
+ expect(posts(/pipelines?$/)).toEqual([]);
193
+ });
194
+
195
+ test("minRole raises the bar", async () => {
196
+ const w: World = { mrs: [mr(3)], notes: { 3: [note(41, "/plywood preview")] }, members: { [uid("alice")]: 30 } };
197
+ expect((await poll(w, { minRole: "maintainer" })).outcomes[0]).toMatchObject({ ran: false, replied: false });
198
+ });
199
+
200
+ test("refuses a fork's merge request and a closed one", async () => {
201
+ const w: World = { mrs: [mr(3, { source_project_id: 99 }), mr(4, { state: "closed" })], notes: { 3: [note(41, "/plywood preview")], 4: [note(51, "/plywood preview")] }, members: { [uid("alice")]: 30 } };
202
+ const got = await poll(w);
203
+ expect(got.outcomes.map((o) => [o.mr, o.ran, o.reason])).toEqual([
204
+ [3, false, "a merge request from a fork runs no command: its code never runs with this project's credentials"],
205
+ [4, false, "!4 is not open, so it is not previewed"],
206
+ ]);
207
+ expect(posts(/pipelines?$/)).toEqual([]);
208
+ });
209
+
210
+ test("leaves notes alone that are not commands, system notes, the job's own, and notes older than the window", async () => {
211
+ const w: World = {
212
+ mrs: [mr(3)],
213
+ notes: { 3: [note(41, "looks good"), note(42, "/plywood preview", "alice", { system: true }), note(43, "/plywood preview", "alice", { created_at: recent(25 * 60) }), note(44, "/plywood preview", "plywood-bot", { author: { id: BOT, username: "plywood-bot" } })] },
214
+ members: { [uid("alice")]: 30 },
215
+ };
216
+ expect((await poll(w)).outcomes).toEqual([]);
217
+ });
218
+
219
+ test("answers refused commands with the reason, and commands with no job as unsupported", async () => {
220
+ const w: World = {
221
+ mrs: [mr(3)],
222
+ notes: { 3: [note(41, "/plywood destroy"), note(42, "/plywood lock"), note(43, "/plywood agent fix it"), note(44, "/plywood fmt"), note(45, "/plywood action apps/a rotate")] },
223
+ members: { [uid("alice")]: 30 },
224
+ };
225
+ const got = await poll(w);
226
+ expect(got.outcomes.map((o) => [o.note, o.ran, o.replied])).toEqual([41, 42, 43, 44, 45].map((n) => [n, false, true]));
227
+ expect(got.outcomes.map((o) => o.reason)).toEqual([
228
+ "a comment never runs `destroy`: plywood re-plans, and runs what an approval covers, on request and nothing more",
229
+ "`/plywood lock` does not run here: this project takes no locks",
230
+ "the agent command is off in this project",
231
+ "`/plywood fmt` does not run here",
232
+ "`/plywood action` does not run from a merge request note on GitLab: run `plywood action apps/a rotate` from a checkout of the default branch",
233
+ ]);
234
+ expect(posts(/pipelines?$/)).toEqual([]);
235
+ });
236
+
237
+ test("fails the poll when GitLab will not list the merge requests, and a member check that breaks fails the note, which is read again", async () => {
238
+ expect((await poll({ mrs: [], notes: {}, fail: /GET \/projects\/7\/merge_requests$/ })).fail).toMatch(/^could not list the merge requests/);
239
+ const got = await poll({ mrs: [mr(3)], notes: { 3: [note(41, "/plywood preview")] }, fail: /members/ });
240
+ expect(got.outcomes[0]).toMatchObject({ ran: false, replied: false, fail: true });
241
+ expect(got.log.outcomes).toEqual([]);
242
+ });
243
+ });
244
+
245
+ describe("pollNoteCommands: the jobs a command starts", () => {
246
+ const members = { [uid("alice")]: 30 };
247
+ const started = () => posts(/\/pipeline$/).map((c) => Object.fromEntries((c.body.variables as { key: string; value: string }[]).map((v) => [v.key, v.value])));
248
+
249
+ test("an apply before merge, a lock, an unlock, the agent and a commit job each start a pipeline of the default branch with their variables", async () => {
250
+ const w: World = {
251
+ mrs: [mr(3)],
252
+ notes: { 3: [note(41, "/plywood up"), note(42, "/plywood lock"), note(43, "/plywood unlock"), note(44, "/plywood agent fix the bucket"), note(45, "/plywood fmt")] },
253
+ members,
254
+ };
255
+ const got = await poll(w, { jobs: { applyBeforeMerge: true, locks: true, agent: true, commits: true } });
256
+ expect(got.outcomes.every((o) => o.ran && o.replied)).toBe(true);
257
+ expect(started()).toEqual([{ CHANT_APPLY_PR: "3" }, { CHANT_LOCK_PR: "3" }, { CHANT_UNLOCK_PR: "3" }, { CHANT_AGENT_PR: "3", CHANT_AGENT_ASK: "fix the bucket" }, { CHANT_COMMIT_PR: "3", CHANT_COMMIT: "fmt" }]);
258
+ expect(posts(/\/pipeline$/).every((c) => c.body.ref === "main")).toBe(true);
259
+ expect(got.outcomes[0]!.reason).toBe(`started pipeline http://gitlab/acme/infra/-/pipelines/78 on main to update !3's head ${HEAD.slice(0, 8)} for alice`);
260
+ });
261
+
262
+ test("a product's own runs: its variables, and its refusal", async () => {
263
+ const runs: NoteCommandRuns = ({ mr: m, note: n, parsed }) =>
264
+ parsed.kind === "apply" ? { kind: "pipeline", ref: "main", variables: { TERRAGUCCI_MR: String(m.number), TERRAGUCCI_NOTE: String(n.id), TERRAGUCCI_HEAD: m.headSha! }, doing: "apply it" } : { kind: "reply", text: "no" };
265
+ const w: World = { mrs: [mr(3)], notes: { 3: [note(41, "/plywood up"), note(42, "/plywood preview")] }, members };
266
+ const got = await poll(w, { runs });
267
+ expect(started()).toEqual([{ TERRAGUCCI_MR: "3", TERRAGUCCI_NOTE: "41", TERRAGUCCI_HEAD: HEAD }]);
268
+ expect(got.outcomes.map((o) => o.reason)).toEqual(["started pipeline http://gitlab/acme/infra/-/pipelines/78 on main to apply it for alice", "no"]);
269
+ });
270
+
271
+ test("a pipeline GitLab will not start fails the note, which is read again", async () => {
272
+ const got = await poll({ mrs: [mr(3)], notes: { 3: [note(41, "/plywood lock")] }, members, fail: /POST \/projects\/7\/pipeline$/ }, { jobs: { locks: true } });
273
+ expect(got.outcomes[0]).toMatchObject({ ran: false, replied: false, fail: true });
274
+ expect(got.outcomes[0]!.reason).toMatch(/^could not start a pipeline on main for !3/);
275
+ expect(got.log.outcomes).toEqual([]);
276
+ });
277
+ });
278
+
279
+ describe("pollNoteCommands: apply on a merged merge request", () => {
280
+ const members = { [uid("alice")]: 30, [uid("rita")]: 20 };
281
+ const merged = (over: Record<string, unknown> = {}) => mr(3, { state: "merged", merge_commit_sha: MERGE, ...over });
282
+ const jobs = { applyOnMerge: true };
283
+ const pipelines = [{ id: 10, sha: MERGE, ref: "main", source: "push", status: "failed" }];
284
+ const applyJobs = { 10: [{ id: 1, name: "plan", status: "success" }, { id: 2, name: "apply-wave-1", status: "success" }, { id: 4, name: "apply-wave-2-share-2", status: "failed" }, { id: 3, name: "apply-wave-2", status: "failed" }] };
285
+
286
+ test("retries the first apply job of the merge commit's pipeline that did not succeed", async () => {
287
+ const got = await poll({ mrs: [merged()], notes: { 3: [note(41, "/plywood up")] }, members, pipelines, jobs: applyJobs }, { jobs });
288
+ expect(posts(/\/jobs\/\d+\/retry$/).map((c) => c.path)).toEqual(["/projects/7/jobs/3/retry"]);
289
+ expect(got.outcomes[0]).toMatchObject({ ran: true, replied: true, url: "http://gitlab/acme/infra/-/jobs/9003" });
290
+ expect(got.outcomes[0]!.reason).toBe(`retried apply-wave-2 of !3's merge commit ${MERGE.slice(0, 8)} (http://gitlab/acme/infra/-/jobs/9003) for alice; its gate decides again, and the jobs after it follow, each behind its own gate`);
291
+ });
292
+
293
+ test("takes the squash commit, or the head of a fast-forward merge, when there is no merge commit", async () => {
294
+ await poll({ mrs: [merged({ merge_commit_sha: null, squash_commit_sha: LATER })], notes: { 3: [note(41, "/plywood up")] }, members, pipelines: [{ id: 11, sha: LATER, ref: "main", source: "push" }], jobs: { 11: applyJobs[10] } }, { jobs });
295
+ expect(posts(/\/retry$/)).toHaveLength(1);
296
+ expect(calls.some((c) => c.path.includes(`sha=${LATER}`))).toBe(true);
297
+ });
298
+
299
+ test("refuses an open merge request, a closed one, a named wave and one merged elsewhere, and retries nothing", async () => {
300
+ const w: World = {
301
+ mrs: [mr(2), mr(4, { state: "closed" }), merged(), mr(5, { state: "merged", merge_commit_sha: MERGE, target_branch: "release" })],
302
+ notes: { 2: [note(21, "/plywood up")], 4: [note(41, "/plywood up")], 3: [note(32, "/plywood up wave-2")], 5: [note(51, "/plywood up")] },
303
+ members,
304
+ pipelines,
305
+ jobs: applyJobs,
306
+ };
307
+ const got = await poll(w, { jobs });
308
+ expect(got.outcomes.map((o) => o.reason)).toEqual([
309
+ "!2 is not merged, and this project updates after a merge request merges, never from its branch",
310
+ "!4 was closed without merging, so there is nothing of it to update",
311
+ "GitLab runs the waves after a retried apply job by itself, so `wave-2` cannot stop them; write `/plywood up`, and each wave still waits behind its own gate",
312
+ "!5 was merged into release, not the default branch main, so nothing applies from it",
313
+ ]);
314
+ expect(posts(/\/retry$/)).toEqual([]);
315
+ });
316
+
317
+ test("refuses a merge commit a later apply superseded, naming that run", async () => {
318
+ const w: World = {
319
+ mrs: [merged()],
320
+ notes: { 3: [note(41, "/plywood up")] },
321
+ members,
322
+ pipelines: [...pipelines, { id: 12, sha: LATER, ref: "main", source: "push" }],
323
+ jobs: applyJobs,
324
+ statuses: { [LATER]: [{ id: 1, name: "plywood/apply", status: "success", target_url: "http://gitlab/acme/infra/-/pipelines/12" }] },
325
+ };
326
+ const got = await poll(w, { jobs });
327
+ expect(got.outcomes[0]!.reason).toBe(`a later apply already ran on main at ${LATER.slice(0, 8)} (http://gitlab/acme/infra/-/pipelines/12), so the merge commit ${MERGE.slice(0, 8)} of !3 is not applied: comment on the merge request that commit came from, or push again`);
328
+ expect(posts(/\/retry$/)).toEqual([]);
329
+ });
330
+
331
+ test("says so when every apply job succeeded, one is still running, or no pipeline ran at the merge commit", async () => {
332
+ const done = await poll({ mrs: [merged()], notes: { 3: [note(41, "/plywood up")] }, members, pipelines, jobs: { 10: [{ id: 2, name: "apply-wave-1", status: "success" }] } }, { jobs });
333
+ expect(done.outcomes[0]!.reason).toBe(`every apply job of !3's merge commit ${MERGE.slice(0, 8)} already succeeded`);
334
+ const running = await poll({ mrs: [merged()], notes: { 3: [note(41, "/plywood up")] }, members, pipelines, jobs: { 10: [{ id: 2, name: "apply", status: "running" }] } }, { jobs });
335
+ expect(running.outcomes[0]!.reason).toBe(`apply at ${MERGE.slice(0, 8)} is running already, so it is not retried`);
336
+ const none = await poll({ mrs: [merged()], notes: { 3: [note(41, "/plywood up")] }, members, pipelines: [] }, { jobs });
337
+ expect(none.outcomes[0]!.reason).toBe(`no pipeline at the merge commit ${MERGE.slice(0, 8)} of !3 has an apply job, so there is nothing to retry; push to main again`);
338
+ expect(posts(/\/retry$/)).toEqual([]);
339
+ });
340
+
341
+ test("a Reporter's apply retries nothing and gets no reply", async () => {
342
+ const w: World = { mrs: [merged()], notes: { 3: [note(41, "/plywood up", "rita")] }, members, pipelines, jobs: applyJobs };
343
+ expect((await poll(w, { jobs })).outcomes[0]).toMatchObject({ ran: false, replied: false });
344
+ expect(posts(/\/retry$/)).toEqual([]);
345
+ expect(replies(w, 3)).toEqual([]);
346
+ });
347
+
348
+ test("the apply jobs: chant's, a member's and terragucci's shares", () => {
349
+ for (const name of ["apply", "apply-wave-3", "api-apply-wave-1", "apply-wave-2-share-4"]) expect(APPLY_JOBS.test(name)).toBe(true);
350
+ for (const name of ["plan", "comment-preview", "apply-wave-0", "applying"]) expect(APPLY_JOBS.test(name)).toBe(false);
351
+ });
352
+ });
353
+
354
+ describe("ledgerNoteLog", () => {
355
+ const git = (dir: string, ...args: string[]): void => {
356
+ const r = spawnSync("git", args, { cwd: dir, encoding: "utf-8" });
357
+ if (r.status !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr}`);
358
+ };
359
+
360
+ test("records an answered note as _notes/<mr>-<note>.json on chant/lifecycle", async () => {
361
+ await withTestDir(async (dir) => {
362
+ git(dir, "init", "-q", "-b", "main");
363
+ git(dir, "config", "user.email", "test@chant.dev");
364
+ git(dir, "config", "user.name", "Test");
365
+ writeFileSync(join(dir, "README.md"), "x\n");
366
+ git(dir, "add", ".");
367
+ git(dir, "commit", "-q", "-m", "init");
368
+ const log = ledgerNoteLog({ cwd: dir, push: false });
369
+ expect(await log.answered(3, 41)).toBe(false);
370
+ await log.record({ mr: 3, note: 41, ran: true, replied: true, reason: "started", at: NOW.toISOString() });
371
+ expect(await log.answered(3, 41)).toBe(true);
372
+ expect(await log.answered(3, 42)).toBe(false);
373
+ const shown = spawnSync("git", ["show", "chant/lifecycle:_notes/3-41.json"], { cwd: dir, encoding: "utf-8" });
374
+ expect(JSON.parse(shown.stdout)).toMatchObject({ mr: 3, note: 41, ran: true });
375
+ });
376
+ });
377
+ });