forgedock 1.63.0 → 1.65.0

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 (89) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +88 -12
  4. package/bin/env/cli.mjs +18 -1
  5. package/bin/lean/basered.mjs +56 -11
  6. package/bin/lean/basered.test.mjs +58 -5
  7. package/bin/lean/batch-health.mjs +46 -4
  8. package/bin/lean/batch-health.test.mjs +55 -1
  9. package/bin/lean/batch.mjs +8 -1
  10. package/bin/lean/batch.test.mjs +71 -6
  11. package/bin/lean/ceiling.mjs +47 -3
  12. package/bin/lean/ceiling.test.mjs +32 -1
  13. package/bin/lean/clear-breaker.mjs +15 -0
  14. package/bin/lean/clear-breaker.test.mjs +100 -0
  15. package/bin/lean/conformance.e2e.test.mjs +32 -6
  16. package/bin/lean/conformance.mjs +57 -13
  17. package/bin/lean/conformance.test.mjs +93 -1
  18. package/bin/lean/execution.mjs +18 -8
  19. package/bin/lean/execution.test.mjs +44 -3
  20. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  21. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  22. package/bin/lean/issuewatch.mjs +3 -0
  23. package/bin/lean/lanecheck.test.mjs +13 -1
  24. package/bin/lean/lean.mjs +157 -28
  25. package/bin/lean/lean.test.mjs +289 -21
  26. package/bin/lean/live-execution.mjs +25 -0
  27. package/bin/lean/live-execution.test.mjs +35 -1
  28. package/bin/lean/merged-park.mjs +76 -0
  29. package/bin/lean/merged-park.test.mjs +64 -0
  30. package/bin/lean/mergetrain.mjs +357 -0
  31. package/bin/lean/mergetrain.test.mjs +348 -0
  32. package/bin/lean/mirror-bundle.mjs +84 -0
  33. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  34. package/bin/lean/orchestrate-stacking.test.mjs +23 -1
  35. package/bin/lean/orchestrate-train.test.mjs +130 -0
  36. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  37. package/bin/lean/orchestrate.mjs +170 -13
  38. package/bin/lean/prompts.mjs +4 -3
  39. package/bin/lean/release-review.mjs +8 -1
  40. package/bin/lean/release-review.test.mjs +42 -2
  41. package/bin/lean/release-status.test.mjs +53 -1
  42. package/bin/lean/release.mjs +6 -3
  43. package/bin/lean/render.mjs +6 -1
  44. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  45. package/bin/lean/sandbox-remote.mjs +43 -3
  46. package/bin/lean/sched.mjs +19 -2
  47. package/bin/lean/sched.test.mjs +33 -1
  48. package/bin/lean/schedd-health.mjs +2 -1
  49. package/bin/lean/schedd-health.test.mjs +7 -0
  50. package/bin/lean/schedd.mjs +58 -7
  51. package/bin/lean/schedd.test.mjs +78 -1
  52. package/bin/lean/stacking.mjs +45 -0
  53. package/bin/lean/stacking.test.mjs +25 -1
  54. package/bin/lean/statuscomment.mjs +14 -8
  55. package/bin/lean/statuscomment.test.mjs +18 -1
  56. package/bin/lean/validate-catalog.mjs +1 -1
  57. package/bin/lean/validate-catalog.test.mjs +3 -0
  58. package/bin/lean/worktree.mjs +8 -3
  59. package/bin/lean/worktree.test.mjs +18 -0
  60. package/bin/pool/agent.mjs +309 -33
  61. package/bin/pool/cache-sweep.mjs +4 -2
  62. package/bin/pool/cli.mjs +125 -6
  63. package/bin/pool/disk.mjs +43 -0
  64. package/bin/pool/docker.mjs +11 -0
  65. package/bin/pool/health.mjs +95 -0
  66. package/bin/pool/mirror-seed.mjs +103 -0
  67. package/bin/pool/router.mjs +301 -27
  68. package/bin/runner.mjs +3 -1
  69. package/bin/stats/chains.mjs +101 -0
  70. package/bin/stats/chains.test.mjs +53 -0
  71. package/bin/stats/efficiency.mjs +7 -6
  72. package/bin/stats/efficiency.test.mjs +48 -7
  73. package/bin/stats/index.mjs +11 -3
  74. package/bin/stats/stats.test.mjs +9 -0
  75. package/docs/CONFIG.md +8 -1
  76. package/docs/OUTCOME-CODES.md +4 -0
  77. package/package.json +1 -1
  78. package/pool/README.md +10 -0
  79. package/pool/image/Dockerfile +2 -1
  80. package/pool/image/entrypoint.sh +25 -6
  81. package/pool/image/mirror.sh +71 -0
  82. package/pool/install/install-agent-linux.sh +57 -5
  83. package/pool/install/install-agent-macos.sh +148 -0
  84. package/pool/install/install-agent.ps1 +11 -0
  85. package/pool/install/install-agent.sh +59 -7
  86. package/pool/install/uninstall-agent-linux.sh +75 -0
  87. package/pool/install/uninstall-agent-macos.sh +60 -0
  88. package/pool/install/uninstall-agent.ps1 +1 -0
  89. package/scripts/transition-label.sh +11 -0
@@ -217,6 +217,13 @@ export function batchStatusLines(root, id, { now = Date.now() } = {}) {
217
217
  const due = checkpointsOf(created, DEFAULT_HEALTH.checksMin).filter((c) => !h?.checks?.[c.label]);
218
218
  if (due.length && !b.readReport()) out.push(` next checks: ${due.map((c) => `${c.label} ${new Date(c.at).toISOString().slice(11, 16)}Z${c.at < now ? " (due)" : ""}`).join(", ")}`);
219
219
  }
220
+ // #5859: an agent/VM restart is one batch event (its lanes were requeued as sandbox.lost), not a health cause
221
+ let st = null;
222
+ try { st = b.store.load(); } catch { st = null; }
223
+ for (const g of Array.isArray(st?.agentRestarts) ? st.agentRestarts : []) {
224
+ const k = Array.isArray(g?.lanes) ? g.lanes.length : Number(g?.requeued) || 0;
225
+ if (g?.agent) out.push(` agent ${g.agent} restarted at ${g.at ?? "?"}; ${k} lane${k === 1 ? "" : "s"} requeued (sandbox.lost)${g.closed ? "" : ", waiting for the agent"}`);
226
+ }
220
227
  return out;
221
228
  }
222
229
 
@@ -306,24 +313,35 @@ export const DEFAULT_STALL_MIN = 3;
306
313
  export const MAX_STALL_RECOVERIES = 3;
307
314
  /** #5745: `; admission held by <code>: <detail>` for each failing preflight gate, "" when none. Pure. */
308
315
  export const holdGateDetail = (gates) => (Array.isArray(gates) ? gates : []).filter((g) => g?.code).map((g) => `; admission held by ${g.code}: ${g.detail ?? "failing"}`).join("");
