forgedock 1.59.1 → 1.60.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 (94) hide show
  1. package/bin/engine/outcome-codes.mjs +3 -3
  2. package/bin/engine-cli.mjs +50 -10
  3. package/bin/labels.json +5 -0
  4. package/bin/lean/batch.mjs +21 -2
  5. package/bin/lean/batch.test.mjs +116 -1
  6. package/bin/lean/conformance.mjs +12 -5
  7. package/bin/lean/conformance.test.mjs +30 -2
  8. package/bin/lean/depcache.mjs +34 -15
  9. package/bin/lean/depcache.test.mjs +100 -1
  10. package/bin/lean/design-gate.mjs +15 -10
  11. package/bin/lean/design-gate.test.mjs +21 -0
  12. package/bin/lean/effects.mjs +18 -2
  13. package/bin/lean/execution.mjs +23 -5
  14. package/bin/lean/execution.test.mjs +81 -1
  15. package/bin/lean/gatewatch.test.mjs +5 -5
  16. package/bin/lean/issuewatch-triage.mjs +68 -0
  17. package/bin/lean/issuewatch-triage.test.mjs +98 -0
  18. package/bin/lean/issuewatch.mjs +34 -6
  19. package/bin/lean/issuewatch.test.mjs +11 -0
  20. package/bin/lean/lanelock.mjs +5 -4
  21. package/bin/lean/lean.mjs +123 -17
  22. package/bin/lean/lean.test.mjs +154 -6
  23. package/bin/lean/orchestrate-cancel.test.mjs +33 -0
  24. package/bin/lean/orchestrate-hostfallback.test.mjs +41 -0
  25. package/bin/lean/orchestrate-recovering.test.mjs +42 -0
  26. package/bin/lean/orchestrate.mjs +23 -10
  27. package/bin/lean/pagegate.mjs +50 -12
  28. package/bin/lean/pagegate.test.mjs +38 -1
  29. package/bin/lean/phaseledger.mjs +65 -2
  30. package/bin/lean/phaseledger.test.mjs +70 -2
  31. package/bin/lean/preflight.mjs +5 -2
  32. package/bin/lean/preflight.test.mjs +7 -0
  33. package/bin/lean/prompts.mjs +2 -1
  34. package/bin/lean/recovery.test.mjs +11 -6
  35. package/bin/lean/release-classify.mjs +143 -0
  36. package/bin/lean/release-classify.test.mjs +130 -0
  37. package/bin/lean/release-conductor.mjs +163 -0
  38. package/bin/lean/release-conductor.test.mjs +194 -0
  39. package/bin/lean/release-config.mjs +60 -8
  40. package/bin/lean/release-config.test.mjs +43 -1
  41. package/bin/lean/release-control.mjs +22 -5
  42. package/bin/lean/release-control.test.mjs +22 -0
  43. package/bin/lean/release-credentials.mjs +40 -0
  44. package/bin/lean/release-credentials.test.mjs +42 -0
  45. package/bin/lean/release-deploy.mjs +3 -3
  46. package/bin/lean/release-deploy.test.mjs +8 -0
  47. package/bin/lean/release-docs.test.mjs +93 -0
  48. package/bin/lean/release-fence.mjs +2 -0
  49. package/bin/lean/release-gate.mjs +88 -0
  50. package/bin/lean/release-gate.test.mjs +116 -0
  51. package/bin/lean/release-gates.mjs +5 -1
  52. package/bin/lean/release-ledger.mjs +47 -1
  53. package/bin/lean/release-ledger.test.mjs +33 -1
  54. package/bin/lean/release-mergeback.mjs +148 -0
  55. package/bin/lean/release-mergeback.test.mjs +129 -0
  56. package/bin/lean/release-p0.mjs +193 -0
  57. package/bin/lean/release-p0.test.mjs +127 -0
  58. package/bin/lean/release-plan.mjs +267 -0
  59. package/bin/lean/release-plan.test.mjs +202 -0
  60. package/bin/lean/release-preflight.mjs +16 -0
  61. package/bin/lean/release-regate.mjs +141 -0
  62. package/bin/lean/release-regate.test.mjs +149 -0
  63. package/bin/lean/release-review.mjs +5 -3
  64. package/bin/lean/release-rollback.mjs +277 -0
  65. package/bin/lean/release-rollback.test.mjs +245 -0
  66. package/bin/lean/release-snapshot.mjs +48 -9
  67. package/bin/lean/release-snapshot.test.mjs +43 -1
  68. package/bin/lean/release-start.mjs +164 -0
  69. package/bin/lean/release-start.test.mjs +171 -0
  70. package/bin/lean/release-status.mjs +6 -2
  71. package/bin/lean/release-train.mjs +159 -0
  72. package/bin/lean/release-train.test.mjs +139 -0
  73. package/bin/lean/release.mjs +127 -5
  74. package/bin/lean/release.test.mjs +80 -0
  75. package/bin/lean/sandbox-remote.mjs +2 -0
  76. package/bin/lean/schedd-load.test.mjs +82 -0
  77. package/bin/lean/schedd.mjs +67 -31
  78. package/bin/lean/schedd.test.mjs +80 -1
  79. package/bin/lean/validate-catalog.mjs +94 -0
  80. package/bin/lean/validate-catalog.test.mjs +42 -0
  81. package/bin/pool/agent.mjs +4 -1
  82. package/bin/pool/lane-tools.mjs +115 -0
  83. package/bin/pool/lane-tools.test.mjs +26 -0
  84. package/bin/pool/warm.mjs +1 -1
  85. package/docs/CONFIG.md +225 -1
  86. package/docs/ISSUE-WATCH.md +1 -0
  87. package/docs/design/visual-gate.md +10 -0
  88. package/docs/eval/adversarial-bench.md +1 -0
  89. package/package.json +5 -2
  90. package/pool/README.md +2 -0
  91. package/scripts/bench-adversarial.mjs +4 -0
  92. package/scripts/bench-lightlane.mjs +2 -1
  93. package/templates/github-actions/forge-conductor.scopes.json +7 -0
  94. package/templates/github-actions/forge-conductor.yml +57 -0
@@ -52,6 +52,7 @@ import { schedDir, pidAlive } from "./sched.mjs";
52
52
  import { DEFAULT_STALL_MIN, FIRST_HOUR_FILE, FIRST_HOUR_MIN, evaluateDispatchStall, firstHourReport, recordStallAlert, writeFirstHour } from "./batch-health.mjs";
53
53
  import { HEARTBEAT_MS, writeHeartbeat, clearHeartbeat } from "./schedd-health.mjs";
