@intentius/chant 0.124.57 → 0.124.59

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 (163) hide show
  1. package/dist/ci-product-words.d.ts +47 -2
  2. package/dist/ci-product-words.d.ts.map +1 -1
  3. package/dist/ci-product-words.js +59 -1
  4. package/dist/ci-product.d.ts +26 -2
  5. package/dist/ci-product.d.ts.map +1 -1
  6. package/dist/ci-product.js +25 -2
  7. package/dist/cli/commands/init.d.ts +2 -0
  8. package/dist/cli/commands/init.d.ts.map +1 -1
  9. package/dist/cli/commands/init.js +1 -1
  10. package/dist/cli/handlers/build.d.ts.map +1 -1
  11. package/dist/cli/handlers/build.js +5 -1
  12. package/dist/cli/handlers/init.d.ts.map +1 -1
  13. package/dist/cli/handlers/init.js +16 -0
  14. package/dist/cli/handlers/lifecycle-drift.d.ts +2 -1
  15. package/dist/cli/handlers/lifecycle-drift.d.ts.map +1 -1
  16. package/dist/cli/handlers/lifecycle-drift.js +4 -2
  17. package/dist/cli/handlers/lock.d.ts.map +1 -1
  18. package/dist/cli/handlers/lock.js +45 -2
  19. package/dist/cli/handlers/serve.d.ts.map +1 -1
  20. package/dist/cli/handlers/serve.js +9 -0
  21. package/dist/cli/main.d.ts.map +1 -1
  22. package/dist/cli/main.js +11 -3
  23. package/dist/cli/mcp/product-tools.d.ts +40 -7
  24. package/dist/cli/mcp/product-tools.d.ts.map +1 -1
  25. package/dist/cli/mcp/product-tools.js +58 -15
  26. package/dist/cli/mcp/read-only.d.ts +2 -1
  27. package/dist/cli/mcp/read-only.d.ts.map +1 -1
  28. package/dist/cli/mcp/read-only.js +2 -1
  29. package/dist/cli/mcp/server.d.ts +11 -0
  30. package/dist/cli/mcp/server.d.ts.map +1 -1
  31. package/dist/cli/mcp/server.js +15 -3
  32. package/dist/cli/mcp-config.d.ts +4 -1
  33. package/dist/cli/mcp-config.d.ts.map +1 -1
  34. package/dist/cli/mcp-config.js +6 -2
  35. package/dist/cli/parse-args.d.ts.map +1 -1
  36. package/dist/cli/parse-args.js +27 -0
  37. package/dist/cli/registry.d.ts +14 -0
  38. package/dist/cli/registry.d.ts.map +1 -1
  39. package/dist/components/pr-pipeline.d.ts +56 -0
  40. package/dist/components/pr-pipeline.d.ts.map +1 -1
  41. package/dist/components/pr-pipeline.js +55 -2
  42. package/dist/components/product-pipeline.d.ts +18 -1
  43. package/dist/components/product-pipeline.d.ts.map +1 -1
  44. package/dist/components/product-pipeline.js +8 -2
  45. package/dist/drift-record.d.ts +5 -0
  46. package/dist/drift-record.d.ts.map +1 -1
  47. package/dist/e2e-harness/driver.d.ts.map +1 -1
  48. package/dist/e2e-harness/driver.js +97 -0
  49. package/dist/e2e-harness/forgejo.d.ts +5 -1
  50. package/dist/e2e-harness/forgejo.d.ts.map +1 -1
  51. package/dist/e2e-harness/forgejo.js +35 -0
  52. package/dist/e2e-harness/index.d.ts +7 -0
  53. package/dist/e2e-harness/index.d.ts.map +1 -1
  54. package/dist/e2e-harness/index.js +10 -1
  55. package/dist/e2e-harness/ports.d.ts +31 -0
  56. package/dist/e2e-harness/ports.d.ts.map +1 -1
  57. package/dist/e2e-harness/scenario.d.ts.map +1 -1
  58. package/dist/e2e-harness/scenario.js +9 -5
  59. package/dist/e2e-harness/schemas/e2e-scenario.schema.json +43 -3
  60. package/dist/e2e-harness/schemas/index.d.ts +22 -1
  61. package/dist/e2e-harness/schemas/index.d.ts.map +1 -1
  62. package/dist/e2e-harness/schemas/index.js +1 -1
  63. package/dist/e2e-harness/steps.d.ts.map +1 -1
  64. package/dist/e2e-harness/steps.js +4 -0
  65. package/dist/lifecycle/lock-beat.d.ts +27 -0
  66. package/dist/lifecycle/lock-beat.d.ts.map +1 -0
  67. package/dist/lifecycle/lock-beat.js +84 -0
  68. package/dist/lifecycle/resource-lock.d.ts +54 -1
  69. package/dist/lifecycle/resource-lock.d.ts.map +1 -1
  70. package/dist/lifecycle/resource-lock.js +128 -7
  71. package/dist/mcp/types.d.ts +9 -0
  72. package/dist/mcp/types.d.ts.map +1 -1
  73. package/dist/op/activities/activity-contracts.d.ts +4 -4
  74. package/dist/op/index.d.ts +1 -1
  75. package/dist/op/index.d.ts.map +1 -1
  76. package/dist/op/index.js +1 -1
  77. package/dist/op/op-waves-notify.d.ts.map +1 -1
  78. package/dist/op/op-waves-notify.js +11 -0
  79. package/dist/op/op-waves-run.d.ts +28 -1
  80. package/dist/op/op-waves-run.d.ts.map +1 -1
  81. package/dist/op/op-waves-run.js +92 -7
  82. package/dist/op/op-waves.d.ts +12 -1
  83. package/dist/op/op-waves.d.ts.map +1 -1
  84. package/dist/op/op-waves.js +9 -2
  85. package/dist/release-floors.d.ts +1 -1
  86. package/dist/release-floors.js +1 -1
  87. package/dist/template-request/index.d.ts +9 -0
  88. package/dist/template-request/index.d.ts.map +1 -0
  89. package/dist/template-request/index.js +8 -0
  90. package/dist/template-request/request-body.d.ts +21 -0
  91. package/dist/template-request/request-body.d.ts.map +1 -0
  92. package/dist/template-request/request-body.js +86 -0
  93. package/dist/template-request/template-request.d.ts +100 -0
  94. package/dist/template-request/template-request.d.ts.map +1 -0
  95. package/dist/template-request/template-request.js +149 -0
  96. package/dist/template-request/template-request.schema.json +100 -0
  97. package/dist/template-request/template-spec.d.ts +83 -0
  98. package/dist/template-request/template-spec.d.ts.map +1 -0
  99. package/dist/template-request/template-spec.js +146 -0
  100. package/dist/template-request/template.schema.json +114 -0
  101. package/dist/template-request/validate.d.ts +4 -0
  102. package/dist/template-request/validate.d.ts.map +1 -0
  103. package/dist/template-request/validate.js +21 -0
  104. package/dist/wave-runtime.mjs +298 -298
  105. package/dist/workspace/drift-cli.d.ts +13 -1
  106. package/dist/workspace/drift-cli.d.ts.map +1 -1
  107. package/dist/workspace/drift-cli.js +19 -3
  108. package/package.json +8 -1
  109. package/src/ci-product-words.test.ts +23 -0
  110. package/src/ci-product-words.ts +68 -3
  111. package/src/ci-product.ts +31 -1
  112. package/src/cli/commands/init.ts +3 -1
  113. package/src/cli/handlers/build.ts +5 -1
  114. package/src/cli/handlers/init.ts +18 -0
  115. package/src/cli/handlers/lifecycle-drift.test.ts +52 -0
  116. package/src/cli/handlers/lifecycle-drift.ts +4 -2
  117. package/src/cli/handlers/lock.ts +41 -2
  118. package/src/cli/handlers/serve.ts +9 -0
  119. package/src/cli/main.ts +11 -3
  120. package/src/cli/mcp/product-tools.test.ts +56 -1
  121. package/src/cli/mcp/product-tools.ts +66 -15
  122. package/src/cli/mcp/read-only.ts +2 -1
  123. package/src/cli/mcp/server.ts +20 -5
  124. package/src/cli/mcp-config.test.ts +52 -2
  125. package/src/cli/mcp-config.ts +6 -3
  126. package/src/cli/parse-args.ts +19 -0
  127. package/src/cli/registry.ts +14 -0
  128. package/src/components/pr-pipeline.ts +87 -2
  129. package/src/components/product-actions.test.ts +76 -0
  130. package/src/components/product-pipeline.ts +21 -2
  131. package/src/drift-record.ts +5 -0
  132. package/src/e2e-harness/driver.test.ts +163 -0
  133. package/src/e2e-harness/driver.ts +86 -1
  134. package/src/e2e-harness/forgejo.ts +42 -1
  135. package/src/e2e-harness/index.ts +11 -1
  136. package/src/e2e-harness/ports.ts +33 -0
  137. package/src/e2e-harness/scenario.ts +8 -6
  138. package/src/e2e-harness/schemas/README.md +11 -2
  139. package/src/e2e-harness/schemas/e2e-scenario.schema.json +43 -3
  140. package/src/e2e-harness/schemas/index.ts +5 -1
  141. package/src/e2e-harness/schemas.test.ts +44 -1
  142. package/src/e2e-harness/steps.ts +4 -0
  143. package/src/lifecycle/lock-beat.ts +99 -0
  144. package/src/lifecycle/resource-lock-liveness.test.ts +289 -0
  145. package/src/lifecycle/resource-lock.ts +143 -8
  146. package/src/mcp/types.ts +9 -0
  147. package/src/op/index.ts +1 -0
  148. package/src/op/op-waves-notify.ts +11 -0
  149. package/src/op/op-waves-preview.test.ts +167 -0
  150. package/src/op/op-waves-run.ts +116 -8
  151. package/src/op/op-waves.ts +20 -3
  152. package/src/release-floors.ts +1 -1
  153. package/src/template-request/__fixtures__/request-body.md +41 -0
  154. package/src/template-request/index.ts +8 -0
  155. package/src/template-request/request-body.ts +91 -0
  156. package/src/template-request/template-request.schema.json +100 -0
  157. package/src/template-request/template-request.test.ts +315 -0
  158. package/src/template-request/template-request.ts +234 -0
  159. package/src/template-request/template-spec.ts +176 -0
  160. package/src/template-request/template.schema.json +114 -0
  161. package/src/template-request/validate.ts +28 -0
  162. package/src/workspace/drift-cli.test.ts +35 -1
  163. package/src/workspace/drift-cli.ts +21 -3