316
+ /** #5938: `{running, k, local, remote, text}`: the live lanes of a saved state against K; a run record with `remote` is a pool lane. Pure. */
317
+ export function runningSplit(state, parallel = null) {
318
+ const recs = Object.values(state?.running ?? {}), running = recs.length, remote = recs.filter((r) => r?.remote).length;
319
+ const k = Number.isInteger(parallel) && parallel > 0 ? parallel : Number.isInteger(state?.parallel) && state.parallel > 0 ? state.parallel : 1;
320
+ return { running, k, local: running - remote, remote, text: `running ${running}/${k} (local ${running - remote}, remote ${remote})` };
321
+ }
322
+
309
323
  /**
310
324
  * #5314: dispatch stall. A batch with ready pending issues, free capacity and no progress for `windowMin` minutes. Ready: pending,
311
325
  * not held, no retry-at in the future, every in-batch dependency ended well. Independent of the runner (it may be dead), so the
312
326
  * schedd polls it. `hosted`: a runner is alive. `gates` (#5745): the failing preflight checks `[{code, detail}]` holding admission, named in the detail. @returns null (healthy) or `{code, ready, idleMin, hosted, detail[, gates]}`. Pure.
313
327
  */
314
- export function evaluateDispatchStall(state, { held = [], parallel = null, hosted = false, lastProgressMs = null, now = Date.now(), windowMin = DEFAULT_STALL_MIN, cancelled = false, reported = false, gates = [] } = {}) {
328
+ export function evaluateDispatchStall(state, { held = [], parallel = null, hosted = false, lastProgressMs = null, now = Date.now(), windowMin = DEFAULT_STALL_MIN, cancelled = false, reported = false, gates = [], lanesAliveMs = null } = {}) {
315
329
  if (!state || cancelled || reported || lastProgressMs === null) return null;
316
330
  if (state.breaker && !state.breaker.transport) return null; // an operator --resume clears it; a re-host would stop again at once
317
331
  const order = new Set((state.order ?? []).map(Number)), results = state.results ?? {}, heldSet = new Set(held.map(Number));
318
332
  const running = Object.keys(state.running ?? {}).length;
319
333
  const k = Number.isInteger(parallel) && parallel > 0 ? parallel : Number.isInteger(state.parallel) && state.parallel > 0 ? state.parallel : 1;
320
- const ready = (state.pending ?? []).map(Number).filter((n) => !heldSet.has(n) && results[n] === undefined && !(Number(state.notBefore?.[n]) > now)
334
+ const live = new Set(Object.keys(state.running ?? {}).map(Number)); // #5938: a recovery lane keeps its issue in `pending`
335
+ const ready = (state.pending ?? []).map(Number).filter((n) => !live.has(n) && !heldSet.has(n) && results[n] === undefined && !(Number(state.notBefore?.[n]) > now)
321
336
  && (state.deps?.[n] ?? []).every((d) => !order.has(Number(d)) || Number(d) === n || GOOD_END.has(results[d]?.outcome)));
322
337
  const idleMin = Math.floor((now - lastProgressMs) / 60000);
323
338
  if (!ready.length || running >= k || idleMin < windowMin) return null;
324
339
  const setup = state.phase === "setup" ? ` (stuck in setup, ${Number(state.setup?.read) || 0}/${Number(state.setup?.total) || ready.length} issues read)` : "";
325
340
  const gated = (Array.isArray(gates) ? gates : []).filter((g) => g?.code);
326
- return { code: "dispatch-stalled", ready, idleMin, hosted, setup: !!setup, ...(gated.length ? { gates: gated.map((g) => g.code) } : {}), detail: `${ready.length} ready issue${ready.length === 1 ? "" : "s"} (${list(ready.slice(0, 8))}${ready.length > 8 ? ", …" : ""}) pending with ${k - running} free lane${k - running === 1 ? "" : "s"} and no ${setup ? "progress" : "dispatch"} for ${idleMin} min${setup}; ${hosted ? "the runner is alive but not dispatching" : "no runner hosts the batch"}${holdGateDetail(gated)}` };
341
+ const split = runningSplit(state, k), alive = Number.isFinite(lanesAliveMs) ? `; lanes alive ${Math.max(0, Math.floor((now - lanesAliveMs) / 60000))} min ago` : "";
342
+ const capReason = ready.every((n) => state.capReasons?.[n]) ? String(state.capReasons[ready[0]]) : null; // #5938: every ready issue is held by the pool
343
+ if (capReason) return { code: "pool-capacity", ready, idleMin, hosted, setup: !!setup, reason: capReason, ...(gated.length ? { gates: gated.map((g) => g.code) } : {}), detail: `${ready.length} ready issue${ready.length === 1 ? "" : "s"} (${list(ready.slice(0, 8))}${ready.length > 8 ? ", …" : ""}) waiting on pool capacity: ${capReason} (${split.text}); no dispatch for ${idleMin} min${alive}${holdGateDetail(gated)}` };
344
+ return { code: "dispatch-stalled", ready, idleMin, hosted, setup: !!setup, ...(gated.length ? { gates: gated.map((g) => g.code) } : {}), detail: `${ready.length} ready issue${ready.length === 1 ? "" : "s"} (${list(ready.slice(0, 8))}${ready.length > 8 ? ", …" : ""}) pending with ${k - running} free lane${k - running === 1 ? "" : "s"} (${split.text}) and no ${setup ? "progress" : "dispatch"} for ${idleMin} min${setup}${alive}; ${hosted ? "the runner is alive but not dispatching" : "no runner hosts the batch"}${holdGateDetail(gated)}` };
327
345
  }
328
346
 
329
347
  /**
@@ -390,6 +408,30 @@ export function recordStallAlert(batch, stall, { now = Date.now(), cause = null
390
408
  return true;
391
409
  }
392
410
 
411
+ /** #5938: drop a stored stall that no longer holds; logs `STALL CLEARED <t>` once. @returns true when one was cleared */
412
+ export function clearStaleStall(batch, { now = Date.now() } = {}) {
413
+ const prev = readHealth(batch.dir);
414
+ if (!prev?.stall) return false;
415
+ const { stall, ...rest } = prev, at = new Date(now).toISOString();
416
+ try { writeHealth(batch.dir, rest); } catch { return false; }
417
+ appendBatchLog(batch.dir, `${at} STALL CLEARED ${at}`);
418
+ return true;
419
+ }
420
+
421
+ /** #5938: the one watchdog line of a batch: healthy, stalled -> action taken, or stalled -> no action, and why. Pure. */
422
+ export function batchVerdict(id, stall, decision = null, { acted = false } = {}) {
423
+ if (!stall) return `batch ${id}: healthy`;
424
+ const why = `${stall.code}: ${stall.detail}`;
425
+ if (decision && decision.action !== "alert" && acted) return `batch ${id}: stalled -> action ${decision.action} (${why})`;
426
+ if (decision && decision.action !== "alert") return `batch ${id}: stalled -> no action yet (${decision.action} pending; ${why})`;
427
+ return `batch ${id}: stalled -> no action, needs you (${decision?.cause ? `${decision.cause}; ` : ""}${why})`;
428
+ }
429
+
430
+ /** #5938: whether the batch still has ready issues with a free lane (the idle window was already met when the stall was stored). */
431
+ const stallStillHolds = (b, now) => {
432
+ try { const state = b.store.peek(); if (!state) return true; return evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: true, lastProgressMs: b.lastProgressMs() ?? now, now, windowMin: 0 }) !== null; } catch { return true; }
433
+ };
434
+
393
435
  /** `sched show` lines: per unfinished batch, its first-hour summary and any dispatch stall. */
