@intentius/chant 0.124.89 → 0.124.91

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 (185) hide show
  1. package/dist/actor.d.ts +5 -3
  2. package/dist/actor.d.ts.map +1 -1
  3. package/dist/actor.js +7 -5
  4. package/dist/audit/core.d.ts.map +1 -1
  5. package/dist/audit/core.js +11 -1
  6. package/dist/ci-comment-commands.d.ts +18 -2
  7. package/dist/ci-comment-commands.d.ts.map +1 -1
  8. package/dist/ci-comment-commands.js +30 -2
  9. package/dist/ci-job-guard.d.ts +42 -45
  10. package/dist/ci-job-guard.d.ts.map +1 -1
  11. package/dist/ci-job-guard.js +206 -3
  12. package/dist/ci-note-commands.d.ts +41 -1
  13. package/dist/ci-note-commands.d.ts.map +1 -1
  14. package/dist/ci-note-commands.js +64 -5
  15. package/dist/ci-product.d.ts +50 -1
  16. package/dist/ci-product.d.ts.map +1 -1
  17. package/dist/ci-product.js +52 -6
  18. package/dist/cli/handlers/pr-comment.d.ts +13 -1
  19. package/dist/cli/handlers/pr-comment.d.ts.map +1 -1
  20. package/dist/cli/handlers/pr-comment.js +90 -1
  21. package/dist/cli/handlers/pr-notes.d.ts.map +1 -1
  22. package/dist/cli/handlers/pr-notes.js +23 -1
  23. package/dist/cli/handlers/pr.d.ts +2 -2
  24. package/dist/cli/handlers/pr.d.ts.map +1 -1
  25. package/dist/cli/handlers/pr.js +41 -20
  26. package/dist/cli/handlers/run-wave.d.ts.map +1 -1
  27. package/dist/cli/handlers/run-wave.js +154 -4
  28. package/dist/cli/main.d.ts.map +1 -1
  29. package/dist/cli/main.js +17 -0
  30. package/dist/cli/parse-args.d.ts.map +1 -1
  31. package/dist/cli/parse-args.js +28 -0
  32. package/dist/cli/registry.d.ts +12 -1
  33. package/dist/cli/registry.d.ts.map +1 -1
  34. package/dist/components/pr-checks.d.ts +39 -1
  35. package/dist/components/pr-checks.d.ts.map +1 -1
  36. package/dist/components/pr-checks.js +45 -2
  37. package/dist/components/pr-pipeline.d.ts +11 -3
  38. package/dist/components/pr-pipeline.d.ts.map +1 -1
  39. package/dist/components/pr-pipeline.js +20 -7
  40. package/dist/components/product-pipeline.d.ts +54 -2
  41. package/dist/components/product-pipeline.d.ts.map +1 -1
  42. package/dist/components/product-pipeline.js +63 -6
  43. package/dist/components/product-plan.d.ts +92 -2
  44. package/dist/components/product-plan.d.ts.map +1 -1
  45. package/dist/components/product-plan.js +172 -22
  46. package/dist/floor-table.data.d.ts.map +1 -1
  47. package/dist/floor-table.data.js +37 -23
  48. package/dist/lexicon-module.d.ts +2 -0
  49. package/dist/lexicon-module.d.ts.map +1 -1
  50. package/dist/lexicon-module.js +6 -2
  51. package/dist/lexicon.d.ts +82 -4
  52. package/dist/lexicon.d.ts.map +1 -1
  53. package/dist/lifecycle/gate-applied.d.ts +9 -0
  54. package/dist/lifecycle/gate-applied.d.ts.map +1 -1
  55. package/dist/op/apply-status.d.ts +84 -0
  56. package/dist/op/apply-status.d.ts.map +1 -0
  57. package/dist/op/apply-status.js +106 -0
  58. package/dist/op/before-merge-decide.d.ts +102 -0
  59. package/dist/op/before-merge-decide.d.ts.map +1 -0
  60. package/dist/op/before-merge-decide.js +142 -0
  61. package/dist/op/before-merge-done.d.ts +56 -0
  62. package/dist/op/before-merge-done.d.ts.map +1 -0
  63. package/dist/op/before-merge-done.js +69 -0
  64. package/dist/op/before-merge-store.d.ts +20 -0
  65. package/dist/op/before-merge-store.d.ts.map +1 -0
  66. package/dist/op/before-merge-store.js +48 -0
  67. package/dist/op/before-merge.d.ts +150 -0
  68. package/dist/op/before-merge.d.ts.map +1 -0
  69. package/dist/op/before-merge.js +207 -0
  70. package/dist/op/follow-on-run.d.ts +117 -0
  71. package/dist/op/follow-on-run.d.ts.map +1 -0
  72. package/dist/op/follow-on-run.js +154 -0
  73. package/dist/op/follow-on-store.d.ts +17 -0
  74. package/dist/op/follow-on-store.d.ts.map +1 -0
  75. package/dist/op/follow-on-store.js +54 -0
  76. package/dist/op/gate.d.ts +6 -0
  77. package/dist/op/gate.d.ts.map +1 -1
  78. package/dist/op/gate.js +10 -1
  79. package/dist/op/index.d.ts +3 -1
  80. package/dist/op/index.d.ts.map +1 -1
  81. package/dist/op/index.js +1 -0
  82. package/dist/op/op-waves-after-plan.d.ts +13 -0
  83. package/dist/op/op-waves-after-plan.d.ts.map +1 -1
  84. package/dist/op/op-waves-evidence-jobs.d.ts +4 -1
  85. package/dist/op/op-waves-evidence-jobs.d.ts.map +1 -1
  86. package/dist/op/op-waves-evidence-jobs.js +10 -2
  87. package/dist/op/op-waves-follow-on.d.ts +162 -0
  88. package/dist/op/op-waves-follow-on.d.ts.map +1 -0
  89. package/dist/op/op-waves-follow-on.js +355 -0
  90. package/dist/op/op-waves-run.d.ts +146 -6
  91. package/dist/op/op-waves-run.d.ts.map +1 -1
  92. package/dist/op/op-waves-run.js +871 -99
  93. package/dist/op/op-waves-split.d.ts +122 -0
  94. package/dist/op/op-waves-split.d.ts.map +1 -0
  95. package/dist/op/op-waves-split.js +166 -0
  96. package/dist/op/op-waves.d.ts +20 -0
  97. package/dist/op/op-waves.d.ts.map +1 -1
  98. package/dist/op/op-waves.js +15 -1
  99. package/dist/op/schedule-overdue.d.ts +15 -1
  100. package/dist/op/schedule-overdue.d.ts.map +1 -1
  101. package/dist/op/schedule-overdue.js +18 -2
  102. package/dist/op/stage-hooks.d.ts +36 -1
  103. package/dist/op/stage-hooks.d.ts.map +1 -1
  104. package/dist/op/stage-hooks.js +17 -3
  105. package/dist/op/wave-stop.d.ts +4 -1
  106. package/dist/op/wave-stop.d.ts.map +1 -1
  107. package/dist/op/wave-stop.js +4 -2
  108. package/dist/planned-files.d.ts +16 -8
  109. package/dist/planned-files.d.ts.map +1 -1
  110. package/dist/planned-files.js +12 -8
  111. package/dist/pr-post.d.ts +6 -0
  112. package/dist/pr-post.d.ts.map +1 -1
  113. package/dist/pr-post.js +7 -5
  114. package/dist/release-floors.d.ts +9 -1
  115. package/dist/release-floors.d.ts.map +1 -1
  116. package/dist/release-floors.js +27 -19
  117. package/dist/wave-blocked.d.ts +7 -1
  118. package/dist/wave-blocked.d.ts.map +1 -1
  119. package/dist/wave-blocked.js +7 -2
  120. package/dist/wave-runtime.mjs +364 -351
  121. package/package.json +1 -1
  122. package/src/actor.test.ts +14 -1
  123. package/src/actor.ts +8 -6
  124. package/src/audit/core.ts +13 -1
  125. package/src/audit/first-load.test.ts +101 -0
  126. package/src/ci-comment-commands.test.ts +63 -0
  127. package/src/ci-comment-commands.ts +43 -4
  128. package/src/ci-image.test.ts +1 -2
  129. package/src/ci-job-guard.before-merge.test.ts +148 -0
  130. package/src/ci-job-guard.follow-on-record.test.ts +137 -0
  131. package/src/ci-job-guard.follow-on.test.ts +144 -0
  132. package/src/ci-job-guard.ts +221 -3
  133. package/src/ci-note-commands.test.ts +76 -1
  134. package/src/ci-note-commands.ts +96 -7
  135. package/src/ci-product.ts +65 -6
  136. package/src/cli/handlers/pr-comment.ts +85 -2
  137. package/src/cli/handlers/pr-notes.ts +30 -6
  138. package/src/cli/handlers/pr.ts +34 -17
  139. package/src/cli/handlers/run-wave.ts +144 -4
  140. package/src/cli/main.ts +17 -0
  141. package/src/cli/parse-args.ts +20 -0
  142. package/src/cli/registry.ts +12 -1
  143. package/src/components/pr-checks.ts +66 -2
  144. package/src/components/pr-pipeline.ts +21 -9
  145. package/src/components/product-pipeline.apply-status.test.ts +50 -0
  146. package/src/components/product-pipeline.ts +117 -9
  147. package/src/components/product-plan-names.test.ts +135 -0
  148. package/src/components/product-plan.test.ts +23 -5
  149. package/src/components/product-plan.ts +248 -25
  150. package/src/floor-table.data.ts +37 -23
  151. package/src/lexicon-module.ts +6 -2
  152. package/src/lexicon.ts +78 -1
  153. package/src/lifecycle/gate-applied.ts +7 -0
  154. package/src/op/apply-status.test.ts +83 -0
  155. package/src/op/apply-status.ts +132 -0
  156. package/src/op/before-merge-decide.ts +190 -0
  157. package/src/op/before-merge-done.ts +99 -0
  158. package/src/op/before-merge-store.ts +44 -0
  159. package/src/op/before-merge.test.ts +201 -0
  160. package/src/op/before-merge.ts +266 -0
  161. package/src/op/follow-on-run.ts +206 -0
  162. package/src/op/follow-on-store.ts +54 -0
  163. package/src/op/gate.ts +16 -1
  164. package/src/op/index.ts +5 -0
  165. package/src/op/op-waves-after-plan.ts +13 -0
  166. package/src/op/op-waves-evidence-jobs.ts +11 -3
  167. package/src/op/op-waves-follow-on-record.test.ts +152 -0
  168. package/src/op/op-waves-follow-on.test.ts +247 -0
  169. package/src/op/op-waves-follow-on.ts +385 -0
  170. package/src/op/op-waves-render-spec.test.ts +1 -2
  171. package/src/op/op-waves-run.ts +971 -93
  172. package/src/op/op-waves-split-product.test.ts +288 -0
  173. package/src/op/op-waves-split-step.test.ts +298 -0
  174. package/src/op/op-waves-split.test.ts +196 -0
  175. package/src/op/op-waves-split.ts +189 -0
  176. package/src/op/op-waves.ts +28 -3
  177. package/src/op/schedule-overdue.test.ts +29 -1
  178. package/src/op/schedule-overdue.ts +27 -3
  179. package/src/op/stage-hooks.ts +52 -4
  180. package/src/op/wave-stop.ts +5 -3
  181. package/src/planned-files.test.ts +33 -0
  182. package/src/planned-files.ts +26 -10
  183. package/src/pr-post.ts +13 -5
  184. package/src/release-floors.ts +31 -19
  185. package/src/wave-blocked.ts +9 -4
