forgedock 1.67.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 (140) 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 +99 -12
  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 +25 -10
  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.test.mjs +51 -2
  17. package/bin/lean/ci-gate.mjs +2 -90
  18. package/bin/lean/ci-gate.test.mjs +1 -127
  19. package/bin/lean/ci-precheck.mjs +25 -8
  20. package/bin/lean/ci-precheck.test.mjs +24 -0
  21. package/bin/lean/clear-breaker.test.mjs +4 -3
  22. package/bin/lean/commentstate.mjs +10 -5
  23. package/bin/lean/commentstate.test.mjs +12 -1
  24. package/bin/lean/conformance.e2e.test.mjs +9 -6
  25. package/bin/lean/conformance.mjs +56 -196
  26. package/bin/lean/conformance.test.mjs +40 -376
  27. package/bin/lean/depcache.mjs +100 -10
  28. package/bin/lean/depcache.test.mjs +105 -0
  29. package/bin/lean/docsgate.mjs +0 -32
  30. package/bin/lean/docsgate.test.mjs +2 -23
  31. package/bin/lean/effects-cap.test.mjs +9 -1
  32. package/bin/lean/effects-killtree.test.mjs +35 -0
  33. package/bin/lean/effects.mjs +42 -24
  34. package/bin/lean/engine-readmit.test.mjs +35 -0
  35. package/bin/lean/envgap.mjs +93 -0
  36. package/bin/lean/envgap.test.mjs +53 -0
  37. package/bin/lean/execution.mjs +10 -4
  38. package/bin/lean/execution.test.mjs +12 -0
  39. package/bin/lean/failure-census.mjs +170 -0
  40. package/bin/lean/failure-census.test.mjs +59 -0
  41. package/bin/lean/guardgate.test.mjs +2 -3
  42. package/bin/lean/heavy.mjs +33 -4
  43. package/bin/lean/heavy.test.mjs +38 -6
  44. package/bin/lean/hotarea.mjs +0 -36
  45. package/bin/lean/hotarea.test.mjs +1 -22
  46. package/bin/lean/issuewatch-verify.mjs +19 -4
  47. package/bin/lean/issuewatch.mjs +21 -4
  48. package/bin/lean/issuewatch.test.mjs +48 -1
  49. package/bin/lean/lane-audit-gap.mjs +66 -0
  50. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  51. package/bin/lean/lane-audit-llm.mjs +5 -0
  52. package/bin/lean/lane-audit-query.mjs +47 -0
  53. package/bin/lean/lane-audit-query.test.mjs +44 -0
  54. package/bin/lean/lane-audit-signatures.mjs +33 -0
  55. package/bin/lean/lane-audit.mjs +110 -0
  56. package/bin/lean/lane-audit.test.mjs +97 -0
  57. package/bin/lean/lane-recovery.test.mjs +33 -0
  58. package/bin/lean/lanecheck.mjs +5 -3
  59. package/bin/lean/lanecheck.test.mjs +6 -0
  60. package/bin/lean/lean.mjs +206 -148
  61. package/bin/lean/lean.test.mjs +406 -190
  62. package/bin/lean/limits.mjs +17 -0
  63. package/bin/lean/limits.test.mjs +15 -1
  64. package/bin/lean/live-execution.mjs +21 -2
  65. package/bin/lean/live-execution.test.mjs +39 -0
  66. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  67. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  68. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  69. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  70. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  71. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  72. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  73. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  74. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  75. package/bin/lean/orchestrate.mjs +188 -33
  76. package/bin/lean/postdeploy-check.test.mjs +1 -3
  77. package/bin/lean/precheck.mjs +20 -0
  78. package/bin/lean/preflight.mjs +100 -11
  79. package/bin/lean/preflight.test.mjs +44 -4
  80. package/bin/lean/prompts.mjs +10 -21
  81. package/bin/lean/recurrence.mjs +6 -148
  82. package/bin/lean/recurrence.test.mjs +11 -147
  83. package/bin/lean/release-flakes.mjs +14 -2
  84. package/bin/lean/release-flakes.test.mjs +17 -1
  85. package/bin/lean/release-ledger.mjs +19 -1
  86. package/bin/lean/release-ledger.test.mjs +23 -0
  87. package/bin/lean/release-preflight.mjs +28 -0
  88. package/bin/lean/release-preflight.test.mjs +42 -1
  89. package/bin/lean/release-review.mjs +40 -5
  90. package/bin/lean/release-review.test.mjs +43 -2
  91. package/bin/lean/release.mjs +43 -14
  92. package/bin/lean/release.test.mjs +32 -0
  93. package/bin/lean/retry.mjs +1 -1
  94. package/bin/lean/retry.test.mjs +6 -1
  95. package/bin/lean/rotator.mjs +9 -0
  96. package/bin/lean/rotator.test.mjs +11 -1
  97. package/bin/lean/sandbox-remote.mjs +16 -9
  98. package/bin/lean/schedd.mjs +11 -6
  99. package/bin/lean/schedd.test.mjs +65 -5
  100. package/bin/lean/selfreview.mjs +1 -1
  101. package/bin/lean/statuscomment.mjs +4 -1
  102. package/bin/lean/validate-catalog.mjs +108 -0
  103. package/bin/lean/validate-catalog.test.mjs +46 -1
  104. package/bin/lean/verify.mjs +1 -1
  105. package/bin/pool/affinity.test.mjs +91 -0
  106. package/bin/pool/agent.mjs +143 -9
  107. package/bin/pool/cache-sweep.mjs +31 -10
  108. package/bin/pool/ci-autoscale.mjs +160 -0
  109. package/bin/pool/cli.mjs +37 -8
  110. package/bin/pool/docker.mjs +3 -0
  111. package/bin/pool/engine-placement.test.mjs +94 -0
  112. package/bin/pool/lane-target.mjs +41 -0
  113. package/bin/pool/lane-tools.mjs +7 -2
  114. package/bin/pool/lane-tools.test.mjs +9 -0
  115. package/bin/pool/mirror-seed.mjs +15 -11
  116. package/bin/pool/router.mjs +88 -32
  117. package/bin/pool/version.mjs +29 -2
  118. package/bin/review-staging.mjs +11 -3
  119. package/bin/runner.mjs +59 -11
  120. package/bin/stats/release.mjs +7 -0
  121. package/bin/stats/release.test.mjs +20 -0
  122. package/bin/stats/scorecard.mjs +187 -0
  123. package/bin/stats/scorecard.test.mjs +89 -0
  124. package/docs/CONFIG.md +41 -0
  125. package/docs/OUTCOME-CODES.md +1 -0
  126. package/docs/STATS.md +17 -0
  127. package/package.json +1 -1
  128. package/pool/image/Dockerfile +14 -2
  129. package/pool/image/manifest.json +25 -0
  130. package/pool/image/mirror.sh +11 -2
  131. package/pool/install/install-agent.ps1 +11 -4
  132. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  133. package/scripts/ci-local/cli.mjs +1 -1
  134. package/scripts/ci-local/plan.mjs +3 -2
  135. package/scripts/ci-local.test.sh +11 -0
  136. package/scripts/failure-census.mjs +67 -0
  137. package/scripts/review-finalize.sh +5 -5
  138. package/scripts/review-finalize.test.sh +8 -1
  139. package/scripts/verify-phase-trail.sh +11 -0
  140. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -43,12 +43,15 @@ const TMP_RE = /^(pnpm|npm|yarn|uv|poetry)-[0-9a-f]{16}\.tmp-(\d+)$/;
