forgedock 1.67.0 → 1.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/bin/config-schema.mjs +1 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +103 -21
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +17 -1
  6. package/bin/help-text.mjs +1 -0
  7. package/bin/lean/admission.mjs +21 -0
  8. package/bin/lean/admission.test.mjs +30 -0
  9. package/bin/lean/advisory.test.mjs +39 -15
  10. package/bin/lean/amendment-schema.mjs +3 -4
  11. package/bin/lean/attempts.mjs +34 -31
  12. package/bin/lean/attempts.test.mjs +33 -19
  13. package/bin/lean/basered.mjs +26 -0
  14. package/bin/lean/batch-health.mjs +17 -12
  15. package/bin/lean/batch-health.test.mjs +39 -11
  16. package/bin/lean/batch.mjs +11 -1
  17. package/bin/lean/batch.test.mjs +51 -2
  18. package/bin/lean/capsample.mjs +25 -0
  19. package/bin/lean/ci-gate.mjs +2 -90
  20. package/bin/lean/ci-gate.test.mjs +1 -127
  21. package/bin/lean/ci-precheck.mjs +25 -8
  22. package/bin/lean/ci-precheck.test.mjs +24 -0
  23. package/bin/lean/clear-breaker.test.mjs +4 -3
  24. package/bin/lean/commentstate.mjs +10 -5
  25. package/bin/lean/commentstate.test.mjs +12 -1
  26. package/bin/lean/conformance.e2e.test.mjs +9 -6
  27. package/bin/lean/conformance.mjs +62 -197
  28. package/bin/lean/conformance.test.mjs +46 -376
  29. package/bin/lean/depcache.mjs +102 -10
  30. package/bin/lean/depcache.test.mjs +105 -0
  31. package/bin/lean/docsgate.mjs +0 -32
  32. package/bin/lean/docsgate.test.mjs +2 -23
  33. package/bin/lean/effects-cap.test.mjs +9 -1
  34. package/bin/lean/effects-killtree.test.mjs +35 -0
  35. package/bin/lean/effects.mjs +57 -25
  36. package/bin/lean/engine-readmit.test.mjs +35 -0
  37. package/bin/lean/envgap.mjs +111 -0
  38. package/bin/lean/envgap.test.mjs +64 -0
  39. package/bin/lean/execution.mjs +13 -4
  40. package/bin/lean/execution.test.mjs +33 -0
  41. package/bin/lean/failure-census.mjs +170 -0
  42. package/bin/lean/failure-census.test.mjs +59 -0
  43. package/bin/lean/failure-stop.mjs +12 -1
  44. package/bin/lean/failure-stop.test.mjs +14 -1
  45. package/bin/lean/guardgate.test.mjs +2 -3
  46. package/bin/lean/heavy.mjs +33 -4
  47. package/bin/lean/heavy.test.mjs +38 -6
  48. package/bin/lean/hostconfig.mjs +54 -0
  49. package/bin/lean/hostconfig.test.mjs +67 -0
  50. package/bin/lean/hotarea.mjs +0 -36
  51. package/bin/lean/hotarea.test.mjs +1 -22
  52. package/bin/lean/issuewatch-verify.mjs +19 -4
  53. package/bin/lean/issuewatch.mjs +21 -4
  54. package/bin/lean/issuewatch.test.mjs +48 -1
  55. package/bin/lean/lane-audit-gap.mjs +66 -0
  56. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  57. package/bin/lean/lane-audit-llm.mjs +52 -0
  58. package/bin/lean/lane-audit-llm.test.mjs +57 -0
  59. package/bin/lean/lane-audit-query.mjs +47 -0
  60. package/bin/lean/lane-audit-query.test.mjs +44 -0
  61. package/bin/lean/lane-audit-signatures.mjs +33 -0
  62. package/bin/lean/lane-audit.mjs +110 -0
  63. package/bin/lean/lane-audit.test.mjs +97 -0
  64. package/bin/lean/lane-recovery.test.mjs +33 -0
  65. package/bin/lean/lanecheck.mjs +5 -3
  66. package/bin/lean/lanecheck.test.mjs +6 -0
  67. package/bin/lean/lean.mjs +247 -152
  68. package/bin/lean/lean.test.mjs +502 -206
  69. package/bin/lean/limits.mjs +17 -0
  70. package/bin/lean/limits.test.mjs +15 -1
  71. package/bin/lean/live-execution.mjs +24 -2
  72. package/bin/lean/live-execution.test.mjs +62 -0
  73. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  74. package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
  75. package/bin/lean/orchestrate-envhold.test.mjs +62 -1
  76. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  77. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  78. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  79. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  80. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  81. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  82. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  83. package/bin/lean/orchestrate.mjs +215 -42
  84. package/bin/lean/postdeploy-check.test.mjs +1 -3
  85. package/bin/lean/precheck.mjs +20 -0
  86. package/bin/lean/preflight.mjs +110 -14
  87. package/bin/lean/preflight.test.mjs +64 -4
  88. package/bin/lean/prompts.mjs +11 -21
  89. package/bin/lean/recurrence.mjs +6 -148
  90. package/bin/lean/recurrence.test.mjs +11 -147
  91. package/bin/lean/release-deploy.mjs +35 -5
  92. package/bin/lean/release-deploy.test.mjs +50 -3
  93. package/bin/lean/release-flakes.mjs +48 -2
  94. package/bin/lean/release-flakes.test.mjs +45 -1
  95. package/bin/lean/release-ledger.mjs +19 -1
  96. package/bin/lean/release-ledger.test.mjs +23 -0
  97. package/bin/lean/release-preflight.mjs +28 -0
  98. package/bin/lean/release-preflight.test.mjs +42 -1
  99. package/bin/lean/release-review.mjs +40 -5
  100. package/bin/lean/release-review.test.mjs +43 -2
  101. package/bin/lean/release.mjs +45 -15
  102. package/bin/lean/release.test.mjs +32 -0
  103. package/bin/lean/retry.mjs +1 -1
  104. package/bin/lean/retry.test.mjs +6 -1
  105. package/bin/lean/rotator.mjs +9 -0
  106. package/bin/lean/rotator.test.mjs +11 -1
  107. package/bin/lean/sandbox-remote.mjs +51 -13
  108. package/bin/lean/schedd.mjs +13 -8
  109. package/bin/lean/schedd.test.mjs +65 -5
  110. package/bin/lean/selfreview.mjs +1 -1
  111. package/bin/lean/statuscomment.mjs +4 -1
  112. package/bin/lean/validate-catalog.mjs +108 -0
  113. package/bin/lean/validate-catalog.test.mjs +46 -1
  114. package/bin/lean/verify.mjs +1 -1
  115. package/bin/pool/affinity.test.mjs +91 -0
  116. package/bin/pool/agent.mjs +247 -23
  117. package/bin/pool/cache-sweep.mjs +31 -10
  118. package/bin/pool/ci-autoscale.mjs +160 -0
  119. package/bin/pool/cli.mjs +56 -9
  120. package/bin/pool/docker.mjs +5 -0
  121. package/bin/pool/engine-placement.test.mjs +94 -0
  122. package/bin/pool/image-manifest.mjs +24 -0
  123. package/bin/pool/image-manifest.test.mjs +20 -0
  124. package/bin/pool/lane-target.mjs +41 -0
  125. package/bin/pool/lane-tools.mjs +29 -5
  126. package/bin/pool/lane-tools.test.mjs +36 -7
  127. package/bin/pool/mirror-seed.mjs +15 -11
  128. package/bin/pool/project-layer.mjs +142 -0
  129. package/bin/pool/project-layer.test.mjs +73 -0
  130. package/bin/pool/router.mjs +106 -36
  131. package/bin/pool/version.mjs +72 -2
  132. package/bin/review-staging.mjs +11 -3
  133. package/bin/runner.mjs +59 -11
  134. package/bin/stats/release.mjs +7 -0
  135. package/bin/stats/release.test.mjs +20 -0
  136. package/bin/stats/scorecard.mjs +187 -0
  137. package/bin/stats/scorecard.test.mjs +89 -0
  138. package/bin/stats/tool-parks.mjs +29 -0
  139. package/bin/stats/tool-parks.test.mjs +21 -0
  140. package/docs/CONFIG.md +41 -0
  141. package/docs/OUTCOME-CODES.md +1 -0
  142. package/docs/STATS.md +17 -0
  143. package/package.json +1 -1
  144. package/pool/image/Dockerfile +15 -3
  145. package/pool/image/manifest.json +25 -0
  146. package/pool/image/mirror.sh +11 -2
  147. package/pool/install/install-agent.ps1 +11 -4
  148. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  149. package/scripts/ci-local/cli.mjs +1 -1
  150. package/scripts/ci-local/plan.mjs +3 -2
  151. package/scripts/ci-local.test.sh +14 -2
  152. package/scripts/failure-census.mjs +67 -0
  153. package/scripts/review-finalize.sh +5 -5
  154. package/scripts/review-finalize.test.sh +8 -1
  155. package/scripts/verify-phase-trail.sh +11 -0
  156. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -1,6 +1,6 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { pollUntil } from "./retry.mjs";
