forgedock 1.59.2 → 1.60.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) 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 +19 -6
  7. package/bin/lean/conformance.test.mjs +37 -3
  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 +144 -21
  22. package/bin/lean/lean.test.mjs +180 -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 +67 -3
  32. package/bin/lean/preflight.test.mjs +37 -1
  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 +110 -0
  80. package/bin/lean/validate-catalog.test.mjs +55 -0
  81. package/bin/pool/agent.mjs +12 -1
  82. package/bin/pool/lane-tools.mjs +146 -0
  83. package/bin/pool/lane-tools.test.mjs +26 -0
  84. package/bin/pool/router.mjs +3 -1
  85. package/bin/pool/warm.mjs +14 -3
  86. package/docs/CONFIG.md +225 -1
  87. package/docs/ISSUE-WATCH.md +1 -0
  88. package/docs/design/visual-gate.md +10 -0
  89. package/docs/eval/adversarial-bench.md +1 -0
  90. package/package.json +1 -1
  91. package/pool/README.md +2 -0
  92. package/scripts/acceptance-red-green.sh +5 -2
  93. package/scripts/acceptance-red-green.test.sh +11 -0
  94. package/scripts/bench-adversarial.mjs +4 -0
  95. package/scripts/bench-lightlane.mjs +2 -1
  96. package/templates/github-actions/forge-conductor.scopes.json +7 -0
  97. package/templates/github-actions/forge-conductor.yml +57 -0
@@ -212,6 +212,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
212
212
  relays,
213
213
  serviceRelay,
