forgedock 1.61.1 → 1.62.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 (134) hide show
  1. package/bin/config-schema.mjs +10 -1
  2. package/bin/engine/outcome-codes.mjs +4 -0
  3. package/bin/engine-cli.mjs +160 -18
  4. package/bin/env/env.mjs +6 -4
  5. package/bin/forge-home-check.mjs +91 -0
  6. package/bin/forgedock.mjs +50 -7
  7. package/bin/gc.mjs +2 -0
  8. package/bin/hooks/pre-tool-use.mjs +4 -0
  9. package/bin/journey.mjs +55 -5
  10. package/bin/lean/admission.mjs +16 -5
  11. package/bin/lean/batch-health.mjs +55 -16
  12. package/bin/lean/batch-health.test.mjs +67 -1
  13. package/bin/lean/batch.mjs +8 -0
  14. package/bin/lean/batch.test.mjs +5 -0
  15. package/bin/lean/ceiling.mjs +20 -0
  16. package/bin/lean/ceiling.test.mjs +33 -2
  17. package/bin/lean/ci-gate.mjs +240 -0
  18. package/bin/lean/ci-gate.test.mjs +227 -0
  19. package/bin/lean/ci-precheck.mjs +178 -0
  20. package/bin/lean/ci-precheck.test.mjs +149 -0
  21. package/bin/lean/conformance.mjs +118 -20
  22. package/bin/lean/conformance.test.mjs +193 -3
  23. package/bin/lean/context.test.mjs +7 -6
  24. package/bin/lean/dag.mjs +128 -0
  25. package/bin/lean/dag.test.mjs +131 -0
  26. package/bin/lean/decisions.mjs +5 -4
  27. package/bin/lean/decisions.test.mjs +11 -0
  28. package/bin/lean/delguard.mjs +84 -0
  29. package/bin/lean/delguard.test.mjs +104 -0
  30. package/bin/lean/depcache.mjs +125 -17
  31. package/bin/lean/depcache.test.mjs +111 -0
  32. package/bin/lean/design-gate.mjs +5 -5
  33. package/bin/lean/design-gate.test.mjs +14 -0
  34. package/bin/lean/effects.mjs +81 -7
  35. package/bin/lean/execution.mjs +81 -15
  36. package/bin/lean/execution.test.mjs +156 -3
  37. package/bin/lean/forgedock-lane-workflow.test.mjs +35 -0
  38. package/bin/lean/guardgate.mjs +30 -7
  39. package/bin/lean/guardgate.test.mjs +44 -1
  40. package/bin/lean/guards.test.mjs +1 -1
  41. package/bin/lean/heavy.test.mjs +87 -0
  42. package/bin/lean/hotarea.mjs +73 -0
  43. package/bin/lean/hotarea.test.mjs +73 -0
  44. package/bin/lean/issuewatch-reconcile.mjs +20 -1
  45. package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
  46. package/bin/lean/lanecheck.mjs +27 -3
  47. package/bin/lean/lanecheck.test.mjs +47 -5
  48. package/bin/lean/laneconfine.mjs +83 -0
  49. package/bin/lean/laneconfine.test.mjs +113 -0
  50. package/bin/lean/lean.mjs +398 -91
  51. package/bin/lean/lean.test.mjs +792 -26
  52. package/bin/lean/live-reconcile.mjs +169 -0
  53. package/bin/lean/live-reconcile.test.mjs +176 -0
  54. package/bin/lean/orchestrate-envhold.test.mjs +245 -0
  55. package/bin/lean/orchestrate-hostfallback.test.mjs +39 -0
  56. package/bin/lean/orchestrate.mjs +207 -17
  57. package/bin/lean/outcomeevidence.mjs +104 -0
  58. package/bin/lean/outcomeevidence.test.mjs +78 -0
  59. package/bin/lean/page-capture.mjs +68 -0
  60. package/bin/lean/page-capture.test.mjs +44 -0
  61. package/bin/lean/pagegate.mjs +46 -7
  62. package/bin/lean/pagegate.test.mjs +66 -1
  63. package/bin/lean/postdeploy-check.mjs +18 -4
  64. package/bin/lean/postdeploy-check.test.mjs +32 -1
  65. package/bin/lean/prefilter.mjs +36 -4
  66. package/bin/lean/prefilter.test.mjs +31 -1
  67. package/bin/lean/preflight.mjs +22 -0
  68. package/bin/lean/preflight.test.mjs +19 -1
  69. package/bin/lean/probe.mjs +18 -0
  70. package/bin/lean/probe.test.mjs +40 -0
  71. package/bin/lean/prompts.mjs +41 -4
  72. package/bin/lean/recovery.test.mjs +20 -0
  73. package/bin/lean/recurrence.mjs +133 -0
  74. package/bin/lean/recurrence.test.mjs +99 -0
  75. package/bin/lean/release-config.mjs +2 -1
  76. package/bin/lean/release-config.test.mjs +18 -0
  77. package/bin/lean/release-control.mjs +4 -2
  78. package/bin/lean/release-control.test.mjs +15 -0
  79. package/bin/lean/release-merge-hold.mjs +65 -0
  80. package/bin/lean/release-merge-hold.test.mjs +69 -0
  81. package/bin/lean/release-review.mjs +26 -9
  82. package/bin/lean/release-review.test.mjs +53 -0
  83. package/bin/lean/release-status.mjs +3 -1
  84. package/bin/lean/release-status.test.mjs +11 -0
  85. package/bin/lean/release.test.mjs +26 -1
  86. package/bin/lean/render.mjs +8 -7
  87. package/bin/lean/repro-output.test.mjs +45 -0
  88. package/bin/lean/routing.mjs +49 -0
  89. package/bin/lean/routing.test.mjs +54 -1
  90. package/bin/lean/run-issue-placement.test.mjs +30 -1
  91. package/bin/lean/sandbox-actions.mjs +121 -0
  92. package/bin/lean/sandbox-actions.test.mjs +94 -0
  93. package/bin/lean/sandbox-provider.contract.test.mjs +22 -1
  94. package/bin/lean/sandbox-remote.mjs +3 -1
  95. package/bin/lean/schedd-health.mjs +14 -2
  96. package/bin/lean/schedd-health.test.mjs +13 -0
  97. package/bin/lean/schedd.mjs +43 -17
  98. package/bin/lean/schedd.test.mjs +61 -1
  99. package/bin/lean/toolchain.mjs +16 -6
  100. package/bin/lean/toolplace.mjs +12 -0
  101. package/bin/lean/weakguard.mjs +105 -0
  102. package/bin/lean/weakguard.test.mjs +59 -0
  103. package/bin/lean/winspawn.mjs +61 -0
  104. package/bin/lean/winspawn.test.mjs +45 -0
  105. package/bin/lean/worktree.mjs +3 -1
  106. package/bin/lean/worktree.test.mjs +11 -0
  107. package/bin/pool/agent.mjs +215 -15
  108. package/bin/pool/cache-sweep.mjs +74 -0
  109. package/bin/pool/cli.mjs +11 -3
  110. package/bin/pool/docker.mjs +33 -2
  111. package/bin/pool/health.mjs +38 -0
  112. package/bin/pool/lane-tools.mjs +23 -4
  113. package/bin/pool/lane-tools.test.mjs +12 -1
  114. package/bin/pool/router.mjs +21 -3
  115. package/bin/runner.mjs +37 -0
  116. package/bin/splash-scene.mjs +356 -0
  117. package/bin/win-hide-children.mjs +114 -0
  118. package/commands/orchestrate.md +18 -27
  119. package/commands/review-pr-agents/infra.md +1 -0
  120. package/commands/review-pr-staging.md +2 -2
  121. package/docs/CONFIG.md +60 -3
  122. package/docs/OUTCOME-CODES.md +3 -0
  123. package/package.json +1 -1
  124. package/plugins/forgedock-splash/.claude-plugin/plugin.json +1 -1
  125. package/plugins/forgedock-splash/README.md +1 -1
  126. package/plugins/forgedock-splash/hooks/scene.ts +142 -8
  127. package/pool/README.md +6 -0
  128. package/pool/image/entrypoint.sh +1 -0
  129. package/scripts/acceptance-red-green.sh +8 -3
  130. package/scripts/acceptance-red-green.test.sh +8 -0
  131. package/scripts/check-spec-size.sh +3 -1
  132. package/scripts/gen-splash-scene.mjs +24 -0
  133. package/scripts/review-staging-pre.sh +8 -3
  134. package/scripts/review-staging-pre.test.sh +2 -0
