forgedock 1.60.1 → 1.61.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.
Files changed (70) hide show
  1. package/bin/config-schema.mjs +44 -1
  2. package/bin/engine/runlog.mjs +52 -0
  3. package/bin/engine-cli.mjs +9 -4
  4. package/bin/env/bench.mjs +38 -0
  5. package/bin/env/cli.mjs +134 -0
  6. package/bin/env/env.mjs +339 -0
  7. package/bin/forgedock.mjs +32 -3
  8. package/bin/help-text.mjs +2 -0
  9. package/bin/lean/ci-budget.mjs +3 -1
  10. package/bin/lean/ci-classify.mjs +74 -0
  11. package/bin/lean/ci-classify.test.mjs +147 -0
  12. package/bin/lean/ci-emit.mjs +175 -0
  13. package/bin/lean/ci-emit.test.mjs +177 -0
  14. package/bin/lean/ci-preflight.mjs +183 -0
  15. package/bin/lean/ci-preflight.test.mjs +122 -0
  16. package/bin/lean/ci-runner-health.mjs +213 -0
  17. package/bin/lean/ci-runner-health.test.mjs +113 -0
  18. package/bin/lean/ci-watch.mjs +79 -0
  19. package/bin/lean/ci-watch.test.mjs +80 -0
  20. package/bin/lean/depcache.mjs +38 -8
  21. package/bin/lean/deploy-stages.mjs +514 -0
  22. package/bin/lean/deploy-stages.test.mjs +580 -0
  23. package/bin/lean/effects.mjs +50 -0
  24. package/bin/lean/execution.mjs +8 -1
  25. package/bin/lean/lean.mjs +38 -6
  26. package/bin/lean/lean.test.mjs +61 -0
  27. package/bin/lean/release-deploy.mjs +12 -6
  28. package/bin/lean/release-flakes.mjs +16 -0
  29. package/bin/lean/release-flakes.test.mjs +15 -0
  30. package/bin/lean/release-gates.mjs +24 -1
  31. package/bin/lean/release-ledger.mjs +21 -0
  32. package/bin/lean/release-minutes-timing.test.mjs +57 -0
  33. package/bin/lean/release-minutes.mjs +98 -0
  34. package/bin/lean/release-promote.mjs +444 -0
  35. package/bin/lean/release-promote.test.mjs +470 -0
  36. package/bin/lean/release-rollback.mjs +14 -6
  37. package/bin/lean/release.mjs +31 -2
  38. package/bin/lean/sandbox-remote.mjs +11 -3
  39. package/bin/lean/testengine-recall.mjs +82 -0
  40. package/bin/lean/testengine-recall.test.mjs +103 -0
  41. package/bin/lean/testengine-shard.mjs +150 -0
  42. package/bin/lean/testengine-shard.test.mjs +111 -0
  43. package/bin/lean/testengine.mjs +486 -0
  44. package/bin/lean/testengine.test.mjs +303 -0
  45. package/bin/lean/verify-settle.test.mjs +156 -0
  46. package/bin/lean/verify.mjs +98 -3
  47. package/bin/pool/agent.mjs +57 -6
  48. package/bin/pool/ci-events.mjs +189 -0
  49. package/bin/pool/ci-events.test.mjs +143 -0
  50. package/bin/pool/docker.mjs +7 -0
  51. package/bin/pool/lane-tools.mjs +1 -0
  52. package/bin/pool/router.mjs +25 -1
  53. package/bin/pool/warm.mjs +1 -1
  54. package/bin/stats/ci-awareness.mjs +66 -0
  55. package/bin/stats/index.mjs +44 -3
  56. package/bin/stats/release-ledger.test.mjs +226 -0
  57. package/bin/stats/release.mjs +365 -1
  58. package/bin/stats/stats.test.mjs +36 -0
  59. package/docs/CI.md +31 -0
  60. package/docs/CONFIG.md +235 -2
  61. package/docs/ENV-LIBRARY.md +172 -0
  62. package/docs/STATS.md +43 -0
  63. package/docs/ci-events.md +88 -0
  64. package/docs/test-engine.md +98 -0
  65. package/package.json +1 -1
  66. package/pool/README.md +1 -0
  67. package/pool/image/entrypoint.sh +15 -3
  68. package/pool/services/docker-compose.yml +53 -0
  69. package/pool/services/git-mirror.sh +22 -0
  70. package/templates/github-actions/forge-env/action.yml +65 -0
@@ -13,7 +13,7 @@ import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
13
13
  import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs";
14
14
  import { jsonStore } from "./store.mjs";
15
15
  import { makeWarm } from "./warm.mjs";
16
- import { resolveLaneImage, laneImageNow } from "./lane-tools.mjs";
16
+ import { resolveLaneImage, laneImageNow, laneToolsTag } from "./lane-tools.mjs";
17
17
 
18
18
  const LABEL = "computeshare=1";
19
19
  const LOG_CHUNK = 256 * 1024;
@@ -52,7 +52,29 @@ export function liveHeadroom(cfg = {}) {
52
52
  }
53
53
  export const dindName = (name) => `${name}-dind`;
54
54
  export const workVolume = (name) => `cs-work-${name.replace(/^cs-/, "")}`;
55
+ /** #5696: the lane worktree is a plain dir on the cache volume (one mount), so depcache hardlinks never hit EXDEV. */
56
+ export const workDirOf = (name) => `/cache/work/${name.replace(/^cs-/, "")}`;
57
+ const WORK_SWEEP_MS = 10 * 60000;
55
58
  export const safeName = (id) => `cs-${String(id).toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 100)}`;
