forgedock 1.67.0 → 1.69.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 (156) hide show
  1. package/bin/config-schema.mjs +1 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +103 -21
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +17 -1
  6. package/bin/help-text.mjs +1 -0
  7. package/bin/lean/admission.mjs +21 -0
  8. package/bin/lean/admission.test.mjs +30 -0
  9. package/bin/lean/advisory.test.mjs +39 -15
  10. package/bin/lean/amendment-schema.mjs +3 -4
  11. package/bin/lean/attempts.mjs +34 -31
  12. package/bin/lean/attempts.test.mjs +33 -19
  13. package/bin/lean/basered.mjs +26 -0
  14. package/bin/lean/batch-health.mjs +17 -12
  15. package/bin/lean/batch-health.test.mjs +39 -11
  16. package/bin/lean/batch.mjs +11 -1
  17. package/bin/lean/batch.test.mjs +51 -2
  18. package/bin/lean/capsample.mjs +25 -0
  19. package/bin/lean/ci-gate.mjs +2 -90
  20. package/bin/lean/ci-gate.test.mjs +1 -127
  21. package/bin/lean/ci-precheck.mjs +25 -8
  22. package/bin/lean/ci-precheck.test.mjs +24 -0
  23. package/bin/lean/clear-breaker.test.mjs +4 -3
  24. package/bin/lean/commentstate.mjs +10 -5
  25. package/bin/lean/commentstate.test.mjs +12 -1
  26. package/bin/lean/conformance.e2e.test.mjs +9 -6
  27. package/bin/lean/conformance.mjs +62 -197
  28. package/bin/lean/conformance.test.mjs +46 -376
  29. package/bin/lean/depcache.mjs +102 -10
  30. package/bin/lean/depcache.test.mjs +105 -0
  31. package/bin/lean/docsgate.mjs +0 -32
  32. package/bin/lean/docsgate.test.mjs +2 -23
  33. package/bin/lean/effects-cap.test.mjs +9 -1
  34. package/bin/lean/effects-killtree.test.mjs +35 -0
  35. package/bin/lean/effects.mjs +57 -25
  36. package/bin/lean/engine-readmit.test.mjs +35 -0
  37. package/bin/lean/envgap.mjs +111 -0
  38. package/bin/lean/envgap.test.mjs +64 -0
  39. package/bin/lean/execution.mjs +13 -4
  40. package/bin/lean/execution.test.mjs +33 -0
  41. package/bin/lean/failure-census.mjs +170 -0
  42. package/bin/lean/failure-census.test.mjs +59 -0
  43. package/bin/lean/failure-stop.mjs +12 -1
  44. package/bin/lean/failure-stop.test.mjs +14 -1
  45. package/bin/lean/guardgate.test.mjs +2 -3
  46. package/bin/lean/heavy.mjs +33 -4
  47. package/bin/lean/heavy.test.mjs +38 -6
  48. package/bin/lean/hostconfig.mjs +54 -0
  49. package/bin/lean/hostconfig.test.mjs +67 -0
  50. package/bin/lean/hotarea.mjs +0 -36
  51. package/bin/lean/hotarea.test.mjs +1 -22
  52. package/bin/lean/issuewatch-verify.mjs +19 -4
  53. package/bin/lean/issuewatch.mjs +21 -4
  54. package/bin/lean/issuewatch.test.mjs +48 -1
  55. package/bin/lean/lane-audit-gap.mjs +66 -0
  56. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  57. package/bin/lean/lane-audit-llm.mjs +52 -0
  58. package/bin/lean/lane-audit-llm.test.mjs +57 -0
  59. package/bin/lean/lane-audit-query.mjs +47 -0
  60. package/bin/lean/lane-audit-query.test.mjs +44 -0
  61. package/bin/lean/lane-audit-signatures.mjs +33 -0
  62. package/bin/lean/lane-audit.mjs +110 -0
  63. package/bin/lean/lane-audit.test.mjs +97 -0
  64. package/bin/lean/lane-recovery.test.mjs +33 -0
  65. package/bin/lean/lanecheck.mjs +5 -3
  66. package/bin/lean/lanecheck.test.mjs +6 -0
  67. package/bin/lean/lean.mjs +247 -152
  68. package/bin/lean/lean.test.mjs +502 -206
  69. package/bin/lean/limits.mjs +17 -0
  70. package/bin/lean/limits.test.mjs +15 -1
  71. package/bin/lean/live-execution.mjs +24 -2
  72. package/bin/lean/live-execution.test.mjs +62 -0
  73. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  74. package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
  75. package/bin/lean/orchestrate-envhold.test.mjs +62 -1
  76. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  77. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  78. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  79. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  80. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  81. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  82. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  83. package/bin/lean/orchestrate.mjs +215 -42
  84. package/bin/lean/postdeploy-check.test.mjs +1 -3
  85. package/bin/lean/precheck.mjs +20 -0
  86. package/bin/lean/preflight.mjs +110 -14
  87. package/bin/lean/preflight.test.mjs +64 -4
  88. package/bin/lean/prompts.mjs +11 -21
  89. package/bin/lean/recurrence.mjs +6 -148
  90. package/bin/lean/recurrence.test.mjs +11 -147
  91. package/bin/lean/release-deploy.mjs +35 -5
  92. package/bin/lean/release-deploy.test.mjs +50 -3
  93. package/bin/lean/release-flakes.mjs +48 -2
  94. package/bin/lean/release-flakes.test.mjs +45 -1
  95. package/bin/lean/release-ledger.mjs +19 -1
  96. package/bin/lean/release-ledger.test.mjs +23 -0
  97. package/bin/lean/release-preflight.mjs +28 -0
  98. package/bin/lean/release-preflight.test.mjs +42 -1
  99. package/bin/lean/release-review.mjs +40 -5
  100. package/bin/lean/release-review.test.mjs +43 -2
  101. package/bin/lean/release.mjs +45 -15
  102. package/bin/lean/release.test.mjs +32 -0
  103. package/bin/lean/retry.mjs +1 -1
  104. package/bin/lean/retry.test.mjs +6 -1
  105. package/bin/lean/rotator.mjs +9 -0
  106. package/bin/lean/rotator.test.mjs +11 -1
  107. package/bin/lean/sandbox-remote.mjs +51 -13
  108. package/bin/lean/schedd.mjs +13 -8
  109. package/bin/lean/schedd.test.mjs +65 -5
  110. package/bin/lean/selfreview.mjs +1 -1
  111. package/bin/lean/statuscomment.mjs +4 -1
  112. package/bin/lean/validate-catalog.mjs +108 -0
  113. package/bin/lean/validate-catalog.test.mjs +46 -1
  114. package/bin/lean/verify.mjs +1 -1
  115. package/bin/pool/affinity.test.mjs +91 -0
  116. package/bin/pool/agent.mjs +247 -23
  117. package/bin/pool/cache-sweep.mjs +31 -10
  118. package/bin/pool/ci-autoscale.mjs +160 -0
  119. package/bin/pool/cli.mjs +56 -9
  120. package/bin/pool/docker.mjs +5 -0
  121. package/bin/pool/engine-placement.test.mjs +94 -0
  122. package/bin/pool/image-manifest.mjs +24 -0
  123. package/bin/pool/image-manifest.test.mjs +20 -0
  124. package/bin/pool/lane-target.mjs +41 -0
  125. package/bin/pool/lane-tools.mjs +29 -5
  126. package/bin/pool/lane-tools.test.mjs +36 -7
  127. package/bin/pool/mirror-seed.mjs +15 -11
  128. package/bin/pool/project-layer.mjs +142 -0
  129. package/bin/pool/project-layer.test.mjs +73 -0
  130. package/bin/pool/router.mjs +106 -36
  131. package/bin/pool/version.mjs +72 -2
  132. package/bin/review-staging.mjs +11 -3
  133. package/bin/runner.mjs +59 -11
  134. package/bin/stats/release.mjs +7 -0
  135. package/bin/stats/release.test.mjs +20 -0
  136. package/bin/stats/scorecard.mjs +187 -0
  137. package/bin/stats/scorecard.test.mjs +89 -0
  138. package/bin/stats/tool-parks.mjs +29 -0
  139. package/bin/stats/tool-parks.test.mjs +21 -0
  140. package/docs/CONFIG.md +41 -0
  141. package/docs/OUTCOME-CODES.md +1 -0
  142. package/docs/STATS.md +17 -0
  143. package/package.json +1 -1
  144. package/pool/image/Dockerfile +15 -3
  145. package/pool/image/manifest.json +25 -0
  146. package/pool/image/mirror.sh +11 -2
  147. package/pool/install/install-agent.ps1 +11 -4
  148. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  149. package/scripts/ci-local/cli.mjs +1 -1
  150. package/scripts/ci-local/plan.mjs +3 -2
  151. package/scripts/ci-local.test.sh +14 -2
  152. package/scripts/failure-census.mjs +67 -0
  153. package/scripts/review-finalize.sh +5 -5
  154. package/scripts/review-finalize.test.sh +8 -1
  155. package/scripts/verify-phase-trail.sh +11 -0
  156. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -25,7 +25,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
