@intentius/chant 0.124.91 → 0.124.92

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 (69) hide show
  1. package/dist/ci-comment-commands.d.ts +11 -1
  2. package/dist/ci-comment-commands.d.ts.map +1 -1
  3. package/dist/ci-comment-commands.js +10 -3
  4. package/dist/ci-product.d.ts +18 -1
  5. package/dist/ci-product.d.ts.map +1 -1
  6. package/dist/ci-product.js +20 -3
  7. package/dist/cli/handlers/pr-comment.d.ts.map +1 -1
  8. package/dist/cli/handlers/pr-comment.js +15 -2
  9. package/dist/cli/handlers/pr.d.ts.map +1 -1
  10. package/dist/cli/handlers/pr.js +4 -1
  11. package/dist/components/pr-pipeline.d.ts +4 -2
  12. package/dist/components/pr-pipeline.d.ts.map +1 -1
  13. package/dist/components/pr-pipeline.js +7 -4
  14. package/dist/components/product-pipeline.d.ts +41 -7
  15. package/dist/components/product-pipeline.d.ts.map +1 -1
  16. package/dist/components/product-pipeline.js +57 -20
  17. package/dist/components/product-plan.d.ts +7 -0
  18. package/dist/components/product-plan.d.ts.map +1 -1
  19. package/dist/components/product-plan.js +1 -0
  20. package/dist/floor-table.data.d.ts.map +1 -1
  21. package/dist/floor-table.data.js +9 -5
  22. package/dist/lexicon.d.ts +42 -1
  23. package/dist/lexicon.d.ts.map +1 -1
  24. package/dist/op/before-merge-decide.d.ts +2 -0
  25. package/dist/op/before-merge-decide.d.ts.map +1 -1
  26. package/dist/op/op-waves-evidence-jobs.d.ts +3 -2
  27. package/dist/op/op-waves-evidence-jobs.d.ts.map +1 -1
  28. package/dist/op/op-waves-evidence-jobs.js +4 -3
  29. package/dist/op/op-waves-follow-on.d.ts +2 -0
  30. package/dist/op/op-waves-follow-on.d.ts.map +1 -1
  31. package/dist/op/op-waves-follow-on.js +8 -2
  32. package/dist/op/op-waves-names.d.ts +122 -0
  33. package/dist/op/op-waves-names.d.ts.map +1 -0
  34. package/dist/op/op-waves-names.js +151 -0
  35. package/dist/pr-forge-job.d.ts +8 -0
  36. package/dist/pr-forge-job.d.ts.map +1 -1
  37. package/dist/pr-forge-job.js +13 -0
  38. package/dist/pr-plan-record.d.ts +3 -1
  39. package/dist/pr-plan-record.d.ts.map +1 -1
  40. package/dist/pr-plan-record.js +1 -1
  41. package/dist/pr-post.d.ts +9 -3
  42. package/dist/pr-post.d.ts.map +1 -1
  43. package/dist/pr-post.js +5 -2
  44. package/dist/release-floors.d.ts +1 -1
  45. package/dist/release-floors.d.ts.map +1 -1
  46. package/dist/release-floors.js +4 -4
  47. package/dist/wave-runtime.mjs +258 -258
  48. package/package.json +1 -1
  49. package/src/ci-comment-commands.test.ts +19 -5
  50. package/src/ci-comment-commands.ts +18 -3
  51. package/src/ci-product.ts +24 -3
  52. package/src/cli/handlers/pr-comment.ts +12 -2
  53. package/src/cli/handlers/pr.ts +4 -1
  54. package/src/components/pr-pipeline.ts +7 -4
  55. package/src/components/product-job-names.test.ts +176 -0
  56. package/src/components/product-pipeline.ts +95 -28
  57. package/src/components/product-plan.ts +8 -0
  58. package/src/floor-table.data.ts +9 -5
  59. package/src/lexicon.ts +42 -1
  60. package/src/op/before-merge-decide.ts +2 -0
  61. package/src/op/op-waves-evidence-jobs.ts +4 -3
  62. package/src/op/op-waves-follow-on.ts +10 -2
  63. package/src/op/op-waves-names.test.ts +131 -0
  64. package/src/op/op-waves-names.ts +241 -0
  65. package/src/pr-forge-job.ts +13 -0
  66. package/src/pr-plan-record.ts +4 -2
  67. package/src/pr-post-head.test.ts +116 -0
  68. package/src/pr-post.ts +15 -5
  69. package/src/release-floors.ts +4 -4
