forgedock 1.65.0 → 1.67.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 (80) hide show
  1. package/bin/config-schema.mjs +2 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +143 -19
  4. package/bin/forgedock.mjs +7 -0
  5. package/bin/help-text.mjs +3 -3
  6. package/bin/introspect-schedule.mjs +98 -0
  7. package/bin/introspect-schedule.test.mjs +67 -0
  8. package/bin/lean/advisory.test.mjs +49 -0
  9. package/bin/lean/amendment-schema.mjs +31 -0
  10. package/bin/lean/attempts.mjs +159 -0
  11. package/bin/lean/attempts.test.mjs +127 -0
  12. package/bin/lean/basered.mjs +55 -0
  13. package/bin/lean/basered.test.mjs +68 -1
  14. package/bin/lean/batch-health.mjs +13 -5
  15. package/bin/lean/batch-health.test.mjs +16 -0
  16. package/bin/lean/batch.mjs +62 -0
  17. package/bin/lean/batch.test.mjs +119 -3
  18. package/bin/lean/capwait.mjs +14 -3
  19. package/bin/lean/capwait.test.mjs +20 -0
  20. package/bin/lean/clear-breaker.mjs +14 -0
  21. package/bin/lean/commentstate.mjs +41 -0
  22. package/bin/lean/commentstate.test.mjs +32 -0
  23. package/bin/lean/concurrency.mjs +89 -0
  24. package/bin/lean/concurrency.test.mjs +113 -0
  25. package/bin/lean/conformance.e2e.test.mjs +4 -2
  26. package/bin/lean/conformance.mjs +35 -3
  27. package/bin/lean/conformance.test.mjs +52 -0
  28. package/bin/lean/depcache.mjs +9 -0
  29. package/bin/lean/efficiency.mjs +162 -0
  30. package/bin/lean/efficiency.test.mjs +79 -0
  31. package/bin/lean/execution.mjs +31 -13
  32. package/bin/lean/execution.test.mjs +46 -0
  33. package/bin/lean/failure-stop.mjs +46 -0
  34. package/bin/lean/failure-stop.test.mjs +45 -0
  35. package/bin/lean/fixtures/capacity-storm.json +609 -0
  36. package/bin/lean/lean.mjs +130 -30
  37. package/bin/lean/lean.test.mjs +138 -47
  38. package/bin/lean/liveness.mjs +37 -0
  39. package/bin/lean/liveness.test.mjs +33 -0
  40. package/bin/lean/orchestrate-attempts.test.mjs +74 -0
  41. package/bin/lean/orchestrate-envhold.test.mjs +17 -0
  42. package/bin/lean/orchestrate-pause.test.mjs +84 -0
  43. package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
  44. package/bin/lean/orchestrate.mjs +202 -28
  45. package/bin/lean/phaseledger.mjs +6 -0
  46. package/bin/lean/phaseledger.test.mjs +13 -1
  47. package/bin/lean/prompts.mjs +6 -10
  48. package/bin/lean/reconcile.mjs +90 -0
  49. package/bin/lean/recurrence.mjs +38 -2
  50. package/bin/lean/recurrence.test.mjs +56 -1
  51. package/bin/lean/sandbox-remote.mjs +33 -2
  52. package/bin/lean/sched.mjs +19 -0
  53. package/bin/lean/sched.test.mjs +11 -1
  54. package/bin/lean/schedd-health.mjs +8 -1
  55. package/bin/lean/schedd-health.test.mjs +19 -0
  56. package/bin/lean/schedd.mjs +97 -10
  57. package/bin/lean/schedd.test.mjs +138 -1
  58. package/bin/lean/slo.mjs +126 -0
  59. package/bin/lean/slo.test.mjs +112 -0
  60. package/bin/lean/statuscomment.mjs +37 -0
  61. package/bin/lean/statuscomment.test.mjs +48 -1
  62. package/bin/lean/verify.mjs +2 -1
  63. package/bin/pool/agent.mjs +46 -8
  64. package/bin/pool/cache-sweep.mjs +41 -4
  65. package/bin/pool/cli.mjs +28 -1
  66. package/bin/pool/health.mjs +18 -0
  67. package/bin/pool/lane-tools.mjs +21 -0
  68. package/bin/pool/mirror-seed.mjs +21 -2
  69. package/bin/pool/router.mjs +6 -2
  70. package/bin/stats/attempts.mjs +54 -0
  71. package/bin/stats/attempts.test.mjs +30 -0
  72. package/bin/stats/churn.mjs +49 -0
  73. package/bin/stats/churn.test.mjs +31 -0
  74. package/bin/stats/index.mjs +11 -3
  75. package/commands/orchestrate.md +21 -18
  76. package/docs/CONFIG.md +1 -0
  77. package/docs/OUTCOME-CODES.md +1 -0
  78. package/package.json +1 -1
  79. package/pool/image/entrypoint.sh +2 -1
  80. package/scripts/check-devdocs-freshness.sh +1 -1
