@intentius/chant 0.124.69 → 0.124.71

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 (170) hide show
  1. package/dist/ci-agent.d.ts +12 -1
  2. package/dist/ci-agent.d.ts.map +1 -1
  3. package/dist/ci-agent.js +13 -8
  4. package/dist/ci-commit.d.ts +297 -0
  5. package/dist/ci-commit.d.ts.map +1 -0
  6. package/dist/ci-commit.js +696 -0
  7. package/dist/ci-product-words.d.ts +6 -1
  8. package/dist/ci-product-words.d.ts.map +1 -1
  9. package/dist/ci-product-words.js +3 -1
  10. package/dist/cli/handlers/approve.d.ts.map +1 -1
  11. package/dist/cli/handlers/approve.js +7 -2
  12. package/dist/cli/handlers/commit.d.ts +26 -0
  13. package/dist/cli/handlers/commit.d.ts.map +1 -0
  14. package/dist/cli/handlers/commit.js +142 -0
  15. package/dist/cli/handlers/pr.d.ts +6 -0
  16. package/dist/cli/handlers/pr.d.ts.map +1 -1
  17. package/dist/cli/handlers/pr.js +16 -7
  18. package/dist/cli/handlers/release.d.ts +9 -0
  19. package/dist/cli/handlers/release.d.ts.map +1 -1
  20. package/dist/cli/handlers/release.js +114 -5
  21. package/dist/cli/main.d.ts.map +1 -1
  22. package/dist/cli/main.js +23 -0
  23. package/dist/cli/parse-args.d.ts.map +1 -1
  24. package/dist/cli/parse-args.js +15 -0
  25. package/dist/cli/registry.d.ts +4 -0
  26. package/dist/cli/registry.d.ts.map +1 -1
  27. package/dist/components/product-pipeline.d.ts +33 -0
  28. package/dist/components/product-pipeline.d.ts.map +1 -1
  29. package/dist/components/product-pipeline.js +34 -1
  30. package/dist/components/release-compile.d.ts +2 -0
  31. package/dist/components/release-compile.d.ts.map +1 -1
  32. package/dist/components/release-compile.js +8 -4
  33. package/dist/config.d.ts +46 -0
  34. package/dist/config.d.ts.map +1 -1
  35. package/dist/config.js +9 -0
  36. package/dist/lexicon.d.ts +37 -0
  37. package/dist/lexicon.d.ts.map +1 -1
  38. package/dist/lexicon.js +28 -0
  39. package/dist/lifecycle/__fixtures__/publish-fakes.d.ts +4 -0
  40. package/dist/lifecycle/__fixtures__/publish-fakes.d.ts.map +1 -1
  41. package/dist/lifecycle/__fixtures__/publish-fakes.js +6 -2
  42. package/dist/lifecycle/gated-request.d.ts +3 -1
  43. package/dist/lifecycle/gated-request.d.ts.map +1 -1
  44. package/dist/lifecycle/gated-request.js +5 -2
  45. package/dist/lifecycle/git.d.ts.map +1 -1
  46. package/dist/lifecycle/git.js +57 -0
  47. package/dist/lifecycle/publish-declaration.d.ts +16 -0
  48. package/dist/lifecycle/publish-declaration.d.ts.map +1 -1
  49. package/dist/lifecycle/publish-declaration.js +35 -3
  50. package/dist/lifecycle/publish-forge.d.ts +12 -0
  51. package/dist/lifecycle/publish-forge.d.ts.map +1 -1
  52. package/dist/lifecycle/publish-forge.js +103 -19
  53. package/dist/lifecycle/publish-npm.d.ts +15 -0
  54. package/dist/lifecycle/publish-npm.d.ts.map +1 -1
  55. package/dist/lifecycle/publish-npm.js +28 -1
  56. package/dist/lifecycle/publish-oci.d.ts +2 -0
  57. package/dist/lifecycle/publish-oci.d.ts.map +1 -1
  58. package/dist/lifecycle/publish-oci.js +10 -0
  59. package/dist/lifecycle/release-cut.d.ts +7 -1
  60. package/dist/lifecycle/release-cut.d.ts.map +1 -1
  61. package/dist/lifecycle/release-cut.js +8 -1
  62. package/dist/lifecycle/release-images.d.ts +87 -0
  63. package/dist/lifecycle/release-images.d.ts.map +1 -0
  64. package/dist/lifecycle/release-images.js +139 -0
  65. package/dist/lifecycle/release-publish.d.ts +2 -0
  66. package/dist/lifecycle/release-publish.d.ts.map +1 -1
  67. package/dist/op/activities/activity-contracts.d.ts +4 -4
  68. package/dist/op/activities/review-agent.d.ts.map +1 -1
  69. package/dist/op/activities/review-agent.js +4 -2
  70. package/dist/op/gate.d.ts +5 -1
  71. package/dist/op/gate.d.ts.map +1 -1
  72. package/dist/op/gate.js +7 -2
  73. package/dist/op/op-waves-notify.d.ts +1 -1
  74. package/dist/op/op-waves-notify.d.ts.map +1 -1
  75. package/dist/op/op-waves-notify.js +2 -1
  76. package/dist/op/op-waves-run.d.ts.map +1 -1
  77. package/dist/op/op-waves-run.js +12 -8
  78. package/dist/op/op-waves.d.ts +9 -0
  79. package/dist/op/op-waves.d.ts.map +1 -1
  80. package/dist/op/op-waves.js +11 -0
  81. package/dist/pr-forge-base.d.ts +18 -0
  82. package/dist/pr-forge-base.d.ts.map +1 -0
  83. package/dist/pr-forge-base.js +29 -0
  84. package/dist/release-floors.d.ts +1 -1
  85. package/dist/release-floors.js +1 -1
  86. package/dist/wave-runtime.mjs +305 -305
  87. package/dist/workspace/ci-green-cli.d.ts +7 -3
  88. package/dist/workspace/ci-green-cli.d.ts.map +1 -1
  89. package/dist/workspace/ci-green-cli.js +29 -8
  90. package/dist/workspace/ci-green-forge.d.ts +29 -0
  91. package/dist/workspace/ci-green-forge.d.ts.map +1 -1
  92. package/dist/workspace/ci-green-forge.js +50 -0
  93. package/dist/workspace/ci-green-workflow.d.ts +9 -1
  94. package/dist/workspace/ci-green-workflow.d.ts.map +1 -1
  95. package/dist/workspace/ci-green-workflow.js +15 -3
  96. package/dist/workspace/ci-green.d.ts +35 -1
  97. package/dist/workspace/ci-green.d.ts.map +1 -1
  98. package/dist/workspace/ci-green.js +122 -4
  99. package/dist/workspace/declaration.d.ts +14 -2
  100. package/dist/workspace/declaration.d.ts.map +1 -1
  101. package/dist/workspace/declaration.js +14 -1
  102. package/dist/workspace/declaration.schema.json +17 -2
  103. package/dist/workspace/release-workflow.d.ts +23 -0
  104. package/dist/workspace/release-workflow.d.ts.map +1 -1
  105. package/dist/workspace/release-workflow.js +203 -12
  106. package/package.json +1 -1
  107. package/src/ci-agent.ts +13 -8
  108. package/src/ci-commit.test.ts +415 -0
  109. package/src/ci-commit.ts +857 -0
  110. package/src/ci-product-words.ts +6 -2
  111. package/src/cli/handlers/approve.ts +6 -2
  112. package/src/cli/handlers/commit.ts +152 -0
  113. package/src/cli/handlers/operator.test.ts +2 -0
  114. package/src/cli/handlers/pr-wave-approve-lines.test.ts +32 -0
  115. package/src/cli/handlers/pr.ts +17 -7
  116. package/src/cli/handlers/release.ts +110 -5
  117. package/src/cli/main.ts +23 -0
  118. package/src/cli/parse-args.ts +11 -0
  119. package/src/cli/registry.ts +4 -0
  120. package/src/components/product-pipeline.test.ts +28 -1
  121. package/src/components/product-pipeline.ts +54 -1
  122. package/src/components/release-compile.ts +9 -3
  123. package/src/config.ts +24 -0
  124. package/src/lexicon.ts +56 -0
  125. package/src/lifecycle/__fixtures__/publish-fakes.ts +11 -5
  126. package/src/lifecycle/gated-request-spend.test.ts +115 -0
  127. package/src/lifecycle/gated-request.ts +5 -2
  128. package/src/lifecycle/git.ts +53 -0
  129. package/src/lifecycle/ledger-two-clones.test.ts +132 -0
  130. package/src/lifecycle/publish-declaration.ts +35 -3
  131. package/src/lifecycle/publish-forge-notes.test.ts +193 -0
  132. package/src/lifecycle/publish-forge.ts +101 -22
  133. package/src/lifecycle/publish-npm.ts +31 -2
  134. package/src/lifecycle/publish-oci.ts +10 -0
  135. package/src/lifecycle/publish-targets.test.ts +2 -1
  136. package/src/lifecycle/release-cut.ts +17 -1
  137. package/src/lifecycle/release-images.test.ts +242 -0
  138. package/src/lifecycle/release-images.ts +175 -0
  139. package/src/lifecycle/release-publish.ts +2 -0
  140. package/src/op/activities/review-agent.test.ts +20 -1
  141. package/src/op/activities/review-agent.ts +5 -2
  142. package/src/op/gate.ts +7 -2
  143. package/src/op/op-waves-approve-target.test.ts +108 -0
  144. package/src/op/op-waves-notify.ts +2 -2
  145. package/src/op/op-waves-run.ts +12 -7
  146. package/src/op/op-waves.ts +12 -0
  147. package/src/pr-forge-base.test.ts +37 -0
  148. package/src/pr-forge-base.ts +36 -0
  149. package/src/release-floors.ts +1 -1
  150. package/src/workspace/__fixtures__/release-workflow/forgejo-plain-member.yml +26 -0
  151. package/src/workspace/__fixtures__/release-workflow/forgejo-plain.yml +23 -0
  152. package/src/workspace/__fixtures__/release-workflow/forgejo-secure-member.yml +27 -0
  153. package/src/workspace/__fixtures__/release-workflow/forgejo-secure.yml +24 -0
  154. package/src/workspace/__fixtures__/release-workflow/github-plain-member.yml +26 -0
  155. package/src/workspace/__fixtures__/release-workflow/github-plain.yml +23 -0
  156. package/src/workspace/__fixtures__/release-workflow/github-secure-member.yml +27 -0
  157. package/src/workspace/__fixtures__/release-workflow/github-secure.yml +24 -0
  158. package/src/workspace/__fixtures__/release-workflow/gitlab-plain-member.yml +13 -0
  159. package/src/workspace/__fixtures__/release-workflow/gitlab-plain.yml +12 -0
  160. package/src/workspace/__fixtures__/release-workflow/gitlab-secure-member.yml +14 -0
  161. package/src/workspace/__fixtures__/release-workflow/gitlab-secure.yml +13 -0
  162. package/src/workspace/ci-green-cli.ts +27 -8
  163. package/src/workspace/ci-green-forge.ts +70 -0
  164. package/src/workspace/ci-green-workflow.ts +15 -3
  165. package/src/workspace/ci-green.ts +130 -5
  166. package/src/workspace/ci-verdict-retries.test.ts +376 -0
  167. package/src/workspace/declaration.schema.json +17 -2
  168. package/src/workspace/declaration.ts +28 -4
  169. package/src/workspace/release-workflow.test.ts +151 -0
  170. package/src/workspace/release-workflow.ts +270 -12
