forgedock 1.67.0 → 1.69.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 (156) hide show
  1. package/bin/config-schema.mjs +1 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +103 -21
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +17 -1
  6. package/bin/help-text.mjs +1 -0
  7. package/bin/lean/admission.mjs +21 -0
  8. package/bin/lean/admission.test.mjs +30 -0
  9. package/bin/lean/advisory.test.mjs +39 -15
  10. package/bin/lean/amendment-schema.mjs +3 -4
  11. package/bin/lean/attempts.mjs +34 -31
  12. package/bin/lean/attempts.test.mjs +33 -19
  13. package/bin/lean/basered.mjs +26 -0
  14. package/bin/lean/batch-health.mjs +17 -12
  15. package/bin/lean/batch-health.test.mjs +39 -11
  16. package/bin/lean/batch.mjs +11 -1
  17. package/bin/lean/batch.test.mjs +51 -2
  18. package/bin/lean/capsample.mjs +25 -0
  19. package/bin/lean/ci-gate.mjs +2 -90
  20. package/bin/lean/ci-gate.test.mjs +1 -127
  21. package/bin/lean/ci-precheck.mjs +25 -8
  22. package/bin/lean/ci-precheck.test.mjs +24 -0
  23. package/bin/lean/clear-breaker.test.mjs +4 -3
  24. package/bin/lean/commentstate.mjs +10 -5
  25. package/bin/lean/commentstate.test.mjs +12 -1
  26. package/bin/lean/conformance.e2e.test.mjs +9 -6
  27. package/bin/lean/conformance.mjs +62 -197
  28. package/bin/lean/conformance.test.mjs +46 -376
  29. package/bin/lean/depcache.mjs +102 -10
  30. package/bin/lean/depcache.test.mjs +105 -0
  31. package/bin/lean/docsgate.mjs +0 -32
  32. package/bin/lean/docsgate.test.mjs +2 -23
  33. package/bin/lean/effects-cap.test.mjs +9 -1
  34. package/bin/lean/effects-killtree.test.mjs +35 -0
  35. package/bin/lean/effects.mjs +57 -25
  36. package/bin/lean/engine-readmit.test.mjs +35 -0
  37. package/bin/lean/envgap.mjs +111 -0
  38. package/bin/lean/envgap.test.mjs +64 -0
  39. package/bin/lean/execution.mjs +13 -4
  40. package/bin/lean/execution.test.mjs +33 -0
  41. package/bin/lean/failure-census.mjs +170 -0
  42. package/bin/lean/failure-census.test.mjs +59 -0
  43. package/bin/lean/failure-stop.mjs +12 -1
  44. package/bin/lean/failure-stop.test.mjs +14 -1
  45. package/bin/lean/guardgate.test.mjs +2 -3
  46. package/bin/lean/heavy.mjs +33 -4
  47. package/bin/lean/heavy.test.mjs +38 -6
  48. package/bin/lean/hostconfig.mjs +54 -0
  49. package/bin/lean/hostconfig.test.mjs +67 -0
  50. package/bin/lean/hotarea.mjs +0 -36
  51. package/bin/lean/hotarea.test.mjs +1 -22
  52. package/bin/lean/issuewatch-verify.mjs +19 -4
  53. package/bin/lean/issuewatch.mjs +21 -4
  54. package/bin/lean/issuewatch.test.mjs +48 -1
  55. package/bin/lean/lane-audit-gap.mjs +66 -0
  56. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  57. package/bin/lean/lane-audit-llm.mjs +52 -0
  58. package/bin/lean/lane-audit-llm.test.mjs +57 -0
  59. package/bin/lean/lane-audit-query.mjs +47 -0
  60. package/bin/lean/lane-audit-query.test.mjs +44 -0
  61. package/bin/lean/lane-audit-signatures.mjs +33 -0
  62. package/bin/lean/lane-audit.mjs +110 -0
  63. package/bin/lean/lane-audit.test.mjs +97 -0
  64. package/bin/lean/lane-recovery.test.mjs +33 -0
  65. package/bin/lean/lanecheck.mjs +5 -3
  66. package/bin/lean/lanecheck.test.mjs +6 -0
  67. package/bin/lean/lean.mjs +247 -152
  68. package/bin/lean/lean.test.mjs +502 -206
  69. package/bin/lean/limits.mjs +17 -0
  70. package/bin/lean/limits.test.mjs +15 -1
  71. package/bin/lean/live-execution.mjs +24 -2
  72. package/bin/lean/live-execution.test.mjs +62 -0
  73. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  74. package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
  75. package/bin/lean/orchestrate-envhold.test.mjs +62 -1
  76. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  77. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  78. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  79. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  80. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  81. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  82. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  83. package/bin/lean/orchestrate.mjs +215 -42
  84. package/bin/lean/postdeploy-check.test.mjs +1 -3
  85. package/bin/lean/precheck.mjs +20 -0
  86. package/bin/lean/preflight.mjs +110 -14
  87. package/bin/lean/preflight.test.mjs +64 -4
  88. package/bin/lean/prompts.mjs +11 -21
  89. package/bin/lean/recurrence.mjs +6 -148
  90. package/bin/lean/recurrence.test.mjs +11 -147
  91. package/bin/lean/release-deploy.mjs +35 -5
  92. package/bin/lean/release-deploy.test.mjs +50 -3
  93. package/bin/lean/release-flakes.mjs +48 -2
  94. package/bin/lean/release-flakes.test.mjs +45 -1
  95. package/bin/lean/release-ledger.mjs +19 -1
  96. package/bin/lean/release-ledger.test.mjs +23 -0
  97. package/bin/lean/release-preflight.mjs +28 -0
  98. package/bin/lean/release-preflight.test.mjs +42 -1
  99. package/bin/lean/release-review.mjs +40 -5
  100. package/bin/lean/release-review.test.mjs +43 -2
  101. package/bin/lean/release.mjs +45 -15
  102. package/bin/lean/release.test.mjs +32 -0
  103. package/bin/lean/retry.mjs +1 -1
  104. package/bin/lean/retry.test.mjs +6 -1
  105. package/bin/lean/rotator.mjs +9 -0
  106. package/bin/lean/rotator.test.mjs +11 -1
  107. package/bin/lean/sandbox-remote.mjs +51 -13
  108. package/bin/lean/schedd.mjs +13 -8
  109. package/bin/lean/schedd.test.mjs +65 -5
  110. package/bin/lean/selfreview.mjs +1 -1
  111. package/bin/lean/statuscomment.mjs +4 -1
  112. package/bin/lean/validate-catalog.mjs +108 -0
  113. package/bin/lean/validate-catalog.test.mjs +46 -1
  114. package/bin/lean/verify.mjs +1 -1
  115. package/bin/pool/affinity.test.mjs +91 -0
  116. package/bin/pool/agent.mjs +247 -23
  117. package/bin/pool/cache-sweep.mjs +31 -10
  118. package/bin/pool/ci-autoscale.mjs +160 -0
  119. package/bin/pool/cli.mjs +56 -9
  120. package/bin/pool/docker.mjs +5 -0
  121. package/bin/pool/engine-placement.test.mjs +94 -0
  122. package/bin/pool/image-manifest.mjs +24 -0
  123. package/bin/pool/image-manifest.test.mjs +20 -0
  124. package/bin/pool/lane-target.mjs +41 -0
  125. package/bin/pool/lane-tools.mjs +29 -5
  126. package/bin/pool/lane-tools.test.mjs +36 -7
  127. package/bin/pool/mirror-seed.mjs +15 -11
  128. package/bin/pool/project-layer.mjs +142 -0
  129. package/bin/pool/project-layer.test.mjs +73 -0
  130. package/bin/pool/router.mjs +106 -36
  131. package/bin/pool/version.mjs +72 -2
  132. package/bin/review-staging.mjs +11 -3
  133. package/bin/runner.mjs +59 -11
  134. package/bin/stats/release.mjs +7 -0
  135. package/bin/stats/release.test.mjs +20 -0
  136. package/bin/stats/scorecard.mjs +187 -0
  137. package/bin/stats/scorecard.test.mjs +89 -0
  138. package/bin/stats/tool-parks.mjs +29 -0
  139. package/bin/stats/tool-parks.test.mjs +21 -0
  140. package/docs/CONFIG.md +41 -0
  141. package/docs/OUTCOME-CODES.md +1 -0
  142. package/docs/STATS.md +17 -0
  143. package/package.json +1 -1
  144. package/pool/image/Dockerfile +15 -3
  145. package/pool/image/manifest.json +25 -0
  146. package/pool/image/mirror.sh +11 -2
  147. package/pool/install/install-agent.ps1 +11 -4
  148. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  149. package/scripts/ci-local/cli.mjs +1 -1
  150. package/scripts/ci-local/plan.mjs +3 -2
  151. package/scripts/ci-local.test.sh +14 -2
  152. package/scripts/failure-census.mjs +67 -0
  153. package/scripts/review-finalize.sh +5 -5
  154. package/scripts/review-finalize.test.sh +8 -1
  155. package/scripts/verify-phase-trail.sh +11 -0
  156. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -4,7 +4,7 @@