@@ -26,7 +26,9 @@ import {
26
26
  pollNoteCommands,
27
27
  type ChantNoteJobs,
28
28
  type NoteCommandRuns,
29
+ type NoteCommandsOptions,
29
30
  } from "./ci-note-commands";
31
+ import { beforeMergeDigest } from "./op/before-merge";
30
32
 
31
33
  const NOW = new Date("2026-10-07T12:00:00Z");
32
34
  const BOT = 900;
@@ -125,7 +127,7 @@ beforeEach(() => {
125
127
  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
128
  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
129
 
128
- async function poll(w: World, o: { jobs?: ChantNoteJobs; runs?: NoteCommandRuns; log?: ReturnType<typeof memoryNoteLog>; minRole?: "developer" | "maintainer" } = {}) {
130
+ async function poll(w: World, o: { jobs?: ChantNoteJobs; runs?: NoteCommandRuns; log?: ReturnType<typeof memoryNoteLog>; minRole?: "developer" | "maintainer"; stops?: NoteCommandsOptions["stops"] } = {}) {
129
131
  world = w;
130
132
  const opts = { apiBase: base, project: "7", token: "t", host: "gitlab" };
131
133
  const log = o.log ?? memoryNoteLog();
@@ -139,6 +141,7 @@ async function poll(w: World, o: { jobs?: ChantNoteJobs; runs?: NoteCommandRuns;
139
141
  log,
140
142
  now: NOW,
141
143
  ...(o.minRole ? { minRole: o.minRole } : {}),
144
+ ...(o.stops ? { stops: o.stops } : {}),
142
145
  });
143
146
  return { ...got, log };
144
147
  }
@@ -351,6 +354,78 @@ describe("pollNoteCommands: apply on a merged merge request", () => {
351
354
  });
352
355
  });
353
356
 
357
+ describe("pollNoteCommands: the waves' stop and the waves before merge (#4984)", () => {
358
+ const members = { [uid("alice")]: 30 };
359
+ const pipelines = [{ id: 10, sha: MERGE, ref: "main", source: "push", status: "failed" }];
360
+ const applyJobs = { 10: [{ id: 2, name: "apply-wave-1", status: "success" }, { id: 3, name: "apply-wave-2", status: "failed" }] };
361
+ const waves = { op: "deploy", count: 3 };
362
+
363
+ test("a merged merge request's wave-<n> writes the stop for the merge commit before the retry, and an apply without one clears it", async () => {
364
+ const stops: unknown[] = [];
365
+ const stopsFn: NoteCommandsOptions["stops"] = async (op, sha, stop) => void stops.push([op, sha, stop && { through: stop.through, by: stop.by, pr: stop.pr }]);
366
+ const w: World = { mrs: [mr(3, { state: "merged", merge_commit_sha: MERGE })], notes: { 3: [note(41, "/plywood up wave-2")] }, members, pipelines, jobs: applyJobs };
367
+ const got = await poll(w, { jobs: { applyOnMerge: true, waves }, stops: stopsFn });
368
+ expect(stops).toEqual([["deploy", MERGE, { through: 2, by: "alice", pr: 3 }]]);
369
+ expect(posts(/\/retry$/)).toHaveLength(1);
370
+ expect(got.outcomes[0]!.reason).toMatch(/; it stops after `wave-2`, and the waves after it wait until `\/plywood up` runs it again$/);
371
+ await poll({ ...w, notes: { 3: [note(42, "/plywood up")] } }, { jobs: { applyOnMerge: true, waves }, stops: stopsFn });
372
+ expect(stops.at(-1)).toEqual(["deploy", MERGE, null]);
373
+ // A wave the waves do not have is refused before anything is written.
374
+ const over = await poll({ ...w, notes: { 3: [note(43, "/plywood up wave-4")] } }, { jobs: { applyOnMerge: true, waves }, stops: stopsFn });
375
+ expect(over.outcomes[0]!.reason).toBe("the update of this project runs in 3 waves, so there is no `wave-4`");
376
+ expect(stops).toHaveLength(2);
377
+ });
378
+
379
+ test("an open merge request's apply is decided, recorded, and started as a pipeline of the default branch with the decision's variables", async () => {
380
+ await withTestDir(async (dir) => {
381
+ const git = (...args: string[]) => {
382
+ const r = spawnSync("git", args, { cwd: dir, encoding: "utf-8", env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } });
383
+ if (r.status !== 0) throw new Error(r.stderr);
384
+ return r.stdout.trim();
385
+ };
386
+ // The default branch and the merge request's head ref, in one repository that is its own origin.
387
+ git("init", "-q", "-b", "main");
388
+ writeFileSync(join(dir, "main.tf"), "1");
389
+ git("add", ".");
390
+ git("commit", "-q", "-m", "base");
391
+ git("checkout", "-q", "-b", "feat-3");
392
+ writeFileSync(join(dir, "main.tf"), "2");
393
+ git("commit", "-q", "-am", "head");
394
+ const head = git("rev-parse", "HEAD");
395
+ git("update-ref", "refs/merge-requests/3/head", head);
396
+ git("checkout", "-q", "main");
397
+ git("remote", "add", "origin", dir);
398
+ const recorded: unknown[] = [];
399
+ const runs = chantNoteRuns(
400
+ { applyOnMerge: true, waves, wavesBeforeMerge: { plan: ["plywood/preview"], pipelineFiles: [".gitlab-ci.yml"] } },
401
+ {
402
+ beforeMerge: {
403
+ requires: async () => null,
404
+ statuses: async () => [{ context: "plywood/preview", state: "success" }],
405
+ git: (argv, o) => {
406
+ const r = spawnSync(argv[0]!, argv.slice(1), { encoding: "utf8", ...(o.cwd ? { cwd: o.cwd } : {}) });
407
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
408
+ },
409
+ cwd: dir,
410
+ record: async (d) => (recorded.push(d), { ...d, digest: beforeMergeDigest("deploy", d) }),
411
+ stop: async () => {},
412
+ now: () => NOW.toISOString(),
413
+ },
414
+ },
415
+ );
416
+ const w: World = { mrs: [mr(3, { sha: head })], notes: { 3: [note(41, "/plywood up")] }, members };
417
+ const got = await poll(w, { runs });
418
+ const started = posts(/^\/projects\/7\/pipeline$/);
419
+ expect(started).toHaveLength(1);
420
+ const vars = Object.fromEntries((started[0]!.body as { variables: Array<{ key: string; value: string }> }).variables.map((v) => [v.key, v.value]));
421
+ const decision = { pr: 3, head, base: git("rev-parse", "main"), at: NOW.toISOString(), by: "alice" };
422
+ expect(recorded).toEqual([decision]);
423
+ expect(vars).toEqual({ CHANT_BEFORE_MERGE_PR: "3", CHANT_BEFORE_MERGE_HEAD: head, CHANT_BEFORE_MERGE_DIGEST: beforeMergeDigest("deploy", decision) });
424
+ 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)} before it merges for alice`);
425
+ });
426
+ });
427
+ });
428
+
354
429
  describe("ledgerNoteLog", () => {
355
430
  const git = (dir: string, ...args: string[]): void => {
356
431
  const r = spawnSync("git", args, { cwd: dir, encoding: "utf-8" });
@@ -34,6 +34,7 @@ import { commandLine, commentTerms, forkReply, memberReply, notRunReply } from "
34
34
  import { GITLAB_APPLY_PR_VAR, GITLAB_LOCK_PR_VAR, GITLAB_PREVIEW_PR_VAR, GITLAB_UNLOCK_PR_VAR, PREVIEW_COMMENT_ENV } from "./components/pr-pipeline";
35
35
  import { ForgeApiError, type ForgeFetch, type ForgeKind, type GitlabForgeOptions, type PrForge } from "./pr-forge";
36
36
  import type { ForgeReads, PullRequestDetail, PullRequestNote, RunJob, WorkflowRun } from "./pr-forge-reads";
37
+ import type { DecideBeforeMergeInput, WavesBeforeMergeJobs } from "./op/before-merge-decide";
37
38
 
38
39
  export { GITLAB_NOTE_COMMANDS_VAR } from "./components/pr-pipeline";
39
40
 
@@ -119,7 +120,17 @@ export type NoteRun =
119
120
  * that has such a job. Refused when a later commit of the default branch
120
121
  * already carries the product's apply status.
121
122
  */
122
- | { kind: "retry"; sha: string; jobs?: RegExp }
123
+ | {
124
+ kind: "retry";
125
+ sha: string;
126
+ jobs?: RegExp;
127
+ /**
128
+ * With the waves' op (#4984, the GitLab half of #4979's stop): the
129
+ * stop written for `sha` on `chant/lifecycle` just before the retry,
130
+ * the last wave that runs, or null to clear an earlier one.
131
+ */
132
+ stop?: { op: string; through: number | null };
133
+ }
123
134
  /** A reply, and nothing runs. */
124
135
  | { kind: "reply"; text: string }
125
136
  /** Something broke: the note gets no reply and is read again next poll. */
@@ -184,6 +195,8 @@ export interface NoteCommandsOptions {
184
195
  env?: Record<string, string | undefined>;
185
196
  /** The commit words that take an argument, as `parseProductComment` takes them. */
186
197
  commitArgs?: Readonly<Record<string, RegExp>>;
198
+ /** Writes a retry's wave stop for op `op` at `sha`, or clears it (#4984). Absent: a retry that carries a stop is refused. */
199
+ stops?: (op: string, sha: string, stop: { through: number; at: string; by?: string; pr?: number } | null) => Promise<void>;
187
200
  }
188
201
 
189
202
  export interface NotePoll {
@@ -306,7 +319,25 @@ async function answer(o: NoteCommandsOptions, mr: PullRequestDetail, note: PullR
306
319
  return reply(`started pipeline${link(started)} to ${run.doing} for ${note.author}`, true, started.url);
307
320
  }
308
321
  case "retry": {
309
- const done = await retryApply(o, "gitlab", mr, note.author, run, gitlabRetry(o.pipelines));
322
+ // #4984: the stop goes on chant/lifecycle just before the retry, so every wave job after it reads it.
323
+ const stop = run.stop;
324
+ if (stop && !o.stops) return broke("the retry carries a wave stop, and this poll cannot write one");
325
+ const retry = gitlabRetry(o.pipelines);
326
+ const author = note.author;
327
+ const rerun: ApplyRerun = stop
328
+ ? async (pipeline, jobs, ctx) => {
329
+ try {
330
+ await o.stops!(stop.op, run.sha, stop.through === null ? null : { through: stop.through, at, by: author, pr: mr.number });
331
+ } catch (e) {
332
+ return { kind: "fail", reason: `could not write the wave stop for ${short(run.sha)}, so nothing was retried (${message(e)})` };
333
+ }
334
+ return retry(pipeline, jobs, ctx);
335
+ }
336
+ : retry;
337
+ const done = await retryApply(o, "gitlab", mr, note.author, run, rerun);
338
+ if (done.kind === "ran" && stop?.through !== null && stop?.through !== undefined) {
339
+ return reply(`${done.text}; it stops after \`wave-${stop.through}\`, and the waves after it wait until ${commandLine(o.words, "apply")} runs it again`, true, done.url);
340
+ }
310
341
  if (done.kind === "fail") return broke(done.reason);
311
342
  return reply(done.text, done.kind === "ran", done.kind === "ran" ? done.url : undefined);
312
343
  }
@@ -447,6 +478,27 @@ export interface ChantNoteJobs {
447
478
  * reply, and nothing starts. Absent: any member a comment may name.
448
479
  */
449
480
  members?: readonly string[];
481
+ /**
482
+ * The waves on merge (#4984, as the comment job's #4979): their op and
483
+ * count. With them a merged merge request's `wave-<n>` writes a stop for
484
+ * the merge commit before the retry, and an apply without a wave clears
485
+ * it; without them a `wave-<n>` is refused, as before.
486
+ */
487
+ waves?: { op: string; count: number };
488
+ /**
489
+ * The waves before merge (#4984), with `waves`: an open merge request's
490
+ * apply is decided here (./op/before-merge-decide.ts), recorded on
491
+ * `chant/lifecycle`, and runs in a pipeline of the default branch started
492
+ * with `CHANT_BEFORE_MERGE_PR`, `CHANT_BEFORE_MERGE_HEAD` and
493
+ * `CHANT_BEFORE_MERGE_DIGEST`.
494
+ */
495
+ wavesBeforeMerge?: WavesBeforeMergeJobs;
496
+ }
497
+
498
+ /** What {@link chantNoteRuns} reads and writes with besides the jobs (#4984). */
499
+ export interface ChantNoteRunsOptions {
500
+ /** With `jobs.wavesBeforeMerge`: what the decision before merge reads and writes with. */
501
+ beforeMerge?: Pick<DecideBeforeMergeInput, "requires" | "statuses" | "git" | "cwd" | "lock" | "record" | "stop" | "now">;
450
502
  }
451
503
 
452
504
  /**
@@ -454,8 +506,8 @@ export interface ChantNoteJobs {
454
506
  * A command no job runs gets the words' reply for it (`words.replies`,
455
507
  * #4946), else chant's.
456
508
  */
457
- export function chantNoteRuns(jobs: ChantNoteJobs): NoteCommandRuns {
458
- return ({ mr, note, parsed, base, words }): NoteRun => {
509
+ export function chantNoteRuns(jobs: ChantNoteJobs, opts: ChantNoteRunsOptions = {}): NoteCommandRuns {
510
+ return ({ mr, note, parsed, base, words }): NoteRun | Promise<NoteRun> => {
459
511
  const iid = String(mr.number);
460
512
  const at = `!${mr.number}`;
461
513
  const line = (kind: CiProductCommand): string => commandLine(words, kind);
@@ -466,7 +518,7 @@ export function chantNoteRuns(jobs: ChantNoteJobs): NoteCommandRuns {
466
518
  const open = mr.state === "open";
467
519
  const intoBase = mr.base === undefined || mr.base === base;
468
520
  // #4946: the product's sentence for an apply no job answers, in place of chant's, which say what the merge does.
469
- if (parsed.kind === "apply" && !jobs.applyBeforeMerge && !jobs.applyOnMerge && words.replies?.apply !== undefined) return { kind: "reply", text: words.replies.apply };
521
+ if (parsed.kind === "apply" && !jobs.applyBeforeMerge && !jobs.applyOnMerge && !jobs.wavesBeforeMerge && words.replies?.apply !== undefined) return { kind: "reply", text: words.replies.apply };
470
522
  switch (parsed.kind) {
471
523
  case "plan":
472
524
  if (!open) return { kind: "reply", text: `${at} is not open, so it is not ${words.verbs.plan[1]}` };
@@ -474,6 +526,8 @@ export function chantNoteRuns(jobs: ChantNoteJobs): NoteCommandRuns {
474
526
  return { kind: "merge-request-pipeline", doing: `${words.verbs.plan[0]} ${at} again` };
475
527
  case "apply":
476
528
  if (open) {
529
+ // #4984: the waves before merge decide here, and the pipeline they start runs the decided head.
530
+ if (jobs.wavesBeforeMerge && jobs.waves && opts.beforeMerge && !jobs.applyBeforeMerge) return wavesBeforeMergeRun(jobs, opts.beforeMerge, { mr, note, parsed, base, words });
477
531
  if (!jobs.applyBeforeMerge) return { kind: "reply", text: `${at} is not merged, and this project ${words.verbs.apply[0]}s after a merge request merges, never from its branch` };
478
532
  if (!intoBase) return { kind: "reply", text: `${at} targets ${mr.base}, not the default branch ${base}, so it is not ${words.verbs.apply[1]}` };
479
533
  return { kind: "pipeline", ref: base, variables: { [GITLAB_APPLY_PR_VAR]: iid }, doing: `${words.verbs.apply[0]} ${at}'s head${mr.headSha ? ` ${short(mr.headSha)}` : ""}` };
@@ -482,10 +536,12 @@ export function chantNoteRuns(jobs: ChantNoteJobs): NoteCommandRuns {
482
536
  if (!jobs.applyOnMerge) {
483
537
  return { kind: "reply", text: jobs.applyBeforeMerge ? `${at} is merged, and this project ${words.verbs.apply[0]}s a merge request before it merges, so there is nothing of it left to ${words.verbs.apply[0]}` : `${at} is merged, and a merge here records the plan: a release deploys it` };
484
538
  }
485
- if (parsed.wave !== undefined) return { kind: "reply", text: `GitLab runs the waves after a retried apply job by itself, so \`wave-${parsed.wave}\` cannot stop them; write ${line("apply")}, and each wave still waits behind its own gate` };
539
+ // #4984: with the waves' op, a wave-<n> writes a stop for the merge commit before the retry, as on GitHub and Forgejo.
540
+ if (parsed.wave !== undefined && !jobs.waves) return { kind: "reply", text: `GitLab runs the waves after a retried apply job by itself, so \`wave-${parsed.wave}\` cannot stop them; write ${line("apply")}, and each wave still waits behind its own gate` };
541
+ if (parsed.wave !== undefined && jobs.waves && parsed.wave > jobs.waves.count) return { kind: "reply", text: `the ${words.verbs.apply[0]} of this project runs in ${jobs.waves.count} wave${jobs.waves.count === 1 ? "" : "s"}, so there is no \`wave-${parsed.wave}\`` };
486
542
  if (!intoBase) return { kind: "reply", text: `${at} was merged into ${mr.base}, not the default branch ${base}, so nothing applies from it` };
487
543
  if (!mr.mergeCommit) return { kind: "fail", reason: `${at} has no merge commit` };
488
- return { kind: "retry", sha: mr.mergeCommit };
544
+ return { kind: "retry", sha: mr.mergeCommit, ...(jobs.waves ? { stop: { op: jobs.waves.op, through: parsed.wave !== undefined && parsed.wave < jobs.waves.count ? parsed.wave : null } } : {}) };
489
545
  case "lock":
490
546
  case "unlock":
491
547
  if (!jobs.locks) return { kind: "reply", text: notRunReply(words, parsed.kind, "gitlab") };
@@ -506,6 +562,39 @@ export function chantNoteRuns(jobs: ChantNoteJobs): NoteCommandRuns {
506
562
  };
507
563
  }
508
564
 
565
+ /**
566
+ * An open merge request's apply under the waves before merge (#4984): the
567
+ * decision records the head, and the run is a pipeline of the default branch
568
+ * started with the decision's three variables, which the wave jobs' guard
569
+ * checks against the record.
570
+ */
571
+ async function wavesBeforeMergeRun(jobs: ChantNoteJobs, deps: NonNullable<ChantNoteRunsOptions["beforeMerge"]>, c: Omit<NoteCommand, "role">): Promise<NoteRun> {
572
+ const parsed = c.parsed as Extract<NoteCommand["parsed"], { kind: "apply" }>;
573
+ const { decideWavesBeforeMerge } = await import("./op/before-merge-decide");
574
+ const { BEFORE_MERGE_DIGEST_ENV, BEFORE_MERGE_HEAD_ENV, BEFORE_MERGE_PR_ENV } = await import("./op/before-merge");
575
+ let variables: Record<string, string> | undefined;
576
+ const done = await decideWavesBeforeMerge({
577
+ ...deps,
578
+ forge: "gitlab",
579
+ pr: c.mr,
580
+ user: c.note.author ?? "",
581
+ base: c.base,
582
+ ...(parsed.wave !== undefined ? { wave: parsed.wave } : {}),
583
+ op: jobs.waves!.op,
584
+ count: jobs.waves!.count,
585
+ jobs: jobs.wavesBeforeMerge!,
586
+ words: c.words,
587
+ // The poll starts the pipeline once the decision is recorded, and its reply links it.
588
+ start: async (r) => {
589
+ variables = { [BEFORE_MERGE_PR_ENV]: String(r.pr), [BEFORE_MERGE_HEAD_ENV]: r.head, [BEFORE_MERGE_DIGEST_ENV]: r.digest };
590
+ return {};
591
+ },
592
+ });
593
+ if (done.kind !== "ran") return done.kind === "fail" ? { kind: "fail", reason: done.reason } : { kind: "reply", text: done.text };
594
+ const through = parsed.wave !== undefined && parsed.wave < jobs.waves!.count ? ` through wave ${parsed.wave}` : "";
595
+ return { kind: "pipeline", ref: c.base, variables: variables!, doing: `${c.words.verbs.apply[0]} !${c.mr.number}'s head ${short(c.mr.headSha ?? "")}${through} before it merges` };
596
+ }
597
+
509
598
  /** The directory on `chant/lifecycle` that keeps the notes the poll answered. */
510
599
  export const NOTES_DIR = "_notes";
511
600
 
package/src/ci-product.ts CHANGED
@@ -151,7 +151,7 @@ export const COMMENT_LEAVES_COMMIT_FLOOR = "0.124.88";
151
151
  /**
152
152
  * The first chant with the comment job on GitHub and Forgejo and the replies to commands no job runs (#4946): `commentJob` in the product pipeline (`chant components pr-comment`, `answerProductComment` in `@intentius/chant/ci-comment-commands`), which replies to a refusal and to a command the pipeline runs no job for, and with waves on merge starts a merged pull request's apply again; the words' `replies` and an alias's `refuse`, which the GitLab note poll reads too, as `chantNoteRuns`' `members`; `retryApply`; and `locks: "plan"` in GitHub's and Forgejo's product plan, with the lock, unlock and comment lock jobs.
153
153
  */
154
- export const COMMENT_COMMANDS_FLOOR = NEXT_RELEASE;
154
+ export const COMMENT_COMMANDS_FLOOR = "0.124.89";
155
155
  export { answerProductComment, answeredElsewhere, COMMENT_JOBS_ENV, commentRuns, PR_COMMENT_JOB, RERUN_APPLY_JOBS, type CommentJobs, type CommentOutcome, type CommentRuns, type AnswerCommentOptions } from "./ci-comment-commands";
156
156
  export { forkReply, memberReply, notRunReply } from "./ci-comment-replies";
157
157
  export type { CiProductCommentReplies } from "./ci-product-words";
@@ -160,7 +160,7 @@ export { productCommentJob, type ProductCommentJob } from "./components/product-
160
160
  /**
161
161
  * The first chant whose product plan locks what a change reaches (#4979): `productPlan.reach`, a reach line the lock job runs at the target branch's commit with `chant lock --reach` (`@intentius/chant/lifecycle/reach-locks`), on GitHub, Forgejo and GitLab, where the lock job runs in the plan notes pipeline with `--open` beside the comment lock and unlock jobs; and whose comment job answers a re-plan comment with flags the product plan's re-plan cannot take (`noPlanFlags`).
162
162
  */
163
- export const PRODUCT_PLAN_REACH_LOCKS_FLOOR = NEXT_RELEASE;
163
+ export const PRODUCT_PLAN_REACH_LOCKS_FLOOR = "0.124.89";
164
164
  export { LOCK_REACH_ENV, reachedTargets, reachOpen, type Reached, type ReachInput } from "./lifecycle/reach-locks";
165
165
  export { productPlanReachLock, type ProductPlanReachLock } from "./components/product-plan";
166
166
  export { planFlagsReply } from "./ci-comment-commands";
@@ -168,14 +168,62 @@ export { planFlagsReply } from "./ci-comment-commands";
168
168
  /**
169
169
  * The first chant whose comment job stops a merged pull request's re-run at a wave (#4979): `/<product> apply wave-<n>` writes a stop for the merge commit on `chant/lifecycle` (`_waves/<op>.stops.json`, `@intentius/chant/op/wave-stop`) before GitHub's re-run or Forgejo's dispatch, and `chant run wave` leaves each wave after n waiting (exit 3).
170
170
  */
171
- export const WAVE_STOP_FLOOR = NEXT_RELEASE;
171
+ export const WAVE_STOP_FLOOR = "0.124.89";
172
172
  export { setWaveStop, waveStopAt, waveStopLine, type WaveStop } from "./op/wave-stop";
173
173
 
174
+ /**
175
+ * The first chant whose Op waves run before merge (#4984): `wavesBeforeMerge` in the product pipeline, where the comment job (GitHub, Forgejo) or the note poll (GitLab) decides `/<product> apply [wave-<n>]` on an open pull request (`decideWavesBeforeMerge`, `@intentius/chant/op/before-merge-decide`), records the head and its digest on `chant/lifecycle` (`_waves/<op>.before-merge.json`) and starts the waves for it; the generators' `beforeMerge`, whose guard admits that head alone, whose jobs check it out and read the base from the default branch, and whose `before-merge-done` job merges and releases the locks (`chant run wave --merge`); `waveJobs.<wave>.prelude`; the GitLab note poll's wave stop (`chantNoteRuns`' `waves`); a re-plan word that never starts with `-`; and the terraform lexicon's reach helpers (`@intentius/chant-lexicon-terraform/reach`).
176
+ */
177
+ export const WAVES_BEFORE_MERGE_FLOOR = "0.124.90";
178
+ export { BEFORE_MERGE_DIGEST_ENV, BEFORE_MERGE_DONE_JOB, BEFORE_MERGE_HEAD_ENV, BEFORE_MERGE_PR_ENV, beforeMergeDigest, beforeMergePath, beforeMergeProblems, WAVES_BASE_ENV, type BeforeMergeDecision, type BeforeMergeRecord, type OpWavesBeforeMerge } from "./op/before-merge";
179
+ export { decideWavesBeforeMerge, defaultPipelineFiles, type WavesBeforeMergeJobs } from "./op/before-merge-decide";
180
+ export type { ProductWavesBeforeMerge } from "./components/product-pipeline";
181
+
182
+ /**
183
+ * The first chant whose Op waves post the apply statuses (#4987): the generators' `applyStatus`, a job `apply-status-<n>` after each wave at the default branch's commit that posts `<product>/apply` on the commit the waves applied (a before-merge run's decided head) with `chant run wave --apply-status` (`@intentius/chant/op/apply-status`), and the product pipeline's `applyStatus`; whose product plan takes `staleNotes`, each target's note carrying the target branch's commit and a `stale-notes` job beside wave 1 on a push marking each target's note (`pr-post --stale` with one `--member` per target); whose `productPipelineJobs` returns `waves.pipeline` for the generators; and whose GitLab reach line reaches the lock and note-commands jobs unexpanded (`expand: false`).
184
+ */
185
+ export const WAVES_APPLY_STATUS_FLOOR = "0.124.90";
186
+ export { applyStatusJobName, opWaveApplyStatus, postOpWaveApplyStatus, type OpWaveApplyStatus, type OpWavesApplyStatus } from "./op/apply-status";
187
+
188
+ /**
189
+ * The first chant whose before-merge waves never run the change's code beside a write token (#4987): with `beforeMerge` each wave is a plan job (the change's code, a checkout with no credentials kept, a read-only token; GitLab drops `CHANT_FORGE_TOKEN` and the job token), a gate job at the default branch with the token, an applying job on the saved plan with no write token, and a record job at the default branch that writes the run records (`chant run wave --phase plan|gate|apply|record`, `@intentius/chant/op/op-waves-split`). A `rest` wave is refused with `beforeMerge`.
190
+ */
191
+ export const WAVES_BEFORE_MERGE_SPLIT_FLOOR = "0.124.90";
192
+ export { opWaveSplitJobs, type OpWavePhase, type OpWaveSplitJob } from "./op/op-waves-split";
193
+
194
+ /**
195
+ * The first chant whose split before-merge waves take a `step` spec, Forgejo's hand-off, holds on other gates and one approval per wave (#4992): the plan job saves each run's step plan, the gate job leases the rows they change (no heartbeat; the decision names the lease) before it spends the approval, the applying job plans its runs again through the step and applies each whose digest the decision holds, and the record job writes the release records and lets go of the rows; a hook in the plan or apply job that holds the wave on another gate reads it with no write token and leaves its pending fact to the gate or record job; on Forgejo the plan and applying jobs hand their files on as job outputs (`packJs`), never through the artifact upload, and the gate and record jobs keep them as the artifacts; the plan job names no environment on GitHub (a wave's `planEnvironment` when set; on GitLab it prepares it), so the environment's reviewers are asked once. A `rest` wave splits from {@link WAVES_BEFORE_MERGE_REST_FLOOR} on.
196
+ */
197
+ export const WAVES_BEFORE_MERGE_STEP_FLOOR = "0.124.90";
198
+ export type { OpWaveSavedStep, OpWaveSplitHandoff, OpWaveSplitLease } from "./op/op-waves-run";
199
+
200
+ /**
201
+ * The first chant whose split waves run a product's own process in every job (#4994): the product wave hook's `hooks` (`runChantInProcess(["run", "wave", ..., "--phase", <phase>], words, { wave: { afterPlan, capabilities, hookExec, runHooks, hooks } })`, `RunOpWaveOptions.inProcessHooks`) serves a spec hook by its name in the process of whichever job runs it, plan, gate or applying job or the one-job shape, in place of a command that called back over a socket; `opWaveProductStateDir` is where the plan job's code keeps what the later jobs read; a `record: true` hold in the plan job is spent by the gate job for a re-run of the hook at the wave's commit (an applied line with `rerun.head`), which the next run's plan job runs and its gate job finishes (`holdsFinished`); and `waveJobs.<wave>.artifact.path` takes a list and `waveJobs.<wave>.gate` gives the gate job a report and an artifact, so a product's own upload steps go through chant's Forgejo hand-off.
202
+ */
203
+ export const WAVES_PRODUCT_HOOKS_FLOOR = "0.124.90";
204
+ export type { OpWaveHandedFinished, OpWaveInProcessHook, OpWaveInProcessHookCall } from "./op/op-waves-run";
205
+ export { opWaveProductStateDir } from "./op/op-waves-split";
206
+
207
+ /**
208
+ * The first chant whose split before-merge waves take a `rest` wave (#4992): its four jobs run one wave per run, the wave `CHANT_WAVES_WAVE` names (their own by default), and its record job, once the run applied and the plan found another wave, starts the waves workflow again for it (GitHub and Forgejo: a dispatch with the inputs `wave` and the decision's `pr`, `head` and `digest`, or a push's `commit`; GitLab: a pipeline with the same variables, with `CHANT_FORGE_TOKEN`), whose guard admits it as the same decided head; the jobs of the waves before it do not run in that follow-on; the record job's note (`rest-wave.json` beside the outcomes, `@intentius/chant/op/op-waves-follow-on`) tells `before-merge-done`, the control dispatch and the apply status that a run which started a follow-on is not the last.
209
+ */
210
+ export const WAVES_BEFORE_MERGE_REST_FLOOR = "0.124.90";
211
+
212
+ /**
213
+ * The first chant whose rest wave's record job records each follow-on it starts on `chant/lifecycle` before it starts it (#4998): `_waves/<op>.follow-on.json` keeps, per decided head or pushed commit, the wave started, the run that started it, the decision (`pr`, `digest`) or the `commit`, and the outcomes of every run of the chain so far; the guard admits a follow-on only for the wave that record names, so a wave started by hand past it is refused; and the last run's control dispatch, apply status and `before-merge-done` add up the outcomes of every run of the chain (the note's `chain`), so a chain whose last wave changed nothing reports `applied`.
214
+ */
215
+ export const WAVES_FOLLOW_ON_RECORD_FLOOR = "0.124.90";
216
+
174
217
  /**
175
218
  * The first chant whose product plan takes `watches`, the product's own scheduled jobs the note job's `pr-post` checks for having stopped with the job's token (#4888), and whose `checkOverdueOps` and `overdueOpsAt` take a product's `logPrefix` and `label`.
176
219
  */
177
220
  export const PRODUCT_PLAN_WATCHES_FLOOR = "0.124.88";
178
- export { PLAN_WATCHES_ENV } from "./op/schedule-overdue";
221
+ export { PLAN_WATCHES_ENV, watchesForTarget } from "./op/schedule-overdue";
222
+
223
+ /**
224
+ * The first chant whose product plan's `watches` take `targets` (#4988): a watch scoped to those targets is checked by their notes alone, and the note of another target checks neither it nor the discovered Op of its name (`watchesForTarget`).
225
+ */
226
+ export const PRODUCT_PLAN_WATCH_TARGETS_FLOOR = "0.124.90";
179
227
 
180
228
  /**
181
229
  * The first chant whose product plan takes `record` (#4899): the plan step writes the plan job's run record into the hand-off, and the note job keeps it as Op `pr-plan` on `chant/lifecycle` with `pr-post --record-run <plan job>` (`--open` on GitLab), as `chant ci run plan --in-place` records `pr-plan`'s.
@@ -186,16 +234,27 @@ export { PLAN_RUN_OP, PLAN_RUN_RECORD_FILE, readPlanRunRecord } from "./pr-plan-
186
234
  /**
187
235
  * The first chant whose product plan carries what terragucci's and sql-yodeler's plan jobs did themselves (#4963, #4951): `trade` (a plan's or a target's) before the checkout, `replan: { dispatch, reply, notAffected }` (a re-plan from `workflow_dispatch`, a reply to a comment no other job takes, `pr-post --not-affected`), `previousMarker` (`CHANT_PLAN_PREVIOUS_MARKER`), `noteSteps.pullRequest`, a `PrReport`'s `marker`, and a hand-off of the product's own note text (`planBodyHandoff`).
188
236
  */
189
- export const PRODUCT_PLAN_REPLAN_FLOOR = NEXT_RELEASE;
237
+ export const PRODUCT_PLAN_REPLAN_FLOOR = "0.124.89";
190
238
  export { gitlabReplanArgumentLines, PREVIOUS_MARKER_JS, replanDecideJs, type ProductPlanReplanOptions } from "./components/product-plan";
191
239
  export { planBodyHandoff, PLAN_BODY_LIMIT, type PrPlanBodyHandoff } from "./pr-plan-note";
192
240
 
193
241
  /**
194
242
  * The first chant whose note job compares the plan's subject with the previous note's (#4972), on GitHub, Forgejo and GitLab: a plan note hand-off's `subject` (`PrPlanSubject`, an id and named parts) is kept in the note, and `pr-post` adds the note words' `sinceLast` line, naming the parts added, gone and changed (`subjectParts`), when the previous note kept another id. The plan job reads no note, and `previousMarker` is deprecated.
195
243
  */
196
- export const PRODUCT_PLAN_SUBJECT_FLOOR = NEXT_RELEASE;
244
+ export const PRODUCT_PLAN_SUBJECT_FLOOR = "0.124.89";
197
245
  export { PLAN_SUBJECT_LIMIT, planSubjectProblem, sinceLastLine, subjectChanges, type PrPlanSubject, type PrPlanSubjectPartWords } from "./pr-plan-note";
198
246
 
247
+ /**
248
+ * The first chant whose product plan keeps a product's own names (#5003): `workflowFile` (the generators' `path`), `jobNames` (the plan, note, re-plan and re-plan note jobs, with `{target}`), `statusContext` (which `pr-post --context`, the pending step, the stale job and the apply before merge use) and `reportDir` (`{output}`, the hand-off, the artifact's path and `pr-post --output`), and whose `pr-post --open` finds a plan job of the product's name (`--plan-job`).
249
+ */
250
+ export const PRODUCT_PLAN_NAMES_FLOOR = NEXT_RELEASE;
251
+ export { productPlanContext, productPlanReportDir, productPlanWorkflowFile } from "./components/product-plan";
252
+
253
+ /**
254
+ * The first chant whose GitLab product plan job keeps a product's own artifacts beside the report directory (#5004): `productPlan.artifacts: { paths, reports }`, as `artifacts:paths` and `artifacts:reports`, such as terragucci's `terraform` report for the merge request's widget, with `{target}` and `{output}` filled. GitHub and Forgejo refuse it.
255
+ */
256
+ export const PRODUCT_PLAN_ARTIFACTS_FLOOR = NEXT_RELEASE;
257
+
199
258
  /**
200
259
  * Day-2 actions in the product pipeline (#4654): the `action` comment
201
260
  * command counted as answered by the product's own workflow
@@ -16,7 +16,9 @@
16
16
 
17
17
  import { readFileSync } from "node:fs";
18
18
  import { activeProductWords } from "../../ci-product-words";
19
- import { answerProductComment, COMMENT_JOBS_ENV, commentRuns, type CommentJobs } from "../../ci-comment-commands";
19
+ import { answerProductComment, COMMENT_JOBS_ENV, commentRuns, type CommentBeforeMerge, type CommentJobs } from "../../ci-comment-commands";
20
+ import type { WavesBeforeMergeJobs } from "../../op/before-merge-decide";
21
+ import { PR_APPLY_REQUIRES } from "../../pr-requires";
20
22
  import { forgeFromEnv, forgeTargetFromEnv, type PrForge } from "../../pr-forge";
21
23
  import { forgeReadsFor } from "../../pr-forge-reads";
22
24
  import { formatError, formatInfo } from "../format";
@@ -32,10 +34,15 @@ export function commentJobsFromEnv(raw: string | undefined): CommentJobs {
32
34
  if (raw === undefined || raw.trim() === "") return {};
33
35
  const v: unknown = JSON.parse(raw);
34
36
  if (typeof v !== "object" || v === null || Array.isArray(v)) throw new Error(`${COMMENT_JOBS_ENV} is a JSON object of the jobs the pipeline has`);
35
- const known = new Set(["preview", "applyBeforeMerge", "applyOnMerge", "locks", "agent", "commits", "actions", "skipForks", "targets", "noPlanFlags", "waves"]);
37
+ const known = new Set(["preview", "applyBeforeMerge", "applyOnMerge", "locks", "agent", "commits", "actions", "skipForks", "targets", "noPlanFlags", "waves", "wavesBeforeMerge"]);
36
38
  const jobs: Record<string, unknown> = {};
37
39
  for (const [k, x] of Object.entries(v)) {
38
40
  if (!known.has(k)) throw new Error(`${COMMENT_JOBS_ENV} names ${JSON.stringify(k)}, which is not one of ${[...known].join(", ")}`);
41
+ // #4984: the waves before merge.
42
+ if (k === "wavesBeforeMerge") {
43
+ jobs.wavesBeforeMerge = wavesBeforeMergeOf(x);
44
+ continue;
45
+ }
39
46
  // #4979: the waves' op and count, for a wave stop on a re-run.
40
47
  if (k === "waves") {
41
48
  const w = x as { op?: unknown; count?: unknown } | null;
@@ -51,9 +58,83 @@ export function commentJobsFromEnv(raw: string | undefined): CommentJobs {
51
58
  if (typeof x !== "boolean") throw new Error(`${COMMENT_JOBS_ENV}.${k} is true or false`);
52
59
  if (x) jobs[k] = true;
53
60
  }
61
+ if (jobs.wavesBeforeMerge && !jobs.waves) throw new Error(`${COMMENT_JOBS_ENV}.wavesBeforeMerge needs waves: { op, count }, the waves it starts`);
54
62
  return jobs as CommentJobs;
55
63
  }
56
64
 
65
+ /** {@link COMMENT_JOBS_ENV}'s `wavesBeforeMerge` (#4984), each field checked, since the comment job pushes and dispatches with what it names. */
66
+ export function wavesBeforeMergeOf(x: unknown): WavesBeforeMergeJobs {
67
+ const what = `${COMMENT_JOBS_ENV}.wavesBeforeMerge`;
68
+ const o = x as Partial<WavesBeforeMergeJobs> | null;
69
+ if (!o || typeof o !== "object" || Array.isArray(o)) throw new Error(`${what} is { workflow?, requires?, plan, pipelineFiles, locks? }`);
70
+ const strings = (v: unknown): v is string[] => Array.isArray(v) && v.every((s) => typeof s === "string" && s.trim() !== "" && !/[\r\n]/.test(s));
71
+ if (o.workflow !== undefined && (typeof o.workflow !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]*\.ya?ml$/.test(o.workflow))) throw new Error(`${what}.workflow is a workflow file name, like deploy.yml`);
72
+ if (o.requires !== undefined && (!Array.isArray(o.requires) || o.requires.some((r) => !(PR_APPLY_REQUIRES as readonly string[]).includes(r)))) throw new Error(`${what}.requires is a list of ${PR_APPLY_REQUIRES.join(", ")}`);
73
+ if (!strings(o.plan)) throw new Error(`${what}.plan is the list of plan statuses that must pass on the head`);
74
+ if (!strings(o.pipelineFiles)) throw new Error(`${what}.pipelineFiles is the list of paths a change may not touch`);
75
+ if (o.locks !== undefined && (typeof o.locks !== "object" || o.locks === null || (o.locks.gate !== undefined && (typeof o.locks.gate !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(o.locks.gate))))) throw new Error(`${what}.locks is { gate? }`);
76
+ return {
77
+ ...(o.workflow ? { workflow: o.workflow } : {}),
78
+ ...(o.requires ? { requires: [...o.requires] } : {}),
79
+ plan: [...o.plan],
80
+ pipelineFiles: [...o.pipelineFiles],
81
+ ...(o.locks ? { locks: { ...(o.locks.gate ? { gate: o.locks.gate } : {}) } } : {}),
82
+ };
83
+ }
84
+
85
+ /**
86
+ * What the decision before merge reads and writes with (#4984), in the
87
+ * comment job (GitHub, Forgejo) and the note poll (GitLab): the requires
88
+ * and statuses through the job's client, git in the checkout of the
89
+ * default branch, the reach line's locks at stage apply, and the decision
90
+ * and the wave stop on this checkout's `chant/lifecycle`.
91
+ */
92
+ export async function beforeMergeDeps(forge: PrForge, jobs: CommentJobs, env: NodeJS.ProcessEnv = process.env): Promise<CommentBeforeMerge> {
93
+ const bm = jobs.wavesBeforeMerge!;
94
+ const op = jobs.waves!.op;
95
+ const { spawnSync } = await import("node:child_process");
96
+ const { checkPrRequires, unmetRequires } = await import("../../pr-requires");
97
+ const { productStatusContext, activeProductWords } = await import("../../ci-product-words");
98
+ const { LOCK_REACH_ENV, reachedTargets } = await import("../../lifecycle/reach-locks");
99
+ const { takeTargetLocks, describeHeldTargetLocks } = await import("../../lifecycle/target-lock");
100
+ const { recordBeforeMerge } = await import("../../op/before-merge-store");
101
+ const { setWaveStop } = await import("../../op/wave-stop");
102
+ const { PR_APPLY_GATE } = await import("../../pr-loop");
103
+ const words = activeProductWords();
104
+ const line = env[LOCK_REACH_ENV];
105
+ const name = (n: number) => (forge.kind === "gitlab" ? `!${n}` : `pull request ${n}`);
106
+ return {
107
+ // The plan and apply statuses never hold the apply back: the plan status is asked for by name (#5003: the product plan's own names too).
108
+ requires: async (pr, head) => unmetRequires(await checkPrRequires(forge, pr, head, { ignore: [...new Set([productStatusContext(words, "apply"), productStatusContext(words, "plan"), `${productStatusContext(words, "plan")}/`, ...bm.plan])], ...(bm.requires ? { only: bm.requires } : {}) })),
109
+ statuses: async (sha) => (await forge.commitStatuses?.(sha)) ?? [],
110
+ git: (argv, o) => {
111
+ const r = spawnSync(argv[0]!, argv.slice(1), { encoding: "utf8", ...(o.cwd ? { cwd: o.cwd } : {}) });
112
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.error ? r.error.message : (r.stderr ?? "") };
113
+ },
114
+ // #4979's reach line says what the change reaches; the locks go up at stage apply, refused while another holds one.
115
+ ...(line && line.trim()
116
+ ? {
117
+ lock: async (pr: number, head: string, base: string, by: string) => {
118
+ const reached = reachedTargets({ forge: forge.kind, pr, head, base, line });
119
+ if ("error" in reached) throw new Error(reached.error);
120
+ if ("moved" in reached) return { ok: false as const, text: `${name(pr)} moved while this comment was read, so nothing is ${words.verbs.apply[1]}; comment again once its checks pass` };
121
+ const isOpen = forge.pullRequestOpen?.bind(forge);
122
+ const r = await takeTargetLocks(bm.locks?.gate ?? PR_APPLY_GATE, reached.targets, { pr, by, at: new Date().toISOString(), stage: "apply", head }, { ...(isOpen ? { isOpen } : {}) });
123
+ if (!r.ok) {
124
+ const request = forge.kind === "gitlab" ? "merge request" : "pull request";
125
+ return { ok: false as const, text: `${describeHeldTargetLocks(r.held, name)}, so ${name(pr)} is not ${words.verbs.apply[1]}. It ${words.verbs.apply[0]}s once that ${request} merges or closes, or someone with write access unlocks it` };
126
+ }
127
+ return { ok: true as const, targets: r.taken };
128
+ },
129
+ }
130
+ : {}),
131
+ record: (d) => recordBeforeMerge(op, d),
132
+ stop: async (head, through) => {
133
+ await setWaveStop(op, head, through === null ? null : { through, at: new Date().toISOString() });
134
+ },
135
+ };
136
+ }
137
+
57
138
  export async function runComponentsPrComment(ctx: CommandContext): Promise<number> {
58
139
  const { args } = ctx;
59
140
  const kind = args.forge;
@@ -87,6 +168,8 @@ export async function runComponentsPrComment(ctx: CommandContext): Promise<numbe
87
168
  base,
88
169
  jobs,
89
170
  env,
171
+ // #4984: the decision before merge, its record and its wave stop on this checkout's chant/lifecycle.
172
+ ...(jobs.wavesBeforeMerge ? { beforeMerge: await beforeMergeDeps(poster, jobs, env) } : {}),
90
173
  // #4979: the wave stop goes on this checkout's chant/lifecycle, which the job pushes with its token.
91
174
  ...(jobs.waves
92
175
  ? {
@@ -12,6 +12,8 @@
12
12
  import { resolve } from "node:path";
13
13
  import { activeProductWords } from "../../ci-product-words";
14
14
  import { chantNoteRuns, gitlabPipelines, ledgerNoteLog, pollNoteCommands } from "../../ci-note-commands";
15
+ import { COMMENT_JOBS_ENV, type CommentJobs } from "../../ci-comment-commands";
16
+ import { beforeMergeDeps, commentJobsFromEnv } from "./pr-comment";
15
17
  import { forgeFromEnv, forgeTargetFromEnv, type PrForge } from "../../pr-forge";
16
18
  import { forgeReadsFor } from "../../pr-forge-reads";
17
19
  import { formatError, formatInfo, formatWarning } from "../format";
@@ -41,20 +43,42 @@ export async function runComponentsPrNotes(ctx: CommandContext): Promise<number>
41
43
  // The ledger keeps the notes answered: read it as the remote has it.
42
44
  await fetchLifecycle({ cwd });
43
45
  const words = activeProductWords();
46
+ // #4984: the waves' op and count, and the waves before merge, as the pipeline wrote them in CHANT_COMMENT_JOBS.
47
+ let more: CommentJobs;
48
+ try {
49
+ more = commentJobsFromEnv(env[COMMENT_JOBS_ENV]);
50
+ } catch (err) {
51
+ return fail(err instanceof Error ? err.message : String(err));
52
+ }
53
+ const beforeMerge = more.wavesBeforeMerge && more.waves ? await beforeMergeDeps(forge, more, env) : undefined;
44
54
  const polled = await pollNoteCommands({
45
55
  reads: forgeReadsFor(target),
46
56
  forge,
47
57
  pipelines: gitlabPipelines({ apiBase: target.apiBase, project: target.repo, token: target.token, host: target.host, ...(target.tokenHeader ? { tokenHeader: target.tokenHeader } : {}) }),
48
58
  words,
49
59
  base,
50
- runs: chantNoteRuns({
51
- ...(args.previewComment ? { preview: true } : {}),
52
- ...(args.applyBeforeMerge ? { applyBeforeMerge: true } : {}),
53
- ...(args.applyOnMerge ? { applyOnMerge: true } : {}),
54
- ...(args.locks ? { locks: true } : {}),
55
- }),
60
+ runs: chantNoteRuns(
61
+ {
62
+ ...(args.previewComment ? { preview: true } : {}),
63
+ ...(args.applyBeforeMerge ? { applyBeforeMerge: true } : {}),
64
+ ...(args.applyOnMerge ? { applyOnMerge: true } : {}),
65
+ ...(args.locks ? { locks: true } : {}),
66
+ ...(more.waves ? { waves: more.waves } : {}),
67
+ ...(more.wavesBeforeMerge ? { wavesBeforeMerge: more.wavesBeforeMerge } : {}),
68
+ },
69
+ beforeMerge ? { beforeMerge } : {},
70
+ ),
56
71
  log: ledgerNoteLog({ cwd }),
57
72
  env,
73
+ // #4984: a merged merge request's wave-<n> stops the retried waves after it.
74
+ ...(more.waves
75
+ ? {
76
+ stops: async (op, sha, stop) => {
77
+ const { setWaveStop } = await import("../../op/wave-stop");
78
+ await setWaveStop(op, sha, stop, { cwd });
79
+ },
80
+ }
81
+ : {}),
58
82
  });
59
83
  let failed = polled.fail !== undefined;
60
84
  for (const o of polled.outcomes) {