forgedock 1.68.0 → 1.70.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.
- package/bin/engine-cli.mjs +4 -9
- package/bin/lean/advisory.test.mjs +14 -5
- package/bin/lean/batch.mjs +11 -1
- package/bin/lean/capsample.mjs +25 -0
- package/bin/lean/conformance.mjs +9 -1
- package/bin/lean/conformance.test.mjs +7 -0
- package/bin/lean/depcache.mjs +2 -0
- package/bin/lean/effects.mjs +15 -1
- package/bin/lean/envgap.mjs +18 -0
- package/bin/lean/envgap.test.mjs +12 -1
- package/bin/lean/execution.mjs +3 -0
- package/bin/lean/execution.test.mjs +21 -0
- package/bin/lean/failure-stop.mjs +12 -1
- package/bin/lean/failure-stop.test.mjs +14 -1
- package/bin/lean/hostconfig.mjs +54 -0
- package/bin/lean/hostconfig.test.mjs +67 -0
- package/bin/lean/issuewatch-parity.test.mjs +1 -1
- package/bin/lean/lane-audit-llm.mjs +51 -4
- package/bin/lean/lane-audit-llm.test.mjs +57 -0
- package/bin/lean/lane-audit.mjs +1 -1
- package/bin/lean/lean.mjs +63 -26
- package/bin/lean/lean.test.mjs +100 -19
- package/bin/lean/live-execution.mjs +3 -0
- package/bin/lean/live-execution.test.mjs +23 -0
- package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
- package/bin/lean/orchestrate-envhold.test.mjs +15 -1
- package/bin/lean/orchestrate.mjs +27 -9
- package/bin/lean/preflight.mjs +10 -3
- package/bin/lean/preflight.test.mjs +21 -1
- package/bin/lean/prompts.mjs +1 -0
- package/bin/lean/release-cigreen.mjs +204 -0
- package/bin/lean/release-cigreen.test.mjs +115 -0
- package/bin/lean/release-deploy.mjs +35 -5
- package/bin/lean/release-deploy.test.mjs +50 -3
- package/bin/lean/release-fixloop.mjs +1 -1
- package/bin/lean/release-flakes.mjs +34 -0
- package/bin/lean/release-flakes.test.mjs +28 -0
- package/bin/lean/release-ledger.test.mjs +4 -4
- package/bin/lean/release-preflight.test.mjs +2 -2
- package/bin/lean/release-rehearsal.test.mjs +1 -1
- package/bin/lean/release-review.e2e.test.mjs +4 -3
- package/bin/lean/release-review.mjs +136 -56
- package/bin/lean/release-review.test.mjs +97 -12
- package/bin/lean/release-status.mjs +3 -2
- package/bin/lean/release-status.test.mjs +2 -2
- package/bin/lean/release.mjs +6 -3
- package/bin/lean/release.test.mjs +33 -12
- package/bin/lean/sandbox-remote.mjs +35 -4
- package/bin/lean/schedd.mjs +2 -2
- package/bin/pool/agent.mjs +105 -15
- package/bin/pool/cli.mjs +22 -4
- package/bin/pool/docker.mjs +2 -0
- package/bin/pool/image-manifest.mjs +24 -0
- package/bin/pool/image-manifest.test.mjs +20 -0
- package/bin/pool/lane-tools.mjs +23 -4
- package/bin/pool/lane-tools.test.mjs +27 -7
- package/bin/pool/project-layer.mjs +142 -0
- package/bin/pool/project-layer.test.mjs +73 -0
- package/bin/pool/router.mjs +20 -6
- package/bin/pool/version.mjs +45 -2
- package/bin/review-staging.mjs +63 -21
- package/bin/stats/tool-parks.mjs +29 -0
- package/bin/stats/tool-parks.test.mjs +21 -0
- package/commands/review-pr-staging.md +1 -1
- package/docs/CONFIG.md +20 -0
- package/package.json +1 -1
- package/pool/image/Dockerfile +1 -1
- 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
|
+
});
|
package/bin/pool/router.mjs
CHANGED
|
@@ -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) =>
|
|
661
|
-
[route("GET", "/sandboxes/:id/result"), fd(async ({ id }) =>
|
|
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`. */
|
package/bin/pool/version.mjs
CHANGED
|
@@ -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 =
|
|
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);
|
package/bin/review-staging.mjs
CHANGED
|
@@ -33,7 +33,7 @@ import { attemptGuard } from "./lean/release-flakes.mjs";
|
|
|
33
33
|
import { requiredChecksRead } from "./lean/effects.mjs";
|
|
34
34
|
|
|
35
35
|
const INSTALL_ROOT = fileURLToPath(new URL("..", import.meta.url));
|
|
36
|
-
const USAGE = "usage: forgedock review-staging [<PR number|PR URL>] [--thorough | --delta <from-sha>] [--json]\n" +
|
|
36
|
+
const USAGE = "usage: forgedock review-staging [<PR number|PR URL>] [--thorough | --delta <from-sha>] [--allow-ci-pending | --gate-only] [--json]\n" +
|
|
37
37
|
" forgedock review-staging [<PR>] --finalize --test-gate-output <file> [--notes-dropped <n>] [--json]\n" +
|
|
38
38
|
" forgedock review-staging [<PR>] --summary [--filed <issue>]... [--json]\n" +
|
|
39
39
|
" forgedock review-staging [<PR>] --post-reviewer <domain> --body-file <file>";
|
|
@@ -53,13 +53,15 @@ class Stop extends Error {
|
|
|
53
53
|
|
|
54
54
|
/** argv -> {pr, thorough, json, mode, testGateOutput, notesDropped, filed, delta}. Throws Stop(2) on anything else. */
|
|
55
55
|
export function parseArgs(argv) {
|
|
56
|
-
const o = { pr: null, thorough: false, json: false, mode: "pre", testGateOutput: null, notesDropped: 0, filed: [], delta: null, domain: null, bodyFile: null };
|
|
56
|
+
const o = { pr: null, thorough: false, json: false, mode: "pre", testGateOutput: null, notesDropped: 0, filed: [], delta: null, domain: null, bodyFile: null, allowCiPending: false, gateOnly: false };
|
|
57
57
|
const setMode = (m, a) => { if (o.mode !== "pre") throw new Stop(2, [`review-staging: ${a} cannot be combined with --${o.mode}`, USAGE]); o.mode = m; };
|
|
58
58
|
const value = (i, a) => { const v = argv[i + 1]; if (v == null || v.startsWith("--")) throw new Stop(2, [`review-staging: ${a} requires a value`, USAGE]); return v; };
|
|
59
59
|
for (let i = 0; i < argv.length; i++) {
|
|
60
60
|
const a = argv[i];
|
|
61
61
|
if (a === "--thorough") o.thorough = true;
|
|
62
62
|
else if (a === "--json") o.json = true;
|
|
63
|
+
else if (a === "--allow-ci-pending") o.allowCiPending = true;
|
|
64
|
+
else if (a === "--gate-only") o.gateOnly = true;
|
|
63
65
|
else if (a === "--finalize") setMode("finalize", a);
|
|
64
66
|
else if (a === "--summary") setMode("summary", a);
|
|
65
67
|
else if (a === "--post-reviewer") { setMode("post-reviewer", a); o.domain = value(i++, a); }
|
|
@@ -90,6 +92,7 @@ export function parseArgs(argv) {
|
|
|
90
92
|
if (o.mode !== "post-reviewer" && o.bodyFile) throw new Stop(2, ["review-staging: --body-file belongs to --post-reviewer", USAGE]);
|
|
91
93
|
if (o.mode !== "finalize" && (o.testGateOutput != null || o.notesDropped)) throw new Stop(2, ["review-staging: --test-gate-output/--notes-dropped belong to --finalize", USAGE]);
|
|
92
94
|
if (o.mode !== "summary" && o.filed.length) throw new Stop(2, ["review-staging: --filed belongs to --summary", USAGE]);
|
|
95
|
+
if (o.mode !== "pre" && (o.gateOnly || o.allowCiPending)) throw new Stop(2, ["review-staging: --allow-ci-pending belongs to the pre-dispatch", USAGE]);
|
|
93
96
|
if (o.mode !== "pre" && o.thorough) throw new Stop(2, ["review-staging: --thorough belongs to the pre-dispatch", USAGE]);
|
|
94
97
|
if (o.mode !== "pre" && o.delta) throw new Stop(2, ["review-staging: --delta belongs to the pre-dispatch (--finalize reads it from the review context)", USAGE]);
|
|
95
98
|
if (o.thorough && o.delta) throw new Stop(2, ["review-staging: --delta cannot be combined with --thorough", USAGE]);
|
|
@@ -233,6 +236,28 @@ async function retryGh(io, args) {
|
|
|
233
236
|
}
|
|
234
237
|
}
|
|
235
238
|
|
|
239
|
+
/** Phase 0A: the bundle PR set, then the open review-finding gate. Throws Stop(1) on a block. @returns {{common, branches, prsFile, gate}} */
|
|
240
|
+
async function bundleAndGate(io, c, pr, sd, env) {
|
|
241
|
+
const common = ["--repo", c.ghRepo, "--pr", String(pr)];
|
|
242
|
+
const branches = ["--default", c.defaultBranch, "--staging", c.stagingBranch];
|
|
243
|
+
const prsFile = join(sd, `${pr}_bundle-prs.txt`);
|
|
244
|
+
const b = await bash(io, "review-staging-pre.sh", ["bundle", ...common, ...branches, "--sd", sd], env);
|
|
245
|
+
if (b.stdout.trim()) io.err(b.stdout.trim());
|
|
246
|
+
if (b.code !== 0) throw new Stop(1, [b.stderr.trim(), `REVIEW_RESULT: status: BLOCKED, blocker: bundle PR set failed (exit ${b.code})`].filter(Boolean));
|
|
247
|
+
let bundlePrs = "";
|
|
248
|
+
try { bundlePrs = io.readFile(prsFile); } catch { /* unreadable: fail closed below */ }
|
|
249
|
+
// An empty bundle would let the gate pass vacuously (forge#4470): nothing gated is never a pass.
|
|
250
|
+
if (!bundlePrs.split("\n").some((l) => /^\d+$/.test(l.trim()))) throw new Stop(1, [`REVIEW_RESULT: status: BLOCKED, blocker: bundle PR set is empty or unreadable (${prsFile}); nothing gated (fail closed)`]);
|
|
251
|
+
const g = await bash(io, "review-staging-pre.sh", ["gate", ...common, "--prs-file", prsFile], env);
|
|
252
|
+
if (g.code !== 0) {
|
|
253
|
+
const out = g.stdout.trim();
|
|
254
|
+
throw new Stop(1, [out, g.stderr.trim(), /RESULT: BLOCK DEPLOY/.test(out) ? "" : "RESULT: BLOCK DEPLOY"].filter(Boolean));
|
|
255
|
+
}
|
|
256
|
+
const gate = /human override/.test(g.stdout) ? "PASS (override)" : "PASS";
|
|
257
|
+
|
|
258
|
+
return { common, branches, prsFile, gate };
|
|
259
|
+
}
|
|
260
|
+
|
|
236
261
|
async function main(argv, io) {
|
|
237
262
|
const a = parseArgs(argv);
|
|
238
263
|
if (a.mode === "finalize") return finalize(a, io);
|
|
@@ -249,6 +274,11 @@ async function main(argv, io) {
|
|
|
249
274
|
const head = await headSha(io, c, pr);
|
|
250
275
|
if (a.delta && a.delta === head) throw new Stop(1, [`REVIEW_RESULT: status: BLOCKED, blocker: --delta ${head} is the current head of PR #${pr}: nothing changed since that pass, nothing to review`]);
|
|
251
276
|
const sha7 = head.slice(0, 7);
|
|
277
|
+
if (a.gateOnly) { // the release job's first check: an open review-finding issue blocks before CI or any reviewer; posts only the gate marker
|
|
278
|
+
const { gate } = await bundleAndGate(io, c, pr, sd, env);
|
|
279
|
+
io.out(a.json ? JSON.stringify({ pr, headSha: head, gate }) : `OPEN_FINDING_GATE: ${gate} on PR #${pr}`);
|
|
280
|
+
return 0;
|
|
281
|
+
}
|
|
252
282
|
// #4865: with selftest.sandbox_repo set, the release needs a passing live selftest for exactly this head (fail closed).
|
|
253
283
|
// Without a sandbox repo there is nothing the harness can run against, so the gate is skipped and says so.
|
|
254
284
|
if (c.sandboxRepo) {
|
|
@@ -264,26 +294,14 @@ async function main(argv, io) {
|
|
|
264
294
|
} catch { /* unreadable: treated as a first pass */ }
|
|
265
295
|
const priorOpen = priorRoutes > 0 ? await priorFindings(io, c, pr, "open") : [];
|
|
266
296
|
const priorResolved = priorRoutes > 0 ? await priorFindings(io, c, pr, "closed") : [];
|
|
267
|
-
await retryGh(io, ["pr", "comment", String(pr), "-R", c.ghRepo, "--body", `<!-- FORGE:REVIEW_ROUTE mode=staging-deploy spec=review-pr-staging.md sha=${sha7} -->`]);
|
|
297
|
+
await retryGh(io, ["pr", "comment", String(pr), "-R", c.ghRepo, "--body", `<!-- FORGE:REVIEW_ROUTE mode=staging-deploy spec=review-pr-staging.md sha=${sha7}${a.allowCiPending ? " allow_ci_pending=true" : ""} -->`]);
|
|
268
298
|
io.writeFile(join(sd, `staging_pr_number.${runKey(io.env)}`), `${pr}\n`);
|
|
269
299
|
|
|
270
|
-
// 0A: bundle PR set, then the open review-finding gate
|
|
271
|
-
const common =
|
|
272
|
-
|
|
273
|
-
const
|
|
274
|
-
|
|
275
|
-
if (b.stdout.trim()) io.err(b.stdout.trim());
|
|
276
|
-
if (b.code !== 0) throw new Stop(1, [b.stderr.trim(), `REVIEW_RESULT: status: BLOCKED, blocker: bundle PR set failed (exit ${b.code})`].filter(Boolean));
|
|
277
|
-
let bundlePrs = "";
|
|
278
|
-
try { bundlePrs = io.readFile(prsFile); } catch { /* unreadable: fail closed below */ }
|
|
279
|
-
// An empty bundle would let the gate pass vacuously (forge#4470): nothing gated is never a pass.
|
|
280
|
-
if (!bundlePrs.split("\n").some((l) => /^\d+$/.test(l.trim()))) throw new Stop(1, [`REVIEW_RESULT: status: BLOCKED, blocker: bundle PR set is empty or unreadable (${prsFile}); nothing gated (fail closed)`]);
|
|
281
|
-
const g = await bash(io, "review-staging-pre.sh", ["gate", ...common, "--prs-file", prsFile], env);
|
|
282
|
-
if (g.code !== 0) {
|
|
283
|
-
const out = g.stdout.trim();
|
|
284
|
-
throw new Stop(1, [out, g.stderr.trim(), /RESULT: BLOCK DEPLOY/.test(out) ? "" : "RESULT: BLOCK DEPLOY"].filter(Boolean));
|
|
285
|
-
}
|
|
286
|
-
const gate = /human override/.test(g.stdout) ? "PASS (override)" : "PASS";
|
|
300
|
+
// 0A: bundle PR set, then the open review-finding gate (it runs first: an open finding blocks before CI or any reviewer)
|
|
301
|
+
const { common, branches, prsFile, gate } = await bundleAndGate(io, c, pr, sd, env);
|
|
302
|
+
// CI green next (default, no off switch): a review of a head whose required checks are pending or red is wasted when CI then moves the head.
|
|
303
|
+
const ciBlock = a.allowCiPending ? null : await ciNotGreen(io, c, pr, env);
|
|
304
|
+
if (ciBlock) throw new Stop(1, [`REVIEW_RESULT: status: BLOCKED, blocker: CI not green on ${sha7} (pending: ${ciBlock.pending.join(", ") || "none"}, failing: ${ciBlock.failing.join(", ") || "none"}); review starts after CI is green`]);
|
|
287
305
|
|
|
288
306
|
// 0B.1: scope
|
|
289
307
|
const s = await bash(io, "review-staging-pre.sh", ["scope", ...common, ...branches, "--prs-file", prsFile, "--sd", sd], env);
|
|
@@ -492,7 +510,7 @@ async function finalize(a, io) {
|
|
|
492
510
|
const items = worklist.items;
|
|
493
511
|
const state = {
|
|
494
512
|
pr, head, bundle, codeBranch, scopeMode, delta, testGate: { verdict: tg.verdict, reason: tg.reason }, counts, notes,
|
|
495
|
-
confirmedCritical: confirmed("CRITICAL"), confirmedHigh: confirmed("HIGH"), resolved,
|
|
513
|
+
confirmedCritical: confirmed("CRITICAL"), confirmedHigh: confirmed("HIGH"), confirmedMedium: confirmed("MEDIUM"), confirmedIds: findings.filter((f) => !resolvedBy.has(f.id) && upper(f.confidence) === "CONFIRMED").map((f) => f.id), resolved,
|
|
496
514
|
toFile: items.filter((i) => i.action === "file"), skipped: items.filter((i) => String(i.action).startsWith("skip-")),
|
|
497
515
|
};
|
|
498
516
|
io.writeFile(join(sd, `${pr}_finalize.json`), JSON.stringify(state));
|
|
@@ -567,6 +585,30 @@ export function cancelOnlyChecks(checks, required = []) {
|
|
|
567
585
|
return [...seen.values()];
|
|
568
586
|
}
|
|
569
587
|
|
|
588
|
+
/** Required checks on the head, by state: `pending` (running, or required but not reported yet) and `failing` (fail/cancel and not pending). */
|
|
589
|
+
export function ciState(checks, required = []) {
|
|
590
|
+
const rows = redChecks(checks, required).blockRows;
|
|
591
|
+
const names = (f) => [...new Set(rows.filter(f).map((k) => String(k.name)))];
|
|
592
|
+
const pend = names((k) => k.bucket === "pending");
|
|
593
|
+
const seen = new Set(checks.map((k) => k?.name));
|
|
594
|
+
const missing = [...new Set(required)].filter((n) => !CI_EXCLUDED_CHECKS.includes(n) && !seen.has(n));
|
|
595
|
+
const pending = [...new Set([...pend, ...missing])];
|
|
596
|
+
return { pending, failing: names((k) => k.bucket === "fail" || k.bucket === "cancel").filter((n) => !pending.includes(n)), green: !pending.length && !rows.length };
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/** Pre-dispatch CI read: `null` when green (or the PR has no checks), else `{pending, failing}`. An unreadable read fails closed. */
|
|
600
|
+
async function ciNotGreen(io, c, pr, env) {
|
|
601
|
+
const r = await io.run("gh", ["pr", "checks", String(pr), "-R", c.ghRepo, "--json", "name,bucket,link"], { env, cwd: io.cwd });
|
|
602
|
+
const checks = r.code === 0 || r.code === 8 ? parseChecks(r.stdout) : null;
|
|
603
|
+
if (!checks) {
|
|
604
|
+
if (/no checks reported/i.test(`${r.stderr ?? ""}${r.stdout ?? ""}`)) return null;
|
|
605
|
+
return { pending: [], failing: ["checks unreadable"] };
|
|
606
|
+
}
|
|
607
|
+
const read = await requiredChecksRead({ gh: io.gh, repo: c.ghRepo, lane: c.defaultBranch });
|
|
608
|
+
const st = ciState(checks, requiredSet(read, c.extraRequiredChecks));
|
|
609
|
+
return st.green ? null : st;
|
|
610
|
+
}
|
|
611
|
+
|
|
570
612
|
const CI_POLL_MS = 20_000, CI_POLL_MAX = 45;
|
|
571
613
|
|
|
572
614
|
/** One `gh run rerun --failed` per cancelled run of the cancel-only required checks (#6014: never past RERUN_ATTEMPT_CAP reruns of a run), then wait until none of them is pending. @returns the re-read checks, or `checks` when nothing could be rerun. */
|
|
@@ -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
|
+
});
|
|
@@ -89,7 +89,7 @@ The **Evidence-Based Review Protocol** and **Structured Findings Protocol** are
|
|
|
89
89
|
|
|
90
90
|
## Step 1: Pre-dispatch (`forgedock review-staging`)
|
|
91
91
|
|
|
92
|
-
**This step is MANDATORY and runs first. No step may be skipped.** One CLI call runs the deterministic pre-dispatch (forge#4358): the `FORGE:REVIEW_ROUTE` marker (route assertion and audit trail), prior-finding awareness on re-entry, the Phase 0A bundle PR set and open review-finding gate (it posts `FORGE:GATE_FAILURE` / `FORGE:GATE_PASS` and stops on a block, including degraded bundle panels), the 0B.1 bundle review scope (`scripts/review-staging-pre.sh`), the 0C prepare (`scripts/review-prepare.sh --no-delta --build-gate advisory`) and the risk-tiered roster (`scripts/review-roster.sh`, inside prepare). It writes one reviewer brief per roster domain and truncates the PR-keyed launched-agent file. All state lives in `$FORGE_SCRATCHPAD` (default `$PWD/.forge-scratch`) under the PR-keyed names the later steps read. Every helper comes from the ForgeDock install, never from the repo under review.
|
|
92
|
+
**This step is MANDATORY and runs first. No step may be skipped.** Order: the open-finding gate, then CI green, then one review pass (the v1.0 contract). The call refuses (`REVIEW_RESULT: status: BLOCKED, blocker: CI not green on <sha> (pending: ..., failing: ...)`) while a required check on the head is pending or failing, also with `--delta`; wait for green (the release job does this in its `ci-green` step) and rerun. `--allow-ci-pending` overrides and is recorded in the `FORGE:REVIEW_ROUTE` marker. One CLI call runs the deterministic pre-dispatch (forge#4358): the `FORGE:REVIEW_ROUTE` marker (route assertion and audit trail), prior-finding awareness on re-entry, the Phase 0A bundle PR set and open review-finding gate (it posts `FORGE:GATE_FAILURE` / `FORGE:GATE_PASS` and stops on a block, including degraded bundle panels), the 0B.1 bundle review scope (`scripts/review-staging-pre.sh`), the 0C prepare (`scripts/review-prepare.sh --no-delta --build-gate advisory`) and the risk-tiered roster (`scripts/review-roster.sh`, inside prepare). It writes one reviewer brief per roster domain and truncates the PR-keyed launched-agent file. All state lives in `$FORGE_SCRATCHPAD` (default `$PWD/.forge-scratch`) under the PR-keyed names the later steps read. Every helper comes from the ForgeDock install, never from the repo under review.
|
|
93
93
|
|
|
94
94
|
**Idempotent re-review (merge-train aware)**: <!-- Added: forge#1328, extended: forge#1332 --> This spec is safe to invoke multiple times on the same PR. Each invocation posts a new `FORGE:REVIEW_ROUTE` marker with the current SHA, so re-review passes are distinguished by SHA, not by PR number. Prior open findings are carried forward into the briefs (do not re-file them). Prior resolved findings are excluded from the verdict.
|
|
95
95
|
|
package/docs/CONFIG.md
CHANGED
|
@@ -850,6 +850,26 @@ release:
|
|
|
850
850
|
|
|
851
851
|
`forgedock release verify <release id>` (#5562) re-runs the deploy verification of a release that passed LIVE_CHECK; a release id (`rYYYYMMDD-HHMMSS-N`) is never mistaken for a sha. Policy `verify` block (default branch, `.forge/release.yaml`): `results` (list of `{workflow, kind: smoke|edge|convergence}`, layer 1), `workflow` (verification workflow dispatched through the epoch fence, layer 2), `slis` (layer 3, entries `{name, tolerance, worse: higher|lower, abs}` read through an injected read-only metric source; without one the layer reports `sli: skipped (no host)`), `post_deploy_checks_file` (layer 4, each issue's `[check:id]` runs once; entries with `for` are windowed and become rollup follow-ups), `flags` (layer 5, `{flag, off_command}` verified in the off state, never activated) and `close_requires: verified|deployed`. With `verified` (default once the block is set) an issue is closed only after a `FORGE:VERIFIED <deploy sha>` comment; `deployed` closes without it. Soak minutes by risk class: low 10, medium 20, full 30, p0 15, overridden by `lanes.<lane>.soak_min` (a number or a map by class). An empty `verify` block leaves VERIFYING a bare transition to LIVE.
|
|
852
852
|
|
|
853
|
+
### Default release flow: the v1.0 contract (#6164)
|
|
854
|
+
|
|
855
|
+
`forgedock release` and `forgedock review-staging` follow the original release contract of `commands/review-pr-staging.md` (commit dcfb86bf, 2026-06-05), restored as the default for every repo. There is no switch to turn it off.
|
|
856
|
+
|
|
857
|
+
1. **Open-finding gate first**: an open `review-finding` issue blocks the release before CI or any reviewer.
|
|
858
|
+
2. **`ci-green` step** before `review`: waits for every required check on the release PR head (protection, rulesets and `gate.required_checks`; `forgedock/verify`, `forge/deploy-gate` and the gate-marker check excluded). A failed check is rerun once; a pass on the rerun counts as green and files a `flaky-test` issue naming the test when the log shows it. A check still red after its rerun gets one CI fix round in the release PR, then CI is awaited again. A draft release PR (host preflight mode) has no Actions CI yet, so the step skips it.
|
|
859
|
+
3. **One review pass** on the green head. Every finding is filed as an issue (Phase 7). Nothing the review finds is fixed inside the release PR: no review fix lanes and no review-driven delta passes. A head that moves during review stops the job; re-run it.
|
|
860
|
+
4. **Verdict**: a CONFIRMED CRITICAL/HIGH finding (or a failed guard) means BLOCK. The job stops with `blocked: review blockers #A #B`, the release PR is closed, the blocker issues are added to the repo's open orchestrate batch (`orchestrate --add`) when one exists, and the next release starts fresh after they merge (the open-finding gate enforces it). Without blockers the release merges on GATE_PASS and everything else stays filed for later.
|
|
861
|
+
5. `forgedock review-staging <PR>` pre-dispatch (also `--delta`) runs the gate, then refuses while a required check is pending or failing (`CI not green on <sha> (pending: ..., failing: ...)`); `--allow-ci-pending` overrides and is recorded in the route marker. `--gate-only` runs just the open-finding gate.
|
|
862
|
+
6. `release status` prints `timing`: `ci_green_min`, `review_min`, `fix_rounds`, `review_passes`; the release ledger mirrors them.
|
|
863
|
+
|
|
864
|
+
Drift this removes: #4358 and #4360 (pre-dispatch and delta passes in the review loop), #5212 (review step fix lanes and delta passes), #5567 (CI and panel started on the same head, `ci.fix.co_start`, now ignored).
|
|
865
|
+
|
|
866
|
+
```yaml
|
|
867
|
+
release:
|
|
868
|
+
block_severity: high # lowest blocking severity: critical | high | medium (default high)
|
|
869
|
+
ci_green_max_wait_min: 40 # how long ci-green waits for pending checks before it blocks (max 240)
|
|
870
|
+
review_fixes: false # compatibility only: true restores the #5212 review fix lanes and delta passes
|
|
871
|
+
```
|
|
872
|
+
|
|
853
873
|
### `.forge/release.yaml` (#5551)
|
|
854
874
|
|
|
855
875
|
Nested release policy (`schema: 1`) lives in a committed `.forge/release.yaml`, not in the host-local forge.yaml. It is read from the default branch with `git show origin/<default>:.forge/release.yaml`, never from the PR head or the worktree, so a PR cannot weaken its own gates. The flat `release.*` keys above stay the fallback when the file is absent there. Sections: `branches`, `trust`, `state`, `units`, `couplings`, `contracts`, `forces`, `classify`, `risk`, `plan`, `lanes`, `merge`, `ci`, `preflight`, `deploy`, `verify`, `rollback`, `controls`.
|