54
54
  import { batchRoot, listBatches, openBatch, SECRET_ENV } from "./batch.mjs";
55
+ import { killTrackedChildren } from "./effects.mjs";
55
56
  import { applySetExecution } from "./live-execution.mjs";
56
57
  import { liveOverload } from "./hostload.mjs";
57
58
 
@@ -62,6 +63,7 @@ export function sharedPendingLines(batches) {
62
63
  return [...shared].filter(([, ids]) => ids.length > 1).map(([n, ids]) => `schedd: warning: #${n} is pending in ${ids.length} batches (${ids.join(", ")}); only one should run it`);
63
64
  }
64
65
 
66
+ export const ORPHAN_AGE_MS = 7 * 24 * 3600 * 1000; // #5469: an unhosted batch idle this long with pending issues is orphaned
65
67
  export const IDLE_MS = 10 * 60 * 1000;
66
68
  export const STOP_MS = 10 * 1000;
67
69
  export const LOCK_CHECK_MS = 5 * 1000;
@@ -74,18 +76,26 @@ export const REQUEST_MS = 15 * 1000; // #4775: default bound of a control/status
74
76
  */
75
77
  export function findUnhosted(root, { isHosted = () => false, now = Date.now(), minAgeMs = ORPHAN_AGE_MS } = {}) {
76
78
  const unhosted = [], orphaned = [];
77
- for (const id of listBatches(root)) {
78
- if (isHosted(id)) continue;
79
- try {
80
- const b = openBatch(root, id), pending = b.pendingIssues();
81
- if (!pending.length || b.readCancel()) continue;
82
- const last = b.lastProgressMs();
83
- (last !== null && now - last > minAgeMs ? orphaned : unhosted).push({ id, pending });
84
- } catch { /* advisory */ }
85
- }
79
+ for (const id of listBatches(root)) classifyUnhosted(root, id, { isHosted, now, minAgeMs, unhosted, orphaned });
86
80
  return { unhosted, orphaned };
87
81
  }
88
- export const ORPHAN_AGE_MS = 7 * 24 * 3600 * 1000; // #5469: an unhosted batch idle this long with pending issues is orphaned
82
+ function classifyUnhosted(root, id, { isHosted, now, minAgeMs, unhosted, orphaned }) {
83
+ if (isHosted(id)) return;
84
+ try {
85
+ const b = openBatch(root, id), pending = b.pendingIssues();
86
+ if (!pending.length || b.readCancel()) return;
87
+ const last = b.lastProgressMs();
88
+ (last !== null && now - last > minAgeMs ? orphaned : unhosted).push({ id, pending });
89
+ } catch { /* advisory */ }
90
+ }
91
+ export const yieldLoop = () => new Promise((r) => setImmediate(r));
92
+ /** #5531: `findUnhosted` that yields to the event loop after every batch, so a long history never occupies one loop turn. */
93
+ export async function findUnhostedAsync(root, { isHosted = () => false, now = Date.now(), minAgeMs = ORPHAN_AGE_MS } = {}) {
94
+ const unhosted = [], orphaned = [];
95
+ for (const id of listBatches(root)) { classifyUnhosted(root, id, { isHosted, now, minAgeMs, unhosted, orphaned }); await yieldLoop(); }
96
+ return { unhosted, orphaned };
97
+ }
98
+ export const ABANDON_AGE_MS = 14 * 24 * 3600 * 1000; // #5531: an unhosted batch with pending issues and no progress for this long is re-hosted (when ready) or abandoned
89
99
  export const UNIT = "forgedock-schedd";
90
100
  export const DUE_MS = 15 * 60 * 1000; // #4627: how often the due callback (windowed post-deploy monitoring) runs while the daemon is up
91
101
 
