@intentius/chant 0.124.89 → 0.124.91

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 (185) hide show
  1. package/dist/actor.d.ts +5 -3
  2. package/dist/actor.d.ts.map +1 -1
  3. package/dist/actor.js +7 -5
  4. package/dist/audit/core.d.ts.map +1 -1
  5. package/dist/audit/core.js +11 -1
  6. package/dist/ci-comment-commands.d.ts +18 -2
  7. package/dist/ci-comment-commands.d.ts.map +1 -1
  8. package/dist/ci-comment-commands.js +30 -2
  9. package/dist/ci-job-guard.d.ts +42 -45
  10. package/dist/ci-job-guard.d.ts.map +1 -1
  11. package/dist/ci-job-guard.js +206 -3
  12. package/dist/ci-note-commands.d.ts +41 -1
  13. package/dist/ci-note-commands.d.ts.map +1 -1
  14. package/dist/ci-note-commands.js +64 -5
  15. package/dist/ci-product.d.ts +50 -1
  16. package/dist/ci-product.d.ts.map +1 -1
  17. package/dist/ci-product.js +52 -6
  18. package/dist/cli/handlers/pr-comment.d.ts +13 -1
  19. package/dist/cli/handlers/pr-comment.d.ts.map +1 -1
  20. package/dist/cli/handlers/pr-comment.js +90 -1
  21. package/dist/cli/handlers/pr-notes.d.ts.map +1 -1
  22. package/dist/cli/handlers/pr-notes.js +23 -1
  23. package/dist/cli/handlers/pr.d.ts +2 -2
  24. package/dist/cli/handlers/pr.d.ts.map +1 -1
  25. package/dist/cli/handlers/pr.js +41 -20
  26. package/dist/cli/handlers/run-wave.d.ts.map +1 -1
  27. package/dist/cli/handlers/run-wave.js +154 -4
  28. package/dist/cli/main.d.ts.map +1 -1
  29. package/dist/cli/main.js +17 -0
  30. package/dist/cli/parse-args.d.ts.map +1 -1
  31. package/dist/cli/parse-args.js +28 -0
  32. package/dist/cli/registry.d.ts +12 -1
  33. package/dist/cli/registry.d.ts.map +1 -1
  34. package/dist/components/pr-checks.d.ts +39 -1
  35. package/dist/components/pr-checks.d.ts.map +1 -1
  36. package/dist/components/pr-checks.js +45 -2
  37. package/dist/components/pr-pipeline.d.ts +11 -3
  38. package/dist/components/pr-pipeline.d.ts.map +1 -1
  39. package/dist/components/pr-pipeline.js +20 -7
  40. package/dist/components/product-pipeline.d.ts +54 -2
  41. package/dist/components/product-pipeline.d.ts.map +1 -1
  42. package/dist/components/product-pipeline.js +63 -6
  43. package/dist/components/product-plan.d.ts +92 -2
  44. package/dist/components/product-plan.d.ts.map +1 -1
  45. package/dist/components/product-plan.js +172 -22
  46. package/dist/floor-table.data.d.ts.map +1 -1
  47. package/dist/floor-table.data.js +37 -23
  48. package/dist/lexicon-module.d.ts +2 -0
  49. package/dist/lexicon-module.d.ts.map +1 -1
  50. package/dist/lexicon-module.js +6 -2
  51. package/dist/lexicon.d.ts +82 -4
  52. package/dist/lexicon.d.ts.map +1 -1
  53. package/dist/lifecycle/gate-applied.d.ts +9 -0
  54. package/dist/lifecycle/gate-applied.d.ts.map +1 -1
  55. package/dist/op/apply-status.d.ts +84 -0
  56. package/dist/op/apply-status.d.ts.map +1 -0
  57. package/dist/op/apply-status.js +106 -0
  58. package/dist/op/before-merge-decide.d.ts +102 -0
  59. package/dist/op/before-merge-decide.d.ts.map +1 -0
  60. package/dist/op/before-merge-decide.js +142 -0
  61. package/dist/op/before-merge-done.d.ts +56 -0
  62. package/dist/op/before-merge-done.d.ts.map +1 -0
  63. package/dist/op/before-merge-done.js +69 -0
  64. package/dist/op/before-merge-store.d.ts +20 -0
  65. package/dist/op/before-merge-store.d.ts.map +1 -0
  66. package/dist/op/before-merge-store.js +48 -0
  67. package/dist/op/before-merge.d.ts +150 -0
  68. package/dist/op/before-merge.d.ts.map +1 -0
  69. package/dist/op/before-merge.js +207 -0
  70. package/dist/op/follow-on-run.d.ts +117 -0
  71. package/dist/op/follow-on-run.d.ts.map +1 -0
  72. package/dist/op/follow-on-run.js +154 -0
  73. package/dist/op/follow-on-store.d.ts +17 -0
  74. package/dist/op/follow-on-store.d.ts.map +1 -0
  75. package/dist/op/follow-on-store.js +54 -0
  76. package/dist/op/gate.d.ts +6 -0
  77. package/dist/op/gate.d.ts.map +1 -1
  78. package/dist/op/gate.js +10 -1
  79. package/dist/op/index.d.ts +3 -1
  80. package/dist/op/index.d.ts.map +1 -1
  81. package/dist/op/index.js +1 -0
  82. package/dist/op/op-waves-after-plan.d.ts +13 -0
  83. package/dist/op/op-waves-after-plan.d.ts.map +1 -1
  84. package/dist/op/op-waves-evidence-jobs.d.ts +4 -1
  85. package/dist/op/op-waves-evidence-jobs.d.ts.map +1 -1
  86. package/dist/op/op-waves-evidence-jobs.js +10 -2
  87. package/dist/op/op-waves-follow-on.d.ts +162 -0
  88. package/dist/op/op-waves-follow-on.d.ts.map +1 -0
  89. package/dist/op/op-waves-follow-on.js +355 -0
  90. package/dist/op/op-waves-run.d.ts +146 -6
  91. package/dist/op/op-waves-run.d.ts.map +1 -1
  92. package/dist/op/op-waves-run.js +871 -99
  93. package/dist/op/op-waves-split.d.ts +122 -0
  94. package/dist/op/op-waves-split.d.ts.map +1 -0
  95. package/dist/op/op-waves-split.js +166 -0
  96. package/dist/op/op-waves.d.ts +20 -0
  97. package/dist/op/op-waves.d.ts.map +1 -1
  98. package/dist/op/op-waves.js +15 -1
  99. package/dist/op/schedule-overdue.d.ts +15 -1
  100. package/dist/op/schedule-overdue.d.ts.map +1 -1
  101. package/dist/op/schedule-overdue.js +18 -2
  102. package/dist/op/stage-hooks.d.ts +36 -1
  103. package/dist/op/stage-hooks.d.ts.map +1 -1
  104. package/dist/op/stage-hooks.js +17 -3
  105. package/dist/op/wave-stop.d.ts +4 -1
  106. package/dist/op/wave-stop.d.ts.map +1 -1
  107. package/dist/op/wave-stop.js +4 -2
  108. package/dist/planned-files.d.ts +16 -8
  109. package/dist/planned-files.d.ts.map +1 -1
  110. package/dist/planned-files.js +12 -8
  111. package/dist/pr-post.d.ts +6 -0
  112. package/dist/pr-post.d.ts.map +1 -1
  113. package/dist/pr-post.js +7 -5
  114. package/dist/release-floors.d.ts +9 -1
  115. package/dist/release-floors.d.ts.map +1 -1
  116. package/dist/release-floors.js +27 -19
  117. package/dist/wave-blocked.d.ts +7 -1
  118. package/dist/wave-blocked.d.ts.map +1 -1
  119. package/dist/wave-blocked.js +7 -2
  120. package/dist/wave-runtime.mjs +364 -351
  121. package/package.json +1 -1
  122. package/src/actor.test.ts +14 -1
  123. package/src/actor.ts +8 -6
  124. package/src/audit/core.ts +13 -1
  125. package/src/audit/first-load.test.ts +101 -0
  126. package/src/ci-comment-commands.test.ts +63 -0
  127. package/src/ci-comment-commands.ts +43 -4
  128. package/src/ci-image.test.ts +1 -2
  129. package/src/ci-job-guard.before-merge.test.ts +148 -0
  130. package/src/ci-job-guard.follow-on-record.test.ts +137 -0
  131. package/src/ci-job-guard.follow-on.test.ts +144 -0
  132. package/src/ci-job-guard.ts +221 -3
  133. package/src/ci-note-commands.test.ts +76 -1
  134. package/src/ci-note-commands.ts +96 -7
  135. package/src/ci-product.ts +65 -6
  136. package/src/cli/handlers/pr-comment.ts +85 -2
  137. package/src/cli/handlers/pr-notes.ts +30 -6
  138. package/src/cli/handlers/pr.ts +34 -17
  139. package/src/cli/handlers/run-wave.ts +144 -4
  140. package/src/cli/main.ts +17 -0
  141. package/src/cli/parse-args.ts +20 -0
  142. package/src/cli/registry.ts +12 -1
  143. package/src/components/pr-checks.ts +66 -2
  144. package/src/components/pr-pipeline.ts +21 -9
  145. package/src/components/product-pipeline.apply-status.test.ts +50 -0
  146. package/src/components/product-pipeline.ts +117 -9
  147. package/src/components/product-plan-names.test.ts +135 -0
  148. package/src/components/product-plan.test.ts +23 -5
  149. package/src/components/product-plan.ts +248 -25
  150. package/src/floor-table.data.ts +37 -23
  151. package/src/lexicon-module.ts +6 -2
  152. package/src/lexicon.ts +78 -1
  153. package/src/lifecycle/gate-applied.ts +7 -0
  154. package/src/op/apply-status.test.ts +83 -0
  155. package/src/op/apply-status.ts +132 -0
  156. package/src/op/before-merge-decide.ts +190 -0
  157. package/src/op/before-merge-done.ts +99 -0
  158. package/src/op/before-merge-store.ts +44 -0
  159. package/src/op/before-merge.test.ts +201 -0
  160. package/src/op/before-merge.ts +266 -0
  161. package/src/op/follow-on-run.ts +206 -0
  162. package/src/op/follow-on-store.ts +54 -0
  163. package/src/op/gate.ts +16 -1
  164. package/src/op/index.ts +5 -0
  165. package/src/op/op-waves-after-plan.ts +13 -0
  166. package/src/op/op-waves-evidence-jobs.ts +11 -3
  167. package/src/op/op-waves-follow-on-record.test.ts +152 -0
  168. package/src/op/op-waves-follow-on.test.ts +247 -0
  169. package/src/op/op-waves-follow-on.ts +385 -0
  170. package/src/op/op-waves-render-spec.test.ts +1 -2
  171. package/src/op/op-waves-run.ts +971 -93
  172. package/src/op/op-waves-split-product.test.ts +288 -0
  173. package/src/op/op-waves-split-step.test.ts +298 -0
  174. package/src/op/op-waves-split.test.ts +196 -0
  175. package/src/op/op-waves-split.ts +189 -0
  176. package/src/op/op-waves.ts +28 -3
  177. package/src/op/schedule-overdue.test.ts +29 -1
  178. package/src/op/schedule-overdue.ts +27 -3
  179. package/src/op/stage-hooks.ts +52 -4
  180. package/src/op/wave-stop.ts +5 -3
  181. package/src/planned-files.test.ts +33 -0
  182. package/src/planned-files.ts +26 -10
  183. package/src/pr-post.ts +13 -5
  184. package/src/release-floors.ts +31 -19
  185. package/src/wave-blocked.ts +9 -4