394
436
  export function summaryLines(root, { now = Date.now() } = {}) {
395
437
  const out = [];
@@ -399,7 +441,7 @@ export function summaryLines(root, { now = Date.now() } = {}) {
399
441
  if (b.readReport() || b.readCancel()) continue;
400
442
  const fh = readFirstHour(b.dir), h = readHealth(b.dir);
401
443
  if (fh?.summary) out.push(` batch ${id}: ${fh.summary}`);
402
- if (h?.stall && now - Date.parse(h.stall.at) < 24 * 3600 * 1000) out.push(` batch ${id}: DISPATCH STALLED since ${h.stall.at}: ${h.stall.detail}${h.stall.cause ? ` (${h.stall.cause})` : ""}`);
444
+ if (h?.stall && now - Date.parse(h.stall.at) < 24 * 3600 * 1000 && stallStillHolds(b, now)) out.push(` batch ${id}: DISPATCH STALLED since ${h.stall.at}: ${h.stall.detail}${h.stall.cause ? ` (${h.stall.cause})` : ""}`);
403
445
  } catch { /* an unreadable batch has no line */ }
404
446
  }
405
447
  return out;
@@ -9,7 +9,7 @@ import { openBatch } from "./batch.mjs";
9
9
  import { DEFAULT_HEALTH, parseHealthConfig, rootsOf, evaluateHealth, formatAlert, runCheck, scheduleChecks, scheduleLine, runNotify, deliverAlert,
10
10
  resolvedOnGithub, recordRefusal, readRefusals, statusLines, REFUSAL_KEEP,
11
11
  evaluateDispatchStall, firstHourReport, writeFirstHour, readFirstHour, recordStallAlert, summaryLines, statelessNeedsHuman, statelessOnGithub,
12
- DEFAULT_STALL_MIN, MAX_STALL_RECOVERIES, decideStallAction, recordStallRecovery, readHealth } from "./batch-health.mjs";
12
+ DEFAULT_STALL_MIN, MAX_STALL_RECOVERIES, decideStallAction, recordStallRecovery, readHealth, runningSplit, clearStaleStall, batchVerdict } from "./batch-health.mjs";
13
13
 
14
14
  // #1 and #3 are roots; #2 depends on #1, #4 on #3.
15
15
  const base = (results, extra = {}) => ({ order: [1, 2, 3, 4], deps: { 2: [1], 4: [3] }, results, running: {}, pending: [], ...extra });
@@ -102,6 +102,15 @@ describe("#5167 checkpoints, alert-once and persistence", () => {
102
102
  assert.match(one, /forgedock orchestrate --cancel b20260101-000000-1/);
103
103
  });
104
104
 
