@intentius/chant 0.124.76 → 0.124.78

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 (212) hide show
  1. package/dist/__fixtures__/agent-guard/plywood.d.ts +8 -0
  2. package/dist/__fixtures__/agent-guard/plywood.d.ts.map +1 -0
  3. package/dist/__fixtures__/agent-guard/plywood.js +19 -0
  4. package/dist/__fixtures__/agent-guard/terragucci.d.ts +8 -0
  5. package/dist/__fixtures__/agent-guard/terragucci.d.ts.map +1 -0
  6. package/dist/__fixtures__/agent-guard/terragucci.js +30 -0
  7. package/dist/__fixtures__/gated-ledger.d.ts +10 -0
  8. package/dist/__fixtures__/gated-ledger.d.ts.map +1 -0
  9. package/dist/__fixtures__/gated-ledger.js +51 -0
  10. package/dist/__fixtures__/notify-messages/events.d.ts +9 -0
  11. package/dist/__fixtures__/notify-messages/events.d.ts.map +1 -0
  12. package/dist/__fixtures__/notify-messages/events.js +21 -0
  13. package/dist/__fixtures__/product-words.d.ts +14 -0
  14. package/dist/__fixtures__/product-words.d.ts.map +1 -1
  15. package/dist/__fixtures__/product-words.js +11 -0
  16. package/dist/__fixtures__/terragucci-notify.d.ts +66 -0
  17. package/dist/__fixtures__/terragucci-notify.d.ts.map +1 -0
  18. package/dist/__fixtures__/terragucci-notify.js +133 -0
  19. package/dist/action-pins.d.ts +8 -0
  20. package/dist/action-pins.d.ts.map +1 -1
  21. package/dist/action-pins.js +9 -0
  22. package/dist/agent-guard.d.ts +143 -0
  23. package/dist/agent-guard.d.ts.map +1 -0
  24. package/dist/agent-guard.js +455 -0
  25. package/dist/ci-commit.d.ts +120 -5
  26. package/dist/ci-commit.d.ts.map +1 -1
  27. package/dist/ci-commit.js +214 -23
  28. package/dist/ci-own-jobs.d.ts +81 -0
  29. package/dist/ci-own-jobs.d.ts.map +1 -0
  30. package/dist/ci-own-jobs.js +233 -0
  31. package/dist/ci-product-words.d.ts +18 -4
  32. package/dist/ci-product-words.d.ts.map +1 -1
  33. package/dist/ci-product-words.js +26 -6
  34. package/dist/ci-product.d.ts +40 -1
  35. package/dist/ci-product.d.ts.map +1 -1
  36. package/dist/ci-product.js +40 -1
  37. package/dist/cli/handlers/approve.d.ts +5 -1
  38. package/dist/cli/handlers/approve.d.ts.map +1 -1
  39. package/dist/cli/handlers/approve.js +17 -11
  40. package/dist/cli/handlers/build.d.ts +1 -1
  41. package/dist/cli/handlers/build.d.ts.map +1 -1
  42. package/dist/cli/handlers/build.js +88 -2
  43. package/dist/cli/handlers/commit.d.ts.map +1 -1
  44. package/dist/cli/handlers/commit.js +3 -1
  45. package/dist/cli/handlers/notify-relay.d.ts +18 -1
  46. package/dist/cli/handlers/notify-relay.d.ts.map +1 -1
  47. package/dist/cli/handlers/notify-relay.js +90 -14
  48. package/dist/cli/handlers/pr.d.ts.map +1 -1
  49. package/dist/cli/handlers/pr.js +3 -1
  50. package/dist/cli/handlers/release.d.ts +5 -1
  51. package/dist/cli/handlers/release.d.ts.map +1 -1
  52. package/dist/cli/handlers/release.js +21 -9
  53. package/dist/cli/handlers/run-generate.d.ts.map +1 -1
  54. package/dist/cli/handlers/run-generate.js +2 -1
  55. package/dist/cli/main.d.ts.map +1 -1
  56. package/dist/cli/main.js +21 -1
  57. package/dist/cli/parse-args.d.ts.map +1 -1
  58. package/dist/cli/parse-args.js +60 -4
  59. package/dist/cli/registry.d.ts +16 -0
  60. package/dist/cli/registry.d.ts.map +1 -1
  61. package/dist/components/pr-env-components.d.ts +65 -0
  62. package/dist/components/pr-env-components.d.ts.map +1 -0
  63. package/dist/components/pr-env-components.js +162 -0
  64. package/dist/components/pr-policy.d.ts +15 -0
  65. package/dist/components/pr-policy.d.ts.map +1 -1
  66. package/dist/components/pr-policy.js +24 -1
  67. package/dist/components/release-compile.d.ts +15 -3
  68. package/dist/components/release-compile.d.ts.map +1 -1
  69. package/dist/components/release-compile.js +66 -15
  70. package/dist/config.d.ts +14 -8
  71. package/dist/config.d.ts.map +1 -1
  72. package/dist/config.js +16 -1
  73. package/dist/gate-policy.d.ts +14 -1
  74. package/dist/gate-policy.d.ts.map +1 -1
  75. package/dist/gate-policy.js +16 -6
  76. package/dist/lexicon.d.ts +25 -1
  77. package/dist/lexicon.d.ts.map +1 -1
  78. package/dist/lexicon.js +10 -0
  79. package/dist/lifecycle/gated-op.d.ts +95 -0
  80. package/dist/lifecycle/gated-op.d.ts.map +1 -0
  81. package/dist/lifecycle/gated-op.js +96 -0
  82. package/dist/lifecycle/git.d.ts.map +1 -1
  83. package/dist/lifecycle/git.js +83 -2
  84. package/dist/lifecycle/release-images.d.ts +77 -3
  85. package/dist/lifecycle/release-images.d.ts.map +1 -1
  86. package/dist/lifecycle/release-images.js +132 -6
  87. package/dist/notify-product.d.ts +11 -2
  88. package/dist/notify-product.d.ts.map +1 -1
  89. package/dist/notify-product.js +16 -4
  90. package/dist/notify-relay-repo.d.ts +131 -0
  91. package/dist/notify-relay-repo.d.ts.map +1 -0
  92. package/dist/notify-relay-repo.js +202 -0
  93. package/dist/notify-relay.d.ts +25 -1
  94. package/dist/notify-relay.d.ts.map +1 -1
  95. package/dist/notify-relay.js +27 -2
  96. package/dist/notify.d.ts +36 -4
  97. package/dist/notify.d.ts.map +1 -1
  98. package/dist/notify.js +31 -21
  99. package/dist/notify.schema.json +1 -0
  100. package/dist/op/activities/review-product.d.ts +111 -0
  101. package/dist/op/activities/review-product.d.ts.map +1 -0
  102. package/dist/op/activities/review-product.js +116 -0
  103. package/dist/op/op-waves-capability.js +2 -2
  104. package/dist/policy-engine.d.ts +95 -0
  105. package/dist/policy-engine.d.ts.map +1 -0
  106. package/dist/policy-engine.js +157 -0
  107. package/dist/pr-forge-reads.d.ts +124 -0
  108. package/dist/pr-forge-reads.d.ts.map +1 -0
  109. package/dist/pr-forge-reads.js +322 -0
  110. package/dist/pr-forge.d.ts +14 -0
  111. package/dist/pr-forge.d.ts.map +1 -1
  112. package/dist/pr-forge.js +21 -13
  113. package/dist/pr-plan-note.d.ts +293 -0
  114. package/dist/pr-plan-note.d.ts.map +1 -0
  115. package/dist/pr-plan-note.js +362 -0
  116. package/dist/release-floors.d.ts +9 -1
  117. package/dist/release-floors.d.ts.map +1 -1
  118. package/dist/release-floors.js +9 -1
  119. package/dist/state-export.d.ts +126 -0
  120. package/dist/state-export.d.ts.map +1 -0
  121. package/dist/state-export.js +156 -0
  122. package/dist/state-migration.d.ts +148 -0
  123. package/dist/state-migration.d.ts.map +1 -0
  124. package/dist/state-migration.js +146 -0
  125. package/dist/state-unlock.d.ts +167 -0
  126. package/dist/state-unlock.d.ts.map +1 -0
  127. package/dist/state-unlock.js +196 -0
  128. package/dist/wave-runtime.mjs +332 -332
  129. package/dist/workspace/declaration.schema.json +1 -1
  130. package/dist/workspace/release-workflow.d.ts +10 -0
  131. package/dist/workspace/release-workflow.d.ts.map +1 -1
  132. package/dist/workspace/release-workflow.js +10 -4
  133. package/package.json +1 -1
  134. package/src/__fixtures__/agent-guard/plywood.ts +27 -0
  135. package/src/__fixtures__/agent-guard/terragucci.ts +39 -0
  136. package/src/__fixtures__/gated-ledger.ts +58 -0
  137. package/src/__fixtures__/notify-messages/events.ts +23 -0
  138. package/src/__fixtures__/notify-messages/messages.json +50 -0
  139. package/src/__fixtures__/pr-loop/terragucci-plan.note.golden.md +53 -0
  140. package/src/__fixtures__/pr-loop/terragucci-plan.note.json +83 -0
  141. package/src/__fixtures__/product-words.ts +12 -0
  142. package/src/__fixtures__/review-agent/terragucci-review.json +94 -0
  143. package/src/__fixtures__/terragucci-notify.ts +170 -0
  144. package/src/action-pins.test.ts +12 -1
  145. package/src/action-pins.ts +11 -0
  146. package/src/agent-guard.test.ts +319 -0
  147. package/src/agent-guard.ts +547 -0
  148. package/src/ci-commit.test.ts +213 -2
  149. package/src/ci-commit.ts +258 -27
  150. package/src/ci-own-jobs.test.ts +108 -0
  151. package/src/ci-own-jobs.ts +252 -0
  152. package/src/ci-product-words.ts +35 -7
  153. package/src/ci-product.ts +81 -1
  154. package/src/cli/handlers/approve-cwd.test.ts +112 -0
  155. package/src/cli/handlers/approve.ts +22 -11
  156. package/src/cli/handlers/build-own-jobs.test.ts +80 -0
  157. package/src/cli/handlers/build-pr-loop-control.test.ts +87 -0
  158. package/src/cli/handlers/build-run-group.test.ts +59 -0
  159. package/src/cli/handlers/build.ts +83 -3
  160. package/src/cli/handlers/commit.ts +3 -0
  161. package/src/cli/handlers/notify-relay.ts +99 -17
  162. package/src/cli/handlers/pr.ts +3 -1
  163. package/src/cli/handlers/release.ts +20 -10
  164. package/src/cli/handlers/run-generate.ts +2 -1
  165. package/src/cli/main.ts +21 -1
  166. package/src/cli/parse-args.ts +45 -3
  167. package/src/cli/registry.ts +16 -0
  168. package/src/components/pr-env-components.test.ts +137 -0
  169. package/src/components/pr-env-components.ts +213 -0
  170. package/src/components/pr-policy.test.ts +41 -1
  171. package/src/components/pr-policy.ts +25 -1
  172. package/src/components/release-compile.test.ts +47 -0
  173. package/src/components/release-compile.ts +70 -13
  174. package/src/config.ts +23 -3
  175. package/src/gate-policy-bundle.test.ts +14 -0
  176. package/src/gate-policy.test.ts +7 -0
  177. package/src/gate-policy.ts +22 -7
  178. package/src/lexicon.ts +28 -1
  179. package/src/lifecycle/gated-op.ts +158 -0
  180. package/src/lifecycle/git.test.ts +92 -0
  181. package/src/lifecycle/git.ts +71 -2
  182. package/src/lifecycle/release-images-dockerfile.test.ts +221 -0
  183. package/src/lifecycle/release-images.ts +167 -8
  184. package/src/notify-message-words.test.ts +186 -0
  185. package/src/notify-product.ts +17 -4
  186. package/src/notify-relay-repo.test.ts +284 -0
  187. package/src/notify-relay-repo.ts +234 -0
  188. package/src/notify-relay.test.ts +12 -0
  189. package/src/notify-relay.ts +29 -3
  190. package/src/notify.schema.json +1 -0
  191. package/src/notify.ts +59 -19
  192. package/src/op/activities/review-product.test.ts +116 -0
  193. package/src/op/activities/review-product.ts +200 -0
  194. package/src/op/op-waves-capability.ts +2 -2
  195. package/src/op/schedule-overdue.test.ts +26 -0
  196. package/src/policy-engine.test.ts +162 -0
  197. package/src/policy-engine.ts +200 -0
  198. package/src/pr-forge-reads.test.ts +285 -0
  199. package/src/pr-forge-reads.ts +424 -0
  200. package/src/pr-forge.ts +30 -16
  201. package/src/pr-plan-note.test.ts +105 -0
  202. package/src/pr-plan-note.ts +521 -0
  203. package/src/release-floors.ts +13 -1
  204. package/src/state-export.test.ts +124 -0
  205. package/src/state-export.ts +227 -0
  206. package/src/state-migration.test.ts +133 -0
  207. package/src/state-migration.ts +236 -0
  208. package/src/state-unlock.test.ts +165 -0
  209. package/src/state-unlock.ts +293 -0
  210. package/src/workspace/declaration.schema.json +1 -1
  211. package/src/workspace/release-workflow.test.ts +34 -0
  212. package/src/workspace/release-workflow.ts +19 -4