@@ -50,6 +50,7 @@
50
50
  import { hostname } from "node:os";
51
51
  import { getRuntime } from "../runtime-adapter";
52
52
  import { pushLifecycleStatus, readBlobBySha, readPathSha, RefCASConflictError, writeBlobToPath } from "./git";
53
+ import { ownBeatStarter } from "./lock-beat";
53
54
  import { lockRowsConflict, sortedLockRows, type LockRow } from "./lock-rows";
54
55
  import { dropRefusedWrite, fetchForLocks, localTip, LOCKS_DIR, targetLockGateProblem } from "./target-lock";
55
56
 
@@ -59,6 +60,15 @@ export const LOCK_ROWS_DIR = `${LOCKS_DIR}/rows`;
59
60
  /** A lease older than this many seconds is taken over (`CHANT_LOCK_STALE`). */
60
61
  export const DEFAULT_LOCK_STALE_SECONDS = 7200;
61
62
 
63
+ /** A hold whose beat is older than this many seconds is gone (`CHANT_LOCK_BEAT_STALE`, #4660). */
64
+ export const DEFAULT_LOCK_BEAT_STALE_SECONDS = 600;
65
+
66
+ /** How often a live apply touches its hold, in seconds (`CHANT_LOCK_BEAT`, #4660). */
67
+ export const DEFAULT_LOCK_BEAT_SECONDS = 60;
68
+
69
+ /** A queued run that has not refreshed its entry for this many seconds is gone (`CHANT_LOCK_WAITER_STALE`, #4660). */
70
+ export const DEFAULT_LOCK_WAITER_STALE_SECONDS = 300;
71
+
62
72
  const STATE_BRANCH = "chant/lifecycle";