@@ -14,11 +14,15 @@
14
14
  * a missing tool, another filesystem (EXDEV) or a failed install leaves the lane as it was before. A snapshot that fails
15
15
  * to link or repair falls back to a fresh install in the lane (status materialize-fallback, #4522); failed only when that
16
16
  * install fails too.
17
+ * #5819: nothing here ever walks, chmods or removes through a link. pnpm links workspace packages into node_modules (a junction
18
+ * on Windows): every walk recreates a link instead of entering it, a recursive removal unlinks it, and a directory that resolves
19
+ * inside the worktree but outside every node_modules/.venv is never removed. A failed publish or materialize then checks out
20
+ * any tracked file that went missing (result `restore`), so a checkpoint can never commit the loss.
17
21
  */
18
22
  import * as nodeFs from "node:fs";
19
23
  import { createHash } from "node:crypto";
20
24
  import { homedir, hostname } from "node:os";
21
- import { join, dirname } from "node:path";
25
+ import { join, dirname, basename, relative, resolve, isAbsolute } from "node:path";
22
26
  import { safeSegment } from "./ledger.mjs";
23
27
 
24
28
  export const depcacheRoot = (env = process.env) => String(env.FORGE_DEPCACHE_ROOT ?? "").trim() || join(homedir(), ".forge", "depcache");
@@ -170,7 +174,7 @@ function commands(d, py = null) {
170
174
  */
171
175
  export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = () => Date.now(), alive = pidAlive, host = hostname(), pid = process.pid,
172
176
  env: procEnv = process.env, installTimeoutMs = DEPCACHE_INSTALL_TIMEOUT_MS, lockWaitMs = DEPCACHE_INSTALL_TIMEOUT_MS, pollMs = 1000,
173
- sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
177
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)), platform = process.platform } = {}) {
174
178
  const disabled = () => String(procEnv.FORGE_DEPCACHE ?? "").trim() === "0";
175
179
  const api = {}; // filled at the end; the env-library hook in prepare() passes it on
176
180
  const store = (n) => join(root, STORES, n);
@@ -266,6 +270,68 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
266
270
  try { return { locked: true, value: await fn() }; } finally { try { fs.rmSync(path, { force: true }); } catch { /* best effort */ } }
267
271
  }
268
272
 
273
+ // ---- containment (#5819): never through a link, never a worktree path outside a dependency tree ----
274
+ const win = platform === "win32";
275
+ const real = (p) => { try { return fs.realpathSync(p); } catch { return null; } };
276
+ const same = (a, b) => (win ? a.toLowerCase() === b.toLowerCase() : a === b);
277
+ const inside = (p, dir) => { const r = relative(dir, p); return r === "" || (r.split(/[\\/]/)[0] !== ".." && !isAbsolute(r)); };
278
+ /** A path inside a dependency tree (some segment is node_modules or .venv). */
279
+ const depRel = (rel) => String(rel).split(/[\\/]/).some((x) => x === "node_modules" || x === ".venv");
280
+ let realMemo = { dir: null, real: null }; // the last parent resolved: a walk asks for siblings in a row
281
+ /**
282
+ * A symlink or junction. The dirent/lstat type decides on POSIX; on Windows a directory also counts when its real path is
283
+ * not its parent's real path plus its name (a junction a filesystem or Node version reports as a plain directory).
284
+ */
285
+ function linkish(p, ent = null) {
286
+ let dir;
287
+ if (ent) { if (ent.isSymbolicLink()) return true; dir = ent.isDirectory(); }
288
+ else { try { const st = fs.lstatSync(p); if (st.isSymbolicLink()) return true; dir = st.isDirectory(); } catch { return false; } }
289
+ if (!win || !dir) return false;
290
+ const parent = dirname(p);
291
+ if (parent !== realMemo.dir) realMemo = { dir: parent, real: real(parent) };
292
+ const rp = real(p), rd = realMemo.real;
293
+ return !rp || !rd || !same(rp, join(rd, basename(p)));
294
+ }
295
+ /** Refuse a directory whose real path is inside `protect` (the worktree) but outside every dependency tree. */
296
+ function guardDep(p, protect, rw = protect ? real(protect) : null) {
297
+ const rp = real(p);
298
+ if (rp && rw && inside(rp, rw) && !depRel(relative(rw, rp))) {
299
+ throw Object.assign(new Error(`refusing to remove ${p}: it resolves to ${rp}, a worktree path outside every node_modules/.venv`), { code: "EFORGE_PROTECTED" });
300
+ }
301
+ }
302
+ /** Remove the link itself (a Windows junction may need rmdir), never its target. */
303
+ const dropLink = (p) => { try { fs.unlinkSync(p); } catch (e) { if (e?.code === "ENOENT") return; fs.rmdirSync(p); } };
304
+ const dropFile = (p) => {
305
+ try { fs.unlinkSync(p); } catch (e) {
306
+ if (e?.code === "ENOENT") return;
307
+ if (e?.code !== "EPERM" && e?.code !== "EACCES") throw e;
308
+ fs.chmodSync(p, 0o666); fs.unlinkSync(p); // a read-only snapshot file on Windows
309
+ }
310
+ };
311
+ /**
312
+ * Recursive removal that never follows a link (unlinks it) and never removes a directory resolving to a worktree path outside a
313
+ * dependency tree (`protect`: the worktree; checked at the root, and at every real directory on Windows).
314
+ */
315
+ function safeRm(p, protect = null) {
316
+ let st;
317
+ realMemo = { dir: null, real: null };
318
+ try { st = fs.lstatSync(p); } catch { return; }
319
+ if (st.isSymbolicLink() || (st.isDirectory() && linkish(p))) { dropLink(p); return; }
320
+ if (!st.isDirectory()) { dropFile(p); return; }
321
+ const rw = protect ? real(protect) : null;
322
+ guardDep(p, protect, rw);
323
+ const walk = (d) => {
324
+ for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
325
+ const q = join(d, ent.name);
326
+ if (linkish(q, ent)) dropLink(q);
327
+ else if (ent.isDirectory()) { if (win) guardDep(q, protect, rw); walk(q); }
328
+ else dropFile(q);
329
+ }
330
+ fs.rmdirSync(d);
331
+ };
332
+ walk(p);
333
+ }
334
+
269
335
  // ---- trees ----
