forgedock 1.63.0 → 1.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +88 -12
  4. package/bin/env/cli.mjs +18 -1
  5. package/bin/lean/basered.mjs +56 -11
  6. package/bin/lean/basered.test.mjs +58 -5
  7. package/bin/lean/batch-health.mjs +46 -4
  8. package/bin/lean/batch-health.test.mjs +55 -1
  9. package/bin/lean/batch.mjs +6 -1
  10. package/bin/lean/batch.test.mjs +71 -6
  11. package/bin/lean/ceiling.mjs +47 -3
  12. package/bin/lean/ceiling.test.mjs +32 -1
  13. package/bin/lean/conformance.e2e.test.mjs +32 -6
  14. package/bin/lean/conformance.mjs +57 -13
  15. package/bin/lean/conformance.test.mjs +93 -1
  16. package/bin/lean/execution.mjs +15 -6
  17. package/bin/lean/execution.test.mjs +44 -3
  18. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  19. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  20. package/bin/lean/issuewatch.mjs +3 -0
  21. package/bin/lean/lanecheck.test.mjs +13 -1
  22. package/bin/lean/lean.mjs +157 -28
  23. package/bin/lean/lean.test.mjs +289 -21
  24. package/bin/lean/live-execution.mjs +25 -0
  25. package/bin/lean/live-execution.test.mjs +35 -1
  26. package/bin/lean/merged-park.mjs +76 -0
  27. package/bin/lean/merged-park.test.mjs +64 -0
  28. package/bin/lean/mergetrain.mjs +357 -0
  29. package/bin/lean/mergetrain.test.mjs +348 -0
  30. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  31. package/bin/lean/orchestrate-stacking.test.mjs +23 -1
  32. package/bin/lean/orchestrate-train.test.mjs +130 -0
  33. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  34. package/bin/lean/orchestrate.mjs +159 -13
  35. package/bin/lean/prompts.mjs +4 -3
  36. package/bin/lean/release-review.mjs +8 -1
  37. package/bin/lean/release-review.test.mjs +42 -2
  38. package/bin/lean/release-status.test.mjs +53 -1
  39. package/bin/lean/release.mjs +6 -3
  40. package/bin/lean/render.mjs +6 -1
  41. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  42. package/bin/lean/sandbox-remote.mjs +12 -2
  43. package/bin/lean/sched.mjs +19 -2
  44. package/bin/lean/sched.test.mjs +33 -1
  45. package/bin/lean/schedd-health.mjs +2 -1
  46. package/bin/lean/schedd-health.test.mjs +7 -0
  47. package/bin/lean/schedd.mjs +55 -7
  48. package/bin/lean/schedd.test.mjs +42 -1
  49. package/bin/lean/stacking.mjs +45 -0
  50. package/bin/lean/stacking.test.mjs +25 -1
  51. package/bin/lean/statuscomment.mjs +14 -8
  52. package/bin/lean/statuscomment.test.mjs +18 -1
  53. package/bin/lean/validate-catalog.mjs +1 -1
  54. package/bin/lean/validate-catalog.test.mjs +3 -0
  55. package/bin/lean/worktree.mjs +8 -3
  56. package/bin/lean/worktree.test.mjs +18 -0
  57. package/bin/pool/agent.mjs +296 -31
  58. package/bin/pool/cli.mjs +120 -6
  59. package/bin/pool/disk.mjs +43 -0
  60. package/bin/pool/docker.mjs +10 -0
  61. package/bin/pool/health.mjs +95 -0
  62. package/bin/pool/router.mjs +274 -27
  63. package/bin/runner.mjs +3 -1
  64. package/bin/stats/chains.mjs +101 -0
  65. package/bin/stats/chains.test.mjs +53 -0
  66. package/bin/stats/efficiency.mjs +7 -6
  67. package/bin/stats/efficiency.test.mjs +48 -7
  68. package/bin/stats/index.mjs +11 -3
  69. package/bin/stats/stats.test.mjs +9 -0
  70. package/docs/CONFIG.md +8 -1
  71. package/docs/OUTCOME-CODES.md +4 -0
  72. package/package.json +1 -1
  73. package/pool/README.md +10 -0
  74. package/pool/image/Dockerfile +2 -1
  75. package/pool/image/entrypoint.sh +6 -6
  76. package/pool/image/mirror.sh +71 -0
  77. package/pool/install/install-agent-linux.sh +57 -5
  78. package/pool/install/install-agent-macos.sh +148 -0
  79. package/pool/install/install-agent.ps1 +11 -0
  80. package/pool/install/install-agent.sh +59 -7
  81. package/pool/install/uninstall-agent-linux.sh +75 -0
  82. package/pool/install/uninstall-agent-macos.sh +60 -0
  83. package/pool/install/uninstall-agent.ps1 +1 -0
  84. package/scripts/transition-label.sh +11 -0
@@ -93,12 +93,44 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
93
93
  if (consume) { c.used = true; store.save(); }
94
94
  return true;
95
95
  }
96
- function issueCode() {
96
+ function issueCode(account) {
97
97
  const code = randomBytes(9).toString("base64url");
98
- codes()[code] = { expires: now() + codeTtlMs, used: false };
98
+ codes()[code] = { expires: now() + codeTtlMs, used: false, ...(account ? { account } : {}) };
99
99
  store.save();
100
100
  return { code, expires_at: new Date(now() + codeTtlMs).toISOString() };
101
101
  }
102
+ // #5886: device-code login. A box asks for a device+user code, the operator approves the user code (binding an account),
103
+ // the box polls /device/token and receives a single-use enroll code that stamps that account on its agent record.
104
+ const devices = () => (store.data.devices ??= {});
105
+ const ACCOUNT_RE = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,63}$/;
106
+ const deviceTtlMs = (cfg.device_ttl_s ?? 600) * 1000, deviceIntervalS = cfg.device_interval_s ?? 5;
107
+ let deviceBurst = { at: 0, n: 0 };
108
+ function deviceStart() {
109
+ if (now() - deviceBurst.at > 60000) deviceBurst = { at: now(), n: 0 };
110
+ if (++deviceBurst.n > (cfg.device_codes_per_min ?? 20) || Object.keys(devices()).length >= 200) return { status: 429, body: { error: "too many device codes" }, retryAfter: 60 };
111
+ const device_code = randomBytes(24).toString("base64url"), user_code = randomBytes(5).toString("hex").toUpperCase().replace(/^(.{4})/, "$1-");
112
+ devices()[device_code] = { user_code, expires: now() + deviceTtlMs, interval: deviceIntervalS, polled: 0 };
113
+ store.save();
114
+ return { status: 200, body: { device_code, user_code, interval: deviceIntervalS, expires_in: Math.floor(deviceTtlMs / 1000) } };
115
+ }
116
+ function deviceApprove(body) {
117
+ const code = String(body?.user_code ?? "").toUpperCase().trim(), account = String(body?.account ?? "default");
118
+ if (!ACCOUNT_RE.test(account)) return { status: 400, body: { error: "account must be 1-64 chars of [A-Za-z0-9._@-]" } };
119
+ const d = Object.values(devices()).find((x) => x.user_code === code && !x.account && x.expires > now());
120
+ if (!d) return { status: 404, body: { error: "unknown, expired or already approved user code" } };
121
+ d.account = account; store.save();
122
+ return { status: 200, body: { ok: true, account } };
123
+ }
124
+ function deviceToken(body) {
125
+ const d = own(devices(), body?.device_code);
126
+ if (!d || d.expires <= now()) { if (d) { delete devices()[body.device_code]; store.save(); } return { status: 400, body: { error: "expired_token" } }; }
127
+ if (d.polled && now() - d.polled < d.interval * 1000) { d.interval += 5; d.polled = now(); return { status: 400, body: { error: "slow_down", interval: d.interval } }; }
128
+ d.polled = now();
129
+ if (!d.account) return { status: 400, body: { error: "authorization_pending", interval: d.interval } };
130
+ delete devices()[body.device_code];
131
+ const { code } = issueCode(d.account);
132
+ return { status: 200, body: { enroll_code: code, account: d.account } };
133
+ }
102
134
  /** The enrolled agent whose token the request carries, or null. */