63
73
  const ATTEMPTS = 30;
64
74
 
@@ -69,6 +79,15 @@ export interface LockRowHolder {
69
79
  /** The run's page, for a refusal that names it. */
70
80
  url?: string;
71
81
  sha?: string;
82
+ /**
83
+ * The liveness token (#4660): the last time a heartbeat of the run's own
84
+ * process touched its hold. A holder with a beat is judged by the beat
85
+ * alone, so a job that is cancelled or killed without running its cleanup
86
+ * frees its rows once the beat is {@link lockBeatStaleSeconds} old, while a
87
+ * job that still beats keeps them however long its apply runs. A holder
88
+ * without one (an older chant, terragucci) keeps the rules below.
89
+ */
90
+ beat?: string;
72
91
  }
73
92
 
74
93
  /** A run waiting for rows: who it is, the rows it waits for, and the commit time that orders it. */
@@ -114,6 +133,26 @@ export function lockStaleSeconds(env: Record<string, string | undefined>): numbe
114
133
  return DEFAULT_LOCK_STALE_SECONDS;
115
134
  }
116
135
 
136
+ function positiveSeconds(env: Record<string, string | undefined>, name: string, fallback: number): number {
137
+ const n = Number(env[name]);
138
+ return env[name] !== undefined && Number.isFinite(n) && n > 0 ? n : fallback;
139
+ }
140
+
141
+ /** How old a hold's beat may be before the hold is gone, in seconds: `CHANT_LOCK_BEAT_STALE`, else {@link DEFAULT_LOCK_BEAT_STALE_SECONDS}. */
142
+ export function lockBeatStaleSeconds(env: Record<string, string | undefined>): number {
143
+ return positiveSeconds(env, "CHANT_LOCK_BEAT_STALE", DEFAULT_LOCK_BEAT_STALE_SECONDS);
144
+ }
145
+
146
+ /** Seconds between beats: `CHANT_LOCK_BEAT`, else {@link DEFAULT_LOCK_BEAT_SECONDS}. */
147
+ export function lockBeatSeconds(env: Record<string, string | undefined>): number {
148
+ return positiveSeconds(env, "CHANT_LOCK_BEAT", DEFAULT_LOCK_BEAT_SECONDS);
149
+ }
150
+
151
+ /** How old a queued run's entry may be before it is gone, in seconds: `CHANT_LOCK_WAITER_STALE`, else {@link DEFAULT_LOCK_WAITER_STALE_SECONDS}. */
152
+ export function lockWaiterStaleSeconds(env: Record<string, string | undefined>): number {
153
+ return positiveSeconds(env, "CHANT_LOCK_WAITER_STALE", DEFAULT_LOCK_WAITER_STALE_SECONDS);
154
+ }
155
+
117
156
  /** Who this apply is, as the rows name it: the forge's run, or this host and process outside CI. */
