@intentius/chant 0.124.76 → 0.124.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/dist/__fixtures__/agent-guard/plywood.d.ts +8 -0
  2. package/dist/__fixtures__/agent-guard/plywood.d.ts.map +1 -0
  3. package/dist/__fixtures__/agent-guard/plywood.js +19 -0
  4. package/dist/__fixtures__/agent-guard/terragucci.d.ts +8 -0
  5. package/dist/__fixtures__/agent-guard/terragucci.d.ts.map +1 -0
  6. package/dist/__fixtures__/agent-guard/terragucci.js +30 -0
  7. package/dist/__fixtures__/gated-ledger.d.ts +10 -0
  8. package/dist/__fixtures__/gated-ledger.d.ts.map +1 -0
  9. package/dist/__fixtures__/gated-ledger.js +51 -0
  10. package/dist/__fixtures__/notify-messages/events.d.ts +9 -0
  11. package/dist/__fixtures__/notify-messages/events.d.ts.map +1 -0
  12. package/dist/__fixtures__/notify-messages/events.js +21 -0
  13. package/dist/__fixtures__/product-words.d.ts +14 -0
  14. package/dist/__fixtures__/product-words.d.ts.map +1 -1
  15. package/dist/__fixtures__/product-words.js +11 -0
  16. package/dist/__fixtures__/terragucci-notify.d.ts +66 -0
  17. package/dist/__fixtures__/terragucci-notify.d.ts.map +1 -0
  18. package/dist/__fixtures__/terragucci-notify.js +133 -0
  19. package/dist/action-pins.d.ts +8 -0
  20. package/dist/action-pins.d.ts.map +1 -1
  21. package/dist/action-pins.js +9 -0
  22. package/dist/agent-guard.d.ts +143 -0
  23. package/dist/agent-guard.d.ts.map +1 -0
  24. package/dist/agent-guard.js +455 -0
  25. package/dist/ci-commit.d.ts +120 -5
  26. package/dist/ci-commit.d.ts.map +1 -1
  27. package/dist/ci-commit.js +214 -23
  28. package/dist/ci-own-jobs.d.ts +81 -0
  29. package/dist/ci-own-jobs.d.ts.map +1 -0
  30. package/dist/ci-own-jobs.js +233 -0
  31. package/dist/ci-product-words.d.ts +18 -4
  32. package/dist/ci-product-words.d.ts.map +1 -1
  33. package/dist/ci-product-words.js +26 -6
  34. package/dist/ci-product.d.ts +40 -1
  35. package/dist/ci-product.d.ts.map +1 -1
  36. package/dist/ci-product.js +40 -1
  37. package/dist/cli/handlers/approve.d.ts +5 -1
  38. package/dist/cli/handlers/approve.d.ts.map +1 -1
  39. package/dist/cli/handlers/approve.js +17 -11
  40. package/dist/cli/handlers/build.d.ts +1 -1
  41. package/dist/cli/handlers/build.d.ts.map +1 -1
  42. package/dist/cli/handlers/build.js +88 -2
  43. package/dist/cli/handlers/commit.d.ts.map +1 -1
  44. package/dist/cli/handlers/commit.js +3 -1
  45. package/dist/cli/handlers/notify-relay.d.ts +18 -1
  46. package/dist/cli/handlers/notify-relay.d.ts.map +1 -1
  47. package/dist/cli/handlers/notify-relay.js +90 -14
  48. package/dist/cli/handlers/pr.d.ts.map +1 -1
  49. package/dist/cli/handlers/pr.js +3 -1
  50. package/dist/cli/handlers/release.d.ts +5 -1
  51. package/dist/cli/handlers/release.d.ts.map +1 -1
  52. package/dist/cli/handlers/release.js +21 -9
  53. package/dist/cli/handlers/run-generate.d.ts.map +1 -1
  54. package/dist/cli/handlers/run-generate.js +2 -1
  55. package/dist/cli/main.d.ts.map +1 -1
  56. package/dist/cli/main.js +21 -1
  57. package/dist/cli/parse-args.d.ts.map +1 -1
  58. package/dist/cli/parse-args.js +60 -4
  59. package/dist/cli/registry.d.ts +16 -0
  60. package/dist/cli/registry.d.ts.map +1 -1
  61. package/dist/components/pr-env-components.d.ts +65 -0
  62. package/dist/components/pr-env-components.d.ts.map +1 -0
  63. package/dist/components/pr-env-components.js +162 -0
  64. package/dist/components/pr-policy.d.ts +15 -0
  65. package/dist/components/pr-policy.d.ts.map +1 -1
  66. package/dist/components/pr-policy.js +24 -1
  67. package/dist/components/release-compile.d.ts +15 -3
  68. package/dist/components/release-compile.d.ts.map +1 -1
  69. package/dist/components/release-compile.js +66 -15
  70. package/dist/config.d.ts +14 -8
  71. package/dist/config.d.ts.map +1 -1
  72. package/dist/config.js +16 -1
  73. package/dist/gate-policy.d.ts +14 -1
  74. package/dist/gate-policy.d.ts.map +1 -1
  75. package/dist/gate-policy.js +16 -6
  76. package/dist/lexicon.d.ts +25 -1
  77. package/dist/lexicon.d.ts.map +1 -1
  78. package/dist/lexicon.js +10 -0
  79. package/dist/lifecycle/gated-op.d.ts +95 -0
  80. package/dist/lifecycle/gated-op.d.ts.map +1 -0
  81. package/dist/lifecycle/gated-op.js +96 -0
  82. package/dist/lifecycle/git.d.ts.map +1 -1
  83. package/dist/lifecycle/git.js +83 -2
  84. package/dist/lifecycle/release-images.d.ts +77 -3
  85. package/dist/lifecycle/release-images.d.ts.map +1 -1
  86. package/dist/lifecycle/release-images.js +132 -6
  87. package/dist/notify-product.d.ts +11 -2
  88. package/dist/notify-product.d.ts.map +1 -1
  89. package/dist/notify-product.js +16 -4
  90. package/dist/notify-relay-repo.d.ts +131 -0
  91. package/dist/notify-relay-repo.d.ts.map +1 -0
  92. package/dist/notify-relay-repo.js +202 -0
  93. package/dist/notify-relay.d.ts +25 -1
  94. package/dist/notify-relay.d.ts.map +1 -1
  95. package/dist/notify-relay.js +27 -2
  96. package/dist/notify.d.ts +36 -4
  97. package/dist/notify.d.ts.map +1 -1
  98. package/dist/notify.js +31 -21
  99. package/dist/notify.schema.json +1 -0
  100. package/dist/op/activities/review-product.d.ts +111 -0
  101. package/dist/op/activities/review-product.d.ts.map +1 -0
  102. package/dist/op/activities/review-product.js +116 -0
  103. package/dist/op/op-waves-capability.js +2 -2
  104. package/dist/policy-engine.d.ts +95 -0
  105. package/dist/policy-engine.d.ts.map +1 -0
  106. package/dist/policy-engine.js +157 -0
  107. package/dist/pr-forge-reads.d.ts +124 -0
  108. package/dist/pr-forge-reads.d.ts.map +1 -0
  109. package/dist/pr-forge-reads.js +322 -0
  110. package/dist/pr-forge.d.ts +14 -0
  111. package/dist/pr-forge.d.ts.map +1 -1
  112. package/dist/pr-forge.js +21 -13
  113. package/dist/pr-plan-note.d.ts +293 -0
  114. package/dist/pr-plan-note.d.ts.map +1 -0
  115. package/dist/pr-plan-note.js +362 -0
  116. package/dist/release-floors.d.ts +9 -1
  117. package/dist/release-floors.d.ts.map +1 -1
  118. package/dist/release-floors.js +9 -1
  119. package/dist/state-export.d.ts +126 -0
  120. package/dist/state-export.d.ts.map +1 -0
  121. package/dist/state-export.js +156 -0
  122. package/dist/state-migration.d.ts +148 -0
  123. package/dist/state-migration.d.ts.map +1 -0
  124. package/dist/state-migration.js +146 -0
  125. package/dist/state-unlock.d.ts +167 -0
  126. package/dist/state-unlock.d.ts.map +1 -0
  127. package/dist/state-unlock.js +196 -0
  128. package/dist/wave-runtime.mjs +332 -332
  129. package/dist/workspace/declaration.schema.json +1 -1
  130. package/dist/workspace/release-workflow.d.ts +10 -0
  131. package/dist/workspace/release-workflow.d.ts.map +1 -1
  132. package/dist/workspace/release-workflow.js +10 -4
  133. package/package.json +1 -1
  134. package/src/__fixtures__/agent-guard/plywood.ts +27 -0
  135. package/src/__fixtures__/agent-guard/terragucci.ts +39 -0
  136. package/src/__fixtures__/gated-ledger.ts +58 -0
  137. package/src/__fixtures__/notify-messages/events.ts +23 -0
  138. package/src/__fixtures__/notify-messages/messages.json +50 -0
  139. package/src/__fixtures__/pr-loop/terragucci-plan.note.golden.md +53 -0
  140. package/src/__fixtures__/pr-loop/terragucci-plan.note.json +83 -0
  141. package/src/__fixtures__/product-words.ts +12 -0
  142. package/src/__fixtures__/review-agent/terragucci-review.json +94 -0
  143. package/src/__fixtures__/terragucci-notify.ts +170 -0
  144. package/src/action-pins.test.ts +12 -1
  145. package/src/action-pins.ts +11 -0
  146. package/src/agent-guard.test.ts +319 -0
  147. package/src/agent-guard.ts +547 -0
  148. package/src/ci-commit.test.ts +213 -2
  149. package/src/ci-commit.ts +258 -27
  150. package/src/ci-own-jobs.test.ts +108 -0
  151. package/src/ci-own-jobs.ts +252 -0
  152. package/src/ci-product-words.ts +35 -7
  153. package/src/ci-product.ts +81 -1
  154. package/src/cli/handlers/approve-cwd.test.ts +112 -0
  155. package/src/cli/handlers/approve.ts +22 -11
  156. package/src/cli/handlers/build-own-jobs.test.ts +80 -0
  157. package/src/cli/handlers/build-pr-loop-control.test.ts +87 -0
  158. package/src/cli/handlers/build-run-group.test.ts +59 -0
  159. package/src/cli/handlers/build.ts +83 -3
  160. package/src/cli/handlers/commit.ts +3 -0
  161. package/src/cli/handlers/notify-relay.ts +99 -17
  162. package/src/cli/handlers/pr.ts +3 -1
  163. package/src/cli/handlers/release.ts +20 -10
  164. package/src/cli/handlers/run-generate.ts +2 -1
  165. package/src/cli/main.ts +21 -1
  166. package/src/cli/parse-args.ts +45 -3
  167. package/src/cli/registry.ts +16 -0
  168. package/src/components/pr-env-components.test.ts +137 -0
  169. package/src/components/pr-env-components.ts +213 -0
  170. package/src/components/pr-policy.test.ts +41 -1
  171. package/src/components/pr-policy.ts +25 -1
  172. package/src/components/release-compile.test.ts +47 -0
  173. package/src/components/release-compile.ts +70 -13
  174. package/src/config.ts +23 -3
  175. package/src/gate-policy-bundle.test.ts +14 -0
  176. package/src/gate-policy.test.ts +7 -0
  177. package/src/gate-policy.ts +22 -7
  178. package/src/lexicon.ts +28 -1
  179. package/src/lifecycle/gated-op.ts +158 -0
  180. package/src/lifecycle/git.test.ts +92 -0
  181. package/src/lifecycle/git.ts +71 -2
  182. package/src/lifecycle/release-images-dockerfile.test.ts +221 -0
  183. package/src/lifecycle/release-images.ts +167 -8
  184. package/src/notify-message-words.test.ts +186 -0
  185. package/src/notify-product.ts +17 -4
  186. package/src/notify-relay-repo.test.ts +284 -0
  187. package/src/notify-relay-repo.ts +234 -0
  188. package/src/notify-relay.test.ts +12 -0
  189. package/src/notify-relay.ts +29 -3
  190. package/src/notify.schema.json +1 -0
  191. package/src/notify.ts +59 -19
  192. package/src/op/activities/review-product.test.ts +116 -0
  193. package/src/op/activities/review-product.ts +200 -0
  194. package/src/op/op-waves-capability.ts +2 -2
  195. package/src/op/schedule-overdue.test.ts +26 -0
  196. package/src/policy-engine.test.ts +162 -0
  197. package/src/policy-engine.ts +200 -0
  198. package/src/pr-forge-reads.test.ts +285 -0
  199. package/src/pr-forge-reads.ts +424 -0
  200. package/src/pr-forge.ts +30 -16
  201. package/src/pr-plan-note.test.ts +105 -0
  202. package/src/pr-plan-note.ts +521 -0
  203. package/src/release-floors.ts +13 -1
  204. package/src/state-export.test.ts +124 -0
  205. package/src/state-export.ts +227 -0
  206. package/src/state-migration.test.ts +133 -0
  207. package/src/state-migration.ts +236 -0
  208. package/src/state-unlock.test.ts +165 -0
  209. package/src/state-unlock.ts +293 -0
  210. package/src/workspace/declaration.schema.json +1 -1
  211. package/src/workspace/release-workflow.test.ts +34 -0
  212. package/src/workspace/release-workflow.ts +19 -4