105
+ it("#5859 agent restart event is shown by status --batch with its requeued count, not as a health cause", () => {
106
+ const { root, b } = mkBatch(base({ 1: { outcome: "merged" } }, { agentRestarts: [{ agent: "legion", at: "2026-01-01T00:05:00.000Z", last: 0, lanes: [1, 2, 3], requeued: 3, closed: true }] }));
107
+ const lines = statusLines(root, { batch: b.id });
108
+ assert.ok(lines.includes(" agent legion restarted at 2026-01-01T00:05:00.000Z; 3 lanes requeued (sandbox.lost)"), lines.join("\n"));
109
+ assert.equal(statusLines(root).length, 0, "not an unhealthy batch");
110
+ const { root: r2, b: b2 } = mkBatch(base({ 1: { outcome: "merged" } }));
111
+ assert.ok(!statusLines(r2, { batch: b2.id }).some((l) => /restarted/.test(l)), "older state without the field");
112
+ });
113
+
105
114
  it("a healthy check records no alert, and a throwing channel never escapes", async () => {
106
115
  const { b, root } = mkBatch(base({ 1: { outcome: "merged" } }, { running: { 3: {} }, pending: [2, 4] }));
107
116
  const r = await runCheck({ batch: b, checkpoint: "T+15", alert: async () => { throw new Error("x"); } });
@@ -352,3 +361,48 @@ describe("#5469: holds in health and the first-hour report", () => {
352
361
  assert.match(rep.summary, /#3 held \(op@h, since 2026-11-11T00:00:00.000Z\)/);
353
362
  });
354
363
  });
364
+
365
+ describe("#5938 stall verdict is re-evaluated: full K, recovery lanes, pool capacity, clear", () => {
366
+ const NOW = 10_000_000, MIN = 60000;
367
+ const st = (extra = {}) => ({ order: [1, 2, 3], deps: {}, results: {}, running: {}, pending: [1, 2, 3], parallel: 2, ...extra });
368
+ const stall = (state, o = {}) => evaluateDispatchStall(state, { lastProgressMs: NOW - 12 * MIN, now: NOW, windowMin: 10, ...o });
369
+
370
+ it("running == K with ready pending issues is healthy", () => {
371
+ assert.equal(stall(st({ running: { 1: { remote: true }, 2: {} } })), null);
372
+ });
373
+ it("a pending issue with a running record (recovery lane) is not ready", () => {
374
+ const r = stall(st({ running: { 1: {} }, pending: [1, 2] }));
375
+ assert.deepEqual(r.ready, [2]);
376
+ assert.equal(stall(st({ running: { 1: {} }, pending: [1], parallel: 2 })), null);
377
+ });
378
+ it("the detail names running/K with the local/remote split", () => {
379
+ const r = stall(st({ running: { 1: { remote: true } }, pending: [2, 3] }));
380
+ assert.match(r.detail, /running 1\/2 \(local 0, remote 1\)/);
381
+ assert.deepEqual(runningSplit(st({ running: { 1: {}, 2: { remote: true } } })), { running: 2, k: 2, local: 1, remote: 1, text: "running 2/2 (local 1, remote 1)" });
382
+ });
383
+ it("pool capacity deferrals report pool-capacity naming the pool's reason", () => {
384
+ const reason = "host_disk_free 10.8 GB < floor 25 + 3.5/sandbox";
385
+ const r = stall(st({ pending: [2, 3], capReasons: { 2: reason, 3: reason } }));
386
+ assert.equal(r.code, "pool-capacity");
387
+ assert.ok(r.detail.includes(reason));
388
+ assert.equal(stall(st({ pending: [2, 3], capReasons: { 2: reason } })).code, "dispatch-stalled", "one unblocked ready issue keeps the stall");
389
+ });
390
+ it("clearStaleStall removes the stored stall and logs STALL CLEARED; summaryLines skips a stall that no longer holds", () => {
391
+ const root = tmpDir("stall-clear-"), b = openBatch(root, "b1");
392
+ b.writePlan({ daemon: true, repo: "o/r" });
393
+ recordStallAlert(b, stall(st()), { now: NOW });
394
+ assert.equal(clearStaleStall(b, { now: NOW }), true);
395
+ assert.equal(readHealth(b.dir).stall, undefined);
396
+ assert.match(readFileSync(join(b.dir, "batch.log"), "utf8"), /STALL CLEARED/);
397
+ assert.equal(clearStaleStall(b, { now: NOW }), false);
398
+ recordStallAlert(b, stall(st()), { now: NOW });
399
+ b.store.save(st({ running: { 1: {}, 2: {} } }));
400
+ assert.ok(!summaryLines(root, { now: NOW }).some((l) => /DISPATCH STALLED/.test(l)));
401
+ });
402
+ it("batchVerdict: healthy, stalled -> action, stalled -> no action", () => {
403
+ const s = stall(st());
404
+ assert.equal(batchVerdict("b1", null), "batch b1: healthy");
405
+ assert.match(batchVerdict("b1", s, { action: "resume" }, { acted: true }), /stalled -> action resume/);
406
+ assert.match(batchVerdict("b1", s, { action: "alert", cause: "no gh" }), /stalled -> no action, needs you \(no gh;/);
407
+ });
408
+ });
@@ -110,7 +110,7 @@ const readAdded = (file) => {
110
110
  };
111
111
 
112
112
  /** `outcome`s `--requeue` may move back to pending (#4550); #5168: a final `engine-error` too (the runner clears its engine-error count); #5162: `held` rows too. */
113
- export const REQUEUABLE = (outcome) => ["needs-human", "engine-error", "held", "invalid", "skipped", "ci-pending", "budget-exceeded", "lane-refused", "deferred"].includes(outcome) || /^dependency-/.test(String(outcome));
113
+ export const REQUEUABLE = (outcome) => ["needs-human", "engine-error", "held", "invalid", "skipped", "ci-pending", "pr-ready", "budget-exceeded", "lane-refused", "deferred"].includes(outcome) || /^dependency-/.test(String(outcome));
114
114
  /** Key of one requeue entry; the runner records the applied keys in state.json `requeueApplied`. */
115
115
  /** #5832: the `{dependency, branch, sha}` a stacked build of `issue` was admitted on (batch state `stacked`), or null. Rows carry `stacked`/`stackedOn`. */
116
116
  export const stackedOnOf = (state, issue) => state?.stacked?.[issue] ?? null;
@@ -223,6 +223,13 @@ export function openBatch(root, id) {
223
223
  if (!Number.isInteger(k) || k < 1) throw new Error("parallel must be a positive integer");
224
224
  put(f("parallel"), `${k}\n`);
225
225
  },
226
+ /** #5947: `--clear-breaker` for a hosted runner: the request file (a timestamp) is consumed by the runner, which answers in `clear-breaker.ack`. */
227
+ requestClearBreaker: () => { try { rmSync(f("clear-breaker.ack"), { force: true }); } catch { /* best effort */ } const at = Date.now(); put(f("clear-breaker"), `${at}\n`); return at; },
228
+ /** #5964: the pending request's `at` without deleting it (the runner consumes it after deciding); null when none. */
229
+ peekClearBreaker: () => { try { const at = Number(readFileSync(f("clear-breaker"), "utf8").trim()); return Number.isFinite(at) && at > 0 ? at : true; } catch { return null; } },
230
+ readClearBreaker: () => { try { readFileSync(f("clear-breaker"), "utf8"); rmSync(f("clear-breaker"), { force: true }); return true; } catch { return false; } },
231
+ ackClearBreaker: (info = {}) => put(f("clear-breaker.ack"), JSON.stringify({ at: Date.now(), ...info }) + "\n"),
232
+ readClearBreakerAck: () => readJson(f("clear-breaker.ack")),
226
233
  /** Live execution override (#5138): the `execution` file `{maxRemote?, mode?, provider?}`, read on every admission; null when missing or invalid. */
227
234
  readExecution: () => sanitizeOverride(readJson(f("execution"))),
228
235
  /** Merge a validated patch into the `execution` file. @returns the stored override. */
@@ -10,8 +10,12 @@ import { resolveLane, makeLaneCache } from "./lane.mjs";
10
10
  import { orchestrate, deferPolicy, DEFER_BACKOFF_S, formatOutcomeLists, CAPACITY_FALLBACK_AFTER, isTransientEngineError, transientRetryDelayMs, DEFAULT_TRANSIENT_RETRIES } from "./orchestrate.mjs";
11
11
  import { openBatch, fsTypeOf, assertDiskPath, isLaneAlive, writeAtomic, launchLane, detachedLanes, stackedOnOf } from "./batch.mjs";
12
12
  import { makeLedger } from "./ledger.mjs";
13
+ import { placeLane } from "./execution.mjs";
14
+ import { liveRemote } from "./live-execution.mjs";
13
15
  import { providerLanes } from "./execution.mjs";
14
16
  import { orchestrateFromCli, runFromCli, readOrchestration, makeRelabelNeedsHuman, makeMarkRecovering, makeDispatchCheck } from "../engine-cli.mjs";
17
+ // Windows hosts: these tests exercise POSIX-only behaviour (file modes, tmpfs, systemd units, sh/bash scripts, file-URL paths); Linux CI runs them.
18
+ const POSIX_ONLY = process.platform === "win32" && "POSIX-only behaviour";
15
19
 
16
20
  // orchestrateFromCli opens the host lane registry (#4191): keep it in a temp dir, also for spawned dispatchers.
17
21
  process.env.FORGEDOCK_SCHED_DIR = tmpDir("batch-sched-");
@@ -241,7 +245,7 @@ await orchestrateFromCli(["1", "2", "3", "--parallel", "2", "--repo", "o/r", "--
241
245
  assert.equal(rows.length, 7);
242
246
  });
243
247
 
244
- it("batch files: atomic writes, live K via --set-parallel, tmpfs refused, pid reuse not adopted", async () => {
248
+ it("batch files: atomic writes, live K via --set-parallel, tmpfs refused, pid reuse not adopted", { skip: POSIX_ONLY }, async () => {
245
249
  const root = tmpDir("batch-files-");
246
250
  const b = openBatch(root, "b1");
247
251
  b.writePlan({ argv: ["1"] });
@@ -269,9 +273,9 @@ await orchestrateFromCli(["1", "2", "3", "--parallel", "2", "--repo", "o/r", "--
269
273
  assert.equal(isLaneAlive(42, "lane", { kill: () => true, procDir: proc }), false);
270
274
  assert.deepEqual(stackedOnOf({ stacked: { 7: { dependency: 6, branch: "b", sha: "abcdef1" } } }, 7), { dependency: 6, branch: "b", sha: "abcdef1" }, "#5832: stackedOn read from batch state");
271
275
  assert.equal(stackedOnOf({}, 7), null);
272
- assert.deepEqual(readOrchestration(root), { breaker: { errors: 3, window_min: 30 }, maxDeferrals: 3, transientRetries: 4, blockedLabel: "blocked", globalParallel: null, stacking: "off", recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 }, baseSync: { enabled: true, unionGlobs: [] } });
276
+ assert.deepEqual(readOrchestration(root), { breaker: { errors: 3, window_min: 30 }, maxDeferrals: 3, transientRetries: 4, blockedLabel: "blocked", globalParallel: null, stacking: "off", recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 }, baseSync: { enabled: true, unionGlobs: [] }, mergeTrain: "off", mergeTrainBatch: 4 });
273
277
  writeFileSync(join(root, "forge.yaml"), "orchestration:\n breaker:\n errors: 5\n window_min: 10\n max_deferrals: 2\n global_parallel: 4\n transient_retries: 2\n");
274
- assert.deepEqual(readOrchestration(root), { breaker: { errors: 5, window_min: 10 }, maxDeferrals: 2, transientRetries: 2, blockedLabel: "blocked", globalParallel: 4, stacking: "off", recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 }, baseSync: { enabled: true, unionGlobs: [] } });
278
+ assert.deepEqual(readOrchestration(root), { breaker: { errors: 5, window_min: 10 }, maxDeferrals: 2, transientRetries: 2, blockedLabel: "blocked", globalParallel: 4, stacking: "off", recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 }, baseSync: { enabled: true, unionGlobs: [] }, mergeTrain: "off", mergeTrainBatch: 4 });
275
279
  });
276
280
 
277
281
  it("run-issue --result-file writes the lane result, also when the run throws", async () => {
@@ -386,6 +390,31 @@ describe("#4318: the batch dispatcher's signal relabel and the needs-human relab
386
390
  assert.deepEqual(h.calls, ["view"]);
387
391
  }
388
392
  });
393
+ it("relabel skips an open issue whose fix PR merged on a non-lean head", async () => {
394
+ const calls = [];
395
+ const gh = async (a) => {
396
+ calls.push(a.slice(0, 2).join(" "));
397
+ if (a[1] === "view" && a[0] === "issue") return JSON.stringify({ state: "OPEN", body: "", labels: [], closedByPullRequestsReferences: [{ number: 41 }] });
398
+ if (a[0] === "pr") return JSON.stringify({ state: "MERGED", mergedAt: "2026-11-17T15:43:35Z" });
399
+ return "";
400
+ };
401
+ for (const parked of [null, { code: "env.validate_timeout" }]) assert.equal(await makeRelabelNeedsHuman({ gh, repo: "o/r", now: () => 1000 })({ issue: 7, evidence: "why", parked }), "skipped");
402
+ assert.ok(!calls.includes("issue edit"));
403
+ const labelled = async (a) => (a[0] === "issue" && a[1] === "view" ? JSON.stringify({ state: "OPEN", body: "", labels: [{ name: "workflow:merged" }] }) : "");
404
+ assert.equal(await makeRelabelNeedsHuman({ gh: labelled, repo: "o/r", now: () => 1000 })({ issue: 7, evidence: "why" }), "skipped");
405
+ });
406
+ it("relabel still parks an issue reopened after merge", async () => {
407
+ const calls = [];
408
+ const gh = async (a) => {
409
+ calls.push(a.slice(0, 2).join(" "));
410
+ if (a[0] === "issue" && a[1] === "view") return JSON.stringify({ state: "OPEN", body: "", labels: [], closedByPullRequestsReferences: [{ number: 41 }] });
411
+ if (a[0] === "pr") return JSON.stringify({ state: "MERGED", mergedAt: "2026-11-17T15:43:35Z" });
412
+ if (a[0] === "api" && a[1].endsWith("/events")) return "reopened\t2026-11-18T00:00:00.000Z\t";
413
+ return "";
414
+ };
415
+ assert.equal(await makeRelabelNeedsHuman({ gh, repo: "o/r", now: () => 1000 })({ issue: 7, evidence: "why" }), true);
416
+ assert.ok(calls.includes("issue edit"));
417
+ });
389
418
  it("an expired lease relabels: the label first, then the comment", async () => {
390
419
  const h = hook({ state: "OPEN", body: LIVE(500) });
391
420
  assert.equal(await h.run(), true);
@@ -1456,7 +1485,7 @@ describe("#4592: forgedock orchestrate --hold / --release", () => {
1456
1485
  });
1457
1486
 
1458
1487
  describe("#4751: batch state is private", () => {
1459
- it("batch state files are private", () => {
1488
+ it("batch state files are private", { skip: POSIX_ONLY }, () => {
1460
1489
  const root = tmpDir("batch-private");
1461
1490
  const old = process.umask(0o022);
1462
1491
  try {
@@ -1477,7 +1506,7 @@ describe("#4751: batch state is private", () => {
1477
1506
  });
1478
1507
 
1479
1508
  describe("batch plan secrets (#4787)", () => {
1480
- it("writePlan never writes secret env values and keeps the plan 0600", () => {
1509
+ it("writePlan never writes secret env values and keeps the plan 0600", { skip: POSIX_ONLY }, () => {
1481
1510
  const b = openBatch(join(tmpDir("batch-sec-"), "batches"), "b20260101-000000-1");
1482
1511
  b.writePlan({ v: 1, env: { PATH: "/bin", COMPUTESHARE_TOKEN: "tok-123", AWS_ACCESS_KEY: "k-456" } });
1483
1512
  const raw = readFileSync(join(b.dir, "plan.json"), "utf8");
@@ -1486,7 +1515,7 @@ describe("batch plan secrets (#4787)", () => {
1486
1515
  assert.deepEqual(b.readPlan().envSecrets, ["AWS_ACCESS_KEY", "COMPUTESHARE_TOKEN"]);
1487
1516
  assert.equal(statSync(join(b.dir, "plan.json")).mode & 0o777, 0o600);
1488
1517
  });
1489
- it("scrubPlan rewrites a pre-fix 0644 plan and is a no-op otherwise", () => {
1518
+ it("scrubPlan rewrites a pre-fix 0644 plan and is a no-op otherwise", { skip: POSIX_ONLY }, () => {
1490
1519
  const b = openBatch(join(tmpDir("batch-sec-"), "batches"), "b20260101-000000-2");
1491
1520
  mkdirSync(b.dir, { recursive: true });
1492
1521
  writeFileSync(join(b.dir, "plan.json"), JSON.stringify({ v: 1, env: { PATH: "/bin", COMPUTESHARE_TOKEN: "tok-123" } }), { mode: 0o644 });
@@ -1592,6 +1621,42 @@ describe("#5138: live max_remote and placement of a running batch", () => {
1592
1621
  assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged", "merged"]);
1593
1622
  assert.deepEqual(seen.find(([n]) => n === 3)[1], [3]);
1594
1623
  });
1624
+ const liveDrain = (state) => liveRemote({ isRemote: () => true, capacity: () => null }, { exec: { mode: "remote", maxRemote: 2 }, readOverride: () => ({ maxRemote: state.m }), place: (e) => placeLane({ exec: e }) });
1625
+ it("#5933 remote batch at max_remote 0 holds lanes pending", async () => {
1626
+ const st = { m: 0 }, seen = [];
1627
+ const done = orchestrate({ issues: [1], parallel: 2, pollMs: 1, readBody: async () => "", sleep: tick, remote: liveDrain(st),
1628
+ runOne: async (n, _ln, ctx = {}) => { seen.push([n, ctx.placement?.where]); return { terminalReason: "merged", pr: 100 + n }; } });
1629
+ for (let i = 0; i < 20; i++) await tick();
1630
+ assert.deepEqual(seen, [], "nothing runs, locally or remotely, at max_remote 0");
1631
+ st.m = 1;
1632
+ await done;
1633
+ assert.deepEqual(seen, [[1, "remote"]]);
1634
+ });
1635
+ it("#5933 lowering max_remote to 0 leaves a running lane running", async () => {
1636
+ const st = { m: 2 }, seen = [];
1637
+ let open, running = false;
1638
+ const gate = new Promise((r) => { open = r; });
1639
+ const done = orchestrate({ issues: [1, 2], parallel: 2, pollMs: 1, readBody: async () => "", sleep: tick, remote: liveDrain(st),
1640
+ runOne: async (n, _ln, ctx = {}) => { seen.push([n, ctx.placement?.where]); if (n === 1) { running = true; await gate; } return { terminalReason: "merged", pr: 100 + n }; } });
1641
+ await until(() => running);
1642
+ st.m = 0;
1643
+ for (let i = 0; i < 20; i++) await tick();
1644
+ assert.ok(!seen.some(([n, w]) => w === "local"), "no lane lands on the host");
1645
+ open();
1646
+ await new Promise((r) => setTimeout(r, 5));
1647
+ st.m = 2;
1648
+ const rows = await done;
1649
+ assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
1650
+ });
1651
+ it("#5933 --set-max-remote 0 prints drain semantics", async () => {
1652
+ const root = tmpDir("batch-drain-");
1653
+ const b = openBatch(root, "b1");
1654
+ b.writePlan({ argv: ["1"] });
1655
+ const lines = [], l = console.log;
1656
+ console.log = (...x) => { lines.push(x.join(" ")); };
1657
+ try { await orchestrateFromCli(["--set-max-remote", "b1", "0"], { batchRoot: root }); } finally { console.log = l; }
1658
+ assert.match(lines.join("\n"), /remote starts paused; nothing runs locally/);
1659
+ });
1595
1660
  it("--set-max-remote / --set-placement write the batch's execution file; bad values and provider-less remote refused", async () => {
1596
1661
  const root = tmpDir("batch-live-exec-");
1597
1662
  const b = openBatch(root, "b1");
@@ -25,10 +25,54 @@ export function parseCeilingBySize(engine) {
25
25
  return Object.keys(out).length ? out : null;
26
26
  }
27
27
 
28
- /** The ceiling for a lane of `size`: its per-size entry, else the global one. */
29
- export function ceilingFor(size, { tokens = 0, bySize = null } = {}) {
28
+ /** The ceiling a model without a known window keeps (#4390). */
29
+ export const DEFAULT_CEILING = 120000;
30
+ /** #5829: the share of a model's input window used as its default ceiling. */
31
+ export const WINDOW_SHARE = 0.5;
32
+ /** #5829: a session at this share of the window always restarts (digest), whatever continuing costs. */
33
+ export const REAL_LIMIT_SHARE = 0.9;
34
+ /** #5829: cache-read USD per token and an estimated restart cost, used when a model has no entry or the engine sets none. */
35
+ export const RESTART_COST_USD = 0.5;
36
+ export const CACHE_READ_USD = 0.5 / 1e6;
37
+ /** #5829: static input windows (tokens) and cache-read prices (USD per token), first match wins; no model-API lookup (this module is pure). */
38
+ export const MODEL_WINDOWS = [
39
+ { match: /1m/i, window: 1000000, cacheRead: 0.5 / 1e6 },
40
+ { match: /opus/i, window: 200000, cacheRead: 0.5 / 1e6 },
41
+ { match: /sonnet/i, window: 200000, cacheRead: 0.3 / 1e6 },
42
+ { match: /haiku/i, window: 200000, cacheRead: 0.1 / 1e6 },
43
+ ];
44
+ /** The static entry for a routed model id; null when unknown. */
45
+ export function modelInfo(model) {
46
+ const m = String(model ?? "");
47
+ return m ? MODEL_WINDOWS.find((e) => e.match.test(m)) ?? null : null;
48
+ }
49
+ /** The default ceiling for `model`: `share` of its window; DEFAULT_CEILING for an unknown model. */
50
+ export function modelCeiling(model, share = WINDOW_SHARE) {
51
+ const e = modelInfo(model);
52
+ const sh = Number.isFinite(share) && share > 0 && share <= 1 ? share : WINDOW_SHARE;
53
+ return e ? Math.floor(e.window * sh) : DEFAULT_CEILING;
54
+ }
55
+
56
+ /**
57
+ * The ceiling for a lane of `size`: its per-size entry, else the global explicit one, else (#5829) the routed model's default
58
+ * (DEFAULT_CEILING for a null or unknown model) when the global one was not set explicitly (`tokens` null), else `tokens`.
59
+ */
60
+ export function ceilingFor(size, { tokens = 0, bySize = null, model = null, share = WINDOW_SHARE } = {}) {
30
61
  const v = bySize && SIZES.includes(size) ? bySize[size] : undefined;
31
- return Number.isFinite(v) && v >= 0 ? v : tokens;
62
+ if (Number.isFinite(v) && v >= 0) return v;
63
+ if (tokens == null) return modelCeiling(model, share); // no explicit ceiling: the model default, DEFAULT_CEILING for a null or unknown model
64
+ return tokens ?? 0;
65
+ }
66
+
67
+ /**
68
+ * #5829: at a context stop, continue the session or restart it from the digest. Continuing costs `turnsLeft x context x cachePrice`;
69
+ * restarting costs `restartCost`. A session at REAL_LIMIT_SHARE of a known `window` always restarts; an unknown window never continues.
70
+ */
71
+ export function restartDecision({ context = 0, turnsLeft = 0, cachePrice = CACHE_READ_USD, restartCost = RESTART_COST_USD, window = 0 } = {}) {
72
+ const continueCost = Math.max(0, turnsLeft) * Math.max(0, context) * cachePrice;
73
+ if (!(window > 0)) return { action: "restart", reason: "unknown_window", continueCost, restartCost };
74
+ if (context >= window * REAL_LIMIT_SHARE) return { action: "restart", reason: "real_limit", continueCost, restartCost };
75
+ return continueCost > restartCost ? { action: "restart", reason: "cost", continueCost, restartCost } : { action: "continue", reason: "cost", continueCost, restartCost };
32
76
  }
33
77
 
34
78
  /**
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { parseCeilingBySize, ceilingFor, predictRestart, handoffFacts, firstEditTurn, HANDOFF_FILES_MAX, routeHandoff, buildReadsOf, ROUTE_DIGEST_MAX_BYTES } from "./ceiling.mjs";
5
+ import { parseCeilingBySize, ceilingFor, predictRestart, handoffFacts, firstEditTurn, HANDOFF_FILES_MAX, routeHandoff, buildReadsOf, ROUTE_DIGEST_MAX_BYTES, modelCeiling, restartDecision, DEFAULT_CEILING, REAL_LIMIT_SHARE } from "./ceiling.mjs";
6
6
  import { contextRestartPrompt, routeDigestPrompt } from "./prompts.mjs";
7
7
  import { toolStats } from "./toolstats.mjs";
8
8
 
@@ -83,3 +83,34 @@ describe("route hand-off (#5812)", () => {
83
83
  assert.match(huge, /<\/route_digest>$/);
84
84
  });
85
85
  });
86
+
87
+ describe("model-aware ceiling and cost gate (#5829)", () => {
88
+ it("modelCeiling 1M model gets about 500000", () => {
89
+ assert.equal(modelCeiling("claude-opus-5-5[1m]"), 500000);
90
+ assert.equal(modelCeiling("claude-sonnet-5-5"), 100000);
91
+ assert.equal(modelCeiling("claude-opus-5-5[1m]", 0.6), 600000);
92
+ });
93
+ it("an unknown or missing model keeps 120000", () => {
94
+ assert.equal(modelCeiling("some-local-model"), DEFAULT_CEILING); assert.equal(modelCeiling(null), 120000);
95
+ });
96
+ it("explicit context_ceiling_tokens wins over model default", () => {
97
+ const m = "claude-opus-5-5[1m]";
98
+ assert.equal(ceilingFor("M", { tokens: 90000, model: m }), 90000);
99
+ assert.equal(ceilingFor("M", { tokens: 0, model: m }), 0, "0 = off");
100
+ assert.equal(ceilingFor("M", { tokens: null, bySize: { M: 80000 }, model: m }), 80000);
101
+ assert.equal(ceilingFor("L", { tokens: null, bySize: { M: 80000 }, model: m }), 500000);
102
+ assert.equal(ceilingFor("M", { tokens: null }), DEFAULT_CEILING, "no model, nothing set: the 120000 default, not off");
103
+ assert.equal(ceilingFor("M", { tokens: null, model: "mystery-1" }), DEFAULT_CEILING);
104
+ assert.equal(ceilingFor("L", { tokens: null, bySize: { M: 80000 } }), DEFAULT_CEILING, "a size without an entry keeps the default");
105
+ });
106
+ it("restartDecision continues when restart costs more", () => {
107
+ const d = restartDecision({ context: 200000, turnsLeft: 2, cachePrice: 0.5e-6, restartCost: 0.5, window: 1000000 });
108
+ assert.equal(d.action, "continue"); assert.ok(d.continueCost < d.restartCost);
109
+ assert.equal(restartDecision({ context: 200000, turnsLeft: 50, cachePrice: 0.5e-6, restartCost: 0.5, window: 1000000 }).action, "restart");
110
+ });
111
+ it("restartDecision restarts at the model real limit", () => {
112
+ const d = restartDecision({ context: 1000000 * REAL_LIMIT_SHARE, turnsLeft: 0, restartCost: 100, window: 1000000 });
113
+ assert.equal(d.action, "restart"); assert.equal(d.reason, "real_limit");
114
+ assert.equal(restartDecision({ context: 1000, turnsLeft: 0, restartCost: 100 }).action, "restart", "unknown window never continues");
115
+ });
116
+ });
@@ -0,0 +1,15 @@
1
+ /**
2
+ * #5964: the runner's decision on a hosted `--clear-breaker` request. The request carries the time it was made;
3
+ * it clears only a breaker that tripped at or before it, so a stale request cannot close a later trip.
4
+ */
5
+
6
+ /**
7
+ * @param {{tripped: ({at?: number}|null|undefined), requestAt: (number|boolean|null|undefined)}} p
8
+ * @returns {{clear: boolean, stale: boolean}} `clear`: reset the breaker; `stale`: the request predates the current trip (discard it)
9
+ */
10
+ export function decideClear({ tripped, requestAt }) {
11
+ if (requestAt === true) return { clear: true, stale: false }; // legacy boolean seam: unconditional
12
+ if (typeof requestAt !== "number" || !Number.isFinite(requestAt)) return { clear: false, stale: false };
13
+ if (tripped && Number.isFinite(tripped.at) && tripped.at > requestAt) return { clear: false, stale: true };
14
+ return { clear: true, stale: false };
15
+ }
@@ -0,0 +1,100 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5964: hosted --clear-breaker is a durable, time-scoped request the runner consumes on its next pass, however long that is.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { existsSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { tmpDir } from "../tests/_tmp.mjs";
9
+ import { decideClear } from "./clear-breaker.mjs";
10
+ import { openBatch } from "./batch.mjs";
11
+ import { orchestrate } from "./orchestrate.mjs";
12
+ import { runBatch } from "../engine-cli.mjs";
13
+
14
+ const memStore = () => { let st = null; return { load: () => (st ? JSON.parse(JSON.stringify(st)) : null), save: (s) => { st = JSON.parse(JSON.stringify(s)); }, log: () => {}, peek: () => st }; };
15
+ const EE = (detail) => ({ terminalReason: "engine-error", detail });
16
+ const MERGED = { terminalReason: "merged", pr: 9 };
17
+
18
+ /** A runner whose every pass costs 12 s of injected time; `req` is the pending request `at` (or null), made `reqAfterMs` after the trip. */
19
+ const slowRun = async ({ reqAfterMs }) => {
20
+ let t = 1_000_000, tripAt = null, req = null, consumed = 0; const acks = [], calls = [];
21
+ const script = { 1: [EE("boom A")], 2: [EE("boom B")], 3: [MERGED] };
22
+ const rows = await orchestrate({ issues: [1, 2, 3], parallel: 1, readBody: async () => "", now: () => t, store: memStore(), pollMs: 12000, breaker: { errors: 2, window_min: 10 },
23
+ sleep: async (ms) => { t += Math.max(12000, Number(ms) || 0); },
24
+ runOne: async (n) => { calls.push(n); t += 12000; return script[n][0]; },
25
+ onUpdate: (u) => { if (u.outcome === "breaker" && tripAt === null) { tripAt = t; req = tripAt + reqAfterMs; } },
26
+ getClearBreaker: () => req, consumeClearBreaker: () => { req = null; consumed++; }, ackClearBreaker: (i) => acks.push(i) });
27
+ return { rows, acks, calls, consumed };
28
+ };
29
+
30
+ describe("#5964 decideClear", () => {
31
+ it("clears a trip at or before the request; never a later one; boolean is legacy; nothing without a request", () => {
32
+ assert.deepEqual(decideClear({ tripped: { at: 100 }, requestAt: 150 }), { clear: true, stale: false });
33
+ assert.deepEqual(decideClear({ tripped: { at: 100 }, requestAt: 100 }), { clear: true, stale: false });
34
+ assert.deepEqual(decideClear({ tripped: { at: 200 }, requestAt: 150 }), { clear: false, stale: true });
35
+ assert.deepEqual(decideClear({ tripped: { at: 200 }, requestAt: true }), { clear: true, stale: false });
36
+ assert.deepEqual(decideClear({ tripped: null, requestAt: 150 }), { clear: true, stale: false });
37
+ for (const requestAt of [null, false, undefined, NaN, "x"]) assert.deepEqual(decideClear({ tripped: { at: 1 }, requestAt }), { clear: false, stale: false }, String(requestAt));
38
+ });
39
+ });
40
+
41
+ describe("#5964 runner pass", () => {
42
+ it("slow pass: request survives and next pass clears (a request 1 s into a 12 s pass is cleared and acked on the next pass, and admissions resume)", async () => {
43
+ const r = await slowRun({ reqAfterMs: 1000 });
44
+ assert.ok(r.acks.some((a) => a.cleared === true), "acked a real clear");
45
+ assert.equal(r.consumed, 1);
46
+ assert.ok(r.calls.includes(3), "issue 3 was admitted after the clear");
47
+ });
48
+
49
+ it("a request older than a later trip does not clear it (stale), and is consumed", async () => {
50
+ const r = await slowRun({ reqAfterMs: -5000 });
51
+ assert.equal(r.acks.some((a) => a.cleared === true), false);
52
+ assert.equal(r.consumed, 1);
53
+ assert.equal(r.calls.includes(3), false, "the later trip stays closed");
54
+ });
55
+ });
56
+
57
+ describe("#5964 slow pass over the real batch request file", () => {
58
+ it("slow pass: a request made 1 s into a 12 s pass stays on disk, the next pass clears tripped, acks, consumes it, and admissions resume", async () => {
59
+ const root = tmpDir("clrbrk-"); const b = openBatch(root, "b3"); b.store.save({ id: "b3" });
60
+ let t = 1_000_000, tripped = false, requested = false, release = null, onDiskAtNextPass = null; const calls = [], acks = [];
61
+ const gate = new Promise((r) => { release = r; });
62
+ const script = { 1: EE("boom A"), 2: EE("boom B"), 3: null, 4: MERGED };
63
+ const rows = await orchestrate({ issues: [1, 2, 3, 4], parallel: 3, readBody: async () => "", now: () => t, store: memStore(), pollMs: 12000, breaker: { errors: 2, window_min: 10 },
64
+ sleep: async () => {
65
+ if (tripped && !requested) { requested = true; b.requestClearBreaker(); t += 12000; release(); } // the request lands during a 12 s pass
66
+ else t += 12000;
67
+ },
68
+ runOne: async (n) => { calls.push(n); if (n === 3) { await gate; return MERGED; } return script[n]; },
69
+ onUpdate: (u) => { if (u.outcome === "breaker") tripped = true; },
70
+ getClearBreaker: () => { if (requested && onDiskAtNextPass === null) onDiskAtNextPass = existsSync(join(root, "b3", "clear-breaker")); return b.peekClearBreaker(); },
71
+ consumeClearBreaker: b.readClearBreaker, ackClearBreaker: (i) => { acks.push(i); b.ackClearBreaker(i); } });
72
+ assert.equal(onDiskAtNextPass, true, "the request survived until the runner's next pass");
73
+ assert.equal(acks.some((a) => a.cleared === true), true, "tripped was cleared and acked");
74
+ assert.equal(b.readClearBreakerAck().cleared, true);
75
+ assert.equal(existsSync(join(root, "b3", "clear-breaker")), false, "consumed after the decision");
76
+ assert.ok(calls.includes(4), "admissions resumed (issue 4 ran) with no restart");
77
+ assert.equal(rows.find((r) => r.issue === 4)?.outcome, "merged");
78
+ });
79
+ });
80
+
81
+ describe("#5964 batch request file and CLI", () => {
82
+ it("peekClearBreaker returns the request time without deleting it; readClearBreaker consumes", () => {
83
+ const root = tmpDir("clrbrk-"); const b = openBatch(root, "b1"); b.store.save({ id: "b1" });
84
+ assert.equal(b.peekClearBreaker(), null);
85
+ const at = b.requestClearBreaker();
86
+ assert.equal(b.peekClearBreaker(), at);
87
+ assert.equal(existsSync(join(root, "b1", "clear-breaker")), true, "peek leaves the file");
88
+ assert.equal(b.readClearBreaker(), true);
89
+ assert.equal(b.peekClearBreaker(), null);
90
+ });
91
+
92
+ it("unhosted (no daemon) batch keeps the direct state.json rewrite", async () => {
93
+ const root = tmpDir("clrbrk-"); const b = openBatch(root, "b2"); b.store.save({ id: "b2", breaker: { at: 1 }, errorTimes: [1] }); writeFileSync(join(root, "b2", "plan.json"), "{}");
94
+ const lines = [];
95
+ const r = await runBatch({ argv: ["--clear-breaker", "b2"], deps: { batchRoot: root, noDaemon: true }, sink: { line: (l) => lines.push(l) } });
96
+ assert.equal(r.cleared, true);
97
+ assert.equal(b.store.load().breaker, null);
98
+ assert.match(lines[0], /breaker cleared/);
99
+ });
100
+ });