3
+ import { pollUntil, GH_TRANSIENT_RE as NET_RE } from "./retry.mjs";
4
4
 
5
5
  test("pollUntil returns the first truthy probe value, sleeping between tries", async () => {
6
6
  let n = 0, t = 0; const sleeps = [];
@@ -14,3 +14,8 @@ test("pollUntil returns null once the timeout passes, probing at least once", as
14
14
  assert.equal(v, null); assert.ok(n >= 3);
15
15
  assert.equal(await pollUntil(() => null, { timeoutMs: -1, pollMs: 1, sleep: async () => {}, now: () => 0 }), null);
16
16
  });
17
+
18
+ test("gh network failures are transient, validation errors are not (2026-11-26: a dropped connection during gh pr merge became an engine-error)", () => {
19
+ for (const t of ["error connecting to api.github.com", "check your internet connection", "dial tcp: lookup api.github.com: no such host", "net/http: TLS handshake timeout", "read tcp: i/o timeout", "connect: connection refused"]) assert.ok(NET_RE.test(t), t);
20
+ for (const t of ["HTTP 422: Validation Failed", "GraphQL: Could not resolve to a PullRequest", "HTTP 404: Not Found"]) assert.ok(!NET_RE.test(t), t);
21
+ });
@@ -213,3 +213,12 @@ export function quotaRequeue({ rotator, r, prior = null, delayMs, exclude = null
213
213
  return { delayMs, rotated: false };
214
214
  } catch { return null; }
215
215
  }
216
+
217
+ /**
218
+ * #5988: the account to try after `failed` (account numbers: the ones whose login just failed) hit a `backend.auth` failure,
219
+ * tried first on resume. Never `failed` itself; null when no rotator or no other account is usable.
220
+ */
221
+ export function nextAccountAfterAuthFailure(rotator, failed = []) {
222
+ if (!rotator || typeof rotator.pick !== "function") return null;
223
+ try { const p = rotator.pick({ exclude: new Set([...failed].map(Number).filter((n) => Number.isInteger(n) && n > 0)) }); return Number.isInteger(p?.account) ? p.account : null; } catch { return null; }
224
+ }
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
5
5
  import { mkdirSync, writeFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { tmpDir } from "../tests/_tmp.mjs";
8
- import { parseLive, openRotator, rotatorRetry, quotaRequeue, rotatorKind, realClaude, accountOfPid, ROTATOR_KINDS, HEADROOM_PCT } from "./rotator.mjs";
8
+ import { parseLive, openRotator, rotatorRetry, quotaRequeue, rotatorKind, nextAccountAfterAuthFailure, realClaude, accountOfPid, ROTATOR_KINDS, HEADROOM_PCT } from "./rotator.mjs";
9
9
  import { laneBackendId, openLimits } from "./limits.mjs";
10
10
  import { orchestrate, formatTable } from "./orchestrate.mjs";
11
11
  import { parseExecution } from "./execution.mjs";
@@ -244,3 +244,13 @@ describe("account rotator: detection, staleness, exclusion, pick (#5205)", () =>
244
244
  assert.equal(accountOfPid(undefined, { procRoot: proc }), null);
245
245
  });
246
246
  });
247
+
248
+ describe("#5988: next account after an auth failure", () => {
249
+ const fake = (accounts) => ({ pick: ({ exclude }) => { const a = accounts.find((n) => !exclude.has(n)); return a ? { account: a } : { account: null }; } });
250
+ it("picks an account other than the failed one; null when none is left or there is no rotator", () => {
251
+ assert.equal(nextAccountAfterAuthFailure(fake([1, 2, 3]), [1]), 2);
252
+ assert.equal(nextAccountAfterAuthFailure(fake([1, 2]), [1, 2]), null);
253
+ assert.equal(nextAccountAfterAuthFailure(null, [1]), null);
254
+ assert.equal(nextAccountAfterAuthFailure({ pick: () => { throw new Error("x"); } }, [1]), null);
255
+ });
256
+ });
@@ -16,7 +16,7 @@
16
16
  * or a session gateway fronts. Tests use an in-memory transport.
17
17
  */
18
18
  import { execFileSync } from "node:child_process";
19
- import { appendFileSync, mkdirSync } from "node:fs";
19
+ import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
20
20
  import { homedir } from "node:os";
21
21
  import { dirname, join } from "node:path";
22
22
  import { mergeRemoteLog } from "../engine/runlog.mjs";