@@ -180,6 +190,7 @@ function takeLock(lock, pid, alive) {
180
190
  export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(process.env.FORGEDOCK_SCHEDD_IDLE_MS) || IDLE_MS,
181
191
  root = batchRoot(), log = (m) => console.log(m), pid = process.pid, alive = pidAlive, resumeOnStart = true, stopMs = STOP_MS,
182
192
  lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, stallCheckMs = Number(process.env.FORGEDOCK_SCHEDD_STALL_CHECK_MS) || 60_000, stallMin = Number(process.env.FORGEDOCK_SCHEDD_STALL_MIN) || DEFAULT_STALL_MIN, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
193
+ abandonMs = (Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) > 0 ? Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) * 24 * 3600 * 1000 : ABANDON_AGE_MS), killChildren = killTrackedChildren,
183
194
  hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined } = {}) {
184
195
  const p = scheddPaths(dir);
185
196
  // #5204: default handover target: a new daemon from the (new) install unless systemd restarts the unit itself
@@ -200,9 +211,14 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
200
211
  const runs = new Map(); // every runBatch in flight (hosted or not yet started) -> its AbortController (#4454)
201
212
  const starting = new Map(); // batch id -> host() promise of a start-up resume not yet hosted (#4503: an attach waits for it)
202
213
  let closing = null, resolveClosed, keepSock = false;
214
+ let idleTimer, lockTimer, lagTimer, stallTimer, dueTimer; // assigned below; close() clears them
203
215
  let lastActive = Date.now();
204
216
  const touch = () => { lastActive = Date.now(); };
205
217
  let lastTick = Date.now();
218
+ let lastPhase = { name: "idle", at: Date.now() };
219
+ const phase = (name) => { lastPhase = { name, at: Date.now() }; };
220
+ // #5531: long-unhosted batches this daemon abandoned (cancel reason "abandoned") or re-hosted; the next `status` reports each once
221
+ const lateReport = { abandoned: [], rehosted: [] };
206
222
 
207
223
  /** Run one batch here. Resolves with {id, dir} once the batch exists, rejects when it fails before that. */
208
224
  const host = ({ argv, cwd, env, keepBreaker = false }, first = null) => new Promise((resolve, reject) => {
@@ -231,7 +247,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
231
247
 
232
248
  // #4917: a batch that ended with a deferred issue still waiting (no report) is re-hosted once its retry-at is near, without a restart
233
249
  const rehostTimers = new Set();
234
- const rehostLater = (id) => {
250
+ function rehostLater(id) {
235
251
  if (closing) return;
236
252
  let b, st;
237
253
  try { b = openBatch(root, id); if (b.readReport() || b.readCancel() || !b.pendingIssues().length) return; st = b.store.load(); } catch { return; }
@@ -249,13 +265,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
249
265
  }, Math.min(60_000, Math.max(1000, at - Date.now())));
250
266
  t.unref?.();
251
267
  rehostTimers.add(t);
252
- };
268
+ }
253
269
 
254
270
  // #5242: an add/requeue that landed while the runner was past its dispatch loop (still "hosted", no longer draining) is
255
271
  // dispatched by re-hosting the batch once the run has ended. Once per distinct set of unrun entries, so an add that cannot
256
272
  // drain (a cancel, a tripped breaker) never loops.
257
273
  const rehostedUnrun = new Map();
258
- const rehostUnrun = (id) => {
274
+ function rehostUnrun(id) {
259
275
  if (closing || hosted.has(id) || starting.has(id)) return;
260
276
  let sig;
261
277
  try {
@@ -272,7 +288,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
272
288
  const started = host({ argv: ["--resume", id], cwd: process.cwd(), env: {}, keepBreaker: true });
273
289
  starting.set(id, started);
274
290
  started.catch((e) => log(`schedd: re-host ${id} failed: ${e?.message ?? e}`)).finally(() => starting.delete(id));
275
- };
291
+ }
276
292
 
277
293
  /** #4775: wait for a batch start at most `admitMs`; the start itself goes on (a second host() would duplicate the batch). */
278
294
  const bound = (p, what) => {
@@ -282,12 +298,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
282
298
  const hostBounded = (args, first = null, what = "batch") => bound(host(args, first), what);
283
299
 
284
300
  /** #4775: per batch id, last progress and pending adds: every hosted batch, plus any daemon batch holding adds it never took. */
285
- const statusBatches = () => {
301
+ const statusBatches = async () => {
286
302
  const now = Date.now(), out = [];
287
303
  const ids = new Set(hosted.keys());
288
304
  for (const id of starting.keys()) ids.add(id);
289
- try { for (const id of listBatches(root)) if (!ids.has(id) && openBatch(root, id).readPlan()?.daemon) ids.add(id); } catch { /* unreadable root */ }
305
+ try { for (const id of listBatches(root)) { if (!ids.has(id)) { const b = openBatch(root, id); if (!b.isTerminal() && b.readPlan()?.daemon) ids.add(id); await yieldLoop(); } } } catch { /* unreadable root */ }
290
306
  for (const id of [...ids].sort()) {
307
+ await yieldLoop();
291
308
  const isHosted = hosted.has(id) || starting.has(id);
292
309
  let last = null, pending = [], pend = [];
293
310
  try { const b = openBatch(root, id); last = b.lastProgressMs(); pending = b.unrunAdds(); pend = b.pendingIssues(); } catch { /* a half-written batch */ }
@@ -297,15 +314,16 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
297
314
  return out;
298
315
  };
299
316
 
300
- const unhostedBatches = (now, minAgeMs = ORPHAN_AGE_MS) => findUnhosted(root, { isHosted: (id) => hosted.has(id) || starting.has(id), now, minAgeMs });
317
+ const unhostedBatches = (now, minAgeMs = ORPHAN_AGE_MS) => findUnhostedAsync(root, { isHosted: (id) => hosted.has(id) || starting.has(id), now, minAgeMs });
301
318
 
302
319
  const handle = async (req, send) => {
303
320
  if (req.op === "status") {
304
321
  // #4917: a batch dir that still holds pending issues but is not hosted (finalised early, or never resumed)
305
322
  // #5469: ones idle longer than ORPHAN_AGE_MS collapse into `orphaned` (one line; `orchestrate --gc-orphans` cancels them)
306
- const { unhosted, orphaned } = unhostedBatches(Date.now());
323
+ phase("status");
324
+ const { unhosted, orphaned } = await unhostedBatches(Date.now());
307
325
  let host = null; try { host = hostLoad?.() ?? null; } catch { host = null; } // #5174
308
- return send({ type: "status", pid, lastTick, batches: statusBatches(), unhosted, orphaned, host }, true);
326
+ return send({ type: "status", pid, lastTick, batches: await statusBatches(), unhosted, orphaned, abandoned: lateReport.abandoned.splice(0), rehosted: lateReport.rehosted.splice(0), host }, true);
309
327
  }
310
328
  if (req.op === "set-parallel") {
311
329
  const b = openBatch(root, req.id);
@@ -425,6 +443,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
425
443
  for (const t of rehostTimers) clearTimeout(t);
426
444
  if (dueTimer) clearInterval(dueTimer);
427
445
  for (const c of conns) c.destroy();
446
+ try { const n = killChildren?.(); if (n) log(`schedd: killed ${n} child process(es) of its own`); } catch { /* best effort */ } // #5531: lanes survive, the daemon's own gh/script children do not
428
447
  const stopping = [...runs.keys()];
429
448
  for (const ac of runs.values()) ac.abort();
430
449
  let timer;
@@ -441,7 +460,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
441
460
  });
442
461
  return closing;
443
462
  };
444
- const idleTimer = setInterval(() => {
463
+ idleTimer = setInterval(() => {
445
464
  if (!hosted.size && !conns.size && Date.now() - lastActive >= idleMs) { log("schedd: idle, exiting"); close(); }
446
465
  }, Math.min(idleMs, 30_000));
447
466
  idleTimer.unref?.();
@@ -449,7 +468,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
449
468
  const versionOf = () => { try { return installedVersion?.() ?? null; } catch { return null; } };
450
469
  const loadedVersion = versionOf();
451
470
  // #4503: a daemon whose lock or socket was taken stops (its batches stay resumable) instead of running unreachable.
452
- const lockTimer = setInterval(() => {
471
+ lockTimer = setInterval(() => {
453
472
  if (closing) return;
454
473
  const now = loadedVersion ? versionOf() : null;
455
474
  if (now && now !== loadedVersion) {
@@ -465,46 +484,63 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
465
484
  lockTimer.unref?.();
466
485
  // #4775: an event loop starved by host load leaves sockets unanswered and children unreaped; leave a trace of it.
467
486
  let lagAt = Date.now(), lagLogged = 0;
468
- const lagTimer = setInterval(() => {
487
+ lagTimer = setInterval(() => {
469
488
  const now = Date.now(), lag = now - lagAt - 1000;
470
489
  lagAt = now;
471
- if (lag >= lagMs && now - lagLogged >= 60_000) { lagLogged = now; log(`schedd: event loop stalled ${Math.round(lag / 1000)}s (host overloaded?)`); }
490
+ if (lag >= lagMs && now - lagLogged >= 60_000) { lagLogged = now; log(`schedd: event loop stalled ${Math.round(lag / 1000)}s (host overloaded?; last phase: ${lastPhase.name}, started ${Math.round((now - lastPhase.at) / 1000)}s ago)`); }
472
491
  }, 1000);
473
492
  lagTimer.unref?.();
474
493
  // #5314: a batch with ready issues, free lanes and no dispatch for `stallMin` is re-hosted once per ready set, else one needs-you
475
494
  // alert is recorded (health.json, status, sched show); every batch also gets its first-hour report once, without operator action.
476
495
  const rehostedStall = new Map();
477
- const watchBatches = () => {
478
- if (closing) return;
496
+ let watching = false;
497
+ const watchBatches = async () => {
498
+ if (closing || watching) return;
499
+ watching = true;
500
+ phase("watch");
501
+ try { await watchPass(); } finally { watching = false; phase("idle"); }
502
+ };
503
+ async function watchPass() {
479
504
  const now = Date.now();
480
505
  for (const id of listBatches(root)) {
506
+ await yieldLoop(); // #5531: one batch per loop turn, so status and dispatch are never starved by a long history
507
+ if (closing) return;
481
508
  try {
482
509
  const b = openBatch(root, id), plan = b.readPlan();
483
510
  if (!plan?.daemon) continue;
484
- const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.load(), created = Date.parse(plan.created ?? "");
485
- const isHosted = hosted.has(id) || starting.has(id);
511
+ const created = Date.parse(plan.created ?? "");
512
+ if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
513
+ const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
486
514
  const stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported });
487
515
  if (Number.isFinite(created) && (reported || now - created >= FIRST_HOUR_MIN * 60_000) && !existsSync(join(b.dir, FIRST_HOUR_FILE)) && now - created < 24 * 3600_000) {
488
516
  if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), holdInfo: b.readHoldInfo?.() ?? null, stall }))) log(`schedd: first-hour report written for batch ${id}`);
489
517
  }
518
+ const sig = stall ? stall.ready.join(",") : "";
519
+ const last = b.lastProgressMs();
520
+ if (!isHosted && !cancelled && !reported && state?.pending?.length && last !== null && now - last > abandonMs && (!stall || rehostedStall.get(id) === sig)) {
521
+ b.requestCancel({ reason: "abandoned" }); // #5531: idle past N days and not re-hostable: marked once (the cancel file ends the scan for it)
522
+ lateReport.abandoned.push(id);
523
+ log(`schedd: batch ${id} abandoned (not hosted, ${state.pending.length} pending, no progress for ${Math.round((now - last) / 86400_000)} days)`);
524
+ continue;
525
+ }
490
526
  if (!stall) continue;
491
- const sig = stall.ready.join(",");
492
527
  if (!isHosted && rehostedStall.get(id) !== sig) {
493
528
  rehostedStall.set(id, sig);
494
529
  log(`schedd: re-hosting batch ${id} (${stall.detail})`);
530
+ if (last !== null && now - last > abandonMs) lateReport.rehosted.push(id); // #5531
495
531
  const started = host({ argv: ["--resume", id], cwd: process.cwd(), env: {}, keepBreaker: true });
496
532
  starting.set(id, started);
497
533
  started.catch((e) => { log(`schedd: re-host ${id} failed: ${e?.message ?? e}`); recordStallAlert(b, stall); }).finally(() => starting.delete(id));
498
534
  } else if (recordStallAlert(b, stall)) log(`schedd: batch ${id} needs you: ${stall.detail}`);
499
535
  } catch { /* advisory: one unreadable batch never stops the watchdog */ }
500
536
  }
501
- };
502
- const stallTimer = setInterval(watchBatches, stallCheckMs);
537
+ }
538
+ stallTimer = setInterval(() => { watchBatches().catch(() => {}); }, stallCheckMs);
503
539
  stallTimer.unref?.();
504
540
 
505
541
  // #4627: windowed post-deploy checks. One run at a time; a failure is logged and never stops the daemon.
506
542
  let dueRunning = false;
507
- const dueTimer = due ? setInterval(async () => {
543
+ dueTimer = due ? setInterval(async () => {
508
544
  if (closing || dueRunning) return;
509
545
  dueRunning = true;
510
546
  try { await due(); } catch (e) { log(`schedd: due run failed: ${e?.message ?? e}`); } finally { dueRunning = false; }
@@ -7,7 +7,8 @@ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, utime
7
7
  import { homedir, tmpdir } from "node:os";
8
8
  import { join } from "node:path";
9
9
  import { tmpDir } from "../tests/_tmp.mjs";
10
- import { openBatch, isLaneAlive, listBatches, SECRET_ENV } from "./batch.mjs";
10
+ import { openBatch, isLaneAlive, listBatches, SECRET_ENV, scanStats } from "./batch.mjs";
11
+ import { killTrackedChildren, runWithInput, trackedChildCount } from "./effects.mjs";
11
12
  import { findUnhosted, startDaemon, scheddPaths, connectDaemon, request, unitState, SCHEDD_SCRIPT, mergeEnv, batchEnv, droppedEnv, sanitizePath, redactEnv, exitOnSignals, readInstalledVersion } from "./schedd.mjs";
12
13
  import { schedDir } from "./sched.mjs";
13
14
  import { readHeartbeat } from "./schedd-health.mjs";
@@ -1000,3 +1001,81 @@ describe("#5469: orphaned batches", () => {
1000
1001
  assert.deepEqual(r.unhosted, [{ id: "recent", pending: [1] }]);
1001
1002
  });
1002
1003
  });
1004
+
1005
+ describe("schedd scans stay off the loop (#5531)", () => {
1006
+ const mk = (root, id, state, ageDays = 0) => {
1007
+ const b = openBatch(root, id);
1008
+ b.writePlan({ daemon: true, repo: "o/r", created: new Date(Date.now() - (ageDays + 1) * 86400000).toISOString() });
1009
+ b.store.save(state);
1010
+ if (ageDays) { const old = new Date(Date.now() - ageDays * 86400000); utimesSync(join(b.dir, "state.json"), old, old); }
1011
+ return b;
1012
+ };
1013
+
1014
+ it("#5531: status and watchdog scans yield and parse each batch state once", async () => {
1015
+ const dir = tmpDir("schedd-scan-"), root = join(dir, "batches");
1016
+ for (let i = 0; i < 60; i++) mk(root, `b20261031-000000-${5000 + i}`, { v: 1, order: [1], results: {}, running: {}, pending: [], parallel: 1 }, 1);
1017
+ const d = await startDaemon({ dir, root, runBatch: async () => {}, log: () => {}, resumeOnStart: false });
1018
+ try {
1019
+ const sock = await connectDaemon({ dir, spawnDaemon: null });
1020
+ let ticks = 0, stop = false;
1021
+ const spin = () => { if (!stop) { ticks++; setImmediate(spin); } };
1022
+ spin();
1023
+ const before = scanStats.parses;
1024
+ const st = await request(sock, { op: "status" });
1025
+ stop = true;
1026
+ assert.equal(st.type, "status");
1027
+ assert.ok(ticks >= 60, `loop turned ${ticks} times during the scan (one yield per batch expected)`);
1028
+ assert.ok(scanStats.parses - before <= 60, `parsed ${scanStats.parses - before} states for 60 batches`);
1029
+ const mid = scanStats.parses;
1030
+ await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "status" });
1031
+ assert.equal(scanStats.parses, mid, "unchanged files are not parsed again");
1032
+ } finally { await d.close(); }
1033
+ });
1034
+
1035
+ it("#5531: close kills the daemon's own tracked child processes", async () => {
1036
+ const dir = tmpDir("schedd-kill-"), root = join(dir, "batches");
1037
+ let called = 0;
1038
+ const d = await startDaemon({ dir, root, runBatch: async () => {}, log: () => {}, resumeOnStart: false, killChildren: () => { called++; return 0; } });
1039
+ await d.close();
1040
+ assert.equal(called, 1);
1041
+ const p = runWithInput("sleep", ["30"], "").catch((e) => e);
1042
+ await until(() => trackedChildCount() === 1, 5000);
1043
+ assert.equal(killTrackedChildren(), 1);
1044
+ assert.ok((await p) instanceof Error, "the killed child rejects");
1045
+ assert.equal(trackedChildCount(), 0);
1046
+ });
1047
+
1048
+ it("#5531: long-unhosted batch abandoned once", async () => {
1049
+ const dir = tmpDir("schedd-abandon-"), root = join(dir, "batches");
1050
+ const blocked = mk(root, "b20261001-000000-6001", { v: 1, order: [2, 9], results: {}, running: {}, pending: [2], deps: { 2: [9] }, parallel: 1 }, 20);
1051
+ const logs = [], calls = [];
1052
+ const d = await startDaemon({ dir, root, runBatch: async ({ argv }) => { calls.push(argv); }, log: (l) => logs.push(l), resumeOnStart: false, stallCheckMs: 50, stallMin: 10 });
1053
+ try {
1054
+ await until(() => blocked.readCancel()?.reason === "abandoned", 8000);
1055
+ await new Promise((r) => setTimeout(r, 300));
1056
+ assert.equal(logs.filter((l) => /abandoned/.test(l)).length, 1, "reported once");
1057
+ assert.equal(calls.length, 0, "nothing ready: not re-hosted");
1058
+ const st = await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "status" });
1059
+ assert.deepEqual(st.abandoned, [blocked.id]);
1060
+ const again = await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "status" });
1061
+ assert.deepEqual(again.abandoned, [], "status reports an abandoned batch once");
1062
+ } finally { await d.close(); }
1063
+ });
1064
+
1065
+ it("#5531: long-unhosted batch with a ready issue is re-hosted, not abandoned", async () => {
1066
+ const dir = tmpDir("schedd-rehost-old-"), root = join(dir, "batches");
1067
+ const ready = mk(root, "b20261001-000000-6002", { v: 1, order: [3], results: {}, running: {}, pending: [3], parallel: 1 }, 20);
1068
+ const calls = [];
1069
+ const runBatch = async ({ argv, sink }) => { calls.push(argv); sink.batch({ id: ready.id, dir: ready.dir }); return await new Promise(() => {}); };
1070
+ const d = await startDaemon({ dir, root, runBatch, log: () => {}, resumeOnStart: false, stallCheckMs: 50, stallMin: 10 });
1071
+ try {
1072
+ await until(() => calls.length === 1, 8000);
1073
+ await new Promise((r) => setTimeout(r, 300));
1074
+ assert.deepEqual(calls[0], ["--resume", ready.id]);
1075
+ assert.equal(ready.readCancel(), null);
1076
+ const st = await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "status" });
1077
+ assert.deepEqual(st.rehosted, [ready.id]);
1078
+ assert.deepEqual((await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "status" })).rehosted, [], "reported once");
1079
+ } finally { await d.close(); }
1080
+ });
1081
+ });
@@ -0,0 +1,94 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5653: deterministic helpers for validate-command executability (0 LLM calls). A catalogue of rewrite entries
5
+ * ({match, replace}, the shape of forge.yaml `validate.recipes`) is derived from the commands the repo's own CI runs;
6
+ * forge.yaml recipes always come first. Also: test-id extraction and the equivalent-substitute verdict, and the
7
+ * base-drift classifier. Pure; lean.mjs owns every effect.
8
+ */
9
+
10
+ /** Default CI sources read for the derived catalogue (repo-relative). */
11
+ export const DEFAULT_CATALOG_SOURCES = [".github/workflows/ci.yml", "scripts/ci-local.sh"];
12
+
13
+ const PY_RUNNER_RE = /\b(uv run(?: +--[\w-]+(?:[ =][^\s|&;-][^\s|&;]*)?)* +)(?:python3? +-m +)?pytest\b/; // an option value never starts with "-" (no ambiguous backtracking)
14
+ const JS_RUNNER_RE = /\b(pnpm exec|npx|yarn) +(vitest|jest)\b/;
15
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
16
+
17
+ /**
18
+ * Entries derived from CI text: the repo's own pytest runner prefix replaces `poetry run pytest` / bare `.venv/bin/pytest`
19
+ * a plan guessed, and its own JS runner replaces another one. Empty when CI shows no such runner.
20
+ */
21
+ export function deriveCatalog(texts) {
22
+ const text = (Array.isArray(texts) ? texts : [texts]).filter((t) => typeof t === "string").join("\n");
23
+ const out = [];
24
+ const py = PY_RUNNER_RE.exec(text);
25
+ if (py) {
26
+ const prefix = py[1].trim();
27
+ out.push({ match: "\\bpoetry run (?:python3? -m )?pytest\\b", replace: `${prefix} pytest` });
28
+ out.push({ match: "(?:\\./)?(?:[\\w./-]*/)?\\.venv/bin/pytest\\b", replace: `${prefix} pytest` });
29
+ }
30
+ const js = JS_RUNNER_RE.exec(text);
31
+ if (js) {
32
+ const alt = ["pnpm exec", "npx", "yarn"].filter((r) => r !== js[1]);
33
+ out.push({ match: `\\b(?:${alt.map(esc).join("|")}) +(vitest|jest)\\b`, replace: `${js[1]} $1` });
34
+ }
35
+ return out;
36
+ }
37
+
38
+ /** forge.yaml recipes first, derived entries after, one entry per `match`. */
39
+ export function mergeRecipes(recipes, derived) {
40
+ const seen = new Set(), out = [];
41
+ for (const r of [...(Array.isArray(recipes) ? recipes : []), ...(Array.isArray(derived) ? derived : [])]) {
42
+ if (!r || !r.match || seen.has(String(r.match))) continue;
43
+ seen.add(String(r.match)); out.push(r);
44
+ }
45
+ return out;
46
+ }
47
+
48
+ /**
49
+ * Rewrite only the commands of `ids` (the ones preflight found unrunnable) from `entries`. `apply` is applyValidateRecipes.
50
+ * Returns {contract, applied[{id, from, to}]}; the contract is the input when nothing changed.
51
+ */
52
+ export function rewriteMissed(contract, entries, ids, apply) {
53
+ const want = new Set(ids ?? []);
54
+ if (!want.size || !entries?.length || !contract || typeof contract !== "object") return { contract, applied: [] };
55
+ const r = apply(contract, entries);
56
+ const applied = r.applied.filter((a) => want.has(a.id));
57
+ if (!applied.length) return { contract, applied: [] };
58
+ const to = new Map(applied.map((a) => [a.id, a.to]));
59
+ const out = { ...contract };
60
+ if (Array.isArray(contract.validate)) out.validate = contract.validate.map((v) => (v && to.has(v.id) ? { ...v, command: to.get(v.id) } : v));
61
+ const t = contract.repro_test;
62
+ if (t && typeof t === "object" && to.has("repro_test")) out.repro_test = { ...t, command: to.get("repro_test") };
63
+ if (Array.isArray(contract.test_plan)) out.test_plan = contract.test_plan.map((p) => (p && to.has(`test_plan ${p.requirement}`) ? { ...p, command: to.get(`test_plan ${p.requirement}`) } : p));
64
+ return { contract: out, applied };
65
+ }
66
+
67
+ /** The tests a runner's output names, as Map(id -> passed): pytest `path::name PASSED`, TAP `ok N - name`, vitest/jest `✓ name`. */
68
+ export function extractTests(output) {
69
+ const tests = new Map();
70
+ for (const line of String(output ?? "").split("\n")) {
71
+ let m;
72
+ if ((m = /^\s*(?:(PASSED|FAILED|ERROR)\s+)?([\w./-]+::[\w:.\[\]-]+)(?:\s+(PASSED|FAILED|ERROR))?/.exec(line))) { const st = m[1] ?? m[3]; if (st) tests.set(m[2], st === "PASSED"); }
73
+ else if ((m = /^\s*(not )?ok \d+ - (.+?)(?:\s+#.*)?$/.exec(line))) tests.set(m[2].trim(), !m[1]);
74
+ else if ((m = /^\s*([✓✔×✗])\s+(.+?)(?:\s+\d+\s*ms)?$/.exec(line))) tests.set(m[2].trim(), m[1] === "✓" || m[1] === "✔");
75
+ }
76
+ return tests;
77
+ }
78
+ /** The test ids a runner's output names. */
79
+ export const extractTestIds = (output) => new Set(extractTests(output).keys());
80
+
81
+ /**
82
+ * A substitute is equivalent to a frozen command that exited non-zero only when both ran the same test ids, every one of
83
+ * them passed in both runs (the frozen exit came from the runner, not a test), and the substitute exited 0. A failing
84
+ * test, a failing substitute, other ids or no ids is never equivalent. `frozen` and `sub` are {rc, output}.
85
+ */
86
+ export function equivalentRuns(frozen, sub) {
87
+ if (!frozen || !sub || sub.rc !== 0) return false;
88
+ const a = extractTests(frozen.output), b = extractTests(sub.output);
89
+ return a.size > 0 && a.size === b.size && [...a].every(([id, ok]) => ok && b.get(id) === true);
90
+ }
91
+
92
+ const DRIFT_RE = /(?:generated|artifact|snapshot)s?\b[^\n]*\b(?:out of date|out-of-date|stale|differ|drift|not up to date)|\b(?:out of date|stale)\b[^\n]*\b(?:generated|regenerate)|run [`'"]?[^\n]*\bgenerate[\w:-]*[`'"]? to (?:update|regenerate)/i;
93
+ /** True when a validate failure's output reads as a stale generated artifact (a regenerate case), not a failing test. */
94
+ export const isDriftFailure = (output) => DRIFT_RE.test(String(output ?? ""));
@@ -0,0 +1,42 @@
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 { deriveCatalog, mergeRecipes, rewriteMissed, extractTestIds, equivalentRuns, isDriftFailure } from "./validate-catalog.mjs";
6
+ import { applyValidateRecipes } from "./conformance.mjs";
7
+
8
+ const CI = "run: uv run --with-requirements r.txt pytest tests\nrun: npx vitest run";
9
+ describe("#5653 validate catalogue", () => {
10
+ it("derives the repo's pytest and JS runners from CI text", () => {
11
+ const c = deriveCatalog([CI]);
12
+ assert.equal("cd api && poetry run pytest t.py".replace(new RegExp(c[0].match), c[0].replace), "cd api && uv run --with-requirements r.txt pytest t.py");
13
+ assert.equal("pnpm exec vitest run x".replace(new RegExp(c[2].match), c[2].replace), "npx vitest run x");
14
+ assert.deepEqual(deriveCatalog(["make test"]), []);
15
+ });
16
+ it("forge.yaml recipes win over derived entries", () => {
17
+ const m = mergeRecipes([{ match: "a", replace: "1" }], [{ match: "a", replace: "2" }, { match: "b", replace: "3" }]);
18
+ assert.deepEqual(m, [{ match: "a", replace: "1" }, { match: "b", replace: "3" }]);
19
+ });
20
+ it("rewrites only the unrunnable ids and leaves unmatched commands unchanged", () => {
21
+ const c = { validate: [{ id: "V1", command: "poetry run pytest a.py" }, { id: "V2", command: "poetry run pytest b.py" }, { id: "V3", command: "node --test x" }] };
22
+ const r = rewriteMissed(c, deriveCatalog([CI]), ["V1", "V3"], applyValidateRecipes);
23
+ assert.match(r.contract.validate[0].command, /^uv run --with-requirements r\.txt pytest a\.py$/);
24
+ assert.equal(r.contract.validate[1].command, "poetry run pytest b.py");
25
+ assert.equal(r.contract.validate[2].command, "node --test x");
26
+ assert.deepEqual(r.applied.map((a) => a.id), ["V1"]);
27
+ assert.equal(rewriteMissed(c, [], ["V1"], applyValidateRecipes).contract, c);
28
+ });
29
+ it("equivalentRuns needs the same passing test ids and a passing substitute", () => {
30
+ const out = "a.py::t1 PASSED\na.py::t2 PASSED\n", bad = "a.py::t1 PASSED\na.py::t2 FAILED\n";
31
+ assert.equal(equivalentRuns({ rc: 1, output: out }, { rc: 0, output: out }), true);
32
+ assert.equal(equivalentRuns({ rc: 1, output: out }, { rc: 1, output: out }), false, "a failing substitute is never equivalent");
33
+ assert.equal(equivalentRuns({ rc: 1, output: bad }, { rc: 0, output: out }), false, "a failing test in the frozen run");
34
+ assert.equal(equivalentRuns({ rc: 1, output: out }, { rc: 0, output: "a.py::t1 PASSED\n" }), false);
35
+ assert.equal(equivalentRuns({ rc: 1, output: "boom" }, { rc: 0, output: "boom" }), false, "no ids is no evidence");
36
+ assert.deepEqual([...extractTestIds("ok 1 - one\nnot ok 2 - two # x")], ["one", "two"]);
37
+ });
38
+ it("classifies a stale generated artifact, not a test failure", () => {
39
+ assert.equal(isDriftFailure("error: generated tools file is out of date"), true);
40
+ assert.equal(isDriftFailure("AssertionError: 1 != 2"), false);
41
+ });
42
+ });
@@ -11,6 +11,7 @@ import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
11
11
  import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs";
12
12
  import { jsonStore } from "./store.mjs";
13
13
  import { makeWarm } from "./warm.mjs";
14
+ import { resolveLaneImage } from "./lane-tools.mjs";
14
15
 
15
16
  const LABEL = "computeshare=1";
16
17
  const LOG_CHUNK = 256 * 1024;
@@ -138,6 +139,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
138
139
  const netArgs = ["--add-host", "host.docker.internal:host-gateway", ...(cfg.dns ?? ["1.1.1.1", "8.8.8.8"]).flatMap((d) => ["--dns", String(d)])];
139
140
  let laneCpus = cpus, laneMem = mem_gb, laneNet = netArgs, work = [];
140
141
  try {
142
+ // #5650: a repo's lane_tools select a derived image (built once per tool list); none keeps spec.image ?? image.
143
+ const laneImage = spec.lane_tools?.length ? await resolveLaneImage({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }) : (spec.image ?? image);
141
144
  if (withDocker) {
142
145
  // Private Docker daemon per sandbox (never the host socket). The lane joins its network namespace, so ports the
143
146
  // project's compose stack publishes are on the lane's localhost, and the API listens on loopback only. Both share
@@ -166,7 +169,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
166
169
  "--env-file", envFile, ...laneNet, ...work,
167
170
  ...(spec.claim_dir ? ["-v", `${join(dir, "claim")}:/claim`] : []), // #4912: warm sandboxes receive their lane here
168
171
  "-v", `cs-cache-${cacheKey}:/cache`, "-v", `${join(dir, "result")}:/result`, "-v", `${join(dir, "out")}:/csout`,
169
- spec.image ?? image, ...spec.command.map(String),
172
+ laneImage, ...spec.command.map(String),
170
173
  ]);
171
174
  rec.state = "running";
172
175
  } catch (e) {
@@ -0,0 +1,115 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { createHash } from "node:crypto";
4
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+
8
+ /**
9
+ * Per-repo lane images (#5650): forge.yaml `execution.lane_tools` lists the tools a repo's lanes need (`name` or
10
+ * `name@version`). The pool derives an image `FROM` the base lane image applying one recipe per tool. RECIPES is the only
11
+ * place tool names appear. To add a tool, add an entry: `versioned` (accepts `@version`) and `steps(version)`, the
12
+ * Dockerfile instructions (Debian/Ubuntu base, building as root) that install it.
13
+ */
14
+ const apt = (...pkgs) => `RUN apt-get update && apt-get install -y --no-install-recommends ${pkgs.join(" ")} && rm -rf /var/lib/apt/lists/*`;
15
+ export const RECIPES = {
16
+ "postgresql-client": { versioned: true, steps: (v) => [apt(v ? `postgresql-client-${v}` : "postgresql-client")] },
17
+ python: { versioned: true, steps: (v) => [apt(v ? `python${v} python${v}-venv` : "python3 python3-venv")] },
18
+ playwright: { versioned: true, steps: (v) => [`RUN npx --yes playwright${v ? `@${v}` : ""} install --with-deps chromium`] },
19
+ // Example of a release-tarball tool; the version is required.
20
+ promtool: { versioned: true, steps: (v) => [`RUN curl -fsSL https://github.com/prometheus/prometheus/releases/download/v${v ?? "2.54.1"}/prometheus-${v ?? "2.54.1"}.linux-amd64.tar.gz | tar -xz --strip-components=1 -C /usr/local/bin --wildcards '*/promtool'`] },
21
+ };
22
+
23
+ const ENTRY_RE = /^([a-z0-9][a-z0-9.+_-]*)(?:@([A-Za-z0-9][A-Za-z0-9.+_-]*))?$/;
24
+ const typed = (code, message) => Object.assign(new Error(message), { code });
25
+
26
+ /** One entry -> {name, version}; throws a message naming the entry when it is empty or has shell metacharacters. */
27
+ export function parseLaneTool(entry) {
28
+ const t = entry === undefined || entry === null ? "" : String(entry).trim();
29
+ const m = ENTRY_RE.exec(t);
30
+ if (!m) throw typed("lane_tools.invalid", `invalid execution.lane_tools entry ${JSON.stringify(t)}: expected name or name@version ([a-z0-9.+_-])`);
31
+ return { name: m[1], version: m[2] ?? null };
32
+ }
33
+
34
+ /** A list (or comma string) -> {tools: sorted, deduped canonical entries, errors: messages naming each bad entry}. */
35
+ export function validateLaneTools(raw) {
36
+ const list = Array.isArray(raw) ? raw : raw === undefined || raw === null || String(raw).trim() === "" ? [] : String(raw).split(",");
37
+ const tools = new Set(), errors = [];
38
+ for (const e of list) {
39
+ try { const p = parseLaneTool(e); tools.add(p.version ? `${p.name}@${p.version}` : p.name); } catch (err) { errors.push(err.message); }
40
+ }
41
+ return { tools: [...tools].sort(), errors };
42
+ }
43
+
44
+ /** True when `name` has a lane_tools recipe (#5652). */
45
+ export function hasRecipe(name) { return Object.hasOwn(RECIPES, String(name)); }
46
+
47
+ /**
48
+ * In-sandbox install commands (#5652) for one tool: the recipe's Dockerfile `RUN` steps as shell commands, `sudo` prefixed
49
+ * when the sandbox user is not root. Empty for a tool with no recipe. Pure; the image build keeps using `steps`.
50
+ */
51
+ export function installCommands(entry, { root = true } = {}) {
52
+ const { name, version } = parseLaneTool(entry);
53
+ if (!hasRecipe(name)) return [];
54
+ const sh = (s) => s.replace(/^RUN\s+/, "");
55
+ return RECIPES[name].steps(version).map((s) => (root ? sh(s) : `sudo sh -c ${JSON.stringify(sh(s))}`));
56
+ }
57
+
58
+ /**
59
+ * Installs `tools` in the running sandbox through the injected `run({command, timeoutMs})` -> {rc, stdout, stderr}.
60
+ * Never throws: {ok:true} or {ok:false, tool, stderrTail}.
61
+ */
62
+ export async function installLaneTools(tools, { run, root = true, timeoutMs = 600000 }) {
63
+ for (const t of tools) {
64
+ for (const command of installCommands(t, { root })) {
65
+ let r;
66
+ try { r = await run({ command, timeoutMs }); } catch (e) { r = { rc: 1, stderr: String(e?.message ?? e) }; }
67
+ if ((r?.rc ?? 0) !== 0) return { ok: false, tool: t, stderrTail: String(r?.stderr || r?.stdout || "").trim().split("\n").slice(-8).join("\n").slice(-600) };
68
+ }
69
+ }
70
+ return { ok: true };
71
+ }
72
+
73
+ /** Fails fast (before any docker call) for a tool with no recipe or an unsupported version. */
74
+ export function checkRecipes(tools) {
75
+ for (const e of tools) {
76
+ const { name, version } = parseLaneTool(e);
77
+ const r = Object.hasOwn(RECIPES, name) ? RECIPES[name] : null;
78
+ if (!r) throw typed("lane_tools.unknown_recipe", `no lane_tools recipe for ${JSON.stringify(name)} (known: ${Object.keys(RECIPES).join(", ")})`);
79
+ if (version && !r.versioned) throw typed("lane_tools.unknown_recipe", `lane_tools recipe ${JSON.stringify(name)} takes no version (got ${version})`);
80
+ }
81
+ }
82
+
83
+ /** Per-repo image tag: base tag plus a hash of the sorted tool list; the same list gives the same tag. */
84
+ export function laneToolsTag(baseImage, tools) {
85
+ const h = createHash("sha256").update([...tools].sort().join("\n")).digest("hex").slice(0, 12);
86
+ return `${baseImage}-t${h}`;
87
+ }
88
+
89
+ /** The generated Dockerfile: FROM the base lane image, then each recipe's steps in sorted order. */
90
+ export function laneToolsDockerfile(baseImage, tools) {
91
+ const steps = [...tools].sort().flatMap((e) => { const { name, version } = parseLaneTool(e); return RECIPES[name].steps(version); });
92
+ return [`FROM ${baseImage}`, "USER root", ...steps, ""].join("\n");
93
+ }
94
+
95
+ /**
96
+ * The image a launch runs: `baseImage` when no tools; else the per-repo tag, reused when present, built from the base
97
+ * otherwise. `docker.hasImage` and `docker.build(dir, tag, args)` are injected. Throws typed lane_tools.unknown_recipe
98
+ * (nothing built) or lane_tools.build_failed (build error or timeout, never a hang).
99
+ */
100
+ export async function resolveLaneImage({ tools = [], baseImage, docker, buildTimeoutMs = 45 * 60000 }) {
101
+ if (!tools.length) return baseImage;
102
+ checkRecipes(tools);
103
+ const tag = laneToolsTag(baseImage, tools);
104
+ if (await docker.hasImage?.(tag)) return tag;
105
+ const dir = mkdtempSync(join(tmpdir(), "lane-tools-"));
106
+ let timer;
107
+ try {
108
+ writeFileSync(join(dir, "Dockerfile"), laneToolsDockerfile(baseImage, tools));
109
+ const timeout = new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`build timed out after ${buildTimeoutMs}ms`)), buildTimeoutMs); });
110
+ await Promise.race([docker.build(dir, tag, {}), timeout]);
111
+ } catch (e) {
112
+ throw typed("lane_tools.build_failed", `lane_tools image ${tag} build failed: ${String(e.stderr || e.message).slice(0, 300)}`);
113
+ } finally { clearTimeout(timer); rmSync(dir, { recursive: true, force: true }); }
114
+ return tag;
115
+ }
@@ -0,0 +1,26 @@
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 { hasRecipe, installCommands, installLaneTools, laneToolsDockerfile } from "./lane-tools.mjs";
6
+
7
+ describe("#5652 in-sandbox lane tool install", () => {
8
+ it("installCommands strips RUN, prefixes sudo when not root, and is empty without a recipe", () => {
9
+ assert.ok(hasRecipe("promtool") && !hasRecipe("nope"));
10
+ assert.match(installCommands("postgresql-client")[0], /^apt-get update/);
11
+ assert.match(installCommands("postgresql-client", { root: false })[0], /^sudo sh -c /);
12
+ assert.deepEqual(installCommands("nope"), []);
13
+ });
14
+ it("installLaneTools runs every step, and returns the stderr tail of the first failure", async () => {
15
+ const seen = [];
16
+ assert.deepEqual(await installLaneTools(["postgresql-client"], { run: async (a) => { seen.push(a.command); return { rc: 0 }; } }), { ok: true });
17
+ assert.equal(seen.length, 1);
18
+ const bad = await installLaneTools(["promtool@2.54.1"], { run: async () => ({ rc: 3, stderr: "a\nb\n404" }) });
19
+ assert.equal(bad.ok, false);
20
+ assert.equal(bad.tool, "promtool@2.54.1");
21
+ assert.match(bad.stderrTail, /404$/);
22
+ });
23
+ it("the image Dockerfile still uses the RUN steps", () => {
24
+ assert.match(laneToolsDockerfile("base:1", ["postgresql-client"]), /\nRUN apt-get update/);
25
+ });
26
+ });