59
+ /** Minimum gap between two environment-snapshot ensure runs for one cache volume. */
60
+ export const ENV_ENSURE_GAP_MS = 5 * 60000;
61
+ /**
62
+ * `docker run` args for the environment-snapshot helper (env.snapshots): a short-lived container of the lane image that
63
+ * reads the repo's bare mirror in the cache volume, builds the snapshot for the ref's lockfiles when it is missing,
64
+ * stages `ready` hardlink copies and collects old snapshots. It writes only under /cache/env, on the same volume as the
65
+ * lane worktrees (/cache/work), so a lane claims a staged copy with a rename. Pure.
66
+ */
67
+ export function envEnsureArgs({ volume, image, slug, ref = null, laneTools = [], snapshots = {}, net = [], cpus = 2, mem_gb = 4 }) {
68
+ const int = (v, d) => (Number.isInteger(v) && v >= 0 ? v : d);
69
+ return [
70
+ "--rm", "--name", `cs-envbuild-${volume.replace(/^cs-cache-/, "")}`.slice(0, 120), "--label", "computeshare.env=1",
71
+ "--cpus", String(cpus), "--memory", `${Math.round(mem_gb * 1024)}m`, ...net, "-v", `${volume}:/cache`,
72
+ "-e", "FORGE_ENV_ROOT=/cache/env", "-e", `FORGE_ENV_IMAGE=${image}`, "-e", "FORGE_DEPCACHE_ROOT=/cache/forge-depcache", "-e", "npm_config_store_dir=/cache/pnpm-store",
73
+ "--entrypoint", "forgedock", image, "env", "ensure", "--mirror", `/cache/git/${String(slug).replace(/\//g, "_")}.git`, ...(ref ? ["--ref", String(ref)] : []),
74
+ "--repo", String(slug), "--ready", String(int(snapshots.ready, 2)), "--keep", String(int(snapshots.keep, 3)), "--max-age-days", String(int(snapshots.max_age_days, 14)),
75
+ ...(laneTools.length ? ["--lane-tools", [...laneTools].sort().join(",")] : []),
76
+ ];
77
+ }
56
78
  const envLine = (k, v) => `${k}=${String(v).replace(/\r?\n/g, " ")}`;
57
79
 
58
80
  /**
@@ -96,6 +118,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
96
118
  const used = () => Object.values(sb()).filter((s) => s.state !== "exited").reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
97
119
  // #5535: disk figures for the router inventory; optional, omitted when unreadable. Sandbox dirs are walked at most every 60s.
98
120
  let diskCache = { at: 0, mb: {} };
121
+ let lastWorkSweep = -Infinity;
99
122
  const dirMb = (d) => { let n = 0, seen = 0; const walk = (x) => { if (seen++ > 200000) return; let st; try { st = lstatSync(x); } catch { return; } n += st.size; if (st.isDirectory()) { try { for (const e of readdirSync(x)) walk(join(x, e)); } catch { /* unreadable */ } } }; walk(d); return Math.round(n / 1048576); };
100
123
  function diskView() {
101
124
  const out = {};
@@ -113,6 +136,20 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
113
136
  return { host: cfg.name ?? hostname(), ...running, vm: vmSize(), ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), cpus_total: cfg.allow_cpus, mem_total_gb: cfg.allow_mem_gb, cpus_free: cfg.allow_cpus - u.cpus, mem_free_gb: cfg.allow_mem_gb - u.mem, active: Object.values(sb()).filter((s) => s.state !== "exited").length, ...diskView(), paused: Boolean(cfg.paused), live: live(cfg), usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
114
137
  }
115
138
 
139
+ /** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
140
+ const envImageOf = (spec) => (spec.lane_tools?.length ? laneToolsTag(spec.image ?? image, spec.lane_tools) : (spec.image ?? image));
141
+ const envEnsured = new Map(); // cache volume -> last ensure start
142
+ /**
143
+ * env.snapshots: start the snapshot helper for the repo, at most once per ENV_ENSURE_GAP_MS and one at a time per cache
144
+ * volume (the fixed container name refuses a second). Never awaited by a launch and never fails one.
145
+ */
146
+ function ensureEnv({ volume, spec, net }) {
147
+ if (now() - (envEnsured.get(volume) ?? -Infinity) < ENV_ENSURE_GAP_MS) return null;
148
+ envEnsured.set(volume, now());
149
+ const args = envEnsureArgs({ volume, image: envImageOf(spec), slug: spec.repo.slug, ref: spec.repo.ref ?? null, laneTools: spec.lane_tools ?? [], snapshots: spec.env_snapshots, net, cpus: cfg.env_build_cpus ?? 2, mem_gb: cfg.env_build_mem_gb ?? 4 });
150
+ return Promise.resolve().then(() => docker.run(args)).then(() => log.info?.(`env snapshot helper started for ${spec.repo.slug}`), (e) => log.warn?.(`env snapshot helper: ${String(e.stderr || e.message).slice(0, 200)}`));
151
+ }
152
+
116
153
  async function launch({ spec, cpus, mem_gb, limit = null }) {
117
154
  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 });
118
155
  const existing = own(spec.id);
@@ -137,15 +174,19 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
137
174
  const envFile = join(dir, "env");
138
175
  const credToken = randomBytes(24).toString("hex");
139
176
  const withDocker = Boolean(spec.docker);
140
- 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 ?? "" };
177
+ 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 ?? "", CS_WORK_DIR: workDirOf(name),
178
+ ...(spec.env_snapshots?.enabled ? { FORGE_ENV_IMAGE: envImageOf(spec) } : {}) }; // the image is part of the snapshot key
141
179
  writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
142
180
  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 };
143
181
  sb()[spec.id] = rec;
144
182
  store.save();
145
183
  const cacheKey = String(spec.cache?.key ?? spec.repo?.slug ?? "default").toLowerCase().replace(/[^a-z0-9_.-]/g, "-");
184
+ rec.cacheVolume = `cs-cache-${cacheKey}`;
185
+ rec.workDir = workDirOf(name);
146
186
  // Public resolvers: host resolvers like Tailscale MagicDNS are not reachable from the container network.
147
187
  const netArgs = ["--add-host", "host.docker.internal:host-gateway", ...(cfg.dns ?? ["1.1.1.1", "8.8.8.8"]).flatMap((d) => ["--dns", String(d)])];
148
188
  let laneCpus = cpus, laneMem = mem_gb, laneNet = netArgs, work = [];