103
135
  function agentFor(req) {
104
136
  const m = /^Bearer\s+(\S.*)$/i.exec(req.headers.authorization ?? "");
@@ -155,15 +187,68 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
155
187
  log.info?.(`claude login limited: account=${n} agent=${agent} until=${new Date(until).toISOString()}`);
156
188
  return { status: 200, body: { account: n, until: new Date(until).toISOString() } };
157
189
  }
158
- const agentCall = (a, method, path, body, timeoutMs) => call(a.url, method, path, { body, token: a.token, timeoutMs, fetchFn });
190
+ // #5882: outbound-only agents (no url) dial the router: GET /agent/poll long-polls for the next queued request (the poll is also
191
+ // the heartbeat) and POST /agent/reply/:rid answers it. In memory only: a router restart drops queued requests, like relayQ.
192
+ const pollSt = new Map(), pollReplies = new Map(); // agent -> {q, waiter, seen}; rid -> {agent, done}
193
+ const POLL_MAX_WAIT_S = 55, pollOfflineMs = (cfg.poll_offline_s ?? 60) * 1000;
194
+ const pollState = (name) => { let st = pollSt.get(name); if (!st) pollSt.set(name, st = { q: [], waiter: null, seen: 0 }); return st; };
195
+ const pollOnline = (name) => { const st = pollSt.get(name); return Boolean(st && (st.waiter || now() - st.seen <= pollOfflineMs)); };
196
+ function pollCall(a, method, path, body, timeoutMs = 15000) {
197
+ if (!pollOnline(a.name)) return Promise.reject(new Error("agent offline (no recent poll)"));
198
+ return new Promise((resolve, reject) => {
199
+ const st = pollState(a.name), rid = randomBytes(12).toString("hex");
200
+ const timer = setTimeout(() => { pollReplies.delete(rid); st.q = st.q.filter((x) => x.rid !== rid); reject(new Error("agent did not answer in time")); }, timeoutMs);
201
+ pollReplies.set(rid, { agent: a.name, done: (r) => { clearTimeout(timer); resolve(r); } });
202
+ st.q.push({ rid, method, path, ...(body !== undefined ? { body } : {}) });
203
+ st.waiter?.();
204
+ });
205
+ }
206
+ async function agentPoll(req, url) {
207
+ const name = agentFor(req), st = pollState(name);
208
+ const w = Number(url.searchParams.get("wait") ?? 25), waitS = Number.isFinite(w) ? Math.min(Math.max(w, 0), POLL_MAX_WAIT_S) : 25;
209
+ st.waiter?.(); // a newer poll from the same agent supersedes the older one
210
+ st.seen = now();
211
+ if (!st.q.length && waitS > 0) await new Promise((res) => {
212
+ let t = null;
213
+ const done = () => { clearTimeout(t); if (st.waiter === done) st.waiter = null; res(); };
214
+ t = setTimeout(done, waitS * 1000);
215
+ st.waiter = done;
216
+ });
217
+ st.seen = now();
218
+ const item = st.q.shift();
219
+ return item ? { status: 200, body: item } : { status: 204 };
220
+ }
221
+ function agentReply(req, { rid }, body) {
222
+ const r = pollReplies.get(rid);
223
+ if (!r || r.agent !== agentFor(req)) return { status: 404, body: { error: "unknown request" } };
224
+ pollReplies.delete(rid);
225
+ const status = Number.isInteger(body?.status) ? body.status : 502;
226
+ r.done({ status, ok: status >= 200 && status < 300, data: body?.data ?? null, retryAfter: body?.retry_after ?? null });
227
+ return { status: 200, body: { ok: true } };
228
+ }
229
+ const agentCall = (a, method, path, body, timeoutMs) => a.transport === "poll"
230
+ ? pollCall(a, method, path, body, timeoutMs)
231
+ : call(a.url, method, path, { body, token: a.token, timeoutMs, fetchFn });
159
232
 
233
+ /** #5891: host drive figures per agent, plus a warning when the projected time until the drive is full is under disk_warn_hours (2). */
234
+ const diskWarned = new Map();
235
+ function diskReport(c) {
236
+ if (!Number.isFinite(c.host_disk_free_gb)) return {};
237
+ const out = { host_disk_free_gb: c.host_disk_free_gb, ...(Number.isFinite(c.host_disk_growth_gb_per_h) ? { host_disk_growth_gb_per_h: c.host_disk_growth_gb_per_h } : {}) };
238
+ const limit = cfg.disk_warn_hours ?? 2;
239
+ if (Number.isFinite(c.host_disk_full_in_h) && c.host_disk_full_in_h < limit) {
240
+ out.disk_warning = `host drive full in ~${c.host_disk_full_in_h} h at ${c.host_disk_growth_gb_per_h} GB/h (${c.host_disk_free_gb} GB free)`;
241
+ if (now() - (diskWarned.get(c.name) ?? -Infinity) > 600000) { diskWarned.set(c.name, now()); log.warn?.(`${c.name}: ${out.disk_warning}`); }
242
+ }
243
+ return out;
244
+ }
160
245
  async function capacities() {
161
246
  const out = [];
162
247
  for (const [name, a] of Object.entries(agents())) {
163
248
  try {
164
249
  const r = await agentCall(a, "GET", "/capacity", undefined, 5000);
165
- out.push(r.ok ? { name, ok: true, ...r.data } : { name, ok: false, error: `HTTP ${r.status}` });
166
- } catch (e) { out.push({ name, ok: false, error: String(e.message ?? e) }); }
250
+ out.push(r.ok ? { name, ok: true, ...(a.transport ? { transport: a.transport } : {}), ...r.data } : { name, ok: false, error: `HTTP ${r.status}` });
251
+ } catch (e) { out.push({ name, ok: false, ...(a.transport ? { transport: a.transport } : {}), error: String(e.message ?? e) }); }
167
252
  }
168
253
  return out;
169
254
  }