118
157
  export function lockRowHolder(env: Record<string, string | undefined>, now: Date = new Date()): LockRowHolder {
119
158
  const gitlab = Boolean(env.CI_PIPELINE_ID);
@@ -137,7 +176,13 @@ type Fetch = (url: string, init?: { headers?: Record<string, string> }) => Promi
137
176
  */
138
177
  export function forgeLockLiveness(env: Record<string, string | undefined>, fetch: Fetch = globalThis.fetch as unknown as Fetch, now: () => number = Date.now): LockLiveness {
139
178
  const stale = lockStaleSeconds(env);
179
+ const beatStale = lockBeatStaleSeconds(env);
140
180
  return async (h) => {
181
+ // #4660: a hold that carries a beat is judged by it alone. The forge may call a cancelled run finished while its process still applies, and an apply may outlast the lease; the beat says whether the process is there.
182
+ if (h.beat !== undefined) {
183
+ const beat = new Date(h.beat).getTime();
184
+ if (Number.isFinite(beat)) return now() - beat >= beatStale * 1000 ? "dead" : "alive";
185
+ }
141
186
  const since = new Date(h.at).getTime();
142
187
  if (Number.isFinite(since) && now() - since >= stale * 1000) return "dead";
143
188
  const local = /^local:(.*):(\d+)$/.exec(h.run);
@@ -180,7 +225,7 @@ export function parseLockRows(text: string | null): LockRowsFile {
180
225
  const holders: Record<string, LockRowHolder> = {};
181
226
  for (const [id, raw] of Object.entries(doc.holders as Record<string, Record<string, unknown>>)) {
182
227
  if (typeof raw?.run !== "string" || typeof raw.at !== "string") continue;
183
- holders[id] = { run: raw.run, at: raw.at, ...(typeof raw.url === "string" ? { url: raw.url } : {}), ...(typeof raw.sha === "string" ? { sha: raw.sha } : {}) };
228
+ holders[id] = { run: raw.run, at: raw.at, ...(typeof raw.url === "string" ? { url: raw.url } : {}), ...(typeof raw.sha === "string" ? { sha: raw.sha } : {}), ...(typeof raw.beat === "string" ? { beat: raw.beat } : {}) };
184
229
  }
185
230
  const rows: Record<string, string> = {};
186
231
  for (const [k, id] of Object.entries(doc.rows as Record<string, unknown>)) if (typeof id === "string" && holders[id]) rows[k] = id;
@@ -434,13 +479,16 @@ export async function commitTimeOf(rev: string, cwd?: string): Promise<string |
434
479
  }
435
480
 
436
481
  /** The live waiters for a row that meets one of `keys` who go before `me`, and the waiters that are gone. */
437
- export async function waitersAhead(file: LockRowsFile, keys: readonly string[], me: LockRowWaiter, alive: LockLiveness): Promise<{ ahead: LockRowWaiter[]; gone: string[] }> {
482
+ export async function waitersAhead(file: LockRowsFile, keys: readonly string[], me: LockRowWaiter, alive: LockLiveness, now: () => number = Date.now): Promise<{ ahead: LockRowWaiter[]; gone: string[] }> {
438
483
  const ahead: LockRowWaiter[] = [];
439
484
  const gone: string[] = [];
485
+ const waiterStale = lockWaiterStaleSeconds(process.env) * 1000;
440
486
  for (const [id, w] of Object.entries(file.waiting ?? {})) {
441
487
  if (id === me.run || w.run === me.run) continue;
442
488
  if (!w.keys.some((k) => keys.some((mine) => lockRowsConflict(k, mine)))) continue;
443
- const verdict = await alive(w);
489
+ // #4660: a waiter refreshes its entry every few poll rounds, so one that has not is gone (cancelled or killed), whatever the forge says.
490
+ const entered = new Date(w.at).getTime();
491
+ const verdict = Number.isFinite(entered) && now() - entered >= waiterStale ? "dead" : await alive(w);
444
492
  if (verdict === "dead") {
445
493
  gone.push(id);
446
494
  continue;
@@ -450,6 +498,13 @@ export async function waitersAhead(file: LockRowsFile, keys: readonly string[],
450
498
  return { ahead: ahead.sort((a, b) => (waiterBefore(a, b) ? -1 : 1)), gone: gone.sort() };
451
499
  }
452
500
 
501
+ /** When each live holder took its rows and last beat, for a wait that gave up (#4660). */
502
+ function holdAges(held: readonly HeldLockRow[]): string {
503
+ const runs = [...new Map(held.map((h) => [h.holder.run, h.holder])).values()];
504
+ if (runs.length === 0) return "";
505
+ return ` (${runs.map((h) => `run ${h.run} took its rows at ${h.at}${h.beat ? `, last beat ${h.beat}` : ", no beat"}`).join("; ")})`;
506
+ }
507
+
453
508
  function describeWait(held: readonly HeldLockRow[], ahead: readonly LockRowWaiter[], rows: readonly LockRow[]): string {
454
509
  const parts: string[] = [];
455
510
  if (held.length > 0) parts.push(describeHeldLockRows(held, rows));
@@ -481,7 +536,7 @@ export async function waitLockRows(gate: string, rows: readonly LockRow[], me: L
481
536
  const { sha, file } = await readCurrent(gate, opts.cwd);
482
537
  const mine = queued ?? waiter();
483
538
  const { live, gone } = await heldLockRowsIn(file, keys, me.run, alive);
484
- const { ahead, gone: goneWaiters } = await waitersAhead(file, keys, mine, alive);
539
+ const { ahead, gone: goneWaiters } = await waitersAhead(file, keys, mine, alive, now);
485
540
  if (live.length === 0 && ahead.length === 0) {
486
541
  const next = withRowsTaken(file, keys, me, gone);
487
542
  for (const id of goneWaiters) delete next.waiting?.[id];
@@ -496,10 +551,10 @@ export async function waitLockRows(gate: string, rows: readonly LockRow[], me: L
496
551
  if (now() >= wait.deadline) {
497
552
  await leaveQueue(gate, me.run, opts.cwd);
498
553
  const waited = Math.round((now() - started) / 1000);
499
- throw new LockWaitTimeoutError(`waited ${waited}s for ${keys.join(", ")} of ${gate} and gave up at the job's deadline: ${why}`, live, ahead, waited);
554
+ throw new LockWaitTimeoutError(`waited ${waited}s for ${keys.join(", ")} of ${gate} and gave up at the job's deadline: ${why}${holdAges(live)}. If a run named here is gone, chant unlock --run <id> --gate ${gate} frees its rows`, live, ahead, waited);
500
555
  }
501
556
  const inFile = file.waiting?.[me.run];
502
- const refresh = inFile ? now() - new Date(inFile.at).getTime() > stale / 2 : true;
557
+ const refresh = inFile ? now() - new Date(inFile.at).getTime() > Math.min(stale / 2, (lockWaiterStaleSeconds(process.env) * 1000) / 3) : true;
503
558
  if (!inFile || refresh || goneWaiters.length > 0) {
504
559
  const entry: LockRowWaiter = { ...waiter(), at: new Date(now()).toISOString() };
505
560
  const wrote = await writeAndPush(gate, sha, withWaiter(file, entry, goneWaiters), `Run ${me.run} waits for ${keys.length} row${keys.length === 1 ? "" : "s"} of ${gate}`, opts.cwd);
@@ -556,6 +611,63 @@ export async function releaseLockRows(gate: string, keys: readonly string[], me:
556
611
  return false;
557
612
  }
558
613
 
614
+ /** The rows file after run `run`'s beat is set to `at`. Unchanged when the run holds no row. */
615
+ export function withRowsBeat(file: LockRowsFile, run: string, at: string): LockRowsFile {
616
+ const holder = file.holders[run];
617
+ if (!holder || !Object.values(file.rows).includes(run)) return file;
618
+ const next = copyRows(file);
619
+ next.holders[run] = { ...holder, beat: at };
620
+ return next;
621
+ }
622
+
623
+ /**
624
+ * Touch run `run`'s hold (#4660): the heartbeat of a live apply. `held` while
625
+ * the run still holds a row, `gone` once it holds none (released, or taken
626
+ * over after its beat went stale), so the heartbeat stops.
627
+ */
628
+ export async function beatLockRows(gate: string, run: string, at: string, opts: { cwd?: string } = {}): Promise<"held" | "gone"> {
629
+ checkGate(gate);
630
+ await fetchForLocks(opts.cwd);
631
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
632
+ const { sha, file } = await readCurrent(gate, opts.cwd);
633
+ if (!Object.values(file.rows).includes(run)) return "gone";
634
+ const wrote = await writeAndPush(gate, sha, withRowsBeat(file, run, at), `Run ${run} still holds its rows of ${gate}`, opts.cwd);
635
+ if (wrote) return "held";
636
+ await pause(200 + Math.floor(Math.random() * 800));
637
+ }
638
+ throw new Error(`could not touch the hold of run ${run} on ${gate}: ${STATE_BRANCH} kept moving`);
639
+ }
640
+
641
+ /** The rows file after every hold and queue entry of `run` is dropped, whether or not the run is gone. */
642
+ export function withRunCleared(file: LockRowsFile, run: string): LockRowsFile {
643
+ const next = copyRows(file);
644
+ delete next.holders[run];
645
+ for (const [k, id] of Object.entries(next.rows)) if (id === run) delete next.rows[k];
646
+ delete next.waiting?.[run];
647
+ return tidyWaiting(next);
648
+ }
649
+
650
+ /**
651
+ * Let go of everything run `run` holds or waits for on `gate`, by hand
652
+ * (#4660, `chant unlock --run`). It does not ask whether the run is alive:
653
+ * the person who runs it says so. Throws when the branch cannot be read or
654
+ * pushed, so a hold that is still there is never reported as cleared.
655
+ */
656
+ export async function clearRunLockRows(gate: string, run: string, opts: { cwd?: string } = {}): Promise<{ released: string[]; waited: boolean; pushed: boolean }> {
657
+ checkGate(gate);
658
+ await fetchForLocks(opts.cwd);
659
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
660
+ const { sha, file } = await readCurrent(gate, opts.cwd);
661
+ const released = Object.entries(file.rows).filter(([, id]) => id === run).map(([k]) => k).sort();
662
+ const waited = file.waiting?.[run] !== undefined;
663
+ if (released.length === 0 && !file.holders[run] && !waited) return { released, waited, pushed: false };
664
+ const wrote = await writeAndPush(gate, sha, withRunCleared(file, run), `Clear the hold of run ${run} on ${gate}`, opts.cwd);
665
+ if (wrote) return { released, waited, pushed: wrote.pushed };
666
+ await pause(200 + Math.floor(Math.random() * 800));
667
+ }
668
+ throw new Error(`could not clear run ${run} from ${gate}: ${STATE_BRANCH} kept moving; check that the job may push to it`);
669
+ }
670
+
559
671
  /** One line naming the runs that hold rows, and what of this apply they hold, for a log line and a refusal. */
560
672
  export function describeHeldLockRows(held: readonly HeldLockRow[], rows: readonly LockRow[]): string {
561
673
  const address = new Map(rows.map((r) => [r.key, `${r.target}: ${r.address}`]));
@@ -578,6 +690,9 @@ export interface LockRowsLease {
578
690
  release(): Promise<boolean>;
579
691
  }
580
692
 
693
+ /** Starts the heartbeat of a hold (#4660) and returns how to stop it. */
694
+ export type LockBeatStarter = (hold: { gate: string; holder: LockRowHolder; cwd?: string }) => () => void;
695
+
581
696
  /**
582
697
  * Lease `rows` for the apply about to run (#4552): take them, or say who
583
698
  * holds them. With no rows, a lease that holds nothing. Throws when the
@@ -587,15 +702,34 @@ export interface LockRowsLease {
587
702
  export async function leaseLockRows(
588
703
  gate: string,
589
704
  rows: readonly LockRow[],
590
- opts: LockRowsOptions & { holder?: LockRowHolder; wait?: LockRowsWait } = {},
705
+ opts: LockRowsOptions & { holder?: LockRowHolder; wait?: LockRowsWait; beat?: LockBeatStarter } = {},
591
706
  ): Promise<{ ok: true; lease: LockRowsLease; tookOver: LockRowHolder[]; waitedSeconds?: number; waited?: boolean } | { ok: false; held: HeldLockRow[]; message: string; timedOut?: true }> {
592
707
  const holder = opts.holder ?? lockRowHolder(process.env);
593
708
  const keys = sortedLockRows(rows).map((r) => r.key);
594
- const lease: LockRowsLease = { gate, holder, keys, release: () => (keys.length === 0 ? Promise.resolve(true) : releaseLockRows(gate, keys, holder.run, { ...(opts.cwd ? { cwd: opts.cwd } : {}) })) };
709
+ let stopBeat: (() => void) | undefined;
710
+ const lease: LockRowsLease = {
711
+ gate,
712
+ holder,
713
+ keys,
714
+ release: () => {
715
+ // The beat stops first, so it cannot touch a hold that is being let go.
716
+ stopBeat?.();
717
+ stopBeat = undefined;
718
+ return keys.length === 0 ? Promise.resolve(true) : releaseLockRows(gate, keys, holder.run, { ...(opts.cwd ? { cwd: opts.cwd } : {}) });
719
+ },
720
+ };
595
721
  if (keys.length === 0) return { ok: true, lease, tookOver: [] };
722
+ const startBeat = () => {
723
+ try {
724
+ stopBeat = (opts.beat ?? ownBeatStarter())?.({ gate, holder, ...(opts.cwd ? { cwd: opts.cwd } : {}) });
725
+ } catch {
726
+ // No beat: the hold keeps the forge and lease rules.
727
+ }
728
+ };
596
729
  if (opts.wait) {
597
730
  try {
598
731
  const waited = await waitLockRows(gate, rows, holder, opts.wait, opts);
732
+ startBeat();
599
733
  return { ok: true, lease, tookOver: waited.tookOver, ...(waited.waited ? { waited: true, waitedSeconds: waited.waitedSeconds } : {}) };
600
734
  } catch (err) {
601
735
  if (err instanceof LockWaitTimeoutError) return { ok: false, held: err.held, message: err.message, timedOut: true };
@@ -604,5 +738,6 @@ export async function leaseLockRows(
604
738
  }
605
739
  const taken = await takeLockRows(gate, rows, holder, opts);
606
740
  if (!taken.ok) return { ok: false, held: taken.held, message: describeHeldLockRows(taken.held, rows) };
741
+ startBeat();
607
742
  return { ok: true, lease, tookOver: taken.tookOver };
608
743
  }
package/src/mcp/types.ts CHANGED
@@ -18,6 +18,15 @@ export interface McpToolContribution {
18
18
  * that leaves it out is served only by the ordinary server.
19
19
  */
20
20
  readOnly?: boolean;
21
+ /**
22
+ * A CI product's tool that writes to the forge and nowhere else (chant#4655):
23
+ * it opens a pull request or posts a comment, and runs no Op, resolves no
24
+ * gate, approves, merges and applies nothing. `chant serve mcp --read-only
25
+ * --propose` serves a product tool that declares this; the read-only server
26
+ * without `--propose` refuses to start with one, and the ordinary server
27
+ * serves it as any other tool. Lexicon tools do not use it.
28
+ */
29
+ forgeWrite?: true;
21
30
  }
22
31
 
23
32
  export interface McpResourceContribution {
package/src/op/index.ts CHANGED
@@ -81,6 +81,7 @@ export {
81
81
  opWavePlanPath,
82
82
  opWavePlansPath,
83
83
  OP_WAVE_PLAN_PATH_FLOOR,
84
+ OP_WAVES_PREVIEW_FLOOR,
84
85
  opWaveRunsPath,
85
86
  opWaveSetDigest,
86
87
  parseOpWavesSpec,
@@ -114,6 +114,17 @@ export function opWaveNotifyFields(
114
114
  reason: result.outcome.reason ?? `another run${holder ? `, ${holder.run},` : ""} holds what the apply changes; apply again once it is done`,
115
115
  };
116
116
  }
117
+ if (result.exitCode === CHANT_EXIT.moved && decision?.refused?.reason === "moved") {
118
+ // The plans moved since the pull request previewed them (`approvals.preview`), or were never previewed.
119
+ return {
120
+ ...base,
121
+ event: "refused",
122
+ status: "moved",
123
+ summary: `${label} refused: ${decision.preview?.status === "unrecorded" ? "its plans were not previewed" : "its plans moved since the pull request previewed them"}`,
124
+ targets: decision.refused.runs,
125
+ reason: decision.refused.message ?? "the plans are not the ones the pull request previewed, so nothing was applied",
126
+ };
127
+ }
117
128
  if (result.exitCode === CHANT_EXIT.moved) {
118
129
  return {
119
130
  ...base,
@@ -0,0 +1,167 @@
1
+ import { afterEach, describe, expect, test } from "vitest";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { assertOpWavesSpec, opWavesPostsApprovalStatus, type OpWavesSpec } from "./op-waves";
6
+ import { OP_WAVES_PREVIEW_FLOOR, readOpWavePolicy, runOpWave, type OpWaveExec, type OpWaveShowAtBase } from "./op-waves-run";
7
+ import { memoryGateLedgerPort } from "./gate";
8
+ import { NEXT_RELEASE } from "../release-floors";
9
+ import { waveSetDigest } from "../gated-waves";
10
+ import type { HeadPlans, MergedReview, ReviewSource } from "./gate-review";
11
+
12
+ const spec: OpWavesSpec = {
13
+ name: "records",
14
+ op: "dns",
15
+ plan: ["tool", "plan", "{target}", "--out", "{plan}"],
16
+ apply: ["tool", "apply", "{target}", "--plan", "{plan}"],
17
+ approvals: { preview: true },
18
+ waves: [{ name: "dev", runs: [{ target: "zone" }], gate: "on-destructive" }],
19
+ };
20
+
21
+ const digest = (n: string) => `sha256:${n.repeat(64)}`;
22
+ const setOf = (n: string) => waveSetDigest([{ member: "zone", planDigest: digest(n) }]);
23
+ const merged: MergedReview = { pr: 7, head: "h".repeat(40), author: "github:dev", approvers: ["github:rev"], refused: [] };
24
+ const reviews = (m: MergedReview | null): ReviewSource => ({ kind: "github", mergedReview: async () => m });
25
+ const recorded = (wave: number, set: string | undefined): ((name: string, head: string) => Promise<HeadPlans | null>) => async (name, head) =>
26
+ set === undefined ? null : { version: 1, name, head, timestamp: "2026-10-30T00:00:00Z", waves: [{ wave, name: "dev", digest: set }] };
27
+
28
+ const dirs: string[] = [];
29
+ afterEach(() => {
30
+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
31
+ });
32
+
33
+ function harness(plan: { planDigest: string; destructive?: boolean }, atBase: OpWavesSpec = spec) {
34
+ const cwd = mkdtempSync(join(tmpdir(), "op-waves-preview-"));
35
+ dirs.push(cwd);
36
+ const calls: string[] = [];
37
+ const exec: OpWaveExec = (argv, dir) => {
38
+ calls.push(argv.join(" "));
39
+ if (argv[1] === "plan") writeFileSync(join(dir, argv[4]!), JSON.stringify(plan));
40
+ return 0;
41
+ };
42
+ const show: OpWaveShowAtBase = () => ({ sha: "b".repeat(40), text: JSON.stringify(atBase) });
43
+ return { cwd, exec, show, applied: () => calls.some((c) => c.startsWith("tool apply")) };
44
+ }
45
+
46
+ const run = (h: ReturnType<typeof harness>, extra: Partial<Parameters<typeof runOpWave>[0]> = {}) =>
47
+ runOpWave({ spec, specFile: "waves.json", wave: 1, cwd: h.cwd, exec: h.exec, show: h.show, gates: memoryGateLedgerPort(), head: "m".repeat(40), now: "2026-10-30T01:00:00Z", log: () => {}, ...extra });
48
+
49
+ describe("a wave applies the plans its pull request previewed (approvals.preview)", () => {
50
+ test("a record that moved between the preview and the merge returns 4 and applies nothing", async () => {
51
+ const h = harness({ planDigest: digest("b") });
52
+ const logs: string[] = [];
53
+ const result = await run(h, { reviews: reviews(merged), headPlans: recorded(1, setOf("a")), log: (l) => logs.push(l) });
54
+ expect(result.exitCode).toBe(4);
55
+ expect(result.moved).toEqual(["zone"]);
56
+ expect(result.decision).toMatchObject({ status: "refused", refused: { reason: "moved", runs: ["zone"] }, preview: { status: "moved", pr: 7, recorded: setOf("a") } });
57
+ expect(result.decision?.refused?.message).toMatch(/the head hhhhhhhhhhhh planned/);
58
+ expect(h.applied()).toBe(false);
59
+ expect(logs.some((l) => /plans moved since #7 previewed them/.test(l))).toBe(true);
60
+ });
61
+
62
+ test("an unchanged record applies, though the gate asks for no approval", async () => {
63
+ const h = harness({ planDigest: digest("a") });
64
+ const result = await run(h, { reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
65
+ expect(result).toMatchObject({ exitCode: 0, applied: ["zone"], decision: { status: "not-required", preview: { status: "matched", pr: 7 } } });
66
+ expect(h.applied()).toBe(true);
67
+ });
68
+
69
+ test("a destructive change still waits for its approval when the preview matches", async () => {
70
+ const h = harness({ planDigest: digest("a"), destructive: true });
71
+ const gates = memoryGateLedgerPort();
72
+ const result = await run(h, { gates, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
73
+ expect(result.exitCode).toBe(3);
74
+ expect(result.decision).toMatchObject({ status: "waiting", preview: { status: "matched" } });
75
+ expect(h.applied()).toBe(false);
76
+ const approved = memoryGateLedgerPort({
77
+ resolutions: [{ version: 1, op: "records", gate: "records-wave-1", resolvedBy: "alice", timestamp: "2026-10-30T00:30:00Z", planDigest: setOf("a") }],
78
+ });
79
+ const again = await run(h, { gates: approved, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
80
+ expect(again).toMatchObject({ exitCode: 0, applied: ["zone"], decision: { status: "approved", approvedBy: "alice" } });
81
+ });
82
+
83
+ test("with no approval required, the wave compares with the digest of the preview it was shown", async () => {
84
+ // gate: never needs nothing, yet the preview still binds the plans.
85
+ const never: OpWavesSpec = { ...spec, waves: [{ ...spec.waves[0]!, gate: "never" }] };
86
+ const moved = harness({ planDigest: digest("c") }, never);
87
+ const refused = await run(moved, { spec: never, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
88
+ expect(refused).toMatchObject({ exitCode: 4, decision: { policy: "never", preview: { status: "moved" } } });
89
+ expect(moved.applied()).toBe(false);
90
+ const same = harness({ planDigest: digest("a") }, never);
91
+ expect(await run(same, { spec: never, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) })).toMatchObject({ exitCode: 0, applied: ["zone"] });
92
+ });
93
+
94
+ test("plans nobody previewed refuse too: no merged pull request, or no record for its head", async () => {
95
+ const direct = harness({ planDigest: digest("a") });
96
+ const none = await run(direct, { reviews: reviews(null), headPlans: recorded(1, setOf("a")) });
97
+ expect(none).toMatchObject({ exitCode: 4, decision: { preview: { status: "unrecorded" } } });
98
+ expect(none.decision?.refused?.message).toMatch(/no merged pull request produced/);
99
+ const unrecorded = harness({ planDigest: digest("a") });
100
+ const missing = await run(unrecorded, { reviews: reviews(merged), headPlans: recorded(1, undefined) });
101
+ expect(missing).toMatchObject({ exitCode: 4, decision: { preview: { status: "unrecorded" } } });
102
+ expect(missing.decision?.refused?.message).toMatch(/--record-plans/);
103
+ expect(direct.applied() || unrecorded.applied()).toBe(false);
104
+ });
105
+
106
+ test("an approval of the plans made now lets a moved wave apply, and the refusal names the command", async () => {
107
+ const h = harness({ planDigest: digest("b") });
108
+ const refused = await run(h, { reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
109
+ expect(refused.decision?.refused?.message).toContain(`chant approve records records-wave-1 ${setOf("b")}`.split(" ").slice(0, 3).join(" "));
110
+ expect(refused.decision?.approve).toContain(setOf("b"));
111
+ const approved = memoryGateLedgerPort({
112
+ resolutions: [{ version: 1, op: "records", gate: "records-wave-1", resolvedBy: "alice", timestamp: "2026-10-30T00:45:00Z", planDigest: setOf("b") }],
113
+ });
114
+ const result = await run(h, { gates: approved, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
115
+ expect(result).toMatchObject({ exitCode: 0, applied: ["zone"], decision: { status: "approved", approvedBy: "alice", preview: { status: "moved", approvedAnyway: true } } });
116
+ });
117
+
118
+ test("a forge that cannot be read fails the wave and applies nothing", async () => {
119
+ const h = harness({ planDigest: digest("a") });
120
+ const broken: ReviewSource = { kind: "github", mergedReview: async () => { throw new Error("403"); } };
121
+ const result = await run(h, { reviews: broken, headPlans: recorded(1, setOf("a")) });
122
+ expect(result.exitCode).toBe(1);
123
+ expect(h.applied()).toBe(false);
124
+ });
125
+
126
+ test("a change cannot switch it off: the setting is read at base", async () => {
127
+ const h = harness({ planDigest: digest("b") });
128
+ const off: OpWavesSpec = { ...spec, approvals: { preview: false } };
129
+ const result = await run(h, { spec: off, reviews: reviews(merged), headPlans: recorded(1, setOf("a")) });
130
+ expect(result.exitCode).toBe(4);
131
+ const without = harness({ planDigest: digest("b") }, { ...spec, approvals: {} });
132
+ expect(await run(without, { reviews: reviews(merged), headPlans: recorded(1, setOf("a")) })).toMatchObject({ exitCode: 0, applied: ["zone"] });
133
+ });
134
+
135
+ test("a spec without it keeps the behaviour it had", async () => {
136
+ const plain: OpWavesSpec = { ...spec, approvals: {} };
137
+ const h = harness({ planDigest: digest("b") }, plain);
138
+ const result = await run(h, { spec: plain });
139
+ expect(result).toMatchObject({ exitCode: 0, applied: ["zone"], decision: { status: "not-required" } });
140
+ expect(result.decision?.preview).toBeUndefined();
141
+ });
142
+
143
+ test("a share job ends on a moved decision with 4", async () => {
144
+ const wide: OpWavesSpec = { ...spec, waves: [{ name: "dev", runs: [{ target: "zone" }, { target: "zone2" }], gate: "on-destructive", shares: 2 }] };
145
+ const h = harness({ planDigest: digest("b") }, wide);
146
+ const decided = await run(h, { spec: wide, decide: true, reviews: reviews(merged), headPlans: recorded(1, waveSetDigest([{ member: "zone", planDigest: digest("a") }, { member: "zone2", planDigest: digest("a") }])) });
147
+ expect(decided.exitCode).toBe(4);
148
+ const share = await run(h, { spec: wide, share: 1 });
149
+ expect(share.exitCode).toBe(4);
150
+ expect(h.applied()).toBe(false);
151
+ });
152
+ });
153
+
154
+ describe("the setting", () => {
155
+ test("its floor is the next release", () => {
156
+ expect(OP_WAVES_PREVIEW_FLOOR).toBe(NEXT_RELEASE);
157
+ });
158
+
159
+ test("is a boolean, is read at base, and makes the head record its plans", () => {
160
+ expect(() => assertOpWavesSpec(spec)).not.toThrow();
161
+ expect(() => assertOpWavesSpec({ ...spec, approvals: { preview: "yes" } } as unknown as OpWavesSpec)).toThrow(/approvals.preview must be true or false/);
162
+ expect(readOpWavePolicy("waves.json", "dev", "HEAD", "/", () => ({ sha: "b".repeat(40), text: JSON.stringify(spec) })).preview).toBe(true);
163
+ expect(readOpWavePolicy("waves.json", "dev", "HEAD", "/", () => ({ sha: "b".repeat(40), text: JSON.stringify({ ...spec, approvals: {} }) })).preview).toBeUndefined();
164
+ expect(opWavesPostsApprovalStatus(spec)).toBe(true);
165
+ expect(opWavesPostsApprovalStatus({ ...spec, approvals: {} })).toBe(false);
166
+ });
167
+ });