189
+ const cacheMount = ["-v", `${rec.cacheVolume}:/cache`];
149
190
  try {
150
191
  // #5650: a repo's lane_tools select a derived image (built once per tool list); none keeps spec.image ?? image.
151
192
  const laneImage = spec.lane_tools?.length ? await resolveLaneImage({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }) : (spec.image ?? image);
@@ -157,7 +198,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
157
198
  if (limit) { dCpus = limit.dind_cpus; dMem = limit.dind_mem_gb; laneCpus = limit.lane_cpus; laneMem = limit.lane_mem_gb; }
158
199
  else { dCpus = Math.min(cfg.dind_cpus ?? 1, cpus - 1); dMem = Math.min(cfg.dind_mem_gb ?? 2, mem_gb - 1); laneCpus = cpus - dCpus; laneMem = mem_gb - dMem; }
159
200
  ({ cpus: dCpus, mem: dMem } = clampToVm(dCpus, dMem));
160
- work = ["-v", `${workVolume(name)}:/work`];
201
+ work = cacheMount; // the daemon sees the checkout at the same /cache/work path as the lane
161
202
  await docker.run([
162
203
  "--name", dindName(name), "--label", LABEL, "--label", `computeshare.id=${spec.id}`, "--label", "computeshare.role=dind",
163
204
  "--privileged", "--cpus", String(dCpus), "--memory", mb(dMem), "--memory-swap", mb(dMem + swapFor(limit?.dind_swap_gb)),
@@ -176,10 +217,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
176
217
  "--cpus", String(laneCpus), "--memory", mb(laneMem), "--memory-swap", mb(laneMem + swapFor(limit?.lane_swap_gb)), "--pids-limit", "4096",
177
218
  "--env-file", envFile, ...laneNet, ...work,
178
219
  ...(spec.claim_dir ? ["-v", `${join(dir, "claim")}:/claim`] : []), // #4912: warm sandboxes receive their lane here
179
- "-v", `cs-cache-${cacheKey}:/cache`, "-v", `${join(dir, "result")}:/result`, "-v", `${join(dir, "out")}:/csout`,
220
+ ...(withDocker ? [] : cacheMount), "-v", `${join(dir, "result")}:/result`, "-v", `${join(dir, "out")}:/csout`,
180
221
  laneImage, ...spec.command.map(String),
181
222
  ]);
182
223
  rec.state = "running";
224
+ if (spec.env_snapshots?.enabled && spec.repo?.slug) ensureEnv({ volume: rec.cacheVolume, spec, net: netArgs });
183
225
  } catch (e) {
184
226
  rec.state = "exited";
185
227
  rec.finishedAt = now();
@@ -228,7 +270,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
228
270
  if (!r) return false;
229
271
  const history = r.usage?.samples ? JSON.stringify({ at: new Date(now()).toISOString(), id: r.id, issue: r.issue, docker: Boolean(r.docker), minutes: Math.round((((r.finishedAt ?? now()) - r.startedAt) / 60000) * 10) / 10, ...usageView(r) }) : null;
230
272
  await docker.remove(r.name);
231
- if (r.docker) { await docker.remove(dindName(r.name)); await docker.removeVolume(workVolume(r.name)); }
273
+ if (r.docker) await docker.remove(dindName(r.name));
274
+ if (r.workDir) { try { await docker.removeWorkDir(r.cacheVolume, image, r.workDir); } catch (e) { log.warn?.(`work dir ${r.workDir}: ${String(e.stderr || e.message).slice(0, 200)}`); } }
275
+ else if (r.docker) await docker.removeVolume(workVolume(r.name)); // sandbox launched before #5696
232
276
  try { await docker.wipe(r.dir, image); } catch (e) { log.warn?.(`wipe ${r.name}: ${String(e.stderr || e.message).slice(0, 200)}`); }
233
277
  rmSync(r.dir, { recursive: true, force: true });
234
278
  delete sb()[r.id];
@@ -254,8 +298,15 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
254
298
  const r = await resize(pendingResize);
255
299
  log.info?.(`pending resize applied: HTTP ${r.status} ${JSON.stringify(r.body)}`);
256
300
  }
257
- const knownVols = new Set(Object.values(sb()).map((r) => workVolume(r.name)));
301
+ const knownVols = new Set(Object.values(sb()).filter((r) => !r.workDir).map((r) => workVolume(r.name)));
258
302
  for (const v of await docker.listVolumes("cs-work-")) if (!knownVols.has(v)) { await docker.removeVolume(v); log.info?.(`removed orphan volume ${v}`); }
303
+ if (t - lastWorkSweep >= WORK_SWEEP_MS) {
304
+ lastWorkSweep = t;
305
+ const keep = Object.values(sb()).map((r) => r.workDir).filter(Boolean);
306
+ for (const v of await docker.listVolumes("cs-cache-")) {
307
+ try { await docker.pruneWorkDirs(v, image, keep); } catch (e) { log.warn?.(`work sweep ${v}: ${String(e.stderr || e.message).slice(0, 200)}`); }
308
+ }
309
+ }
259
310
  store.save();
260
311
  }
261
312
 