@@ -171,7 +256,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
171
256
  /** Agent liveness for the scheduler (#4547): an agent is online when it answers and is not paused. */
172
257
  async function status() {
173
258
  const caps = await capacities();
174
- const agentsView = caps.map((c) => ({ name: c.name, ok: c.ok, paused: Boolean(c.paused) }));
259
+ const agentsView = caps.map((c) => ({ name: c.name, ok: c.ok, paused: Boolean(c.paused), transport: c.transport ?? "direct", ...diskReport(c) }));
175
260
  return { online: agentsView.filter((a) => a.ok && !a.paused).length, total: agentsView.length, agents: agentsView };
176
261
  }
177
262
 
@@ -195,6 +280,39 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
195
280
  catch (e) { log.warn?.(`forge.yaml for ${spec.repo.slug} unreadable: ${e.message}`); return spec; }
196
281
  }
197
282
 
283
+ // #5735: per-agent lane ceiling across all batches. A lane sandbox is one whose id starts with `fdrsbx-`; other tenants'
284
+ // sandboxes are never counted or refused. Ceiling: the agent state entry's `max_lanes` (`pool limit`), else router.json
285
+ // `agents.<name>.max_lanes`; no valid value = no ceiling. In-flight launches reserve their slot synchronously before the
286
+ // awaited agent call, so concurrent launches cannot overshoot.
287
+ const isLane = (id) => typeof id === "string" && id.startsWith("fdrsbx-");
288
+ const validCeiling = (v) => Number.isInteger(v) && v >= 0;
289
+ function ceilingOf(name) {
290
+ const st = own(agents(), name)?.max_lanes;
291
+ if (validCeiling(st)) return st;
292
+ const c = cfg.agents && Object.hasOwn(cfg.agents, name) ? cfg.agents[name]?.max_lanes : undefined;
293
+ return validCeiling(c) ? c : null;
294
+ }
295
+ const pending = new Map(); // agent -> Set of lane ids reserved by an in-flight launch or claim
296
+ const lanesOn = (name) => {
297
+ const ids = new Set(pending.get(name) ?? []);
298
+ for (const [id, s] of Object.entries(sbx())) if (s?.agent === name && isLane(id)) ids.add(id);
299
+ return ids.size;
300
+ };
301
+ const atCeiling = (name) => { const c = ceilingOf(name); return c !== null && lanesOn(name) >= c; };
302
+ const reserve = (name, id) => { if (!pending.has(name)) pending.set(name, new Set()); pending.get(name).add(id); };
303
+ const release = (name, id) => { const s = pending.get(name); s?.delete(id); if (s && !s.size) pending.delete(name); };
304
+ const laneView = (name) => ({ used: lanesOn(name), ceiling: ceilingOf(name) });
305
+ function setLimit(name, body) {
306
+ const a = own(agents(), name);
307
+ if (!a) return { status: 404, body: { error: "unknown agent" } };
308
+ const v = body?.max_lanes;
309
+ if (v !== null && !validCeiling(v)) return { status: 400, body: { error: "max_lanes must be a non-negative integer or null" } };
310
+ if (v === null) delete a.max_lanes; else a.max_lanes = v;
311
+ store.save();
312
+ log.info?.(`agent ${name} max_lanes ${v === null ? "none" : v}`);
313
+ return { status: 200, body: { name, max_lanes: v, lanes: laneView(name) } };
314
+ }
315
+
198
316
  /** #5053: an agent's 401 reaches the dispatcher through this router; tag it so it is not mistaken for a router auth failure. */
199
317
  const agentBody = (r, name) => (r.status === 401 ? { ...(r.data && typeof r.data === "object" ? r.data : {}), error: "unauthorized", hop: "agent", agent: name, reason: typeof r.data?.reason === "string" ? r.data.reason : "agent auth: router token rejected by agent" } : r.data ?? {});
200
318
  // #5856: placement by priority. Agents that report no reservations/borrowable fields are flat (cpus_free), as before.
@@ -211,6 +329,8 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
211
329
  return cpusFree >= size.cpus && memFree >= size.mem_gb;
212
330
  };
213
331
  const headroom = (c, spec) => (spec?.priority === "borrow" && Number.isFinite(c.cpus_free_unreserved) ? c.cpus_free_unreserved : 0);
332
+ /** #5886: a spec naming an account is placed only on that account's agents; without one, any enrolled agent (as before). */
333
+ const inAccount = (c, spec) => typeof spec?.account !== "string" || own(agents(), c.name)?.account === spec.account;
214
334
  async function launch(spec) {
215
335
  if (typeof spec?.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(spec.id)) return { status: 400, body: { error: "spec.id required ([A-Za-z0-9._-], max 128)" } };
216
336
  const known = own(sbx(), spec.id);
@@ -222,18 +342,26 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
222
342
  delete sbx()[spec.id]; store.save();
223
343
  }
224
344
  const size = sizeFor(spec);
225
- const sized = (await capacities()).filter((c) => c.ok && !c.paused && fitsPriority(c, spec, size));
345
+ const sized = (await capacities()).filter((c) => c.ok && !c.paused && inAccount(c, spec) && fitsPriority(c, spec, size));
226
346
  const diskLow = sized.filter((c) => c.host_disk_low === true).map((c) => c.name); // #5733: never POST to a host whose drive is short