4
4
  // itself runs inside a short-lived container of the lane image with the cache volume on /cache. The agent ships this
5
5
  // file's source in CS_CACHE_SWEEP_SRC and the options in CS_CACHE_SWEEP_OPTS; the JSON result goes to stdout.
6
6
  import { execFileSync } from "node:child_process";
7
- import { existsSync, readFileSync, rmSync } from "node:fs";
7
+ import { existsSync, readFileSync, rmSync, statSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
 
10
10
  export const CACHE_LABEL = "computeshare.cache=1";
@@ -15,6 +15,7 @@ export const PACKAGE_STORES = ["pnpm-store", ...["pnpm-store", "npm-cache", "uv-
15
15
  /** #5881: owner label; the reaper and sweeps touch only containers and volumes carrying their own agent's label. */
16
16
  export const agentLabel = (id) => `computeshare.agent=${id}`;
17
17
  const DAY = 86400000;
18
+ const LOCK_LIVE_MS = 2 * 3600000; // a depcache key lock younger than this may belong to a running install or lane
18
19
 
19
20
  /**
20
21
  * Oldest-first deletion plan to bring `entries` ({path, bytes, mtimeMs, live}) under `capBytes`. Live entries (the work
@@ -55,22 +56,42 @@ const sizeOf = (p) => (Number(sh("du", ["-sk", p]).split(/\s/)[0]) || 0) * 1024;
55
56
  const kids = (dir) => sh("find", [dir, "-mindepth", "1", "-maxdepth", "1", "-printf", "%p\t%T@\n"]).split("\n").filter(Boolean).map((l) => { const i = l.lastIndexOf("\t"); return { path: l.slice(0, i), mtimeMs: Number(l.slice(i + 1)) * 1000 }; });
56
57
 
57
58
  const SNAP = /^[a-z]+-[0-9a-f]{16}$/;
59
+ const num = (p) => { try { const n = Number(readFileSync(p, "utf8").trim()); return Number.isFinite(n) && n > 0 ? n : null; } catch { return null; } };
60
+ const mtimeOf = (p) => { try { return statSync(p).mtimeMs; } catch { return null; } };
61
+ /** #5898: a snapshot is in use while its `<snap>.lock` is younger than LOCK_LIVE_MS (the container cannot check pids). */
62
+ const lockLive = (p, now) => { const m = mtimeOf(`${p}.lock`); return m !== null && now - m < LOCK_LIVE_MS; };
58
63
  /** Last use of a depcache snapshot: its `last-used` file (epoch ms, written on every hit), else the directory mtime. */
59
- const snapLastUsed = (k) => { try { const n = Number(readFileSync(join(k.path, "last-used"), "utf8").trim()); if (n > 0) return n; } catch { /* none yet */ } return k.mtimeMs; };
64
+ const snapLastUsed = (k) => {
65
+ let created = null;
66
+ try { created = Number(JSON.parse(readFileSync(join(k.path, "manifest.json"), "utf8")).created) || null; } catch { /* no manifest */ }
67
+ return num(join(k.path, "last-used")) ?? created ?? k.mtimeMs;
68
+ };
69
+ /** Every depcache snapshot as {path, lastUsedMs, live}; last use falls back to manifest `created`, then mtime. */
70
+ function depcacheSnaps(dc, now) {
71
+ const out = [];
72
+ for (const repo of kids(dc)) {
73
+ if (repo.path.endsWith("/stores")) continue;
74
+ for (const k of kids(repo.path)) {
75
+ if (!SNAP.test(k.path.slice(repo.path.length + 1))) continue;
76
+ out.push({ ...k, lastUsedMs: snapLastUsed(k), live: lockLive(k.path, now) });
77
+ }
78
+ }
79
+ return out;
80
+ }
60
81
 
61
82
  /**
62
83
  * #5901: depcache is `<dc>/<repoKey>/<eco>-<key>/`. Each snapshot (not the repo dir, whose mtime moves with every new
63
84
  * snapshot) ages out by its last use and is trimmed least-recently-used past the per-repo cap. A snapshot with a lock file
64
85
  * is in use and kept. Fills `depcacheBytes[repoKey]` with what remains.
65
86
  */
66
- function sweepDepcache(dc, { cutoff, capBytes, rm, depcacheBytes }) {
87
+ function sweepDepcache(dc, { cutoff, now, capBytes, rm, depcacheBytes }) {
67
88
  for (const repo of kids(dc)) {
68
89
  const rk = repo.path.slice(dc.length + 1);
69
90
  if (rk === "stores") continue;
70
- if (SNAP.test(rk)) { if (repo.mtimeMs < cutoff) rm(repo.path); continue; } // an entry of the flat layout (no repo level)
91
+ if (SNAP.test(rk)) { if (snapLastUsed(repo) < cutoff && !lockLive(repo.path, now)) rm(repo.path); continue; } // an entry of the flat layout (no repo level)
71
92
  let snaps = kids(repo.path).filter((k) => SNAP.test(k.path.slice(repo.path.length + 1)));
72
- const live = (k) => existsSync(`${k.path}.lock`);
73
- snaps = snaps.map((k) => ({ ...k, lastUsedMs: snapLastUsed(k), live: live(k) }));
93
+ for (const k of kids(repo.path)) if (/\.(tmp-\d+|lock)$/.test(k.path) && k.mtimeMs < cutoff) rm(k.path); // dead publishers' tmp dirs, old locks
94
+ snaps = snaps.map((k) => ({ ...k, lastUsedMs: snapLastUsed(k), live: lockLive(k.path, now) }));
74
95
  for (const k of snaps.filter((x) => x.lastUsedMs < cutoff && !x.live)) rm(k.path);
75
96
  snaps = snaps.filter((x) => existsSync(x.path));
76
97
  if (!snaps.length) { if (repo.mtimeMs < cutoff) rm(repo.path); continue; } // nothing left in it and untouched for the max age
@@ -94,7 +115,7 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ma
94
115
  const ageOut = (dir, skip = []) => { for (const k of kids(dir)) if (k.mtimeMs < cutoff && !skip.includes(k.path)) rm(k.path); };
95
116
  const dc = join(root, "forge-depcache");
96
117
  const depcacheBytes = {};
97
- if (existsSync(dc)) { ageOut(join(dc, "stores")); sweepDepcache(dc, { cutoff, capBytes: Number.isFinite(maxDepcacheGb) ? maxDepcacheGb * 1024 ** 3 : null, rm, depcacheBytes }); } // store entries, then snapshots per repo
118
+ if (existsSync(dc)) { ageOut(join(dc, "stores")); sweepDepcache(dc, { cutoff, now, capBytes: Number.isFinite(maxDepcacheGb) ? maxDepcacheGb * 1024 ** 3 : null, rm, depcacheBytes }); } // store entries, then snapshots per repo
98
119
  if (existsSync(join(root, "env"))) ageOut(join(root, "env"));
99
120
  const ps = join(root, "pnpm-store");
100
121
  if (existsSync(ps)) sh("pnpm", ["store", "prune", "--store-dir", ps]);
@@ -103,12 +124,12 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ma
103
124
  const entries = [];
104
125
  const keepSet = new Set(keep);
105
126
  for (const k of kids(join(root, "work"))) entries.push({ ...k, bytes: sizeOf(k.path), live: keepSet.has(k.path) });
106
- for (const d of [...PACKAGE_STORES, "env", "forge-depcache", "forge-depcache/stores"]) for (const k of kids(join(root, d))) if (!k.path.endsWith("/stores")) entries.push({ ...k, bytes: sizeOf(k.path), live: false });
127
+ for (const d of [...PACKAGE_STORES, "env", "forge-depcache/stores"]) for (const k of kids(join(root, d))) entries.push({ ...k, bytes: sizeOf(k.path), live: false });
128
+ for (const k of depcacheSnaps(dc, now)) entries.push({ path: k.path, mtimeMs: k.lastUsedMs, bytes: sizeOf(k.path), live: k.live });
107
129
  const plan = planCacheCap(entries, maxGb * 1024 ** 3);
108
130
  for (const p of plan.delete) rm(p);
109
131
  }
110
- let last = null;
111
- try { const n = Number(readFileSync(join(root, ".last-used"), "utf8").trim()); if (Number.isFinite(n) && n > 0) last = n * 1000; } catch { /* never recorded */ }
132
+ const lastSec = num(join(root, ".last-used")), last = lastSec === null ? null : lastSec * 1000;
112
133
  return { size_bytes: sizeOf(root), last_used_ms: last, depcache_bytes: depcacheBytes, removed: removed.length, errors: errors.slice(0, 5) };
113
134
  }
114
135
 
@@ -0,0 +1,160 @@
1
+ // #5695: demand- and capacity-driven CI runner autoscaler for the pool router. The decision logic (admitRunner, planScale,
2
+ // runnerPriority, decisionRecord) is pure; createAutoscaler wires it to the router's webhook, tick and agents.
3
+ // Imports stay inside bin/pool: the router ships agents only AGENT_BUNDLE_PATHS (pool-agent-bundle.test.mjs).
4
+
5
+ /** Priority classes, lowest number first: deploy > release-PR CI > lanes > ordinary PR CI. */
6
+ export const PRIORITY = { deploy: 0, release: 1, lane: 2, pr: 3 };
7
+ export const DEFAULT_FLOORS = { mem_available_gb: 3, load_per_cpu: 0.8, lane_cpus: 2, lane_mem_gb: 3, net_rx_mbps_max: null };
8
+ export const DEFAULT_SIZE = { cpus: 1, mem_gb: 2 };
9
+
10
+ const num = (v, d) => (Number.isFinite(Number(v)) && v !== null && v !== "" ? Number(v) : d);
11
+
12
+ /** Deploy labels and an explicit job.priority win; a release branch or job.release is release CI; the rest is PR CI. */
13
+ export function runnerPriority(job = {}) {
14
+ if (Number.isInteger(job.priority) && job.priority >= 0 && job.priority <= PRIORITY.pr) return job.priority;
15
+ if (/deploy/i.test(String(job.label ?? "")) || (job.labels ?? []).some((l) => /deploy/i.test(l))) return PRIORITY.deploy;
16
+ if (job.release === true || /^(release|hotfix)[/-]/i.test(String(job.head_branch ?? ""))) return PRIORITY.release;
17
+ return PRIORITY.pr;
18
+ }
19
+
20
+ /** One telemetry record per decision, carrying every input it was made from. */
21
+ export function decisionRecord({ action, label, job = null, admit = null, reason, inputs = {}, dry_run = false, at = null }) {
22
+ return { at, action, label, job: job?.id ?? null, priority: job ? runnerPriority(job) : null, admit, reason, dry_run, inputs };
23
+ }
24
+
25
+ /**
26
+ * Does one more runner fit? free = {mem_available_gb, load_per_cpu, vcpus, cpus_free, mem_free_gb}; reserved = what earlier
27
+ * admissions of this round already took; net = {rx_mbps}. The lane floor keeps cpus_free/mem_free_gb for lanes at every
28
+ * priority, so CI never blocks a lane beyond it.
29
+ */
30
+ export function admitRunner({ free, floors = {}, reserved = {}, job = {}, net = null, size = null }) {
31
+ const f = { ...DEFAULT_FLOORS, ...floors }, sz = size ?? job.size ?? DEFAULT_SIZE;
32
+ const rc = num(reserved.cpus, 0), rm = num(reserved.mem_gb, 0), vcpus = Math.max(1, num(free.vcpus, 1));
33
+ const after = {
34
+ mem_available_gb: num(free.mem_available_gb, Infinity) - rm - sz.mem_gb,
35
+ load_per_cpu: num(free.load_per_cpu, 0) + (rc + sz.cpus) / vcpus,
36
+ cpus_free: num(free.cpus_free, Infinity) - rc - sz.cpus,
37
+ mem_free_gb: num(free.mem_free_gb, Infinity) - rm - sz.mem_gb,
38
+ };
39
+ const inputs = { free, floors: f, reserved: { cpus: rc, mem_gb: rm }, size: sz, after, ...(net ? { net } : {}) };
40
+ const no = (reason) => ({ admit: false, reason, inputs });
41
+ if (after.mem_available_gb < f.mem_available_gb) return no(`MemAvailable ${after.mem_available_gb.toFixed(1)} GB after reservation < floor ${f.mem_available_gb}`);
42
+ if (after.load_per_cpu > f.load_per_cpu) return no(`load ${after.load_per_cpu.toFixed(2)}/cpu after reservation > ${f.load_per_cpu}`);
43
+ if (after.cpus_free < f.lane_cpus || after.mem_free_gb < f.lane_mem_gb) return no("lane floor: reservation would leave lanes less than the configured floor");
44
+ const rx = num(net?.rx_mbps, null);
45
+ if (f.net_rx_mbps_max && rx !== null && rx > f.net_rx_mbps_max && runnerPriority(job) > PRIORITY.deploy) return no(`network ${rx} MB/s > ${f.net_rx_mbps_max} (saturated)`);
46
+ return { admit: true, reason: "fits", inputs };
47
+ }
48
+
49
+ const inWindow = (window, t) => (window ?? []).find((w) => Number(w.from) <= t && t < Number(w.to)) ?? null;
50
+
51
+ /**
52
+ * Decide this round's runner starts and stops.
53
+ * demand: {label: [job]} queued jobs; running: {label: {total, busy}}; labels: {label: {min, max, size}};
54
+ * lanes: {waiting} (a waiting lane outranks ordinary PR CI); window: [{from,to}] maintenance windows in epoch ms.
55
+ * Returns decision records; `start`/`stop` ones are actionable. Candidates are admitted in priority order.
56
+ */
57
+ export function planScale({ demand = {}, running = {}, labels = {}, lanes = {}, window = [], free, floors = {}, net = null, now = 0, dry_run = false }) {
58
+ const out = [], rec = (d) => out.push(decisionRecord({ at: now, dry_run, ...d }));
59
+ const win = inWindow(window, now), cand = [];
60
+ for (const [label, cfg] of Object.entries(labels)) {
61
+ const queued = demand[label] ?? [], r = running[label] ?? { total: 0, busy: 0 };
62
+ const min = num(cfg.min, 0), max = num(cfg.max, 0), size = cfg.size ?? DEFAULT_SIZE, idle = Math.max(0, r.total - r.busy);
63
+ const ctx = { queued: queued.length, total: r.total, busy: r.busy, idle, min, max, size };
64
+ const want = Math.min(Math.max(queued.length - idle, min - r.total, 0), Math.max(0, max - r.total));
65
+ const jobs = [...queued].sort((a, b) => runnerPriority({ label, ...a }) - runnerPriority({ label, ...b }));
66
+ for (let i = 0; i < want; i++) cand.push({ label, size, job: { label, ...(jobs[i] ?? { id: null }) }, ctx });
67
+ const keep = Math.max(min, queued.length), surplus = Math.max(0, idle - Math.max(0, keep - r.busy));
68
+ if (surplus > 0 && !win) rec({ action: "stop", label, admit: true, reason: `${surplus} idle runner(s) above max(min, queued)`, inputs: { ...ctx, surplus } });
69
+ else if (want === 0) rec({ action: "hold", label, admit: null, reason: "no runner needed", inputs: ctx });
70
+ }
71
+ cand.sort((a, b) => runnerPriority(a.job) - runnerPriority(b.job));
72
+ const reserved = { cpus: 0, mem_gb: 0 };
73
+ for (const c of cand) {
74
+ if (win) { rec({ action: "hold", label: c.label, job: c.job, admit: false, reason: `maintenance window${win.why ? `: ${win.why}` : ""}`, inputs: { ...c.ctx, window: win } }); continue; }
75
+ if ((lanes.waiting ?? 0) > 0 && runnerPriority(c.job) > PRIORITY.lane) { rec({ action: "hold", label: c.label, job: c.job, admit: false, reason: "a lane is waiting and outranks ordinary PR CI", inputs: { ...c.ctx, lanes } }); continue; }
76
+ const v = admitRunner({ free, floors, reserved, job: c.job, net, size: c.size });
77
+ if (v.admit) { reserved.cpus += c.size.cpus; reserved.mem_gb += c.size.mem_gb; }
78
+ rec({ action: v.admit ? "start" : "hold", label: c.label, job: c.job, admit: v.admit, reason: v.reason, inputs: { ...v.inputs, ...c.ctx } });
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /**
84
+ * Router-side controller. `ingest` takes a GitHub workflow_job payload (queued/in_progress/completed); `reconcile` (router
85
+ * tick) polls the jobs API as a fallback, plans, and asks an agent to start or stop ephemeral JIT runners. Off by default;
86
+ * dry_run logs every decision and starts nothing.
87
+ */
88
+ export function createAutoscaler({ cfg = {}, now, log, capacities, agentCall, githubToken, fetchFn, agents }) {
89
+ const c = cfg.ci_autoscale ?? {};
90
+ const jobs = new Map(); // job id -> {id,label,status,runner,head_branch,at}
91
+ const decisions = [];
92
+ let lastPoll = -Infinity, seq = 0;
93
+ const labelOf = (wj) => (wj?.labels ?? []).find((l) => Object.hasOwn(c.labels ?? {}, l)) ?? null;
94
+ const track = (wj) => {
95
+ const label = labelOf(wj);
96
+ if (!label || !Number.isFinite(Number(wj.id))) return null;
97
+ if (wj.status === "completed") { jobs.delete(Number(wj.id)); return { label, status: "completed" }; }
98
+ const j = { id: Number(wj.id), label, labels: wj.labels, status: wj.status === "in_progress" ? "in_progress" : "queued", runner: wj.runner_name ?? null, head_branch: wj.head_branch ?? null, at: now() };
99
+ jobs.set(j.id, j);
100
+ return { label, status: j.status };
101
+ };
102
+ function ingest(body) {
103
+ if (!c.enabled) return { enabled: false, tracked: false };
104
+ const t = body?.workflow_job ? track(body.workflow_job) : null;
105
+ return { enabled: true, tracked: Boolean(t), ...(t ?? {}) };
106
+ }
107
+ const gh = async (path, body) => {
108
+ const r = await fetchFn(`https://api.github.com${path}`, { method: body ? "POST" : "GET", headers: { authorization: `Bearer ${await githubToken()}`, accept: "application/vnd.github+json", ...(body ? { "content-type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
109
+ if (!r.ok) throw new Error(`GitHub ${path} -> ${r.status}`);
110
+ return r.json();
111
+ };
112
+ async function poll() {
113
+ if (!c.repo || now() - lastPoll < (c.poll_s ?? 300) * 1000) return;
114
+ lastPoll = now();
115
+ const seen = new Set();
116
+ try {
117
+ const runs = (await gh(`/repos/${c.repo}/actions/runs?status=queued&per_page=20`)).workflow_runs ?? [];
118
+ for (const run of runs) for (const wj of (await gh(`/repos/${c.repo}/actions/runs/${run.id}/jobs?per_page=100`)).jobs ?? []) {
119
+ if (wj.status === "queued" && labelOf(wj)) { seen.add(Number(wj.id)); if (!jobs.has(Number(wj.id))) track({ ...wj, head_branch: wj.head_branch ?? run.head_branch }); }
120
+ }
121
+ for (const [id, j] of jobs) if (j.status === "queued" && !seen.has(id) && now() - j.at > (c.poll_s ?? 300) * 1000) jobs.delete(id); // the API no longer lists it
122
+ } catch (e) { log.warn?.(`ci-autoscale poll: ${e.message}`); }
123
+ }
124
+ const emit = (d) => { decisions.push(d); if (decisions.length > 200) decisions.shift(); log.info?.(`ci-autoscale ${JSON.stringify(d)}`); };
125
+
126
+ async function reconcile() {
127
+ if (!c.enabled) return [];
128
+ for (const [id, j] of jobs) if (now() - j.at > 6 * 3600000) jobs.delete(id); // a lost completed event
129
+ await poll();
130
+ const caps = (await capacities()).filter((x) => x.ok && !x.paused);
131
+ if (!caps.length) return [];
132
+ const host = caps.sort((a, b) => (b.live?.mem_available_gb ?? 0) - (a.live?.mem_available_gb ?? 0))[0];
133
+ const free = { mem_available_gb: host.live?.mem_available_gb, load_per_cpu: host.live?.load_per_core, vcpus: host.vm?.cpus ?? host.cpus_total, cpus_free: host.cpus_free, mem_free_gb: host.mem_free_gb };
134
+ const demand = {}, running = {};
135
+ for (const label of Object.keys(c.labels ?? {})) {
136
+ demand[label] = [...jobs.values()].filter((j) => j.label === label && j.status === "queued");
137
+ const mine = (host.runners ?? []).filter((r) => r.label === label), busyNames = new Set([...jobs.values()].filter((j) => j.status === "in_progress" && j.runner).map((j) => j.runner));
138
+ running[label] = { total: mine.length, busy: mine.filter((r) => busyNames.has(r.name)).length, names: mine.map((r) => r.name).filter((n) => !busyNames.has(n)) };
139
+ }
140
+ const win = (c.windows ?? []).map((w) => ({ from: Date.parse(w.from), to: Date.parse(w.to), why: w.why }));
141
+ const plan = planScale({ demand, running, labels: c.labels, lanes: { waiting: 0 }, window: win, free, floors: { ...c.floors, lane_cpus: c.lane_floor?.cpus ?? c.floors?.lane_cpus, lane_mem_gb: c.lane_floor?.mem_gb ?? c.floors?.lane_mem_gb }, net: host.net ?? null, now: now(), dry_run: Boolean(c.dry_run) });
142
+ for (const d of plan) {
143
+ emit(d);
144
+ if (c.dry_run) continue;
145
+ const a = agents()[host.name];
146
+ try {
147
+ if (d.action === "start") {
148
+ const name = `ci-${d.label}-${now().toString(36)}-${seq++}`.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 64);
149
+ const jit = await gh(`/repos/${c.repo}/actions/runners/generate-jitconfig`, { name, runner_group_id: c.runner_group_id ?? 1, labels: ["self-hosted", d.label], work_folder: "_work" });
150
+ const r = await agentCall(a, "POST", "/runners", { name, label: d.label, jitconfig: jit.encoded_jit_config, cpus: d.inputs.size.cpus, mem_gb: d.inputs.size.mem_gb });
151
+ if (!r.ok) log.warn?.(`ci-autoscale start ${name} on ${host.name}: HTTP ${r.status}`);
152
+ } else if (d.action === "stop") {
153
+ for (const n of running[d.label].names.slice(0, d.inputs.surplus)) await agentCall(a, "DELETE", `/runners/${encodeURIComponent(n)}`);
154
+ }
155
+ } catch (e) { log.warn?.(`ci-autoscale ${d.action} ${d.label}: ${e.message}`); }
156
+ }
157
+ return plan;
158
+ }
159
+ return { ingest, reconcile, decisions, jobs };
160
+ }
package/bin/pool/cli.mjs CHANGED
@@ -11,11 +11,12 @@ import { startRouter } from "./router.mjs";
11
11
  import { dockerCli } from "./docker.mjs";
12
12
  import { readSecret } from "./store.mjs";
13
13
  import { call as httpCall } from "./http.mjs";
14
+ import { agentsLeftBehind, leftBehindLine } from "./version.mjs";
14
15
 
15
16
  const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
16
17
  const loadJson = (p) => JSON.parse(readFileSync(p, "utf8"));
17
18
 
18
- const USAGE = "usage: forgedock pool router [install] | enroll [--cpus N --mem GB --agent-url URL | --outbound | --one-liner] | status [--json] [--account A] | link <user_code> [--account A] | policy <agent> [--cpus N --mem GB --idle-only --pause --resume-policy] | limit <agent> --lanes N|none | pause | resume | uninstall [--yes] | upgrade [agent] | remove <agent> [--config path]";
19
+ const USAGE = "usage: forgedock pool router [install] | enroll [--cpus N --mem GB --agent-url URL | --outbound | --one-liner] | status [--json] [--account A] | link <user_code> [--account A] | policy <agent> [--cpus N --mem GB --idle-only --pause --resume-policy] | limit <agent> --lanes N|none | pause | resume | uninstall [--yes] | upgrade [agent] [--wait [--timeout S] | --now] | remove <agent> [--config path]";
19
20
  const HELP_FLAGS = ["--help", "-h"];
20
21
  // Flags each verb accepts: `value` flags consume the next token, `bool` flags stand alone. Anything else dash-prefixed is rejected (#5008).
21
22
  const VERB_FLAGS = {
@@ -27,7 +28,7 @@ const VERB_FLAGS = {
27
28
  pause: { value: ["--config"], bool: [] },
28
29
  resume: { value: ["--config"], bool: [] },
29
30
  uninstall: { value: [], bool: ["--yes"] },
30
- upgrade: { value: ["--config"], bool: [] },
31
+ upgrade: { value: ["--config", "--timeout"], bool: ["--now", "--wait"] },
31
32
  remove: { value: ["--config"], bool: [] },
32
33
  limit: { value: ["--config", "--lanes"], bool: [] },
33
34
  enroll: { value: ["--config", "--cpus", "--mem", "--agent-url"], bool: ["--outbound", "--one-liner"] },
@@ -59,23 +60,41 @@ export async function keptRows(root, { now = Date.now() } = {}) {
59
60
  } catch { return []; }
60
61
  }
61
62
  export const keptLines = (rows) => rows.length ? [`kept sandboxes (${rows.length}):`, ...rows.map((k) => ` #${k.issue} batch ${k.batch} age ${Math.round((k.ageMs ?? 0) / 60000)}m phase ${k.phase ?? "?"}`)] : [];
63
+ /** #6062: queue_wait p50/p95 (ms) per worker from batch report rows whose phases.queue_wait names the worker. */
64
+ export function queueWaitByWorker(rows) {
65
+ const by = {};
66
+ for (const r of rows ?? []) { const q = r?.phases?.queue_wait; if (q?.worker && Number.isFinite(q.ms)) (by[q.worker] ??= []).push(q.ms); }
67
+ const pct = (xs, p) => xs[Math.min(xs.length - 1, Math.ceil(p * xs.length) - 1)];
68
+ return Object.fromEntries(Object.entries(by).map(([w, xs]) => { xs.sort((a, b) => a - b); return [w, { n: xs.length, p50_ms: pct(xs, 0.5), p95_ms: pct(xs, 0.95) }]; }));
69
+ }
70
+ export async function queueRows(root) {
71
+ try {
72
+ const B = await import("../lean/batch.mjs"), out = [];
73
+ for (const id of B.listBatches(root)) out.push(...(B.openBatch(root, id).readReport()?.rows ?? []));
74
+ return out;
75
+ } catch { return []; }
76
+ }
62
77
  const num = (x) => (Number.isFinite(x) ? String(Math.round(x * 10) / 10) : "-");
78
+ const usedCell = (u) => (u?.used && u.admitted ? `${num(u.used.cpu_avg)}/${num(u.used.mem_avg_gb)} vs ${num(u.admitted.cpus)}/${num(u.admitted.mem_gb)}` : "-");
79
+ const queueCell = (q) => (q && Number.isFinite(q.p50_ms) ? `${num(q.p50_ms / 1000)}/${num(q.p95_ms / 1000)}` : "-");
63
80
  /** #5885: one row per host: used/borrowable/total cpus and memory, lane counts, pause state and why lanes are throttled or drained. */
64
81
  export function statusTable(agents) {
65
82
  const withAccount = agents.some((a) => a.account); // #5886: the column appears only when an agent has an account
66
- const head = ["HOST", ...(withAccount ? ["ACCOUNT"] : []), "CPUS used/borrow/total", "MEM GB used/borrow/total", "ACTIVE", "THROTTLED", "PAUSED", "REASON"];
83
+ const withEngine = agents.some((a) => a.engine_version); // the ENGINE column appears only when an agent reports its lane engine
84
+ const head = ["HOST", ...(withAccount ? ["ACCOUNT"] : []), "CPUS used/borrow/total", "MEM GB used/borrow/total", "ACTIVE", "THROTTLED", "PAUSED", ...(withEngine ? ["ENGINE"] : []), "REASON", "USED cpu/mem vs admitted", "QUEUE p50/p95 s"];
67
85
  const rows = agents.map((a) => {
68
86
  const name = a.name ?? a.host ?? "?";
69
87
  const acct = withAccount ? [a.account ?? "-"] : [];
70
- if (a.ok === false) return [name, ...acct, "-", "-", "-", "-", "-", `unreachable${a.error ? `: ${a.error}` : ""}`];
88
+ if (a.ok === false) return [name, ...acct, "-", "-", "-", "-", ...(withEngine ? ["-"] : []), "-", `unreachable${a.error ? `: ${a.error}` : ""}`, "-", "-"];
71
89
  const used = (tot, free) => (Number.isFinite(tot) && Number.isFinite(free) ? tot - Math.max(0, free) : null);
72
90
  const borrow = (b, free) => num(b ?? free);
73
91
  const paused = a.owner_paused ? "owner" : a.paused ? (a.pending_resize ? "resize" : "yes") : "no";
74
92
  const why = [a.owner_paused ? "paused by owner" : null, a.paused && !a.owner_paused && a.pending_resize ? "draining for resize" : null,
93
+ Number.isInteger(a.lane_target) ? `lane target ${a.lane_target}/${a.lane_ceiling ?? "-"}` : null, a.draining && !a.owner_paused && !a.pending_resize ? `draining: ${a.draining_reason ?? "yes"}` : null,
75
94
  a.idle_gate ? `owner busy: ${a.idle_gate}` : null, a.last_drain ? `last drain ${a.last_drain.sandbox} at ${a.last_drain.at}: ${a.last_drain.reason}` : null].filter(Boolean).join("; ");
76
95
  return [name, ...acct, `${num(used(a.cpus_total, a.cpus_free))}/${borrow(a.cpus_borrowable, a.cpus_free)}/${num(a.cpus_total)}`,
77
96
  `${num(used(a.mem_total_gb, a.mem_free_gb))}/${borrow(a.mem_borrowable_gb, a.mem_free_gb)}/${num(a.mem_total_gb)}`,
78
- String(a.active ?? "-"), String(a.throttled ?? 0), paused, why || "-"];
97
+ String(a.active ?? "-"), String(a.throttled ?? 0), paused, ...(withEngine ? [a.engine_version ? `${a.engine_version}${a.engine_skew ? " SKEW" : ""}` : "-"] : []), why || "-", usedCell(a.usage_summary), queueCell(a.queue_wait)];
79
98
  });
80
99
  const w = head.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
81
100
  return [head, ...rows].map((r) => r.map((c, i) => (i === r.length - 1 ? c : c.padEnd(w[i]))).join(" ")).join("\n");
@@ -137,7 +156,9 @@ export async function runPoolCli(argv, deps = {}) {
137
156
  case "status": {
138
157
  const cfg = routerConfig();
139
158
  const r = await call(`http://${cfg.listen.host}:${cfg.listen.port}`, "GET", `/agents${flag("account") ? `?account=${encodeURIComponent(flag("account"))}` : ""}`, { token: cfg.forgedock_token });
140
- const kept = await keptRows((await import("../lean/batch.mjs")).batchRoot());
159
+ const root = (await import("../lean/batch.mjs")).batchRoot(), kept = await keptRows(root);
160
+ const qw = queueWaitByWorker(await queueRows(root)); // #6062
161
+ if (Array.isArray(r.data?.agents)) r.data = { ...r.data, agents: r.data.agents.map((a) => (qw[a?.name] ? { ...a, queue_wait: qw[a.name] } : a)) };
141
162
  if (rest.includes("--json")) console.log(JSON.stringify(r.data && typeof r.data === "object" && !Array.isArray(r.data) && kept.length ? { ...r.data, kept_sandboxes: kept } : r.data, null, 2));
142
163
  else if (!r.ok) throw new Error(`router refused: HTTP ${r.status} ${JSON.stringify(r.data)}`);
143
164
  else console.log(statusTable(r.data?.agents ?? []));
@@ -267,12 +288,38 @@ export async function runPoolCli(argv, deps = {}) {
267
288
  // Push the current code (and lane image, when its recipe changed) to one agent or all of them.
268
289
  const cfg = routerConfig();
269
290
  const base = `http://${cfg.listen.host}:${cfg.listen.port}`;
270
- const only = rest.find((x) => !x.startsWith("--") && x !== flag("config"));
271
- const list = (await call(base, "GET", "/agents", { token: cfg.forgedock_token })).data?.agents ?? [];
291
+ const only = rest.find((x) => !x.startsWith("--") && x !== flag("config") && x !== flag("timeout"));
292
+ const now = rest.includes("--now"), wait = rest.includes("--wait");
293
+ const timeoutS = flag("timeout") === undefined ? 1800 : Number(flag("timeout"));
294
+ if (!Number.isFinite(timeoutS) || timeoutS < 0) throw new Error("usage: --timeout takes a number of seconds");
295
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
296
+ const clock = deps.now ?? Date.now;
297
+ const agentsNow = async () => (await call(base, "GET", "/agents", { token: cfg.forgedock_token })).data?.agents ?? [];
298
+ const list = await agentsNow();
272
299
  for (const a of list.filter((x) => !only || x.name === only)) {
273
- const r = await call(base, "POST", `/agents/${encodeURIComponent(a.name)}/upgrade`, { token: cfg.forgedock_token, timeoutMs: 30000 });
300
+ // The pool host is shared: upgrading restarts the agent under live sandboxes, so refuse unless asked (--wait drains, --now forces).
301
+ let active = a.active;
302
+ if (Number(active) > 0 && wait && !now) {
303
+ const deadline = clock() + timeoutS * 1000;
304
+ while (Number(active) > 0) {
305
+ if (clock() >= deadline) throw new Error(`${a.name}: still ${active} active sandbox(es) after ${timeoutS}s; not upgraded`);
306
+ await sleep(deps.pollMs ?? 10000);
307
+ active = (await agentsNow()).find((x) => x.name === a.name)?.active;
308
+ }
309
+ } else if (Number(active) > 0 && !now) {
310
+ throw new Error(`${a.name}: ${active} active sandbox(es) on this shared host; not upgraded. Use --wait to wait for idle, or --now to force.`);
311
+ }
312
+ const r = await call(base, "POST", `/agents/${encodeURIComponent(a.name)}/upgrade`, { body: now ? { force: true } : undefined, token: cfg.forgedock_token, timeoutMs: 30000 });
313
+ if (r.status === 409) throw new Error(`${a.name}: ${r.data?.active ?? "some"} active sandbox(es); not upgraded (HTTP 409)`);
274
314
  console.log(`${a.name}: HTTP ${r.status} ${JSON.stringify(r.data)}`);
275
315
  }
316
+ // R5: name the agents still on an older engine once the pushes are done (an agent restarts asynchronously, so this can lag briefly).
317
+ const behind = deps.leftBehind ? await deps.leftBehind(base, cfg) : deps.call ? [] : await (async () => { // a custom `call` seam is a fixture without /status
318
+ const get = (p) => httpCall(base, "GET", p, { token: cfg.forgedock_token }).catch(() => null);
319
+ const target = (await get("/version"))?.data?.version;
320
+ return agentsLeftBehind((await get("/status"))?.data?.agents, target).map((r) => ({ ...r, target }));
321
+ })();
322
+ if (behind.length) console.log(leftBehindLine(behind, behind[0].target));
276
323
  break;
277
324
  }
278
325
  case "remove": {
@@ -4,6 +4,9 @@ import { execFile } from "node:child_process";
4
4
  import { readFileSync } from "node:fs";
5
5
  import { PACKAGE_STORES } from "./cache-sweep.mjs";
6
6
 
7
+ /** #6047: the lane's CPU quota as env, for lanes whose cgroup files are hidden (read by quotaCores in lean/admission.mjs). */
8
+ export const cpuQuotaEnv = (cpus) => (Number.isFinite(cpus) && cpus > 0 ? { CS_CPU_QUOTA: String(cpus) } : {});
9
+
7
10
  /** #5757: work-dir and cache sweeps walk big trees (node_modules): 10 min, not the 120 s of a small rm. */
8
11
  export const SWEEP_TIMEOUT_MS = 10 * 60000;
9
12
  const SWEEP_SRC = new URL("./cache-sweep.mjs", import.meta.url);
@@ -29,6 +32,8 @@ export const dockerCli = {
29
32
  throw e;
30
33
  }
31
34
  },
35
+ /** #6117: copies `src` (a path inside container `name`, running or exited) into the host dir `dest`. */
36
+ async copyOut(name, src, dest) { await docker(["cp", `${name}:${src}`, dest], { timeoutMs: 60000 }); },
32
37
  async remove(name) { try { await docker(["rm", "-f", "-v", name], { timeoutMs: 60000 }); } catch (e) { if (!/No such container/i.test(e.stderr ?? "")) throw e; } },
33
38
  /** Signal the container's main process (the lane). False when the container is gone or already stopped. */
34
39
  async kill(name, signal = "TERM") {
@@ -0,0 +1,94 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #6091: engine-version aware placement (prefer the orchestrator's engine, execution.min_lane_engine gate), status skew, left-behind report.
4
+ import { test } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { createRouter } from "./router.mjs";
7
+ import { statusTable } from "./cli.mjs";
8
+ import { cmpVersion, agentsLeftBehind, upgradeAgentsAfterUpdate } from "./version.mjs";
9
+ import { tmpDir } from "../tests/_tmp.mjs";
10
+
11
+ const quiet = { info() {}, warn() {}, error() {} };
12
+ const json = (o, status = 200) => new Response(JSON.stringify(o), { status, headers: { "content-type": "application/json" } });
13
+ const spec = (id, extra = {}) => ({ id, issue: 1, batch: "b", repo: { slug: "o/x", url: "https://github.com/o/x.git" }, command: ["x"], ...extra });
14
+ const TARGET = "1.67.0"; // the router's own target: this repo's package.json version (asserted below)
15
+
16
+ // `old` has more free cpus, so capacity order alone would pick it.
17
+ function fixture({ oldFree = true, newFree = true } = {}) {
18
+ const posts = [];
19
+ const caps = { old: { version: "1.66.0", cpus_free: 8, mem_free_gb: 16 }, new: { version: TARGET, cpus_free: newFree ? 2 : 0, mem_free_gb: newFree ? 16 : 0 } };
20
+ if (!oldFree) caps.old = { version: "1.66.0", cpus_free: 0, mem_free_gb: 0 };
21
+ const fetchFn = async (url, init) => {
22
+ const u = new URL(url), h = u.hostname;
23
+ if (u.pathname === "/capacity") return json(caps[h]);
24
+ posts.push(`${h}${u.pathname}`);
25
+ return json({ id: JSON.parse(init.body).spec.id, state: "running" }, u.pathname === "/warm/claim" ? 200 : 201);
26
+ };
27
+ const router = createRouter({ state_dir: tmpDir("cs-eng-"), lane: { cpus: 2, mem_gb: 3 }, enroll_token: "e", forgedock_token: "fd", repo_root: process.cwd() }, { fetchFn, now: () => 5_000_000, log: quiet });
28
+ router.store.data.agents.old = { url: "http://old:7711", token: "t" };
29
+ router.store.data.agents.new = { url: "http://new:7711", token: "t" };
30
+ return { router, posts };
31
+ }
32
+ const target = async () => (await import("./version.mjs")).versionOf(process.cwd()).version;
33
+ test("fixture target is the router's target", async () => assert.equal(await target(), TARGET));
34
+
35
+ test("launch prefers the agent on the orchestrator engine over one with more free cpus", async () => {
36
+ const { router } = fixture();
37
+ const r = await router.launch(spec("l1"));
38
+ assert.equal(r.status, 201);
39
+ assert.equal(r.body.agent, "new");
40
+ });
41
+
42
+ test("only the old agent free and min_lane_engine unset: the lane runs there and says its engine", async () => {
43
+ const { router } = fixture({ newFree: false });
44
+ const r = await router.launch(spec("l2"));
45
+ assert.equal(r.status, 201);
46
+ assert.equal(r.body.agent, "old");
47
+ assert.equal(r.body.engine_version, "1.66.0");
48
+ });
49
+
50
+ test("min_lane_engine above the only free agent defers with pool.engine_old", async () => {
51
+ const { router, posts } = fixture({ newFree: false });
52
+ const r = await router.launch(spec("l3", { min_lane_engine: "1.67" }));
53
+ assert.equal(r.status, 503);
54
+ assert.equal(r.body.code, "pool.engine_old");
55
+ assert.ok(r.retryAfter > 0);
56
+ assert.deepEqual(posts, []);
57
+ });
58
+
59
+ test("claim follows the same order and gate", async () => {
60
+ const { router, posts } = fixture();
61
+ const c = await router.claim(spec("c1", { min_lane_engine: "1.67" }));
62
+ assert.equal(c.body.agent, "new");
63
+ assert.deepEqual(posts, ["new/warm/claim"]);
64
+ });
65
+
66
+ test("status carries each agent's engine and flags skew; statusTable shows it", async () => {
67
+ const { router } = fixture();
68
+ const s = await router.status();
69
+ const t = await target();
70
+ const old = s.agents.find((a) => a.name === "old");
71
+ assert.equal(old.engine_version, "1.66.0");
72
+ assert.equal(old.engine_skew, cmpVersion("1.66.0", t) < 0);
73
+ const table = statusTable([{ name: "a", ok: true, engine_version: "1.66.0", engine_skew: true }, { name: "b", ok: true, engine_version: TARGET, engine_skew: false }]);
74
+ assert.match(table, /ENGINE/);
75
+ assert.match(table, /1\.66\.0 SKEW/);
76
+ assert.doesNotMatch(table.split("\n")[2], /SKEW/);
77
+ assert.doesNotMatch(statusTable([{ name: "a", ok: true }]), /ENGINE/, "no version info: table as before");
78
+ });
79
+
80
+ test("cmpVersion is numeric, agents without a version never lag", () => {
81
+ assert.ok(cmpVersion("1.10.0", "1.9.9") > 0);
82
+ assert.equal(cmpVersion("1.67", "1.67.0"), 0);
83
+ assert.equal(cmpVersion(undefined, "1.67.0"), null);
84
+ assert.deepEqual(agentsLeftBehind([{ name: "a", ok: true, engine_version: "1.66.0" }, { name: "b", ok: true }, { name: "c", ok: true, engine_version: "1.67.0" }], "1.67.0"), [{ name: "a", version: "1.66.0" }]);
85
+ });
86
+
87
+ test("upgradeAgentsAfterUpdate names agents left behind and keeps its string result", async () => {
88
+ const warned = [], dir = tmpDir("cs-eng-cfg-"), cfgPath = `${dir}/router.json`;
89
+ (await import("node:fs")).writeFileSync(cfgPath, "{}");
90
+ const r = await upgradeAgentsAfterUpdate({ configPath: cfgPath, runPoolCli: async () => {}, warn: (m) => warned.push(m),
91
+ leftBehind: async () => ({ target: "1.67.0", rows: [{ name: "old", version: "1.66.0" }] }) });
92
+ assert.equal(r, "upgraded");
93
+ assert.match(warned[0], /left behind.*old 1\.66\.0/);
94
+ });
@@ -0,0 +1,24 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { readFileSync } from "node:fs";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ /**
7
+ * The lane image manifest (#6035, #6037): pool/image/manifest.json lists the tools the pool image ships. Plan-time preflight
8
+ * and the sandbox install path resolve a tool against it instead of probing or installing it. Pure apart from the file read.
9
+ */
10
+ export const MANIFEST_PATH = fileURLToPath(new URL("../../pool/image/manifest.json", import.meta.url));
11
+
12
+ /** {tools: [{name, binary, ...}]}; a missing or malformed file yields an empty manifest, never throws. */
13
+ export function loadImageManifest(path = MANIFEST_PATH) {
14
+ try {
15
+ const raw = JSON.parse(readFileSync(path, "utf8"));
16
+ return { tools: (Array.isArray(raw?.tools) ? raw.tools : []).filter((t) => t && typeof t.name === "string") };
17
+ } catch { return { tools: [] }; }
18
+ }
19
+
20
+ /** True when `tool` is the name or binary of a manifest entry. */
21
+ export function manifestProvides(manifest, tool) {
22
+ const t = String(tool ?? "");
23
+ return !!t && (manifest?.tools ?? []).some((e) => e.name === t || e.binary === t);
24
+ }
@@ -0,0 +1,20 @@
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 { join } from "node:path";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { loadImageManifest, manifestProvides } from "./image-manifest.mjs";
8
+
9
+ describe("#6037 image manifest", () => {
10
+ it("resolves names and binaries of the real manifest", () => {
11
+ const m = loadImageManifest();
12
+ for (const t of ["shellcheck", "yq", "psql", "python3.12", "xvfb-run"]) assert.ok(manifestProvides(m, t), t);
13
+ for (const t of ["vite", "promtool", "", undefined]) assert.ok(!manifestProvides(m, t), String(t));
14
+ });
15
+ it("a missing or malformed file gives an empty manifest", () => {
16
+ const d = tmpDir("imgm");
17
+ assert.deepEqual(loadImageManifest(join(d, "nope.json")), { tools: [] });
18
+ assert.ok(!manifestProvides(loadImageManifest(join(d, "nope.json")), "yq"));
19
+ });
20
+ });
@@ -0,0 +1,41 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #6061: the per-worker lane target. Same AIMD thresholds as the orchestrator controller (bin/lean/concurrency.mjs, imported):
5
+ * +1 while free memory is above floor + headroom and load per core is green for a hold window, halve (min 1) on load above
6
+ * 1.5/core or low memory, never above the configured ceiling. `drainState` says when the worker accepts no new lane (running
7
+ * lanes always finish). Pure: the caller keeps `greenSince` / busy timers and feeds the clock.
8
+ */
9
+ import { LOAD_GREEN, LOAD_HALVE, MEM_FLOOR_GB, MEM_HEADROOM_GB } from "../lean/concurrency.mjs";
10
+
11
+ export const GREEN_HOLD_MS = 60_000;
12
+ export const DRAIN_AFTER_MS = 5 * 60_000;
13
+ const fin = (v) => typeof v === "number" && Number.isFinite(v);
14
+
15
+ /** Is the host over its pressure line (load above 1.5/core or free memory under the floor)? Unknown figures are not pressure. */
16
+ export const pressured = (live, { memFloorGb = MEM_FLOOR_GB } = {}) =>
17
+ (fin(live?.load_per_core) && live.load_per_core > LOAD_HALVE) || (fin(live?.mem_available_gb) && live.mem_available_gb < memFloorGb);
18
+
19
+ /** Next `{ target, greenSince, change }` (change: "grow" | "halve" | null). `refused` (a pool.* refusal) also halves. */
20
+ export function step({ target, ceiling, live, refused = false, now = Date.now(), greenSince = null, holdMs = GREEN_HOLD_MS, memFloorGb = MEM_FLOOR_GB, memHeadroomGb = MEM_HEADROOM_GB } = {}) {
21
+ const top = Math.max(1, Number.isInteger(ceiling) ? ceiling : 1);
22
+ const t = Math.min(top, Math.max(1, Number.isInteger(target) ? target : 1));
23
+ if (refused || pressured(live, { memFloorGb })) {
24
+ const next = Math.max(1, Math.floor(t / 2));
25
+ return { target: next, greenSince: null, change: next < t ? "halve" : null };
26
+ }
27
+ const green = fin(live?.load_per_core) && live.load_per_core < LOAD_GREEN && fin(live?.mem_available_gb) && live.mem_available_gb > memFloorGb + memHeadroomGb;
28
+ if (!green) return { target: t, greenSince: null, change: null };
29
+ const since = greenSince ?? now;
30
+ if (t < top && now - since >= holdMs) return { target: t + 1, greenSince: now, change: "grow" }; // each step needs a fresh hold window
31
+ return { target: t, greenSince: since, change: null };
32
+ }
33
+
34
+ /** `{ draining, reason }`: paused (owner, policy or config), or the host busy for `drainAfterMs`. */
35
+ export function drainState({ paused = false, ownerPaused = false, policyPaused = false, busyForMs = 0, drainAfterMs = DRAIN_AFTER_MS } = {}) {
36
+ if (ownerPaused) return { draining: true, reason: "paused by owner" };
37
+ if (policyPaused) return { draining: true, reason: "paused by policy" };
38
+ if (paused) return { draining: true, reason: "paused" };
39
+ if (busyForMs >= drainAfterMs) return { draining: true, reason: `host busy for ${Math.round(busyForMs / 60000)}m` };
40
+ return { draining: false, reason: null };
41
+ }