forgedock 1.66.0 → 1.68.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 (173) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +2 -0
  3. package/bin/engine-cli.mjs +193 -27
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +24 -1
  6. package/bin/help-text.mjs +4 -3
  7. package/bin/introspect-schedule.mjs +98 -0
  8. package/bin/introspect-schedule.test.mjs +67 -0
  9. package/bin/lean/admission.mjs +21 -0
  10. package/bin/lean/admission.test.mjs +30 -0
  11. package/bin/lean/advisory.test.mjs +64 -0
  12. package/bin/lean/amendment-schema.mjs +30 -0
  13. package/bin/lean/attempts.mjs +162 -0
  14. package/bin/lean/attempts.test.mjs +141 -0
  15. package/bin/lean/basered.mjs +81 -0
  16. package/bin/lean/basered.test.mjs +68 -1
  17. package/bin/lean/batch-health.mjs +20 -12
  18. package/bin/lean/batch-health.test.mjs +55 -11
  19. package/bin/lean/batch.mjs +45 -0
  20. package/bin/lean/batch.test.mjs +105 -5
  21. package/bin/lean/capwait.mjs +14 -3
  22. package/bin/lean/capwait.test.mjs +20 -0
  23. package/bin/lean/ci-gate.mjs +2 -90
  24. package/bin/lean/ci-gate.test.mjs +1 -127
  25. package/bin/lean/ci-precheck.mjs +25 -8
  26. package/bin/lean/ci-precheck.test.mjs +24 -0
  27. package/bin/lean/clear-breaker.mjs +14 -0
  28. package/bin/lean/clear-breaker.test.mjs +4 -3
  29. package/bin/lean/commentstate.mjs +46 -0
  30. package/bin/lean/commentstate.test.mjs +43 -0
  31. package/bin/lean/concurrency.mjs +89 -0
  32. package/bin/lean/concurrency.test.mjs +113 -0
  33. package/bin/lean/conformance.e2e.test.mjs +13 -8
  34. package/bin/lean/conformance.mjs +73 -181
  35. package/bin/lean/conformance.test.mjs +61 -345
  36. package/bin/lean/depcache.mjs +100 -10
  37. package/bin/lean/depcache.test.mjs +105 -0
  38. package/bin/lean/docsgate.mjs +0 -32
  39. package/bin/lean/docsgate.test.mjs +2 -23
  40. package/bin/lean/effects-cap.test.mjs +9 -1
  41. package/bin/lean/effects-killtree.test.mjs +35 -0
  42. package/bin/lean/effects.mjs +42 -24
  43. package/bin/lean/efficiency.mjs +162 -0
  44. package/bin/lean/efficiency.test.mjs +79 -0
  45. package/bin/lean/engine-readmit.test.mjs +35 -0
  46. package/bin/lean/envgap.mjs +93 -0
  47. package/bin/lean/envgap.test.mjs +53 -0
  48. package/bin/lean/execution.mjs +41 -17
  49. package/bin/lean/execution.test.mjs +58 -0
  50. package/bin/lean/failure-census.mjs +170 -0
  51. package/bin/lean/failure-census.test.mjs +59 -0
  52. package/bin/lean/failure-stop.mjs +46 -0
  53. package/bin/lean/failure-stop.test.mjs +45 -0
  54. package/bin/lean/fixtures/capacity-storm.json +609 -0
  55. package/bin/lean/guardgate.test.mjs +2 -3
  56. package/bin/lean/heavy.mjs +33 -4
  57. package/bin/lean/heavy.test.mjs +38 -6
  58. package/bin/lean/hotarea.mjs +0 -36
  59. package/bin/lean/hotarea.test.mjs +1 -22
  60. package/bin/lean/issuewatch-verify.mjs +19 -4
  61. package/bin/lean/issuewatch.mjs +21 -4
  62. package/bin/lean/issuewatch.test.mjs +48 -1
  63. package/bin/lean/lane-audit-gap.mjs +66 -0
  64. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  65. package/bin/lean/lane-audit-llm.mjs +5 -0
  66. package/bin/lean/lane-audit-query.mjs +47 -0
  67. package/bin/lean/lane-audit-query.test.mjs +44 -0
  68. package/bin/lean/lane-audit-signatures.mjs +33 -0
  69. package/bin/lean/lane-audit.mjs +110 -0
  70. package/bin/lean/lane-audit.test.mjs +97 -0
  71. package/bin/lean/lane-recovery.test.mjs +33 -0
  72. package/bin/lean/lanecheck.mjs +5 -3
  73. package/bin/lean/lanecheck.test.mjs +6 -0
  74. package/bin/lean/lean.mjs +311 -154
  75. package/bin/lean/lean.test.mjs +530 -223
  76. package/bin/lean/limits.mjs +17 -0
  77. package/bin/lean/limits.test.mjs +15 -1
  78. package/bin/lean/live-execution.mjs +21 -2
  79. package/bin/lean/live-execution.test.mjs +39 -0
  80. package/bin/lean/liveness.mjs +37 -0
  81. package/bin/lean/liveness.test.mjs +33 -0
  82. package/bin/lean/orchestrate-attempts.test.mjs +82 -0
  83. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  84. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  85. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  86. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  87. package/bin/lean/orchestrate-pause.test.mjs +76 -1
  88. package/bin/lean/orchestrate-reconcile.test.mjs +164 -0
  89. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  90. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  91. package/bin/lean/orchestrate.mjs +344 -45
  92. package/bin/lean/phaseledger.mjs +6 -0
  93. package/bin/lean/phaseledger.test.mjs +13 -1
  94. package/bin/lean/postdeploy-check.test.mjs +1 -3
  95. package/bin/lean/precheck.mjs +20 -0
  96. package/bin/lean/preflight.mjs +100 -11
  97. package/bin/lean/preflight.test.mjs +44 -4
  98. package/bin/lean/prompts.mjs +13 -28
  99. package/bin/lean/reconcile.mjs +90 -0
  100. package/bin/lean/recurrence.mjs +6 -112
  101. package/bin/lean/recurrence.test.mjs +11 -92
  102. package/bin/lean/release-flakes.mjs +14 -2
  103. package/bin/lean/release-flakes.test.mjs +17 -1
  104. package/bin/lean/release-ledger.mjs +19 -1
  105. package/bin/lean/release-ledger.test.mjs +23 -0
  106. package/bin/lean/release-preflight.mjs +28 -0
  107. package/bin/lean/release-preflight.test.mjs +42 -1
  108. package/bin/lean/release-review.mjs +40 -5
  109. package/bin/lean/release-review.test.mjs +43 -2
  110. package/bin/lean/release.mjs +43 -14
  111. package/bin/lean/release.test.mjs +32 -0
  112. package/bin/lean/retry.mjs +1 -1
  113. package/bin/lean/retry.test.mjs +6 -1
  114. package/bin/lean/rotator.mjs +9 -0
  115. package/bin/lean/rotator.test.mjs +11 -1
  116. package/bin/lean/sandbox-remote.mjs +49 -11
  117. package/bin/lean/sched.mjs +19 -0
  118. package/bin/lean/sched.test.mjs +11 -1
  119. package/bin/lean/schedd-health.mjs +4 -4
  120. package/bin/lean/schedd-health.test.mjs +8 -4
  121. package/bin/lean/schedd.mjs +45 -8
  122. package/bin/lean/schedd.test.mjs +120 -7
  123. package/bin/lean/selfreview.mjs +1 -1
  124. package/bin/lean/slo.mjs +126 -0
  125. package/bin/lean/slo.test.mjs +112 -0
  126. package/bin/lean/statuscomment.mjs +40 -0
  127. package/bin/lean/statuscomment.test.mjs +48 -1
  128. package/bin/lean/validate-catalog.mjs +108 -0
  129. package/bin/lean/validate-catalog.test.mjs +46 -1
  130. package/bin/lean/verify.mjs +3 -2
  131. package/bin/pool/affinity.test.mjs +91 -0
  132. package/bin/pool/agent.mjs +144 -10
  133. package/bin/pool/cache-sweep.mjs +31 -10
  134. package/bin/pool/ci-autoscale.mjs +160 -0
  135. package/bin/pool/cli.mjs +53 -9
  136. package/bin/pool/docker.mjs +3 -0
  137. package/bin/pool/engine-placement.test.mjs +94 -0
  138. package/bin/pool/lane-target.mjs +41 -0
  139. package/bin/pool/lane-tools.mjs +26 -0
  140. package/bin/pool/lane-tools.test.mjs +9 -0
  141. package/bin/pool/mirror-seed.mjs +15 -11
  142. package/bin/pool/router.mjs +88 -32
  143. package/bin/pool/version.mjs +29 -2
  144. package/bin/review-staging.mjs +11 -3
  145. package/bin/runner.mjs +59 -11
  146. package/bin/stats/attempts.mjs +54 -0
  147. package/bin/stats/attempts.test.mjs +30 -0
  148. package/bin/stats/churn.mjs +49 -0
  149. package/bin/stats/churn.test.mjs +31 -0
  150. package/bin/stats/index.mjs +11 -3
  151. package/bin/stats/release.mjs +7 -0
  152. package/bin/stats/release.test.mjs +20 -0
  153. package/bin/stats/scorecard.mjs +187 -0
  154. package/bin/stats/scorecard.test.mjs +89 -0
  155. package/commands/orchestrate.md +21 -18
  156. package/docs/CONFIG.md +41 -0
  157. package/docs/OUTCOME-CODES.md +2 -0
  158. package/docs/STATS.md +17 -0
  159. package/package.json +1 -1
  160. package/pool/image/Dockerfile +14 -2
  161. package/pool/image/manifest.json +25 -0
  162. package/pool/image/mirror.sh +11 -2
  163. package/pool/install/install-agent.ps1 +11 -4
  164. package/scripts/check-devdocs-freshness.sh +1 -1
  165. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  166. package/scripts/ci-local/cli.mjs +1 -1
  167. package/scripts/ci-local/plan.mjs +3 -2
  168. package/scripts/ci-local.test.sh +11 -0
  169. package/scripts/failure-census.mjs +67 -0
  170. package/scripts/review-finalize.sh +5 -5
  171. package/scripts/review-finalize.test.sh +8 -1
  172. package/scripts/verify-phase-trail.sh +11 -0
  173. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -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";