package/src/ci-commit.ts CHANGED
@@ -29,8 +29,10 @@ import { spawn } from "node:child_process";
29
29
  import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
30
30
  import { join } from "node:path";
31
31
  import { CHANT_EXIT } from "./exit-codes";
32
+ import { FORGE_TOKEN_VARS } from "./ci-handover";
32
33
  import { agentForbiddenPaths, AgentError, branchOk, errText, LOGIN, readSmall, SHA, type AgentGit } from "./ci-agent";
33
- import { parseProductComment, type CiProductWords } from "./ci-product-words";
34
+ import { COMMIT_COMMENT_ARG, parseProductComment, type CiProductWords } from "./ci-product-words";
35
+ import { NEXT_RELEASE } from "./release-floors";
34
36
  import type { OpRunRecord, OpRunRecordInput } from "./op/runtime";
35
37
  import type { RunOrigin } from "./lifecycle/release-ledger";
36
38
  import type { PrForge } from "./pr-forge";
@@ -42,6 +44,16 @@ export const CI_COMMIT_FLOOR = "0.124.71";
42
44
  export const CI_COMMIT_PUSH_FLOOR = "0.124.72";
43
45
  /** The first chant whose commit job takes `allowedFiles` (#4758). */
44
46
  export const CI_COMMIT_FILES_FLOOR = "0.124.73";
