forgedock 1.68.0 → 1.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/bin/engine-cli.mjs +4 -9
  2. package/bin/lean/advisory.test.mjs +14 -5
  3. package/bin/lean/batch.mjs +11 -1
  4. package/bin/lean/capsample.mjs +25 -0
  5. package/bin/lean/conformance.mjs +6 -1
  6. package/bin/lean/conformance.test.mjs +6 -0
  7. package/bin/lean/depcache.mjs +2 -0
  8. package/bin/lean/effects.mjs +15 -1
  9. package/bin/lean/envgap.mjs +18 -0
  10. package/bin/lean/envgap.test.mjs +12 -1
  11. package/bin/lean/execution.mjs +3 -0
  12. package/bin/lean/execution.test.mjs +21 -0
  13. package/bin/lean/failure-stop.mjs +12 -1
  14. package/bin/lean/failure-stop.test.mjs +14 -1
  15. package/bin/lean/hostconfig.mjs +54 -0
  16. package/bin/lean/hostconfig.test.mjs +67 -0
  17. package/bin/lean/lane-audit-llm.mjs +51 -4
  18. package/bin/lean/lane-audit-llm.test.mjs +57 -0
  19. package/bin/lean/lane-audit.mjs +1 -1
  20. package/bin/lean/lean.mjs +63 -26
  21. package/bin/lean/lean.test.mjs +99 -19
  22. package/bin/lean/live-execution.mjs +3 -0
  23. package/bin/lean/live-execution.test.mjs +23 -0
  24. package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
  25. package/bin/lean/orchestrate-envhold.test.mjs +15 -1
  26. package/bin/lean/orchestrate.mjs +27 -9
  27. package/bin/lean/preflight.mjs +10 -3
  28. package/bin/lean/preflight.test.mjs +21 -1
  29. package/bin/lean/prompts.mjs +1 -0
  30. package/bin/lean/release-deploy.mjs +35 -5
  31. package/bin/lean/release-deploy.test.mjs +50 -3
  32. package/bin/lean/release-flakes.mjs +34 -0
  33. package/bin/lean/release-flakes.test.mjs +28 -0
  34. package/bin/lean/release.mjs +2 -1
  35. package/bin/lean/sandbox-remote.mjs +35 -4
  36. package/bin/lean/schedd.mjs +2 -2
  37. package/bin/pool/agent.mjs +105 -15
  38. package/bin/pool/cli.mjs +22 -4
  39. package/bin/pool/docker.mjs +2 -0
  40. package/bin/pool/image-manifest.mjs +24 -0
  41. package/bin/pool/image-manifest.test.mjs +20 -0
  42. package/bin/pool/lane-tools.mjs +23 -4
  43. package/bin/pool/lane-tools.test.mjs +27 -7
  44. package/bin/pool/project-layer.mjs +142 -0
  45. package/bin/pool/project-layer.test.mjs +73 -0
  46. package/bin/pool/router.mjs +20 -6
  47. package/bin/pool/version.mjs +45 -2
  48. package/bin/stats/tool-parks.mjs +29 -0
  49. package/bin/stats/tool-parks.test.mjs +21 -0
  50. package/package.json +1 -1
  51. package/pool/image/Dockerfile +1 -1
  52. package/scripts/ci-local.test.sh +3 -2