43
43
  const LOCK_RE = /^(pnpm|npm|yarn|uv|poetry)-[0-9a-f]{16}\.lock$/;
44
44
 
45
45
  const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e?.code === "EPERM"; } };
46
+ /** #5731: how long a failed (lock, interpreter) install is remembered, and the failures that mean "these pins do not build under this interpreter" (retried under the next candidate). */
47
+ const NEG_TTL_MS = 6 * 3600 * 1000;
48
+ const PY_BUILD_RE = /build requirements are incompatible|incompatible with your operating system|_finalize_license_expression|Failed building wheel|No matching distribution|no matching wheel|Could not find a version that satisfies/i;
49
+ /** #5592: poetry cannot install the project itself (not package-mode: no package dir, no `package-mode = false`). */
50
+ const NO_ROOT_RE = /--no-root|current project could not be installed|No file\/folder found for package|does not contain any element/i;
46
51
  /**
47
52
  * Error text for a reason: pnpm prints its ERR_PNPM_* errors on stdout (#4522), so the first such line from either
48
53
  * stream leads, then the last lines of stderr and stdout; the message only when both streams are empty.
49
54
  */
50
- /** #5592: poetry cannot install the project itself (not package-mode: no package dir, no `package-mode = false`). */
51
- const NO_ROOT_RE = /--no-root|current project could not be installed|No file\/folder found for package|does not contain any element/i;
52
55
  const msg = (e) => {
53
56
  const lines = (s) => String(s ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
54
57
  const err = lines(e?.stderr), out = lines(e?.stdout);
@@ -151,6 +154,21 @@ function clauseOk(clause, v) {
151
154
  default: { const up = (op === "~=" ? n.length === 2 : n.length === 1) ? [n[0] + 1] : [n[0], (n[1] ?? 0) + 1]; return cmpVer(v, n) >= 0 && cmpVer(v, up) < 0; } // ~ / ~=
152
155
  }
153
156
  }
157
+ /** #5731: [major, minor] the repo pins for its Python: `.python-version`, else the first CI `python-version`; null when none. */
158
+ function pyHint(fs, wt) {
159
+ const minor = (t) => { const m = /^\s*(?:cpython-)?(\d+)\.(\d+)/.exec(t); return m ? [Number(m[1]), Number(m[2])] : null; };
160
+ try { const h = minor(String(fs.readFileSync(join(wt, ".python-version")))); if (h) return h; } catch { /* no .python-version */ }
161
+ try {
162
+ const dir = join(wt, ".github", "workflows");
163
+ for (const f of fs.readdirSync(dir).sort()) {
164
+ if (!/\.ya?ml$/.test(f)) continue;
165
+ const m = /python-version:\s*\[?\s*["']?(\d+\.\d+)/.exec(String(fs.readFileSync(join(dir, f))));
166
+ if (m) return minor(m[1]);
167
+ }
168
+ } catch { /* no workflows */ }
169
+ return null;
170
+ }
171
+
154
172
  /** #5590: does version `v` ([major, minor, patch]) satisfy the PEP 440 / poetry range `spec` ("||" alternatives, comma or space joined clauses)? */
155
173
  export function pySatisfies(spec, v) {
156
174
  return String(spec).split("||").some((grp) => grp.replace(/(\^|~=|~|==|!=|>=|<=|>|<)\s+/g, "$1").split(/[,\s]+/).filter(Boolean).every((c) => clauseOk(c, v)));
@@ -208,17 +226,33 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
208
226
  return ["package.json"];
209
227
  }
210
228
 
229
+ /** #5731: the hinted minor on PATH, else `uv python find`, else provisioned with `uv python install`; null when unavailable. */
230
+ async function hintedPython([maj, min], probe) {
231
+ const want = `${maj}.${min}`;
232
+ const ok = (c) => (c && c.v[0] === maj && c.v[1] === min ? c : null);
233
+ const onPath = ok(await probe(`python${want}`));
234
+ if (onPath) return onPath;
235
+ const find = async () => { try { const p = String(await exec("uv", ["python", "find", want], { timeoutMs: 30000 })).trim().split("\n")[0]; return p ? ok(await probe(p)) : null; } catch { return null; } };
236
+ const found = await find();
237
+ if (found) return found;
238
+ try { await exec("uv", ["python", "install", want], { timeoutMs: 600000 }); } catch { return null; }
239
+ return find();
240
+ }
241
+
211
242
  /**
212
- * #5590/#5651: for a Python project whose pyproject declares a range, {py: null} (no range, or the default python3 is in range),
243
+ * #5590/#5651: for a Python project whose pyproject declares a range, {py: null} (no range, or the default python3 is in range), the repo's .python-version / CI pin first (#5731),
213
244
  * {py: {cmd, version}} (the interpreter that satisfies it: pythonX.Y on PATH, then `uv python find`) or {missing: {range, probed}}
214
245
  * (nothing in range: the caller stops, the out-of-range default is never used).
215
246
  */
216
- async function pythonFor(wt, d) {
247
+ async function pythonFor(wt, d, tried = []) {
217
248
  if (!PY.has(d.eco)) return { py: null };
218
249
  let range = null;
219
250
  try { range = pyRange(String(fs.readFileSync(join(wt, "pyproject.toml"))), d.eco); } catch { /* no pyproject */ }
220
- if (!range) return { py: null };
251
+ const hint = pyHint(fs, wt);
252
+ if (!range && !hint) return { py: null };
221
253
  const probed = [];
254
+ const skip = (c) => tried.includes(`${c.v[0]}.${c.v[1]}`); // #5731: minors whose install already failed
255
+ const fits = (c) => c && !skip(c) && (!range || pySatisfies(range, c.v));
222
256
  const probe = async (cmd) => {
223
257
  try {
224
258
  const version = String(await exec(cmd, ["--version"], { timeoutMs: 30000 })).trim();
@@ -229,14 +263,18 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
229
263
  return null;
230
264
  };
231
265
  const def = await probe("python3");
232
- if (def && pySatisfies(range, def.v)) return { py: null };
266
+ // #5731: the repo's own pin (.python-version, then CI setup-python) wins over a default python3 that merely satisfies the range.
267
+ const hinted = hint && !(hint && tried.includes(`${hint[0]}.${hint[1]}`)) && (!def || def.v[0] !== hint[0] || def.v[1] !== hint[1]) ? await hintedPython(hint, probe) : null;
268
+ if (fits(hinted)) return { py: hinted };
269
+ if (!range) return tried.length ? { missing: { range: "(none declared)", probed } } : fits(def) ? { py: null, minor: `${def.v[0]}.${def.v[1]}` } : { py: null };
270
+ if (fits(def)) return { py: null, minor: `${def.v[0]}.${def.v[1]}` };
233
271
  const minors = [14, 13, 12, 11, 10, 9, 8];
234
- for (const x of minors) { const c = await probe(`python3.${x}`); if (c && pySatisfies(range, c.v)) return { py: c }; }
272
+ for (const x of minors) { const c = await probe(`python3.${x}`); if (fits(c)) return { py: c }; }
235
273
  for (const x of minors) {
236
274
  let path = "";
237
275
  try { path = String(await exec("uv", ["python", "find", `3.${x}`], { timeoutMs: 30000 })).trim().split("\n")[0]; } catch { probed.push("uv python find (unavailable)"); break; } // no uv
238
276
  const c = path ? await probe(path) : null;
239
- if (c && pySatisfies(range, c.v)) return { py: c };
277
+ if (fits(c)) return { py: c };
240
278
  }
241
279
  return { missing: { range, probed } };
242
280
  }
@@ -469,13 +507,49 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
469
507
  }
470
508
  const failedRun = (r) => r.status === "failed" || r.status === "materialize-fallback" || (r.published === false && /^(publish failed|cache is on another filesystem)/.test(String(r.reason ?? "")));
471
509
 
510
+ /** #5731: the in-range minors on PATH that were not used (`python3.X`), for the final failure to name. */
511
+ async function untriedAlternatives(wt, d, exclude) {
512
+ let range = null;
513
+ try { range = pyRange(String(fs.readFileSync(join(wt, "pyproject.toml"))), d.eco); } catch { /* no pyproject */ }
514
+ const out = [];
515
+ for (const x of [14, 13, 12, 11, 10, 9, 8]) {
516
+ if (exclude.includes(`3.${x}`)) continue;
517
+ try {
518
+ const v = /(\d+)\.(\d+)\.(\d+)/.exec(String(await exec(`python3.${x}`, ["--version"], { timeoutMs: 30000 })));
519
+ if (v && (!range || pySatisfies(range, v.slice(1, 4).map(Number)))) out.push(`python3.${x}`);
520
+ } catch { /* not installed */ }
521
+ }
522
+ return out;
523
+ }
524
+
525
+ /** #5731: an install that fails with a build/wheel incompatibility is retried once per remaining in-range interpreter; the final env.setup_failed names the interpreters used and the in-range alternatives not tried. */
472
526
  async function prepareOne(wt, keyRoot, d, laneEnv, publishSnap = true) {
527
+ const tried = [];
528
+ let last = null;
529
+ const finish = async (r, retryMinor) => {
530
+ const { pyMinor, ...rest } = r;
531
+ if (rest.status !== "failed" || !pyMinor) return rest;
532
+ const used = [...tried, pyMinor].filter((m, i, a) => a.indexOf(m) === i);
533
+ const alts = await untriedAlternatives(wt, d, [...used, retryMinor].filter(Boolean));
534
+ return { ...rest, code: "env.setup_failed", reason: `${rest.reason} (interpreters used: ${used.join(", ")}; in-range alternatives not tried: ${alts.join(", ") || "none"})` };
535
+ };
536
+ for (;;) {
537
+ const r = await prepareWith(wt, keyRoot, d, laneEnv, publishSnap, tried);
538
+ if (last && r.status === "failed" && r.code === "env.tool_missing") return finish({ ...last, reason: `${last.reason}; no further in-range interpreter to retry` });
539
+ const { retryMinor, ...rest } = r;
540
+ if (!retryMinor || tried.length >= 3) return finish(rest, retryMinor);
541
+ tried.push(retryMinor);
542
+ last = rest;
543
+ }
544
+ }
545
+
546
+ async function prepareWith(wt, keyRoot, d, laneEnv, publishSnap, tried) {
473
547
  const t0 = now();
474
548
  let repaired = null;
475
549
  const done = (status, extra = {}) => ({ status, eco: d.eco, key: extra.key ?? null, ms: now() - t0, reason: extra.reason ?? repaired, ...(extra.published === undefined ? {} : { published: extra.published }) });
476
550
  if (d.skip) return done("skipped", { reason: d.skip });
477
551
  const pkgs = JS.has(d.eco) ? await manifests(wt) : [];
478
- const found = await pythonFor(wt, d);
552
+ const found = await pythonFor(wt, d, tried);
479
553
  if (found.missing) {
480
554
  // #5651: never resolve under an out-of-range default interpreter (poetry dies in _finalize_license_expression on python 3.14).
481
555
  const { range, probed } = found.missing;
@@ -501,6 +575,15 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
501
575
  }
502
576
  fs.mkdirSync(keyRoot, { recursive: true, mode: 0o700 });
503
577
 
578
+ // #5731: a negative result is cached per key (lock hash + interpreter version): the same failing build is not re-run by this lane or the next.
579
+ const negFile = join(keyRoot, `${d.eco}-${key}.failed.json`);
580
+ if (PY.has(d.eco) && !present(join(snap, "manifest.json"))) {
581
+ try {
582
+ const neg = JSON.parse(String(fs.readFileSync(negFile)));
583
+ if (now() - neg.at < NEG_TTL_MS) return { ...done("failed", { key, reason: `${neg.reason} (cached negative result)` }), pyMinor: neg.minor, retryMinor: neg.minor };
584
+ } catch { /* none cached */ }
585
+ }
586
+
504
587
  // #5592: `poetry install` fails on a project that is not package-mode (root package not installable): retry once with --no-root (dependencies only).
505
588
  const runList = async (list) => {
506
589
  for (const [c, a] of list) {
@@ -531,7 +614,14 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
531
614
  const install = async () => {
532
615
  try { await runList(cmds.install); } catch (e) {
533
616
  rmTrees(wt, expected);
534
- return { failed: done("failed", { key, reason: `${e?.code === "ENOENT" ? "tool not found" : "install failed"}: ${msg(e)}` }) };
617
+ const f = done("failed", { key, reason: `${e?.code === "ENOENT" ? "tool not found" : "install failed"}: ${msg(e)}${py ? ` (under ${py.cmd} ${py.version})` : ""}` });
618
+ const minor = py ? `${py.v[0]}.${py.v[1]}` : found.minor;
619
+ if (PY.has(d.eco) && minor) f.pyMinor = minor;
620
+ if (PY.has(d.eco) && minor && PY_BUILD_RE.test(`${msg(e)}\n${e?.stderr ?? ""}\n${e?.stdout ?? ""}`)) {
621
+ f.retryMinor = minor; // #5731
622
+ try { fs.writeFileSync(negFile, JSON.stringify({ reason: f.reason, minor, at: now() })); } catch { /* best effort */ }
623
+ }
624
+ return { failed: f };
535
625
  }
536
626
  return { trees: treesOf(wt, d, pkgs) };
537
627
  };
@@ -690,6 +690,111 @@ describe("depcache (#5651): no silent fallback to an out-of-range default python
690
690
  });
691
691
  });
692
692
 
693
+ describe("depcache (#5731): the repo's python pin beats an in-range default python3", () => {
694
+ const project = (hint) => { const base = scratch(), wt = join(base, "wt"); mkdirSync(wt, { recursive: true }); FIXTURES.poetry(wt); put(join(wt, "pyproject.toml"), '[tool.poetry.dependencies]\npython = "^3.11"\n'); if (hint) put(join(wt, ".python-version"), `${hint}\n`); return { base, wt }; };
695
+ const run = async (f, wt, base, key) => (await makeDepCache({ root: join(base, "cache"), exec: f.exec, env: {}, pollMs: 5 }).prepare({ wt, repoKey: key }))[0];
696
+ const viaOf = (f) => f.calls.filter((c) => c.cmd === "poetry").map((c) => c.via);
697
+ it("#5731 .python-version 3.11 is used although python3 is 3.14 and in range", async () => {
698
+ const f = fakeExec({ pythons: { python3: "3.14.0", "python3.11": "3.11.8" } });
699
+ const { base, wt } = project("3.11");
700
+ const r = await run(f, wt, base, "repo-5731a");
701
+ assert.notEqual(r.status, "failed", JSON.stringify(r));
702
+ assert.ok(viaOf(f).length >= 2 && viaOf(f).every((v) => v === "python3.11"), JSON.stringify(viaOf(f)));
703
+ });
704
+ it("#5731 the CI python-version is the hint when there is no .python-version", async () => {
705
+ const f = fakeExec({ pythons: { python3: "3.14.0", "python3.12": "3.12.3" } });
706
+ const { base, wt } = project(null);
707
+ put(join(wt, ".github/workflows/ci.yml"), 'jobs:\n t:\n steps:\n - uses: actions/setup-python@v5\n with:\n python-version: "3.12"\n');
708
+ const r = await run(f, wt, base, "repo-5731b");
709
+ assert.notEqual(r.status, "failed", JSON.stringify(r));
710
+ assert.ok(viaOf(f).length >= 2 && viaOf(f).every((v) => v === "python3.12"), JSON.stringify(viaOf(f)));
711
+ });
712
+ it("#5731 a hinted minor that is not installed is provisioned with uv python install", async () => {
713
+ const f = fakeExec({ pythons: { python3: "3.14.0", "python3.11": "3.11.8" } });
714
+ let installed = false;
715
+ const exec = async (cmd, args, o) => {
716
+ if (cmd === "python3.11" && args[0] === "--version" && !installed) throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
717
+ if (cmd === "uv" && args[0] === "python" && args[1] === "install") { installed = true; return ""; }
718
+ if (cmd === "uv" && args[0] === "python" && args[1] === "find") { if (!installed) throw new Error("none"); return "python3.11\n"; }
719
+ return f.exec(cmd, args, o);
720
+ };
721
+ const { base, wt } = project("3.11");
722
+ const [r] = await makeDepCache({ root: join(base, "cache"), exec, env: {}, pollMs: 5 }).prepare({ wt, repoKey: "repo-5731c" });
723
+ assert.ok(installed, "uv python install ran");
724
+ assert.notEqual(r.status, "failed", JSON.stringify(r));
725
+ });
726
+ it("#5731 an unavailable hint falls back to the in-range default", async () => {
727
+ const f = fakeExec({ pythons: { python3: "3.12.3" } });
728
+ const { base, wt } = project("3.11");
729
+ const r = await run(f, wt, base, "repo-5731d");
730
+ assert.notEqual(r.status, "failed", JSON.stringify(r));
731
+ });
732
+ });
733
+
734
+ describe("depcache (#5731): hint without a range, and retry under the next interpreter", () => {
735
+ const project = (range, hint) => { const base = scratch(), wt = join(base, "wt"); mkdirSync(wt, { recursive: true }); FIXTURES.poetry(wt); if (range) put(join(wt, "pyproject.toml"), `[tool.poetry.dependencies]\npython = "${range}"\n`); if (hint) put(join(wt, ".python-version"), `${hint}\n`); return { base, wt }; };
736
+ const BUILD = { stderr: "build requirements are incompatible with your operating system or Python version" };
737
+ const wrap = (f, failMinors) => async (cmd, args, o) => {
738
+ const under = cmd === "poetry" ? "python3" : cmd, rest = cmd === "poetry" ? args : args.slice(2);
739
+ if (failMinors.includes(under) && rest[0] === "install" && !args.includes("--no-root")) throw Object.assign(new Error("install failed"), BUILD);
740
+ return f.exec(cmd, args, o);
741
+ };
742
+ it("#5731 the pin is used when pyproject declares no python range", async () => {
743
+ const f = fakeExec({ pythons: { python3: "3.14.0", "python3.11": "3.11.8" } });
744
+ const { base, wt } = project(null, "3.11");
745
+ const [r] = await makeDepCache({ root: join(base, "cache"), exec: f.exec, env: {}, pollMs: 5 }).prepare({ wt, repoKey: "repo-5731e" });
746
+ assert.notEqual(r.status, "failed", JSON.stringify(r));
747
+ assert.ok(f.calls.filter((c) => c.cmd === "poetry").every((c) => c.via === "python3.11"), JSON.stringify(f.calls.map((c) => c.via)));
748
+ });
749
+ it("#5731 a build-incompatibility failure under the pin is retried under the next in-range interpreter", async () => {
750
+ const f = fakeExec({ pythons: { python3: "3.14.0", "python3.11": "3.11.8", "python3.12": "3.12.3" } });
751
+ const { base, wt } = project("^3.11", "3.11");
752
+ const [r] = await makeDepCache({ root: join(base, "cache"), exec: wrap(f, ["python3.11"]), env: {}, pollMs: 5 }).prepare({ wt, repoKey: "repo-5731f" });
753
+ assert.notEqual(r.status, "failed", JSON.stringify(r));
754
+ assert.ok(f.calls.some((c) => c.cmd === "poetry" && c.args[0] === "install" && c.via !== "python3.11"), JSON.stringify(f.calls.map((c) => c.via)));
755
+ });
756
+ it("#5731 when every candidate fails the reason names the interpreters tried", async () => {
757
+ const f = fakeExec({ pythons: { python3: "3.14.0", "python3.11": "3.11.8" } });
758
+ const { base, wt } = project("^3.11", "3.11");
759
+ const [r] = await makeDepCache({ root: join(base, "cache"), exec: wrap(f, ["python3.11", "python3.14", "python3"]), env: {}, pollMs: 5 }).prepare({ wt, repoKey: "repo-5731g" });
760
+ assert.equal(r.status, "failed", JSON.stringify(r));
761
+ assert.match(r.reason, /3\.11/);
762
+ assert.match(r.reason, /tried/);
763
+ assert.equal(r.code, "env.setup_failed");
764
+ assert.match(r.reason, /interpreters used: 3\.11, 3\.14/);
765
+ assert.match(r.reason, /in-range alternatives not tried: none/);
766
+ });
767
+ it("#5731 a failing install is cached per (lock, interpreter): the second prepare does not re-run it", async () => {
768
+ const f = fakeExec({ pythons: { python3: "3.11.8" } });
769
+ const { base, wt } = project("3.11", "3.11");
770
+ let n = 0;
771
+ const installs = () => n;
772
+ const w = wrap(f, ["python3"]);
773
+ const dc = () => makeDepCache({ root: join(base, "cache"), exec: async (c, a, o) => { if (c === "poetry" && a[0] === "install" && !a.includes("--no-root")) n++; return w(c, a, o); }, env: {}, pollMs: 5 });
774
+ const [r1] = await dc().prepare({ wt, repoKey: "repo-5731i" });
775
+ const n1 = installs();
776
+ const [r2] = await dc().prepare({ wt, repoKey: "repo-5731i" });
777
+ assert.equal(r1.status, "failed", JSON.stringify(r1));
778
+ assert.equal(r2.status, "failed", JSON.stringify(r2));
779
+ assert.ok(n1 >= 1 && installs() === n1, `installs ${n1} then ${installs()}`);
780
+ assert.match(r2.reason, /cached negative result/);
781
+ });
782
+ it("#5731 a failed install is env.setup_failed naming the interpreter used and the in-range alternatives not tried", async () => {
783
+ const f = fakeExec({ pythons: { python3: "3.14.0", "python3.11": "3.11.8", "python3.12": "3.12.3" } });
784
+ const { base, wt } = project("^3.11", "3.11");
785
+ const exec = async (cmd, args, o) => {
786
+ const rest = cmd === "poetry" ? args : args.slice(2);
787
+ if (cmd === "python3.11" && rest[0] === "install" && !args.includes("--no-root")) throw Object.assign(new Error("install failed"), { stderr: "boom" });
788
+ return f.exec(cmd, args, o);
789
+ };
790
+ const [r] = await makeDepCache({ root: join(base, "cache"), exec, env: {}, pollMs: 5 }).prepare({ wt, repoKey: "repo-5731h" });
791
+ assert.equal(r.status, "failed", JSON.stringify(r));
792
+ assert.equal(r.code, "env.setup_failed");
793
+ assert.match(r.reason, /interpreters used: 3\.11/);
794
+ assert.match(r.reason, /in-range alternatives not tried: .*python3\.12/);
795
+ });
796
+ });
797
+
693
798
  describe("depcache (#5819): a failed publish or materialize never touches workspace package sources", () => {
694
799
  const sh = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8" });
695
800
  const SRC = Array.from({ length: 6 }, (_, i) => `packages/adapters/src/f${i}.ts`);
@@ -69,38 +69,6 @@ export function linkResolves(link, cfg, files) {
69
69
  return (files ?? []).some((f) => re.test(f) && anyGlob(globs, f));
70
70
  }
71
71
 
72
- /**
73
- * Blocking failures (conformance.unimplemented): `docs_missing` (a touched surface with no docs change and no result.docs justification),
74
- * `docs_link_broken` (a `/docs/...` link the diff adds that does not resolve). `run` is ({command}) => {rc, output}; `tracked` the repo's files.
75
- */
76
- export async function docsFailures({ cfg, files = [], diff = "", result = null, run = null, tracked = null }) {
77
- if (!cfg) return [];
78
- const C = OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, out = [];
79
- const surfaces = userFacingSurfaces(files, cfg);
80
- const docGlobs = [...(cfg.paths.length ? cfg.paths : DEFAULT_PATHS), ...cfg.registries];
81
- const changedDocs = files.map(norm).filter((f) => anyGlob(docGlobs, f));
82
- const given = Array.isArray(result?.docs) ? result.docs : [];
83
- for (const [kind, fs] of Object.entries(surfaces)) {
84
- if (changedDocs.length || given.some((d) => String(d?.surface ?? "").trim().toLowerCase() === kind && String(d?.justification ?? "").trim())) continue;
85
- out.push({ code: C, kind: "docs_missing", detail: `${fs.slice(0, 3).join(", ")} changes the user-facing ${kind} surface (forge.yaml docs.required_for) but no docs file changed: add the page(s) under ${(cfg.paths.length ? cfg.paths : DEFAULT_PATHS).join(", ")}${cfg.registries.length ? ` and register them (${cfg.registries.join(", ")})` : ""}, or record docs: [{"surface":"${kind}","justification":"<why none>"}] in the result file` });
86
- }
87
- const links = docsLinks(diff, cfg.link_prefixes);
88
- if (!links.length) return out;
89
- if (cfg.link_check && run) {
90
- let r;
91
- try { r = await run({ command: `${cfg.link_check} ${links.map(sq).join(" ")}` }); r = r?.r ?? r; } catch (e) { r = { rc: 127, output: String(e?.message ?? e) }; }
92
- if (r?.rc !== 0) {
93
- const tail = String(r?.output ?? "").trim().split("\n").slice(-12).join("\n").slice(0, 1500);
94
- out.push({ code: C, kind: "docs_link_broken", detail: `forge.yaml docs.link_check (\`${cfg.link_check}\`) exited ${r?.rc ?? "?"} for the docs link(s) ${links.join(", ")} this diff adds: create the page or fix the link${tail ? `:\n${tail}` : ""}` });
95
- }
96
- } else if (!cfg.link_check && tracked) {
97
- const known = [...new Set([...tracked, ...files].map(norm))];
98
- const bad = links.filter((l) => !linkResolves(l, cfg, known));
99
- if (bad.length) out.push({ code: C, kind: "docs_link_broken", detail: `the diff links to ${bad.join(", ")} but no docs file under ${(cfg.paths.length ? cfg.paths : DEFAULT_PATHS).join(", ")} serves it (forge.yaml docs): create the page or fix the link` });
100
- }
101
- return out;
102
- }
103
-
104
72
  const names = (c) => (c.labels ?? []).map((l) => String(l?.name ?? l).toLowerCase());
105
73
  /** Milestone children `{number, state, labels}` -> {ok, reasons}. User-facing = labelled `user-facing` or a configured kind; the docs child is labelled `docs`. */
106
74
  export function milestoneDocsGate({ children = [], cfg }) {
@@ -2,8 +2,8 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { parseDocsConfig, userFacingSurfaces, docsLinks, docsFailures, milestoneDocsGate, docsFromCli } from "./docsgate.mjs";
6
- import { docsPlanNote, domainChecksBlock } from "./prompts.mjs";
5
+ import { parseDocsConfig, userFacingSurfaces, docsLinks, milestoneDocsGate, docsFromCli } from "./docsgate.mjs";
6
+ import { domainChecksBlock } from "./prompts.mjs";
7
7
  import { pathDomains } from "./review-trigger.mjs";
8
8
 
9
9
  const cfg = parseDocsConfig({ required_for: "[api, dashboard]", paths: ["web/docs/**"], registries: ["web/public/llms.txt"] });
@@ -16,8 +16,6 @@ describe("docs gate (#5419)", () => {
16
16
  assert.equal(parseDocsConfig(undefined), null);
17
17
  assert.equal(parseDocsConfig({ paths: ["docs/**"] }), null);
18
18
  assert.equal(parseDocsConfig({ required_for: "bogus" }), null);
19
- assert.deepEqual(await docsFailures({ cfg: null, files: handsFiles, diff: handsDiff }), []);
20
- assert.equal(docsPlanNote(null), "");
21
19
  });
22
20
  it("detects configured surfaces only, ignoring tests", () => {
23
21
  assert.deepEqual(Object.keys(userFacingSurfaces(["web/app/api/x/route.ts", "web/app/dashboard/p/page.tsx", "web/app/api/x/route.test.ts"], cfg)).sort(), ["api", "dashboard"]);
@@ -28,25 +26,6 @@ describe("docs gate (#5419)", () => {
28
26
  assert.deepEqual(docsLinks(handsDiff), ["/docs/hands", "/docs/hands/credentials"]);
29
27
  assert.deepEqual(docsLinks("-<a href=\"/docs/old\">\n+<a href=\"https://x.io/docs/a\">"), []);
30
28
  });
31
- it("replay: the Hands dashboard diff fails docs_missing and the link gate, and its plan carries R-docs", async () => {
32
- const f = await docsFailures({ cfg, files: handsFiles, diff: handsDiff, tracked: ["web/docs/api/index.mdx"] });
33
- assert.deepEqual(f.map((x) => x.kind).sort(), ["docs_link_broken", "docs_missing"]);
34
- assert.match(docsPlanNote(cfg), /R-docs/);
35
- assert.match(docsPlanNote(cfg), /web\/docs\/\*\*/);
36
- });
37
- it("passes when the pages exist, or the repo link_check exits 0, or the change is justified", async () => {
38
- const files = [...handsFiles, "web/docs/hands/index.mdx", "web/docs/hands/credentials.mdx"];
39
- assert.deepEqual(await docsFailures({ cfg, files, diff: handsDiff, tracked: [] }), []);
40
- const c2 = parseDocsConfig({ required_for: ["dashboard"], paths: ["web/docs/**"], link_check: "bash chk.sh" });
41
- let ran; const run = async ({ command }) => { ran = command; return { rc: 0 }; };
42
- assert.deepEqual(await docsFailures({ cfg: c2, files: [...handsFiles, "web/docs/x.mdx"], diff: handsDiff, run }), []);
43
- assert.match(ran, /^bash chk\.sh '\/docs\/hands' '\/docs\/hands\/credentials'$/);
44
- const bad = await docsFailures({ cfg: c2, files: ["web/docs/x.mdx"], diff: handsDiff, run: async () => ({ rc: 1, output: "404 /docs/hands" }) });
45
- assert.equal(bad[0].kind, "docs_link_broken");
46
- const crashed = await docsFailures({ cfg: c2, files: [], diff: handsDiff, run: async () => { throw new Error("nope"); } });
47
- assert.match(crashed[0].detail, /exited 127/);
48
- assert.deepEqual(await docsFailures({ cfg, files: handsFiles, result: { docs: [{ surface: "dashboard", justification: "internal page" }] }, diff: "" }), []);
49
- });
50
29
  it("adds the docs domain and its reviewer check only for a configured surface", () => {
51
30
  assert.ok(pathDomains(handsFiles, { docs: cfg })?.includes("docs"));
52
31
  assert.ok(!pathDomains(handsFiles)?.includes("docs"));
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { execCapped } from "./effects.mjs";
5
+ import { execCapped, elideArgs } from "./effects.mjs";
6
6
 
7
7
  describe("#5592 a huge git/gh output never crashes the lane", () => {
8
8
  it("output past the cap is truncated with a marker, not a maxBuffer error", async () => {
@@ -14,4 +14,12 @@ describe("#5592 a huge git/gh output never crashes the lane", () => {
14
14
  assert.equal(await execCapped(process.execPath, ["-e", "process.stdout.write('hi')"]), "hi");
15
15
  await assert.rejects(execCapped(process.execPath, ["-e", "console.error('boom');process.exit(3)"]), (e) => e.code === 3 && /boom/.test(e.stderr) && /boom/.test(e.message));
16
16
  });
17
+ it("a failure message elides long arguments so stderr (the reason) stays near the start (2026-11-26 #6034)", async () => {
18
+ const body = "<!-- FORGE:CONTRACT -->" + "x".repeat(5000);
19
+ await assert.rejects(execCapped(process.execPath, ["-e", "console.error('HTTP 502: unexpected EOF');process.exit(1)", body]), (e) => {
20
+ const head = e.message.slice(0, 300);
21
+ return /<\d+ chars>/.test(head) && /HTTP 502: unexpected EOF/.test(head) && !head.includes("xxxx") && e.stderr.includes("HTTP 502");
22
+ });
23
+ assert.equal(elideArgs(["issue", "comment", "7"]), "issue comment 7");
24
+ });
17
25
  });
@@ -0,0 +1,35 @@
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 { spawn } from "node:child_process";
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { tmpDir } from "../tests/_tmp.mjs";
9
+ import { killLedgerPid, descendantPids } from "./effects.mjs";
10
+
11
+ // a signalled-but-unreaped (zombie) process counts as stopped
12
+ const alive = (p) => { try { process.kill(p, 0); } catch { return false; } try { return !readFileSync(`/proc/${p}/stat`, "utf8").includes(") Z "); } catch { return true; } };
13
+
14
+ // #5746: stopping a lane kills its whole process tree, including a builder that left the lane's process group (setsid)
15
+ describe("#5746 killLedgerPid stops the whole process tree", () => {
16
+ it("descendantPids walks /proc ppids, grandchildren included, unrelated pids excluded", () => {
17
+ const d = tmpDir("proc-");
18
+ const st = (pid, ppid, comm = "node") => { mkdirSync(join(d, String(pid))); writeFileSync(join(d, String(pid), "stat"), `${pid} (${comm}) S ${ppid} ${pid} ${pid} 0`); };
19
+ st(10, 1); st(11, 10, "a b) c"); st(12, 11); st(13, 1); st(14, 13);
20
+ assert.deepEqual(descendantPids(10, { procDir: d }).sort(), [11, 12]);
21
+ });
22
+ it("a setsid grandchild outside the lane's process group is signalled too", { skip: !existsSync("/proc") }, async () => {
23
+ const marker = `killtree-${process.pid}`;
24
+ const inner = "setInterval(()=>{},1000)";
25
+ const outer = `const c=require("child_process").spawn(process.execPath,["-e",${JSON.stringify(inner)}],{detached:true,stdio:"ignore"});console.log(c.pid);setInterval(()=>{},1000)`;
26
+ const lane = spawn(process.execPath, ["-e", outer, marker], { detached: true, stdio: ["ignore", "pipe", "ignore"] });
27
+ const gc = await new Promise((res) => lane.stdout.once("data", (b) => res(Number(String(b).trim()))));
28
+ try {
29
+ assert.ok(alive(gc));
30
+ assert.equal(killLedgerPid(lane.pid, marker), true);
31
+ for (let i = 0; i < 50 && alive(gc); i++) await new Promise((r) => setTimeout(r, 50));
32
+ assert.equal(alive(gc), false, "the setsid grandchild survived the stop");
33
+ } finally { for (const p of [gc, lane.pid]) { try { process.kill(p, "SIGKILL"); } catch { /* gone */ } } }
34
+ });
35
+ });
@@ -9,8 +9,9 @@ import { dirname, join, resolve, sep } from "node:path";
9
9
  import { resolveSpawn } from "./winspawn.mjs";
10
10
  import { fileURLToPath } from "node:url";
11
11
  import { randomBytes } from "node:crypto";
12
- import { runCliBackendAsync, resolveClaudeCliBinary, getClaudeCliCapabilities, buildLeanSessionFlags, buildReadOnlyToolFlags, sanitizeCliModel } from "../runner.mjs";
12
+ import { runCliBackendAsync, resolveClaudeCliBinary, cliProbeTimedOut, spawnTargetMissing, getClaudeCliCapabilities, buildLeanSessionFlags, buildReadOnlyToolFlags, sanitizeCliModel } from "../runner.mjs";
13
13
  import { makeIo, readSubagentModel } from "../engine-cli.mjs";
14
+ import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
14
15
  import { makeProjector } from "../engine/projector.mjs";
15
16
  import { makeLedger, countLiveLanes, ledgerRoot } from "./ledger.mjs";
16
17
  import { makeDepCache } from "./depcache.mjs";
@@ -134,10 +135,15 @@ export const leanSettingsFlags = ({ subagentModel = null, reread = false, guard
134
135
  return ["--settings", JSON.stringify({ env: ownedModelEnv(subagentModel), includeCoAuthoredBy: false, attribution: { commit: "", pr: "" }, ...(Object.keys(hooks).length ? { hooks } : {}) })];
135
136
  };
136
137
 
137
- export function makeLeanRunner({ runCli = runCliBackendAsync, probe = systemdRunAvailable, subagentModel = null, sandboxed = inSandbox() } = {}) {
138
+ export function makeLeanRunner({ runCli = runCliBackendAsync, probe = systemdRunAvailable, subagentModel = null, sandboxed = inSandbox(), resolveBin = resolveClaudeCliBinary, probeTimedOut = cliProbeTimedOut, platform = process.platform, binMissing = spawnTargetMissing } = {}) {
138
139
  return async ({ role, issue, cwd, model, resume, system, prompt, readOnly = false, noTools = false, rereadNudge = false, maxTurns = null, agents = null, env = null, idleMs = 0, maxMs = 0, laneLimits = null, control = null, onSpawn = null, session = null, contextMax = 0, turnMax = 0, busy = null, busyMs = 0, onIdleExtend = null, bin: pinnedBin = null, fullSession = false }) => {
139
140
  // #5205: a rotation relaunch pins the real claude past the tokenbaton shim; absent, the usual resolution
140
- const bin = pinnedBin || resolveClaudeCliBinary(cwd) || resolveSpawn("claude", []).bin; // win32: a probe miss must not fall back to a bare name (spawn ENOENT)
141
+ const resolved = pinnedBin || resolveBin(cwd);
142
+ // #5844: a probe that timed out under host load is not an absent CLI; spawning a bare name would end needs-human
143
+ if (!resolved && probeTimedOut(cwd)) throw Object.assign(new Error("the claude CLI probe timed out (host busy); not spawning an unresolved name"), { deferCode: OUTCOME_CODES.HOST_BUSY, retryInSeconds: 120, deferDetail: "the claude CLI probe timed out under host load; retried later" });
144
+ const bin = resolved || resolveSpawn("claude", [], { platform }).bin; // win32: a probe miss must not fall back to a bare name (spawn ENOENT)
145
+ // #5844: win32 cannot spawn a bare name; left unresolved while absence is not proven, defer instead of ENOENT
146
+ if (!resolved && platform === "win32" && bin === "claude" && !binMissing("claude", process.env, { platform })) throw Object.assign(new Error("the claude CLI is on PATH but did not resolve to a spawnable target; not spawning a bare name"), { deferCode: OUTCOME_CODES.HOST_BUSY, retryInSeconds: 120, deferDetail: "the claude CLI did not resolve to a spawnable target; retried later" });
141
147
  const caps = getClaudeCliCapabilities(cwd);
142
148
  // #4391: custom subagents (the explorer) for the builder session; null leaves argv unchanged
143
149
  // #5516: fullSession keeps slash commands/Skill/Task (the release test gate invokes /test-gate); otherwise the lean minimal group
@@ -231,9 +237,28 @@ export function makeRunTmp({ root = runTmpRoot(), now = () => Date.now(), alive
231
237
  }
232
238
 
233
239
  /**
234
- * SIGTERM to a ledger-registered pid's process group (#4179). Only when the pid is alive and, where /proc exists, its
240
+ * SIGTERM to a ledger-registered pid's process group (#4179) and every descendant pid (#5746). Only when the pid is alive and, where /proc exists, its
235
241
  * command line still names `marker`, so a reused pid is never signalled. Returns true when the pid is gone or signalled.
236
242
  */
243
+ /** #5746: every descendant pid of `pid` from `/proc/<n>/stat` ppids, children before none; includes ones that left the group (setsid). */
244
+ export function descendantPids(pid, { procDir = "/proc" } = {}) {
245
+ const kids = new Map();
246
+ let names = [];
247
+ try { names = readdirSync(procDir); } catch { return []; }
248
+ for (const d of names) {
249
+ if (!/^\d+$/.test(d)) continue;
250
+ let st = "";
251
+ try { st = readFileSync(join(procDir, d, "stat"), "utf8"); } catch { continue; }
252
+ const ppid = Number(st.slice(st.lastIndexOf(")") + 2).split(" ")[1]); // fields after comm: state ppid ...
253
+ if (!Number.isSafeInteger(ppid)) continue;
254
+ if (!kids.has(ppid)) kids.set(ppid, []);
255
+ kids.get(ppid).push(Number(d));
256
+ }
257
+ const out = [], seen = new Set([Number(pid)]), queue = [Number(pid)];
258
+ while (queue.length) for (const c of kids.get(queue.shift()) ?? []) if (!seen.has(c)) { seen.add(c); out.push(c); queue.push(c); }
259
+ return out;
260
+ }
261
+
237
262
  export function killLedgerPid(pid, marker, { kill = process.kill.bind(process), procDir = "/proc" } = {}) {
238
263
  const n = Number(pid);
239
264
  if (!Number.isSafeInteger(n) || n <= 1) return false;
@@ -243,7 +268,12 @@ export function killLedgerPid(pid, marker, { kill = process.kill.bind(process),
243
268
  try { cmd = readFileSync(join(procDir, String(n), "cmdline"), "utf8"); } catch { return true; } // exited meanwhile
244
269
  if (!cmd.includes(String(marker))) return true; // pid reused by something else: not ours any more
245
270
  }
246
- try { kill(-n, "SIGTERM"); return true; } catch { try { kill(n, "SIGTERM"); return true; } catch (e) { return e?.code === "ESRCH"; } }
271
+ // #5746: stopping a lane stops its whole process tree; a builder that left the lane's process group (setsid) is signalled by pid
272
+ const tree = existsSync(procDir) ? descendantPids(n, { procDir }) : [];
273
+ let ok;
274
+ try { kill(-n, "SIGTERM"); ok = true; } catch { try { kill(n, "SIGTERM"); ok = true; } catch (e) { ok = e?.code === "ESRCH"; } }
275
+ for (const c of tree) { try { kill(c, "SIGTERM"); } catch { /* gone */ } }
276
+ return ok;
247
277
  }
248
278
 
249
279
  /**
@@ -389,6 +419,9 @@ export async function requiredChecksRead({ gh, repo, lane }) {
389
419
 
390
420
  export const requiredChecksFor = async (opts) => (await requiredChecksRead(opts)).checks;
391
421
 
422
+ /** Command-failure messages keep short args verbatim and replace any longer than 200 chars with its length, so stderr stays visible. */
423
+ export const elideArgs = (args) => (args ?? []).map((a) => { const t = String(a); return t.length > 200 ? `<${t.length} chars>` : t; }).join(" ");
424
+
392
425
  /** #5592: stdout cap of a lane-path git/gh/docker call; output past it is cut, never an error. */
393
426
  export const EXEC_CAPPED_BYTES = 100 * 1024 * 1024;
394
427
  /**
@@ -414,7 +447,8 @@ export function execCapped(bin, args, { cwd, env, timeout = 120000, cap = EXEC_C
414
447
  if (timer) clearTimeout(timer);
415
448
  const out = Buffer.concat(chunks).toString("utf8") + (cut ? `\n[forgedock: output truncated at ${cap} bytes]\n` : "");
416
449
  if (cut || code === 0) return res(out);
417
- const e = new Error(`Command failed: ${bin} ${args.join(" ")}${timedOut ? " (timed out)" : ""}\n${err}`);
450
+ // 2026-11-26: a long argument (a --body of a FORGE:CONTRACT) filled the recorded detail and hid stderr, the actual reason
451
+ const e = new Error(`Command failed: ${bin} ${elideArgs(args)}${timedOut ? " (timed out)" : ""}\n${err}`);
418
452
  Object.assign(e, { code: timedOut ? null : code, signal, killed: timedOut, stdout: out, stderr: err });
419
453
  rej(e);
420
454
  });
@@ -501,11 +535,11 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
501
535
  * #5820: the scripts/ci-local plan of the lane's change (CI definitions from the base ref plus the lane's edits, change
502
536
  * scoped), in a child process so the yq calls never block the lane. Rejects with ci-local's DEGRADED reason (no yq).
503
537
  */
504
- async ciLocalPlan({ repo: wt, base, baseBranch, files = [] }) {
538
+ async ciLocalPlan({ repo: wt, base, baseBranch, releaseBranch = "", files = [] }) {
505
539
  const list = join(wt, ".forge-lean", "ci-precheck", "files.txt");
506
540
  mkdirSync(dirname(list), { recursive: true }); writeFileSync(list, `${files.join("\n")}\n`);
507
541
  try {
508
- const { stdout } = await pexec(process.execPath, [script("ci-local/cli.mjs"), "plan", "--repo", wt, "--base", base, "--base-branch", baseBranch, "--files-from", list, "--json"], { cwd: wt, timeout: 120000, maxBuffer: 64 * 1024 * 1024 });
542
+ const { stdout } = await pexec(process.execPath, [script("ci-local/cli.mjs"), "plan", "--repo", wt, "--base", base, "--base-branch", baseBranch, ...(releaseBranch ? ["--release-branch", releaseBranch] : []), "--files-from", list, "--json"], { cwd: wt, timeout: 120000, maxBuffer: 64 * 1024 * 1024 });
509
543
  return JSON.parse(String(stdout));
510
544
  } catch (e) {
511
545
  const why = /CI_LOCAL_RESULT: DEGRADED reason=(.*)/.exec(String(e?.stdout ?? ""))?.[1] ?? String(e?.stderr || e?.message || e).split("\n")[0];
@@ -696,22 +730,6 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
696
730
  return { base: m[1], head: m[2], ...(m[3] ? { pristine: m[3] } : {}), ...(headOutput != null ? { headOutput } : {}), ...(baseOutput != null ? { baseOutput } : {}) }; // #5544: pristine only when the base's own test version failed
697
731
  } catch { return null; } finally { if (outDir) rmSync(outDir, { recursive: true, force: true }); }
698
732
  },
699
- /**
700
- * The target repo's own docs-move-with-code rule, when it has one (scripts/check-devdocs-freshness.sh, forge#4185),
701
- * over base...HEAD in cwd. null when the repo has no such script or it cannot run (exit 2+, timeout): never blocks.
702
- * Otherwise {ok, output} with the script's stdout+stderr (exit 0 = ok, exit 1 = stale docs).
703
- */
704
- async docsFreshness({ cwd, base }) {
705
- const s = join(cwd, "scripts", "check-devdocs-freshness.sh");
706
- if (!existsSync(s)) return null;
707
- try {
708
- const r = await pexec("bash", [s, base], { cwd, timeout: 60000, maxBuffer: 4 * 1024 * 1024, env: { ...process.env, PR_BODY: "" } });
709
- return { ok: true, output: String(r.stdout ?? "") };
710
- } catch (e) {
711
- if (e?.code !== 1) return null;
712
- return { ok: false, output: `${e.stdout ?? ""}${e.stderr ?? ""}`.slice(0, 6000) };
713
- }
714
- },
715
733
  /** #5825: is the lane folder a worktree of this repo (toplevel + common dir), and moving aside a folder that is not. */
716
734
  confine: { verify: ({ wt, cwd }) => verifyLaneWorktree({ git: run("git"), exists: async (p) => existsSync(p), wt, cwd }), quarantine: async ({ wt }) => quarantineDir(wt) },
717
735
  /** #4162: processes left running inside a lane worktree (Linux /proc). */
@@ -0,0 +1,35 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #6091: a lane held on env.engine_skew is re-admitted by the engine of the agent that will run it, not the orchestrator's.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { orchestrate } from "./orchestrate.mjs";
7
+
8
+ const SKEW = { terminalReason: "needs-human", code: "recurrence.design_missing", detail: "gate fired", engineVersion: "1.66.0" };
9
+ const MERGED = { terminalReason: "merged", pr: 9 };
10
+ const run = ({ agentVersion, script }) => {
11
+ let t = 1_000_000, k = 0;
12
+ const calls = [];
13
+ return orchestrate({ issues: [1], parallel: 1, readBody: async () => "", now: () => t, pollMs: 1000, version: "1.67.0",
14
+ sleep: async (ms) => { t += Math.max(1, Number(ms) || 0); },
15
+ envHold: { version: () => "1.67.0", maxMs: 120_000, watchMs: 30_000, agentVersion: () => agentVersion(calls.length) },
16
+ runOne: async (n) => { calls.push(n); t += 1000; return script[Math.min(k++, script.length - 1)]; },
17
+ remote: { max: 2, isRemote: () => true, admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0 } })
18
+ .then((rows) => ({ rows, calls }));
19
+ };
20
+
21
+ describe("#6091 engine-held re-admission follows the agent's engine", () => {
22
+ it("stays held while the only agent is still on the old engine", async () => {
23
+ const { rows, calls } = await run({ agentVersion: () => "1.66.0", script: [SKEW, MERGED] });
24
+ assert.equal(calls.length, 1, "not relaunched onto the old agent");
25
+ assert.equal(rows[0].outcome, "held");
26
+ assert.equal(rows[0].code, "env.engine_skew");
27
+ assert.equal(rows[0].engineVersion, "1.66.0", "the engine that ran stays on the row");
28
+ });
29
+
30
+ it("is re-admitted once the agent upgrades to the needed engine", async () => {
31
+ const { rows, calls } = await run({ agentVersion: (n) => (n >= 1 ? "1.67.1" : "1.66.0"), script: [SKEW, MERGED] });
32
+ assert.deepEqual(calls, [1, 1]);
33
+ assert.equal(rows[0].outcome, "merged");
34
+ });
35
+ });