@@ -0,0 +1,189 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { createHash } from "node:crypto";
4
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ // The pool agent's self-update bundle carries only AGENT_BUNDLE_PATHS (router.mjs), never bin/lean, and the agent loads this
7
+ // module through cli.mjs -> router.mjs. Classification is a router-side extra, so it is optional here: a missing module
8
+ // leaves classify null (events pass through unclassified) instead of crashing the agent at import (1.61.0 outage).
9
+ const { classifyCiFailure = null } = await import("../lean/ci-classify.mjs").catch((e) => {
10
+ if (e?.code === "ERR_MODULE_NOT_FOUND") return {};
11
+ throw e;
12
+ });
13
+
14
+ /** #5688: CI runner events pushed to the pool router and long-polled by agents (parent #5687). */
15
+ export const CI_EVENT_TYPES = ["job_started", "step_started", "step_failed", "test_failed", "job_finished", "runner_unhealthy"];
16
+ export const MAX_BATCH = 200, MAX_LINES = 40, MAX_LINE_CHARS = 500, RING_CAP = 2000, TTL_MS = 24 * 3600 * 1000, MAX_WAIT_S = 60;
17
+ const MAX_STR = 500;
18
+ const DAY_MS = 24 * 3600 * 1000;
19
+
20
+ const bad = (key, why, status = 400) => Object.assign(new Error(`invalid event: ${key} ${why}`), { status, key });
21
+ const str = (e, key, required) => {
22
+ const v = e[key];
23
+ if (v === undefined || v === null) { if (required) throw bad(key, "is required"); return undefined; }
24
+ if (typeof v !== "string" || !v || v.length > MAX_STR) throw bad(key, "must be a non-empty string of at most 500 chars");
25
+ return v;
26
+ };
27
+ const int = (e, key) => {
28
+ const v = e[key];
29
+ if (v === undefined || v === null) return undefined;
30
+ if (!Number.isInteger(v)) throw bad(key, "must be an integer");
31
+ return v;
32
+ };
33
+
34
+ /** Returns the normalized event (known keys only) or throws an error carrying `status` (400 bad key, 413 over a limit) and `key`. */
35
+ export function validateEvent(e) {
36
+ if (!e || typeof e !== "object" || Array.isArray(e)) throw bad("event", "must be an object");
37
+ if (!CI_EVENT_TYPES.includes(e.type)) throw bad("type", `must be one of ${CI_EVENT_TYPES.join(", ")}`);
38
+ const out = { type: e.type, repo: str(e, "repo", true), sha: str(e, "sha", true) };
39
+ const run = e.run_id;
40
+ if (run === undefined || run === null) throw bad("run_id", "is required");
41
+ if (!(typeof run === "string" && run && run.length <= MAX_STR) && !Number.isInteger(run)) throw bad("run_id", "must be a string or integer");
42
+ out.run_id = run;
43
+ out.job = str(e, "job", true);
44
+ const ts = e.ts;
45
+ if (ts === undefined || ts === null) throw bad("ts", "is required");
46
+ if (!(typeof ts === "string" && ts && ts.length <= MAX_STR) && !Number.isFinite(ts)) throw bad("ts", "must be a string or number");
47
+ out.ts = ts;
48
+ if (e.pr !== undefined && e.pr !== null) {
49
+ if (!Number.isInteger(e.pr) && !(typeof e.pr === "string" && /^\d{1,9}$/.test(e.pr))) throw bad("pr", "must be an integer");
50
+ out.pr = Number(e.pr);
51
+ }
52
+ const step = str(e, "step"), cls = str(e, "class"), code = int(e, "exit_code");
53
+ if (step !== undefined) out.step = step;
54
+ if (cls !== undefined) out.class = cls;
55
+ if (code !== undefined) out.exit_code = code;
56
+ if (e.lines !== undefined && e.lines !== null) {
57
+ if (!Array.isArray(e.lines) || !e.lines.every((l) => typeof l === "string")) throw bad("lines", "must be a list of strings");
58
+ if (e.lines.length > MAX_LINES) throw bad("lines", `has more than ${MAX_LINES} entries`, 413);
59
+ if (e.lines.some((l) => l.length > MAX_LINE_CHARS)) throw bad("lines", `has an entry over ${MAX_LINE_CHARS} chars`, 413);
60
+ out.lines = e.lines;
61
+ }
62
+ if (e.test !== undefined && e.test !== null) {
63
+ const t = e.test;
64
+ if (typeof t !== "object" || Array.isArray(t)) throw bad("test", "must be an object");
65
+ const tid = str(t, "id", true), file = str(t, "file"), line = int(t, "line"), message = t.message;
66
+ if (message !== undefined && (typeof message !== "string" || message.length > 4 * MAX_STR)) throw bad("test.message", "must be a string of at most 2000 chars");
67
+ out.test = { id: tid, ...(file !== undefined ? { file } : {}), ...(line !== undefined ? { line } : {}), ...(message !== undefined ? { message } : {}) };
68
+ }
69
+ return out;
70
+ }
71
+
72
+ /** Fixed-capacity circular buffer: pushing past the cap overwrites the oldest entry without shifting. */
73
+ class Ring {
74
+ constructor(cap) { this.cap = cap; this.a = new Array(cap); this.start = 0; this.len = 0; }
75
+ push(v) {
76
+ if (this.len < this.cap) this.a[(this.start + this.len++) % this.cap] = v;
77
+ else { this.a[this.start] = v; this.start = (this.start + 1) % this.cap; }
78
+ }
79
+ dropWhile(pred) { while (this.len && pred(this.a[this.start])) { this.a[this.start] = undefined; this.start = (this.start + 1) % this.cap; this.len--; } }
80
+ *[Symbol.iterator]() { for (let i = 0; i < this.len; i++) yield this.a[(this.start + i) % this.cap]; }
81
+ }
82
+
83
+ const repoKey = (repo) => `${repo.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80)}-${createHash("sha1").update(repo).digest("hex").slice(0, 8)}`;
84
+ const dayOf = (ms) => new Date(ms).toISOString().slice(0, 10);
85
+
86
+ /**
87
+ * Event store. Memory: a ring per (repo, sha), 2000 events, 24 h TTL. Disk: `<dir>/<repo-key>.ndjson`, rotated to
88
+ * `<repo-key>.<YYYY-MM-DD>.ndjson` when the UTC day changes; the last 24 h are reloaded on creation and `seq` resumes.
89
+ */
90
+ /** `classify(event, flakes)` fills `class` on failures that lack one; `flakes()` returns the ledger list (default none). Neither cancels anything. */
91
+ export function createCiEvents({ dir, now = () => Date.now(), cap = RING_CAP, ttlMs = TTL_MS, classify = classifyCiFailure, flakes = () => [] } = {}) {
92
+ const rings = new Map(); // `${repo}\n${sha}` -> Ring
93
+ const fileDay = new Map(); // repo-key -> UTC day of its active file's last write
94
+ const waiters = new Set();
95
+ let seq = 0, lastSweep = now();
96
+
97
+ const keep = (e, t) => t - e.received_at < ttlMs;
98
+ const put = (e) => {
99
+ const k = `${e.repo}\n${e.sha}`;
100
+ let r = rings.get(k);
101
+ if (!r) rings.set(k, (r = new Ring(cap)));
102
+ r.push(e);
103
+ };
104
+ const sweep = (t) => {
105
+ lastSweep = t;
106
+ for (const [k, r] of rings) { r.dropWhile((e) => !keep(e, t)); if (!r.len) rings.delete(k); }
107
+ };
108
+
109
+ function load() {
110
+ if (!dir || !existsSync(dir)) return;
111
+ const t = now(), all = [];
112
+ for (const f of readdirSync(dir)) {
113
+ if (!f.endsWith(".ndjson")) continue;
114
+ const p = join(dir, f);
115
+ try { if (t - statSync(p).mtimeMs > ttlMs + DAY_MS) continue; } catch { continue; }
116
+ for (const line of readFileSync(p, "utf8").split("\n")) {
117
+ if (!line) continue;
118
+ try { const e = JSON.parse(line); if (Number.isFinite(e.seq) && Number.isFinite(e.received_at)) all.push(e); } catch { /* torn line */ }
119
+ }
120
+ }
121
+ all.sort((a, b) => a.seq - b.seq);
122
+ for (const e of all) { seq = Math.max(seq, e.seq); if (keep(e, t)) put(e); }
123
+ }
124
+
125
+ function persist(batch) {
126
+ if (!dir) return;
127
+ mkdirSync(dir, { recursive: true });
128
+ const t = now(), today = dayOf(t), byFile = new Map();
129
+ for (const e of batch) { const k = repoKey(e.repo); (byFile.get(k) ?? byFile.set(k, []).get(k)).push(e); }
130
+ for (const [k, es] of byFile) {
131
+ const file = join(dir, `${k}.ndjson`);
132
+ let day = fileDay.get(k);
133
+ if (!day && existsSync(file)) day = dayOf(statSync(file).mtimeMs);
134
+ if (day && day !== today && existsSync(file)) renameSync(file, join(dir, `${k}.${day}.ndjson`));
135
+ fileDay.set(k, today);
136
+ appendFileSync(file, es.map((e) => JSON.stringify(e)).join("\n") + "\n", { mode: 0o600 });
137
+ }
138
+ if (byFile.size) for (const f of readdirSync(dir)) { // drop rotated files whose whole day is past the TTL
139
+ const m = /\.(\d{4}-\d{2}-\d{2})\.ndjson$/.exec(f);
140
+ if (m && t - Date.parse(`${m[1]}T00:00:00Z`) > ttlMs + DAY_MS) try { unlinkSync(join(dir, f)); } catch { /* raced */ }
141
+ }
142
+ }
143
+
144
+ const matches = (e, q) => e.repo === q.repo && (q.sha === undefined || e.sha === q.sha) && (q.pr === undefined || e.pr === q.pr);
145
+
146
+ /** Events of `q` ({repo, sha?, pr?}) with seq > since, oldest first; `next` is the cursor to resume from. */
147
+ function query(q, since = 0) {
148
+ const t = now();
149
+ if (t - lastSweep > 60000) sweep(t);
150
+ const out = [];
151
+ if (q.sha !== undefined) { const r = rings.get(`${q.repo}\n${q.sha}`); if (r) for (const e of r) if (e.seq > since && keep(e, t) && matches(e, q)) out.push(e); }
152
+ else for (const [k, r] of rings) if (k.startsWith(`${q.repo}\n`)) for (const e of r) if (e.seq > since && keep(e, t) && matches(e, q)) out.push(e);
153
+ out.sort((a, b) => a.seq - b.seq);
154
+ return { events: out, next: out.length ? out[out.length - 1].seq : Math.max(since, seq) };
155
+ }
156
+
157
+ const safeFlakes = () => { try { return flakes() ?? []; } catch { return []; } };
158
+ const withClass = (e, fl) => {
159
+ if (!classify || e.class !== undefined || (!e.lines?.length && !e.test) || (e.type !== "step_failed" && e.type !== "test_failed")) return e;
160
+ try { const c = classify({ step: e.step, lines: e.lines, test: e.test, flakes: fl }); return c?.class ? { ...e, class: c.class } : e; } catch { return e; }
161
+ };
162
+
163
+ /** Validates the whole list first (nothing is stored when one event is bad), then stamps `received_at` and `seq`. */
164
+ function ingest(input) {
165
+ const list = Array.isArray(input) ? input : [input];
166
+ if (!list.length) throw Object.assign(new Error("invalid event: body is empty"), { status: 400 });
167
+ if (list.length > MAX_BATCH) throw Object.assign(new Error(`too many events (max ${MAX_BATCH})`), { status: 413 });
168
+ const clean = list.map((e, i) => { try { return validateEvent(e); } catch (err) { if (list.length > 1) err.message = `${err.message} (event ${i})`; throw err; } });
169
+ const t = now(), fl = classify ? safeFlakes() : [];
170
+ const stamped = clean.map((e) => ({ ...withClass(e, fl), seq: ++seq, received_at: t }));
171
+ persist(stamped);
172
+ for (const e of stamped) put(e);
173
+ for (const w of [...waiters]) { const r = query(w.q, w.since); if (r.events.length) { waiters.delete(w); clearTimeout(w.timer); w.resolve(r); } }
174
+ return { accepted: stamped.length, seq };
175
+ }
176
+
177
+ /** Long-poll: resolves at once when events exist, else on the next matching ingest or after `waitS` seconds (max 60). */
178
+ function wait(q, since = 0, waitS = 0) {
179
+ const r = query(q, since), ms = Math.min(Math.max(Number(waitS) || 0, 0), MAX_WAIT_S) * 1000;
180
+ if (r.events.length || !ms) return Promise.resolve(r);
181
+ return new Promise((resolve) => {
182
+ const w = { q, since, resolve, timer: setTimeout(() => { waiters.delete(w); resolve(query(q, since)); }, ms) };
183
+ waiters.add(w);
184
+ });
185
+ }
186
+
187
+ load();
188
+ return { ingest, query, wait, get seq() { return seq; }, size: () => [...rings.values()].reduce((n, r) => n + r.len, 0) };
189
+ }
@@ -0,0 +1,143 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { test } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { appendFileSync, readdirSync, readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { CI_EVENT_TYPES, createCiEvents, validateEvent } from "./ci-events.mjs";
8
+ import { tmpDir } from "../tests/_tmp.mjs";
9
+
10
+ const ev = (type, extra = {}) => ({ type, repo: "o/r", sha: "abc", run_id: 7, job: "unit", ts: "2026-11-15T00:00:00Z", ...extra });
11
+ const fail = (status, key) => (e) => e.status === status && (key ? e.message.includes(key) : true);
12
+
13
+ test("all 6 event types validate; optional keys are kept", () => {
14
+ for (const t of CI_EVENT_TYPES) assert.equal(validateEvent(ev(t)).type, t);
15
+ const e = validateEvent(ev("test_failed", { pr: 12, step: "s", exit_code: 1, class: "code", lines: ["a"], test: { id: "t1", file: "f.py", line: 3, message: "boom" }, junk: 1 }));
16
+ assert.deepEqual([e.pr, e.step, e.exit_code, e.class, e.lines, e.test.id, e.junk], [12, "s", 1, "code", ["a"], "t1", undefined]);
17
+ });
18
+
19
+ test("missing repo/sha/ts/run_id/job and an unknown type are 400 naming the key", () => {
20
+ for (const k of ["repo", "sha", "ts", "run_id", "job"]) { const e = ev("step_failed"); delete e[k]; assert.throws(() => validateEvent(e), fail(400, k)); }
21
+ assert.throws(() => validateEvent(ev("nope")), fail(400, "type"));
22
+ assert.throws(() => validateEvent(ev("step_failed", { pr: "x" })), fail(400, "pr"));
23
+ assert.throws(() => validateEvent(ev("step_failed", { exit_code: "1" })), fail(400, "exit_code"));
24
+ assert.throws(() => validateEvent(null), fail(400));
25
+ });
26
+
27
+ test("more than 40 lines, a line over 500 chars, or more than 200 events is 413", () => {
28
+ assert.throws(() => validateEvent(ev("step_failed", { lines: Array(41).fill("x") })), fail(413, "lines"));
29
+ assert.equal(validateEvent(ev("step_failed", { lines: Array(40).fill("x".repeat(500)) })).lines.length, 40);
30
+ assert.throws(() => validateEvent(ev("step_failed", { lines: ["x".repeat(501)] })), fail(413, "lines"));
31
+ const s = createCiEvents({});
32
+ assert.throws(() => s.ingest(Array(201).fill(ev("job_started"))), fail(413));
33
+ assert.equal(s.ingest(Array(200).fill(ev("job_started"))).accepted, 200);
34
+ });
35
+
36
+ test("a bad event rejects the whole array and stores nothing", () => {
37
+ const s = createCiEvents({});
38
+ assert.throws(() => s.ingest([ev("job_started"), ev("step_failed", { sha: undefined })]), fail(400, "sha"));
39
+ assert.equal(s.size(), 0);
40
+ assert.equal(s.seq, 0);
41
+ });
42
+
43
+ test("seq is monotonic; sha and pr filters and since work", () => {
44
+ const s = createCiEvents({});
45
+ s.ingest([ev("job_started"), ev("step_failed", { sha: "def", pr: 5 }), ev("step_failed", { pr: 5 })]);
46
+ const all = s.query({ repo: "o/r", sha: "abc" });
47
+ assert.deepEqual(all.events.map((e) => e.seq), [1, 3]);
48
+ assert.equal(all.next, 3);
49
+ assert.deepEqual(s.query({ repo: "o/r", pr: 5 }).events.map((e) => e.sha), ["def", "abc"]);
50
+ assert.equal(s.query({ repo: "o/r", sha: "abc" }, 1).events.length, 1);
51
+ const none = s.query({ repo: "o/r", sha: "abc" }, 3);
52
+ assert.deepEqual([none.events.length, none.next], [0, 3]);
53
+ assert.equal(s.query({ repo: "other", sha: "abc" }).events.length, 0);
54
+ });
55
+
56
+ test("ring cap keeps the newest events; TTL expires old ones", () => {
57
+ let t = 1_000_000;
58
+ const s = createCiEvents({ cap: 5, ttlMs: 1000, now: () => t });
59
+ for (let i = 0; i < 8; i++) s.ingest(ev("step_started", { step: `s${i}` }));
60
+ assert.deepEqual(s.query({ repo: "o/r", sha: "abc" }).events.map((e) => e.step), ["s3", "s4", "s5", "s6", "s7"]);
61
+ t += 1500;
62
+ assert.equal(s.query({ repo: "o/r", sha: "abc" }).events.length, 0);
63
+ t += 61000;
64
+ s.query({ repo: "o/r", sha: "abc" });
65
+ assert.equal(s.size(), 0);
66
+ });
67
+
68
+ test("NDJSON is written, rotates on a new UTC day, and a restart reloads and resumes seq", () => {
69
+ const dir = tmpDir("ci-ev-");
70
+ let t = Date.parse("2026-11-15T10:00:00Z");
71
+ const a = createCiEvents({ dir, now: () => t });
72
+ a.ingest([ev("job_started"), ev("step_failed")]);
73
+ const [f] = readdirSync(dir);
74
+ assert.match(f, /^o_r-[0-9a-f]{8}\.ndjson$/);
75
+ assert.equal(readFileSync(join(dir, f), "utf8").trim().split("\n").length, 2);
76
+ t = Date.parse("2026-11-16T01:00:00Z");
77
+ a.ingest(ev("job_finished"));
78
+ assert.ok(readdirSync(dir).some((n) => /\.2026-11-15\.ndjson$/.test(n)), "yesterday's file rotated");
79
+ assert.equal(readFileSync(join(dir, f), "utf8").trim().split("\n").length, 1);
80
+ t += 3600000;
81
+ const b = createCiEvents({ dir, now: () => t });
82
+ assert.equal(b.seq, 3);
83
+ assert.deepEqual(b.query({ repo: "o/r", sha: "abc" }, 1).events.map((e) => e.type), ["step_failed", "job_finished"]);
84
+ assert.equal(b.ingest(ev("job_started")).seq, 4);
85
+ t += 25 * 3600000; // past the TTL
86
+ assert.equal(createCiEvents({ dir, now: () => t }).size(), 0);
87
+ });
88
+
89
+ test("a restart ignores a torn trailing line", () => {
90
+ const dir = tmpDir("ci-ev-");
91
+ createCiEvents({ dir }).ingest(ev("job_started"));
92
+ appendFileSync(join(dir, readdirSync(dir)[0]), '{"seq":2,"rec');
93
+ const b = createCiEvents({ dir });
94
+ assert.deepEqual([b.size(), b.seq], [1, 1]);
95
+ });
96
+
97
+ test("long-poll wakes within 200 ms of a matching POST and ignores non-matching ones", async () => {
98
+ const s = createCiEvents({});
99
+ const t0 = performance.now();
100
+ const p = s.wait({ repo: "o/r", sha: "abc" }, 0, 30);
101
+ setTimeout(() => { s.ingest(ev("step_failed", { sha: "zzz" })); s.ingest(ev("step_failed")); }, 20);
102
+ const r = await p;
103
+ assert.ok(performance.now() - t0 < 200);
104
+ assert.deepEqual([r.events.length, r.events[0].sha, r.next], [1, "abc", 2]);
105
+ const empty = await s.wait({ repo: "o/r", sha: "abc" }, 2, 0.05);
106
+ assert.deepEqual([empty.events.length, empty.next], [0, 2]);
107
+ assert.equal((await s.wait({ repo: "o/r", sha: "abc" }, 0, 30)).events.length, 1, "existing events return at once");
108
+ });
109
+
110
+ test("bench: 10000 events ingest at 2000+/s with under 50 MB RSS growth", () => {
111
+ const s = createCiEvents({ dir: tmpDir("ci-ev-") });
112
+ const batch = (i) => Array.from({ length: 200 }, (_, j) => ev("test_failed", { sha: `sha${(i + j) % 5}`, lines: ["AssertionError: x".repeat(4)], test: { id: `t${i}-${j}`, file: "a.py", line: 1, message: "m" } }));
113
+ const rss0 = process.memoryUsage().rss, t0 = performance.now();
114
+ for (let i = 0; i < 50; i++) s.ingest(batch(i));
115
+ const secs = (performance.now() - t0) / 1000, rate = 10000 / secs, grow = (process.memoryUsage().rss - rss0) / 1048576;
116
+ console.log(`# ci-events bench: ${rate.toFixed(0)} events/s, rss +${grow.toFixed(1)} MB`);
117
+ assert.equal(s.seq, 10000);
118
+ assert.ok(rate >= 2000, `${rate} events/s`);
119
+ assert.ok(grow < 50, `rss +${grow} MB`);
120
+ });
121
+
122
+ test("ingest classifies step_failed/test_failed without a class (#5690)", () => {
123
+ const ci = createCiEvents({ dir: tmpDir("ci-class") });
124
+ ci.ingest([
125
+ ev("step_failed", { lines: ["sh: tsc: command not found"] }),
126
+ ev("test_failed", { test: { id: "t1", message: "AssertionError: 1 !== 2" } }),
127
+ ev("step_failed", { lines: ["sh: tsc: command not found"], class: "infra" }),
128
+ ev("step_failed"),
129
+ ev("job_started", { lines: ["sh: tsc: command not found"] }),
130
+ ]);
131
+ const got = ci.query({ repo: "o/r", sha: "abc" }).events;
132
+ assert.deepEqual(got.map((e) => e.class), ["deterministic-setup", "code", "infra", undefined, undefined]);
133
+ });
134
+
135
+ test("ingest uses an injected classifier and flake ledger; a throwing classifier never rejects the batch (#5690)", () => {
136
+ let seen;
137
+ const ci = createCiEvents({ dir: tmpDir("ci-class2"), classify: (x) => { seen = x; return { class: "flaky-suspect" }; }, flakes: () => ["f"] });
138
+ ci.ingest(ev("step_failed", { lines: ["x"] }));
139
+ assert.deepEqual(seen.flakes, ["f"]);
140
+ assert.equal(ci.query({ repo: "o/r", sha: "abc" }).events[0].class, "flaky-suspect");
141
+ const bad = createCiEvents({ dir: tmpDir("ci-class3"), classify: () => { throw new Error("x"); } });
142
+ assert.equal(bad.ingest(ev("step_failed", { lines: ["x"] })).accepted, 1);
143
+ });
@@ -56,6 +56,13 @@ export const dockerCli = {
56
56
  return res;
57
57
  },
58
58
  async build(dir, tag, buildArgs = {}) { return docker(["build", "-q", "-t", tag, ...Object.entries(buildArgs).flatMap(([k, v]) => ["--build-arg", `${k}=${v}`]), dir], { timeoutMs: 45 * 60000 }); },
59
+ /** #5696: removes one lane worktree (/cache/work/<id>) from a cache volume. */
60
+ async removeWorkDir(volume, image, workDir) { await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", 'rm -rf -- "$1"', "sh", workDir], { timeoutMs: 120000 }); },
61
+ /** #5696: removes every /cache/work/* dir of a cache volume except the kept ones (full paths). */
62
+ async pruneWorkDirs(volume, image, keep) {
63
+ const script = 'for d in /cache/work/* /cache/work/.[!.]*; do [ -e "$d" ] || continue; for k in "$@"; do [ "$d" = "$k" ] && continue 2; done; rm -rf -- "$d"; done';
64
+ await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", script, "sh", ...keep], { timeoutMs: 120000 });
65
+ },
59
66
  /** Removes files the root-owned lane container wrote into a bind mount, using the lane image itself. */
60
67
  async wipe(dir, image) { await docker(["run", "--rm", "--network", "none", "-v", `${dir}:/d`, "--entrypoint", "sh", image, "-c", "rm -rf /d/* /d/.[!.]* 2>/dev/null; true"], { timeoutMs: 120000 }); },
61
68
  };
@@ -15,6 +15,7 @@ const apt = (...pkgs) => `RUN apt-get update && apt-get install -y --no-install-
15
15
  export const RECIPES = {
16
16
  "postgresql-client": { versioned: true, steps: (v) => [apt(v ? `postgresql-client-${v}` : "postgresql-client")] },
17
17
  python: { versioned: true, steps: (v) => [apt(v ? `python${v} python${v}-venv` : "python3 python3-venv")] },
18
+ xvfb: { versioned: false, steps: () => [apt("xvfb xauth")] }, // headless X for browser/GUI tests that call xvfb-run
18
19
  playwright: { versioned: true, steps: (v) => [`RUN npx --yes playwright${v ? `@${v}` : ""} install --with-deps chromium`] },
19
20
  // Example of a release-tarball tool; the version is required.
20
21
  promtool: { versioned: true, steps: (v) => [`RUN curl -fsSL https://github.com/prometheus/prometheus/releases/download/v${v ?? "2.54.1"}/prometheus-${v ?? "2.54.1"}.linux-amd64.tar.gz | tar -xz --strip-components=1 -C /usr/local/bin --wildcards '*/promtool'`] },
@@ -8,9 +8,16 @@ import { execFile, spawn } from "node:child_process";
8
8
  import { promisify } from "node:util";
9
9
  import { join } from "node:path";
10
10
  import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
11
+ import { createCiEvents, MAX_WAIT_S } from "./ci-events.mjs";
11
12
  import { jsonStore } from "./store.mjs";
12
13
  import { versionOf } from "./version.mjs";
13
14
 
15
+ /**
16
+ * What the router ships to pool agents (self-update and bootstrap). Every module the agent can load statically from
17
+ * bin/pool/agent.mjs must live under these paths; bin/tests/pool-agent-bundle.test.mjs enforces it.
18
+ */
19
+ export const AGENT_BUNDLE_PATHS = Object.freeze(["package.json", "bin/pool", "pool"]);
20
+
14
21
  const run = promisify(execFile);
15
22
 
16
23
  /** #5274: an agent destroy (docker rm, volume rm, wipe) outlasts the 15s call default; DELETE would 502 while the destroy still succeeded. */
@@ -29,6 +36,17 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
29
36
  const store = jsonStore(join(cfg.state_dir, "router-state.json"), { agents: {}, sandboxes: {} });
30
37
  const agents = () => store.data.agents;
31
38
  const sbx = () => store.data.sandboxes;
39
+ // #5688: CI runner events (POST by a `ci` token or the fd token, GET long-poll by the fd token); state in <state_dir>/ci-events/.
40
+ const ciEvents = createCiEvents({ dir: join(cfg.state_dir, "ci-events"), now });
41
+ const ciOk = (req) => bearerOk(req, cfg.forgedock_token) || (cfg.ci_tokens ?? []).some((t) => bearerOk(req, t));
42
+ const ciQuery = (url) => {
43
+ const repo = url.searchParams.get("repo"), sha = url.searchParams.get("sha"), pr = url.searchParams.get("pr");
44
+ if (!repo || (!sha && !pr)) return { status: 400, body: { error: "repo and one of sha or pr are required" } };
45
+ if (pr && !/^\d{1,9}$/.test(pr)) return { status: 400, body: { error: "pr must be an integer" } };
46
+ const since = Number(url.searchParams.get("since") ?? 0), waitS = Number(url.searchParams.get("wait") ?? 0);
47
+ if (!Number.isInteger(since) || since < 0 || !Number.isFinite(waitS) || waitS < 0 || waitS > MAX_WAIT_S) return { status: 400, body: { error: `since must be a non-negative integer and wait 0-${MAX_WAIT_S}` } };
48
+ return { q: { repo, ...(sha ? { sha } : {}), ...(pr ? { pr: Number(pr) } : {}) }, since, waitS };
49
+ };
32
50
  const lane = { cpus: cfg.lane?.cpus ?? 2, mem_gb: cfg.lane?.mem_gb ?? 3 };
33
51
  const abandonMs = (cfg.abandon_after_s ?? 1800) * 1000;
34
52
  const codes = () => (store.data.codes ??= {});
@@ -293,7 +311,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
293
311
  }
