@intentius/chant 0.124.75 → 0.124.77

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 (147) 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/agent-guard.d.ts +143 -0
  11. package/dist/agent-guard.d.ts.map +1 -0
  12. package/dist/agent-guard.js +456 -0
  13. package/dist/ci-commit.d.ts +54 -3
  14. package/dist/ci-commit.d.ts.map +1 -1
  15. package/dist/ci-commit.js +69 -7
  16. package/dist/ci-own-jobs.d.ts +81 -0
  17. package/dist/ci-own-jobs.d.ts.map +1 -0
  18. package/dist/ci-own-jobs.js +234 -0
  19. package/dist/ci-product.d.ts +39 -0
  20. package/dist/ci-product.d.ts.map +1 -1
  21. package/dist/ci-product.js +40 -0
  22. package/dist/cli/handlers/approve.d.ts +5 -1
  23. package/dist/cli/handlers/approve.d.ts.map +1 -1
  24. package/dist/cli/handlers/approve.js +17 -11
  25. package/dist/cli/handlers/build.d.ts +1 -1
  26. package/dist/cli/handlers/build.d.ts.map +1 -1
  27. package/dist/cli/handlers/build.js +88 -2
  28. package/dist/cli/handlers/commit.d.ts.map +1 -1
  29. package/dist/cli/handlers/commit.js +3 -1
  30. package/dist/cli/handlers/notify-relay.d.ts +18 -1
  31. package/dist/cli/handlers/notify-relay.d.ts.map +1 -1
  32. package/dist/cli/handlers/notify-relay.js +90 -14
  33. package/dist/cli/handlers/pr.d.ts.map +1 -1
  34. package/dist/cli/handlers/pr.js +3 -1
  35. package/dist/cli/handlers/release.d.ts +9 -1
  36. package/dist/cli/handlers/release.d.ts.map +1 -1
  37. package/dist/cli/handlers/release.js +34 -6
  38. package/dist/cli/handlers/run-generate.d.ts.map +1 -1
  39. package/dist/cli/handlers/run-generate.js +2 -1
  40. package/dist/cli/main.d.ts.map +1 -1
  41. package/dist/cli/main.js +21 -1
  42. package/dist/cli/parse-args.d.ts.map +1 -1
  43. package/dist/cli/parse-args.js +60 -4
  44. package/dist/cli/registry.d.ts +16 -0
  45. package/dist/cli/registry.d.ts.map +1 -1
  46. package/dist/components/pr-env-components.d.ts +65 -0
  47. package/dist/components/pr-env-components.d.ts.map +1 -0
  48. package/dist/components/pr-env-components.js +163 -0
  49. package/dist/components/pr-policy.d.ts +15 -0
  50. package/dist/components/pr-policy.d.ts.map +1 -1
  51. package/dist/components/pr-policy.js +24 -1
  52. package/dist/components/release-compile.d.ts +15 -3
  53. package/dist/components/release-compile.d.ts.map +1 -1
  54. package/dist/components/release-compile.js +66 -15
  55. package/dist/gate-policy.d.ts +14 -1
  56. package/dist/gate-policy.d.ts.map +1 -1
  57. package/dist/gate-policy.js +16 -6
  58. package/dist/lexicon.d.ts +17 -1
  59. package/dist/lexicon.d.ts.map +1 -1
  60. package/dist/lexicon.js +1 -0
  61. package/dist/lifecycle/gated-op.d.ts +95 -0
  62. package/dist/lifecycle/gated-op.d.ts.map +1 -0
  63. package/dist/lifecycle/gated-op.js +96 -0
  64. package/dist/lifecycle/git.d.ts.map +1 -1
  65. package/dist/lifecycle/git.js +83 -2
  66. package/dist/notify-relay-repo.d.ts +131 -0
  67. package/dist/notify-relay-repo.d.ts.map +1 -0
  68. package/dist/notify-relay-repo.js +202 -0
  69. package/dist/notify-relay.d.ts +25 -1
  70. package/dist/notify-relay.d.ts.map +1 -1
  71. package/dist/notify-relay.js +28 -2
  72. package/dist/op/op-waves-capability.js +2 -2
  73. package/dist/policy-engine.d.ts +95 -0
  74. package/dist/policy-engine.d.ts.map +1 -0
  75. package/dist/policy-engine.js +158 -0
  76. package/dist/release-floors.d.ts +1 -1
  77. package/dist/release-floors.js +1 -1
  78. package/dist/state-export.d.ts +126 -0
  79. package/dist/state-export.d.ts.map +1 -0
  80. package/dist/state-export.js +157 -0
  81. package/dist/state-migration.d.ts +148 -0
  82. package/dist/state-migration.d.ts.map +1 -0
  83. package/dist/state-migration.js +147 -0
  84. package/dist/state-unlock.d.ts +167 -0
  85. package/dist/state-unlock.d.ts.map +1 -0
  86. package/dist/state-unlock.js +197 -0
  87. package/dist/wave-runtime.mjs +329 -329
  88. package/dist/workspace/declaration.schema.json +1 -1
  89. package/dist/workspace/release-workflow.d.ts +10 -0
  90. package/dist/workspace/release-workflow.d.ts.map +1 -1
  91. package/dist/workspace/release-workflow.js +8 -3
  92. package/package.json +1 -1
  93. package/src/__fixtures__/agent-guard/plywood.ts +27 -0
  94. package/src/__fixtures__/agent-guard/terragucci.ts +39 -0
  95. package/src/__fixtures__/gated-ledger.ts +58 -0
  96. package/src/agent-guard.test.ts +320 -0
  97. package/src/agent-guard.ts +548 -0
  98. package/src/ci-commit.test.ts +50 -2
  99. package/src/ci-commit.ts +93 -9
  100. package/src/ci-own-jobs.test.ts +109 -0
  101. package/src/ci-own-jobs.ts +253 -0
  102. package/src/ci-product.ts +81 -0
  103. package/src/cli/handlers/approve-cwd.test.ts +112 -0
  104. package/src/cli/handlers/approve.ts +22 -11
  105. package/src/cli/handlers/build-own-jobs.test.ts +80 -0
  106. package/src/cli/handlers/build-pr-loop-control.test.ts +88 -0
  107. package/src/cli/handlers/build-run-group.test.ts +60 -0
  108. package/src/cli/handlers/build.ts +83 -3
  109. package/src/cli/handlers/commit.ts +3 -0
  110. package/src/cli/handlers/notify-relay.ts +99 -17
  111. package/src/cli/handlers/pr.ts +3 -1
  112. package/src/cli/handlers/release-cut-archives.test.ts +21 -0
  113. package/src/cli/handlers/release.ts +31 -6
  114. package/src/cli/handlers/run-generate.ts +2 -1
  115. package/src/cli/main.ts +21 -1
  116. package/src/cli/parse-args.ts +45 -3
  117. package/src/cli/registry.ts +16 -0
  118. package/src/components/pr-env-components.test.ts +138 -0
  119. package/src/components/pr-env-components.ts +214 -0
  120. package/src/components/pr-policy.test.ts +41 -1
  121. package/src/components/pr-policy.ts +25 -1
  122. package/src/components/release-compile.test.ts +47 -0
  123. package/src/components/release-compile.ts +70 -13
  124. package/src/gate-policy-bundle.test.ts +14 -0
  125. package/src/gate-policy.test.ts +7 -0
  126. package/src/gate-policy.ts +22 -7
  127. package/src/lexicon.ts +18 -1
  128. package/src/lifecycle/gated-op.ts +158 -0
  129. package/src/lifecycle/git.test.ts +92 -0
  130. package/src/lifecycle/git.ts +71 -2
  131. package/src/notify-relay-repo.test.ts +284 -0
  132. package/src/notify-relay-repo.ts +234 -0
  133. package/src/notify-relay.test.ts +12 -0
  134. package/src/notify-relay.ts +30 -3
  135. package/src/op/op-waves-capability.ts +2 -2
  136. package/src/policy-engine.test.ts +163 -0
  137. package/src/policy-engine.ts +201 -0
  138. package/src/release-floors.ts +1 -1
  139. package/src/state-export.test.ts +125 -0
  140. package/src/state-export.ts +228 -0
  141. package/src/state-migration.test.ts +134 -0
  142. package/src/state-migration.ts +237 -0
  143. package/src/state-unlock.test.ts +166 -0
  144. package/src/state-unlock.ts +294 -0
  145. package/src/workspace/declaration.schema.json +1 -1
  146. package/src/workspace/release-workflow.test.ts +34 -0
  147. package/src/workspace/release-workflow.ts +17 -3