@@ -57,7 +57,7 @@ export function isActionsEndpoint(endpoint) {
57
57
  * `GET /agents -> {sandboxes}` is the router's live sandbox list (#5422, `inventory()`; malformed or any error throws).
58
58
  * Optional relay (#4778): `GET /sandboxes/:id/relay -> {requests: [{rid, argv}]}` lists a sandbox's pending read-only capability
59
59
  * requests (404/405 or malformed = none, an older router) and `POST /sandboxes/:id/relay/:rid` `{rc, stdout, stderr}` answers one.
60
- * Optional `GET /status -> {free: N, online?, total?}` is the pool's free slots (#4540); without `online` the agents of `GET /agents` give it (#4788). Anything else (404, error, malformed) is unknown (null).
60
+ * Optional `GET /status[?repo=<slug>] -> {free: N, online?, total?}` is the pool's free slots (#4540); `?repo=` (#6041) limits `/status` and `/agents` to the agents the repo may use (router.json `repos.<slug>.agents` / `exclude_agents`); without `online` the agents of `GET /agents` give it (#4788). Anything else (404, error, malformed) is unknown (null).
61
61
  */
62
62
  export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fetch }) {
63
63
  const root = String(endpoint ?? "").replace(/\/+$/, "");
@@ -75,7 +75,10 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
75
75
  const hop = r.status === 401 && ["router", "agent"].includes(r.data?.hop) ? r.data.hop : null;
76
76
  const who = hop === "agent" && typeof r.data?.agent === "string" ? `agent ${r.data.agent.slice(0, 64)}` : hop;
77
77
  const reason = hop && typeof r.data?.reason === "string" ? r.data.reason.replace(/^(router|agent) auth: /, "").replace(/[^\x20-\x7e]/g, "").slice(0, 80) : "";
78
- const e = new Error(`sandbox ${what}: HTTP ${r.status}${who ? ` (${who} auth${reason ? `: ${reason}` : ""})` : ""}`);
78
+ // 2026-11-26: non-auth failures keep the pool's error text (printable, ≤160 chars, never a token), so a seed 409/422 says why
79
+ const live = typeof token === "function" ? (() => { try { return token(); } catch { return null; } })() : token;
80
+ const err = !hop && typeof r.data?.error === "string" ? redact(r.data.error, [live]).replace(/[^\x20-\x7e]/g, "").slice(0, 160) : "";
81
+ const e = new Error(`sandbox ${what}: HTTP ${r.status}${who ? ` (${who} auth${reason ? `: ${reason}` : ""})` : ""}${err ? `: ${err}` : ""}`);
79
82
  e.status = r.status;
80
83
  if (hop) e.hop = hop;
81
84
  if (typeof r.data?.code === "string" && r.data.code.startsWith("pool.")) e.poolCode = r.data.code; // #5985: the pool's refusal code reaches the deferral row
@@ -88,8 +91,9 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
88
91
  return e;
89
92
  };
90
93
  const p = (id) => `/sandboxes/${encodeURIComponent(id)}`;
94
+ const placedEngine = new Map(); // sandbox id -> lane-engine version of the agent the router placed it on (R3: the ran version is recorded even when the lane reports none)
91
95
  return {
92
- async launch(spec) { const r = await call("POST", "/sandboxes", spec); if (!r.ok) throw fail("launch", r); return r.data ?? {}; },
96
+ async launch(spec) { const r = await call("POST", "/sandboxes", spec); if (!r.ok) throw fail("launch", r); if (typeof r.data?.engine_version === "string" && typeof spec?.id === "string") placedEngine.set(spec.id, r.data.engine_version); return r.data ?? {}; },
93
97
  /** #4912: hand the lane to a ready warm sandbox. 200/201 = claimed; 204/404/405 (none ready, or a pool without warm sandboxes) = null. */
94
98
  async claim(spec) { const r = await call("POST", "/sandboxes/claim", spec); if (r.status === 200 || r.status === 201) return r.data ?? {}; if (r.status === 204 || r.status === 404 || r.status === 405) return null; throw fail("claim", r); },
95
99
  async status(id) {
@@ -100,7 +104,9 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
100
104
  return s === "running" || s === "pending" || s === "starting" || s === "paused" ? "running" : s === "gone" ? "gone" : "exited";
101
105
  },
102
106
  async logs(id, cursor = 0) { const r = await call("GET", `${p(id)}/logs?cursor=${encodeURIComponent(cursor)}`); return r.ok ? { text: String(r.data?.text ?? ""), cursor: r.data?.cursor ?? cursor } : { text: "", cursor }; },
103
- async result(id) { const r = await call("GET", `${p(id)}/result`); if (r.status === 401) throw Object.assign(fail("result", r), { transient: true }); if (r.ok && r.data?.disk_pressure === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_DISK_PRESSURE, retryInSeconds: 120, cost_usd: 0, detail: `sandbox ${id} was stopped to save the host drive (disk pressure); worktree and volume kept, requeued to resume` }; /* #5891 */ if (r.ok && r.data?.drained === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, retryInSeconds: 60, cost_usd: 0, detail: `sandbox ${id} was drained to free capacity for reserved work (${String(r.data.reason ?? "").slice(0, 120)}); rescheduled` }; /* #5856 */ return r.ok && r.data && typeof r.data === "object" ? r.data : null; },
107
+ async result(id) { const r = await call("GET", `${p(id)}/result`); if (r.status === 401) throw Object.assign(fail("result", r), { transient: true }); if (r.ok && r.data?.disk_pressure === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_DISK_PRESSURE, retryInSeconds: 120, cost_usd: 0, detail: `sandbox ${id} was stopped to save the host drive (disk pressure); worktree and volume kept, requeued to resume` }; /* #5891 */ if (r.ok && r.data?.drained === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, retryInSeconds: 60, cost_usd: 0, detail: `sandbox ${id} was drained to free capacity for reserved work (${String(r.data.reason ?? "").slice(0, 120)}); rescheduled` }; /* #5856 */ if (r.ok && r.data && typeof r.data === "object") { const v = r.data.engineVersion ?? r.data.engine_version ?? r.data.forge_version ?? /ForgeDock\s*[·-]\s*v?(\d+\.\d+(?:\.\d+)?)/.exec(String(r.data.banner ?? r.data.log ?? ""))?.[1]; const pv = v ?? placedEngine.get(id); return pv && !r.data.engineVersion ? { ...r.data, engineVersion: String(pv) } : r.data; } return null; }, /* #5931 */
108
+ /** #6117: the lane's run log (jsonl text, capped) and the last ~200 lines of its stderr/stdout; null from a pool without the endpoint (404/405) or any error. Kept by the agent for a grace period after destroy. */
109
+ async runlog(id) { const r = await call("GET", `${p(id)}/runlog`); return r.ok && r.data && typeof r.data === "object" ? { runLog: String(r.data.run_log ?? ""), tail: String(r.data.tail ?? "") } : null; },
104
110
  async usage(id) { const r = await call("GET", `${p(id)}/usage`); return r.ok && Number.isFinite(Number(r.data?.minutes)) ? { minutes: Number(r.data.minutes), ...(typeof r.data.agent === "string" && r.data.agent ? { agent: r.data.agent } : {}) } : null; }, // agent: #4549, optional
105
111
  async stop(id) { const r = await call("POST", `${p(id)}/stop`); if (r.ok) return true; if (r.status === 404 || r.status === 405) return false; throw fail("stop", r); },
106
112
  async destroy(id) { const r = await call("DELETE", p(id)); if (r.ok || r.status === 404) return true; throw fail("destroy", r); },
@@ -161,19 +167,21 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
161
167
  if (!list) throw fail("agents", r);
162
168
  return list.some((a) => a?.ok === true && !a.paused && (!agent || a.name === agent));
163
169
  },
