forgedock 1.64.0 → 1.65.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.
@@ -1797,10 +1797,10 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1797
1797
  try { sock = await schedd.connectDaemon({ dir: deps.scheddDir ?? (await import("./lean/sched.mjs")).schedDir(), spawnDaemon: null }); } catch { sock = null; }
1798
1798
  if (sock) {
1799
1799
  let r = null;
1800
- try { r = await schedd.request(sock, { op: "clear-breaker", id: b.id }, undefined, { timeoutMs: 15000 }); } catch { r = null; }
1800
+ try { const waitMs = 2 * (deps.pollMs || 15000); r = await schedd.request(sock, { op: "clear-breaker", id: b.id, waitMs }, undefined, { timeoutMs: waitMs + 5000 }); } catch { r = null; }
1801
1801
  if (r?.hosted) {
1802
- sink.line(`batch ${b.id}: ${r.acknowledged ? (r.cleared ? "breaker cleared" : "no breaker was tripped") : "breaker cleared in state.json; the live runner did not acknowledge"}${r.acknowledged ? " (live runner acknowledged)" : ""}`);
1803
- return { ok: true, batch: b.id, cleared: Boolean(r.cleared), acknowledged: Boolean(r.acknowledged) };
1802
+ sink.line(`batch ${b.id}: ${r.acknowledged ? (r.cleared ? "breaker cleared" : "no breaker was tripped") : "pending: the runner will clear it on its next pass"}${r.acknowledged ? " (live runner acknowledged)" : ""}`);
1803
+ return { ok: true, batch: b.id, cleared: Boolean(r.cleared), acknowledged: Boolean(r.acknowledged), ...(r.pending ? { pending: true } : {}) };
1804
1804
  }
1805
1805
  }
1806
1806
  }
@@ -2309,7 +2309,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2309
2309
  trusted: (n) => trustedOf.get(n) === true,
2310
2310
  autoChildren,
2311
2311
  ...(autoMod.addsEpicChildren(autoChildren.mode) ? { getChildren: async () => ({ list: await autoMod.readChildList({ gh: (a) => leanIo.gh(a), repo, fields: childFields ??= await autoMod.hostListFields((a) => leanIo.gh(a)) }), elsewhere: autoMod.liveElsewhere({ batchMod, root, self: batch.id, repo }) }) } : {}),
2312
- issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getClearBreaker: batch.readClearBreaker, ackClearBreaker: batch.ackClearBreaker, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, expireHolds: batch.expireHolds, getHoldInfo: batch.readHoldInfo, getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
2312
+ issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getClearBreaker: batch.peekClearBreaker, consumeClearBreaker: batch.readClearBreaker, ackClearBreaker: batch.ackClearBreaker, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, expireHolds: batch.expireHolds, getHoldInfo: batch.readHoldInfo, getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
2313
2313
  breaker: orch.breaker, maxDeferrals: orch.maxDeferrals, ...(Number.isInteger(orch.transientRetries) ? { transientRetries: orch.transientRetries } : {}), ...(deps.pollMs ? { pollMs: deps.pollMs } : {}), ...budget, limits, identity, rotator, batchId: batch.id, drift, lifecycle, integration,
2314
2314
  ...(registry ? { sched: { registry, batch: batch.id, repo, cap: liveLaneCap(orch.globalParallel ?? null, { cfg: readAdmission(cwd), host: { cores: () => cpus().length, memAvailableMb, rampingMb: rampProbe.rampingMb } }), exclusive: true }, priorityOf: async (n) => schedMod.priorityFromLabels(await labelNames(n)) } : {}),
2315
2315
  // #5174: hold new local admissions while loadavg/cores is above engine.overload_load_per_core (host-wide batches only)
@@ -225,6 +225,8 @@ export function openBatch(root, id) {
225
225
  },
226
226
  /** #5947: `--clear-breaker` for a hosted runner: the request file (a timestamp) is consumed by the runner, which answers in `clear-breaker.ack`. */
227
227
  requestClearBreaker: () => { try { rmSync(f("clear-breaker.ack"), { force: true }); } catch { /* best effort */ } const at = Date.now(); put(f("clear-breaker"), `${at}\n`); return at; },
228
+ /** #5964: the pending request's `at` without deleting it (the runner consumes it after deciding); null when none. */
229
+ peekClearBreaker: () => { try { const at = Number(readFileSync(f("clear-breaker"), "utf8").trim()); return Number.isFinite(at) && at > 0 ? at : true; } catch { return null; } },
228
230
  readClearBreaker: () => { try { readFileSync(f("clear-breaker"), "utf8"); rmSync(f("clear-breaker"), { force: true }); return true; } catch { return false; } },
229
231
  ackClearBreaker: (info = {}) => put(f("clear-breaker.ack"), JSON.stringify({ at: Date.now(), ...info }) + "\n"),
230
232
  readClearBreakerAck: () => readJson(f("clear-breaker.ack")),