@@ -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);
@@ -0,0 +1,21 @@
1
+ /** #4657: a cut with --at builds the images in the commit's own checkout; the archives are put back where release.images names them. */
2
+ import { describe, expect, test } from "vitest";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { copyImageArchives } from "./release";
7
+
8
+ describe("copyImageArchives", () => {
9
+ test("a tar archive and a layout directory land at the same paths in the caller's directory; a missing one is skipped", () => {
10
+ const from = mkdtempSync(join(tmpdir(), "chant-cut-from-"));
11
+ const to = mkdtempSync(join(tmpdir(), "chant-cut-to-"));
12
+ mkdirSync(join(from, "dist/images"), { recursive: true });
13
+ writeFileSync(join(from, "dist/images/tofu.tar"), "tar bytes");
14
+ mkdirSync(join(from, "out/layout/blobs/sha256"), { recursive: true });
15
+ writeFileSync(join(from, "out/layout/index.json"), "{}");
16
+ copyImageArchives([{ archive: "dist/images/tofu.tar" }, { archive: "out/layout" }, { archive: "dist/images/none.tar" }], from, to);
17
+ expect(readFileSync(join(to, "dist/images/tofu.tar"), "utf8")).toBe("tar bytes");
18
+ expect(readFileSync(join(to, "out/layout/index.json"), "utf8")).toBe("{}");
19
+ expect(existsSync(join(to, "dist/images/none.tar"))).toBe(false);
20
+ });
21
+ });
@@ -42,9 +42,9 @@
42
42
  */