164
- async capacity() {
170
+ async capacity({ repo } = {}) {
171
+ const q = typeof repo === "string" && repo ? `?repo=${encodeURIComponent(repo)}` : ""; // #6041: only the repo's allowed agents count
165
172
  // `free` (#4540) and agent liveness `online`/`total` (#4547) are each optional; none valid is unknown.
166
173
  const ok = (v) => Number.isInteger(v) && v >= 0;
167
174
  let out = {}, reached = false, lastErr = null;
168
175
  try {
169
- const r = await call("GET", "/status");
176
+ const r = await call("GET", `/status${q}`);
170
177
  reached = true;
171
- if (r.ok) { const { free, online, total } = r.data ?? {}; out = { ...(ok(free) ? { free } : {}), ...(ok(online) ? { online } : {}), ...(ok(total) ? { total } : {}) }; }
178
+ if (r.ok) { const { free, online, total } = r.data ?? {}; const agents = (Array.isArray(r.data?.agents) ? r.data.agents : []).filter((a) => typeof a?.engine_version === "string").map((a) => ({ name: a.name, ok: a.ok === true, paused: a.paused === true, engine_version: a.engine_version })); // R6: per-agent lane engines
179
+ out = { ...(ok(free) ? { free } : {}), ...(ok(online) ? { online } : {}), ...(ok(total) ? { total } : {}), ...(agents.length ? { agents } : {}) }; }
172
180
  } catch (e) { out = {}; lastErr = e; }
173
181
  if (out.online === undefined || out.load_per_core === undefined) {
174
182
  // #4788: a router without /status liveness: online = agents answering and not paused, as bin/pool/router.mjs status() does.
175
183
  try {
176
- const r = await call("GET", "/agents");
184
+ const r = await call("GET", `/agents${q}`);
177
185
  reached = true;
178
186
  const list = r.ok && Array.isArray(r.data?.agents) ? r.data.agents : null;
179
187
  if (list && out.online === undefined) out = { ...out, online: list.filter((a) => a?.ok === true && !a.paused).length, total: list.length };
@@ -253,13 +261,41 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
253
261
  }
254
262
  return b64 ? { CS_RELAY_PREFETCH_B64: b64 } : {};
255
263
  };
264
+ /** Appends the sandbox log chunk past the handle's cursor to the lane log. {ok, bytes}: ok=false when the pool could not answer. */
256
265
  const pullLogs = async (h) => {
257
- if (!transport.logs) return;
266
+ if (!transport.logs) return { ok: false, bytes: 0 };
258
267
  try {
259
268
  const { text, cursor } = (await transport.logs(h.id, h.logCursor ?? 0)) ?? {};
260
269
  if (text) { const f = batch.logFile(h.issue); mkdirSync(dirname(f), { recursive: true }); appendFileSync(f, redact(text, [...known])); }
261
270
  if (cursor !== undefined) h.logCursor = cursor;
262
- } catch { /* the next poll retries */ }
271
+ return { ok: true, bytes: text ? String(text).length : 0 };
272
+ } catch { return { ok: false, bytes: 0 }; /* the next poll retries */ }
273
+ };
274
+ /** #6117: `<n>.runlog.jsonl` beside the lane log (`<n>.log`): the sandbox's own run log, so an env park stays triageable after teardown. */
275
+ const runLogFile = (issue) => { const f = batch.logFile(issue); return /\.log$/.test(f) ? f.replace(/\.log$/, ".runlog.jsonl") : `${f}.runlog.jsonl`; };
276
+ const keepRunLog = (h, runLog) => {
277
+ if (!runLog) return;
278
+ try { const f = runLogFile(h.issue); mkdirSync(dirname(f), { recursive: true }); writeFileSync(f, redact(String(runLog), [...known])); } catch { /* evidence only */ }
279
+ mergeRemoteLog(env.FORGE_RUNS_DIR || join(homedir(), ".forge", "runs"), h.issue, runLog, { repo });
280
+ };
281
+ /**
282
+ * #6117: everything the sandbox still holds, copied to the dispatcher BEFORE it is destroyed: the rest of the lane log
283
+ * (chunks past the cursor, until drained), the run log, and (when the log could not be drained) the stderr tail.
284
+ * Runs on every terminal path (teardown is their one choke point) and never throws.
285
+ */
286
+ const collectEvidence = async (h) => {
287
+ try {
288
+ let drained = false;
289
+ for (let i = 0; i < 64; i++) { const r = await pullLogs(h); drained = r.ok; if (!r.ok || r.bytes === 0) break; }
290
+ if (typeof transport.runlog !== "function") return;
291
+ const e = await transport.runlog(h.id).catch(() => null);
292
+ if (!e) return;
293
+ keepRunLog(h, e.runLog);
294
+ if (!drained && e.tail) {
295
+ const f = batch.logFile(h.issue); mkdirSync(dirname(f), { recursive: true });
296
+ appendFileSync(f, redact(`\n[sandbox ${h.id}] last lines of its log (the live stream could not be drained before teardown):\n${e.tail}${e.tail.endsWith("\n") ? "" : "\n"}`, [...known]));
297
+ }
298
+ } catch { /* teardown goes on */ }
263
299
  };
264
300
  return {
265
301
  name,
@@ -280,6 +316,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
280
316
  const envSnap = settings.forgeYaml ? readEnvSnapshots(settings.forgeYaml) : null; // env.snapshots: off unless enabled
281
317
  const spec = {
282
318
  id, issue, batch: batch.id, image: settings.image ?? null,
319
+ ...(typeof settings.minLaneEngine === "string" && settings.minLaneEngine ? { min_lane_engine: settings.minLaneEngine } : {}), // R2: the router drops lower-engine agents (pool.engine_old deferral)
283
320
  priority: "borrow", // #5856: lanes run on leftover capacity; a pool with reservations throttles/drains them for reserved work
284
321
  repo: { slug: repo, url: repo ? `https://github.com/${repo}.git` : null, ref: li >= 0 ? args[li + 1] ?? null : null },
285
322
  ...(settings.laneTools?.length ? { lane_tools: settings.laneTools } : {}), // #5650: per-repo lane image
@@ -323,7 +360,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
323
360
  if (r) { await pullLogs(h); await minutesOf(h); }
324
361
  if (!r) return null;
325
362
  const { runLog, ...rest } = r; // #5697: the lane's run log goes to the host run log, not into the result
326
- if (runLog) mergeRemoteLog(env.FORGE_RUNS_DIR || join(homedir(), ".forge", "runs"), h.issue, runLog, { repo });
363
+ keepRunLog(h, runLog); // #6117: the host run log and `<n>.runlog.jsonl` beside the lane log
327
364
  return rest;
328
365
  },
329
366
  /** #5991: is the pool agent of this handle answering? Unknown (null) without transport support; transport errors propagate. */
@@ -334,7 +371,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
334
371
  async capacity() {
335
372
  // #5048: no capacity() is unknown (null); a transport error propagates, so the caller can report the pool down
336
373
  if (typeof transport.capacity !== "function") return null;
337
- return (await transport.capacity()) ?? null;
374
+ return (await transport.capacity({ repo })) ?? null;
338
375
  },
339
376
  /** #5985: the pool's usage-history rows; null when the transport has none. */
340
377
  async usageHistory() { return typeof transport.usageHistory === "function" ? (await transport.usageHistory()) ?? null : null; },
@@ -350,6 +387,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
350
387
  /** #5241: why the last `stop(h)` returned false (null when it succeeded or never ran), so a cancel can report it. */
351
388
  stopReason: (h) => stopWhy.get(h?.id) ?? null,
352
389
  async teardown(h) {
390
+ await collectEvidence(h); // #6117: the run log and the log tail leave the sandbox before it is destroyed
353
391
  await minutesOf(h);
354
392
  try { return (await transport.destroy(h.id)) !== false; } catch { return false; }
355
393
  },
@@ -78,8 +78,8 @@ export function batchVerdicts(root, { now = Date.now(), windowMin = DEFAULT_STAL
78
78
  try {
79
79
  const b = openBatch(root, id);
80
80
  if (!b.readPlan()?.daemon || b.isTerminal()) continue;
81
- const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, paused: b.readPause?.() ?? null, lastProgressMs: b.lastProgressMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
82
- const decision = stall ? decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, hosted: false }) : null;
81
+ const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, paused: b.readPause?.() ?? null, lastProgressMs: b.lastDispatchClockMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
82
+ const decision = stall ? decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, hosted: false, now, windowMin }) : null;
83
83
  out.push(batchVerdict(id, stall, decision));
84
84
  } catch { /* one unreadable batch has no verdict */ }