@@ -0,0 +1,142 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #6038: a repo's project deps as a cached image layer. deriveProjectDeps reads a worktree (lockfiles via depcache's detect,
5
+ * runtime pins from .tool-versions / .nvmrc / .python-version / CI setup-node|setup-python); projectLayerImageNow builds a
6
+ * layer FROM the lane image tagged `<base>-p<12hex>` (hash of lockfile contents + runtimes), in the background, and falls
7
+ * back to the base image while building or after a failure. Docker and fs are injected; nothing here blocks a launch.
8
+ */
9
+ import * as nodeFs from "node:fs";
10
+ import { createHash } from "node:crypto";
11
+ import { join, posix } from "node:path";
12
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import { detect, pyHint, depCommands } from "../lean/depcache.mjs";
15
+ import { isLaneToolsTagOf } from "./lane-tools.mjs";
16
+
17
+ const JS = new Set(["pnpm", "npm", "yarn"]);
18
+ const MANIFESTS = ["package.json", "pnpm-workspace.yaml", ".npmrc", ".yarnrc.yml", "pyproject.toml", ".python-version"];
19
+ const MAX_FILE = 4 * 1024 * 1024;
20
+ export const PROJECT_BUILD_RETRY_MS = 10 * 60000;
21
+ export const PROJECT_LAYER_ROOT = "/opt/project-deps";
22
+
23
+ const read = (fs, p) => { try { return String(fs.readFileSync(p)); } catch { return null; } };
24
+
25
+ /** Node version the repo pins: .nvmrc, .tool-versions `nodejs`, else the first CI setup-node `node-version`. */
26
+ function nodeHint(fs, wt) {
27
+ const norm = (t) => { const m = /^\s*(?:v|node\/|lts\/)?(\d+(?:\.\d+){0,2})/.exec(t ?? ""); return m ? m[1] : null; };
28
+ const nvmrc = norm(read(fs, join(wt, ".nvmrc")));
29
+ if (nvmrc) return nvmrc;
30
+ const tv = /^\s*node(?:js)?\s+(\S+)/m.exec(read(fs, join(wt, ".tool-versions")) ?? "");
31
+ if (tv && norm(tv[1])) return norm(tv[1]);
32
+ try {
33
+ const dir = join(wt, ".github", "workflows");
34
+ for (const f of fs.readdirSync(dir).sort()) {
35
+ if (!/\.ya?ml$/.test(f)) continue;
36
+ const m = /node-version:\s*\[?\s*["']?v?(\d+(?:\.\d+){0,2})/.exec(read(fs, join(dir, f)) ?? "");
37
+ if (m) return m[1];
38
+ }
39
+ } catch { /* no workflows */ }
40
+ return null;
41
+ }
42
+
43
+ /** Python minor the repo pins: depcache's .python-version / setup-python hint, else .tool-versions `python`. */
44
+ function pythonHint(fs, wt) {
45
+ const h = pyHint(fs, wt);
46
+ if (h) return `${h[0]}.${h[1]}`;
47
+ const m = /^\s*python\s+(\d+\.\d+)/m.exec(read(fs, join(wt, ".tool-versions")) ?? "");
48
+ return m ? m[1] : null;
49
+ }
50
+
51
+ /** {ecosystems, lockfiles, node, python, files, hash} for a worktree; hash is null when there is nothing to install. */
52
+ export function deriveProjectDeps(worktree, fs = nodeFs) {
53
+ const found = detect(fs, worktree).filter((d) => !d.skip);
54
+ const lockfiles = found.map((d) => ({ eco: d.eco, dir: d.dir ?? ".", path: d.dir ? `${d.dir}/${d.lock}` : d.lock, ...(d.berry ? { berry: true } : {}) }));
55
+ const files = {};
56
+ for (const d of lockfiles) {
57
+ for (const name of [posix.basename(d.path), ...MANIFESTS]) {
58
+ const rel = d.dir === "." ? name : `${d.dir}/${name}`;
59
+ if (rel in files) continue;
60
+ const t = read(fs, join(worktree, rel));
61
+ if (t !== null && t.length <= MAX_FILE) files[rel] = t;
62
+ }
63
+ }
64
+ const ecosystems = [...new Set(lockfiles.map((d) => d.eco))].sort();
65
+ const node = lockfiles.some((d) => JS.has(d.eco)) ? nodeHint(fs, worktree) : null;
66
+ const python = lockfiles.some((d) => !JS.has(d.eco)) ? pythonHint(fs, worktree) : null;
67
+ if (!lockfiles.length) return { ecosystems, lockfiles, node, python, files, hash: null };
68
+ const h = createHash("sha256").update(`v1\0${node ?? ""}\0${python ?? ""}\0${process.arch}\0`);
69
+ for (const d of lockfiles) h.update(`${d.eco}\0${d.path}\0${d.berry ? 1 : 0}\0`);
70
+ for (const k of Object.keys(files).sort()) h.update(`${k}\0${files[k]}\0`);
71
+ return { ecosystems, lockfiles, node, python, files, hash: h.digest("hex") };
72
+ }
73
+
74
+ /** Per-project image tag: base plus 12 hex of the deps hash; separate from the lane_tools `-t` tag. */
75
+ export function projectLayerTag(baseImage, hash) {
76
+ return `${baseImage}-p${String(hash).slice(0, 12)}`;
77
+ }
78
+
79
+ /** True for `<base>-p<12 hex>` where `<base>` is the base image or a lane_tools variant of it. */
80
+ export function isProjectLayerTagOf(tag, base) {
81
+ if (typeof tag !== "string") return false;
82
+ const m = /^(.*)-p[0-9a-f]{12}$/.exec(tag);
83
+ return Boolean(m) && isLaneToolsTagOf(m[1], base);
84
+ }
85
+
86
+ const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
87
+
88
+ /** The layer Dockerfile: FROM base, runtimes, then per lockfile dir copy manifests and run the frozen install. */
89
+ export function projectLayerDockerfile(baseImage, deps) {
90
+ const out = [`FROM ${baseImage}`, "USER root"];
91
+ if (deps.node) out.push(`RUN npm install -g n && n ${q(deps.node)}`);
92
+ if (deps.python) out.push(`RUN uv python install ${q(deps.python)}`);
93
+ for (const d of deps.lockfiles) {
94
+ const target = d.dir === "." ? PROJECT_LAYER_ROOT : `${PROJECT_LAYER_ROOT}/${d.dir}`;
95
+ const cmds = depCommands(d)?.install ?? [];
96
+ out.push(`COPY ctx/${d.dir === "." ? "" : d.dir} ${target}/`, `WORKDIR ${target}`);
97
+ for (const [cmd, args] of cmds) out.push(`RUN ${[cmd, ...args].map(q).join(" ")}`);
98
+ }
99
+ return [...out, "WORKDIR /", ""].join("\n");
100
+ }
101
+
102
+ const BUILDS = new Map();
103
+ const FAILED = new Map();
104
+
105
+ async function buildLayer({ tag, baseImage, deps, docker, buildTimeoutMs }) {
106
+ const dir = mkdtempSync(join(tmpdir(), "project-layer-"));
107
+ let timer;
108
+ try {
109
+ for (const [rel, text] of Object.entries(deps.files ?? {})) {
110
+ const p = join(dir, "ctx", rel);
111
+ mkdirSync(join(p, ".."), { recursive: true });
112
+ writeFileSync(p, text);
113
+ }
114
+ for (const d of deps.lockfiles) mkdirSync(join(dir, "ctx", d.dir === "." ? "" : d.dir), { recursive: true });
115
+ writeFileSync(join(dir, "Dockerfile"), projectLayerDockerfile(baseImage, deps));
116
+ const timeout = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`build timed out after ${buildTimeoutMs}ms`)), buildTimeoutMs); });
117
+ await Promise.race([docker.build(dir, tag, {}), timeout]);
118
+ } catch (e) {
119
+ throw new Error(`project layer ${tag} build failed: ${String(e.stderr || e.message).slice(0, 300)}`);
120
+ } finally { clearTimeout(timer); rmSync(dir, { recursive: true, force: true }); }
121
+ return tag;
122
+ }
123
+
124
+ /**
125
+ * Never blocks: {image: tag} when the layer exists, else starts (or joins) one background build and returns
126
+ * {image: baseImage, building: true}; a build that failed in the last PROJECT_BUILD_RETRY_MS returns {image: baseImage, failed}.
127
+ */
128
+ export async function projectLayerImageNow({ deps, baseImage, docker, buildTimeoutMs = 45 * 60000, now = Date.now }) {
129
+ if (!deps?.hash || !deps.lockfiles?.length) return { image: baseImage };
130
+ const tag = projectLayerTag(baseImage, deps.hash);
131
+ try { if (await docker.hasImage?.(tag)) return { image: tag }; } catch { return { image: baseImage }; }
132
+ const f = FAILED.get(tag);
133
+ if (f && now() - f.at < PROJECT_BUILD_RETRY_MS) return { image: baseImage, failed: f.message };
134
+ if (!BUILDS.has(tag)) {
135
+ FAILED.delete(tag);
136
+ BUILDS.set(tag, buildLayer({ tag, baseImage, deps, docker, buildTimeoutMs }).catch((e) => { FAILED.set(tag, { at: now(), message: e.message }); }).finally(() => BUILDS.delete(tag)));
137
+ }
138
+ return { image: baseImage, building: true, tag };
139
+ }
140
+
141
+ /** Test hook: the in-flight build of a tag. */
142
+ export const pendingBuild = (tag) => BUILDS.get(tag);
@@ -0,0 +1,73 @@
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 { deriveProjectDeps, projectLayerTag, isProjectLayerTagOf, projectLayerDockerfile, projectLayerImageNow, pendingBuild } from "./project-layer.mjs";
6
+ import { laneToolsTag } from "./lane-tools.mjs";
7
+
8
+ const fakeFs = (files) => ({
9
+ existsSync: (p) => p in files || Object.keys(files).some((k) => k.startsWith(`${p}/`)),
10
+ readFileSync: (p) => { if (!(p in files)) throw new Error("ENOENT"); return files[p]; },
11
+ readdirSync: (p) => { const s = new Set(Object.keys(files).filter((k) => k.startsWith(`${p}/`)).map((k) => k.slice(p.length + 1).split("/")[0])); if (!s.size) throw new Error("ENOENT"); return [...s]; },
12
+ });
13
+ const W = "/w";
14
+ const repo = (extra = {}) => fakeFs({ [`${W}/package-lock.json`]: "lock1", [`${W}/package.json`]: "{}", ...extra });
15
+
16
+ describe("#6038 project layer", () => {
17
+ it("same lockfile gives the same tag; a changed lockfile a new one", () => {
18
+ const a = deriveProjectDeps(W, repo()), b = deriveProjectDeps(W, repo()), c = deriveProjectDeps(W, repo({ [`${W}/package-lock.json`]: "lock2" }));
19
+ assert.equal(a.hash, b.hash);
20
+ assert.notEqual(a.hash, c.hash);
21
+ assert.match(projectLayerTag("img:1", a.hash), /^img:1-p[0-9a-f]{12}$/);
22
+ assert.deepEqual(a.ecosystems, ["npm"]);
23
+ });
24
+ it("derives runtime versions from .nvmrc, .tool-versions, .python-version and setup-python/setup-node", () => {
25
+ assert.equal(deriveProjectDeps(W, repo({ [`${W}/.nvmrc`]: "v20.11.1\n" })).node, "20.11.1");
26
+ assert.equal(deriveProjectDeps(W, repo({ [`${W}/.tool-versions`]: "nodejs 22.3.0\n" })).node, "22.3.0");
27
+ assert.equal(deriveProjectDeps(W, repo({ [`${W}/.github/workflows/ci.yml`]: "with:\n node-version: '18'\n" })).node, "18");
28
+ const py = (extra) => deriveProjectDeps(W, fakeFs({ [`${W}/uv.lock`]: "x", ...extra }));
29
+ assert.equal(py({ [`${W}/.python-version`]: "3.12.2\n" }).python, "3.12");
30
+ assert.equal(py({ [`${W}/.github/workflows/ci.yml`]: "python-version: \"3.11\"\n" }).python, "3.11");
31
+ assert.equal(py({ [`${W}/.tool-versions`]: "python 3.10.4\n" }).python, "3.10");
32
+ assert.notEqual(deriveProjectDeps(W, repo()).hash, deriveProjectDeps(W, repo({ [`${W}/.nvmrc`]: "20" })).hash);
33
+ });
34
+ it("no lockfile means no hash; tag ownership does not collide with lane_tools tags", () => {
35
+ assert.equal(deriveProjectDeps(W, fakeFs({})).hash, null);
36
+ const t = laneToolsTag("img:1", ["shellcheck"]);
37
+ assert.ok(isProjectLayerTagOf(projectLayerTag("img:1", "ab".repeat(8)), "img:1"));
38
+ assert.ok(isProjectLayerTagOf(projectLayerTag(t, "ab".repeat(8)), "img:1"));
39
+ assert.ok(!isProjectLayerTagOf(t, "img:1") && !isProjectLayerTagOf("img:1", "img:1") && !isProjectLayerTagOf("img:1-pzz", "img:1"));
40
+ });
41
+ it("Dockerfile is FROM base with the frozen install", () => {
42
+ const df = projectLayerDockerfile("img:1", deriveProjectDeps(W, repo({ [`${W}/.nvmrc`]: "20" })));
43
+ assert.match(df, /^FROM img:1\n/);
44
+ assert.match(df, /RUN 'npm' 'ci'/);
45
+ assert.match(df, /n '20'/);
46
+ });
47
+ it("an existing tag is reused without a build", async () => {
48
+ const deps = deriveProjectDeps(W, repo()), tag = projectLayerTag("img:2", deps.hash);
49
+ let built = 0;
50
+ const docker = { hasImage: async (t) => t === tag, build: async () => { built++; } };
51
+ assert.deepEqual(await projectLayerImageNow({ deps, baseImage: "img:2", docker }), { image: tag });
52
+ assert.equal(built, 0);
53
+ });
54
+ it("concurrent launches share one background build and run the base meanwhile", async () => {
55
+ const deps = deriveProjectDeps(W, repo({ [`${W}/package-lock.json`]: "conc" })), tag = projectLayerTag("img:3", deps.hash);
56
+ let built = 0, release; const gate = new Promise((r) => { release = r; });
57
+ const docker = { hasImage: async () => false, build: async () => { built++; await gate; } };
58
+ const [a, b] = await Promise.all([1, 2].map(() => projectLayerImageNow({ deps, baseImage: "img:3", docker })));
59
+ assert.equal(a.image, "img:3"); assert.ok(a.building && b.building);
60
+ release(); await pendingBuild(tag);
61
+ assert.equal(built, 1);
62
+ });
63
+ it("a failed build falls back to base and is not retried within the window", async () => {
64
+ const deps = deriveProjectDeps(W, repo({ [`${W}/package-lock.json`]: "fail" })), tag = projectLayerTag("img:4", deps.hash);
65
+ let built = 0; let t = 1000;
66
+ const docker = { hasImage: async () => false, build: async () => { built++; throw new Error("boom"); } };
67
+ await projectLayerImageNow({ deps, baseImage: "img:4", docker, now: () => t });
68
+ await pendingBuild(tag);
69
+ const r = await projectLayerImageNow({ deps, baseImage: "img:4", docker, now: () => t });
70
+ assert.equal(r.image, "img:4"); assert.match(r.failed, /boom/);
71
+ assert.equal(built, 1);
72
+ });
73
+ });
@@ -17,7 +17,7 @@ import { cmpVersion, versionOf } from "./version.mjs";
17
17
  * What the router ships to pool agents (self-update and bootstrap). Every module the agent can load statically from