@@ -34,6 +34,8 @@
34
34
  * Exit reasons (#4503): every exit logs a line: `idle, exiting`, `exiting (<signal>|uncaught: …)`, `lost lock|socket …,
35
35
  * exiting` (checked every `lockCheckMs`: the lock no longer holds this pid, or the socket is gone; nothing it does not own
36
36
  * is removed), then `exited (code N)`. Taking over a dead owner's lock is logged, so a SIGKILLed daemon leaves a trace.
37
+ * Standing orders (#5978): a `--select` batch's reconcile tick (selector join/leave, re-admission, breaker auto-reset) runs inside the
38
+ * batch's runner, which this daemon hosts: no watcher process, and no change to how the daemon or its batches are kept alive.
37
39
  * Upgrade handover (#5204): the same `lockCheckMs` tick compares `installedVersion()` (the `version` of the package.json of
38
40
  * this install) with the version loaded at start. When the install moved (`npm i -g`, `forgedock update`) it logs
39
41
  * `schedd: install moved v<old> → v<new>; handing over` once, runs `close()` (no admission, lanes keep running, lock and
@@ -42,7 +44,7 @@
42
44
  * `interrupted: upgrade vX→vY` row (orchestrate.mjs).
43
45
  * `runBatch({argv, cwd, env, sink, keepBreaker, signal})` is injected (engine-cli `runBatch`); `sink` gets `batch(b)`, `row(r)`, `line(text)`.
44
46
  */
45
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeSync } from "node:fs";
47
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
46
48
  import { createConnection, createServer } from "node:net";
47
49
  import { execFileSync, spawn } from "node:child_process";
48
50
  import { homedir, tmpdir } from "node:os";
@@ -52,6 +54,10 @@ import { fileURLToPath } from "node:url";
52
54
  import { schedDir, pidAlive } from "./sched.mjs";
53
55
  import { DEFAULT_STALL_MIN, FIRST_HOUR_FILE, FIRST_HOUR_MIN, batchVerdict, clearStaleStall, decideStallAction, evaluateDispatchStall, firstHourReport, readHealth, recordStallAlert, recordStallRecovery, runningSplit, writeFirstHour } from "./batch-health.mjs";
54
56
  import { probeBatchEnv } from "./lanecheck.mjs";
57
+ import { computeEfficiency, idleCause, operatorEvents, readEfficiency, writeEfficiency } from "./efficiency.mjs";
58
+ import { ledgerPass, parseSloConfig } from "./slo.mjs";
59
+ import { introspectReportPath } from "../introspect-schedule.mjs";
60
+ import { parseForgeYaml } from "../forge-utils.mjs";
55
61
  import { HEARTBEAT_MS, writeHeartbeat, clearHeartbeat } from "./schedd-health.mjs";
56
62
  import { batchRoot, listBatches, openBatch, SECRET_ENV } from "./batch.mjs";
57
63
  import { killTrackedChildren } from "./effects.mjs";
@@ -72,7 +78,7 @@ export function batchVerdicts(root, { now = Date.now(), windowMin = DEFAULT_STAL
72
78
  try {
73
79
  const b = openBatch(root, id);
74
80
  if (!b.readPlan()?.daemon || b.isTerminal()) continue;
75
- const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, lastProgressMs: b.lastProgressMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
81
+ const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, paused: b.readPause?.() ?? null, lastProgressMs: b.lastProgressMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
76
82
  const decision = stall ? decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, hosted: false }) : null;
77
83
  out.push(batchVerdict(id, stall, decision));
78
84
  } catch { /* one unreadable batch has no verdict */ }
@@ -90,6 +96,8 @@ export function sharedPendingLines(batches) {
90
96
  export const ORPHAN_AGE_MS = 7 * 24 * 3600 * 1000; // #5469: an unhosted batch idle this long with pending issues is orphaned
91
97
  export const IDLE_MS = 10 * 60 * 1000;
92
98
  export const STOP_MS = 10 * 1000;
99
+ export const HARD_EXIT_MS = 30 * 1000; // #5966: a self-initiated stop exits by then even if close() hangs
100
+ export const SUCCESSOR_MS = 10 * 1000; // #5966: how long a handover waits for the successor to listen
93
101
  export const LOCK_CHECK_MS = 5 * 1000;
94
102
  export const ADMIT_MS = 120 * 1000; // #4775: how long one add/requeue/attach/resume waits for its batch to start before answering an error
95
103
  export const LAG_MS = 5 * 1000; // #4775: an event-loop stall longer than this is logged
@@ -218,7 +226,9 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
218
226
  root = batchRoot(), log = (m) => console.log(m), pid = process.pid, alive = pidAlive, resumeOnStart = true, stopMs = STOP_MS,
219
227
  lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, stallCheckMs = Number(process.env.FORGEDOCK_SCHEDD_STALL_CHECK_MS) || 60_000, stallMin = Number(process.env.FORGEDOCK_SCHEDD_STALL_MIN) || DEFAULT_STALL_MIN, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
220
228
  abandonMs = (Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) > 0 ? Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) * 24 * 3600 * 1000 : ABANDON_AGE_MS), killChildren = killTrackedChildren,
221
- hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined, probeEnv = (env) => probeBatchEnv(env), restartForStall = undefined } = {}) {
229
+ hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined, probeEnv = (env) => probeBatchEnv(env), restartForStall = undefined,
230
+ exit = null, hardExitMs = HARD_EXIT_MS, unit = unitState, probe = undefined, successorMs = SUCCESSOR_MS, successorPollMs = 200, rehost = undefined, sloGh = undefined, introspect = undefined } = {}) {
231
+ const startOpts = arguments[0] ?? {};
222
232
  const p = scheddPaths(dir);
223
233
  // #5204: default handover target: a new daemon from the (new) install unless systemd restarts the unit itself
224
234
  const respawnFn = respawn !== undefined ? respawn : () => { if (!["active", "activating"].includes(unitState())) defaultSpawn({ dir }); };
@@ -237,7 +247,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
237
247
  const conns = new Set();
238
248
  const runs = new Map(); // every runBatch in flight (hosted or not yet started) -> its AbortController (#4454)
239
249
  const starting = new Map(); // batch id -> host() promise of a start-up resume not yet hosted (#4503: an attach waits for it)
240
- let closing = null, resolveClosed, keepSock = false;
250
+ let closing = null, resolveClosed, keepSock = false, stopCode = null, rehosted = null;
241
251
  let idleTimer, lockTimer, lagTimer, stallTimer, dueTimer; // assigned below; close() clears them
242
252
  let lastActive = Date.now();
243
253
  const touch = () => { lastActive = Date.now(); };
@@ -418,6 +428,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
418
428
  const changed = req.op === "hold" ? b.holdIssues(req.issues ?? [], req.meta ?? null) : b.releaseIssues(req.issues ?? []);
419
429
  return send({ type: "ok", changed, held: b.readHeld(), hosted: hosted.has(req.id) }, true);
420
430
  }
431
+ if (req.op === "pause" || req.op === "unpause") { // #5975: batch-level admission pause
432
+ const b = openBatch(root, req.id);
433
+ if (!b.exists()) throw new Error(`no batch ${req.id} in ${root}`);
434
+ if (req.op === "pause" && !req.meta?.reason) throw new Error("--pause needs --reason <text>");
435
+ const res = req.op === "pause" ? { pause: b.setPause(req.meta ?? {}) } : { changed: b.clearPause() };
436
+ return send({ type: "ok", ...res, hosted: hosted.has(req.id) }, true);
437
+ }
421
438
  if (req.op === "gc-orphans") { // #5469: cancel every orphaned batch (unhosted, pending issues, idle past the threshold)
422
439
  const { orphaned } = unhostedBatches(Date.now(), Number.isFinite(req.minAgeMs) ? req.minAgeMs : ORPHAN_AGE_MS);
423
440
  for (const o of orphaned) openBatch(root, o.id).requestCancel({ reason: "gc-orphans" });
@@ -515,6 +532,50 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
515
532
  });
516
533
  return closing;
517
534
  };
535
+ // #5966: a self-initiated stop (version handover, stall recovery). Under a systemd unit the process exits non-zero after a bounded
536
+ // drain so `Restart=` starts the successor (a hard timer fires even if close() hangs); without a unit it starts the successor and
537
+ // waits for it to listen, retrying once, then exits non-zero instead of lingering as an unreachable zombie.
538
+ const defaultProbe = () => new Promise((r) => {
539
+ if (process.platform === "win32") return r(true);
540
+ const c = createConnection(p.sock);
541
+ c.once("connect", () => { c.destroy(); r(true); });
542
+ c.once("error", () => r(false));
543
+ });
544
+ const probeFn = probe !== undefined ? probe : respawn === undefined ? defaultProbe : null;
545
+ const waitListening = async () => {
546
+ const end = Date.now() + successorMs;
547
+ for (;;) {
548
+ try { if (await probeFn()) return true; } catch { /* not yet */ }
549
+ if (Date.now() >= end) return false;
550
+ await new Promise((r) => setTimeout(r, successorPollMs));
551
+ }
552
+ };
553
+ let selfStopping = null;
554
+ const selfStop = () => (selfStopping ??= (async () => {
555
+ stopCode = 1;
556
+ const underUnit = ["active", "activating"].includes(unit());
557
+ let hard;
558
+ if (exit) { hard = setTimeout(() => { log(`schedd: stop did not finish within ${hardExitMs} ms, exiting`); exit(1); }, hardExitMs); hard.unref?.(); }
559
+ try {
560
+ await close();
561
+ const spawnOnce = () => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } };
562
+ spawnOnce();
563
+ if (probeFn && !underUnit) {
564
+ let ok = await waitListening();
565
+ if (!ok) { log("schedd: successor not listening; retrying"); spawnOnce(); ok = await waitListening(); }
566
+ if (!ok) {
567
+ // R1 (#5966): no successor came up: keep hosting by resuming the batches in this process (the lock is free again)
568
+ log(`schedd: no successor listening after ${successorMs} ms; hosting the batches again`);
569
+ try { rehosted = await (rehost !== undefined ? rehost() : startDaemon({ ...startOpts })); } catch (e) { log(`schedd: re-host failed: ${e?.message ?? e}`); }
570
+ if (rehosted?.running) { clearTimeout(hard); return; }
571
+ rehosted = null;
572
+ log("schedd: could not host again; exiting non-zero");
573
+ }
574
+ }
575
+ } catch (e) { log(`schedd: stop failed: ${e?.message ?? e}`); }
576
+ clearTimeout(hard);
577
+ if (exit) exit(1);
578
+ })());
518
579
  idleTimer = setInterval(() => {
519
580
  if (!hosted.size && !conns.size && Date.now() - lastActive >= idleMs) { log("schedd: idle, exiting"); close(); }
520
581
  }, Math.min(idleMs, 30_000));
@@ -528,13 +589,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
528
589
  const now = loadedVersion ? versionOf() : null;
529
590
  if (now && now !== loadedVersion) {
530
591
  log(`schedd: install moved v${loadedVersion} → v${now}; handing over`);
531
- close().then(() => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } });
592
+ selfStop();
532
593
  return;
533
594
  }
534
595
  let owner = NaN;
535
596
  try { owner = parseInt(readFileSync(p.lock, "utf8"), 10); } catch { /* gone */ }
536
597
  if (owner !== pid) { keepSock = true; log(`schedd: lost lock (owner ${Number.isInteger(owner) ? `pid ${owner}` : "none"}), exiting`); close(); }
537
- else if (process.platform !== "win32" && !existsSync(p.sock)) { log(`schedd: lost socket ${p.sock}, exiting`); close(); }
598
+ else if (process.platform !== "win32" && !existsSync(p.sock)) { log(`schedd: lost socket ${p.sock}, exiting`); stopCode = 1; close(); }
538
599
  }, lockCheckMs);
539
600
  lockTimer.unref?.();
540
601
  // #4775: an event loop starved by host load leaves sockets unanswered and children unreaped; leave a trace of it.
@@ -552,7 +613,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
552
613
  // upgrade handover path (#5204): close() aborts every runner and kills the daemon's own children (lanes keep running), then a
553
614
  // fresh daemon resumes every batch. Once per batch and ready set (recorded in health.json before the restart).
554
615
  const restartStall = restartForStall !== undefined ? (id) => restartForStall(id)
555
- : (id) => { log(`schedd: restarting to recover stalled batch ${id}`); close().then(() => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } }); };
616
+ : (id) => { log(`schedd: restarting to recover stalled batch ${id}`); selfStop(); };
556
617
  let watching = false;
557
618
  const watchBatches = async () => {
558
619
  if (closing || watching) return;
@@ -560,6 +621,26 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
560
621
  phase("watch");
561
622
  try { await watchPass(); } finally { watching = false; phase("idle"); }
562
623
  };
624
+ // #5987: per-pass efficiency ledger + SLO filing (default-off) + one introspect run at batch end. Advisory: every failure is swallowed.
625
+ const sloGhDefault = (args) => new Promise((ok, no) => { import("node:child_process").then(({ execFile }) => execFile("gh", args, { timeout: 30000 }, (e, out) => (e ? no(e) : ok(String(out))))); });
626
+ async function efficiencyTick(b, plan, state, { now, reported, cancelled }) {
627
+ try {
628
+ if (cancelled || !state) return;
629
+ const repoCwd = plan.cwd ?? process.cwd();
630
+ let cfg;
631
+ try { cfg = parseSloConfig(parseForgeYaml(readFileSync(join(repoCwd, "forge.yaml"), "utf8"))); } catch { cfg = parseSloConfig({}); }
632
+ const ceiling = b.readParallel() ?? Number(state.parallel ?? plan.parallel) ?? 0, running = Object.keys(state.running ?? {}).length;
633
+ const sample = reported ? null : { t: now, running, ceiling: Number.isFinite(ceiling) ? ceiling : running, ready: (state.pending ?? []).length, ...((c) => (c ? { cause: c } : {}))(b.readPause?.() ? "auth-pause" : idleCause(b.readLog(), now) ?? (b.readHeld().length ? "hold" : undefined)) };
634
+ const r = await ledgerPass({ batch: b, sample, cfg, gh: sloGh ?? sloGhDefault, now, repo: plan.repo ?? null, operator: operatorEvents(b.dir), compute: computeEfficiency, readEff: readEfficiency, writeEff: writeEfficiency, reportPath: cfg.fileIssues ? introspectReportPath(repoCwd) : null });
635
+ if (r?.actions?.length) log(`schedd: slo ${r.actions.map((a) => `${a.op} ${a.sig} #${a.issue}`).join(", ")}`);
636
+ const mark = join(b.dir, "introspect.json");
637
+ if (reported && cfg.fileIssues && !existsSync(mark)) {
638
+ writeEfficiency(b.dir, { ...r.eff, introspect: { at: new Date(now).toISOString() } });
639
+ writeFileSync(mark, JSON.stringify({ at: new Date(now).toISOString() }) + "\n", { mode: 0o600 });
640
+ (introspect ?? ((id, cwd) => spawn(process.execPath, [join(fileURLToPath(new URL("..", import.meta.url)), "introspect-schedule.mjs"), "--run"], { cwd, stdio: "ignore", detached: true, windowsHide: true }).unref()))(b.id, repoCwd);
641
+ }
642
+ } catch { /* advisory */ }
643
+ }
563
644
  async function watchPass() {
564
645
  const now = Date.now();
565
646
  for (const id of listBatches(root)) {
@@ -571,7 +652,8 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
571
652
  const created = Date.parse(plan.created ?? "");
572
653
  if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
573
654
  const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
574
- const stallOpts = { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
655
+ await efficiencyTick(b, plan, state, { now, reported, cancelled }); // #5987: advisory; never throws, never changes dispatch
656
+ const stallOpts = { held: b.readHeld(), paused: b.readPause?.() ?? null, parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
575
657
  let stall = evaluateDispatchStall(state, stallOpts);
576
658
  if (stall && preflight) { // #5745: name the preflight gate holding admission (advisory; dispatch decisions are unchanged)
577
659
  let gates = [];
@@ -579,7 +661,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
579
661
  if (gates.length) stall = evaluateDispatchStall(state, { ...stallOpts, gates }) ?? stall;
580
662
  }
581
663
  if (Number.isFinite(created) && (reported || now - created >= FIRST_HOUR_MIN * 60_000) && !existsSync(join(b.dir, FIRST_HOUR_FILE)) && now - created < 24 * 3600_000) {
582
- if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), holdInfo: b.readHoldInfo?.() ?? null, stall }))) log(`schedd: first-hour report written for batch ${id}`);
664
+ if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), holdInfo: b.readHoldInfo?.() ?? null, paused: b.readPause?.() ?? null, stall }))) log(`schedd: first-hour report written for batch ${id}`);
583
665
  }
584
666
  const sig = stall ? stall.ready.join(",") : "";
585
667
  const last = b.lastProgressMs();
@@ -645,7 +727,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
645
727
  started.catch((e) => log(`schedd: resume ${id} failed: ${e?.message ?? e}`)).finally(() => starting.delete(id));
646
728
  }
647
729
  }
648
- return { running: true, pid, sock: p.sock, close, closed };
730
+ return { running: true, pid, sock: p.sock, close: () => (rehosted ? rehosted.close() : close()), closed, stopCode: () => stopCode, rehosted: () => rehosted, settled: () => selfStopping ?? closed };
649
731
  }
650
732
 
651
733
  /** #5204: `version` of the package.json of this install (../../package.json), null when it cannot be read. */
@@ -691,6 +773,11 @@ export function startUnit({ run = execFileSync } = {}) {
691
773
  try { run("systemctl", ["--user", "start", "--no-block", UNIT], { timeout: 5000, stdio: "ignore" }); } catch { /* reported by the connect retry */ }
692
774
  }
693
775
 
776
+ /** Restart the installed unit (best effort); `start` is a no-op on an active unit with no daemon (#5966). */
777
+ export function restartUnit({ run = execFileSync } = {}) {
778
+ try { run("systemctl", ["--user", "restart", "--no-block", UNIT], { timeout: 5000, stdio: "ignore" }); } catch { /* the next watchdog run alerts again */ }
779
+ }
780
+
694
781
  /**
695
782
  * Connect to the daemon. When nobody listens it is started: a systemd-managed instance (`unitState()` active, activating
696
783
  * or reloading: restarting) is waited for and never raced by a second daemon, an installed but stopped unit is started
@@ -9,7 +9,7 @@ import { join } from "node:path";
9
9
  import { tmpDir } from "../tests/_tmp.mjs";
10
10
  import { openBatch, isLaneAlive, listBatches, SECRET_ENV, scanStats } from "./batch.mjs";
11
11
  import { killTrackedChildren, runWithInput, trackedChildCount } from "./effects.mjs";
12
- import { findUnhosted, startDaemon, scheddPaths, connectDaemon, request, unitState, SCHEDD_SCRIPT, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals, readInstalledVersion, batchVerdicts } from "./schedd.mjs";
12
+ import { findUnhosted, startDaemon, scheddPaths, connectDaemon, request, unitState, SCHEDD_SCRIPT, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals, readInstalledVersion, batchVerdicts, restartUnit } from "./schedd.mjs";
13
13
  import { schedDir } from "./sched.mjs";
14
14
  import { readHeartbeat } from "./schedd-health.mjs";
15
15
  import { formatTable, orchestrate } from "./orchestrate.mjs";
@@ -541,6 +541,25 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
541
541
  } finally { await d.close(); }
542
542
  });
543
543
 
544
+ it("R3: efficiencyTick reads forge.yaml from plan.cwd (not the daemon cwd) and spawns introspect there", async () => {
545
+ const dir = tmpDir("schedd-slo-cwd-"), root = join(dir, "batches"), repo = join(dir, "repo"), id = "b20261126-000000-6025", ghCalls = [], spawned = [];
546
+ mkdirSync(repo, { recursive: true });
547
+ const b = openBatch(root, id);
548
+ b.writePlan({ daemon: true, repo: "o/r", cwd: repo, created: new Date().toISOString() });
549
+ b.store.save({ v: 1, order: [1], results: {}, running: {}, pending: [], parallel: 2 });
550
+ b.writeReport({ done: true });
551
+ const start = () => startDaemon({ dir, root, runBatch: async () => ({}), log: () => {}, resumeOnStart: false, stallCheckMs: 50, sloGh: async (a) => { ghCalls.push(a); return "[]"; }, introspect: (i, cwd) => spawned.push([i, cwd]) });
552
+ writeFileSync(join(repo, "forge.yaml"), "orchestrate:\n slo:\n file_issues: false\n");
553
+ let d = await start();
554
+ try { await new Promise((r) => setTimeout(r, 600)); } finally { await d.close(); }
555
+ assert.deepEqual(spawned, [], "file_issues false in plan.cwd is honored");
556
+ assert.equal(ghCalls.length, 0);
557
+ writeFileSync(join(repo, "forge.yaml"), "orchestrate:\n slo:\n file_issues: true\n");
558
+ d = await start();
559
+ try { await until(() => spawned.length === 1, 8000); } finally { await d.close(); }
560
+ assert.deepEqual(spawned[0], [id, repo], "introspect runs on the batch repo");
561
+ });
562
+
544
563
  it("#5938: a stored stall clears within one tick (STALL CLEARED) once the batch is at K; status shows running/K and the split; the watchdog verdict is healthy", async () => {
545
564
  const dir = tmpDir("schedd-stall-clear-"), root = join(dir, "batches"), id = "b20261122-000000-5938", lines = [];
546
565
  const b = openBatch(root, id);
@@ -793,6 +812,92 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
793
812
  } finally { await d2?.close?.(); }
794
813
  });
795
814
 
815
+ it("#5966: a handover under an active unit exits non-zero after close, and the hard bound fires when a batch stop hangs", async () => {
816
+ for (const hang of [false, true]) {
817
+ const dir = tmpDir("schedd-exit-"), root = join(dir, "batches"), lines = [], exits = [];
818
+ let version = "1.51.0";
819
+ const d = await startDaemon({ dir, root, log: (m) => lines.push(m), resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => "active",
820
+ exit: (c) => exits.push(c), stopMs: hang ? 60_000 : 1000, hardExitMs: 200,
821
+ runBatch: ({ sink, signal }) => { sink.batch({ id: "x", dir }); return new Promise((_, rej) => { if (!hang) signal.addEventListener("abort", () => rej(Object.assign(new Error("stopped"), { code: "batch.stopped" }))); }); } });
822
+ request(await connectDaemon({ dir, spawnDaemon: null }), { op: "submit", argv: ["x"], cwd: dir, env: {} }).catch(() => {});
823
+ await until(() => lines.some((l) => l.includes("listening")));
824
+ version = "1.52.0";
825
+ await until(() => exits.length > 0);
826
+ assert.deepEqual(exits, [1], `hang=${hang}`);
827
+ assert.equal(d.stopCode(), 1);
828
+ if (hang) assert.ok(lines.some((l) => l.includes("did not finish within")), lines.join("\n"));
829
+ await d.close();
830
+ }
831
+ });
832
+
833
+ it("#5966 R1: without a unit, a handover whose successor never listens keeps hosting (re-hosted here); if that fails it exits non-zero", async () => {
834
+ const dir = tmpDir("schedd-nosucc-"), root = join(dir, "batches"), lines = [], exits = [];
835
+ let version = "1.51.0", spawns = 0;
836
+ const d = await startDaemon({ dir, root, log: (m) => lines.push(m), resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
837
+ exit: (c) => exits.push(c), respawn: () => { spawns++; }, probe: async () => false, successorMs: 50, successorPollMs: 10, runBatch: async () => ({}) });
838
+ version = "1.52.0";
839
+ await until(() => d.rehosted());
840
+ const d2 = d.rehosted();
841
+ try {
842
+ assert.equal(d2.running, true, "a daemon hosts again and holds the lock");
843
+ assert.equal(readFileSync(scheddPaths(dir).lock, "utf8").trim(), String(process.pid));
844
+ assert.deepEqual(exits, [], "no exit while hosting continues");
845
+ assert.equal(spawns, 2, "the successor was started twice");
846
+ assert.ok(lines.some((l) => l.includes("hosting the batches again")));
847
+ } finally { await d2.close(); }
848
+ // re-host impossible -> exit non-zero
849
+ const dir2 = tmpDir("schedd-nosucc2-"), exits2 = [];
850
+ let v2 = "1.51.0";
851
+ await startDaemon({ dir: dir2, root: join(dir2, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => v2, unit: () => null,
852
+ exit: (c) => exits2.push(c), respawn: () => {}, probe: async () => false, successorMs: 30, successorPollMs: 10, rehost: async () => null, runBatch: async () => ({}) });
853
+ v2 = "1.52.0";
854
+ await until(() => exits2.length > 0);
855
+ assert.deepEqual(exits2, [1]);
856
+ });
857
+
858
+ it("#5984 handover: settled() outlives closed until the successor is spawned and probed (CLI exits only after it)", async () => {
859
+ const dir = tmpDir("schedd-settled-"), order = [];
860
+ let version = "1.51.0";
861
+ const d = await startDaemon({ dir, root: join(dir, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
862
+ exit: (c) => order.push(`daemon-exit${c}`), respawn: () => order.push("respawn"), probe: async () => { order.push("probe"); return true; }, successorMs: 200, successorPollMs: 10, runBatch: async () => ({}) });
863
+ version = "1.52.0";
864
+ await d.closed;
865
+ order.push("closed-seen"); // what scheddFromCli used to exit on
866
+ await d.settled();
867
+ order.push("settled");
868
+ order.push(`exit${d.stopCode()}`); // the CLI's exit(stopCode), issued only once settled() resolved
869
+ assert.ok(order.indexOf("respawn") < order.indexOf("settled") && order.indexOf("probe") < order.indexOf("settled"), order.join(","));
870
+ assert.ok(order.indexOf("probe") < order.indexOf("settled") && order.indexOf("settled") < order.indexOf("exit1"), `exit1 after respawn, probe and settled: ${order.join(",")}`);
871
+ assert.equal(d.stopCode(), 1);
872
+ });
873
+
874
+ it("#5984 rehost: settled() of the stopped daemon resolves once the rehosted daemon is up; lost-lock/idle close settles via closed", async () => {
875
+ const dir = tmpDir("schedd-settled2-");
876
+ let version = "1.51.0";
877
+ const d = await startDaemon({ dir, root: join(dir, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
878
+ exit: () => {}, respawn: () => {}, probe: async () => false, successorMs: 30, successorPollMs: 10, runBatch: async () => ({}) });
879
+ version = "1.52.0";
880
+ await d.closed; await d.settled();
881
+ const d2 = d.rehosted();
882
+ assert.equal(d2?.running, true, "rehosted before settled resolves");
883
+ await d2.close();
884
+ const dir3 = tmpDir("schedd-settled3-");
885
+ const d3 = await startDaemon({ dir: dir3, root: join(dir3, "batches"), log: () => {}, resumeOnStart: false, runBatch: async () => ({}) });
886
+ await d3.close();
887
+ await d3.settled();
888
+ assert.equal(d3.stopCode(), null);
889
+ });
890
+
891
+ it("#5966: a stall-recovery restart also exits (shared self-stop path)", async () => {
892
+ const dir = tmpDir("schedd-stallexit-"), root = join(dir, "batches"), exits = [];
893
+ let version = "1.51.0";
894
+ const d = await startDaemon({ dir, root, log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => "active", exit: (c) => exits.push(c), runBatch: async () => ({}) });
895
+ version = "1.52.0";
896
+ await until(() => exits.length > 0);
897
+ assert.deepEqual(exits, [1]);
898
+ await d.closed;
899
+ });
900
+
796
901
  it("#5204: readInstalledVersion reads this install's package.json version, null when unreadable", () => {
797
902
  assert.equal(readInstalledVersion(), JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version);
798
903
  const dir = tmpDir("schedd-ver-");
@@ -1023,6 +1128,15 @@ describe("schedd under load and restart (#4775)", () => {
1023
1128
  await assert.rejects(connectDaemon({ dir: tmpDir("schedd-unit-"), spawnDaemon: null, unit: () => { throw new Error("not consulted"); } }), { code: "ENOENT" });
1024
1129
  });
1025
1130
 
1131
+ it("restartUnit issues systemctl --user restart --no-block and never throws", () => {
1132
+ const calls = [];
1133
+ restartUnit({ run: (...a) => { calls.push(a); } });
1134
+ assert.equal(calls[0][0], "systemctl");
1135
+ assert.deepEqual(calls[0][1].slice(0, 3), ["--user", "restart", "--no-block"]);
1136
+ assert.equal(calls[0][1].length, 4);
1137
+ restartUnit({ run: () => { throw new Error("x"); } });
1138
+ });
1139
+
1026
1140
  it("unitState reads the systemctl state (also from a non-zero exit) and is null without a unit file", () => {
1027
1141
  assert.equal(unitState({ exists: () => false }), null);
1028
1142
  assert.equal(unitState({ exists: () => true, run: () => "activating\n" }), "activating");
@@ -1093,6 +1207,29 @@ describe("schedd under load and restart (#4775)", () => {
1093
1207
  } finally { await d.close(); }
1094
1208
  });
1095
1209
 
1210
+ it("#6001 scheddFromCli handover: exit(stopCode) runs only after the successor is spawned and probed (awaits d.settled)", async () => {
1211
+ const events = [], tick = () => new Promise((r) => setTimeout(r, 15));
1212
+ const d = { running: true, closed: Promise.resolve(), stopCode: () => 1, rehosted: () => null,
1213
+ settled: async () => { await tick(); events.push("respawn"); await tick(); events.push("probe"); } };
1214
+ const res = await scheddFromCli([], { scheddDir: tmpDir("schedd-cli-h-"), startDaemon: async () => d, processOn: () => {}, exit: (c) => events.push(`exit${c}`), due: null, renice: () => {}, batchDeps: {} });
1215
+ assert.deepEqual(events, ["respawn", "probe", "exit1"]);
1216
+ assert.deepEqual(res, { running: false, exitCode: 1 });
1217
+ });
1218
+
1219
+ it("#6001 scheddFromCli rehost: exit waits for the rehosted daemon's closed and settled", async () => {
1220
+ const events = [], tick = () => new Promise((r) => setTimeout(r, 15));
1221
+ let closeB, settleB;
1222
+ const b = { running: true, closed: new Promise((r) => { closeB = r; }), stopCode: () => 1, rehosted: () => null, settled: () => new Promise((r) => { settleB = r; }) };
1223
+ const a = { running: true, closed: Promise.resolve(), stopCode: () => 1, rehosted: () => b, settled: async () => {} };
1224
+ const done = scheddFromCli([], { scheddDir: tmpDir("schedd-cli-r-"), startDaemon: async () => a, processOn: () => {}, exit: (c) => events.push(`exit${c}`), due: null, renice: () => {}, batchDeps: {} });
1225
+ await tick();
1226
+ assert.deepEqual(events, [], "exit must wait for the rehosted daemon's closed");
1227
+ closeB(); await tick();
1228
+ assert.deepEqual(events, [], "exit must wait for the rehosted daemon's settled");
1229
+ settleB(); await done;
1230
+ assert.deepEqual(events, ["exit1"]);
1231
+ });
1232
+
1096
1233
  it("the unit stands by while another daemon holds the lock instead of exiting 0 (no Restart=always loop)", async () => {
1097
1234
  const dir = tmpDir("schedd-sb-"), root = tmpDir("schedd-sb-b-");
1098
1235
  const owner = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore" });
@@ -0,0 +1,126 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Batch efficiency SLOs (#5987): `orchestrate.slo.*` thresholds with defaults, breach evaluation over an efficiency.json ledger
5
+ * (efficiency.mjs), and the filer that turns a breach into one rolling `engine-gap` issue per signature `slo:<code>:<repo>`.
6
+ * Filing is opt-in (`orchestrate.slo.file_issues: true` enables; default off, nothing is posted off-host); breaches are always recorded in efficiency.json.
7
+ * The filer takes an injected `gh(args) -> stdout`, appends a counter comment on a re-breach at most once per 6 h, and closes the
8
+ * issue after 24 h green. Its state lives in efficiency.json (`slo.sigs`), so a daemon restart neither re-files nor re-comments.
9
+ */
10
+ export const DEFAULT_SLO = Object.freeze({ concurrencyMin: 0.6, concurrencyMinutes: 30, repeatMax: 3, attemptsMax: 2, commentsMax: 20, interventionsMax: 6,
11
+ phaseRatioMax: 1.5, capacityRefusalsMax: 20, idleShareMax: 0.2, fileIssues: false, repo: "RapierCraftStudios/ForgeDock", label: "engine-gap" });
12
+ export const SLO_UPDATE_MS = 6 * 3_600_000;
13
+ export const SLO_CLOSE_GREEN_MS = 24 * 3_600_000;
14
+ const SNAKE = { concurrencyMin: "concurrency_min", concurrencyMinutes: "concurrency_minutes", repeatMax: "repeat_max", attemptsMax: "attempts_max", commentsMax: "comments_max",
15
+ interventionsMax: "interventions_max", phaseRatioMax: "phase_ratio_max", capacityRefusalsMax: "capacity_refusals_max", idleShareMax: "idle_share_max" };
16
+
17
+ /** forge.yaml (parsed) -> SLO config; the parser may nest (`orchestrate.slo.x`) or flatten (`orchestrate.x`). Bad values fall back. */
18
+ export function parseSloConfig(yaml) {
19
+ const o = yaml?.orchestrate && typeof yaml.orchestrate === "object" ? yaml.orchestrate : {};
20
+ const s = { ...o, ...(o.slo && typeof o.slo === "object" ? o.slo : {}) };
21
+ const out = { ...DEFAULT_SLO };
22
+ for (const [k, snake] of Object.entries(SNAKE)) { const v = s[snake] ?? s[`slo_${snake}`]; if (v !== undefined && String(v).trim() !== "" && Number.isFinite(Number(v)) && Number(v) >= 0) out[k] = Number(v); }
23
+ const f = s.file_issues ?? s.slo_file_issues;
24
+ out.fileIssues = f !== undefined && String(f).trim().toLowerCase() === "true";
25
+ const repo = String(s.repo ?? s.slo_repo ?? "").trim();
26
+ if (/^[\w.-]+\/[\w.-]+$/.test(repo)) out.repo = repo;
27
+ return out;
28
+ }
29
+
30
+ /** `[{code, sig, detail, issues, cause}]` for the ledger's current breaches. Pure. */
31
+ export function evaluateSlo(eff, cfg = DEFAULT_SLO, { repo = eff?.repo ?? "unknown" } = {}) {
32
+ if (!eff) return [];
33
+ const out = [], add = (code, detail, issues = [], cause = "") => out.push({ code, sig: `slo:${code}:${repo}`, detail, issues, cause });
34
+ const c = eff.concurrency ?? {};
35
+ if (c.ready > 0 && c.lowSinceMin >= cfg.concurrencyMinutes) add("concurrency", `achieved/ceiling ${c.achieved}/${c.ceiling} below ${cfg.concurrencyMin} for ${c.lowSinceMin} min with ${c.ready} ready`, [], `limiter ${(eff.limiters ?? []).join(", ") || "unknown"}`);
36
+ for (const r of eff.repeats ?? []) if (r.count >= cfg.repeatMax) add("repeat", `signature "${r.signature}" repeated ${r.count}x`, r.issues, "the same failure is retried without a change");
37
+ if (eff.attemptsPerMerged != null && eff.attemptsPerMerged > cfg.attemptsMax) add("attempts", `${eff.attemptsPerMerged} attempts per merged issue (max ${cfg.attemptsMax}, 24 h)`, [], "retry loop");
38
+ const cm = eff.commentsPerIssue ?? {};
39
+ if (cm.max > cfg.commentsMax) add("comments", `${cm.max} engine comments on one issue (max ${cfg.commentsMax})`, (cm.issues ?? []).filter((i) => i.comments > cfg.commentsMax).map((i) => i.issue), "comment bloat");
40
+ if (eff.interventionsPerDay > cfg.interventionsMax) add("interventions", `${eff.interventionsPerDay} operator interventions in 24 h (max ${cfg.interventionsMax})`, [], "the batch needs hand-holding");
41
+ const slow = Object.entries(eff.phases ?? {}).filter(([, v]) => v.ratio != null && v.ratio > cfg.phaseRatioMax);
42
+ if (slow.length) add("phase", slow.map(([id, v]) => `${id} p90 ${v.ratio}x baseline`).join("; "), [], `phase regression: ${slow.map(([id]) => id).join(", ")}`);
43
+ if (eff.capacityRefusalsPerHour > cfg.capacityRefusalsMax) add("capacity", `${eff.capacityRefusalsPerHour} capacity refusals in the last hour (max ${cfg.capacityRefusalsMax})`, [], "sandbox capacity");
44
+ for (const [cause, share] of Object.entries(eff.idle?.share ?? {})) if (cause !== "no-ready" && share > cfg.idleShareMax) add(`idle-${cause}`, `${Math.round(share * 100)}% of slot time idle for ${cause} (max ${Math.round(cfg.idleShareMax * 100)}%)`, [], `idle cause ${cause}`);
45
+ return out;
46
+ }
47
+
48
+ const body = (eff, b, { count = 1 } = {}) => [
49
+ `<!-- forge-slo: ${b.sig} -->`, `**SLO breach \`${b.code}\`** (batch \`${eff.batch}\`, repo \`${eff.repo}\`), occurrence ${count}`, "",
50
+ "| field | value |", "| --- | --- |", `| evidence | ${b.detail.replace(/\|/g, "/")} |`, `| window | 24 h to ${eff.at} (concurrency ${eff.concurrency?.windowMin} min) |`,
51
+ `| offending issues | ${b.issues.length ? b.issues.map((n) => `#${n}`).join(", ") : "none named"} |`, `| suggested cause | ${b.cause || "unknown"} |`,
52
+ `| signature | \`${b.sig}\` |`].join("\n");
53
+
54
+ /**
55
+ * Apply the filing rules. Returns `{slo, actions}` where `slo` is the next `slo.sigs` state (persist it in efficiency.json).
56
+ * With `enabled` false nothing is called and the state is unchanged. Never throws: a gh failure leaves that signature's state as it was.
57
+ */
58
+ export async function fileSloIssues({ eff, breaches, gh, cfg = DEFAULT_SLO, now = Date.now(), enabled = cfg.fileIssues, reportPath = null }) {
59
+ const sigs = { ...(eff?.slo?.sigs ?? {}) }, actions = [];
60
+ if (!enabled || typeof gh !== "function") return { slo: { sigs }, actions };
61
+ const live = new Set(breaches.map((b) => b.sig));
62
+ for (const b of breaches) {
63
+ const prev = sigs[b.sig];
64
+ try {
65
+ if (!prev?.issue) {
66
+ let found = null;
67
+ try { found = JSON.parse(String(await gh(["issue", "list", "--repo", cfg.repo, "--label", cfg.label, "--state", "open", "--search", `"${b.sig}" in:body`, "--json", "number,body"])) || "[]").find((i) => String(i.body ?? "").includes(b.sig)); } catch { found = null; }
68
+ if (found) { sigs[b.sig] = { issue: found.number, count: 1, openedAt: now, updatedAt: now, greenSince: null }; actions.push({ op: "adopt", sig: b.sig, issue: found.number }); continue; }
69
+ const out = String(await gh(["issue", "create", "--repo", cfg.repo, "--label", cfg.label, "--title", `engine-gap: ${b.code} SLO breach (${eff.repo})`, "--body", body(eff, b, { reportPath })]));
70
+ const n = Number(out.match(/(\d+)\s*$/)?.[1]);
71
+ if (Number.isSafeInteger(n)) { sigs[b.sig] = { issue: n, count: 1, openedAt: now, updatedAt: now, greenSince: null }; actions.push({ op: "create", sig: b.sig, issue: n }); }
72
+ continue;
73
+ }
74
+ if (now - prev.updatedAt < SLO_UPDATE_MS) { sigs[b.sig] = { ...prev, greenSince: null }; continue; } // alert noise: one update per signature per 6 h
75
+ const count = (prev.count ?? 1) + 1;
76
+ await gh(["issue", "comment", String(prev.issue), "--repo", cfg.repo, "--body", body(eff, b, { count, reportPath })]);
77
+ sigs[b.sig] = { ...prev, count, updatedAt: now, greenSince: null };
78
+ actions.push({ op: "comment", sig: b.sig, issue: prev.issue, count });
79
+ } catch { /* advisory: retried on the next pass */ }
80
+ }
81
+ for (const [sig, st] of Object.entries(sigs)) {
82
+ if (live.has(sig)) continue;
83
+ const since = st.greenSince ?? now;
84
+ if (now - since < SLO_CLOSE_GREEN_MS) { sigs[sig] = { ...st, greenSince: since }; continue; }
85
+ try { await gh(["issue", "close", String(st.issue), "--repo", cfg.repo, "--comment", `SLO \`${sig}\` has been green for 24 h; closing.`]); delete sigs[sig]; actions.push({ op: "close", sig, issue: st.issue }); } catch { /* retried */ }
86
+ }
87
+ return { slo: { sigs }, actions };
88
+ }
89
+
90
+ /** One advisory ledger pass for a batch: compute, evaluate, file (when enabled), persist. Never throws. */
91
+ export async function ledgerPass({ batch, sample, cfg, gh, now = Date.now(), repo = null, compute, readEff, writeEff, reportPath = null, operator = [] }) {
92
+ try {
93
+ const rows = batch.readLog(), prev = readEff(batch.dir);
94
+ let eff = compute({ rows, state: batch.store.peek(), prev, sample, now, batchId: batch.id, repo, operator, concurrencyMin: cfg.concurrencyMin });
95
+ const breaches = evaluateSlo(eff, cfg, { repo: repo ?? "unknown" });
96
+ const { slo, actions } = await fileSloIssues({ eff, breaches, gh, cfg, now, reportPath });
97
+ eff = { ...eff, slo, breaches: breaches.map((b) => ({ code: b.code, sig: b.sig, detail: b.detail, issue: slo.sigs[b.sig]?.issue ?? null })) };
98
+ writeEff(batch.dir, eff);
99
+ return { eff, breaches, actions };
100
+ } catch { return null; }
101
+ }
102
+
103
+ /**
104
+ * Introspect findings (#5987): file the `forgedock stats --conformance-outcomes` report as one rolling `engine-gap` issue per
105
+ * signature `introspect:<scope>`. Deduped against an open issue carrying the signature and against the prior report (`prior`
106
+ * = last filed `{hash, issue}`): an unchanged report files nothing. Returns `{action, issue?, hash}`; never throws.
107
+ */
108
+ export async function fileIntrospect({ report, scope, gh, cfg = DEFAULT_SLO, prior = null, reportPath = null }) {
109
+ const text = String(report ?? "").trim(), sig = `introspect:${scope}`;
110
+ if (!text || typeof gh !== "function") return { action: "none", hash: null };
111
+ const { createHash } = await import("node:crypto");
112
+ const hash = createHash("sha1").update(text).digest("hex").slice(0, 12);
113
+ if (prior?.hash === hash) return { action: "unchanged", hash, issue: prior.issue ?? null };
114
+ const body = `<!-- forge-slo: ${sig} -->\n**fd-introspect** (${scope})\n\n\`\`\`\n${text.slice(0, 6000)}\n\`\`\``;
115
+ try {
116
+ let found = null;
117
+ try { found = JSON.parse(String(await gh(["issue", "list", "--repo", cfg.repo, "--label", cfg.label, "--state", "open", "--search", `"${sig}" in:body`, "--json", "number,body"])) || "[]").find((i) => String(i.body ?? "").includes(sig)); } catch { found = null; }
118
+ if (found || prior?.issue) {
119
+ const n = found?.number ?? prior.issue;
120
+ await gh(["issue", "comment", String(n), "--repo", cfg.repo, "--body", body]);
121
+ return { action: "comment", issue: n, hash };
122
+ }
123
+ const out = String(await gh(["issue", "create", "--repo", cfg.repo, "--label", cfg.label, "--title", `engine-gap: fd-introspect findings (${scope})`, "--body", body]));
124
+ return { action: "create", issue: Number(out.match(/(\d+)\s*$/)?.[1]) || null, hash };
125
+ } catch { return { action: "failed", hash }; }
126
+ }