@@ -73,7 +79,7 @@ export function batchVerdicts(root, { now = Date.now(), windowMin = DEFAULT_STAL
73
79
  const b = openBatch(root, id);
74
80
  if (!b.readPlan()?.daemon || b.isTerminal()) continue;
75
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
- const decision = stall ? decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, hosted: false }) : null;
82
+ const decision = stall ? decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, hosted: false, now, windowMin }) : null;
77
83
  out.push(batchVerdict(id, stall, decision));
78
84
  } catch { /* one unreadable batch has no verdict */ }
79
85
  }
@@ -221,7 +227,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
221
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,
222
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,
223
229
  hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined, probeEnv = (env) => probeBatchEnv(env), restartForStall = undefined,
224
- exit = null, hardExitMs = HARD_EXIT_MS, unit = unitState, probe = undefined, successorMs = SUCCESSOR_MS, successorPollMs = 200, rehost = undefined } = {}) {
230
+ exit = null, hardExitMs = HARD_EXIT_MS, unit = unitState, probe = undefined, successorMs = SUCCESSOR_MS, successorPollMs = 200, rehost = undefined, sloGh = undefined, introspect = undefined } = {}) {
225
231
  const startOpts = arguments[0] ?? {};
226
232
  const p = scheddPaths(dir);
227
233
  // #5204: default handover target: a new daemon from the (new) install unless systemd restarts the unit itself
@@ -282,7 +288,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
282
288
  if (closing) return;
283
289
  let b, st;
284
290
  try { b = openBatch(root, id); if (b.readReport() || b.readCancel() || !b.pendingIssues().length) return; st = b.store.load(); } catch { return; }
285
- if (st?.breaker && !st.breaker.transport) return; // a tripped breaker holds the batch for an operator --resume (a re-host would stop again at once)
291
+ if (st?.breaker && !st.breaker.transport && !st.breaker.environmental) return; // a tripped breaker holds the batch for an operator --resume (a re-host would stop again at once)
286
292
  const at = Math.min(...b.pendingIssues().map((n) => Number(st?.notBefore?.[n]) || Infinity));
287
293
  if (!Number.isFinite(at)) return; // nothing waits on the clock: a deliberate hold stays for --resume
288
294
  if (at <= Date.now()) return; // the run that just ended already saw this retry-at pass and did not admit: re-hosting would loop every second
@@ -309,7 +315,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
309
315
  const b = openBatch(root, id);
310
316
  if (b.readCancel()) return;
311
317
  const st = b.store.load();
312
- if (st?.breaker && !st.breaker.transport) return;
318
+ if (st?.breaker && !st.breaker.transport && !st.breaker.environmental) return;
313
319
  sig = JSON.stringify([b.unrunAdds(), b.unrunRequeues().map((e) => e.issue ?? e)]);
314
320
  if (!b.unrunAdds().length && !b.unrunRequeues().length) { rehostedUnrun.delete(id); return; }
315
321
  } catch { return; }