43
43
 
44
44
  import { execFileSync } from "node:child_process";
45
- import { existsSync } from "node:fs";
45
+ import { cpSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
46
46
  import { tmpdir } from "node:os";
47
- import { join, relative, resolve } from "node:path";
47
+ import { dirname, join, relative, resolve } from "node:path";
48
48
  import { formatBold, formatError, formatSuccess, formatWarning } from "../format";
49
49
  import { parseParamFlags } from "../build-params-cli";
50
50
  import type { CommandContext } from "../registry";
@@ -120,6 +120,17 @@ async function releaseImagesOf(cwd: string): Promise<Array<{ name: string; build
120
120
  return (await loadChantConfig(cwd)).config.release?.images ?? [];
121
121
  }
122
122
 
123
+ /** Copy each `release.images` archive from the directory the cut built it in to the same path under `to`. */
124
+ export function copyImageArchives(images: ReadonlyArray<{ archive: string }>, from: string, to: string): void {
125
+ for (const i of images) {
126
+ const src = resolve(from, i.archive);
127
+ if (!existsSync(src)) continue;
128
+ const dest = resolve(to, i.archive);
129
+ mkdirSync(dirname(dest), { recursive: true });
130
+ cpSync(src, dest, { recursive: true, force: true });
131
+ }
132
+ }
133
+
123
134
  /** A commit's time in seconds, the `SOURCE_DATE_EPOCH` a release's image builds run with (#4657). */
124
135
  function commitTime(cwd: string, commit: string): number {
125
136
  return Number(execFileSync("git", ["show", "-s", "--format=%ct", commit], { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).trim());
@@ -459,6 +470,10 @@ export async function runReleaseCut(ctx: CommandContext): Promise<number> {
459
470
  }
460
471
 
461
472
  const result = await cutRelease(request);
473
+ // #4657: under --at the images were built in the commit's own checkout, which is removed below; the archives the
474
+ // release records are put where release.images names them here, so the job's next step (the hand-off to the
475
+ // publish job) finds them.
476
+ if (checkout && declaredImages.length > 0) copyImageArchives(declaredImages, cutCwd, cwd);
462
477
  const push = await pushLifecycleReport({ cwd }).catch(() => ({ pushed: false, pushWarning: undefined }));
463
478
  // The tag names the release's label, which a re-cut with no label reads from the earlier cut.
464
479
  let tagged: { name: string; created: boolean } | null = null;
@@ -869,7 +884,11 @@ export async function runReleaseExport(ctx: CommandContext): Promise<number> {
869
884
  return 0;
870
885
  }
871
886
 
872
- /** 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
+ */
873
892
  export async function runReleaseCompile(ctx: CommandContext): Promise<number> {
874
893
  const { args } = ctx;
875
894
  const env = args.env;
@@ -877,16 +896,22 @@ export async function runReleaseCompile(ctx: CommandContext): Promise<number> {
877
896
  console.error(formatError({ message: "release compile needs --env <env>" }));
878
897
  return 1;
879
898
  }
880
- 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];
881
903
  const params = parseParamFlags(args.param);
882
904
  const inputs = compileInputs(ctx, params);
883
905
  try {
906
+ let result: unknown;
884
907
  if (args.artifacts) {
885
908
  const names = (args.component ?? "").split(",").map((n) => n.trim()).filter(Boolean);
886
- console.log(JSON.stringify({ artifacts: await buildReleaseArtifacts(inputs, env, names) }));
909
+ result = { artifacts: await buildReleaseArtifacts(inputs, env, names) };
887
910
  } else {
888
- console.log(JSON.stringify(await compileEnvironment(inputs, env)));
911
+ result = await compileEnvironment(inputs, env);
889
912
  }
913
+ if (resultFile) writeFileSync(resultFile, JSON.stringify(result));
914
+ else console.log(JSON.stringify(result));
890
915
  return 0;
891
916
  } catch (err) {
892
917
  console.error(formatError({ message: err instanceof Error ? err.message : String(err) }));
@@ -99,7 +99,8 @@ async function runOpWavesGenerate(ctx: CommandContext, provider: string, specPat
99
99
  console.error(formatError({ message: err instanceof Error ? err.message : String(err) }));
100
100
  return 1;
101
101
  }
102
- const result = await generateOpWavesPipeline(spec, provider, { ...options, specFile: specPath.replace(/^\.\//, "") });
102
+ // #4771: --run-group, or the spec's options.runGroup, gives each Forgejo workflow a run group.
103
+ const result = await generateOpWavesPipeline(spec, provider, { ...options, ...(args.runGroup ? { runGroup: args.runGroup } : {}), specFile: specPath.replace(/^\.\//, "") });
103
104
  if (!result.success) {
104
105
  console.error(formatError({ message: result.error ?? "Failed to generate the Op waves pipeline" }));
105
106
  return 1;
package/src/cli/main.ts CHANGED
@@ -737,7 +737,12 @@ Ops:
737
737
  CHANT_RELAY_KEY, SLACK_SIGNING_SECRET,
738
738
  TEAMS_WEBHOOK_SECRET, CHANT_RELAY_PRINCIPAL,
739
739
  CHANT_RELAY_MAX_AGE, CHANT_RELAY_HOST (default
740
- 127.0.0.1) and CHANT_RELAY_PORT (default 8787)
740
+ 127.0.0.1, or --host) and CHANT_RELAY_PORT (default
741
+ 8787, or --port). --repo <url> --token-env <VAR>
742
+ (#4759) refuses a token that is more than
743
+ approve-only and clones the repo's default branch
744
+ itself, the token passed to git as a header only;
745
+ --forge names the forge off github.com and gitlab.com
741
746
 
742
747
  lock <target>... Lock targets for a pull request on chant/lifecycle
743
748
  (--pr <n>, --stage plan|apply|lock, --head <sha>,
@@ -1519,6 +1524,21 @@ Options:
1519
1524
  { ops, options }
1520
1525
  --promote-to <env> (build --components --generate) Add a job that
1521
1526
  promotes the deployed releases to <env>
1527
+ --own-jobs <file> (build --components --generate) Add the jobs of a
1528
+ YAML file, in the forge's syntax, after chant's; a
1529
+ name chant's file has is refused
1530
+ --keep-own-jobs (build --components --generate) Keep the jobs of the
1531
+ old --output file that run neither chant nor the
1532
+ product's bin
1533
+ --run-group <key> (build --components --generate, run --generate with
1534
+ an op waves spec) Give a Forgejo workflow a run
1535
+ group: commit or pull-request. GitHub and GitLab
1536
+ files are unchanged
1537
+ --control <repo> (build --pr-loop) The control repo: the note job
1538
+ reads its records for the cross-stack edges, and an
1539
+ apply on merge tells it. With --control-setting
1540
+ <key>=<value> (repeatable) for op, member,
1541
+ readTokenSecret and the other control settings
1522
1542
  --no-release-record Skip auto-emitting a release-ledger record after a
1523
1543
  successful \`run --components\` deploy (default: on;
1524
1544
  also settable via chant.config.ts's
@@ -814,9 +814,23 @@ export function parseArgs(args: string[]): ParsedArgs {
814
814
  result.ciSecrets = args[++i];
815
815
  if (!result.ciSecrets || result.ciSecrets.startsWith("-")) throw new Error("--secrets needs the host's secrets file, a dotenv or JSON file only its owner can read: --secrets <file>");
816
816
  } else if (arg === "--repo") {
817
- // `chant ci serve --repo <owner/repo>` (#4095): the repository whose pull requests and target branch it polls.
818
- result.ciRepo = args[++i];
819
- if (!result.ciRepo || !/^[^/\s-][^/\s]*\/[^/\s]+$/.test(result.ciRepo)) throw new Error("--repo needs the repository as owner/name: --repo <owner/repo>");
817
+ const value = args[++i];
818
+ if (value && /^https?:\/\//.test(value)) {
819
+ // `chant notify relay --repo <url>` (#4759): the repository the relay clones.
820
+ result.repoUrl = value;
821
+ } else {
822
+ // `chant ci serve --repo <owner/repo>` (#4095): the repository whose pull requests and target branch it polls.
823
+ result.ciRepo = value;
824
+ if (!result.ciRepo || !/^[^/\s-][^/\s]*\/[^/\s]+$/.test(result.ciRepo)) throw new Error("--repo needs the repository as owner/name, or for chant notify relay its https clone address: --repo <owner/repo>, --repo <url>");
825
+ }
826
+ } else if (arg === "--token-env") {
827
+ // `chant notify relay --token-env <VAR>` (#4759): the variable holding the relay's approve-only token.
828
+ result.tokenEnv = args[++i];
829
+ if (!result.tokenEnv || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(result.tokenEnv)) throw new Error("--token-env needs a variable's name: --token-env <VAR>");
830
+ } else if (arg === "--host") {
831
+ // `chant notify relay --host <address>` (#4759): where the relay listens; 0.0.0.0 for every interface.
832
+ result.host = args[++i];
833
+ if (!result.host || result.host.startsWith("-")) throw new Error("--host needs an address to listen on, such as 0.0.0.0: --host <address>");
820
834
  } else if (arg === "--run-index-limit") {
821
835
  // `chant ci run --run-index-limit <n>` (#4098): how many runs the index at the report URL keeps.
822
836
  const n = Number(args[++i]);
@@ -868,6 +882,30 @@ export function parseArgs(args: string[]): ParsedArgs {
868
882
  if (!result.by || result.by.startsWith("-")) throw new Error("--by needs the reviewer: --by <principal>");
869
883
  // Repeatable for `workspace points answer` (#2739): each person who answered.
870
884
  (result.bys ??= []).push(result.by);
885
+ } else if (arg === "--own-jobs") {
886
+ // `chant build --components --generate <forge> --own-jobs <file>` (#4769).
887
+ const value = args[++i];
888
+ if (value === undefined || value.startsWith("-")) throw new Error("--own-jobs needs the YAML file of your own jobs: --own-jobs <file>");
889
+ result.ownJobs = value;
890
+ } else if (arg === "--keep-own-jobs") {
891
+ // `chant build --components --generate <forge> --keep-own-jobs` (#4769).
892
+ result.keepOwnJobs = true;
893
+ } else if (arg === "--run-group") {
894
+ // `chant build --components --generate forgejo --run-group <key>`, and `chant run --generate` for op waves (#4771).
895
+ const value = args[++i];
896
+ if (value !== "commit" && value !== "pull-request") throw new Error(`--run-group takes commit or pull-request: got "${value ?? ""}"`);
897
+ result.runGroup = value;
898
+ } else if (arg === "--control") {
899
+ // `chant build --pr-loop --control <repo>` (#4772).
900
+ const value = args[++i];
901
+ if (value === undefined || value.startsWith("-")) throw new Error("--control needs the control repo, such as github.com/acme/control");
902
+ result.controlRepo = value;
903
+ } else if (arg === "--control-setting") {
904
+ // `chant build --pr-loop --control-setting <key>=<value>` (#4772), repeatable.
905
+ const raw = args[++i] ?? "";
906
+ const m = /^(op|member|readTokenSecret|tokenSecret|forge|ref|apiBase|sentCheck|markSent)=(.+)$/s.exec(raw);
907
+ if (!m) throw new Error(`--control-setting needs <key>=<value>, the key one of op, member, readTokenSecret, tokenSecret, forge, ref, apiBase, sentCheck, markSent: got "${raw}"`);
908
+ (result.controlSettings ??= {})[m[1]!] = m[2]!;
871
909
  } else if (arg === "--stale-notes") {
872
910
  // `chant build --pr-loop --stale-notes` (#4628).
873
911
  result.staleNotes = true;
@@ -1308,6 +1346,10 @@ export function parseArgs(args: string[]): ParsedArgs {
1308
1346
  "--promote-to needs build --components --generate <lexicon>: it adds a promote job to the generated CI pipeline, and only generate mode emits one.",
1309
1347
  );
1310
1348
  }
1349
+ // #4769: own jobs go into the pipeline generate mode writes, and nowhere else.
1350
+ if ((result.ownJobs !== undefined || result.keepOwnJobs) && !(result.command === "build" && result.components && result.generate)) {
1351
+ throw new Error(`${result.ownJobs !== undefined ? "--own-jobs" : "--keep-own-jobs"} needs build --components --generate <forge>: it adds your own jobs to the pipeline file generate mode writes.`);
1352
+ }
1311
1353
 
1312
1354
  return result;
1313
1355
  }
@@ -567,6 +567,16 @@ export interface ParsedArgs {
567
567
  bys?: string[];
568
568
  /** `chant workspace points --open` (#2739): only the questions still open. */
569
569
  open?: boolean;
570
+ /** `chant build --components --generate <forge> --own-jobs <file>` (#4769): a YAML map of jobs, in the forge's syntax, merged after chant's jobs; a name chant's file has is refused. */
571
+ ownJobs?: string;
572
+ /** `chant build --components --generate <forge> --keep-own-jobs` (#4769): the jobs of the old output file that run neither chant nor the product's bin are kept after chant's. */
573
+ keepOwnJobs?: boolean;
574
+ /** `chant build --components --generate forgejo --run-group <key>` and `chant run --generate forgejo --spec <waves> --run-group <key>` (#4771): the Forgejo workflow's run group, `commit` or `pull-request`. */
575
+ runGroup?: "commit" | "pull-request";
576
+ /** `chant build --pr-loop --control <repo>` (#4772): the control repo, as a project key such as github.com/acme/control. The note job reads its records for the cross-stack edges, and an apply on merge tells it. */
577
+ controlRepo?: string;
578
+ /** `chant build --pr-loop --control-setting <key>=<value>` (#4772), repeatable: the rest of the control settings (op, member, readTokenSecret, tokenSecret, forge, ref, apiBase, sentCheck, markSent). */
579
+ controlSettings?: Record<string, string>;
570
580
  /** `chant build --pr-loop --stale-notes` (#4628): the note carries its target commit, and a push to the target branch marks open notes stale. */
571
581
  staleNotes?: boolean;
572
582
  /** `chant components pr-post --stale` (#4628): mark the open pull requests' notes stale after the target branch moved. */
@@ -657,6 +667,12 @@ export interface ParsedArgs {
657
667
  runIndexLimit?: number;
658
668
  /** `chant ci serve --repo <owner/repo>` (#4095): the repository it polls. */
659
669
  ciRepo?: string;
670
+ /** `chant notify relay --repo <url>` (#4759): the https clone address of the repository the relay clones. */
671
+ repoUrl?: string;
672
+ /** `chant notify relay --token-env <VAR>` (#4759): the variable holding the relay's approve-only token. */
673
+ tokenEnv?: string;
674
+ /** `chant notify relay --host <address>` (#4759): where the relay listens. */
675
+ host?: string;
660
676
  /** `chant ci serve --max-jobs <n>` (#4095): how many jobs run at once. Default 1. */
661
677
  maxJobs?: number;
662
678
  /** `chant ci serve --author <login>`, repeatable (#4095): plan only pull requests these logins opened. */