@@ -0,0 +1,857 @@
1
+ /**
2
+ * The commit job (#4722): run a product's fixed command on a pull request's
3
+ * head and push what it changed to the pull request's branch. terragucci's
4
+ * `respond.fmt` (a formatter after a failed format check) and sql-yodeler's
5
+ * `yodel rebase` (a forked migrations directory) are the motivating uses.
6
+ *
7
+ * It has the agent job's shape (./ci-agent.ts) without the model:
8
+ *
9
+ * - the commit job holds a read token. `chant commit prepare` reads the
10
+ * request from the run (a `/<product> <word>` comment, or the check job
11
+ * that failed before it), refuses a fork, a commenter who cannot write, a
12
+ * head the job pushed itself (the loop guard) and a pull request over
13
+ * `maxRuns`, and on the `check` trigger a head whose plan is approved on
14
+ * the ledger. `chant commit run` then runs the command's argv, with no
15
+ * shell and no forge token, in a worktree of the head, and leaves what it
16
+ * changed as a patch.
17
+ * - the push job holds the push token. `chant commit land` reads the
18
+ * request from the event again, checks the head, the limit and the
19
+ * approval again, refuses a patch outside `allowed` or on a path no job
20
+ * may change ({@link agentForbiddenPaths}), commits with a `Commit-run:`
21
+ * trailer, pushes without force, replies on a comment, and records the
22
+ * run on the ledger under op `<name>`.
23
+ *
24
+ * An empty patch lands nothing, and on the `check` trigger says nothing.
25
+ * Nothing here applies, approves or merges.
26
+ */
27
+
28
+ import { spawn } from "node:child_process";
29
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
30
+ import { join } from "node:path";
31
+ import { CHANT_EXIT } from "./exit-codes";
32
+ import { agentForbiddenPaths, AgentError, branchOk, errText, LOGIN, readSmall, SHA, type AgentGit } from "./ci-agent";
33
+ import { parseProductComment, type CiProductWords } from "./ci-product-words";
34
+ import type { OpRunRecord, OpRunRecordInput } from "./op/runtime";
35
+ import type { RunOrigin } from "./lifecycle/release-ledger";
36
+ import type { PrForge } from "./pr-forge";
37
+ import { NEXT_RELEASE } from "./release-floors";
38
+
39
+ /** The first chant with the commit job and the scheduled Op spec's `commit` (#4722). Products feature-detect on it. */
40
+ export const CI_COMMIT_FLOOR = NEXT_RELEASE;
41
+
42
+ /** What starts a commit run: a person's comment, or a check job's finding. */
43
+ export type CommitTrigger = "comment" | "check";
44
+ export const COMMIT_TRIGGERS: readonly CommitTrigger[] = ["comment", "check"];
45
+
46
+ /**
47
+ * A scheduled Op spec's `commit` (#4722). With `on: "comment"` the spec is
48
+ * the commit job's own workflow, answering `comment` on a pull request, and
49
+ * its trigger is not read. With `on: "check"` the jobs follow the Op's own
50
+ * job (the check) on a pull request and run when its run exits with one of
51
+ * `findings`.
52
+ */
53
+ export interface OpCommitSpec {
54
+ on: CommitTrigger;
55
+ /** The comment the job answers, `/<product> <word>`, for `on: "comment"`. The word maps onto `commit` in the product's words. */
56
+ comment?: string;
57
+ /** The command, an argv run with no shell: the product's own, such as `["terraform", "fmt", "-recursive"]`. */
58
+ command: string[];
59
+ /** The only paths the change may touch, from the repository root; a trailing `/` names a directory. */
60
+ allowed: string[];
61
+ /** For `on: "check"`: the exit codes of the Op's run that name a finding. Default `[2]`, chant's `drift` code. */
62
+ findings?: number[];
63
+ /** The secret (GitHub, Forgejo) or protected variable (GitLab) holding the push token. Required on GitHub and Forgejo; `CHANT_FORGE_TOKEN` by default on GitLab. */
64
+ tokenEnv?: string;
65
+ /** The most commits the job pushes to one pull request, counted on the ledger. Default 3. */
66
+ maxRuns?: number;
67
+ /** Paths beyond chant's own that the change may not touch. */
68
+ guarded?: string[];
69
+ /** Minutes the command may run. Default 10. */
70
+ timeout?: number;
71
+ /** The ledger environment the runs are recorded under. Default `local`. */
72
+ env?: string;
73
+ /** GitLab only: run the `check` trigger, which is off there by default. */
74
+ gitlabCheck?: boolean;
75
+ /**
76
+ * Merge the base branch's tip into the head (`--no-ff`) before the command
77
+ * runs (#4723), as a migrations fork shows only on that merge. A conflict
78
+ * is refused. The pushed commit is that merge, with the command's change:
79
+ * its parents are the head and the base tip.
80
+ */
81
+ mergeBase?: boolean;
82
+ }
83
+
84
+ /** A commit job's settings, every default filled and checked. */
85
+ export interface CommitSettings {
86
+ name: string;
87
+ on: CommitTrigger;
88
+ comment?: string;
89
+ command: string[];
90
+ allowed: string[];
91
+ findings: number[];
92
+ maxRuns: number;
93
+ guarded: string[];
94
+ timeout: number;
95
+ env: string;
96
+ mergeBase: boolean;
97
+ }
98
+
99
+ export const COMMIT_MAX_RUNS = 3;
100
+ export const COMMIT_TIMEOUT_MINUTES = 10;
101
+ /** The GitLab variable the push job reads its token from unless `tokenEnv` names another. */
102
+ export const COMMIT_GITLAB_TOKEN_ENV = "CHANT_FORGE_TOKEN";
103
+ /** The trailer each of the job's commits carries, naming the job. The loop guard reads it. */
104
+ export const COMMIT_TRAILER = "Commit-run";
105
+
106
+ /** The variables the generated jobs carry the settings in. The workflow file is the base branch's, so they are not the change's. */
107
+ export const COMMIT_ENV = {
108
+ name: "CHANT_COMMIT_NAME",
109
+ on: "CHANT_COMMIT_ON",
110
+ comment: "CHANT_COMMIT_COMMENT",
111
+ command: "CHANT_COMMIT_COMMAND",
112
+ allowed: "CHANT_COMMIT_ALLOWED",
113
+ findings: "CHANT_COMMIT_FINDINGS",
114
+ maxRuns: "CHANT_COMMIT_MAX_RUNS",
115
+ guarded: "CHANT_COMMIT_GUARDED",
116
+ timeout: "CHANT_COMMIT_TIMEOUT",
117
+ env: "CHANT_COMMIT_ENV",
118
+ mergeBase: "CHANT_COMMIT_MERGE_BASE",
119
+ } as const;
120
+
121
+ /** GitLab starts no pipeline on a note: a pipeline of the default branch started with these runs a comment commit job. */
122
+ export const GITLAB_COMMIT_PR_VAR = "CHANT_COMMIT_PR";
123
+ export const GITLAB_COMMIT_WORD_VAR = "CHANT_COMMIT";
124
+
125
+ /** Where the jobs keep the decision, the exit code and the patch, from the job's directory. */
126
+ export const COMMIT_DIR = ".chant/commit";
127
+ /** The local ref the checkout fetches a pull request's head into. */
128
+ export const COMMIT_HEAD_REF = "refs/chant/commit-head";
129
+ /** The local ref the jobs fetch the base branch's tip into, with `mergeBase`. */
130
+ export const COMMIT_BASE_REF = "refs/chant/commit-base";
131
+ export const COMMIT_DECISION_FILE = "decision.json";
132
+ export const COMMIT_PATCH_FILE = "change.patch";
133
+ export const COMMIT_RC_FILE = "rc";
134
+
135
+ /** The commit identity the job's commits carry. */
136
+ export const COMMIT_GIT_NAME = "chant commit";
137
+ export const COMMIT_GIT_EMAIL = "chant-commit@localhost";
138
+
139
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/;
140
+ const VAR = /^[A-Za-z_][A-Za-z0-9_]*$/;
141
+ /** An argv word as the job may carry it: no control characters, and the first one names a program, not a flag. */
142
+ const ARG = /^[^\u0000-\u001f\u007f]{1,500}$/;
143
+
144
+ function intIn(where: string, v: unknown, lo: number, hi: number): number {
145
+ if (typeof v !== "number" || !Number.isInteger(v) || v < lo || v > hi) throw new AgentError(`${where} is a whole number from ${lo} to ${hi}`);
146
+ return v;
147
+ }
148
+
149
+ function pathsIn(where: string, v: unknown): string[] {
150
+ if (!Array.isArray(v) || !v.every((p) => typeof p === "string" && p !== "" && !p.startsWith("/") && !p.split("/").some((s) => s === ".." ))) {
151
+ throw new AgentError(`${where} is a list of paths from the repository root`);
152
+ }
153
+ return (v as string[]).map((p) => p.replace(/^\.\//, ""));
154
+ }
155
+
156
+ /** The settings of commit job `name` from a spec's `commit`, checked. */
157
+ export function resolveCommitSpec(name: string, spec: OpCommitSpec, product = "chant"): CommitSettings {
158
+ const where = `Scheduled Op "${name}" commit`;
159
+ if (!NAME.test(name)) throw new AgentError(`${where}: the name is letters, digits, '.', '_' and '-'`);
160
+ if (!COMMIT_TRIGGERS.includes(spec.on)) throw new AgentError(`${where}: on is "comment" or "check"`);
161
+ if (spec.on === "comment" && !(typeof spec.comment === "string" && /^\/[a-z][a-z0-9-]* [a-z][a-z0-9-]*$/.test(spec.comment))) {
162
+ throw new AgentError(`${where}: on "comment" needs comment, the line it answers, such as "/${product} fmt"`);
163
+ }
164
+ if (!Array.isArray(spec.command) || spec.command.length === 0 || !spec.command.every((a) => typeof a === "string" && ARG.test(a)) || spec.command[0]!.startsWith("-")) {
165
+ throw new AgentError(`${where}: command is an argv, a program and its arguments, with no control characters`);
166
+ }
167
+ const allowed = pathsIn(`${where}: allowed`, spec.allowed);
168
+ if (allowed.length === 0) throw new AgentError(`${where}: allowed names at least one path the change may touch`);
169
+ const guarded = spec.guarded === undefined ? [] : pathsIn(`${where}: guarded`, spec.guarded);
170
+ if (spec.tokenEnv !== undefined && !VAR.test(spec.tokenEnv)) throw new AgentError(`${where}: tokenEnv is a variable name`);
171
+ const findings = spec.findings ?? [CHANT_EXIT.drift];
172
+ if (!Array.isArray(findings) || findings.length === 0) throw new AgentError(`${where}: findings lists at least one exit code`);
173
+ for (const f of findings) intIn(`${where}: findings`, f, 1, 255);
174
+ const env = spec.env ?? "local";
175
+ if (!NAME.test(env)) throw new AgentError(`${where}: env is a ledger environment name`);
176
+ return {
177
+ name,
178
+ on: spec.on,
179
+ ...(spec.on === "comment" ? { comment: spec.comment! } : {}),
180
+ command: [...spec.command],
181
+ allowed,
182
+ findings: [...findings],
183
+ maxRuns: spec.maxRuns === undefined ? COMMIT_MAX_RUNS : intIn(`${where}: maxRuns`, spec.maxRuns, 1, 100),
184
+ guarded,
185
+ timeout: spec.timeout === undefined ? COMMIT_TIMEOUT_MINUTES : intIn(`${where}: timeout`, spec.timeout, 1, 120),
186
+ env,
187
+ mergeBase: spec.mergeBase === true,
188
+ };
189
+ }
190
+
191
+ /** The settings as the generated jobs' variables. */
192
+ export function commitSettingsEnv(s: CommitSettings): Record<string, string> {
193
+ return {
194
+ [COMMIT_ENV.name]: s.name,
195
+ [COMMIT_ENV.on]: s.on,
196
+ ...(s.comment ? { [COMMIT_ENV.comment]: s.comment } : {}),
197
+ [COMMIT_ENV.command]: JSON.stringify(s.command),
198
+ [COMMIT_ENV.allowed]: JSON.stringify(s.allowed),
199
+ [COMMIT_ENV.findings]: s.findings.join(","),
200
+ [COMMIT_ENV.maxRuns]: String(s.maxRuns),
201
+ ...(s.guarded.length > 0 ? { [COMMIT_ENV.guarded]: JSON.stringify(s.guarded) } : {}),
202
+ [COMMIT_ENV.timeout]: String(s.timeout),
203
+ [COMMIT_ENV.env]: s.env,
204
+ ...(s.mergeBase ? { [COMMIT_ENV.mergeBase]: "1" } : {}),
205
+ };
206
+ }
207
+
208
+ /** The settings back from the job's variables, checked as {@link resolveCommitSpec} checks a spec. */
209
+ export function commitSettingsFromEnv(env: Record<string, string | undefined>, product = "chant"): CommitSettings {
210
+ const name = env[COMMIT_ENV.name];
211
+ if (!name) throw new AgentError(`${COMMIT_ENV.name} is not set: run this in a job the Op generator wrote`);
212
+ const list = (k: string): string[] | undefined => {
213
+ const v = env[k];
214
+ if (v === undefined || v === "") return undefined;
215
+ try {
216
+ const parsed: unknown = JSON.parse(v);
217
+ if (!Array.isArray(parsed) || !parsed.every((p) => typeof p === "string")) throw new Error("not a list of strings");
218
+ return parsed as string[];
219
+ } catch (e) {
220
+ throw new AgentError(`${k} is a JSON list of strings (${(e as Error).message})`);
221
+ }
222
+ };
223
+ const num = (k: string): number | undefined => {
224
+ const v = env[k];
225
+ if (v === undefined || v === "") return undefined;
226
+ if (!/^[0-9]+$/.test(v)) throw new AgentError(`${k} is a whole number: got ${JSON.stringify(v)}`);
227
+ return Number(v);
228
+ };
229
+ const f = env[COMMIT_ENV.findings];
230
+ if (f !== undefined && f !== "" && !/^[0-9]+(,[0-9]+)*$/.test(f)) throw new AgentError(`${COMMIT_ENV.findings} is exit codes separated by commas: got ${JSON.stringify(f)}`);
231
+ const maxRuns = num(COMMIT_ENV.maxRuns);
232
+ const timeout = num(COMMIT_ENV.timeout);
233
+ const guarded = list(COMMIT_ENV.guarded);
234
+ const spec: OpCommitSpec = {
235
+ on: env[COMMIT_ENV.on] as CommitTrigger,
236
+ ...(env[COMMIT_ENV.comment] ? { comment: env[COMMIT_ENV.comment] } : {}),
237
+ command: list(COMMIT_ENV.command) ?? [],
238
+ allowed: list(COMMIT_ENV.allowed) ?? [],
239
+ ...(f ? { findings: f.split(",").map(Number) } : {}),
240
+ ...(maxRuns !== undefined ? { maxRuns } : {}),
241
+ ...(timeout !== undefined ? { timeout } : {}),
242
+ ...(guarded ? { guarded } : {}),
243
+ ...(env[COMMIT_ENV.env] ? { env: env[COMMIT_ENV.env] } : {}),
244
+ ...(env[COMMIT_ENV.mergeBase] === "1" ? { mergeBase: true } : {}),
245
+ };
246
+ return resolveCommitSpec(name, spec, product);
247
+ }
248
+
249
+ // ── what the change may touch ──────────────────────────────────────────────
250
+
251
+ /** Whether `path` is inside one of `allowed` (a trailing `/` names a directory), matched as git spells it. */
252
+ function inAllowed(path: string, allowed: readonly string[]): boolean {
253
+ return allowed.some((a) => (a.endsWith("/") ? path.startsWith(a) || `${path}/` === a : path === a));
254
+ }
255
+
256
+ /** The paths of a change the job may not push: outside `allowed`, or on a path no job changes ({@link agentForbiddenPaths}). */
257
+ export function commitRefusedPaths(paths: readonly string[], s: Pick<CommitSettings, "allowed" | "guarded">): { forbidden: string[]; outside: string[] } {
258
+ return { forbidden: agentForbiddenPaths(paths, s.guarded), outside: paths.filter((p) => !inAllowed(p, s.allowed)) };
259
+ }
260
+
261
+ // ── the request ────────────────────────────────────────────────────────────
262
+
263
+ /** What a run was asked for: the pull request, and who asked on the `comment` trigger. */
264
+ export interface CommitRequest {
265
+ pr: number;
266
+ /** The commenter, or the person who started the GitLab pipeline. Absent on the `check` trigger. */
267
+ user?: string;
268
+ }
269
+
270
+ /**
271
+ * The request from the run. `comment`: the event's comment on GitHub and
272
+ * Forgejo, read against the product's grammar, which must name this job's
273
+ * word; on GitLab the pipeline's {@link GITLAB_COMMIT_PR_VAR} and
274
+ * {@link GITLAB_COMMIT_WORD_VAR}, and the user who started it. `check`: the
275
+ * pull request the check ran for, from the `pull_request` event or the
276
+ * merge request pipeline.
277
+ */
278
+ export function commitRequestFromRun(words: CiProductWords, s: Pick<CommitSettings, "on" | "comment">, env: Record<string, string | undefined>, event: unknown): CommitRequest | { refused: string } {
279
+ const gitlab = env.GITLAB_CI === "true";
280
+ let pr: unknown;
281
+ if (s.on === "check") {
282
+ pr = gitlab ? (env.CI_MERGE_REQUEST_IID ? Number(env.CI_MERGE_REQUEST_IID) : openMergeRequestOf(env)) : (event as { pull_request?: { number?: unknown } } | undefined)?.pull_request?.number;
283
+ if (typeof pr !== "number" || !Number.isInteger(pr) || pr < 1) return { refused: "the run names no pull request" };
284
+ return { pr };
285
+ }
286
+ let body: unknown;
287
+ let user: unknown;
288
+ const word = s.comment?.split(" ")[1];
289
+ if (gitlab) {
290
+ pr = Number(env[GITLAB_COMMIT_PR_VAR]);
291
+ body = env[GITLAB_COMMIT_WORD_VAR] === word ? s.comment : `/${words.product} ${env[GITLAB_COMMIT_WORD_VAR] ?? ""}`;
292
+ user = env.GITLAB_USER_LOGIN;
293
+ } else {
294
+ const e = event as { comment?: { body?: unknown; user?: { login?: unknown } }; issue?: { number?: unknown } } | undefined;
295
+ body = e?.comment?.body;
296
+ pr = e?.issue?.number;
297
+ user = e?.comment?.user?.login;
298
+ }
299
+ if (typeof pr !== "number" || !Number.isInteger(pr) || pr < 1) return { refused: "the run names no pull request" };
300
+ if (typeof user !== "string" || !LOGIN.test(user)) return { refused: "the run names nobody who asked" };
301
+ const parsed = parseProductComment(words, body, env);
302
+ if (parsed?.kind === "refused") return { refused: parsed.reason };
303
+ if (parsed?.kind !== "commit" || parsed.word !== word) return { refused: `the comment is not ${s.comment}` };
304
+ return { pr, user };
305
+ }
306
+
307
+ /**
308
+ * GitLab, a branch pipeline (a check that runs on push): the merge request
309
+ * of this project whose source is the branch, from `CI_OPEN_MERGE_REQUESTS`
310
+ * (`group/project!12,other/fork!3`), which GitLab sets with no token. The
311
+ * first of this project's when there are several; undefined when none.
312
+ */
313
+ function openMergeRequestOf(env: Record<string, string | undefined>): number | undefined {
314
+ const project = env.CI_PROJECT_PATH;
315
+ if (!project) return undefined;
316
+ for (const ref of (env.CI_OPEN_MERGE_REQUESTS ?? "").split(",")) {
317
+ const at = ref.trim().lastIndexOf("!");
318
+ if (at > 0 && ref.trim().slice(0, at) === project) {
319
+ const n = Number(ref.trim().slice(at + 1));
320
+ if (Number.isInteger(n) && n > 0) return n;
321
+ }
322
+ }
323
+ return undefined;
324
+ }
325
+
326
+ /** The branch a push run is for, on GitHub and Forgejo: `refs/heads/<branch>` from `GITHUB_REF` on a `push` event. */
327
+ function pushedBranch(env: Record<string, string | undefined>): string | undefined {
328
+ if (env.GITHUB_EVENT_NAME !== "push") return undefined;
329
+ const ref = env.GITHUB_REF ?? "";
330
+ return ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : undefined;
331
+ }
332
+
333
+ /**
334
+ * {@link commitRequestFromRun}, and for the `check` trigger of a check that
335
+ * runs on push (as terragucci's does), the open pull request whose head is
336
+ * the pushed branch, asked of the forge on GitHub and Forgejo. A branch with
337
+ * no open pull request is refused as before, which the check trigger skips.
338
+ */
339
+ export async function resolveCommitRequest(
340
+ words: CiProductWords,
341
+ s: Pick<CommitSettings, "on" | "comment">,
342
+ env: Record<string, string | undefined>,
343
+ event: unknown,
344
+ forge?: Partial<Pick<PrForge, "findPullRequest">>,
345
+ ): Promise<CommitRequest | { refused: string }> {
346
+ const req = commitRequestFromRun(words, s, env, event);
347
+ if (!("refused" in req) || s.on !== "check" || env.GITLAB_CI === "true" || !forge?.findPullRequest) return req;
348
+ const branch = pushedBranch(env);
349
+ if (!branch) return req;
350
+ const found = await forge.findPullRequest(branch);
351
+ return found && found.number > 0 ? { pr: found.number } : { refused: `${branch} has no open pull request` };
352
+ }
353
+
354
+ // ── the files between the jobs ─────────────────────────────────────────────
355
+
356
+ /** How a run ended, as its record says. `skipped` is a run with nothing to do, which says nothing and is not recorded. */
357
+ export type CommitResult = "pushed" | "refused" | "stopped" | "skipped" | "failed";
358
+
359
+ /** What `commit prepare` decided. The push job reads it as data and checks every field it uses. */
360
+ export interface CommitDecision {
361
+ version: 1;
362
+ name: string;
363
+ on: CommitTrigger;
364
+ go: boolean;
365
+ reason?: string;
366
+ /** Why not, as the record says it: `skipped` says nothing on the pull request. */
367
+ stop?: Exclude<CommitResult, "pushed" | "failed">;
368
+ sha?: string;
369
+ pr?: number;
370
+ branch?: string;
371
+ user?: string;
372
+ /** With `mergeBase`: the base branch and the tip the command ran on. */
373
+ base?: string;
374
+ baseSha?: string;
375
+ started: string;
376
+ }
377
+
378
+ export function readCommitDecision(dir: string): CommitDecision | undefined {
379
+ try {
380
+ const d = JSON.parse(readFileSync(join(dir, COMMIT_DECISION_FILE), "utf8")) as Partial<CommitDecision>;
381
+ if (d.version !== 1 || typeof d.name !== "string" || !COMMIT_TRIGGERS.includes(d.on as CommitTrigger) || typeof d.go !== "boolean" || typeof d.started !== "string") return undefined;
382
+ if (d.sha !== undefined && !SHA.test(d.sha)) return undefined;
383
+ if (d.pr !== undefined && !(Number.isInteger(d.pr) && d.pr > 0)) return undefined;
384
+ if (d.branch !== undefined && !branchOk(d.branch)) return undefined;
385
+ if (d.base !== undefined && !branchOk(d.base)) return undefined;
386
+ if (d.baseSha !== undefined && !SHA.test(d.baseSha)) return undefined;
387
+ return d as CommitDecision;
388
+ } catch {
389
+ return undefined;
390
+ }
391
+ }
392
+
393
+ // ── the ledger ─────────────────────────────────────────────────────────────
394
+
395
+ /** The commits the job pushed to pull request `pr`, from its run records. */
396
+ export function pushedTo(records: readonly Pick<OpRunRecord, "outcomes">[], pr: number): number {
397
+ return records.filter((r) => {
398
+ const c = r.outcomes?.commit as { pr?: unknown; result?: unknown } | undefined;
399
+ return c?.pr === pr && c.result === "pushed";
400
+ }).length;
401
+ }
402
+
403
+ function overRuns(s: Pick<CommitSettings, "maxRuns" | "name">, records: readonly Pick<OpRunRecord, "outcomes">[], pr: number): string | undefined {
404
+ const n = pushedTo(records, pr);
405
+ return n >= s.maxRuns ? `${s.name} pushed ${n} commit${n === 1 ? "" : "s"} to #${pr}, and its limit is ${s.maxRuns}` : undefined;
406
+ }
407
+
408
+ /** Whether the head's own last commit is this job's: the loop guard of the `check` trigger. */
409
+ function ownCommit(git: AgentGit, sha: string, name: string): boolean {
410
+ try {
411
+ const values = git(["log", "-1", `--format=%(trailers:key=${COMMIT_TRAILER},valueonly)`, sha]).split("\n").map((v) => v.trim());
412
+ return values.includes(name);
413
+ } catch {
414
+ return false;
415
+ }
416
+ }
417
+
418
+ /** The run record of one commit run: op `<name>`, one phase with one step, the outcome in `outcomes.commit`. */
419
+ export function commitRunRecordInput(o: {
420
+ settings: Pick<CommitSettings, "name" | "on" | "env">;
421
+ started: string;
422
+ ended: string;
423
+ result: CommitResult;
424
+ reason: string;
425
+ requestedBy?: string;
426
+ pr?: number;
427
+ commit?: string;
428
+ approvalVoided?: string;
429
+ gitSha?: string;
430
+ runOrigin?: RunOrigin;
431
+ }): OpRunRecordInput {
432
+ const ok = o.result === "pushed";
433
+ const durationMs = Math.max(0, Date.parse(o.ended) - Date.parse(o.started)) || 0;
434
+ const status = ok ? "ok" : o.result === "failed" ? "fail" : "skipped";
435
+ return {
436
+ op: o.settings.name,
437
+ env: o.settings.env,
438
+ started: o.started,
439
+ ended: o.ended,
440
+ status: o.result === "failed" ? "fail" : "ok",
441
+ labels: { Commit: o.settings.on },
442
+ outcomes: {
443
+ commit: {
444
+ trigger: o.settings.on,
445
+ result: o.result,
446
+ reason: o.reason,
447
+ ...(o.requestedBy ? { requestedBy: o.requestedBy } : {}),
448
+ ...(o.pr !== undefined ? { pr: o.pr } : {}),
449
+ ...(o.commit ? { commit: o.commit } : {}),
450
+ ...(o.approvalVoided ? { approvalVoided: o.approvalVoided } : {}),
451
+ },
452
+ },
453
+ phases: [{ name: "commit", status, steps: [{ fn: `commit:${o.settings.on}`, status, durationMs, ...(o.result === "failed" ? { error: o.reason } : {}) }] }],
454
+ ...(o.gitSha ? { gitSha: o.gitSha } : {}),
455
+ ...(o.runOrigin ? { runOrigin: o.runOrigin } : {}),
456
+ };
457
+ }
458
+
459
+ // ── the base merge (#4723) ─────────────────────────────────────────────────
460
+
461
+ /**
462
+ * The branch the pull request merges into: the forge's answer, else the
463
+ * run's own (the `pull_request` event's base, GitLab's target branch).
464
+ */
465
+ function baseBranchOf(asked: string | undefined, env: Record<string, string | undefined>, event: unknown): string | undefined {
466
+ const fromEvent = (event as { pull_request?: { base?: { ref?: unknown } } } | undefined)?.pull_request?.base?.ref;
467
+ const b = asked ?? (typeof fromEvent === "string" ? fromEvent : undefined) ?? (env.GITLAB_CI === "true" ? env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME : undefined);
468
+ return b && branchOk(b) ? b : undefined;
469
+ }
470
+
471
+ /** Fetch the base branch's tip into {@link COMMIT_BASE_REF} and return it. */
472
+ function fetchBase(git: AgentGit, base: string): string {
473
+ git(["fetch", "-q", "--no-tags", "origin", `+refs/heads/${base}:${COMMIT_BASE_REF}`]);
474
+ return git(["rev-parse", COMMIT_BASE_REF]).trim();
475
+ }
476
+
477
+ /** The identity the base merge is made under; the job's commit carries it too. */
478
+ const MERGE_ID = ["-c", `user.name=${COMMIT_GIT_NAME}`, "-c", `user.email=${COMMIT_GIT_EMAIL}`, "-c", "commit.gpgsign=false"];
479
+
480
+ // ── commit prepare ─────────────────────────────────────────────────────────
481
+
482
+ /** Who approved the plan of a pull request's head on the ledger, or undefined. The job's own records never answer it. */
483
+ export type HeadApproval = (pr: number, sha: string) => Promise<string | undefined>;
484
+
485
+ export interface CommitPrepareInput {
486
+ settings: CommitSettings;
487
+ words: CiProductWords;
488
+ dir: string;
489
+ env: Record<string, string | undefined>;
490
+ event?: unknown;
491
+ /** A read client: who may write, and the pull request's head. Absent on GitLab, where this job holds no token. */
492
+ forge?: Pick<PrForge, "pullRequestHead" | "userCanWrite"> & Partial<Pick<PrForge, "findPullRequest">>;
493
+ /** The branch pull request `pr` merges into, asked of the forge (./pr-forge-base.ts), for `mergeBase` (#4723). */
494
+ pullRequestBase?: (pr: number) => Promise<string | undefined>;
495
+ readRuns: () => Promise<OpRunRecord[]>;
496
+ approval: HeadApproval;
497
+ git: AgentGit;
498
+ now: Date;
499
+ }
500
+
501
+ /**
502
+ * `chant commit prepare`: decide whether the command runs, and on what. Every
503
+ * outcome is a decision file; the push job answers a refusal. The return is
504
+ * the decision.
505
+ */
506
+ export async function prepareCommitRun(i: CommitPrepareInput): Promise<CommitDecision> {
507
+ const s = i.settings;
508
+ const base = { version: 1 as const, name: s.name, on: s.on, started: i.now.toISOString() };
509
+ const write = (d: CommitDecision): CommitDecision => {
510
+ mkdirSync(i.dir, { recursive: true });
511
+ writeFileSync(join(i.dir, COMMIT_DECISION_FILE), JSON.stringify(d, null, 2) + "\n");
512
+ return d;
513
+ };
514
+ const no = (reason: string, stop: CommitDecision["stop"], extra: Partial<CommitDecision> = {}): CommitDecision => write({ ...base, go: false, reason, stop, ...extra });
515
+
516
+ const req = await resolveCommitRequest(i.words, s, i.env, i.event, i.forge);
517
+ if ("refused" in req) return no(req.refused, s.on === "check" ? "skipped" : "refused");
518
+ const who = { pr: req.pr, ...(req.user ? { user: req.user } : {}) };
519
+ if (req.user && i.forge?.userCanWrite && !(await i.forge.userCanWrite(req.user))) return no(`${req.user} cannot write to the repository, so ${s.name} does not run for them`, "refused", who);
520
+
521
+ let sha: string;
522
+ try {
523
+ sha = i.git(["rev-parse", COMMIT_HEAD_REF]).trim();
524
+ } catch (e) {
525
+ return no(`the pull request's head was not fetched (${errText(e)})`, "refused", who);
526
+ }
527
+ if (!SHA.test(sha)) return no("the pull request's head was not fetched", "refused", who);
528
+ let branch: string | undefined;
529
+ if (i.forge?.pullRequestHead) {
530
+ const head = await i.forge.pullRequestHead(req.pr);
531
+ if (!head) return no(`pull request #${req.pr} could not be read`, "refused", who);
532
+ if (!head.open) return no(`pull request #${req.pr} is not open`, "refused", who);
533
+ if (!head.sameRepo) return no(`pull request #${req.pr} comes from a fork, and ${s.name} pushes only to this repository's branches`, "refused", who);
534
+ if (!branchOk(head.branch)) return no(`pull request #${req.pr}'s branch is not one ${s.name} pushes to`, "refused", who);
535
+ if (sha !== head.sha) return no(`pull request #${req.pr} moved while ${s.name} was starting`, s.on === "check" ? "skipped" : "refused", who);
536
+ branch = head.branch;
537
+ }
538
+ // The loop guard: a check that fails on the job's own commit does not start it again.
539
+ if (s.on === "check" && ownCommit(i.git, sha, s.name)) return no(`the head is ${s.name}'s own commit`, "skipped", { ...who, sha });
540
+
541
+ let records: OpRunRecord[];
542
+ try {
543
+ records = await i.readRuns();
544
+ } catch (e) {
545
+ return no(`${s.name}'s runs could not be read from the ledger (${errText(e)}), so its limit cannot be checked`, "refused", who);
546
+ }
547
+ const over = overRuns(s, records, req.pr);
548
+ if (over) return no(over, "stopped", who);
549
+
550
+ if (s.on === "check") {
551
+ let approved: string | undefined;
552
+ try {
553
+ approved = await i.approval(req.pr, sha);
554
+ } catch (e) {
555
+ return no(`the approvals could not be read from the ledger (${errText(e)})`, "refused", who);
556
+ }
557
+ if (approved) return no(`the plan of ${sha.slice(0, 8)} is approved by ${approved}, and a commit would void that approval`, "refused", { ...who, sha });
558
+ }
559
+ let merge: { base: string; baseSha: string } | undefined;
560
+ if (s.mergeBase) {
561
+ const target = baseBranchOf(await i.pullRequestBase?.(req.pr), i.env, i.event);
562
+ if (!target) return no(`the branch #${req.pr} merges into is not known, so ${s.name} cannot merge it first`, "refused", who);
563
+ try {
564
+ merge = { base: target, baseSha: fetchBase(i.git, target) };
565
+ } catch (e) {
566
+ return no(`${target} could not be fetched (${errText(e)})`, "refused", who);
567
+ }
568
+ }
569
+ return write({ ...base, go: true, sha, ...who, ...(branch ? { branch } : {}), ...(merge ?? {}) });
570
+ }
571
+
572
+ // ── commit run ─────────────────────────────────────────────────────────────
573
+
574
+ /** Run an argv in `cwd`, with no shell. A failure or a timeout is an outcome. */
575
+ export type CommitRunCommand = (argv: readonly string[], o: { cwd: string; env: Record<string, string>; timeoutMs: number }) => Promise<{ exitCode: number | null; timedOut: boolean }>;
576
+
577
+ export const runCommitArgv: CommitRunCommand = (argv, o) =>
578
+ new Promise((done) => {
579
+ let timedOut = false;
580
+ const child = spawn(argv[0]!, argv.slice(1), { cwd: o.cwd, env: o.env, stdio: ["ignore", "inherit", "inherit"] });
581
+ const timer = setTimeout(() => {
582
+ timedOut = true;
583
+ child.kill("SIGTERM");
584
+ setTimeout(() => child.kill("SIGKILL"), 10_000).unref();
585
+ }, o.timeoutMs);
586
+ child.on("error", () => {
587
+ clearTimeout(timer);
588
+ done({ exitCode: null, timedOut });
589
+ });
590
+ child.on("close", (code) => {
591
+ clearTimeout(timer);
592
+ done({ exitCode: code, timedOut });
593
+ });
594
+ });
595
+
596
+ /**
597
+ * The variables the command sees: process basics, with the checkout's
598
+ * `node_modules/.bin` first on `PATH` so a product's bin installed on the
599
+ * target branch runs on the head's files. Never a forge or cloud token.
600
+ */
601
+ export function commitCommandEnv(env: Record<string, string | undefined>, checkout: string): Record<string, string> {
602
+ const out: Record<string, string> = {};
603
+ for (const name of ["PATH", "HOME", "TMPDIR", "LANG", "LC_ALL", "TERM", "SystemRoot", "npm_config_cache"]) {
604
+ const v = env[name];
605
+ if (v !== undefined) out[name] = v;
606
+ }
607
+ const bin = join(checkout, "node_modules", ".bin");
608
+ if (existsSync(bin)) out.PATH = out.PATH ? `${bin}:${out.PATH}` : bin;
609
+ return out;
610
+ }
611
+
612
+ export interface CommitRunInput {
613
+ settings: CommitSettings;
614
+ dir: string;
615
+ /** The checkout the job runs in: the target branch, with the product installed. */
616
+ checkout: string;
617
+ /** Where the worktree of the head goes: outside the checkout. */
618
+ workDir: string;
619
+ env: Record<string, string | undefined>;
620
+ git: AgentGit;
621
+ runCommand: CommitRunCommand;
622
+ }
623
+
624
+ /** `chant commit run`: the command in a worktree of the head; what it changed leaves as a patch. This step holds no forge token. */
625
+ export async function runCommit(i: CommitRunInput): Promise<{ rc: string; changed: boolean }> {
626
+ const rcFile = join(i.dir, COMMIT_RC_FILE);
627
+ const decision = readCommitDecision(i.dir);
628
+ if (!decision || !decision.go || !decision.sha) {
629
+ writeFileSync(rcFile, "refused\n");
630
+ return { rc: "refused", changed: false };
631
+ }
632
+ i.git(["worktree", "add", "--detach", "--force", i.workDir, decision.sha]);
633
+ if (i.settings.mergeBase) {
634
+ if (!decision.baseSha) {
635
+ writeFileSync(rcFile, "refused\n");
636
+ return { rc: "refused", changed: false };
637
+ }
638
+ try {
639
+ i.git([...MERGE_ID, "merge", "-q", "--no-ff", "--no-edit", decision.baseSha], { cwd: i.workDir });
640
+ } catch {
641
+ writeFileSync(rcFile, "conflict\n");
642
+ writeFileSync(join(i.dir, COMMIT_PATCH_FILE), "");
643
+ return { rc: "conflict", changed: false };
644
+ }
645
+ }
646
+ const out = await i.runCommand(i.settings.command, { cwd: i.workDir, env: commitCommandEnv(i.env, i.checkout), timeoutMs: i.settings.timeout * 60_000 });
647
+ const rc = out.timedOut ? "timeout" : out.exitCode === null ? "no-exit" : String(out.exitCode);
648
+ writeFileSync(rcFile, `${rc}\n`);
649
+ i.git(["add", "-A"], { cwd: i.workDir });
650
+ const patch = i.git(["diff", "--cached", "--binary", "--no-renames", "HEAD"], { cwd: i.workDir });
651
+ writeFileSync(join(i.dir, COMMIT_PATCH_FILE), patch);
652
+ return { rc, changed: patch.length > 0 };
653
+ }
654
+
655
+ // ── commit land ────────────────────────────────────────────────────────────
656
+
657
+ export interface CommitLandOutcome {
658
+ result: CommitResult;
659
+ reason: string;
660
+ commit?: string;
661
+ paths?: string[];
662
+ requestedBy?: string;
663
+ code: number;
664
+ }
665
+
666
+ export interface CommitLandInput {
667
+ settings: CommitSettings;
668
+ words: CiProductWords;
669
+ dir: string;
670
+ workDir: string;
671
+ env: Record<string, string | undefined>;
672
+ event?: unknown;
673
+ /** A write client. */
674
+ forge: Pick<PrForge, "pullRequestHead" | "addComment"> & Partial<Pick<PrForge, "findPullRequest">>;
675
+ /** As {@link CommitPrepareInput.pullRequestBase}: the land checks the base is still the one the command ran on. */
676
+ pullRequestBase?: (pr: number) => Promise<string | undefined>;
677
+ git: AgentGit;
678
+ /** Push `HEAD` of `cwd` to `ref`, never with force. */
679
+ push: (o: { cwd: string; ref: string }) => void;
680
+ readRuns: () => Promise<OpRunRecord[]>;
681
+ approval: HeadApproval;
682
+ /** Append the run's record to the ledger and push it. */
683
+ record: (input: OpRunRecordInput) => Promise<void>;
684
+ now: () => Date;
685
+ runOrigin?: RunOrigin;
686
+ }
687
+
688
+ const code = (s: string): string => "`" + s.replaceAll("`", "'") + "`";
689
+
690
+ /**
691
+ * `chant commit land`: from the commit job's patch to a pushed commit, or a
692
+ * reply saying why not. The request comes from the event again; the
693
+ * decision file is the commit job's and is checked against what this job
694
+ * reads itself. Every outcome but `skipped` is recorded on the ledger.
695
+ */
696
+ export async function landCommitChange(i: CommitLandInput): Promise<CommitLandOutcome> {
697
+ const s = i.settings;
698
+ const started = readCommitDecision(i.dir)?.started ?? i.now().toISOString();
699
+ const product = i.words.product;
700
+ const what = i.env.GITLAB_CI === "true" ? "merge request" : "pull request";
701
+ let pr: number | undefined;
702
+ let user: string | undefined;
703
+ let headSha: string | undefined;
704
+
705
+ const say = async (text: string): Promise<void> => {
706
+ if (pr === undefined) return;
707
+ try {
708
+ await i.forge.addComment(pr, `${product}: ${text}`);
709
+ } catch (e) {
710
+ console.error(`${product}: could not reply on #${pr}: ${errText(e)}`);
711
+ }
712
+ };
713
+ const finish = async (o: Omit<CommitLandOutcome, "code" | "requestedBy"> & { approvalVoided?: string }, reply?: string): Promise<CommitLandOutcome> => {
714
+ // A check run replies only when it pushed: a refusal there is the check's own red, already on the pull request.
715
+ if (reply && (s.on === "comment" || o.result === "pushed")) await say(reply);
716
+ const out = { result: o.result, reason: o.reason, ...(o.commit ? { commit: o.commit } : {}), ...(o.paths ? { paths: o.paths } : {}), ...(user ? { requestedBy: user } : {}) };
717
+ if (o.result === "skipped") return { ...out, code: CHANT_EXIT.done };
718
+ try {
719
+ await i.record(
720
+ commitRunRecordInput({
721
+ settings: s,
722
+ started,
723
+ ended: i.now().toISOString(),
724
+ result: o.result,
725
+ reason: o.reason,
726
+ ...(user ? { requestedBy: user } : {}),
727
+ ...(pr !== undefined ? { pr } : {}),
728
+ ...(o.commit ? { commit: o.commit } : {}),
729
+ ...(o.approvalVoided ? { approvalVoided: o.approvalVoided } : {}),
730
+ ...(headSha ? { gitSha: headSha } : {}),
731
+ ...(i.runOrigin ? { runOrigin: i.runOrigin } : {}),
732
+ }),
733
+ );
734
+ } catch (e) {
735
+ // The limit counts on the record, so one that cannot be written fails the job.
736
+ console.error(`${product}: could not record the ${s.name} run on the ledger: ${errText(e)}`);
737
+ return { ...out, code: CHANT_EXIT.failed };
738
+ }
739
+ return { ...out, code: o.result === "failed" ? CHANT_EXIT.failed : CHANT_EXIT.done };
740
+ };
741
+
742
+ // Who asked and for which pull request: from the event, never from the commit job's files.
743
+ const req = await resolveCommitRequest(i.words, s, i.env, i.event, i.forge);
744
+ if ("refused" in req) return finish({ result: s.on === "check" ? "skipped" : "refused", reason: req.refused });
745
+ ({ pr, user } = req);
746
+ const decision = readCommitDecision(i.dir);
747
+ if (!decision || decision.name !== s.name || decision.on !== s.on || (decision.pr !== undefined && decision.pr !== pr)) {
748
+ return finish({ result: "failed", reason: "the commit job left no decision this job can read" }, "the commit job left nothing to land, so nothing was pushed.");
749
+ }
750
+ if (!decision.go) return finish({ result: decision.stop ?? "refused", reason: decision.reason ?? "refused" }, `${decision.reason ?? `${s.name} did not run`}, so nothing was pushed.`);
751
+ const rc = readSmall(join(i.dir, COMMIT_RC_FILE))?.trim() ?? "";
752
+ if (rc === "conflict") {
753
+ return finish({ result: "refused", reason: `merging ${decision.base ?? "the base"} into the head conflicts` }, `merging ${code(decision.base ?? "the base")} into the ${what} conflicts, so ${s.name} did not run and nothing was pushed. Resolve the conflict on the branch.`);
754
+ }
755
+ if (rc === "timeout") return finish({ result: "stopped", reason: `the command passed its ${s.timeout} minute limit` }, `${code(s.command.join(" "))} was stopped at its ${s.timeout} minute limit, so nothing was pushed.`);
756
+ if (rc !== "0") return finish({ result: "failed", reason: `the command exited ${rc || "with no code"}` }, `${code(s.command.join(" "))} stopped with ${rc ? `exit code ${rc}` : "no exit code"}, so nothing was pushed. The commit job's log has its output.`);
757
+
758
+ const head = await i.forge.pullRequestHead?.(pr!).catch(() => undefined);
759
+ if (!head || !head.open || !head.sameRepo || !branchOk(head.branch)) return finish({ result: "refused", reason: `#${pr} is not an open ${what} from this repository` }, `#${pr} is not an open ${what} from this repository, so nothing was pushed.`);
760
+ let sha: string;
761
+ try {
762
+ sha = i.git(["rev-parse", COMMIT_HEAD_REF]).trim();
763
+ } catch (e) {
764
+ return finish({ result: "failed", reason: `could not read the head (${errText(e)})` });
765
+ }
766
+ headSha = sha;
767
+ if (sha !== head.sha || sha !== decision.sha) return finish({ result: s.on === "check" ? "skipped" : "refused", reason: "the head moved" }, `the ${what} moved while ${s.name} ran, so nothing was pushed. Ask again.`);
768
+ let baseSha: string | undefined;
769
+ if (s.mergeBase) {
770
+ const target = baseBranchOf(await i.pullRequestBase?.(pr!), i.env, i.event);
771
+ if (!target || target !== decision.base || !decision.baseSha) return finish({ result: "refused", reason: "the base branch is not the one the command ran on" }, `the branch #${pr} merges into is not the one ${s.name} merged, so nothing was pushed. Ask again.`);
772
+ try {
773
+ baseSha = fetchBase(i.git, target);
774
+ } catch (e) {
775
+ return finish({ result: "failed", reason: `could not fetch ${target} (${errText(e)})` });
776
+ }
777
+ if (baseSha !== decision.baseSha) return finish({ result: s.on === "check" ? "skipped" : "refused", reason: "the base moved" }, `${code(target)} moved while ${s.name} ran, so nothing was pushed. Ask again.`);
778
+ }
779
+
780
+ // The limit and the approval again, on this job's own read.
781
+ const earlier = (await i.readRuns().catch(() => [] as OpRunRecord[])).filter((r) => Date.parse(r.started) < Date.parse(started));
782
+ const over = overRuns(s, earlier, pr!);
783
+ if (over) return finish({ result: "stopped", reason: over }, `${over}, so nothing was pushed.`);
784
+ let approved: string | undefined;
785
+ try {
786
+ approved = await i.approval(pr!, sha);
787
+ } catch (e) {
788
+ return finish({ result: "failed", reason: `the approvals could not be read from the ledger (${errText(e)})` }, `the approvals could not be read from the ledger, so nothing was pushed.`);
789
+ }
790
+ if (approved && s.on === "check") return finish({ result: "refused", reason: `the plan of ${sha.slice(0, 8)} is approved by ${approved}, and a commit would void that approval` });
791
+
792
+ const patch = join(i.dir, COMMIT_PATCH_FILE);
793
+ const nothing = (): Promise<CommitLandOutcome> =>
794
+ finish({ result: s.on === "check" ? "skipped" : "refused", reason: "the command changed nothing" }, `${code(s.command.join(" "))} changed nothing, so nothing was pushed.`);
795
+ if (!existsSync(patch) || statSync(patch).size === 0) return nothing();
796
+ let paths: string[];
797
+ try {
798
+ i.git(["worktree", "add", "--detach", "--force", i.workDir, sha]);
799
+ // The same merge the commit job made, with no code run: the patch was taken against it.
800
+ let against = "HEAD";
801
+ if (baseSha) {
802
+ try {
803
+ i.git([...MERGE_ID, "merge", "-q", "--no-ff", "--no-commit", baseSha], { cwd: i.workDir });
804
+ } catch {
805
+ return finish({ result: "refused", reason: `merging ${decision.base} into the head conflicts` }, `merging ${code(decision.base!)} into the ${what} conflicts, so nothing was pushed.`);
806
+ }
807
+ against = i.git(["write-tree"], { cwd: i.workDir }).trim();
808
+ }
809
+ i.git(["apply", "--index", "--binary", "--whitespace=nowarn", patch], { cwd: i.workDir });
810
+ paths = i.git(["diff", "--cached", "--name-only", "--no-renames", "-z", against], { cwd: i.workDir }).split("\0").filter(Boolean);
811
+ } catch (e) {
812
+ return finish({ result: "refused", reason: `the patch does not apply to ${sha.slice(0, 8)}` }, `the change does not apply to ${sha.slice(0, 8)} (${errText(e)}), so nothing was pushed.`);
813
+ }
814
+ if (paths.length === 0) return nothing();
815
+ const { forbidden, outside } = commitRefusedPaths(paths, s);
816
+ if (forbidden.length > 0 || outside.length > 0) {
817
+ const bad = [...new Set([...forbidden, ...outside])];
818
+ return finish(
819
+ { result: "refused", reason: `the change touches ${bad.join(", ")}`, paths },
820
+ `${code(s.command.join(" "))} changed ${bad.map(code).join(", ")}, which ${s.name} may not change (it may change ${s.allowed.map(code).join(", ")}, and never CI, chant's settings and state, code owners, agent instructions or git settings), so nothing was pushed.`,
821
+ );
822
+ }
823
+
824
+ const title = s.on === "comment" ? `${s.comment} asked for by ${user} on ${what} #${pr}` : `${s.name} after the check found something at ${sha.slice(0, 8)}`;
825
+ const ran = baseSha ? `Merged ${decision.base} at ${baseSha.slice(0, 12)} into ${sha.slice(0, 12)}, then ran ${s.command.join(" ")}.` : `Ran ${s.command.join(" ")} on ${sha.slice(0, 12)}.`;
826
+ const message = [title, "", ran, "", ...(user ? [`Requested-by: ${user}`] : []), `${COMMIT_TRAILER}: ${s.name}`, ""].join("\n");
827
+ let commitSha: string;
828
+ try {
829
+ i.git([...MERGE_ID, "commit", "-q", "-F", "-"], { cwd: i.workDir, input: message });
830
+ commitSha = i.git(["rev-parse", "HEAD"], { cwd: i.workDir }).trim();
831
+ } catch (e) {
832
+ return finish({ result: "failed", reason: `could not commit (${errText(e)})` });
833
+ }
834
+ // Never a force push to a person's branch: a branch that moved keeps what it has.
835
+ try {
836
+ i.push({ cwd: i.workDir, ref: `refs/heads/${head.branch}` });
837
+ } catch (e) {
838
+ return finish({ result: "failed", reason: `could not push to ${head.branch} (${errText(e)})`, commit: commitSha }, `could not push to ${code(head.branch)} (${errText(e)}), so nothing was pushed.`);
839
+ }
840
+ const voided = approved ? ` The plan of ${code(sha.slice(0, 8))} was approved by ${approved}; the new commit is planned again and needs approval again.` : "";
841
+ return finish(
842
+ { result: "pushed", reason: `pushed ${commitSha} to ${head.branch}`, commit: commitSha, paths, ...(approved ? { approvalVoided: approved } : {}) },
843
+ `pushed ${code(commitSha.slice(0, 8))} to ${code(head.branch)}${user ? ` for ${user}` : ""}, from ${baseSha ? `a merge of ${code(decision.base!)} and ` : ""}${code(s.command.join(" "))}, changing ${paths.map(code).join(", ")}.${voided} Nothing was applied, approved or merged.`,
844
+ );
845
+ }
846
+
847
+ // ── what the generated jobs run ────────────────────────────────────────────
848
+
849
+ /** The three commands of the commit jobs, through the product's bin. */
850
+ export function commitCommandLines(forge: "github" | "gitlab" | "forgejo", bin?: string, dir: string = COMMIT_DIR): { prepare: string; run: string; land: string } {
851
+ if (!/^[A-Za-z0-9._\/-]+$/.test(dir) || dir.split("/").includes("..")) throw new AgentError(`the commit directory ${JSON.stringify(dir)} is a plain path from the repository root`);
852
+ const line = (action: string): string => {
853
+ const chant = ["chant", "commit", action, "--forge", forge, "--output", dir].join(" ");
854
+ return bin ? chant.replace(/^chant /, `${bin} `) : chant;
855
+ };
856
+ return { prepare: line("prepare"), run: line("run"), land: line("land") };
857
+ }