@@ -0,0 +1,241 @@
1
+ /**
2
+ * A product's own names in an Op waves pipeline (#5022), as the product
3
+ * plan keeps them (#5003).
4
+ *
5
+ * Maintainer decision (2026-11-11, on #5000): chant keeps a product's
6
+ * names. A product whose wave jobs live in its own workflow beside its plan
7
+ * jobs (terragucci's `apply-wave-<k>` in `terragucci.yml`) hands the
8
+ * generators the names, and they render them, so the product never renames
9
+ * or edits what chant wrote:
10
+ *
11
+ * - `jobNames`: a name for each job the generator writes (a wave's job, its
12
+ * deciding, share and job group jobs, a split wave's plan, gate, apply and
13
+ * record jobs, the policy and evidence jobs, the apply status, stale,
14
+ * before-merge done and control jobs). Every `needs:`, `if:`, artifact
15
+ * `{job}` and `--from-job` follows it.
16
+ * - `stageNames` (GitLab): a name for each stage.
17
+ * - `artifactNames` (GitHub, Forgejo): the outcome, decision, saved plan and
18
+ * check claims artifacts, and the pattern a wave job downloads the
19
+ * earlier outcomes with.
20
+ * - `workflowFile`, `runIf` and `dispatchInputs`: the jobs go in the
21
+ * product's workflow, each running only on a push `runIf` admits (or a
22
+ * before-merge or follow-on dispatch), and the dispatch inputs take the
23
+ * product's names so they never meet its own. On GitLab `runIf` joins
24
+ * every rule of every job.
25
+ *
26
+ * Left out, each is chant's, and the generators render as before.
27
+ */
28
+
29
+ import type { OpWaveJob, OpWavesSpec } from "./op-waves";
30
+
31
+ /** What a job of an Op waves pipeline is (#5022), for {@link OpWavesJobNames}. */
32
+ export type OpWavesJobRole =
33
+ | "wave"
34
+ | "decide"
35
+ | "share"
36
+ | "group"
37
+ | "plan"
38
+ | "gate"
39
+ | "apply"
40
+ | "record"
41
+ | "policy"
42
+ | "evidence"
43
+ | "apply-status"
44
+ | "stale-notes"
45
+ | "before-merge-done"
46
+ | "control";
47
+
48
+ /** One job the generator names (#5022). */
49
+ export interface OpWavesJobRef {
50
+ /** The name chant gives it. A policy or evidence job's is the job it belongs to's name, as the product named it, with `-policy` or `-evidence`. */
51
+ name: string;
52
+ /**
53
+ * `wave`: a wave's one job. `decide`, `share`, `group`: a wide wave's
54
+ * deciding job, a share's job and a job group's (or a group share's)
55
+ * job. `plan`, `gate`, `apply`, `record`: a split wave's jobs before merge
56
+ * (`apply` with `share` or `group` for a wide wave's). `policy` (GitLab),
57
+ * `evidence`: the jobs of a wave's checks. The rest are the jobs after
58
+ * or beside the waves.
59
+ */
60
+ role: OpWavesJobRole;
61
+ /** The wave's number from 1, and its name, on every job but the stale and control jobs and the before-merge done job. */
62
+ wave?: number;
63
+ waveName?: string;
64
+ share?: number;
65
+ group?: string;
66
+ /** A job of the spec's `rest` wave. */
67
+ rest?: true;
68
+ /** A policy or evidence job: the name of the job it belongs to. */
69
+ of?: string;
70
+ }
71
+
72
+ /** A product's job names (#5022): its name for a job, or undefined for chant's. */
73
+ export type OpWavesJobNames = (job: OpWavesJobRef) => string | undefined;
74
+
75
+ /** One GitLab stage the generator names (#5022). */
76
+ export interface OpWavesStageRef {
77
+ /** The name chant gives it: `plans`, `wave-<k>-<wave name>`, `before-merge-done`, `control` or `resume`. */
78
+ name: string;
79
+ role: "plans" | "wave" | "before-merge-done" | "control" | "resume";
80
+ wave?: number;
81
+ waveName?: string;
82
+ }
83
+
84
+ /** A product's GitLab stage names (#5022): its name for a stage, or undefined for chant's. Two stages may share a name. */
85
+ export type OpWavesStageNames = (stage: OpWavesStageRef) => string | undefined;
86
+
87
+ /**
88
+ * A product's artifact names (#5022, GitHub and Forgejo). `{job}` is the
89
+ * job's name as the product named it, `{wave}` the wave's number.
90
+ */
91
+ export interface OpWavesArtifactNames {
92
+ /** A job's outcome file. Default `<spec>-{job}-outcome`. */
93
+ outcome?: string;
94
+ /** A wave's decision, which its share, apply and record jobs download. Default `<spec>-wave-{wave}-decision`. */
95
+ decision?: string;
96
+ /** A split wave's saved plan (#4987). Default `<spec>-wave-{wave}-plan`. */
97
+ plan?: string;
98
+ /** A job's check claims, for its evidence job (#4926). Default `<spec>-{job}-checks`. */
99
+ checks?: string;
100
+ /**
101
+ * GitHub: the pattern a wave job downloads the earlier jobs' outcomes
102
+ * with, such as `terragucci-report-apply-wave-*`. It has to match every
103
+ * earlier outcome artifact. The jobs after the waves download every
104
+ * artifact of the run, and so does every job on Forgejo. Default: every
105
+ * artifact of the run.
106
+ */
107
+ earlier?: string;
108
+ }
109
+
110
+ /** The `workflow_dispatch` inputs of a waves workflow (#4984, #4992), by chant's name. */
111
+ export type OpWavesDispatchInput = "pr" | "head" | "digest" | "wave" | "commit";
112
+
113
+ /** The dispatch inputs' names, chant's unless the product gave its own (#5022). */
114
+ export function opWavesDispatchInputs(given: Partial<Record<OpWavesDispatchInput, string>> | undefined): Record<OpWavesDispatchInput, string> {
115
+ const out = { pr: "pr", head: "head", digest: "digest", wave: "wave", commit: "commit" } as Record<OpWavesDispatchInput, string>;
116
+ const seen = new Map<string, string>();
117
+ for (const key of Object.keys(out) as OpWavesDispatchInput[]) {
118
+ const v = given?.[key];
119
+ if (given && key in given && (typeof v !== "string" || !/^[A-Za-z_][A-Za-z0-9_-]*$/.test(v))) throw new Error(`dispatchInputs.${key} ${JSON.stringify(v)} is not an input name of letters, digits, _ and -, starting with a letter or _`);
120
+ if (v !== undefined) out[key] = v;
121
+ const other = seen.get(out[key]);
122
+ if (other !== undefined) throw new Error(`dispatchInputs names two inputs ${out[key]}: ${other} and ${key}`);
123
+ seen.set(out[key], key);
124
+ }
125
+ for (const key of Object.keys(given ?? {})) if (!(key in out)) throw new Error(`dispatchInputs.${key} is none of pr, head, digest, wave and commit`);
126
+ return out;
127
+ }
128
+
129
+ /** Whether a product renamed any dispatch input (#5022). */
130
+ export function opWavesInputsRenamed(inputs: Record<OpWavesDispatchInput, string>): boolean {
131
+ return Object.entries(inputs).some(([k, v]) => k !== v);
132
+ }
133
+
134
+ const ARTIFACT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
135
+
136
+ /** The artifact names of a pipeline (#5022), from {@link OpWavesArtifactNames} or chant's. Throws on a template that cannot name one. */
137
+ export function opWavesArtifacts(spec: Pick<OpWavesSpec, "name">, given: OpWavesArtifactNames | undefined): {
138
+ outcome(job: string): string;
139
+ decision(wave: number): string;
140
+ plan(wave: number): string;
141
+ checks(job: string): string;
142
+ earlier?: string;
143
+ } {
144
+ const t = {
145
+ outcome: given?.outcome ?? `${spec.name}-{job}-outcome`,
146
+ decision: given?.decision ?? `${spec.name}-wave-{wave}-decision`,
147
+ plan: given?.plan ?? `${spec.name}-wave-{wave}-plan`,
148
+ checks: given?.checks ?? `${spec.name}-{job}-checks`,
149
+ };
150
+ const marks = { outcome: "{job}", decision: "{wave}", plan: "{wave}", checks: "{job}" } as const;
151
+ for (const key of Object.keys(marks) as Array<keyof typeof marks>) {
152
+ if (given?.[key] === undefined) continue;
153
+ const v = t[key];
154
+ if (!v.includes(marks[key]) || !ARTIFACT.test(v.replaceAll("{job}", "j").replaceAll("{wave}", "1"))) {
155
+ throw new Error(`artifactNames.${key} ${JSON.stringify(v)} holds ${marks[key]} and is otherwise letters, digits, '.', '_' and '-'`);
156
+ }
157
+ }
158
+ const distinct = new Set([t.outcome.replace("{job}", "x"), t.checks.replace("{job}", "x")]);
159
+ if (distinct.size < 2) throw new Error(`artifactNames gives the outcome and the check claims one name, ${JSON.stringify(t.outcome)}`);
160
+ if (t.decision === t.plan) throw new Error(`artifactNames gives the decision and the saved plan one name, ${JSON.stringify(t.plan)}`);
161
+ const earlier = given?.earlier;
162
+ if (earlier !== undefined && !/^[A-Za-z0-9._*-]+$/.test(earlier)) throw new Error(`artifactNames.earlier ${JSON.stringify(earlier)} is a pattern of letters, digits, '.', '_', '-' and '*'`);
163
+ return {
164
+ outcome: (job) => t.outcome.replaceAll("{job}", job),
165
+ decision: (wave) => t.decision.replaceAll("{wave}", String(wave)),
166
+ plan: (wave) => t.plan.replaceAll("{wave}", String(wave)),
167
+ checks: (job) => t.checks.replaceAll("{job}", job),
168
+ ...(earlier !== undefined ? { earlier } : {}),
169
+ };
170
+ }
171
+
172
+ /** The file a waves workflow goes in (#5022): `workflowFile`, else `<spec>.yml`. */
173
+ export function opWavesWorkflowFile(spec: Pick<OpWavesSpec, "name">, file: string | undefined): string {
174
+ if (file === undefined) return `${spec.name}.yml`;
175
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.ya?ml$/.test(file)) throw new Error(`workflowFile ${JSON.stringify(file)} is a workflow file's name, like terragucci.yml, in the forge's workflow directory`);
176
+ return file;
177
+ }
178
+
179
+ const GITLAB_KEYWORDS = new Set(["default", "include", "stages", "variables", "workflow", "image", "services", "cache", "before_script", "after_script", "spec", "pages"]);
180
+
181
+ /** A job of a pipeline as {@link opWavesNamer} reads it: an `opWaveJobs` job, or a split one with its phase. */
182
+ type NamedJob = OpWaveJob & { phase?: "plan" | "gate" | "apply" | "record"; rest?: true };
183
+
184
+ /** What a job is, for its {@link OpWavesJobRef}. */
185
+ function roleOf(job: NamedJob): OpWavesJobRole {
186
+ if (job.phase !== undefined) return job.phase;
187
+ return job.kind === "share" && job.group !== undefined ? "group" : job.kind;
188
+ }
189
+
190
+ /**
191
+ * The names of a pipeline's jobs (#5022): {@link OpWavesJobNames}, else
192
+ * chant's. `name` gives one job's (the same each time it is asked),
193
+ * `jobs` names a list of wave jobs and their `needs`, and `claim` keeps a
194
+ * name the generator writes as it is. Throws on a name the forge cannot
195
+ * take and on two jobs that share one.
196
+ */
197
+ export function opWavesNamer(spec: Pick<OpWavesSpec, "waves">, forge: "github" | "forgejo" | "gitlab", given: OpWavesJobNames | undefined): {
198
+ name(ref: OpWavesJobRef): string;
199
+ jobs<T extends NamedJob>(jobs: readonly T[]): T[];
200
+ claim(name: string): string;
201
+ } {
202
+ const github = forge !== "gitlab";
203
+ const byKey = new Map<string, string>();
204
+ const owner = new Map<string, string>();
205
+ const take = (key: string, name: string, what: string): string => {
206
+ const other = owner.get(name);
207
+ if (other !== undefined && other !== key) throw new Error(`the Op waves pipeline names two jobs ${name}: ${other.split("|")[1]} and ${what}`);
208
+ owner.set(name, key);
209
+ byKey.set(key, name);
210
+ return name;
211
+ };
212
+ const name = (ref: OpWavesJobRef): string => {
213
+ const key = `${ref.role}|${ref.name}`;
214
+ const known = byKey.get(key);
215
+ if (known !== undefined) return known;
216
+ const mine = given?.(ref);
217
+ if (mine !== undefined) {
218
+ const ok = typeof mine === "string" && (github ? /^[A-Za-z_][A-Za-z0-9_-]*$/.test(mine) : /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(mine) && !GITLAB_KEYWORDS.has(mine));
219
+ if (!ok) throw new Error(`jobNames gives the ${ref.role} job ${ref.name} the name ${JSON.stringify(mine)}, which is not a job name of letters, digits, _ and -, starting with a letter or _${github ? "" : " or a digit, and no GitLab keyword"}`);
220
+ }
221
+ return take(key, mine ?? ref.name, ref.name);
222
+ };
223
+ const restWave = spec.waves[spec.waves.length - 1]?.rest === true ? spec.waves.length : undefined;
224
+ const jobs = <T extends NamedJob>(list: readonly T[]): T[] => {
225
+ const renamed = new Map<string, string>();
226
+ for (const job of list) {
227
+ const ref: OpWavesJobRef = {
228
+ name: job.jobName,
229
+ role: roleOf(job),
230
+ wave: job.wave,
231
+ waveName: job.waveName,
232
+ ...(job.share !== undefined ? { share: job.share } : {}),
233
+ ...(job.group !== undefined ? { group: job.group } : {}),
234
+ ...(job.rest || job.wave === restWave ? { rest: true as const } : {}),
235
+ };
236
+ renamed.set(job.jobName, name(ref));
237
+ }
238
+ return list.map((job) => ({ ...job, jobName: renamed.get(job.jobName)!, needs: job.needs.map((n) => renamed.get(n) ?? n) }));
239
+ };
240
+ return { name, jobs, claim: (n) => take(`claim|${n}`, n, n) };
241
+ }
@@ -30,6 +30,19 @@ export function pullRequestEventHead(env: Record<string, string | undefined>): s
30
30
  }