294
312
 
295
313
  function sendBundle(res) {
296
- const tar = spawn("tar", ["-czf", "-", "-C", cfg.repo_root, "package.json", "bin/pool", "pool"]);
314
+ const tar = spawn("tar", ["-czf", "-", "-C", cfg.repo_root, ...AGENT_BUNDLE_PATHS]);
297
315
  res.writeHead(200, { "content-type": "application/gzip" });
298
316
  tar.stdout.pipe(res);
299
317
  tar.on("error", () => res.destroy());
@@ -354,6 +372,11 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
354
372
  return { status: r.status, body: r.data };
355
373
  })],
356
374
  [route("GET", "/version"), fd(async () => ({ status: 200, body: versionOf(cfg.repo_root) }))],
375
+ [route("POST", "/ci/events"), { fn: async (_p, body) => ({ status: 202, body: ciEvents.ingest(body) }), auth: "ci" }], // #5688
376
+ [route("GET", "/ci/events"), fd(async (_p, _b, url) => {
377
+ const c = ciQuery(url);
378
+ return c.q ? { status: 200, body: await ciEvents.wait(c.q, c.since, c.waitS) } : c;
379
+ })],
357
380
  [route("POST", "/enroll"), { fn: async (_p, body) => enroll(body), auth: "none" }],