18
18
  * bin/pool/agent.mjs must live under these paths; bin/tests/pool-agent-bundle.test.mjs enforces it.
19
19
  */
20
- export const AGENT_BUNDLE_PATHS = Object.freeze(["package.json", "bin/pool", "bin/lean/concurrency.mjs", "pool"]); // concurrency.mjs: thresholds imported by pool/lane-target.mjs (#6061); it has no imports
20
+ export const AGENT_BUNDLE_PATHS = Object.freeze(["package.json", "bin/pool", "bin/lean/concurrency.mjs", "bin/lean/depcache.mjs", "bin/lean/ledger.mjs", "pool"]); // depcache.mjs+ledger.mjs: pool/project-layer.mjs (#6038); concurrency.mjs: thresholds imported by pool/lane-target.mjs (#6061); it has no imports
21
21
 
22
22
  const run = promisify(execFile);
23
23
 
@@ -460,6 +460,18 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
460
460
  return { status: 404, body: { error: "no warm sandbox ready" } };
461
461
  }
462
462
 
463
+ // #6117: a destroyed sandbox's placing agent, for the agent's log grace period: a late log/result/runlog read still reaches it.
464
+ const graced = new Map(); // id -> {agent, until}
465
+ const GRACE_MS = Number(cfg.keep_log_s ?? 600) * 1000;
466
+ const grace = (id, agent) => { const t = now(); for (const [k, v] of graced) if (v.until <= t) graced.delete(k); graced.set(id, { agent, until: t + GRACE_MS }); }; // expired entries go on every insert
467
+ async function forwardRead(id, path) {
468
+ if (own(sbx(), id)) return forward(id, "GET", path);
469
+ const g = graced.get(id);
470
+ if (!g || g.until <= now()) { graced.delete(id); return { status: 404, body: { state: "gone" } }; }
471
+ const a = own(agents(), g.agent);
472
+ if (!a) return { status: 404, body: { state: "gone" } };
473
+ try { const r = await agentCall(a, "GET", path); return { status: r.status, body: agentBody(r, g.agent) }; } catch (e) { return { status: 502, body: { error: `agent ${g.agent} unreachable: ${e.message}` } }; }
474
+ }
463
475
  async function forward(id, method, path, timeoutMs) {
464
476
  const s = own(sbx(), id);
465
477
  const a = s && own(agents(), s.agent);
@@ -467,7 +479,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
467
479
  s.touched = now(); store.save();
468
480
  try {
469
481
  const r = await agentCall(a, method, path, undefined, timeoutMs);
470
- if (method === "DELETE" && (r.ok || r.status === 404)) { delete sbx()[id]; relayQ.delete(id); store.save(); }
482
+ if (method === "DELETE" && (r.ok || r.status === 404)) { if (r.ok && GRACE_MS > 0) grace(id, s.agent); delete sbx()[id]; relayQ.delete(id); store.save(); }
471
483
  return { status: r.status, body: agentBody(r, s.agent) };
472
484
  } catch (e) { return { status: 502, body: { error: `agent ${s.agent} unreachable: ${e.message}` } }; }
473
485
  }