25
25
  import { writeAtomic } from "./batch.mjs";
26
26
  import { schedDir, pidAlive, DEFAULT_PRIORITY } from "./sched.mjs";
27
27
  import { which } from "./toolchain.mjs";
28
- import { hostParallelism } from "./admission.mjs";
28
+ import { hostParallelism, quotaCores } from "./admission.mjs";
29
29
  import { lowerPriority } from "./hostload.mjs";
30
30
 
31
31
  export const HEAVY_DEFAULTS = Object.freeze({ enabled: true, max: null, step_mem_mb: 2048, reserve_mb: 1024, ramp_s: 60, max_wait_s: 1800 });
@@ -253,6 +253,33 @@ export async function acquireHeavy(h, entry = {}, { pollMs = HEAVY_POLL_MS, slee
253
253
  }
254
254
  }
255
255
 
256
+ /**
257
+ * #6047: remote-token backend, chosen when CS_HEAVY_BASE (the pool agent's per-sandbox /heavy route) is set. Acquire polls
258
+ * while the agent denies, renews the lease on a timer, release is best effort; an unreachable or erroring agent, or a wait past
259
+ * `maxWaitMs`, fails open (the step runs, `failOpen: true`). `fetchFn` returns {status, json()}.
260
+ */
261
+ export async function acquireRemote({ base, credToken = "", fetchFn = (u, o) => fetch(u, o), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = () => Date.now(), pollMs = 5000, renewMs = 60000, maxWaitMs = HEAVY_DEFAULTS.max_wait_s * 1000, setTimer = setInterval, clearTimer = clearInterval } = {}) {
262
+ const call = async (action, body) => {
263
+ const r = await fetchFn(`${base}/${action}`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${credToken}` }, body: JSON.stringify(body ?? {}), signal: AbortSignal.timeout(10000) });
264
+ if (r.status !== 200) throw new Error(`heavy ${action}: HTTP ${r.status}`);
265
+ return r.json();
266
+ };
267
+ const t0 = now(), open = { waitMs: 0, queued: 0, holders: 1, release: () => {} };
268
+ for (;;) {
269
+ let r;
270
+ try { r = await call("acquire"); } catch { return { ...open, waitMs: now() - t0, failOpen: true }; }
271
+ if (r?.granted && r.token) {
272
+ const token = r.token, timer = setTimer(() => { call("renew", { token }).catch(() => {}); }, renewMs);
273
+ timer?.unref?.();
274
+ let released = false;
275
+ return { ...open, waitMs: now() - t0, token, release: () => { if (released) return; released = true; clearTimer(timer); call("release", { token }).catch(() => {}); } };
276
+ }
277
+ if (now() - t0 >= maxWaitMs) return { ...open, waitMs: now() - t0, failOpen: true, timedOut: true };
278
+ await sleep(Math.min(pollMs, Math.max(1, Number(r?.retry_after_s) * 1000 || pollMs)));
279
+ }
280
+ }
281
+ const cgroupRead = (f) => readFileSync(f, "utf8");
282
+
256
283
  /** Default lane effect: `acquire(entry, cfg)` → {waitMs, queued, release()} (cfg = the lane's forge.yaml heavy keys); `stats()`; `lane(pids)` (#4405). */
257
284
  export function makeHeavyIo({ dir = schedDir(), env = process.env, host } = {}) {
258
285
  const open = (cfg) => openHeavy(dir, { cfg, env, ...(host ? { host } : {}) });
@@ -385,7 +412,7 @@ export function labelDockerArgs(name, args, env = {}) {
385
412
  * CLI body: `run --name <n> -- <real> args...`. Pass-through when FORGE_HEAVY_HELD is set or the step is llm; else
386
413
  * acquire, run with FORGE_HEAVY_HELD=1 and FORGE_HOST_PARALLELISM from live holders, release, propagate the exit.
387
414
  */
388
- export async function runWrapped(argv, { env: env0 = process.env, open = openHeavy, run = spawnInherit, host } = {}) {
415
+ export async function runWrapped(argv, { env: env0 = process.env, open = openHeavy, run = spawnInherit, host, remote = acquireRemote, read = cgroupRead } = {}) {
389
416
  let env = env0;
390
417
  const sep = argv.indexOf("--");
391
418
  if (argv[0] !== "run" || sep < 0 || !argv[sep + 1]) throw new Error("usage: heavy.mjs run --name <name> -- <command> [args...]");
@@ -398,12 +425,14 @@ export async function runWrapped(argv, { env: env0 = process.env, open = openHea
398
425
  cmd = g0.cmd; env = g0.env; args = labelDockerArgs(name, args, env);
399
426
  if (env.FORGE_HEAVY_HELD || env.FORGE_HEAVY_DISABLED === "1" || classifyStep(name, args) === "llm") return run(cmd, args, env);
400
427
  const hostP = host ?? defaultHost();
401
- const h = open(env.FORGEDOCK_SCHED_DIR || schedDir(env), { env, host: hostP });
402
428
  const priority = Number.isFinite(Number(env.FORGE_LANE_PRIORITY)) && String(env.FORGE_LANE_PRIORITY).trim() !== "" ? Number(env.FORGE_LANE_PRIORITY) : DEFAULT_PRIORITY;
403
429
  const phase = env.FORGE_LANE_PHASE || "step";
404
- const g = await acquireHeavy(h, { issue: Number(env.FORGE_LANE_ISSUE) || null, phase, priority, mb: c.step_mem_mb });
430
+ const useRemote = Boolean(env.CS_HEAVY_BASE); // #6047: the pool agent's token semaphore; fail-open, else the local file semaphore
431
+ const g = useRemote ? await remote({ base: env.CS_HEAVY_BASE, credToken: env.CS_CRED_TOKEN ?? "", maxWaitMs: c.max_wait_s * 1000 })
432
+ : await acquireHeavy(open(env.FORGEDOCK_SCHED_DIR || schedDir(env), { env, host: hostP }), { issue: Number(env.FORGE_LANE_ISSUE) || null, phase, priority, mb: c.step_mem_mb });
405
433
  if (env.FORGE_HEAVY_WAITS) { try { appendFileSync(env.FORGE_HEAVY_WAITS, JSON.stringify({ phase, name, waitMs: g.waitMs, queued: g.queued }) + "\n"); } catch { /* metrics are best effort */ } }
406
434
  let cores = 1; try { cores = hostP.cores() || 1; } catch { /* 1 */ }
435
+ cores = quotaCores({ cores, read, env }); // #6047: the container's CPU quota, never the VM
407
436
  const childEnv = { ...env, FORGE_HEAVY_HELD: "1",
408
437
  ...(env.FORGE_HEAVY_PARALLELISM_PINNED === "1" ? {} : { FORGE_HOST_PARALLELISM: String(hostParallelism({ cores, lanes: g.holders })) }) };
409
438
  // #5174: a gated step runs at nice 10 / ionice idle so local test runners and installs do not starve the schedd event loop.
@@ -6,12 +6,13 @@ import { spawnSync } from "node:child_process";
6
6
  import { writeFileSync, readFileSync, mkdirSync, chmodSync, existsSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import { tmpDir } from "../tests/_tmp.mjs";
9
- import { guardChain, isPassThroughWrapper, SHIM_LOOP_MAX, SHIM_DEPTH_MAX, classifyStep, heavyConfig, openHeavy, acquireHeavy, writeHeavyShims, heavyShimScript, sumWaits, runWrapped, HEAVY_BINS, isHeavyProcess } from "./heavy.mjs";
9
+ import { guardChain, isPassThroughWrapper, SHIM_LOOP_MAX, SHIM_DEPTH_MAX, classifyStep, heavyConfig, openHeavy, acquireHeavy, writeHeavyShims, heavyShimScript, sumWaits, runWrapped, acquireRemote, HEAVY_BINS, isHeavyProcess } from "./heavy.mjs";
10
10
  import { checkAdmission, ADMISSION_DEFAULTS, localLaneCap } from "./admission.mjs";
11
11
  import { formatAlertLines, formatWaitSummary } from "./orchestrate.mjs";
12
12
  import { readHeavy, readAdmission, liveLaneCap } from "../engine-cli.mjs";
13
13
  import { makeRampStore } from "./effects.mjs";
14
14
 
15
+ const noCgroup = () => { throw new Error("no cgroup"); }; // #6047: the test host's own CPU quota must not change expected worker counts
15
16
  // Injected pids, clock and host: `live` is the set of pids the registry sees as alive; `mem` the MemAvailable in MB.
16
17
  const world = ({ mem = 12000, cores = 4, swapFree = 0 } = {}) => {
17
18
  const live = new Set(), clock = { t: 1_000_000 }, h = { mem, cores, swapFree };
@@ -208,16 +209,16 @@ describe("heavy shims and the run wrapper (#4169)", () => {
208
209
  const open = (dir, o) => { w.live.add(process.pid); return openHeavy(dir, { ...o, alive: (p) => w.live.has(p) }); };
209
210
  const host = { memAvailableMb: () => 64000, cores: () => 8 };
210
211
  const run = async (cmd, args, e) => { calls.push({ cmd, args, held: e.FORGE_HEAVY_HELD, par: e.FORGE_HOST_PARALLELISM, holders: openHeavy(w.dir, { host }).stats().holders }); return { code: 3, signal: null }; };
211
- assert.deepEqual(await runWrapped(["run", "--name", "tsc", "--", "/r/tsc", "--noEmit"], { env, open, run, host }), { code: 3, signal: null });
212
+ assert.deepEqual(await runWrapped(["run", "--name", "tsc", "--", "/r/tsc", "--noEmit"], { env, open, run, host, read: noCgroup }), { code: 3, signal: null });
212
213
  assert.deepEqual(calls[0], { cmd: "/r/tsc", args: ["--noEmit"], held: "1", par: "8", holders: 1 });
213
214
  assert.equal(openHeavy(w.dir, { host }).stats().holders, 0, "released after the step");
214
215
  assert.deepEqual(sumWaits(readFileSync(waitsFile, "utf8")), { waits: { implement: JSON.parse(readFileSync(waitsFile, "utf8")).waitMs }, queueMax: 1 });
215
- await runWrapped(["run", "--name", "tsc", "--", "/r/tsc", "--version"], { env, open, run, host });
216
- await runWrapped(["run", "--name", "pnpm", "--", "/r/pnpm", "install"], { env: { ...env, FORGE_HEAVY_HELD: "1" }, open, run, host });
216
+ await runWrapped(["run", "--name", "tsc", "--", "/r/tsc", "--version"], { env, open, run, host, read: noCgroup });
217
+ await runWrapped(["run", "--name", "pnpm", "--", "/r/pnpm", "install"], { env: { ...env, FORGE_HEAVY_HELD: "1" }, open, run, host, read: noCgroup });
217
218
  assert.deepEqual(calls.slice(1).map((c) => [c.held, c.holders]), [[undefined, 0], ["1", 0]], "llm and nested calls take no slot");
218
- await runWrapped(["run", "--name", "tsc", "--", "/r/tsc"], { env: { ...env, FORGE_HOST_PARALLELISM: "2", FORGE_HEAVY_PARALLELISM_PINNED: "1" }, open, run, host });
219
+ await runWrapped(["run", "--name", "tsc", "--", "/r/tsc"], { env: { ...env, FORGE_HOST_PARALLELISM: "2", FORGE_HEAVY_PARALLELISM_PINNED: "1" }, open, run, host, read: noCgroup });
219
220
  assert.equal(calls.at(-1).par, "2", "an operator-set FORGE_HOST_PARALLELISM wins");
220
- await assert.rejects(runWrapped(["run", "--name", "x"], { env, open, run, host }), /usage/);
221
+ await assert.rejects(runWrapped(["run", "--name", "x"], { env, open, run, host, read: noCgroup }), /usage/);
221
222
  });
222
223
 
223
224
  it("sumWaits sums per phase and ignores bad lines; formatWaitSummary renders the batch-report line", () => {
@@ -488,3 +489,34 @@ describe("admission ramp (#5845)", () => {
488
489
  assert.equal(makeRampStore({ dir: join(tmpDir("ramp-"), "none", "x") }).rampingMb(60), null, "an unreadable stamp dir is unknown, not zero");
489
490
  });
490
491
  });
492
+
493
+ describe("remote token backend (#6047)", () => {
494
+ const resp = (status, body) => ({ status, json: async () => body });
495
+ const opts = (calls, replies) => ({ base: "http://h/sandboxes/l1/heavy", credToken: "tok", pollMs: 1, sleep: async () => {}, setTimer: () => ({ unref() {} }), clearTimer: () => {},
496
+ fetchFn: async (u, o) => { calls.push(u.split("/heavy/")[1]); const r = replies.shift(); if (r instanceof Error) throw r; return r ?? resp(200, { ok: true }); } });
497
+ it("grant: acquires, then release posts the token back", async () => {
498
+ const calls = [], g = await acquireRemote(opts(calls, [resp(200, { granted: true, token: "t1" })]));
499
+ assert.equal(g.token, "t1"); g.release(); g.release();
500
+ await new Promise((r) => setImmediate(r));
501
+ assert.deepEqual(calls, ["acquire", "release"]);
502
+ });
503
+ it("deny then poll until granted", async () => {
504
+ const calls = [], g = await acquireRemote(opts(calls, [resp(200, { granted: false, retry_after_s: 1 }), resp(200, { granted: false }), resp(200, { granted: true, token: "t2" })]));
505
+ assert.equal(g.token, "t2"); assert.equal(calls.filter((c) => c === "acquire").length, 3);
506
+ });
507
+ it("fails open when the agent is unreachable or errors", async () => {
508
+ assert.equal((await acquireRemote(opts([], [new Error("ECONNREFUSED")]))).failOpen, true);
509
+ assert.equal((await acquireRemote(opts([], [resp(500, {})]))).failOpen, true);
510
+ });
511
+ it("runWrapped uses the remote backend only when CS_HEAVY_BASE is set; otherwise the local file semaphore", async () => {
512
+ const ran = [], run = async (cmd, args, env) => { ran.push(env); return { code: 0, signal: null }; };
513
+ let remoteCalls = 0, localOpens = 0;
514
+ const remote = async () => { remoteCalls++; return { waitMs: 0, holders: 1, release() {} }; };
515
+ const dir = tmpDir("heavy-rw-"), host = { memAvailableMb: () => 12000, cores: () => 4 };
516
+ await runWrapped(["run", "--name", "pnpm", "--", "pnpm", "install"], { env: { CS_HEAVY_BASE: "http://h/x", FORGEDOCK_SCHED_DIR: dir }, run, remote, host, read: () => { throw new Error("none"); } });
517
+ assert.equal(remoteCalls, 1);
518
+ await runWrapped(["run", "--name", "pnpm", "--", "pnpm", "install"], { env: { FORGEDOCK_SCHED_DIR: dir }, run, remote, host, open: (d, o) => { localOpens++; return openHeavy(d, { ...o, host }); }, read: () => { throw new Error("none"); } });
519
+ assert.equal(remoteCalls, 1); assert.equal(localOpens, 1);
520
+ assert.equal(ran[0].FORGE_HEAVY_HELD, "1");
521
+ });
522
+ });
@@ -0,0 +1,54 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5917: a lane must not rewrite host-global tool config (`poetry config virtualenvs.create false` poisoned every later host
5
+ * `poetry install`). Every tool reads its user config from an env-named path, so the lane env points those at files under the
6
+ * per-run dir: any process the lane spawns writes there. Nothing is seeded from the host (a poisoned value would carry over);
7
+ * git's global file `[include]`s the host's so identity and credential helpers still apply while `--global` writes stay in the lane.
8
+ */
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { homedir } from "node:os";
12
+
13
+ export const HOSTCONFIG_DIR = "hostconfig";
14
+ export const ENV_POETRY_CREATE_FALSE = "env.host_poetry_config";
15
+
16
+ const realFs = { exists: existsSync, mkdir: (p) => mkdirSync(p, { recursive: true }), read: (p) => readFileSync(p, "utf8"), write: writeFileSync };
17
+
18
+ /** The env that redirects tool user-config into `<dir>/hostconfig`. Creates the dir and the git include file; {} without a dir. */
19
+ export function laneConfigEnv({ dir, hostHome = homedir(), env = process.env, fs = realFs } = {}) {
20
+ if (!dir) return {};
21
+ const root = join(dir, HOSTCONFIG_DIR), poetry = join(root, "poetry"), gitFile = join(root, "gitconfig");
22
+ const out = {
23
+ POETRY_CONFIG_DIR: poetry,
24
+ npm_config_userconfig: join(root, "npmrc"),
25
+ PIP_CONFIG_FILE: join(root, "pip.conf"),
26
+ UV_CONFIG_FILE: join(root, "uv.toml"),
27
+ GIT_CONFIG_GLOBAL: gitFile,
28
+ };
29
+ try {
30
+ fs.mkdir(poetry);
31
+ const host = env.GIT_CONFIG_GLOBAL || (hostHome ? join(hostHome, ".gitconfig") : "");
32
+ fs.write(gitFile, host && fs.exists(host) ? `[include]\n\tpath = ${host}\n` : "");
33
+ } catch { /* best effort: the vars still redirect writes into the lane dir */ }
34
+ return out;
35
+ }
36
+
37
+ /** Host poetry config with `virtualenvs.create = false`: every `poetry install` there skips the venv. Null when fine, missing or unreadable. */
38
+ export function hostPoetryConfigProblem({ env = process.env, home = homedir(), read = (p) => readFileSync(p, "utf8") } = {}) {
39
+ const base = env.POETRY_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(home, ".config"), "pypoetry");
40
+ const file = join(base, "config.toml");
41
+ let text;
42
+ try { text = read(file); } catch { return null; }
43
+ let section = "";
44
+ for (const raw of String(text).split("\n")) {
45
+ const line = raw.replace(/#.*$/, "").trim();
46
+ const sec = line.match(/^\[(.+)\]$/);
47
+ if (sec) { section = sec[1].trim(); continue; }
48
+ const kv = line.match(/^(?:"?virtualenvs"?\.)?"?create"?\s*=\s*(\S+)$/);
49
+ const full = line.match(/^virtualenvs\.create\s*=\s*(\S+)$/);
50
+ const v = full ? full[1] : kv && section === "virtualenvs" ? kv[1] : null;
51
+ if (v === "false") return { code: ENV_POETRY_CREATE_FALSE, detail: `${file} sets virtualenvs.create = false: every host \`poetry install\` skips the virtualenv and fails; run \`poetry config virtualenvs.create true\` (or remove the line)` };
52
+ }
53
+ return null;
54
+ }
@@ -0,0 +1,67 @@
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 { mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { spawnSync } from "node:child_process";
8
+ import { laneConfigEnv, hostPoetryConfigProblem } from "./hostconfig.mjs";
9
+ import { tmpDir } from "../tests/_tmp.mjs";
10
+
11
+ describe("laneConfigEnv (#5917)", () => {
12
+ it("points every tool config into the lane dir, not HOME; nothing without a dir", () => {
13
+ const dir = tmpDir("hc-dir-"), home = tmpDir("hc-home-");
14
+ const e = laneConfigEnv({ dir, hostHome: home, env: {} });
15
+ for (const k of ["POETRY_CONFIG_DIR", "npm_config_userconfig", "PIP_CONFIG_FILE", "UV_CONFIG_FILE", "GIT_CONFIG_GLOBAL"]) {
16
+ assert.ok(e[k].startsWith(join(dir, "hostconfig")), k);
17
+ assert.ok(!e[k].startsWith(home), k);
18
+ }
19
+ assert.deepEqual(laneConfigEnv({}), {});
20
+ });
21
+ it("a poetry-style writer honouring POETRY_CONFIG_DIR leaves the host config.toml byte-identical (R5)", () => {
22
+ const dir = tmpDir("hc-dir-"), home = tmpDir("hc-home-");
23
+ const hostCfg = join(home, ".config", "pypoetry"); mkdirSync(hostCfg, { recursive: true });
24
+ writeFileSync(join(hostCfg, "config.toml"), "[virtualenvs]\ncreate = true\n");
25
+ const before = readFileSync(join(hostCfg, "config.toml"));
26
+ const e = laneConfigEnv({ dir, hostHome: home, env: {} });
27
+ const r = spawnSync(process.execPath, ["-e", `const fs=require("fs"),p=require("path");const d=process.env.POETRY_CONFIG_DIR||p.join(process.env.HOME,".config/pypoetry");fs.mkdirSync(d,{recursive:true});fs.writeFileSync(p.join(d,"config.toml"),"[virtualenvs]\\ncreate = false\\n")`], { env: { ...process.env, HOME: home, ...e } });
28
+ assert.equal(r.status, 0);
29
+ assert.ok(readFileSync(join(hostCfg, "config.toml")).equals(before));
30
+ assert.match(readFileSync(join(e.POETRY_CONFIG_DIR, "config.toml"), "utf8"), /create = false/);
31
+ });
32
+ it("git config --global writes the lane file, leaves ~/.gitconfig alone, still reads its user.name", () => {
33
+ const dir = tmpDir("hc-dir-"), home = tmpDir("hc-home-");
34
+ writeFileSync(join(home, ".gitconfig"), "[user]\n\tname = Host Person\n");
35
+ const before = readFileSync(join(home, ".gitconfig"));
36
+ const e = laneConfigEnv({ dir, hostHome: home, env: {} });
37
+ const env = { ...process.env, HOME: home, ...e }, g = (...a) => spawnSync("git", a, { env, encoding: "utf8" });
38
+ assert.equal(g("config", "--global", "core.foo", "bar").status, 0);
39
+ assert.ok(readFileSync(join(home, ".gitconfig")).equals(before));
40
+ assert.equal(g("config", "user.name").stdout.trim(), "Host Person");
41
+ assert.equal(g("config", "--global", "--get", "core.foo").stdout.trim(), "bar");
42
+ });
43
+ it("no host gitconfig: an empty lane file", () => {
44
+ const dir = tmpDir("hc-dir-");
45
+ const e = laneConfigEnv({ dir, hostHome: tmpDir("hc-home-"), env: {} });
46
+ assert.equal(readFileSync(e.GIT_CONFIG_GLOBAL, "utf8"), "");
47
+ });
48
+ });
49
+
50
+ describe("hostPoetryConfigProblem (#5917)", () => {
51
+ const home = (toml) => { const h = tmpDir("hc-home-"); if (toml != null) { mkdirSync(join(h, ".config", "pypoetry"), { recursive: true }); writeFileSync(join(h, ".config", "pypoetry", "config.toml"), toml); } return h; };
52
+ const run = (toml, env = {}) => hostPoetryConfigProblem({ env, home: home(toml) });
53
+ it("flags virtualenvs.create=false (table and dotted forms)", () => {
54
+ assert.match(run("[virtualenvs]\ncreate = false\n").detail, /virtualenvs\.create = false/);
55
+ assert.ok(run("virtualenvs.create = false\n"));
56
+ });
57
+ it("passes create=true, other tables' create, and a missing file", () => {
58
+ assert.equal(run("[virtualenvs]\ncreate = true\n"), null);
59
+ assert.equal(run("[other]\ncreate = false\n"), null);
60
+ assert.equal(run(null), null);
61
+ });
62
+ it("honours POETRY_CONFIG_DIR", () => {
63
+ const d = tmpDir("hc-pcd-"); writeFileSync(join(d, "config.toml"), "[virtualenvs]\ncreate = false\n");
64
+ assert.ok(run(null, { POETRY_CONFIG_DIR: d }));
65
+ assert.ok(!existsSync(join(d, "nope")));
66
+ });
67
+ });
@@ -35,39 +35,3 @@ export async function acquireHotArea({ gitCommonDir, areas = [], owner, waitMs =
35
35
  }
36
36
  return { ok: true, release, areas: [...new Set(areas)].sort() };
37
37
  }
38
-
39
- /**
40
- * Each counter's match count at `ref` (git grep -c -E; no checkout). `git(args)` returns stdout and throws on a non-zero
41
- * exit: git grep exits 1 on no match, so a throw counts as 0.
42
- * @returns {Promise<Record<string, number>>}
43
- */
44
- export async function countCounters({ git, ref = "HEAD", counters = [] }) {
45
- const out = {};
46
- for (const c of counters ?? []) {
47
- let n = 0;
48
- try {
49
- const txt = String(await git(["grep", "-c", "-E", "-e", c.pattern, ref, "--", ...(c.paths?.length ? c.paths : ["."])]));
50
- for (const line of txt.split("\n")) { const m = /:(\d+)\s*$/.exec(line); if (m) n += Number(m[1]); }
51
- } catch { n = 0; }
52
- out[c.name] = n;
53
- }
54
- return out;
55
- }
56
-
57
- const okRe = (name) => new RegExp(`counter-ok:\\s*${String(name).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s+\\S`, "i");
58
- /** True when the contract decisions (or a result decision amendment) carry `counter-ok: <name> <reason>`. */
59
- export function counterExempt(name, contract, result = null) {
60
- const re = okRe(name);
61
- const texts = [...(contract?.decisions ?? []).flatMap((d) => [d?.choice, d?.justification, d?.why]),
62
- ...(Array.isArray(result?.amendments) ? result.amendments : []).filter((a) => a?.kind === "decision").flatMap((a) => [a?.decision?.choice, a?.why])];
63
- return texts.some((t) => typeof t === "string" && re.test(t));
64
- }
65
-
66
- /** Failures for every counter that grew from `before` to `after` without an explicit decision. */
67
- export function counterGrowth({ before = null, after = null, contract = null, result = null } = {}) {
68
- if (!before || !after) return [];
69
- return Object.keys(after)
70
- .filter((name) => Number.isFinite(before[name]) && Number(after[name]) > Number(before[name]) && !counterExempt(name, contract, result))
71
- .map((name) => ({ code: C.MAINTENANCE_COUNTER_GROWTH, kind: "counter_growth",
72
- detail: `counter ${name} grew from ${before[name]} to ${after[name]} without a contract decision "counter-ok: ${name} <reason>"` }));
73
- }
@@ -4,7 +4,7 @@ import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
5
  import { existsSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";
6
6
  import { join } from "node:path";
7
- import { areaOf, acquireHotArea, countCounters, counterGrowth, counterExempt } from "./hotarea.mjs";
7
+ import { areaOf, acquireHotArea } from "./hotarea.mjs";
8
8
  import { LOCK_DIR } from "./branchlock.mjs";
9
9
  import { tmpDir } from "../tests/_tmp.mjs";
10
10
 
@@ -50,24 +50,3 @@ describe("hot areas (#5751)", () => {
50
50
  });
51
51
  });