47
+ /**
48
+ * The first chant whose commit job takes `commandEnv`, gives the command
49
+ * `CHANT_COMMIT_PR`, keeps the tail of its standard error and replies with a
50
+ * product's refusal text ({@link setCommitRefusalReply}) (#4724).
51
+ */
52
+ export const CI_COMMIT_REPLY_FLOOR = "0.124.77";
53
+ /** The first chant whose commit job takes `commentArg`, one argument after the comment's word passed into the argv (#4820). */
54
+ export const CI_COMMIT_ARG_FLOOR = NEXT_RELEASE;
55
+ /** The first chant whose `commit land` reads {@link COMMIT_HARNESS_BREAK_ENV} in a BREAK arm of chant's e2e harness (#4836). */
56
+ export const CI_COMMIT_HARNESS_BREAK_FLOOR = NEXT_RELEASE;
45
57
 
46
58
  /** What starts a commit run: a person's comment, or a check job's finding. */
47
59
  export type CommitTrigger = "comment" | "check";
@@ -103,6 +115,30 @@ export interface OpCommitSpec {
103
115
  * the new head. Not run when nothing was pushed.
104
116
  */
105
117
  after?: string[];
118
+ /**
119
+ * Variables of the commit job the command sees, by name (#4724), such as a
120
+ * database reader's user and password. Every other variable is left out,
121
+ * as before. A forge token's name is refused. GitHub and Forgejo pass each
122
+ * one from the secret of the same name to the step that runs the command;
123
+ * on GitLab they are the project's CI/CD variables.
124
+ */
125
+ commandEnv?: string[];
126
+ /**
127
+ * For `on: "comment"` (#4820): the comment may carry one argument after
128
+ * the word, `/<product> <word> <arg>`, which must match `pattern` (a
129
+ * regular expression's source, anchored with `^` and `$`) and chant's
130
+ * own plain-name check ({@link COMMIT_COMMENT_ARG}). It goes into the
131
+ * command's argv at index `position`, from 1 (after the program) to the
132
+ * argv's length (at the end). With no argument the argv is `command`. On
133
+ * GitLab the pipeline's {@link GITLAB_COMMIT_ARG_VAR} carries it.
134
+ */
135
+ commentArg?: CommitCommentArg;
136
+ }
137
+
138
+ /** Where a commit job's command takes the comment's argument (#4820). */
139
+ export interface CommitCommentArg {
140
+ pattern: string;
141
+ position: number;
106
142
  }
107
143
 
108
144
  /** A commit job's settings, every default filled and checked. */
@@ -123,6 +159,10 @@ export interface CommitSettings {
123
159
  jobToken: boolean;
124
160
  /** Lines the push job runs after a push (#4749). */
125
161
  after: string[];
162
+ /** The job variables the command sees (#4724). */
163
+ commandEnv: string[];
164
+ /** The comment's argument and where it goes in the argv (#4820). */
165
+ commentArg?: CommitCommentArg;
126
166
  }
127
167
 
128
168
  export const COMMIT_MAX_RUNS = 3;
@@ -146,11 +186,18 @@ export const COMMIT_ENV = {
146
186
  timeout: "CHANT_COMMIT_TIMEOUT",
147
187
  env: "CHANT_COMMIT_ENV",
148
188
  mergeBase: "CHANT_COMMIT_MERGE_BASE",
189
+ commandEnv: "CHANT_COMMIT_COMMAND_ENV",
190
+ commentArg: "CHANT_COMMIT_COMMENT_ARG",
149
191
  } as const;
150
192
 
193
+ /** The variable the command reads the pull request's number from (#4724), such as for a default name. */
194
+ export const COMMIT_PR_ENV = "CHANT_COMMIT_PR";
195
+
151
196
  /** GitLab starts no pipeline on a note: a pipeline of the default branch started with these runs a comment commit job. */
152
197
  export const GITLAB_COMMIT_PR_VAR = "CHANT_COMMIT_PR";
153
198
  export const GITLAB_COMMIT_WORD_VAR = "CHANT_COMMIT";
199
+ /** With `commentArg` (#4820): the argument, as the comment would give it after the word. */
200
+ export const GITLAB_COMMIT_ARG_VAR = "CHANT_COMMIT_ARG";
154
201
 
155
202
  /** Where the jobs keep the decision, the exit code and the patch, from the job's directory. */
156
203
  export const COMMIT_DIR = ".chant/commit";
@@ -161,6 +208,10 @@ export const COMMIT_BASE_REF = "refs/chant/commit-base";
161
208
  export const COMMIT_DECISION_FILE = "decision.json";
162
209
  export const COMMIT_PATCH_FILE = "change.patch";
163
210
  export const COMMIT_RC_FILE = "rc";
211
+ /** The tail of the command's standard error (#4724), which a product's refusal reply reads. */
212
+ export const COMMIT_OUTPUT_FILE = "output";
213
+ /** How much of the command's standard error {@link COMMIT_OUTPUT_FILE} keeps, from the end. */
214
+ export const COMMIT_OUTPUT_LIMIT = 8192;
164
215
  /** What `chant commit land` leaves when it pushed (#4749): the pushed commit, which the push job's `after` lines read. */
165
216
  export const COMMIT_PUSHED_FILE = "pushed";
166
217
 
