@intentius/chant 0.124.88 → 0.124.89

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 (303) hide show
  1. package/dist/actor.d.ts +36 -1
  2. package/dist/actor.d.ts.map +1 -1
  3. package/dist/actor.js +39 -1
  4. package/dist/chant-install.d.ts.map +1 -1
  5. package/dist/chant-install.js +1 -2
  6. package/dist/ci-base.d.ts +30 -0
  7. package/dist/ci-base.d.ts.map +1 -0
  8. package/dist/ci-base.js +33 -0
  9. package/dist/ci-comment-commands.d.ts +177 -0
  10. package/dist/ci-comment-commands.d.ts.map +1 -0
  11. package/dist/ci-comment-commands.js +325 -0
  12. package/dist/ci-comment-replies.d.ts +40 -0
  13. package/dist/ci-comment-replies.d.ts.map +1 -0
  14. package/dist/ci-comment-replies.js +59 -0
  15. package/dist/ci-evidence-from-job.d.ts +25 -0
  16. package/dist/ci-evidence-from-job.d.ts.map +1 -1
  17. package/dist/ci-evidence-from-job.js +43 -2
  18. package/dist/ci-evidence-jobs.d.ts +30 -1
  19. package/dist/ci-evidence-jobs.d.ts.map +1 -1
  20. package/dist/ci-evidence-jobs.js +46 -3
  21. package/dist/ci-image.d.ts +21 -4
  22. package/dist/ci-image.d.ts.map +1 -1
  23. package/dist/ci-image.js +62 -10
  24. package/dist/ci-note-commands.d.ts +63 -3
  25. package/dist/ci-note-commands.d.ts.map +1 -1
  26. package/dist/ci-note-commands.js +69 -35
  27. package/dist/ci-product-words.d.ts +42 -0
  28. package/dist/ci-product-words.d.ts.map +1 -1
  29. package/dist/ci-product-words.js +25 -0
  30. package/dist/ci-product.d.ts +31 -0
  31. package/dist/ci-product.d.ts.map +1 -1
  32. package/dist/ci-product.js +34 -4
  33. package/dist/cli/commands/build.d.ts.map +1 -1
  34. package/dist/cli/commands/build.js +29 -2
  35. package/dist/cli/handlers/approve.d.ts.map +1 -1
  36. package/dist/cli/handlers/approve.js +2 -1
  37. package/dist/cli/handlers/ci-check.d.ts +1 -1
  38. package/dist/cli/handlers/ci-check.d.ts.map +1 -1
  39. package/dist/cli/handlers/ci-check.js +17 -7
  40. package/dist/cli/handlers/ci-evidence.d.ts.map +1 -1
  41. package/dist/cli/handlers/ci-evidence.js +33 -7
  42. package/dist/cli/handlers/components.d.ts.map +1 -1
  43. package/dist/cli/handlers/components.js +3 -1
  44. package/dist/cli/handlers/generated-check.d.ts +8 -0
  45. package/dist/cli/handlers/generated-check.d.ts.map +1 -1
  46. package/dist/cli/handlers/generated-check.js +31 -1
  47. package/dist/cli/handlers/lock.d.ts.map +1 -1
  48. package/dist/cli/handlers/lock.js +121 -4
  49. package/dist/cli/handlers/pr-comment.d.ts +21 -0
  50. package/dist/cli/handlers/pr-comment.d.ts.map +1 -0
  51. package/dist/cli/handlers/pr-comment.js +112 -0
  52. package/dist/cli/handlers/pr-env.d.ts.map +1 -1
  53. package/dist/cli/handlers/pr-env.js +6 -3
  54. package/dist/cli/handlers/pr.d.ts +23 -1
  55. package/dist/cli/handlers/pr.d.ts.map +1 -1
  56. package/dist/cli/handlers/pr.js +55 -9
  57. package/dist/cli/handlers/promote.d.ts.map +1 -1
  58. package/dist/cli/handlers/promote.js +2 -1
  59. package/dist/cli/handlers/release.d.ts.map +1 -1
  60. package/dist/cli/handlers/release.js +11 -2
  61. package/dist/cli/handlers/run-wave.d.ts.map +1 -1
  62. package/dist/cli/handlers/run-wave.js +28 -2
  63. package/dist/cli/handlers/run.d.ts.map +1 -1
  64. package/dist/cli/handlers/run.js +2 -1
  65. package/dist/cli/main.d.ts.map +1 -1
  66. package/dist/cli/main.js +24 -2
  67. package/dist/cli/parse-args.d.ts.map +1 -1
  68. package/dist/cli/parse-args.js +16 -0
  69. package/dist/cli/registry.d.ts +11 -0
  70. package/dist/cli/registry.d.ts.map +1 -1
  71. package/dist/components/auto-release.d.ts.map +1 -1
  72. package/dist/components/auto-release.js +2 -1
  73. package/dist/components/pr-checks.d.ts +70 -6
  74. package/dist/components/pr-checks.d.ts.map +1 -1
  75. package/dist/components/pr-checks.js +74 -13
  76. package/dist/components/pr-pipeline.d.ts +16 -12
  77. package/dist/components/pr-pipeline.d.ts.map +1 -1
  78. package/dist/components/pr-pipeline.js +3 -11
  79. package/dist/components/product-pipeline.d.ts +42 -1
  80. package/dist/components/product-pipeline.d.ts.map +1 -1
  81. package/dist/components/product-pipeline.js +64 -12
  82. package/dist/components/product-plan.d.ts +190 -5
  83. package/dist/components/product-plan.d.ts.map +1 -1
  84. package/dist/components/product-plan.js +220 -39
  85. package/dist/drift-record.d.ts +7 -0
  86. package/dist/drift-record.d.ts.map +1 -1
  87. package/dist/drift-record.js +19 -0
  88. package/dist/floor-table.data.d.ts.map +1 -1
  89. package/dist/floor-table.data.js +54 -31
  90. package/dist/forge-check/contract.d.ts +11 -1
  91. package/dist/forge-check/contract.d.ts.map +1 -1
  92. package/dist/forge-check/contract.js +4 -1
  93. package/dist/forge-check/index.d.ts +2 -0
  94. package/dist/forge-check/index.d.ts.map +1 -1
  95. package/dist/forge-check/index.js +2 -0
  96. package/dist/gate-resume-run.d.ts +9 -1
  97. package/dist/gate-resume-run.d.ts.map +1 -1
  98. package/dist/gate-resume-run.js +26 -3
  99. package/dist/generated-check.d.ts +18 -4
  100. package/dist/generated-check.d.ts.map +1 -1
  101. package/dist/generated-check.js +37 -5
  102. package/dist/image-pins.d.ts +26 -0
  103. package/dist/image-pins.d.ts.map +1 -0
  104. package/dist/image-pins.js +19 -0
  105. package/dist/lexicon.d.ts +11 -0
  106. package/dist/lexicon.d.ts.map +1 -1
  107. package/dist/lifecycle/git.d.ts +11 -0
  108. package/dist/lifecycle/git.d.ts.map +1 -1
  109. package/dist/lifecycle/git.js +30 -3
  110. package/dist/lifecycle/publish-npm.d.ts +11 -0
  111. package/dist/lifecycle/publish-npm.d.ts.map +1 -1
  112. package/dist/lifecycle/publish-npm.js +27 -1
  113. package/dist/lifecycle/reach-locks.d.ts +131 -0
  114. package/dist/lifecycle/reach-locks.d.ts.map +1 -0
  115. package/dist/lifecycle/reach-locks.js +118 -0
  116. package/dist/lifecycle/release-cut.d.ts +3 -1
  117. package/dist/lifecycle/release-cut.d.ts.map +1 -1
  118. package/dist/lifecycle/release-cut.js +15 -0
  119. package/dist/lifecycle/release-images.d.ts.map +1 -1
  120. package/dist/lifecycle/release-images.js +1 -2
  121. package/dist/notify-product.d.ts +12 -3
  122. package/dist/notify-product.d.ts.map +1 -1
  123. package/dist/notify-product.js +10 -6
  124. package/dist/op/activities/source-release.d.ts.map +1 -1
  125. package/dist/op/activities/source-release.js +2 -1
  126. package/dist/op/activities/source-rollback.d.ts.map +1 -1
  127. package/dist/op/activities/source-rollback.js +2 -1
  128. package/dist/op/index.d.ts +2 -0
  129. package/dist/op/index.d.ts.map +1 -1
  130. package/dist/op/index.js +1 -0
  131. package/dist/op/op-waves-evidence-jobs.d.ts +6 -1
  132. package/dist/op/op-waves-evidence-jobs.d.ts.map +1 -1
  133. package/dist/op/op-waves-evidence-jobs.js +9 -3
  134. package/dist/op/op-waves-render-spec.d.ts +100 -0
  135. package/dist/op/op-waves-render-spec.d.ts.map +1 -0
  136. package/dist/op/op-waves-render-spec.js +162 -0
  137. package/dist/op/op-waves-run.d.ts +2 -0
  138. package/dist/op/op-waves-run.d.ts.map +1 -1
  139. package/dist/op/op-waves-run.js +2 -1
  140. package/dist/op/op-waves.d.ts +4 -0
  141. package/dist/op/op-waves.d.ts.map +1 -1
  142. package/dist/op/op-waves.js +4 -1
  143. package/dist/op/schedule-overdue.d.ts.map +1 -1
  144. package/dist/op/schedule-overdue.js +59 -3
  145. package/dist/op/wave-stop.d.ts +64 -0
  146. package/dist/op/wave-stop.d.ts.map +1 -0
  147. package/dist/op/wave-stop.js +127 -0
  148. package/dist/planned-files.d.ts +76 -0
  149. package/dist/planned-files.d.ts.map +1 -0
  150. package/dist/planned-files.js +108 -0
  151. package/dist/pr-forge-job.d.ts +22 -0
  152. package/dist/pr-forge-job.d.ts.map +1 -0
  153. package/dist/pr-forge-job.js +46 -0
  154. package/dist/pr-loop.d.ts +3 -6
  155. package/dist/pr-loop.d.ts.map +1 -1
  156. package/dist/pr-loop.js +4 -81
  157. package/dist/pr-plan-note.d.ts +97 -0
  158. package/dist/pr-plan-note.d.ts.map +1 -1
  159. package/dist/pr-plan-note.js +94 -1
  160. package/dist/pr-post.d.ts +28 -3
  161. package/dist/pr-post.d.ts.map +1 -1
  162. package/dist/pr-post.js +145 -13
  163. package/dist/pr-status.d.ts +16 -0
  164. package/dist/pr-status.d.ts.map +1 -0
  165. package/dist/pr-status.js +90 -0
  166. package/dist/ref-gate-init.d.ts +16 -2
  167. package/dist/ref-gate-init.d.ts.map +1 -1
  168. package/dist/ref-gate-init.js +24 -13
  169. package/dist/release-floors.d.ts +37 -1
  170. package/dist/release-floors.d.ts.map +1 -1
  171. package/dist/release-floors.js +61 -25
  172. package/dist/render-module.d.ts +15 -0
  173. package/dist/render-module.d.ts.map +1 -0
  174. package/dist/render-module.js +73 -0
  175. package/dist/state-migration.d.ts.map +1 -1
  176. package/dist/state-migration.js +1 -2
  177. package/dist/wave-runtime.mjs +304 -301
  178. package/dist/workspace/ci-green-cli.d.ts.map +1 -1
  179. package/dist/workspace/ci-green-cli.js +3 -2
  180. package/dist/workspace/release-train.d.ts.map +1 -1
  181. package/dist/workspace/release-train.js +2 -1
  182. package/dist/workspace/release-workflow.d.ts +4 -3
  183. package/dist/workspace/release-workflow.d.ts.map +1 -1
  184. package/dist/workspace/release-workflow.js +10 -7
  185. package/dist/workspace/trust/check-evidence-report.d.ts +7 -2
  186. package/dist/workspace/trust/check-evidence-report.d.ts.map +1 -1
  187. package/dist/workspace/trust/check-evidence-report.js +15 -8
  188. package/dist/workspace/trust/ref-gate-cli.d.ts +10 -1
  189. package/dist/workspace/trust/ref-gate-cli.d.ts.map +1 -1
  190. package/dist/workspace/trust/ref-gate-cli.js +30 -10
  191. package/dist/workspace/workspace-run.d.ts.map +1 -1
  192. package/dist/workspace/workspace-run.js +2 -1
  193. package/package.json +1 -1
  194. package/src/actor.test.ts +68 -2
  195. package/src/actor.ts +61 -1
  196. package/src/chant-install.test.ts +2 -3
  197. package/src/chant-install.ts +1 -2
  198. package/src/ci-base.test.ts +41 -0
  199. package/src/ci-base.ts +43 -0
  200. package/src/ci-comment-commands.test.ts +376 -0
  201. package/src/ci-comment-commands.ts +389 -0
  202. package/src/ci-comment-replies.ts +78 -0
  203. package/src/ci-commit.test.ts +2 -3
  204. package/src/ci-evidence-from-job.test.ts +18 -0
  205. package/src/ci-evidence-from-job.ts +58 -2
  206. package/src/ci-evidence-jobs.ts +50 -5
  207. package/src/ci-image.test.ts +130 -9
  208. package/src/ci-image.ts +85 -12
  209. package/src/ci-note-commands.ts +104 -41
  210. package/src/ci-product-words.ts +59 -0
  211. package/src/ci-product.ts +40 -4
  212. package/src/cli/commands/build.test.ts +41 -0
  213. package/src/cli/commands/build.ts +27 -2
  214. package/src/cli/handlers/approve.ts +2 -1
  215. package/src/cli/handlers/ci-check.ts +19 -7
  216. package/src/cli/handlers/ci-evidence.ts +29 -8
  217. package/src/cli/handlers/components.ts +3 -1
  218. package/src/cli/handlers/generated-check.ts +31 -1
  219. package/src/cli/handlers/lock-reach.test.ts +103 -0
  220. package/src/cli/handlers/lock.ts +100 -4
  221. package/src/cli/handlers/pr-comment.ts +104 -0
  222. package/src/cli/handlers/pr-env.ts +6 -3
  223. package/src/cli/handlers/pr-record.test.ts +1 -1
  224. package/src/cli/handlers/pr.ts +50 -10
  225. package/src/cli/handlers/promote.ts +2 -1
  226. package/src/cli/handlers/release.e2e.test.ts +35 -0
  227. package/src/cli/handlers/release.ts +14 -2
  228. package/src/cli/handlers/run-wave.ts +28 -2
  229. package/src/cli/handlers/run.ts +2 -1
  230. package/src/cli/main.ts +24 -2
  231. package/src/cli/parse-args.ts +12 -0
  232. package/src/cli/registry.ts +11 -0
  233. package/src/components/auto-release.ts +2 -1
  234. package/src/components/pr-checks.ts +112 -17
  235. package/src/components/pr-pipeline.ts +17 -15
  236. package/src/components/product-pipeline.ts +93 -11
  237. package/src/components/product-plan.test.ts +40 -2
  238. package/src/components/product-plan.ts +331 -45
  239. package/src/drift-record.test.ts +20 -0
  240. package/src/drift-record.ts +16 -0
  241. package/src/floor-table.data.ts +54 -31
  242. package/src/forge-check/contract.ts +12 -1
  243. package/src/forge-check/forge-check.test.ts +17 -0
  244. package/src/forge-check/index.ts +2 -0
  245. package/src/gate-resume-run.ts +27 -3
  246. package/src/generated-check.e2e.test.ts +21 -1
  247. package/src/generated-check.test.ts +66 -0
  248. package/src/generated-check.ts +51 -10
  249. package/src/image-pins.ts +31 -0
  250. package/src/lexicon.ts +11 -0
  251. package/src/lifecycle/git.test.ts +48 -0
  252. package/src/lifecycle/git.ts +27 -4
  253. package/src/lifecycle/publish-npm.ts +31 -1
  254. package/src/lifecycle/reach-locks.test.ts +87 -0
  255. package/src/lifecycle/reach-locks.ts +169 -0
  256. package/src/lifecycle/release-cut.ts +17 -1
  257. package/src/lifecycle/release-images.test.ts +56 -0
  258. package/src/lifecycle/release-images.ts +1 -2
  259. package/src/notify-product.ts +19 -8
  260. package/src/op/activities/source-release.ts +2 -1
  261. package/src/op/activities/source-rollback.ts +2 -1
  262. package/src/op/gate-resume.test.ts +27 -0
  263. package/src/op/index.ts +10 -0
  264. package/src/op/op-waves-evidence-jobs.ts +10 -4
  265. package/src/op/op-waves-notify-words.test.ts +18 -0
  266. package/src/op/op-waves-render-spec.test.ts +160 -0
  267. package/src/op/op-waves-render-spec.ts +171 -0
  268. package/src/op/op-waves-run.ts +2 -1
  269. package/src/op/op-waves.ts +5 -2
  270. package/src/op/schedule-overdue.test.ts +43 -0
  271. package/src/op/schedule-overdue.ts +57 -3
  272. package/src/op/wave-stop.test.ts +72 -0
  273. package/src/op/wave-stop.ts +137 -0
  274. package/src/planned-files.test.ts +80 -0
  275. package/src/planned-files.ts +134 -0
  276. package/src/pr-forge-job.test.ts +53 -0
  277. package/src/pr-forge-job.ts +46 -0
  278. package/src/pr-loop-narrowed.test.ts +2 -1
  279. package/src/pr-loop-words.test.ts +2 -1
  280. package/src/pr-loop.test.ts +1 -2
  281. package/src/pr-loop.ts +4 -80
  282. package/src/pr-plan-note.ts +155 -3
  283. package/src/pr-post-replan.test.ts +144 -0
  284. package/src/pr-post-subject.test.ts +230 -0
  285. package/src/pr-post.test.ts +2 -1
  286. package/src/pr-post.ts +150 -15
  287. package/src/pr-status.ts +91 -0
  288. package/src/ref-gate-init.ts +30 -11
  289. package/src/release-floors.ts +78 -25
  290. package/src/render-module.ts +73 -0
  291. package/src/state-migration-record.test.ts +2 -3
  292. package/src/state-migration.ts +1 -2
  293. package/src/workspace/ci-green-cli.ts +3 -2
  294. package/src/workspace/ci-green-workflow.test.ts +32 -1
  295. package/src/workspace/release-train.ts +2 -1
  296. package/src/workspace/release-workflow.test.ts +36 -5
  297. package/src/workspace/release-workflow.ts +10 -7
  298. package/src/workspace/trust/check-evidence-report.ts +15 -8
  299. package/src/workspace/trust/check-evidence.test.ts +5 -0
  300. package/src/workspace/trust/ref-gate-cli.ts +30 -8
  301. package/src/workspace/trust/ref-gate-pieces.test.ts +46 -1
  302. package/src/workspace/trust/ref-gate.test.ts +10 -0
  303. package/src/workspace/workspace-run.ts +2 -1