@@ -527,7 +533,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
527
533
  return closing;
528
534
  };
529
535
  // #5966: a self-initiated stop (version handover, stall recovery). Under a systemd unit the process exits non-zero after a bounded
530
- // drain so `Restart=` starts the successor (a hard timer fires even if close() hangs); without a unit it starts the successor and
536
+ // drain so `Restart=` starts the successor (a hard bound fires even if close() hangs; path-scoped, see selfStop, #5983); without a unit it starts the successor and
531
537
  // waits for it to listen, retrying once, then exits non-zero instead of lingering as an unreachable zombie.
532
538
  const defaultProbe = () => new Promise((r) => {
533
539
  if (process.platform === "win32") return r(true);
@@ -549,9 +555,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
549
555
  stopCode = 1;
550
556
  const underUnit = ["active", "activating"].includes(unit());
551
557
  let hard;
552
- if (exit) { hard = setTimeout(() => { log(`schedd: stop did not finish within ${hardExitMs} ms, exiting`); exit(1); }, hardExitMs); hard.unref?.(); }
558
+ // Path-scoped bound: under a unit it covers the whole stop (close only); unitless it covers close(), then a last-resort bound
559
+ // outlasts the two successor waits and the re-host (a flat hardExitMs equals the sum of those phases and would exit unhosted).
560
+ const arm = (ms, what) => { if (!exit) return undefined; const t = setTimeout(() => { log(`schedd: ${what} did not finish within ${ms} ms, exiting`); exit(1); }, ms); t.unref?.(); return t; };
561
+ hard = arm(hardExitMs, "stop");
553
562
  try {
554
563
  await close();
564
+ if (!underUnit && exit) { clearTimeout(hard); hard = arm(2 * successorMs + 2 * successorPollMs + hardExitMs, "successor handover"); }
555
565
  const spawnOnce = () => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } };
556
566
  spawnOnce();
557
567
  if (probeFn && !underUnit) {
@@ -615,6 +625,26 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
615
625
  phase("watch");
616
626
  try { await watchPass(); } finally { watching = false; phase("idle"); }
617
627
  };
628
+ // #5987: per-pass efficiency ledger + SLO filing (default-off) + one introspect run at batch end. Advisory: every failure is swallowed.
629
+ 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))))); });
630
+ async function efficiencyTick(b, plan, state, { now, reported, cancelled }) {
631
+ try {
632
+ if (cancelled || !state) return;
633
+ const repoCwd = plan.cwd ?? process.cwd();
634
+ let cfg;
635
+ try { cfg = parseSloConfig(parseForgeYaml(readFileSync(join(repoCwd, "forge.yaml"), "utf8"))); } catch { cfg = parseSloConfig({}); }
636
+ const ceiling = b.readParallel() ?? Number(state.parallel ?? plan.parallel) ?? 0, running = Object.keys(state.running ?? {}).length;
637
+ 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)) };
638
+ 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 });
639
+ if (r?.actions?.length) log(`schedd: slo ${r.actions.map((a) => `${a.op} ${a.sig} #${a.issue}`).join(", ")}`);
640
+ const mark = join(b.dir, "introspect.json");
641
+ if (reported && cfg.fileIssues && !existsSync(mark)) {
642
+ writeEfficiency(b.dir, { ...r.eff, introspect: { at: new Date(now).toISOString() } });
643
+ writeFileSync(mark, JSON.stringify({ at: new Date(now).toISOString() }) + "\n", { mode: 0o600 });
644
+ (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);
645
+ }
646
+ } catch { /* advisory */ }
647
+ }
618
648
  async function watchPass() {
619
649
  const now = Date.now();
620
650
  for (const id of listBatches(root)) {
@@ -626,6 +656,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
626
656
  const created = Date.parse(plan.created ?? "");
627
657
  if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
628
658
  const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
659
+ await efficiencyTick(b, plan, state, { now, reported, cancelled }); // #5987: advisory; never throws, never changes dispatch
629
660
  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) };