@@ -483,7 +495,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
483
495
  try {
484
496
  if (now() - s.touched > abandonMs) {
485
497
  const r = await agentCall(a, "DELETE", `/sandboxes/${encodeURIComponent(id)}`, undefined, DESTROY_TIMEOUT_MS);
486
- if (r.ok || r.status === 404) { delete sbx()[id]; relayQ.delete(id); log.info?.(`abandoned ${id} destroyed on ${s.agent}`); }
498
+ if (r.ok || r.status === 404) { if (r.ok && GRACE_MS > 0) grace(id, s.agent); delete sbx()[id]; relayQ.delete(id); log.info?.(`abandoned ${id} destroyed on ${s.agent}`); }
487
499
  } else {
488
500
  const r = await agentCall(a, "POST", `/sandboxes/${encodeURIComponent(id)}/lease`);
489
501
  if (r.status === 404) { delete sbx()[id]; relayQ.delete(id); log.info?.(`${id} gone on ${s.agent}`); }
@@ -657,8 +669,9 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
657
669
  [route("GET", "/sandboxes/:id/mirrors"), fd(async ({ id }, _b, url) => seedForward(id, "GET", `/mirrors?${new URLSearchParams([...[...url.searchParams].filter(([k]) => ["slug", "cache_key", "upload"].includes(k)), ["uploader", id]])}`, undefined, url.searchParams.get("slug")))], // #5949; uploader: per-sandbox part file (concurrent identical bundles)
658
670
  [route("POST", "/sandboxes/:id/seed"), fd(async ({ id }, body) => seedForward(id, "POST", "/mirrors/seed", { ...(body ?? {}), uploader: id }, body?.slug))],
659
671
  [route("GET", "/sandboxes/:id"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}`))],
660
- [route("GET", "/sandboxes/:id/logs"), fd(async ({ id }, _b, url) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/logs?cursor=${encodeURIComponent(url.searchParams.get("cursor") ?? "0")}`))],
661
- [route("GET", "/sandboxes/:id/result"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/result`))],
672
+ [route("GET", "/sandboxes/:id/logs"), fd(async ({ id }, _b, url) => forwardRead(id, `/sandboxes/${encodeURIComponent(id)}/logs?cursor=${encodeURIComponent(url.searchParams.get("cursor") ?? "0")}`))],
673
+ [route("GET", "/sandboxes/:id/result"), fd(async ({ id }) => forwardRead(id, `/sandboxes/${encodeURIComponent(id)}/result`))],
674
+ [route("GET", "/sandboxes/:id/runlog"), fd(async ({ id }) => forwardRead(id, `/sandboxes/${encodeURIComponent(id)}/runlog`))], // #6117
662
675
  [route("GET", "/sandboxes/:id/usage"), fd(async ({ id }) => { // #4549: the placing agent rides along for per-agent minutes
663
676
  const agent = own(sbx(), id)?.agent, r = await forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/usage`);
664
677
  return agent && r.status === 200 && r.body && typeof r.body === "object" ? { ...r, body: { ...r.body, agent } } : r;
@@ -674,6 +687,7 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
674
687
  const caps = (await capacities()).filter((c) => (acct === null || own(agents(), c.name)?.account === acct) && placeable(c, view)).map((c) => { const a = own(agents(), c.name); return { ...c, ...(a?.account ? { account: a.account } : {}), ...(a?.policy ? { policy: a.policy } : {}) }; }), byName = new Map(caps.map((c) => [c.name, c])), out = {};
675
688
  for (const [id, s] of Object.entries(sbx())) { if ((acct !== null || repo) && !byName.has(s?.agent)) continue; const mb = byName.get(s?.agent)?.sandbox_disk_mb?.[id]; out[id] = Number.isFinite(mb) ? { ...s, disk_used_mb: mb } : s; }
676
689
  const remote_lanes = Object.keys(sbx()).filter(isLane).length; // #5735: lane sandboxes across all batches and agents
690
+ // #6062: usage_summary rides on each capacity record (spread above) unchanged
677
691
  return { status: 200, body: { agents: caps.map((c) => ({ ...c, lanes: laneView(c.name), ...diskReport(c) })), sandboxes: out, remote_lanes } };
678
692
  })],