270
336
  const boundary = (p) => new RegExp(p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "(?=$|[/\\\\'\"\\s:;])", "g");
271
337
  /** Hardlink a file; across filesystems (EXDEV, #4909) copy it with its mode so the cache is reused instead of reinstalled. */
@@ -282,16 +348,33 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
282
348
  * shared inode, or the open-for-write fails with EACCES and the lane falls back to a full install.
283
349
  */
284
350
  const mutableState = (rel, name) => (rel === "" && /^\.(modules\.yaml|pnpm-workspace-state.*\.json|package-lock\.json|yarn-state\.yml)$/.test(name)) || (rel === ".pnpm" && name === "lock.yaml");
285
- /** Hardlink `src` into `dst` (copy on EXDEV); symlinks recreated; files in bin dirs that name `from` are copied with `to` instead. */
286
- function linkTree(src, dst, { from = null, to = null, binDir = () => false } = {}) {
351
+ /**
352
+ * Recreate the link `sp` -> `t` at `dp`. #5807/#5819: without the symlink privilege on Windows (EPERM) a directory target
353
+ * becomes a junction (absolute, resolved against `at`, where `dp` finally lives) and a file target a hardlink or copy of the
354
+ * file; the target itself is never entered, moved or copied as a tree.
355
+ */
356
+ function relink(sp, dp, t, at) {
357
+ try { fs.symlinkSync(t, dp); return; } catch (e) { if (!(win && e?.code === "EPERM")) throw e; }
358
+ const fileAt = isAbsolute(t) ? t : resolve(dirname(sp), t);
359
+ let st = null;
360
+ try { st = fs.statSync(fileAt); } catch { /* dangling: a junction to where it will be */ }
361
+ if (st?.isFile()) { linkOrCopy(fileAt, dp); return; }
362
+ fs.symlinkSync(isAbsolute(t) ? t : resolve(dirname(at), t), dp, "junction");
363
+ }
364
+ /**
365
+ * Hardlink `src` into `dst` (copy on EXDEV); links recreated (never entered, #5819); files in bin dirs that name `from` are copied
366
+ * with `to` instead. `at`: where `dst` finally lives (a publish builds in a tmp dir renamed into place), for junction targets.
367
+ */
368
+ function linkTree(src, dst, { from = null, to = null, binDir = () => false, at = dst } = {}) {
287
369
  const re = from && to && from !== to ? boundary(from) : null;
370
+ realMemo = { dir: null, real: null };
288
371
  const walk = (s, d, rel) => {
289
372
  fs.mkdirSync(d, { recursive: true });
290
373
  for (const ent of fs.readdirSync(s, { withFileTypes: true })) {
291
374
  const sp = join(s, ent.name), dp = join(d, ent.name), r = rel ? `${rel}/${ent.name}` : ent.name;
292
- if (ent.isSymbolicLink()) {
375
+ if (linkish(sp, ent)) {
293
376
  const t = String(fs.readlinkSync(sp));
294
- fs.symlinkSync(re ? t.replace(re, to) : t, dp);
377
+ relink(sp, dp, re ? t.replace(re, to) : t, join(at, r));
295
378
  } else if (ent.isDirectory()) walk(sp, dp, r);
296
379
  else if (ent.isFile()) {
297
380
  if (re && binDir(rel)) {
@@ -313,6 +396,7 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
313
396
  function readOnly(dir) {
314
397
  for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
315
398
  const p = join(dir, ent.name);
399
+ if (linkish(p, ent)) continue; // #5819: never chmod through a link
316
400
  if (ent.isDirectory()) readOnly(p);
317
401
  else if (ent.isFile()) fs.chmodSync(p, fs.statSync(p).mode & 0o7555);
318
402
  }
@@ -321,7 +405,8 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
321
405
  const treesOf = (wt, d, pkgs) => (JS.has(d.eco) ? pkgs.map((p) => (dirname(p) === "." ? "node_modules" : `${dirname(p)}/node_modules`)) : [".venv"])
322
406
  .filter((t, i, a) => a.indexOf(t) === i && fs.existsSync(join(wt, t)));
323
407
  const binDirFor = (d) => (JS.has(d.eco) ? (rel) => rel.split("/").includes(".bin") : (rel) => rel === "bin");
324
- const rmTrees = (wt, trees) => { for (const t of trees) { try { fs.rmSync(join(wt, t), { recursive: true, force: true }); } catch { /* best effort */ } } };
408
+ /** #5819: only dependency trees, never through a link, never a worktree path outside a dependency tree. */
409
+ const rmTrees = (wt, trees) => { for (const t of trees) { if (!depRel(t)) continue; try { safeRm(join(wt, t), wt); } catch { /* best effort */ } } };
325
410
 
326
411
  /** #5590: the existing trees an install did not finish (no marker, a declared dependency missing, a venv without a working python). */
327
412
  function brokenTrees(wt, d, trees) {
@@ -340,22 +425,41 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
340
425
  function publish(wt, d, key, trees, snap) {
341
426
  const tmp = `${snap}.tmp-${pid}`;
342
427
  try {
343
- fs.rmSync(tmp, { recursive: true, force: true });
344
- for (const t of trees) linkTree(join(wt, t), join(tmp, t));
428
+ safeRm(tmp, wt);
429
+ for (const t of trees) linkTree(join(wt, t), join(tmp, t), { at: join(snap, t) });
345
430
  readOnly(tmp);
346
431
  fs.writeFileSync(join(tmp, "manifest.json"), JSON.stringify({ v: 1, eco: d.eco, key, prefix: wt, trees, created: now() }) + "\n");
347
432
  fs.writeFileSync(join(tmp, "last-used"), String(now()));
348
433
  try { fs.renameSync(tmp, snap); } catch (e) {
349
434
  if (!fs.existsSync(join(snap, "manifest.json"))) throw e;
350
- fs.rmSync(tmp, { recursive: true, force: true }); // another lane published first: never write into its snapshot
435
+ safeRm(tmp, wt); // another lane published first: never write into its snapshot
351
436
  }
352
437
  return null;
353
438
  } catch (e) {
354
- try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* best effort */ }
439
+ try { safeRm(tmp, wt); } catch { /* best effort */ }
355
440
  return e?.code === "EXDEV" ? "cache is on another filesystem than the worktree (EXDEV)" : `publish failed: ${msg(e)}`;
356
441
  }
357
442
  }
358
443
 
444
+ /**
445
+ * #5819: after a failed publish/materialize/install, check out every tracked file (outside node_modules/.venv) that is missing
446
+ * from the checkout `wt` belongs to. null: not a git checkout or nothing missing; else {restored, missing, sample} or {error}.
447
+ */
448
+ async function restoreTracked(wt) {
449
+ let top = "";
450
+ try { top = String(await exec("git", ["rev-parse", "--show-toplevel"], { cwd: wt, timeoutMs: 60000 })).trim().split("\n")[0]; } catch { return null; }
451
+ if (!top || !isAbsolute(top)) return null;
452
+ try {
453
+ const out = String(await exec("git", ["ls-files", "--deleted", "-z"], { cwd: top, timeoutMs: 60000 }));
454
+ const gone = [...new Set(out.split("\0").filter((p) => p && !/\n/.test(p) && !depRel(p)))].filter((p) => !present(join(top, p)));
455
+ if (!gone.length) return null;
456
+ for (let i = 0; i < gone.length; i += 200) await exec("git", ["checkout", "-q", "--", ...gone.slice(i, i + 200)], { cwd: top, timeoutMs: 120000 });
457
+ const left = gone.filter((p) => !present(join(top, p)));
458
+ return { restored: gone.length - left.length, missing: left.length, sample: gone.slice(0, 10) };
459
+ } catch (e) { return { error: msg(e) }; }
460
+ }
461
+ const failedRun = (r) => r.status === "failed" || r.status === "materialize-fallback" || (r.published === false && /^(publish failed|cache is on another filesystem)/.test(String(r.reason ?? "")));
462
+
359
463
  async function prepareOne(wt, keyRoot, d, laneEnv, publishSnap = true) {
360
464
  const t0 = now();
361
465
  let repaired = null;
@@ -467,11 +571,15 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
467
571
  const keyRoot = join(root, safeSegment(repoKey ?? "repo"));
468
572
  const out = [];
469
573
  for (const d of found) {
574
+ const at = d.dir ? join(wt, d.dir) : wt;
575
+ let r;
470
576
  try {
471
- const r = await prepareOne(d.dir ? join(wt, d.dir) : wt, keyRoot, d, laneEnv && typeof laneEnv === "object" ? laneEnv : undefined, publishSnap);
577
+ r = await prepareOne(at, keyRoot, d, laneEnv && typeof laneEnv === "object" ? laneEnv : undefined, publishSnap);
472
578
  const claimed = envHit && r.status === "skipped" && /already exists in the worktree$/.test(String(r.reason ?? ""));
473
- out.push(claimed ? { ...r, status: "hit", key: envHit.key, ms: r.ms + (out.some((x) => x.env) ? 0 : envHit.ms), reason: `env snapshot (${envHit.mode})`, env: true, dir: d.dir ?? "." } : { ...r, dir: d.dir ?? "." });
474
- } catch (e) { out.push({ status: "failed", eco: d.eco, key: null, ms: 0, reason: msg(e), dir: d.dir ?? "." }); }
579
+ r = claimed ? { ...r, status: "hit", key: envHit.key, ms: r.ms + (out.some((x) => x.env) ? 0 : envHit.ms), reason: `env snapshot (${envHit.mode})`, env: true, dir: d.dir ?? "." } : { ...r, dir: d.dir ?? "." };
580
+ } catch (e) { r = { status: "failed", eco: d.eco, key: null, ms: 0, reason: msg(e), dir: d.dir ?? "." }; }
581
+ if (failedRun(r)) { const restore = await restoreTracked(at); if (restore) r = { ...r, restore }; } // #5819
582
+ out.push(r);
475
583
  }
476
584
  return out;
477
585
  }
@@ -532,8 +640,8 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
532
640
  async function remove(entry) {
533
641
  const p = String(entry?.path ?? "");
534
642
  if (!p.startsWith(root + "/") || p.slice(root.length + 1).split("/").length !== 2) return false;
535
- if (entry.kind === "snapshot") return (await withLock(`${p}.lock`, async () => { fs.rmSync(p, { recursive: true, force: true }); return true; }, { wait: false })).locked;
536
- fs.rmSync(p, { recursive: true, force: true });
643
+ if (entry.kind === "snapshot") return (await withLock(`${p}.lock`, async () => { safeRm(p); return true; }, { wait: false })).locked; // #5819: never through a link
644
+ safeRm(p);
537
645
  return true;
538
646
  }
539
647
 
@@ -544,6 +652,6 @@ export function makeDepCache({ root = depcacheRoot(), exec, fs = nodeFs, now = (
544
652
  return removed;
545
653
  }
546
654
 
547
- return Object.assign(api, { env, prepare, describe, prune, scan, remove, root, linkTree, readOnly });
655
+ return Object.assign(api, { env, prepare, describe, prune, scan, remove, root, linkTree, readOnly, safeRm });
548
656
  }
549
657
 
@@ -5,6 +5,7 @@ import { describe, it } from "node:test";
5
5
  import assert from "node:assert/strict";
6
6
  import * as fs from "node:fs";
7
7
  import { mkdirSync, writeFileSync, readFileSync, existsSync, statSync, lstatSync, readlinkSync, readdirSync, symlinkSync, rmSync, renameSync } from "node:fs";
8
+ import { execFileSync } from "node:child_process";
8
9
  import { tmpDir } from "../tests/_tmp.mjs";
9
10
  import { join, dirname, relative } from "node:path";
10
11
  import { makeDepCache } from "./depcache.mjs";
@@ -688,3 +689,113 @@ describe("depcache (#5651): no silent fallback to an out-of-range default python
688
689
  assert.match(r.reason ?? "", /--no-root/);
689
690
  });
690
691
  });
692
+
693
+ describe("depcache (#5819): a failed publish or materialize never touches workspace package sources", () => {
694
+ const sh = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8" });
695
+ const SRC = Array.from({ length: 6 }, (_, i) => `packages/adapters/src/f${i}.ts`);
696
+ /** A pnpm workspace in a real git repo; node_modules ignored. */
697
+ const wsRepo = (base, name) => {
698
+ const wt = join(base, "wt", name);
699
+ mkdirSync(wt, { recursive: true });
700
+ put(join(wt, "package.json"), '{"name":"web","private":true}');
701
+ put(join(wt, "pnpm-workspace.yaml"), "packages:\n - packages/*\n");
702
+ put(join(wt, "pnpm-lock.yaml"), "lockfileVersion: 9\nlodash: 4.17.21\n");
703
+ put(join(wt, "packages/a/package.json"), '{"name":"a"}');
704
+ put(join(wt, "packages/adapters/package.json"), '{"name":"@scope/adapters"}');
705
+ for (const f of SRC) put(join(wt, f), `export const v = "${f}";\n`);
706
+ put(join(wt, ".gitignore"), "node_modules/\n");
707
+ sh(wt, "init", "-q"); sh(wt, "config", "user.email", "t@t"); sh(wt, "config", "user.name", "t");
708
+ sh(wt, "add", "-A"); sh(wt, "commit", "-q", "-m", "base");
709
+ return wt;
710
+ };
711
+ /** Real git; the fake pnpm, plus pnpm's link of the workspace package (absolute, as a Windows junction reads back). */
712
+ const wsExec = (f) => async (cmd, args, o = {}) => {
713
+ if (cmd === "git") return execFileSync("git", args, { cwd: o.cwd, encoding: "utf8" });
714
+ const out = await f.exec(cmd, args, o);
715
+ if (cmd === "pnpm" && !args.includes("--offline")) {
716
+ mkdirSync(join(o.cwd, "node_modules/@scope"), { recursive: true });
717
+ symlinkSync(join(o.cwd, "packages/adapters"), join(o.cwd, "node_modules/@scope/adapters"));
718
+ }
719
+ return out;
720
+ };
721
+ const eperm = () => Object.assign(new Error("EPERM: operation not permitted, symlink"), { code: "EPERM" });
722
+ /** Windows without the symlink privilege, where a junction reads as a plain directory (the worst case for a tree walk). */
723
+ const winFs = ({ junctions = true, extra = {} } = {}) => ({
724
+ ...fs,
725
+ readdirSync: (p, o) => {
726
+ const l = fs.readdirSync(p, o);
727
+ if (!o?.withFileTypes) return l;
728
+ return l.map((e) => {
729
+ if (!e.isSymbolicLink()) return e;
730
+ let dir = false;
731
+ try { dir = fs.statSync(join(p, e.name)).isDirectory(); } catch { /* dangling */ }
732
+ return dir ? { name: e.name, isSymbolicLink: () => false, isDirectory: () => true, isFile: () => false } : e;
733
+ });
734
+ },
735
+ symlinkSync: (t, p, type) => { if (type !== "junction" || !junctions) throw eperm(); return fs.symlinkSync(t, p); },
736
+ ...extra,
737
+ });
738
+ const clean = (wt) => sh(wt, "status", "--porcelain").trim();
739
+ const filesUnder = (dir) => { const out = []; const walk = (d) => { for (const e of readdirSync(d, { withFileTypes: true })) { const p = join(d, e.name); if (e.isDirectory()) walk(p); else out.push(p); } }; walk(dir); return out; };
740
+
741
+ it("publish: a link to a workspace package is recreated (a junction on EPERM), never entered, copied or chmodded", async () => {
742
+ const base = scratch(), root = join(base, "cache"), wt = wsRepo(base, "a");
743
+ const before = statSync(join(wt, SRC[0]));
744
+ const [r] = await makeDepCache({ root, exec: wsExec(fakeExec()), env: {}, fs: winFs(), platform: "win32", pollMs: 5 }).prepare({ wt, repoKey: "r" });
745
+ assert.equal(r.status, "miss-installed", JSON.stringify(r));
746
+ assert.equal(r.published, true, r.reason);
747
+ assert.equal(clean(wt), "", "every tracked file untouched");
748
+ assert.equal(statSync(join(wt, SRC[0])).mode, before.mode, "the source was not made read-only through a hardlink");
749
+ const [snap] = snapDirs(root, "pnpm");
750
+ assert.ok(lstatSync(join(snap, "node_modules/@scope/adapters")).isSymbolicLink(), "the snapshot holds a link, not the package");
751
+ const inos = new Set(SRC.map((f) => statSync(join(wt, f)).ino));
752
+ assert.deepEqual(filesUnder(snap).filter((p) => !lstatSync(p).isSymbolicLink() && inos.has(statSync(p).ino)), [], "no workspace source is hardlinked into the cache");
753
+ });
754
+
755
+ it("a publish that fails mid-way (EPERM, no junction either) leaves every tracked file and no tmp dir", async () => {
756
+ const base = scratch(), root = join(base, "cache"), wt = wsRepo(base, "a");
757
+ const [r] = await makeDepCache({ root, exec: wsExec(fakeExec()), env: {}, fs: winFs({ junctions: false }), platform: "win32", pollMs: 5 }).prepare({ wt, repoKey: "r" });
758
+ assert.equal(r.status, "miss-installed");
759
+ assert.equal(r.published, false);
760
+ assert.match(r.reason, /^publish failed: EPERM/);
761
+ assert.equal(clean(wt), "");
762
+ for (const f of SRC) assert.ok(existsSync(join(wt, f)), f);
763
+ assert.equal(r.restore, undefined, "nothing was missing");
764
+ assert.deepEqual(readdirSync(join(root, "r")).filter((n) => /\.tmp-/.test(n)), []);
765
+ assert.equal(snapDirs(root, "pnpm").length, 0);
766
+ });
767
+
768
+ it("tracked files that go missing during a failed publish are checked out again, with the evidence on the result", async () => {
769
+ const base = scratch(), root = join(base, "cache"), wt = wsRepo(base, "a");
770
+ let hit = false;
771
+ const destructive = { ...fs, linkSync: (s, d) => { if (!hit) { hit = true; rmSync(join(wt, "packages/adapters/src"), { recursive: true }); throw eperm(); } return fs.linkSync(s, d); } };
772
+ const [r] = await makeDepCache({ root, exec: wsExec(fakeExec()), env: {}, fs: destructive, pollMs: 5 }).prepare({ wt, repoKey: "r" });
773
+ assert.equal(r.published, false);
774
+ assert.deepEqual({ restored: r.restore.restored, missing: r.restore.missing }, { restored: SRC.length, missing: 0 });
775
+ assert.deepEqual([...r.restore.sample].sort(), [...SRC].sort());
776
+ assert.equal(clean(wt), "", "the worktree is whole again before the lane goes on");
777
+ });
778
+
779
+ it("materialize: a failed repair removes the linked trees without following the workspace link", async () => {
780
+ const base = scratch(), root = join(base, "cache");
781
+ const a = wsRepo(base, "a");
782
+ const [ra] = await makeDepCache({ root, exec: wsExec(fakeExec()), env: {}, pollMs: 5 }).prepare({ wt: a, repoKey: "r" });
783
+ assert.equal(ra.published, true, ra.reason);
784
+ const b = wsRepo(base, "b");
785
+ const [rb] = await makeDepCache({ root, exec: wsExec(fakeExec({ failRepair: true })), env: {}, fs: winFs(), platform: "win32", pollMs: 5 }).prepare({ wt: b, repoKey: "r" });
786
+ assert.equal(rb.status, "materialize-fallback", JSON.stringify(rb));
787
+ for (const wt of [a, b]) { assert.equal(clean(wt), "", wt); for (const f of SRC) assert.ok(existsSync(join(wt, f)), `${wt} ${f}`); }
788
+ });
789
+
790
+ it("safeRm unlinks links, never their targets, and refuses a worktree path outside node_modules/.venv", async () => {
791
+ const base = scratch(), wt = wsRepo(base, "a");
792
+ const cache = makeDepCache({ root: join(base, "cache"), exec: wsExec(fakeExec()), env: {}, fs: winFs(), platform: "win32" });
793
+ mkdirSync(join(wt, "node_modules/@scope"), { recursive: true });
794
+ symlinkSync(join(wt, "packages/adapters"), join(wt, "node_modules/@scope/adapters"));
795
+ put(join(wt, "node_modules/x/index.js"), "x");
796
+ assert.throws(() => cache.safeRm(join(wt, "packages"), wt), (e) => e.code === "EFORGE_PROTECTED");
797
+ cache.safeRm(join(wt, "node_modules"), wt);
798
+ assert.ok(!existsSync(join(wt, "node_modules")));
799
+ assert.equal(clean(wt), "");
800
+ });
801
+ });
@@ -111,11 +111,11 @@ export function visualGate({ cfg = null, files = [], specs = false, sources = {}
111
111
  // #5648: `changes` {file: pageChange class}: generated files are exempt, a copy-only edit needs the visual check but no spec
112
112
  const routeFiles = designFiles(files, cfg).filter((f) => changes[f] !== "generated");
113
113
  const routes = routeFiles.map((file) => ({ file, route: routeOf(file), page: PAGE_ENTRY_RE.test(file) }));
114
- const rows = [], add = (kind, route, detail) => rows.push({ kind, route, detail });
114
+ const rows = [], add = (kind, route, detail, file) => rows.push({ kind, route, detail, file });
115
115
  for (const r of routes) {
116
116
  const spec = typeof specs === "object" && specs !== null ? Boolean(specs[r.route] ?? specs[r.file]) : Boolean(specs);
117
117
  const copy = changes[r.file] === "copy";
118
- if (r.page && !spec && !copy) add("design_spec_missing", r.route, `${r.file} has no approved FORGE:DESIGN_SPEC (label ${cfg.specLabel}): run /design first`);
118
+ if (r.page && !spec && !copy) add("design_spec_missing", r.route, `${r.file} has no approved FORGE:DESIGN_SPEC (label ${cfg.specLabel}): run /design first`, r.file);
119
119
  if (r.page && !copy && sources[r.file] != null) {
120
120
  for (const f of critiqueMarkup(sources[r.file])) if (f.severity === "block") add("visual_critique_failed", r.route, `${r.file}: ${f.id}: ${f.detail}`);
121
121
  }
@@ -133,12 +133,12 @@ export function visualGate({ cfg = null, files = [], specs = false, sources = {}
133
133
  }
134
134
 
135
135
  /** Lane precheck rows (conformance.unimplemented) for the diff's user-visible routes; [] unless design.routes is set and gate is blocking. */
136
- export function designFailures({ cfg = null, files = [], specs = false, readFile = () => "", added = null, diff = "" } = {}) {
136
+ export function designFailures({ cfg = null, files = [], specs = false, readFile = () => "", added = null, diff = "", covered = [], bugFix = false } = {}) {
137
137
  if (!designOn(cfg) || cfg.gate !== "blocking") return [];
138
138
  const sources = {}, changes = {};
139
- for (const f of designFiles(files, cfg)) changes[f] = pageChange(f, { added, diff, readFile }); // no added list: "new", fail closed
139
+ for (const f of designFiles(files, cfg)) changes[f] = pageChange(f, { added, diff, readFile, bugFix }); // no added list: "new", fail closed
140
140
  for (const f of designPages(files, cfg)) sources[f] = String(readFile(f) ?? "");
141
- return visualGate({ cfg, files, specs, sources, changes }).rows.map((r) => ({ code: OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, kind: r.kind, detail: r.detail }));
141
+ return visualGate({ cfg, files, specs, sources, changes }).rows.filter((r) => !(r.kind === "design_spec_missing" && covered.includes(r.file))).map((r) => ({ code: OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED, kind: r.kind, detail: r.detail })); // #5729: `covered`: files the page gate already reports page_design_missing for
142
142
  }
143
143
 
144
144
  /** Markdown for the FORGE:VISUAL_GATE comment (review-pr-staging). Rendered screenshots are listed by path. */
@@ -188,3 +188,17 @@ describe("copy-only edits to existing pages (#5648)", () => {
188
188
  assert.equal(designGate({ files: [P], cfg }).route, true);
189
189
  });
190
190
  });
191
+
192
+ describe("designFailures dedupe against the page gate (#5729)", () => {
193
+ const page = "web/src/app/(site)/pricing/page.tsx";
194
+ const diff = `+++ b/${page}\n-<a href="/x">x</a>\n+<a href="/y">x</a>\n`;
195
+ const base = { cfg, files: [page], added: [], diff, readFile: () => "line\n".repeat(60) };
196
+ it("href-only edit is exempt from design_spec_missing", () => {
197
+ assert.ok(!designFailures(base).some((r) => r.kind === "design_spec_missing"));
198
+ });
199
+ it("a rewrite keeps one design_spec_missing unless the page gate covers the file", () => {
200
+ const rw = { ...base, diff: `+++ b/${page}\n+<div className="x">hi</div>\n` };
201
+ assert.equal(designFailures(rw).filter((r) => r.kind === "design_spec_missing").length, 1);
202
+ assert.equal(designFailures({ ...rw, covered: [page] }).filter((r) => r.kind === "design_spec_missing").length, 0);
203
+ });
204
+ });
@@ -6,6 +6,7 @@ import { readFileSync, appendFileSync, mkdirSync, mkdtempSync, statSync, existsS
6
6
  import { homedir, hostname, freemem, loadavg, cpus, tmpdir } from "node:os";
7
7
  import { promises as fsp } from "node:fs";
8
8
  import { dirname, join, resolve, sep } from "node:path";
9
+ import { resolveSpawn } from "./winspawn.mjs";
9
10
  import { fileURLToPath } from "node:url";
10
11
  import { randomBytes } from "node:crypto";
11
12
  import { runCliBackendAsync, resolveClaudeCliBinary, getClaudeCliCapabilities, buildLeanSessionFlags, buildReadOnlyToolFlags, sanitizeCliModel } from "../runner.mjs";
@@ -14,7 +15,9 @@ import { makeProjector } from "../engine/projector.mjs";
14
15
  import { makeLedger, countLiveLanes, ledgerRoot } from "./ledger.mjs";
15
16
  import { makeDepCache } from "./depcache.mjs";
16
17
  import { makeHeavyIo } from "./heavy.mjs";
17
- import { diskLow } from "./admission.mjs";
18
+ import { diskLow, ADMISSION_DEFAULTS } from "./admission.mjs";
19
+ import { writeAtomic } from "./batch.mjs";
20
+ import { schedDir } from "./sched.mjs";
18
21
  import { gatherContextFacts } from "./context.mjs";
19
22
  import { makePitfallStore } from "./pitfalls.mjs";
20
23
  import { enumeratingTests, missingEntries } from "./enumerating.mjs";
@@ -29,6 +32,7 @@ import { parseVersioned } from "./seqversioned.mjs";
29
32
  import { followupMap } from "./conformance.mjs";
30
33
  import { toolStats } from "./toolstats.mjs";
31
34
  import { detectApiShape } from "./apishape.mjs";
35
+ import { verifyLaneWorktree, quarantineDir } from "./laneconfine.mjs";
32
36
 
33
37
  /** #5531: children started by this process's gh/script helpers still running; the schedd kills them on close so none outlives the daemon. */
34
38
  const liveChildren = new Set();
@@ -39,7 +43,8 @@ export function killTrackedChildren(signal = "SIGKILL") {
39
43
  return n;
40
44
  }
41
45
  export const trackedChildCount = () => liveChildren.size;
42
- const pexec = (bin, args, opts) => new Promise((res, rej) => {
46
+ const pexec = (bin0, args0, opts) => new Promise((res, rej) => {
47
+ const { bin, args } = resolveSpawn(bin0, args0, { env: opts?.env ?? process.env }); // #5799: npm .cmd shims on Windows
43
48
  const child = execFile(bin, args, opts, (err, stdout, stderr) => {
44
49
  liveChildren.delete(child);
45
50
  if (err) { err.stdout = stdout; err.stderr = stderr; rej(err); } else res({ stdout, stderr });
@@ -132,7 +137,7 @@ export const leanSettingsFlags = ({ subagentModel = null, reread = false, guard
132
137
  export function makeLeanRunner({ runCli = runCliBackendAsync, probe = systemdRunAvailable, subagentModel = null, sandboxed = inSandbox() } = {}) {
133
138
  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 }) => {
134
139
  // #5205: a rotation relaunch pins the real claude past the tokenbaton shim; absent, the usual resolution
135
- const bin = pinnedBin || resolveClaudeCliBinary(cwd) || "claude";
140
+ const bin = pinnedBin || resolveClaudeCliBinary(cwd) || resolveSpawn("claude", []).bin; // win32: a probe miss must not fall back to a bare name (spawn ENOENT)
136
141
  const caps = getClaudeCliCapabilities(cwd);
137
142
  // #4391: custom subagents (the explorer) for the builder session; null leaves argv unchanged
138
143
  // #5516: fullSession keeps slash commands/Skill/Task (the release test gate invokes /test-gate); otherwise the lean minimal group
@@ -146,7 +151,8 @@ export function makeLeanRunner({ runCli = runCliBackendAsync, probe = systemdRun
146
151
  idleMs, maxMs, stream: idleMs > 0, control, onSpawn, session, busy, busyMs, onIdleExtend, ...(contextMax > 0 ? { contextMax } : {}), ...(turnMax > 0 ? { turnMax } : {}), wrap: probe() ? (b, a) => wrapLaneLimits(b, a, laneLimits) : null });
147
152
  // #4395: a resumed session's first turn carries the prior history, so only a fresh session reports a baseline.
148
153
  return { text: r.text, sessionId: r.sessionId, usage: r.usage, costUsd: r.costUsd, durationMs: r.durationMs, turns: r.turns, model: r.cliModel ?? "default",
149
- baselineTokens: resume ? null : (r.baselineTokens ?? null), tools: toolStats(r.toolUses) }; // #4410: tool calls per turn, re-reads
154
+ baselineTokens: resume ? null : (r.baselineTokens ?? null), tools: toolStats(r.toolUses), // #4410: tool calls per turn, re-reads
155
+ endTokens: r.endTokens ?? null, toolUses: Array.isArray(r.toolUses) ? r.toolUses : null }; // #5812: the route hand-off sizes the plan session and lists what it read
150
156
  };
151
157
  }
152
158
 
@@ -261,9 +267,54 @@ export function guardHeavyDisk(heavy, { host, minFreeGb = () => null, gc = async
261
267
  };
262
268
  }
263
269
 
270
+ /**
271
+ * Lane ramp stamps (#5845): lanes are separate processes, so the lanes admitted within the ramp window are files in
272
+ * `schedDir()/lane-ramp/` (one `<pid>.json` per lane, `{pid, at, mb}`, so concurrent lanes never overwrite each other),
273
+ * plus `peaks.json` (recent peak RSS in MB, newest last). Every read fails open to null/0 and drops dead or expired stamps.
274
+ */
275
+ const PEAKS_KEPT = 20;
276
+ export function makeRampStore({ dir = join(schedDir(), "lane-ramp"), now = () => Date.now(), pid = process.pid, defaultMb = ADMISSION_DEFAULTS.lane_mem_mb } = {}) {
277
+ const live = (rampS) => {
278
+ const out = [];
279
+ for (const f of readdirSync(dir)) {
280
+ if (!/^\d+\.json$/.test(f)) continue;
281
+ const file = join(dir, f);
282
+ try {
283
+ const st = JSON.parse(readFileSync(file, "utf8"));
284
+ const stale = now() - st.at >= Math.max(rampS, 1) * 1000 * 2; // kept for one extra window so a slightly longer ramp still sees it
285
+ if (stale || !pidAlive(st.pid)) { rmSync(file, { force: true }); continue; }
286
+ if (now() - st.at < rampS * 1000) out.push(st);
287
+ } catch { /* unreadable stamp: ignore */ }
288
+ }
289
+ return out;
290
+ };
291
+ const peaks = () => { try { return (JSON.parse(readFileSync(join(dir, "peaks.json"), "utf8")).peaks ?? []).filter(Number.isFinite); } catch { return []; } };
292
+ const footprint = () => {
293
+ const p = peaks();
294
+ if (!p.length) return defaultMb;
295
+ const sorted = [...p].sort((a, b) => a - b);
296
+ return Math.max(defaultMb, Math.ceil(sorted[Math.floor(sorted.length / 2)]), Math.ceil(sorted[sorted.length - 1] * 0.9)); // conservative: near the max, never under the default
297
+ };
298
+ const guard = (fn, fallback) => (...a) => { try { return fn(...a); } catch { return fallback; } };
299
+ return {
300
+ rampingMb: guard((rampS) => live(rampS).reduce((t, st) => t + (Number(st.mb) > 0 ? Number(st.mb) : defaultMb), 0), null),
301
+ rampingLanes: guard((rampS) => live(rampS).length, null),
302
+ laneFootprintMb: guard(footprint, null),
303
+ /** Called once this lane passed admission: it will grow for the next ramp window. */
304
+ recordAdmission: guard((mb = footprint()) => { writeAtomic(join(dir, `${pid}.json`), JSON.stringify({ pid, at: now(), mb })); return true; }, false),
305
+ /** Called at lane end with the lane's peak RSS in MB. */
306
+ recordPeakRss: guard((mb) => {
307
+ if (!(Number(mb) > 0)) return false;
308
+ writeAtomic(join(dir, "peaks.json"), JSON.stringify({ peaks: [...peaks(), Math.ceil(Number(mb))].slice(-PEAKS_KEPT) }));
309
+ return true;
310
+ }, false),
311
+ };
312
+ }
313
+
264
314
  /** Real host probes for admission (#4105). MemAvailable from /proc/meminfo (fallback os.freemem), statfs for tmp. */
265
315
  export function makeHostProbe() {
266
316
  return {
317
+ ...makeRampStore(),
267
318
  memAvailableMb() {
268
319
  try {
269
320
  const m = /^MemAvailable:\s+(\d+)\s+kB/m.exec(readFileSync("/proc/meminfo", "utf8"));
@@ -446,6 +497,21 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
446
497
  deps: makeDepCache({ exec: async (cmd, args, { cwd, env, timeoutMs } = {}) => String((await pexec(cmd, args, { cwd, env: { ...process.env, ...(env ?? {}) }, timeout: timeoutMs ?? 0, maxBuffer: 100 * 1024 * 1024 })).stdout) }),
447
498
  /** Names of the checks the base branch requires: classic protection plus rulesets (#4158). [] when neither has any. */
448
499
  async requiredChecks(lane) { return requiredChecksFor({ gh: run("gh"), repo, lane }); },
500
+ /**
501
+ * #5820: the scripts/ci-local plan of the lane's change (CI definitions from the base ref plus the lane's edits, change
502
+ * scoped), in a child process so the yq calls never block the lane. Rejects with ci-local's DEGRADED reason (no yq).
503
+ */
504
+ async ciLocalPlan({ repo: wt, base, baseBranch, files = [] }) {
505
+ const list = join(wt, ".forge-lean", "ci-precheck", "files.txt");
506
+ mkdirSync(dirname(list), { recursive: true }); writeFileSync(list, `${files.join("\n")}\n`);
507
+ 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 });
509
+ return JSON.parse(String(stdout));
510
+ } catch (e) {
511
+ const why = /CI_LOCAL_RESULT: DEGRADED reason=(.*)/.exec(String(e?.stdout ?? ""))?.[1] ?? String(e?.stderr || e?.message || e).split("\n")[0];
512
+ throw new Error(why);
513
+ }
514
+ },
449
515
  /** [{name, state: success|failure|pending, url, head}] for the PR's checks; `head` is the PR head the rollup belongs to (#4240). */
450
516
  async checkStates(pr) {
451
517
  const j = JSON.parse(await run("gh")(["pr", "view", String(pr), "-R", repo, "--json", "statusCheckRollup,headRefOid"]));
@@ -618,11 +684,17 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
618
684
  * `env` (#4325): the lane env (run TMPDIR, toolchain), merged over process.env, so the command sees what the builder saw.
619
685
  */
620
686
  async redGreen({ cwd, base, command, timeoutSec = 300, env = null }) {
621
- const args = [script("acceptance-red-green.sh"), "--repo-path", cwd, "--base-ref", base, "--test-cmd", command, "--timeout", String(timeoutSec)];
687
+ let outDir = null;
688
+ try { outDir = mkdtempSync(join(tmpdir(), "forge-rg-out-")); } catch { /* no output tails, the words still come back */ }
689
+ const args = [script("acceptance-red-green.sh"), "--repo-path", cwd, "--base-ref", base, "--test-cmd", command, "--timeout", String(timeoutSec), ...(outDir ? ["--output-dir", outDir] : [])];
690
+ // #5732: the last 64 KB of a run's output, for the failure's output tail; undefined when the harness kept none
691
+ const tailOf = (f) => { try { const t = readFileSync(join(outDir, f), "utf8"); return t.length > 65536 ? t.slice(-65536) : t; } catch { return undefined; } };
622
692
  try {
623
693
  const m = /BASE=(\w+) HEAD=(\w+)(?: PRISTINE=(\w+))?/.exec(String((await pexec("bash", args, { cwd, timeout: (timeoutSec * 2 + 60) * 1000, maxBuffer: 4 * 1024 * 1024, ...(env ? { env: { ...process.env, ...env } } : {}) })).stdout ?? ""));
624
- return m ? { base: m[1], head: m[2], ...(m[3] ? { pristine: m[3] } : {}) } : null; // #5544: pristine only when the base's own test version failed
625
- } catch { return null; }
694
+ if (!m) return null;
695
+ const headOutput = outDir ? tailOf("head.out") : undefined, baseOutput = outDir ? tailOf("base.out") : undefined;
696
+ 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
+ } catch { return null; } finally { if (outDir) rmSync(outDir, { recursive: true, force: true }); }
626
698
  },
627
699
  /**
628
700
  * The target repo's own docs-move-with-code rule, when it has one (scripts/check-devdocs-freshness.sh, forge#4185),
@@ -640,6 +712,8 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
640
712
  return { ok: false, output: `${e.stdout ?? ""}${e.stderr ?? ""}`.slice(0, 6000) };
641
713
  }
642
714
  },
715
+ /** #5825: is the lane folder a worktree of this repo (toplevel + common dir), and moving aside a folder that is not. */
716
+ confine: { verify: ({ wt, cwd }) => verifyLaneWorktree({ git: run("git"), exists: async (p) => existsSync(p), wt, cwd }), quarantine: async ({ wt }) => quarantineDir(wt) },
643
717
  /** #4162: processes left running inside a lane worktree (Linux /proc). */
644
718
  proc: { inDir: async (dir) => procsInDir(dir), alive: pidAlive, kill: (pid, sig) => { try { process.kill(pid, sig); } catch { /* already gone */ } } },
645
719
  fs: {