227
- const fits = sized.filter((c) => c.host_disk_low !== true).sort((a, b) => headroom(b, spec) - headroom(a, spec) || b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
347
+ const capped = sized.filter((c) => c.disk_capped === true && c.host_disk_low !== true).map((c) => c.name); // #5884: lane disk at its hard cap
348
+ 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
+ const laneId = isLane(spec.id), laneCapped = []; // #5735: agents skipped because their lane ceiling is reached
228
350
  let busy = null; // the last agent 503 (e.g. lane_tools image building): its body and Retry-After are passed back
229
351
  for (const c of fits) {
230
- const r = await agentCall(own(agents(), c.name), "POST", "/sandboxes", { spec: withForgeYaml(spec), ...size }, 120000);
231
- if (r.status === 503) { busy = { r, name: c.name }; continue; } // raced with another launch, or still building; try the next host
232
- if (r.ok) { sbx()[spec.id] = { agent: c.name, issue: spec.issue ?? null, batch: spec.batch ?? null, createdAt: now(), touched: now() }; store.save(); }
233
- return { status: r.status, body: { ...agentBody(r, c.name), agent: c.name } };
352
+ if (laneId && atCeiling(c.name)) { laneCapped.push({ name: c.name, ...laneView(c.name) }); continue; }
353
+ if (laneId) reserve(c.name, spec.id);
354
+ try {
355
+ const r = await agentCall(own(agents(), c.name), "POST", "/sandboxes", { spec: withForgeYaml(spec), ...size }, 120000);
356
+ if (r.status === 503) { busy = { r, name: c.name }; continue; } // raced with another launch, or still building; try the next host
357
+ if (r.ok) { sbx()[spec.id] = { agent: c.name, issue: spec.issue ?? null, batch: spec.batch ?? null, createdAt: now(), touched: now() }; store.save(); }
358
+ return { status: r.status, body: { ...agentBody(r, c.name), agent: c.name } };
359
+ } finally { if (laneId) release(c.name, spec.id); }
234
360
  }
361
+ if (laneCapped.length && !busy) return { status: 503, body: { error: "pool.host_lane_ceiling", code: "pool.host_lane_ceiling", agents: laneCapped }, retryAfter: cfg.retry_after_s ?? 60 };
235
362
  if (busy) return { status: 503, body: { ...agentBody(busy.r, busy.name), agent: busy.name }, retryAfter: busy.r.retryAfter ?? cfg.retry_after_s ?? 60 };
236
363
  if (diskLow.length) return { status: 503, body: { error: "no host has free disk", code: "pool.disk_low", agents: diskLow }, retryAfter: cfg.disk_low_retry_after_s ?? 300 }; // a capacity deferral, not a failure
364
+ if (capped.length) return { status: 503, body: { error: "no host has lane disk below its cap", code: "pool.disk_cap", agents: capped }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
237
365
  return { status: 503, body: { error: "no host has a free reservation", lane: size }, retryAfter: cfg.retry_after_s ?? 60 };
238
366
  }
239
367
 
@@ -242,12 +370,17 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
242
370
  if (typeof spec?.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(spec.id)) return { status: 400, body: { error: "spec.id required ([A-Za-z0-9._-], max 128)" } };
243
371
  if (own(sbx(), spec.id)) return launch(spec); // already placed: the same idempotent path
244
372
  const size = sizeFor(spec);
245
- for (const c of (await capacities()).filter((x) => x.ok && !x.paused)) {
246
- const r = await agentCall(own(agents(), c.name), "POST", "/warm/claim", { spec: withForgeYaml(spec), ...size }, 30000);
247
- if (!r.ok) continue;
248
- sbx()[spec.id] = { agent: c.name, issue: spec.issue ?? null, batch: spec.batch ?? null, createdAt: now(), touched: now() };
249
- store.save();
250
- return { status: 200, body: { ...(r.data ?? {}), agent: c.name } };
373
+ const laneId = isLane(spec.id);
374
+ for (const c of (await capacities()).filter((x) => x.ok && !x.paused && inAccount(x, spec))) {
375
+ if (laneId && atCeiling(c.name)) continue; // #5735: the 404 makes the caller cold-launch, which gets the ceiling 503
376
+ if (laneId) reserve(c.name, spec.id);
377
+ try {
378
+ const r = await agentCall(own(agents(), c.name), "POST", "/warm/claim", { spec: withForgeYaml(spec), ...size }, 30000);
379
+ if (!r.ok) continue;
380
+ sbx()[spec.id] = { agent: c.name, issue: spec.issue ?? null, batch: spec.batch ?? null, createdAt: now(), touched: now() };
381
+ store.save();
382
+ return { status: 200, body: { ...(r.data ?? {}), agent: c.name } };
383
+ } finally { if (laneId) release(c.name, spec.id); }
251
384
  }
252
385
  return { status: 404, body: { error: "no warm sandbox ready" } };
253
386
  }
@@ -267,6 +400,8 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
267
400
  /** Renew leases for sandboxes ForgeDock still polls; destroy the ones it abandoned. */
268
401
  async function tick() {
269
402
  for (const [k, c] of Object.entries(codes())) if (c.expires <= now()) delete codes()[k];
403
+ for (const [k, d] of Object.entries(devices())) if (d.expires <= now()) delete devices()[k];
404
+ for (const [name, a] of Object.entries(agents())) if (a.policy_pending) await pushPolicy(name); // #5886: re-push a policy the box missed
270
405
  for (const [id, s] of Object.entries(sbx())) {
271
406
  const a = own(agents(), s.agent);
272
407
  if (!a) { delete sbx()[id]; continue; }
@@ -286,17 +421,52 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
286
421
  function enroll(body) {
287
422
  if (!enrollOk(body?.token)) return { status: 401, body: { error: "bad enrollment token", hop: "router", reason: "router auth: bad enrollment token" } };
288
423
  const name = String(body.name ?? "").toLowerCase().replace(/[^a-z0-9-]/g, "");
289
- let url;
290
- try { url = new URL(String(body.url)); } catch { return { status: 400, body: { error: "url required" } }; }
424
+ // #5882: no url means an outbound-only agent that polls this router (no inbound port on its host).
425
+ let url = null;
426
+ if (body.url) { try { url = new URL(String(body.url)); } catch { return { status: 400, body: { error: "url must be a valid URL (or omitted for an outbound agent)" } }; } }
291
427
  if (!name) return { status: 400, body: { error: "name required" } };
428
+ const account = own(codes(), body.token)?.account; // #5886: a device-login code carries its account
292
429
  enrollOk(body.token, true);
293
430
  const token = randomBytes(32).toString("hex");
294
- agents()[name] = { url: url.origin, token, enrolledAt: new Date(now()).toISOString() };
431
+ const keep = own(agents(), name)?.max_lanes; // #5735: re-enrollment keeps a `pool limit` ceiling
432
+ const keepCfg = validCeiling(keep) ? { max_lanes: keep } : {};
433
+ agents()[name] = { ...(url ? { url: url.origin, token, enrolledAt: new Date(now()).toISOString(), ...keepCfg } : { name, transport: "poll", token, enrolledAt: new Date(now()).toISOString(), ...keepCfg }), ...(account ? { account } : {}) };
295
434
  store.save();
296
- log.info?.(`enrolled agent ${name} at ${url.origin}`);
435
+ log.info?.(`enrolled agent ${name} ${url ? `at ${url.origin}` : "(outbound poll)"}`);
297
436
  return { status: 200, body: { name, agent_token: token } };
298
437
  }
299
438
 
439
+ /** #5886: per-box policy, allowlisted keys only; pushed to the agent's /admin/policy (the agent keeps its owner pause). */
440
+ function validPolicy(b) {
441
+ if (!b || typeof b !== "object" || Array.isArray(b)) return "policy must be an object";
442
+ const bad = Object.keys(b).filter((k) => !["cpus", "mem_gb", "idle_only", "paused", "floors"].includes(k));
443
+ if (bad.length) return `unknown policy key: ${bad[0]}`;
444
+ const int = (v, hi) => Number.isInteger(v) && v >= 1 && v <= hi;
445
+ if ("cpus" in b && !int(b.cpus, 256)) return "cpus must be an integer 1-256";
446
+ if ("mem_gb" in b && !int(b.mem_gb, 1024)) return "mem_gb must be an integer 1-1024";
447
+ if (("idle_only" in b && typeof b.idle_only !== "boolean") || ("paused" in b && typeof b.paused !== "boolean")) return "idle_only and paused must be booleans";
448
+ if ("floors" in b && !(b.floors && typeof b.floors === "object" && Object.keys(b.floors).every((k) => k === "host_disk_gb" && Number.isFinite(b.floors[k]) && b.floors[k] >= 0))) return "floors accepts only host_disk_gb >= 0";
449
+ return null;
450
+ }
451
+ async function pushPolicy(name) {
452
+ const a = own(agents(), name);
453
+ try {
454
+ const r = await agentCall(a, "POST", "/admin/policy", a.policy);
455
+ if (r.ok) { delete a.policy_pending; store.save(); }
456
+ return r.ok;
457
+ } catch { return false; }
458
+ }
459
+ async function setPolicy(name, body) {
460
+ const a = own(agents(), name);
461
+ if (!a) return { status: 404, body: { error: "unknown agent" } };
462
+ const err = validPolicy(body);
463
+ if (err) return { status: 400, body: { error: err } };
464
+ a.policy = { ...(a.policy ?? {}), ...body, ...(body.floors ? { floors: { ...(a.policy?.floors ?? {}), ...body.floors } } : {}) };
465
+ a.policy_pending = true; store.save();
466
+ const pushed = await pushPolicy(name);
467
+ return { status: pushed ? 200 : 202, body: { ok: true, policy: a.policy, pushed } };
468
+ }
469
+
300
470
  function bootstrapScript(token, url) {
301
471
  const q = (s) => `'${String(s).replace(/'/g, "''")}'`;
302
472
  const int = (k) => { const v = Number(url?.searchParams.get(k)); return Number.isInteger(v) && v > 0 ? v : 0; };
@@ -316,6 +486,73 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
316
486
  ].join("\r\n");
317
487
  }
318
488
 
489
+ /**
490
+ * #5883: the POSIX sh one-command installer served at GET /install (no auth: it holds no secret, only this router's URL).
491
+ * The one-time code arrives as `--code` and is checked only by /bootstrap/bundle.tar.gz and consumed by /enroll.
492
+ */
493
+ function installScript() {
494
+ const q = (s) => `'${String(s ?? "").replace(/'/g, "'\\''")}'`;
495
+ return `#!/bin/sh
496
+ # computeshare agent one-command installer for Linux (systemd) and macOS (launchd), served by the router (#5883).
497
+ # Install: curl -fsSL ${q(`${cfg.public_url}/install`)} | sudo sh -s -- --code CODE [--name N] [--cpus N] [--mem GB]
498
+ # Uninstall: curl -fsSL ${q(`${cfg.public_url}/install`)} | sudo sh -s -- --uninstall
499
+ # Rerunning is safe: an enrolled host reuses its installed code and agent token (no download, no re-enrollment).
500
+ set -eu
501
+ ROUTER=${q(cfg.public_url)}
502
+ CODE=""; NAME=""; CPUS=""; MEM=""; UNINSTALL=0; DRY=0
503
+ while [ $# -gt 0 ]; do
504
+ case "$1" in
505
+ --code) CODE="\${2:?--code needs a value}"; shift 2 ;;
506
+ --name) NAME="\${2:?--name needs a value}"; shift 2 ;;
507
+ --cpus) CPUS="\${2:?--cpus needs a value}"; shift 2 ;;
508
+ --mem) MEM="\${2:?--mem needs a value}"; shift 2 ;;
509
+ --uninstall) UNINSTALL=1; shift ;;
510
+ --dry-run) DRY=1; shift ;;
511
+ *) echo "unknown argument: $1" >&2; exit 2 ;;
512
+ esac
513
+ done
514
+ case "$(uname -s)" in
515
+ Linux) OS=linux; ROOT=/opt/computeshare; TOKEN_FILE=/etc/computeshare/agent.token ;;
516
+ Darwin) OS=macos; ROOT=/usr/local/computeshare; TOKEN_FILE=/usr/local/etc/computeshare/agent.token ;;
517
+ *) echo "unsupported OS $(uname -s): Linux or macOS only (Windows: forgedock pool enroll prints a PowerShell command)" >&2; exit 1 ;;
518
+ esac
519
+ if [ "$UNINSTALL" = 1 ]; then ACTION=uninstall; elif [ -s "$TOKEN_FILE" ] && [ -f "$ROOT/pool/install/install-agent-$OS.sh" ]; then ACTION=reinstall; else ACTION=install; fi
520
+ if [ "$DRY" = 1 ]; then
521
+ echo "os=$OS action=$ACTION router=$ROUTER root=$ROOT name=\${NAME:-<hostname>} cpus=\${CPUS:-<auto>} mem_gb=\${MEM:-<auto>} code=\${CODE:+<redacted>}"
522
+ exit 0
523
+ fi
524
+ [ "$(id -u)" = 0 ] || { echo "run as root: curl -fsSL '$ROUTER/install' | sudo sh -s -- ..." >&2; exit 1; }
525
+ command -v bash >/dev/null 2>&1 && command -v curl >/dev/null 2>&1 && command -v tar >/dev/null 2>&1 || { echo "needs bash, curl and tar" >&2; exit 1; }
526
+ TMP=""
527
+ cleanup() { [ -z "$TMP" ] || rm -rf "$TMP"; }
528
+ trap cleanup EXIT
529
+ fetch_bundle() {
530
+ TMP="$(mktemp -d "\${TMPDIR:-/tmp}/computeshare-install.XXXXXX")"
531
+ curl -fsS "$ROUTER/bootstrap/bundle.tar.gz?token=$CODE" -o "$TMP/bundle.tar.gz" || { echo "bundle download refused: the code is wrong, used or expired (forgedock pool enroll --outbound prints a new one)" >&2; exit 1; }
532
+ tar -xzf "$TMP/bundle.tar.gz" -C "$TMP"
533
+ }
534
+ if [ "$ACTION" = uninstall ]; then
535
+ if [ -f "$ROOT/pool/install/uninstall-agent-$OS.sh" ]; then bash "$ROOT/pool/install/uninstall-agent-$OS.sh"; exit $?; fi
536
+ if [ -z "$CODE" ]; then echo "[computeshare] $ROOT is not installed here; nothing to uninstall (pass --code to run the full cleanup from a fresh bundle)"; exit 0; fi
537
+ fetch_bundle
538
+ bash "$TMP/pool/install/uninstall-agent-$OS.sh"
539
+ exit $?
540
+ fi
541
+ set -- --router "$ROUTER" --outbound
542
+ if [ -n "$NAME" ]; then set -- "$@" --name "$NAME"; fi
543
+ if [ -n "$CPUS" ]; then set -- "$@" --cpus "$CPUS"; fi
544
+ if [ -n "$MEM" ]; then set -- "$@" --mem "$MEM"; fi
545
+ if [ "$ACTION" = reinstall ]; then
546
+ echo "[computeshare] already enrolled: reusing $ROOT and its agent token (no bundle download, no re-enrollment)"
547
+ bash "$ROOT/pool/install/install-agent-$OS.sh" "$@" --token "\${CODE:-enrolled}"
548
+ exit $?
549
+ fi
550
+ [ -n "$CODE" ] || { echo "--code CODE required (forgedock pool enroll --outbound prints the command)" >&2; exit 2; }
551
+ fetch_bundle
552
+ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TMP/bundle.tar.gz"
553
+ `;
554
+ }
555
+
319
556
  /** Stream an allow-listed image (docker save) to an agent whose daemon cannot reach the registry itself. */
320
557
  async function sendImage(res, ref) {
321
558
  const allowed = cfg.agent_images ?? ["docker:27.5.1-dind"];
@@ -352,17 +589,25 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
352
589
  [route("POST", "/sandboxes/:id/stop"), fd(async ({ id }) => forward(id, "POST", `/sandboxes/${encodeURIComponent(id)}/stop`))], // #5274
353
590
  [route("DELETE", "/sandboxes/:id"), fd(async ({ id }) => forward(id, "DELETE", `/sandboxes/${encodeURIComponent(id)}`, DESTROY_TIMEOUT_MS))],
354
591
  [route("GET", "/status"), fd(async () => ({ status: 200, body: await status() }))],
355
- [route("GET", "/agents"), fd(async () => { // #5535: each sandbox carries disk_used_mb from its agent's sandbox_disk_mb when the agent reports it
356
- const caps = await capacities(), byName = new Map(caps.map((c) => [c.name, c])), out = {};
357
- for (const [id, s] of Object.entries(sbx())) { const mb = byName.get(s?.agent)?.sandbox_disk_mb?.[id]; out[id] = Number.isFinite(mb) ? { ...s, disk_used_mb: mb } : s; }
358
- return { status: 200, body: { agents: caps, sandboxes: out } };
592
+ [route("GET", "/agents"), fd(async (_p, _b, url) => { // #5535: each sandbox carries disk_used_mb from its agent's sandbox_disk_mb when the agent reports it
593
+ const acct = url.searchParams.get("account"); // #5886: ?account= is the per-account view; `account` and `policy` ride on enrolled records that have them
594
+ const caps = (await capacities()).filter((c) => acct === null || own(agents(), c.name)?.account === acct).map((c) => { const a = own(agents(), c.name); return { ...c, ...(a?.account ? { account: a.account } : {}), ...(a?.policy ? { policy: a.policy } : {}) }; }), byName = new Map(caps.map((c) => [c.name, c])), out = {};
595
+ for (const [id, s] of Object.entries(sbx())) { if (acct !== null && !byName.has(s?.agent)) continue; const mb = byName.get(s?.agent)?.sandbox_disk_mb?.[id]; out[id] = Number.isFinite(mb) ? { ...s, disk_used_mb: mb } : s; }
596
+ const remote_lanes = Object.keys(sbx()).filter(isLane).length; // #5735: lane sandboxes across all batches and agents
597
+ return { status: 200, body: { agents: caps.map((c) => ({ ...c, lanes: laneView(c.name), ...diskReport(c) })), sandboxes: out, remote_lanes } };
359
598
  })],
599
+ [route("POST", "/device/code"), { fn: async () => deviceStart(), auth: "none" }], // #5886
600
+ [route("POST", "/device/token"), { fn: async (_p, body) => deviceToken(body), auth: "none" }],
601
+ [route("POST", "/device/approve"), fd(async (_p, body) => deviceApprove(body))],
602
+ [route("PUT", "/agents/:name/policy"), fd(async ({ name }, body) => setPolicy(name, body))],
360
603
  [route("POST", "/codes"), fd(async () => ({ status: 200, body: issueCode() }))],
361
604
  [route("GET", "/agent/creds/github"), { fn: async () => ({ status: 200, body: { token: await githubToken() } }), auth: "agent" }],
362
605
  [route("GET", "/agent/creds/claude"), { fn: async (_p, _b, _u, req) => claudeToken(req), auth: "agent" }],
363
606
  [route("POST", "/agent/creds/claude/limited"), { fn: async (_p, body, _u, req) => claudeLimited(req, body), auth: "agent" }], // #5205
364
607
  [route("POST", "/agent/relay/:id"), { fn: async (p, body, _u, req) => relayPost(req, p, body), auth: "agent" }], // #4778
365
608
  [route("GET", "/agent/relay/:id/:rid"), { fn: async (p, _b, _u, req) => relayPoll(req, p), auth: "agent" }],
609
+ [route("GET", "/agent/poll"), { fn: async (_p, _b, url, req) => agentPoll(req, url), auth: "agent" }], // #5882
610
+ [route("POST", "/agent/reply/:rid"), { fn: async (p, body, _u, req) => agentReply(req, p, body), auth: "agent" }],
366
611
  [route("GET", "/agent/bundle"), { fn: async () => ({ bundle: true }), auth: "agent" }],
367
612
  [route("GET", "/agent/images/:ref"), { fn: async ({ ref }) => ({ image: ref }), auth: "agent" }],
368
613
  [route("POST", "/agents/:name/upgrade"), fd(async ({ name }) => {
@@ -383,6 +628,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
383
628
  const r = await agentCall(a, "POST", "/admin/resize", body ?? {});
384
629
  return { status: r.status, body: r.data };
385
630
  })],
631
+ [route("POST", "/agents/:name/limit"), fd(async ({ name }, body) => setLimit(name, body))], // #5735
386
632
  [route("GET", "/agents/:name/usage"), fd(async ({ name }) => {
387
633
  const a = own(agents(), name);
388
634
  if (!a) return { status: 404, body: { error: "unknown agent" } };
@@ -396,6 +642,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
396
642
  return c.q ? { status: 200, body: await ciEvents.wait(c.q, c.since, c.waitS) } : c;
397
643
  })],
398
644
  [route("POST", "/enroll"), { fn: async (_p, body) => enroll(body), auth: "none" }],
645
+ [route("GET", "/install"), { fn: async () => ({ status: 200, body: installScript() }), auth: "none" }], // #5883: script text only, the code comes as --code
399
646
  [route("GET", "/bootstrap/install.ps1"), { fn: async (_p, _b, url) => ({ status: 200, body: bootstrapScript(url.searchParams.get("token"), url) }), auth: "enroll" }],
400
647
  [route("GET", "/bootstrap/bundle.tar.gz"), { fn: async () => ({ bundle: true }), auth: "enroll" }],
401
648
  ];
@@ -418,7 +665,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
418
665
  if (r.auth === "ci" && !ciOk(req)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
419
666
  if (r.auth === "agent" && !agentFor(req)) return send(res, 401, { error: "unauthorized", hop: "router", reason: "router auth: bad or missing token" });
420
667
  if (r.auth === "enroll" && !enrollOk(url.searchParams.get("token"))) return send(res, 401, "unauthorized\n");
421
- const body = req.method === "POST" ? await readJson(req) : null;
668
+ const body = req.method === "POST" || req.method === "PUT" ? await readJson(req) : null;
422
669
  if (typeof body?.repo?.slug === "string") meta.repo = body.repo.slug.slice(0, 200);
423
670
  if (typeof body?.id === "string") meta.id = body.id;
424
671
  const out = await r.fn(p, body, url, req);
package/bin/runner.mjs CHANGED
@@ -2150,6 +2150,7 @@ export async function runCliBackendAsync(opts) {
2150
2150
  let limitInfo = null;
2151
2151
  const ceiling = maxMs > 0 ? maxMs : o.timeout;
2152
2152
  let collected, idleInfo = null, ctxInfo = null, turnInfo = null;
2153
+ let streamSessionId = null;
2153
2154
  const msgUsage = new Map(); // #4390: assistant message id -> its usage (a message spans several stream lines)
2154
2155
  const toolUses = new Map(); // #4410: tool_use id -> {msg, name, path, cmd}
2155
2156
  const sum = (k) => [...msgUsage.values()].reduce((a, u) => a + toFiniteUsageNumber(u[k]), 0);
@@ -2214,6 +2215,7 @@ export async function runCliBackendAsync(opts) {
2214
2215
  const noteLine = (line) => {
2215
2216
  if (!line.startsWith("{") || line.length > 4_000_000) return;
2216
2217
  let j; try { j = JSON.parse(line); } catch { return; }
2218
+ if (typeof j?.session_id === "string" && j.session_id) streamSessionId = j.session_id; // #5829: a context stop names the session so it can be compacted
2217
2219
  if (j?.type === "result") resultLine = line;
2218
2220
  else if (j?.type === "user" && Array.isArray(j.message?.content)) {
2219
2221
  // #5346: a tool_result closes its edit; a ceiling crossed mid-edit stops the session at this safe point
@@ -2271,7 +2273,7 @@ export async function runCliBackendAsync(opts) {
2271
2273
  }
2272
2274
  if (ctxInfo) {
2273
2275
  const err = new Error(`claude CLI session reached ${ctxInfo.context} context tokens (ceiling ${contextMax}) after ${msgUsage.size} turn(s) and was stopped`);
2274
- err.code = "CLI_CONTEXT"; err.context = ctxInfo.context; err.contextMax = contextMax; err.turns = msgUsage.size; err.lastTool = ctxInfo.lastTool;
2276
+ err.code = "CLI_CONTEXT"; err.sessionId = streamSessionId; err.context = ctxInfo.context; err.contextMax = contextMax; err.turns = msgUsage.size; err.lastTool = ctxInfo.lastTool;
2275
2277
  err.usage = streamUsage(); err.toolUses = [...toolUses.values()];
2276
2278
  throw err;
2277
2279
  }
@@ -0,0 +1,101 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5834: stacked-lane chain metrics for `forgedock stats --chains`, from the repo's local batch report.json rows (`deps`,
5
+ * `admitted_at`, `ended_at`, `plan_minutes`, `stacked`, `cascade*`). No network, no model. A chain is a connected set of
6
+ * in-batch dependency edges; depth is its longest path in issues; wall time runs from the first admission to the last end.
7
+ */
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { listBatches } from "../lean/batch.mjs";
11
+ import { sameRepo, windowLabel } from "./efficiency.mjs";
12
+
13
+ const readJson = (f) => { try { return JSON.parse(readFileSync(f, "utf8")); } catch { return null; } };
14
+ const round1 = (x) => Math.round(x * 10) / 10;
15
+ const MIN = 60000;
16
+ const p50 = (xs) => { if (!xs.length) return null; const s = [...xs].sort((a, b) => a - b), m = s.length >> 1; return round1(s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2); };
17
+
18
+ const byDepth = (chains) => {
19
+ const depths = {};
20
+ for (const c of chains) (depths[c.depth] ??= []).push(c.wall_min);
21
+ return Object.fromEntries(Object.entries(depths).map(([d, w]) => [d, { chains: w.length, wall_p50_min: p50(w) }]));
22
+ };
23
+
24
+ /** Cascade rework over the stacked dependents among `rows`: share that cascaded, cascades each, and rework minutes and cost. */
25
+ export function cascadeMetrics(rows) {
26
+ const stacked = (rows ?? []).filter((r) => r?.stacked);
27
+ const cascaded = stacked.filter((r) => r.cascade);
28
+ const count = cascaded.reduce((s, r) => s + (Array.isArray(r.cascades) ? r.cascades.length : 1), 0);
29
+ return {
30
+ stacked: stacked.length, cascaded: cascaded.length, cascades: count,
31
+ rework_rate: stacked.length ? Math.round((cascaded.length / stacked.length) * 1000) / 1000 : null,
32
+ per_stacked: stacked.length ? Math.round((count / stacked.length) * 100) / 100 : null,
33
+ cost_usd: Math.round(cascaded.reduce((s, r) => s + (Number(r.cascade_cost_usd) || 0), 0) * 1e6) / 1e6,
34
+ minutes: round1(cascaded.reduce((s, r) => s + (Number(r.cascade_minutes) || 0), 0)),
35
+ };
36
+ }
37
+
38
+ /** Chains, per-depth wall p50 and cascade rework from final rows (latest row per issue). Rows without timestamps are skipped. */
39
+ export function chainMetrics(rows) {
40
+ const by = new Map();
41
+ for (const r of rows ?? []) if (Number.isSafeInteger(r?.issue) && Number.isFinite(r.admitted_at) && Number.isFinite(r.ended_at)) by.set(r.issue, r);
42
+ const edges = (n) => (by.get(n)?.deps ?? []).filter((d) => by.has(d) && d !== n);
43
+ const parent = new Map([...by.keys()].map((n) => [n, n]));
44
+ const find = (n) => { while (parent.get(n) !== n) { parent.set(n, parent.get(parent.get(n))); n = parent.get(n); } return n; };
45
+ for (const n of by.keys()) for (const d of edges(n)) parent.set(find(n), find(d));
46
+ const groups = new Map();
47
+ for (const n of by.keys()) { const g = find(n); (groups.get(g) ?? groups.set(g, []).get(g)).push(n); }
48
+ const depthMemo = new Map();
49
+ const depthOf = (n, seen = new Set()) => {
50
+ if (depthMemo.has(n)) return depthMemo.get(n);
51
+ if (seen.has(n)) return 1; // a cycle cannot extend a chain
52
+ seen.add(n);
53
+ const d = 1 + Math.max(0, ...edges(n).map((e) => depthOf(e, seen)));
54
+ seen.delete(n); depthMemo.set(n, d); return d;
55
+ };
56
+ const chains = [];
57
+ for (const members of groups.values()) {
58
+ if (members.length < 2) continue;
59
+ members.sort((a, b) => a - b);
60
+ const start = Math.min(...members.map((n) => by.get(n).admitted_at)), end = Math.max(...members.map((n) => by.get(n).ended_at));
61
+ const links = [];
62
+ for (const n of members) for (const d of edges(n)) {
63
+ const a = by.get(n), p = by.get(d);
64
+ links.push({ issue: n, dependency: d, overlap_min: round1(Math.max(0, Math.min(a.ended_at, p.ended_at) - a.admitted_at) / MIN) });
65
+ }
66
+ chains.push({ issues: members, depth: Math.max(...members.map((n) => depthOf(n))), wall_min: round1((end - start) / MIN), links });
67
+ }
68
+ return { chains, by_depth: byDepth(chains), cascade: cascadeMetrics(rows) };
69
+ }
70
+
71
+ /** Per window: the repo's batches created in it; an issue in several batches counts once (latest row). */
72
+ export function chainsReport({ batchRoot, repo = null, windows, now = Date.now() }) {
73
+ const batches = (existsSync(batchRoot) ? listBatches(batchRoot) : []).map((id) => {
74
+ const dir = join(batchRoot, id), plan = readJson(join(dir, "plan.json")) ?? {};
75
+ return { dir, plan, created: Date.parse(plan.created ?? "") };
76
+ }).filter((b) => Number.isFinite(b.created) && (!repo || sameRepo(b.plan.repo, repo))).sort((a, b) => a.created - b.created);
77
+ const out = {};
78
+ for (const w of windows) {
79
+ const inWin = batches.filter((b) => b.created <= now && now - b.created <= w);
80
+ const chains = [], rows = [];
81
+ for (const b of inWin) { // chains stay within one batch: edges are in-batch; cascade rates pool every batch's rows
82
+ const r = readJson(join(b.dir, "report.json"))?.rows ?? [];
83
+ chains.push(...chainMetrics(r).chains); rows.push(...r);
84
+ }
85
+ out[windowLabel(w)] = { batches: inWin.length, chains: chains.length, by_depth: byDepth(chains), cascade: cascadeMetrics(rows), detail: chains };
86
+ }
87
+ return out;
88
+ }
89
+
90
+ export function formatChainLines(windows) {
91
+ return Object.entries(windows).flatMap(([w, m]) => {
92
+ const head = `chains ${w}: ${m.batches} batch${m.batches === 1 ? "" : "es"}, ${m.chains} chain${m.chains === 1 ? "" : "s"}`;
93
+ const depth = Object.entries(m.by_depth).sort((a, b) => Number(a[0]) - Number(b[0]))
94
+ .map(([d, e]) => ` depth ${d}: ${e.chains} chain${e.chains === 1 ? "" : "s"}, wall p50 ${e.wall_p50_min.toFixed(1)} min`);
95
+ const overlap = m.detail.flatMap((c) => c.links).map((l) => l.overlap_min);
96
+ const c = m.cascade;
97
+ return [head, ...(depth.length ? depth : [" chain wall p50: n/a"]),
98
+ ` link overlap p50: ${overlap.length ? `${p50(overlap).toFixed(1)} min` : "n/a"}`,
99
+ ` cascade rework: ${c.rework_rate == null ? "n/a" : `${Math.round(c.rework_rate * 100)}% of ${c.stacked} stacked dependent${c.stacked === 1 ? "" : "s"}, ${c.per_stacked} cascades each, ${c.minutes.toFixed(1)} min, $${c.cost_usd}`}`];
100
+ });
101
+ }
@@ -0,0 +1,53 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { mkdirSync, writeFileSync } from "node:fs";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { join } from "node:path";
8
+ import { chainMetrics, cascadeMetrics, chainsReport, formatChainLines } from "./chains.mjs";
9
+
10
+ const M = 60000;
11
+ const row = (issue, a, e, extra = {}) => ({ issue, admitted_at: a * M, ended_at: e * M, outcome: "merged", ...extra });
12
+
13
+ describe("chain metrics (#5834)", () => {
14
+ it("depth, wall time and per-link overlap for a depth-3 chain", () => {
15
+ const m = chainMetrics([row(1, 0, 50), row(2, 5, 70, { deps: [1], stacked: true }), row(3, 10, 90, { deps: [2], stacked: true }), row(9, 0, 5)]);
16
+ assert.equal(m.chains.length, 1, "a lone issue is not a chain");
17
+ assert.equal(m.chains[0].depth, 3); assert.equal(m.chains[0].wall_min, 90);
18
+ assert.deepEqual(m.chains[0].links.map((l) => [l.issue, l.dependency, l.overlap_min]), [[2, 1, 45], [3, 2, 60]]);
19
+ assert.deepEqual(m.by_depth, { 3: { chains: 1, wall_p50_min: 90 } });
20
+ });
21
+ it("p50 by depth over several chains", () => {
22
+ const m = chainMetrics([row(1, 0, 40), row(2, 0, 60, { deps: [1] }), row(3, 0, 50), row(4, 0, 100, { deps: [3] }), row(5, 0, 80), row(6, 0, 90, { deps: [5] })]);
23
+ assert.deepEqual(m.by_depth, { 2: { chains: 3, wall_p50_min: 90 } });
24
+ });
25
+ it("a dependent that started after its dependency ended has no overlap", () => {
26
+ const m = chainMetrics([row(1, 0, 10), row(2, 20, 30, { deps: [1] })]);
27
+ assert.equal(m.chains[0].links[0].overlap_min, 0);
28
+ });
29
+ it("rows without timestamps are skipped; a dependency cycle does not hang", () => {
30
+ assert.deepEqual(chainMetrics([{ issue: 1 }, { issue: 2, deps: [1] }]).chains, []);
31
+ assert.equal(chainMetrics([row(1, 0, 5, { deps: [2] }), row(2, 0, 5, { deps: [1] })]).chains.length, 1);
32
+ });
33
+ it("cascade rework rate, with and without cascades", () => {
34
+ assert.equal(cascadeMetrics([{ issue: 1 }]).rework_rate, null);
35
+ assert.equal(cascadeMetrics([{ issue: 2, stacked: true }]).rework_rate, 0);
36
+ const c = cascadeMetrics([{ issue: 2, stacked: true, cascade: "rebase", cascades: ["reverify", "rebase"], cascade_cost_usd: 0.5, cascade_minutes: 4 }, { issue: 3, stacked: true }]);
37
+ assert.deepEqual(c, { stacked: 2, cascaded: 1, cascades: 2, rework_rate: 0.5, per_stacked: 1, cost_usd: 0.5, minutes: 4 });
38
+ });
39
+ it("chainsReport reads a batch's report.json and formats p50 by depth and the rework rate", () => {
40
+ const root = tmpDir("chains-"), dir = join(root, "b1");
41
+ mkdirSync(dir);
42
+ const now = Date.parse("2026-11-23T00:00:00Z");
43
+ writeFileSync(join(dir, "plan.json"), JSON.stringify({ created: "2026-11-22T00:00:00Z", repo: "o/r" }));
44
+ writeFileSync(join(dir, "report.json"), JSON.stringify({ rows: [row(1, 0, 50), row(2, 5, 70, { deps: [1], stacked: true, cascade: "rebase", cascades: ["rebase"], cascade_minutes: 3 })] }));
45
+ const w = chainsReport({ batchRoot: root, repo: "o/r", windows: [7 * 86400000], now });
46
+ assert.equal(w["7d"].chains, 1);
47
+ assert.equal(chainsReport({ batchRoot: root, repo: "x/y", windows: [7 * 86400000], now })["7d"].chains, 0);
48
+ const text = formatChainLines(w).join("\n");
49
+ assert.match(text, /depth 2: 1 chain, wall p50 70\.0 min/);
50
+ assert.match(text, /cascade rework: 100% of 1 stacked dependent/);
51
+ assert.match(formatChainLines(chainsReport({ batchRoot: root, repo: "x/y", windows: [86400000], now })).join("\n"), /chain wall p50: n\/a/);
52
+ });
53
+ });