679
693
  [route("POST", "/device/code"), { fn: async () => deviceStart(), auth: "none" }], // #5886
@@ -767,7 +781,7 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
767
781
  }
768
782
  }
769
783
 
770
- return { handle, launch, claim, tick, autoscale, enroll, issueCode, capacities, status, store };
784
+ return { handle, launch, claim, tick, autoscale, enroll, issueCode, capacities, status, store, forward, forwardRead };
771
785
  }
772
786
 
773
787
  /** tokenbaton's usage dir (#5165): router.json `usage_source`, else `$TOKENBATON_HOME`, else `~/.tokenbaton`. */
@@ -40,10 +40,18 @@ export function cmpVersion(a, b) {
40
40
  export const agentsLeftBehind = (agents, target) => (agents ?? []).filter((a) => a?.ok !== false && cmpVersion(a?.engine_version, target) < 0).map((a) => ({ name: a.name, version: a.engine_version }));
41
41
  export const leftBehindLine = (rows, target) => `agents left behind on an older engine (target ${target}): ${rows.map((r) => `${r.name} ${r.version}`).join(", ")}`;
42
42
 
43
+ /** The router config the pool CLI uses: router.json plus the forgedock token (inline, `forgedock_token_file`, or forgedock.token beside it). */
44
+ export function readRouterConfig(configPath) {
45
+ const cfg = JSON.parse(readFileSync(configPath, "utf8"));
46
+ let token = cfg.forgedock_token;
47
+ if (!token) { try { token = readFileSync(cfg.forgedock_token_file ?? join(dirname(configPath), "forgedock.token"), "utf8").trim(); } catch { token = undefined; } }
48
+ return { ...cfg, forgedock_token: token };
49
+ }
50
+
43
51
  /** Ask the local router which agents lag the target engine; [] when the router is unreachable. */
44
52
  async function fetchLeftBehind(configPath) {
45
53
  try {
46
- const cfg = JSON.parse(readFileSync(configPath, "utf8"));
54
+ const cfg = readRouterConfig(configPath);
47
55
  const base = `http://${cfg.listen.host}:${cfg.listen.port}`;
48
56
  const { call } = await import("./http.mjs");
49
57
  const [st, v] = await Promise.all([call(base, "GET", "/status", { token: cfg.forgedock_token }), call(base, "GET", "/version", { token: cfg.forgedock_token })]);
@@ -51,14 +59,49 @@ async function fetchLeftBehind(configPath) {
51
59
  } catch { return { target: undefined, rows: [] }; }
52
60
  }
53
61
 
62
+ /**
63
+ * The local router runs the installed bin/pool code (its /version `code` hash equals versionOf().code). When it does not,
64
+ * restart it through `restart()` (systemd user unit by default) and poll `/version` for up to `waitMs`. Returns
65
+ * {ok, running, installed, why}. `probe(configPath)` returns the router's /version data or null.
66
+ */
67
+ export async function routerFresh(configPath, { installed = installedFor(configPath), probe = probeRouterVersion, restart = restartRouterUnit, waitMs = 30000, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
68
+ const same = (v) => v && v.code === installed.code && v.version === installed.version;
69
+ let v = await probe(configPath);
70
+ if (same(v)) return { ok: true, running: v.version, installed: installed.version };
71
+ if (!v) return { ok: false, running: null, installed: installed.version, why: "router unreachable" };
72
+ if (!(await restart())) return { ok: false, running: v.version, installed: installed.version, why: "could not restart the router" };
73
+ for (let t = 0; t < waitMs; t += 1000) { await sleep(1000); v = await probe(configPath); if (same(v)) return { ok: true, running: v.version, installed: installed.version }; }
74
+ return { ok: false, running: v?.version ?? null, installed: installed.version, why: "router did not come back on the installed code" };
75
+ }
76
+ /** What the router would hash: its configured repo_root, else this package. */
77
+ function installedFor(configPath) {
78
+ try { const c = JSON.parse(readFileSync(configPath, "utf8")); return versionOf(c.repo_root ?? repoRoot); } catch { return versionOf(); }
79
+ }
80
+ async function probeRouterVersion(configPath) {
81
+ try {
82
+ const cfg = readRouterConfig(configPath);
83
+ const { call } = await import("./http.mjs");
84
+ const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "GET", "/version", { token: cfg.forgedock_token });
85
+ const d = r?.data;
86
+ return d && typeof d.code === "string" && typeof d.version === "string" ? d : null; // a 401/500 body is "unknown", never "stale"
87
+ } catch { return null; }
88
+ }
89
+ async function restartRouterUnit() {
90
+ try { const { execFileSync } = await import("node:child_process"); execFileSync("systemctl", ["--user", "restart", "computeshare-router.service"], { stdio: "ignore", timeout: 30000 }); return true; } catch { return false; }
91
+ }
92
+
54
93
  /**
55
94
  * `forgedock update` hook: push the new code and lane image to every enrolled agent. A no-op on hosts without a
56
95
  * pool router config; never throws (a failed push must not fail the update). Returns "skipped" | "upgraded" | "failed";
57
96
  * agents still on an older engine afterwards are named through `warn` (and `onLeftBehind`).
58
97
  */
59
- export async function upgradeAgentsAfterUpdate({ configPath = process.env.COMPUTESHARE_CONFIG ?? join(homedir(), ".config/computeshare/router.json"), runPoolCli, warn = console.warn, leftBehind = fetchLeftBehind, onLeftBehind } = {}) {
98
+ export async function upgradeAgentsAfterUpdate({ configPath = process.env.COMPUTESHARE_CONFIG ?? join(homedir(), ".config/computeshare/router.json"), runPoolCli, warn = console.warn, leftBehind = fetchLeftBehind, onLeftBehind, ensureRouterFresh } = {}) {
60
99
  if (!existsSync(configPath)) return "skipped";
61
100
  try {
101
+ // The router builds the agent bundle from the code it is RUNNING: a router still on the old version ships an incomplete
102
+ // bundle and the upgraded agent crash-loops at import. Restart it onto the installed code first, or do not push.
103
+ const fresh = await (ensureRouterFresh ?? routerFresh)(configPath);
104
+ if (!fresh.ok) { warn(`pool upgrade skipped: the router runs ${fresh.running ?? "unknown"} code but ${fresh.installed} is installed (${fresh.why}); restart computeshare-router, then run forgedock pool upgrade`); return "skipped"; }
62
105
  const run = runPoolCli ?? (await import("./cli.mjs")).runPoolCli;
63
106
  await run(["upgrade", "--config", configPath]);
64
107
  const { target, rows } = await leftBehind(configPath);
@@ -0,0 +1,29 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { manifestProvides } from "../pool/image-manifest.mjs";
4
+
5
+ /**
6
+ * #6037 zero-park metric: needs-human parks coded `env.tool_missing` whose detail names a tool the image manifest ships.
7
+ * `parks`: [{issue, code, detail, ts}]. Pure. ok is true only when no such park falls inside the window.
8
+ */
9
+ export function manifestToolParks(parks, manifest, { now = Date.now(), windowDays = 7 } = {}) {
10
+ const since = now - windowDays * 864e5, offenders = [];
11
+ for (const p of Array.isArray(parks) ? parks : []) {
12
+ const ts = Date.parse(p?.ts);
13
+ if (p?.code !== "env.tool_missing" || !(ts >= since) || ts > now) continue;
14
+ const words = String(p.detail ?? "").split(/[\s,`'"():;]+/);
15
+ const tool = words.find((w) => manifestProvides(manifest, w));
16
+ if (tool) offenders.push({ issue: p.issue, tool });
17
+ }
18
+ return { count: offenders.length, offenders, ok: offenders.length === 0 };
19
+ }
20
+
21
+ /** Reports the metric and sets a nonzero exit code when a manifest tool was parked. Returns the result. */
22
+ export function check(parks, manifest, opts = {}) {
23
+ const r = manifestToolParks(parks, manifest, opts);
24
+ if (!r.ok) {
25
+ process.stderr.write(`tool-parks: ${r.count} env.tool_missing park(s) name an image-manifest tool: ${r.offenders.map((o) => `#${o.issue} ${o.tool}`).join(", ")}\n`);
26
+ process.exitCode = 1;
27
+ }
28
+ return r;
29
+ }
@@ -0,0 +1,21 @@
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 { manifestToolParks } from "./tool-parks.mjs";
6
+
7
+ const manifest = { tools: [{ name: "shellcheck", binary: "shellcheck" }] };
8
+ const now = Date.parse("2026-11-26T00:00:00Z");
9
+ const park = (o) => ({ issue: 1, code: "env.tool_missing", detail: "Remote sandbox lacks shellcheck, and no recipe", ts: "2026-11-25T00:00:00Z", ...o });
10
+
11
+ describe("#6037 zero-park metric", () => {
12
+ it("no parks is ok", () => assert.deepEqual(manifestToolParks([], manifest, { now }), { count: 0, offenders: [], ok: true }));
13
+ it("a recent manifest-tool park is an offender", () => {
14
+ const r = manifestToolParks([park()], manifest, { now });
15
+ assert.deepEqual([r.ok, r.count, r.offenders], [false, 1, [{ issue: 1, tool: "shellcheck" }]]);
16
+ });
17
+ it("old, non-manifest or other-code parks are ignored", () => {
18
+ const r = manifestToolParks([park({ ts: "2026-11-01T00:00:00Z" }), park({ detail: "Remote sandbox lacks ripgrep" }), park({ code: "other" })], manifest, { now });
19
+ assert.equal(r.ok, true);
20
+ });
21
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "forgedock",
3
- "version": "1.68.0",
3
+ "version": "1.69.0",
4
4
  "description": "An AI engineering team that ships to production",
5
5
  "bin": {
6
6
  "forgedock": "bin/forgedock.mjs"
@@ -22,7 +22,7 @@ RUN test -n "$FORGEDOCK_VERSION" || { echo "FORGEDOCK_VERSION build arg is requi
22
22
  ENV IS_SANDBOX=1 DEBIAN_FRONTEND=noninteractive LANG=C.UTF-8 PLAYWRIGHT_BROWSERS_PATH=/opt/playwright UV_PYTHON_INSTALL_DIR=/opt/uv-python PATH=/opt/cs/bin:/opt/node/bin:/root/.local/bin:$PATH
23
23
 
24
24
  RUN apt-get update && apt-get install -y --no-install-recommends \
25
- ca-certificates curl git jq xz-utils build-essential python3 python3-venv python3-dev pkg-config libpq-dev \
25
+ ca-certificates curl git jq xz-utils build-essential python3 python3-venv python3-dev python3-yaml pkg-config libpq-dev \
26
26
  shellcheck xvfb xauth postgresql-client redis-tools \
27
27
  && install -d -m 0755 /etc/apt/keyrings \
28
28
  && curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg -o /etc/apt/keyrings/githubcli.gpg \
@@ -518,7 +518,8 @@ echo '{"a":1}' > "$r/lib/data.json"; P=$(plan "$r")
518
518
  has "jest: a changed data file widens (not reachable through imports)" "$(step_field "$P" task:npm:test 1 '.scope.widen_reason')" "unknown-language"
519
519
 
520
520
  # ------------------------------------------------------------------------------------------------ ForgeDock's own workflows
521
- P=$(bash "$S" plan --repo "$ROOT" --base HEAD --base-branch staging --head-branch feat/spec-change --files "commands/work-on/build.md" --json --no-cache 2>/dev/null)
521
+ # PR CI runs only on release PRs to main (owner decision 2026-11-27); staging is checked on push.
522
+ P=$(bash "$S" plan --repo "$ROOT" --base HEAD --base-branch main --head-branch release/spec-change --files "commands/work-on/build.md" --json --no-cache 2>/dev/null)
522
523
  if [ -z "$P" ]; then bad "plan on ForgeDock's own workflows produced no output"; else
523
524
  eq "ForgeDock: a spec change selects a check-commands job" runnable "$(state "$P" gha:check-commands:check-native-conflicts)"
524
525
  eq "ForgeDock: a spec change selects the ci unit-tests job" runnable "$(state "$P" gha:ci:unit-tests)"
@@ -529,7 +530,7 @@ if [ -z "$P" ]; then bad "plan on ForgeDock's own workflows produced no output";
529
530
  eq "ForgeDock: portability checks run" runnable "$(state "$P" portability:builtin)"
530
531
  # Narrowing is asserted on a spec with a small reference reach (design-bench.md: ~10 referrers). Specs that name the release engine
531
532
  # (build.md, review-pr-staging.md) sit near the 600-file fan-out cap, so any growth in bin/lean widens them to the full suite; that is the cap working.
532
- PN=$(bash "$S" plan --repo "$ROOT" --base HEAD --base-branch staging --head-branch feat/spec-change --files "commands/design-bench.md" --json --no-cache 2>/dev/null)
533
+ PN=$(bash "$S" plan --repo "$ROOT" --base HEAD --base-branch main --head-branch release/spec-change --files "commands/design-bench.md" --json --no-cache 2>/dev/null)
533
534
  eq "ForgeDock: the unit-test step is narrowed by the reference graph" scoped "$(printf '%s' "$PN" | jq -r '[.jobs[] | select(.id == "gha:ci:unit-tests") | .steps[] | select(.scope.selector == "refgraph-nodetest") | .scope.mode][0]')"
534
535
  fi
535
536