@@ -0,0 +1,355 @@
1
+ /**
2
+ * `rest` waves in a split pipeline (#4992): one wave per run, each run
3
+ * starting the next.
4
+ *
5
+ * Maintainer decision (2026-11-10): a follow-on run. Before merge (and on a
6
+ * push of the same pipeline) each wave is four jobs (./op-waves-split.ts),
7
+ * and the jobs of a wave the plan finds at run time cannot be rendered up
8
+ * front. So the rest wave's four jobs (the last rendered wave, N) run wave
9
+ * N in a run, and their record job, once every wave of the run applied and
10
+ * the plan found more waves, starts the waves workflow again for wave N+1:
11
+ *
12
+ * - GitHub and Forgejo dispatch the workflow on its branch with the inputs
13
+ * `wave` and, before merge, `pr`, `head` and `digest`, or, for a push,
14
+ * `commit` (the pushed commit, which every job of the follow-on checks
15
+ * out and checks is on the branch). GitHub dispatches with the job's
16
+ * token (`actions: write` on that job alone); Forgejo with the
17
+ * `CHANT_FORGE_TOKEN` secret, as its resume does.
18
+ * - GitLab starts a pipeline of the branch with the same values as
19
+ * variables (`CHANT_WAVES_WAVE`, the decision's three or
20
+ * `CHANT_WAVES_COMMIT`), with `CHANT_FORGE_TOKEN`, since the job token
21
+ * cannot start one.
22
+ *
23
+ * In the follow-on the jobs of waves 1 to N-1 do not run, and the rest
24
+ * wave's jobs run wave N+1 (`--wave "${CHANT_WAVES_WAVE:-N}"`, and their
25
+ * files at that wave's paths, {@link opWaveRestPath}). The guard admits the
26
+ * run as the same decided head (./follow-on-run.ts). It goes on until the
27
+ * wave the plan found last.
28
+ *
29
+ * The record job leaves a note in the outcome directory
30
+ * ({@link OP_WAVE_REST_NOTE}): the wave it ran, how many the plan found, and
31
+ * the wave it started, if it started one. `before-merge-done`, the control
32
+ * dispatch and the apply status read it, so a run that started a follow-on
33
+ * is not the last: nothing merges, the control repo hears from the last
34
+ * run, and the status stays pending with `wave k of M applied`.
35
+ *
36
+ * #4998: before it starts a follow-on, the record job records it on
37
+ * `chant/lifecycle` (./follow-on-run.ts, ./follow-on-store.ts): the wave it
38
+ * starts, its own run, the decision or the pushed commit, and the outcomes
39
+ * of every run of the chain so far, its own added. The follow-on's guard
40
+ * admits that wave alone. A follow-on's record job reads the record that
41
+ * started it and puts the earlier runs' outcomes in its note as `chain`, so
42
+ * the last run's control dispatch and apply status add up the whole chain
43
+ * ({@link withChainOutcomes}): a chain whose last wave changed nothing
44
+ * reports `applied` when an earlier run applied.
45
+ */
46
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
47
+ import { isAbsolute, join } from "node:path";
48
+ import { CHANT_EXIT } from "../exit-codes.js";
49
+ import { CONTROL_OUTCOME_VAR } from "../control/dispatch.js";
50
+ import { beforeMergeRunFromEnv, isBeforeMergeRun } from "./before-merge.js";
51
+ import { OP_WAVES_COMMIT_ENV, OP_WAVES_WAVE_ENV } from "./follow-on-run.js";
52
+ import { opWaveOutcomeDir, opWaveRecordPath } from "./op-waves.js";
53
+ export { FOLLOW_ON_INPUTS, OP_WAVES_COMMIT_ENV, OP_WAVES_WAVE_ENV } from "./follow-on-run.js";
54
+ /** The variable the rest wave's record job is told how to start a follow-on in: `{ "forge": ..., "workflow": ... }` as JSON. */
55
+ export const OP_WAVES_FOLLOW_ON_ENV = "CHANT_WAVES_FOLLOW_ON";
56
+ /**
57
+ * The variable the rest wave's record step hands the token that starts the
58
+ * follow-on in (GitHub: the job's token; Forgejo: the `CHANT_FORGE_TOKEN`
59
+ * secret), so no other line of the job reads it as the forge's token.
60
+ * Unset (GitLab), the record job reads {@link FORGE_TOKEN_VAR}.
61
+ */
62
+ export const FOLLOW_ON_TOKEN_ENV = "CHANT_WAVES_FOLLOW_ON_TOKEN";
63
+ /** The secret (Forgejo) or CI/CD variable (GitLab) a token that may start a run is kept in. */
64
+ export const FORGE_TOKEN_VAR = "CHANT_FORGE_TOKEN";
65
+ /** The rest wave's number when the spec's last wave has `rest`, else undefined. */
66
+ export function opWavesRestWave(spec) {
67
+ return spec.waves[spec.waves.length - 1]?.rest === true ? spec.waves.length : undefined;
68
+ }
69
+ /**
70
+ * A path of the rest wave's (`wave-N.json`, `wave-N/`, `outcome-wave-N-apply.json`,
71
+ * `run-record-wave-N.json`) with its wave number put as `token`, the form
72
+ * the forge reads `CHANT_WAVES_WAVE` in at that place.
73
+ */
74
+ export function opWaveRestPath(path, wave, token) {
75
+ return path.replace(new RegExp(`(^|[/-])wave-${wave}(?=[./-]|$)`, "g"), (_m, lead) => `${lead}wave-${token}`);
76
+ }
77
+ /** The value of {@link OP_WAVES_FOLLOW_ON_ENV} for a forge. */
78
+ export function opWavesFollowOnEnv(target) {
79
+ return JSON.stringify(target);
80
+ }
81
+ /** Read {@link OP_WAVES_FOLLOW_ON_ENV}; undefined when unset, and a value that is no target throws. */
82
+ export function parseFollowOnTarget(raw) {
83
+ if (raw === undefined || raw.trim() === "")
84
+ return undefined;
85
+ let v;
86
+ try {
87
+ v = JSON.parse(raw);
88
+ }
89
+ catch {
90
+ throw new Error(`${OP_WAVES_FOLLOW_ON_ENV} is not JSON`);
91
+ }
92
+ const o = v;
93
+ if (!o || (o.forge !== "github" && o.forge !== "forgejo" && o.forge !== "gitlab"))
94
+ throw new Error(`${OP_WAVES_FOLLOW_ON_ENV}.forge is github, forgejo or gitlab`);
95
+ if (o.forge !== "gitlab" && (typeof o.workflow !== "string" || !/^[A-Za-z0-9._-]+\.ya?ml$/.test(o.workflow)))
96
+ throw new Error(`${OP_WAVES_FOLLOW_ON_ENV}.workflow names the waves workflow's file`);
97
+ return { forge: o.forge, ...(o.workflow ? { workflow: o.workflow } : {}) };
98
+ }
99
+ /**
100
+ * The lines every job of the rest wave runs after its checkout (#4992): in
101
+ * a push's follow-on, stop (exit 9, `misplaced`) unless the commit it goes
102
+ * on with is on the branch the run checked out, then check that commit
103
+ * out. Nothing in any other run. The guard checked it is a commit sha.
104
+ */
105
+ export function followOnCommitScript(product) {
106
+ return [
107
+ `if [ -n "\${${OP_WAVES_COMMIT_ENV}:-}" ]; then`,
108
+ ` git merge-base --is-ancestor "$${OP_WAVES_COMMIT_ENV}" HEAD || { echo "${product}: the follow-on's commit $(printf %.12s "$${OP_WAVES_COMMIT_ENV}") is not on the branch this run checked out, so nothing is applied" >&2; exit ${CHANT_EXIT.misplaced}; }`,
109
+ ` git checkout -q --detach "$${OP_WAVES_COMMIT_ENV}" || exit 1`,
110
+ "fi",
111
+ ].join("\n");
112
+ }
113
+ /**
114
+ * The first line of the control dispatch's script in a pipeline with a rest
115
+ * wave (#4992): `chant run wave --waves-outcome` adds up nothing for a run
116
+ * that started a follow-on, and the dispatch sends nothing then; the last
117
+ * run of the waves sends the outcome.
118
+ */
119
+ export function followOnControlSkip(product) {
120
+ return `if [ -z "\${${CONTROL_OUTCOME_VAR}:-}" ]; then echo "${product}: this run started a follow-on run for the next wave, which tells the control repo how the waves ended"; exit 0; fi`;
121
+ }
122
+ /** The note the rest wave's record job leaves in the outcome directory. */
123
+ export const OP_WAVE_REST_NOTE = "rest-wave.json";
124
+ /** The outcomes of a chain's runs: a valid entry of each, the rest dropped. */
125
+ function chainOf(v) {
126
+ if (!v || typeof v !== "object")
127
+ return undefined;
128
+ const out = {};
129
+ for (const [member, o] of Object.entries(v)) {
130
+ if (!o || typeof o.status !== "string" || !Number.isInteger(o.wave) || typeof o.at !== "string" || (o.by !== undefined && typeof o.by !== "string"))
131
+ continue;
132
+ out[member] = { status: o.status, ...(o.by !== undefined ? { by: o.by } : {}), wave: o.wave, at: o.at };
133
+ }
134
+ return Object.keys(out).length > 0 ? out : undefined;
135
+ }
136
+ /**
137
+ * The outcomes the jobs after the waves add up (#4998): this run's, from
138
+ * its outcome files (`members`, `earlierWaveOutcomes` below wave `before`),
139
+ * with the chain's earlier runs' from the rest wave's note. A member's
140
+ * newer outcome wins. With no note, or one with no chain, `members`.
141
+ */
142
+ export function withChainOutcomes(members, note, before = Number.MAX_SAFE_INTEGER) {
143
+ const out = new Map();
144
+ for (const [member, o] of Object.entries(note?.chain ?? {}))
145
+ if (o.wave < before)
146
+ out.set(member, o);
147
+ for (const [member, o] of members) {
148
+ const had = out.get(member);
149
+ if (!had || had.at <= o.at)
150
+ out.set(member, o);
151
+ }
152
+ return out;
153
+ }
154
+ /** Where the record job writes the note. */
155
+ export function opWaveRestNotePath(spec) {
156
+ return `${opWaveOutcomeDir(spec)}/${OP_WAVE_REST_NOTE}`;
157
+ }
158
+ /** The note under `dirs` (downloaded artifacts keep it in a directory of their own, four deep at most), the newest wave's when there are more. */
159
+ export function readOpWaveRestNote(dirs) {
160
+ let found;
161
+ const walk = (dir, depth) => {
162
+ let names;
163
+ try {
164
+ names = readdirSync(dir);
165
+ }
166
+ catch {
167
+ return;
168
+ }
169
+ for (const name of names) {
170
+ const abs = join(dir, name);
171
+ let isDir = false;
172
+ try {
173
+ isDir = statSync(abs).isDirectory();
174
+ }
175
+ catch {
176
+ continue;
177
+ }
178
+ if (isDir) {
179
+ if (depth < 4)
180
+ walk(abs, depth + 1);
181
+ continue;
182
+ }
183
+ if (name !== OP_WAVE_REST_NOTE)
184
+ continue;
185
+ let v;
186
+ try {
187
+ v = JSON.parse(readFileSync(abs, "utf-8"));
188
+ }
189
+ catch {
190
+ continue;
191
+ }
192
+ if (!v || v.version !== 1 || typeof v.op !== "string" || !Number.isInteger(v.wave) || !Number.isInteger(v.found))
193
+ continue;
194
+ if (v.next !== undefined && (!Number.isInteger(v.next) || v.next !== v.wave + 1))
195
+ continue;
196
+ const chain = chainOf(v.chain);
197
+ if (!found || v.wave > found.wave)
198
+ found = { version: 1, op: v.op, wave: v.wave, found: v.found, ...(v.next !== undefined ? { next: v.next } : {}), ...(chain ? { chain } : {}) };
199
+ }
200
+ };
201
+ for (const d of dirs)
202
+ if (existsSync(d))
203
+ walk(d, 0);
204
+ return found;
205
+ }
206
+ /** What a chain is keyed by and what its record names (#4998): before merge the decision, for a push the commit the run applied. */
207
+ export function followOnChainOf(forge, env) {
208
+ const run = beforeMergeRunFromEnv(env);
209
+ if (isBeforeMergeRun(run))
210
+ return run.head ? { key: run.head, ...(run.pr && /^[1-9][0-9]*$/.test(run.pr) ? { pr: Number(run.pr) } : {}), ...(run.digest ? { digest: run.digest } : {}) } : undefined;
211
+ const commit = env[OP_WAVES_COMMIT_ENV]?.trim() || (forge === "gitlab" ? env.CI_COMMIT_SHA : env.GITHUB_SHA)?.trim();
212
+ return commit ? { key: commit, commit } : undefined;
213
+ }
214
+ /** The run a record job runs in, as the record names it: GitHub and Forgejo `GITHUB_RUN_ID`, GitLab `CI_PIPELINE_ID`, and its page when the forge says. */
215
+ function runOf(forge, env) {
216
+ if (forge === "gitlab") {
217
+ const url = env.CI_PIPELINE_URL?.trim();
218
+ return { run: env.CI_PIPELINE_ID?.trim() || "unknown", ...(url && /^https?:\/\//.test(url) ? { url } : {}) };
219
+ }
220
+ const id = env.GITHUB_RUN_ID?.trim();
221
+ const server = env.GITHUB_SERVER_URL?.trim().replace(/\/+$/, "");
222
+ const repo = env.GITHUB_REPOSITORY?.trim();
223
+ return { run: id || "unknown", ...(forge === "github" && id && server && repo && /^https?:\/\//.test(server) ? { url: `${server}/${repo}/actions/runs/${id}` } : {}) };
224
+ }
225
+ /**
226
+ * After the rest wave's record job wrote its run records (#4992): leave the
227
+ * note, and when the run applied every wave it ran and the plan found more,
228
+ * start the follow-on for the next one. Resolves to the job's exit: the
229
+ * record job's own, or failed when the follow-on could not be started (the
230
+ * note still says it was to be, so nothing after the run takes it for the
231
+ * last). A job that is not the rest wave's, or whose pipeline sets no
232
+ * {@link OP_WAVES_FOLLOW_ON_ENV}, is left as it is.
233
+ */
234
+ export async function followOnAfterRecord(i) {
235
+ const env = i.env ?? process.env;
236
+ const log = i.log ?? ((line) => console.error(line));
237
+ const rest = opWavesRestWave(i.spec);
238
+ if (rest === undefined || i.wave < rest)
239
+ return i.exitCode;
240
+ const target = parseFollowOnTarget(env[OP_WAVES_FOLLOW_ON_ENV]);
241
+ if (!target)
242
+ return i.exitCode;
243
+ const cwd = i.cwd ?? process.cwd();
244
+ let found;
245
+ try {
246
+ const decision = JSON.parse(readFileSync(join(cwd, opWaveRecordPath(i.spec, i.wave)), "utf-8"));
247
+ const w = decision?.discovered?.waves;
248
+ if (Number.isInteger(w))
249
+ found = w;
250
+ }
251
+ catch {
252
+ found = undefined;
253
+ }
254
+ const outcomeDir = opWaveOutcomeDir(i.spec);
255
+ const dir = isAbsolute(outcomeDir) ? outcomeDir : join(cwd, outcomeDir);
256
+ const { earlierWaveOutcomes } = await import("../wave-blocked.js");
257
+ const { applyOutcomeOf } = await import("../control/applied.js");
258
+ const own = earlierWaveOutcomes([dir], Number.MAX_SAFE_INTEGER).members;
259
+ const summary = applyOutcomeOf(own);
260
+ const through = summary.outcome === "applied" || summary.outcome === "unchanged";
261
+ const next = i.exitCode === CHANT_EXIT.done && through && found !== undefined && found > i.wave ? i.wave + 1 : undefined;
262
+ // #4998: a follow-on's record job reads the record that started it, for the outcomes of the chain's earlier runs.
263
+ const chainKey = followOnChainOf(target.forge, env);
264
+ let port = i.chain;
265
+ const chainPort = async () => (port ?? (port = (await import("./follow-on-store.js")).gitFollowOnChainPort({ cwd })));
266
+ let chain = {};
267
+ if (i.wave > rest && chainKey) {
268
+ try {
269
+ const started = await (await chainPort()).read(i.spec.name, chainKey.key);
270
+ if (started && started.wave === i.wave)
271
+ chain = started.outcomes;
272
+ else
273
+ log(`wave ${i.wave}: no record on chant/lifecycle started this wave for ${chainKey.key.slice(0, 12)}, so the outcomes of the chain's earlier runs are not added up`);
274
+ }
275
+ catch (err) {
276
+ log(`wave ${i.wave}: the record that started this run could not be read (${(err instanceof Error ? err.message : String(err)).split("\n")[0]}), so the outcomes of the chain's earlier runs are not added up`);
277
+ }
278
+ }
279
+ mkdirSync(dir, { recursive: true });
280
+ const note = { version: 1, op: i.spec.name, wave: i.wave, found: found ?? i.wave, ...(next !== undefined ? { next } : {}), ...(Object.keys(chain).length > 0 ? { chain } : {}) };
281
+ writeFileSync(join(dir, OP_WAVE_REST_NOTE), JSON.stringify(note, null, 2) + "\n");
282
+ if (next === undefined) {
283
+ if (found !== undefined && found > i.wave)
284
+ log(`wave ${i.wave}: the plan found ${found} waves, and this run ended ${summary.outcome} (exit ${i.exitCode}), so no run starts wave ${i.wave + 1}`);
285
+ return i.exitCode;
286
+ }
287
+ // #4998: record the follow-on before it starts: its guard admits the wave this record names, and no other.
288
+ try {
289
+ if (!chainKey)
290
+ throw new Error("the run names no decided head and no commit to go on with");
291
+ const outcomes = {};
292
+ for (const [member, o] of withChainOutcomes(own, note))
293
+ outcomes[member] = { status: o.status, ...(o.by !== undefined ? { by: o.by } : {}), wave: o.wave, at: o.at };
294
+ const record = { ...chainKey, wave: next, from: i.wave, ...runOf(target.forge, env), at: (i.now ?? (() => new Date()))().toISOString(), outcomes };
295
+ await (await chainPort()).write(i.spec.name, record);
296
+ }
297
+ catch (err) {
298
+ const message = err instanceof Error ? err.message : String(err);
299
+ log(`wave ${i.wave} applied, and the follow-on for wave ${next} could not be recorded on chant/lifecycle (${message.split("\n")[0]}), so none is started: its guard would refuse it`);
300
+ return CHANT_EXIT.failed;
301
+ }
302
+ try {
303
+ const started = await (i.start ?? startFollowOn)(target, next, env);
304
+ log(`wave ${i.wave} applied; the plan found ${found} waves, so a follow-on run${started.url ? ` (${started.url})` : ""} goes on with wave ${next}`);
305
+ return i.exitCode;
306
+ }
307
+ catch (err) {
308
+ const message = err instanceof Error ? err.message : String(err);
309
+ log(`wave ${i.wave} applied, and the follow-on run for wave ${next} could not be started (${message.split("\n")[0]}); start the waves workflow by hand with ${OP_WAVES_WAVE_ENV}=${next} and this run's other inputs`);
310
+ return CHANT_EXIT.failed;
311
+ }
312
+ }
313
+ /**
314
+ * Start the follow-on run for wave `wave` through the forge's API: the
315
+ * values the run carries come from the record job's own variables (the
316
+ * decision, or the commit the run applied).
317
+ */
318
+ export async function startFollowOn(target, wave, env, fetchFn = fetch) {
319
+ const run = beforeMergeRunFromEnv(env);
320
+ const bm = isBeforeMergeRun(run);
321
+ const commit = bm ? undefined : followOnChainOf(target.forge, env)?.commit;
322
+ if (!bm && !commit)
323
+ throw new Error("the run names no commit to go on with");
324
+ const values = bm ? { pr: run.pr, head: run.head, digest: run.digest, wave: String(wave) } : { wave: String(wave), commit: commit };
325
+ const { forgeTargetFromEnv } = await import("../pr-forge.js");
326
+ const tokenEnv = [FOLLOW_ON_TOKEN_ENV, FORGE_TOKEN_VAR].find((n) => env[n]?.trim());
327
+ const t = forgeTargetFromEnv(env, { kind: target.forge, ...(tokenEnv ? { tokenEnv } : {}) });
328
+ const post = async (url, headers, body) => {
329
+ const res = await fetchFn(url, { method: "POST", headers: { ...headers, Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify(body) });
330
+ const text = await res.text();
331
+ if (!res.ok)
332
+ throw new Error(`POST ${url} answered ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
333
+ try {
334
+ return text ? JSON.parse(text) : null;
335
+ }
336
+ catch {
337
+ return null;
338
+ }
339
+ };
340
+ if (target.forge === "gitlab") {
341
+ const ref = env.CI_COMMIT_REF_NAME;
342
+ if (!ref)
343
+ throw new Error("the job names no branch (no CI_COMMIT_REF_NAME)");
344
+ const names = { pr: "CHANT_BEFORE_MERGE_PR", head: "CHANT_BEFORE_MERGE_HEAD", digest: "CHANT_BEFORE_MERGE_DIGEST", wave: OP_WAVES_WAVE_ENV, commit: OP_WAVES_COMMIT_ENV };
345
+ const variables = Object.entries(values).map(([k, value]) => ({ key: names[k], value, variable_type: "env_var" }));
346
+ const project = encodeURIComponent(decodeURIComponent(t.repo));
347
+ const v = (await post(`${t.apiBase}/projects/${project}/pipeline`, { [t.tokenHeader ?? "PRIVATE-TOKEN"]: t.token }, { ref, variables }));
348
+ return typeof v?.web_url === "string" && /^https?:\/\//.test(v.web_url) ? { url: v.web_url } : {};
349
+ }
350
+ const ref = env.GITHUB_REF_NAME?.trim() || env.GITHUB_REF?.replace(/^refs\/heads\//, "");
351
+ if (!ref)
352
+ throw new Error("the job names no branch (no GITHUB_REF_NAME)");
353
+ await post(`${t.apiBase}/repos/${t.repo}/actions/workflows/${encodeURIComponent(target.workflow)}/dispatches`, { Authorization: `token ${t.token}` }, { ref, inputs: values });
354
+ return {};
355
+ }
@@ -48,34 +48,36 @@
48
48
  * question is answered, `chant run resume --op <name>` starts the job again
49
49
  * (`pointGateResumable`, #3835).
50
50
  */
51
+ import { type OpWavePhase } from "./op-waves-split.js";
51
52
  import type { ResolvedGatePolicySource } from "../policy-source.js";
52
53
  import { type WaveMember } from "../wave-engine.js";
53
- import { type GateDigestMismatch, type GateLedgerPort } from "./gate.js";
54
+ import { type GateCheckInput, type GateDigestMismatch, type GateLedgerPort } from "./gate.js";
54
55
  import type { GateAnswerRef, PendingGateRecord } from "../lifecycle/gate-ledger.js";
55
56
  import type { GatePointAsker } from "../point-decision.js";
56
57
  import type { WaitingPoint } from "./steward-points.js";
58
+ import { type AppliedGateRecord } from "../lifecycle/gate-applied.js";
57
59
  import type { HeadPlans, ReviewSource } from "./gate-review.js";
58
60
  import type { TrustPolicy } from "../workspace/trust/policy.js";
59
61
  import type { GateSigners } from "../lifecycle/gate-seal.js";
60
62
  import type { OpRunPolicyRow, OpRunRecordInput, OpRunWavePlan, OpRunWaveTarget } from "./runtime.js";
61
63
  import { type OpWaveRunHooks } from "./op-waves-run-hooks.js";
62
- import { type OpWaveAfterPlanHook } from "./op-waves-after-plan.js";
64
+ import { type OpWaveAfterPlanHook, type OpWaveAnswerApproval } from "./op-waves-after-plan.js";
63
65
  import { type OtlpExporter } from "../otlp.js";
64
66
  import { type RunEventSink } from "../run-event-stream.js";
65
67
  import type { ChangeSetDocument, ChangeSetPart } from "../change-set.js";
66
68
  import type { CapabilityRegistry } from "../components/capability.js";
67
69
  import type { RunEventResource } from "../run-event.js";
68
- import { type OpWaveReleasePort } from "./op-waves-release.js";
70
+ import { type OpWaveReleasePort, type OpWaveReleaseRequest } from "./op-waves-release.js";
69
71
  import type { LockGrain } from "../lifecycle/lock-rows.js";
70
72
  import type { LockLiveness } from "../lifecycle/resource-lock.js";
71
73
  import type { GatePolicyExec } from "../gate-policy.js";
72
74
  import { type OpWaveNewerCommitPort } from "./op-waves-stand-down.js";
73
- import { type OpWaveHolds } from "./op-waves-capability.js";
75
+ import { type OpWaveHolds, type OpWaveStepPlan } from "./op-waves-capability.js";
74
76
  import { type GateQuorumRule, type GateQuorumRuleProgress } from "./gate-quorum.js";
75
77
  import { type GateApprovalSource, type OpWaveApplyHooksRunner, type OpWaveGatePolicy, type OpWaveHook, type OpWaveHookMoment, type OpWavePoint, type OpWavesInvolved, type OpWavesSpec } from "./op-waves.js";
76
- import { OP_WAVE_PENDING_RESERVED, opWaveArgv, runStageHooks, runStageHooksAsync, spawnExecAsync, type OpWaveAsyncExec, type OpWaveExec, type OpWaveHoldFinished, type OpWaveHoldRequest, type OpWaveHookOutcome, type OpWaveHookRun, type RunStageHooksAsyncOptions, type RunStageHooksOptions, type StageHooksRun } from "./stage-hooks.js";
78
+ import { OP_WAVE_PENDING_RESERVED, opWaveArgv, runStageHooks, runStageHooksAsync, spawnExecAsync, type OpWaveAsyncExec, type OpWaveExec, type OpWaveHoldFinished, type OpWaveHoldRequest, type OpWaveHookOutcome, type OpWaveHookRun, type OpWaveInProcessHook, type OpWaveInProcessHookCall, type RunStageHooksAsyncOptions, type RunStageHooksOptions, type StageHooksRun } from "./stage-hooks.js";
77
79
  export { OP_WAVE_PENDING_RESERVED, opWaveArgv, runStageHooks, runStageHooksAsync, spawnExecAsync };
78
- export type { OpWaveAsyncExec, OpWaveExec, OpWaveHoldFinished, OpWaveHoldRequest, OpWaveHookOutcome, OpWaveHookRun, RunStageHooksAsyncOptions, RunStageHooksOptions, StageHooksRun };
80
+ export type { OpWaveAsyncExec, OpWaveExec, OpWaveHoldFinished, OpWaveHoldRequest, OpWaveHookOutcome, OpWaveHookRun, OpWaveInProcessHook, OpWaveInProcessHookCall, RunStageHooksAsyncOptions, RunStageHooksOptions, StageHooksRun };
79
81
  /** What a run's plan command writes to `{plan}`. */
80
82
  export interface OpWavePlanFile {
81
83
  planDigest: string;
@@ -339,6 +341,12 @@ export interface OpWaveDecision {
339
341
  * workspace at base, or no policy ran.
340
342
  */
341
343
  ciPolicySource?: ResolvedGatePolicySource;
344
+ /**
345
+ * A split wave with a `step` (#4992): the rows its gate job leased for
346
+ * the applying jobs, held with no heartbeat until its record job lets go
347
+ * of them, or the forge says the run is gone.
348
+ */
349
+ lease?: OpWaveSplitLease;
342
350
  }
343
351
  /**
344
352
  * The plans the merged pull request previewed for a wave, against the plans
@@ -406,6 +414,37 @@ export interface OpWaveHeldOn {
406
414
  * approved, oldest first (#3847): its approved re-runs asked for this one.
407
415
  */
408
416
  after?: OpWaveHeldOnApproval[];
417
+ /**
418
+ * Set by a split wave's plan or apply job (#4992), which holds no write
419
+ * token: the pending fact it read the gate for and did not record, and
420
+ * the file the request carries. The gate job (for a plan job's hold) or
421
+ * the record job (for an apply job's) records them and drops this.
422
+ *
423
+ * `spend` (#4994): the gate is approved and the hold asks chant to
424
+ * `record` it, so its approval is spent before the hook runs again. The
425
+ * plan job cannot spend it; the gate job checks the approval again under
426
+ * its own rules and spends it for a re-run of the hook at `head`, and the
427
+ * wave waits until it runs again from its plan job.
428
+ */
429
+ deferred?: {
430
+ input: GateCheckInput;
431
+ mode: GateApprovalSource;
432
+ base: string;
433
+ attachment?: string;
434
+ spend?: {
435
+ approvedBy: string;
436
+ approvedAt: string;
437
+ head?: string;
438
+ };
439
+ };
440
+ /**
441
+ * Set by a split wave's plan job (#4994): the applied line the gate job of
442
+ * an earlier run of the same head wrote for this hold, with no finished
443
+ * line yet. The hook runs again under it, and the next gate job writes the
444
+ * finished line. On a decision it says the approval was spent for that
445
+ * re-run and the wave waits for it.
446
+ */
447
+ spentForRerun?: AppliedGateRecord;
409
448
  }
410
449
  /** An approved hold on another gate (#3847), as `CHANT_HOLD_APPROVED` and `CHANT_HOLDS_APPROVED` carry it. */
411
450
  export interface OpWaveHeldOnApproval {
@@ -570,6 +609,17 @@ export interface RunOpWaveOptions {
570
609
  * {@link opWaveChecksDir} and no outcome file or run record.
571
610
  */
572
611
  policyOnly?: boolean;
612
+ /**
613
+ * One of the four jobs of a split wave before merge (#4987,
614
+ * `./op-waves-split.ts`). `plan`: plan the wave and save the plan
615
+ * ({@link OpWaveSavedPlan}), writing nothing to `chant/lifecycle`. `gate`:
616
+ * read the rules at base, check the saved plan against its plan files,
617
+ * and decide the gate on it as a deciding job does. `apply`: apply the
618
+ * saved plan files whose digest the decision holds, as a share job does,
619
+ * and leave the run record in a file. `record`: write those run records
620
+ * to the run ledger. A `step` spec cannot run in phases.
621
+ */
622
+ phase?: OpWavePhase;
573
623
  /** Apply this 1-based share of a decided wave, or with `group`, of that job group. */
574
624
  share?: number;
575
625
  /**
@@ -703,6 +753,16 @@ export interface RunOpWaveOptions {
703
753
  * while a hook does. Default: `exec`, which waits with `spawnSync`.
704
754
  */
705
755
  hookExec?: OpWaveAsyncExec;
756
+ /**
757
+ * Hooks served in the job's own process (#4994), by the spec hook's
758
+ * `name`: a hook the spec names (read at base) whose name this holds is
759
+ * called with its command's argv and variables in place of running the
760
+ * command, at every moment and in every job that runs it, a split wave's
761
+ * plan, gate and applying jobs included. Its exit code counts as the
762
+ * command's, and its approved re-run after a hold on another gate calls it
763
+ * again. See {@link OpWaveInProcessHook}.
764
+ */
765
+ inProcessHooks?: Readonly<Record<string, OpWaveInProcessHook>>;
706
766
  }
707
767
  /** Where an op wave job's run record goes (#4551). */
708
768
  export interface OpWaveRunPort {
@@ -760,6 +820,8 @@ export interface RunOpWaveResult {
760
820
  plans?: Record<string, OpRunWavePlan>;
761
821
  /** With `policyOnly` (#4926): the `ci.policy` rows the wave's policy hold gave, in run order. Empty when no policy ran. */
762
822
  policyRows?: OpRunPolicyRow[];
823
+ /** A split wave's applying job (#4992): what its record job writes with the token, beside the run record. */
824
+ handoff?: OpWaveSplitHandoff;
763
825
  }
764
826
  /**
765
827
  * A wave's set digest (#3821): {@link waveSetDigest} over its runs' plans,
@@ -772,6 +834,18 @@ export declare function opWaveSetDigest(spec: Pick<OpWavesSpec, "digest">, membe
772
834
  }>, extras?: readonly WaveMember[]): string;
773
835
  /** How many gates one hook call holds a wave on in turn (#3847): the first hold and the holds its approved re-runs ask for. */
774
836
  export declare const OP_WAVE_MAX_CHAINED_HOLDS = 10;
837
+ /**
838
+ * A held hook's re-run in a split wave's plan job under an approval an
839
+ * earlier gate job spent (#4994): how it ended, which the gate job after
840
+ * this plan job writes as the finished line.
841
+ */
842
+ export interface OpWaveHandedFinished {
843
+ hook: string;
844
+ /** The applied line the re-run ran under. */
845
+ applied: Pick<AppliedGateRecord, "op" | "gate" | "planDigest" | "timestamp" | "rerun">;
846
+ result: "applied" | "failed";
847
+ detail?: Record<string, string | number | boolean>;
848
+ }
775
849
  /**
776
850
  * Read the hooks file chant hands an apply command (#3804): the one at
777
851
  * `path`, by default `CHANT_HOOKS`. Null when there is none, as for an apply
@@ -843,6 +917,72 @@ export declare function opWaveRunRecord(options: Pick<RunOpWaveOptions, "spec" |
843
917
  } | {
844
918
  error: unknown;
845
919
  }): OpRunRecordInput;
920
+ /**
921
+ * What a split wave's plan job saves for its gate and applying jobs
922
+ * (#4987), at {@link opWaveSavedPlanPath} beside the run plan files: the
923
+ * plans and their set digest, what the holds and hooks said of them, and
924
+ * the runs a failure blocked. `end` instead: the plan job ended the wave,
925
+ * with that result, and the gate job records it.
926
+ */
927
+ export interface OpWaveSavedPlan {
928
+ version: 1;
929
+ op: string;
930
+ wave: number;
931
+ name: string;
932
+ end?: RunOpWaveResult;
933
+ digest?: string;
934
+ members?: OpWaveMember[];
935
+ extras?: WaveMember[];
936
+ pending?: Record<string, unknown>;
937
+ overriders?: string[];
938
+ overridersSource?: string;
939
+ changeSet?: ChangeSetDocument;
940
+ /** The holds of the rules at base, the wave's holds and the in-process after-plan hooks. */
941
+ holds?: string[];
942
+ /** The holds of the before-plan hooks. */
943
+ before?: string[];
944
+ blocked?: Record<string, string>;
945
+ report?: string;
946
+ answerApprovals?: OpWaveAnswerApproval[];
947
+ ciPolicySource?: ResolvedGatePolicySource;
948
+ discovered?: {
949
+ waves?: number;
950
+ };
951
+ hooks?: OpWaveHookOutcome[];
952
+ plans?: Record<string, OpRunWavePlan>;
953
+ /**
954
+ * With a `step` (#4992): each run's plan through it, without the engine's
955
+ * artifact, its change-set part or the wave's group plan. The gate job
956
+ * leases the rows these name; the applying job plans its runs again
957
+ * through the step and applies each whose plan digest the decision holds.
958
+ */
959
+ steps?: OpWaveSavedStep[];
960
+ /**
961
+ * The held hooks the plan job ran again under an approval an earlier gate
962
+ * job spent for them (#4994), and how each ended: the gate job writes
963
+ * their finished lines, whatever else the plan job came to.
964
+ */
965
+ holdsFinished?: OpWaveHandedFinished[];
966
+ }
967
+ /** A run's step plan as a split wave's plan job saves it (#4992). */
968
+ export type OpWaveSavedStep = Omit<OpWaveStepPlan, "artifact" | "part" | "group">;
969
+ /**
970
+ * What a split wave's applying job hands its record job beside its run
971
+ * record (#4992): the release records of the runs it applied through the
972
+ * step, and a hold on another gate its hooks found waiting, which the
973
+ * record job writes with the token.
974
+ */
975
+ export interface OpWaveSplitHandoff {
976
+ releases?: OpWaveReleaseRequest[];
977
+ heldOn?: OpWaveHeldOn;
978
+ }
979
+ /** The lease a split wave's gate job takes for the wave's rows (#4992), which its record job lets go of. */
980
+ export interface OpWaveSplitLease {
981
+ gate: string;
982
+ /** The holder the rows name: the forge's run, the same in every job of it. */
983
+ run: string;
984
+ keys: string[];
985
+ }
846
986
  /** How many times one wave job plans again when its apply asks to (#3821). */
847
987
  export declare const OP_WAVE_MAX_REPLANS = 10;
848
988
  /** Where a wave's reports go for the job that explains a moved approval (#4842), relative to the job's directory. */