52
52
 
53
- describe("named counters (#5751)", () => {
54
- it("countCounters sums git grep -c at a ref; no match counts 0", async () => {
55
- const calls = [];
56
- const git = async (a) => { calls.push(a); if (a.includes("NONE")) throw new Error("exit 1"); return "origin/main:src/a.js:3\norigin/main:src/b.js:2\n"; };
57
- const c = await countCounters({ git, ref: "origin/main", counters: [{ name: "flags", pattern: "FLAG_", paths: ["src/**"] }, { name: "none", pattern: "NONE", paths: [] }] });
58
- assert.deepEqual(c, { flags: 5, none: 0 });
59
- assert.deepEqual(calls[0], ["grep", "-c", "-E", "-e", "FLAG_", "origin/main", "--", "src/**"]);
60
- assert.deepEqual(calls[1].slice(-2), ["--", "."]);
61
- });
62
- it("growth fails without a decision and passes with a counter-ok decision", () => {
63
- const f = counterGrowth({ before: { flags: 5 }, after: { flags: 6 }, contract: { decisions: [] } });
64
- assert.equal(f.length, 1);
65
- assert.equal(f[0].code, "maintenance.counter_growth");
66
- assert.equal(counterGrowth({ before: { flags: 5 }, after: { flags: 6 }, contract: { decisions: [{ choice: "counter-ok: flags one rollout flag, removed in #9" }] } }).length, 0);
67
- assert.equal(counterGrowth({ before: { flags: 5 }, after: { flags: 6 }, result: { amendments: [{ kind: "decision", decision: { choice: "counter-ok: flags needed" }, why: "x" }] } }).length, 0);
68
- assert.equal(counterExempt("flags", { decisions: [{ choice: "counter-ok: flags" }] }), false, "a reason is required");
69
- assert.equal(counterExempt("flags", { decisions: [{ choice: "counter-ok: flagsx because" }] }), false, "another counter's decision does not exempt");
70
- assert.equal(counterGrowth({ before: { flags: 5 }, after: { flags: 5 } }).length, 0);
71
- assert.equal(counterGrowth({ before: null, after: { flags: 9 } }).length, 0);
72
- });
73
- });
@@ -7,7 +7,7 @@
7
7
  * `CONFORMS`, shadow `would PASS`, or a `review.trigger` skip; an enforced NONCONFORMING/BLOCK/FAIL fails; a shadow