@@ -687,6 +687,98 @@ describe("lifecycle/git", () => {
687
687
  }
688
688
  });
689
689
 
690
+ describe("on git older than 2.40, without merge-tree --merge-base (#4768)", () => {
691
+ /** A `git` ahead of the real one on PATH that refuses `merge-tree --merge-base` as git 2.39 does: usage text, exit 129. */
692
+ async function withOldGit(fn: () => Promise<void>): Promise<void> {
693
+ const real = spawnSync("sh", ["-c", "command -v git"], { encoding: "utf-8" }).stdout.trim();
694
+ const bin = join(tmpdir(), `chant-old-git-${Date.now()}-${Math.random()}`);
695
+ mkdirSync(bin);
696
+ writeFileSync(
697
+ join(bin, "git"),
698
+ `#!/bin/sh\nfor a in "$@"; do case "$a" in --merge-base=*) echo "usage: git merge-tree [--write-tree] [<options>] <branch1> <branch2>" >&2; exit 129;; esac; done\nexec "${real}" "$@"\n`,
699
+ { mode: 0o755 },
700
+ );
701
+ const path = process.env.PATH;
702
+ process.env.PATH = `${bin}:${path ?? ""}`;
703
+ try {
704
+ await fn();
705
+ } finally {
706
+ process.env.PATH = path;
707
+ const { rm } = await import("node:fs/promises");
708
+ await rm(bin, { recursive: true, force: true });
709
+ }
710
+ }
711
+
712
+ test("a lost race replays on the remote's tip and lands, with both writes kept", async () => {
713
+ const { a, b, remotePath, done } = await twoWriters();
714
+ try {
715
+ await withOldGit(async () => {
716
+ await advance(a, "wave.json", '{"wave":1}');
717
+ await writeBlobToPath("prod", "merge.json", '{"merge":1}', "Merge record: abc", { cwd: b });
718
+ expect(await pushLifecycleRebasing({ cwd: b })).toEqual({ pushed: true });
719
+ });
720
+ const tip = git(["rev-parse", "refs/heads/chant/lifecycle"], remotePath).stdout.trim();
721
+ expect(git(["show", `${tip}:prod/merge.json`], remotePath).stdout).toBe('{"merge":1}');
722
+ expect(git(["show", `${tip}:prod/wave.json`], remotePath).stdout).toBe('{"wave":1}');
723
+ expect(git(["log", "-1", "--format=%s|%an", tip], remotePath).stdout.trim()).toBe("Merge record: abc|Record");
724
+ expect(git(["log", "-1", "--format=%s", `${tip}^`], remotePath).stdout.trim()).toBe("wave: wave.json");
725
+ } finally {
726
+ await done();
727
+ }
728
+ });
729
+
730
+ test("two writers that append lines to one ledger file both land, in push order", async () => {
731
+ const { a, b, remotePath, done } = await twoWriters();
732
+ try {
733
+ await withOldGit(async () => {
734
+ git(["fetch", "-q", "origin", "+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle"], a);
735
+ await appendReleaseRecordLine("prod", '{"from":"wave"}', { cwd: a });
736
+ expect(await pushLifecycle({ cwd: a })).toBe(true);
737
+ await appendReleaseRecordLine("prod", '{"from":"record"}', { cwd: b });
738
+ expect(await pushLifecycleRebasing({ cwd: b })).toEqual({ pushed: true });
739
+ });
740
+ const tip = git(["rev-parse", "refs/heads/chant/lifecycle"], remotePath).stdout.trim();
741
+ expect(git(["show", `${tip}:prod/releases.jsonl`], remotePath).stdout).toBe('{"from":"wave"}\n{"from":"record"}\n');
742
+ } finally {
743
+ await done();
744
+ }
745
+ });
746
+
747
+ test("edits to different lines of one file by the two writers merge as merge-tree merges them", async () => {
748
+ const lines = (first: string, last: string) => [first, "2", "3", "4", "5", "6", "7", "8", last].join("\n") + "\n";
749
+ const { a, b, remotePath, done } = await twoWriters();
750
+ try {
751
+ await advance(a, "notes.txt", lines("1", "9"));
752
+ git(["fetch", "-q", "origin", "chant/lifecycle:chant/lifecycle"], b);
753
+ git(["fetch", "-q", "origin", "+refs/heads/chant/lifecycle:refs/remotes/origin/chant/lifecycle"], b);
754
+ await withOldGit(async () => {
755
+ await advance(a, "notes.txt", lines("wave", "9"));
756
+ await writeBlobToPath("prod", "notes.txt", lines("1", "record"), "record: notes", { cwd: b });
757
+ expect(await pushLifecycleRebasing({ cwd: b })).toEqual({ pushed: true });
758
+ });
759
+ const tip = git(["rev-parse", "refs/heads/chant/lifecycle"], remotePath).stdout.trim();
760
+ expect(git(["show", `${tip}:prod/notes.txt`], remotePath).stdout).toBe(lines("wave", "record"));
761
+ } finally {
762
+ await done();
763
+ }
764
+ });
765
+
766
+ test("a commit that rewrote the file the other writer changed is still refused by name", async () => {
767
+ const { a, b, done } = await twoWriters();
768
+ try {
769
+ await withOldGit(async () => {
770
+ await advance(a, "merge.json", '{"merge":"wave"}');
771
+ await writeBlobToPath("prod", "merge.json", '{"merge":"record"}', "Merge record: abc", { cwd: b });
772
+ const err = await pushLifecycleRebasing({ cwd: b }).catch((e: unknown) => e);
773
+ expect(err).toBeInstanceOf(LifecyclePushLostError);
774
+ expect((err as Error).message).toContain("changes files the other writer changed too");
775
+ });
776
+ } finally {
777
+ await done();
778
+ }
779
+ });
780
+ });
781
+
690
782
  test("no remote reads as the local note, as pushLifecycleReport says it", async () => {
691
783
  await withTestDir(async (dir) => {
692
784
  await initRepo(dir);
@@ -4,7 +4,7 @@
4
4
  * All operations use git plumbing commands — no checkout, no branch switching,
5
5
  * no working tree changes.
6
6
  */
7
- import { unlinkSync } from "node:fs";
7
+ import { unlinkSync, writeFileSync } from "node:fs";
8
8
  import { isAbsolute, join } from "node:path";
9
9
  import { getRuntime } from "../runtime-adapter";
10
10
  import { memberLedgerPrefix, resolveMemberLedger } from "./member-ledger";
@@ -1028,7 +1028,9 @@ async function rebaseLifecycleOnRemote(remote: string, cwd?: string): Promise<{
1028
1028
  for (const commit of ours) {
1029
1029
  const parent = await run(["rev-parse", "--verify", "--quiet", `${commit}^1`]);
1030
1030
  if (parent.exitCode !== 0) return { error: `${commit.slice(0, 12)} shares no history with the remote's ${STATE_BRANCH}` };
1031
- const merged = await run(["merge-tree", "--write-tree", `--merge-base=${parent.stdout.trim()}`, onto, commit]);
1031
+ let merged = await run(["merge-tree", "--write-tree", `--merge-base=${parent.stdout.trim()}`, onto, commit]);
1032
+ // #4768: git before 2.40 has no --merge-base and exits 129 with its usage text (node:22-bookworm-slim's apt git is 2.39).
1033
+ if (merged.exitCode === 129) merged = await mergeTreesInIndex(parent.stdout.trim(), onto, commit, cwd);
1032
1034
  const subject = firstLine((await run(["log", "-1", "--format=%s", commit])).stdout);
1033
1035
  let tree: string;
1034
1036
  if (merged.exitCode === 1) {
@@ -1064,6 +1066,73 @@ async function rebaseLifecycleOnRemote(remote: string, cwd?: string): Promise<{
1064
1066
  }
1065
1067
  }
1066
1068
 
1069
+ /**
1070
+ * `git merge-tree --write-tree --merge-base=<base> <ours> <theirs>` for git
1071
+ * older than 2.40 (#4768), with the same exit codes: 0 with the merged tree
1072
+ * on stdout, 1 when a path conflicts, anything else when git failed. A 3-way
1073
+ * `read-tree` into a scratch index takes every path only one side changed;
1074
+ * a file both sides changed is merged by `git merge-file`, and any other
1075
+ * path both sides touched (an add on both sides, a delete against a change)
1076
+ * is a conflict. Nothing touches a work tree.
1077
+ */
1078
+ async function mergeTreesInIndex(base: string, ours: string, theirs: string, cwd?: string): Promise<{ exitCode: number; stdout: string; stderr: string }> {
1079
+ const rt = getRuntime();
1080
+ const scratch = (await rt.spawn(["git", "rev-parse", "--git-path", `chant-lifecycle-merge-${process.pid}`], { cwd, env: C_LOCALE_ENV })).stdout.trim();
1081
+ if (!scratch) return { exitCode: 2, stdout: "", stderr: "no scratch index path" };
1082
+ const index = isAbsolute(scratch) || !cwd ? scratch : join(cwd, scratch);
1083
+ const env = { ...C_LOCALE_ENV, GIT_INDEX_FILE: `${index}.index` };
1084
+ const run = (args: string[], stdin?: string) => rt.spawn(["git", ...args], { cwd, env, ...(stdin !== undefined ? { stdin } : {}) });
1085
+ const files: string[] = [];
1086
+ try {
1087
+ const read = await run(["read-tree", "-i", "-m", "--aggressive", base, ours, theirs]);
1088
+ if (read.exitCode !== 0) return read;
1089
+ const unmerged = await run(["ls-files", "-u", "-z"]);
1090
+ if (unmerged.exitCode !== 0) return unmerged;
1091
+ // "<mode> <sha> <stage>\t<path>" per stage of each path both sides changed.
1092
+ const stages = new Map<string, Map<number, { mode: string; sha: string }>>();
1093
+ for (const entry of unmerged.stdout.split("\0").filter((e) => e !== "")) {
1094
+ const tab = entry.indexOf("\t");
1095
+ const [mode, sha, stage] = entry.slice(0, tab).split(" ");
1096
+ const path = entry.slice(tab + 1);
1097
+ if (!stages.has(path)) stages.set(path, new Map());
1098
+ stages.get(path)!.set(Number(stage), { mode: mode!, sha: sha! });
1099
+ }
1100
+ for (const [path, by] of stages) {
1101
+ const b = by.get(1);
1102
+ const o = by.get(2);
1103
+ const t = by.get(3);
1104
+ if (!b || !o || !t || o.mode !== t.mode || !o.mode.startsWith("100")) return { exitCode: 1, stdout: "", stderr: `${path} conflicts` };
1105
+ const blobs: string[] = [];
1106
+ for (const [i, s] of [b, o, t].entries()) {
1107
+ const content = await run(["cat-file", "blob", s.sha]);
1108
+ if (content.exitCode !== 0) return content;
1109
+ const file = `${index}.${i}`;
1110
+ writeFileSync(file, content.stdout);
1111
+ files.push(file);
1112
+ blobs.push(file);
1113
+ }
1114
+ // merge-file <current> <base> <other>: ours is current, as merge-tree's first branch is.
1115
+ const mergedFile = await rt.spawn(["git", "merge-file", "-p", blobs[1]!, blobs[0]!, blobs[2]!], { cwd, env: C_LOCALE_ENV });
1116
+ if (mergedFile.exitCode !== 0) return { exitCode: mergedFile.exitCode > 0 && mergedFile.exitCode < 128 ? 1 : 2, stdout: "", stderr: mergedFile.stderr || `${path} conflicts` };
1117
+ const hashed = await run(["hash-object", "-w", "--stdin"], mergedFile.stdout);
1118
+ if (hashed.exitCode !== 0) return hashed;
1119
+ const removed = await run(["update-index", "--force-remove", "--", path]);
1120
+ if (removed.exitCode !== 0) return removed;
1121
+ const added = await run(["update-index", "--add", "--cacheinfo", `${o.mode},${hashed.stdout.trim()},${path}`]);
1122
+ if (added.exitCode !== 0) return added;
1123
+ }
1124
+ return await run(["write-tree"]);
1125
+ } finally {
1126
+ for (const f of [...files, `${index}.index`]) {
1127
+ try {
1128
+ unlinkSync(f);
1129
+ } catch {
1130
+ // Not written.
1131
+ }
1132
+ }
1133
+ }
1134
+ }
1135
+
1067
1136
  /**
1068
1137
  * Replay a commit whose only changes are lines appended to `.jsonl` ledger
1069
1138
  * files, or new `.jsonl` files, onto `onto` (plywood#22 finding 9): each
@@ -0,0 +1,221 @@
1
+ /**
2
+ * #4819: a `release.images` entry that names a Dockerfile, which chant builds
3
+ * as the reproducible OCI archive itself, and the helpers that turn the cut's
4
+ * digests file and a product's `{ name: reference }` into the table its
5
+ * bundle bakes in and the pins file its npm target reads. terragucci's and
6
+ * plywood's `scripts/release-image.sh` and `releaseDigests` are what these
7
+ * replace; the expectations below are what those wrote.
8
+ */
9
+
10
+ import { spawnSync } from "node:child_process";
11
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { describe, expect, test } from "vitest";
15
+ import { ChantConfigSchema } from "../config";
16
+ import { NEXT_RELEASE } from "../release-floors";
17
+ import {
18
+ buildReleaseImages,
19
+ checkReleaseImages,
20
+ RELEASE_DIGESTS_ENV,
21
+ RELEASE_IMAGE_BUILDER,
22
+ RELEASE_IMAGE_DOCKERFILE_FLOOR,
23
+ releaseImageBuildCommand,
24
+ releaseImagePins,
25
+ ReleaseImageError,
26
+ resolveReleaseImages,
27
+ writeReleaseImagePins,
28
+ type ReleaseImageDeclaration,
29
+ } from "./release-images";
30
+
31
+ const D = (c: string) => `sha256:${c.repeat(64)}`;
32
+ const scratch = () => mkdtempSync(join(tmpdir(), "chant-release-image-"));
33
+
34
+ describe("a release.images entry that names a Dockerfile (#4819)", () => {
35
+ test("chant builds it the way both products' release-image.sh did", () => {
36
+ expect(releaseImageBuildCommand({ name: "pulumi", dockerfile: "images/plywood-pulumi/Dockerfile" })).toBe(
37
+ [
38
+ `{ docker buildx inspect ${RELEASE_IMAGE_BUILDER} >/dev/null 2>&1 || docker buildx create --name ${RELEASE_IMAGE_BUILDER} --driver docker-container >/dev/null; }`,
39
+ "mkdir -p dist/images",
40
+ 'docker buildx build --builder chant-release --no-cache --platform linux/amd64,linux/arm64 --provenance=false --sbom=false --build-arg SOURCE_DATE_EPOCH="$SOURCE_DATE_EPOCH" --output type=oci,dest=dist/images/pulumi.tar,rewrite-timestamp=true -f images/plywood-pulumi/Dockerfile . >&2',
41
+ ].join(" && "),
42
+ );
43
+ const own = releaseImageBuildCommand({ name: "tofu", dockerfile: "images/Dockerfile.tofu", context: "images/ctx", platforms: ["linux/amd64"], archive: "out/tofu image.tar" });
44
+ expect(own).toContain("--platform linux/amd64 ");
45
+ expect(own).toContain("--output 'type=oci,dest=out/tofu image.tar,rewrite-timestamp=true' -f images/Dockerfile.tofu images/ctx >&2");
46
+ expect(own).toContain("mkdir -p out && ");
47
+ });
48
+
49
+ test("the archive defaults to dist/images/<name>.tar, and a build entry is as it was", () => {
50
+ const images: ReleaseImageDeclaration[] = [
51
+ { name: "pulumi", dockerfile: "images/plywood-pulumi/Dockerfile" },
52
+ { name: "old", build: "scripts/release-image.sh old", archive: "dist/images/old.tar" },
53
+ ];
54
+ expect(resolveReleaseImages(images).map((i) => [i.name, i.archive])).toEqual([
55
+ ["pulumi", "dist/images/pulumi.tar"],
56
+ ["old", "dist/images/old.tar"],
57
+ ]);
58
+ expect(resolveReleaseImages(images)[1]).toEqual({ name: "old", build: "scripts/release-image.sh old", archive: "dist/images/old.tar" });
59
+ });
60
+
61
+ test("the prepare command runs once, before the builds, with no digests file named", () => {
62
+ const cwd = scratch();
63
+ const runs: { command: string; digests: string | undefined; epoch: string | undefined }[] = [];
64
+ const prepare = "npm run build && npm pack -w @intentius/plywood --pack-destination images/pack";
65
+ const built = buildReleaseImages({
66
+ images: [
67
+ { name: "pulumi", dockerfile: "images/plywood-pulumi/Dockerfile", prepare },
68
+ { name: "plunge", dockerfile: "images/plywood-plunge/Dockerfile", prepare },
69
+ ],
70
+ cwd,
71
+ sourceDateEpoch: 1_700_000_000,
72
+ label: "0.3.0",
73
+ env: { PATH: process.env.PATH, [RELEASE_DIGESTS_ENV]: "/tmp/stale.json" },
74
+ archiveDigest: (abs) => (abs.endsWith("pulumi.tar") ? D("a") : D("b")),
75
+ run: (command, o) => {
76
+ runs.push({ command, digests: o.env[RELEASE_DIGESTS_ENV], epoch: o.env.SOURCE_DATE_EPOCH });
77
+ const m = /dest=([^,]+),/.exec(command);
78
+ if (m) {
79
+ mkdirSync(join(cwd, "dist/images"), { recursive: true });
80
+ writeFileSync(join(cwd, m[1]!), "");
81
+ }
82
+ return 0;
83
+ },
84
+ });
85
+ expect(runs.map((r) => r.command.slice(0, 20))).toEqual([prepare.slice(0, 20), "{ docker buildx insp", "{ docker buildx insp"]);
86
+ expect(runs[0]!.digests).toBeUndefined();
87
+ expect(runs.every((r) => r.epoch === "1700000000")).toBe(true);
88
+ expect(built).toEqual([
89
+ { component: "pulumi", kind: "image", path: "dist/images/pulumi.tar", digest: D("a") },
90
+ { component: "plunge", kind: "image", path: "dist/images/plunge.tar", digest: D("b") },
91
+ ]);
92
+ });
93
+
94
+ test("run: the command reaches docker as the argv both scripts passed", () => {
95
+ const cwd = scratch();
96
+ const bin = join(cwd, "bin");
97
+ mkdirSync(bin);
98
+ const log = join(cwd, "docker.log");
99
+ // A docker that records its argv, and writes the archive --output names.
100
+ writeFileSync(
101
+ join(bin, "docker"),
102
+ `#!/bin/sh\nprintf '%s\\n' "$*" >> "${log}"\nfor a in "$@"; do case "$a" in type=oci,dest=*) d="\${a#type=oci,dest=}"; d="\${d%%,*}"; : > "$d" ;; esac; done\nexit 0\n`,
103
+ );
104
+ chmodSync(join(bin, "docker"), 0o755);
105
+ buildReleaseImages({
106
+ images: [{ name: "tofu", dockerfile: "images/Dockerfile.tofu" }],
107
+ cwd,
108
+ sourceDateEpoch: 42,
109
+ label: null,
110
+ env: { ...process.env, PATH: `${bin}:${process.env.PATH}` },
111
+ archiveDigest: () => D("c"),
112
+ });
113
+ const calls = readFileSync(log, "utf-8").trim().split("\n");
114
+ expect(calls).toEqual([
115
+ "buildx inspect chant-release",
116
+ "buildx build --builder chant-release --no-cache --platform linux/amd64,linux/arm64 --provenance=false --sbom=false --build-arg SOURCE_DATE_EPOCH=42 --output type=oci,dest=dist/images/tofu.tar,rewrite-timestamp=true -f images/Dockerfile.tofu .",
117
+ ]);
118
+ expect(existsSync(join(cwd, "dist/images/tofu.tar"))).toBe(true);
119
+ });
120
+
121
+ test("an entry with both build and dockerfile, a path outside the member, or a bad platform is refused", () => {
122
+ const refused = (i: unknown) => {
123
+ try {
124
+ checkReleaseImages([i as ReleaseImageDeclaration]);
125
+ return "";
126
+ } catch (e) {
127
+ return (e as ReleaseImageError).code;
128
+ }
129
+ };
130
+ expect(refused({ name: "a", dockerfile: "D", build: "x", archive: "a.tar" })).toBe("release-image-invalid");
131
+ expect(refused({ name: "a", dockerfile: "../D" })).toBe("release-image-archive-outside");
132
+ expect(refused({ name: "a", dockerfile: "D", context: "/abs" })).toBe("release-image-archive-outside");
133
+ expect(refused({ name: "a", dockerfile: "D", platforms: ["linux/amd64; rm"] })).toBe("release-image-invalid");
134
+ expect(refused({ name: "a", dockerfile: "D", platforms: [] })).toBe("release-image-invalid");
135
+ expect(refused({ name: "a", dockerfile: "D", platforms: ["linux/arm64/v8"] })).toBe("");
136
+ });
137
+
138
+ test("chant.config.ts takes either form", () => {
139
+ const ok = (images: unknown) => ChantConfigSchema.safeParse({ release: { images } }).success;
140
+ expect(ok([{ name: "pulumi", dockerfile: "images/plywood-pulumi/Dockerfile", context: ".", platforms: ["linux/amd64"], archive: "dist/images/pulumi.tar", prepare: "npm run build" }])).toBe(true);
141
+ expect(ok([{ name: "old", build: "x", archive: "a.tar" }])).toBe(true);
142
+ expect(ok([{ name: "old", build: "x" }])).toBe(false);
143
+ expect(ok([{ name: "both", build: "x", archive: "a.tar", dockerfile: "D" }])).toBe(false);
144
+ });
145
+
146
+ test("the floor names the next release", () => expect(RELEASE_IMAGE_DOCKERFILE_FLOOR).toBe(NEXT_RELEASE));
147
+ });
148
+
149
+ describe("the digest table and the pins file (#4819)", () => {
150
+ const digestsFile = (named: Record<string, string>) => {
151
+ const f = join(scratch(), "digests.json");
152
+ writeFileSync(f, JSON.stringify(named));
153
+ return f;
154
+ };
155
+
156
+ test("outside a release build there is no table, and the pins file is removed", () => {
157
+ const dir = scratch();
158
+ const out = join(dir, "dist/image-digests.json");
159
+ mkdirSync(join(dir, "dist"));
160
+ writeFileSync(out, "{}\n");
161
+ const table = releaseImagePins({ images: { pulumi: "ghcr.io/intentius/plywood-pulumi:0.3.0-pulumi3.272.0" }, version: "0.3.0", env: {} });
162
+ expect(table).toBeUndefined();
163
+ writeReleaseImagePins(table, { out });
164
+ expect(existsSync(out)).toBe(false);
165
+ });
166
+
167
+ test("plywood's table: each image's reference at the version, to the digest the cut recorded", () => {
168
+ const file = digestsFile({ plunge: D("b"), pulumi: D("a") });
169
+ const images = { pulumi: "ghcr.io/intentius/plywood-pulumi:0.3.0-pulumi3.272.0", plunge: "ghcr.io/intentius/plywood-plunge:0.3.0-plunge0.2.0" };
170
+ const table = releaseImagePins({ images, version: "0.3.0", env: { [RELEASE_DIGESTS_ENV]: file, CHANT_RELEASE_LABEL: "0.3.0" } });
171
+ expect(table).toEqual({ "ghcr.io/intentius/plywood-pulumi:0.3.0-pulumi3.272.0": D("a"), "ghcr.io/intentius/plywood-plunge:0.3.0-plunge0.2.0": D("b") });
172
+ expect(Object.keys(table!)).toEqual(Object.values(images));
173
+
174
+ const dir = scratch();
175
+ const bundle = join(dir, "plywood.mjs");
176
+ writeFileSync(bundle, `const digests = ${JSON.stringify(table)};\n`);
177
+ const out = join(dir, "dist/image-digests.json");
178
+ writeReleaseImagePins(table, { out, bundles: [bundle] });
179
+ // The bytes both build-cli.mjs scripts wrote.
180
+ expect(readFileSync(out, "utf-8")).toBe(`${JSON.stringify(table, null, 2)}\n`);
181
+ });
182
+
183
+ test("terragucci's table, for its four images", () => {
184
+ const names = ["tofu", "terraform", "terragrunt", "choudoufu"];
185
+ const file = digestsFile(Object.fromEntries(names.map((n, i) => [n, D(String(i + 1))])));
186
+ const images = Object.fromEntries(names.map((n) => [n, `ghcr.io/intentius/terragucci-${n}:0.4.51-${n}`]));
187
+ const table = releaseImagePins({ images, version: "0.4.51", env: { [RELEASE_DIGESTS_ENV]: file } })!;
188
+ expect(Object.entries(table)).toEqual(names.map((n, i) => [`ghcr.io/intentius/terragucci-${n}:0.4.51-${n}`, D(String(i + 1))]));
189
+ });
190
+
191
+ test("a label that is not the version, a missing digest, and a bundle without the digests are refused", () => {
192
+ const file = digestsFile({ pulumi: D("a"), plunge: "latest" });
193
+ const code = (f: () => unknown) => {
194
+ try {
195
+ f();
196
+ return "";
197
+ } catch (e) {
198
+ return `${(e as ReleaseImageError).code}: ${(e as Error).message}`;
199
+ }
200
+ };
201
+ expect(code(() => releaseImagePins({ images: { pulumi: "r" }, version: "0.3.0", env: { [RELEASE_DIGESTS_ENV]: file, CHANT_RELEASE_LABEL: "0.3.1" } }))).toBe(
202
+ "release-label-not-version: the release is labelled 0.3.1, and the package is at 0.3.0",
203
+ );
204
+ expect(code(() => releaseImagePins({ images: { plunge: "r" }, version: "0.3.0", env: { [RELEASE_DIGESTS_ENV]: file } }))).toBe(
205
+ `release-image-digest-missing: ${file} has no digest for the plunge image, which the release builds`,
206
+ );
207
+ const dir = scratch();
208
+ const bundle = join(dir, "b.mjs");
209
+ writeFileSync(bundle, "nothing here\n");
210
+ expect(code(() => writeReleaseImagePins({ "ghcr.io/x:1": D("a") }, { out: join(dir, "p.json"), bundles: [bundle] }))).toBe(`release-pin-not-bundled: ${bundle} does not carry ghcr.io/x:1@${D("a")}`);
211
+ expect(existsSync(join(dir, "p.json"))).toBe(false);
212
+ });
213
+
214
+ test("plain Node loads the module a product's build script imports", () => {
215
+ // The products' build-cli.mjs run under node with no TypeScript loader; the module must reach only node: built-ins at run time.
216
+ const src = readFileSync(join(__dirname, "release-images.ts"), "utf-8");
217
+ const runtime = [...src.matchAll(/^import (?!type)[^;]*from "([^"]+)";/gm)].map((m) => m[1]);
218
+ expect(runtime.filter((s) => !s!.startsWith("node:") && s !== "../release-floors")).toEqual([]);
219
+ expect(spawnSync("node", ["--version"]).status).toBe(0);
220
+ });
221
+ });
@@ -21,11 +21,24 @@
21
21
  * An npm target's `pins` names the file in a package that carries the
22
22
  * digests. The publish plan and `chant release verify` read it and refuse a
23
23
  * digest the release does not record as an image.
24
+ *
25
+ * An entry may name a Dockerfile instead of a command (#4819): chant runs
26
+ * the reproducible build itself ({@link releaseImageBuildCommand}), a
27
+ * `docker-container` buildx builder writing an OCI archive with timestamps
28
+ * rewritten from `SOURCE_DATE_EPOCH` and no attestations, for every
29
+ * platform. Its `prepare` command (the bundle the image carries, a packed
30
+ * package) runs first with no digests file named, so the image is the same
31
+ * in the cut and the publish job. A product's package build turns the
32
+ * digests file and its `{ name: reference }` into the table it bakes in with
33
+ * {@link releaseImagePins}, and writes the pins file with
34
+ * {@link writeReleaseImagePins}. This module reaches only Node's built-ins at
35
+ * run time, so a product's build script imports it under plain Node.
24
36
  */
25
37
 
26
38
  import { spawnSync } from "node:child_process";
27
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
28
- import { dirname, isAbsolute, relative, resolve } from "node:path";
39
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
40
+ import { dirname, isAbsolute, posix, relative, resolve } from "node:path";
41
+ import { NEXT_RELEASE } from "../release-floors";
29
42
  import type { PublishDeclaration } from "./publish-declaration";
30
43
  import type { Release, ReleaseArtifact } from "./release-store";
31
44
 
@@ -35,8 +48,15 @@ export const RELEASE_DIGESTS_ENV = "CHANT_RELEASE_DIGESTS";
35
48
  /** The first chant with `release.images`, `CHANT_RELEASE_DIGESTS`, `chant release images` and an npm target's `pins` (#4657). Products feature-detect on it. */
36
49
  export const RELEASE_IMAGES_FLOOR = "0.124.71";
37
50
 
38
- /** One image a release builds in its cut. */
39
- export interface ReleaseImageDeclaration {
51
+ /**
52
+ * The first chant whose `release.images` takes a Dockerfile entry, with
53
+ * `releaseImagePins` and `writeReleaseImagePins` for a product's package
54
+ * build (#4819).
55
+ */
56
+ export const RELEASE_IMAGE_DOCKERFILE_FLOOR = NEXT_RELEASE;
57
+
58
+ /** One image a release builds in its cut with a command of the product's. */
59
+ export interface ReleaseImageBuild {
40
60
  /** The image's name: its key in the digests file, and its artifact's `component` in the release. */
41
61
  name: string;
42
62
  /** The shell command, run in the member's directory, that writes the archive. */
@@ -45,6 +65,65 @@ export interface ReleaseImageDeclaration {
45
65
  archive: string;
46
66
  }
47
67
 
68
+ /** One image chant builds from a Dockerfile (#4819). */
69
+ export interface ReleaseImageDockerfile {
70
+ name: string;
71
+ /** The Dockerfile, relative to the member. */
72
+ dockerfile: string;
73
+ /** The build context, relative to the member. Default `.`. */
74
+ context?: string;
75
+ /** The platforms the archive's image index holds. Default {@link RELEASE_IMAGE_PLATFORMS}. */
76
+ platforms?: string[];
77
+ /** Where the archive goes, relative to the member. Default `dist/images/<name>.tar`. */
78
+ archive?: string;
79
+ /** A command run once before the builds, with `CHANT_RELEASE_DIGESTS` unset: what the image copies in, such as the bundle or a packed package. */
80
+ prepare?: string;
81
+ }
82
+
83
+ /** One image a release builds in its cut. */
84
+ export type ReleaseImageDeclaration = ReleaseImageBuild | ReleaseImageDockerfile;
85
+
86
+ /** The platforms a Dockerfile entry builds by default. Building arm64 on amd64 needs QEMU's binfmt handlers. */
87
+ export const RELEASE_IMAGE_PLATFORMS: readonly string[] = ["linux/amd64", "linux/arm64"];
88
+
89
+ /** The buildx builder a Dockerfile entry builds with, created with the `docker-container` driver when missing: the default driver cannot rewrite timestamps in an OCI archive. */
90
+ export const RELEASE_IMAGE_BUILDER = "chant-release";
91
+
92
+ const PLATFORM = /^[a-z0-9]+\/[a-z0-9_]+(?:\/[a-z0-9]+)?$/;
93
+
94
+ /** A word the shell reads as itself. */
95
+ const sh = (s: string): string => (/^[A-Za-z0-9_./:=,@+%-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`);
96
+
97
+ const isDockerfile = (i: ReleaseImageDeclaration): i is ReleaseImageDockerfile => "dockerfile" in i && i.dockerfile !== undefined;
98
+
99
+ const archiveOf = (i: ReleaseImageDeclaration): string => i.archive ?? `dist/images/${i.name}.tar`;
100
+
101
+ /**
102
+ * The shell command a Dockerfile entry builds with (#4819), the one
103
+ * terragucci's and plywood's `scripts/release-image.sh` ran: `--no-cache`,
104
+ * no provenance or SBOM in the archive (chant attaches its own), the
105
+ * `SOURCE_DATE_EPOCH` the cut sets passed as a build argument and used to
106
+ * rewrite every timestamp, and every platform in one image index.
107
+ */
108
+ export function releaseImageBuildCommand(i: ReleaseImageDockerfile): string {
109
+ const archive = archiveOf(i);
110
+ const b = RELEASE_IMAGE_BUILDER;
111
+ return [
112
+ `{ docker buildx inspect ${b} >/dev/null 2>&1 || docker buildx create --name ${b} --driver docker-container >/dev/null; }`,
113
+ `mkdir -p ${sh(posix.dirname(archive))}`,
114
+ [
115
+ `docker buildx build --builder ${b} --no-cache --platform ${sh((i.platforms ?? RELEASE_IMAGE_PLATFORMS).join(","))}`,
116
+ `--provenance=false --sbom=false --build-arg SOURCE_DATE_EPOCH="$SOURCE_DATE_EPOCH"`,
117
+ `--output ${sh(`type=oci,dest=${archive},rewrite-timestamp=true`)} -f ${sh(i.dockerfile)} ${sh(i.context ?? ".")} >&2`,
118
+ ].join(" "),
119
+ ].join(" && ");
120
+ }
121
+
122
+ /** Each entry as a command and an archive: a Dockerfile entry's command is {@link releaseImageBuildCommand}, its archive the default when it names none. */
123
+ export function resolveReleaseImages(images: readonly ReleaseImageDeclaration[]): ReleaseImageBuild[] {
124
+ return images.map((i) => (isDockerfile(i) ? { name: i.name, build: releaseImageBuildCommand(i), archive: archiveOf(i) } : i));
125
+ }
126
+
48
127
  export class ReleaseImageError extends Error {
49
128
  constructor(
50
129
  readonly code: string,
@@ -58,15 +137,22 @@ export class ReleaseImageError extends Error {
58
137
 
59
138
  const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
60
139
 
61
- /** Check a member's `release.images`: names valid and unique, archives inside the member. */
140
+ const outside = (p: string): boolean => isAbsolute(p) || p.split(/[\\/]/).includes("..");
141
+
142
+ /** Check a member's `release.images`: names valid and unique, one of `build` and `dockerfile`, paths inside the member, platforms of the form os/arch. */
62
143
  export function checkReleaseImages(images: readonly ReleaseImageDeclaration[]): void {
63
144
  const seen = new Set<string>();
64
145
  for (const i of images) {
65
146
  if (!NAME.test(i.name)) throw new ReleaseImageError("release-image-name-invalid", `release.images: "${i.name}" is not a name of letters, digits, ".", "_" and "-"`);
66
147
  if (seen.has(i.name)) throw new ReleaseImageError("release-image-name-taken", `release.images names "${i.name}" twice`);
67
148
  seen.add(i.name);
68
- if (isAbsolute(i.archive) || i.archive.split(/[\\/]/).includes("..")) {
69
- throw new ReleaseImageError("release-image-archive-outside", `release.images "${i.name}": the archive ${i.archive} is not a path inside the member`);
149
+ if (isDockerfile(i) && "build" in i) throw new ReleaseImageError("release-image-invalid", `release.images "${i.name}" names a build command and a Dockerfile; chant builds a Dockerfile itself, so name one`);
150
+ const paths: [string, string | undefined][] = isDockerfile(i) ? [["the archive", archiveOf(i)], ["the Dockerfile", i.dockerfile], ["the context", i.context]] : [["the archive", i.archive]];
151
+ for (const [what, p] of paths) {
152
+ if (p !== undefined && outside(p)) throw new ReleaseImageError("release-image-archive-outside", `release.images "${i.name}": ${what} ${p} is not a path inside the member`);
153
+ }
154
+ if (isDockerfile(i) && i.platforms !== undefined && (i.platforms.length === 0 || !i.platforms.every((p) => PLATFORM.test(p)))) {
155
+ throw new ReleaseImageError("release-image-invalid", `release.images "${i.name}": platforms is a list of os/arch such as linux/amd64, not ${JSON.stringify(i.platforms)}`);
70
156
  }
71
157
  }
72
158
  }
@@ -100,10 +186,24 @@ export function buildReleaseImages(i: BuildImagesInput): ReleaseArtifact[] {
100
186
  checkReleaseImages(i.images);
101
187
  const run = i.run ?? defaultRun;
102
188
  const out: ReleaseArtifact[] = [];
103
- for (const image of i.images) {
189
+ const envFor = (): NodeJS.ProcessEnv => {
104
190
  const env: NodeJS.ProcessEnv = { ...(i.env ?? process.env), SOURCE_DATE_EPOCH: String(i.sourceDateEpoch) };
105
191
  delete env.CHANT_RELEASE_LABEL;
106
192
  if (i.label !== null) env.CHANT_RELEASE_LABEL = i.label;
193
+ return env;
194
+ };
195
+ // #4819: each prepare command once, before any build, with no digests file, as the image's contents are built in the cut and the publish job alike.
196
+ const prepared = new Set<string>();
197
+ for (const image of i.images) {
198
+ if (!isDockerfile(image) || !image.prepare || prepared.has(image.prepare)) continue;
199
+ prepared.add(image.prepare);
200
+ const env = envFor();
201
+ delete env[RELEASE_DIGESTS_ENV];
202
+ const status = run(image.prepare, { cwd: i.cwd, env });
203
+ if (status !== 0) throw new ReleaseImageError("release-image-build-failed", `the prepare command of image "${image.name}" exited ${status ?? "with a signal"}: ${image.prepare}`);
204
+ }
205
+ for (const image of resolveReleaseImages(i.images)) {
206
+ const env = envFor();
107
207
  const status = run(image.build, { cwd: i.cwd, env });
108
208
  if (status !== 0) throw new ReleaseImageError("release-image-build-failed", `the build of image "${image.name}" exited ${status ?? "with a signal"}: ${image.build}`);
109
209
  const abs = resolve(i.cwd, image.archive);
@@ -124,6 +224,65 @@ export function releaseImageDigests(release: Pick<Release, "artifactDigests">, n
124
224
  return out;
125
225
  }
126
226
 
227
+ // ── a product's package build (#4819) ──────────────────────────────────
228
+
229
+ const SHA256 = /^sha256:[0-9a-f]{64}$/;
230
+
231
+ export interface ReleaseImagePinsInput {
232
+ /** Each image's name in `release.images`, to its reference at this version: `ghcr.io/intentius/plywood-pulumi:0.3.0-pulumi3.272.0`. */
233
+ images: Record<string, string>;
234
+ /** The package's version. A cut's label (`CHANT_RELEASE_LABEL`) must be it. */
235
+ version: string;
236
+ env?: NodeJS.ProcessEnv;
237
+ }
238
+
239
+ /**
240
+ * The digest table a release's package build bakes into its bundle: each
241
+ * reference in `images` to the digest the cut recorded for its name, in
242
+ * `images`' order. Undefined outside a release build (no
243
+ * `CHANT_RELEASE_DIGESTS`), when a pipeline names the images by tag. Refuses
244
+ * a label that is not the version and a name the digests file has no digest
245
+ * for.
246
+ */
247
+ export function releaseImagePins(i: ReleaseImagePinsInput): Record<string, string> | undefined {
248
+ const env = i.env ?? process.env;
249
+ const file = env[RELEASE_DIGESTS_ENV];
250
+ if (!file) return undefined;
251
+ const label = env.CHANT_RELEASE_LABEL;
252
+ if (label && label !== i.version) {
253
+ throw new ReleaseImageError("release-label-not-version", `the release is labelled ${label}, and the package is at ${i.version}`, `Set the package's version to ${label} on the default branch, then cut the merged commit.`);
254
+ }
255
+ const named = JSON.parse(readFileSync(file, "utf-8")) as Record<string, unknown>;
256
+ const table: Record<string, string> = {};
257
+ for (const [name, reference] of Object.entries(i.images)) {
258
+ const digest = named[name];
259
+ if (typeof digest !== "string" || !SHA256.test(digest)) throw new ReleaseImageError("release-image-digest-missing", `${file} has no digest for the ${name} image, which the release builds`);
260
+ table[reference] = digest;
261
+ }
262
+ return table;
263
+ }
264
+
265
+ /**
266
+ * Write the pins file an npm target's `pins` names, once the bundle is
267
+ * built: the table as JSON, after checking that every bundle in `bundles`
268
+ * carries each digest. With no table (not a release build), remove the file,
269
+ * so a package never ships a stale one.
270
+ */
271
+ export function writeReleaseImagePins(table: Record<string, string> | undefined, o: { out: string; bundles?: readonly string[] }): void {
272
+ if (!table) {
273
+ rmSync(o.out, { force: true });
274
+ return;
275
+ }
276
+ for (const bundle of o.bundles ?? []) {
277
+ const text = readFileSync(bundle, "utf-8");
278
+ for (const [reference, digest] of Object.entries(table)) {
279
+ if (!text.includes(digest)) throw new ReleaseImageError("release-pin-not-bundled", `${bundle} does not carry ${reference}@${digest}`);
280
+ }
281
+ }
282
+ mkdirSync(dirname(o.out), { recursive: true });
283
+ writeFileSync(o.out, `${JSON.stringify(table, null, 2)}\n`);
284
+ }
285
+
127
286
  /** Write the digests file a package build reads. */
128
287
  export function writeReleaseDigests(file: string, digests: Record<string, string>): void {
129
288
  mkdirSync(dirname(file), { recursive: true });