@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,696 @@
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
+ import { spawn } from "node:child_process";
28
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
29
+ import { join } from "node:path";
30
+ import { CHANT_EXIT } from "./exit-codes.js";
31
+ import { agentForbiddenPaths, AgentError, branchOk, errText, LOGIN, readSmall, SHA } from "./ci-agent.js";
32
+ import { parseProductComment } from "./ci-product-words.js";
33
+ import { NEXT_RELEASE } from "./release-floors.js";
34
+ /** The first chant with the commit job and the scheduled Op spec's `commit` (#4722). Products feature-detect on it. */
35
+ export const CI_COMMIT_FLOOR = NEXT_RELEASE;
36
+ export const COMMIT_TRIGGERS = ["comment", "check"];
37
+ export const COMMIT_MAX_RUNS = 3;
38
+ export const COMMIT_TIMEOUT_MINUTES = 10;
39
+ /** The GitLab variable the push job reads its token from unless `tokenEnv` names another. */
40
+ export const COMMIT_GITLAB_TOKEN_ENV = "CHANT_FORGE_TOKEN";
41
+ /** The trailer each of the job's commits carries, naming the job. The loop guard reads it. */
42
+ export const COMMIT_TRAILER = "Commit-run";
43
+ /** The variables the generated jobs carry the settings in. The workflow file is the base branch's, so they are not the change's. */
44
+ export const COMMIT_ENV = {
45
+ name: "CHANT_COMMIT_NAME",
46
+ on: "CHANT_COMMIT_ON",
47
+ comment: "CHANT_COMMIT_COMMENT",
48
+ command: "CHANT_COMMIT_COMMAND",
49
+ allowed: "CHANT_COMMIT_ALLOWED",
50
+ findings: "CHANT_COMMIT_FINDINGS",
51
+ maxRuns: "CHANT_COMMIT_MAX_RUNS",
52
+ guarded: "CHANT_COMMIT_GUARDED",
53
+ timeout: "CHANT_COMMIT_TIMEOUT",
54
+ env: "CHANT_COMMIT_ENV",
55
+ mergeBase: "CHANT_COMMIT_MERGE_BASE",
56
+ };
57
+ /** GitLab starts no pipeline on a note: a pipeline of the default branch started with these runs a comment commit job. */
58
+ export const GITLAB_COMMIT_PR_VAR = "CHANT_COMMIT_PR";
59
+ export const GITLAB_COMMIT_WORD_VAR = "CHANT_COMMIT";
60
+ /** Where the jobs keep the decision, the exit code and the patch, from the job's directory. */
61
+ export const COMMIT_DIR = ".chant/commit";
62
+ /** The local ref the checkout fetches a pull request's head into. */
63
+ export const COMMIT_HEAD_REF = "refs/chant/commit-head";
64
+ /** The local ref the jobs fetch the base branch's tip into, with `mergeBase`. */
65
+ export const COMMIT_BASE_REF = "refs/chant/commit-base";
66
+ export const COMMIT_DECISION_FILE = "decision.json";
67
+ export const COMMIT_PATCH_FILE = "change.patch";
68
+ export const COMMIT_RC_FILE = "rc";
69
+ /** The commit identity the job's commits carry. */
70
+ export const COMMIT_GIT_NAME = "chant commit";
71
+ export const COMMIT_GIT_EMAIL = "chant-commit@localhost";
72
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/;
73
+ const VAR = /^[A-Za-z_][A-Za-z0-9_]*$/;
74
+ /** An argv word as the job may carry it: no control characters, and the first one names a program, not a flag. */
75
+ const ARG = /^[^\u0000-\u001f\u007f]{1,500}$/;
76
+ function intIn(where, v, lo, hi) {
77
+ if (typeof v !== "number" || !Number.isInteger(v) || v < lo || v > hi)
78
+ throw new AgentError(`${where} is a whole number from ${lo} to ${hi}`);
79
+ return v;
80
+ }
81
+ function pathsIn(where, v) {
82
+ if (!Array.isArray(v) || !v.every((p) => typeof p === "string" && p !== "" && !p.startsWith("/") && !p.split("/").some((s) => s === ".."))) {
83
+ throw new AgentError(`${where} is a list of paths from the repository root`);
84
+ }
85
+ return v.map((p) => p.replace(/^\.\//, ""));
86
+ }
87
+ /** The settings of commit job `name` from a spec's `commit`, checked. */
88
+ export function resolveCommitSpec(name, spec, product = "chant") {
89
+ const where = `Scheduled Op "${name}" commit`;
90
+ if (!NAME.test(name))
91
+ throw new AgentError(`${where}: the name is letters, digits, '.', '_' and '-'`);
92
+ if (!COMMIT_TRIGGERS.includes(spec.on))
93
+ throw new AgentError(`${where}: on is "comment" or "check"`);
94
+ if (spec.on === "comment" && !(typeof spec.comment === "string" && /^\/[a-z][a-z0-9-]* [a-z][a-z0-9-]*$/.test(spec.comment))) {
95
+ throw new AgentError(`${where}: on "comment" needs comment, the line it answers, such as "/${product} fmt"`);
96
+ }
97
+ if (!Array.isArray(spec.command) || spec.command.length === 0 || !spec.command.every((a) => typeof a === "string" && ARG.test(a)) || spec.command[0].startsWith("-")) {
98
+ throw new AgentError(`${where}: command is an argv, a program and its arguments, with no control characters`);
99
+ }
100
+ const allowed = pathsIn(`${where}: allowed`, spec.allowed);
101
+ if (allowed.length === 0)
102
+ throw new AgentError(`${where}: allowed names at least one path the change may touch`);
103
+ const guarded = spec.guarded === undefined ? [] : pathsIn(`${where}: guarded`, spec.guarded);
104
+ if (spec.tokenEnv !== undefined && !VAR.test(spec.tokenEnv))
105
+ throw new AgentError(`${where}: tokenEnv is a variable name`);
106
+ const findings = spec.findings ?? [CHANT_EXIT.drift];
107
+ if (!Array.isArray(findings) || findings.length === 0)
108
+ throw new AgentError(`${where}: findings lists at least one exit code`);
109
+ for (const f of findings)
110
+ intIn(`${where}: findings`, f, 1, 255);
111
+ const env = spec.env ?? "local";
112
+ if (!NAME.test(env))
113
+ throw new AgentError(`${where}: env is a ledger environment name`);
114
+ return {
115
+ name,
116
+ on: spec.on,
117
+ ...(spec.on === "comment" ? { comment: spec.comment } : {}),
118
+ command: [...spec.command],
119
+ allowed,
120
+ findings: [...findings],
121
+ maxRuns: spec.maxRuns === undefined ? COMMIT_MAX_RUNS : intIn(`${where}: maxRuns`, spec.maxRuns, 1, 100),
122
+ guarded,
123
+ timeout: spec.timeout === undefined ? COMMIT_TIMEOUT_MINUTES : intIn(`${where}: timeout`, spec.timeout, 1, 120),
124
+ env,
125
+ mergeBase: spec.mergeBase === true,
126
+ };
127
+ }
128
+ /** The settings as the generated jobs' variables. */
129
+ export function commitSettingsEnv(s) {
130
+ return {
131
+ [COMMIT_ENV.name]: s.name,
132
+ [COMMIT_ENV.on]: s.on,
133
+ ...(s.comment ? { [COMMIT_ENV.comment]: s.comment } : {}),
134
+ [COMMIT_ENV.command]: JSON.stringify(s.command),
135
+ [COMMIT_ENV.allowed]: JSON.stringify(s.allowed),
136
+ [COMMIT_ENV.findings]: s.findings.join(","),
137
+ [COMMIT_ENV.maxRuns]: String(s.maxRuns),
138
+ ...(s.guarded.length > 0 ? { [COMMIT_ENV.guarded]: JSON.stringify(s.guarded) } : {}),
139
+ [COMMIT_ENV.timeout]: String(s.timeout),
140
+ [COMMIT_ENV.env]: s.env,
141
+ ...(s.mergeBase ? { [COMMIT_ENV.mergeBase]: "1" } : {}),
142
+ };
143
+ }
144
+ /** The settings back from the job's variables, checked as {@link resolveCommitSpec} checks a spec. */
145
+ export function commitSettingsFromEnv(env, product = "chant") {
146
+ const name = env[COMMIT_ENV.name];
147
+ if (!name)
148
+ throw new AgentError(`${COMMIT_ENV.name} is not set: run this in a job the Op generator wrote`);
149
+ const list = (k) => {
150
+ const v = env[k];
151
+ if (v === undefined || v === "")
152
+ return undefined;
153
+ try {
154
+ const parsed = JSON.parse(v);
155
+ if (!Array.isArray(parsed) || !parsed.every((p) => typeof p === "string"))
156
+ throw new Error("not a list of strings");
157
+ return parsed;
158
+ }
159
+ catch (e) {
160
+ throw new AgentError(`${k} is a JSON list of strings (${e.message})`);
161
+ }
162
+ };
163
+ const num = (k) => {
164
+ const v = env[k];
165
+ if (v === undefined || v === "")
166
+ return undefined;
167
+ if (!/^[0-9]+$/.test(v))
168
+ throw new AgentError(`${k} is a whole number: got ${JSON.stringify(v)}`);
169
+ return Number(v);
170
+ };
171
+ const f = env[COMMIT_ENV.findings];
172
+ if (f !== undefined && f !== "" && !/^[0-9]+(,[0-9]+)*$/.test(f))
173
+ throw new AgentError(`${COMMIT_ENV.findings} is exit codes separated by commas: got ${JSON.stringify(f)}`);
174
+ const maxRuns = num(COMMIT_ENV.maxRuns);
175
+ const timeout = num(COMMIT_ENV.timeout);
176
+ const guarded = list(COMMIT_ENV.guarded);
177
+ const spec = {
178
+ on: env[COMMIT_ENV.on],
179
+ ...(env[COMMIT_ENV.comment] ? { comment: env[COMMIT_ENV.comment] } : {}),
180
+ command: list(COMMIT_ENV.command) ?? [],
181
+ allowed: list(COMMIT_ENV.allowed) ?? [],
182
+ ...(f ? { findings: f.split(",").map(Number) } : {}),
183
+ ...(maxRuns !== undefined ? { maxRuns } : {}),
184
+ ...(timeout !== undefined ? { timeout } : {}),
185
+ ...(guarded ? { guarded } : {}),
186
+ ...(env[COMMIT_ENV.env] ? { env: env[COMMIT_ENV.env] } : {}),
187
+ ...(env[COMMIT_ENV.mergeBase] === "1" ? { mergeBase: true } : {}),
188
+ };
189
+ return resolveCommitSpec(name, spec, product);
190
+ }
191
+ // ── what the change may touch ──────────────────────────────────────────────
192
+ /** Whether `path` is inside one of `allowed` (a trailing `/` names a directory), matched as git spells it. */
193
+ function inAllowed(path, allowed) {
194
+ return allowed.some((a) => (a.endsWith("/") ? path.startsWith(a) || `${path}/` === a : path === a));
195
+ }
196
+ /** The paths of a change the job may not push: outside `allowed`, or on a path no job changes ({@link agentForbiddenPaths}). */
197
+ export function commitRefusedPaths(paths, s) {
198
+ return { forbidden: agentForbiddenPaths(paths, s.guarded), outside: paths.filter((p) => !inAllowed(p, s.allowed)) };
199
+ }
200
+ /**
201
+ * The request from the run. `comment`: the event's comment on GitHub and
202
+ * Forgejo, read against the product's grammar, which must name this job's
203
+ * word; on GitLab the pipeline's {@link GITLAB_COMMIT_PR_VAR} and
204
+ * {@link GITLAB_COMMIT_WORD_VAR}, and the user who started it. `check`: the
205
+ * pull request the check ran for, from the `pull_request` event or the
206
+ * merge request pipeline.
207
+ */
208
+ export function commitRequestFromRun(words, s, env, event) {
209
+ const gitlab = env.GITLAB_CI === "true";
210
+ let pr;
211
+ if (s.on === "check") {
212
+ pr = gitlab ? (env.CI_MERGE_REQUEST_IID ? Number(env.CI_MERGE_REQUEST_IID) : openMergeRequestOf(env)) : event?.pull_request?.number;
213
+ if (typeof pr !== "number" || !Number.isInteger(pr) || pr < 1)
214
+ return { refused: "the run names no pull request" };
215
+ return { pr };
216
+ }
217
+ let body;
218
+ let user;
219
+ const word = s.comment?.split(" ")[1];
220
+ if (gitlab) {
221
+ pr = Number(env[GITLAB_COMMIT_PR_VAR]);
222
+ body = env[GITLAB_COMMIT_WORD_VAR] === word ? s.comment : `/${words.product} ${env[GITLAB_COMMIT_WORD_VAR] ?? ""}`;
223
+ user = env.GITLAB_USER_LOGIN;
224
+ }
225
+ else {
226
+ const e = event;
227
+ body = e?.comment?.body;
228
+ pr = e?.issue?.number;
229
+ user = e?.comment?.user?.login;
230
+ }
231
+ if (typeof pr !== "number" || !Number.isInteger(pr) || pr < 1)
232
+ return { refused: "the run names no pull request" };
233
+ if (typeof user !== "string" || !LOGIN.test(user))
234
+ return { refused: "the run names nobody who asked" };
235
+ const parsed = parseProductComment(words, body, env);
236
+ if (parsed?.kind === "refused")
237
+ return { refused: parsed.reason };
238
+ if (parsed?.kind !== "commit" || parsed.word !== word)
239
+ return { refused: `the comment is not ${s.comment}` };
240
+ return { pr, user };
241
+ }
242
+ /**
243
+ * GitLab, a branch pipeline (a check that runs on push): the merge request
244
+ * of this project whose source is the branch, from `CI_OPEN_MERGE_REQUESTS`
245
+ * (`group/project!12,other/fork!3`), which GitLab sets with no token. The
246
+ * first of this project's when there are several; undefined when none.
247
+ */
248
+ function openMergeRequestOf(env) {
249
+ const project = env.CI_PROJECT_PATH;
250
+ if (!project)
251
+ return undefined;
252
+ for (const ref of (env.CI_OPEN_MERGE_REQUESTS ?? "").split(",")) {
253
+ const at = ref.trim().lastIndexOf("!");
254
+ if (at > 0 && ref.trim().slice(0, at) === project) {
255
+ const n = Number(ref.trim().slice(at + 1));
256
+ if (Number.isInteger(n) && n > 0)
257
+ return n;
258
+ }
259
+ }
260
+ return undefined;
261
+ }
262
+ /** The branch a push run is for, on GitHub and Forgejo: `refs/heads/<branch>` from `GITHUB_REF` on a `push` event. */
263
+ function pushedBranch(env) {
264
+ if (env.GITHUB_EVENT_NAME !== "push")
265
+ return undefined;
266
+ const ref = env.GITHUB_REF ?? "";
267
+ return ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : undefined;
268
+ }
269
+ /**
270
+ * {@link commitRequestFromRun}, and for the `check` trigger of a check that
271
+ * runs on push (as terragucci's does), the open pull request whose head is
272
+ * the pushed branch, asked of the forge on GitHub and Forgejo. A branch with
273
+ * no open pull request is refused as before, which the check trigger skips.
274
+ */
275
+ export async function resolveCommitRequest(words, s, env, event, forge) {
276
+ const req = commitRequestFromRun(words, s, env, event);
277
+ if (!("refused" in req) || s.on !== "check" || env.GITLAB_CI === "true" || !forge?.findPullRequest)
278
+ return req;
279
+ const branch = pushedBranch(env);
280
+ if (!branch)
281
+ return req;
282
+ const found = await forge.findPullRequest(branch);
283
+ return found && found.number > 0 ? { pr: found.number } : { refused: `${branch} has no open pull request` };
284
+ }
285
+ export function readCommitDecision(dir) {
286
+ try {
287
+ const d = JSON.parse(readFileSync(join(dir, COMMIT_DECISION_FILE), "utf8"));
288
+ if (d.version !== 1 || typeof d.name !== "string" || !COMMIT_TRIGGERS.includes(d.on) || typeof d.go !== "boolean" || typeof d.started !== "string")
289
+ return undefined;
290
+ if (d.sha !== undefined && !SHA.test(d.sha))
291
+ return undefined;
292
+ if (d.pr !== undefined && !(Number.isInteger(d.pr) && d.pr > 0))
293
+ return undefined;
294
+ if (d.branch !== undefined && !branchOk(d.branch))
295
+ return undefined;
296
+ if (d.base !== undefined && !branchOk(d.base))
297
+ return undefined;
298
+ if (d.baseSha !== undefined && !SHA.test(d.baseSha))
299
+ return undefined;
300
+ return d;
301
+ }
302
+ catch {
303
+ return undefined;
304
+ }
305
+ }
306
+ // ── the ledger ─────────────────────────────────────────────────────────────
307
+ /** The commits the job pushed to pull request `pr`, from its run records. */
308
+ export function pushedTo(records, pr) {
309
+ return records.filter((r) => {
310
+ const c = r.outcomes?.commit;
311
+ return c?.pr === pr && c.result === "pushed";
312
+ }).length;
313
+ }
314
+ function overRuns(s, records, pr) {
315
+ const n = pushedTo(records, pr);
316
+ return n >= s.maxRuns ? `${s.name} pushed ${n} commit${n === 1 ? "" : "s"} to #${pr}, and its limit is ${s.maxRuns}` : undefined;
317
+ }
318
+ /** Whether the head's own last commit is this job's: the loop guard of the `check` trigger. */
319
+ function ownCommit(git, sha, name) {
320
+ try {
321
+ const values = git(["log", "-1", `--format=%(trailers:key=${COMMIT_TRAILER},valueonly)`, sha]).split("\n").map((v) => v.trim());
322
+ return values.includes(name);
323
+ }
324
+ catch {
325
+ return false;
326
+ }
327
+ }
328
+ /** The run record of one commit run: op `<name>`, one phase with one step, the outcome in `outcomes.commit`. */
329
+ export function commitRunRecordInput(o) {
330
+ const ok = o.result === "pushed";
331
+ const durationMs = Math.max(0, Date.parse(o.ended) - Date.parse(o.started)) || 0;
332
+ const status = ok ? "ok" : o.result === "failed" ? "fail" : "skipped";
333
+ return {
334
+ op: o.settings.name,
335
+ env: o.settings.env,
336
+ started: o.started,
337
+ ended: o.ended,
338
+ status: o.result === "failed" ? "fail" : "ok",
339
+ labels: { Commit: o.settings.on },
340
+ outcomes: {
341
+ commit: {
342
+ trigger: o.settings.on,
343
+ result: o.result,
344
+ reason: o.reason,
345
+ ...(o.requestedBy ? { requestedBy: o.requestedBy } : {}),
346
+ ...(o.pr !== undefined ? { pr: o.pr } : {}),
347
+ ...(o.commit ? { commit: o.commit } : {}),
348
+ ...(o.approvalVoided ? { approvalVoided: o.approvalVoided } : {}),
349
+ },
350
+ },
351
+ phases: [{ name: "commit", status, steps: [{ fn: `commit:${o.settings.on}`, status, durationMs, ...(o.result === "failed" ? { error: o.reason } : {}) }] }],
352
+ ...(o.gitSha ? { gitSha: o.gitSha } : {}),
353
+ ...(o.runOrigin ? { runOrigin: o.runOrigin } : {}),
354
+ };
355
+ }
356
+ // ── the base merge (#4723) ─────────────────────────────────────────────────
357
+ /**
358
+ * The branch the pull request merges into: the forge's answer, else the
359
+ * run's own (the `pull_request` event's base, GitLab's target branch).
360
+ */
361
+ function baseBranchOf(asked, env, event) {
362
+ const fromEvent = event?.pull_request?.base?.ref;
363
+ const b = asked ?? (typeof fromEvent === "string" ? fromEvent : undefined) ?? (env.GITLAB_CI === "true" ? env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME : undefined);
364
+ return b && branchOk(b) ? b : undefined;
365
+ }
366
+ /** Fetch the base branch's tip into {@link COMMIT_BASE_REF} and return it. */
367
+ function fetchBase(git, base) {
368
+ git(["fetch", "-q", "--no-tags", "origin", `+refs/heads/${base}:${COMMIT_BASE_REF}`]);
369
+ return git(["rev-parse", COMMIT_BASE_REF]).trim();
370
+ }
371
+ /** The identity the base merge is made under; the job's commit carries it too. */
372
+ const MERGE_ID = ["-c", `user.name=${COMMIT_GIT_NAME}`, "-c", `user.email=${COMMIT_GIT_EMAIL}`, "-c", "commit.gpgsign=false"];
373
+ /**
374
+ * `chant commit prepare`: decide whether the command runs, and on what. Every
375
+ * outcome is a decision file; the push job answers a refusal. The return is
376
+ * the decision.
377
+ */
378
+ export async function prepareCommitRun(i) {
379
+ const s = i.settings;
380
+ const base = { version: 1, name: s.name, on: s.on, started: i.now.toISOString() };
381
+ const write = (d) => {
382
+ mkdirSync(i.dir, { recursive: true });
383
+ writeFileSync(join(i.dir, COMMIT_DECISION_FILE), JSON.stringify(d, null, 2) + "\n");
384
+ return d;
385
+ };
386
+ const no = (reason, stop, extra = {}) => write({ ...base, go: false, reason, stop, ...extra });
387
+ const req = await resolveCommitRequest(i.words, s, i.env, i.event, i.forge);
388
+ if ("refused" in req)
389
+ return no(req.refused, s.on === "check" ? "skipped" : "refused");
390
+ const who = { pr: req.pr, ...(req.user ? { user: req.user } : {}) };
391
+ if (req.user && i.forge?.userCanWrite && !(await i.forge.userCanWrite(req.user)))
392
+ return no(`${req.user} cannot write to the repository, so ${s.name} does not run for them`, "refused", who);
393
+ let sha;
394
+ try {
395
+ sha = i.git(["rev-parse", COMMIT_HEAD_REF]).trim();
396
+ }
397
+ catch (e) {
398
+ return no(`the pull request's head was not fetched (${errText(e)})`, "refused", who);
399
+ }
400
+ if (!SHA.test(sha))
401
+ return no("the pull request's head was not fetched", "refused", who);
402
+ let branch;
403
+ if (i.forge?.pullRequestHead) {
404
+ const head = await i.forge.pullRequestHead(req.pr);
405
+ if (!head)
406
+ return no(`pull request #${req.pr} could not be read`, "refused", who);
407
+ if (!head.open)
408
+ return no(`pull request #${req.pr} is not open`, "refused", who);
409
+ if (!head.sameRepo)
410
+ return no(`pull request #${req.pr} comes from a fork, and ${s.name} pushes only to this repository's branches`, "refused", who);
411
+ if (!branchOk(head.branch))
412
+ return no(`pull request #${req.pr}'s branch is not one ${s.name} pushes to`, "refused", who);
413
+ if (sha !== head.sha)
414
+ return no(`pull request #${req.pr} moved while ${s.name} was starting`, s.on === "check" ? "skipped" : "refused", who);
415
+ branch = head.branch;
416
+ }
417
+ // The loop guard: a check that fails on the job's own commit does not start it again.
418
+ if (s.on === "check" && ownCommit(i.git, sha, s.name))
419
+ return no(`the head is ${s.name}'s own commit`, "skipped", { ...who, sha });
420
+ let records;
421
+ try {
422
+ records = await i.readRuns();
423
+ }
424
+ catch (e) {
425
+ return no(`${s.name}'s runs could not be read from the ledger (${errText(e)}), so its limit cannot be checked`, "refused", who);
426
+ }
427
+ const over = overRuns(s, records, req.pr);
428
+ if (over)
429
+ return no(over, "stopped", who);
430
+ if (s.on === "check") {
431
+ let approved;
432
+ try {
433
+ approved = await i.approval(req.pr, sha);
434
+ }
435
+ catch (e) {
436
+ return no(`the approvals could not be read from the ledger (${errText(e)})`, "refused", who);
437
+ }
438
+ if (approved)
439
+ return no(`the plan of ${sha.slice(0, 8)} is approved by ${approved}, and a commit would void that approval`, "refused", { ...who, sha });
440
+ }
441
+ let merge;
442
+ if (s.mergeBase) {
443
+ const target = baseBranchOf(await i.pullRequestBase?.(req.pr), i.env, i.event);
444
+ if (!target)
445
+ return no(`the branch #${req.pr} merges into is not known, so ${s.name} cannot merge it first`, "refused", who);
446
+ try {
447
+ merge = { base: target, baseSha: fetchBase(i.git, target) };
448
+ }
449
+ catch (e) {
450
+ return no(`${target} could not be fetched (${errText(e)})`, "refused", who);
451
+ }
452
+ }
453
+ return write({ ...base, go: true, sha, ...who, ...(branch ? { branch } : {}), ...(merge ?? {}) });
454
+ }
455
+ export const runCommitArgv = (argv, o) => new Promise((done) => {
456
+ let timedOut = false;
457
+ const child = spawn(argv[0], argv.slice(1), { cwd: o.cwd, env: o.env, stdio: ["ignore", "inherit", "inherit"] });
458
+ const timer = setTimeout(() => {
459
+ timedOut = true;
460
+ child.kill("SIGTERM");
461
+ setTimeout(() => child.kill("SIGKILL"), 10000).unref();
462
+ }, o.timeoutMs);
463
+ child.on("error", () => {
464
+ clearTimeout(timer);
465
+ done({ exitCode: null, timedOut });
466
+ });
467
+ child.on("close", (code) => {
468
+ clearTimeout(timer);
469
+ done({ exitCode: code, timedOut });
470
+ });
471
+ });
472
+ /**
473
+ * The variables the command sees: process basics, with the checkout's
474
+ * `node_modules/.bin` first on `PATH` so a product's bin installed on the
475
+ * target branch runs on the head's files. Never a forge or cloud token.
476
+ */
477
+ export function commitCommandEnv(env, checkout) {
478
+ const out = {};
479
+ for (const name of ["PATH", "HOME", "TMPDIR", "LANG", "LC_ALL", "TERM", "SystemRoot", "npm_config_cache"]) {
480
+ const v = env[name];
481
+ if (v !== undefined)
482
+ out[name] = v;
483
+ }
484
+ const bin = join(checkout, "node_modules", ".bin");
485
+ if (existsSync(bin))
486
+ out.PATH = out.PATH ? `${bin}:${out.PATH}` : bin;
487
+ return out;
488
+ }
489
+ /** `chant commit run`: the command in a worktree of the head; what it changed leaves as a patch. This step holds no forge token. */
490
+ export async function runCommit(i) {
491
+ const rcFile = join(i.dir, COMMIT_RC_FILE);
492
+ const decision = readCommitDecision(i.dir);
493
+ if (!decision || !decision.go || !decision.sha) {
494
+ writeFileSync(rcFile, "refused\n");
495
+ return { rc: "refused", changed: false };
496
+ }
497
+ i.git(["worktree", "add", "--detach", "--force", i.workDir, decision.sha]);
498
+ if (i.settings.mergeBase) {
499
+ if (!decision.baseSha) {
500
+ writeFileSync(rcFile, "refused\n");
501
+ return { rc: "refused", changed: false };
502
+ }
503
+ try {
504
+ i.git([...MERGE_ID, "merge", "-q", "--no-ff", "--no-edit", decision.baseSha], { cwd: i.workDir });
505
+ }
506
+ catch {
507
+ writeFileSync(rcFile, "conflict\n");
508
+ writeFileSync(join(i.dir, COMMIT_PATCH_FILE), "");
509
+ return { rc: "conflict", changed: false };
510
+ }
511
+ }
512
+ const out = await i.runCommand(i.settings.command, { cwd: i.workDir, env: commitCommandEnv(i.env, i.checkout), timeoutMs: i.settings.timeout * 60000 });
513
+ const rc = out.timedOut ? "timeout" : out.exitCode === null ? "no-exit" : String(out.exitCode);
514
+ writeFileSync(rcFile, `${rc}\n`);
515
+ i.git(["add", "-A"], { cwd: i.workDir });
516
+ const patch = i.git(["diff", "--cached", "--binary", "--no-renames", "HEAD"], { cwd: i.workDir });
517
+ writeFileSync(join(i.dir, COMMIT_PATCH_FILE), patch);
518
+ return { rc, changed: patch.length > 0 };
519
+ }
520
+ const code = (s) => "`" + s.replaceAll("`", "'") + "`";
521
+ /**
522
+ * `chant commit land`: from the commit job's patch to a pushed commit, or a
523
+ * reply saying why not. The request comes from the event again; the
524
+ * decision file is the commit job's and is checked against what this job
525
+ * reads itself. Every outcome but `skipped` is recorded on the ledger.
526
+ */
527
+ export async function landCommitChange(i) {
528
+ const s = i.settings;
529
+ const started = readCommitDecision(i.dir)?.started ?? i.now().toISOString();
530
+ const product = i.words.product;
531
+ const what = i.env.GITLAB_CI === "true" ? "merge request" : "pull request";
532
+ let pr;
533
+ let user;
534
+ let headSha;
535
+ const say = async (text) => {
536
+ if (pr === undefined)
537
+ return;
538
+ try {
539
+ await i.forge.addComment(pr, `${product}: ${text}`);
540
+ }
541
+ catch (e) {
542
+ console.error(`${product}: could not reply on #${pr}: ${errText(e)}`);
543
+ }
544
+ };
545
+ const finish = async (o, reply) => {
546
+ // A check run replies only when it pushed: a refusal there is the check's own red, already on the pull request.
547
+ if (reply && (s.on === "comment" || o.result === "pushed"))
548
+ await say(reply);
549
+ const out = { result: o.result, reason: o.reason, ...(o.commit ? { commit: o.commit } : {}), ...(o.paths ? { paths: o.paths } : {}), ...(user ? { requestedBy: user } : {}) };
550
+ if (o.result === "skipped")
551
+ return { ...out, code: CHANT_EXIT.done };
552
+ try {
553
+ await i.record(commitRunRecordInput({
554
+ settings: s,
555
+ started,
556
+ ended: i.now().toISOString(),
557
+ result: o.result,
558
+ reason: o.reason,
559
+ ...(user ? { requestedBy: user } : {}),
560
+ ...(pr !== undefined ? { pr } : {}),
561
+ ...(o.commit ? { commit: o.commit } : {}),
562
+ ...(o.approvalVoided ? { approvalVoided: o.approvalVoided } : {}),
563
+ ...(headSha ? { gitSha: headSha } : {}),
564
+ ...(i.runOrigin ? { runOrigin: i.runOrigin } : {}),
565
+ }));
566
+ }
567
+ catch (e) {
568
+ // The limit counts on the record, so one that cannot be written fails the job.
569
+ console.error(`${product}: could not record the ${s.name} run on the ledger: ${errText(e)}`);
570
+ return { ...out, code: CHANT_EXIT.failed };
571
+ }
572
+ return { ...out, code: o.result === "failed" ? CHANT_EXIT.failed : CHANT_EXIT.done };
573
+ };
574
+ // Who asked and for which pull request: from the event, never from the commit job's files.
575
+ const req = await resolveCommitRequest(i.words, s, i.env, i.event, i.forge);
576
+ if ("refused" in req)
577
+ return finish({ result: s.on === "check" ? "skipped" : "refused", reason: req.refused });
578
+ ({ pr, user } = req);
579
+ const decision = readCommitDecision(i.dir);
580
+ if (!decision || decision.name !== s.name || decision.on !== s.on || (decision.pr !== undefined && decision.pr !== pr)) {
581
+ 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.");
582
+ }
583
+ if (!decision.go)
584
+ return finish({ result: decision.stop ?? "refused", reason: decision.reason ?? "refused" }, `${decision.reason ?? `${s.name} did not run`}, so nothing was pushed.`);
585
+ const rc = readSmall(join(i.dir, COMMIT_RC_FILE))?.trim() ?? "";
586
+ if (rc === "conflict") {
587
+ 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.`);
588
+ }
589
+ if (rc === "timeout")
590
+ 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.`);
591
+ if (rc !== "0")
592
+ 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.`);
593
+ const head = await i.forge.pullRequestHead?.(pr).catch(() => undefined);
594
+ if (!head || !head.open || !head.sameRepo || !branchOk(head.branch))
595
+ 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.`);
596
+ let sha;
597
+ try {
598
+ sha = i.git(["rev-parse", COMMIT_HEAD_REF]).trim();
599
+ }
600
+ catch (e) {
601
+ return finish({ result: "failed", reason: `could not read the head (${errText(e)})` });
602
+ }
603
+ headSha = sha;
604
+ if (sha !== head.sha || sha !== decision.sha)
605
+ 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.`);
606
+ let baseSha;
607
+ if (s.mergeBase) {
608
+ const target = baseBranchOf(await i.pullRequestBase?.(pr), i.env, i.event);
609
+ if (!target || target !== decision.base || !decision.baseSha)
610
+ 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.`);
611
+ try {
612
+ baseSha = fetchBase(i.git, target);
613
+ }
614
+ catch (e) {
615
+ return finish({ result: "failed", reason: `could not fetch ${target} (${errText(e)})` });
616
+ }
617
+ if (baseSha !== decision.baseSha)
618
+ 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.`);
619
+ }
620
+ // The limit and the approval again, on this job's own read.
621
+ const earlier = (await i.readRuns().catch(() => [])).filter((r) => Date.parse(r.started) < Date.parse(started));
622
+ const over = overRuns(s, earlier, pr);
623
+ if (over)
624
+ return finish({ result: "stopped", reason: over }, `${over}, so nothing was pushed.`);
625
+ let approved;
626
+ try {
627
+ approved = await i.approval(pr, sha);
628
+ }
629
+ catch (e) {
630
+ 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.`);
631
+ }
632
+ if (approved && s.on === "check")
633
+ return finish({ result: "refused", reason: `the plan of ${sha.slice(0, 8)} is approved by ${approved}, and a commit would void that approval` });
634
+ const patch = join(i.dir, COMMIT_PATCH_FILE);
635
+ const nothing = () => finish({ result: s.on === "check" ? "skipped" : "refused", reason: "the command changed nothing" }, `${code(s.command.join(" "))} changed nothing, so nothing was pushed.`);
636
+ if (!existsSync(patch) || statSync(patch).size === 0)
637
+ return nothing();
638
+ let paths;
639
+ try {
640
+ i.git(["worktree", "add", "--detach", "--force", i.workDir, sha]);
641
+ // The same merge the commit job made, with no code run: the patch was taken against it.
642
+ let against = "HEAD";
643
+ if (baseSha) {
644
+ try {
645
+ i.git([...MERGE_ID, "merge", "-q", "--no-ff", "--no-commit", baseSha], { cwd: i.workDir });
646
+ }
647
+ catch {
648
+ return finish({ result: "refused", reason: `merging ${decision.base} into the head conflicts` }, `merging ${code(decision.base)} into the ${what} conflicts, so nothing was pushed.`);
649
+ }
650
+ against = i.git(["write-tree"], { cwd: i.workDir }).trim();
651
+ }
652
+ i.git(["apply", "--index", "--binary", "--whitespace=nowarn", patch], { cwd: i.workDir });
653
+ paths = i.git(["diff", "--cached", "--name-only", "--no-renames", "-z", against], { cwd: i.workDir }).split("\0").filter(Boolean);
654
+ }
655
+ catch (e) {
656
+ 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.`);
657
+ }
658
+ if (paths.length === 0)
659
+ return nothing();
660
+ const { forbidden, outside } = commitRefusedPaths(paths, s);
661
+ if (forbidden.length > 0 || outside.length > 0) {
662
+ const bad = [...new Set([...forbidden, ...outside])];
663
+ return finish({ result: "refused", reason: `the change touches ${bad.join(", ")}`, paths }, `${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.`);
664
+ }
665
+ 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)}`;
666
+ 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)}.`;
667
+ const message = [title, "", ran, "", ...(user ? [`Requested-by: ${user}`] : []), `${COMMIT_TRAILER}: ${s.name}`, ""].join("\n");
668
+ let commitSha;
669
+ try {
670
+ i.git([...MERGE_ID, "commit", "-q", "-F", "-"], { cwd: i.workDir, input: message });
671
+ commitSha = i.git(["rev-parse", "HEAD"], { cwd: i.workDir }).trim();
672
+ }
673
+ catch (e) {
674
+ return finish({ result: "failed", reason: `could not commit (${errText(e)})` });
675
+ }
676
+ // Never a force push to a person's branch: a branch that moved keeps what it has.
677
+ try {
678
+ i.push({ cwd: i.workDir, ref: `refs/heads/${head.branch}` });
679
+ }
680
+ catch (e) {
681
+ 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.`);
682
+ }
683
+ 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.` : "";
684
+ return finish({ result: "pushed", reason: `pushed ${commitSha} to ${head.branch}`, commit: commitSha, paths, ...(approved ? { approvalVoided: approved } : {}) }, `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.`);
685
+ }
686
+ // ── what the generated jobs run ────────────────────────────────────────────
687
+ /** The three commands of the commit jobs, through the product's bin. */
688
+ export function commitCommandLines(forge, bin, dir = COMMIT_DIR) {
689
+ if (!/^[A-Za-z0-9._\/-]+$/.test(dir) || dir.split("/").includes(".."))
690
+ throw new AgentError(`the commit directory ${JSON.stringify(dir)} is a plain path from the repository root`);
691
+ const line = (action) => {
692
+ const chant = ["chant", "commit", action, "--forge", forge, "--output", dir].join(" ");
693
+ return bin ? chant.replace(/^chant /, `${bin} `) : chant;
694
+ };
695
+ return { prepare: line("prepare"), run: line("run"), land: line("land") };
696
+ }