@intentius/chant 0.124.89 → 0.124.90

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 (163) hide show
  1. package/dist/ci-comment-commands.d.ts +18 -2
  2. package/dist/ci-comment-commands.d.ts.map +1 -1
  3. package/dist/ci-comment-commands.js +30 -2
  4. package/dist/ci-job-guard.d.ts +42 -45
  5. package/dist/ci-job-guard.d.ts.map +1 -1
  6. package/dist/ci-job-guard.js +206 -3
  7. package/dist/ci-note-commands.d.ts +41 -1
  8. package/dist/ci-note-commands.d.ts.map +1 -1
  9. package/dist/ci-note-commands.js +64 -5
  10. package/dist/ci-product.d.ts +41 -1
  11. package/dist/ci-product.d.ts.map +1 -1
  12. package/dist/ci-product.js +44 -7
  13. package/dist/cli/handlers/pr-comment.d.ts +13 -1
  14. package/dist/cli/handlers/pr-comment.d.ts.map +1 -1
  15. package/dist/cli/handlers/pr-comment.js +90 -1
  16. package/dist/cli/handlers/pr-notes.d.ts.map +1 -1
  17. package/dist/cli/handlers/pr-notes.js +23 -1
  18. package/dist/cli/handlers/pr.js +16 -14
  19. package/dist/cli/handlers/run-wave.d.ts.map +1 -1
  20. package/dist/cli/handlers/run-wave.js +154 -4
  21. package/dist/cli/main.d.ts.map +1 -1
  22. package/dist/cli/main.js +17 -0
  23. package/dist/cli/parse-args.d.ts.map +1 -1
  24. package/dist/cli/parse-args.js +15 -0
  25. package/dist/cli/registry.d.ts +8 -1
  26. package/dist/cli/registry.d.ts.map +1 -1
  27. package/dist/components/pr-checks.d.ts +28 -1
  28. package/dist/components/pr-checks.d.ts.map +1 -1
  29. package/dist/components/pr-checks.js +35 -2
  30. package/dist/components/pr-pipeline.d.ts +3 -2
  31. package/dist/components/pr-pipeline.d.ts.map +1 -1
  32. package/dist/components/pr-pipeline.js +4 -2
  33. package/dist/components/product-pipeline.d.ts +54 -2
  34. package/dist/components/product-pipeline.d.ts.map +1 -1
  35. package/dist/components/product-pipeline.js +59 -5
  36. package/dist/components/product-plan.d.ts +13 -1
  37. package/dist/components/product-plan.d.ts.map +1 -1
  38. package/dist/components/product-plan.js +36 -10
  39. package/dist/floor-table.data.d.ts.map +1 -1
  40. package/dist/floor-table.data.js +32 -23
  41. package/dist/lexicon.d.ts +82 -4
  42. package/dist/lexicon.d.ts.map +1 -1
  43. package/dist/lifecycle/gate-applied.d.ts +9 -0
  44. package/dist/lifecycle/gate-applied.d.ts.map +1 -1
  45. package/dist/op/apply-status.d.ts +84 -0
  46. package/dist/op/apply-status.d.ts.map +1 -0
  47. package/dist/op/apply-status.js +106 -0
  48. package/dist/op/before-merge-decide.d.ts +102 -0
  49. package/dist/op/before-merge-decide.d.ts.map +1 -0
  50. package/dist/op/before-merge-decide.js +142 -0
  51. package/dist/op/before-merge-done.d.ts +56 -0
  52. package/dist/op/before-merge-done.d.ts.map +1 -0
  53. package/dist/op/before-merge-done.js +69 -0
  54. package/dist/op/before-merge-store.d.ts +20 -0
  55. package/dist/op/before-merge-store.d.ts.map +1 -0
  56. package/dist/op/before-merge-store.js +48 -0
  57. package/dist/op/before-merge.d.ts +150 -0
  58. package/dist/op/before-merge.d.ts.map +1 -0
  59. package/dist/op/before-merge.js +207 -0
  60. package/dist/op/follow-on-run.d.ts +117 -0
  61. package/dist/op/follow-on-run.d.ts.map +1 -0
  62. package/dist/op/follow-on-run.js +154 -0
  63. package/dist/op/follow-on-store.d.ts +17 -0
  64. package/dist/op/follow-on-store.d.ts.map +1 -0
  65. package/dist/op/follow-on-store.js +54 -0
  66. package/dist/op/gate.d.ts +6 -0
  67. package/dist/op/gate.d.ts.map +1 -1
  68. package/dist/op/gate.js +10 -1
  69. package/dist/op/index.d.ts +3 -1
  70. package/dist/op/index.d.ts.map +1 -1
  71. package/dist/op/index.js +1 -0
  72. package/dist/op/op-waves-after-plan.d.ts +13 -0
  73. package/dist/op/op-waves-after-plan.d.ts.map +1 -1
  74. package/dist/op/op-waves-evidence-jobs.d.ts +4 -1
  75. package/dist/op/op-waves-evidence-jobs.d.ts.map +1 -1
  76. package/dist/op/op-waves-evidence-jobs.js +10 -2
  77. package/dist/op/op-waves-follow-on.d.ts +162 -0
  78. package/dist/op/op-waves-follow-on.d.ts.map +1 -0
  79. package/dist/op/op-waves-follow-on.js +355 -0
  80. package/dist/op/op-waves-run.d.ts +146 -6
  81. package/dist/op/op-waves-run.d.ts.map +1 -1
  82. package/dist/op/op-waves-run.js +871 -99
  83. package/dist/op/op-waves-split.d.ts +122 -0
  84. package/dist/op/op-waves-split.d.ts.map +1 -0
  85. package/dist/op/op-waves-split.js +166 -0
  86. package/dist/op/op-waves.d.ts +20 -0
  87. package/dist/op/op-waves.d.ts.map +1 -1
  88. package/dist/op/op-waves.js +15 -1
  89. package/dist/op/schedule-overdue.d.ts +15 -1
  90. package/dist/op/schedule-overdue.d.ts.map +1 -1
  91. package/dist/op/schedule-overdue.js +18 -2
  92. package/dist/op/stage-hooks.d.ts +36 -1
  93. package/dist/op/stage-hooks.d.ts.map +1 -1
  94. package/dist/op/stage-hooks.js +17 -3
  95. package/dist/op/wave-stop.d.ts +4 -1
  96. package/dist/op/wave-stop.d.ts.map +1 -1
  97. package/dist/op/wave-stop.js +4 -2
  98. package/dist/pr-post.d.ts.map +1 -1
  99. package/dist/pr-post.js +2 -1
  100. package/dist/release-floors.d.ts +3 -1
  101. package/dist/release-floors.d.ts.map +1 -1
  102. package/dist/release-floors.js +21 -19
  103. package/dist/wave-blocked.d.ts +7 -1
  104. package/dist/wave-blocked.d.ts.map +1 -1
  105. package/dist/wave-blocked.js +7 -2
  106. package/dist/wave-runtime.mjs +364 -351
  107. package/package.json +1 -1
  108. package/src/ci-comment-commands.test.ts +63 -0
  109. package/src/ci-comment-commands.ts +43 -4
  110. package/src/ci-image.test.ts +1 -2
  111. package/src/ci-job-guard.before-merge.test.ts +148 -0
  112. package/src/ci-job-guard.follow-on-record.test.ts +137 -0
  113. package/src/ci-job-guard.follow-on.test.ts +144 -0
  114. package/src/ci-job-guard.ts +221 -3
  115. package/src/ci-note-commands.test.ts +76 -1
  116. package/src/ci-note-commands.ts +96 -7
  117. package/src/ci-product.ts +55 -7
  118. package/src/cli/handlers/pr-comment.ts +85 -2
  119. package/src/cli/handlers/pr-notes.ts +30 -6
  120. package/src/cli/handlers/pr.ts +14 -11
  121. package/src/cli/handlers/run-wave.ts +144 -4
  122. package/src/cli/main.ts +17 -0
  123. package/src/cli/parse-args.ts +11 -0
  124. package/src/cli/registry.ts +8 -1
  125. package/src/components/pr-checks.ts +55 -2
  126. package/src/components/pr-pipeline.ts +5 -3
  127. package/src/components/product-pipeline.apply-status.test.ts +50 -0
  128. package/src/components/product-pipeline.ts +113 -8
  129. package/src/components/product-plan.test.ts +23 -5
  130. package/src/components/product-plan.ts +43 -12
  131. package/src/floor-table.data.ts +32 -23
  132. package/src/lexicon.ts +78 -1
  133. package/src/lifecycle/gate-applied.ts +7 -0
  134. package/src/op/apply-status.test.ts +83 -0
  135. package/src/op/apply-status.ts +132 -0
  136. package/src/op/before-merge-decide.ts +190 -0
  137. package/src/op/before-merge-done.ts +99 -0
  138. package/src/op/before-merge-store.ts +44 -0
  139. package/src/op/before-merge.test.ts +201 -0
  140. package/src/op/before-merge.ts +266 -0
  141. package/src/op/follow-on-run.ts +206 -0
  142. package/src/op/follow-on-store.ts +54 -0
  143. package/src/op/gate.ts +16 -1
  144. package/src/op/index.ts +5 -0
  145. package/src/op/op-waves-after-plan.ts +13 -0
  146. package/src/op/op-waves-evidence-jobs.ts +11 -3
  147. package/src/op/op-waves-follow-on-record.test.ts +152 -0
  148. package/src/op/op-waves-follow-on.test.ts +247 -0
  149. package/src/op/op-waves-follow-on.ts +385 -0
  150. package/src/op/op-waves-render-spec.test.ts +1 -2
  151. package/src/op/op-waves-run.ts +971 -93
  152. package/src/op/op-waves-split-product.test.ts +288 -0
  153. package/src/op/op-waves-split-step.test.ts +298 -0
  154. package/src/op/op-waves-split.test.ts +196 -0
  155. package/src/op/op-waves-split.ts +189 -0
  156. package/src/op/op-waves.ts +28 -3
  157. package/src/op/schedule-overdue.test.ts +29 -1
  158. package/src/op/schedule-overdue.ts +27 -3
  159. package/src/op/stage-hooks.ts +52 -4
  160. package/src/op/wave-stop.ts +5 -3
  161. package/src/pr-post.ts +2 -1
  162. package/src/release-floors.ts +22 -19
  163. package/src/wave-blocked.ts +9 -4
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant",
3
- "version": "0.124.89",
3
+ "version": "0.124.90",
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",
@@ -374,3 +374,66 @@ describe("a wave stop on a re-run, and a re-plan comment with flags (#4979)", ()
374
374
  expect(() => commentJobsFromEnv('{"waves":{"op":"tf-apply","count":0}}')).toThrow(/waves is \{ op, count \}/);
375
375
  });