@@ -0,0 +1,15 @@
1
+ /**
2
+ * #5964: the runner's decision on a hosted `--clear-breaker` request. The request carries the time it was made;
3
+ * it clears only a breaker that tripped at or before it, so a stale request cannot close a later trip.
4
+ */
5
+
6
+ /**
7
+ * @param {{tripped: ({at?: number}|null|undefined), requestAt: (number|boolean|null|undefined)}} p
8
+ * @returns {{clear: boolean, stale: boolean}} `clear`: reset the breaker; `stale`: the request predates the current trip (discard it)
9
+ */
10
+ export function decideClear({ tripped, requestAt }) {
11
+ if (requestAt === true) return { clear: true, stale: false }; // legacy boolean seam: unconditional
12
+ if (typeof requestAt !== "number" || !Number.isFinite(requestAt)) return { clear: false, stale: false };
13
+ if (tripped && Number.isFinite(tripped.at) && tripped.at > requestAt) return { clear: false, stale: true };
14
+ return { clear: true, stale: false };
15
+ }
@@ -0,0 +1,100 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5964: hosted --clear-breaker is a durable, time-scoped request the runner consumes on its next pass, however long that is.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { existsSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { tmpDir } from "../tests/_tmp.mjs";
9
+ import { decideClear } from "./clear-breaker.mjs";
10
+ import { openBatch } from "./batch.mjs";
11
+ import { orchestrate } from "./orchestrate.mjs";
12
+ import { runBatch } from "../engine-cli.mjs";
13
+
14
+ const memStore = () => { let st = null; return { load: () => (st ? JSON.parse(JSON.stringify(st)) : null), save: (s) => { st = JSON.parse(JSON.stringify(s)); }, log: () => {}, peek: () => st }; };
15
+ const EE = (detail) => ({ terminalReason: "engine-error", detail });
16
+ const MERGED = { terminalReason: "merged", pr: 9 };
17
+
18
+ /** A runner whose every pass costs 12 s of injected time; `req` is the pending request `at` (or null), made `reqAfterMs` after the trip. */
19
+ const slowRun = async ({ reqAfterMs }) => {
20
+ let t = 1_000_000, tripAt = null, req = null, consumed = 0; const acks = [], calls = [];
21
+ const script = { 1: [EE("boom A")], 2: [EE("boom B")], 3: [MERGED] };
22
+ const rows = await orchestrate({ issues: [1, 2, 3], parallel: 1, readBody: async () => "", now: () => t, store: memStore(), pollMs: 12000, breaker: { errors: 2, window_min: 10 },
23
+ sleep: async (ms) => { t += Math.max(12000, Number(ms) || 0); },
24
+ runOne: async (n) => { calls.push(n); t += 12000; return script[n][0]; },
25
+ onUpdate: (u) => { if (u.outcome === "breaker" && tripAt === null) { tripAt = t; req = tripAt + reqAfterMs; } },
26
+ getClearBreaker: () => req, consumeClearBreaker: () => { req = null; consumed++; }, ackClearBreaker: (i) => acks.push(i) });
27
+ return { rows, acks, calls, consumed };
28
+ };
29
+
30
+ describe("#5964 decideClear", () => {
31
+ it("clears a trip at or before the request; never a later one; boolean is legacy; nothing without a request", () => {
32
+ assert.deepEqual(decideClear({ tripped: { at: 100 }, requestAt: 150 }), { clear: true, stale: false });
33
+ assert.deepEqual(decideClear({ tripped: { at: 100 }, requestAt: 100 }), { clear: true, stale: false });
34
+ assert.deepEqual(decideClear({ tripped: { at: 200 }, requestAt: 150 }), { clear: false, stale: true });
35
+ assert.deepEqual(decideClear({ tripped: { at: 200 }, requestAt: true }), { clear: true, stale: false });
36
+ assert.deepEqual(decideClear({ tripped: null, requestAt: 150 }), { clear: true, stale: false });
37
+ for (const requestAt of [null, false, undefined, NaN, "x"]) assert.deepEqual(decideClear({ tripped: { at: 1 }, requestAt }), { clear: false, stale: false }, String(requestAt));
38
+ });
39
+ });
40
+
41
+ describe("#5964 runner pass", () => {
42
+ it("slow pass: request survives and next pass clears (a request 1 s into a 12 s pass is cleared and acked on the next pass, and admissions resume)", async () => {
43
+ const r = await slowRun({ reqAfterMs: 1000 });
44
+ assert.ok(r.acks.some((a) => a.cleared === true), "acked a real clear");
45
+ assert.equal(r.consumed, 1);
46
+ assert.ok(r.calls.includes(3), "issue 3 was admitted after the clear");
47
+ });
48
+
49
+ it("a request older than a later trip does not clear it (stale), and is consumed", async () => {
50
+ const r = await slowRun({ reqAfterMs: -5000 });
51
+ assert.equal(r.acks.some((a) => a.cleared === true), false);
52
+ assert.equal(r.consumed, 1);
53
+ assert.equal(r.calls.includes(3), false, "the later trip stays closed");
54
+ });
55
+ });
56
+
57
+ describe("#5964 slow pass over the real batch request file", () => {
58
+ it("slow pass: a request made 1 s into a 12 s pass stays on disk, the next pass clears tripped, acks, consumes it, and admissions resume", async () => {
59
+ const root = tmpDir("clrbrk-"); const b = openBatch(root, "b3"); b.store.save({ id: "b3" });
60
+ let t = 1_000_000, tripped = false, requested = false, release = null, onDiskAtNextPass = null; const calls = [], acks = [];
61
+ const gate = new Promise((r) => { release = r; });
62
+ const script = { 1: EE("boom A"), 2: EE("boom B"), 3: null, 4: MERGED };
63
+ const rows = await orchestrate({ issues: [1, 2, 3, 4], parallel: 3, readBody: async () => "", now: () => t, store: memStore(), pollMs: 12000, breaker: { errors: 2, window_min: 10 },
64
+ sleep: async () => {
65
+ if (tripped && !requested) { requested = true; b.requestClearBreaker(); t += 12000; release(); } // the request lands during a 12 s pass
66
+ else t += 12000;
67
+ },
68
+ runOne: async (n) => { calls.push(n); if (n === 3) { await gate; return MERGED; } return script[n]; },
69
+ onUpdate: (u) => { if (u.outcome === "breaker") tripped = true; },
70
+ getClearBreaker: () => { if (requested && onDiskAtNextPass === null) onDiskAtNextPass = existsSync(join(root, "b3", "clear-breaker")); return b.peekClearBreaker(); },
71
+ consumeClearBreaker: b.readClearBreaker, ackClearBreaker: (i) => { acks.push(i); b.ackClearBreaker(i); } });
72
+ assert.equal(onDiskAtNextPass, true, "the request survived until the runner's next pass");
73
+ assert.equal(acks.some((a) => a.cleared === true), true, "tripped was cleared and acked");
74
+ assert.equal(b.readClearBreakerAck().cleared, true);
75
+ assert.equal(existsSync(join(root, "b3", "clear-breaker")), false, "consumed after the decision");
76
+ assert.ok(calls.includes(4), "admissions resumed (issue 4 ran) with no restart");
77
+ assert.equal(rows.find((r) => r.issue === 4)?.outcome, "merged");
78
+ });
79
+ });
80
+
81
+ describe("#5964 batch request file and CLI", () => {
82
+ it("peekClearBreaker returns the request time without deleting it; readClearBreaker consumes", () => {
83
+ const root = tmpDir("clrbrk-"); const b = openBatch(root, "b1"); b.store.save({ id: "b1" });
84
+ assert.equal(b.peekClearBreaker(), null);
85
+ const at = b.requestClearBreaker();
86
+ assert.equal(b.peekClearBreaker(), at);
87
+ assert.equal(existsSync(join(root, "b1", "clear-breaker")), true, "peek leaves the file");
88
+ assert.equal(b.readClearBreaker(), true);
89
+ assert.equal(b.peekClearBreaker(), null);
90
+ });
91
+
92
+ it("unhosted (no daemon) batch keeps the direct state.json rewrite", async () => {
93
+ const root = tmpDir("clrbrk-"); const b = openBatch(root, "b2"); b.store.save({ id: "b2", breaker: { at: 1 }, errorTimes: [1] }); writeFileSync(join(root, "b2", "plan.json"), "{}");
94
+ const lines = [];
95
+ const r = await runBatch({ argv: ["--clear-breaker", "b2"], deps: { batchRoot: root, noDaemon: true }, sink: { line: (l) => lines.push(l) } });
96
+ assert.equal(r.cleared, true);
97
+ assert.equal(b.store.load().breaker, null);
98
+ assert.match(lines[0], /breaker cleared/);
99
+ });
100
+ });
@@ -144,6 +144,7 @@ export function parseExecution(sec = {}) {
144
144
  const patRaw = Array.isArray(s.host_capability_patterns) ? s.host_capability_patterns : str(s.host_capability_patterns) ? str(s.host_capability_patterns).split(",") : [];
145
145
  const hostCapabilityPatterns = patRaw.map((x) => { const t = str(x), i = t.indexOf(":"); return { name: t.slice(0, i).trim().toLowerCase(), pattern: t.slice(i + 1).trim() }; })
146
146
  .filter((x) => CAPABILITY_RE.test(x.name) && x.pattern && safeRegExp(x.pattern));
147
+ const repoSource = ["dispatcher", "github", "auto"].includes(str(s.repo_source).toLowerCase()) ? str(s.repo_source).toLowerCase() : null; // #5949: where a pool sandbox's repo mirror comes from; unset = auto
147
148
  const wsN = Number(str(s.warm_sandboxes));
148
149
  const warmSandboxes = str(s.warm_sandboxes) !== "" && Number.isInteger(wsN) && wsN > 0 ? wsN : 0; // #4912: warm sandboxes the pool agent keeps ready; 0 = off
149
150
  const lt = validateLaneTools(s.lane_tools); // #5650: invalid entries are dropped here and reported in laneToolsErrors; the remote provider refuses to start with them
@@ -160,7 +161,7 @@ export function parseExecution(sec = {}) {
160
161
  const plan = ["free", "pro", "team", "enterprise"].includes(str(s.plan).toLowerCase()) ? str(s.plan).toLowerCase() : null;
161
162
  const publicDefault = str(s.public_default).toLowerCase() === "actions" ? "actions" : null; // #5900: opt-in only
162
163
  const dispatcher = /^[A-Za-z0-9][A-Za-z0-9-]*(\[bot\])?$/.test(str(s.dispatcher)) ? str(s.dispatcher) : null;
163
- return { mode, maxRemote, provider, image, secrets, budget, ...(jobLimit ? { jobLimit } : {}), ...(ciReserve !== null ? { ciReserve } : {}), ...(plan ? { plan } : {}), ...(publicDefault ? { publicDefault } : {}), ...(dispatcher ? { dispatcher } : {}), ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
164
+ return { mode, maxRemote, provider, image, secrets, budget, ...(jobLimit ? { jobLimit } : {}), ...(ciReserve !== null ? { ciReserve } : {}), ...(plan ? { plan } : {}), ...(publicDefault ? { publicDefault } : {}), ...(dispatcher ? { dispatcher } : {}), ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(repoSource ? { repoSource } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
164
165
  }
165
166
 
166
167
  const round1 = (x) => Math.round(x * 10) / 10;
@@ -667,7 +668,7 @@ export function providerByName(name, opts) {
667
668
  // #4685/#5131: an empty env/keychain lookup of `token_env` falls back to `token_file`, then the (matching) router's token file.
668
669
  const credentials = (n) => (n === tokenEnv ? resolve().token : resolveCredential(n, { env, keychain })); // per call, keychain memoised (#5159)
669
670
  const settings = { ...exec, ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(forgeYaml ? { forgeYaml } : {}),
670
- ...(typeof opts?.prefetch === "function" ? { prefetch: opts.prefetch } : {}) }; // #4778: dispatch-time relay pre-fetch
671
+ ...(typeof opts?.prefetch === "function" ? { prefetch: opts.prefetch } : {}), ...(pool && opts?.cwd ? { repoDir: opts.cwd } : {}) }; // #4778; #5949: the dispatcher's clone seeds the pool mirror: dispatch-time relay pre-fetch
671
672
  return remoteProvider({ batch: opts.batch, repo: opts.repo, settings, ...(pool ? { name: "pool" } : {}), env, credentials,
672
673
  transport: remoteTransportFor(settings, { transport: opts?.transport, env, credentials, ...(opts?.fetchFn ? { fetchFn: opts.fetchFn } : {}) }), ...(opts?.now ? { now: opts.now } : {}) });
673
674
  }
@@ -0,0 +1,84 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5949: dispatcher side of repo seeding. Builds an incremental `git bundle` from the dispatching host's own clone (everything the
5
+ * agent's mirror lacks; `--all`-equivalent when the mirror is absent) and uploads it through the pool router in checksummed,
6
+ * resumable chunks (`transport.mirrors` / `transport.seed`). Any failure throws; the caller falls back to the GitHub path.
7
+ */
8
+ import { execFile } from "node:child_process";
9
+ import { createHash } from "node:crypto";
10
+ import { promisify } from "node:util";
11
+
12
+ const run = promisify(execFile);
13
+ /** Decoded bytes per chunk (the agent and router cap it at 512 KB). */
14
+ export const CHUNK = 384 * 1024;
15
+ const MAX_CHUNK_RETRIES = 3;
16
+ const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
17
+ const git = async (cwd, args, opts = {}) => (await run("git", args, { cwd, encoding: opts.binary ? "buffer" : "utf8", maxBuffer: 1 << 30 })).stdout;
18
+
19
+ /** The refs to ship: origin's branches (the agent maps them to refs/heads/*; local branches only when there are none) and tags; never the origin/HEAD symref. */
20
+ async function wantRefs(repoDir) {
21
+ const list = async (...pats) => (await git(repoDir, ["for-each-ref", "--format=%(refname)", ...pats])).split("\n").filter(Boolean);
22
+ const origin = (await list("refs/remotes/origin")).filter((r) => r !== "refs/remotes/origin/HEAD");
23
+ return [...(origin.length ? origin : await list("refs/heads")), ...(await list("refs/tags"))];
24
+ }
25
+
26
+ /**
27
+ * The bundle bytes for `repoDir` given the agent's `tips` ({ref: sha} or "absent"), or null when the agent already has everything.
28
+ * Tips the dispatcher's repo does not contain are skipped as exclusions (the bundle is then larger, never invalid).
29
+ */
30
+ export async function buildBundle(repoDir, tips) {
31
+ const refs = await wantRefs(repoDir);
32
+ if (!refs.length) throw new Error("local repo has no refs to bundle");
33
+ const excl = [];
34
+ if (tips && typeof tips === "object") {
35
+ for (const sha of new Set(Object.values(tips))) {
36
+ try { await git(repoDir, ["cat-file", "-e", `${sha}^{commit}`]); excl.push(`^${sha}`); } catch { /* unknown here: not excluded */ }
37
+ }
38
+ }
39
+ try { return await git(repoDir, ["bundle", "create", "-", ...refs, ...excl], { binary: true }); }
40
+ catch (e) { if (/empty bundle/i.test(String(e.stderr))) return null; throw e; }
41
+ }
42
+
43
+ /** Size of the whole repo's packed objects in bytes (what a full transfer would move). */
44
+ async function repoBytes(repoDir) {
45
+ try { const o = await git(repoDir, ["count-objects", "-v"]); const n = (k) => Number(new RegExp(`^${k}: (\\d+)`, "m").exec(o)?.[1] ?? 0); return (n("size") + n("size-pack")) * 1024; } catch { return 0; }
46
+ }
47
+
48
+ /**
49
+ * Seed the agent mirror of `slug` for sandbox `id`. Returns {sent, bytes, chunks, full, ms, upToDate}. Throws on any failure;
50
+ * an older router/agent without the endpoints (404/405 from `transport.mirrors`) throws `{unsupported: true}`.
51
+ */
52
+ export async function seedMirror({ transport, id, slug, cacheKey = null, repoDir, now = () => Date.now() }) {
53
+ if (typeof transport.mirrors !== "function" || typeof transport.seed !== "function") throw Object.assign(new Error("transport has no mirror seeding"), { unsupported: true });
54
+ const t0 = now();
55
+ if (!(await wantRefs(repoDir).catch(() => [])).length) throw new Error("local repo has no refs to bundle"); // nothing to seed from: no round trip
56
+ const q = await transport.mirrors(id, { slug, cache_key: cacheKey });
57
+ const tips = q?.mirrors?.[slug];
58
+ if (tips === undefined) throw Object.assign(new Error("agent answered /mirrors without this repo"), { unsupported: true });
59
+ const full = tips === "absent";
60
+ const bundle = await buildBundle(repoDir, full ? null : tips);
61
+ if (!bundle) return { sent: false, bytes: 0, chunks: 0, full, ms: now() - t0, upToDate: true };
62
+ const upload = sha256(bundle), base = { slug, cache_key: cacheKey, upload };
63
+ let offset = (await transport.mirrors(id, { slug, cache_key: cacheKey, upload }))?.upload_offset ?? 0, chunks = 0, sent = 0;
64
+ if (!Number.isInteger(offset) || offset < 0 || offset > bundle.length) offset = 0;
65
+ while (offset < bundle.length) {
66
+ const buf = bundle.subarray(offset, offset + CHUNK);
67
+ const body = { ...base, offset, data_b64: buf.toString("base64"), sha256: sha256(buf) };
68
+ let res = null;
69
+ for (let attempt = 0; attempt < MAX_CHUNK_RETRIES && res === null; attempt++) {
70
+ try { res = await transport.seed(id, body); }
71
+ catch (e) {
72
+ if (e.status === 409 && Number.isInteger(e.offset)) { res = { offset: e.offset, resumed: true }; break; } // the agent has a different length: resume from its offset
73
+ if (e.status && e.status < 500 && e.status !== 429) throw e;
74
+ if (attempt === MAX_CHUNK_RETRIES - 1) throw e;
75
+ }
76
+ }
77
+ if (!res.resumed) { sent += buf.length; chunks++; }
78
+ offset = res.offset;
79
+ }
80
+ await transport.seed(id, { ...base, finish: { size: bundle.length, sha256: upload } });
81
+ const ms = now() - t0, whole = await repoBytes(repoDir);
82
+ const saved_ms = sent > 0 && ms > 0 && whole > sent ? Math.round(((whole - sent) / sent) * ms) : null; // estimate: the whole repo at this upload's own rate
83
+ return { sent: true, bytes: sent, bundle_bytes: bundle.length, chunks, full, ms, saved_ms, upToDate: false };
84
+ }
@@ -124,6 +124,7 @@
124
124
  * then queue order. A sub-issue's estimate is the parent's ÷ N, floored at the M default. Without `estimate` the order is
125
125
  * the queue order except that decomposed sub-issues go first. A settled row carries `est_minutes` (estimated vs. actual).
126
126
  */
127
+ import { decideClear } from "./clear-breaker.mjs";
127
128
  import { parseDependsOn } from "../engine/phases.mjs";
128
129
  import { classifyNeedsHuman, recoveryCodeOf, recoveryClassOf, OUTCOME_CODES, ENV_VALIDATE_PLACEMENT, ENV_VALIDATE_TIMEOUT, MECHANICAL_CODES } from "../engine/outcome-codes.mjs";
129
130
  import { detectGateDeadlock, formatGateDeadlock } from "./gatewatch.mjs";
@@ -335,7 +336,7 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
335
336
  * @returns {Promise<Array<{issue:number, outcome:string, pr:?number, cost_usd:number, minutes:number, detail?:string}>>}
336
337
  */
337
338
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), blockedRefreshMs = 60000, onUpdate = () => {}, onCrossLane = () => {},
338
- store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000, getClearBreaker = null, ackClearBreaker = null,
339
+ store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000, getClearBreaker = null, consumeClearBreaker = null, ackClearBreaker = null,
339
340
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
340
341
  recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
341
342
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
@@ -1983,7 +1984,17 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1983
1984
  // #4685: a breaker tripped only by link failures (a router restart) closes itself after a cooldown
1984
1985
  if (tripped?.transport && now() - tripped.at >= TRANSPORT_COOLDOWN_MS) { tripped = null; errorTimes = []; transportErrors = 0; save(); }
1985
1986
  // #5947: --clear-breaker on a schedd-hosted batch reaches this runner through the batch's request file
1986
- if (getClearBreaker) { let req = false; try { req = Boolean(getClearBreaker()); } catch { req = false; } if (req) { const was = Boolean(tripped); tripped = null; errorTimes = []; transportErrors = 0; save(); try { ackClearBreaker?.({ cleared: was }); } catch { /* advisory */ } } }
1987
+ if (getClearBreaker) { // #5964: time-scoped; the request is consumed only after the decision, so a long pass never loses it
1988
+ let req = null; try { req = getClearBreaker(); } catch { req = null; }
1989
+ if (req) {
1990
+ const d = decideClear({ tripped, requestAt: req });
1991
+ const wasTripped = Boolean(tripped);
1992
+ if (d.clear) { const was = wasTripped; tripped = null; errorTimes = []; transportErrors = 0; save(); try { ackClearBreaker?.({ cleared: was }); } catch { /* advisory */ } }
1993
+ else if (d.stale) { try { ackClearBreaker?.({ cleared: false }); } catch { /* advisory */ } }
1994
+ try { consumeClearBreaker?.(); } catch { /* advisory */ }
1995
+ if (d.clear && wasTripped) continue; // admission ran before this check: re-run the pass so the cleared batch resumes instead of falling to the "nothing runnable" skip
1996
+ }
1997
+ }
1987
1998
  if (tripped && !running.size) { await drainAdds(); break; } // breaker: let running lanes finish, keep the rest pending for a resume
1988
1999
  if (cancelled && !running.size) { await drainAdds(); break; } // #4376: cancel: the rest end held for a resume
1989
2000
  if (budgetStop && !running.size) { await drainAdds(); break; } // execution budget (stop): the same, the rest end held
@@ -25,8 +25,11 @@ import { scopedEnv } from "./execution.mjs";
25
25
  import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
26
26
  import { laneEnvFor, readEnvSnapshots } from "../env/env.mjs";
27
27
  import { resolveCredential } from "./credentials.mjs";
28
+ import { seedMirror } from "./mirror-bundle.mjs";
28
29
  import { relayCommandNames, runRelayed, servicePending } from "./relay.mjs";
29
30
 
31
+ /** #5949: one log line for a launch's seed stats: bytes sent, and the time saved against shipping the whole repo at the same rate. */
32
+ const seedLine = (s) => (s.fallback ? `fell back to GitHub (${s.reason})` : s.upToDate ? "mirror already up to date, nothing sent" : `${s.full ? "full" : "incremental"} bundle, ${s.bytes} bytes in ${s.chunks} chunks, ${s.ms} ms${Number.isFinite(s.saved_ms) ? `, about ${Math.round(s.saved_ms / 1000)} s saved` : ""}`);
30
33
  const REDACTED = "[redacted]";
31
34
  const PREFETCH_MAX_B64 = 96 * 1024; // one env string stays under Linux MAX_ARG_STRLEN (128 KB)
32
35
  /** Replace every value of `secrets` (4+ chars, longest first) in `text`. */
@@ -114,6 +117,20 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
114
117
  if (!Array.isArray(r.data?.agents)) throw new Error("agent disk: malformed router answer");
115
118
  return r.data.agents.map((a) => ({ name: String(a?.name ?? "?"), disk_free_gb: Number.isFinite(a?.disk_free_gb) ? a.disk_free_gb : null }));
116
119
  },
120
+ /** #5949: the agent mirror's ref tips for a repo ({mirrors: {slug: {ref: sha} | "absent"}, upload_offset?}); 404/405 = an older router/agent (unsupported). */
121
+ async mirrors(id, q) {
122
+ const r = await call("GET", `${p(id)}/mirrors?${new URLSearchParams(Object.entries(q).filter(([, v]) => v !== null && v !== undefined).map(([k, v]) => [k, String(v)]))}`);
123
+ if (r.status === 404 || r.status === 405) throw Object.assign(fail("mirrors", r), { unsupported: true });
124
+ if (!r.ok) throw fail("mirrors", r);
125
+ return r.data ?? {};
126
+ },
127
+ /** #5949: one bundle chunk or the finish call; a 409 carries the agent's resume offset. */
128
+ async seed(id, body) {
129
+ const r = await call("POST", `${p(id)}/seed`, body);
130
+ if (r.status === 404 || r.status === 405) throw Object.assign(fail("seed", r), { unsupported: true });
131
+ if (!r.ok) throw Object.assign(fail("seed", r), Number.isInteger(r.data?.offset) ? { offset: r.data.offset } : {});
132
+ return r.data ?? {};
133
+ },
117
134
  /** #5735: lane sandboxes per pool agent (`GET /agents` -> `agents[].lanes {used, ceiling}`) and across all batches (`remote_lanes`; else the `fdrsbx-` keys of `sandboxes`). A bad answer throws. */
118
135
  async agentLanes() {
119
136
  const r = await call("GET", "/agents");
@@ -253,8 +270,21 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
253
270
  // #4912: a ready warm sandbox first; none, an error or a transport without claim is the cold start.
254
271
  let claimed = null;
255
272
  if (warm && typeof transport.claim === "function") { try { claimed = await transport.claim(spec); } catch { claimed = null; } }
273
+ // #5949: seed the pool agent's mirror from this host first (repo_source dispatcher|github|auto); failure falls back to GitHub, or fails under `dispatcher`.
274
+ let seed = null;
275
+ const source = ["dispatcher", "github"].includes(settings.repoSource) ? settings.repoSource : "auto";
276
+ if (!claimed && repo && settings.repoDir && source !== "github" && typeof transport.seed === "function") {
277
+ try { seed = await seedMirror({ transport, id, slug: repo, cacheKey: spec.cache?.key ?? repo, repoDir: settings.repoDir, now }); }
278
+ catch (e) {
279
+ if (source === "dispatcher") throw Object.assign(new Error(`repo seeding failed (repo_source=dispatcher): ${redact(e?.message ?? e, [...known]).slice(0, 200)}`), { code: "pool.seed_failed", transient: e?.transient === true });
280
+ seed = { sent: false, fallback: true, reason: redact(e?.message ?? e, [...known]).slice(0, 160) };
281
+ }
282
+ }
256
283
  if (!claimed) await transport.launch(spec);
257
- return { provider: name, id, issue, startedAt, minutes: 0 };
284
+ if (seed) {
285
+ try { const f = batch.logFile(issue); mkdirSync(dirname(f), { recursive: true }); appendFileSync(f, `[seed] ${seedLine(seed)}\n`); } catch { /* logging only */ }
286
+ }
287
+ return { provider: name, id, issue, startedAt, minutes: 0, ...(seed ? { seed } : {}) };
258
288
  },
259
289
  async status(h) {
260
290
  let s;
@@ -11,7 +11,7 @@
11
11
  * {op:"attach", id, resume?} → (`resume` also clears a pending cancel, #4592) log.jsonl rows replayed, then live rows/lines and done; a finished batch replays report.json
12
12
  * ({type:"done", replay:true}) unless it has unrun added issues; a batch nobody hosts is resumed here
13
13
  * {op:"set-parallel", id, k} → {type:"ok", parallel}
14
- * {op:"clear-breaker", id} → {type:"ok", cleared, acknowledged, hosted} (#5947): a hosted runner resets its in-memory breaker (request file + ack); otherwise state.json is rewritten
14
+ * {op:"clear-breaker", id} → {type:"ok", cleared, acknowledged, hosted} (#5947): a hosted runner resets its in-memory breaker (request file + ack, #5964: the request is never dropped; no ack within waitMs → pending:true); otherwise state.json is rewritten
15
15
  * {op:"set-execution", id, maxRemote?, mode?} → {type:"ok", execution} (#5138): live max_remote / placement (remote|hybrid|local); remote/hybrid refused for a batch with no provider
16
16
  * {op:"requeue", id, issues, reason, by} → {type:"ok", requeued, refused, hosted, reopened} (#4550): see batch.requeue; a finished batch is hosted again
17
17
  * {op:"add", id, issues} → {type:"ok", added, skipped, hosted} (#4408): merged into the batch's `add` file, which a
@@ -370,10 +370,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
370
370
  let acknowledged = false, cleared = false;
371
371
  if (isHosted) {
372
372
  const at = b.requestClearBreaker();
373
- for (let i = 0; i < 140 && !acknowledged; i++) {
373
+ // #5964: never drop the request: the runner consumes it on its next pass (time-scoped against the trip)
374
+ const budget = Math.min(Number.isFinite(req.waitMs) && req.waitMs > 0 ? req.waitMs : 7000, 60000);
375
+ for (let i = 0, n = Math.ceil(budget / 50); i < n && !acknowledged; i++) {
374
376
  const a = b.readClearBreakerAck();
375
377
  if (a && a.at >= at) { acknowledged = true; cleared = Boolean(a.cleared); } else await new Promise((r) => setTimeout(r, 50));
376
378
  }
379
+ if (!acknowledged) return send({ type: "ok", cleared: false, acknowledged: false, pending: true, hosted: true }, true);
377
380
  }
378
381
  if (!acknowledged) {
379
382
  b.readClearBreaker(); // drop an unconsumed request so it cannot clear a later trip
@@ -149,6 +149,42 @@ describe("schedd host scheduler (#4192)", () => {
149
149
  } finally { await h.cleanup(); }
150
150
  });
151
151
 
152
+ it("#5964 a hosted clear-breaker not acked within its wait answers pending, and the request is still honoured by the runner (never dropped)", async () => {
153
+ const h = host();
154
+ try {
155
+ await h.daemon();
156
+ const all = capture(() => h.inWork(() => orchestrateFromCli(["1", "2", "--parallel", "1", "--repo", "o/r", "--no-prefilter"], h.client)));
157
+ await until(() => h.launched().length === 1 && h.lanePids().length === 1);
158
+ const [id] = listBatches(h.root);
159
+ const b = openBatch(h.root, id);
160
+ // a 1 ms wait only polls the ack once, so the reply is pending unless the runner happened to ack in that instant: retry until it does not
161
+ let r = null;
162
+ for (let i = 0; i < 40 && !r?.pending; i++) r = await request(await connectDaemon({ dir: h.sched, spawnDaemon: null }), { op: "clear-breaker", id, waitMs: 1 }, undefined, { timeoutMs: 20000 });
163
+ assert.deepEqual({ hosted: r.hosted, acknowledged: r.acknowledged, pending: r.pending }, { hosted: true, acknowledged: false, pending: true });
164
+ // the old code deleted the request here and rewrote state.json, so no ack would ever follow
165
+ await until(() => b.readClearBreakerAck() && !existsSync(join(h.root, id, "clear-breaker")));
166
+ writeFileSync(h.release, "");
167
+ await all;
168
+ } finally { await h.cleanup(); }
169
+ });
170
+
171
+ it("#5964 cli prints pending message when the hosted runner has not acked within its wait", async () => {
172
+ const h = host();
173
+ try {
174
+ await h.daemon();
175
+ const all = capture(() => h.inWork(() => orchestrateFromCli(["1", "2", "--parallel", "1", "--repo", "o/r", "--no-prefilter"], h.client)));
176
+ await until(() => h.launched().length === 1 && h.lanePids().length === 1);
177
+ const [id] = listBatches(h.root);
178
+ const lines = []; let r = null;
179
+ for (let i = 0; i < 40 && !r?.pending; i++) { lines.length = 0; r = await runBatch({ argv: ["--clear-breaker", id], deps: { batchRoot: h.root, scheddDir: h.sched, pollMs: 1 }, sink: { line: (l) => lines.push(l) } }); }
180
+ assert.equal(r.pending, true);
181
+ assert.match(lines[0], /pending: the runner will clear it on its next pass/);
182
+ assert.doesNotMatch(lines[0], /did not acknowledge/);
183
+ writeFileSync(h.release, "");
184
+ await all;
185
+ } finally { await h.cleanup(); }
186
+ });
187
+
152
188
  it("#5947 clear-breaker on a hosted batch reaches the live runner, which acknowledges it (no daemon restart)", async () => {
153
189
  const h = host();
154
190
  try {
@@ -16,6 +16,7 @@ import { makeWarm } from "./warm.mjs";
16
16
  import { resolveLaneImage, laneImageNow, laneToolsTag, isLaneToolsTagOf } from "./lane-tools.mjs";
17
17
  import { hostDiskFree, ensureNatPin, netState } from "./health.mjs";
18
18
  import { laneDiskUsedGb, planDiskCap, fstrimDue, runFstrim } from "./disk.mjs";
19
+ import { makeMirrorSeed, dockerRunner } from "./mirror-seed.mjs";
19
20
  import { planIdleEviction, CACHE_LABEL, agentLabel } from "./cache-sweep.mjs";
20
21
 
21
22
  const LABEL = "computeshare=1";
@@ -103,7 +104,7 @@ export async function buildWithRetry(build, { sleep = (ms) => new Promise((r) =>
103
104
  }
104
105
  }
105
106
 
106
- export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, net = netState, vm = vmSize, trim = runFstrim } = {}) {
107
+ export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null } = {}) {
107
108
  const stateDir = cfg.state_dir;
108
109
  const store = jsonStore(join(stateDir, "state.json"), { sandboxes: {} });
109
110
  const sb = () => store.data.sandboxes;
@@ -379,6 +380,15 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
379
380
  /** cgroup cpu weight per class (docker --cpu-shares); a borrowed lane yields to a reserved one under contention. */
380
381
  const sharesArgs = (prio) => (weighted() ? ["--cpu-shares", String(SHARES()[prio])] : []);
381
382
 
383
+ /** The per-repo cache volume (`/cache`: worktrees, bare mirror, stores). An explicit agent_id gives this agent its own volume. */
384
+ const cacheVolumeOf = (key) => `cs-cache-${cfg.agent_id ? `${agentId}-` : ""}${String(key ?? "default").toLowerCase().replace(/[^a-z0-9_.-]/g, "-")}`;
385
+ /** #5949: dispatcher-seeded mirrors (GET /mirrors, POST /mirrors/seed); git runs in a helper container on the cache volume. */
386
+ const mirrors = makeMirrorSeed({ seedDir: join(stateDir, "seed"), runnerFor: ({ slug, cache_key }) => {
387
+ const volume = cacheVolumeOf(cache_key ?? slug), run = (mirrorRunner ?? dockerRunner)({ volume, image, seedDir: join(stateDir, "seed") });
388
+ return async (script, env) => { try { await docker.createVolume?.(volume, [CACHE_LABEL, AGENT]); } catch { /* an unlabelled volume still works */ } cacheUsed.set(volume, now()); return run(script, env); };
389
+ } });
390
+ const seedFail = (e) => { if (e.status) throw Object.assign(new Error(e.message), { status: e.status, body: { error: e.message, ...(e.extra ?? {}) } }); throw e; };
391
+
382
392
  async function launch({ spec, cpus, mem_gb, limit = null }) {
383
393
  if (typeof spec?.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(spec.id) || !Array.isArray(spec.command) || !spec.command.length) throw Object.assign(new Error("spec.id ([A-Za-z0-9._-], max 128) and spec.command are required"), { status: 400 });
384
394
  let existing = own(spec.id);
@@ -438,8 +448,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
438
448
  const rec = { id: spec.id, name, dir, issue: spec.issue ?? null, slug: spec.repo?.slug ?? null, repo: slugOf(spec), batch: spec.batch ?? null, cpus, mem_gb, result_file: spec.result_file ?? null, state: "starting", startedAt: now(), finishedAt: null, lease: now(), credToken, docker: withDocker, ...(weighted() || spec.priority ? { priority: prio, ...(reservation ? { reservation } : {}) } : {}) };
439
449
  sb()[spec.id] = rec;
440
450
  store.save();
441
- const cacheKey = String(spec.cache?.key ?? spec.repo?.slug ?? "default").toLowerCase().replace(/[^a-z0-9_.-]/g, "-");
442
- rec.cacheVolume = `cs-cache-${cfg.agent_id ? `${agentId}-` : ""}${cacheKey}`; // an explicit agent_id gives this agent its own volume: a shared one would let its work sweep delete a co-resident agent's worktrees
451
+ rec.cacheVolume = cacheVolumeOf(spec.cache?.key ?? spec.repo?.slug); // an explicit agent_id gives this agent its own volume: a shared one would let its work sweep delete a co-resident agent's worktrees
443
452
  rec.workDir = workDirOf(name);
444
453
  cacheUsed.set(rec.cacheVolume, now());
445
454
  try { await docker.createVolume?.(rec.cacheVolume, [CACHE_LABEL, AGENT]); } catch (e) { log.warn?.(`label ${rec.cacheVolume}: ${String(e.stderr || e.message).slice(0, 200)}`); } // an unlabelled volume still works
@@ -901,6 +910,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
901
910
 
902
911
  const routes = [
903
912
  [route("GET", "/health"), async () => ({ status: 200, body: { ok: true, ...capacity() } })],
913
+ [route("GET", "/mirrors"), async (_p, _b, url) => ({ status: 200, body: await mirrors.tips({ slug: url.searchParams.get("slug"), cache_key: url.searchParams.get("cache_key"), upload: url.searchParams.get("upload") }).catch(seedFail) })], // #5949
914
+ [route("POST", "/mirrors/seed"), async (_p, body) => { try { return { status: 200, body: body?.finish ? await mirrors.finish(body) : mirrors.chunk(body) }; } catch (e) { return { status: e.status ?? 500, body: { error: e.message, ...(e.extra ?? {}) } }; } }],
904
915
  [route("GET", "/capacity"), async () => ({ status: 200, body: capacity() })],
905
916
  [route("POST", "/sandboxes"), async (_p, body) => { const r = await launch(body ?? {}); if (Number.isInteger(body?.spec?.warm)) warm.replenish().catch((e) => log.warn?.(`warm replenish: ${e.message}`)); return r; }],
906
917
  [route("GET", "/warm"), async () => ({ status: 200, body: { warm: warm.list() } })],
@@ -8,6 +8,8 @@ import { existsSync, readFileSync, rmSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
 
10
10
  export const CACHE_LABEL = "computeshare.cache=1";
11
+ /** #5955: every package-manager store the lanes write (depcache.mjs env(), agent.mjs pnpm store), relative to the /cache volume root. One list for the sweep and pruneCaches. */
12
+ export const PACKAGE_STORES = ["pnpm-store", ...["pnpm-store", "npm-cache", "uv-cache", "poetry-cache", "pip-cache"].map((n) => `forge-depcache/stores/${n}`)];
11
13
  /** #5881: owner label; the reaper and sweeps touch only containers and volumes carrying their own agent's label. */
12
14
  export const agentLabel = (id) => `computeshare.agent=${id}`;
13
15
  const DAY = 86400000;
@@ -47,7 +49,7 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ke
47
49
  const errors = [], removed = [];
48
50
  const rm = (p) => { try { rmSync(p, { recursive: true, force: true }); removed.push(p); } catch (e) { errors.push(`${p}: ${e.message}`); } };
49
51
  const cutoff = now - maxAgeDays * DAY;
50
- for (const d of ["uv", "npm", "pip", "poetry"]) { // package caches: old files out, then the empty dirs
52
+ for (const d of PACKAGE_STORES) { // package caches: old files out, then the empty dirs
51
53
  const dir = join(root, d);
52
54
  if (!existsSync(dir)) continue;
53
55
  sh("find", [dir, "-type", "f", "-mtime", `+${maxAgeDays}`, "-delete"]);
@@ -64,7 +66,7 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ke
64
66
  const entries = [];
65
67
  const keepSet = new Set(keep);
66
68
  for (const k of kids(join(root, "work"))) entries.push({ ...k, bytes: sizeOf(k.path), live: keepSet.has(k.path) });
67
- for (const d of ["uv", "npm", "pip", "poetry", "env", "forge-depcache", "forge-depcache/stores"]) for (const k of kids(join(root, d))) if (!k.path.endsWith("/stores")) entries.push({ ...k, bytes: sizeOf(k.path), live: false });
69
+ for (const d of [...PACKAGE_STORES, "env", "forge-depcache", "forge-depcache/stores"]) for (const k of kids(join(root, d))) if (!k.path.endsWith("/stores")) entries.push({ ...k, bytes: sizeOf(k.path), live: false });
68
70
  const plan = planCacheCap(entries, maxGb * 1024 ** 3);
69
71
  for (const p of plan.delete) rm(p);
70
72
  }
package/bin/pool/cli.mjs CHANGED
@@ -15,7 +15,7 @@ import { call as httpCall } from "./http.mjs";
15
15
  const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
16
16
  const loadJson = (p) => JSON.parse(readFileSync(p, "utf8"));
17
17
 
18
- const USAGE = "usage: forgedock pool router [install] | enroll [--cpus N --mem GB --agent-url URL | --outbound | --one-liner] | status [--json] [--account A] | link <user_code> [--account A] | policy <agent> [--cpus N --mem GB --idle-only --pause --resume-policy] | limit <agent> --lanes N|none | pause | resume | uninstall --yes | upgrade [agent] | remove <agent> [--config path]";
18
+ const USAGE = "usage: forgedock pool router [install] | enroll [--cpus N --mem GB --agent-url URL | --outbound | --one-liner] | status [--json] [--account A] | link <user_code> [--account A] | policy <agent> [--cpus N --mem GB --idle-only --pause --resume-policy] | limit <agent> --lanes N|none | pause | resume | uninstall [--yes] | upgrade [agent] | remove <agent> [--config path]";
19
19
  const HELP_FLAGS = ["--help", "-h"];
20
20
  // Flags each verb accepts: `value` flags consume the next token, `bool` flags stand alone. Anything else dash-prefixed is rejected (#5008).
21
21
  const VERB_FLAGS = {
@@ -26,7 +26,7 @@ const VERB_FLAGS = {
26
26
  policy: { value: ["--config", "--cpus", "--mem"], bool: ["--idle-only", "--no-idle-only", "--pause", "--resume-policy"] },
27
27
  pause: { value: ["--config"], bool: [] },
28
28
  resume: { value: ["--config"], bool: [] },
29
- uninstall: { value: ["--config"], bool: ["--yes"] },
29
+ uninstall: { value: [], bool: ["--yes"] },
30
30
  upgrade: { value: ["--config"], bool: [] },
31
31
  remove: { value: ["--config"], bool: [] },
32
32
  limit: { value: ["--config", "--lanes"], bool: [] },
@@ -178,13 +178,18 @@ export async function runPoolCli(argv, deps = {}) {
178
178
  }
179
179
  case "uninstall": {
180
180
  // #5885: the owner removes this box's agent. Destructive, so it needs --yes; running lanes are not waited for.
181
- const win = (deps.platform ?? process.platform) === "win32";
181
+ // The shipped per-OS scripts (#5883) own the teardown at fixed install paths; no path from the command line reaches a delete, and
182
+ // without --yes the script's own --dry-run is the preview, so what is shown is what --yes does.
183
+ const platform = deps.platform ?? process.platform;
182
184
  const run = deps.spawn ?? spawnSync;
183
- if (!rest.includes("--yes")) { console.log(win ? "would run pool/install/uninstall-agent.ps1 (removes the keep-alive task, firewall rules and the computeshare WSL distro)" : "would stop and disable computeshare-agent, delete its systemd unit and /etc/computeshare"); console.log("re-run with --yes to proceed"); break; }
184
- const steps = win
185
- ? [["powershell", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", join(repoRoot, "pool", "install", "uninstall-agent.ps1")]]]
186
- : [["systemctl", ["disable", "--now", "computeshare-agent"]], ["rm", ["-f", "/etc/systemd/system/computeshare-agent.service"]], ["systemctl", ["daemon-reload"]], ["rm", ["-rf", flag("config") ? dirname(flag("config")) : "/etc/computeshare"]]];
185
+ const dir = join(repoRoot, "pool", "install");
186
+ const dry = !rest.includes("--yes");
187
+ const steps = platform === "win32"
188
+ ? (dry ? [] : [["powershell", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", join(dir, "uninstall-agent.ps1")]]])
189
+ : [["bash", [join(dir, platform === "darwin" ? "uninstall-agent-macos.sh" : "uninstall-agent-linux.sh"), ...(dry ? ["--dry-run"] : [])]]];
190
+ if (dry && platform === "win32") console.log("would run pool/install/uninstall-agent.ps1 (removes the keep-alive task, firewall rules and the computeshare WSL distro)");
187
191
  for (const [bin, args] of steps) { const r = run(bin, args, { stdio: "inherit" }); if (r.status !== 0) throw new Error(`${bin} ${args[0]} exited ${r.status}`); }
192
+ if (dry) { console.log("re-run with --yes to proceed"); break; }
188
193
  console.log("agent uninstalled from this box. Remove it from the router with: forgedock pool remove <agent>");
189
194
  break;
190
195
  }
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { execFile } from "node:child_process";
4
4
  import { readFileSync } from "node:fs";
5
+ import { PACKAGE_STORES } from "./cache-sweep.mjs";
5
6
 
6
7
  /** #5757: work-dir and cache sweeps walk big trees (node_modules): 10 min, not the 120 s of a small rm. */
7
8
  export const SWEEP_TIMEOUT_MS = 10 * 60000;
@@ -64,7 +65,7 @@ export const dockerCli = {
64
65
  /** #5891: dangling images (rebuildable) only; never a tagged or in-use one. */
65
66
  async pruneImages() { return docker(["image", "prune", "-f"], { timeoutMs: 10 * 60000 }); },
66
67
  /** #5891: package-manager caches inside a running sandbox (rebuildable); the worktree and lane state are untouched. Best effort. */
67
- async pruneCaches(name) { try { await docker(["exec", name, "sh", "-c", "rm -rf \"$HOME\"/.npm/_cacache \"$HOME\"/.cache/pip \"$HOME\"/.cache/yarn \"$HOME\"/.cache/pnpm /root/.npm/_cacache /root/.cache/pip 2>/dev/null; true"], { timeoutMs: 120000 }); } catch (e) { if (!/No such container|is not running|is paused/i.test(e.stderr ?? "")) throw e; } },
68
+ async pruneCaches(name) { try { await docker(["exec", name, "sh", "-c", `rm -rf ${PACKAGE_STORES.map((d) => `/cache/${d}`).join(" ")} 2>/dev/null; true`], { timeoutMs: 120000 }); } catch (e) { if (!/No such container|is not running|is paused/i.test(e.stderr ?? "")) throw e; } },
68
69
  /** #5884: removes this agent's stopped containers and dangling images only (`label` carries the agent id, #5881). */
69
70
  async containerPrune(label) { return docker(["container", "prune", "-f", ...[].concat(label).flatMap((l) => ["--filter", `label=${l}`])], { timeoutMs: 120000 }); },
70
71
  async imagePrune(label) { return docker(["image", "prune", "-f", ...[].concat(label).flatMap((l) => ["--filter", `label=${l}`])], { timeoutMs: 120000 }); },
@@ -0,0 +1,103 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5949: dispatcher-seeded repo mirrors. The agent receives a git bundle in checksummed chunks (resumable by offset) and applies
5
+ * it to the repo's bare mirror in the cache volume (`<cache>/git/<slug>.git`, the path entrypoint.sh and `env ensure` read):
6
+ * copy of the mirror (or a fresh bare repo) -> `git fetch <bundle>` -> `fsck --connectivity-only` -> rename into place, under a
7
+ * per-slug flock. Any failure removes the tmp copy and leaves the live mirror untouched. The git steps run in a helper container
8
+ * of the lane image that mounts the volume (`runner`); tests inject a runner that runs the same script on a local directory.
9
+ */
10
+ import { createHash } from "node:crypto";
11
+ import { execFile } from "node:child_process";
12
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync } from "node:fs";
13
+ import { join } from "node:path";
14
+
15
+ /** Per-chunk cap on the decoded payload; base64 of it stays under the 1 MB JSON body limit of the router and agent. */
16
+ export const SEED_CHUNK_MAX = 512 * 1024;
17
+ export const mirrorName = (slug) => String(slug).replace(/\//g, "_");
18
+ const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9._-]+)?$/;
19
+ const SHA_RE = /^[a-f0-9]{64}$/;
20
+ const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
21
+ const fail = (status, error, extra = {}) => Object.assign(new Error(error), { status, extra });
22
+
23
+ /** Lists the mirror's ref tips (`sha ref` lines), or prints ABSENT. Env: CACHE, NAME. */
24
+ export const TIPS_SCRIPT = 'm="$CACHE/git/$NAME.git"; if [ -d "$m" ]; then git -C "$m" for-each-ref --format="%(objectname) %(refname)" refs/heads refs/tags; else echo ABSENT; fi';
25
+ /** Applies $BUNDLE to the mirror atomically. Env: CACHE, NAME, BUNDLE. Exit non-zero leaves the live mirror as it was. */
26
+ export const APPLY_SCRIPT = `set -eu
27
+ m="$CACHE/git/$NAME.git"; t="$m.tmp"; old="$m.old"
28
+ mkdir -p "$CACHE/git"
29
+ exec 9>"$CACHE/git/$NAME.lock"
30
+ if command -v flock >/dev/null 2>&1; then flock 9; fi
31
+ cleanup() { rm -rf "$t"; }
32
+ trap cleanup EXIT
33
+ rm -rf "$t" "$old"
34
+ if [ -d "$m" ]; then cp -al "$m" "$t"; else git init --bare --quiet "$t"; fi
35
+ git -C "$t" bundle verify "$BUNDLE" >/dev/null
36
+ if git -C "$t" bundle list-heads "$BUNDLE" | grep -q ' refs/remotes/origin/'; then heads='+refs/remotes/origin/*:refs/heads/*'; else heads='+refs/heads/*:refs/heads/*'; fi
37
+ git -C "$t" fetch --quiet --no-tags "$BUNDLE" "$heads" '+refs/tags/*:refs/tags/*'
38
+ git -C "$t" fsck --connectivity-only --no-dangling >/dev/null
39
+ date +%s > "$t/cs-seeded"
40
+ if [ -d "$m" ]; then mv "$m" "$old"; fi
41
+ mv "$t" "$m"
42
+ rm -rf "$old"
43
+ trap - EXIT`;
44
+
45
+ /** Default runner: the script in a helper container of the lane image with the cache volume at /cache and the seed dir at /seed. */
46
+ export function dockerRunner({ volume, image, seedDir }) {
47
+ return (script, env) => new Promise((resolve, reject) => {
48
+ const e = { ...env, CACHE: "/cache", ...(env.BUNDLE ? { BUNDLE: `/seed/${env.BUNDLE}` } : {}) };
49
+ const args = ["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "-v", `${seedDir}:/seed:ro`, ...Object.entries(e).flatMap(([k, v]) => ["-e", `${k}=${v}`]), "--entrypoint", "bash", image, "-c", script];
50
+ execFile("docker", args, { timeout: 10 * 60000, maxBuffer: 1 << 24 }, (err, stdout, stderr) => (err ? reject(Object.assign(err, { stderr })) : resolve(String(stdout))));
51
+ });
52
+ }
53
+
54
+ /** Local runner (tests, and agents whose cache is a host directory): the same script on `root` as the cache dir. */
55
+ export function localRunner({ root, seedDir }) {
56
+ return (script, env) => new Promise((resolve, reject) => {
57
+ const e = { ...process.env, ...env, CACHE: root, ...(env.BUNDLE ? { BUNDLE: join(seedDir, env.BUNDLE) } : {}) };
58
+ execFile("bash", ["-c", script], { env: e, timeout: 10 * 60000, maxBuffer: 1 << 24 }, (err, stdout, stderr) => (err ? reject(Object.assign(err, { stderr })) : resolve(String(stdout))));
59
+ });
60
+ }
61
+
62
+ /** `runnerFor({slug, cache_key})` -> runner. Returns the agent's mirror seed handlers. */
63
+ export function makeMirrorSeed({ seedDir, runnerFor }) {
64
+ mkdirSync(seedDir, { recursive: true });
65
+ const part = (up) => join(seedDir, `${up}.part`);
66
+ const size = (up) => { try { return statSync(part(up)).size; } catch { return 0; } };
67
+ const check = (b) => {
68
+ if (typeof b?.slug !== "string" || !SLUG_RE.test(b.slug)) throw fail(400, "slug required");
69
+ if (typeof b.upload !== "string" || !SHA_RE.test(b.upload)) throw fail(400, "upload must be the bundle sha256");
70
+ };
71
+ return {
72
+ /** `GET /mirrors`: {mirrors: {slug: {ref: sha} | "absent"}, upload_offset?}. */
73
+ async tips({ slug, cache_key = null, upload = null }) {
74
+ if (typeof slug !== "string" || !SLUG_RE.test(slug)) throw fail(400, "slug required");
75
+ const out = String(await runnerFor({ slug, cache_key })(TIPS_SCRIPT, { NAME: mirrorName(slug) })).trim();
76
+ const mirror = out === "ABSENT" ? "absent" : Object.fromEntries(out.split("\n").filter(Boolean).map((l) => { const i = l.indexOf(" "); return [l.slice(i + 1), l.slice(0, i)]; }));
77
+ return { mirrors: { [slug]: mirror }, ...(upload && SHA_RE.test(upload) ? { upload_offset: size(upload) } : {}) };
78
+ },
79
+ /** One chunk: {slug, cache_key, upload, offset, data_b64, sha256}. A wrong offset is a 409 carrying the offset to resume from. */
80
+ chunk(b) {
81
+ check(b);
82
+ const buf = Buffer.from(String(b.data_b64 ?? ""), "base64");
83
+ if (!buf.length || buf.length > SEED_CHUNK_MAX) throw fail(413, `chunk must be 1..${SEED_CHUNK_MAX} bytes`);
84
+ if (sha256(buf) !== b.sha256) throw fail(422, "chunk checksum mismatch");
85
+ const have = size(b.upload);
86
+ if (b.offset !== have) throw fail(409, "offset mismatch", { offset: have });
87
+ appendFileSync(part(b.upload), buf);
88
+ return { offset: have + buf.length };
89
+ },
90
+ /** Verifies the whole bundle against {size, sha256 = upload} and applies it. A corrupt upload is dropped; the mirror is never touched on failure. */
91
+ async finish(b) {
92
+ check(b);
93
+ const f = b.finish ?? {};
94
+ const have = size(b.upload);
95
+ if (!Number.isInteger(f.size) || have !== f.size) throw fail(409, "incomplete upload", { offset: have });
96
+ if (!existsSync(part(b.upload)) || sha256(readFileSync(part(b.upload))) !== b.upload) { rmSync(part(b.upload), { force: true }); throw fail(422, "bundle checksum mismatch"); }
97
+ try { await runnerFor(b)(APPLY_SCRIPT, { NAME: mirrorName(b.slug), BUNDLE: `${b.upload}.part` }); }
98
+ catch (e) { rmSync(part(b.upload), { force: true }); throw fail(422, `bundle apply failed: ${String(e.stderr || e.message).slice(-300)}`); }
99
+ rmSync(part(b.upload), { force: true });
100
+ return { ok: true, ...(await this.tips({ slug: b.slug, cache_key: b.cache_key })) };
101
+ },
102
+ };
103
+ }
@@ -329,6 +329,29 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
329
329
  return cpusFree >= size.cpus && memFree >= size.mem_gb;
330
330
  };
331
331
  const headroom = (c, spec) => (spec?.priority === "borrow" && Number.isFinite(c.cpus_free_unreserved) ? c.cpus_free_unreserved : 0);
332
+ // #5949: the dispatcher seeds a repo mirror before launch. The agent that will own the sandbox is picked here (the placing agent
333
+ // when it is known, else the best-fitting one) and remembered, so launch() prefers it and the seeded mirror is the one the lane uses.
334
+ const seedPick = new Map(); // sandbox id -> {agent, at}
335
+ const SEED_CHUNK_B64_MAX = 768 * 1024;
336
+ async function seedAgent(id) {
337
+ const known = own(sbx(), id);
338
+ if (known && own(agents(), known.agent)) return known.agent;
339
+ const hit = seedPick.get(id);
340
+ if (hit && own(agents(), hit.agent) && now() - hit.at < 30 * 60000) return hit.agent;
341
+ for (const [k, v] of seedPick) if (now() - v.at >= 30 * 60000) seedPick.delete(k);
342
+ const fits = (await capacities()).filter((c) => c.ok && !c.paused && c.host_disk_low !== true && c.disk_capped !== true).sort((a, b) => b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
343
+ if (!fits.length) return null;
344
+ seedPick.set(id, { agent: fits[0].name, at: now() });
345
+ return fits[0].name;
346
+ }
347
+ async function seedForward(id, method, path, body) {
348
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(id)) return { status: 400, body: { error: "bad sandbox id" } };
349
+ if (typeof body?.data_b64 === "string" && body.data_b64.length > SEED_CHUNK_B64_MAX) return { status: 413, body: { error: "chunk too large" } };
350
+ const name = await seedAgent(id), a = name && own(agents(), name);
351
+ if (!a) return { status: 503, body: { error: "no agent available to seed" }, retryAfter: cfg.retry_after_s ?? 60 };
352
+ try { const r = await agentCall(a, method, path, body, 120000); return { status: r.status, body: agentBody(r, name) }; }
353
+ catch (e) { return { status: 502, body: { error: `agent ${name} unreachable: ${e.message}` } }; }
354
+ }
332
355
  /** #5886: a spec naming an account is placed only on that account's agents; without one, any enrolled agent (as before). */
333
356
  const inAccount = (c, spec) => typeof spec?.account !== "string" || own(agents(), c.name)?.account === spec.account;
334
357
  async function launch(spec) {
@@ -348,6 +371,8 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
348
371
  const fits = sized.filter((c) => c.host_disk_low !== true && c.disk_capped !== true).sort((a, b) => headroom(b, spec) - headroom(a, spec) || b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
349
372
  const laneId = isLane(spec.id), laneCapped = []; // #5735: agents skipped because their lane ceiling is reached
350
373
  let busy = null; // the last agent 503 (e.g. lane_tools image building): its body and Retry-After are passed back
374
+ const seeded = seedPick.get(spec.id)?.agent; // #5949: the agent holding this lane's seeded mirror goes first
375
+ if (seeded) fits.sort((a, b) => (b.name === seeded) - (a.name === seeded));
351
376
  for (const c of fits) {
352
377
  if (laneId && atCeiling(c.name)) { laneCapped.push({ name: c.name, ...laneView(c.name) }); continue; }
353
378
  if (laneId) reserve(c.name, spec.id);
@@ -577,6 +602,8 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
577
602
  [route("GET", "/health"), { fn: async () => ({ status: 200, body: { ok: true, agents: Object.keys(agents()).length, sandboxes: Object.keys(sbx()).length } }), auth: "none" }],
578
603
  [route("POST", "/sandboxes"), fd(async (_p, body) => launch(body))],
579
604
  [route("POST", "/sandboxes/claim"), fd(async (_p, body) => claim(body))],
605
+ [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)))}`))], // #5949
606
+ [route("POST", "/sandboxes/:id/seed"), fd(async ({ id }, body) => seedForward(id, "POST", "/mirrors/seed", body))],
580
607
  [route("GET", "/sandboxes/:id"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}`))],
581
608
  [route("GET", "/sandboxes/:id/logs"), fd(async ({ id }, _b, url) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/logs?cursor=${encodeURIComponent(url.searchParams.get("cursor") ?? "0")}`))],
582
609
  [route("GET", "/sandboxes/:id/result"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/result`))],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "forgedock",
3
- "version": "1.64.0",
3
+ "version": "1.65.0",
4
4
  "description": "An AI engineering team that ships to production",
5
5
  "bin": {
6
6
  "forgedock": "bin/forgedock.mjs"
@@ -45,6 +45,25 @@ checkout_repo() {
45
45
  if [ -n "${CS_REPO_URL:-}" ]; then
46
46
  # Shared bare mirror in the cache volume: later lanes fetch a delta instead of a full clone.
47
47
  mirror="/cache/git/$(echo "${CS_REPO_SLUG:-repo}" | tr '/' '_').git"
48
+ # #5949: a mirror seeded by the dispatcher (cs-seeded marker, written by the agent's atomic apply) is cloned from directly:
49
+ # no GitHub transfer is needed to start. Its fetch is best effort with retries, and skipped when it already has the lane ref.
50
+ if [ -f "$mirror/cs-seeded" ]; then
51
+ if [ -n "${CS_REPO_REF:-}" ] && git -C "$mirror" rev-parse --verify --quiet "refs/heads/$CS_REPO_REF" >/dev/null; then
52
+ echo "[computeshare] mirror seeded by the dispatcher; skipping the GitHub fetch"
53
+ else
54
+ for attempt in 1 2 3; do
55
+ timeout 90 git -C "$mirror" fetch --prune --quiet origin '+refs/heads/*:refs/heads/*' && break || { echo "[computeshare] GitHub fetch attempt $attempt failed (best effort)"; sleep $((attempt * 5)); }
56
+ done
57
+ fi
58
+ rm -rf /work/repo
59
+ if git clone --quiet --shared ${CS_REPO_REF:+--branch "$CS_REPO_REF"} "$mirror" /work/repo; then
60
+ git -C /work/repo remote set-url origin "$CS_REPO_URL" # pushes stay on GitHub
61
+ cd "$(readlink -f /work/repo)"
62
+ return 0
63
+ fi
64
+ echo "[computeshare] clone from the seeded mirror failed; falling back to GitHub"
65
+ rm -rf /work/repo
66
+ fi
48
67
  # #5947: mirror.sh validates (refs, no empty objects), quarantines a bad one, builds under a lock; `direct` = no --reference.
49
68
  use="$(/usr/local/bin/cs-mirror prepare "$CS_REPO_URL" "$mirror" 2>/dev/null || echo direct)"
50
69
  rm -rf /work/repo