85
85
  }
@@ -288,7 +288,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
288
288
  if (closing) return;
289
289
  let b, st;
290
290
  try { b = openBatch(root, id); if (b.readReport() || b.readCancel() || !b.pendingIssues().length) return; st = b.store.load(); } catch { return; }
291
- if (st?.breaker && !st.breaker.transport) return; // a tripped breaker holds the batch for an operator --resume (a re-host would stop again at once)
291
+ if (st?.breaker && !st.breaker.transport && !st.breaker.environmental) return; // a tripped breaker holds the batch for an operator --resume (a re-host would stop again at once)
292
292
  const at = Math.min(...b.pendingIssues().map((n) => Number(st?.notBefore?.[n]) || Infinity));
293
293
  if (!Number.isFinite(at)) return; // nothing waits on the clock: a deliberate hold stays for --resume
294
294
  if (at <= Date.now()) return; // the run that just ended already saw this retry-at pass and did not admit: re-hosting would loop every second
@@ -315,7 +315,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
315
315
  const b = openBatch(root, id);
316
316
  if (b.readCancel()) return;
317
317
  const st = b.store.load();
318
- if (st?.breaker && !st.breaker.transport) return;
318
+ if (st?.breaker && !st.breaker.transport && !st.breaker.environmental) return;
319
319
  sig = JSON.stringify([b.unrunAdds(), b.unrunRequeues().map((e) => e.issue ?? e)]);
320
320
  if (!b.unrunAdds().length && !b.unrunRequeues().length) { rehostedUnrun.delete(id); return; }
321
321
  } catch { return; }
@@ -533,7 +533,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
533
533
  return closing;
534
534
  };
535
535
  // #5966: a self-initiated stop (version handover, stall recovery). Under a systemd unit the process exits non-zero after a bounded
536
- // drain so `Restart=` starts the successor (a hard timer fires even if close() hangs); without a unit it starts the successor and
536
+ // drain so `Restart=` starts the successor (a hard bound fires even if close() hangs; path-scoped, see selfStop, #5983); without a unit it starts the successor and
537
537
  // waits for it to listen, retrying once, then exits non-zero instead of lingering as an unreachable zombie.
538
538
  const defaultProbe = () => new Promise((r) => {
539
539
  if (process.platform === "win32") return r(true);
@@ -555,9 +555,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
555
555
  stopCode = 1;
556
556
  const underUnit = ["active", "activating"].includes(unit());
557
557
  let hard;
558
- if (exit) { hard = setTimeout(() => { log(`schedd: stop did not finish within ${hardExitMs} ms, exiting`); exit(1); }, hardExitMs); hard.unref?.(); }
558
+ // Path-scoped bound: under a unit it covers the whole stop (close only); unitless it covers close(), then a last-resort bound
559
+ // outlasts the two successor waits and the re-host (a flat hardExitMs equals the sum of those phases and would exit unhosted).
560
+ const arm = (ms, what) => { if (!exit) return undefined; const t = setTimeout(() => { log(`schedd: ${what} did not finish within ${ms} ms, exiting`); exit(1); }, ms); t.unref?.(); return t; };
561
+ hard = arm(hardExitMs, "stop");
559
562
  try {
560
563
  await close();
564
+ if (!underUnit && exit) { clearTimeout(hard); hard = arm(2 * successorMs + 2 * successorPollMs + hardExitMs, "successor handover"); }
561
565
  const spawnOnce = () => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } };
562
566
  spawnOnce();
563
567
  if (probeFn && !underUnit) {
@@ -653,7 +657,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
653
657
  if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
654
658
  const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
655
659
  await efficiencyTick(b, plan, state, { now, reported, cancelled }); // #5987: advisory; never throws, never changes dispatch
656
- const stallOpts = { held: b.readHeld(), paused: b.readPause?.() ?? null, parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
660
+ const stallOpts = { held: b.readHeld(), paused: b.readPause?.() ?? null, parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastDispatchClockMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
657
661
  let stall = evaluateDispatchStall(state, stallOpts);
658
662
  if (stall && preflight) { // #5745: name the preflight gate holding admission (advisory; dispatch decisions are unchanged)
659
663
  let gates = [];
@@ -676,7 +680,8 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
676
680
  // ready set is recovered once (health.json stallRecovery survives a daemon restart), a repeat alerts with the probed cause.
677
681
  let probe = null;
678
682
  try { probe = plan.env ? probeEnv(mergeEnv(process.env, plan.env)) : null; } catch { probe = null; }
679
- const decision = decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, probe, hosted: isHosted });
683
+ const decision = decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, probe, hosted: isHosted, now, windowMin: stallMin });
684
+ if (decision.action === "wait") continue; // #6082: a capacity wait or a recovery still inside its backoff
680
685
  if (decision.action === "alert") {
681
686
  if (recordStallAlert(b, stall, { cause: decision.cause })) log(`schedd: batch ${id} needs you: ${stall.detail}${decision.cause ? `; probed: ${decision.cause}` : ""}`);
682
687
  continue;
@@ -582,7 +582,7 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
582
582
  } finally { await d.close(); }
583
583
  });
584
584
 
585
- it("#5806: a hosted runner wedged in setup restarts the daemon once (decision logged); the same stall again alerts and never loops", async () => {
585
+ it("#5806: a hosted runner wedged in setup restarts the daemon (decision logged); the same stall again is healed again after the backoff, no alert (#6082)", async () => {
586
586
  const dir = tmpDir("schedd-stall-setup-"), root = join(dir, "batches"), id = "b20261121-000000-5806";
587
587
  const b = openBatch(root, id);
588
588
  b.writePlan({ daemon: true, repo: "o/r", created: new Date().toISOString() });
@@ -598,10 +598,9 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
598
598
  assert.ok(lines.some((l) => /FORGE:DECISION batch .+ stall-recovery: restart the hosting schedd/.test(l)), lines.join("\n"));
599
599
  assert.equal(JSON.parse(readFileSync(join(b.dir, "health.json"), "utf8")).stallRecovery.action, "restart-daemon");
600
600
  utimesSync(join(b.dir, "state.json"), old, old);
601
- await until(() => readFileSync(join(b.dir, "health.json"), "utf8").includes("stalled again after auto-recovery"), 8000);
602
- await new Promise((r) => setTimeout(r, 300));
603
- assert.equal(restarts.length, 1, "recovered once, then alerted");
604
- assert.match(readFileSync(join(b.dir, "batch.log"), "utf8"), /BATCH UNHEALTHY .*\(stuck in setup, 0\/2 issues read\).*probed: stalled again after auto-recovery/);
601
+ await until(() => restarts.length >= 2, 8000);
602
+ assert.equal(JSON.parse(readFileSync(join(b.dir, "health.json"), "utf8")).stallRecovery.count >= 2, true, "a second recovery is recorded");
603
+ assert.doesNotMatch(readFileSync(join(b.dir, "batch.log"), "utf8"), /BATCH UNHEALTHY/, "no operator alert while self-heal has attempts left");
605
604
  } finally { await d.close(); }
606
605
  });
607
606
 
@@ -660,6 +659,24 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
660
659
  } finally { await d.close(); }
661
660
  });
662
661
 