214
214
  async start({ issue, args = [], env: laneEnv = env, secrets = settings.secrets ?? [] }) {
215
+ if (settings.laneToolsErrors?.length) throw Object.assign(new Error(settings.laneToolsErrors.join("; ")), { code: "lane_tools.invalid" }); // #5650
215
216
  const id = idFor(issue);
216
217
  // Each allowlisted secret from the env, else the keychain (#4254); nothing else from the host.
217
218
  const resolved = {};
@@ -224,6 +225,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
224
225
  const spec = {
225
226
  id, issue, batch: batch.id, image: settings.image ?? null,
226
227
  repo: { slug: repo, url: repo ? `https://github.com/${repo}.git` : null, ref: li >= 0 ? args[li + 1] ?? null : null },
228
+ ...(settings.laneTools?.length ? { lane_tools: settings.laneTools } : {}), // #5650: per-repo lane image
227
229
  ...(warm ? { warm } : {}), // #4912: the pool agent keeps this many warm sandboxes for the repo
228
230
  cache: settings.cacheStore ? { store: settings.cacheStore, key: safeSegment(String(repo ?? "repo")) } : null,
229
231
  // The host's git identity: without it the lane image falls back to a placeholder author that fails DCO.
@@ -0,0 +1,82 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5531: a real schedd process under synthetic CPU load still answers `status` in under a second and keeps dispatching.
4
+ // End to end: the daemon runs in its own node process (real socket, real batch dir, a runBatch that dispatches by writing
5
+ // log rows), the CPU hogs are real processes, and the client is this process plus the real `forgedock schedd status` CLI.
6
+ // FORGEDOCK_SCHEDD_LOAD_HOGS: hog count (default 2); `auto` = 4 x nproc (the issue's load; run on a dedicated host only).
7
+ import { describe, it } from "node:test";
8
+ import assert from "node:assert/strict";
9
+ import { execFile, spawn } from "node:child_process";
10
+ import { readFileSync } from "node:fs";
11
+ import { cpus, setPriority } from "node:os";
12
+ import { join } from "node:path";
13
+ import { fileURLToPath, pathToFileURL } from "node:url";
14
+ import { tmpDir } from "../tests/_tmp.mjs";
15
+ import { openBatch } from "./batch.mjs";
16
+ import { connectDaemon, request } from "./schedd.mjs";
17
+
18
+ const hogs = process.env.FORGEDOCK_SCHEDD_LOAD_HOGS === "auto" ? cpus().length * 4 : Number(process.env.FORGEDOCK_SCHEDD_LOAD_HOGS) || 2;
19
+ const CLI = fileURLToPath(new URL("../forgedock.mjs", import.meta.url));
20
+ const SCHEDD = pathToFileURL(fileURLToPath(new URL("./schedd.mjs", import.meta.url))).href;
21
+ const BATCH = pathToFileURL(fileURLToPath(new URL("./batch.mjs", import.meta.url))).href;
22
+
23
+ /** The daemon process: hosts the given batch and dispatches one log row every 50 ms until it is told to stop. */
24
+ const daemonSrc = (dir, root, id) => `
25
+ import { startDaemon } from ${JSON.stringify(SCHEDD)};
26
+ import { openBatch } from ${JSON.stringify(BATCH)};
27
+ const b = openBatch(${JSON.stringify(root)}, ${JSON.stringify(id)});
28
+ let n = 0;
29
+ const runBatch = async ({ sink, signal }) => {
30
+ sink.batch({ id: b.id, dir: b.dir });
31
+ const t = setInterval(() => b.store.log({ type: "dispatch", n: ++n }), 50);
32
+ await new Promise((r) => signal?.addEventListener?.("abort", r));
33
+ clearInterval(t);
34
+ };
35
+ const d = await startDaemon({ dir: ${JSON.stringify(dir)}, root: ${JSON.stringify(root)}, runBatch, log: (m) => console.log(m), resumeOnStart: true });
36
+ process.on("SIGTERM", async () => { await d.close(); process.exit(0); });
37
+ console.log("ready");
38
+ `;
39
+
40
+ const dispatches = (b) => { try { return readFileSync(join(b.dir, "log.jsonl"), "utf8").split("\n").filter((l) => l.includes('"dispatch"')).length; } catch { return 0; } };
41
+ const until = async (fn, ms) => { const end = Date.now() + ms; while (!fn()) { if (Date.now() > end) throw new Error("timed out"); await new Promise((r) => setTimeout(r, 25)); } };
42
+
43
+ describe("schedd under CPU load (#5531)", () => {
44
+ it("#5531: status answers in under 1 s and a hosted batch keeps dispatching while CPU hogs run", async () => {
45
+ const dir = tmpDir("schedd-load-"), root = join(dir, "batches");
46
+ const b = openBatch(root, "b20261031-000000-8001");
47
+ b.writePlan({ daemon: true, repo: "o/r", created: new Date().toISOString() });
48
+ b.store.save({ v: 1, order: [1], results: {}, running: {}, pending: [1], parallel: 1 });
49
+ // a long history the status scan has to walk (finished batches)
50
+ for (let i = 0; i < 100; i++) { const o = openBatch(root, `b20261001-000000-${7000 + i}`); o.writePlan({ daemon: true, created: "2026-10-01T00:00:00Z" }); o.store.save({ v: 1, order: [1], pending: [] }); o.requestCancel({ reason: "done" }); }
51
+ const daemon = spawn(process.execPath, ["--input-type=module", "-e", daemonSrc(dir, root, b.id)], { stdio: ["ignore", "pipe", "pipe"] });
52
+ let out = ""; daemon.stdout.on("data", (c) => { out += c; }); daemon.stderr.on("data", (c) => { out += c; });
53
+ const procs = [];
54
+ try {
55
+ await until(() => out.includes("ready") && dispatches(b) > 0, 45000);
56
+ // the hogs stand in for lanes: lower class than the daemon, as in production (the unit runs CPUWeight=500, pool/install/unit-hardening.sh)
57
+ for (let i = 0; i < hogs; i++) { const h = spawn(process.execPath, ["-e", "for(;;){}"], { stdio: "ignore" }); try { setPriority(h.pid, 10); } catch { /* best effort */ } procs.push(h); }
58
+ await new Promise((r) => setTimeout(r, 500));
59
+ const n0 = dispatches(b);
60
+ // a client outside the daemon process, over the real socket
61
+ const sock = await connectDaemon({ dir, spawnDaemon: null });
62
+ const times = []; let st;
63
+ for (let i = 0; i < 5; i++) { const t0 = Date.now(); st = await request(i ? await connectDaemon({ dir, spawnDaemon: null }) : sock, { op: "status" }, undefined, { timeoutMs: 5000 }); times.push(Date.now() - t0); }
64
+ const took = Math.min(...times); // best of 5: the full suite runs other test files at normal priority beside this one
65
+ assert.equal(st.type, "status");
66
+ assert.equal(st.pid, daemon.pid, "answered by the spawned daemon");
67
+ assert.ok(st.batches.some((x) => x.id === b.id && x.running), "the batch is hosted");
68
+ assert.ok(took < 1000, `status took ${took} ms under ${hogs} hogs`);
69
+ // the real CLI: `forgedock schedd status` against the same daemon (node startup excluded from the 1 s bound)
70
+ const cli = await new Promise((res) => execFile(process.execPath, [CLI, "schedd", "status"], { env: { ...process.env, FORGEDOCK_SCHED_DIR: dir }, timeout: 60000 }, (err, stdout) => res({ err, stdout })));
71
+ assert.equal(cli.err, null, String(cli.err));
72
+ assert.match(cli.stdout, new RegExp(`schedd: pid ${daemon.pid}, `));
73
+ assert.match(cli.stdout, new RegExp(b.id));
74
+ await new Promise((r) => setTimeout(r, 500));
75
+ assert.ok(dispatches(b) > n0, `the hosted batch kept dispatching (${n0} → ${dispatches(b)})`);
76
+ } finally {
77
+ for (const p of procs) p.kill("SIGKILL");
78
+ daemon.kill("SIGTERM");
79
+ await new Promise((r) => { const t = setTimeout(() => { daemon.kill("SIGKILL"); r(); }, 5000); daemon.on("exit", () => { clearTimeout(t); r(); }); });
80
+ }
81
+ });
82
+ });
@@ -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,110 @@
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
+ import { venvPythonRewrite } from "./preflight.mjs";
11
+
12
+ /** Default CI sources read for the derived catalogue (repo-relative). */
13
+ export const DEFAULT_CATALOG_SOURCES = [".github/workflows/ci.yml", "scripts/ci-local.sh"];
14
+
15
+ const PY_RUNNER_RE = /\b(uv run(?: +--[\w-]+(?:[ =][^\s|&;-][^\s|&;]*)?)* +)(?:python3? +-m +)?pytest\b/; // an option value never starts with "-" (no ambiguous backtracking)
16
+ const JS_RUNNER_RE = /\b(pnpm exec|npx|yarn) +(vitest|jest)\b/;
17
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
18
+
19
+ /**
20
+ * Entries derived from CI text: the repo's own pytest runner prefix replaces `poetry run pytest` / bare `.venv/bin/pytest`
21
+ * a plan guessed, and its own JS runner replaces another one. Empty when CI shows no such runner.
22
+ */
23
+ export function deriveCatalog(texts) {
24
+ const text = (Array.isArray(texts) ? texts : [texts]).filter((t) => typeof t === "string").join("\n");
25
+ const out = [];
26
+ const py = PY_RUNNER_RE.exec(text);
27
+ if (py) {
28
+ const prefix = py[1].trim();
29
+ out.push({ match: "\\bpoetry run (?:python3? -m )?pytest\\b", replace: `${prefix} pytest` });
30
+ out.push({ match: "(?:\\./)?(?:[\\w./-]*/)?\\.venv/bin/pytest\\b", replace: `${prefix} pytest` });
31
+ }
32
+ const js = JS_RUNNER_RE.exec(text);
33
+ if (js) {
34
+ const alt = ["pnpm exec", "npx", "yarn"].filter((r) => r !== js[1]);
35
+ out.push({ match: `\\b(?:${alt.map(esc).join("|")}) +(vitest|jest)\\b`, replace: `${js[1]} $1` });
36
+ }
37
+ return out;
38
+ }
39
+
40
+ /** forge.yaml recipes first, derived entries after, one entry per `match`. */
41
+ export function mergeRecipes(recipes, derived) {
42
+ const seen = new Set(), out = [];
43
+ for (const r of [...(Array.isArray(recipes) ? recipes : []), ...(Array.isArray(derived) ? derived : [])]) {
44
+ if (!r || !r.match || seen.has(String(r.match))) continue;
45
+ seen.add(String(r.match)); out.push(r);
46
+ }
47
+ return out;
48
+ }
49
+
50
+ /**
51
+ * Rewrite only the commands of `ids` (the ones preflight found unrunnable) from `entries`. `apply` is applyValidateRecipes.
52
+ * Returns {contract, applied[{id, from, to}]}; the contract is the input when nothing changed.
53
+ */
54
+ export function rewriteMissed(contract, entries, ids, apply) {
55
+ const want = new Set(ids ?? []);
56
+ if (!want.size || !entries?.length || !contract || typeof contract !== "object") return { contract, applied: [] };
57
+ const r = apply(contract, entries);
58
+ const applied = r.applied.filter((a) => want.has(a.id));
59
+ if (!applied.length) return { contract, applied: [] };
60
+ const to = new Map(applied.map((a) => [a.id, a.to]));
61
+ const out = { ...contract };
62
+ if (Array.isArray(contract.validate)) out.validate = contract.validate.map((v) => (v && to.has(v.id) ? { ...v, command: to.get(v.id) } : v));
63
+ const t = contract.repro_test;
64
+ if (t && typeof t === "object" && to.has("repro_test")) out.repro_test = { ...t, command: to.get("repro_test") };
65
+ 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));
66
+ return { contract: out, applied };
67
+ }
68
+
69
+ /** The tests a runner's output names, as Map(id -> passed): pytest `path::name PASSED`, TAP `ok N - name`, vitest/jest `✓ name`. */
70
+ export function extractTests(output) {
71
+ const tests = new Map();
72
+ for (const line of String(output ?? "").split("\n")) {
73
+ let m;
74
+ 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"); }
75
+ else if ((m = /^\s*(not )?ok \d+ - (.+?)(?:\s+#.*)?$/.exec(line))) tests.set(m[2].trim(), !m[1]);
76
+ else if ((m = /^\s*([✓✔×✗])\s+(.+?)(?:\s+\d+\s*ms)?$/.exec(line))) tests.set(m[2].trim(), m[1] === "✓" || m[1] === "✔");
77
+ }
78
+ return tests;
79
+ }
80
+ /** The test ids a runner's output names. */
81
+ export const extractTestIds = (output) => new Set(extractTests(output).keys());
82
+
83
+ /**
84
+ * A substitute is equivalent to a frozen command that exited non-zero only when both ran the same test ids, every one of
85
+ * them passed in both runs (the frozen exit came from the runner, not a test), and the substitute exited 0. A failing
86
+ * test, a failing substitute, other ids or no ids is never equivalent. `frozen` and `sub` are {rc, output}.
87
+ */
88
+ export function equivalentRuns(frozen, sub) {
89
+ if (!frozen || !sub || sub.rc !== 0) return false;
90
+ const a = extractTests(frozen.output), b = extractTests(sub.output);
91
+ return a.size > 0 && a.size === b.size && [...a].every(([id, ok]) => ok && b.get(id) === true);
92
+ }
93
+
94
+ 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;
95
+ /** True when a validate failure's output reads as a stale generated artifact (a regenerate case), not a failing test. */
96
+ export const isDriftFailure = (output) => DRIFT_RE.test(String(output ?? ""));
97
+
98
+ /**
99
+ * #5683: the repro and validate commands that run a bare `python -m pytest` / `pytest` inside a sub-project with a tracked
100
+ * Python manifest and a `.venv` run through that venv's interpreter. Returns {contract, applied[{id, from, to}]}.
101
+ */
102
+ export function rewriteSubprojectVenv(contract, files, exists) {
103
+ if (!contract || typeof contract !== "object") return { contract, applied: [] };
104
+ const applied = [], fix = (id, cmd) => { const to = venvPythonRewrite(cmd, files, exists); if (to !== cmd) applied.push({ id, from: cmd, to }); return to; };
105
+ const out = { ...contract };
106
+ if (Array.isArray(contract.validate)) out.validate = contract.validate.map((v) => (v && typeof v.command === "string" ? { ...v, command: fix(v.id, v.command) } : v));
107
+ const t = contract.repro_test;
108
+ if (t && typeof t === "object" && typeof t.command === "string") out.repro_test = { ...t, command: fix("repro_test", t.command) };
109
+ return applied.length ? { contract: out, applied } : { contract, applied };
110
+ }
@@ -0,0 +1,55 @@
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, rewriteSubprojectVenv } 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
+ });
43
+
44
+ describe("#5683 sub-project venv rewrite", () => {
45
+ const files = ["services/api/pyproject.toml"], exists = (p) => p === "services/api/.venv/bin/python";
46
+ it("rewrites the repro and validate commands, leaves others, and returns the input when nothing changes", () => {
47
+ const c = { repro_test: { path: "t", id: "i", command: "cd services/api && python -m pytest tests/a.py" }, validate: [{ id: "V1", command: "cd services/api && pytest" }, { id: "V2", command: "node --test x" }] };
48
+ const r = rewriteSubprojectVenv(c, files, exists);
49
+ assert.equal(r.contract.repro_test.command, "cd services/api && .venv/bin/python -m pytest tests/a.py");
50
+ assert.deepEqual(r.contract.validate.map((v) => v.command), ["cd services/api && .venv/bin/python -m pytest", "node --test x"]);
51
+ assert.deepEqual(r.applied.map((a) => a.id).sort(), ["V1", "repro_test"]);
52
+ const same = { validate: [{ id: "V1", command: "node --test x" }] };
53
+ assert.equal(rewriteSubprojectVenv(same, files, exists).contract, same);
54
+ });
55
+ });