376
376
  });
377
+
378
+ describe("the comment job's apply before merge on the waves (#4984)", () => {
379
+ const bm = { workflow: "tf-apply.yml", plan: ["terragucci/plan"], pipelineFiles: [".github/workflows/"] };
380
+ const jobs: CommentJobs = { applyOnMerge: true, waves: { op: "tf-apply", count: 2 }, wavesBeforeMerge: bm };
381
+
382
+ test("an open pull request's apply is decided, and the waves workflow dispatched on the default branch with the decided head", async () => {
383
+ const { spawnSync } = await import("node:child_process");
384
+ const { mkdtempSync, writeFileSync } = await import("node:fs");
385
+ const { tmpdir } = await import("node:os");
386
+ const { join } = await import("node:path");
387
+ const { beforeMergeDigest } = await import("./op/before-merge");
388
+ const dir = mkdtempSync(join(tmpdir(), "chant-cc-bm-"));
389
+ const git = (...args: string[]) => {
390
+ 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" } });
391
+ if (r.status !== 0) throw new Error(r.stderr);
392
+ return r.stdout.trim();
393
+ };
394
+ git("init", "-q", "-b", "main");
395
+ writeFileSync(join(dir, "main.tf"), "1");
396
+ git("add", ".");
397
+ git("commit", "-q", "-m", "base");
398
+ const baseSha = git("rev-parse", "HEAD");
399
+ git("checkout", "-q", "-b", "feature");
400
+ writeFileSync(join(dir, "main.tf"), "2");
401
+ git("commit", "-q", "-am", "head");
402
+ const head = git("rev-parse", "HEAD");
403
+ git("update-ref", "refs/pull/12/head", head);
404
+ git("checkout", "-q", "main");
405
+ git("remote", "add", "origin", dir);
406
+ const s = setup({ pr: { state: "open", headSha: head, mergeCommit: undefined } }, jobs, "/terragucci apply wave-1");
407
+ const sent: Array<[string, string, Record<string, string> | undefined]> = [];
408
+ const stops: Array<[string, number | null]> = [];
409
+ const at = "2026-11-10T12:00:00.000Z";
410
+ const got = await answerProductComment({
411
+ ...s.opts,
412
+ runs: { rerunFailed: async () => ({}), dispatch: async (wf, ref, inputs) => (sent.push([wf, ref, inputs]), {}) },
413
+ beforeMerge: {
414
+ requires: async () => null,
415
+ statuses: async () => [{ context: "terragucci/plan", state: "success" }],
416
+ git: (argv, o) => {
417
+ const r = spawnSync(argv[0]!, argv.slice(1), { encoding: "utf8", ...(o.cwd ? { cwd: o.cwd } : {}) });
418
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
419
+ },
420
+ cwd: dir,
421
+ record: async (d) => ({ ...d, digest: beforeMergeDigest("tf-apply", d) }),
422
+ stop: async (h, through) => void stops.push([h, through]),
423
+ now: () => at,
424
+ },
425
+ });
426
+ const digest = beforeMergeDigest("tf-apply", { pr: 12, head, base: baseSha, through: 1, at, by: "alice" });
427
+ expect(sent).toEqual([["tf-apply.yml", "main", { pr: "12", head, digest }]]);
428
+ expect(stops).toEqual([[head, 1]]);
429
+ expect(got).toMatchObject({ command: "apply", ran: true, replied: true });
430
+ expect(s.posted).toEqual([`terragucci: started the waves of tf-apply on pull request 12's head ${head.slice(0, 8)} through wave 1 for alice; each wave's gate decides, and the run says when the head applied`]);
431
+ });
432
+
433
+ test("CHANT_COMMENT_JOBS carries the waves before merge, each field checked", () => {
434
+ expect(commentJobsFromEnv(JSON.stringify(jobs))).toEqual(jobs);
435
+ expect(() => commentJobsFromEnv(JSON.stringify({ wavesBeforeMerge: bm }))).toThrow("wavesBeforeMerge needs waves");
436
+ expect(() => commentJobsFromEnv(JSON.stringify({ ...jobs, wavesBeforeMerge: { ...bm, workflow: "../x" } }))).toThrow("workflow is a workflow file name");
437
+ expect(() => commentJobsFromEnv(JSON.stringify({ ...jobs, wavesBeforeMerge: { ...bm, requires: ["green"] } }))).toThrow("requires is a list of approved, mergeable, undiverged, checks");
438
+ });
439
+ });
@@ -32,6 +32,10 @@
32
32
  * the reply says so.