662
+ it("#6042: a batch whose breaker is environmental is re-hosted by the timer", async () => {
663
+ const dir = tmpDir("schedd-rehost-env-"), root = join(dir, "batches"), id = "b20261031-000000-6042";
664
+ const calls = [];
665
+ const runBatch = async ({ argv, sink }) => {
666
+ calls.push(argv);
667
+ const b = openBatch(root, id);
668
+ if (argv[0] !== "--resume") { b.writePlan({ daemon: true, repo: "o/r" }); b.store.save({ v: 1, order: [1], results: {}, running: {}, pending: [1], notBefore: { 1: Date.now() + 300 }, breaker: { at: Date.now(), errors: 3, environmental: true } }); }
669
+ sink.batch({ id, dir: b.dir });
670
+ return {};
671
+ };
672
+ const d = await startDaemon({ dir, root, runBatch, log: () => {}, resumeOnStart: false });
673
+ try {
674
+ await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "submit", argv: ["1"], cwd: dir, env: {} });
675
+ await until(() => calls.length >= 2, 8000);
676
+ assert.equal(calls[1][0], "--resume");
677
+ } finally { await d.close(); }
678
+ });
679
+
663
680
  it("#4454: close() stops every hosted batch loop before releasing the lock; no batch admits a lane after close()", async () => {
664
681
  const dir = tmpDir("schedd-stop-"), root = join(dir, "batches"), lock = scheddPaths(dir).lock;
665
682
  const started = { a: [], b: [] }, stoppedWithLock = {};
@@ -855,6 +872,49 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
855
872
  assert.deepEqual(exits2, [1]);
856
873
  });
857
874
 
