@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
@@ -0,0 +1,80 @@
1
+ /**
2
+ * `chant build --components --generate <forge> --own-jobs <file>` and
3
+ * `--keep-own-jobs` (#4769): the generated file carries the repository's
4
+ * own jobs, and a build without either writes what it wrote before.
5
+ */
6
+ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { beforeEach, describe, expect, test, vi } from "vitest";
10
+ import { parseArgs } from "../parse-args";
11
+ import { setActiveProductWords } from "../../ci-product-words";
12
+
13
+ const generateComponentsPipelineMock = vi.fn();
14
+ vi.mock("../../components/cli-support", () => ({
15
+ generateComponentsPipeline: (...args: unknown[]) => generateComponentsPipelineMock(...args),
16
+ }));
17
+ vi.mock("../../config", async () => {
18
+ const actual = await vi.importActual<typeof import("../../config")>("../../config");
19
+ return { ...actual, loadChantConfigUpward: async () => ({ config: {} }) };
20
+ });
21
+ vi.mock("../plugins", async () => {
22
+ const actual = await vi.importActual<typeof import("../plugins")>("../plugins");
23
+ return { ...actual, resolveProjectLexicons: async () => [] };
24
+ });
25
+
26
+ const { runBuild } = await import("./build");
27
+
28
+ const GENERATED = ["name: chant", "jobs:", " plan:", " steps:", " - run: npx --no-install plywood components pr-plan prod", ""].join("\n");
29
+
30
+ async function build(argv: string[]): Promise<{ code: number; err: string }> {
31
+ const err: string[] = [];
32
+ vi.spyOn(console, "error").mockImplementation((s: string) => void err.push(String(s)));
33
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
34
+ const code = await runBuild({ args: parseArgs(argv) } as never);
35
+ return { code, err: err.join("\n") };
36
+ }
37
+
38
+ describe("build --own-jobs and --keep-own-jobs", () => {
39
+ let dir: string;
40
+ beforeEach(() => {
41
+ dir = mkdtempSync(join(tmpdir(), "chant-build-own-"));
42
+ generateComponentsPipelineMock.mockReset().mockResolvedValue({ success: true, yaml: GENERATED, stages: [], jobs: [] });
43
+ });
44
+
45
+ test("without either flag the file is what the generator wrote", async () => {
46
+ const out = join(dir, "ci.yml");
47
+ expect((await build(["build", ".", "--components", "--generate", "github", "--output", out])).code).toBe(0);
48
+ expect(readFileSync(out, "utf-8")).toBe(GENERATED);
49
+ });
50
+
51
+ test("--own-jobs merges the file's jobs after chant's, and refuses a collision", async () => {
52
+ const out = join(dir, "ci.yml");
53
+ writeFileSync(join(dir, "own.yml"), "lint:\n runs-on: x\n");
54
+ expect((await build(["build", ".", "--components", "--generate", "forgejo", "--own-jobs", join(dir, "own.yml"), "--output", out])).code).toBe(0);
55
+ expect(readFileSync(out, "utf-8")).toMatch(/\n {2}# Your own jobs[^\n]*\n {2}lint:\n {4}runs-on: x\n$/);
56
+ writeFileSync(join(dir, "bad.yml"), "plan:\n runs-on: x\n");
57
+ const refused = await build(["build", ".", "--components", "--generate", "forgejo", "--own-jobs", join(dir, "bad.yml"), "--output", join(dir, "other.yml")]);
58
+ expect(refused.code).toBe(1);
59
+ expect(refused.err).toMatch(/plan: chant's file has a job of that name/);
60
+ });
61
+
62
+ test("--keep-own-jobs keeps the old file's hand-added job, and drops one that runs the product's bin", async () => {
63
+ const out = join(dir, "ci.yml");
64
+ writeFileSync(out, GENERATED + " audit:\n steps:\n - run: npm audit\n stale:\n steps:\n - run: npx --no-install plywood ci run drift\n");
65
+ const before = setActiveProductWords({ product: "plywood", bin: "npx --no-install plywood" });
66
+ try {
67
+ expect((await build(["build", ".", "--components", "--generate", "github", "--keep-own-jobs", "--output", out])).code).toBe(0);
68
+ } finally {
69
+ setActiveProductWords(before);
70
+ }
71
+ const text = readFileSync(out, "utf-8");
72
+ expect(text).toContain(" audit:\n steps:\n - run: npm audit\n");
73
+ expect(text).not.toContain("stale:");
74
+ });
75
+
76
+ test("--keep-own-jobs needs a file to read, and the flags need generate mode", async () => {
77
+ expect((await build(["build", ".", "--components", "--generate", "github", "--keep-own-jobs"])).err).toMatch(/needs --output/);
78
+ expect(() => parseArgs(["build", ".", "--own-jobs", "own.yml"])).toThrow(/--own-jobs needs build --components --generate/);
79
+ });
80
+ });
@@ -0,0 +1,87 @@
1
+ /**
2
+ * `chant build --pr-loop --control <repo> --control-setting <key>=<value>`
3
+ * (#4772): the build takes the control repo and its read secret, so the
4
+ * note job it writes reads the control repo's records itself, and no
5
+ * product splices `productPipelineJobs(...).post.control` into the file.
6
+ */
7
+ import { describe, expect, test, vi } from "vitest";
8
+ import { parseYAML } from "../../yaml";
9
+ import { parseArgs } from "../parse-args";
10
+ import { prLoopFlagsProblem } from "./build";
11
+ import { controlNoteCheckout } from "../../control/dispatch";
12
+ import { productPipelineJobs } from "../../components/product-pipeline";
13
+ import type { DriverComponent } from "../../components/driver";
14
+
15
+ const generateComponentsPipelineMock = vi.fn(async () => ({ success: true, yaml: "x", stages: [], jobs: [] }));
16
+ vi.mock("../../components/cli-support", () => ({ generateComponentsPipeline: (...a: unknown[]) => generateComponentsPipelineMock(...(a as [])) }));
17
+ vi.mock("../../config", async () => {
18
+ const actual = await vi.importActual<typeof import("../../config")>("../../config");
19
+ return { ...actual, loadChantConfigUpward: async () => ({ config: {} }) };
20
+ });
21
+ vi.mock("../plugins", async () => {
22
+ const actual = await vi.importActual<typeof import("../plugins")>("../plugins");
23
+ return { ...actual, resolveProjectLexicons: async () => [] };
24
+ });
25
+
26
+ const { runBuild } = await import("./build");
27
+
28
+ const CONTROL = ["--control", "github.com/acme/control", "--control-setting", "op=deploy", "--control-setting", "member=network", "--control-setting", "readTokenSecret=PLYWOOD_CONTROL_READ"];
29
+ const ESTATE: DriverComponent[] = [{ name: "net", dependsOn: [], deploy: [{ phase: "Apply", steps: [{ kind: "terraform-apply", root: "net" }] }] }];
30
+
31
+ async function options(forge: string, extra: string[] = []): Promise<{ code: number; options: Record<string, unknown> | undefined; err: string }> {
32
+ generateComponentsPipelineMock.mockClear();
33
+ const err: string[] = [];
34
+ vi.spyOn(console, "error").mockImplementation((s: string) => void err.push(String(s)));
35
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
36
+ const code = await runBuild({ args: parseArgs(["build", ".", "--components", "--generate", forge, "--pr-loop", ...extra]) } as never);
37
+ const call = generateComponentsPipelineMock.mock.calls[0] as unknown[] | undefined;
38
+ return { code, options: call?.[2] as Record<string, unknown> | undefined, err: err.join("\n") };
39
+ }
40
+
41
+ describe("build --pr-loop --control", () => {
42
+ test("hands the generator the control target, with the read secret", async () => {
43
+ const { code, options: o } = await options("github", CONTROL);
44
+ expect(code).toBe(0);
45
+ const control = (o!.prLoop as { control: { target: Record<string, unknown> } }).control;
46
+ expect(control.target).toMatchObject({ repo: "github.com/acme/control", forge: "github", op: "deploy", member: "network", readTokenSecret: "PLYWOOD_CONTROL_READ" });
47
+ });
48
+
49
+ for (const forge of ["github", "forgejo", "gitlab"] as const) {
50
+ test(`the ${forge} note job carries the read, the step productPipelineJobs hands back as post.control`, async () => {
51
+ const { options: o } = await options(forge, CONTROL);
52
+ const prLoop = o!.prLoop as { control: { target: import("../../control/dispatch").ControlTarget } };
53
+ const step = controlNoteCheckout(forge, prLoop.control.target);
54
+ expect(productPipelineJobs(forge, "prod", { words: { commands: {} }, control: { target: prLoop.control.target } }).post.control).toEqual(step);
55
+ const lexicon = forge === "gitlab" ? "gitlab" : "github";
56
+ const gen = (await import(`@intentius/chant-lexicon-${lexicon}/components/generate-pipeline`)) as Record<string, (c: DriverComponent[], o: unknown) => { yaml: string }>;
57
+ const { yaml } = forge === "gitlab" ? gen.generateGitlabPipeline!(ESTATE, o) : gen.generateGithubPipeline!(ESTATE, { ...o, prLoop: { ...prLoop, forge } });
58
+ const note = (parseYAML(yaml) as Record<string, unknown> & { jobs?: Record<string, unknown> });
59
+ const job = JSON.stringify(forge === "gitlab" ? note["plan-note"] : note.jobs!["plan-note"]);
60
+ expect(job).toContain(JSON.stringify(step.script).slice(1, -1));
61
+ if (forge !== "gitlab") expect(job).toContain("secrets.PLYWOOD_CONTROL_READ");
62
+ else expect(job).toContain("PLYWOOD_CONTROL_READ");
63
+ });
64
+ }
65
+
66
+ test("without --control no control reaches the generator", async () => {
67
+ const { options: o } = await options("github");
68
+ expect((o!.prLoop as Record<string, unknown>).control).toBeUndefined();
69
+ });
70
+
71
+ test("refuses settings that do not hold, and the flags without --pr-loop", async () => {
72
+ const missing = await options("github", ["--control", "github.com/acme/control"]);
73
+ expect(missing.code).toBe(1);
74
+ expect(missing.err).toMatch(/control\.op must name the Op/);
75
+ expect(missing.err).toMatch(/control\.member must name this repo/);
76
+ const same = await options("github", [...CONTROL, "--control-setting", "tokenSecret=PLYWOOD_CONTROL_READ"]);
77
+ expect(same.err).toMatch(/must not be the dispatch token's secret/);
78
+ expect(() => parseArgs(["build", "--control-setting", "color=blue"])).toThrow(/--control-setting needs <key>=<value>/);
79
+ expect(prLoopFlagsProblem({ controlRepo: "github.com/acme/control" })).toMatch(/--control .*needs --pr-loop/);
80
+ expect(prLoopFlagsProblem({ prLoop: true, controlSettings: { op: "deploy" } })).toMatch(/needs --control <repo>/);
81
+ });
82
+ });
83
+
84
+ test("PR_LOOP_CONTROL_FLOOR marks it in the ci-product entry", async () => {
85
+ const ciProduct = await import("../../ci-product");
86
+ expect((ciProduct as Record<string, unknown>).PR_LOOP_CONTROL_FLOOR).toBe("0.124.77");
87
+ });
@@ -0,0 +1,59 @@
1
+ /**
2
+ * `--run-group <key>` (#4771) reaches the generator's `runGroup`, on `chant
3
+ * build --components --generate` and on `chant run --generate` with an op
4
+ * waves spec, and a build without it passes no `runGroup`.
5
+ */
6
+ import { mkdtempSync, writeFileSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { describe, expect, test, vi } from "vitest";
10
+ import { parseArgs } from "../parse-args";
11
+
12
+ const generateComponentsPipelineMock = vi.fn(async () => ({ success: true, yaml: "x", stages: [], jobs: [] }));
13
+ const generateOpWavesPipelineMock = vi.fn(async () => ({ success: true, files: [], jobs: [] }));
14
+ vi.mock("../../components/cli-support", () => ({ generateComponentsPipeline: (...a: unknown[]) => generateComponentsPipelineMock(...(a as [])) }));
15
+ vi.mock("../../op/generate-pipeline", async () => {
16
+ const actual = await vi.importActual<typeof import("../../op/generate-pipeline")>("../../op/generate-pipeline");
17
+ return { ...actual, generateOpWavesPipeline: (...a: unknown[]) => generateOpWavesPipelineMock(...(a as [])) };
18
+ });
19
+ vi.mock("../../config", async () => {
20
+ const actual = await vi.importActual<typeof import("../../config")>("../../config");
21
+ return { ...actual, loadChantConfigUpward: async () => ({ config: {} }) };
22
+ });
23
+ vi.mock("../plugins", async () => {
24
+ const actual = await vi.importActual<typeof import("../plugins")>("../plugins");
25
+ return { ...actual, resolveProjectLexicons: async () => [] };
26
+ });
27
+
28
+ const { runBuild } = await import("./build");
29
+ const { runOpGenerate } = await import("./run-generate");
30
+
31
+ describe("--run-group", () => {
32
+ test("takes commit or pull-request", () => {
33
+ expect(parseArgs(["build", ".", "--components", "--generate", "forgejo", "--run-group", "pull-request"]).runGroup).toBe("pull-request");
34
+ expect(() => parseArgs(["build", "--run-group", "branch"])).toThrow(/--run-group takes commit or pull-request/);
35
+ });
36
+
37
+ test("build passes it to the generator, and passes none without it", async () => {
38
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
39
+ await runBuild({ args: parseArgs(["build", ".", "--components", "--generate", "forgejo", "--run-group", "pull-request"]) } as never);
40
+ expect((generateComponentsPipelineMock.mock.calls[0] as unknown[])[2]).toMatchObject({ runGroup: "pull-request" });
41
+ await runBuild({ args: parseArgs(["build", ".", "--components", "--generate", "forgejo"]) } as never);
42
+ expect((generateComponentsPipelineMock.mock.calls[1] as unknown[])[2]).not.toHaveProperty("runGroup");
43
+ });
44
+
45
+ test("run --generate passes it with an op waves spec", async () => {
46
+ const dir = mkdtempSync(join(tmpdir(), "chant-run-group-"));
47
+ const spec = join(dir, "waves.json");
48
+ writeFileSync(spec, JSON.stringify({ name: "w", op: "o", plan: ["p"], waves: [{ name: "a", runs: [{ target: "a" }] }] }));
49
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
50
+ await runOpGenerate({ args: parseArgs(["run", "--generate", "forgejo", "--spec", spec, "--run-group", "commit", "--output", dir]) } as never);
51
+ expect((generateOpWavesPipelineMock.mock.calls[0] as unknown[])[2]).toMatchObject({ runGroup: "commit" });
52
+ });
53
+ });
54
+
55
+ test("FORGEJO_RUN_GROUP_FLOOR marks it in the ci-product entry", async () => {
56
+ const ciProduct = await import("../../ci-product");
57
+ expect(ciProduct.FORGEJO_RUN_GROUP_FLOOR).toBe("0.124.77");
58
+ expect(ciProduct.RUN_GROUP_KEYS).toEqual(["commit", "pull-request"]);
59
+ });
@@ -110,8 +110,10 @@ function prLoopOption(args: CommandContext["args"], reportUrl: string | undefine
110
110
  * they do. Each value is refused by name, as `pr-apply` and `pr-post` refuse
111
111
  * it, so a build never writes a job that fails on its own line.
112
112
  */
113
- export function prLoopFlagsProblem(args: Pick<CommandContext["args"], "prLoop" | "applyBeforeMerge" | "merge" | "mergeTokenEnv" | "mergeMethod" | "respond" | "decideBackend" | "decideModel" | "targetDependents">): string | undefined {
113
+ export function prLoopFlagsProblem(args: Pick<CommandContext["args"], "prLoop" | "applyBeforeMerge" | "merge" | "mergeTokenEnv" | "mergeMethod" | "respond" | "decideBackend" | "decideModel" | "targetDependents"> & Partial<Pick<CommandContext["args"], "controlRepo" | "controlSettings">>): string | undefined {
114
114
  const given = [
115
+ ...(args.controlRepo !== undefined ? ["--control"] : []),
116
+ ...(args.controlSettings !== undefined ? ["--control-setting"] : []),
115
117
  ...(args.merge !== undefined ? ["--merge"] : []),
116
118
  ...(args.mergeTokenEnv !== undefined ? ["--merge-token-env"] : []),
117
119
  ...(args.mergeMethod !== undefined ? ["--merge-method"] : []),
@@ -133,6 +135,7 @@ export function prLoopFlagsProblem(args: Pick<CommandContext["args"], "prLoop" |
133
135
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(args.mergeTokenEnv)) return `--merge-token-env takes a variable name, not ${args.mergeTokenEnv}`;
134
136
  if (args.mergeMethod !== undefined && !(PR_MERGE_METHODS as readonly string[]).includes(args.mergeMethod)) return `--merge-method takes ${PR_MERGE_METHODS.join(", ")}, not ${args.mergeMethod}`;
135
137
  }
138
+ if (args.controlSettings !== undefined && args.controlRepo === undefined) return "--control-setting sets the control repo's settings, so it needs --control <repo>";
136
139
  const respond = args.respond ? parseRespondList(args.respond) : {};
137
140
  if ("error" in respond) return respond.error;
138
141
  const check = respond.description === "check";
@@ -141,6 +144,60 @@ export function prLoopFlagsProblem(args: Pick<CommandContext["args"], "prLoop" |
141
144
  return undefined;
142
145
  }
143
146
 
147
+ /**
148
+ * `--own-jobs <file>` and `--keep-own-jobs` (#4769): `yaml` with the jobs of
149
+ * `file` after chant's, then the jobs of the file at `target` that the new
150
+ * one lacks and that run neither chant nor the product's bin. A
151
+ * collision, a GitLab keyword, a file that is not a map of jobs, or a forge
152
+ * with no jobs file is refused.
153
+ */
154
+ async function withOwnJobs(yaml: string, lexicon: string, file: string | undefined, keep: boolean, target: string | undefined): Promise<{ yaml: string } | { error: string }> {
155
+ const ownJobs = await import("../../ci-own-jobs");
156
+ if (!(ownJobs.OWN_JOBS_FORGES as readonly string[]).includes(lexicon)) return { error: `--own-jobs and --keep-own-jobs take a ${ownJobs.OWN_JOBS_FORGES.join(", ")} pipeline, not ${lexicon}` };
157
+ const forge = lexicon as import("../../ci-own-jobs").OwnJobsForge;
158
+ if (keep && !target) return { error: "--keep-own-jobs keeps the jobs of the file the build writes over, so it needs --output <file>" };
159
+ let out = yaml;
160
+ try {
161
+ if (file !== undefined) out = ownJobs.mergeOwnJobs(out, forge, ownJobs.readOwnJobsFile(resolve(file), file), { where: file });
162
+ } catch (err) {
163
+ return { error: err instanceof Error ? err.message : String(err) };
164
+ }
165
+ if (keep && target) {
166
+ const { existsSync, readFileSync } = await import("node:fs");
167
+ const previous = existsSync(target) ? readFileSync(target, "utf-8") : undefined;
168
+ const words = activeProductWords();
169
+ const kept = ownJobs.keepOwnJobs(previous, out, forge, { bins: words.bin ? [words.bin] : [] });
170
+ out = kept.text;
171
+ }
172
+ return { yaml: out };
173
+ }
174
+
175
+ /**
176
+ * The pull request loop's `control` from `--control <repo>` and each
177
+ * `--control-setting <key>=<value>` (#4772), checked as an op waves spec's
178
+ * `control` is: `op` and `member` are needed, since a build has no
179
+ * repository name to default the member to, and the read secret is never
180
+ * the dispatch token's. The generated note job then reads the control
181
+ * repo's records with the read secret (`controlNoteCheckout`), and an apply
182
+ * on merge sends its dispatch.
183
+ */
184
+ async function buildControl(repo: string, settings: Record<string, string>): Promise<{ control: { target: import("../../control/dispatch").ControlTarget; sentCheck?: string; markSent?: string } } | { error: string }> {
185
+ const { controlSettingsProblems, resolveControlTarget, CONTROL_NAME } = await import("../../control/dispatch");
186
+ const { sentCheck, markSent, ...rest } = settings;
187
+ const input = { repo, ...rest } as import("../../control/dispatch").ControlSettingsInput;
188
+ const problems = controlSettingsProblems(input, "control");
189
+ if (!(typeof input.member === "string" && CONTROL_NAME.test(input.member))) problems.push("control.member must name this repo in the control repo's workspace");
190
+ for (const [key, line] of [["sentCheck", sentCheck], ["markSent", markSent]] as const) {
191
+ if (line !== undefined && line.includes("\n")) problems.push(`control.${key} must be one shell line`);
192
+ }
193
+ if (problems.length > 0) return { error: `--control: ${problems.join("; ")} (set each with --control-setting <key>=<value>)` };
194
+ try {
195
+ return { control: { target: resolveControlTarget(input, input.member!), ...(sentCheck ? { sentCheck } : {}), ...(markSent ? { markSent } : {}) } };
196
+ } catch (err) {
197
+ return { error: err instanceof Error ? err.message : String(err) };
198
+ }
199
+ }
200
+
144
201
  /**
145
202
  * `chant build --components --generate <lexicon>` — generate mode (#563,
146
203
  * epic #551 Phase 3). Discovers `Component` declarations under `args.path`
@@ -293,6 +350,17 @@ async function runGenerateComponents(ctx: CommandContext): Promise<number> {
293
350
  lockGrain = (await import("../../workspace/ci-lock-grain")).ciLockGrainAt(resolve(args.path), undefined, plan?.member.name) === "repo" ? "repo" : undefined;
294
351
  }
295
352
 
353
+ // #4772: --control names the control repo; the note job reads its records, and an apply on merge tells it.
354
+ let control: { target: import("../../control/dispatch").ControlTarget; sentCheck?: string; markSent?: string } | undefined;
355
+ if (args.prLoop && args.controlRepo !== undefined) {
356
+ const resolved = await buildControl(args.controlRepo, args.controlSettings ?? {});
357
+ if ("error" in resolved) {
358
+ console.error(formatError({ message: resolved.error }));
359
+ return 1;
360
+ }
361
+ control = resolved.control;
362
+ }
363
+
296
364
  // Which lexicons support generate mode is a property of the loaded lexicon
297
365
  // plugins (those implementing `generateComponentPipeline`, #688), not a
298
366
  // hard-coded core list — `generateComponentsPipeline` returns a descriptive
@@ -314,10 +382,12 @@ async function runGenerateComponents(ctx: CommandContext): Promise<number> {
314
382
  : {}),
315
383
  // #3183: a plan job per pull request and an apply job per merge.
316
384
  // #4292: on the branch ci.branches routes the member to, when it routes it.
317
- ...(args.prLoop ? { prLoop: { ...prLoopOption(args, reportUrl, reviewRules, isolatedRunners), ...(plan?.branch ? { branch: plan.branch } : {}), ...(identity ? { identity } : {}), ...(prEnvIdentity ? { prEnvIdentity } : {}), ...(locks ? { locks } : {}), ...(engineSetup.length > 0 ? { engineSetup } : {}), ...(lockGrain ? { lockGrain } : {}) } } : {}),
385
+ ...(args.prLoop ? { prLoop: { ...prLoopOption(args, reportUrl, reviewRules, isolatedRunners), ...(plan?.branch ? { branch: plan.branch } : {}), ...(identity ? { identity } : {}), ...(prEnvIdentity ? { prEnvIdentity } : {}), ...(locks ? { locks } : {}), ...(engineSetup.length > 0 ? { engineSetup } : {}), ...(lockGrain ? { lockGrain } : {}), ...(control ? { control } : {}) } } : {}),
318
386
  // #4002: the job image and the lines that install what it lacks, chant itself included.
319
387
  ...(args.image ? { image: args.image } : {}),
320
388
  ...(args.beforeScript?.length ? { beforeScript: args.beforeScript } : {}),
389
+ // #4771: a workflow-level run group, which Forgejo's generator writes.
390
+ ...(args.runGroup ? { runGroup: args.runGroup } : {}),
321
391
  },
322
392
  args.sandbox,
323
393
  paramsResolution.provenance,
@@ -328,7 +398,17 @@ async function runGenerateComponents(ctx: CommandContext): Promise<number> {
328
398
  return 1;
329
399
  }
330
400
 
331
- const yaml = result.yaml ?? "";
401
+ let yaml = result.yaml ?? "";
402
+ // #4769: the repository's own jobs, from a file and from the file this build writes over.
403
+ if (args.ownJobs !== undefined || args.keepOwnJobs) {
404
+ const target = plan ? plan.target : args.output ? resolve(args.output) : undefined;
405
+ const own = await withOwnJobs(yaml, lexicon, args.ownJobs, args.keepOwnJobs === true, target);
406
+ if ("error" in own) {
407
+ console.error(formatError({ message: own.error }));
408
+ return 1;
409
+ }
410
+ yaml = own.yaml;
411
+ }
332
412
  if (args.format === "json") {
333
413
  console.log(
334
414
  JSON.stringify(
@@ -25,6 +25,7 @@ import {
25
25
  prepareCommitRun,
26
26
  runCommit,
27
27
  runCommitArgv,
28
+ activeCommitRefusalReply,
28
29
  type HeadApproval,
29
30
  COMMIT_PUSHED_FILE,
30
31
  } from "../../ci-commit";
@@ -143,6 +144,8 @@ export async function runCommitCommandLine(ctx: CommandContext): Promise<number>
143
144
  },
144
145
  now: () => new Date(),
145
146
  ...(ci ? { runOrigin: ci.runOrigin } : {}),
147
+ // #4724: the product's bin sets its reply to a command that refused, as it sets its words.
148
+ ...(activeCommitRefusalReply() ? { refusalReply: activeCommitRefusalReply()! } : {}),
146
149
  });
147
150
  // #4749: what was pushed, for the push job's `after` lines.
148
151
  if (out.result === "pushed" && out.commit) writeFileSync(join(dir, COMMIT_PUSHED_FILE), `${out.commit}\n`);
@@ -13,15 +13,31 @@
13
13
  * 127.0.0.1:8787). The relay refuses to start with neither chat secret, or
14
14
  * with no relay key, since it could then verify nothing.
15
15
  *
16
- * Each click fetches `chant/lifecycle`, reads the signers file at base, and
17
- * records through `recordGateApproval`, one click at a time, so two clicks
18
- * never race on the ledger. A gate that asks a decision point gets its
19
- * question answered through `answerPoint` instead (#4611).
16
+ * Each click fetches the default branch and `chant/lifecycle`, reads the
17
+ * signers file at the default branch's tip, and records through
18
+ * `recordGateApproval`, one click at a time, so two clicks never race on the
19
+ * ledger. A gate that asks a decision point gets its question answered
20
+ * through `answerPoint` instead (#4611).
21
+ *
22
+ * With `--repo <url>` the relay checks its token and clones the repo itself
23
+ * (#4759, ../../notify-relay-repo.ts):
24
+ *
25
+ * ```
26
+ * chant notify relay --repo https://github.com/acme/infra.git --token-env RELAY_TOKEN --host 0.0.0.0
27
+ * ```
28
+ *
29
+ * `--token-env` names the variable holding the approve-only token (default
30
+ * `CHANT_RELAY_TOKEN`), `--forge` the forge for a host other than github.com
31
+ * and gitlab.com, and `--host` and `--port` override `CHANT_RELAY_HOST` and
32
+ * `CHANT_RELAY_PORT`. `CHANT_RELAY_REPO` and `CHANT_RELAY_FORGE` stand in for
33
+ * the flags.
20
34
  */
35
+ import { execFile } from "node:child_process";
36
+ import { promisify } from "node:util";
21
37
  import { activeProductWords } from "../../ci-product-words";
22
38
  import { CHANT_EXIT } from "../../exit-codes";
23
39
  import { DEFAULT_RELAY_MAX_AGE_SECONDS } from "../../notify";
24
- import { DEFAULT_RELAY_HOST, DEFAULT_RELAY_PORT, RELAY_ENV, startRelayServer, type RelayDeps, type RelayPending, type RelaySettings } from "../../notify-relay";
40
+ import { DEFAULT_RELAY_HOST, DEFAULT_RELAY_PORT, RELAY_ENV, RELAY_REPO_ENV, startRelayServer, type RelayDeps, type RelayPending, type RelaySettings } from "../../notify-relay";
25
41
  import { formatError, formatInfo } from "../format";
26
42
  import type { CommandContext } from "../registry";
27
43
 
@@ -56,6 +72,31 @@ function serial(): <T>(fn: () => Promise<T>) => Promise<T> {
56
72
  };
57
73
  }
58
74
 
75
+ const run = promisify(execFile);
76
+
77
+ /**
78
+ * Fetch the default branch, the one `origin/HEAD` names, so the signers are
79
+ * read at its current tip (#4759). A checkout with no `origin/HEAD` reads its
80
+ * local branch as before. A fetch that fails throws: signers read from a
81
+ * stale tip could still count one removed since.
82
+ */
83
+ export async function fetchDefaultBranch(cwd: string): Promise<void> {
84
+ let head: string;
85
+ try {
86
+ head = (await run("git", ["symbolic-ref", "-q", "refs/remotes/origin/HEAD"], { cwd })).stdout.trim();
87
+ } catch {
88
+ return;
89
+ }
90
+ const branch = head.replace(/^refs\/remotes\/origin\//, "");
91
+ if (!branch || branch === head) return;
92
+ try {
93
+ await run("git", ["fetch", "-q", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`], { cwd });
94
+ } catch (e) {
95
+ const err = e as { stderr?: string; message: string };
96
+ throw new Error(`cannot fetch ${branch} to read the signers at its tip: ${(err.stderr ?? "").trim() || err.message}`);
97
+ }
98
+ }
99
+
59
100
  /** The relay's reads and writes against the checkout at `cwd`. */
60
101
  export function checkoutRelayDeps(cwd: string, principal: string): RelayDeps {
61
102
  const words = activeProductWords();
@@ -63,11 +104,13 @@ export function checkoutRelayDeps(cwd: string, principal: string): RelayDeps {
63
104
  return {
64
105
  principal,
65
106
  words,
66
- async signers() {
67
- const { scopeSource } = await import("../../workspace/write-scope");
68
- const policy = scopeSource(cwd).policy;
69
- return { signers: policy.signers, path: policy.signersPath };
70
- },
107
+ signers: () =>
108
+ one(async () => {
109
+ await fetchDefaultBranch(cwd);
110
+ const { scopeSource } = await import("../../workspace/write-scope");
111
+ const policy = scopeSource(cwd).policy;
112
+ return { signers: policy.signers, path: policy.signersPath };
113
+ }),
71
114
  pending: (digest) =>
72
115
  one(async () => {
73
116
  const { fetchLifecycle } = await import("../../lifecycle/git");
@@ -132,16 +175,55 @@ export function checkoutRelayDeps(cwd: string, principal: string): RelayDeps {
132
175
  };
133
176
  }
134
177
 
178
+ /** The flags and variables that make the relay clone the repo itself (#4759). */
179
+ export interface RelayRepoOptions {
180
+ repo?: string;
181
+ tokenEnv?: string;
182
+ forge?: string;
183
+ host?: string;
184
+ port?: string;
185
+ }
186
+
135
187
  /** `chant notify relay`. Runs until the process is stopped. */
136
- export async function runNotifyRelay(_ctx: CommandContext): Promise<number> {
137
- const read = relaySettingsFromEnv(process.env);
138
- if ("error" in read) {
139
- console.error(formatError({ message: `chant notify relay did not start: ${read.error}` }));
188
+ export async function runNotifyRelay(ctx: CommandContext): Promise<number> {
189
+ const a = ctx.args;
190
+ return serveNotifyRelay({
191
+ ...(a.repoUrl ? { repo: a.repoUrl } : {}),
192
+ ...(a.tokenEnv ? { tokenEnv: a.tokenEnv } : {}),
193
+ ...(a.forge ? { forge: a.forge } : {}),
194
+ ...(a.host ? { host: a.host } : {}),
195
+ ...(a.port?.[0] ? { port: a.port[0] } : {}),
196
+ });
197
+ }
198
+
199
+ /** Read the settings, clone when asked, and serve. Runs until the process is stopped. */
200
+ export async function serveNotifyRelay(o: RelayRepoOptions, env: NodeJS.ProcessEnv = process.env): Promise<number> {
201
+ const fail = (why: string): number => {
202
+ console.error(formatError({ message: `chant notify relay did not start: ${why}` }));
140
203
  return CHANT_EXIT.failed;
141
- }
204
+ };
205
+ const read = relaySettingsFromEnv({ ...env, ...(o.host ? { [RELAY_ENV.host]: o.host } : {}), ...(o.port ? { [RELAY_ENV.port]: o.port } : {}) });
206
+ if ("error" in read) return fail(read.error);
142
207
  const words = activeProductWords();
143
- const principal = process.env[RELAY_ENV.principal]?.trim() || `${words.product}-relay`;
144
- const deps = checkoutRelayDeps(process.cwd(), principal);
208
+ const principal = env[RELAY_ENV.principal]?.trim() || `${words.product}-relay`;
209
+ if (/[\r\n]/.test(principal)) return fail(`${RELAY_ENV.principal} is one principal on one line`);
210
+ let cwd = process.cwd();
211
+ const repoUrl = o.repo ?? (env[RELAY_REPO_ENV.repo] || undefined);
212
+ if (repoUrl) {
213
+ const tokenEnv = o.tokenEnv ?? RELAY_REPO_ENV.token;
214
+ const { prepareRelayCheckout } = await import("../../notify-relay-repo");
215
+ const made = await prepareRelayCheckout({ url: repoUrl, token: env[tokenEnv]?.trim() ?? "", forge: o.forge ?? (env[RELAY_REPO_ENV.forge] || undefined), env });
216
+ if ("error" in made) return fail(made.error.startsWith("the token is empty") ? `${tokenEnv} is empty: the relay pushes approvals with an approve-only token` : made.error);
217
+ // The token as a git header for this process's git calls only: the relay fetches and pushes chant/lifecycle with it.
218
+ Object.assign(process.env, made.gitEnv);
219
+ cwd = made.dir;
220
+ // chant approve writes and pushes the ledger of the process's directory.
221
+ process.chdir(cwd);
222
+ console.error(formatInfo(`cloned ${made.repo.path} (${made.repo.forge}, default branch ${made.branch}) into ${cwd}, pushing as ${made.user}`));
223
+ } else if (o.tokenEnv || o.forge) {
224
+ return fail("--token-env and --forge go with --repo <url>");
225
+ }
226
+ const deps = checkoutRelayDeps(cwd, principal);
145
227
  const { url } = await startRelayServer(read.settings, deps, { host: read.host, port: read.port, log: (line) => console.error(formatInfo(line)) });
146
228
  console.error(formatInfo(`${words.product} notify relay listens at ${url} (POST /slack, POST /teams, GET /healthz), recording approvals relayed by ${principal}`));
147
229
  await new Promise<void>(() => {});
@@ -141,7 +141,7 @@ import { prPlanTargets } from "../../components/pr-targets";
141
141
  import { PREVIEW_COMMENT_ENV } from "../../components/pr-pipeline";
142
142
  import type { ComponentEnvironmentDeclaration } from "../../components/component";
143
143
  import { prLoopHooksAt, runPrHooks, type PrHoldSettled, type PrHookPlace, type PrLoopHooks } from "../../components/pr-hooks";
144
- import { decidePrPolicyOverride, policyReviewOf, prLoopPolicyAt, prPolicyReport, runPrPolicy, spendPrPolicyOverride, type PrLoopPolicy } from "../../components/pr-policy";
144
+ import { decidePrPolicyOverride, policyReviewOf, prLoopPolicyAt, preparePrPolicyEngine, prPolicyReport, runPrPolicy, spendPrPolicyOverride, type PrLoopPolicy } from "../../components/pr-policy";
145
145
  import type { OpWaveHookMoment } from "../../op/op-waves";
146
146
  import type { PrHookOutcome } from "../../pr-loop";
147
147
  import type { PrMigrationFile } from "../../pr-migrations";
@@ -817,6 +817,8 @@ interface PolicyJudged {
817
817
  async function judgePolicy(p: Prepared, at: { stage: "plan" | "apply"; op: string; pr: number | null; set: PrPlanSet }): Promise<PolicyJudged> {
818
818
  // The review is read only when a policy will run: a workspace with no policy makes no forge call for it.
819
819
  const review = p.policy.settings ? await policyReviewOf(p.forge, at.pr) : undefined;
820
+ // #4774: with ci.policy.install, the engine is fetched here, once, and only for a stage that runs the policy.
821
+ p.policy = await preparePrPolicyEngine(p.policy);
820
822
  const verdict = runPrPolicy(p.policy, { version: 1, stage: at.stage, op: at.op, gate: p.gate, env: p.env, pr: at.pr, base: p.base, head: p.head, changeSet: at.set.doc, ...(review ? { review } : {}) });
821
823
  if (!verdict) return { held: false };
822
824
  const report = prPolicyReport(verdict, p.policy.base);
@@ -42,7 +42,7 @@
42
42
  */
43
43
 
44
44
  import { execFileSync } from "node:child_process";
45
- import { cpSync, existsSync, mkdirSync } from "node:fs";
45
+ import { cpSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
46
46
  import { tmpdir } from "node:os";
47
47
  import { dirname, join, relative, resolve } from "node:path";
48
48
  import { formatBold, formatError, formatSuccess, formatWarning } from "../format";
@@ -114,8 +114,8 @@ async function laneOf(ctx: CommandContext, cwd: string): Promise<string | undefi
114
114
  }
115
115
  }
116
116
 
117
- /** The member's `release.images` (#4657), or none when the config declares none. */
118
- async function releaseImagesOf(cwd: string): Promise<Array<{ name: string; build: string; archive: string }>> {
117
+ /** The member's `release.images` (#4657), or none when the config declares none. A Dockerfile entry (#4819) keeps its form, so its prepare command runs. */
118
+ async function releaseImagesOf(cwd: string): Promise<import("../../lifecycle/release-images").ReleaseImageDeclaration[]> {
119
119
  const { loadChantConfig } = await import("../../config");
120
120
  return (await loadChantConfig(cwd)).config.release?.images ?? [];
121
121
  }
@@ -155,7 +155,7 @@ export async function runReleaseImages(ctx: CommandContext): Promise<number> {
155
155
  if (!ref) return fail("release-not-named", "release images needs a release, by label or digest", USAGE);
156
156
  const cwd = resolve(".");
157
157
  const { resolveRelease } = await import("../../lifecycle/release-store");
158
- const { buildReleaseImages, releaseImageDigests, writeReleaseDigests, ReleaseImageError, RELEASE_DIGESTS_ENV } = await import("../../lifecycle/release-images");
158
+ const { buildReleaseImages, releaseImageDigests, resolveReleaseImages, writeReleaseDigests, ReleaseImageError, RELEASE_DIGESTS_ENV } = await import("../../lifecycle/release-images");
159
159
  const { ociArchiveDigest } = await import("../../lifecycle/publish-oci");
160
160
  const { getHeadCommit } = await import("../../lifecycle/git");
161
161
  const found = await resolveRelease(ref, { cwd });
@@ -171,7 +171,7 @@ export async function runReleaseImages(ctx: CommandContext): Promise<number> {
171
171
  try {
172
172
  // --no-build: the archives the cut built were handed to this job, so they are read as they are.
173
173
  built = args.noBuild
174
- ? declared.map((d) => {
174
+ ? resolveReleaseImages(declared).map((d) => {
175
175
  const abs = resolve(cwd, d.archive);
176
176
  if (!existsSync(abs)) throw new ReleaseImageError("release-image-no-archive", `image "${d.name}" has no archive at ${d.archive}`, "Hand this job the archives the cut built, or run without --no-build to build them again.");
177
177
  return { component: d.name, kind: "image" as const, path: d.archive, digest: ociArchiveDigest(abs) };
@@ -473,7 +473,7 @@ export async function runReleaseCut(ctx: CommandContext): Promise<number> {
473
473
  // #4657: under --at the images were built in the commit's own checkout, which is removed below; the archives the
474
474
  // release records are put where release.images names them here, so the job's next step (the hand-off to the
475
475
  // publish job) finds them.
476
- if (checkout && declaredImages.length > 0) copyImageArchives(declaredImages, cutCwd, cwd);
476
+ if (checkout && declaredImages.length > 0) copyImageArchives((await import("../../lifecycle/release-images")).resolveReleaseImages(declaredImages), cutCwd, cwd);
477
477
  const push = await pushLifecycleReport({ cwd }).catch(() => ({ pushed: false, pushWarning: undefined }));
478
478
  // The tag names the release's label, which a re-cut with no label reads from the earlier cut.
479
479
  let tagged: { name: string; created: boolean } | null = null;
@@ -884,7 +884,11 @@ export async function runReleaseExport(ctx: CommandContext): Promise<number> {
884
884
  return 0;
885
885
  }
886
886
 
887
- /** Internal: compile one environment, or build artifacts, in this process, and print the JSON the cut reads. */
887
+ /**
888
+ * Internal: compile one environment, or build artifacts, in this process, and
889
+ * write the JSON the cut reads to the file `CHANT_RELEASE_COMPILE_RESULT`
890
+ * names (#4764), or print it when that is unset.
891
+ */
888
892
  export async function runReleaseCompile(ctx: CommandContext): Promise<number> {
889
893
  const { args } = ctx;
890
894
  const env = args.env;
@@ -892,16 +896,22 @@ export async function runReleaseCompile(ctx: CommandContext): Promise<number> {
892
896
  console.error(formatError({ message: "release compile needs --env <env>" }));
893
897
  return 1;
894
898
  }
895
- const { compileEnvironment, buildReleaseArtifacts } = await import("../../components/release-compile");
899
+ const { compileEnvironment, buildReleaseArtifacts, RELEASE_COMPILE_RESULT_ENV } = await import("../../components/release-compile");
900
+ // Read and cleared before the project loads, so neither a build command nor a project module inherits it.
901
+ const resultFile = process.env[RELEASE_COMPILE_RESULT_ENV];
902
+ delete process.env[RELEASE_COMPILE_RESULT_ENV];
896
903
  const params = parseParamFlags(args.param);
897
904
  const inputs = compileInputs(ctx, params);
898
905
  try {
906
+ let result: unknown;
899
907
  if (args.artifacts) {
900
908
  const names = (args.component ?? "").split(",").map((n) => n.trim()).filter(Boolean);
901
- console.log(JSON.stringify({ artifacts: await buildReleaseArtifacts(inputs, env, names) }));
909
+ result = { artifacts: await buildReleaseArtifacts(inputs, env, names) };
902
910
  } else {
903
- console.log(JSON.stringify(await compileEnvironment(inputs, env)));
911
+ result = await compileEnvironment(inputs, env);
904
912
  }
913
+ if (resultFile) writeFileSync(resultFile, JSON.stringify(result));
914
+ else console.log(JSON.stringify(result));
905
915
  return 0;
906
916
  } catch (err) {
907
917
  console.error(formatError({ message: err instanceof Error ? err.message : String(err) }));