630
661
  let stall = evaluateDispatchStall(state, stallOpts);
631
662
  if (stall && preflight) { // #5745: name the preflight gate holding admission (advisory; dispatch decisions are unchanged)
@@ -649,7 +680,8 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
649
680
  // ready set is recovered once (health.json stallRecovery survives a daemon restart), a repeat alerts with the probed cause.
650
681
  let probe = null;
651
682
  try { probe = plan.env ? probeEnv(mergeEnv(process.env, plan.env)) : null; } catch { probe = null; }
652
- const decision = decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, probe, hosted: isHosted });
683
+ const decision = decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, probe, hosted: isHosted, now, windowMin: stallMin });
684
+ if (decision.action === "wait") continue; // #6082: a capacity wait or a recovery still inside its backoff
653
685
  if (decision.action === "alert") {
654
686
  if (recordStallAlert(b, stall, { cause: decision.cause })) log(`schedd: batch ${id} needs you: ${stall.detail}${decision.cause ? `; probed: ${decision.cause}` : ""}`);
655
687
  continue;
@@ -746,6 +778,11 @@ export function startUnit({ run = execFileSync } = {}) {
746
778
  try { run("systemctl", ["--user", "start", "--no-block", UNIT], { timeout: 5000, stdio: "ignore" }); } catch { /* reported by the connect retry */ }
747
779
  }
748
780
 
781
+ /** Restart the installed unit (best effort); `start` is a no-op on an active unit with no daemon (#5966). */
782
+ export function restartUnit({ run = execFileSync } = {}) {
783
+ try { run("systemctl", ["--user", "restart", "--no-block", UNIT], { timeout: 5000, stdio: "ignore" }); } catch { /* the next watchdog run alerts again */ }
784
+ }
785
+
749
786
  /**
750
787
  * Connect to the daemon. When nobody listens it is started: a systemd-managed instance (`unitState()` active, activating
751
788
  * 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);
@@ -563,7 +582,7 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
563
582
  } finally { await d.close(); }
564
583
  });
565
584
 
566
- it("#5806: a hosted runner wedged in setup restarts the daemon once (decision logged); the same stall again alerts and never loops", async () => {
585
+ it("#5806: a hosted runner wedged in setup restarts the daemon (decision logged); the same stall again is healed again after the backoff, no alert (#6082)", async () => {
567
586
  const dir = tmpDir("schedd-stall-setup-"), root = join(dir, "batches"), id = "b20261121-000000-5806";
568
587
  const b = openBatch(root, id);
569
588
  b.writePlan({ daemon: true, repo: "o/r", created: new Date().toISOString() });
@@ -579,10 +598,9 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
579
598
  assert.ok(lines.some((l) => /FORGE:DECISION batch .+ stall-recovery: restart the hosting schedd/.test(l)), lines.join("\n"));
580
599
  assert.equal(JSON.parse(readFileSync(join(b.dir, "health.json"), "utf8")).stallRecovery.action, "restart-daemon");
581
600
  utimesSync(join(b.dir, "state.json"), old, old);
582
- await until(() => readFileSync(join(b.dir, "health.json"), "utf8").includes("stalled again after auto-recovery"), 8000);
583
- await new Promise((r) => setTimeout(r, 300));
584
- assert.equal(restarts.length, 1, "recovered once, then alerted");
585
- assert.match(readFileSync(join(b.dir, "batch.log"), "utf8"), /BATCH UNHEALTHY .*\(stuck in setup, 0\/2 issues read\).*probed: stalled again after auto-recovery/);
601
+ await until(() => restarts.length >= 2, 8000);
602
+ assert.equal(JSON.parse(readFileSync(join(b.dir, "health.json"), "utf8")).stallRecovery.count >= 2, true, "a second recovery is recorded");
603
+ assert.doesNotMatch(readFileSync(join(b.dir, "batch.log"), "utf8"), /BATCH UNHEALTHY/, "no operator alert while self-heal has attempts left");
586
604
  } finally { await d.close(); }
587
605
  });
588
606
 
@@ -641,6 +659,24 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
641
659
  } finally { await d.close(); }
642
660
  });
643
661
 
662
+ it("#6042: a batch whose breaker is environmental is re-hosted by the timer", async () => {
663
+ const dir = tmpDir("schedd-rehost-env-"), root = join(dir, "batches"), id = "b20261031-000000-6042";
664
+ const calls = [];
665
+ const runBatch = async ({ argv, sink }) => {
666
+ calls.push(argv);
667
+ const b = openBatch(root, id);
668
+ if (argv[0] !== "--resume") { b.writePlan({ daemon: true, repo: "o/r" }); b.store.save({ v: 1, order: [1], results: {}, running: {}, pending: [1], notBefore: { 1: Date.now() + 300 }, breaker: { at: Date.now(), errors: 3, environmental: true } }); }
669
+ sink.batch({ id, dir: b.dir });
670
+ return {};
671
+ };
672
+ const d = await startDaemon({ dir, root, runBatch, log: () => {}, resumeOnStart: false });
673
+ try {
674
+ await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "submit", argv: ["1"], cwd: dir, env: {} });
675
+ await until(() => calls.length >= 2, 8000);
676
+ assert.equal(calls[1][0], "--resume");
677
+ } finally { await d.close(); }
678
+ });
679
+
644
680
  it("#4454: close() stops every hosted batch loop before releasing the lock; no batch admits a lane after close()", async () => {
645
681
  const dir = tmpDir("schedd-stop-"), root = join(dir, "batches"), lock = scheddPaths(dir).lock;
646
682
  const started = { a: [], b: [] }, stoppedWithLock = {};
@@ -836,17 +872,62 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
836
872
  assert.deepEqual(exits2, [1]);
837
873
  });
838
874
 
875
+ it("#5983: unitless, the hard bound does not cut the successor waits short of the re-host; a hung close still exits", async () => {
876
+ const dir = tmpDir("schedd-bound-"), lines = [], exits = [];
877
+ let version = "1.51.0";
878
+ const d = await startDaemon({ dir, root: join(dir, "batches"), log: (m) => lines.push(m), resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
879
+ exit: (c) => exits.push(c), hardExitMs: 100, respawn: () => {}, probe: async () => false, successorMs: 150, successorPollMs: 10, runBatch: async () => ({}) });
880
+ version = "1.52.0";
881
+ await until(() => d.rehosted());
882
+ try {
883
+ assert.equal(d.rehosted().running, true, "re-hosted after waits longer than hardExitMs");
884
+ await new Promise((r) => setTimeout(r, 250));
885
+ assert.deepEqual(exits, [], "the hard timer did not fire");
886
+ } finally { await d.rehosted().close(); }
887
+ const dir2 = tmpDir("schedd-bound2-"), exits2 = [];
888
+ let v2 = "1.51.0";
889
+ await startDaemon({ dir: dir2, root: join(dir2, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => v2, unit: () => null,
890
+ exit: (c) => exits2.push(c), hardExitMs: 150, stopMs: 400, respawn: () => {}, probe: async () => false, successorMs: 50, successorPollMs: 10,
891
+ runBatch: ({ sink }) => { sink.batch({ id: "x", dir: dir2 }); return new Promise(() => {}); } }).then(async (d3) => {
892
+ request(await connectDaemon({ dir: dir2, spawnDaemon: null }), { op: "submit", argv: ["x"], cwd: dir2, env: {} }).catch(() => {});
893
+ await until(() => d3.running);
894
+ v2 = "1.52.0";
895
+ await until(() => exits2.length > 0);
896
+ assert.deepEqual(exits2, [1]);
897
+ await until(() => d3.rehosted()); // the stop carries on after the bound fired; release what it re-hosts
898
+ await d3.rehosted().close();
899
+ });
900
+ });
901
+
902
+ it("#5983: unitless re-host that hangs still exits via the last-resort timer", async () => {
903
+ const dir = tmpDir("schedd-bound3-"), exits = [];
904
+ let version = "1.51.0";
905
+ const d = await startDaemon({ dir, root: join(dir, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
906
+ exit: (c) => exits.push(c), hardExitMs: 100, respawn: () => {}, probe: async () => false, successorMs: 30, successorPollMs: 10,
907
+ rehost: () => new Promise(() => {}), runBatch: async () => ({}) });
908
+ try {
909
+ version = "1.52.0";
910
+ await until(() => exits.length > 0);
911
+ assert.deepEqual(exits, [1]);
912
+ } finally {
913
+ // the mocked exit leaves the daemon's timers and socket alive: close it (bounded, the re-host never settles) so the test file can exit
914
+ await Promise.race([d.close(), new Promise((r) => setTimeout(r, 1000).unref())]);
915
+ }
916
+ });
917
+
839
918
  it("#5984 handover: settled() outlives closed until the successor is spawned and probed (CLI exits only after it)", async () => {
840
919
  const dir = tmpDir("schedd-settled-"), order = [];
841
920
  let version = "1.51.0";
842
921
  const d = await startDaemon({ dir, root: join(dir, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
843
- exit: (c) => order.push(`exit${c}`), respawn: () => order.push("respawn"), probe: async () => { order.push("probe"); return true; }, successorMs: 200, successorPollMs: 10, runBatch: async () => ({}) });
922
+ exit: (c) => order.push(`daemon-exit${c}`), respawn: () => order.push("respawn"), probe: async () => { order.push("probe"); return true; }, successorMs: 200, successorPollMs: 10, runBatch: async () => ({}) });
844
923
  version = "1.52.0";
845
924
  await d.closed;
846
925
  order.push("closed-seen"); // what scheddFromCli used to exit on
847
926
  await d.settled();
848
927
  order.push("settled");
928
+ order.push(`exit${d.stopCode()}`); // the CLI's exit(stopCode), issued only once settled() resolved
849
929
  assert.ok(order.indexOf("respawn") < order.indexOf("settled") && order.indexOf("probe") < order.indexOf("settled"), order.join(","));
930
+ assert.ok(order.indexOf("probe") < order.indexOf("settled") && order.indexOf("settled") < order.indexOf("exit1"), `exit1 after respawn, probe and settled: ${order.join(",")}`);
850
931
  assert.equal(d.stopCode(), 1);
851
932
  });
852
933
 
@@ -1107,6 +1188,15 @@ describe("schedd under load and restart (#4775)", () => {
1107
1188
  await assert.rejects(connectDaemon({ dir: tmpDir("schedd-unit-"), spawnDaemon: null, unit: () => { throw new Error("not consulted"); } }), { code: "ENOENT" });
1108
1189
  });
1109
1190
 
1191
+ it("restartUnit issues systemctl --user restart --no-block and never throws", () => {
1192
+ const calls = [];
1193
+ restartUnit({ run: (...a) => { calls.push(a); } });
1194
+ assert.equal(calls[0][0], "systemctl");
1195
+ assert.deepEqual(calls[0][1].slice(0, 3), ["--user", "restart", "--no-block"]);
1196
+ assert.equal(calls[0][1].length, 4);
1197
+ restartUnit({ run: () => { throw new Error("x"); } });
1198
+ });
1199
+
1110
1200
  it("unitState reads the systemctl state (also from a non-zero exit) and is null without a unit file", () => {
1111
1201
  assert.equal(unitState({ exists: () => false }), null);
1112
1202
  assert.equal(unitState({ exists: () => true, run: () => "activating\n" }), "activating");
@@ -1177,6 +1267,29 @@ describe("schedd under load and restart (#4775)", () => {
1177
1267
  } finally { await d.close(); }
1178
1268
  });
1179
1269
 
1270
+ it("#6001 scheddFromCli handover: exit(stopCode) runs only after the successor is spawned and probed (awaits d.settled)", async () => {
1271
+ const events = [], tick = () => new Promise((r) => setTimeout(r, 15));
1272
+ const d = { running: true, closed: Promise.resolve(), stopCode: () => 1, rehosted: () => null,
1273
+ settled: async () => { await tick(); events.push("respawn"); await tick(); events.push("probe"); } };
1274
+ const res = await scheddFromCli([], { scheddDir: tmpDir("schedd-cli-h-"), startDaemon: async () => d, processOn: () => {}, exit: (c) => events.push(`exit${c}`), due: null, renice: () => {}, batchDeps: {} });
1275
+ assert.deepEqual(events, ["respawn", "probe", "exit1"]);
1276
+ assert.deepEqual(res, { running: false, exitCode: 1 });
1277
+ });
1278
+
1279
+ it("#6001 scheddFromCli rehost: exit waits for the rehosted daemon's closed and settled", async () => {
1280
+ const events = [], tick = () => new Promise((r) => setTimeout(r, 15));
1281
+ let closeB, settleB;
1282
+ const b = { running: true, closed: new Promise((r) => { closeB = r; }), stopCode: () => 1, rehosted: () => null, settled: () => new Promise((r) => { settleB = r; }) };
1283
+ const a = { running: true, closed: Promise.resolve(), stopCode: () => 1, rehosted: () => b, settled: async () => {} };
1284
+ const done = scheddFromCli([], { scheddDir: tmpDir("schedd-cli-r-"), startDaemon: async () => a, processOn: () => {}, exit: (c) => events.push(`exit${c}`), due: null, renice: () => {}, batchDeps: {} });
1285
+ await tick();
1286
+ assert.deepEqual(events, [], "exit must wait for the rehosted daemon's closed");
1287
+ closeB(); await tick();
1288
+ assert.deepEqual(events, [], "exit must wait for the rehosted daemon's settled");
1289
+ settleB(); await done;
1290
+ assert.deepEqual(events, ["exit1"]);
1291
+ });
1292
+
1180
1293
  it("the unit stands by while another daemon holds the lock instead of exiting 0 (no Restart=always loop)", async () => {
1181
1294
  const dir = tmpDir("schedd-sb-"), root = tmpDir("schedd-sb-b-");
1182
1295
  const owner = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore" });
@@ -69,7 +69,7 @@ export const PLANNER_TIGHTENING = Object.freeze({
69
69
  });
70
70
 
71
71
  const PATH_RE = /[\w@.-]+(?:\/[\w@.*-]+)+\.\w+|[\w@.-]+\/[\w@.*-]+\/?/g;
72
- const NEEDS_RESULT = new Set(["requirement_unimplemented", "untracked_deferral"]);
72
+ const NEEDS_RESULT = new Set(["requirement_unimplemented", "requirement_no_status", "untracked_deferral"]);
73
73
 
74
74
  /**
75
75
  * The deterministic conformance findings of the current tree: [{code, kind, detail, section}]. Validate commands are not
@@ -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
+ }
@@ -0,0 +1,112 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { computeEfficiency } from "./efficiency.mjs";
6
+ import { DEFAULT_SLO, ledgerPass, SLO_CLOSE_GREEN_MS, SLO_UPDATE_MS, evaluateSlo, fileSloIssues, parseSloConfig } from "./slo.mjs";
7
+
8
+ const eff = (o = {}) => ({ batch: "b1", repo: "o/r", at: "t", concurrency: { ready: 0, lowSinceMin: 0, windowMin: 15 }, repeats: [], commentsPerIssue: { max: 0, issues: [] }, phases: {}, idle: { share: {} }, ...o });
9
+ const codes = (o) => evaluateSlo(eff(o), DEFAULT_SLO).map((b) => b.code);
10
+ const fakeGh = () => { const calls = []; return { calls, gh: async (a) => { calls.push(a); return a[1] === "list" ? "[]" : a[1] === "create" ? "https://github.com/x/y/issues/42\n" : ""; } }; };
11
+
12
+ describe("#5987 SLOs", () => {
13
+ it("defaults and file_issues off unless explicitly true", () => {
14
+ const c = parseSloConfig({});
15
+ assert.equal(c.fileIssues, false); assert.equal(DEFAULT_SLO.fileIssues, false);
16
+ assert.equal(parseSloConfig({ orchestrate: { slo: { file_issues: "yes" } } }).fileIssues, false); assert.equal(c.repeatMax, 3); assert.equal(c.concurrencyMin, 0.6);
17
+ assert.equal(parseSloConfig({ orchestrate: { slo: { file_issues: "true", repeat_max: "5", attempts_max: "bad" } } }).repeatMax, 5);
18
+ assert.equal(parseSloConfig({ orchestrate: { file_issues: "true" } }).fileIssues, true);
19
+ assert.equal(parseSloConfig({ orchestrate: { slo: { file_issues: "false" } } }).fileIssues, false);
20
+ assert.equal(parseSloConfig({ orchestrate: { slo: { attempts_max: "bad" } } }).attemptsMax, 2);
21
+ });
22
+
23
+ it("each SLO breaches past its limit and not at it", () => {
24
+ assert.deepEqual(codes({ concurrency: { ready: 3, lowSinceMin: 30, achieved: 1, ceiling: 4, windowMin: 15 } }), ["concurrency"]);
25
+ assert.deepEqual(codes({ concurrency: { ready: 0, lowSinceMin: 90 } }), [], "nothing ready is not a breach");
26
+ assert.deepEqual(codes({ repeats: [{ signature: "s", count: 3, issues: [1] }] }), ["repeat"]);
27
+ assert.deepEqual(codes({ repeats: [{ signature: "s", count: 2, issues: [1] }] }), []);
28
+ assert.deepEqual(codes({ attemptsPerMerged: 2.5 }), ["attempts"]);
29
+ assert.deepEqual(codes({ attemptsPerMerged: 2 }), []);
30
+ assert.deepEqual(codes({ commentsPerIssue: { max: 21, issues: [{ issue: 5, comments: 21 }] } }), ["comments"]);
31
+ assert.deepEqual(codes({ interventionsPerDay: 7 }), ["interventions"]);
32
+ assert.deepEqual(codes({ interventionsPerDay: 6 }), []);
33
+ assert.deepEqual(codes({ phases: { fix: { ratio: 1.6 } } }), ["phase"]);
34
+ assert.deepEqual(codes({ phases: { fix: { ratio: 1.5 } } }), []);
35
+ assert.deepEqual(codes({ capacityRefusalsPerHour: 21 }), ["capacity"]);
36
+ assert.deepEqual(codes({ idle: { share: { hold: 0.3, "no-ready": 0.9 } } }), ["idle-hold"]);
37
+ });
38
+
39
+ it("files nothing unless enabled", async () => {
40
+ const f = fakeGh(), b = evaluateSlo(eff({ interventionsPerDay: 9 }), DEFAULT_SLO);
41
+ const r = await fileSloIssues({ eff: eff(), breaches: b, gh: f.gh, cfg: { ...DEFAULT_SLO, fileIssues: false }, now: 1e9 });
42
+ assert.equal(f.calls.length, 0); assert.deepEqual(r.slo.sigs, {});
43
+ });
44
+
45
+ it("posted bodies carry no local path", async () => {
46
+ const f = fakeGh(), cfg = { ...DEFAULT_SLO, fileIssues: true }, b = evaluateSlo(eff({ interventionsPerDay: 9 }), cfg);
47
+ await fileSloIssues({ eff: eff(), breaches: b, gh: f.gh, cfg, now: 1e12, reportPath: "/home/u/.forge/introspect/x.txt" });
48
+ assert.ok(f.calls.some((c) => c[1] === "create"));
49
+ assert.ok(!f.calls.some((c) => c.join(" ").includes("/home/u")), "reportPath never posted");
50
+ });
51
+
52
+ it("one issue per signature, a re-breach inside 6 h is silent, after 6 h a counter comment, 24 h green closes", async () => {
53
+ const f = fakeGh(), cfg = { ...DEFAULT_SLO, fileIssues: true }, b = evaluateSlo(eff({ interventionsPerDay: 9, attemptsPerMerged: 5 }), cfg);
54
+ let now = 1e12, e = eff();
55
+ const pass = async (br) => { const r = await fileSloIssues({ eff: e, breaches: br, gh: f.gh, cfg, now }); e = { ...e, slo: r.slo }; return r; };
56
+ let r = await pass(b);
57
+ assert.equal(f.calls.filter((c) => c[1] === "create").length, 2, "one create per signature");
58
+ assert.equal(e.slo.sigs["slo:interventions:o/r"].issue, 42);
59
+ now += SLO_UPDATE_MS - 1; r = await pass(b);
60
+ assert.deepEqual(r.actions, [], "no update inside 6 h");
61
+ now += 2; r = await pass(b);
62
+ assert.deepEqual(r.actions.map((a) => [a.op, a.count]), [["comment", 2], ["comment", 2]]);
63
+ now += 1000; r = await pass([]);
64
+ assert.deepEqual(r.actions, []);
65
+ now += SLO_CLOSE_GREEN_MS - 1; r = await pass([]);
66
+ assert.deepEqual(r.actions, []);
67
+ now += 2; r = await pass([]);
68
+ assert.deepEqual(r.actions.map((a) => a.op), ["close", "close"]);
69
+ assert.deepEqual(e.slo.sigs, {});
70
+ });
71
+
72
+ it("adopts an open issue found by signature instead of creating a second", async () => {
73
+ const calls = [], cfg = { ...DEFAULT_SLO, fileIssues: true }, b = evaluateSlo(eff({ interventionsPerDay: 9 }), cfg);
74
+ const gh = async (a) => { calls.push(a); return a[1] === "list" ? JSON.stringify([{ number: 7, body: `<!-- forge-slo: ${b[0].sig} -->` }]) : ""; };
75
+ const r = await fileSloIssues({ eff: eff(), breaches: b, gh, cfg, now: 1 });
76
+ assert.equal(r.slo.sigs[b[0].sig].issue, 7); assert.ok(!calls.some((c) => c[1] === "create"));
77
+ });
78
+
79
+ it("a gh failure never throws", async () => {
80
+ const cfg = { ...DEFAULT_SLO, fileIssues: true };
81
+ const r = await fileSloIssues({ eff: eff(), breaches: evaluateSlo(eff({ interventionsPerDay: 9 }), cfg), gh: async () => { throw new Error("down"); }, cfg, now: 1 });
82
+ assert.deepEqual(r.slo.sigs, {});
83
+ });
84
+
85
+ // R8: replay of the slow batches (11-20..11-24), rows in the shape orchestrate.mjs update() writes; no recorded batch is checked in files exactly one issue per breached signature; a healthy batch files none
86
+ const replay = async (rows, running) => {
87
+ const NOW = Date.parse("2026-11-24T12:00:00Z"), calls = [], cfg = { ...DEFAULT_SLO, fileIssues: true };
88
+ const prev = { v: 1, samples: Array.from({ length: 40 }, (_, i) => ({ t: NOW - (40 - i) * 60000, running, ceiling: 12, ready: 5 })) };
89
+ let stored = prev;
90
+ const batch = { id: "b", dir: "d", readLog: () => rows, store: { peek: () => null } };
91
+ const gh = async (a) => { calls.push(a); return a[1] === "list" ? "[]" : a[1] === "create" ? `https://github.com/x/y/issues/${100 + calls.length}\n` : ""; };
92
+ const operator = Array.from({ length: 5 }, (_, i) => ({ at: NOW - (100 - i) * 60000, kind: i % 2 ? "requeue" : "hold" }));
93
+ const run = () => ledgerPass({ batch, sample: null, operator, cfg, gh, now: NOW, repo: "o/r", compute: computeEfficiency, readEff: () => stored, writeEff: (_d, e) => { stored = e; } });
94
+ const first = await run(), second = await run();
95
+ return { first, second, creates: calls.filter((c) => c[1] === "create") };
96
+ };
97
+ it("fixture replay: slow batch files one issue per signature, healthy files none", async () => {
98
+ const at = (m, r) => ({ at: new Date(Date.parse("2026-11-24T12:00:00Z") - m * 60000).toISOString(), ...r });
99
+ const slow = [
100
+ ...[1, 2, 3, 4].map((i) => at(300 - i, { issue: 7, outcome: "engine-error", reason: "sandbox.capacity", minutes: 30 })),
101
+ at(200, { issue: 7, outcome: "merged", minutes: 20 }), at(190, { issue: 8, outcome: "ci-failed", minutes: 10 }), at(180, { issue: 8, outcome: "merged", minutes: 10 }),
102
+ at(110, { issue: null, outcome: "added", detail: "9" }), at(105, { issue: 9, outcome: "deferred", code: "run.interrupted", detail: "interrupted: upgrade; requeued" }),
103
+ ];
104
+ const r = await replay(slow, 3);
105
+ const sigs = r.first.breaches.map((b) => b.sig);
106
+ for (const c of ["concurrency", "repeat", "attempts", "interventions"]) assert.ok(sigs.includes(`slo:${c}:o/r`), c);
107
+ assert.equal(r.creates.length, new Set(sigs).size, "one create per signature, the second pass adds none");
108
+ assert.equal(r.second.actions.length, 0);
109
+ const ok = await replay([at(60, { issue: 1, outcome: "merged", minutes: 20 })], 11);
110
+ assert.equal(ok.creates.length, 0);
111
+ });
112
+ });