8
8
  * `would BLOCK` is advisory, as its label says: the lane merges by design, so it is recorded in the evidence, not reopened); every required check of the
9
9
  * lane is green on the merged head; the merge commit is on the lane; no check on the merge commit failed
10
- * (`forgedock/verify` is report-only; a `cancelled`/`stale` check, superseded by a newer run, is resolved against the newest
10
+ * (a check also red on the first parent is base-red, noted and not blamed on the PR; `forgedock/verify` is report-only; a `cancelled`/`stale` check, superseded by a newer run, is resolved against the newest
11
11
  * descendant run of the same check on the lane). A failure reopens the issue with `needs-human` and the evidence; nothing is
12
12
  * reverted, a human decides. No LLM calls.
13
13
  */
@@ -95,7 +95,10 @@ export async function verifyMerge({ gh, repo, lane, issue, comments, requiredChe
95
95
  ev.push(`PR #${pr.number} merged into ${pr.baseRefName} at ${sha.slice(0, 12) || "?"}`);
96
96
  if (pr.baseRefName !== lane) return fail(`PR #${pr.number} targets ${pr.baseRefName}, not ${lane}`, { pr: pr.number });
97
97
  if (labelNames(pr).has("review-degraded")) return fail(`PR #${pr.number} merged with an incomplete review (review-degraded)`, { pr: pr.number });
98
- const verdict = reviewVerdict(comments);
98
+ let verdict = reviewVerdict(comments);
99
+ if (verdict === null) { // no trusted issue-level record: the PR's own review record (FORGE:REVIEW incl. the trigger-skip note), best effort
100
+ try { verdict = reviewVerdict(JSON.parse(String(await gh(["pr", "view", String(pr.number), "-R", repo, "--json", "comments"])) || "{}").comments ?? []); } catch { verdict = null; }
101
+ }
99
102
  if (verdict !== "pass" && verdict !== "shadow-block") return fail(verdict === "block" ? "the latest FORGE:REVIEW did not pass (enforced NONCONFORMING)" : "no trusted FORGE:REVIEW on the issue", { pr: pr.number });
100
103
  ev.push(verdict === "pass" ? "FORGE:REVIEW passed" : "FORGE:REVIEW shadow `would BLOCK` (advisory: shadow mode does not enforce; see the review comment)");
101
104
  let required = [];
@@ -122,13 +125,25 @@ export async function verifyMerge({ gh, repo, lane, issue, comments, requiredChe
122
125
  ev.push(`merge commit is on ${lane}`);
123
126
  const post = (await checkStates({ gh, repo, sha })).filter((x) => !REPORT_ONLY_CHECKS.has(x.name));
124
127
  const red = post.filter((x) => !OK_STATES.has(x.state) && x.state !== "pending" && !SUPERSEDED_STATES.has(x.state));
125
- if (red.length) return fail(`${lane} CI red on the merge commit: ${red.map((x) => `${x.name}=${x.state}`).join(", ")}`, { pr: pr.number, sha });
128
+ const baseRed = [];
129
+ if (red.length) { // red on the merge commit counts against the PR only when it was green or absent on the first parent
130
+ let parent = "";
131
+ try { parent = String(await gh(["api", `repos/${repo}/commits/${sha}`, "--jq", ".parents[0].sha"])).trim(); } catch { parent = ""; }
132
+ const before = parent ? await checkStates({ gh, repo, sha: parent }) : [];
133
+ for (const x of red) {
134
+ const b = before.find((c) => c.name === x.name);
135
+ if (b && !OK_STATES.has(b.state) && b.state !== "pending" && !SUPERSEDED_STATES.has(b.state)) baseRed.push(`${x.name}=${x.state} (also ${b.state} on the first parent ${parent.slice(0, 12)})`);
136
+ }
137
+ const own = red.filter((x) => !baseRed.some((l) => l.startsWith(`${x.name}=`)));
138
+ if (own.length) return fail(`${lane} CI red on the merge commit: ${own.map((x) => `${x.name}=${x.state}`).join(", ")}`, { pr: pr.number, sha });
139
+ ev.push(`base-red, not blamed on the PR: ${baseRed.join(", ")}`);
140
+ }
126
141
  const sup = await resolveSuperseded({ gh, repo, lane, sha, names: post.filter((x) => SUPERSEDED_STATES.has(x.state)).map((x) => x.name) });
127
142
  if (sup.red.length) return fail(`${lane} CI red: a cancelled check on the merge commit was superseded by a failing run: ${sup.red.join(", ")}`, { pr: pr.number, sha });
128
143
  ev.push(...sup.green);
129
144
  const pending = [...post.filter((x) => x.state === "pending"), ...sup.pending.map((name) => ({ name }))];
130
145
  if (pending.length) return { status: "pending", evidence: [...ev, `${lane} CI pending: ${pending.map((x) => x.name).join(", ")}`], pr: pr.number, sha };
131
- ev.push(post.length ? `${lane} CI green on the merge commit (${post.length} check(s))` : "no CI ran on the merge commit");
146
+ ev.push(baseRed.length ? `${lane} CI otherwise green on the merge commit (${post.length - baseRed.length} check(s))` : post.length ? `${lane} CI green on the merge commit (${post.length} check(s))` : "no CI ran on the merge commit");
132
147
  return { status: "verified", evidence: ev, pr: pr.number, sha };
133
148
  }
134
149
 
@@ -29,6 +29,7 @@ import { APP_SLUG } from "../init-repo.mjs";
29
29
  import { noComments } from "./render.mjs";
30
30
  import { listAssociations } from "./gh-assoc.mjs";
31
31
  import { verifyMerge, verifyComment } from "./issuewatch-verify.mjs";
32
+ import { percentile } from "./efficiency.mjs";
32
33
  import { DEFAULT_SKIP_LABELS, isPullRequest, searchesPullRequests, skipLabelHit, closingPrIssues, releaseInFlight, watchLiveness, alertDeadWatches, resolveOnPath } from "./issuewatch-parity.mjs";
33
34
 
34
35
  const WATCH_KEYS = ["milestone", "labels", "exclude_labels", "search", "title_regex", "since", "version", "lane", "max_issues", "max_inflight", "until", "mode", "parallel", "include_followups", "postdeploy_rollup", "threshold", "immediate", "max_release_issues", "theme_map", "tracker", "sweep_needs_human", "max_launches", "trust_app", "trust_app_labels", "skip_labels", "release_pause", "max_remediations", "triage.max_per_hour", "triage"];
@@ -39,7 +40,16 @@ const readFile = (f) => readFileSync(f, "utf8");
39
40
  const JUDGE_TIMEOUT_MS = 120_000; // a hung `claude --print` must not stall the watch round
40
41
  const CLAUDE_MAX_BUFFER = 8 * 1024 * 1024;
41
42
  const PENDING_START_MS = 10 * 60000; // #5425: how long a slow `orchestrate` start may take to create its batch before the claims are released
42
- const VERIFY_WAIT_MS = 60 * 60000; // how long a merge commit's CI may stay pending before verification fails
43
+ const VERIFY_WAIT_MS = 60 * 60000; // floor and fallback of how long a merge commit's CI may stay pending before verification fails
44
+ const VERIFY_WAIT_CAP_MS = 6 * 60 * 60000;
45
+ const VERIFY_WAIT_FACTOR = 3; // window = p90 of recent CI run minutes x this
46
+
47
+ /** Verify window (ms) from recent CI run durations in minutes: p90 x 3, floored at 60 min, capped at 6 h; no history = 60 min. */
48
+ export function verifyWindowMs(minutes) {
49
+ const sorted = (Array.isArray(minutes) ? minutes : []).map(Number).filter((m) => Number.isFinite(m) && m > 0).sort((a, b) => a - b);
50
+ const p90 = percentile(sorted, 0.9);
51
+ return p90 === null ? VERIFY_WAIT_MS : Math.min(VERIFY_WAIT_CAP_MS, Math.max(VERIFY_WAIT_MS, Math.round(p90 * VERIFY_WAIT_FACTOR * 60000)));
52
+ }
43
53
  const readJson = (f) => { try { return JSON.parse(readFileSync(f, "utf8")); } catch { return null; } };
44
54
 
45
55
  // ── config ───────────────────────────────────────────────────────────────────────────────────────────────────
@@ -288,15 +298,18 @@ export function claimIssue(rdir, issue, name) {
288
298
  } finally { rmdirSync(lock); }
289
299
  }
290
300
 
291
- /** Verify closed issue `n` (see tick); a pending result waits up to VERIFY_WAIT_MS from the first attempt. */
301
+ /** Verify closed issue `n` (see tick); a pending result waits up to the CI-derived window (verifyWindowMs) from the first attempt. */
292
302
  async function verifyClosed({ n, repo, io, state, now, lane }) {
293
303
  const comments = JSON.parse(String(await io.gh(["issue", "view", String(n), "-R", repo, "--json", "comments"]))).comments ?? [];
294
304
  let r = await verifyMerge({ gh: io.gh, repo, lane, issue: n, comments, ...(io.requiredChecks ? { requiredChecks: io.requiredChecks } : {}) });
295
305
  state.verifyFrom = { ...(state.verifyFrom ?? {}) };
296
306
  state.verifyFrom[n] ??= now;
297
307
  if (r.status === "pending") {
298
- if (now - state.verifyFrom[n] < VERIFY_WAIT_MS) return;
299
- r = { ...r, status: "failed", evidence: [...r.evidence, `FAIL: still unverified after ${VERIFY_WAIT_MS / 60000} min`] };
308
+ let minutes = null;
309
+ try { minutes = (await io.ciDurations?.(repo, lane)) ?? null; } catch { minutes = null; } // best effort: unreadable = the 60 min floor
310
+ const wait = verifyWindowMs(minutes);
311
+ if (now - state.verifyFrom[n] < wait) return;
312
+ r = { ...r, status: "failed", evidence: [...r.evidence, `FAIL: still unverified after ${Math.round(wait / 60000)} min${wait === VERIFY_WAIT_MS ? "" : " (window from recent CI run p90)"}`] };
300
313
  }
301
314
  // Side effects first, state last: a failed gh call throws with the issue still closed and in pendingVerify, so the next tick
302
315
  // resumes (state.escalation records the finished steps). Reopen is last because only closed issues are revisited.
@@ -631,6 +644,10 @@ function realIo(repo, env = process.env) {
631
644
  const gh = ghRunner(execFileSync, (l) => console.error(l));
632
645
  const root = batchRoot(env), findNew = (before) => listBatches(root).find((b) => !before.includes(b)) ?? null;
633
646
  return { env, gh, now: () => Date.now(), sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
647
+ ciDurations: async (r, lane) => { // minutes of the lane's recent completed Actions runs, for the verify window
648
+ const out = String(await gh(["api", `repos/${r}/actions/runs?per_page=100&status=completed&branch=${encodeURIComponent(lane)}`, "--jq", ".workflow_runs[] | [.run_started_at // .created_at, .updated_at] | @tsv"]));
649
+ return out.split("\n").filter(Boolean).map((l) => { const [a, b] = l.split("\t"); return (Date.parse(b) - Date.parse(a)) / 60000; }).filter((m) => m > 0);
650
+ },
634
651
  classify: (issues, themes) => { // the one LLM judgment of release mode: issues no theme_map rule classifies
635
652
  const prompt = `Classify each GitHub issue into exactly one theme of [${themes.join(", ")}], or "general" when none fits. Reply with only a JSON object {"<number>": "<theme>"}.\n\n${issues.map((i) => `#${i.number} ${i.title}\n${String(i.body ?? "").slice(0, 600)}`).join("\n---\n")}`;
636
653
  return JSON.parse(/\{[\s\S]*\}/.exec(execFileSync("claude", ["--print"], { input: prompt, encoding: "utf8", maxBuffer: 8 * 1024 * 1024 }))[0]);
@@ -22,17 +22,21 @@ const REVIEW_PASS = { author: { login: "rapiercraft-forgedock" }, authorAssociat
22
22
  * issue has a merged `feat/issue-N-lean` PR into staging with a passing review and green CI unless `prs[n]` / `comments[n]` /
23
23
  * `checks[sha]` / `compare` say otherwise.
24
24
  */
25
- function fakeIo(env, issues, { closed = new Set(), exit = () => 0, bodies = {}, prs = {}, comments = {}, checks = {}, compare = "behind", descendants = {}, failGh = () => false } = {}) {
25
+ function fakeIo(env, issues, { closed = new Set(), exit = () => 0, bodies = {}, prs = {}, comments = {}, prComments = {}, parents = {}, ciDurations = null, checks = {}, compare = "behind", descendants = {}, failGh = () => false } = {}) {
26
26
  const calls = [], launched = [], batchOps = [];
27
27
  let clock = Date.parse("2026-10-30T00:00:00Z"), nb = 0;
28
28
  const io = { env: { FORGEDOCK_WATCH_DIR: env }, calls, launched, batchOps, closed, bodies, prs, comments, checks, tickClock: (ms) => { clock += ms; }, now: () => clock, sleep: async () => {},
29
29
  requiredChecks: async () => [],
30
+ ...(ciDurations ? { ciDurations: async () => ciDurations } : {}),
30
31
  gh: async (a) => {
31
32
  calls.push(a);
32
33
  if (failGh(a)) throw new Error("gh transient");
33
34
  const desc = a[0] === "api" && /\/compare\/([0-9a-f]+)\.\.\.staging/.exec(a[1]); // descendants of a commit, oldest first
34
35
  if (desc) return (descendants[desc[1]] ?? []).join("\n");
35
36
  if (a[0] === "api" && /\/compare\//.test(a[1])) return compare;
37
+ const par = a[0] === "api" && /\/commits\/([0-9a-f]+)$/.exec(a[1]);
38
+ if (par) return parents[par[1]] ?? "";
39
+ if (a[0] === "pr" && a[1] === "view" && a.includes("comments")) return JSON.stringify({ comments: prComments[a[2]] ?? [] });
36
40
  if (a[0] === "api" && /\/commits\/([0-9a-f]+)\/check-runs/.test(a.join(" "))) { const sha = /commits\/([0-9a-f]+)/.exec(a.join(" "))[1]; return (checks[sha] ?? []).map(([n, st, c], i) => `${i + 1}\t${n}\t${st}\t${c ?? ""}`).join("\n"); }
37
41
  if (a[0] === "api" && /\/commits\/[0-9a-f]+\/status/.test(a[1])) return "";
38
42
  if (a[0] === "api") return issues.filter((i) => !closed.has(i.number)).map((i) => `${i.number}\t${i.authorAssociation}`).join("\n"); // #4859: REST association list
@@ -400,6 +404,49 @@ test("verify: a review comment from an untrusted author does not count", async (
400
404
  assert.match(r.posted[0], /no trusted FORGE:REVIEW/);
401
405
  });
402
406
 
407
+ test("verify: base-red check red on first parent and merge commit verifies with base-red evidence", async () => {
408
+ const r = await settleOne({ parents: { bb1: "ee1" }, checks: { bb1: [["lint", "completed", "failure"], ["test", "completed", "success"]], ee1: [["lint", "completed", "failure"]] } });
409
+ assert.deepEqual(r.state.verified, [1]);
410
+ assert.equal(r.reopened || r.escalated, false);
411
+ assert.match(r.posted[0], /merge verified[\s\S]*base-red, not blamed on the PR: lint=failure \(also failure on the first parent ee1\)/);
412
+ });
413
+
414
+ test("verify: red on the merge commit but green, absent or unreadable on the first parent still fails", async () => {
415
+ for (const opts of [
416
+ { parents: { bb1: "ee1" }, checks: { bb1: [["lint", "completed", "failure"]], ee1: [["lint", "completed", "success"]] } },
417
+ { parents: { bb1: "ee1" }, checks: { bb1: [["lint", "completed", "failure"]], ee1: [["other", "completed", "failure"]] } },
418
+ { checks: { bb1: [["lint", "completed", "failure"]] } },
419
+ ]) {
420
+ const r = await settleOne(opts);
421
+ assert.deepEqual(r.state.unverified, [1]);
422
+ assert.ok(r.reopened && r.escalated);
423
+ assert.match(r.posted[0], /staging CI red on the merge commit: lint=failure/);
424
+ }
425
+ });
426
+
427
+ test("verify: no issue FORGE:REVIEW but the PR carries the trigger-skip record verifies; an enforced block there still fails", async () => {
428
+ const skip = { ...REVIEW_PASS, body: "<!-- FORGE:REVIEW -->\n## Conformance Review\n**Skipped by `review.trigger: enforce`:** no risk path." };
429
+ const ok = await settleOne({ comments: { 1: [] }, prComments: { 1001: [skip] } });
430
+ assert.deepEqual(ok.state.verified, [1]);
431
+ assert.equal(ok.reopened, false);
432
+ const bad = await settleOne({ comments: { 1: [] }, prComments: { 1001: [{ ...REVIEW_PASS, body: "<!-- FORGE:REVIEW -->\n**Verdict:** NONCONFORMING" }] } });
433
+ assert.deepEqual(bad.state.unverified, [1]);
434
+ assert.match(bad.posted[0], /did not pass/);
435
+ });
436
+
437
+ test("verify: a slow-but-green run verifies inside the CI-derived window; without history the 60 min fail stays", async () => {
438
+ const r = await settleOne({ checks: { bb1: [["test", "in_progress"]] }, ciDurations: Array(10).fill(40) }, { ticks: 2, gap: 90 * 60000 });
439
+ assert.deepEqual(r.state.pendingVerify, [1]); // 90 min > 60 but < p90 40 x 3 = 120
440
+ r.io.checks.bb1 = [["test", "completed", "success"]];
441
+ await tick({ watch: W({ max_issues: "1" }), repo: "o/r", io: r.io, state: r.state, handles: new Map() });
442
+ assert.deepEqual(r.state.verified, [1]);
443
+ const none = await settleOne({ checks: { bb1: [["test", "in_progress"]] } }, { ticks: 3, gap: 30 * 60000 });
444
+ assert.deepEqual(none.state.unverified, [1]);
445
+ const late = await settleOne({ checks: { bb1: [["test", "in_progress"]] }, ciDurations: Array(10).fill(40) }, { ticks: 3, gap: 60 * 60000 });
446
+ assert.deepEqual(late.state.unverified, [1]);
447
+ assert.match(late.posted.at(-1), /still unverified after 120 min \(window from recent CI run p90\)/);
448
+ });
449
+
403
450
  test("verify: review-degraded, wrong base, missing required check, merge commit off the lane, red lane CI each fail", async () => {
404
451
  const pr = (o) => ({ 1: [{ number: 1001, baseRefName: "staging", headRefOid: "aa1", mergeCommit: { oid: "bb1" }, labels: [], ...o }] });
405
452
  const cases = [
@@ -0,0 +1,66 @@
1
+ // Gap audit of an active pipeline/env/pool failure (#6078): opt-in (forge.yaml orchestrate.lane_audit.file_gaps, default off) engine-gap issue per signature with a count and the affected lanes.
2
+ export const GAP_CLASSES = Object.freeze(["pipeline", "env", "pool"]);
3
+ export const DEFAULT_GAP = Object.freeze({ fileGaps: false, repo: "RapierCraftStudios/ForgeDock", label: "engine-gap" });
4
+
5
+ /** forge.yaml (parsed) -> gap config; the parser may nest (`orchestrate.lane_audit.x`) or flatten. Only the string "true" enables. */
6
+ export function parseGapConfig(yaml) {
7
+ const o = yaml?.orchestrate && typeof yaml.orchestrate === "object" ? yaml.orchestrate : {};
8
+ const s = { ...o, ...(o.lane_audit && typeof o.lane_audit === "object" ? o.lane_audit : {}) };
9
+ const out = { ...DEFAULT_GAP };
10
+ const f = s.file_gaps ?? s.lane_audit_file_gaps;
11
+ out.fileGaps = f !== undefined && String(f).trim().toLowerCase() === "true";
12
+ const repo = String(s.repo ?? s.lane_audit_repo ?? "").trim();
13
+ if (/^[\w.-]+\/[\w.-]+$/.test(repo)) out.repo = repo;
14
+ const label = String(s.label ?? s.lane_audit_label ?? "").trim();
15
+ if (/^[\w. :-]+$/.test(label)) out.label = label;
16
+ return out;
17
+ }
18
+
19
+ const esc = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
20
+
21
+ /** Strip what must not reach the engine repo (#6020): the lane's own repo, any owner/name, absolute paths. */
22
+ export function redactGap(text, { repo = "" } = {}) {
23
+ let t = String(text ?? "");
24
+ const [, name] = String(repo).split("/");
25
+ if (repo) t = t.replace(new RegExp(esc(repo), "gi"), "<repo>");
26
+ if (name && name.length > 2) t = t.replace(new RegExp(`(?<![\\w.-])${esc(name)}(?![\\w.-])`, "gi"), "<repo>");
27
+ t = t.replace(/(?:[A-Za-z]:\\|~\/|\/)[\w.@+~-]+(?:[\\/][\w.@+~ -]*)+/g, "<path>");
28
+ t = t.replace(/(?<![\w.-])[\w.-]+\/[\w.-]+(?![\w.-])/g, "<repo>");
29
+ return t;
30
+ }
31
+
32
+ const lanesOf = (body) => [...new Set([...(/Affected lanes:\s*([^\n]*)/.exec(body)?.[1] ?? "").matchAll(/#(\d+)/g)].map((m) => Number(m[1])))];
33
+ const render = ({ sig, c, count, lanes, version, repo }) => `<!-- forge-gap: ${sig} -->\n**Engine gap** \`${sig}\`\n\n- Class: ${redactGap(c.class, { repo })}\n- Owner: ${redactGap(c.owner ?? "-", { repo })}\n- Action: ${redactGap(c.action ?? "-", { repo })}\n- Engine version: ${redactGap(version ?? "-", { repo })}\n- Occurrences: ${count}\n- Affected lanes: ${lanes.map((n) => `#${n}`).join(", ")}\n`;
34
+
35
+ /**
36
+ * Build the gap seam for runLaneAudit: async (bundle, classified) -> {issue, count, action} | null. Never throws.
37
+ * @param {{gh: Function, cfg?: object, repo?: string}} o
38
+ */
39
+ export function makeGapAuditor({ gh, cfg = DEFAULT_GAP, repo = "" } = {}) {
40
+ return async (bundle, classified = null) => {
41
+ try {
42
+ const c = classified;
43
+ if (!cfg?.fileGaps || typeof gh !== "function" || !c || !c.active || c.fixed_in_later || !GAP_CLASSES.includes(c.class) || !c.signature) return null;
44
+ const sig = String(c.signature), marker = `<!-- forge-gap: ${sig} -->`, lane = Number(bundle?.issue);
45
+ if (!Number.isSafeInteger(lane)) return null;
46
+ const version = bundle?.stamp?.engine_version ?? null;
47
+ const list = JSON.parse(String(await gh(["issue", "list", "--repo", cfg.repo, "--label", cfg.label, "--state", "open", "--search", `"${sig}" in:body`, "--json", "number,body"])) || "[]");
48
+ const found = list.find((i) => String(i.body ?? "").includes(marker));
49
+ if (found) {
50
+ const lanes = lanesOf(String(found.body));
51
+ if (lanes.includes(lane)) return { issue: found.number, count: lanes.length, action: "unchanged" };
52
+ lanes.push(lane);
53
+ await gh(["issue", "edit", String(found.number), "--repo", cfg.repo, "--body", render({ sig, c, count: lanes.length, lanes, version, repo })]);
54
+ return { issue: found.number, count: lanes.length, action: "update" };
55
+ }
56
+ const out = String(await gh(["issue", "create", "--repo", cfg.repo, "--label", cfg.label, "--title", `engine-gap: ${redactGap(sig, { repo })} (${c.class})`, "--body", render({ sig, c, count: 1, lanes: [lane], version, repo })]));
57
+ const n = Number(out.match(/(\d+)\s*$/)?.[1]);
58
+ return Number.isSafeInteger(n) ? { issue: n, count: 1, action: "create" } : null;
59
+ } catch { return null; }
60
+ };
61
+ }
62
+
63
+ /** Default seam: no gap finding. @param {object} bundle the evidence bundle of lane-audit.mjs @param {object} [classified] the signature match, when any */
64
+ export async function auditGap(bundle, classified = null) { // eslint-disable-line no-unused-vars
65
+ return null;
66
+ }