@@ -213,9 +213,61 @@ function yamlDocs(repoRoot: string, path: string): Record<string, unknown>[] {
213
213
 
214
214
  /** When `path` was first committed (ISO 8601), if the checkout's history has it. */
215
215
  export function fileAdded(repoRoot: string, path: string): string | undefined {
216
- const r = spawnSync("git", ["-C", repoRoot, "log", "--format=%cI", "--diff-filter=A", "--", path], { encoding: "utf-8" });
216
+ return addedCommit(repoRoot, path)?.at;
217
+ }
218
+
219
+ /** The oldest commit the checkout's history says added `path`, with its commit time. */
220
+ function addedCommit(repoRoot: string, path: string): { sha: string; at: string } | undefined {
221
+ const r = spawnSync("git", ["-C", repoRoot, "log", "--format=%H %cI", "--diff-filter=A", "--", path], { encoding: "utf-8" });
217
222
  if (r.status !== 0) return undefined;
218
- return r.stdout.trim().split("\n").filter(Boolean).pop();
223
+ const last = r.stdout.trim().split("\n").filter(Boolean).pop();
224
+ if (!last) return undefined;
225
+ const [sha, at] = last.split(" ");
226
+ return sha && at ? { sha, at } : undefined;
227
+ }
228
+
229
+ /**
230
+ * The commits a shallow checkout's history stops at (#4952), from git's
231
+ * `shallow` file. Empty for a full clone.
232
+ */
233
+ function shallowBoundary(repoRoot: string): Set<string> {
234
+ const r = spawnSync("git", ["-C", repoRoot, "rev-parse", "--path-format=absolute", "--git-path", "shallow"], { encoding: "utf-8" });
235
+ if (r.status !== 0) return new Set();
236
+ try {
237
+ return new Set(readFileSync(r.stdout.trim(), "utf-8").split("\n").map((l) => l.trim()).filter(Boolean));
238
+ } catch {
239
+ return new Set();
240
+ }
241
+ }
242
+
243
+ /** How long the check waits for the fetch that deepens a shallow checkout. */
244
+ const DEEPEN_TIMEOUT_MS = 120_000;
245
+
246
+ /**
247
+ * When `path` was added, read so a shallow checkout does not under-report
248
+ * (#4952). A CI checkout is often shallow, and its oldest commit lists
249
+ * every file as added, so a job that never ran would count from that
250
+ * commit. When the commit found is at the shallow boundary, the check
251
+ * fetches the rest of the history once per run (`git fetch --unshallow`,
252
+ * with the job's own credentials) and reads the file again. When that fetch
253
+ * fails, the boundary's time is still a lower bound, so the check counts
254
+ * from it and says so in the log.
255
+ */
256
+ function addedDate(repoRoot: string, path: string, op: string, state: { deepened?: boolean; failed?: string }, log: (line: string) => void): string | undefined {
257
+ let found = addedCommit(repoRoot, path);
258
+ if (!found || !shallowBoundary(repoRoot).has(found.sha)) return found?.at;
259
+ if (!state.deepened) {
260
+ state.deepened = true;
261
+ const r = spawnSync("git", ["-C", repoRoot, "fetch", "--quiet", "--unshallow"], { encoding: "utf-8", timeout: DEEPEN_TIMEOUT_MS });
262
+ if (r.status !== 0) state.failed = (r.stderr || r.error?.message || `git fetch exited ${r.status}`).trim().split("\n")[0];
263
+ // A checkout with no remote answers 0 and stays shallow.
264
+ else if (shallowBoundary(repoRoot).size > 0) state.failed = "git fetch --unshallow left it shallow";
265
+ found = addedCommit(repoRoot, path) ?? found;
266
+ }
267
+ if (state.failed !== undefined && shallowBoundary(repoRoot).has(found.sha)) {
268
+ log(`schedule check: the checkout is shallow and its history could not be fetched, so Op ${op} counts from its oldest commit, ${found.at.slice(0, 10)}: ${state.failed}`);
269
+ }
270
+ return found.at;
219
271
  }
220
272
 
221
273
  const HINT: Record<ForgeKind, string> = {
@@ -278,6 +330,8 @@ export async function checkOverdueOps(input: {
278
330
  if (!forge.scheduledRuns) return [];
279
331
  const log = (line: string): void => input.log(`${input.logPrefix ?? ""}${line}`);
280
332
  const out: OverdueOp[] = [];
333
+ // One fetch at most per check, however many Ops count from a shallow boundary (#4952).
334
+ const history: { deepened?: boolean; failed?: string } = {};
281
335
  for (const watch of input.watches) {
282
336
  const file = opPipelineFile(input.repoRoot, forge.kind, watch, input.member);
283
337
  if (!file) continue;
@@ -288,7 +342,7 @@ export async function checkOverdueOps(input: {
288
342
  log(`schedule check: ${forge.kind} did not say when Op ${watch.op} last ran, so it is not checked: ${(err instanceof Error ? err.message : String(err)).split("\n")[0]}`);
289
343
  continue;
290
344
  }
291
- const found = overdueVerdict(watch, forge.kind, runs, runs.last ? undefined : fileAdded(input.repoRoot, file), input.now);
345
+ const found = overdueVerdict(watch, forge.kind, runs, runs.last ? undefined : addedDate(input.repoRoot, file, watch.op, history, log), input.now);
292
346
  if (found) {
293
347
  log(found.message);
294
348
  out.push(input.label ? { ...found, message: `${input.label}${found.message}` } : found);
@@ -0,0 +1,72 @@
1
+ /**
2
+ * #4979: the wave stop a comment writes before a re-run, `_waves/<op>.stops.json`
3
+ * on `chant/lifecycle`, and what a wave job says when it waits behind it.
4
+ */
5
+ import { describe, expect, test } from "vitest";
6
+ import { execFileSync } from "node:child_process";
7
+ import { mkdtempSync, realpathSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { parseWaveStops, renderWaveStops, setWaveStop, waveStopAt, waveStopLine, waveStopped, WAVE_STOPS_KEPT } from "./wave-stop";
11
+
12
+ const SHA = "a".repeat(40);
13
+
14
+ function git(cwd: string, ...args: string[]): string {
15
+ return execFileSync("git", args, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }).trim();
16
+ }
17
+
18
+ function initRepo(): string {
19
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), "chant-wave-stop-")));
20
+ git(dir, "init", "-q", "-b", "main");
21
+ git(dir, "config", "user.email", "test@chant.dev");
22
+ git(dir, "config", "user.name", "Test");
23
+ git(dir, "config", "commit.gpgsign", "false");
24
+ writeFileSync(join(dir, "README.md"), "# t\n");
25
+ git(dir, "add", "README.md");
26
+ git(dir, "commit", "-q", "-m", "init");
27
+ return dir;
28
+ }
29
+
30
+ describe("the stops file (#4979)", () => {
31
+ test("reads back what it wrote, drops what is not a stop, and keeps the newest", () => {
32
+ const file = { version: 1 as const, stops: { [SHA]: { through: 2, at: "2026-11-10T00:00:00.000Z", by: "alice", pr: 12 } } };
33
+ expect(parseWaveStops(renderWaveStops(file))).toEqual(file);
34
+ expect(parseWaveStops('{"version":1,"stops":{"nope":{"through":1,"at":"x"},"' + SHA + '":{"through":0,"at":"x"}}}')).toEqual({ version: 1, stops: {} });
35
+ expect(parseWaveStops("not json")).toEqual({ version: 1, stops: {} });
36
+ const many = { version: 1 as const, stops: Object.fromEntries(Array.from({ length: WAVE_STOPS_KEPT + 5 }, (_, i) => [i.toString(16).padStart(40, "0"), { through: 1, at: `2026-11-10T00:00:${String(i).padStart(2, "0")}.000Z` }])) };
37
+ const kept = parseWaveStops(renderWaveStops(many)).stops;
38
+ expect(Object.keys(kept)).toHaveLength(WAVE_STOPS_KEPT);
39
+ expect(kept["0".repeat(40)]).toBeUndefined();
40
+ });
41
+
42
+ test("a wave after the stop waits, and the stop's own wave runs", () => {
43
+ const stop = { through: 2, at: "x" };
44
+ expect(waveStopped(stop, 2)).toBe(false);
45
+ expect(waveStopped(stop, 3)).toBe(true);
46
+ expect(waveStopped(undefined, 9)).toBe(false);
47
+ });
48
+ });
49
+
50
+ describe("a stop on chant/lifecycle (#4979)", () => {
51
+ test("is written for a commit, read by the wave job at that commit, and cleared", async () => {
52
+ const dir = initRepo();
53
+ const head = git(dir, "rev-parse", "HEAD");
54
+ expect(await waveStopLine("tf-apply", 3, { cwd: dir })).toBeUndefined();
55
+ expect(await setWaveStop("tf-apply", head, { through: 2, at: "2026-11-10T00:00:00.000Z", by: "alice", pr: 12 }, { cwd: dir })).toEqual({ changed: true, pushed: false });
56
+ expect(await waveStopAt("tf-apply", head, { cwd: dir })).toEqual({ through: 2, at: "2026-11-10T00:00:00.000Z", by: "alice", pr: 12 });
57
+ expect(git(dir, "show", "chant/lifecycle:_waves/tf-apply.stops.json")).toContain('"through": 2');
58
+ expect(await waveStopLine("tf-apply", 2, { cwd: dir })).toBeUndefined();
59
+ expect(await waveStopLine("tf-apply", 3, { cwd: dir })).toBe(`wave 3 waits: alice's comment on pull request 12 ran tf-apply again at ${head.slice(0, 12)} through wave 2; comment the apply again without a wave to run the waves after it`);
60
+ // Another op's waves, and another commit, are not stopped.
61
+ expect(await waveStopLine("other", 3, { cwd: dir })).toBeUndefined();
62
+ expect(await waveStopAt("tf-apply", SHA, { cwd: dir })).toBeUndefined();
63
+ expect(await setWaveStop("tf-apply", head, null, { cwd: dir })).toEqual({ changed: true, pushed: false });
64
+ expect(await waveStopLine("tf-apply", 3, { cwd: dir })).toBeUndefined();
65
+ expect(await setWaveStop("tf-apply", head, null, { cwd: dir })).toEqual({ changed: false, pushed: false });
66
+ });
67
+
68
+ test("refuses an op or a commit that is not one", async () => {
69
+ await expect(setWaveStop("a b", SHA, null)).rejects.toThrow(/not a stops file name/);
70
+ await expect(setWaveStop("tf-apply", "main", null)).rejects.toThrow(/not a commit sha/);
71
+ });
72
+ });
@@ -0,0 +1,137 @@
1
+ /**
2
+ * A wave stop on a re-run (#4979): `/<product> apply wave-<n>` on a merged
3
+ * pull request runs its apply again and stops after wave n.
4
+ *
5
+ * A forge re-run cannot be told where to stop: GitHub's re-run of a run's
6
+ * failed jobs runs every job after them, Forgejo's dispatch runs the whole
7
+ * workflow, and GitLab runs the jobs after a retried one by itself. So the
8
+ * comment's job writes the stop on `chant/lifecycle` before it starts the
9
+ * run, `_waves/<op>.stops.json`, keyed by the commit the run applies, and
10
+ * each wave job of op `<op>` at that commit reads it before it plans: a wave
11
+ * after the stop waits, as a wave whose gate has no approval waits (exit 3),
12
+ * so a later `/<product> apply` runs it. An apply comment without a wave
13
+ * clears the commit's stop. The newest {@link WAVE_STOPS_KEPT} stops are
14
+ * kept.
15
+ */
16
+
17
+ import { fetchLifecycleStatus, getHeadCommit, pushLifecycleStatus, readBlobBySha, readPathSha, writeBlobToPath } from "../lifecycle/git";
18
+
19
+ /** The directory of the stops on `chant/lifecycle`. */
20
+ export const WAVE_STOPS_DIR = "_waves";
21
+
22
+ /** How many commits' stops the file keeps. */
23
+ export const WAVE_STOPS_KEPT = 50;
24
+
25
+ /** The stops file of op `op`. */
26
+ export function waveStopsFile(op: string): string {
27
+ return `${op}.stops.json`;
28
+ }
29
+
30
+ /** One commit's stop: the last wave that runs, and who asked. */
31
+ export interface WaveStop {
32
+ through: number;
33
+ at: string;
34
+ by?: string;
35
+ pr?: number;
36
+ }
37
+
38
+ /** The stops file. */
39
+ export interface WaveStopsFile {
40
+ version: 1;
41
+ stops: Record<string, WaveStop>;
42
+ }
43
+
44
+ const SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
45
+ const OP = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/;
46
+
47
+ /** Read a stops file; anything that is not one reads as no stops, and a malformed entry is dropped. */
48
+ export function parseWaveStops(text: string | null): WaveStopsFile {
49
+ let doc: unknown;
50
+ try {
51
+ doc = JSON.parse(text ?? "null");
52
+ } catch {
53
+ return { version: 1, stops: {} };
54
+ }
55
+ const stops: Record<string, WaveStop> = {};
56
+ const given = doc && typeof doc === "object" && (doc as { version?: unknown }).version === 1 ? (doc as { stops?: unknown }).stops : undefined;
57
+ if (given && typeof given === "object") {
58
+ for (const [sha, s] of Object.entries(given as Record<string, unknown>)) {
59
+ const v = s as Partial<WaveStop> | null;
60
+ if (!SHA.test(sha) || !v || !Number.isInteger(v.through) || (v.through as number) < 1 || typeof v.at !== "string") continue;
61
+ stops[sha] = { through: v.through as number, at: v.at, ...(typeof v.by === "string" ? { by: v.by } : {}), ...(Number.isInteger(v.pr) ? { pr: v.pr as number } : {}) };
62
+ }
63
+ }
64
+ return { version: 1, stops };
65
+ }
66
+
67
+ /** The file's text: the newest {@link WAVE_STOPS_KEPT} stops, by commit. */
68
+ export function renderWaveStops(file: WaveStopsFile): string {
69
+ const newest = Object.entries(file.stops).sort((a, b) => b[1].at.localeCompare(a[1].at)).slice(0, WAVE_STOPS_KEPT);
70
+ return `${JSON.stringify({ version: 1, stops: Object.fromEntries(newest.sort((a, b) => a[0].localeCompare(b[0]))) }, null, 2)}\n`;
71
+ }
72
+
73
+ /** Whether wave `k` waits under `stop`. */
74
+ export function waveStopped(stop: WaveStop | undefined, k: number): boolean {
75
+ return stop !== undefined && k > stop.through;
76
+ }
77
+
78
+ /** The stop of op `op` at commit `sha`, from the local `chant/lifecycle` after a fetch. Undefined when there is none or the branch cannot be read. */
79
+ export async function waveStopAt(op: string, sha: string, opts: { cwd?: string } = {}): Promise<WaveStop | undefined> {
80
+ if (!OP.test(op) || !SHA.test(sha)) return undefined;
81
+ await fetchLifecycleStatus(opts);
82
+ const blob = await readPathSha(WAVE_STOPS_DIR, waveStopsFile(op), opts);
83
+ if (!blob) return undefined;
84
+ return parseWaveStops(await readBlobBySha(blob, opts)).stops[sha];
85
+ }
86
+
87
+ /**
88
+ * What a wave job of op `op` says when wave `k` waits behind a comment's
89
+ * stop at the job's checkout (`git rev-parse HEAD`). Undefined when it runs:
90
+ * no stop, no commit to read, or a branch that cannot be read, so a stop
91
+ * never fails a wave that would have run.
92
+ */
93
+ export async function waveStopLine(op: string, k: number, opts: { cwd?: string } = {}): Promise<string | undefined> {
94
+ let sha: string;
95
+ try {
96
+ sha = await getHeadCommit(opts);
97
+ } catch {
98
+ return undefined;
99
+ }
100
+ let stop: WaveStop | undefined;
101
+ try {
102
+ stop = await waveStopAt(op, sha, opts);
103
+ } catch {
104
+ return undefined;
105
+ }
106
+ if (!waveStopped(stop, k)) return undefined;
107
+ const who = stop!.by ? `${stop!.by}'s` : "a";
108
+ const where = stop!.pr !== undefined ? ` on pull request ${stop!.pr}` : "";
109
+ return `wave ${k} waits: ${who} comment${where} ran ${op} again at ${sha.slice(0, 12)} through wave ${stop!.through}; comment the apply again without a wave to run the waves after it`;
110
+ }
111
+
112
+ /**
113
+ * Set op `op`'s stop at commit `sha`, or clear it (`stop` null), and push
114
+ * `chant/lifecycle`. Read, written and pushed again when another writer
115
+ * pushed first, up to three times.
116
+ */
117
+ export async function setWaveStop(op: string, sha: string, stop: WaveStop | null, opts: { cwd?: string } = {}): Promise<{ changed: boolean; pushed: boolean }> {
118
+ if (!OP.test(op)) throw new Error(`the op name ${JSON.stringify(op)} is not a stops file name`);
119
+ if (!SHA.test(sha)) throw new Error(`${JSON.stringify(sha)} is not a commit sha`);
120
+ for (let attempt = 1; attempt <= 3; attempt++) {
121
+ const fetched = await fetchLifecycleStatus(opts);
122
+ if (fetched.status === "unreachable") throw new Error("chant/lifecycle could not be fetched, so the stop was not written");
123
+ const blob = await readPathSha(WAVE_STOPS_DIR, waveStopsFile(op), opts);
124
+ const file = parseWaveStops(blob ? await readBlobBySha(blob, opts) : null);
125
+ const next: WaveStopsFile = { version: 1, stops: { ...file.stops } };
126
+ if (stop) next.stops[sha] = stop;
127
+ else delete next.stops[sha];
128
+ if (renderWaveStops(next) === renderWaveStops(file)) return { changed: false, pushed: false };
129
+ const what = stop ? `Stop ${op} after wave ${stop.through} at ${sha.slice(0, 12)}` : `Clear the stop of ${op} at ${sha.slice(0, 12)}`;
130
+ await writeBlobToPath(WAVE_STOPS_DIR, waveStopsFile(op), renderWaveStops(next), what, { ...opts, expectPriorPathSha: blob });
131
+ const pushed = await pushLifecycleStatus(opts);
132
+ if (pushed.status === "stale") continue;
133
+ if (pushed.status === "failed") throw new Error(`could not push the stop to chant/lifecycle (${pushed.stderr.trim()})`);
134
+ return { changed: true, pushed: pushed.status === "pushed" };
135
+ }
136
+ throw new Error("chant/lifecycle kept moving, so the stop was not written; comment again");
137
+ }
@@ -0,0 +1,80 @@
1
+ /** #4966: a product's planned files with their modes, and its stale generated files found by header. */
2
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { describe, expect, test } from "vitest";
6
+ import { planFile, planRemoval, staleGeneratedFiles, writePlannedFiles } from "./planned-files";
7
+
8
+ const dir = (): string => mkdtempSync(join(tmpdir(), "chant-planned-"));
9
+ const modeOf = (p: string): number => statSync(p).mode & 0o777;
10
+
11
+ describe("planFile and writePlannedFiles", () => {
12
+ test("plans against the disk, writes the plan with its modes, and leaves an unchanged file alone", () => {
13
+ const root = dir();
14
+ const script = join(root, "bin", "run.sh");
15
+ const config = join(root, "tool.yml");
16
+ writeFileSync(config, "a: 1\n");
17
+ const plan = [planFile(script, "#!/bin/sh\n", { mode: 0o755 }), planFile(config, "a: 1\n"), planFile(join(root, "new.txt"), "new\n")];
18
+ expect(plan.map((f) => f.status)).toEqual(["created", "unchanged", "created"]);
19
+ writePlannedFiles(plan);
20
+ expect(readFileSync(script, "utf-8")).toBe("#!/bin/sh\n");
21
+ expect(modeOf(script)).toBe(0o755);
22
+ expect(readFileSync(join(root, "new.txt"), "utf-8")).toBe("new\n");
23
+ expect(planFile(script, "#!/bin/sh\n", { mode: 0o755 }).status).toBe("unchanged");
24
+ });
25
+
26
+ test("a file whose content is the same and whose mode is not is updated", () => {
27
+ const root = dir();
28
+ const script = join(root, "run.sh");
29
+ writeFileSync(script, "#!/bin/sh\n");
30
+ chmodSync(script, 0o644);
31
+ const plan = planFile(script, "#!/bin/sh\n", { mode: 0o755, local: true });
32
+ expect(plan).toEqual({ path: script, status: "updated", content: "#!/bin/sh\n", mode: 0o755, local: true });
33
+ writePlannedFiles([plan]);
34
+ expect(modeOf(script)).toBe(0o755);
35
+ });
36
+
37
+ test("a removal is planned only for a file that is there, and written by unlinking it", () => {
38
+ const root = dir();
39
+ const old = join(root, "old.yml");
40
+ writeFileSync(old, "x\n");
41
+ expect(planRemoval(join(root, "absent.yml"))).toBeUndefined();
42
+ const removal = planRemoval(old)!;
43
+ expect(removal.status).toBe("removed");
44
+ writePlannedFiles([removal, removal]);
45
+ expect(existsSync(old)).toBe(false);
46
+ });
47
+ });
48
+
49
+ describe("staleGeneratedFiles", () => {
50
+ const HEADER = "# Rendered by tool ci from tool.config.ts.";
51
+
52
+ test("lists the files that open with the header and are not rendered now, never a person's own", () => {
53
+ const root = dir();
54
+ mkdirSync(join(root, ".github", "workflows"), { recursive: true });
55
+ mkdirSync(join(root, ".forgejo", "workflows"), { recursive: true });
56
+ writeFileSync(join(root, ".github/workflows/tool-pr.yml"), `${HEADER}\non: pull_request\n`);
57
+ writeFileSync(join(root, ".github/workflows/tool-old.yml"), `${HEADER}\r\non: push\n`);
58
+ writeFileSync(join(root, ".github/workflows/mine.yml"), "# my own\non: push\n");
59
+ writeFileSync(join(root, ".github/workflows/notes.md"), `${HEADER}\n`);
60
+ writeFileSync(join(root, ".forgejo/workflows/tool-pr.yml"), `${HEADER}\n`);
61
+ writeFileSync(join(root, ".gitlab-ci.yml"), `${HEADER}\n`);
62
+ const stale = staleGeneratedFiles({
63
+ root,
64
+ dirs: [".github/workflows", ".forgejo/workflows", ".gitlab"],
65
+ files: [".gitlab-ci.yml"],
66
+ match: /\.ya?ml$/,
67
+ header: HEADER,
68
+ rendered: [".github/workflows/tool-pr.yml"],
69
+ });
70
+ expect(stale).toEqual([".gitlab-ci.yml", ".github/workflows/tool-old.yml", ".forgejo/workflows/tool-pr.yml"]);
71
+ });
72
+
73
+ test("takes a test of the text in place of the header line", () => {
74
+ const root = dir();
75
+ writeFileSync(join(root, "a.yml"), "# generated by tool\n");
76
+ writeFileSync(join(root, "b.yml"), "# hand-written\n");
77
+ expect(staleGeneratedFiles({ root, dirs: ["."], header: (t) => t.includes("generated by tool"), rendered: [] })).toEqual(["a.yml"]);
78
+ expect(staleGeneratedFiles({ root, files: ["a.yml", "b.yml", "c.yml"], header: (t) => t.includes("generated by tool"), rendered: [] })).toEqual(["a.yml"]);
79
+ });
80
+ });
@@ -0,0 +1,134 @@
1
+ /**
2
+ * `@intentius/chant/planned-files` (#4966): the files a product's init or
3
+ * render plans, written in one call, and the generated files it no longer
4
+ * renders.
5
+ *
6
+ * Each product carried its own: terragucci's `init.ts` plans a
7
+ * `FileChange` per file and writes or unlinks them in a loop, with a
8
+ * `chmodSync` beside its image recipe's writes; plywood's `init.ts` `put`
9
+ * writes a file when it differs; sql-yodeler's `yodel ci` finds the
10
+ * pipeline files that open with its header and removes the ones it no
11
+ * longer renders (its #348).
12
+ *
13
+ * - {@link planFile} plans one file against what is on disk, its mode
14
+ * included, and writes nothing, so a dry run prints the plan as it is.
15
+ * - {@link planRemoval} plans the removal of a file an earlier run wrote.
16
+ * - {@link writePlannedFiles} writes the plan: each directory made, each
17
+ * file's mode set, each removed file unlinked, an unchanged one left as
18
+ * it is.
19
+ * - {@link staleGeneratedFiles} lists the files under some directories that
20
+ * open with a product's header and that the product no longer renders.
21
+ *
22
+ * `@intentius/chant/ref-gate-init` writes its plan with
23
+ * {@link writePlannedFiles}.
24
+ *
25
+ * This module imports only Node's own modules.
26
+ */
27
+
28
+ import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
29
+ import { dirname, join } from "node:path";
30
+
31
+ /** One planned file. */
32
+ export interface PlannedFile {
33
+ /** Where it is written. Absolute, or relative to the process's directory. */
34
+ path: string;
35
+ /** `removed`: a file an earlier run wrote that this one no longer asks for. */
36
+ status: "created" | "updated" | "unchanged" | "removed";
37
+ /** The text to write; empty for a removal. */
38
+ content: string;
39
+ /** The permission bits to set, such as `0o755` for a script. Unset, a new file gets the process's default and an existing one keeps its own. */
40
+ mode?: number;
41
+ /** In the git directory or otherwise never committed, such as a hook. */
42
+ local?: boolean;
43
+ }
44
+
45
+ /** The permission bits of the file at `path`, or undefined when there is none. */
46
+ function modeOf(path: string): number | undefined {
47
+ try {
48
+ return statSync(path).mode & 0o777;
49
+ } catch {
50
+ return undefined;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Plan `content` at `path`: `created` when there is no file, `unchanged`
56
+ * when the file holds the content (and, with `mode`, has that mode),
57
+ * `updated` otherwise. Writes nothing.
58
+ */
59
+ export function planFile(path: string, content: string, extra: Pick<PlannedFile, "mode" | "local"> = {}): PlannedFile {
60
+ const own = { ...(extra.mode !== undefined ? { mode: extra.mode } : {}), ...(extra.local ? { local: true } : {}) };
61
+ if (!existsSync(path)) return { path, status: "created", content, ...own };
62
+ const same = readFileSync(path, "utf-8") === content && (extra.mode === undefined || modeOf(path) === extra.mode);
63
+ return { path, status: same ? "unchanged" : "updated", content, ...own };
64
+ }
65
+
66
+ /** Plan the removal of the file at `path`; undefined when there is nothing there to remove. */
67
+ export function planRemoval(path: string): PlannedFile | undefined {
68
+ return existsSync(path) ? { path, status: "removed", content: "" } : undefined;
69
+ }
70
+
71
+ /**
72
+ * Write a plan: each created or updated file written, its directory made
73
+ * and its mode set; each removed file unlinked; an unchanged file not
74
+ * touched. A removed file that is already gone is not an error.
75
+ */
76
+ export function writePlannedFiles(files: readonly Pick<PlannedFile, "path" | "status" | "content" | "mode">[]): void {
77
+ for (const f of files) {
78
+ if (f.status === "unchanged") continue;
79
+ if (f.status === "removed") {
80
+ if (existsSync(f.path)) unlinkSync(f.path);
81
+ continue;
82
+ }
83
+ mkdirSync(dirname(f.path), { recursive: true });
84
+ writeFileSync(f.path, f.content);
85
+ if (f.mode !== undefined) chmodSync(f.path, f.mode);
86
+ }
87
+ }
88
+
89
+ export interface StaleGeneratedOptions {
90
+ /** The directory the paths are relative to: a product's checkout. */
91
+ root: string;
92
+ /** Directories, relative to `root`, whose files (not their subdirectories) may be generated. */
93
+ dirs?: readonly string[];
94
+ /** Single files, relative to `root`, that may be generated, such as `.gitlab-ci.yml`. */
95
+ files?: readonly string[];
96
+ /** The names in `dirs` to look at. Default every file. */
97
+ match?: RegExp;
98
+ /** The product's header: its first line, which a generated file opens with, or a test of the file's text. */
99
+ header: string | ((text: string) => boolean);
100
+ /** The paths, relative to `root` and written with `/`, the product renders now. */
101
+ rendered: Iterable<string>;
102
+ }
103
+
104
+ /**
105
+ * The files under `dirs` and among `files` that open with the product's
106
+ * header and that it does not render now, relative to `root`, in the order
107
+ * found (each directory's names sorted). A file without the header is the
108
+ * person's own and never listed.
109
+ */
110
+ export function staleGeneratedFiles(options: StaleGeneratedOptions): string[] {
111
+ const { root } = options;
112
+ const header = options.header;
113
+ const isGenerated = typeof header === "string" ? (text: string) => text.split(/\r?\n/, 1)[0] === header : header;
114
+ const candidates = [...(options.files ?? [])];
115
+ for (const d of options.dirs ?? []) {
116
+ const abs = join(root, d);
117
+ if (!existsSync(abs)) continue;
118
+ const prefix = d.replace(/\/+$/, "");
119
+ for (const e of readdirSync(abs, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
120
+ if (e.isFile() && (!options.match || options.match.test(e.name))) candidates.push(prefix === "" || prefix === "." ? e.name : `${prefix}/${e.name}`);
121
+ }
122
+ }
123
+ const rendered = new Set(options.rendered);
124
+ const out: string[] = [];
125
+ for (const p of candidates) {
126
+ if (rendered.has(p) || out.includes(p)) continue;
127
+ const abs = join(root, p);
128
+ if (!existsSync(abs) || !statSync(abs).isFile()) continue;
129
+ if (isGenerated(readFileSync(abs, "utf-8"))) out.push(p);
130
+ }
131
+ return out;
132
+ }
133
+
134
+ export { PLANNED_FILES_FLOOR } from "./release-floors";
@@ -0,0 +1,53 @@
1
+ /**
2
+ * #4964: a GitHub pull_request run plans, checks and signs its merge
3
+ * preview (`GITHUB_SHA`), and the forge shows no status of that commit on
4
+ * the pull request, so the plan note's, the check evidence's and the ref
5
+ * gate's statuses for it go on the pull request's head.
6
+ */
7
+ import { mkdtempSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { describe, expect, test } from "vitest";
11
+ import type { ForgeFetch } from "./pr-forge";
12
+ import { forgeFromJobEnv } from "./pr-forge-job";
13
+
14
+ const HEAD = "a".repeat(40);
15
+ const MERGE = "b".repeat(40);
16
+ const OTHER = "c".repeat(40);
17
+
18
+ function recorder(): { fetch: ForgeFetch; posted: string[] } {
19
+ const posted: string[] = [];
20
+ const fetch: ForgeFetch = async (url) => {
21
+ posted.push(url.replace(/^.*\/statuses\//, ""));
22
+ return { ok: true, status: 201, text: async () => "{}" };
23
+ };
24
+ return { fetch, posted };
25
+ }
26
+
27
+ function eventFile(body: unknown): string {
28
+ const path = join(mkdtempSync(join(tmpdir(), "chant-4964-")), "event.json");
29
+ writeFileSync(path, JSON.stringify(body));
30
+ return path;
31
+ }
32
+
33
+ const status = { context: "chant/plan", state: "success" as const, description: "d" };
34
+
35
+ describe("statuses of a pull_request run on the pull request's head (#4964)", () => {
36
+ const env = { GITHUB_REPOSITORY: "acme/infra", GITHUB_TOKEN: "t", GITHUB_EVENT_NAME: "pull_request", GITHUB_SHA: MERGE, GITHUB_EVENT_PATH: eventFile({ number: 7, pull_request: { number: 7, head: { sha: HEAD } } }) };
37
+
38
+ test("a status for the merge preview goes on the head; one for another commit where it was asked", async () => {
39
+ const { fetch, posted } = recorder();
40
+ const forge = forgeFromJobEnv("github", env, fetch);
41
+ await forge.setStatus(MERGE, status);
42
+ await forge.setStatus(OTHER, status);
43
+ expect(posted).toEqual([HEAD, OTHER]);
44
+ });
45
+
46
+ test("a run of another event, or one whose payload names no head, posts where it was asked", async () => {
47
+ const { fetch, posted } = recorder();
48
+ await forgeFromJobEnv("github", { ...env, GITHUB_EVENT_NAME: "push" }, fetch).setStatus(MERGE, status);
49
+ await forgeFromJobEnv("github", { ...env, GITHUB_EVENT_PATH: eventFile({ ref: "refs/heads/main" }) }, fetch).setStatus(MERGE, status);
50
+ await forgeFromJobEnv("github", { ...env, GITHUB_EVENT_PATH: join(tmpdir(), "chant-4964-missing.json") }, fetch).setStatus(MERGE, status);
51
+ expect(posted).toEqual([MERGE, MERGE, MERGE]);
52
+ });
53
+ });
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The forge client a chant command in a CI job posts with (#4964): the
3
+ * pull request loop's {@link forgeFromEnv}, with each commit status for the
4
+ * run's own commit put on the pull request's head.
5
+ *
6
+ * A GitHub `pull_request` run checks out `GITHUB_SHA`, the merge preview
7
+ * (`refs/pull/<n>/merge`), and the loop's jobs plan, check and sign that
8
+ * commit, as a merge would make it. The forge shows no status of that commit
9
+ * on the pull request, and a required status is read from the head, so a
10
+ * status the plan note, the check evidence or the ref gate sets for it goes
11
+ * on `pull_request.head.sha` instead. Forgejo's run is of the head already,
12
+ * and so is a status for any other commit; both are posted as asked. GitLab
13
+ * is left as it is: its merge request pipeline runs on the head.
14
+ *
15
+ * Kept out of ./pr-forge.ts, whose bundle a product posts with.
16
+ */
17
+
18
+ import { readFileSync } from "node:fs";
19
+ import { forgeFromEnv, type ForgeKind, type PrForge } from "./pr-forge";
20
+
21
+ /** The pull request's head from a GitHub-style `pull_request` run's event payload, or undefined for any other run. */
22
+ export function pullRequestEventHead(env: Record<string, string | undefined>): string | undefined {
23
+ if (!env.GITHUB_EVENT_NAME?.startsWith("pull_request") || !env.GITHUB_EVENT_PATH) return undefined;
24
+ try {
25
+ const event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, "utf8")) as { pull_request?: { head?: { sha?: unknown } } };
26
+ const sha = event.pull_request?.head?.sha;
27
+ return typeof sha === "string" && /^[0-9a-f]{40,64}$/.test(sha) ? sha : undefined;
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ }
32
+
33
+ /** {@link forgeFromEnv}, whose statuses for the run's merge preview go on the pull request's head (#4964). */
34
+ export function forgeFromJobEnv(kind: ForgeKind, env: Record<string, string | undefined> = process.env, fetchImpl?: Parameters<typeof forgeFromEnv>[2]): PrForge {
35
+ const forge = forgeFromEnv(kind, env, fetchImpl);
36
+ const merge = env.GITHUB_SHA;
37
+ const head = kind === "gitlab" ? undefined : pullRequestEventHead(env);
38
+ if (!head || !merge || head === merge) return forge;
39
+ const at = (sha: string): string => (sha === merge ? head : sha);
40
+ const { setStatus, setCommitStatus } = forge;
41
+ return {
42
+ ...forge,
43
+ setStatus: (sha, status) => setStatus(at(sha), status),
44
+ ...(setCommitStatus ? { setCommitStatus: (sha: string, status: Parameters<typeof setCommitStatus>[1]) => setCommitStatus(at(sha), status) } : {}),
45
+ };
46
+ }
@@ -6,7 +6,8 @@
6
6
  */
7
7
  import { describe, expect, test } from "vitest";
8
8
  import { composeChangeSet } from "./change-set";
9
- import { memberCounts, PR_REPORT_SCHEMA_ID, prStatusDescription, renderPrNote, type PrReport } from "./pr-loop";
9
+ import { memberCounts, PR_REPORT_SCHEMA_ID, renderPrNote, type PrReport } from "./pr-loop";
10
+ import { prStatusDescription } from "./pr-status";
10
11
  import { assertProductWords } from "./ci-product-words";
11
12
  import { PLYWOOD } from "./__fixtures__/product-words";
12
13
 
@@ -5,7 +5,8 @@
5
5
  */
6
6
  import { describe, expect, test } from "vitest";
7
7
  import { composeChangeSet } from "./change-set";
8
- import { memberCounts, PR_REPORT_SCHEMA_ID, prApproveCommand, prApproveCommands, prMergeSentence, prStatusContext, prStatusDescription, renderPrNote, type PrReport } from "./pr-loop";
8
+ import { memberCounts, PR_REPORT_SCHEMA_ID, prApproveCommand, prApproveCommands, prMergeSentence, prStatusContext, renderPrNote, type PrReport } from "./pr-loop";
9
+ import { prStatusDescription } from "./pr-status";
9
10
  import { assertProductWords, CHANT_WORDS } from "./ci-product-words";
10
11
  import { PLYWOOD, TERRAGUCCI, YODEL } from "./__fixtures__/product-words";
11
12
 
@@ -23,11 +23,10 @@ import {
23
23
  PR_GATE_OP,
24
24
  prOp,
25
25
  prStatusContext,
26
- prStatusDescription,
27
- prStatusState,
28
26
  renderPrNote,
29
27
  type PrReport,
30
28
  } from "./pr-loop";
29
+ import { prStatusDescription, prStatusState } from "./pr-status";
31
30
  import { contract, validSchema } from "./workspace/__fixtures__/contract-repo";
32
31
  import schema from "./workspace/pr-report.schema.json";
33
32
  import changeSetSchema from "./workspace/change-set.schema.json";