31
31
  }
32
32
 
33
+ /**
34
+ * The commit a GitHub `pull_request` run's plan job checked out for `head`
35
+ * when it is not `head` (#5020): the run's merge preview, `GITHUB_SHA`, when
36
+ * `head` is the event's pull request head. The note job names the head, and
37
+ * takes a report for the merge preview as the head's. Undefined on any other
38
+ * run, on Forgejo (whose run is of the head) and on GitLab.
39
+ */
40
+ export function plannedForHead(head: string, env: Record<string, string | undefined> = process.env): string | undefined {
41
+ const merge = env.GITHUB_SHA;
42
+ if (!merge || merge === head || !/^[0-9a-f]{40,64}$/.test(merge)) return undefined;
43
+ return pullRequestEventHead(env) === head ? merge : undefined;
44
+ }
45
+
33
46
  /** {@link forgeFromEnv}, whose statuses for the run's merge preview go on the pull request's head (#4964). */
34
47
  export function forgeFromJobEnv(kind: ForgeKind, env: Record<string, string | undefined> = process.env, fetchImpl?: Parameters<typeof forgeFromEnv>[2]): PrForge {
35
48
  const forge = forgeFromEnv(kind, env, fetchImpl);
@@ -32,8 +32,10 @@ export const PLAN_RUN_OP = "pr-plan";
32
32
  export interface PlanRunExpect {
33
33
  /** The pipeline's environment, `--env`. */
34
34
  env: string;
35
- /** The commit the plan job checked out, `--head`. */
35
+ /** The pull request's head, `--head`. */
36
36
  head: string;
37
+ /** The commit the plan job checked out when it is not `head` (#5020): a GitHub `pull_request` run's merge preview. */
38
+ planned?: string;
37
39
  /** The target, `--member`. */
38
40
  target?: string;
39
41
  /** The plan job's result as the forge says it (`needs.<job>.result`, GitLab's job status). */
@@ -69,7 +71,7 @@ export function readPlanRunRecord(dir: string, expect: PlanRunExpect): { record:
69
71
  if (r.env !== expect.env) return { refused: `the run record is for environment ${JSON.stringify(r.env)}, not ${expect.env}` };
70
72
  const labels = r.labels && typeof r.labels === "object" && !Array.isArray(r.labels) ? (r.labels as Record<string, unknown>) : {};
71
73
  if ((labels.Target ?? undefined) !== expect.target) return { refused: `the run record is for target ${JSON.stringify(labels.Target ?? null)}, not ${JSON.stringify(expect.target ?? null)}` };
72
- if (r.gitSha !== undefined && r.gitSha !== expect.head) return { refused: `the run record is for commit ${JSON.stringify(r.gitSha)}, not ${expect.head}` };
74
+ if (r.gitSha !== undefined && r.gitSha !== expect.head && r.gitSha !== expect.planned) return { refused: `the run record is for commit ${JSON.stringify(r.gitSha)}, not ${expect.head}` };
73
75
  if (!SHA.test(expect.head)) return { refused: `the head ${JSON.stringify(expect.head)} is not a full commit` };
74
76
  const started = instant(r.started);
75
77
  const ended = instant(r.ended);
@@ -0,0 +1,116 @@
1
+ /**
2
+ * #5020: on GitHub the note job names the pull request's head
3
+ * (`github.event.pull_request.head.sha`), while the plan job checked out
4
+ * the run's merge preview (`github.sha`). `pr-post --head <head>` takes a
5
+ * report, a plan note hand-off or a run record for that merge preview as the
6
+ * head's, and for the head itself (terragucci's plan verb writes its
7
+ * hand-off for the head), and posts the status on the head.
8
+ */
9
+ import { execFileSync } from "node:child_process";
10
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { afterAll, describe, expect, test } from "vitest";
14
+ import { PLAN_RECORD_JS, PLAN_RUN_RECORD_ENV } from "./components/product-plan";
15
+ import { plannedForHead } from "./pr-forge-job";
16
+ import type { ForgeStatus, PrForge } from "./pr-forge";
17
+ import type { PrReport } from "./pr-loop";
18
+ import { planBodyHandoff, PR_PLAN_NOTE_FILE } from "./pr-plan-note";
19
+ import { PLAN_RUN_RECORD_FILE, readPlanRunRecord } from "./pr-plan-record";
20
+ import { postPlanReport, readPlanNoteHandoff } from "./pr-post";
21
+
22
+ const REPORT = JSON.parse(readFileSync(join(import.meta.dirname, "__fixtures__", "pr-loop", "pr-plan.golden.json"), "utf-8")) as PrReport;
23
+ const HEAD = "a".repeat(40);
24
+ const MERGE = "b".repeat(40);
25
+ const OTHER = "c".repeat(40);
26
+
27
+ const dirs: string[] = [];
28
+ afterAll(() => {
29
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
30
+ });
31
+ const tmp = (): string => {
32
+ const d = mkdtempSync(join(tmpdir(), "chant-5020-"));
33
+ dirs.push(d);
34
+ return d;
35
+ };
36
+
37
+ function eventEnv(event = "pull_request"): Record<string, string> {
38
+ const path = join(tmp(), "event.json");
39
+ writeFileSync(path, JSON.stringify({ number: 12, pull_request: { number: 12, head: { sha: HEAD } } }));
40
+ return { GITHUB_EVENT_NAME: event, GITHUB_SHA: MERGE, GITHUB_EVENT_PATH: path };
41
+ }
42
+
43
+ function fakeForge(): { forge: PrForge; statuses: string[] } {
44
+ const statuses: string[] = [];
45
+ const forge = {
46
+ kind: "github",
47
+ host: "github.com",
48
+ async setStatus(sha: string, _status: ForgeStatus) {
49
+ statuses.push(sha);
50
+ },
51
+ async upsertNote() {
52
+ return "1";
53
+ },
54
+ } as unknown as PrForge;
55
+ return { forge, statuses };
56
+ }
57
+
58
+ describe("the commit a pull_request run's plan job planned for the head (#5020)", () => {
59
+ test("the merge preview, when --head is the event's head", () => {
60
+ expect(plannedForHead(HEAD, eventEnv())).toBe(MERGE);
61
+ });
62
+
63
+ test("nothing for another head, another event, a run of the head itself, or no event", () => {
64
+ expect(plannedForHead(OTHER, eventEnv())).toBeUndefined();
65
+ expect(plannedForHead(HEAD, eventEnv("push"))).toBeUndefined();
66
+ expect(plannedForHead(HEAD, { ...eventEnv(), GITHUB_SHA: HEAD })).toBeUndefined();
67
+ expect(plannedForHead(HEAD, { GITHUB_SHA: MERGE })).toBeUndefined();
68
+ });
69
+ });
70
+
71
+ describe("pr-post for the head takes the merge preview's report as the head's (#5020)", () => {
72
+ const at = { pr: REPORT.pr!, head: HEAD, planned: MERGE, env: REPORT.env };
73
+ const reportDir = (head: string): string => {
74
+ const d = tmp();
75
+ writeFileSync(join(d, "pr-plan.json"), JSON.stringify({ ...REPORT, head }));
76
+ return d;
77
+ };
78
+
79
+ test.each([
80
+ ["the merge preview the plan job checked out", MERGE],
81
+ ["the head", HEAD],
82
+ ])("a report for %s posts on the head", async (_what, head) => {
83
+ const { forge, statuses } = fakeForge();
84
+ const r = await postPlanReport({ forge, dir: reportDir(head), ...at, result: "success" });
85
+ expect(r.refused).toBeUndefined();
86
+ expect(r.state).toBe("success");
87
+ expect(statuses).toEqual([HEAD]);
88
+ });
89
+
90
+ test("a report for another commit is refused, and so is the merge preview's when nothing says the plan job checked it out", async () => {
91
+ const other = await postPlanReport({ forge: fakeForge().forge, dir: reportDir(OTHER), ...at });
92
+ expect(other.refused).toMatch(/the report is for head/);
93
+ const { planned: _planned, ...bare } = at;
94
+ const merge = await postPlanReport({ forge: fakeForge().forge, dir: reportDir(MERGE), ...bare });
95
+ expect(merge.refused).toMatch(/the report is for head/);
96
+ });
97
+
98
+ test("a product's plan note hand-off for the merge preview or the head is the head's", () => {
99
+ for (const head of [MERGE, HEAD]) {
100
+ const d = tmp();
101
+ writeFileSync(join(d, PR_PLAN_NOTE_FILE), JSON.stringify(planBodyHandoff("planned", { pr: 12, head, env: "prod", state: "success", description: "planned" })));
102
+ expect(readPlanNoteHandoff({ dir: d, pr: 12, head: HEAD, planned: MERGE, env: "prod" })).toHaveProperty("handoff");
103
+ if (head === MERGE) expect(readPlanNoteHandoff({ dir: d, pr: 12, head: HEAD, env: "prod" })).toEqual({ refused: expect.stringMatching(/for head/) });
104
+ }
105
+ });
106
+
107
+ test("the plan job's run record of the merge preview is the head's", () => {
108
+ const d = tmp();
109
+ const config = JSON.stringify({ op: "pr-plan", env: "prod", labels: { Env: "prod", Pipeline: "pr", Job: "plan" } });
110
+ execFileSync(process.execPath, ["-e", PLAN_RECORD_JS, d], { cwd: d, env: { ...process.env, [PLAN_RUN_RECORD_ENV]: config, CHANT_PLAN_EXIT: "0", CHANT_PLAN_STARTED: "2026-11-10T00:00:00Z" } });
111
+ const file = join(d, PLAN_RUN_RECORD_FILE);
112
+ writeFileSync(file, JSON.stringify({ ...JSON.parse(readFileSync(file, "utf-8")), gitSha: MERGE }));
113
+ expect(readPlanRunRecord(d, { env: "prod", head: HEAD, planned: MERGE })).toHaveProperty("record");
114
+ expect(readPlanRunRecord(d, { env: "prod", head: HEAD })).toEqual({ refused: expect.stringMatching(/for commit/) });
115
+ });
116
+ });
package/src/pr-post.ts CHANGED
@@ -54,8 +54,14 @@ export interface PlanPostInput {
54
54
  dir: string;
55
55
  /** The pull request, from the forge's event. */
56
56
  pr: number;
57
- /** The commit the plan job checked out, from the forge's event. */
57
+ /** The pull request's head, from the forge's event: the commit the statuses go on. */
58
58
  head: string;
59
+ /**
60
+ * The commit the plan job checked out when it is not `head` (#5020): a
61
+ * GitHub `pull_request` run's merge preview (`GITHUB_SHA`). A report, plan
62
+ * note or run record for it counts as the head's.
63
+ */
64
+ planned?: string;
59
65
  env: string;
60
66
  member?: string;
61
67
  /** The plan status's context (#5003, a product plan's `statusContext`), in place of {@link prStatusContext}'s. */
@@ -142,12 +148,15 @@ export interface PlanPostResult {
142
148
 
143
149
  const SHA = /^[0-9a-f]{40}$/;
144
150
 
151
+ /** Whether `sha` is the head a caller posts for, or the merge preview its plan job checked out for it (#5020). */
152
+ const isPlannedHead = (sha: string, input: Pick<PlanPostInput, "head" | "planned">): boolean => sha === input.head || (input.planned !== undefined && sha === input.planned);
153
+
145
154
  /**
146
155
  * Read the plan report under `dir` and check it is the one the caller ran:
147
156
  * a plan report for the same pull request, head, environment and member.
148
157
  * Returns the report, or why it is not used.
149
158
  */
150
- export function readPlanReport(input: Pick<PlanPostInput, "dir" | "pr" | "head" | "env" | "member">): { report: PrReport } | { refused: string } {
159
+ export function readPlanReport(input: Pick<PlanPostInput, "dir" | "pr" | "head" | "planned" | "env" | "member">): { report: PrReport } | { refused: string } {
151
160
  const file = join(input.dir, PR_PLAN_REPORT_FILE);
152
161
  if (!existsSync(file)) return { refused: "the plan job wrote no report" };
153
162
  let doc: unknown;
@@ -160,7 +169,7 @@ export function readPlanReport(input: Pick<PlanPostInput, "dir" | "pr" | "head"
160
169
  const r = doc as Record<string, unknown>;
161
170
  if (r.stage !== "plan") return { refused: `the report is not a plan report (stage ${JSON.stringify(r.stage)})` };
162
171
  if (r.pr !== input.pr) return { refused: `the report is for pull request ${JSON.stringify(r.pr)}, not ${input.pr}` };
163
- if (typeof r.head !== "string" || !SHA.test(r.head) || r.head !== input.head) return { refused: `the report is for head ${JSON.stringify(r.head)}, not ${input.head}` };
172
+ if (typeof r.head !== "string" || !SHA.test(r.head) || !isPlannedHead(r.head, input)) return { refused: `the report is for head ${JSON.stringify(r.head)}, not ${input.head}` };
164
173
  if (r.env !== input.env) return { refused: `the report is for environment ${JSON.stringify(r.env)}, not ${input.env}` };
165
174
  if ((r.member ?? undefined) !== input.member) return { refused: `the report is for member ${JSON.stringify(r.member ?? null)}, not ${JSON.stringify(input.member ?? null)}` };
166
175
  if (!Array.isArray(r.members) || !r.changeSet || typeof r.changeSet !== "object" || !r.selection || typeof r.selection !== "object" || !r.approval || typeof r.approval !== "object") {
@@ -370,6 +379,7 @@ async function keepRunRecord(input: PlanPostInput, warnings: string[]): Promise<
370
379
  const read = readPlanRunRecord(input.dir, {
371
380
  env: input.env,
372
381
  head: input.head,
382
+ ...(input.planned ? { planned: input.planned } : {}),
373
383
  ...(input.member ? { target: input.member } : {}),
374
384
  ...(input.result ? { result: input.result } : {}),
375
385
  ...(input.recordRun.origin ? { origin: input.recordRun.origin } : {}),
@@ -437,7 +447,7 @@ async function postOutcome(
437
447
  * Read a product's plan note hand-off under `dir` (#4799) and check it is the
438
448
  * one the caller ran, as {@link readPlanReport} checks a report.
439
449
  */
440
- export function readPlanNoteHandoff(input: Pick<PlanPostInput, "dir" | "pr" | "head" | "env" | "member">): { handoff: PrPlanNoteHandoff | PrPlanBodyHandoff } | { refused: string } {
450
+ export function readPlanNoteHandoff(input: Pick<PlanPostInput, "dir" | "pr" | "head" | "planned" | "env" | "member">): { handoff: PrPlanNoteHandoff | PrPlanBodyHandoff } | { refused: string } {
441
451
  let doc: unknown;
442
452
  try {
443
453
  doc = JSON.parse(readFileSync(join(input.dir, PR_PLAN_NOTE_FILE), "utf-8"));
@@ -449,7 +459,7 @@ export function readPlanNoteHandoff(input: Pick<PlanPostInput, "dir" | "pr" | "h
449
459
  if (r.kind !== "plan-note-handoff") return { refused: `the file is not a plan note hand-off (kind ${JSON.stringify(r.kind)})` };
450
460
  if (r.contract !== PR_PLAN_NOTE_CONTRACT) return { refused: `the plan note follows contract ${JSON.stringify(r.contract)}, and this chant reads ${PR_PLAN_NOTE_CONTRACT}` };
451
461
  if (r.pr !== input.pr) return { refused: `the plan note is for pull request ${JSON.stringify(r.pr)}, not ${input.pr}` };
452
- if (typeof r.head !== "string" || !SHA.test(r.head) || r.head !== input.head) return { refused: `the plan note is for head ${JSON.stringify(r.head)}, not ${input.head}` };
462
+ if (typeof r.head !== "string" || !SHA.test(r.head) || !isPlannedHead(r.head, input)) return { refused: `the plan note is for head ${JSON.stringify(r.head)}, not ${input.head}` };
453
463
  if (r.env !== input.env) return { refused: `the plan note is for environment ${JSON.stringify(r.env)}, not ${input.env}` };
454
464
  if ((r.member ?? undefined) !== input.member) return { refused: `the plan note is for ${JSON.stringify(r.member ?? null)}, not ${JSON.stringify(input.member ?? null)}` };
455
465
  if (r.state !== "success" && r.state !== "failure" && r.state !== "pending") return { refused: `the plan note's state ${JSON.stringify(r.state)} is not success, failure or pending` };
@@ -19,7 +19,7 @@
19
19
  * this constant to the next patch (#4501). The check fails while a floor
20
20
  * still names this constant after its version shipped.
21
21
  */
22
- export const NEXT_RELEASE = "0.124.91";
22
+ export const NEXT_RELEASE = "0.124.92";
23
23
 
24
24
  /** The first chant with `chant dev local` and `chant dev bundle-check`, `@intentius/chant/local-chant` and `@intentius/chant/bundle-check` (`chantRuntimeTarget`, `chantExternalPlugin`, `checkBundle`): a product built against a chant checkout, and its bundle checked, without its own scripts (#4787). */
25
25
  export const LOCAL_CHANT_FLOOR = "0.124.86";
@@ -211,7 +211,7 @@ export const GITLAB_WAVE_KEY_SCOPE_FLOOR = "0.124.89";
211
211
  export const ACTOR_ORDER_FLOOR = "0.124.89";
212
212
 
213
213
  /** The first chant whose `actorOf({ env, repo })` runs `git config` in `repo` with the `env` it is given rather than the process's, so a job's `GIT_CONFIG_GLOBAL` or `HOME` picks the `user.name` it reads (#5005). */
214
- export const ACTOR_GIT_ENV_FLOOR = NEXT_RELEASE;
214
+ export const ACTOR_GIT_ENV_FLOOR = "0.124.91";
215
215
 
216
216
  /** The first chant with `@intentius/chant/ci-base` (`ciBaseRef`), the base a CI job measures a change from (the pull request's target branch, else the default branch for a push to another branch), and whose `chant ci check` defaults `--base` to it (#4966). */
217
217
  export const CI_BASE_REF_FLOOR = "0.124.89";
@@ -220,7 +220,7 @@ export const CI_BASE_REF_FLOOR = "0.124.89";
220
220
  export const PLANNED_FILES_FLOOR = "0.124.89";
221
221
 
222
222
  /** The first chant whose `planFile` in `@intentius/chant/planned-files` takes bytes (`Uint8Array` or `Buffer`) as well as text: `writePlannedFiles` writes them unchanged and the plan compares them with the file byte for byte (#5006). */
223
- export const PLANNED_BYTES_FLOOR = NEXT_RELEASE;
223
+ export const PLANNED_BYTES_FLOOR = "0.124.91";
224
224
 
225
225
  /** The first chant whose `pipelineContract` takes `jobs`, the jobs a product builds from its own config, beside or in place of `pipelines`, so a product's forge check gets the required statuses and `refGateStatus` from chant (#4966). */
226
226
  export const FORGE_CHECK_OWN_JOBS_FLOOR = "0.124.89";
@@ -238,4 +238,4 @@ export const RUNTIME_WAVES_SPEC_FLOOR = "0.124.89";
238
238
  export const GITLAB_WAVE_EVIDENCE_RETRY_FLOOR = "0.124.89";
239
239
 
240
240
  /** The first chant whose terraform lexicon's engine runs carry what a product's own command tracing read: `runBinary` and the engine runner's `exec` and `execSync` answer stderr apart (`Ran.stderr`) and a spawn failure's message (`Ran.error`), a hook's `after` gets a binary that could not be started as a null code with `error`, `commandTrace` ends that span with the message, and `composeCommandHooks` runs a product's own hook and `commandTrace` as one `onCommand` (#5007). */
241
- export const TERRAFORM_COMMAND_TRACE_FLOOR = NEXT_RELEASE;
241
+ export const TERRAFORM_COMMAND_TRACE_FLOOR = "0.124.91";