@@ -229,6 +280,24 @@ export function resolveCommitSpec(name: string, spec: OpCommitSpec, product = "c
229
280
  if (spec.jobToken && spec.tokenEnv !== undefined) throw new AgentError(`${where}: jobToken pushes with the job's own token, so leave tokenEnv out`);
230
281
  const after = spec.after ?? [];
231
282
  if (!Array.isArray(after) || !after.every((l) => typeof l === "string" && l.trim() !== "" && !l.includes("\n"))) throw new AgentError(`${where}: after is a list of shell lines, one command each`);
283
+ const commandEnv = spec.commandEnv ?? [];
284
+ if (!Array.isArray(commandEnv) || !commandEnv.every((v) => typeof v === "string" && VAR.test(v))) throw new AgentError(`${where}: commandEnv is a list of variable names`);
285
+ const tokens = commandEnv.filter((v) => (FORGE_TOKEN_VARS as readonly string[]).includes(v) || v === spec.tokenEnv || v.startsWith("CHANT_COMMIT_"));
286
+ if (tokens.length > 0) throw new AgentError(`${where}: commandEnv may not pass ${tokens.join(", ")}: the command never sees a forge token or the job's own settings`);
287
+ let commentArg: CommitCommentArg | undefined;
288
+ if (spec.commentArg !== undefined) {
289
+ const a = spec.commentArg as Partial<CommitCommentArg>;
290
+ if (spec.on !== "comment") throw new AgentError(`${where}: commentArg is for the comment trigger, which has a comment to read it from`);
291
+ if (typeof a.pattern !== "string" || !a.pattern.startsWith("^") || !a.pattern.endsWith("$") || a.pattern.length > 200) {
292
+ throw new AgentError(`${where}: commentArg's pattern is a regular expression's source anchored with ^ and $, such as "^[a-z0-9]+(?:[-_][a-z0-9]+)*$"`);
293
+ }
294
+ try {
295
+ new RegExp(a.pattern);
296
+ } catch (e) {
297
+ throw new AgentError(`${where}: commentArg's pattern is not a regular expression (${(e as Error).message})`);
298
+ }
299
+ commentArg = { pattern: a.pattern, position: intIn(`${where}: commentArg's position`, a.position, 1, spec.command.length) };
300
+ }
232
301
  return {
233
302
  name,
234
303
  on: spec.on,
@@ -244,9 +313,29 @@ export function resolveCommitSpec(name: string, spec: OpCommitSpec, product = "c
244
313
  mergeBase: spec.mergeBase === true,
245
314
  jobToken: spec.jobToken === true,
246
315
  after: [...after],
316
+ commandEnv: [...new Set(commandEnv)],
317
+ ...(commentArg ? { commentArg } : {}),
247
318
  };
248
319
  }
249
320
 
321
+ /** The words that take an argument, for {@link parseProductComment}: this job's word, when it has `commentArg`. */
322
+ function commentArgPatterns(s: Partial<Pick<CommitSettings, "comment" | "commentArg">>): Record<string, RegExp> {
323
+ const word = s.comment?.split(" ")[1];
324
+ return word && s.commentArg ? { [word]: new RegExp(s.commentArg.pattern) } : {};
325
+ }
326
+
327
+ /**
328
+ * The argv the command runs (#4820): `command`, with the comment's argument
329
+ * at `commentArg.position` when there is one. An argument the settings do
330
+ * not take, or one off its pattern, throws.
331
+ */
332
+ export function commitArgv(s: Pick<CommitSettings, "command"> & Partial<Pick<CommitSettings, "commentArg">>, arg: string | undefined): string[] {
333
+ if (arg === undefined) return [...s.command];
334
+ if (!s.commentArg) throw new AgentError("this commit job takes no argument after its word");
335
+ if (!COMMIT_COMMENT_ARG.test(arg) || !new RegExp(s.commentArg.pattern).test(arg)) throw new AgentError(`${JSON.stringify(arg)} is not a name this commit job takes`);
336
+ return [...s.command.slice(0, s.commentArg.position), arg, ...s.command.slice(s.commentArg.position)];
337
+ }
338
+
250
339
  /** The settings as the generated jobs' variables. */
251
340
  export function commitSettingsEnv(s: CommitSettings): Record<string, string> {
252
341
  return {
@@ -262,6 +351,8 @@ export function commitSettingsEnv(s: CommitSettings): Record<string, string> {
262
351
  [COMMIT_ENV.timeout]: String(s.timeout),
263
352
  [COMMIT_ENV.env]: s.env,
264
353
  ...(s.mergeBase ? { [COMMIT_ENV.mergeBase]: "1" } : {}),
354
+ ...(s.commandEnv.length > 0 ? { [COMMIT_ENV.commandEnv]: JSON.stringify(s.commandEnv) } : {}),
355
+ ...(s.commentArg ? { [COMMIT_ENV.commentArg]: JSON.stringify(s.commentArg) } : {}),
265
356
  };
266
357
  }
267
358
 
@@ -291,6 +382,17 @@ export function commitSettingsFromEnv(env: Record<string, string | undefined>, p
291
382
  const maxRuns = num(COMMIT_ENV.maxRuns);
292
383
  const timeout = num(COMMIT_ENV.timeout);
293
384
  const guarded = list(COMMIT_ENV.guarded);
385
+ let commentArg: CommitCommentArg | undefined;
386
+ const argText = env[COMMIT_ENV.commentArg];
387
+ if (argText) {
388
+ try {
389
+ const parsed = JSON.parse(argText) as unknown;
390
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
391
+ commentArg = parsed as CommitCommentArg;
392
+ } catch (e) {
393
+ throw new AgentError(`${COMMIT_ENV.commentArg} is a JSON object with pattern and position (${(e as Error).message})`);
394
+ }
395
+ }
294
396
  const spec: OpCommitSpec = {
295
397
  on: env[COMMIT_ENV.on] as CommitTrigger,
296
398
  ...(env[COMMIT_ENV.comment] ? { comment: env[COMMIT_ENV.comment] } : {}),
@@ -303,6 +405,8 @@ export function commitSettingsFromEnv(env: Record<string, string | undefined>, p
303
405
  ...(guarded ? { guarded } : {}),
304
406
  ...(env[COMMIT_ENV.env] ? { env: env[COMMIT_ENV.env] } : {}),
305
407
  ...(env[COMMIT_ENV.mergeBase] === "1" ? { mergeBase: true } : {}),
408
+ ...(list(COMMIT_ENV.commandEnv) ? { commandEnv: list(COMMIT_ENV.commandEnv)! } : {}),
409
+ ...(commentArg ? { commentArg } : {}),
306
410
  };
307
411
  return resolveCommitSpec(name, spec, product);
308
412
  }
@@ -335,6 +439,8 @@ export interface CommitRequest {
335
439
  pr: number;
336
440
  /** The commenter, or the person who started the GitLab pipeline. Absent on the `check` trigger. */
337
441
  user?: string;
442
+ /** The comment's argument (#4820), checked against `commentArg`. */
443
+ arg?: string;
338
444
  }
339
445
 
340
446
  /**
@@ -345,7 +451,7 @@ export interface CommitRequest {
345
451
  * pull request the check ran for, from the `pull_request` event or the
346
452
  * merge request pipeline.
347
453
  */
348
- export function commitRequestFromRun(words: CiProductWords, s: Pick<CommitSettings, "on" | "comment">, env: Record<string, string | undefined>, event: unknown): CommitRequest | { refused: string } {
454
+ export function commitRequestFromRun(words: CiProductWords, s: Pick<CommitSettings, "on" | "comment"> & Partial<Pick<CommitSettings, "commentArg">>, env: Record<string, string | undefined>, event: unknown): CommitRequest | { refused: string } {
349
455
  const gitlab = env.GITLAB_CI === "true";
350
456
  let pr: unknown;
351
457
  if (s.on === "check") {
@@ -358,7 +464,8 @@ export function commitRequestFromRun(words: CiProductWords, s: Pick<CommitSettin
358
464
  const word = s.comment?.split(" ")[1];
359
465
  if (gitlab) {
360
466
  pr = Number(env[GITLAB_COMMIT_PR_VAR]);
361
- body = env[GITLAB_COMMIT_WORD_VAR] === word ? s.comment : `/${words.product} ${env[GITLAB_COMMIT_WORD_VAR] ?? ""}`;
467
+ const arg = env[GITLAB_COMMIT_ARG_VAR];
468
+ body = env[GITLAB_COMMIT_WORD_VAR] === word ? `${s.comment}${arg ? ` ${arg}` : ""}` : `/${words.product} ${env[GITLAB_COMMIT_WORD_VAR] ?? ""}`;
362
469
  user = env.GITLAB_USER_LOGIN;
363
470
  } else {
364
471
  const e = event as { comment?: { body?: unknown; user?: { login?: unknown } }; issue?: { number?: unknown } } | undefined;
@@ -368,10 +475,10 @@ export function commitRequestFromRun(words: CiProductWords, s: Pick<CommitSettin
368
475
  }
369
476
  if (typeof pr !== "number" || !Number.isInteger(pr) || pr < 1) return { refused: "the run names no pull request" };
370
477
  if (typeof user !== "string" || !LOGIN.test(user)) return { refused: "the run names nobody who asked" };
371
- const parsed = parseProductComment(words, body, env);
478
+ const parsed = parseProductComment(words, body, env, commentArgPatterns(s));
372
479
  if (parsed?.kind === "refused") return { refused: parsed.reason };
373
480
  if (parsed?.kind !== "commit" || parsed.word !== word) return { refused: `the comment is not ${s.comment}` };
374
- return { pr, user };
481
+ return { pr, user, ...(parsed.arg !== undefined ? { arg: parsed.arg } : {}) };
375
482
  }
376
483
 
377
484
  /**
@@ -408,7 +515,7 @@ function pushedBranch(env: Record<string, string | undefined>): string | undefin
408
515
  */
409
516
  export async function resolveCommitRequest(
410
517
  words: CiProductWords,
411
- s: Pick<CommitSettings, "on" | "comment">,
518
+ s: Pick<CommitSettings, "on" | "comment"> & Partial<Pick<CommitSettings, "commentArg">>,
412
519
  env: Record<string, string | undefined>,
413
520
  event: unknown,
414
521
  forge?: Partial<Pick<PrForge, "findPullRequest">>,
@@ -439,6 +546,8 @@ export interface CommitDecision {
439
546
  pr?: number;
440
547
  branch?: string;
441
548
  user?: string;
549
+ /** The comment's argument (#4820), which `commit run` puts in the argv. */
550
+ arg?: string;
442
551
  /** With `mergeBase`: the base branch and the tip the command ran on. */
443
552
  base?: string;
444
553
  baseSha?: string;
@@ -454,6 +563,7 @@ export function readCommitDecision(dir: string): CommitDecision | undefined {
454
563
  if (d.branch !== undefined && !branchOk(d.branch)) return undefined;
455
564
  if (d.base !== undefined && !branchOk(d.base)) return undefined;
456
565
  if (d.baseSha !== undefined && !SHA.test(d.baseSha)) return undefined;
566
+ if (d.arg !== undefined && !(typeof d.arg === "string" && COMMIT_COMMENT_ARG.test(d.arg))) return undefined;
457
567
  return d as CommitDecision;
458
568
  } catch {
459
569
  return undefined;
@@ -585,7 +695,7 @@ export async function prepareCommitRun(i: CommitPrepareInput): Promise<CommitDec
585
695
 
586
696
  const req = await resolveCommitRequest(i.words, s, i.env, i.event, i.forge);
587
697
  if ("refused" in req) return no(req.refused, s.on === "check" ? "skipped" : "refused");
588
- const who = { pr: req.pr, ...(req.user ? { user: req.user } : {}) };
698
+ const who = { pr: req.pr, ...(req.user ? { user: req.user } : {}), ...(req.arg !== undefined ? { arg: req.arg } : {}) };
589
699
  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);
590
700
 
591
701
  let sha: string;
@@ -641,13 +751,25 @@ export async function prepareCommitRun(i: CommitPrepareInput): Promise<CommitDec
641
751
 
642
752
  // ── commit run ─────────────────────────────────────────────────────────────
643
753
 
644
- /** Run an argv in `cwd`, with no shell. A failure or a timeout is an outcome. */
645
- export type CommitRunCommand = (argv: readonly string[], o: { cwd: string; env: Record<string, string>; timeoutMs: number }) => Promise<{ exitCode: number | null; timedOut: boolean }>;
754
+ /**
755
+ * Run an argv in `cwd`, with no shell. A failure or a timeout is an outcome.
756
+ * `output` is the tail of its standard error (#4724), at most
757
+ * {@link COMMIT_OUTPUT_LIMIT} bytes.
758
+ */
759
+ export type CommitRunCommand = (argv: readonly string[], o: { cwd: string; env: Record<string, string>; timeoutMs: number }) => Promise<{ exitCode: number | null; timedOut: boolean; output?: string }>;
646
760
 
647
761
  export const runCommitArgv: CommitRunCommand = (argv, o) =>
648
762
  new Promise((done) => {
649
763
  let timedOut = false;
650
- const child = spawn(argv[0]!, argv.slice(1), { cwd: o.cwd, env: o.env, stdio: ["ignore", "inherit", "inherit"] });
764
+ let tail = Buffer.alloc(0);
765
+ const child = spawn(argv[0]!, argv.slice(1), { cwd: o.cwd, env: o.env, stdio: ["ignore", "inherit", "pipe"] });
766
+ // The job's log still gets all of it; the tail is kept for the reply.
767
+ child.stderr?.on("data", (chunk: Buffer) => {
768
+ process.stderr.write(chunk);
769
+ tail = Buffer.concat([tail, chunk]);
770
+ if (tail.length > COMMIT_OUTPUT_LIMIT) tail = tail.subarray(tail.length - COMMIT_OUTPUT_LIMIT);
771
+ });
772
+ const output = (): string => tail.toString("utf8");
651
773
  const timer = setTimeout(() => {
652
774
  timedOut = true;
653
775
  child.kill("SIGTERM");
@@ -655,25 +777,28 @@ export const runCommitArgv: CommitRunCommand = (argv, o) =>
655
777
  }, o.timeoutMs);
656
778
  child.on("error", () => {
657
779
  clearTimeout(timer);
658
- done({ exitCode: null, timedOut });
780
+ done({ exitCode: null, timedOut, output: output() });
659
781
  });
660
782
  child.on("close", (code) => {
661
783
  clearTimeout(timer);
662
- done({ exitCode: code, timedOut });
784
+ done({ exitCode: code, timedOut, output: output() });
663
785
  });
664
786
  });
665
787
 
666
788
  /**
667
789
  * The variables the command sees: process basics, with the checkout's
668
790
  * `node_modules/.bin` first on `PATH` so a product's bin installed on the
669
- * target branch runs on the head's files. Never a forge or cloud token.
791
+ * target branch runs on the head's files. Never a forge or cloud token. Also
792
+ * the variables the spec's `commandEnv` names, and {@link COMMIT_PR_ENV}, the
793
+ * pull request's number (#4724).
670
794
  */
671
- export function commitCommandEnv(env: Record<string, string | undefined>, checkout: string): Record<string, string> {
795
+ export function commitCommandEnv(env: Record<string, string | undefined>, checkout: string, o: { names?: readonly string[]; pr?: number } = {}): Record<string, string> {
672
796
  const out: Record<string, string> = {};
673
- for (const name of ["PATH", "HOME", "TMPDIR", "LANG", "LC_ALL", "TERM", "SystemRoot", "npm_config_cache"]) {
797
+ for (const name of ["PATH", "HOME", "TMPDIR", "LANG", "LC_ALL", "TERM", "SystemRoot", "npm_config_cache", ...(o.names ?? [])]) {
674
798
  const v = env[name];
675
799
  if (v !== undefined) out[name] = v;
676
800
  }
801
+ if (o.pr !== undefined) out[COMMIT_PR_ENV] = String(o.pr);
677
802
  const bin = join(checkout, "node_modules", ".bin");
678
803
  if (existsSync(bin)) out.PATH = out.PATH ? `${bin}:${out.PATH}` : bin;
679
804
  return out;
@@ -699,6 +824,13 @@ export async function runCommit(i: CommitRunInput): Promise<{ rc: string; change
699
824
  writeFileSync(rcFile, "refused\n");
700
825
  return { rc: "refused", changed: false };
701
826
  }
827
+ let argv: string[];
828
+ try {
829
+ argv = commitArgv(i.settings, decision.arg);
830
+ } catch {
831
+ writeFileSync(rcFile, "refused\n");
832
+ return { rc: "refused", changed: false };
833
+ }
702
834
  i.git(["worktree", "add", "--detach", "--force", i.workDir, decision.sha]);
703
835
  if (i.settings.mergeBase) {
704
836
  if (!decision.baseSha) {
@@ -713,17 +845,87 @@ export async function runCommit(i: CommitRunInput): Promise<{ rc: string; change
713
845
  return { rc: "conflict", changed: false };
714
846
  }
715
847
  }
716
- const out = await i.runCommand(i.settings.command, { cwd: i.workDir, env: commitCommandEnv(i.env, i.checkout), timeoutMs: i.settings.timeout * 60_000 });
848
+ const env = commitCommandEnv(i.env, i.checkout, { names: i.settings.commandEnv, ...(decision.pr !== undefined ? { pr: decision.pr } : {}) });
849
+ const out = await i.runCommand(argv, { cwd: i.workDir, env, timeoutMs: i.settings.timeout * 60_000 });
717
850
  const rc = out.timedOut ? "timeout" : out.exitCode === null ? "no-exit" : String(out.exitCode);
718
851
  writeFileSync(rcFile, `${rc}\n`);
852
+ if (out.output) writeFileSync(join(i.dir, COMMIT_OUTPUT_FILE), out.output.slice(-COMMIT_OUTPUT_LIMIT));
719
853
  i.git(["add", "-A"], { cwd: i.workDir });
720
854
  const patch = i.git(["diff", "--cached", "--binary", "--no-renames", "HEAD"], { cwd: i.workDir });
721
855
  writeFileSync(join(i.dir, COMMIT_PATCH_FILE), patch);
722
856
  return { rc, changed: patch.length > 0 };
723
857
  }
724
858
 
859
+ // ── the harness's BREAK switch (#4836) ─────────────────────────────────────
860
+
861
+ /**
862
+ * The push job's variable that turns one of land's checks off, for a BREAK
863
+ * arm of a product's e2e harness scenario: a comma list of
864
+ * {@link COMMIT_HARNESS_CHECKS}. It proves the check matters: with it off,
865
+ * the scenario's expectations must fail. Read only by `chant commit land`,
866
+ * and refused anywhere but chant's harness ({@link commitHarnessBreaks}).
867
+ * The command never sees it: `commandEnv` refuses every `CHANT_COMMIT_*`.
868
+ */
869
+ export const COMMIT_HARNESS_BREAK_ENV = "CHANT_COMMIT_HARNESS_BREAK";
870
+
871
+ /**
872
+ * The checks the switch may turn off. `paths`: a change outside `allowed`
873
+ * and `allowedFiles` lands (a guarded path is still refused). `moved-base`:
874
+ * with `mergeBase`, a base that moved while the command ran lands the merge
875
+ * of the tip the command ran on.
876
+ */
877
+ export const COMMIT_HARNESS_CHECKS = ["paths", "moved-base"] as const;
878
+ export type CommitHarnessCheck = (typeof COMMIT_HARNESS_CHECKS)[number];
879
+
880
+ /** The forge a job of chant's e2e harness reaches, `HARNESS_HOSTS.forgejo` (./e2e-harness/stack.ts). */
881
+ export const COMMIT_HARNESS_FORGE = "http://forgejo:3000";
882
+
883
+ const HARNESS_WORDS: Record<CommitHarnessCheck, string> = { paths: "the path check", "moved-base": "the moved-base check" };
884
+
885
+ /**
886
+ * The checks {@link COMMIT_HARNESS_BREAK_ENV} turns off, or why it is
887
+ * refused. It is read only in a BREAK arm of chant's e2e harness: `BREAK=1`,
888
+ * not GitLab, and a job whose `GITHUB_SERVER_URL` is the harness's Forgejo,
889
+ * {@link COMMIT_HARNESS_FORGE}. Unset or empty, no check is off.
890
+ */
891
+ export function commitHarnessBreaks(env: Record<string, string | undefined>): { checks: CommitHarnessCheck[] } | { refused: string } {
892
+ const raw = env[COMMIT_HARNESS_BREAK_ENV]?.trim() ?? "";
893
+ if (raw === "") return { checks: [] };
894
+ const server = env.GITHUB_SERVER_URL?.replace(/\/+$/, "");
895
+ if (env.BREAK !== "1" || env.GITLAB_CI === "true" || server !== COMMIT_HARNESS_FORGE) {
896
+ return { refused: `${COMMIT_HARNESS_BREAK_ENV} is read only in a BREAK arm of chant's e2e harness (BREAK=1 on the harness's Forgejo, ${COMMIT_HARNESS_FORGE}), and this job is not one` };
897
+ }
898
+ const named = raw.split(",").map((c) => c.trim()).filter((c) => c !== "");
899
+ const bad = named.filter((c) => !(COMMIT_HARNESS_CHECKS as readonly string[]).includes(c));
900
+ if (bad.length > 0) return { refused: `${COMMIT_HARNESS_BREAK_ENV} names ${bad.join(", ")}; the checks it turns off are ${COMMIT_HARNESS_CHECKS.join(" and ")}` };
901
+ return { checks: [...new Set(named)] as CommitHarnessCheck[] };
902
+ }
903
+
725
904
  // ── commit land ────────────────────────────────────────────────────────────
726
905
 
906
+ /**
907
+ * A product's reply to a command that exited non-zero (#4724): the text that
908
+ * says why, from the command's exit code and the tail of its standard error,
909
+ * or undefined for chant's own reply. The output comes from a command run on
910
+ * the pull request's files, so a reply quotes from it only what it checked.
911
+ * A reply makes the run `refused`, not `failed`.
912
+ */
913
+ export type CommitRefusalReply = (o: { settings: CommitSettings; rc: string; output: string }) => string | undefined;
914
+
915
+ let activeRefusalReply: CommitRefusalReply | undefined;
916
+
917
+ /** Set the refusal reply for this process (a product's bin, once, as it sets its words). Returns the one it replaced. */
918
+ export function setCommitRefusalReply(reply: CommitRefusalReply | undefined): CommitRefusalReply | undefined {
919
+ const was = activeRefusalReply;
920
+ activeRefusalReply = reply;
921
+ return was;
922
+ }
923
+
924
+ /** The refusal reply {@link setCommitRefusalReply} set, if any. */
925
+ export function activeCommitRefusalReply(): CommitRefusalReply | undefined {
926
+ return activeRefusalReply;
927
+ }
928
+
727
929
  export interface CommitLandOutcome {
728
930
  result: CommitResult;
729
931
  reason: string;
@@ -753,6 +955,8 @@ export interface CommitLandInput {
753
955
  record: (input: OpRunRecordInput) => Promise<void>;
754
956
  now: () => Date;
755
957
  runOrigin?: RunOrigin;
958
+ /** The product's reply to a command that exited non-zero (#4724). */
959
+ refusalReply?: CommitRefusalReply;
756
960
  }
757
961
 
758
962
  const code = (s: string): string => "`" + s.replaceAll("`", "'") + "`";
@@ -813,17 +1017,37 @@ export async function landCommitChange(i: CommitLandInput): Promise<CommitLandOu
813
1017
  const req = await resolveCommitRequest(i.words, s, i.env, i.event, i.forge);
814
1018
  if ("refused" in req) return finish({ result: s.on === "check" ? "skipped" : "refused", reason: req.refused });
815
1019
  ({ pr, user } = req);
1020
+ // #4836: a BREAK arm of the harness may turn a check off; anywhere else the switch fails the land.
1021
+ const harness = commitHarnessBreaks(i.env);
1022
+ if ("refused" in harness) return finish({ result: "failed", reason: harness.refused }, `${harness.refused}, so nothing was pushed.`);
1023
+ const off = new Set(harness.checks);
816
1024
  const decision = readCommitDecision(i.dir);
817
- if (!decision || decision.name !== s.name || decision.on !== s.on || (decision.pr !== undefined && decision.pr !== pr)) {
1025
+ if (!decision || decision.name !== s.name || decision.on !== s.on || (decision.pr !== undefined && decision.pr !== pr) || (decision.go && decision.arg !== req.arg)) {
818
1026
  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.");
819
1027
  }
820
1028
  if (!decision.go) return finish({ result: decision.stop ?? "refused", reason: decision.reason ?? "refused" }, `${decision.reason ?? `${s.name} did not run`}, so nothing was pushed.`);
1029
+ // What ran, as the replies and the commit name it: the command with the comment's argument (#4820).
1030
+ let ranArgv: string;
1031
+ try {
1032
+ ranArgv = commitArgv(s, req.arg).join(" ");
1033
+ } catch (e) {
1034
+ return finish({ result: "refused", reason: errText(e) }, `${errText(e)}, so nothing was pushed.`);
1035
+ }
821
1036
  const rc = readSmall(join(i.dir, COMMIT_RC_FILE))?.trim() ?? "";
822
1037
  if (rc === "conflict") {
823
1038
  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.`);
824
1039
  }
825
- 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.`);
826
- 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.`);
1040
+ if (rc === "timeout") return finish({ result: "stopped", reason: `the command passed its ${s.timeout} minute limit` }, `${code(ranArgv)} was stopped at its ${s.timeout} minute limit, so nothing was pushed.`);
1041
+ if (rc !== "0" && /^[0-9]+$/.test(rc) && i.refusalReply) {
1042
+ let said: string | undefined;
1043
+ try {
1044
+ said = i.refusalReply({ settings: s, rc, output: readSmall(join(i.dir, COMMIT_OUTPUT_FILE), COMMIT_OUTPUT_LIMIT * 2) ?? "" });
1045
+ } catch {
1046
+ said = undefined;
1047
+ }
1048
+ if (said) return finish({ result: "refused", reason: `the command refused, exiting ${rc}` }, `${said.trim()} Nothing was pushed.`);
1049
+ }
1050
+ if (rc !== "0") return finish({ result: "failed", reason: `the command exited ${rc || "with no code"}` }, `${code(ranArgv)} stopped with ${rc ? `exit code ${rc}` : "no exit code"}, so nothing was pushed. The commit job's log has its output.`);
827
1051
 
828
1052
  const head = await i.forge.pullRequestHead?.(pr!).catch(() => undefined);
829
1053
  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.`);
@@ -844,7 +1068,11 @@ export async function landCommitChange(i: CommitLandInput): Promise<CommitLandOu
844
1068
  } catch (e) {
845
1069
  return finish({ result: "failed", reason: `could not fetch ${target} (${errText(e)})` });
846
1070
  }
847
- 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.`);
1071
+ if (baseSha !== decision.baseSha) {
1072
+ if (!off.has("moved-base")) 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.`);
1073
+ // BREAK: land the merge of the tip the command ran on, which the check exists to stop.
1074
+ baseSha = decision.baseSha;
1075
+ }
848
1076
  }
849
1077
 
850
1078
  // The limit and the approval again, on this job's own read.
@@ -861,7 +1089,7 @@ export async function landCommitChange(i: CommitLandInput): Promise<CommitLandOu
861
1089
 
862
1090
  const patch = join(i.dir, COMMIT_PATCH_FILE);
863
1091
  const nothing = (): Promise<CommitLandOutcome> =>
864
- finish({ result: s.on === "check" ? "skipped" : "refused", reason: "the command changed nothing" }, `${code(s.command.join(" "))} changed nothing, so nothing was pushed.`);
1092
+ finish({ result: s.on === "check" ? "skipped" : "refused", reason: "the command changed nothing" }, `${code(ranArgv)} changed nothing, so nothing was pushed.`);
865
1093
  if (!existsSync(patch) || statSync(patch).size === 0) return nothing();
866
1094
  let paths: string[];
867
1095
  try {
@@ -882,17 +1110,19 @@ export async function landCommitChange(i: CommitLandInput): Promise<CommitLandOu
882
1110
  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.`);
883
1111
  }
884
1112
  if (paths.length === 0) return nothing();
885
- const { forbidden, outside } = commitRefusedPaths(paths, s);
1113
+ const refusedPaths = commitRefusedPaths(paths, s);
1114
+ const forbidden = refusedPaths.forbidden;
1115
+ const outside = off.has("paths") ? [] : refusedPaths.outside;
886
1116
  if (forbidden.length > 0 || outside.length > 0) {
887
1117
  const bad = [...new Set([...forbidden, ...outside])];
888
1118
  return finish(
889
1119
  { result: "refused", reason: `the change touches ${bad.join(", ")}`, paths },
890
- `${code(s.command.join(" "))} changed ${bad.map(code).join(", ")}, which ${s.name} may not change (it may change ${[...s.allowed, ...s.allowedFiles].map(code).join(", ")}, and never CI, chant's settings and state, code owners, agent instructions or git settings), so nothing was pushed.`,
1120
+ `${code(ranArgv)} changed ${bad.map(code).join(", ")}, which ${s.name} may not change (it may change ${[...s.allowed, ...s.allowedFiles].map(code).join(", ")}, and never CI, chant's settings and state, code owners, agent instructions or git settings), so nothing was pushed.`,
891
1121
  );
892
1122
  }
893
1123
 
894
- 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)}`;
895
- 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)}.`;
1124
+ const title = s.on === "comment" ? `${s.comment}${req.arg !== undefined ? ` ${req.arg}` : ""} asked for by ${user} on ${what} #${pr}` : `${s.name} after the check found something at ${sha.slice(0, 8)}`;
1125
+ const ran = baseSha ? `Merged ${decision.base} at ${baseSha.slice(0, 12)} into ${sha.slice(0, 12)}, then ran ${ranArgv}.` : `Ran ${ranArgv} on ${sha.slice(0, 12)}.`;
896
1126
  const message = [title, "", ran, "", ...(user ? [`Requested-by: ${user}`] : []), `${COMMIT_TRAILER}: ${s.name}`, ""].join("\n");
897
1127
  let commitSha: string;
898
1128
  try {
@@ -907,10 +1137,11 @@ export async function landCommitChange(i: CommitLandInput): Promise<CommitLandOu
907
1137
  } catch (e) {
908
1138
  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.`);
909
1139
  }
1140
+ const breakNote = off.size > 0 ? ` (BREAK: ${[...off].map((c) => HARNESS_WORDS[c]).join(" and ")} ${off.size === 1 ? "was" : "were"} off)` : "";
910
1141
  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.` : "";
911
1142
  return finish(
912
- { result: "pushed", reason: `pushed ${commitSha} to ${head.branch}`, commit: commitSha, paths, ...(approved ? { approvalVoided: approved } : {}) },
913
- `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.`,
1143
+ { result: "pushed", reason: `pushed ${commitSha} to ${head.branch}${breakNote}`, commit: commitSha, paths, ...(approved ? { approvalVoided: approved } : {}) },
1144
+ `pushed ${code(commitSha.slice(0, 8))} to ${code(head.branch)}${user ? ` for ${user}` : ""}, from ${baseSha ? `a merge of ${code(decision.base!)} and ` : ""}${code(ranArgv)}, changing ${paths.map(code).join(", ")}.${voided} Nothing was applied, approved or merged.${breakNote}`,
914
1145
  );
915
1146
  }
916
1147
 
@@ -0,0 +1,108 @@
1
+ /**
2
+ * A repository's own jobs in the pipeline file chant generates (#4769): a
3
+ * jobs file merged after chant's jobs, and the old file's hand-added jobs
4
+ * kept across regeneration.
5
+ */
6
+ import { mkdtempSync, writeFileSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { describe, expect, test } from "vitest";
10
+ import { isGeneratedJob, jobNames, keepOwnJobs, mergeOwnJobs, OWN_JOBS_LINE, OwnJobsError, readOwnJobsFile } from "./ci-own-jobs";
11
+ import * as ciProduct from "./ci-product";
12
+
13
+ const GITHUB = ["name: chant", "on:", " pull_request:", "jobs:", " plan:", " runs-on: ubuntu-latest", " steps:", " - run: chant components pr-plan prod", " plan-note:", " runs-on: ubuntu-latest", " steps:", " - run: chant components pr-post prod", ""].join("\n");
14
+ const GITLAB = ["stages:", " - plan", "variables:", " A: b", "plan:", " stage: plan", " script:", " - chant components pr-plan prod", ""].join("\n");
15
+
16
+ describe("mergeOwnJobs", () => {
17
+ test("puts the jobs after chant's, under the line, on GitHub and Forgejo", () => {
18
+ const out = mergeOwnJobs(GITHUB, "github", { lint: { "runs-on": "ubuntu-latest", steps: [{ run: "npm run lint" }] } });
19
+ expect(out).toBe(GITHUB + [" " + OWN_JOBS_LINE, " lint:", " runs-on: ubuntu-latest", " steps:", " - run: npm run lint", ""].join("\n"));
20
+ expect(jobNames(out, "forgejo")).toEqual(["plan", "plan-note", "lint"]);
21
+ });
22
+
23
+ test("puts them inside jobs: when a key follows it", () => {
24
+ const text = GITHUB.replace(/\n$/, "") + "\nenv:\n A: b\n";
25
+ const out = mergeOwnJobs(text, "github", { lint: { "runs-on": "x" } }, { line: "# mine" });
26
+ expect(out).toContain(" - run: chant components pr-post prod\n # mine\n lint:\n runs-on: x\nenv:\n A: b\n");
27
+ });
28
+
29
+ test("puts them at the top level on GitLab", () => {
30
+ expect(mergeOwnJobs(GITLAB, "gitlab", { lint: { script: ["npm run lint"] } })).toBe(GITLAB + [OWN_JOBS_LINE, "lint:", " script:", " - npm run lint", ""].join("\n"));
31
+ });
32
+
33
+ test("refuses a name chant's file has, and a GitLab keyword", () => {
34
+ expect(() => mergeOwnJobs(GITHUB, "github", { plan: { "runs-on": "x" } })).toThrow(OwnJobsError);
35
+ expect(() => mergeOwnJobs(GITHUB, "github", { plan: { "runs-on": "x" } }, { where: "own.yml" })).toThrow(/own\.yml\.plan: chant's file has a job of that name/);
36
+ for (const name of ["variables", "workflow", "default", "pages"]) {
37
+ expect(() => mergeOwnJobs(GITLAB, "gitlab", { [name]: { script: ["x"] } })).toThrow(/GitLab reads .* as a keyword/);
38
+ }
39
+ // On GitHub a top-level GitLab keyword is a name like any other.
40
+ expect(mergeOwnJobs(GITHUB, "github", { variables: { "runs-on": "x" } })).toContain(" variables:\n");
41
+ });
42
+
43
+ test("an empty map, or none, leaves the file byte for byte", () => {
44
+ expect(mergeOwnJobs(GITHUB, "github", {})).toBe(GITHUB);
45
+ expect(mergeOwnJobs(GITLAB, "gitlab", undefined)).toBe(GITLAB);
46
+ });
47
+ });
48
+
49
+ describe("readOwnJobsFile", () => {
50
+ const dir = mkdtempSync(join(tmpdir(), "chant-own-jobs-"));
51
+
52
+ test("reads a map of jobs", () => {
53
+ writeFileSync(join(dir, "ok.yml"), "lint:\n runs-on: x\n");
54
+ expect(readOwnJobsFile(join(dir, "ok.yml"))).toEqual({ lint: { "runs-on": "x" } });
55
+ });
56
+
57
+ test("refuses a missing file, a list and an empty job", () => {
58
+ expect(() => readOwnJobsFile(join(dir, "none.yml"), "none.yml")).toThrow(/none\.yml: no such file/);
59
+ writeFileSync(join(dir, "list.yml"), "- a\n");
60
+ expect(() => readOwnJobsFile(join(dir, "list.yml"), "list.yml")).toThrow(/must be a map of job name to job/);
61
+ writeFileSync(join(dir, "empty.yml"), "lint: {}\n");
62
+ expect(() => readOwnJobsFile(join(dir, "empty.yml"), "empty.yml")).toThrow(/empty\.yml\.lint must be a job/);
63
+ });
64
+ });
65
+
66
+ describe("keepOwnJobs", () => {
67
+ const own = [" # The team's own check.", " audit:", " runs-on: ubuntu-latest", " steps:", " - run: npm audit # as written"].join("\n");
68
+ const previous = GITHUB.replace(" plan-note:", own + "\n plan-note:");
69
+
70
+ test("keeps a hand-added job as written, after chant's, and keeps it again the next time", () => {
71
+ const first = keepOwnJobs(previous, GITHUB, "github");
72
+ expect(first.kept).toEqual(["audit"]);
73
+ expect(first.text).toBe(GITHUB + [" " + OWN_JOBS_LINE, " audit:", " runs-on: ubuntu-latest", " steps:", " - run: npm audit # as written", ""].join("\n"));
74
+ expect(keepOwnJobs(first.text, GITHUB, "github").text).toBe(first.text);
75
+ });
76
+
77
+ test("drops a job that runs chant or the product's bin, and one the new file has", () => {
78
+ const old = previous + [" old-plan:", " steps:", " - run: npx --no-install plywood ci run plan", " older:", " steps:", " - run: plywood components pr-plan", " gone:", " steps:", " - run: chant lock"].join("\n") + "\n";
79
+ expect(keepOwnJobs(old, GITHUB, "github", { bins: ["npx --no-install plywood"] }).kept).toEqual(["audit"]);
80
+ // Without the bin, plywood's lines are the team's own.
81
+ expect(keepOwnJobs(old, GITHUB, "github").kept).toEqual(["audit", "old-plan", "older"]);
82
+ });
83
+
84
+ test("on GitLab keeps top-level jobs and never a keyword", () => {
85
+ const old = GITLAB + "cache:\n key: x\nlint:\n script:\n - npm run lint\n";
86
+ const kept = keepOwnJobs(old, GITLAB, "gitlab");
87
+ expect(kept.kept).toEqual(["lint"]);
88
+ expect(kept.text).toBe(GITLAB + `${OWN_JOBS_LINE}\nlint:\n script:\n - npm run lint\n`);
89
+ });
90
+
91
+ test("no old file, or no own job in it, leaves the file byte for byte", () => {
92
+ expect(keepOwnJobs(undefined, GITHUB, "github")).toEqual({ text: GITHUB, kept: [] });
93
+ expect(keepOwnJobs(GITHUB, GITHUB, "github")).toEqual({ text: GITHUB, kept: [] });
94
+ });
95
+
96
+ test("a job counts as generated by its chant or bin line, not by a word in a path", () => {
97
+ expect(isGeneratedJob(" - run: npm i @intentius/chant\n")).toBe(false);
98
+ expect(isGeneratedJob(' - run: "chant components pr-plan"')).toBe(true);
99
+ expect(isGeneratedJob(" - run: $(npm bin)/yodel plan", ["npx yodel"])).toBe(false);
100
+ expect(isGeneratedJob(" - run: yodel plan", ["npx yodel"])).toBe(true);
101
+ });
102
+ });
103
+
104
+ test("the ci-product entry carries both, and OWN_JOBS_FLOOR marks them", () => {
105
+ expect(ciProduct.OWN_JOBS_FLOOR).toBe("0.124.77");
106
+ expect(typeof ciProduct.mergeOwnJobs).toBe("function");
107
+ expect(typeof ciProduct.keepOwnJobs).toBe("function");
108
+ });