875
+ it("#5983: unitless, the hard bound does not cut the successor waits short of the re-host; a hung close still exits", async () => {
876
+ const dir = tmpDir("schedd-bound-"), lines = [], exits = [];
877
+ let version = "1.51.0";
878
+ const d = await startDaemon({ dir, root: join(dir, "batches"), log: (m) => lines.push(m), resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
879
+ exit: (c) => exits.push(c), hardExitMs: 100, respawn: () => {}, probe: async () => false, successorMs: 150, successorPollMs: 10, runBatch: async () => ({}) });
880
+ version = "1.52.0";
881
+ await until(() => d.rehosted());
882
+ try {
883
+ assert.equal(d.rehosted().running, true, "re-hosted after waits longer than hardExitMs");
884
+ await new Promise((r) => setTimeout(r, 250));
885
+ assert.deepEqual(exits, [], "the hard timer did not fire");
886
+ } finally { await d.rehosted().close(); }
887
+ const dir2 = tmpDir("schedd-bound2-"), exits2 = [];
888
+ let v2 = "1.51.0";
889
+ await startDaemon({ dir: dir2, root: join(dir2, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => v2, unit: () => null,
890
+ exit: (c) => exits2.push(c), hardExitMs: 150, stopMs: 400, respawn: () => {}, probe: async () => false, successorMs: 50, successorPollMs: 10,
891
+ runBatch: ({ sink }) => { sink.batch({ id: "x", dir: dir2 }); return new Promise(() => {}); } }).then(async (d3) => {
892
+ request(await connectDaemon({ dir: dir2, spawnDaemon: null }), { op: "submit", argv: ["x"], cwd: dir2, env: {} }).catch(() => {});
893
+ await until(() => d3.running);
894
+ v2 = "1.52.0";
895
+ await until(() => exits2.length > 0);
896
+ assert.deepEqual(exits2, [1]);
897
+ await until(() => d3.rehosted()); // the stop carries on after the bound fired; release what it re-hosts
898
+ await d3.rehosted().close();
899
+ });
900
+ });
901
+
902
+ it("#5983: unitless re-host that hangs still exits via the last-resort timer", async () => {
903
+ const dir = tmpDir("schedd-bound3-"), exits = [];
904
+ let version = "1.51.0";
905
+ const d = await startDaemon({ dir, root: join(dir, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
906
+ exit: (c) => exits.push(c), hardExitMs: 100, respawn: () => {}, probe: async () => false, successorMs: 30, successorPollMs: 10,
907
+ rehost: () => new Promise(() => {}), runBatch: async () => ({}) });
908
+ try {
909
+ version = "1.52.0";
910
+ await until(() => exits.length > 0);
911
+ assert.deepEqual(exits, [1]);
912
+ } finally {
913
+ // the mocked exit leaves the daemon's timers and socket alive: close it (bounded, the re-host never settles) so the test file can exit
914
+ await Promise.race([d.close(), new Promise((r) => setTimeout(r, 1000).unref())]);
915
+ }
916
+ });
917
+
858
918
  it("#5984 handover: settled() outlives closed until the successor is spawned and probed (CLI exits only after it)", async () => {
859
919
  const dir = tmpDir("schedd-settled-"), order = [];
860
920
  let version = "1.51.0";
@@ -69,7 +69,7 @@ export const PLANNER_TIGHTENING = Object.freeze({
69
69
  });
70
70
 
71
71
  const PATH_RE = /[\w@.-]+(?:\/[\w@.*-]+)+\.\w+|[\w@.-]+\/[\w@.*-]+\/?/g;
72
- const NEEDS_RESULT = new Set(["requirement_unimplemented", "untracked_deferral"]);
72
+ const NEEDS_RESULT = new Set(["requirement_unimplemented", "requirement_no_status", "untracked_deferral"]);
73
73
 
74
74
  /**
75
75
  * The deterministic conformance findings of the current tree: [{code, kind, detail, section}]. Validate commands are not
@@ -27,7 +27,10 @@ export const ENTRY_SEP = "\n\n---\n\n";
27
27
  /** Markers posted once and edited in place (the marker leads the comment body, so anchored readers still match). */
28
28
  export const UPSERT_MARKERS = Object.freeze(["FORGE:INVESTIGATION", "FORGE:IMPLEMENTATION", "FORGE:PARKED"]);
29
29
  /** #5979: markers re-derived on every pass; a repeat of the same state posts nothing (FACTS and DEPENDENCY are edited in place, NEEDS_HUMAN stays a new comment when it changed). */
30
- export const IN_PLACE_MARKERS = Object.freeze(["FORGE:FACTS", "FORGE:DEPENDENCY", "FORGE:NEEDS_HUMAN"]);
30
+ export const IN_PLACE_MARKERS = Object.freeze(["FORGE:FACTS", "FORGE:DEPENDENCY", "FORGE:NEEDS_HUMAN", "FORGE:AMENDMENT-STATE"]);
31
+ /** #5931: the hidden tag that keys an in-place comment to its issue's contract hash: one comment per (marker, hash), edited in place while the hash holds. */
32
+ export const contractKey = (hash) => (hash ? `<!-- forge-contract hash=${String(hash).replace(/[^\w]/g, "")} -->` : "");
33
+ export const contractKeyOf = (body) => /<!-- forge-contract hash=(\w+) -->/.exec(String(body ?? ""))?.[1] ?? null;
31
34
 
32
35
  const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
33
36
  const markLine = (m) => `<!-- ${m} -->`;
@@ -7,6 +7,7 @@
7
7
  * base-drift classifier. Pure; lean.mjs owns every effect.
8
8
  */
9
9
 
10
+ import { posix } from "node:path";
10
11
  import { venvPythonRewrite } from "./preflight.mjs";
11
12
 
12
13
  /** Default CI sources read for the derived catalogue (repo-relative). */
@@ -108,3 +109,110 @@ export function rewriteSubprojectVenv(contract, files, exists) {
108
109
  if (t && typeof t === "object" && typeof t.command === "string") out.repro_test = { ...t, command: fix("repro_test", t.command) };
109
110
  return applied.length ? { contract: out, applied } : { contract, applied };
110
111
  }
112
+
113
+ const CI_PY_RUNNER_RE = /\b((?:poetry|uv) run(?: +--[\w-]+(?:[ =][^\s|&;-][^\s|&;]*)?)*) +(?:python3? +-m +)?pytest\b([^\n|&;]*)/; // PY_RUNNER_RE's option grammar
114
+ const PYTEST_SEG_RE = /^(\s*(?:[A-Za-z_]\w*=\S*\s+)*)((?:\S*\/)?\.venv\/bin\/python3?\s+-m\s+pytest|(?:\S*\/)?\.venv\/bin\/pytest|python3?(?:\.\d+)?\s+-m\s+pytest|pytest)(?=\s|$)(.*)$/s;
115
+ const normRel = (p) => { const n = posix.normalize(String(p).replace(/^\.\//, "").replace(/\/+$/, "")); return n === "" ? "." : n.replace(/\/+$/, ""); };
116
+ const under = (p, root) => (root === "." ? !p.startsWith("..") : p === root || p.startsWith(`${root}/`));
117
+ const pathish = (x) => !!x && !x.startsWith("-") && !x.startsWith("$") && !x.includes("=") && (x.includes("/") || /\.py(?:::|$)/.test(x) || x === ".");
118
+ const indent = (l) => /^\s*/.exec(l)[0].length;
119
+
120
+ /**
121
+ * #5753: which env the repo's own CI runs each Python test path in, parsed from CI text (0 LLM calls). Every `poetry run` /
122
+ * `uv run` pytest line, with its step's `working-directory:` (and an inline `cd X &&`), becomes {dir, runner, paths}: `paths`
123
+ * are repo-relative (`../../shared` under `services/worker` is `shared`); no path argument means the whole `dir`. Pure.
124
+ */
125
+ export function deriveTestEnvMap(texts) {
126
+ const out = [], seen = new Set();
127
+ for (const text of (Array.isArray(texts) ? texts : [texts]).filter((t) => typeof t === "string")) {
128
+ const lines = text.split("\n");
129
+ for (let i = 0; i < lines.length; i++) {
130
+ const m = CI_PY_RUNNER_RE.exec(lines[i]);
131
+ if (!m) continue;
132
+ let s = i;
133
+ while (s > 0 && !/^\s*-\s/.test(lines[s])) s--; // the step this line belongs to
134
+ let e = s + 1;
135
+ while (e < lines.length && !(lines[e].trim() && indent(lines[e]) <= indent(lines[s]))) e++;
136
+ const wd = lines.slice(s, e).map((l) => /^\s*-?\s*working-directory:\s*["']?([^"'\s#]+)/.exec(l)).find(Boolean);
137
+ if (wd && wd[1].includes("$")) continue;
138
+ let dir = wd ? normRel(wd[1]) : ".";
139
+ const cd = /\bcd\s+["']?([^"'\s&;]+)["']?\s*&&[^&|;]*$/.exec(lines[i].slice(0, m.index));
140
+ if (cd) {
141
+ if (cd[1].includes("$") || cd[1].startsWith("/")) continue;
142
+ dir = normRel(posix.join(dir, cd[1]));
143
+ }
144
+ if (dir.startsWith("..")) continue;
145
+ const args = m[2].trim().split(/\s+/).filter(pathish).map((x) => x.replace(/::.*$/, ""));
146
+ const paths = (args.length ? args : ["."]).map((p) => normRel(posix.join(dir, p))).filter((p) => !p.startsWith(".."));
147
+ const runner = m[1].trim(), key = `${dir}|${runner}|${paths.join(",")}`;
148
+ if (paths.length && !seen.has(key)) { seen.add(key); out.push({ dir, runner, paths }); }
149
+ }
150
+ }
151
+ return out;
152
+ }
153
+
154
+ /** #5753: one pytest segment run from `cwd` -> {dir, cmd} in its CI env (or its lock's runner), or null when it stays. */
155
+ function ciEnvSegment(seg, cwd, map, files, exists) {
156
+ const m = PYTEST_SEG_RE.exec(seg);
157
+ if (!m) return null;
158
+ const [, envs, interp, rest] = m;
159
+ const venv = /^(\S*?)\.venv\/bin\/(\S+)/.exec(interp);
160
+ if (venv && exists(normRel(posix.join(cwd, `${venv[1]}.venv/bin/${venv[2]}`)))) return null; // #5683: a venv that resolves stays
161
+ const toks = rest.trim() ? rest.trim().split(/\s+/) : [];
162
+ const tests = toks.filter(pathish).map((x) => normRel(posix.join(cwd, x.replace(/::.*$/, ""))));
163
+ const all = tests.length ? tests : [cwd];
164
+ const hit = all.some((p) => p.startsWith("..")) ? null : map.find((en) => all.every((p) => en.paths.some((root) => under(p, root))));
165
+ if (hit) {
166
+ const reRel = (x) => { const [p, ...id] = x.split("::"); return [posix.relative(hit.dir === "." ? "" : hit.dir, normRel(posix.join(cwd, p))) || ".", ...id].join("::"); };
167
+ const args = toks.map((x) => (pathish(x) ? reRel(x) : x));
168
+ return { dir: hit.dir, cmd: `${envs}${hit.runner} pytest${args.length ? ` ${args.join(" ")}` : ""}` };
169
+ }
170
+ if (!venv) return null; // a bare interpreter CI does not map stays (rewriteSubprojectVenv owns the sub-project venv case)
171
+ const proj = normRel(posix.join(cwd, venv[1] || "."));
172
+ if (proj !== cwd) return null;
173
+ const at = (f) => (proj === "." ? f : `${proj}/${f}`);
174
+ const runner = files.includes(at("poetry.lock")) ? "poetry run" : files.includes(at("uv.lock")) ? "uv run" : null;
175
+ return runner ? { dir: cwd, cmd: `${envs}${runner} pytest${rest.replace(/\s+$/, "")}` } : null;
176
+ }
177
+
178
+ /**
179
+ * #5753: the repro and validate pytest commands that run under a bare interpreter (`python -m pytest`, `pytest`) or a
180
+ * `.venv/bin/python` that does not exist, for test paths CI runs in another env (`map`: deriveTestEnvMap), become
181
+ * `cd <dir> && <runner> pytest <dir-relative paths>`. With no map entry, a missing `.venv` with a poetry.lock / uv.lock next
182
+ * to it runs through `poetry run` / `uv run`. Commands already using poetry/uv run, a venv that resolves and unmapped bare
183
+ * commands are unchanged. `files`: tracked paths; `exists(rel)`: repo-relative check. Returns {contract, applied[{id, from, to}]}.
184
+ */
185
+ export function rewriteToCiEnv(contract, map = [], files = [], exists = () => false) {
186
+ if (!contract || typeof contract !== "object") return { contract, applied: [] };
187
+ const fix1 = (command) => {
188
+ const parts = String(command).split(/(&&|\|\||;|\||\n)/);
189
+ let cwd = ".", onlyCd = true, changed = false;
190
+ const out = [];
191
+ for (let i = 0; i < parts.length; i++) {
192
+ const seg = parts[i];
193
+ if (i % 2) { out.push(seg); continue; }
194
+ const cd = /^\s*cd\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s*$/.exec(seg);
195
+ if (cd) {
196
+ const t = cd[1] ?? cd[2] ?? cd[3];
197
+ cwd = cwd === "?" || t.startsWith("/") || t.startsWith("$") ? "?" : normRel(posix.join(cwd, t));
198
+ if (cwd.startsWith("..")) cwd = "?";
199
+ out.push(seg); continue;
200
+ }
201
+ const r = cwd === "?" || /\b(?:poetry|uv)\s+(?:-\S+\s+)*run\b/.test(seg) ? null : ciEnvSegment(seg, cwd, map, files, exists);
202
+ if (!r) { onlyCd = false; out.push(seg); continue; }
203
+ changed = true;
204
+ const lead = /^\s*/.exec(seg)[0], tail = /\s*$/.exec(seg)[0], cmd = r.cmd.trim(), last = i === parts.length - 1;
205
+ if (onlyCd && last) { out.length = 0; out.push(r.dir === "." ? cmd : `cd ${r.dir} && ${cmd}`); } // leading cds give way to the env's dir
206
+ else if (r.dir === cwd) out.push(`${lead}${cmd}${tail}`);
207
+ else { const rel = posix.relative(cwd === "." ? "" : cwd, r.dir === "." ? "" : r.dir) || "."; out.push(`${lead}${last ? `cd ${rel} && ${cmd}` : `(cd ${rel} && ${cmd})`}${tail}`); } // later segments keep their cwd
208
+ onlyCd = false;
209
+ }
210
+ return changed ? out.join("") : String(command);
211
+ };
212
+ const applied = [], fix = (id, cmd) => { const to = fix1(cmd); if (to !== cmd) applied.push({ id, from: cmd, to }); return to; };
213
+ const out = { ...contract };
214
+ if (Array.isArray(contract.validate)) out.validate = contract.validate.map((v) => (v && typeof v.command === "string" ? { ...v, command: fix(v.id, v.command) } : v));
215
+ const t = contract.repro_test;
216
+ if (t && typeof t === "object" && typeof t.command === "string") out.repro_test = { ...t, command: fix("repro_test", t.command) };
217
+ return applied.length ? { contract: out, applied } : { contract, applied };
218
+ }
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  import { describe, it } from "node:test";
4
4
  import assert from "node:assert/strict";
5
- import { deriveCatalog, mergeRecipes, rewriteMissed, extractTestIds, equivalentRuns, isDriftFailure, rewriteSubprojectVenv } from "./validate-catalog.mjs";
5
+ import { deriveCatalog, mergeRecipes, rewriteMissed, extractTestIds, equivalentRuns, isDriftFailure, rewriteSubprojectVenv, deriveTestEnvMap, rewriteToCiEnv } from "./validate-catalog.mjs";
6
6
  import { applyValidateRecipes } from "./conformance.mjs";
7
7
 
8
8
  const CI = "run: uv run --with-requirements r.txt pytest tests\nrun: npx vitest run";
@@ -56,3 +56,48 @@ describe("#5683 sub-project venv rewrite", () => {
56
56
  assert.equal(rewriteSubprojectVenv(same, files, exists).contract, same);
57
57
  });
58
58
  });
59
+
60
+ describe("#5753 CI test-env map: a test path runs in the env CI runs it in", () => {
61
+ const CI = [
62
+ "jobs:",
63
+ " worker:",
64
+ " steps:",
65
+ " - uses: actions/checkout@v4",
66
+ " - name: Test worker",
67
+ " working-directory: services/worker",
68
+ " run: poetry run pytest tests/ ../../shared -q",
69
+ " - run: |",
70
+ " cd services/api && uv run --frozen pytest",
71
+ "",
72
+ ].join("\n");
73
+ it("deriveTestEnvMap reads working-directory, inline cd and poetry/uv run pytest paths, repo-relative", () => {
74
+ assert.deepEqual(deriveTestEnvMap([CI, ""]), [
75
+ { dir: "services/worker", runner: "poetry run", paths: ["services/worker/tests", "shared"] },
76
+ { dir: "services/api", runner: "uv run --frozen", paths: ["services/api"] },
77
+ ]);
78
+ assert.deepEqual(deriveTestEnvMap(["run: python -m pytest tests", "run: npm test"]), [], "a bare interpreter or no pytest is no env");
79
+ });
80
+ it("a shared/ pytest under a bare interpreter is rewritten to the services/worker env", () => {
81
+ const map = deriveTestEnvMap(CI);
82
+ const c = { validate: [{ id: "V1", command: "python -m pytest shared/detection/test_x.py" }, { id: "V2", command: "cd shared && python3 -m pytest -q detection/test_x.py::test_a" }, { id: "V3", command: "pytest services/api/tests/t.py && echo ok" }] };
83
+ const r = rewriteToCiEnv(c, map, [], () => false);
84
+ assert.deepEqual(r.contract.validate.map((v) => v.command), [
85
+ "cd services/worker && poetry run pytest ../../shared/detection/test_x.py",
86
+ "cd services/worker && poetry run pytest -q ../../shared/detection/test_x.py::test_a",
87
+ "(cd services/api && uv run --frozen pytest tests/t.py) && echo ok",
88
+ ]);
89
+ assert.deepEqual(r.applied.map((a) => a.id), ["V1", "V2", "V3"]);
90
+ });
91
+ it("wrapped, unmapped and resolving-venv commands stay byte-identical", () => {
92
+ const map = deriveTestEnvMap(CI);
93
+ const c = { validate: [{ id: "V1", command: "cd services/worker && poetry run pytest tests" }, { id: "V2", command: "uv run pytest shared/t.py" }, { id: "V3", command: "python -m pytest other/test_y.py" }, { id: "V4", command: "services/worker/.venv/bin/python -m pytest shared/t.py" }], repro_test: { command: "node --test x.test.mjs" } };
94
+ const r = rewriteToCiEnv(c, map, [], (rel) => rel === "services/worker/.venv/bin/python");
95
+ assert.equal(r.contract, c); assert.deepEqual(r.applied, []);
96
+ });
97
+ it("a .venv/bin/python that does not exist falls back to the lock's runner; no lock leaves it", () => {
98
+ const c = { repro_test: { command: "cd services/x && .venv/bin/python -m pytest t.py" } };
99
+ assert.equal(rewriteToCiEnv(c, [], ["services/x/poetry.lock"], () => false).contract.repro_test.command, "cd services/x && poetry run pytest t.py");
100
+ assert.equal(rewriteToCiEnv(c, [], ["services/x/uv.lock"], () => false).contract.repro_test.command, "cd services/x && uv run pytest t.py");
101
+ assert.equal(rewriteToCiEnv(c, [], [], () => false).contract, c);
102
+ });
103
+ });
@@ -300,7 +300,7 @@ export async function cancelSuperseded({ io, branch, head, mode = "off", pushedA
300
300
  return out;
301
301
  }
302
302
 
303
- const VALIDATE_KINDS = ["validate_missing", "validate_failed"], REQUIREMENT_KINDS = ["requirement_unimplemented", "untracked_deferral"];
303
+ const VALIDATE_KINDS = ["validate_missing", "validate_failed"], REQUIREMENT_KINDS = ["requirement_unimplemented", "requirement_no_status", "untracked_deferral"];
304
304
  /**
305
305
  * #4270: the `forgedock/verify` check-run payload from the results the lane already computed (no gate logic of its own).
306
306
  * commands: [{command, rc}] of the last declared-check round, or null (none configured); structure: the structure delta or