33
33
  * - with `noPlanFlags` (#4979), a plan comment with flags the product
34
34
  * plan's re-plan cannot take, with the reason.
35
+ * - with `wavesBeforeMerge` (#4984), `/<product> apply [wave-<n>]` on an
36
+ * open pull request: the decision before merge
37
+ * (./op/before-merge-decide.ts) records the head on `chant/lifecycle`
38
+ * and dispatches the waves workflow on the default branch for it.
35
39
  *
36
40
  * Who asked comes first. On GitHub the commenter's permission is read from
37
41
  * the forge; Forgejo answers 403 when a job's token asks for another user's
@@ -51,6 +55,7 @@ import { retryApply, type ApplyRerun, type ApplyRetried, type ChantNoteJobs, typ
51
55
  import { parseProductComment, type CiProductWords, type ParsedProductComment } from "./ci-product-words";
52
56
  import { ForgeApiError, type ForgeFetch, type PrForge } from "./pr-forge";
53
57
  import type { ForgeReads, PullRequestDetail } from "./pr-forge-reads";
58
+ import type { DecideBeforeMergeInput, WavesBeforeMergeJobs } from "./op/before-merge-decide";
54
59
 
55
60
  /** The comment job's name in a generated workflow (#4946). */
56
61
  export const PR_COMMENT_JOB = "comment";
@@ -90,8 +95,18 @@ export interface CommentJobs extends Omit<ChantNoteJobs, "members"> {
90
95
  * clears it.
91
96
  */
92
97
  waves?: { op: string; count: number };
98
+ /**
99
+ * The waves before merge (#4984), with `waves`: `/<product> apply
100
+ * [wave-<n>]` on an open pull request is this job's. It decides
101
+ * (./op/before-merge-decide.ts), records the decided head on
102
+ * `chant/lifecycle`, and dispatches the waves workflow for it.
103
+ */
104
+ wavesBeforeMerge?: WavesBeforeMergeJobs;
93
105
  }
94
106
 
107
+ /** What the decision before merge reads and writes with (#4984), the comment job's handler's. */
108
+ export type CommentBeforeMerge = Pick<DecideBeforeMergeInput, "requires" | "statuses" | "git" | "cwd" | "lock" | "record" | "stop" | "now">;
109
+
95
110
  /** Writes a wave stop for op `op` at `sha` on `chant/lifecycle`, or clears it (#4979). */
96
111
  export type CommentWaveStops = (op: string, sha: string, stop: { through: number; at: string; by?: string; pr?: number } | null) => Promise<void>;
97
112
 
@@ -106,8 +121,8 @@ export const RERUN_APPLY_JOBS = /^(?:wave-([1-9][0-9]*)-[a-z0-9][a-z0-9_-]*|(?:[
106
121
  export interface CommentRuns {
107
122
  /** GitHub: `POST /repos/{repo}/actions/runs/{run}/rerun-failed-jobs`. */
108
123
  rerunFailed(run: number): Promise<StartedRun>;
109
- /** Forgejo: `POST /repos/{repo}/actions/workflows/{workflow}/dispatches` on `ref`. */
110
- dispatch(workflow: string, ref: string): Promise<StartedRun>;
124
+ /** Forgejo (and before merge, #4984, both): `POST /repos/{repo}/actions/workflows/{workflow}/dispatches` on `ref`, with `inputs`. */
125
+ dispatch(workflow: string, ref: string, inputs?: Record<string, string>): Promise<StartedRun>;
111
126
  }
112
127
 
113
128
  /** The writes for a GitHub or Forgejo API root, repository and token. */
@@ -123,7 +138,7 @@ export function commentRuns(opts: { apiBase: string; repo: string; token: string
123
138
  };
124
139
  return {
125
140
  rerunFailed: (run) => post(`/actions/runs/${run}/rerun-failed-jobs`, {}),
126
- dispatch: (workflow, ref) => post(`/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, { ref }),
141
+ dispatch: (workflow, ref, inputs) => post(`/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, { ref, ...(inputs ? { inputs } : {}) }),
127
142
  };
128
143
  }
129
144
 
@@ -150,6 +165,8 @@ export interface AnswerCommentOptions {
150
165
  stops?: CommentWaveStops;
151
166
  /** The time a stop is written at. Default now. */
152
167
  now?: () => string;
168
+ /** With `jobs.wavesBeforeMerge` (#4984): what the decision reads and writes with. Absent: an open pull request's apply is refused, as before. */
169
+ beforeMerge?: CommentBeforeMerge;
153
170
  }
154
171
 
155
172
  /** What the comment job did. */
@@ -281,7 +298,7 @@ export async function answerProductComment(o: AnswerCommentOptions): Promise<Com
281
298
  }
282
299
 
283
300
  // An apply: the apply before merge answers an open pull request; this job a merged one, with applyOnMerge.
284
- if (!o.jobs.applyBeforeMerge && !o.jobs.applyOnMerge) return reply(notRunReply(o.words, "apply", o.forge));
301
+ if (!o.jobs.applyBeforeMerge && !o.jobs.applyOnMerge && !o.jobs.wavesBeforeMerge) return reply(notRunReply(o.words, "apply", o.forge));
285
302
  let pr: PullRequestDetail | undefined;
286
303
  try {
287
304
  pr = await o.reads.pullRequest(n);
@@ -293,6 +310,28 @@ export async function answerProductComment(o: AnswerCommentOptions): Promise<Com
293
310
  const verb = o.words.verbs.apply;
294
311
  if (pr.state === "open") {
295
312
  if (o.jobs.applyBeforeMerge) return silent("the apply before merge answers this comment", command);
313
+ // #4984: the waves before merge: decide, record the head and dispatch the waves workflow for it.
314
+ const bm = o.jobs.wavesBeforeMerge;
315
+ if (bm && o.jobs.waves && o.beforeMerge) {
316
+ const workflow = bm.workflow;
317
+ if (!workflow) return broke("the waves before merge name no workflow to dispatch", command);
318
+ const { decideWavesBeforeMerge } = await import("./op/before-merge-decide");
319
+ const done = await decideWavesBeforeMerge({
320
+ ...o.beforeMerge,
321
+ forge: o.forge,
322
+ pr,
323
+ user,
324
+ base: o.base,
325
+ ...(parsed.wave !== undefined ? { wave: parsed.wave } : {}),
326
+ op: o.jobs.waves.op,
327
+ count: o.jobs.waves.count,
328
+ jobs: bm,
329
+ words: o.words,
330
+ start: (r) => o.runs.dispatch(workflow, o.base, { pr: String(r.pr), head: r.head, digest: r.digest }),
331
+ });
332
+ if (done.kind === "fail") return broke(done.reason, command);
333
+ return reply(done.text, done.kind === "ran", done.kind === "ran" ? done.url : undefined);
334
+ }
296
335
  return reply(`${at} is not merged: \`/${o.words.product} ${typedApply(o.words)}\` runs the ${verb[0]} of a merged ${t.request} again, from the default branch, and never ${verb[0]}s a ${t.request}'s branch`);
297
336
  }
298
337
  if (pr.state === "closed") return reply(`${at} was closed without merging, so there is nothing of it to ${verb[0]}`);
@@ -28,7 +28,6 @@ import {
28
28
  unzipEntry,
29
29
  type CiTool,
30
30
  } from "./ci-image";
31
- import { NEXT_RELEASE } from "./release-floors";
32
31
 
33
32
  const tmp = (): string => mkdtempSync(join(tmpdir(), "ci-image-"));
34
33
  const sha = (b: Uint8Array): string => createHash("sha256").update(b).digest("hex");
@@ -209,7 +208,7 @@ describe("ciToolRelease", () => {
209
208
  expect(CI_IMAGE_FLOOR).toBe("0.124.86");
210
209
  expect(CI_IMAGE_NON_ROOT_FLOOR).toBe("0.124.88");
211
210
  expect(CI_IMAGE_DOCKER_STAGES_FLOOR).toBe("0.124.88");
212
- expect(CI_TOOL_NODE_DOWNLOAD_FLOOR).toBe(NEXT_RELEASE);
211
+ expect(CI_TOOL_NODE_DOWNLOAD_FLOOR).toBe("0.124.89");
213
212
  });
214
213
  });
215
214
 
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The guard before merge (#4984): a waves run started for an open pull
3
+ * request's head is admitted only as the decision recorded for that head on
4
+ * `chant/lifecycle`, and every other run that names a head is refused. The
5
+ * `node -e` program reads the decision from a real repository and agrees
6
+ * with checkJob.
7
+ */
8
+
9
+ import { spawnSync } from "node:child_process";
10
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { beforeAll, describe, expect, test } from "vitest";
14
+ import { checkJob, describeJobGuard, JOB_GUARD_ENV, JOB_GUARD_JS, jobGuardSpec, jobSeen, type JobGuardSpec } from "./ci-job-guard";
15
+ import { CHANT_EXIT } from "./exit-codes";
16
+ import { beforeMergeDigest, beforeMergePath, renderBeforeMerge, type BeforeMergeRecord } from "./op/before-merge";
17
+
18
+ const HEAD = "a".repeat(40);
19
+ const OTHER = "b".repeat(40);
20
+ const BASE = "c".repeat(40);
21
+ const decision = { pr: 7, head: HEAD, base: BASE, at: "2026-11-10T12:00:00.000Z", by: "alice" };
22
+ const record: BeforeMergeRecord = { ...decision, digest: beforeMergeDigest("deploy", decision) };
23
+
24
+ const gh: JobGuardSpec = { forge: "github", job: "wave 1 (prod) of deploy", branches: ["main"], beforeMerge: { op: "deploy" } };
25
+ const gl: JobGuardSpec = { forge: "gitlab", job: "wave 1 (prod) of deploy", branches: ["main"], beforeMerge: { op: "deploy" } };
26
+ const run = { pr: "7", head: HEAD, digest: record.digest };
27
+
28
+ describe("checkJob before merge", () => {
29
+ test("the decided head, on the default branch, runs", () => {
30
+ const r = checkJob(gh, { ref: "refs/heads/main", beforeMerge: run, beforeMergeRecord: record });
31
+ expect(r.problems).toEqual([]);
32
+ expect(r.checked).toEqual(["ref refs/heads/main", `before merge: pull request 7's decided head ${HEAD.slice(0, 12)}`]);
33
+ });
34
+
35
+ test("a push run names no head and is checked as before", () => {
36
+ expect(checkJob(gh, { ref: "refs/heads/main" }).checked).toEqual(["ref refs/heads/main"]);
37
+ });
38
+
39
+ test("a head no decision names is refused", () => {
40
+ const r = checkJob(gh, { ref: "refs/heads/main", beforeMerge: { ...run, head: OTHER }, beforeMergeRecord: null });
41
+ expect(r.problems).toEqual([`before merge: no decision on chant/lifecycle names head ${OTHER.slice(0, 12)} of deploy, so this run applies nothing`]);
42
+ });
43
+
44
+ test("another pull request's run, another digest, and a decision edited by hand are refused", () => {
45
+ expect(checkJob(gh, { ref: "refs/heads/main", beforeMerge: { ...run, pr: "8" }, beforeMergeRecord: record }).problems).toEqual([`before merge: the decision for head ${HEAD.slice(0, 12)} is pull request 7's, not 8's`]);
46
+ const other = `sha256:${"0".repeat(64)}`;
47
+ expect(checkJob(gh, { ref: "refs/heads/main", beforeMerge: { ...run, digest: other }, beforeMergeRecord: record }).problems).toEqual([`before merge: the run carries digest ${other}, and the decision for head ${HEAD.slice(0, 12)} has ${record.digest}`]);
48
+ expect(checkJob(gh, { ref: "refs/heads/main", beforeMerge: run, beforeMergeRecord: { ...record, through: 1 } }).problems).toEqual([`before merge: the decision for head ${HEAD.slice(0, 12)} was changed after it was made: its fields give another digest`]);
49
+ });
50
+
51
+ test("a decided head started on another ref is refused for the ref", () => {
52
+ const r = checkJob(gh, { ref: "refs/heads/feature", beforeMerge: run, beforeMergeRecord: record });
53
+ expect(r.problems).toEqual(["ref: expected refs/heads/main, found refs/heads/feature"]);
54
+ const l = checkJob(gl, { ref: "feature", refProtected: "false", forgeEnvironment: null, beforeMerge: run, beforeMergeRecord: record });
55
+ expect(l.problems).toEqual(["ref: expected main, found feature", "ref: expected a protected ref (CI_COMMIT_REF_PROTECTED true), found false"]);
56
+ });
57
+
58
+ test("a job without the before-merge mode refuses any run that names a head", () => {
59
+ const spec: JobGuardSpec = { forge: "github", job: "w", branches: ["main"] };
60
+ expect(checkJob(spec, { ref: "refs/heads/main", beforeMerge: run }).problems).toEqual([`before merge: the run names pull request 7's head ${HEAD}, and this job applies only the pushes to its branches`]);
61
+ });
62
+
63
+ test("variables that are not a decision's, and a ledger that cannot be read", () => {
64
+ expect(checkJob(gh, { ref: "refs/heads/main", beforeMerge: { head: "main" } }).problems).toEqual([
65
+ "before merge: the run's pull request none is not a number",
66
+ 'before merge: the run\'s head "main" is not a commit sha',
67
+ "before merge: the run's digest none is not a sha256 digest",
68
+ ]);
69
+ expect(checkJob(gh, { ref: "refs/heads/main", beforeMerge: run, beforeMergeError: "no token" }).problems).toEqual(["before merge: the decisions on chant/lifecycle could not be read: no token"]);
70
+ });
71
+
72
+ test("jobGuardSpec carries the mode", () => {
73
+ expect(jobGuardSpec({ forge: "forgejo", job: "w", branches: ["main"], beforeMerge: { op: "deploy" } }).beforeMerge).toEqual({ op: "deploy" });
74
+ });
75
+
76
+ test("jobSeen reads the decision for the run's head only with the mode", async () => {
77
+ const env = { GITHUB_REF: "refs/heads/main", CHANT_BEFORE_MERGE_PR: "7", CHANT_BEFORE_MERGE_HEAD: HEAD, CHANT_BEFORE_MERGE_DIGEST: record.digest };
78
+ const read: string[] = [];
79
+ const reader = (_f: string, _e: NodeJS.ProcessEnv, path: string) => {
80
+ read.push(path);
81
+ return renderBeforeMerge({ version: 1, heads: { [HEAD]: record } });
82
+ };
83
+ const seen = await jobSeen(gh, env, fetch, reader);
84
+ expect(read).toEqual([beforeMergePath("deploy")]);
85
+ expect(seen.beforeMergeRecord).toEqual(record);
86
+ const plain = await jobSeen({ forge: "github", job: "w", branches: ["main"] }, env, fetch, reader);
87
+ expect(plain.beforeMergeRecord).toBeUndefined();
88
+ expect(read).toHaveLength(1);
89
+ });
90
+ });
91
+
92
+ describe("the node -e program reads the decision from chant/lifecycle", () => {
93
+ let server = "";
94
+ beforeAll(() => {
95
+ // A bare repository standing in for the forge, with the decisions file on chant/lifecycle.
96
+ server = mkdtempSync(join(tmpdir(), "chant-guard-forge-"));
97
+ const work = mkdtempSync(join(tmpdir(), "chant-guard-work-"));
98
+ const git = (cwd: string, ...args: string[]) => {
99
+ const r = spawnSync("git", args, { cwd, encoding: "utf-8", env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } });
100
+ if (r.status !== 0) throw new Error(r.stderr);
101
+ };
102
+ mkdirSync(join(server, "acme"), { recursive: true });
103
+ git(join(server, "acme"), "init", "-q", "--bare", "infra.git");
104
+ git(work, "init", "-q", "-b", "chant/lifecycle");
105
+ mkdirSync(join(work, "_waves"));
106
+ writeFileSync(join(work, beforeMergePath("deploy")), renderBeforeMerge({ version: 1, heads: { [HEAD]: record } }));
107
+ git(work, "add", ".");
108
+ git(work, "commit", "-q", "-m", "decide");
109
+ git(work, "push", "-q", join(server, "acme", "infra.git"), "chant/lifecycle");
110
+ });
111
+
112
+ const run = (spec: JobGuardSpec, env: Record<string, string>) =>
113
+ spawnSync(process.execPath, ["-e", JOB_GUARD_JS], { env: { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "", [JOB_GUARD_ENV]: JSON.stringify(spec), ...env }, encoding: "utf-8" });
114
+ const forgeEnv = (spec: JobGuardSpec): Record<string, string> =>
115
+ spec.forge === "gitlab"
116
+ ? { CI_SERVER_URL: `file://${server}`, CI_PROJECT_PATH: "acme/infra", CI_JOB_TOKEN: "t", CI_COMMIT_REF_NAME: "main", CI_COMMIT_REF_PROTECTED: "true" }
117
+ : { GITHUB_SERVER_URL: `file://${server}`, GITHUB_REPOSITORY: "acme/infra", GITHUB_TOKEN: "t", GITHUB_REF: "refs/heads/main" };
118
+
119
+ const cases: Array<[string, JobGuardSpec, Record<string, string>]> = [
120
+ ["GitHub: the decided head", gh, { CHANT_BEFORE_MERGE_PR: "7", CHANT_BEFORE_MERGE_HEAD: HEAD, CHANT_BEFORE_MERGE_DIGEST: record.digest }],
121
+ ["GitLab: the decided head", gl, { CHANT_BEFORE_MERGE_PR: "7", CHANT_BEFORE_MERGE_HEAD: HEAD, CHANT_BEFORE_MERGE_DIGEST: record.digest }],
122
+ ["Forgejo: a head nothing decided", { ...gh, forge: "forgejo" }, { CHANT_BEFORE_MERGE_PR: "7", CHANT_BEFORE_MERGE_HEAD: OTHER, CHANT_BEFORE_MERGE_DIGEST: record.digest }],
123
+ ["GitHub: another pull request's number", gh, { CHANT_BEFORE_MERGE_PR: "9", CHANT_BEFORE_MERGE_HEAD: HEAD, CHANT_BEFORE_MERGE_DIGEST: record.digest }],
124
+ ["GitHub: the decided head dispatched on another branch", gh, { GITHUB_REF: "refs/heads/feature", CHANT_BEFORE_MERGE_PR: "7", CHANT_BEFORE_MERGE_HEAD: HEAD, CHANT_BEFORE_MERGE_DIGEST: record.digest }],
125
+ ["GitLab: a head that is not a sha", gl, { CHANT_BEFORE_MERGE_HEAD: "refs/heads/feature" }],
126
+ ["GitHub: no mode, and a run that names a head", { forge: "github", job: "w", branches: ["main"] }, { CHANT_BEFORE_MERGE_HEAD: HEAD }],
127
+ ];
128
+
129
+ for (const [name, spec, extra] of cases) {
130
+ test(name, async () => {
131
+ const env = { ...forgeEnv(spec), ...extra };
132
+ const r = run(spec, env);
133
+ const want = describeJobGuard(spec, checkJob(spec, await jobSeen(spec, { ...process.env, ...env }, (() => Promise.reject(new Error("no fetch"))) as unknown as typeof fetch)));
134
+ expect(r.status).toBe(want.ok ? 0 : CHANT_EXIT.misplaced);
135
+ expect(r.stdout.trim().split("\n").filter(Boolean)).toEqual(want.out);
136
+ expect(r.stderr.trim().split("\n").filter(Boolean)).toEqual(want.err);
137
+ });
138
+ }
139
+
140
+ test("the decided head is admitted, and any other ref refused", async () => {
141
+ expect(run(gh, { ...forgeEnv(gh), CHANT_BEFORE_MERGE_PR: "7", CHANT_BEFORE_MERGE_HEAD: HEAD, CHANT_BEFORE_MERGE_DIGEST: record.digest }).status).toBe(0);
142
+ for (const head of [OTHER, BASE]) {
143
+ const r = run(gh, { ...forgeEnv(gh), CHANT_BEFORE_MERGE_PR: "7", CHANT_BEFORE_MERGE_HEAD: head, CHANT_BEFORE_MERGE_DIGEST: record.digest });
144
+ expect(r.status).toBe(CHANT_EXIT.misplaced);
145
+ expect(r.stderr).toContain(`no decision on chant/lifecycle names head ${head.slice(0, 12)}`);
146
+ }
147
+ });
148
+ });
@@ -0,0 +1,137 @@
1
+ /**
2
+ * #4998: the guard admits a follow-on run only for the wave the newest
3
+ * record job of its chain started, as its record on `chant/lifecycle`
4
+ * names it. A wave started by hand past it (wave N+3 of a chain at N+1),
5
+ * or an earlier wave run again after the chain went on, is refused, on
6
+ * each forge, by checkJob and by the `node -e` program alike.
7
+ */
8
+
9
+ import { spawnSync } from "node:child_process";
10
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { beforeAll, describe, expect, test } from "vitest";
14
+ import { checkJob, describeJobGuard, JOB_GUARD_ENV, JOB_GUARD_JS, jobSeen, type JobGuardForge, type JobGuardSpec } from "./ci-job-guard";
15
+ import { CHANT_EXIT } from "./exit-codes";
16
+ import { beforeMergeDigest, beforeMergePath, renderBeforeMerge, type BeforeMergeRecord } from "./op/before-merge";
17
+ import { followOnPath, followOnRecordProblems, parseFollowOn, renderFollowOn, type FollowOnRecord } from "./op/follow-on-run";
18
+
19
+ const HEAD = "a".repeat(40);
20
+ const BASE = "c".repeat(40);
21
+ const PUSHED = "d".repeat(40);
22
+ const UNRECORDED = "e".repeat(40);
23
+ const decision = { pr: 7, head: HEAD, base: BASE, at: "2026-11-10T12:00:00.000Z", by: "alice" };
24
+ const record: BeforeMergeRecord = { ...decision, digest: beforeMergeDigest("deploy", decision) };
25
+ const decided = { CHANT_BEFORE_MERGE_PR: "7", CHANT_BEFORE_MERGE_HEAD: HEAD, CHANT_BEFORE_MERGE_DIGEST: record.digest };
26
+
27
+ // The rest wave is wave 3 (N); its record job started wave 4 (N+1), which is where each chain stands.
28
+ const chained = (key: string, wave: number, extra: Partial<FollowOnRecord> = {}): FollowOnRecord => ({ key, wave, from: wave - 1, run: "41", at: "2026-11-10T12:30:00.000Z", outcomes: { vpc: { status: "applied", wave: 3, at: "2026-11-10T12:20:00.000Z" } }, ...extra });
29
+ const headChain = chained(HEAD, 4, { pr: 7, digest: record.digest });
30
+ const pushChain = chained(PUSHED, 4, { commit: PUSHED });
31
+ const restOn = (forge: JobGuardForge): JobGuardSpec => ({ forge, job: "the plan job of wave 3 (rest) of deploy", branches: ["main"], beforeMerge: { op: "deploy" }, rest: 3 });
32
+
33
+ describe("the follow-on records (#4998)", () => {
34
+ test("parse keeps a well-formed entry, drops a malformed one, and renders the newest chains", () => {
35
+ const text = renderFollowOn({ version: 1, chains: { [HEAD]: headChain, [PUSHED]: pushChain } });
36
+ expect(parseFollowOn(text).chains).toEqual({ [HEAD]: headChain, [PUSHED]: pushChain });
37
+ const bad = JSON.stringify({ version: 1, chains: { [HEAD]: { ...headChain, wave: 1 }, [PUSHED]: { ...pushChain, key: HEAD }, main: pushChain } });
38
+ expect(parseFollowOn(bad).chains).toEqual({});
39
+ expect(parseFollowOn("not json").chains).toEqual({});
40
+ expect(followOnPath("deploy")).toBe("_waves/deploy.follow-on.json");
41
+ });
42
+
43
+ test("the lines: no record, another wave, another decision", () => {
44
+ expect(followOnRecordProblems("deploy", "4", HEAD, record.digest, headChain)).toEqual([]);
45
+ expect(followOnRecordProblems("deploy", "6", HEAD, record.digest, headChain)).toEqual([`follow-on: the newest record job of deploy for head ${HEAD.slice(0, 12)} started wave 4, and this run names wave 6`]);
46
+ expect(followOnRecordProblems("deploy", "4", UNRECORDED, undefined, null)).toEqual([`follow-on: no record job of deploy started a follow-on for commit ${UNRECORDED.slice(0, 12)}, so this run applies nothing`]);
47
+ });
48
+ });
49
+
50
+ describe("checkJob refuses a follow-on its chain's record does not name (#4998)", () => {
51
+ const at = { ref: "refs/heads/main" };
52
+ for (const forge of ["github", "gitlab", "forgejo"] as const) {
53
+ const seenAt = forge === "gitlab" ? { ref: "main", refProtected: "true" } : at;
54
+ test(`${forge}: a wave started by hand past the chain's (wave 6 of a chain at wave 4) is refused`, () => {
55
+ const r = checkJob(restOn(forge), { ...seenAt, beforeMerge: { pr: "7", head: HEAD, digest: record.digest }, beforeMergeRecord: record, followOn: { wave: "6" }, followOnRecord: headChain });
56
+ expect(r.problems).toEqual([`follow-on: the newest record job of deploy for head ${HEAD.slice(0, 12)} started wave 4, and this run names wave 6`]);
57
+ expect(r.checked).not.toContain("follow-on wave 6");
58
+ const push = checkJob(restOn(forge), { ...seenAt, followOn: { wave: "6", commit: PUSHED }, followOnRecord: pushChain });
59
+ expect(push.problems).toEqual([`follow-on: the newest record job of deploy for commit ${PUSHED.slice(0, 12)} started wave 4, and this run names wave 6`]);
60
+ });
61
+ }
62
+
63
+ test("an earlier wave run again once the chain went on is refused; the wave the record names is admitted", () => {
64
+ const moved = chained(PUSHED, 5, { commit: PUSHED });
65
+ expect(checkJob(restOn("github"), { ...at, followOn: { wave: "4", commit: PUSHED }, followOnRecord: moved }).problems).toEqual([
66
+ `follow-on: the newest record job of deploy for commit ${PUSHED.slice(0, 12)} started wave 5, and this run names wave 4`,
67
+ ]);
68
+ expect(checkJob(restOn("github"), { ...at, followOn: { wave: "5", commit: PUSHED }, followOnRecord: moved }).checked).toContain(`follow-on wave 5 at ${PUSHED.slice(0, 12)}`);
69
+ });
70
+
71
+ test("records that cannot be read refuse the run, and a run that is no follow-on reads none", async () => {
72
+ expect(checkJob(restOn("github"), { ...at, followOn: { wave: "4", commit: PUSHED }, followOnError: "could not fetch chant/lifecycle: denied" }).problems).toEqual([
73
+ "follow-on: the follow-on records on chant/lifecycle could not be read: could not fetch chant/lifecycle: denied",
74
+ ]);
75
+ const reads: string[] = [];
76
+ const reader = (_f: JobGuardForge, _e: NodeJS.ProcessEnv, path: string) => (reads.push(path), null);
77
+ await jobSeen(restOn("github"), { GITHUB_REF: "refs/heads/main", CHANT_WAVES_WAVE: "3" }, fetch, reader);
78
+ await jobSeen(restOn("github"), { GITHUB_REF: "refs/heads/main", CHANT_WAVES_WAVE: "2", CHANT_WAVES_COMMIT: PUSHED }, fetch, reader);
79
+ expect(reads).toEqual([]);
80
+ const seen = await jobSeen(restOn("github"), { GITHUB_REF: "refs/heads/main", CHANT_WAVES_WAVE: "4", CHANT_WAVES_COMMIT: PUSHED }, fetch, reader);
81
+ expect(reads).toEqual(["_waves/deploy.follow-on.json"]);
82
+ expect(seen.followOnRecord).toBeNull();
83
+ });
84
+ });
85
+
86
+ describe("the node -e program agrees on each forge (#4998)", () => {
87
+ let server = "";
88
+ beforeAll(() => {
89
+ server = mkdtempSync(join(tmpdir(), "chant-guard-follow-on-record-"));
90
+ const work = mkdtempSync(join(tmpdir(), "chant-guard-follow-on-record-work-"));
91
+ const git = (cwd: string, ...args: string[]) => {
92
+ const r = spawnSync("git", args, { cwd, encoding: "utf-8", env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } });
93
+ if (r.status !== 0) throw new Error(r.stderr);
94
+ };
95
+ mkdirSync(join(server, "acme"), { recursive: true });
96
+ git(join(server, "acme"), "init", "-q", "--bare", "infra.git");
97
+ git(work, "init", "-q", "-b", "chant/lifecycle");
98
+ mkdirSync(join(work, "_waves"));
99
+ writeFileSync(join(work, beforeMergePath("deploy")), renderBeforeMerge({ version: 1, heads: { [HEAD]: record } }));
100
+ writeFileSync(join(work, followOnPath("deploy")), renderFollowOn({ version: 1, chains: { [HEAD]: headChain, [PUSHED]: pushChain } }));
101
+ git(work, "add", ".");
102
+ git(work, "commit", "-q", "-m", "decide and follow on");
103
+ git(work, "push", "-q", join(server, "acme", "infra.git"), "chant/lifecycle");
104
+ });
105
+
106
+ const node = (spec: JobGuardSpec, env: Record<string, string>) =>
107
+ spawnSync(process.execPath, ["-e", JOB_GUARD_JS], { env: { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "", [JOB_GUARD_ENV]: JSON.stringify(spec), ...env }, encoding: "utf-8" });
108
+ const forgeEnv = (forge: JobGuardForge): Record<string, string> =>
109
+ forge === "gitlab"
110
+ ? { CI_SERVER_URL: `file://${server}`, CI_PROJECT_PATH: "acme/infra", CI_JOB_TOKEN: "t", CI_COMMIT_REF_NAME: "main", CI_COMMIT_REF_PROTECTED: "true" }
111
+ : { GITHUB_SERVER_URL: `file://${server}`, GITHUB_REPOSITORY: "acme/infra", GITHUB_TOKEN: "t", GITHUB_REF: "refs/heads/main" };
112
+
113
+ const cases: Array<[string, JobGuardForge, Record<string, string>, boolean]> = [];
114
+ for (const forge of ["github", "gitlab", "forgejo"] as const) {
115
+ cases.push(
116
+ [`${forge}: the wave the record job started, of the decided head`, forge, { ...decided, CHANT_WAVES_WAVE: "4" }, true],
117
+ [`${forge}: a wave started by hand past it, of the decided head`, forge, { ...decided, CHANT_WAVES_WAVE: "6" }, false],
118
+ [`${forge}: the wave the record job started, of a push`, forge, { CHANT_WAVES_WAVE: "4", CHANT_WAVES_COMMIT: PUSHED }, true],
119
+ [`${forge}: a wave started by hand past it, of a push`, forge, { CHANT_WAVES_WAVE: "6", CHANT_WAVES_COMMIT: PUSHED }, false],
120
+ [`${forge}: a push no record job followed on`, forge, { CHANT_WAVES_WAVE: "4", CHANT_WAVES_COMMIT: UNRECORDED }, false],
121
+ );
122
+ }
123
+
124
+ for (const [name, forge, extra, ok] of cases) {
125
+ test(name, async () => {
126
+ const spec = restOn(forge);
127
+ const env = { ...forgeEnv(forge), ...extra };
128
+ const r = node(spec, env);
129
+ const want = describeJobGuard(spec, checkJob(spec, await jobSeen(spec, { ...process.env, ...env }, (() => Promise.reject(new Error("no fetch"))) as unknown as typeof fetch)));
130
+ expect(want.ok).toBe(ok);
131
+ expect(r.status).toBe(ok ? 0 : CHANT_EXIT.misplaced);
132
+ expect(r.stdout.trim().split("\n").filter(Boolean)).toEqual(want.out);
133
+ expect(r.stderr.trim().split("\n").filter(Boolean)).toEqual(want.err);
134
+ if (!ok) expect(want.err[0]).toMatch(/follow-on: (the newest record job of deploy .* started wave 4, and this run names wave 6|no record job of deploy started a follow-on)/);
135
+ });
136
+ }
137
+ });
@@ -0,0 +1,144 @@
1
+ /**
2
+ * #4992: the guard admits a follow-on run of the rest wave only in a job of
3
+ * the rest wave, only for a wave after it, and only as the same decided
4
+ * head: a follow-on for another head or digest is refused as any run of
5
+ * one is. A push's follow-on names its commit. The `node -e` program agrees
6
+ * with checkJob, reading the decision from a real repository.
7
+ */
8
+
9
+ import { spawnSync } from "node:child_process";
10
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { beforeAll, describe, expect, test } from "vitest";
14
+ import { checkJob, describeJobGuard, JOB_GUARD_ENV, JOB_GUARD_JS, jobGuardSpec, jobSeen, parseJobGuardSpec, type JobGuardSpec } from "./ci-job-guard";
15
+ import { CHANT_EXIT } from "./exit-codes";
16
+ import { beforeMergeDigest, beforeMergePath, renderBeforeMerge, type BeforeMergeRecord } from "./op/before-merge";
17
+ import { followOnPath, renderFollowOn, type FollowOnRecord } from "./op/follow-on-run";
18
+
19
+ const HEAD = "a".repeat(40);
20
+ const OTHER = "b".repeat(40);
21
+ const BASE = "c".repeat(40);
22
+ const PUSHED = "d".repeat(40);
23
+ const decision = { pr: 7, head: HEAD, base: BASE, at: "2026-11-10T12:00:00.000Z", by: "alice" };
24
+ const record: BeforeMergeRecord = { ...decision, digest: beforeMergeDigest("deploy", decision) };
25
+ const run = { pr: "7", head: HEAD, digest: record.digest };
26
+
27
+ /** #4998: the record a record job wrote when it started wave `wave` of the chain keyed `key`. */
28
+ const chained = (key: string, wave: number, extra: Partial<FollowOnRecord> = {}): FollowOnRecord => ({ key, wave, from: wave - 1, run: "41", at: "2026-11-10T12:30:00.000Z", outcomes: {}, ...extra });
29
+ const headChain = chained(HEAD, 4, { pr: 7, digest: record.digest });
30
+ const pushChain = chained(PUSHED, 4, { commit: PUSHED });
31
+
32
+ const rest: JobGuardSpec ={ forge: "github", job: "the plan job of wave 3 (rest) of deploy", branches: ["main"], beforeMerge: { op: "deploy" }, rest: 3 };
33
+ const earlier: JobGuardSpec = { forge: "github", job: "the plan job of wave 2 (layer) of deploy", branches: ["main"], beforeMerge: { op: "deploy" } };
34
+ const at = { ref: "refs/heads/main" };
35
+
36
+ describe("checkJob in a follow-on run (#4992)", () => {
37
+ test("the rest wave's jobs admit a follow-on of the decided head for a later wave", () => {
38
+ const r = checkJob(rest, { ...at, beforeMerge: run, beforeMergeRecord: record, followOn: { wave: "4" }, followOnRecord: headChain });
39
+ expect(r.problems).toEqual([]);
40
+ expect(r.checked).toEqual(["ref refs/heads/main", `before merge: pull request 7's decided head ${HEAD.slice(0, 12)}`, "follow-on wave 4"]);
41
+ });
42
+
43
+ test("a follow-on for another head or another digest is refused", () => {
44
+ expect(checkJob(rest, { ...at, beforeMerge: { ...run, head: OTHER }, beforeMergeRecord: null, followOn: { wave: "4" }, followOnRecord: null }).problems).toEqual([
45
+ `before merge: no decision on chant/lifecycle names head ${OTHER.slice(0, 12)} of deploy, so this run applies nothing`,
46
+ `follow-on: no record job of deploy started a follow-on for head ${OTHER.slice(0, 12)}, so this run applies nothing`,
47
+ ]);
48
+ const other = `sha256:${"0".repeat(64)}`;
49
+ expect(checkJob(rest, { ...at, beforeMerge: { ...run, digest: other }, beforeMergeRecord: record, followOn: { wave: "4" }, followOnRecord: headChain }).problems).toEqual([
50
+ `before merge: the run carries digest ${other}, and the decision for head ${HEAD.slice(0, 12)} has ${record.digest}`,
51
+ `follow-on: wave 4 of head ${HEAD.slice(0, 12)} was started for the decision with digest ${record.digest}, and the run carries ${other}`,
52
+ ]);
53
+ });
54
+
55
+ test("the rest wave's own number is no follow-on, and a run that is none is checked as before", () => {
56
+ expect(checkJob(rest, { ...at, beforeMerge: run, beforeMergeRecord: record, followOn: { wave: "3" } }).problems).toEqual([]);
57
+ expect(checkJob(rest, { ...at }).checked).toEqual(["ref refs/heads/main"]);
58
+ expect(checkJob(earlier, { ...at }).checked).toEqual(["ref refs/heads/main"]);
59
+ });
60
+
61
+ test("a wave that is not after the rest wave, a job of another wave, and a commit beside a decided head are refused", () => {
62
+ expect(checkJob(rest, { ...at, beforeMerge: run, beforeMergeRecord: record, followOn: { wave: "2" } }).problems).toEqual(['follow-on: the run\'s wave "2" is no wave after wave 3']);
63
+ expect(checkJob(rest, { ...at, beforeMerge: run, beforeMergeRecord: record, followOn: { wave: "4; rm -rf /" } }).problems).toEqual(['follow-on: the run\'s wave "4; rm -rf /" is no wave after wave 3']);
64
+ expect(checkJob(earlier, { ...at, beforeMerge: run, beforeMergeRecord: record, followOn: { wave: "4" } }).problems).toEqual([
65
+ "follow-on: the run names wave 4 and commit none, and this job is none of the rest wave's, which alone runs in a follow-on",
66
+ ]);
67
+ expect(checkJob(rest, { ...at, beforeMerge: run, beforeMergeRecord: record, followOn: { wave: "4", commit: PUSHED } }).problems).toEqual([
68
+ `follow-on: a follow-on of a decided head checks out that head, and the run names the commit ${PUSHED} too`,
69
+ ]);
70
+ });
71
+
72
+ test("a push's follow-on names the commit it goes on with", () => {
73
+ const r = checkJob(rest, { ...at, followOn: { wave: "4", commit: PUSHED }, followOnRecord: pushChain });
74
+ expect(r.problems).toEqual([]);
75
+ expect(r.checked).toEqual(["ref refs/heads/main", `follow-on wave 4 at ${PUSHED.slice(0, 12)}`]);
76
+ expect(checkJob(rest, { ...at, followOn: { wave: "4" } }).problems).toEqual(["follow-on: a push's follow-on names the commit it goes on with, and the run's none is not a commit sha"]);
77
+ expect(checkJob(rest, { ...at, followOn: { wave: "4", commit: "main" } }).problems).toEqual(['follow-on: a push\'s follow-on names the commit it goes on with, and the run\'s "main" is not a commit sha']);
78
+ expect(checkJob(rest, { ...at, followOn: { commit: PUSHED } }).problems).toEqual([`follow-on: the run names the commit ${PUSHED} and no wave after wave 3, so it is no follow-on`]);
79
+ });
80
+
81
+ test("jobGuardSpec carries the rest wave, the parse checks it, and jobSeen reads the variables", async () => {
82
+ expect(jobGuardSpec({ forge: "gitlab", job: "w", branches: ["main"], rest: 3 }).rest).toBe(3);
83
+ expect(() => parseJobGuardSpec(JSON.stringify({ ...rest, rest: "3" }))).toThrow("rest is the rest wave's number");
84
+ const seen = await jobSeen(rest, { GITHUB_REF: "refs/heads/main", CHANT_WAVES_WAVE: " 4 ", CHANT_WAVES_COMMIT: PUSHED });
85
+ expect(seen.followOn).toEqual({ wave: "4", commit: PUSHED });
86
+ expect((await jobSeen(rest, { GITHUB_REF: "refs/heads/main" })).followOn).toBeUndefined();
87
+ });
88
+ });
89
+
90
+ describe("the node -e program agrees in a follow-on run", () => {
91
+ let server = "";
92
+ beforeAll(() => {
93
+ server = mkdtempSync(join(tmpdir(), "chant-guard-follow-on-"));
94
+ const work = mkdtempSync(join(tmpdir(), "chant-guard-follow-on-work-"));
95
+ const git = (cwd: string, ...args: string[]) => {
96
+ const r = spawnSync("git", args, { cwd, encoding: "utf-8", env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } });
97
+ if (r.status !== 0) throw new Error(r.stderr);
98
+ };
99
+ mkdirSync(join(server, "acme"), { recursive: true });
100
+ git(join(server, "acme"), "init", "-q", "--bare", "infra.git");
101
+ git(work, "init", "-q", "-b", "chant/lifecycle");
102
+ mkdirSync(join(work, "_waves"));
103
+ writeFileSync(join(work, beforeMergePath("deploy")), renderBeforeMerge({ version: 1, heads: { [HEAD]: record } }));
104
+ writeFileSync(join(work, followOnPath("deploy")), renderFollowOn({ version: 1, chains: { [HEAD]: headChain, [PUSHED]: pushChain } }));
105
+ git(work, "add", ".");
106
+ git(work, "commit", "-q", "-m", "decide");
107
+ git(work, "push", "-q", join(server, "acme", "infra.git"), "chant/lifecycle");
108
+ });
109
+
110
+ const node = (spec: JobGuardSpec, env: Record<string, string>) =>
111
+ spawnSync(process.execPath, ["-e", JOB_GUARD_JS], { env: { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "", [JOB_GUARD_ENV]: JSON.stringify(spec), ...env }, encoding: "utf-8" });
112
+ const forgeEnv = (spec: JobGuardSpec): Record<string, string> =>
113
+ spec.forge === "gitlab"
114
+ ? { CI_SERVER_URL: `file://${server}`, CI_PROJECT_PATH: "acme/infra", CI_JOB_TOKEN: "t", CI_COMMIT_REF_NAME: "main", CI_COMMIT_REF_PROTECTED: "true" }
115
+ : { GITHUB_SERVER_URL: `file://${server}`, GITHUB_REPOSITORY: "acme/infra", GITHUB_TOKEN: "t", GITHUB_REF: "refs/heads/main" };
116
+ const decided = { CHANT_BEFORE_MERGE_PR: "7", CHANT_BEFORE_MERGE_HEAD: HEAD, CHANT_BEFORE_MERGE_DIGEST: record.digest };
117
+ const gl: JobGuardSpec = { ...rest, forge: "gitlab" };
118
+ const fj: JobGuardSpec = { ...rest, forge: "forgejo" };
119
+
120
+ const cases: Array<[string, JobGuardSpec, Record<string, string>, boolean]> = [
121
+ ["GitHub: a follow-on of the decided head", rest, { ...decided, CHANT_WAVES_WAVE: "4" }, true],
122
+ ["GitLab: a follow-on of the decided head", gl, { ...decided, CHANT_WAVES_WAVE: "4" }, true],
123
+ ["Forgejo: a push's follow-on", fj, { CHANT_WAVES_WAVE: "4", CHANT_WAVES_COMMIT: PUSHED }, true],
124
+ ["GitHub: the rest wave's own number in a run that is none", rest, { ...decided, CHANT_WAVES_WAVE: "3" }, true],
125
+ ["GitHub: a follow-on for another head", rest, { ...decided, CHANT_BEFORE_MERGE_HEAD: OTHER, CHANT_WAVES_WAVE: "4" }, false],
126
+ ["GitLab: a follow-on for another digest", gl, { ...decided, CHANT_BEFORE_MERGE_DIGEST: `sha256:${"0".repeat(64)}`, CHANT_WAVES_WAVE: "4" }, false],
127
+ ["Forgejo: a follow-on in a job of an earlier wave", { ...earlier, forge: "forgejo" }, { ...decided, CHANT_WAVES_WAVE: "4" }, false],
128
+ ["GitHub: a wave before the rest wave", rest, { ...decided, CHANT_WAVES_WAVE: "1" }, false],
129
+ ["GitLab: a push's follow-on with no commit", gl, { CHANT_WAVES_WAVE: "4" }, false],
130
+ ["GitHub: a commit beside a decided head", rest, { ...decided, CHANT_WAVES_WAVE: "4", CHANT_WAVES_COMMIT: PUSHED }, false],
131
+ ];
132
+
133
+ for (const [name, spec, extra, ok] of cases) {
134
+ test(name, async () => {
135
+ const env = { ...forgeEnv(spec), ...extra };
136
+ const r = node(spec, env);
137
+ const want = describeJobGuard(spec, checkJob(spec, await jobSeen(spec, { ...process.env, ...env }, (() => Promise.reject(new Error("no fetch"))) as unknown as typeof fetch)));
138
+ expect(want.ok).toBe(ok);
139
+ expect(r.status).toBe(ok ? 0 : CHANT_EXIT.misplaced);
140
+ expect(r.stdout.trim().split("\n").filter(Boolean)).toEqual(want.out);
141
+ expect(r.stderr.trim().split("\n").filter(Boolean)).toEqual(want.err);
142
+ });
143
+ }
144
+ });