358
381
  [route("GET", "/bootstrap/install.ps1"), { fn: async (_p, _b, url) => ({ status: 200, body: bootstrapScript(url.searchParams.get("token"), url) }), auth: "enroll" }],
359
382
  [route("GET", "/bootstrap/bundle.tar.gz"), { fn: async () => ({ bundle: true }), auth: "enroll" }],
@@ -374,6 +397,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
374
397
  const p = match(req, url);
375
398
  if (!p) continue;
376
399
  if (r.auth === "forgedock" && !bearerOk(req, cfg.forgedock_token)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
400
+ if (r.auth === "ci" && !ciOk(req)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
377
401
  if (r.auth === "agent" && !agentFor(req)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
378
402
  if (r.auth === "enroll" && !enrollOk(url.searchParams.get("token"))) return send(res, 401, "unauthorized\n");
379
403
  const body = req.method === "POST" ? await readJson(req) : null;
package/bin/pool/warm.mjs CHANGED
@@ -23,7 +23,7 @@ export function makeWarm({ store, sb, own, now, launch, destroy, view, log = con
23
23
  function configure({ spec, cpus, mem_gb, limit = null, n }) {
24
24
  const key = keyOf(spec), want = Math.min(MAX_WARM, Number.isInteger(n) ? n : 0);
25
25
  if (want <= 0) { delete wanted()[key]; store.save(); return { key, n: 0 }; }
26
- wanted()[key] = { n: want, cpus, mem_gb, limit, spec: { image: spec.image ?? null, repo: spec.repo ?? null, cache: spec.cache ?? null, docker: Boolean(spec.docker), ...(spec.lane_tools?.length ? { lane_tools: spec.lane_tools } : {}) } };
26
+ wanted()[key] = { n: want, cpus, mem_gb, limit, spec: { image: spec.image ?? null, repo: spec.repo ?? null, cache: spec.cache ?? null, docker: Boolean(spec.docker), ...(spec.lane_tools?.length ? { lane_tools: spec.lane_tools } : {}), ...(spec.env_snapshots?.enabled ? { env_snapshots: spec.env_snapshots } : {}) } };
27
27
  store.save();
28
28
  return { key, n: want };
29
29
  }