forgedock 1.37.0 → 1.38.1
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/outcome-codes.mjs +12 -3
- package/bin/engine/telemetry-seam.mjs +5 -0
- package/bin/engine-cli.mjs +97 -18
- package/bin/forgedock.mjs +13 -2
- package/bin/lean/activation.mjs +76 -0
- package/bin/lean/activation.test.mjs +75 -0
- package/bin/lean/admission.mjs +17 -1
- package/bin/lean/batch.mjs +51 -21
- package/bin/lean/batch.test.mjs +95 -5
- package/bin/lean/conformance.mjs +53 -4
- package/bin/lean/conformance.test.mjs +24 -1
- package/bin/lean/decision-engine.mjs +217 -0
- package/bin/lean/decision-engine.test.mjs +159 -0
- package/bin/lean/effects.mjs +39 -13
- package/bin/lean/execution.mjs +74 -5
- package/bin/lean/execution.test.mjs +64 -1
- package/bin/lean/explore.test.mjs +1 -1
- package/bin/lean/guards.mjs +3 -2
- package/bin/lean/guards.test.mjs +24 -3
- package/bin/lean/heavy.mjs +15 -2
- package/bin/lean/heavy.test.mjs +31 -2
- package/bin/lean/issuewatch-release.mjs +245 -0
- package/bin/lean/issuewatch-release.test.mjs +244 -0
- package/bin/lean/issuewatch.mjs +386 -0
- package/bin/lean/issuewatch.test.mjs +280 -0
- package/bin/lean/lane.mjs +4 -3
- package/bin/lean/lane.test.mjs +12 -0
- package/bin/lean/lean.mjs +103 -16
- package/bin/lean/lean.test.mjs +127 -5
- package/bin/lean/needs-human-premise.mjs +177 -0
- package/bin/lean/needs-human-premise.test.mjs +136 -0
- package/bin/lean/orchestrate-blocked.test.mjs +71 -0
- package/bin/lean/orchestrate.mjs +93 -21
- package/bin/lean/postdeploy-check.mjs +88 -2
- package/bin/lean/postdeploy-check.test.mjs +78 -0
- package/bin/lean/prodwatch-sources.mjs +165 -0
- package/bin/lean/prodwatch-sources.test.mjs +108 -0
- package/bin/lean/prompts.mjs +9 -3
- package/bin/lean/recovery.test.mjs +14 -0
- package/bin/lean/relay.mjs +182 -0
- package/bin/lean/relay.test.mjs +214 -0
- package/bin/lean/sandbox-provider.contract.test.mjs +13 -1
- package/bin/lean/sandbox-remote.mjs +53 -9
- package/bin/lean/sched.test.mjs +30 -0
- package/bin/lean/schedd-health.mjs +69 -0
- package/bin/lean/schedd-health.test.mjs +51 -0
- package/bin/lean/schedd.mjs +29 -12
- package/bin/lean/schedd.test.mjs +40 -4
- package/bin/lean/sequence.mjs +57 -24
- package/bin/lean/sequence.test.mjs +71 -0
- package/bin/pool/agent.mjs +15 -1
- package/bin/pool/router.mjs +43 -5
- package/bin/runner.mjs +18 -1
- package/commands/deploy-pr.md +12 -0
- package/commands/forgedock-init.md +1 -0
- package/commands/orchestrate/phase-4-execution.md +1 -0
- package/commands/orchestrate.md +1 -0
- package/commands/review-pr.md +17 -13
- package/docs/CONFIG.md +73 -2
- package/docs/DECISIONS.md +32 -0
- package/docs/ISSUE-WATCH.md +95 -0
- package/docs/NORTHSTAR-TEMPLATE.md +21 -0
- package/docs/OUTCOME-CODES.md +2 -1
- package/docs/TELEMETRY.md +7 -0
- package/package.json +1 -2
- package/pool/README.md +1 -1
- package/pool/image/Dockerfile +2 -1
- package/pool/image/cs-relay +31 -0
- package/pool/image/entrypoint.sh +10 -0
- package/pool/install/install-schedd.sh +22 -0
- package/pool/install/unit-hardening.sh +6 -0
- package/scripts/postdeploy-rollup-link.sh +40 -0
- package/scripts/postdeploy-rollup-link.test.sh +46 -0
- package/scripts/refresh-bot-token.sh +122 -0
- package/scripts/review-delta.sh +14 -4
- package/scripts/review-delta.test.sh +21 -0
- package/scripts/review-finalize.sh +69 -25
- package/scripts/review-finalize.test.sh +32 -0
- package/scripts/review-pr-arguments.test.sh +10 -0
- package/scripts/review-pr-changed-verification.test.sh +54 -0
- package/scripts/review-pr-delta-wiring.test.sh +1 -1
package/bin/lean/schedd.mjs
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
* {type:"ok", cancelled:false, finished:true}, nothing written
|
|
21
21
|
* {op:"hold"|"release", id, issues} → {type:"ok", changed, hosted} (#4592): merges into / removes from the batch's `hold` file; a hosted
|
|
22
22
|
* runner admits no held issue from its next pass (running lanes are not stopped)
|
|
23
|
-
* {op:"status"} → {type:"status", pid, batches:[{id, running}]}
|
|
23
|
+
* {op:"status"} → {type:"status", pid, lastTick, batches:[{id, running}]} (#4780: `lastTick` = epoch ms of the last heartbeat; see schedd-health.mjs)
|
|
24
24
|
* Failures answer {type:"error", message}. A client closing its connection never cancels a batch (only `cancel` stops one), and stopping the daemon
|
|
25
25
|
* never stops a lane (lanes are detached sessions). On start the daemon resumes every daemon-hosted batch without a
|
|
26
26
|
* report, so live lanes are re-adopted through the batch runner's `adopt`. It exits after `idleMs` with no batch and no client.
|
|
@@ -36,17 +36,22 @@ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, write
|
|
|
36
36
|
import { createConnection, createServer } from "node:net";
|
|
37
37
|
import { spawn } from "node:child_process";
|
|
38
38
|
import { tmpdir } from "node:os";
|
|
39
|
-
import {
|
|
39
|
+
import { createHash } from "node:crypto";
|
|
40
|
+
import { join, resolve } from "node:path";
|
|
41
|
+
import { fileURLToPath } from "node:url";
|
|
40
42
|
import { schedDir, pidAlive } from "./sched.mjs";
|
|
41
|
-
import {
|
|
43
|
+
import { HEARTBEAT_MS, writeHeartbeat, clearHeartbeat } from "./schedd-health.mjs";
|
|
44
|
+
import { batchRoot, listBatches, openBatch, SECRET_ENV } from "./batch.mjs";
|
|
42
45
|
|
|
43
46
|
export const IDLE_MS = 10 * 60 * 1000;
|
|
44
47
|
export const STOP_MS = 10 * 1000;
|
|
45
48
|
export const LOCK_CHECK_MS = 5 * 1000;
|
|
46
49
|
export const DUE_MS = 15 * 60 * 1000; // #4627: how often the due callback (windowed post-deploy monitoring) runs while the daemon is up
|
|
47
50
|
|
|
48
|
-
|
|
49
|
-
|
|
51
|
+
/** #4762: win32 `net` servers only accept named pipes, so the socket is a per-dir pipe there (it vanishes with its server). */
|
|
52
|
+
export function scheddPaths(dir = schedDir(), platform = process.platform) {
|
|
53
|
+
const sock = platform === "win32" ? `\\\\.\\pipe\\forgedock-schedd-${createHash("sha1").update(resolve(dir)).digest("hex").slice(0, 12)}` : join(dir, "schedd.sock");
|
|
54
|
+
return { dir, sock, lock: join(dir, "schedd.lock"), log: join(dir, "schedd.log") };
|
|
50
55
|
}
|
|
51
56
|
|
|
52
57
|
// Env keys a batch keeps for its lanes (account selectors, tool paths); persisted in plan.json (#4691). Session-scoped
|
|
@@ -57,7 +62,6 @@ const ENV_KEEP = /^(PATH|HOME|USER|SHELL|LANG|LC_.*|TMPDIR|CLAUDE_CONFIG_DIR|CLA
|
|
|
57
62
|
const LEGACY_PIN = /^(CLAUDE_.*|ANTHROPIC_.*|GH_.*|GITHUB_.*|FORGEDOCK_.*)$/;
|
|
58
63
|
const SESSION_SCOPED = /^(CLAUDE_PID|CLAUDE_CODE_(SESSION|MESSAGING|ENTRYPOINT|EXECPATH|SSE).*)$/;
|
|
59
64
|
// A secret never rides the allowlist: it resolves at lane start (env, keychain) unless the operator names it as a passthrough.
|
|
60
|
-
export const SECRET_ENV = /(TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|API_?KEY|PRIVATE_?KEY)/i;
|
|
61
65
|
const SESSION_DIR = /(^|\/)(arg0|claude[^/]*)(\/|$)/;
|
|
62
66
|
|
|
63
67
|
/** A forge.yaml glob (`*` within a segment, `**` across segments, `?`) as an anchored RegExp. */
|
|
@@ -137,7 +141,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
137
141
|
log(`schedd: already running (pid ${owner})`);
|
|
138
142
|
return { running: false, owner };
|
|
139
143
|
}
|
|
140
|
-
rmSync(p.sock, { force: true });
|
|
144
|
+
if (process.platform !== "win32") rmSync(p.sock, { force: true });
|
|
141
145
|
|
|
142
146
|
const hosted = new Map(); // batch id -> {id, dir, subs:Set<fn>}
|
|
143
147
|
const conns = new Set();
|
|
@@ -146,6 +150,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
146
150
|
let closing = null, resolveClosed, keepSock = false;
|
|
147
151
|
let lastActive = Date.now();
|
|
148
152
|
const touch = () => { lastActive = Date.now(); };
|
|
153
|
+
let lastTick = Date.now();
|
|
149
154
|
|
|
150
155
|
/** Run one batch here. Resolves with {id, dir} once the batch exists, rejects when it fails before that. */
|
|
151
156
|
const host = ({ argv, cwd, env, keepBreaker = false }, first = null) => new Promise((resolve, reject) => {
|
|
@@ -172,7 +177,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
172
177
|
});
|
|
173
178
|
|
|
174
179
|
const handle = async (req, send) => {
|
|
175
|
-
if (req.op === "status") return send({ type: "status", pid, batches: [...hosted.keys()].map((id) => ({ id, running: true })) }, true);
|
|
180
|
+
if (req.op === "status") return send({ type: "status", pid, lastTick, batches: [...hosted.keys()].map((id) => ({ id, running: true })) }, true);
|
|
176
181
|
if (req.op === "set-parallel") {
|
|
177
182
|
const b = openBatch(root, req.id);
|
|
178
183
|
if (!b.exists()) throw new Error(`no batch ${req.id} in ${root}`);
|
|
@@ -261,12 +266,18 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
261
266
|
});
|
|
262
267
|
await new Promise((res, rej) => { server.once("error", rej); server.listen(p.sock, () => { server.off("error", rej); res(); }); });
|
|
263
268
|
log(`schedd: pid ${pid} listening on ${p.sock}`);
|
|
269
|
+
// #4780: a heartbeat from the event loop itself; a starved or wedged loop stops it and the watchdog restarts the daemon.
|
|
270
|
+
const beat = () => { lastTick = Date.now(); try { writeHeartbeat({ dir, pid, now: () => lastTick }); } catch { /* a full disk must not stop the daemon */ } };
|
|
271
|
+
beat();
|
|
272
|
+
const beatTimer = setInterval(beat, HEARTBEAT_MS);
|
|
273
|
+
beatTimer.unref?.();
|
|
264
274
|
|
|
265
275
|
const closed = new Promise((r) => { resolveClosed = r; });
|
|
266
276
|
const close = () => {
|
|
267
277
|
if (closing) return closing;
|
|
268
278
|
clearInterval(idleTimer);
|
|
269
279
|
clearInterval(lockTimer);
|
|
280
|
+
clearInterval(beatTimer);
|
|
270
281
|
if (dueTimer) clearInterval(dueTimer);
|
|
271
282
|
for (const c of conns) c.destroy();
|
|
272
283
|
const stopping = [...runs.keys()];
|
|
@@ -279,7 +290,8 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
279
290
|
const serverClosed = keepSock ? Promise.resolve(server.unref()) : new Promise((r) => server.close(() => r()));
|
|
280
291
|
closing = Promise.all([serverClosed, stopped]).then(() => {
|
|
281
292
|
try { if (parseInt(readFileSync(p.lock, "utf8"), 10) === pid) rmSync(p.lock, { force: true }); } catch { /* gone */ }
|
|
282
|
-
if (!keepSock) rmSync(p.sock, { force: true });
|
|
293
|
+
if (!keepSock && process.platform !== "win32") rmSync(p.sock, { force: true });
|
|
294
|
+
if (!keepSock) clearHeartbeat(dir);
|
|
283
295
|
resolveClosed();
|
|
284
296
|
});
|
|
285
297
|
return closing;
|
|
@@ -294,7 +306,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
294
306
|
let owner = NaN;
|
|
295
307
|
try { owner = parseInt(readFileSync(p.lock, "utf8"), 10); } catch { /* gone */ }
|
|
296
308
|
if (owner !== pid) { keepSock = true; log(`schedd: lost lock (owner ${Number.isInteger(owner) ? `pid ${owner}` : "none"}), exiting`); close(); }
|
|
297
|
-
else if (!existsSync(p.sock)) { log(`schedd: lost socket ${p.sock}, exiting`); close(); }
|
|
309
|
+
else if (process.platform !== "win32" && !existsSync(p.sock)) { log(`schedd: lost socket ${p.sock}, exiting`); close(); }
|
|
298
310
|
}, lockCheckMs);
|
|
299
311
|
lockTimer.unref?.();
|
|
300
312
|
// #4627: windowed post-deploy checks. One run at a time; a failure is logged and never stops the daemon.
|
|
@@ -306,6 +318,9 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
306
318
|
}, dueMs) : null;
|
|
307
319
|
dueTimer?.unref?.();
|
|
308
320
|
|
|
321
|
+
// #4787: plans written before secrets were dropped still hold token values; scrub them on start.
|
|
322
|
+
for (const id of listBatches(root)) { try { const n = openBatch(root, id).scrubPlan(); if (n.length) log(`schedd: scrubbed ${n.join(", ")} from batch ${id}`); } catch { /* advisory */ } }
|
|
323
|
+
|
|
309
324
|
// Daemon restart: resume every daemon-hosted batch that never wrote its report; live lanes are re-adopted.
|
|
310
325
|
if (resumeOnStart) {
|
|
311
326
|
for (const id of listBatches(root)) {
|
|
@@ -360,8 +375,10 @@ export async function connectDaemon({ dir = schedDir(), spawnDaemon = defaultSpa
|
|
|
360
375
|
}
|
|
361
376
|
}
|
|
362
377
|
|
|
378
|
+
export const SCHEDD_SCRIPT = fileURLToPath(new URL("../forgedock.mjs", import.meta.url));
|
|
379
|
+
|
|
363
380
|
/** `forgedock schedd` in its own session, output to `schedd.log`. */
|
|
364
|
-
export function defaultSpawn({ dir = schedDir(), script =
|
|
381
|
+
export function defaultSpawn({ dir = schedDir(), script = SCHEDD_SCRIPT, env = process.env } = {}) {
|
|
365
382
|
mkdirSync(dir, { recursive: true });
|
|
366
383
|
const out = openSync(scheddPaths(dir).log, "a");
|
|
367
384
|
try {
|
|
@@ -399,4 +416,4 @@ export function request(sock, msg, onMsg = () => {}) {
|
|
|
399
416
|
});
|
|
400
417
|
}
|
|
401
418
|
|
|
402
|
-
export const scheddExists = (dir = schedDir()) => existsSync(scheddPaths(dir).sock);
|
|
419
|
+
export const scheddExists = (dir = schedDir()) => existsSync(process.platform === "win32" ? scheddPaths(dir).lock : scheddPaths(dir).sock);
|
package/bin/lean/schedd.test.mjs
CHANGED
|
@@ -7,9 +7,10 @@ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, write
|
|
|
7
7
|
import { homedir, tmpdir } from "node:os";
|
|
8
8
|
import { join } from "node:path";
|
|
9
9
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
10
|
-
import { openBatch, isLaneAlive, listBatches } from "./batch.mjs";
|
|
11
|
-
import { startDaemon, scheddPaths, connectDaemon, request, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals } from "./schedd.mjs";
|
|
10
|
+
import { openBatch, isLaneAlive, listBatches, SECRET_ENV } from "./batch.mjs";
|
|
11
|
+
import { startDaemon, scheddPaths, connectDaemon, request, SCHEDD_SCRIPT, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals } from "./schedd.mjs";
|
|
12
12
|
import { schedDir } from "./sched.mjs";
|
|
13
|
+
import { readHeartbeat } from "./schedd-health.mjs";
|
|
13
14
|
import { formatTable, orchestrate } from "./orchestrate.mjs";
|
|
14
15
|
import { orchestrateFromCli } from "../engine-cli.mjs";
|
|
15
16
|
|
|
@@ -98,6 +99,20 @@ describe("schedd host scheduler (#4192)", () => {
|
|
|
98
99
|
try { return await fn(); } finally { if (prev === undefined) delete process.env.FORGEDOCK_BATCH_DIR; else process.env.FORGEDOCK_BATCH_DIR = prev; }
|
|
99
100
|
};
|
|
100
101
|
|
|
102
|
+
it("writes a heartbeat that advances, reports lastTick in status and removes it on a clean close (#4780)", async () => {
|
|
103
|
+
const h = host();
|
|
104
|
+
try {
|
|
105
|
+
const child = await h.daemon();
|
|
106
|
+
await until(() => readHeartbeat(h.sched) !== null, 30000);
|
|
107
|
+
const first = readHeartbeat(h.sched);
|
|
108
|
+
assert.equal(first.pid, child.pid);
|
|
109
|
+
const st = await request(await connectDaemon({ dir: h.sched, spawnDaemon: null }), { op: "status" });
|
|
110
|
+
assert.ok(Number.isFinite(st.lastTick) && st.lastTick >= first.ts);
|
|
111
|
+
child.kill("SIGTERM");
|
|
112
|
+
await until(() => readHeartbeat(h.sched) === null && !existsSync(scheddPaths(h.sched).lock), 30000);
|
|
113
|
+
} finally { await h.cleanup(); }
|
|
114
|
+
});
|
|
115
|
+
|
|
101
116
|
it("one daemon hosts every batch: registry slots are the daemon's, its RSS stays ≤ 150 MB, set-parallel goes through it", async () => {
|
|
102
117
|
const h = host();
|
|
103
118
|
try {
|
|
@@ -514,6 +529,12 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
|
|
|
514
529
|
assert.deepEqual(env, { NODE_OPTIONS: "x", ANTHROPIC_API_KEY: "daemon-key", PATH: "/", CLAUDE_CONFIG_DIR: "/acct-b", FORGEDOCK_SCHED_DIR: "/s", LC_CTYPE: "C" });
|
|
515
530
|
});
|
|
516
531
|
|
|
532
|
+
it("#4787: a plan without the token resumes with the daemon's token; SECRET_ENV covers *_KEY", () => {
|
|
533
|
+
assert.ok(SECRET_ENV.test("AWS_ACCESS_KEY") && SECRET_ENV.test("COMPUTESHARE_TOKEN") && !SECRET_ENV.test("KEYBOARD"));
|
|
534
|
+
const env = mergeEnv({ COMPUTESHARE_TOKEN: "daemon-tok", PATH: "/d" }, { PATH: "/" });
|
|
535
|
+
assert.equal(env.COMPUTESHARE_TOKEN, "daemon-tok");
|
|
536
|
+
});
|
|
537
|
+
|
|
517
538
|
it("#4734: the pin keeps non-secret provider selectors, drops secrets and session ids, and droppedEnv names what was left out", () => {
|
|
518
539
|
const client = { PATH: "/", GH_TOKEN: "fresh", CLAUDE_CODE_USE_BEDROCK: "1", ANTHROPIC_BASE_URL: "http://proxy", ANTHROPIC_MODEL: "m", ANTHROPIC_API_KEY: "k",
|
|
519
540
|
FORGEDOCK_POOL_TOKEN: "p", CLAUDE_CONFIG_DIR: "/acct", CLAUDE_CODE_SESSION_ID: "s", CLAUDE_PID: "1" };
|
|
@@ -565,10 +586,10 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
|
|
|
565
586
|
for (const bad of ["msg-token", "sess", "CLAUDE_CODE_", session, wrapper]) assert.equal(raw.includes(bad), false, `${bad} not pinned`);
|
|
566
587
|
await withRoot(h, async () => {
|
|
567
588
|
await capture(() => orchestrateFromCli(["--set-env", id, "MY_VAR=1"], h.client));
|
|
568
|
-
await
|
|
589
|
+
await assert.rejects(() => orchestrateFromCli(["--set-env", id, "GH_TOKEN=abc"], h.client), /never stored in batch state/); // #4787
|
|
569
590
|
assert.equal(openBatch(h.root, id).readPlan().env.MY_VAR, "1");
|
|
570
591
|
const { lines } = await capture(() => orchestrateFromCli(["--show-env", id], h.client));
|
|
571
|
-
assert.
|
|
592
|
+
assert.equal(/GH_TOKEN/.test(lines.join("\n")), false);
|
|
572
593
|
assert.match(lines.join("\n"), /^MY_VAR=1$/m);
|
|
573
594
|
assert.equal(lines.join("\n").includes("abc"), false);
|
|
574
595
|
await capture(() => orchestrateFromCli(["--unset-env", id, "MY_VAR"], h.client));
|
|
@@ -613,3 +634,18 @@ describe("schedd due timer (#4627)", () => {
|
|
|
613
634
|
await d.close();
|
|
614
635
|
});
|
|
615
636
|
});
|
|
637
|
+
|
|
638
|
+
describe("#4762 win32 socket path", () => {
|
|
639
|
+
it("win32 derives a stable per-dir named pipe; other platforms keep the unix socket file", () => {
|
|
640
|
+
const a = scheddPaths("/tmp/a", "win32"), b = scheddPaths("/tmp/b", "win32");
|
|
641
|
+
assert.match(a.sock, /^\\\\\.\\pipe\\forgedock-schedd-[0-9a-f]{12}$/);
|
|
642
|
+
assert.equal(a.sock, scheddPaths("/tmp/a", "win32").sock);
|
|
643
|
+
assert.notEqual(a.sock, b.sock);
|
|
644
|
+
assert.equal(a.lock, scheddPaths("/tmp/a").lock);
|
|
645
|
+
for (const pl of ["linux", "darwin"]) assert.equal(scheddPaths("/tmp/a", pl).sock, join("/tmp/a", "schedd.sock"));
|
|
646
|
+
});
|
|
647
|
+
it("the spawn script is a filesystem path, not a URL pathname", () => {
|
|
648
|
+
assert.ok(existsSync(SCHEDD_SCRIPT), SCHEDD_SCRIPT);
|
|
649
|
+
assert.doesNotMatch(SCHEDD_SCRIPT, /^\/[A-Za-z]:/);
|
|
650
|
+
});
|
|
651
|
+
});
|
package/bin/lean/sequence.mjs
CHANGED
|
@@ -137,8 +137,7 @@ export function headerOnlyChange(was, now, fromPath, toPath) {
|
|
|
137
137
|
const split = (t) => { const s = String(t), i = s.indexOf("\n"); return i < 0 ? [s, ""] : [s.slice(0, i), s.slice(i)]; };
|
|
138
138
|
const [h1, r1] = split(was), [h2, r2] = split(now);
|
|
139
139
|
if (r1 !== r2) return false;
|
|
140
|
-
|
|
141
|
-
return mapped === h2;
|
|
140
|
+
return swapNum(h1.replaceAll(stemOf(fromPath), stemOf(toPath)), from, to) === h2;
|
|
142
141
|
}
|
|
143
142
|
|
|
144
143
|
/** Lane-added numbered files with their blobs, recorded before a renumber so verifyRenumber can prove the SQL kept. */
|
|
@@ -146,13 +145,23 @@ export const snapshotLane = ({ git, base }) => laneNumbered(git, base).catch(()
|
|
|
146
145
|
|
|
147
146
|
const stemOf = (p) => basename(p).replace(/\.[^.]*$/, "");
|
|
148
147
|
const word = (x) => new RegExp(`(?<![\\w-])${esc(x)}(?![\\w-])`, "g");
|
|
149
|
-
|
|
150
|
-
|
|
148
|
+
const swapNum = (s, from, to) => s.replace(new RegExp(`(?<!\\d)0*${Number(from)}(?!\\d)`, "g"), (tok) => (tok.length >= to.length ? to : String(Number(to))));
|
|
149
|
+
/**
|
|
150
|
+
* #4386/#4732: the one substitution a renumber may make: every move's old stem (a moved `<stem>_rollback` file included, as its own move) → new stem,
|
|
151
|
+
* in any file, and the moved file's own number in its heading (Markdown) or first line (SQL). The engine writes it and
|
|
152
|
+
* verifyRenumber compares against it, so a migration's own header and rollback pointer follow the new number.
|
|
153
|
+
*/
|
|
154
|
+
export function renumberText(text, path, moves) {
|
|
151
155
|
let t = String(text);
|
|
152
156
|
for (const m of moves) t = t.replace(word(stemOf(m.from)), stemOf(m.to));
|
|
153
157
|
const own = moves.find((m) => m.from === path);
|
|
154
|
-
|
|
158
|
+
if (!own || !numOf(own.from) || !numOf(own.to)) return t;
|
|
159
|
+
if (/\.mdx?$/i.test(own.to)) return retitle(t, numOf(own.from), numOf(own.to));
|
|
160
|
+
if (!/\.sql$/i.test(own.to)) return t;
|
|
161
|
+
const i = t.indexOf("\n");
|
|
162
|
+
return swapNum(i < 0 ? t : t.slice(0, i), numOf(own.from), numOf(own.to)) + (i < 0 ? "" : t.slice(i));
|
|
155
163
|
}
|
|
164
|
+
const normalise = renumberText;
|
|
156
165
|
/** A numbered document's own number in its first heading (else its first non-empty line): 0017 → 0018, or 17 → 18. */
|
|
157
166
|
function retitle(text, oldNum, newNum) {
|
|
158
167
|
const ls = String(text).split("\n");
|
|
@@ -180,7 +189,7 @@ export async function verifyRenumber({ git, base, before = [], moves = null }) {
|
|
|
180
189
|
const now = await laneNumbered(git, base);
|
|
181
190
|
const rest = (p) => basename(p).slice(numOf(p).length);
|
|
182
191
|
const mv = moves?.length ? moves : before.flatMap((b) => {
|
|
183
|
-
const to = now.find((f) => dirname(f.path) === dirname(b.path) && f.path !== b.path && rest(f.path) === rest(b.path)
|
|
192
|
+
const to = now.find((f) => dirname(f.path) === dirname(b.path) && f.path !== b.path && rest(f.path) === rest(b.path));
|
|
184
193
|
return to && !now.some((f) => f.path === b.path) ? [{ from: b.path, to: to.path }] : [];
|
|
185
194
|
});
|
|
186
195
|
for (const b of before.filter((f) => !f.path.endsWith(".json"))) {
|
|
@@ -215,10 +224,11 @@ const SUPPORTED_RE = /\.(?:sql|md|mdx)$/i;
|
|
|
215
224
|
* and an index file beside numbered files (README.md, index.md) keeps both sides (union). Commits the merge.
|
|
216
225
|
* #4465: a numbered file (or snapshot) only counts when renumberLane can restore the lane's side: an add/add conflict
|
|
217
226
|
* (no merge-base stage, so the lane added it) in a directory that holds a series on the base being merged (MERGE_HEAD).
|
|
218
|
-
* Any other conflicted file: {unsupported}, and the merge is left as is for the builder.
|
|
219
|
-
*
|
|
227
|
+
* Any other conflicted file: {unsupported}, and the merge is left as is for the builder. #4732: `partial`
|
|
228
|
+
* resolves only the sequence files, leaves the others conflicted and uncommitted, and returns {remaining}. Never throws.
|
|
229
|
+
* @returns {Promise<{ok:true}|{remaining:string[]}|{unsupported:string}>}
|
|
220
230
|
*/
|
|
221
|
-
export async function resolveSequenceConflicts({ git, files = [] }) {
|
|
231
|
+
export async function resolveSequenceConflicts({ git, files = [], partial = false }) {
|
|
222
232
|
try {
|
|
223
233
|
const g = out(git);
|
|
224
234
|
if (!files.length) return { unsupported: "no conflicted files" };
|
|
@@ -236,8 +246,9 @@ export async function resolveSequenceConflicts({ git, files = [] }) {
|
|
|
236
246
|
if (JOURNAL_RE.test(f) || (indexFile(f) && !numOf(f))) continue;
|
|
237
247
|
if (!(numOf(f) && (await laneAdded(f)))) other.push(f);
|
|
238
248
|
}
|
|
239
|
-
if (other.length) return { unsupported: `non-sequence conflict: ${other.join(", ")}` };
|
|
249
|
+
if (other.length && !partial) return { unsupported: `non-sequence conflict: ${other.join(", ")}` };
|
|
240
250
|
for (const f of files) {
|
|
251
|
+
if (other.includes(f)) continue;
|
|
241
252
|
if (indexFile(f) && !numOf(f)) {
|
|
242
253
|
const tmp = mkdtempSync(join(tmpdir(), "seq-union-"));
|
|
243
254
|
try {
|
|
@@ -263,6 +274,7 @@ export async function resolveSequenceConflicts({ git, files = [] }) {
|
|
|
263
274
|
catch { await git(["rm", "-q", "-f", "--", f]); } // the base deleted it
|
|
264
275
|
}
|
|
265
276
|
}
|
|
277
|
+
if (other.length) return { remaining: other };
|
|
266
278
|
await git(["commit", "--no-edit"]);
|
|
267
279
|
return { ok: true };
|
|
268
280
|
} catch (e) { return { unsupported: `sequence conflict resolution failed: ${String(e?.message ?? e).split("\n")[0]}` }; }
|
|
@@ -283,11 +295,13 @@ const writeJson = (p, o) => writeFileSync(p, `${JSON.stringify(o, null, 2)}\n`);
|
|
|
283
295
|
* 4. per moved SQL with a snapshot: data-only (equal to its lane predecessor but id/prevId) clones the tip snapshot with
|
|
284
296
|
* a fresh id and prevId = tip id; otherwise `regenerate` runs (none configured: unsupported);
|
|
285
297
|
* 5. every tracked file naming an old stem (links, comments) is rewritten to the new one (SQL bodies stay untouched);
|
|
298
|
+
* #4732: a lane-added `<stem>_rollback.*` in another directory moves with its migration to the same number, and the
|
|
299
|
+
* old->new substitution (`renumberText`) is written into every moved or lane-changed file, SQL included.
|
|
286
300
|
* then one commit. Any other migration language, a failed generator or an error: {unsupported}, the branch reset to
|
|
287
301
|
* where it started. Never throws.
|
|
288
|
-
* @returns {Promise<{ok:true, moves:Array<{from,to}>, commit:string|null}|{unsupported:string}>}
|
|
302
|
+
* @returns {Promise<{ok:true, moves:Array<{from,to}>, commit:string|null}|{unsupported:string, nonSequence?:string[]}>}
|
|
289
303
|
*/
|
|
290
|
-
export async function renumberLane({ git, base, cwd, laneRef = "HEAD", regenerate = null, regenerateCustom = null, run = null, uuid = randomUUID, reserve = null }) {
|
|
304
|
+
export async function renumberLane({ git, base, cwd, laneRef = "HEAD", regenerate = null, regenerateCustom = null, run = null, uuid = randomUUID, reserve = null, openNumbers = null }) {
|
|
291
305
|
const custom = regenerateCustom ?? (regenerate ? `${regenerate} --custom` : null);
|
|
292
306
|
const g = out(git);
|
|
293
307
|
const start = (await g(["rev-parse", "HEAD"])).trim();
|
|
@@ -306,16 +320,32 @@ export async function renumberLane({ git, base, cwd, laneRef = "HEAD", regenerat
|
|
|
306
320
|
const odd = collisions.find((c) => !SUPPORTED_RE.test(c.lane));
|
|
307
321
|
if (odd) return { unsupported: `${odd.lane}: no deterministic renumber for .${basename(odd.lane).split(".").pop()} migrations` };
|
|
308
322
|
// #4526: numbers above every other live lane's host reservation, not only above the base (fail-open: base-derived).
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
323
|
+
// #4732: and above the numbers other open PRs on the lane already carry (`openNumbers`, fail-open).
|
|
324
|
+
for (const dir of [...new Set(collisions.map((c) => c.dir))].sort()) {
|
|
325
|
+
const cs = collisions.filter((c) => c.dir === dir), width = cs[0].next.length;
|
|
326
|
+
let floor = Number(cs[0].next) - 1;
|
|
327
|
+
if (openNumbers) {
|
|
328
|
+
try { floor = Math.max(floor, ...(await openNumbers({ dir })).map(Number).filter(Number.isFinite)); } catch { /* fail-open */ }
|
|
329
|
+
cs.forEach((c, i) => { c.next = String(floor + 1 + i).padStart(width, "0"); });
|
|
316
330
|
}
|
|
331
|
+
if (!reserve) continue;
|
|
332
|
+
let got = null;
|
|
333
|
+
try { got = await reserve({ dir, floor, count: cs.length }); } catch { /* fail-open */ }
|
|
334
|
+
const nums = Array.isArray(got?.numbers) ? got.numbers.map(Number) : [];
|
|
335
|
+
if (nums.length === cs.length && nums.every(Number.isInteger)) cs.forEach((c, i) => { c.next = String(nums[i]).padStart(width, "0"); });
|
|
317
336
|
}
|
|
318
337
|
const moves = collisions.map((c) => ({ from: c.lane, to: posix.join(c.dir, c.next + basename(c.lane).slice(c.number.length)), dir: c.dir, oldNum: c.number, newNum: c.next }));
|
|
338
|
+
// #4732: a lane-added rollback file in another directory (`rollbacks/0487_x_rollback.sql`) follows its migration's number.
|
|
339
|
+
const laneAdded = await laneNumbered(git, base, lane);
|
|
340
|
+
for (const m of [...moves].filter((x) => /\.sql$/i.test(x.from))) {
|
|
341
|
+
const rb = laneAdded.find((f) => dirname(f.path) !== m.dir && basename(f.path).startsWith(`${stemOf(m.from)}_rollback.`));
|
|
342
|
+
if (!rb) continue;
|
|
343
|
+
const num = m.newNum.padStart(numOf(rb.path).length, "0"), to = posix.join(dirname(rb.path), num + basename(rb.path).slice(numOf(rb.path).length));
|
|
344
|
+
const had = moves.find((x) => x.from === rb.path);
|
|
345
|
+
if (lines(await g(["-c", "core.quotepath=off", "ls-tree", "--name-only", base, ...inDir(dirname(rb.path))])).some((p) => dirname(p) === dirname(rb.path) && numOf(p) === num)) continue; // the base uses that number there
|
|
346
|
+
if (had) Object.assign(had, { to, newNum: num });
|
|
347
|
+
else moves.push({ from: rb.path, to, dir: dirname(rb.path), oldNum: numOf(rb.path), newNum: num });
|
|
348
|
+
}
|
|
319
349
|
// Plan the journals and snapshots before touching anything, so an unsupported migration leaves the branch as it was.
|
|
320
350
|
const baseList = lines(await g(["-c", "core.quotepath=off", "ls-tree", "-r", "--name-only", base]));
|
|
321
351
|
const plans = [];
|
|
@@ -344,15 +374,17 @@ export async function renumberLane({ git, base, cwd, laneRef = "HEAD", regenerat
|
|
|
344
374
|
try { await git(["merge", "--no-edit", base]); } catch {
|
|
345
375
|
const files = lines(await g(["-c", "core.quotepath=off", "diff", "--name-only", "--diff-filter=U"]));
|
|
346
376
|
const r = await resolveSequenceConflicts({ git, files });
|
|
347
|
-
if (!r.ok)
|
|
377
|
+
if (!r.ok) {
|
|
378
|
+
const non = /^non-sequence conflict: (.+)$/.exec(r.unsupported ?? "")?.[1]?.split(", ") ?? [];
|
|
379
|
+
return { ...(await fail(r.unsupported)), ...(non.length ? { nonSequence: non } : {}) };
|
|
380
|
+
}
|
|
348
381
|
}
|
|
349
382
|
}
|
|
350
383
|
const head = lines(await g(["-c", "core.quotepath=off", "ls-files"]));
|
|
351
384
|
const touched = new Set();
|
|
352
385
|
// 2. the files, highest number first so a lane file never lands on another lane file not yet moved
|
|
353
386
|
for (const m of [...moves].sort((a, b) => Number(b.oldNum) - Number(a.oldNum))) {
|
|
354
|
-
|
|
355
|
-
if (/\.mdx?$/i.test(m.to)) text = retitle(text, m.oldNum, m.newNum);
|
|
387
|
+
const text = renumberText(await g(["cat-file", "blob", `${lane}:${m.from}`]), m.from, moves);
|
|
356
388
|
mkdirSync(dirname(join(cwd, m.to)), { recursive: true });
|
|
357
389
|
writeFileSync(join(cwd, m.to), text);
|
|
358
390
|
written.push(m.to);
|
|
@@ -416,11 +448,12 @@ export async function renumberLane({ git, base, cwd, laneRef = "HEAD", regenerat
|
|
|
416
448
|
}
|
|
417
449
|
}
|
|
418
450
|
}
|
|
419
|
-
// 5. references to the old names, repo-wide (moved files included; SQL
|
|
451
|
+
// 5. references to the old names, repo-wide (moved files included; SQL only the lane's own, never the base's)
|
|
452
|
+
const laneOwn = new Set(lines(await g(["-c", "core.quotepath=off", "diff", "--name-only", `${base}...${lane}`])));
|
|
420
453
|
await git(["add", "-A", "--", ...touched]);
|
|
421
454
|
for (const [from, to] of stem) {
|
|
422
455
|
for (const f of lines(await g(["-c", "core.quotepath=off", "grep", "-l", "-I", "-F", "-e", from, "--"]))) {
|
|
423
|
-
if (/\.sql$/i.test(f) || f.startsWith(".forge-lean/") || JOURNAL_RE.test(f)) continue;
|
|
456
|
+
if ((/\.sql$/i.test(f) && !laneOwn.has(f) && !touched.has(f)) || f.startsWith(".forge-lean/") || JOURNAL_RE.test(f)) continue;
|
|
424
457
|
const p = join(cwd, f), t = readFileSync(p, "utf8"), u = t.replace(word(from), to);
|
|
425
458
|
if (u !== t) { writeFileSync(p, u); touched.add(f); }
|
|
426
459
|
}
|
|
@@ -522,3 +522,74 @@ describe("journal when ordering across parallel milestone branches (#4661)", ()
|
|
|
522
522
|
assert.match(migrationGeneratorPrompt(p), /re-stamp/);
|
|
523
523
|
});
|
|
524
524
|
});
|
|
525
|
+
|
|
526
|
+
describe("renumber rewrites the migration's own references (#4732)", () => {
|
|
527
|
+
const MIG = (n) => `-- ${n}_nclt.sql\n-- Rollback: rollbacks/${n}_nclt_rollback.sql\nINSERT INTO adapters (name) VALUES ('nclt');\n`;
|
|
528
|
+
const RB = (n) => `-- Rollback of ${n}_nclt.sql\nDELETE FROM adapters WHERE name = 'nclt';\n`;
|
|
529
|
+
const repo = (rollbackBase = {}) => {
|
|
530
|
+
const d = tmpDir("seq4732-");
|
|
531
|
+
sh(d, "init", "-q", "-b", "main");
|
|
532
|
+
put(d, { "db/0048_init.sql": "a;\n", "db/0049_a.sql": "b;\n", "rollbacks/0048_init_rollback.sql": "x;\n", "rollbacks/0049_a_rollback.sql": "y;\n", ...rollbackBase });
|
|
533
|
+
commit(d, "base");
|
|
534
|
+
sh(d, "checkout", "-qb", "lane");
|
|
535
|
+
put(d, { "db/0049_nclt.sql": MIG("0049"), "rollbacks/0049_nclt_rollback.sql": RB("0049"), "docs/migrations.md": "See db/0049_nclt.sql\n" });
|
|
536
|
+
commit(d, "lane");
|
|
537
|
+
return d;
|
|
538
|
+
};
|
|
539
|
+
const show = (d, p) => sh(d, "show", `HEAD:${p}`);
|
|
540
|
+
|
|
541
|
+
it("renumberLane rewrites the header, rollback pointer, rollback file and index docs, and verifyRenumber accepts it", async () => {
|
|
542
|
+
const d = repo();
|
|
543
|
+
const before = await snapshotLane({ git: gitIn(d), base: "main" });
|
|
544
|
+
const r = await renumberLane({ git: gitIn(d), base: "main", cwd: d });
|
|
545
|
+
assert.deepEqual(r.moves, [
|
|
546
|
+
{ from: "db/0049_nclt.sql", to: "db/0050_nclt.sql" },
|
|
547
|
+
{ from: "rollbacks/0049_nclt_rollback.sql", to: "rollbacks/0050_nclt_rollback.sql" },
|
|
548
|
+
]);
|
|
549
|
+
assert.equal(show(d, "db/0050_nclt.sql"), MIG("0050"));
|
|
550
|
+
assert.equal(show(d, "rollbacks/0050_nclt_rollback.sql"), RB("0050"));
|
|
551
|
+
assert.equal(show(d, "docs/migrations.md"), "See db/0050_nclt.sql\n");
|
|
552
|
+
const v = await verifyRenumber({ git: gitIn(d), base: "main", before, moves: r.moves });
|
|
553
|
+
assert.equal(v.ok, true, v.problems.join("; "));
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
it("a rollback in another directory follows its migration's number when the base does not use it there", async () => {
|
|
557
|
+
const d = repo({ "rollbacks/0050_other_rollback.sql": "z;\n", "rollbacks/0051_more_rollback.sql": "w;\n" });
|
|
558
|
+
const r = await renumberLane({ git: gitIn(d), base: "main", cwd: d });
|
|
559
|
+
assert.ok(r.moves, JSON.stringify(r));
|
|
560
|
+
assert.equal(show(d, "db/0050_nclt.sql"), MIG("0050").replace("0050_nclt_rollback", "0052_nclt_rollback"), "the pointer names the rollback's own new path");
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
it("a builder that only swaps the old number for the new one in the migration and its rollback is accepted; any other edit is not", async () => {
|
|
564
|
+
for (const [extra, ok] of [["", true], ["-- and more\n", false]]) {
|
|
565
|
+
const d = repo();
|
|
566
|
+
const before = await snapshotLane({ git: gitIn(d), base: "main" });
|
|
567
|
+
sh(d, "mv", "db/0049_nclt.sql", "db/0050_nclt.sql");
|
|
568
|
+
sh(d, "mv", "rollbacks/0049_nclt_rollback.sql", "rollbacks/0050_nclt_rollback.sql");
|
|
569
|
+
put(d, { "db/0050_nclt.sql": MIG("0050") + extra, "rollbacks/0050_nclt_rollback.sql": RB("0050"), "docs/migrations.md": "See db/0050_nclt.sql\n" });
|
|
570
|
+
commit(d, "builder renumber");
|
|
571
|
+
const v = await verifyRenumber({ git: gitIn(d), base: "main", before });
|
|
572
|
+
assert.equal(v.ok, ok, v.problems.join("; "));
|
|
573
|
+
}
|
|
574
|
+
});
|
|
575
|
+
|
|
576
|
+
it("openNumbers lifts the new number above numbers other open PRs already carry", async () => {
|
|
577
|
+
const d = repo();
|
|
578
|
+
const r = await renumberLane({ git: gitIn(d), base: "main", cwd: d, openNumbers: async ({ dir }) => (dir === "db" ? [50, 51] : []) });
|
|
579
|
+
assert.ok(r.moves.some((m) => m.to === "db/0052_nclt.sql"), JSON.stringify(r));
|
|
580
|
+
assert.equal(show(d, "db/0052_nclt.sql"), MIG("0052"));
|
|
581
|
+
});
|
|
582
|
+
|
|
583
|
+
it("a non-sequence conflict is reported as nonSequence, and partial resolution takes the base side only for sequence files", async () => {
|
|
584
|
+
const d = repo();
|
|
585
|
+
put(d, { ".env.example": "A=lane\n" }); commit(d, "env lane");
|
|
586
|
+
sh(d, "checkout", "-q", "main"); put(d, { ".env.example": "A=base\n", "db/0050_b.sql": "c;\n" }); commit(d, "base env");
|
|
587
|
+
sh(d, "checkout", "-q", "lane");
|
|
588
|
+
const r = await renumberLane({ git: gitIn(d), base: "main", cwd: d });
|
|
589
|
+
assert.deepEqual(r.nonSequence, [".env.example"]);
|
|
590
|
+
assert.equal(sh(d, "status", "--porcelain").trim(), "", "the branch is back where it started");
|
|
591
|
+
try { sh(d, "merge", "--no-edit", "main"); } catch { /* conflicts expected */ }
|
|
592
|
+
const rs = await resolveSequenceConflicts({ git: gitIn(d), files: [".env.example"], partial: true });
|
|
593
|
+
assert.deepEqual(rs.remaining, [".env.example"]);
|
|
594
|
+
});
|
|
595
|
+
});
|
package/bin/pool/agent.mjs
CHANGED
|
@@ -111,7 +111,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
111
111
|
const envFile = join(dir, "env");
|
|
112
112
|
const credToken = randomBytes(24).toString("hex");
|
|
113
113
|
const withDocker = Boolean(spec.docker);
|
|
114
|
-
const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), CS_CRED_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/creds`, CS_CRED_TOKEN: credToken, CS_SANDBOX_ID: spec.id, CS_REPO_SLUG: spec.repo?.slug ?? "", CS_REPO_URL: spec.repo?.url ?? "", CS_REPO_REF: spec.repo?.ref ?? "", CS_RESULT_FILE: spec.result_file ?? "" };
|
|
114
|
+
const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), CS_CRED_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/creds`, CS_RELAY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/relay`, CS_CRED_TOKEN: credToken, CS_SANDBOX_ID: spec.id, CS_REPO_SLUG: spec.repo?.slug ?? "", CS_REPO_URL: spec.repo?.url ?? "", CS_REPO_REF: spec.repo?.ref ?? "", CS_RESULT_FILE: spec.result_file ?? "" };
|
|
115
115
|
writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
|
|
116
116
|
const rec = { id: spec.id, name, dir, issue: spec.issue ?? null, batch: spec.batch ?? null, cpus, mem_gb, result_file: spec.result_file ?? null, state: "starting", startedAt: now(), finishedAt: null, lease: now(), credToken, docker: withDocker };
|
|
117
117
|
sb()[spec.id] = rec;
|
|
@@ -244,6 +244,18 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
244
244
|
return { status: 200, body: { token: credCache[kind].token } };
|
|
245
245
|
}
|
|
246
246
|
|
|
247
|
+
// #4778: read-only capability relay. The sandbox's request is forwarded to the router queue with the agent token; the
|
|
248
|
+
// dispatching host runs (or refuses) it. This agent never executes the command.
|
|
249
|
+
async function sandboxRelay(id, rid, req) {
|
|
250
|
+
const r = own(id);
|
|
251
|
+
const m = /^Bearer\s+(\S.*)$/i.exec(req.headers.authorization ?? "");
|
|
252
|
+
if (!r || r.state === "exited" || !m || !sameSecret(m[1].trim(), r.credToken)) return { status: 401, body: { error: "unauthorized" } };
|
|
253
|
+
const path = `/agent/relay/${encodeURIComponent(id)}${rid ? `/${encodeURIComponent(rid)}` : ""}`;
|
|
254
|
+
const x = rid ? await call(cfg.router_url, "GET", path, { token: cfg.token, timeoutMs: 20000 })
|
|
255
|
+
: await call(cfg.router_url, "POST", path, { token: cfg.token, timeoutMs: 20000, body: { argv: (await readJson(req, 32 * 1024))?.argv } });
|
|
256
|
+
return { status: x.status, body: x.data };
|
|
257
|
+
}
|
|
258
|
+
|
|
247
259
|
/** Pull the current bundle from the router, rebuild the lane image if its recipe changed, then restart (systemd). */
|
|
248
260
|
async function selfUpdate() {
|
|
249
261
|
if (upgrade.state === "running") return;
|
|
@@ -375,6 +387,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
375
387
|
try {
|
|
376
388
|
const cred = req.method === "GET" && /^\/sandboxes\/([^/]+)\/creds\/([a-z]+)$/.exec(url.pathname);
|
|
377
389
|
if (cred) { const r = await sandboxCred(decodeURIComponent(cred[1]), cred[2], req); return send(res, r.status, r.body); }
|
|
390
|
+
const relay = (req.method === "POST" && /^\/sandboxes\/([^/]+)\/relay$/.exec(url.pathname)) || (req.method === "GET" && /^\/sandboxes\/([^/]+)\/relay\/([^/]+)$/.exec(url.pathname));
|
|
391
|
+
if (relay) { const r = await sandboxRelay(decodeURIComponent(relay[1]), relay[2] ? decodeURIComponent(relay[2]) : null, req); return send(res, r.status, r.body ?? {}); }
|
|
378
392
|
if (url.pathname !== "/health" && !bearerOk(req, cfg.token)) return send(res, 401, { error: "unauthorized" });
|
|
379
393
|
for (const [match, fn] of routes) {
|
|
380
394
|
const p = match(req, url);
|
package/bin/pool/router.mjs
CHANGED
|
@@ -18,6 +18,9 @@ const run = promisify(execFile);
|
|
|
18
18
|
* DELETE /sandboxes/:id). It places each sandbox on the enrolled agent with the most free reserved CPU, forwards every
|
|
19
19
|
* later call to that agent, renews the agent lease while ForgeDock keeps polling, and destroys sandboxes ForgeDock
|
|
20
20
|
* has abandoned. It also serves the agent installer and enrollment.
|
|
21
|
+
* Relay (#4778): an in-memory per-sandbox queue of read-only capability requests (agent `POST /agent/relay/:id`,
|
|
22
|
+
* `GET /agent/relay/:id/:rid`) that the dispatching ForgeDock lists (`GET /sandboxes/:id/relay`) and answers
|
|
23
|
+
* (`POST /sandboxes/:id/relay/:rid`). The router never runs or gates a command; a restart drops pending requests.
|
|
21
24
|
*/
|
|
22
25
|
export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date.now(), log = console } = {}) {
|
|
23
26
|
const store = jsonStore(join(cfg.state_dir, "router-state.json"), { agents: {}, sandboxes: {} });
|
|
@@ -30,6 +33,37 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
30
33
|
// "__proto__" or "constructor" never resolves to an inherited member.
|
|
31
34
|
const own = (map, key) => (typeof key === "string" && Object.hasOwn(map, key) ? map[key] : undefined);
|
|
32
35
|
const codeTtlMs = (cfg.code_ttl_s ?? 1800) * 1000;
|
|
36
|
+
// #4778: relay queue, sandbox id -> {rid -> {argv, done?, rc, stdout, stderr}}; not persisted.
|
|
37
|
+
const relayQ = new Map();
|
|
38
|
+
const RELAY_MAX_PENDING = 8, RELAY_MAX_ARGS = 64, RELAY_MAX_BYTES = 16 * 1024;
|
|
39
|
+
/** The caller agent's own sandbox (else null), so one agent never reads or queues for another's sandbox. */
|
|
40
|
+
const ownedBy = (req, id) => { const s = own(sbx(), id), a = agentFor(req); return s && a && s.agent === a ? s : null; };
|
|
41
|
+
function relayPost(req, { id }, body) {
|
|
42
|
+
if (!ownedBy(req, id)) return { status: 404, body: { error: "unknown sandbox" } };
|
|
43
|
+
const argv = body?.argv;
|
|
44
|
+
if (!Array.isArray(argv) || !argv.length || !argv.every((a) => typeof a === "string")) return { status: 400, body: { error: "argv must be a non-empty string list" } };
|
|
45
|
+
if (argv.length > RELAY_MAX_ARGS || Buffer.byteLength(JSON.stringify(argv)) > RELAY_MAX_BYTES) return { status: 400, body: { error: "argv too large" } };
|
|
46
|
+
const q = relayQ.get(id) ?? new Map();
|
|
47
|
+
if ([...q.values()].filter((r) => !r.done).length >= RELAY_MAX_PENDING) return { status: 429, body: { error: "too many pending relay requests" }, retryAfter: 5 };
|
|
48
|
+
const rid = randomBytes(12).toString("hex");
|
|
49
|
+
q.set(rid, { argv });
|
|
50
|
+
relayQ.set(id, q);
|
|
51
|
+
return { status: 202, body: { rid } };
|
|
52
|
+
}
|
|
53
|
+
function relayPoll(req, { id, rid }) {
|
|
54
|
+
if (!ownedBy(req, id)) return { status: 404, body: { error: "unknown sandbox" } };
|
|
55
|
+
const q = relayQ.get(id), r = q?.get(rid);
|
|
56
|
+
if (!r) return { status: 404, body: { error: "unknown relay request" } };
|
|
57
|
+
if (!r.done) return { status: 200, body: { state: "pending" } };
|
|
58
|
+
q.delete(rid);
|
|
59
|
+
return { status: 200, body: { state: "done", rc: r.rc, stdout: r.stdout, stderr: r.stderr } };
|
|
60
|
+
}
|
|
61
|
+
function relayAnswer({ id, rid }, body) {
|
|
62
|
+
const r = relayQ.get(id)?.get(rid);
|
|
63
|
+
if (!r || r.done) return { status: 404, body: { error: "unknown relay request" } };
|
|
64
|
+
Object.assign(r, { done: true, rc: Number.isInteger(body?.rc) ? body.rc : 1, stdout: String(body?.stdout ?? ""), stderr: String(body?.stderr ?? "") });
|
|
65
|
+
return { status: 200, body: { ok: true } };
|
|
66
|
+
}
|
|
33
67
|
/** The long-lived enroll token, or an unexpired one-time install code (consumed by a successful enrollment). */
|
|
34
68
|
function enrollOk(token, consume = false) {
|
|
35
69
|
if (sameSecret(token, cfg.enroll_token)) return true;
|
|
@@ -140,7 +174,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
140
174
|
s.touched = now(); store.save();
|
|
141
175
|
try {
|
|
142
176
|
const r = await agentCall(a, method, path);
|
|
143
|
-
if (method === "DELETE" && (r.ok || r.status === 404)) { delete sbx()[id]; store.save(); }
|
|
177
|
+
if (method === "DELETE" && (r.ok || r.status === 404)) { delete sbx()[id]; relayQ.delete(id); store.save(); }
|
|
144
178
|
return { status: r.status, body: r.data };
|
|
145
179
|
} catch (e) { return { status: 502, body: { error: `agent ${s.agent} unreachable: ${e.message}` } }; }
|
|
146
180
|
}
|
|
@@ -154,10 +188,10 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
154
188
|
try {
|
|
155
189
|
if (now() - s.touched > abandonMs) {
|
|
156
190
|
const r = await agentCall(a, "DELETE", `/sandboxes/${encodeURIComponent(id)}`);
|
|
157
|
-
if (r.ok || r.status === 404) { delete sbx()[id]; log.info?.(`abandoned ${id} destroyed on ${s.agent}`); }
|
|
191
|
+
if (r.ok || r.status === 404) { delete sbx()[id]; relayQ.delete(id); log.info?.(`abandoned ${id} destroyed on ${s.agent}`); }
|
|
158
192
|
} else {
|
|
159
193
|
const r = await agentCall(a, "POST", `/sandboxes/${encodeURIComponent(id)}/lease`);
|
|
160
|
-
if (r.status === 404) { delete sbx()[id]; log.info?.(`${id} gone on ${s.agent}`); }
|
|
194
|
+
if (r.status === 404) { delete sbx()[id]; relayQ.delete(id); log.info?.(`${id} gone on ${s.agent}`); }
|
|
161
195
|
}
|
|
162
196
|
} catch (e) { log.warn?.(`lease ${id} on ${s.agent}: ${e.message}`); }
|
|
163
197
|
}
|
|
@@ -226,12 +260,16 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
226
260
|
const agent = own(sbx(), id)?.agent, r = await forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/usage`);
|
|
227
261
|
return agent && r.status === 200 && r.body && typeof r.body === "object" ? { ...r, body: { ...r.body, agent } } : r;
|
|
228
262
|
})],
|
|
263
|
+
[route("GET", "/sandboxes/:id/relay"), fd(async ({ id }) => ({ status: 200, body: { requests: [...(relayQ.get(id) ?? new Map())].filter(([, r]) => !r.done).map(([rid, r]) => ({ rid, argv: r.argv })) } }))],
|
|
264
|
+
[route("POST", "/sandboxes/:id/relay/:rid"), fd(async (p, body) => relayAnswer(p, body))],
|
|
229
265
|
[route("DELETE", "/sandboxes/:id"), fd(async ({ id }) => forward(id, "DELETE", `/sandboxes/${encodeURIComponent(id)}`))],
|
|
230
266
|
[route("GET", "/status"), fd(async () => ({ status: 200, body: await status() }))],
|
|
231
267
|
[route("GET", "/agents"), fd(async () => ({ status: 200, body: { agents: await capacities(), sandboxes: sbx() } }))],
|
|
232
268
|
[route("POST", "/codes"), fd(async () => ({ status: 200, body: issueCode() }))],
|
|
233
269
|
[route("GET", "/agent/creds/github"), { fn: async () => ({ status: 200, body: { token: await githubToken() } }), auth: "agent" }],
|
|
234
270
|
[route("GET", "/agent/creds/claude"), { fn: async () => ({ status: 200, body: claudeToken() }), auth: "agent" }],
|
|
271
|
+
[route("POST", "/agent/relay/:id"), { fn: async (p, body, _u, req) => relayPost(req, p, body), auth: "agent" }], // #4778
|
|
272
|
+
[route("GET", "/agent/relay/:id/:rid"), { fn: async (p, _b, _u, req) => relayPoll(req, p), auth: "agent" }],
|
|
235
273
|
[route("GET", "/agent/bundle"), { fn: async () => ({ bundle: true }), auth: "agent" }],
|
|
236
274
|
[route("GET", "/agent/images/:ref"), { fn: async ({ ref }) => ({ image: ref }), auth: "agent" }],
|
|
237
275
|
[route("POST", "/agents/:name/upgrade"), fd(async ({ name }) => {
|
|
@@ -242,7 +280,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
242
280
|
})],
|
|
243
281
|
[route("DELETE", "/agents/:name"), fd(async ({ name }) => {
|
|
244
282
|
if (!own(agents(), name)) return { status: 404, body: { error: "unknown agent" } };
|
|
245
|
-
for (const [id, x] of Object.entries(sbx())) if (x.agent === name) delete sbx()[id];
|
|
283
|
+
for (const [id, x] of Object.entries(sbx())) if (x.agent === name) { delete sbx()[id]; relayQ.delete(id); }
|
|
246
284
|
delete agents()[name]; store.save();
|
|
247
285
|
return { status: 200, body: { ok: true } };
|
|
248
286
|
})],
|
|
@@ -275,7 +313,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
|
|
|
275
313
|
if (r.auth === "agent" && !agentFor(req)) return send(res, 401, { error: "unauthorized" });
|
|
276
314
|
if (r.auth === "enroll" && !enrollOk(url.searchParams.get("token"))) return send(res, 401, "unauthorized\n");
|
|
277
315
|
const body = req.method === "POST" ? await readJson(req) : null;
|
|
278
|
-
const out = await r.fn(p, body, url);
|
|
316
|
+
const out = await r.fn(p, body, url, req);
|
|
279
317
|
if (out.bundle) return sendBundle(res);
|
|
280
318
|
if (out.image) return sendImage(res, out.image);
|
|
281
319
|
return send(res, out.status, out.body, out.retryAfter ? { "retry-after": String(out.retryAfter) } : {});
|